@mastra/agent-builder 1.1.9 → 1.1.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/CHANGELOG.md +23 -0
- package/dist/index.js +29 -9
- package/dist/index.js.map +1 -1
- package/package.json +12 -12
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["exec","execNodejs","execFile","execFileNodejs","spawn","nodeSpawn","nodeSpawn","execFile","exec","symbol$1","_a$1","name$1","marker2","symbol2","_a2","_b2","name2","marker3","symbol3","_a3","_b3","name3","marker4","symbol4","_a4","_b4","name4","marker5","symbol5","_a5","_b5","name5","marker6","symbol6","_a6","_b6","name6","marker7","symbol7","_a7","_b7","name7","marker8","symbol8","_a8","_b8","name8","marker9","symbol9","_a9","_b9","name9","marker10","symbol10","_a10","name10","marker11","symbol11","_a11","name11","marker12","symbol12","_a12","name12","marker13","symbol13","_a13","name13","marker14","symbol14","_a14","name","marker","symbol","_a","_b","VERSION","resolve","z","resolve","z$1","DownloadError$1"],"sources":["../src/types.ts","../src/utils.ts","../src/defaults.ts","../src/processors/tool-summary.ts","../src/agent/index.ts","../src/workflows/template-builder/template-builder.ts","../../_vendored/ai_v5/dist/dist-Qv-F35RT.js","../../_vendored/ai_v5/dist/index.js","../src/workflows/shared/schema.ts","../src/workflows/task-planning/prompts.ts","../src/workflows/workflow-builder/schema.ts","../src/workflows/task-planning/schema.ts","../src/workflows/task-planning/task-planning.ts","../src/workflows/workflow-builder/prompts.ts","../src/workflows/workflow-builder/tools.ts","../src/workflows/workflow-builder/workflow-builder.ts","../src/workflows/workflow-map.ts"],"sourcesContent":["import type { ToolsInput } from '@mastra/core/agent';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport type { MastraStorage } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { z } from 'zod';\n\n/**\n * Configuration options for the AgentBuilder\n */\nexport interface AgentBuilderConfig {\n /** The language model to use for agent generation */\n model: MastraModelConfig;\n /** Storage provider for memory (optional) */\n storage?: MastraStorage;\n /** Vector provider for memory (optional) */\n vectorProvider?: MastraVector;\n /** Additional tools to include beyond the default set */\n tools?: ToolsInput;\n /** Custom instructions to append to the default system prompt */\n instructions?: string;\n /** Memory configuration options */\n memoryConfig?: {\n maxMessages?: number;\n tokenLimit?: number;\n };\n /** Project path */\n projectPath: string;\n /** Summary model */\n summaryModel?: MastraModelConfig;\n /** Mode */\n mode?: 'template' | 'code-editor';\n}\n\n/**\n * Options for generating agents with AgentBuilder\n */\nexport interface GenerateAgentOptions {\n /** Request Context for the generation */\n requestContext?: any;\n /** Output format preference */\n outputFormat?: 'code' | 'explanation' | 'both';\n}\n\n/**\n * Project management action types\n */\nexport type ProjectAction = 'create' | 'install' | 'upgrade' | 'check';\n\n/**\n * Project types that can be created\n */\nexport type ProjectType = 'standalone' | 'api' | 'nextjs';\n\n/**\n * Package manager options\n */\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn';\n\n/**\n * Validation types for code validation\n */\nexport type ValidationType = 'types' | 'schemas' | 'tests' | 'integration';\n\n// Processing order for units (lower index = higher priority)\nexport const UNIT_KINDS = ['mcp-server', 'tool', 'workflow', 'agent', 'integration', 'network', 'other'] as const;\n\n// Types for the merge template workflow\nexport type UnitKind = (typeof UNIT_KINDS)[number];\n\nexport interface TemplateUnit {\n kind: UnitKind;\n id: string;\n file: string;\n}\n\nexport interface TemplateManifest {\n slug: string;\n ref?: string;\n description?: string;\n units: TemplateUnit[];\n}\n\nexport interface MergePlan {\n slug: string;\n commitSha: string;\n templateDir: string;\n units: TemplateUnit[];\n}\n\n// Schema definitions\nexport const TemplateUnitSchema = z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n file: z.string(),\n});\n\nexport const TemplateManifestSchema = z.object({\n slug: z.string(),\n ref: z.string().optional(),\n description: z.string().optional(),\n units: z.array(TemplateUnitSchema),\n});\n\nexport const AgentBuilderInputSchema = z.object({\n repo: z.string().describe('Git URL or local path of the template repo'),\n ref: z.string().optional().describe('Tag/branch/commit to checkout (defaults to main/master)'),\n slug: z.string().optional().describe('Slug for branch/scripts; defaults to inferred from repo'),\n targetPath: z.string().optional().describe('Project path to merge into; defaults to current directory'),\n variables: z.record(z.string(), z.string()).optional().describe('Environment variables to set in .env file'),\n});\n\nexport const MergePlanSchema = z.object({\n slug: z.string(),\n commitSha: z.string(),\n templateDir: z.string(),\n units: z.array(TemplateUnitSchema),\n});\n\n// File copy schemas and types\nexport const CopiedFileSchema = z.object({\n source: z.string(),\n destination: z.string(),\n unit: z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n }),\n});\n\nexport const ConflictSchema = z.object({\n unit: z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n }),\n issue: z.string(),\n sourceFile: z.string(),\n targetFile: z.string(),\n});\n\nexport const FileCopyInputSchema = z.object({\n orderedUnits: z.array(TemplateUnitSchema),\n templateDir: z.string(),\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n variables: z.record(z.string(), z.string()).optional(),\n});\n\nexport const FileCopyResultSchema = z.object({\n success: z.boolean(),\n copiedFiles: z.array(CopiedFileSchema),\n conflicts: z.array(ConflictSchema),\n message: z.string(),\n error: z.string().optional(),\n});\n\n// Intelligent merge schemas and types\nexport const ConflictResolutionSchema = z.object({\n unit: z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n }),\n issue: z.string(),\n resolution: z.string(),\n});\n\nexport const IntelligentMergeInputSchema = z.object({\n conflicts: z.array(ConflictSchema),\n copiedFiles: z.array(CopiedFileSchema),\n templateDir: z.string(),\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n branchName: z.string().optional(),\n});\n\nexport const IntelligentMergeResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n message: z.string(),\n conflictsResolved: z.array(ConflictResolutionSchema),\n error: z.string().optional(),\n});\n\n// Validation schemas and types\nexport const ValidationResultsSchema = z.object({\n valid: z.boolean(),\n errorsFixed: z.number(),\n remainingErrors: z.number(),\n errors: z.array(z.any()).optional(), // Include specific validation errors\n});\n\nexport const ValidationFixInputSchema = z.object({\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n templateDir: z.string(),\n orderedUnits: z.array(TemplateUnitSchema),\n copiedFiles: z.array(CopiedFileSchema),\n conflictsResolved: z.array(ConflictResolutionSchema).optional(),\n maxIterations: z.number().optional().default(5),\n});\n\nexport const ValidationFixResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n message: z.string(),\n validationResults: ValidationResultsSchema,\n error: z.string().optional(),\n});\n\n// Final workflow result schema\nexport const ApplyResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n branchName: z.string().optional(),\n message: z.string(),\n validationResults: ValidationResultsSchema.optional(),\n error: z.string().optional(),\n errors: z.array(z.string()).optional(),\n stepResults: z\n .object({\n cloneSuccess: z.boolean().optional(),\n analyzeSuccess: z.boolean().optional(),\n discoverSuccess: z.boolean().optional(),\n orderSuccess: z.boolean().optional(),\n prepareBranchSuccess: z.boolean().optional(),\n packageMergeSuccess: z.boolean().optional(),\n installSuccess: z.boolean().optional(),\n copySuccess: z.boolean().optional(),\n mergeSuccess: z.boolean().optional(),\n validationSuccess: z.boolean().optional(),\n filesCopied: z.number(),\n conflictsSkipped: z.number(),\n conflictsResolved: z.number(),\n })\n .optional(),\n});\n\nexport const CloneTemplateResultSchema = z.object({\n templateDir: z.string(),\n commitSha: z.string(),\n slug: z.string(),\n success: z.boolean().optional(),\n error: z.string().optional(),\n targetPath: z.string().optional(),\n});\n\n// Package analysis schemas and types\nexport const PackageAnalysisSchema = z.object({\n name: z.string().optional(),\n version: z.string().optional(),\n description: z.string().optional(),\n dependencies: z.record(z.string(), z.string()).optional(),\n devDependencies: z.record(z.string(), z.string()).optional(),\n peerDependencies: z.record(z.string(), z.string()).optional(),\n scripts: z.record(z.string(), z.string()).optional(),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n\n// Discovery step schemas and types\nexport const DiscoveryResultSchema = z.object({\n units: z.array(TemplateUnitSchema),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n\n// Unit ordering schemas and types\nexport const OrderedUnitsSchema = z.object({\n orderedUnits: z.array(TemplateUnitSchema),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n\n// Package merge schemas and types\nexport const PackageMergeInputSchema = z.object({\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n packageInfo: PackageAnalysisSchema,\n});\n\nexport const PackageMergeResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n message: z.string(),\n error: z.string().optional(),\n});\n\n// Install schemas and types\nexport const InstallInputSchema = z.object({\n targetPath: z.string().optional().describe('Path to the project to install packages in'),\n});\n\nexport const InstallResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional(),\n});\n\nexport const PrepareBranchInputSchema = z.object({\n slug: z.string(),\n commitSha: z.string().optional(), // from clone-template if relevant\n targetPath: z.string().optional(),\n});\n\nexport const PrepareBranchResultSchema = z.object({\n branchName: z.string(),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n","import { exec as execNodejs, execFile as execFileNodejs, spawn as nodeSpawn } from 'node:child_process';\nimport type { SpawnOptions } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { copyFile, readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, basename, extname, resolve, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { MastraLanguageModel, MastraLegacyLanguageModel } from '@mastra/core/agent';\nimport { ModelRouterLanguageModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { UNIT_KINDS } from './types';\nimport type { UnitKind } from './types';\n\nexport const exec = promisify(execNodejs);\nexport const execFile = promisify(execFileNodejs);\n\n// Helper function to detect if we're in a workspace subfolder\nfunction isInWorkspaceSubfolder(cwd: string): boolean {\n try {\n // First, check if current directory has package.json (it's a package)\n const currentPackageJson = resolve(cwd, 'package.json');\n if (!existsSync(currentPackageJson)) {\n return false; // Not a package, so not a workspace subfolder\n }\n\n // Walk up the directory tree looking for workspace indicators\n let currentDir = cwd;\n let previousDir = '';\n\n // Keep going up until we reach the filesystem root or stop making progress\n while (currentDir !== previousDir && currentDir !== '/') {\n previousDir = currentDir;\n currentDir = dirname(currentDir);\n\n // Skip if we're back at the original directory\n if (currentDir === cwd) {\n continue;\n }\n\n console.info(`Checking for workspace indicators in: ${currentDir}`);\n\n // Check for pnpm workspace\n if (existsSync(resolve(currentDir, 'pnpm-workspace.yaml'))) {\n return true;\n }\n\n // Check for npm/yarn workspaces in package.json\n const parentPackageJson = resolve(currentDir, 'package.json');\n if (existsSync(parentPackageJson)) {\n try {\n const parentPkg = JSON.parse(readFileSync(parentPackageJson, 'utf-8'));\n if (parentPkg.workspaces) {\n return true; // Found workspace config\n }\n } catch {\n // Ignore JSON parse errors\n }\n }\n\n // Check for lerna\n if (existsSync(resolve(currentDir, 'lerna.json'))) {\n return true;\n }\n }\n\n return false;\n } catch (error) {\n console.warn(`Error in workspace detection: ${error}`);\n return false; // Default to false on any error\n }\n}\n\nexport function spawn(command: string, args: string[], options: any) {\n return new Promise((resolve, reject) => {\n const childProcess = nodeSpawn(command, args, {\n stdio: 'inherit', // Enable proper stdio handling\n ...options,\n });\n childProcess.on('error', error => {\n reject(error);\n });\n childProcess.on('close', code => {\n if (code === 0) {\n resolve(void 0);\n } else {\n reject(new Error(`Command failed with exit code ${code}`));\n }\n });\n });\n}\n\n// --- Git environment probes ---\nexport async function isGitInstalled(): Promise<boolean> {\n try {\n await spawnWithOutput('git', ['--version'], {});\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function isInsideGitRepo(cwd: string): Promise<boolean> {\n try {\n if (!(await isGitInstalled())) return false;\n const { stdout } = await spawnWithOutput('git', ['rev-parse', '--is-inside-work-tree'], { cwd });\n return stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\n// Variant of spawn that captures stdout and stderr\nexport function spawnWithOutput(\n command: string,\n args: string[],\n options: SpawnOptions,\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolvePromise, rejectPromise) => {\n const childProcess = nodeSpawn(command, args, {\n ...options,\n });\n let stdout = '';\n let stderr = '';\n childProcess.on('error', error => {\n rejectPromise(error);\n });\n childProcess.stdout?.on('data', chunk => {\n process.stdout.write(chunk);\n stdout += chunk?.toString?.() ?? String(chunk);\n });\n childProcess.stderr?.on('data', chunk => {\n stderr += chunk?.toString?.() ?? String(chunk);\n process.stderr.write(chunk);\n });\n childProcess.on('close', code => {\n if (code === 0) {\n resolvePromise({ stdout, stderr, code: code ?? 0 });\n } else {\n const err = new Error(stderr || `Command failed: ${command} ${args.join(' ')}`);\n // @ts-expect-error augment\n err.code = code;\n rejectPromise(err);\n }\n });\n });\n}\n\nexport async function spawnSWPM(cwd: string, command: string, packageNames: string[]) {\n // 1) Try local swpm module resolution/execution\n try {\n console.info('Running install command with swpm');\n const swpmPath = createRequire(import.meta.filename).resolve('swpm');\n await spawn(swpmPath, [command, ...packageNames], { cwd });\n return;\n } catch (e) {\n console.warn('Failed to run install command with swpm', e);\n // ignore and try fallbacks\n }\n\n // 2) Fallback to native package manager based on lock files\n try {\n // Detect package manager from lock files\n let packageManager: string;\n\n if (existsSync(resolve(cwd, 'pnpm-lock.yaml'))) {\n packageManager = 'pnpm';\n } else if (existsSync(resolve(cwd, 'yarn.lock'))) {\n packageManager = 'yarn';\n } else {\n packageManager = 'npm';\n }\n\n // Normalize command\n let nativeCommand = command === 'add' ? 'add' : command === 'install' ? 'install' : command;\n\n // Build args with non-interactive flags for install commands\n const args = [nativeCommand];\n if (nativeCommand === 'install') {\n const inWorkspace = isInWorkspaceSubfolder(cwd);\n if (packageManager === 'pnpm') {\n args.push('--force'); // pnpm install --force\n\n // Check if we're in a workspace subfolder\n if (inWorkspace) {\n args.push('--ignore-workspace');\n }\n } else if (packageManager === 'npm') {\n args.push('--yes'); // npm install --yes\n\n // Check if we're in a workspace subfolder\n if (inWorkspace) {\n args.push('--ignore-workspaces');\n }\n }\n }\n args.push(...packageNames);\n\n console.info(`Falling back to ${packageManager} ${args.join(' ')}`);\n await spawn(packageManager, args, { cwd });\n return;\n } catch (e) {\n console.warn(`Failed to run install command with native package manager: ${e}`);\n }\n\n throw new Error(`Failed to run install command with swpm and native package managers`);\n}\n\n// Utility functions\nexport function kindWeight(kind: UnitKind): number {\n const idx = UNIT_KINDS.indexOf(kind as any);\n return idx === -1 ? UNIT_KINDS.length : idx;\n}\n\n// Utility functions to work with Mastra templates\nexport async function fetchMastraTemplates(): Promise<\n Array<{\n slug: string;\n title: string;\n description: string;\n githubUrl: string;\n tags: string[];\n agents: string[];\n workflows: string[];\n tools: string[];\n }>\n> {\n try {\n const response = await fetch('https://mastra.ai/api/templates.json');\n const data = (await response.json()) as Array<{\n slug: string;\n title: string;\n description: string;\n githubUrl: string;\n tags: string[];\n agents: string[];\n workflows: string[];\n tools: string[];\n }>;\n return data;\n } catch (error) {\n throw new Error(`Failed to fetch Mastra templates: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n// Helper to get a specific template by slug\nexport async function getMastraTemplate(slug: string) {\n const templates = await fetchMastraTemplates();\n const template = templates.find(t => t.slug === slug);\n if (!template) {\n throw new Error(`Template \"${slug}\" not found. Available templates: ${templates.map(t => t.slug).join(', ')}`);\n }\n return template;\n}\n\n// Git commit tracking utility\nexport async function logGitState(targetPath: string, label: string): Promise<void> {\n try {\n // Skip if not a git repo\n if (!(await isInsideGitRepo(targetPath))) return;\n const gitStatusResult = await git(targetPath, 'status', '--porcelain');\n const gitLogResult = await git(targetPath, 'log', '--oneline', '-3');\n const gitCountResult = await git(targetPath, 'rev-list', '--count', 'HEAD');\n\n console.info(`📊 Git state ${label}:`);\n console.info('Status:', gitStatusResult.stdout.trim() || 'Clean working directory');\n console.info('Recent commits:', gitLogResult.stdout.trim());\n console.info('Total commits:', gitCountResult.stdout.trim());\n } catch (gitError) {\n console.warn(`Could not get git state ${label}:`, gitError);\n }\n}\n\n// Generic git runner that captures stdout/stderr\nexport async function git(cwd: string, ...args: string[]): Promise<{ stdout: string; stderr: string }> {\n const { stdout, stderr } = await spawnWithOutput('git', args, { cwd });\n return { stdout: stdout ?? '', stderr: stderr ?? '' };\n}\n\n// Common git helpers\nexport async function gitClone(repo: string, destDir: string, cwd?: string) {\n await git(cwd ?? process.cwd(), 'clone', repo, destDir);\n}\n\nexport async function gitCheckoutRef(cwd: string, ref: string) {\n if (!(await isInsideGitRepo(cwd))) return;\n await git(cwd, 'checkout', ref);\n}\n\nexport async function gitRevParse(cwd: string, rev: string): Promise<string> {\n if (!(await isInsideGitRepo(cwd))) return '';\n const { stdout } = await git(cwd, 'rev-parse', rev);\n return stdout.trim();\n}\n\nexport async function gitAddFiles(cwd: string, files: string[]) {\n if (!files || files.length === 0) return;\n if (!(await isInsideGitRepo(cwd))) return;\n await git(cwd, 'add', ...files);\n}\n\nexport async function gitAddAll(cwd: string) {\n if (!(await isInsideGitRepo(cwd))) return;\n await git(cwd, 'add', '.');\n}\n\nexport async function gitHasStagedChanges(cwd: string): Promise<boolean> {\n if (!(await isInsideGitRepo(cwd))) return false;\n const { stdout } = await git(cwd, 'diff', '--cached', '--name-only');\n return stdout.trim().length > 0;\n}\n\nexport async function gitCommit(\n cwd: string,\n message: string,\n opts?: { allowEmpty?: boolean; skipIfNoStaged?: boolean },\n): Promise<boolean> {\n try {\n if (!(await isInsideGitRepo(cwd))) return false;\n if (opts?.skipIfNoStaged) {\n const has = await gitHasStagedChanges(cwd);\n if (!has) return false;\n }\n const args = ['commit', '-m', message];\n if (opts?.allowEmpty) args.push('--allow-empty');\n await git(cwd, ...args);\n return true;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (/nothing to commit/i.test(msg) || /no changes added to commit/i.test(msg)) {\n return false;\n }\n throw e;\n }\n}\n\nexport async function gitAddAndCommit(\n cwd: string,\n message: string,\n files?: string[],\n opts?: { allowEmpty?: boolean; skipIfNoStaged?: boolean },\n): Promise<boolean> {\n try {\n if (!(await isInsideGitRepo(cwd))) return false;\n if (files && files.length > 0) {\n await gitAddFiles(cwd, files);\n } else {\n await gitAddAll(cwd);\n }\n return gitCommit(cwd, message, opts);\n } catch (e) {\n console.error(`Failed to add and commit files: ${e instanceof Error ? e.message : String(e)}`);\n return false;\n }\n}\n\nexport async function gitCheckoutBranch(branchName: string, targetPath: string) {\n try {\n if (!(await isInsideGitRepo(targetPath))) return;\n // Try to create new branch using centralized git runner\n await git(targetPath, 'checkout', '-b', branchName);\n console.info(`Created new branch: ${branchName}`);\n } catch (error) {\n // If branch exists, check if we can switch to it or create a unique name\n const errorStr = error instanceof Error ? error.message : String(error);\n if (errorStr.includes('already exists')) {\n try {\n // Try to switch to existing branch\n await git(targetPath, 'checkout', branchName);\n console.info(`Switched to existing branch: ${branchName}`);\n } catch {\n // If can't switch, create a unique branch name\n const timestamp = Date.now().toString().slice(-6);\n const uniqueBranchName = `${branchName}-${timestamp}`;\n await git(targetPath, 'checkout', '-b', uniqueBranchName);\n console.info(`Created unique branch: ${uniqueBranchName}`);\n }\n } else {\n throw error; // Re-throw if it's a different error\n }\n }\n}\n\n// File conflict resolution utilities (for future use)\nexport async function backupAndReplaceFile(sourceFile: string, targetFile: string): Promise<void> {\n // Create backup of existing file\n const backupFile = `${targetFile}.backup-${Date.now()}`;\n await copyFile(targetFile, backupFile);\n console.info(`📦 Created backup: ${basename(backupFile)}`);\n\n // Replace with template file\n await copyFile(sourceFile, targetFile);\n console.info(`🔄 Replaced file with template version (backup created)`);\n}\n\nexport async function renameAndCopyFile(sourceFile: string, targetFile: string): Promise<string> {\n // Find unique filename\n let counter = 1;\n let uniqueTargetFile = targetFile;\n const baseName = basename(targetFile, extname(targetFile));\n const extension = extname(targetFile);\n const directory = dirname(targetFile);\n\n while (existsSync(uniqueTargetFile)) {\n const uniqueName = `${baseName}.template-${counter}${extension}`;\n uniqueTargetFile = resolve(directory, uniqueName);\n counter++;\n }\n\n await copyFile(sourceFile, uniqueTargetFile);\n console.info(`📝 Copied with unique name: ${basename(uniqueTargetFile)}`);\n return uniqueTargetFile;\n}\n\n// Type guard to check if object is a valid language model (V1, V2, or V3)\nexport const isValidMastraLanguageModel = (model: any): model is MastraLanguageModel | MastraLegacyLanguageModel => {\n return model && typeof model === 'object' && typeof model.modelId === 'string';\n};\n\n// Helper function to resolve target path with smart defaults\nexport const resolveTargetPath = (inputData: any, requestContext: any): string => {\n // If explicitly provided, use it\n if (inputData.targetPath) {\n return inputData.targetPath;\n }\n\n // Check request context\n const contextPath = requestContext.get('targetPath');\n if (contextPath) {\n return contextPath;\n }\n\n // Smart resolution logic from prepareAgentBuilderWorkflowInstallation\n const envRoot = process.env.MASTRA_PROJECT_ROOT?.trim();\n if (envRoot) {\n return envRoot;\n }\n\n const cwd = process.cwd();\n const parent = dirname(cwd);\n const grand = dirname(parent);\n\n // Detect when running under `<project>/.mastra/output` and resolve back to project root\n if (basename(cwd) === 'output' && basename(parent) === '.mastra') {\n return grand;\n }\n\n return cwd;\n};\n\n// Helper function to merge .gitignore files intelligently\nexport const mergeGitignoreFiles = (targetContent: string, templateContent: string, templateSlug: string): string => {\n // Normalize line endings and split into lines\n const targetLines = targetContent.replace(/\\r\\n/g, '\\n').split('\\n');\n const templateLines = templateContent.replace(/\\r\\n/g, '\\n').split('\\n');\n\n // Parse existing target entries (normalize for comparison)\n const existingEntries = new Set<string>();\n\n for (const line of targetLines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n // Normalize path for comparison (remove leading ./, handle different separators)\n const normalized = trimmed.replace(/^\\.\\//, '').replace(/\\\\/g, '/');\n existingEntries.add(normalized);\n }\n }\n\n // Extract new entries from template that don't already exist\n const newEntries: string[] = [];\n for (const line of templateLines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n const normalized = trimmed.replace(/^\\.\\//, '').replace(/\\\\/g, '/');\n if (!existingEntries.has(normalized)) {\n // Check for conflicts (e.g., !file vs file)\n const isNegation = normalized.startsWith('!');\n const basePath = isNegation ? normalized.slice(1) : normalized;\n const hasConflict = isNegation ? existingEntries.has(basePath) : existingEntries.has('!' + basePath);\n\n if (!hasConflict) {\n newEntries.push(trimmed);\n } else {\n console.info(`⚠ Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);\n }\n }\n }\n }\n\n // If no new entries, return original content\n if (newEntries.length === 0) {\n return targetContent;\n }\n\n // Build merged content\n const result: string[] = [...targetLines];\n\n // Add a blank line if the file doesn't end with one\n const lastLine = result[result.length - 1];\n if (result.length > 0 && lastLine && lastLine.trim() !== '') {\n result.push('');\n }\n\n // Add template section header\n result.push(`# Added by template: ${templateSlug}`);\n result.push(...newEntries);\n\n return result.join('\\n');\n};\n\n// Helper function to merge .env files intelligently\nexport const mergeEnvFiles = (\n targetContent: string,\n templateVariables: Record<string, string>,\n templateSlug: string,\n): string => {\n // Parse existing target .env file\n const targetLines = targetContent.replace(/\\r\\n/g, '\\n').split('\\n');\n const existingVars = new Set<string>();\n\n // Extract existing variable names (handle comments and empty lines)\n for (const line of targetLines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n const equalIndex = trimmed.indexOf('=');\n if (equalIndex > 0) {\n const varName = trimmed.substring(0, equalIndex).trim();\n existingVars.add(varName);\n }\n }\n }\n\n // Filter out variables that already exist\n const newVars: Array<{ key: string; value: string }> = [];\n for (const [key, value] of Object.entries(templateVariables)) {\n if (!existingVars.has(key)) {\n newVars.push({ key, value });\n } else {\n console.info(`⚠ Skipping existing environment variable: ${key} (already exists in .env)`);\n }\n }\n\n // If no new variables, return original content\n if (newVars.length === 0) {\n return targetContent;\n }\n\n // Build merged content\n const result: string[] = [...targetLines];\n\n // Add a blank line if the file doesn't end with one\n const lastLine = result[result.length - 1];\n if (result.length > 0 && lastLine && lastLine.trim() !== '') {\n result.push('');\n }\n\n // Add template section header\n result.push(`# Added by template: ${templateSlug}`);\n\n // Add new environment variables\n for (const { key, value } of newVars) {\n result.push(`${key}=${value}`);\n }\n\n return result.join('\\n');\n};\n\n// Helper function to detect AI SDK version from package.json\nexport const detectAISDKVersion = async (projectPath: string): Promise<'v1' | 'v2'> => {\n try {\n const packageJsonPath = join(projectPath, 'package.json');\n\n if (!existsSync(packageJsonPath)) {\n console.info('No package.json found, defaulting to v2');\n return 'v2';\n }\n\n const packageContent = await readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageContent);\n\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Check individual provider packages for version hints\n const providerPackages = ['@ai-sdk/openai', '@ai-sdk/anthropic', '@ai-sdk/google', '@ai-sdk/groq', '@ai-sdk/xai'];\n for (const pkg of providerPackages) {\n const version = allDeps[pkg];\n if (version) {\n const versionMatch = version.match(/(\\d+)/);\n if (versionMatch) {\n const majorVersion = parseInt(versionMatch[1]);\n if (majorVersion >= 2) {\n console.info(`Detected ${pkg} v${majorVersion} -> using v2 specification`);\n return 'v2';\n } else {\n console.info(`Detected ${pkg} v${majorVersion} -> using v1 specification`);\n return 'v1';\n }\n }\n }\n }\n\n console.info('No AI SDK version detected, defaulting to v2');\n return 'v2';\n } catch (error) {\n console.warn(`Failed to detect AI SDK version: ${error instanceof Error ? error.message : String(error)}`);\n return 'v2';\n }\n};\n\n// Helper function to create model instance based on provider and version\nexport const createModelInstance = async (\n provider: string,\n modelId: string,\n version: 'v1' | 'v2' = 'v2',\n): Promise<MastraLanguageModel | MastraLegacyLanguageModel | ModelRouterLanguageModel | null> => {\n try {\n // Dynamic imports to avoid issues if packages aren't available\n const providerMap = {\n v1: {\n openai: async () => {\n const { openai } = await import('@ai-sdk/openai');\n return openai(modelId);\n },\n anthropic: async () => {\n const { anthropic } = await import('@ai-sdk/anthropic');\n return anthropic(modelId);\n },\n groq: async () => {\n const { groq } = await import('@ai-sdk/groq');\n return groq(modelId);\n },\n xai: async () => {\n const { xai } = await import('@ai-sdk/xai');\n return xai(modelId);\n },\n google: async () => {\n const { google } = await import('@ai-sdk/google');\n return google(modelId);\n },\n },\n };\n\n const providerFn =\n version === `v1`\n ? providerMap[version][provider as keyof (typeof providerMap)[typeof version]]\n : () => new ModelRouterLanguageModel(`${provider}/${modelId}`);\n\n if (!providerFn) {\n console.error(`Unsupported provider: ${provider}`);\n return null;\n }\n\n const modelInstance = await providerFn();\n console.info(`Created ${provider} model instance (${version}): ${modelId}`);\n return modelInstance;\n } catch (error) {\n console.error(`Failed to create model instance: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n};\n\n// Helper function to resolve model from request context with AI SDK version detection\nexport const resolveModel = async ({\n requestContext,\n defaultModel = 'openai/gpt-4.1',\n projectPath,\n}: {\n requestContext: RequestContext;\n defaultModel?: MastraLanguageModel | MastraLegacyLanguageModel | string;\n projectPath?: string;\n}): Promise<MastraLanguageModel | MastraLegacyLanguageModel> => {\n // First try to get model from request context\n const modelFromContext = requestContext.get('model');\n if (modelFromContext) {\n console.info('Using model from request context');\n // Type check to ensure it's a MastraLanguageModel\n if (isValidMastraLanguageModel(modelFromContext)) {\n return modelFromContext;\n }\n throw new Error(\n 'Invalid model provided. Model must be a MastraLanguageModel instance (e.g., openai(\"gpt-4\"), anthropic(\"claude-3-5-sonnet\"), etc.)',\n );\n }\n\n // Check for selected model info in request context\n const selectedModel = requestContext.get('selectedModel') as { provider: string; modelId: string } | undefined;\n if (selectedModel?.provider && selectedModel?.modelId && projectPath) {\n console.info(`Resolving selected model: ${selectedModel.provider}/${selectedModel.modelId}`);\n\n // Detect AI SDK version from project\n const version = await detectAISDKVersion(projectPath);\n\n // Create model instance with detected version\n const modelInstance = await createModelInstance(selectedModel.provider, selectedModel.modelId, version);\n if (modelInstance) {\n // Store resolved model back in context for other steps to use\n requestContext.set('model', modelInstance);\n return modelInstance;\n }\n }\n\n console.info('Using default model');\n return typeof defaultModel === `string` ? new ModelRouterLanguageModel(defaultModel) : defaultModel;\n};\n","import { spawn as nodeSpawn } from 'node:child_process';\nimport { readFile, writeFile, mkdir, stat, readdir } from 'node:fs/promises';\nimport { join, dirname, relative, isAbsolute, resolve } from 'node:path';\nimport { createTool } from '@mastra/core/tools';\nimport ignore from 'ignore';\nimport { z } from 'zod';\nimport { exec, execFile, spawnSWPM, spawnWithOutput } from './utils';\n\ntype TaskManagerInputType = {\n action: 'create' | 'update' | 'list' | 'complete' | 'remove';\n tasks?: Array<{\n id: string;\n content?: string;\n status: 'pending' | 'in_progress' | 'completed' | 'blocked';\n priority: 'high' | 'medium' | 'low';\n dependencies?: string[];\n notes?: string;\n }>;\n taskId?: string;\n};\n\nexport class AgentBuilderDefaults {\n static DEFAULT_INSTRUCTIONS = (\n projectPath?: string,\n ) => `You are a Mastra Expert Agent, specialized in building production-ready AI applications using the Mastra framework. You excel at creating agents, tools, workflows, and complete applications with real, working implementations.\n\n## Core Identity & Capabilities\n\n**Primary Role:** Transform natural language requirements into working Mastra applications\n**Key Strength:** Deep knowledge of Mastra patterns, conventions, and best practices\n**Output Quality:** Production-ready code that follows Mastra ecosystem standards\n\n## Workflow: The MASTRA Method\n\nFollow this sequence for every coding task:\n\nIF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT\n\nDO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE\n\n### 1. 🔍 **UNDERSTAND** (Information Gathering)\n- **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs\n- **Analyze Project**: Use file exploration to understand existing codebase structure\n- **Web Research**: Search for packages, examples, or solutions when docs are insufficient\n- **Clarify Requirements**: Ask targeted questions only when critical information is missing\n\n### 2. 📋 **PLAN** (Strategy & Design)\n- **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)\n- **Dependencies**: Identify required packages and Mastra components\n- **Integration**: Plan how to integrate with existing project structure\n- **Validation**: Define how to test and verify the implementation\n\n### 3. 🛠️ **BUILD** (Implementation)\n- **Install First**: Use \\`manageProject\\` tool to install required packages\n- **Follow Patterns**: Implement using established Mastra conventions\n- **Real Code Only**: Build actual working functionality, never mock implementations\n- **Environment Setup**: Create proper .env configuration and documentation\n\n### 4. ✅ **VALIDATE** (Quality Assurance)\n- **Code Validation**: Run \\`validateCode\\` with types and lint checks\n- **Testing**: Execute tests if available\n- **Server Testing**: Use \\`manageServer\\` and \\`httpRequest\\` for API validation\n- **Fix Issues**: Address all errors before completion\n\n## Mastra-Specific Guidelines\n\n### Framework Knowledge\n- **Agents**: Use \\`@mastra/core/agent\\` with proper configuration\n- **Tools**: Create tools with \\`@mastra/core/tools\\` and proper schemas\n- **Memory**: Implement memory with \\`@mastra/memory\\` and appropriate processors\n- **Workflows**: Build workflows with \\`@mastra/core/workflows\\`\n- **Integrations**: Leverage Mastra's extensive integration ecosystem\n\n### Code Standards\n- **TypeScript First**: All code must be properly typed\n- **Zod Schemas**: Use Zod for all data validation\n- **Environment Variables**: Proper .env configuration with examples\n- **Error Handling**: Comprehensive error handling with meaningful messages\n- **Security**: Never expose credentials or sensitive data\n\n### Project Structure\n- Follow Mastra project conventions (\\`src/mastra/\\`, config files)\n- Use proper file organization (agents, tools, workflows in separate directories)\n- Maintain consistent naming conventions\n- Include proper exports and imports\n\n## Communication Style\n\n**Conciseness**: Keep responses focused and actionable\n**Clarity**: Explain complex concepts in simple terms\n**Directness**: State what you're doing and why\n**No Fluff**: Avoid unnecessary explanations or apologies\n\n### Response Format\n1. **Brief Status**: One line stating what you're doing\n2. **Tool Usage**: Execute necessary tools\n3. **Results Summary**: Concise summary of what was accomplished\n4. **Next Steps**: Clear indication of completion or next actions\n\n## Tool Usage Strategy\n\n### File Operations\n- **Project-Relative Paths**: All file paths are resolved relative to the project directory (unless absolute paths are used)\n- **Read First**: Always read files before editing to understand context\n- **Precise Edits**: Use exact text matching for search/replace operations\n- **Batch Operations**: Group related file operations when possible\n\n### Project Management\n- **manageProject**: Use for package installation, project creation, dependency management\n- **validateCode**: Always run after code changes to ensure quality\n- **manageServer**: Use for testing Mastra server functionality\n- **httpRequest**: Test API endpoints and integrations\n\n### Information Gathering\n- **Mastra Docs**: Primary source for Mastra-specific information\n- **Web Search**: Secondary source for packages and external solutions\n- **File Exploration**: Understand existing project structure and patterns\n\n## Error Handling & Recovery\n\n### Validation Failures\n- Fix TypeScript errors immediately\n- Address linting issues systematically\n- Re-validate until clean\n\n### Build Issues\n- Check dependencies and versions\n- Verify Mastra configuration\n- Test in isolation when needed\n\n### Integration Problems\n- Verify API keys and environment setup\n- Test connections independently\n- Debug with logging and error messages\n\n## Security & Best Practices\n\n**Never:**\n- Hard-code API keys or secrets\n- Generate mock or placeholder implementations\n- Skip error handling\n- Ignore TypeScript errors\n- Create insecure code patterns\n- ask for file paths, you should be able to use the provided tools to explore the file system\n\n**Always:**\n- Use environment variables for configuration\n- Implement proper input validation\n- Follow security best practices\n- Create complete, working implementations\n- Test thoroughly before completion\n\n## Output Requirements\n\n### Code Quality\n- ✅ TypeScript compilation passes\n- ✅ ESLint validation passes\n- ✅ Proper error handling implemented\n- ✅ Environment variables configured\n- ✅ Tests included when appropriate\n\n### Documentation\n- ✅ Clear setup instructions\n- ✅ Environment variable documentation\n- ✅ Usage examples provided\n- ✅ API documentation for custom tools\n\n### Integration\n- ✅ Follows Mastra conventions\n- ✅ Integrates with existing project\n- ✅ Proper imports and exports\n- ✅ Compatible with Mastra ecosystem\n\n## Project Context\n\n**Working Directory**: ${projectPath}\n**Focus**: Mastra framework applications\n**Goal**: Production-ready implementations\n\nRemember: You are building real applications, not prototypes. Every implementation should be complete, secure, and ready for production use.\n\n## Enhanced Tool Set\n\nYou have access to an enhanced set of tools based on production coding agent patterns:\n\n### Task Management\n- **taskManager**: Create and track multi-step coding tasks with states (pending, in_progress, completed, blocked). Use this for complex projects that require systematic progress tracking.\n\n### Code Discovery & Analysis\n- **codeAnalyzer**: Analyze codebase structure, discover definitions (functions, classes, interfaces), map dependencies, and understand architectural patterns.\n- **smartSearch**: Intelligent search with context awareness, pattern matching, and relevance scoring.\n\n### Advanced File Operations\n- **readFile**: Read files with optional line ranges, encoding support, metadata\n- **writeFile**: Write files with directory creation\n- **listDirectory**: Directory listing with filtering, recursion, metadata\n- **multiEdit**: Perform multiple search-replace operations across files atomically with backup creation\n- **executeCommand**: Execute shell commands with proper error handling and working directory support\n\n**Important**: All file paths are resolved relative to the project directory unless absolute paths are provided.\n\n### Communication & Workflow\n- **attemptCompletion**: Signal task completion with validation status and confidence metrics.\n\n### Guidelines for Enhanced Tools:\n\n1. **Use taskManager proactively** for any task requiring 3+ steps or complex coordination\n2. **Start with codeAnalyzer** when working with unfamiliar codebases to understand structure\n3. **Use smartSearch** for intelligent pattern discovery across the codebase\n4. **Apply multiEdit** for systematic refactoring across multiple files\n5. **Ask for clarification** when requirements are ambiguous rather than making assumptions\n6. **Signal completion** with comprehensive summaries and validation status\n\nUse the following basic examples to guide your implementation.\n\n<examples>\n### Weather Agent\n\\`\\`\\`\n// ./src/agents/weather-agent.ts\nimport { openai } from '@ai-sdk/openai';\nimport { Agent } from '@mastra/core/agent';\nimport { Memory } from '@mastra/memory';\nimport { LibSQLStore } from '@mastra/libsql';\nimport { weatherTool } from '../tools/weather-tool';\n\nexport const weatherAgent = new Agent({\n id: 'weather-agent',\n name: 'Weather Agent',\n instructions: \\${instructions},\n model: openai('gpt-4o-mini'),\n tools: { weatherTool },\n memory: new Memory({\n storage: new LibSQLStore({\n id: 'mastra-memory-storage',\n url: 'file:../mastra.db', // ask user what database to use, use this as the default\n }),\n }),\n});\n\\`\\`\\`\n\n### Weather Tool\n\\`\\`\\`\n// ./src/tools/weather-tool.ts\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\nimport { getWeather } from '../tools/weather-tool';\n\nexport const weatherTool = createTool({\n id: 'get-weather',\n description: 'Get current weather for a location',\n inputSchema: z.object({\n location: z.string().describe('City name'),\n }),\n outputSchema: z.object({\n temperature: z.number(),\n feelsLike: z.number(),\n humidity: z.number(),\n windSpeed: z.number(),\n windGust: z.number(),\n conditions: z.string(),\n location: z.string(),\n }),\n execute: async (inputData) => {\n return await getWeather(inputData.location);\n },\n});\n\\`\\`\\`\n\n### Weather Workflow\n\\`\\`\\`\n// ./src/workflows/weather-workflow.ts\nimport { createStep, createWorkflow } from '@mastra/core/workflows';\nimport { z } from 'zod';\n\nconst fetchWeather = createStep({\n id: 'fetch-weather',\n description: 'Fetches weather forecast for a given city',\n inputSchema: z.object({\n city: z.string().describe('The city to get the weather for'),\n }),\n outputSchema: forecastSchema,\n execute: async (inputData) => {\n if (!inputData) {\n throw new Error('Input data not found');\n }\n\n const geocodingUrl = \\`https://geocoding-api.open-meteo.com/v1/search?name=\\${encodeURIComponent(inputData.city)}&count=1\\`;\n const geocodingResponse = await fetch(geocodingUrl);\n const geocodingData = (await geocodingResponse.json()) as {\n results: { latitude: number; longitude: number; name: string }[];\n };\n\n if (!geocodingData.results?.[0]) {\n throw new Error(\\`Location '\\${inputData.city}' not found\\`);\n }\n\n const { latitude, longitude, name } = geocodingData.results[0];\n\n const weatherUrl = \\`https://api.open-meteo.com/v1/forecast?latitude=\\${latitude}&longitude=\\${longitude}¤t=precipitation,weathercode&timezone=auto,&hourly=precipitation_probability,temperature_2m\\`\n const response = await fetch(weatherUrl);\n const data = (await response.json()) as {\n current: {\n time: string;\n precipitation: number;\n weathercode: number;\n };\n hourly: {\n precipitation_probability: number[];\n temperature_2m: number[];\n };\n };\n\n const forecast = {\n date: new Date().toISOString(),\n maxTemp: Math.max(...data.hourly.temperature_2m),\n minTemp: Math.min(...data.hourly.temperature_2m),\n condition: getWeatherCondition(data.current.weathercode),\n precipitationChance: data.hourly.precipitation_probability.reduce(\n (acc, curr) => Math.max(acc, curr),\n 0,\n ),\n location: name,\n };\n\n return forecast;\n },\n});\n\nconst planActivities = createStep({\n id: 'plan-activities',\n description: 'Suggests activities based on weather conditions',\n inputSchema: forecastSchema,\n outputSchema: z.object({\n activities: z.string(),\n }),\n execute: async (inputData, context) => {\n const mastra = context?.mastra;\n const forecast = inputData;\n\n if (!forecast) {\n throw new Error('Forecast data not found');\n }\n\n const agent = mastra?.getAgent('weatherAgent');\n if (!agent) {\n throw new Error('Weather agent not found');\n }\n\n const prompt = \\${weatherWorkflowPrompt}\n\n const response = await agent.stream([\n {\n role: 'user',\n content: prompt,\n },\n ]);\n\n let activitiesText = '';\n\n for await (const chunk of response.textStream) {\n process.stdout.write(chunk);\n activitiesText += chunk;\n }\n\n return {\n activities: activitiesText,\n };\n },\n});\n\nconst weatherWorkflow = createWorkflow({\n id: 'weather-workflow',\n inputSchema: z.object({\n city: z.string().describe('The city to get the weather for'),\n }),\n outputSchema: z.object({\n activities: z.string(),\n }),\n})\n .then(fetchWeather)\n .then(planActivities);\n\nweatherWorkflow.commit();\n\\`\\`\\`\nexport { weatherWorkflow };\n\\`\\`\\`\n\n### Mastra instance\n\\`\\`\\`\n// ./src/mastra.ts\n\nimport { Mastra } from '@mastra/core/mastra';\nimport { PinoLogger } from '@mastra/loggers';\nimport { LibSQLStore } from '@mastra/libsql';\nimport { weatherWorkflow } from './workflows/weather-workflow';\nimport { weatherAgent } from './agents/weather-agent';\n\nexport const mastra = new Mastra({\n workflows: { weatherWorkflow },\n agents: { weatherAgent },\n storage: new LibSQLStore({\n id: 'mastra-storage',\n // stores observability, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db\n url: \":memory:\",\n }),\n logger: new PinoLogger({\n name: 'Mastra',\n level: 'info',\n }),\n});\n\\`\\`\\`\n\n</examples>`;\n\n static DEFAULT_MEMORY_CONFIG = {\n lastMessages: 20,\n };\n\n static DEFAULT_FOLDER_STRUCTURE = {\n agent: 'src/mastra/agents',\n workflow: 'src/mastra/workflows',\n tool: 'src/mastra/tools',\n 'mcp-server': 'src/mastra/mcp',\n network: 'src/mastra/networks',\n };\n\n static DEFAULT_TOOLS = async (projectPath: string) => {\n return {\n readFile: createTool({\n id: 'read-file',\n description: 'Read contents of a file with optional line range selection.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to read'),\n startLine: z.number().optional().describe('Starting line number (1-indexed)'),\n endLine: z.number().optional().describe('Ending line number (1-indexed, inclusive)'),\n encoding: z.string().default('utf-8').describe('File encoding'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n content: z.string().optional(),\n lines: z.array(z.string()).optional(),\n metadata: z\n .object({\n size: z.number(),\n totalLines: z.number(),\n encoding: z.string(),\n lastModified: z.string(),\n })\n .optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.readFile({ ...inputData, projectPath });\n },\n }),\n\n writeFile: createTool({\n id: 'write-file',\n description: 'Write content to a file, with options for creating directories.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to write'),\n content: z.string().describe('Content to write to the file'),\n createDirs: z.boolean().default(true).describe(\"Create parent directories if they don't exist\"),\n encoding: z.string().default('utf-8').describe('File encoding'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n filePath: z.string(),\n bytesWritten: z.number().optional(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.writeFile({ ...inputData, projectPath });\n },\n }),\n\n listDirectory: createTool({\n id: 'list-directory',\n description: 'List contents of a directory with filtering and metadata options.',\n inputSchema: z.object({\n path: z.string().describe('Directory path to list'),\n recursive: z.boolean().default(false).describe('List subdirectories recursively'),\n includeHidden: z.boolean().default(false).describe('Include hidden files and directories'),\n pattern: z.string().default('*').describe('Glob pattern to filter files'),\n maxDepth: z.number().default(10).describe('Maximum recursion depth'),\n includeMetadata: z.boolean().default(true).describe('Include file metadata'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n items: z.array(\n z.object({\n name: z.string(),\n path: z.string(),\n type: z.enum(['file', 'directory', 'symlink']),\n size: z.number().optional(),\n lastModified: z.string().optional(),\n permissions: z.string().optional(),\n }),\n ),\n totalItems: z.number(),\n path: z.string(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.listDirectory({ ...inputData, projectPath });\n },\n }),\n\n executeCommand: createTool({\n id: 'execute-command',\n description: 'Execute shell commands with proper error handling and output capture.',\n inputSchema: z.object({\n command: z.string().describe('Shell command to execute'),\n workingDirectory: z.string().optional().describe('Working directory for command execution'),\n timeout: z.number().default(30000).describe('Timeout in milliseconds'),\n captureOutput: z.boolean().default(true).describe('Capture command output'),\n shell: z.string().optional().describe('Shell to use (defaults to system shell)'),\n env: z.record(z.string(), z.string()).optional().describe('Environment variables'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n exitCode: z.number().optional(),\n stdout: z.string().optional(),\n stderr: z.string().optional(),\n command: z.string(),\n workingDirectory: z.string().optional(),\n executionTime: z.number().optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.executeCommand({\n ...inputData,\n workingDirectory: inputData.workingDirectory || projectPath,\n env: inputData.env as Record<string, string> | undefined,\n });\n },\n }),\n // Enhanced Task Management (Critical for complex coding tasks)\n taskManager: createTool({\n id: 'task-manager',\n description:\n 'Create and manage structured task lists for coding sessions. Use this for complex multi-step tasks to track progress and ensure thoroughness.',\n inputSchema: z.object({\n action: z.enum(['create', 'update', 'list', 'complete', 'remove']).describe('Task management action'),\n tasks: z\n .array(\n z.object({\n id: z.string().describe('Unique task identifier'),\n content: z.string().describe('Task description, optional if just updating the status').optional(),\n status: z.enum(['pending', 'in_progress', 'completed', 'blocked']).describe('Task status'),\n priority: z.enum(['high', 'medium', 'low']).default('medium').describe('Task priority'),\n dependencies: z.array(z.string()).optional().describe('IDs of tasks this depends on'),\n notes: z.string().optional().describe('Additional notes or context'),\n }),\n )\n .optional()\n .describe('Tasks to create or update'),\n taskId: z.string().optional().describe('Specific task ID for single task operations'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n tasks: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n status: z.string(),\n priority: z.string(),\n dependencies: z.array(z.string()).optional(),\n notes: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n }),\n ),\n message: z.string(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.manageTaskList(inputData as TaskManagerInputType);\n },\n }),\n\n // Advanced File Operations\n multiEdit: createTool({\n id: 'multi-edit',\n description: 'Perform multiple search-replace operations on one or more files in a single atomic operation.',\n inputSchema: z.object({\n operations: z\n .array(\n z.object({\n filePath: z.string().describe('Path to the file to edit'),\n edits: z\n .array(\n z.object({\n oldString: z.string().describe('Exact text to replace'),\n newString: z.string().describe('Replacement text'),\n replaceAll: z.boolean().default(false).describe('Replace all occurrences'),\n }),\n )\n .describe('List of edit operations for this file'),\n }),\n )\n .describe('File edit operations to perform'),\n createBackup: z.boolean().default(false).describe('Create backup files before editing'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n results: z.array(\n z.object({\n filePath: z.string(),\n editsApplied: z.number(),\n errors: z.array(z.string()),\n backup: z.string().optional(),\n }),\n ),\n message: z.string(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.performMultiEdit({ ...inputData, projectPath });\n },\n }),\n\n replaceLines: createTool({\n id: 'replace-lines',\n description:\n 'Replace specific line ranges in files with new content. IMPORTANT: This tool replaces ENTIRE lines, not partial content within lines. Lines are 1-indexed.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to edit'),\n startLine: z\n .number()\n .describe('Starting line number to replace (1-indexed, inclusive). Count from the first line = 1'),\n endLine: z\n .number()\n .describe(\n 'Ending line number to replace (1-indexed, inclusive). To replace single line, use same number as startLine',\n ),\n newContent: z\n .string()\n .describe(\n 'New content to replace the lines with. Use empty string \"\" to delete lines completely. For multiline content, include \\\\n characters',\n ),\n createBackup: z.boolean().default(false).describe('Create backup file before editing'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n message: z.string(),\n linesReplaced: z.number().optional(),\n backup: z.string().optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.replaceLines({ ...inputData, projectPath });\n },\n }),\n\n // File diagnostics tool to help debug line replacement issues\n showFileLines: createTool({\n id: 'show-file-lines',\n description:\n 'Show specific lines from a file with line numbers. Useful for debugging before using replaceLines.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to examine'),\n startLine: z\n .number()\n .optional()\n .describe('Starting line number to show (1-indexed). If not provided, shows all lines'),\n endLine: z\n .number()\n .optional()\n .describe(\n 'Ending line number to show (1-indexed, inclusive). If not provided but startLine is, shows only that line',\n ),\n context: z.number().default(2).describe('Number of context lines to show before and after the range'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n lines: z.array(\n z.object({\n lineNumber: z.number(),\n content: z.string(),\n isTarget: z.boolean().describe('Whether this line is in the target range'),\n }),\n ),\n totalLines: z.number(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.showFileLines({ ...inputData, projectPath });\n },\n }),\n\n // Enhanced Pattern Search\n smartSearch: createTool({\n id: 'smart-search',\n description: 'Intelligent search across codebase with context awareness and pattern matching.',\n inputSchema: z.object({\n query: z.string().describe('Search query or pattern'),\n type: z.enum(['text', 'regex', 'fuzzy', 'semantic']).default('text').describe('Type of search to perform'),\n scope: z\n .object({\n paths: z.array(z.string()).optional().describe('Specific paths to search'),\n fileTypes: z.array(z.string()).optional().describe('File extensions to include'),\n excludePaths: z.array(z.string()).optional().describe('Paths to exclude'),\n maxResults: z.number().default(50).describe('Maximum number of results'),\n })\n .optional(),\n context: z\n .object({\n beforeLines: z.number().default(2).describe('Lines of context before match'),\n afterLines: z.number().default(2).describe('Lines of context after match'),\n includeDefinitions: z.boolean().default(false).describe('Include function/class definitions'),\n })\n .optional(),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n matches: z.array(\n z.object({\n file: z.string(),\n line: z.number(),\n column: z.number().optional(),\n match: z.string(),\n context: z.object({\n before: z.array(z.string()),\n after: z.array(z.string()),\n }),\n relevance: z.number().optional(),\n }),\n ),\n summary: z.object({\n totalMatches: z.number(),\n filesSearched: z.number(),\n patterns: z.array(z.string()),\n }),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.performSmartSearch(inputData, projectPath);\n },\n }),\n\n validateCode: createTool({\n id: 'validate-code',\n description:\n 'Validates code using a fast hybrid approach: syntax → semantic → lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.',\n inputSchema: z.object({\n projectPath: z.string().optional().describe('Path to the project to validate (defaults to current project)'),\n validationType: z\n .array(z.enum(['types', 'lint', 'schemas', 'tests', 'build']))\n .describe('Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality'),\n files: z\n .array(z.string())\n .optional()\n .describe(\n 'RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check → semantic types → ESLint. Without files, falls back to slower CLI validation.',\n ),\n }),\n outputSchema: z.object({\n valid: z.boolean(),\n errors: z.array(\n z.object({\n type: z.enum(['typescript', 'eslint', 'schema', 'test', 'build']),\n severity: z.enum(['error', 'warning', 'info']),\n message: z.string(),\n file: z.string().optional(),\n line: z.number().optional(),\n column: z.number().optional(),\n code: z.string().optional(),\n }),\n ),\n summary: z.object({\n totalErrors: z.number(),\n totalWarnings: z.number(),\n validationsPassed: z.array(z.string()),\n validationsFailed: z.array(z.string()),\n }),\n }),\n execute: async inputData => {\n const { projectPath: validationProjectPath, validationType, files } = inputData;\n const targetPath = validationProjectPath || projectPath;\n\n // BEST PRACTICE: Always provide files array for optimal performance\n // Hybrid approach: syntax (1ms) → semantic (100ms) → ESLint (50ms)\n // Without files: falls back to CLI validation (2000ms+)\n\n return await AgentBuilderDefaults.validateCode({\n projectPath: targetPath,\n validationType,\n files,\n });\n },\n }),\n\n // Web Search (replaces MCP web search)\n webSearch: createTool({\n id: 'web-search',\n description: 'Search the web for current information and return structured results.',\n inputSchema: z.object({\n query: z.string().describe('Search query'),\n maxResults: z.number().default(10).describe('Maximum number of results to return'),\n region: z.string().default('us').describe('Search region/country code'),\n language: z.string().default('en').describe('Search language'),\n includeImages: z.boolean().default(false).describe('Include image results'),\n dateRange: z.enum(['day', 'week', 'month', 'year', 'all']).default('all').describe('Date range filter'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n query: z.string(),\n results: z.array(\n z.object({\n title: z.string(),\n url: z.string(),\n snippet: z.string(),\n domain: z.string(),\n publishDate: z.string().optional(),\n relevanceScore: z.number().optional(),\n }),\n ),\n totalResults: z.number(),\n searchTime: z.number(),\n suggestions: z.array(z.string()).optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.webSearch(inputData);\n },\n }),\n\n // Task Completion Signaling\n attemptCompletion: createTool({\n id: 'attempt-completion',\n description: 'Signal that you believe the requested task has been completed and provide a summary.',\n inputSchema: z.object({\n summary: z.string().describe('Summary of what was accomplished'),\n changes: z\n .array(\n z.object({\n type: z.enum(['file_created', 'file_modified', 'file_deleted', 'command_executed', 'dependency_added']),\n description: z.string(),\n path: z.string().optional(),\n }),\n )\n .describe('List of changes made'),\n validation: z\n .object({\n testsRun: z.boolean().default(false),\n buildsSuccessfully: z.boolean().default(false),\n manualTestingRequired: z.boolean().default(false),\n })\n .describe('Validation status'),\n nextSteps: z.array(z.string()).optional().describe('Suggested next steps or follow-up actions'),\n }),\n outputSchema: z.object({\n completionId: z.string(),\n status: z.enum(['completed', 'needs_review', 'needs_testing']),\n summary: z.string(),\n confidence: z.number().min(0).max(100),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.signalCompletion(inputData);\n },\n }),\n\n manageProject: createTool({\n id: 'manage-project',\n description:\n 'Handles project management including creating project structures, managing dependencies, and package operations.',\n inputSchema: z.object({\n action: z.enum(['create', 'install', 'upgrade']).describe('The action to perform'),\n features: z\n .array(z.string())\n .optional()\n .describe('Mastra features to include (e.g., [\"agents\", \"memory\", \"workflows\"])'),\n packages: z\n .array(\n z.object({\n name: z.string(),\n version: z.string().optional(),\n }),\n )\n .optional()\n .describe('Packages to install/upgrade'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n installed: z.array(z.string()).optional(),\n upgraded: z.array(z.string()).optional(),\n warnings: z.array(z.string()).optional(),\n message: z.string().optional(),\n details: z.string().optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n const { action, features, packages } = inputData;\n try {\n switch (action) {\n case 'create':\n return await AgentBuilderDefaults.createMastraProject({\n projectName: projectPath,\n features,\n });\n case 'install':\n if (!packages?.length) {\n return {\n success: false,\n message: 'Packages array is required for install action',\n };\n }\n return await AgentBuilderDefaults.installPackages({\n packages,\n projectPath,\n });\n case 'upgrade':\n if (!packages?.length) {\n return {\n success: false,\n message: 'Packages array is required for upgrade action',\n };\n }\n return await AgentBuilderDefaults.upgradePackages({\n packages,\n projectPath,\n });\n default:\n return {\n success: false,\n message: `Unknown action: ${action}`,\n };\n }\n } catch (error) {\n return {\n success: false,\n message: `Error executing ${action}: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n }),\n manageServer: createTool({\n id: 'manage-server',\n description:\n 'Manages the Mastra server - start, stop, restart, and check status, use the terminal tool to make curl requests to the server. There is an openapi spec for the server at http://localhost:{port}/openapi.json',\n inputSchema: z.object({\n action: z.enum(['start', 'stop', 'restart', 'status']).describe('Server management action'),\n port: z.number().optional().default(4200).describe('Port to run the server on'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n status: z.enum(['running', 'stopped', 'starting', 'stopping', 'unknown']),\n pid: z.number().optional(),\n port: z.number().optional(),\n url: z.string().optional(),\n message: z.string().optional(),\n stdout: z.array(z.string()).optional().describe('Server output lines captured during startup'),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n const { action, port } = inputData;\n try {\n switch (action) {\n case 'start':\n return await AgentBuilderDefaults.startMastraServer({\n port,\n projectPath,\n });\n case 'stop':\n return await AgentBuilderDefaults.stopMastraServer({\n port,\n projectPath,\n });\n case 'restart':\n const stopResult = await AgentBuilderDefaults.stopMastraServer({\n port,\n projectPath,\n });\n if (!stopResult.success) {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Failed to restart: could not stop server on port ${port}`,\n errorMessage: stopResult.errorMessage || 'Unknown stop error',\n };\n }\n await new Promise(resolve => setTimeout(resolve, 500));\n const startResult = await AgentBuilderDefaults.startMastraServer({\n port,\n projectPath,\n });\n if (!startResult.success) {\n return {\n success: false,\n status: 'stopped' as const,\n message: `Failed to restart: server stopped successfully but failed to start on port ${port}`,\n errorMessage: startResult.errorMessage || 'Unknown start error',\n };\n }\n return {\n ...startResult,\n message: `Mastra server restarted successfully on port ${port}`,\n };\n case 'status':\n return await AgentBuilderDefaults.checkMastraServerStatus({\n port,\n projectPath,\n });\n default:\n return {\n success: false,\n status: 'unknown' as const,\n message: `Unknown action: ${action}`,\n };\n }\n } catch (error) {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Error managing server: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n }),\n httpRequest: createTool({\n id: 'http-request',\n description: 'Makes HTTP requests to the Mastra server or external APIs for testing and integration',\n inputSchema: z.object({\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).describe('HTTP method'),\n url: z.string().describe('Full URL or path (if baseUrl provided)'),\n baseUrl: z.string().optional().describe('Base URL for the server (e.g., http://localhost:4200)'),\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n body: z.any().optional().describe('Request body (will be JSON stringified if object)'),\n timeout: z.number().optional().default(30000).describe('Request timeout in milliseconds'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n status: z.number().optional(),\n statusText: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n data: z.any().optional(),\n errorMessage: z.string().optional(),\n url: z.string(),\n method: z.string(),\n }),\n execute: async inputData => {\n const { method, url, baseUrl, headers, body, timeout } = inputData;\n try {\n return await AgentBuilderDefaults.makeHttpRequest({\n method,\n url,\n baseUrl,\n headers: headers as Record<string, string> | undefined,\n body,\n timeout,\n });\n } catch (error) {\n return {\n success: false,\n url: baseUrl ? `${baseUrl}${url}` : url,\n method,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n },\n }),\n };\n };\n\n /**\n * Filter tools for template builder mode (excludes web search and other advanced tools)\n */\n static filterToolsForTemplateBuilder(tools: Record<string, any>): Record<string, any> {\n const templateBuilderTools = [\n 'readFile',\n 'writeFile',\n 'listDirectory',\n 'executeCommand',\n 'taskManager',\n 'multiEdit',\n 'replaceLines',\n 'showFileLines',\n 'smartSearch',\n 'validateCode',\n ];\n\n const filtered: Record<string, ReturnType<typeof createTool>> = {};\n for (const toolName of templateBuilderTools) {\n if (tools[toolName]) {\n filtered[toolName] = tools[toolName];\n }\n }\n return filtered;\n }\n\n /**\n * Filter tools for code editor mode (includes all tools)\n */\n static filterToolsForCodeEditor(tools: Record<string, any>): Record<string, any> {\n return tools; // Return all tools for code editor mode\n }\n\n /**\n * Get tools for a specific mode\n */\n static async listToolsForMode(\n projectPath: string,\n mode: 'template' | 'code-editor' = 'code-editor',\n ): Promise<Record<string, any>> {\n const allTools = await AgentBuilderDefaults.DEFAULT_TOOLS(projectPath);\n\n if (mode === 'template') {\n return AgentBuilderDefaults.filterToolsForTemplateBuilder(allTools);\n } else {\n return AgentBuilderDefaults.filterToolsForCodeEditor(allTools);\n }\n }\n\n /**\n * Create a new Mastra project using create-mastra CLI\n */\n static async createMastraProject({ features, projectName }: { features?: string[]; projectName?: string }) {\n try {\n const args = ['pnpx', 'create-mastra@latest', projectName?.replace(/[;&|`$(){}\\[\\]]/g, '') ?? '', '-l', 'openai'];\n if (features && features.length > 0) {\n args.push('--components', features.join(','));\n }\n args.push('--example');\n\n const { stdout, stderr } = await spawnWithOutput(args[0]!, args.slice(1), {});\n\n return {\n success: true,\n projectPath: `./${projectName}`,\n message: `Successfully created Mastra project: ${projectName}.`,\n details: stdout,\n errorMessage: stderr,\n };\n } catch (error) {\n console.error(error);\n return {\n success: false,\n message: `Failed to create project: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Install packages using the detected package manager\n */\n static async installPackages({\n packages,\n projectPath,\n }: {\n packages: Array<{ name: string; version?: string }>;\n projectPath?: string;\n }) {\n try {\n console.info('Installing packages:', JSON.stringify(packages, null, 2));\n\n const packageStrings = packages.map(p => `${p.name}`);\n\n await spawnSWPM(projectPath || '', 'add', packageStrings);\n\n return {\n success: true,\n installed: packageStrings,\n message: `Successfully installed ${packages.length} package(s).`,\n details: '',\n };\n } catch (error) {\n return {\n success: false,\n message: `Failed to install packages: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Upgrade packages using the detected package manager\n */\n static async upgradePackages({\n packages,\n projectPath,\n }: {\n packages?: Array<{ name: string; version?: string }>;\n projectPath?: string;\n }) {\n try {\n console.info('Upgrading specific packages:', JSON.stringify(packages, null, 2));\n\n let packageNames: string[] = [];\n\n if (packages && packages.length > 0) {\n packageNames = packages.map(p => `${p.name}`);\n }\n await spawnSWPM(projectPath || '', 'upgrade', packageNames);\n\n return {\n success: true,\n upgraded: packages?.map(p => p.name) || ['all packages'],\n message: `Packages upgraded successfully.`,\n details: '',\n };\n } catch (error) {\n return {\n success: false,\n message: `Failed to upgrade packages: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Start the Mastra server\n */\n static async startMastraServer({\n port = 4200,\n projectPath,\n env = {},\n }: {\n port?: number;\n projectPath?: string;\n env?: Record<string, string>;\n }) {\n try {\n const serverEnv = { ...process.env, ...env, PORT: port.toString() };\n const execOptions = {\n cwd: projectPath || process.cwd(),\n env: serverEnv,\n };\n\n const serverProcess = nodeSpawn('pnpm', ['run', 'dev'], {\n ...execOptions,\n detached: true,\n stdio: 'pipe',\n });\n\n const stdoutLines: string[] = [];\n\n const serverStarted = new Promise<any>((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(`Server startup timeout after 30 seconds. Output: ${stdoutLines.join('\\n')}`));\n }, 30000);\n\n serverProcess.stdout?.on('data', data => {\n const output = data.toString();\n const lines = output.split('\\n').filter((line: string) => line.trim());\n stdoutLines.push(...lines);\n\n if (output.includes('Mastra API running')) {\n clearTimeout(timeout);\n resolve({\n success: true,\n status: 'running' as const,\n pid: serverProcess.pid,\n port,\n url: `http://localhost:${port}`,\n message: `Mastra server started successfully on port ${port}`,\n stdout: stdoutLines,\n });\n }\n });\n\n serverProcess.stderr?.on('data', data => {\n const errorOutput = data.toString();\n stdoutLines.push(`[STDERR] ${errorOutput}`);\n clearTimeout(timeout);\n reject(new Error(`Server startup failed with error: ${errorOutput}`));\n });\n\n serverProcess.on('error', error => {\n clearTimeout(timeout);\n reject(error);\n });\n\n serverProcess.on('exit', (code, signal) => {\n clearTimeout(timeout);\n if (code !== 0 && code !== null) {\n reject(\n new Error(\n `Server process exited with code ${code}${signal ? ` (signal: ${signal})` : ''}. Output: ${stdoutLines.join('\\n')}`,\n ),\n );\n }\n });\n });\n\n return await serverStarted;\n } catch (error) {\n return {\n success: false,\n status: 'stopped' as const,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Stop the Mastra server\n */\n static async stopMastraServer({ port = 4200, projectPath: _projectPath }: { port?: number; projectPath?: string }) {\n // Validate port to ensure it is a safe integer\n if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535) {\n return {\n success: false,\n status: 'error' as const,\n errorMessage: `Invalid port value: ${String(port)}`,\n };\n }\n try {\n // Run lsof safely without shell interpretation\n const { stdout } = await execFile('lsof', ['-ti', String(port)]);\n // If no output, treat as \"No process found\"\n const effectiveStdout = stdout.trim() ? stdout : 'No process found';\n\n if (!effectiveStdout || effectiveStdout === 'No process found') {\n return {\n success: true,\n status: 'stopped' as const,\n message: `No Mastra server found running on port ${port}`,\n };\n }\n\n const pids = stdout\n .trim()\n .split('\\n')\n .filter((pid: string) => pid.trim());\n const killedPids: number[] = [];\n const failedPids: number[] = [];\n\n for (const pidStr of pids) {\n const pid = parseInt(pidStr.trim());\n if (isNaN(pid)) continue;\n\n try {\n process.kill(pid, 'SIGTERM');\n killedPids.push(pid);\n } catch (e) {\n failedPids.push(pid);\n console.warn(`Failed to kill process ${pid}:`, e);\n }\n }\n\n // If some processes failed to be killed, still report partial success\n // but include warning about failed processes\n\n if (killedPids.length === 0) {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Failed to stop any processes on port ${port}`,\n errorMessage: `Could not kill PIDs: ${failedPids.join(', ')}`,\n };\n }\n\n // Report partial success if some processes were killed but others failed\n if (failedPids.length > 0) {\n console.warn(\n `Killed ${killedPids.length} processes but failed to kill ${failedPids.length} processes: ${failedPids.join(', ')}`,\n );\n }\n\n // Wait a bit and check if processes are still running\n await new Promise(resolve => setTimeout(resolve, 2000));\n\n try {\n const { stdout: checkStdoutRaw } = await execFile('lsof', ['-ti', String(port)]);\n const checkStdout = checkStdoutRaw.trim() ? checkStdoutRaw : 'No process found';\n if (checkStdout && checkStdout !== 'No process found') {\n // Force kill remaining processes\n const remainingPids = checkStdout\n .trim()\n .split('\\n')\n .filter((pid: string) => pid.trim());\n for (const pidStr of remainingPids) {\n const pid = parseInt(pidStr.trim());\n if (!isNaN(pid)) {\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n // ignore\n }\n }\n }\n\n // Final check\n await new Promise(resolve => setTimeout(resolve, 1000));\n const { stdout: finalCheckRaw } = await execFile('lsof', ['-ti', String(port)]);\n const finalCheck = finalCheckRaw.trim() ? finalCheckRaw : 'No process found';\n if (finalCheck && finalCheck !== 'No process found') {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Server processes still running on port ${port} after stop attempts`,\n errorMessage: `Remaining PIDs: ${finalCheck.trim()}`,\n };\n }\n }\n } catch (error) {\n console.warn('Failed to verify server stop:', error);\n }\n\n return {\n success: true,\n status: 'stopped' as const,\n message: `Mastra server stopped successfully (port ${port}). Killed PIDs: ${killedPids.join(', ')}`,\n };\n } catch (error) {\n return {\n success: false,\n status: 'unknown' as const,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Check Mastra server status\n */\n static async checkMastraServerStatus({\n port = 4200,\n projectPath: _projectPath,\n }: {\n port?: number;\n projectPath?: string;\n }) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 5000);\n\n const response = await fetch(`http://localhost:${port}/health`, {\n method: 'GET',\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n return {\n success: true,\n status: 'running' as const,\n port,\n url: `http://localhost:${port}`,\n message: 'Mastra server is running and healthy',\n };\n } else {\n return {\n success: false,\n status: 'unknown' as const,\n port,\n message: `Server responding but not healthy (status: ${response.status})`,\n };\n }\n } catch {\n // Check if process exists on port\n try {\n const { stdout } = await execFile('lsof', ['-ti', String(port)]);\n const effectiveStdout = stdout.trim() ? stdout : 'No process found';\n const hasProcess = effectiveStdout && effectiveStdout !== 'No process found';\n\n return {\n success: Boolean(hasProcess),\n status: hasProcess ? ('starting' as const) : ('stopped' as const),\n port,\n message: hasProcess\n ? 'Server process exists but not responding to health checks'\n : 'No server process found on specified port',\n };\n } catch {\n return {\n success: false,\n status: 'stopped' as const,\n port,\n message: 'Server is not running',\n };\n }\n }\n }\n\n // Cache for TypeScript program (lazily loaded)\n private static tsProgram: any | null = null;\n private static programProjectPath: string | null = null;\n\n /**\n * Validate code using hybrid approach: syntax -> types -> lint\n *\n * BEST PRACTICES FOR CODING AGENTS:\n *\n * ✅ RECOMMENDED (Fast & Accurate):\n * validateCode({\n * validationType: ['types', 'lint'],\n * files: ['src/workflows/my-workflow.ts', 'src/components/Button.tsx']\n * })\n *\n * Performance: ~150ms\n * - Syntax check (1ms) - catches 80% of issues instantly\n * - Semantic validation (100ms) - full type checking with dependencies\n * - ESLint (50ms) - style and best practices\n * - Only shows errors from YOUR files\n *\n * ❌ AVOID (Slow & Noisy):\n * validateCode({ validationType: ['types', 'lint'] }) // no files specified\n *\n * Performance: ~2000ms+\n * - Full project CLI validation\n * - Shows errors from all project files (confusing)\n * - Much slower for coding agents\n *\n * @param projectPath - Project root directory (defaults to cwd)\n * @param validationType - ['types', 'lint'] recommended for most use cases\n * @param files - ALWAYS provide this for best performance\n */\n static async validateCode({\n projectPath,\n validationType,\n files,\n }: {\n projectPath?: string;\n validationType: Array<'types' | 'lint' | 'schemas' | 'tests' | 'build'>;\n files?: string[];\n }) {\n const errors: Array<{\n type: 'typescript' | 'eslint' | 'schema' | 'test' | 'build';\n severity: 'error' | 'warning' | 'info';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n const validationsPassed: string[] = [];\n const validationsFailed: string[] = [];\n\n const targetProjectPath = projectPath || process.cwd();\n\n // If no files specified, use legacy CLI-based validation for backward compatibility\n if (!files || files.length === 0) {\n return this.validateCodeCLI({ projectPath, validationType });\n }\n\n // Hybrid validation approach for specific files (default behavior)\n for (const filePath of files) {\n const absolutePath = isAbsolute(filePath) ? filePath : resolve(targetProjectPath, filePath);\n\n try {\n const fileContent = await readFile(absolutePath, 'utf-8');\n const fileResults = await this.validateSingleFileHybrid(\n absolutePath,\n fileContent,\n targetProjectPath,\n validationType,\n );\n\n errors.push(...fileResults.errors);\n\n // Track validation results\n for (const type of validationType) {\n const hasErrors = fileResults.errors.some(e => e.type === type && e.severity === 'error');\n if (hasErrors) {\n if (!validationsFailed.includes(type)) validationsFailed.push(type);\n } else {\n if (!validationsPassed.includes(type)) validationsPassed.push(type);\n }\n }\n } catch (error) {\n errors.push({\n type: 'typescript',\n severity: 'error',\n message: `Failed to read file ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n file: filePath,\n });\n validationsFailed.push('types');\n }\n }\n\n const totalErrors = errors.filter(e => e.severity === 'error').length;\n const totalWarnings = errors.filter(e => e.severity === 'warning').length;\n const isValid = totalErrors === 0;\n\n return {\n valid: isValid,\n errors,\n summary: {\n totalErrors,\n totalWarnings,\n validationsPassed,\n validationsFailed,\n },\n };\n }\n\n /**\n * CLI-based validation for when no specific files are provided\n */\n static async validateCodeCLI({\n projectPath,\n validationType,\n }: {\n projectPath?: string;\n validationType: Array<'types' | 'lint' | 'schemas' | 'tests' | 'build'>;\n }) {\n const errors: Array<{\n type: 'typescript' | 'eslint' | 'schema' | 'test' | 'build';\n severity: 'error' | 'warning' | 'info';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n const validationsPassed: string[] = [];\n const validationsFailed: string[] = [];\n\n const execOptions = { cwd: projectPath };\n\n // TypeScript validation (legacy approach)\n if (validationType.includes('types')) {\n try {\n // Use execFile for safe argument passing to avoid shell interpretation\n const args = ['tsc', '--noEmit'];\n await execFile('npx', args, execOptions);\n validationsPassed.push('types');\n } catch (error: any) {\n let tsOutput = '';\n if (error.stdout) {\n tsOutput = error.stdout;\n } else if (error.stderr) {\n tsOutput = error.stderr;\n } else if (error.message) {\n tsOutput = error.message;\n }\n\n errors.push({\n type: 'typescript',\n severity: 'error',\n message: tsOutput.trim() || `TypeScript validation failed: ${error.message || String(error)}`,\n });\n validationsFailed.push('types');\n }\n }\n\n // ESLint validation\n if (validationType.includes('lint')) {\n try {\n const eslintArgs = ['eslint', '--format', 'json'];\n const { stdout } = await execFile('npx', eslintArgs, execOptions);\n\n if (stdout) {\n const eslintResults = JSON.parse(stdout);\n const eslintErrors = AgentBuilderDefaults.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n\n if (eslintErrors.some(e => e.severity === 'error')) {\n validationsFailed.push('lint');\n } else {\n validationsPassed.push('lint');\n }\n } else {\n validationsPassed.push('lint');\n }\n } catch (error: any) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (errorMessage.includes('\"filePath\"') || errorMessage.includes('messages')) {\n try {\n const eslintResults = JSON.parse(errorMessage);\n const eslintErrors = AgentBuilderDefaults.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n validationsFailed.push('lint');\n } catch {\n errors.push({\n type: 'eslint',\n severity: 'error',\n message: `ESLint validation failed: ${errorMessage}`,\n });\n validationsFailed.push('lint');\n }\n } else {\n validationsPassed.push('lint');\n }\n }\n }\n\n const totalErrors = errors.filter(e => e.severity === 'error').length;\n const totalWarnings = errors.filter(e => e.severity === 'warning').length;\n const isValid = totalErrors === 0;\n\n return {\n valid: isValid,\n errors,\n summary: {\n totalErrors,\n totalWarnings,\n validationsPassed,\n validationsFailed,\n },\n };\n }\n\n /**\n * Hybrid validation for a single file\n */\n static async validateSingleFileHybrid(\n filePath: string,\n fileContent: string,\n projectPath: string,\n validationType: Array<'types' | 'lint' | 'schemas' | 'tests' | 'build'>,\n ) {\n const errors: Array<{\n type: 'typescript' | 'eslint' | 'schema' | 'test' | 'build';\n severity: 'error' | 'warning' | 'info';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n\n // Step 1: Fast syntax validation\n if (validationType.includes('types')) {\n const syntaxErrors = await this.validateSyntaxOnly(fileContent, filePath);\n errors.push(...syntaxErrors);\n\n // Fail fast on syntax errors\n if (syntaxErrors.length > 0) {\n return { errors };\n }\n\n // Step 2: TypeScript semantic validation (if syntax is clean)\n const typeErrors = await this.validateTypesSemantic(filePath, projectPath);\n errors.push(...typeErrors);\n }\n\n // Step 3: ESLint validation (only if no critical errors)\n if (validationType.includes('lint') && !errors.some(e => e.severity === 'error')) {\n const lintErrors = await this.validateESLintSingle(filePath, projectPath);\n errors.push(...lintErrors);\n }\n\n return { errors };\n }\n\n /**\n * Fast syntax-only validation using TypeScript parser\n */\n static async validateSyntaxOnly(fileContent: string, fileName: string) {\n const errors: Array<{\n type: 'typescript';\n severity: 'error';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n }> = [];\n\n try {\n // Dynamically import TypeScript to avoid bundling issues\n const ts = await import('typescript');\n\n const sourceFile = ts.createSourceFile(fileName, fileContent, ts.ScriptTarget.Latest, true);\n\n // Create a minimal program to get syntax diagnostics\n const options: any = {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n };\n\n const host: any = {\n getSourceFile: (name: string) => (name === fileName ? sourceFile : undefined),\n writeFile: () => {},\n getCurrentDirectory: () => '',\n getDirectories: () => [],\n fileExists: (name: string) => name === fileName,\n readFile: (name: string) => (name === fileName ? fileContent : undefined),\n getCanonicalFileName: (name: string) => name,\n useCaseSensitiveFileNames: () => true,\n getNewLine: () => '\\n',\n getDefaultLibFileName: () => 'lib.d.ts',\n };\n\n const program = ts.createProgram([fileName], options, host);\n const diagnostics = program.getSyntacticDiagnostics(sourceFile);\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.start !== undefined) {\n const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start);\n errors.push({\n type: 'typescript',\n severity: 'error',\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n file: fileName,\n line: position.line + 1,\n column: position.character + 1,\n });\n }\n }\n } catch (error) {\n // If TypeScript is not available, fall back to basic validation\n console.warn('TypeScript not available for syntax validation:', error);\n\n // Basic syntax check - look for common syntax errors\n const lines = fileContent.split('\\n');\n const commonErrors = [\n { pattern: /\\bimport\\s+.*\\s+from\\s+['\"\"][^'\"]*$/, message: 'Unterminated import statement' },\n { pattern: /\\{[^}]*$/, message: 'Unclosed brace' },\n { pattern: /\\([^)]*$/, message: 'Unclosed parenthesis' },\n { pattern: /\\[[^\\]]*$/, message: 'Unclosed bracket' },\n ];\n\n lines.forEach((line, index) => {\n commonErrors.forEach(({ pattern, message }) => {\n if (pattern.test(line)) {\n errors.push({\n type: 'typescript',\n severity: 'error',\n message,\n file: fileName,\n line: index + 1,\n });\n }\n });\n });\n }\n\n return errors;\n }\n\n /**\n * TypeScript semantic validation using incremental program\n */\n static async validateTypesSemantic(filePath: string, projectPath: string) {\n const errors: Array<{\n type: 'typescript';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n }> = [];\n\n try {\n // Initialize or reuse TypeScript program\n const program = await this.getOrCreateTSProgram(projectPath);\n if (!program) {\n return errors; // Fallback to no validation if program creation fails\n }\n\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) {\n return errors; // File not in program\n }\n\n const diagnostics = [\n ...program.getSemanticDiagnostics(sourceFile),\n ...program.getSyntacticDiagnostics(sourceFile),\n ];\n\n // Dynamically import TypeScript for diagnostic processing\n const ts = await import('typescript');\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.start !== undefined) {\n const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start);\n errors.push({\n type: 'typescript',\n severity: diagnostic.category === ts.DiagnosticCategory.Warning ? 'warning' : 'error',\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n file: filePath,\n line: position.line + 1,\n column: position.character + 1,\n });\n }\n }\n } catch (error) {\n // Fallback to no semantic validation on error\n console.warn(`TypeScript semantic validation failed for ${filePath}:`, error);\n }\n\n return errors;\n }\n\n /**\n * ESLint validation for a single file\n */\n static async validateESLintSingle(filePath: string, projectPath: string) {\n const errors: Array<{\n type: 'eslint';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n\n try {\n const { stdout } = await execFile('npx', ['eslint', filePath, '--format', 'json'], { cwd: projectPath });\n\n if (stdout) {\n const eslintResults = JSON.parse(stdout);\n const eslintErrors = this.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n }\n } catch (error: any) {\n // Try to parse error output\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes('\"filePath\"') || errorMessage.includes('messages')) {\n try {\n const eslintResults = JSON.parse(errorMessage);\n const eslintErrors = this.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n } catch {\n // Ignore ESLint errors in hybrid mode for now\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get or create TypeScript program\n */\n static async getOrCreateTSProgram(projectPath: string): Promise<any | null> {\n // Return cached program if same project\n if (this.tsProgram && this.programProjectPath === projectPath) {\n return this.tsProgram;\n }\n\n try {\n // Dynamically import TypeScript\n const ts = await import('typescript');\n\n const configPath = ts.findConfigFile(projectPath, ts.sys.fileExists, 'tsconfig.json');\n if (!configPath) {\n return null; // No tsconfig found\n }\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (configFile.error) {\n return null;\n }\n\n const parsedConfig = ts.parseJsonConfigFileContent(configFile.config, ts.sys, projectPath);\n\n if (parsedConfig.errors.length > 0) {\n return null;\n }\n\n // Create regular program\n this.tsProgram = ts.createProgram({\n rootNames: parsedConfig.fileNames,\n options: parsedConfig.options,\n });\n\n this.programProjectPath = projectPath;\n return this.tsProgram;\n } catch (error) {\n console.warn('Failed to create TypeScript program:', error);\n return null;\n }\n }\n\n // Note: Old filterTypeScriptErrors method removed in favor of hybrid validation approach\n\n /**\n * Parse ESLint errors from JSON output\n */\n static parseESLintErrors(eslintResults: any[]): Array<{\n type: 'eslint';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> {\n const errors: Array<{\n type: 'eslint';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n\n for (const result of eslintResults) {\n for (const message of result.messages || []) {\n if (message.message) {\n errors.push({\n type: 'eslint',\n severity: message.severity === 1 ? 'warning' : 'error',\n message: message.message,\n file: result.filePath || undefined,\n line: message.line || undefined,\n column: message.column || undefined,\n code: message.ruleId || undefined,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Make HTTP request to server or external API\n */\n static async makeHttpRequest({\n method,\n url,\n baseUrl,\n headers = {},\n body,\n timeout = 30000,\n }: {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n url: string;\n baseUrl?: string;\n headers?: Record<string, string>;\n body?: any;\n timeout?: number;\n }) {\n try {\n const fullUrl = baseUrl ? `${baseUrl}${url}` : url;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const requestOptions: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n signal: controller.signal,\n };\n\n if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {\n requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);\n }\n\n const response = await fetch(fullUrl, requestOptions);\n clearTimeout(timeoutId);\n\n let data: any;\n const contentType = response.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n data = await response.json();\n } else {\n data = await response.text();\n }\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n return {\n success: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n data,\n url: fullUrl,\n method,\n };\n } catch (error) {\n return {\n success: false,\n url: baseUrl ? `${baseUrl}${url}` : url,\n method,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Enhanced task management system for complex coding tasks\n */\n static async manageTaskList(context: {\n action: 'create' | 'update' | 'list' | 'complete' | 'remove';\n tasks?: Array<{\n id: string;\n content?: string;\n status: 'pending' | 'in_progress' | 'completed' | 'blocked';\n priority: 'high' | 'medium' | 'low';\n dependencies?: string[];\n notes?: string;\n }>;\n taskId?: string;\n }) {\n // In-memory task storage (could be enhanced with persistent storage)\n if (!AgentBuilderDefaults.taskStorage) {\n AgentBuilderDefaults.taskStorage = new Map();\n }\n\n // Cleanup old sessions to prevent memory leaks\n // Keep only the last 10 sessions\n const sessions = Array.from(AgentBuilderDefaults.taskStorage.keys());\n if (sessions.length > 10) {\n const sessionsToRemove = sessions.slice(0, sessions.length - 10);\n sessionsToRemove.forEach(session => AgentBuilderDefaults.taskStorage.delete(session));\n }\n\n const sessionId = 'current'; // Could be enhanced with proper session management\n const existingTasks = AgentBuilderDefaults.taskStorage.get(sessionId) || [];\n\n try {\n switch (context.action) {\n case 'create':\n if (!context.tasks?.length) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'No tasks provided for creation',\n };\n }\n\n const newTasks = context.tasks.map(task => ({\n ...task,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n }));\n\n const allTasks = [...existingTasks, ...newTasks];\n AgentBuilderDefaults.taskStorage.set(sessionId, allTasks);\n\n return {\n success: true,\n tasks: allTasks,\n message: `Created ${newTasks.length} new task(s)`,\n };\n\n case 'update':\n if (!context.tasks?.length) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'No tasks provided for update',\n };\n }\n\n const updatedTasks = existingTasks.map(existing => {\n const update = context.tasks!.find(t => t.id === existing.id);\n return update ? { ...existing, ...update, updatedAt: new Date().toISOString() } : existing;\n });\n\n AgentBuilderDefaults.taskStorage.set(sessionId, updatedTasks);\n\n return {\n success: true,\n tasks: updatedTasks,\n message: 'Tasks updated successfully',\n };\n\n case 'complete':\n if (!context.taskId) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'Task ID required for completion',\n };\n }\n\n const completedTasks = existingTasks.map(task =>\n task.id === context.taskId\n ? { ...task, status: 'completed' as const, updatedAt: new Date().toISOString() }\n : task,\n );\n\n AgentBuilderDefaults.taskStorage.set(sessionId, completedTasks);\n\n return {\n success: true,\n tasks: completedTasks,\n message: `Task ${context.taskId} marked as completed`,\n };\n\n case 'remove':\n if (!context.taskId) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'Task ID required for removal',\n };\n }\n\n const filteredTasks = existingTasks.filter(task => task.id !== context.taskId);\n AgentBuilderDefaults.taskStorage.set(sessionId, filteredTasks);\n\n return {\n success: true,\n tasks: filteredTasks,\n message: `Task ${context.taskId} removed`,\n };\n\n case 'list':\n default:\n return {\n success: true,\n tasks: existingTasks,\n message: `Found ${existingTasks.length} task(s)`,\n };\n }\n } catch (error) {\n return {\n success: false,\n tasks: existingTasks,\n message: `Task management error: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Perform multiple edits across files atomically\n */\n static async performMultiEdit(context: {\n operations: Array<{\n filePath: string;\n edits: Array<{\n oldString: string;\n newString: string;\n replaceAll?: boolean;\n }>;\n }>;\n createBackup?: boolean;\n projectPath?: string;\n }) {\n const { operations, createBackup = false, projectPath = process.cwd() } = context;\n const results: Array<{\n filePath: string;\n editsApplied: number;\n errors: string[];\n backup?: string;\n }> = [];\n\n try {\n for (const operation of operations) {\n const filePath = isAbsolute(operation.filePath) ? operation.filePath : join(projectPath, operation.filePath);\n let editsApplied = 0;\n const errors: string[] = [];\n let backup: string | undefined;\n\n try {\n // Create backup if requested\n if (createBackup) {\n const backupPath = `${filePath}.backup.${Date.now()}`;\n const originalContent = await readFile(filePath, 'utf-8');\n await writeFile(backupPath, originalContent, 'utf-8');\n backup = backupPath;\n }\n\n // Read current file content\n let content = await readFile(filePath, 'utf-8');\n\n // Apply each edit\n for (const edit of operation.edits) {\n const { oldString, newString, replaceAll = false } = edit;\n\n if (replaceAll) {\n const regex = new RegExp(oldString.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g');\n const matches = content.match(regex);\n if (matches) {\n content = content.replace(regex, newString);\n editsApplied += matches.length;\n }\n } else {\n if (content.includes(oldString)) {\n content = content.replace(oldString, newString);\n editsApplied++;\n } else {\n errors.push(`String not found: \"${oldString.substring(0, 50)}${oldString.length > 50 ? '...' : ''}\"`);\n }\n }\n }\n\n // Write updated content back\n await writeFile(filePath, content, 'utf-8');\n } catch (error) {\n errors.push(`File operation error: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n results.push({\n filePath: operation.filePath,\n editsApplied,\n errors,\n backup,\n });\n }\n\n const totalEdits = results.reduce((sum, r) => sum + r.editsApplied, 0);\n const totalErrors = results.reduce((sum, r) => sum + r.errors.length, 0);\n\n return {\n success: totalErrors === 0,\n results,\n message: `Applied ${totalEdits} edits across ${operations.length} files${totalErrors > 0 ? ` with ${totalErrors} errors` : ''}`,\n };\n } catch (error) {\n return {\n success: false,\n results,\n message: `Multi-edit operation failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Replace specific line ranges in a file with new content\n */\n static async replaceLines(context: {\n filePath: string;\n startLine: number;\n endLine: number;\n newContent: string;\n createBackup?: boolean;\n projectPath?: string;\n }) {\n const { filePath, startLine, endLine, newContent, createBackup = false, projectPath = process.cwd() } = context;\n\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(projectPath, filePath);\n\n // Read current file content\n const content = await readFile(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n // Validate line numbers\n if (startLine < 1 || endLine < 1) {\n return {\n success: false,\n message: `Line numbers must be 1 or greater. Got startLine: ${startLine}, endLine: ${endLine}`,\n errorMessage: 'Invalid line range',\n };\n }\n\n if (startLine > lines.length || endLine > lines.length) {\n return {\n success: false,\n 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}.`,\n errorMessage: 'Invalid line range',\n };\n }\n\n if (startLine > endLine) {\n return {\n success: false,\n message: `Start line (${startLine}) cannot be greater than end line (${endLine}).`,\n errorMessage: 'Invalid line range',\n };\n }\n\n // Create backup if requested\n let backup: string | undefined;\n if (createBackup) {\n const backupPath = `${fullPath}.backup.${Date.now()}`;\n await writeFile(backupPath, content, 'utf-8');\n backup = backupPath;\n }\n\n // Replace the specified line range\n const beforeLines = lines.slice(0, startLine - 1);\n const afterLines = lines.slice(endLine);\n const newLines = newContent ? newContent.split('\\n') : [];\n\n const updatedLines = [...beforeLines, ...newLines, ...afterLines];\n const updatedContent = updatedLines.join('\\n');\n\n // Write updated content back\n await writeFile(fullPath, updatedContent, 'utf-8');\n\n const linesReplaced = endLine - startLine + 1;\n const newLineCount = newLines.length;\n\n return {\n success: true,\n message: `Successfully replaced ${linesReplaced} lines (${startLine}-${endLine}) with ${newLineCount} new lines in ${filePath}`,\n linesReplaced,\n backup,\n };\n } catch (error) {\n return {\n success: false,\n message: `Failed to replace lines: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Show file lines with line numbers for debugging\n */\n static async showFileLines(context: {\n filePath: string;\n startLine?: number;\n endLine?: number;\n context?: number;\n projectPath?: string;\n }) {\n const { filePath, startLine, endLine, context: contextLines = 2, projectPath = process.cwd() } = context;\n\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(projectPath, filePath);\n\n // Read current file content\n const content = await readFile(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n let targetStart = startLine;\n let targetEnd = endLine;\n\n // If no range specified, show all lines\n if (!targetStart) {\n targetStart = 1;\n targetEnd = lines.length;\n } else if (!targetEnd) {\n targetEnd = targetStart;\n }\n\n // Calculate actual display range with context\n const displayStart = Math.max(1, targetStart - contextLines);\n const displayEnd = Math.min(lines.length, targetEnd + contextLines);\n\n const result = [];\n for (let i = displayStart; i <= displayEnd; i++) {\n const lineIndex = i - 1; // Convert to 0-based for array access\n const isTarget = i >= targetStart && i <= targetEnd;\n\n result.push({\n lineNumber: i,\n content: lineIndex < lines.length ? (lines[lineIndex] ?? '') : '',\n isTarget,\n });\n }\n\n return {\n success: true,\n lines: result,\n totalLines: lines.length,\n message: `Showing lines ${displayStart}-${displayEnd} of ${lines.length} total lines in ${filePath}`,\n };\n } catch (error) {\n return {\n success: false,\n lines: [],\n totalLines: 0,\n message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Signal task completion\n */\n static async signalCompletion(context: {\n summary: string;\n changes: Array<{\n type: 'file_created' | 'file_modified' | 'file_deleted' | 'command_executed' | 'dependency_added';\n description: string;\n path?: string;\n }>;\n validation: {\n testsRun?: boolean;\n buildsSuccessfully?: boolean;\n manualTestingRequired?: boolean;\n };\n nextSteps?: string[];\n }) {\n const completionId = `completion_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n // Calculate confidence based on validation status\n let confidence = 70; // Base confidence\n if (context.validation.testsRun) confidence += 15;\n if (context.validation.buildsSuccessfully) confidence += 15;\n if (context.validation.manualTestingRequired) confidence -= 10;\n\n // Determine status\n let status: 'completed' | 'needs_review' | 'needs_testing';\n if (context.validation.testsRun && context.validation.buildsSuccessfully) {\n status = 'completed';\n } else if (context.validation.manualTestingRequired) {\n status = 'needs_testing';\n } else {\n status = 'needs_review';\n }\n\n return {\n completionId,\n status,\n summary: context.summary,\n confidence: Math.min(100, Math.max(0, confidence)),\n };\n }\n\n /**\n * Perform intelligent search with context\n */\n static async performSmartSearch(\n context: {\n query: string;\n type?: 'text' | 'regex' | 'fuzzy' | 'semantic';\n scope?: {\n paths?: string[];\n fileTypes?: string[];\n excludePaths?: string[];\n maxResults?: number;\n };\n context?: {\n beforeLines?: number;\n afterLines?: number;\n includeDefinitions?: boolean;\n };\n },\n projectPath: string,\n ) {\n try {\n const { query, type = 'text', scope = {}, context: searchContext = {} } = context;\n\n const { paths = ['.'], fileTypes = [], excludePaths = [], maxResults = 50 } = scope;\n\n const { beforeLines = 2, afterLines = 2 } = searchContext;\n\n // Build command and arguments array safely\n const rgArgs: string[] = [];\n\n // Add context lines\n if (beforeLines > 0) {\n rgArgs.push('-B', beforeLines.toString());\n }\n if (afterLines > 0) {\n rgArgs.push('-A', afterLines.toString());\n }\n\n // Add line numbers\n rgArgs.push('-n');\n\n // Handle search type\n if (type === 'regex') {\n rgArgs.push('-e');\n } else if (type === 'fuzzy') {\n rgArgs.push('--fixed-strings');\n }\n\n // Add file type filters\n if (fileTypes.length > 0) {\n fileTypes.forEach(ft => {\n rgArgs.push('--type-add', `custom:*.${ft}`, '-t', 'custom');\n });\n }\n\n // Add exclude patterns\n excludePaths.forEach(path => {\n rgArgs.push('--glob', `!${path}`);\n });\n\n // Add max count\n rgArgs.push('-m', maxResults.toString());\n\n // Add the search query and paths\n rgArgs.push(query);\n rgArgs.push(...paths);\n\n // Execute safely using execFile\n const { stdout } = await execFile('rg', rgArgs, {\n cwd: projectPath,\n });\n const lines = stdout.split('\\n').filter((line: string) => line.trim());\n\n const matches: Array<{\n file: string;\n line: number;\n column?: number;\n match: string;\n context: { before: string[]; after: string[] };\n relevance?: number;\n }> = [];\n\n let currentMatch: any = null;\n\n lines.forEach((line: string) => {\n if (line.includes(':') && !line.startsWith('-')) {\n // This is a match line\n const parts = line.split(':');\n if (parts.length >= 3) {\n // Save previous match if exists\n if (currentMatch) {\n matches.push(currentMatch);\n }\n\n currentMatch = {\n file: parts[0] || '',\n line: parseInt(parts[1] || '0'),\n match: parts.slice(2).join(':'),\n context: { before: [], after: [] },\n relevance: type === 'fuzzy' ? Math.random() * 100 : undefined,\n };\n }\n } else if (line.startsWith('-') && currentMatch) {\n // This is a context line\n const contextLine = line.substring(1);\n if (currentMatch.context.before.length < beforeLines) {\n currentMatch.context.before.push(contextLine);\n } else {\n currentMatch.context.after.push(contextLine);\n }\n }\n });\n\n // Add the last match\n if (currentMatch) {\n matches.push(currentMatch);\n }\n\n // Count files searched (approximate)\n const filesSearched = new Set(matches.map(m => m.file)).size;\n\n return {\n success: true,\n matches: matches.slice(0, maxResults),\n summary: {\n totalMatches: matches.length,\n filesSearched,\n patterns: [query],\n },\n };\n } catch {\n return {\n success: false,\n matches: [],\n summary: {\n totalMatches: 0,\n filesSearched: 0,\n patterns: [context.query],\n },\n };\n }\n }\n\n // Static storage properties\n private static taskStorage: Map<string, any[]>;\n private static pendingQuestions: Map<string, any>;\n\n /**\n * Read file contents with optional line range\n */\n static async readFile(context: {\n filePath: string;\n startLine?: number;\n endLine?: number;\n encoding?: string;\n projectPath?: string;\n }) {\n try {\n const { filePath, startLine, endLine, encoding = 'utf-8', projectPath } = context;\n\n // Resolve path relative to project directory if it's not absolute\n const resolvedPath = isAbsolute(filePath) ? filePath : resolve(projectPath || process.cwd(), filePath);\n\n const stats = await stat(resolvedPath);\n const content = await readFile(resolvedPath, { encoding: encoding as BufferEncoding });\n const lines = content.split('\\n');\n\n let resultContent = content;\n let resultLines = lines;\n\n if (startLine !== undefined || endLine !== undefined) {\n const start = Math.max(0, (startLine || 1) - 1);\n const end = endLine !== undefined ? Math.min(lines.length, endLine) : lines.length;\n resultLines = lines.slice(start, end);\n resultContent = resultLines.join('\\n');\n }\n\n return {\n success: true,\n content: resultContent,\n lines: resultLines,\n metadata: {\n size: stats.size,\n totalLines: lines.length,\n encoding,\n lastModified: stats.mtime.toISOString(),\n },\n };\n } catch (error) {\n return {\n success: false,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Write content to file with directory creation and backup options\n */\n static async writeFile(context: {\n filePath: string;\n content: string;\n createDirs?: boolean;\n encoding?: string;\n projectPath?: string;\n }) {\n try {\n const { filePath, content, createDirs = true, encoding = 'utf-8', projectPath } = context;\n\n // Resolve path relative to project directory if it's not absolute\n const resolvedPath = isAbsolute(filePath) ? filePath : resolve(projectPath || process.cwd(), filePath);\n const dir = dirname(resolvedPath);\n\n // Create directories if needed\n if (createDirs) {\n await mkdir(dir, { recursive: true });\n }\n\n // Write the file\n await writeFile(resolvedPath, content, { encoding: encoding as BufferEncoding });\n\n return {\n success: true,\n filePath: resolvedPath,\n bytesWritten: Buffer.byteLength(content, encoding as BufferEncoding),\n message: `Successfully wrote ${Buffer.byteLength(content, encoding as BufferEncoding)} bytes to ${filePath}`,\n };\n } catch (error) {\n return {\n success: false,\n filePath: context.filePath,\n message: `Failed to write file: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * List directory contents with filtering and metadata\n */\n static async listDirectory(context: {\n path: string;\n recursive?: boolean;\n includeHidden?: boolean;\n pattern?: string;\n maxDepth?: number;\n includeMetadata?: boolean;\n projectPath?: string;\n }) {\n try {\n const {\n path,\n recursive = false,\n includeHidden = false,\n pattern,\n maxDepth = 10,\n includeMetadata = true,\n projectPath,\n } = context;\n\n const gitignorePath = join(projectPath || process.cwd(), '.gitignore');\n let gitignoreFilter: ignore.Ignore | undefined;\n\n try {\n const gitignoreContent = await readFile(gitignorePath, 'utf-8');\n gitignoreFilter = ignore().add(gitignoreContent);\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n console.error(`Error reading .gitignore file:`, err);\n }\n // If .gitignore doesn't exist, gitignoreFilter remains undefined, meaning no files are ignored by gitignore.\n }\n\n // Resolve path relative to project directory if it's not absolute\n const resolvedPath = isAbsolute(path) ? path : resolve(projectPath || process.cwd(), path);\n\n const items: Array<{\n name: string;\n path: string;\n type: 'file' | 'directory' | 'symlink';\n size?: number;\n lastModified?: string;\n permissions?: string;\n }> = [];\n\n async function processDirectory(dirPath: string, currentDepth: number = 0) {\n const relativeToProject = relative(projectPath || process.cwd(), dirPath);\n if (gitignoreFilter?.ignores(relativeToProject)) return;\n if (currentDepth > maxDepth) return;\n\n const entries = await readdir(dirPath);\n\n for (const entry of entries) {\n const entryPath = join(dirPath, entry);\n const relativeEntryPath = relative(projectPath || process.cwd(), entryPath);\n if (gitignoreFilter?.ignores(relativeEntryPath)) continue;\n if (!includeHidden && entry.startsWith('.')) continue;\n\n const fullPath = entryPath;\n const relativePath = relative(resolvedPath, fullPath);\n\n if (pattern) {\n // Simple pattern matching\n const regexPattern = pattern.replace(/\\*/g, '.*').replace(/\\?/g, '.');\n if (!new RegExp(regexPattern).test(entry)) continue;\n }\n\n let stats;\n let type: 'file' | 'directory' | 'symlink';\n\n try {\n stats = await stat(fullPath);\n if (stats.isDirectory()) {\n type = 'directory';\n } else if (stats.isSymbolicLink()) {\n type = 'symlink';\n } else {\n type = 'file';\n }\n } catch {\n continue; // Skip entries we can't stat\n }\n\n const item: any = {\n name: entry,\n path: relativePath || entry,\n type,\n };\n\n if (includeMetadata) {\n item.size = stats.size;\n item.lastModified = stats.mtime.toISOString();\n item.permissions = `0${(stats.mode & parseInt('777', 8)).toString(8)}`;\n }\n\n items.push(item);\n\n // Recurse into directories if requested\n if (recursive && type === 'directory') {\n await processDirectory(fullPath, currentDepth + 1);\n }\n }\n }\n\n await processDirectory(resolvedPath);\n\n return {\n success: true,\n items,\n totalItems: items.length,\n path: resolvedPath,\n message: `Listed ${items.length} items in ${resolvedPath}`,\n };\n } catch (error) {\n return {\n success: false,\n items: [],\n totalItems: 0,\n path: context.path,\n message: `Failed to list directory: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Execute shell commands with proper error handling\n */\n static async executeCommand(context: {\n command: string;\n workingDirectory?: string;\n timeout?: number;\n captureOutput?: boolean;\n shell?: string;\n env?: Record<string, string>;\n }) {\n const startTime = Date.now();\n try {\n const { command, workingDirectory, timeout = 30000, captureOutput = true, shell, env } = context;\n\n const execOptions: any = {\n timeout,\n env: { ...process.env, ...env },\n };\n\n if (workingDirectory) {\n execOptions.cwd = workingDirectory;\n }\n\n if (shell) {\n execOptions.shell = shell;\n }\n\n const { stdout, stderr } = await exec(command, execOptions);\n const executionTime = Date.now() - startTime;\n\n return {\n success: true,\n exitCode: 0,\n stdout: captureOutput ? String(stdout) : undefined,\n stderr: captureOutput ? String(stderr) : undefined,\n command,\n workingDirectory,\n executionTime,\n };\n } catch (error: any) {\n const executionTime = Date.now() - startTime;\n\n return {\n success: false,\n exitCode: error.code || 1,\n stdout: String(error.stdout || ''),\n stderr: String(error.stderr || ''),\n command: context.command,\n workingDirectory: context.workingDirectory,\n executionTime,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Web search using a simple search approach\n */\n static async webSearch(context: {\n query: string;\n maxResults?: number;\n region?: string;\n language?: string;\n includeImages?: boolean;\n dateRange?: 'day' | 'week' | 'month' | 'year' | 'all';\n }) {\n try {\n const {\n query,\n maxResults = 10,\n // region = 'us',\n // language = 'en',\n // includeImages = false,\n // dateRange = 'all',\n } = context;\n\n const startTime = Date.now();\n\n // For now, implement a basic search using DuckDuckGo's instant answer API\n // In a real implementation, you'd want to use a proper search API\n const searchUrl = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&skip_disambig=1`;\n\n const response = await fetch(searchUrl);\n const data: any = await response.json();\n\n const results: Array<{\n title: string;\n url: string;\n snippet: string;\n domain: string;\n publishDate?: string;\n relevanceScore?: number;\n }> = [];\n\n // Parse DuckDuckGo results\n if (data.RelatedTopics && Array.isArray(data.RelatedTopics)) {\n for (const topic of data.RelatedTopics.slice(0, maxResults)) {\n if (topic.FirstURL && topic.Text) {\n const url = new URL(topic.FirstURL);\n results.push({\n title: topic.Text.split(' - ')[0] || topic.Text.substring(0, 60),\n url: topic.FirstURL,\n snippet: topic.Text,\n domain: url.hostname,\n relevanceScore: Math.random() * 100, // Placeholder scoring\n });\n }\n }\n }\n\n // Add abstract as first result if available\n if (data.Abstract && data.AbstractURL) {\n const url = new URL(data.AbstractURL);\n results.unshift({\n title: data.Heading || 'Main Result',\n url: data.AbstractURL,\n snippet: data.Abstract,\n domain: url.hostname,\n relevanceScore: 100,\n });\n }\n\n const searchTime = Date.now() - startTime;\n\n return {\n success: true,\n query,\n results: results.slice(0, maxResults),\n totalResults: results.length,\n searchTime,\n suggestions:\n data.RelatedTopics?.slice(maxResults, maxResults + 3)\n ?.map((t: any) => t.Text?.split(' - ')[0] || t.Text?.substring(0, 30))\n .filter(Boolean) || [],\n };\n } catch (error) {\n return {\n success: false,\n query: context.query,\n results: [],\n totalResults: 0,\n searchTime: 0,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n}\n","import { Agent } from '@mastra/core/agent';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport type { Processor } from '@mastra/core/processors';\n\n/**\n * Summarizes tool calls and caches results to avoid re-summarizing identical calls\n */\nexport class ToolSummaryProcessor implements Processor {\n readonly id = 'tool-summary-processor';\n readonly name = 'ToolSummaryProcessor';\n\n private summaryAgent: Agent;\n private summaryCache: Map<string, string> = new Map();\n\n constructor({ summaryModel }: { summaryModel: MastraModelConfig }) {\n this.summaryAgent = new Agent({\n id: 'tool-summary-agent',\n name: 'Tool Summary Agent',\n description: 'A summary agent that summarizes tool calls and results',\n instructions: 'You are a summary agent that summarizes tool calls and results',\n model: summaryModel,\n });\n }\n\n /**\n * Creates a cache key from tool call arguments\n */\n public createCacheKey(toolCall: any): string {\n if (!toolCall) return 'unknown';\n\n // Create a deterministic key from tool name and arguments\n const toolName = toolCall.toolName || 'unknown';\n const args = toolCall.args || {};\n\n // Sort keys for consistent hashing\n const sortedArgs = Object.keys(args)\n .sort()\n .reduce((result: Record<string, any>, key) => {\n result[key] = args[key];\n return result;\n }, {});\n\n return `${toolName}:${JSON.stringify(sortedArgs)}`;\n }\n\n /**\n * Clears the summary cache\n */\n public clearCache(): void {\n this.summaryCache.clear();\n }\n\n /**\n * Gets cache statistics\n */\n public getCacheStats(): { size: number; keys: string[] } {\n return {\n size: this.summaryCache.size,\n keys: Array.from(this.summaryCache.keys()),\n };\n }\n\n async processInput({\n messages,\n messageList: _messageList,\n }: {\n messages: MastraDBMessage[];\n messageList: MessageList;\n abort: (reason?: string) => never;\n }): Promise<MastraDBMessage[]> {\n // Collect all tool calls that need summarization\n const summaryTasks: Array<{\n message: MastraDBMessage;\n partIndex: number;\n promise: Promise<any>;\n cacheKey: string;\n }> = [];\n\n // First pass: collect all tool results that need summarization\n for (const message of messages) {\n if (message.content.format === 2 && message.content.parts) {\n for (let partIndex = 0; partIndex < message.content.parts.length; partIndex++) {\n const part = message.content.parts[partIndex];\n\n // Check if this is a tool invocation with a result\n if (part && part.type === 'tool-invocation' && part.toolInvocation?.state === 'result') {\n const cacheKey = this.createCacheKey(part.toolInvocation);\n const cachedSummary = this.summaryCache.get(cacheKey);\n\n if (cachedSummary) {\n // Use cached summary - update the tool invocation result\n message.content.parts[partIndex] = {\n type: 'tool-invocation',\n toolInvocation: {\n state: 'result',\n step: part.toolInvocation.step,\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n result: `Tool call summary: ${cachedSummary}`,\n },\n };\n } else {\n // Create a promise for this summary (but don't await yet)\n const summaryPromise = this.summaryAgent.generate(\n `Summarize the following tool call: ${JSON.stringify(part.toolInvocation)}`,\n );\n\n summaryTasks.push({\n message,\n partIndex,\n promise: summaryPromise,\n cacheKey,\n });\n }\n }\n }\n }\n }\n\n // Execute all non-cached summaries in parallel\n if (summaryTasks.length > 0) {\n const summaryResults = await Promise.allSettled(summaryTasks.map(task => task.promise));\n\n // Apply the results back to the content and cache them\n summaryTasks.forEach((task, index) => {\n const result = summaryResults[index];\n if (!result) return;\n\n if (result.status === 'fulfilled') {\n const summaryResult = result.value;\n const summaryText = summaryResult.text;\n\n // Cache the summary for future use\n this.summaryCache.set(task.cacheKey, summaryText);\n\n // Apply to message content\n if (task.message.content.format === 2 && task.message.content.parts) {\n const part = task.message.content.parts[task.partIndex];\n if (part && part.type === 'tool-invocation' && part.toolInvocation?.state === 'result') {\n task.message.content.parts[task.partIndex] = {\n type: 'tool-invocation',\n toolInvocation: {\n state: 'result',\n step: part.toolInvocation.step,\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n result: `Tool call summary: ${summaryText}`,\n },\n };\n }\n }\n } else if (result.status === 'rejected') {\n // Handle failed summary - use fallback or log error\n console.warn(`Failed to generate summary for tool call:`, result.reason);\n }\n });\n }\n\n return messages;\n }\n}\n","import { Agent } from '@mastra/core/agent';\nimport type {\n AiMessageType,\n AgentGenerateOptions,\n AgentStreamOptions,\n AgentExecutionOptions,\n AgentExecutionOptionsBase,\n ToolsInput,\n AgentConfig,\n PublicStructuredOutputOptions,\n} from '@mastra/core/agent';\nimport type { MessageListInput } from '@mastra/core/agent/message-list';\nimport type { CoreMessage } from '@mastra/core/llm';\nimport { InMemoryStore } from '@mastra/core/storage';\nimport type { MastraModelOutput, FullOutput } from '@mastra/core/stream';\nimport { Memory } from '@mastra/memory';\nimport type { InferStandardSchemaOutput, StandardSchemaWithJSON } from '@mastra/schema-compat/schema';\nimport { AgentBuilderDefaults } from '../defaults';\nimport { ToolSummaryProcessor } from '../processors/tool-summary';\nimport type { AgentBuilderConfig, GenerateAgentOptions } from '../types';\n\n// =============================================================================\n// Template Merge Workflow Implementation\n// =============================================================================\n//\n// This workflow implements a comprehensive template merging system that:\n// 1. Clones template repositories at specific refs (tags/commits)\n// 2. Discovers units (agents, workflows, MCP servers/tools) in templates\n// 3. Topologically orders units based on dependencies\n// 4. Analyzes conflicts and creates safety classifications\n// 5. Applies changes with git branching and checkpoints per unit\n//\n// The workflow follows the \"auto-decide vs ask\" principles:\n// - Auto: adding new files, missing deps, appending arrays, new scripts with template:slug:* namespace\n// - Prompt: overwriting files, major upgrades, renaming conflicts, new ports, postInstall commands\n// - Block: removing files, downgrading deps, changing TS target/module, modifying CI/CD secrets\n//\n// Usage with Mastra templates (see https://mastra.ai/api/templates.json):\n// const run = await agentBuilderTemplateWorkflow.createRun();\n// const result = await run.start({\n// inputData: {\n// repo: 'https://github.com/mastra-ai/template-pdf-questions',\n// ref: 'main', // optional\n// targetPath: './my-project', // optional, defaults to cwd\n// }\n// });\n// // The workflow will automatically analyze and merge the template structure\n//\n// =============================================================================\n\nexport class AgentBuilder<TTools extends ToolsInput = ToolsInput, TOutput = undefined> extends Agent<\n 'agent-builder',\n TTools,\n TOutput\n> {\n private builderConfig: AgentBuilderConfig;\n\n /**\n * Constructor for AgentBuilder\n */\n constructor(config: AgentBuilderConfig) {\n const additionalInstructions = config.instructions ? `## Priority Instructions \\n\\n${config.instructions}` : '';\n const combinedInstructions = additionalInstructions + AgentBuilderDefaults.DEFAULT_INSTRUCTIONS(config.projectPath);\n\n // Create Memory with storage for AgentBuilder\n // Use provided storage if available, otherwise fall back to in-memory storage\n const memory = new Memory({\n options: AgentBuilderDefaults.DEFAULT_MEMORY_CONFIG,\n });\n memory.setStorage(config.storage ?? new InMemoryStore());\n\n const agentConfig: AgentConfig<'agent-builder', TTools, TOutput> = {\n id: 'agent-builder',\n name: 'agent-builder',\n description:\n 'An AI agent specialized in generating Mastra agents, tools, and workflows from natural language requirements.',\n instructions: combinedInstructions,\n model: config.model,\n tools: async (): Promise<TTools> => {\n return {\n ...(await AgentBuilderDefaults.listToolsForMode(config.projectPath, config.mode)),\n ...(config.tools || ({} as TTools)),\n } as TTools;\n },\n memory,\n inputProcessors: [\n // use the write to disk processor to debug the agent's context\n // new WriteToDiskProcessor({ prefix: 'before-filter' }),\n new ToolSummaryProcessor({ summaryModel: config.summaryModel || config.model }),\n // new WriteToDiskProcessor({ prefix: 'after-filter' }),\n ],\n };\n\n super(agentConfig);\n this.builderConfig = config;\n }\n\n /**\n * Enhanced generate method with AgentBuilder-specific configuration\n * Overrides the base Agent generate method to provide additional project context\n */\n generateLegacy: Agent['generateLegacy'] = async (\n messages: string | string[] | CoreMessage[] | AiMessageType[],\n generateOptions: (GenerateAgentOptions & AgentGenerateOptions<any, any>) | undefined = {},\n ): Promise<any> => {\n const { maxSteps, ...baseOptions } = generateOptions;\n\n const originalInstructions = await this.getInstructions({ requestContext: generateOptions?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n\n const enhancedContext = [...(baseOptions.context || [])];\n\n const enhancedOptions = {\n ...baseOptions,\n maxSteps: maxSteps || 100, // Higher default for code generation\n temperature: 0.3, // Lower temperature for more consistent code generation\n instructions: enhancedInstructions,\n context: enhancedContext,\n } satisfies AgentGenerateOptions<any, any>;\n\n this.logger.debug('Starting generation with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.generateLegacy(messages, enhancedOptions);\n };\n\n /**\n * Enhanced stream method with AgentBuilder-specific configuration\n * Overrides the base Agent stream method to provide additional project context\n */\n streamLegacy: Agent['streamLegacy'] = async (\n messages: string | string[] | CoreMessage[] | AiMessageType[],\n streamOptions: (GenerateAgentOptions & AgentStreamOptions<any, any>) | undefined = {},\n ): Promise<any> => {\n const { maxSteps, ...baseOptions } = streamOptions;\n\n const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n const enhancedContext = [...(baseOptions.context || [])];\n\n const enhancedOptions = {\n ...baseOptions,\n maxSteps: maxSteps || 100, // Higher default for code generation\n temperature: 0.3, // Lower temperature for more consistent code generation\n instructions: enhancedInstructions,\n context: enhancedContext,\n };\n\n this.logger.debug('Starting streaming with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.streamLegacy(messages, enhancedOptions);\n };\n\n /**\n * Enhanced stream method with AgentBuilder-specific configuration\n * Overrides the base Agent stream method to provide additional project context\n */\n async stream<\n OUTPUT extends StandardSchemaWithJSON<any, any>,\n T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>,\n >(\n messages: MessageListInput,\n streamOptions: AgentExecutionOptionsBase<T> & {\n structuredOutput: PublicStructuredOutputOptions<T>;\n },\n ): Promise<MastraModelOutput<T>>;\n async stream<OUTPUT extends {}>(\n messages: MessageListInput,\n streamOptions: AgentExecutionOptionsBase<OUTPUT> & {\n structuredOutput: PublicStructuredOutputOptions<OUTPUT>;\n },\n ): Promise<MastraModelOutput<OUTPUT>>;\n async stream(\n messages: MessageListInput,\n streamOptions: AgentExecutionOptionsBase<unknown> & {\n structuredOutput?: never;\n },\n ): Promise<MastraModelOutput<TOutput>>;\n async stream(messages: MessageListInput): Promise<MastraModelOutput<TOutput>>;\n async stream<OUTPUT = TOutput>(\n messages: MessageListInput,\n streamOptions?: AgentExecutionOptionsBase<any> & {\n structuredOutput?: PublicStructuredOutputOptions<any>;\n },\n ): Promise<MastraModelOutput<OUTPUT>> {\n const { ...baseOptions } = streamOptions || ({} as AgentExecutionOptions<OUTPUT>);\n\n const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n const enhancedContext = [...(baseOptions.context || ([] as AgentExecutionOptions<OUTPUT>['context'][]))];\n\n const enhancedOptions = {\n ...baseOptions,\n temperature: 0.3, // Lower temperature for more consistent code generation\n maxSteps: baseOptions?.maxSteps || 100,\n instructions: enhancedInstructions,\n context: enhancedContext,\n } as any;\n\n this.logger.debug('Starting streaming with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.stream(messages, enhancedOptions);\n }\n\n async generate<\n OUTPUT extends StandardSchemaWithJSON<any, any>,\n T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>,\n >(\n messages: MessageListInput,\n options: AgentExecutionOptionsBase<T> & {\n structuredOutput: PublicStructuredOutputOptions<T>;\n },\n ): Promise<FullOutput<T>>;\n async generate<OUTPUT extends {}>(\n messages: MessageListInput,\n options: AgentExecutionOptionsBase<OUTPUT> & {\n structuredOutput: PublicStructuredOutputOptions<OUTPUT>;\n },\n ): Promise<FullOutput<OUTPUT>>;\n async generate(\n messages: MessageListInput,\n options: AgentExecutionOptionsBase<unknown> & {\n structuredOutput?: never;\n },\n ): Promise<FullOutput<TOutput>>;\n async generate<OUTPUT = TOutput>(messages: MessageListInput): Promise<FullOutput<OUTPUT>>;\n async generate<OUTPUT = TOutput>(\n messages: MessageListInput,\n options?: AgentExecutionOptionsBase<any> & {\n structuredOutput?: PublicStructuredOutputOptions<any>;\n },\n ): Promise<FullOutput<OUTPUT>> {\n const { ...baseOptions } = options || {};\n\n const originalInstructions = await this.getInstructions({ requestContext: options?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n const enhancedContext = [...(baseOptions.context || [])];\n\n const enhancedOptions = {\n ...baseOptions,\n temperature: 0.3, // Lower temperature for more consistent code generation\n maxSteps: baseOptions?.maxSteps || 100,\n instructions: enhancedInstructions,\n context: enhancedContext,\n } as any;\n\n this.logger.debug('Starting generation with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.generate(messages, enhancedOptions);\n }\n}\n","import { existsSync } from 'node:fs';\nimport { mkdtemp, copyFile, readFile, mkdir, readdir, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join, dirname, resolve, extname, basename } from 'node:path';\nimport { openai } from '@ai-sdk/openai';\nimport {\n Agent,\n tryGenerateWithJsonFallback,\n tryStreamWithJsonFallback,\n isSupportedLanguageModel,\n} from '@mastra/core/agent';\nimport { toStandardSchema } from '@mastra/core/schema';\nimport type { FullOutput } from '@mastra/core/stream';\nimport { createTool } from '@mastra/core/tools';\nimport { createWorkflow, createStep } from '@mastra/core/workflows';\nimport { standardSchemaToJSONSchema } from '@mastra/schema-compat/schema';\nimport { z } from 'zod';\nimport { AgentBuilder } from '../..';\nimport { AgentBuilderDefaults } from '../../defaults';\nimport type { TemplateUnit, UnitKind } from '../../types';\nimport {\n ApplyResultSchema,\n AgentBuilderInputSchema,\n CloneTemplateResultSchema,\n PackageAnalysisSchema,\n DiscoveryResultSchema,\n OrderedUnitsSchema,\n PackageMergeInputSchema,\n PackageMergeResultSchema,\n InstallInputSchema,\n InstallResultSchema,\n FileCopyInputSchema,\n FileCopyResultSchema,\n IntelligentMergeInputSchema,\n IntelligentMergeResultSchema,\n ValidationFixInputSchema,\n ValidationFixResultSchema,\n PrepareBranchInputSchema,\n PrepareBranchResultSchema,\n} from '../../types';\nimport {\n getMastraTemplate,\n kindWeight,\n spawnSWPM,\n logGitState,\n backupAndReplaceFile,\n renameAndCopyFile,\n gitCheckoutBranch,\n gitClone,\n gitCheckoutRef,\n gitRevParse,\n gitAddAndCommit,\n resolveTargetPath,\n mergeGitignoreFiles,\n mergeEnvFiles,\n resolveModel,\n} from '../../utils';\n\ntype AgentBuilderInputSchemaType = z.infer<typeof AgentBuilderInputSchema>;\n\n// Step 1: Clone template to temp directory\nconst cloneTemplateStep = createStep({\n id: 'clone-template',\n description: 'Clone the template repository to a temporary directory at the specified ref',\n inputSchema: AgentBuilderInputSchema,\n outputSchema: CloneTemplateResultSchema,\n execute: async ({ inputData }) => {\n const { repo, ref = 'main', slug, targetPath } = inputData;\n\n if (!repo) {\n throw new Error('Repository URL or path is required');\n }\n\n // Extract slug from repo URL if not provided\n const inferredSlug =\n slug ||\n repo\n .split('/')\n .pop()\n ?.replace(/\\.git$/, '') ||\n 'template';\n\n // Create temporary directory\n const tempDir = await mkdtemp(join(tmpdir(), 'mastra-template-'));\n\n try {\n // Clone repository\n await gitClone(repo, tempDir);\n\n // Checkout specific ref if provided\n if (ref !== 'main' && ref !== 'master') {\n await gitCheckoutRef(tempDir, ref);\n }\n\n // Get commit SHA\n const commitSha = await gitRevParse(tempDir, 'HEAD');\n\n return {\n templateDir: tempDir,\n commitSha: commitSha.trim(),\n slug: inferredSlug,\n success: true,\n targetPath,\n };\n } catch (error) {\n // Cleanup on error\n try {\n await rm(tempDir, { recursive: true, force: true });\n } catch {}\n\n return {\n templateDir: '',\n commitSha: '',\n slug: slug || 'unknown',\n success: false,\n error: `Failed to clone template: ${error instanceof Error ? error.message : String(error)}`,\n targetPath,\n };\n }\n },\n});\n\n// Step 2: Analyze template package.json for dependencies\nconst analyzePackageStep = createStep({\n id: 'analyze-package',\n description: 'Analyze the template package.json to extract dependency information',\n inputSchema: CloneTemplateResultSchema,\n outputSchema: PackageAnalysisSchema,\n execute: async ({ inputData }) => {\n console.info('Analyzing template package.json...');\n const { templateDir } = inputData;\n const packageJsonPath = join(templateDir, 'package.json');\n\n try {\n const packageJsonContent = await readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageJsonContent);\n\n console.info('Template package.json:', JSON.stringify(packageJson, null, 2));\n\n return {\n dependencies: packageJson.dependencies || {},\n devDependencies: packageJson.devDependencies || {},\n peerDependencies: packageJson.peerDependencies || {},\n scripts: packageJson.scripts || {},\n name: packageJson.name || '',\n version: packageJson.version || '',\n description: packageJson.description || '',\n success: true,\n };\n } catch (error) {\n console.warn(`Failed to read template package.json: ${error instanceof Error ? error.message : String(error)}`);\n return {\n dependencies: {},\n devDependencies: {},\n peerDependencies: {},\n scripts: {},\n name: '',\n version: '',\n description: '',\n success: true, // This is a graceful fallback, not a failure\n };\n }\n },\n});\n\n// Step 3: Discover template units by scanning the templates directory\nconst discoverUnitsStep = createStep({\n id: 'discover-units',\n description: 'Discover template units by analyzing the templates directory structure',\n inputSchema: CloneTemplateResultSchema,\n outputSchema: DiscoveryResultSchema,\n execute: async ({ inputData, requestContext }) => {\n const { templateDir } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n const tools = await AgentBuilderDefaults.DEFAULT_TOOLS(templateDir);\n\n console.info('targetPath', targetPath);\n\n const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai('gpt-4.1') });\n\n try {\n const agent = new Agent({\n id: 'mastra-project-discoverer',\n model,\n instructions: `You are an expert at analyzing Mastra projects.\n\nYour task is to scan the provided directory and identify all available units (agents, workflows, tools, MCP servers, networks).\n\nMastra Project Structure Analysis:\n- Each Mastra project has a structure like: ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.agent}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.workflow}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE['mcp-server']}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.network}\n- Analyze TypeScript files in each category directory to identify exported units\n\nCRITICAL: YOU MUST USE YOUR TOOLS (readFile, listDirectory) TO DISCOVER THE UNITS IN THE TEMPLATE DIRECTORY.\n\nIMPORTANT - Agent Discovery Rules:\n1. **Multiple Agent Files**: Some templates have separate files for each agent (e.g., evaluationAgent.ts, researchAgent.ts)\n2. **Single File Multiple Agents**: Some files may export multiple agents (look for multiple 'export const' or 'export default' statements)\n3. **Agent Identification**: Look for exported variables that are instances of 'new Agent()' or similar patterns\n4. **Naming Convention**: Agent names should be extracted from the export name (e.g., 'weatherAgent', 'evaluationAgent')\n\nFor each Mastra project directory you analyze:\n1. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.agent} and identify ALL exported agents\n2. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.workflow} and identify ALL exported workflows\n3. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool} and identify ALL exported tools\n4. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE['mcp-server']} and identify ALL exported MCP servers\n5. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.network} and identify ALL exported networks\n6. Scan for any OTHER files in src/mastra that are NOT in the above default folders (e.g., lib/, utils/, types/, etc.) and identify them as 'other' files\n\nIMPORTANT - Naming Consistency Rules:\n- For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension\n- For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable\n- use the base filename without extension for the id (e.g., 'util.ts' → name: 'util')\n- use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' → file: 'src/mastra/lib/util.ts')\n\nReturn the actual exported names of the units, as well as the file names.`,\n name: 'Mastra Project Discoverer',\n tools: {\n readFile: tools.readFile,\n listDirectory: tools.listDirectory,\n },\n });\n\n const resolvedModel = await agent.getModel();\n const isSupported = isSupportedLanguageModel(resolvedModel);\n\n const prompt = `Analyze the Mastra project directory structure at \"${templateDir}\".\n\n List directory contents using listDirectory tool, and then analyze each file with readFile tool.\n IMPORTANT:\n - Look inside the actual file content to find export statements like 'export const agentName = new Agent(...)'\n - A single file may contain multiple exports\n - Return the actual exported variable names, as well as the file names\n - If a directory doesn't exist or has no files, return an empty array\n\n Return the analysis in the exact format specified in the output schema.`;\n\n const output = z.object({\n agents: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n workflows: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n tools: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n mcp: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n networks: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n other: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n });\n\n let result: FullOutput<z.infer<typeof output>>;\n if (isSupported) {\n result = await tryGenerateWithJsonFallback(agent, prompt, {\n structuredOutput: {\n schema: output,\n },\n maxSteps: 100,\n });\n } else {\n const standardSchema = toStandardSchema(output);\n const jsonSchema = standardSchemaToJSONSchema(standardSchema);\n\n result = (await agent.generateLegacy(prompt, {\n experimental_output: jsonSchema,\n maxSteps: 100,\n })) as unknown as FullOutput<z.infer<typeof output>>;\n }\n\n const template = result.object ?? {};\n\n const units: TemplateUnit[] = [];\n\n // Add agents\n template.agents?.forEach((agentId: { name: string; file: string }) => {\n units.push({ kind: 'agent', id: agentId.name, file: agentId.file });\n });\n\n // Add workflows\n template.workflows?.forEach((workflowId: { name: string; file: string }) => {\n units.push({ kind: 'workflow', id: workflowId.name, file: workflowId.file });\n });\n\n // Add tools\n template.tools?.forEach((toolId: { name: string; file: string }) => {\n units.push({ kind: 'tool', id: toolId.name, file: toolId.file });\n });\n\n // Add MCP servers\n template.mcp?.forEach((mcpId: { name: string; file: string }) => {\n units.push({ kind: 'mcp-server', id: mcpId.name, file: mcpId.file });\n });\n\n // Add networks\n template.networks?.forEach((networkId: { name: string; file: string }) => {\n units.push({ kind: 'network', id: networkId.name, file: networkId.file });\n });\n\n // Add other files\n template.other?.forEach((otherId: { name: string; file: string }) => {\n units.push({ kind: 'other', id: otherId.name, file: otherId.file });\n });\n\n console.info('Discovered units:', JSON.stringify(units, null, 2));\n\n if (units.length === 0) {\n throw new Error(`No Mastra units (agents, workflows, tools) found in template.\n Possible causes:\n - Template may not follow standard Mastra structure\n - AI agent couldn't analyze template files (model/token limits)\n - Template is empty or in wrong branch\n\n Debug steps:\n - Check template has files in src/mastra/ directories\n - Try a different branch\n - Check template repository structure manually`);\n }\n\n return {\n units,\n success: true,\n };\n } catch (error) {\n console.error('Failed to discover units:', error);\n return {\n units: [],\n success: false,\n error: `Failed to discover units: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n});\n\n// Step 4: Topological ordering (simplified)\nconst orderUnitsStep = createStep({\n id: 'order-units',\n description: 'Sort units in topological order based on kind weights',\n inputSchema: DiscoveryResultSchema,\n outputSchema: OrderedUnitsSchema,\n execute: async ({ inputData }) => {\n const { units } = inputData;\n\n // Simple sort by kind weight (mcp-servers first, then tools, agents, workflows, integration last)\n const orderedUnits = [...units].sort((a, b) => {\n const aWeight = kindWeight(a.kind);\n const bWeight = kindWeight(b.kind);\n return aWeight - bWeight;\n });\n\n return {\n orderedUnits,\n success: true,\n };\n },\n});\n\n// Step 5: Prepare branch\nconst prepareBranchStep = createStep({\n id: 'prepare-branch',\n description: 'Create or switch to integration branch before modifications',\n inputSchema: PrepareBranchInputSchema,\n outputSchema: PrepareBranchResultSchema,\n execute: async ({ inputData, requestContext }) => {\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n const branchName = `feat/install-template-${inputData.slug}`;\n await gitCheckoutBranch(branchName, targetPath);\n\n return {\n branchName,\n success: true,\n };\n } catch (error) {\n console.error('Failed to prepare branch:', error);\n return {\n branchName: `feat/install-template-${inputData.slug}`, // Return the intended name anyway\n success: false,\n error: `Failed to prepare branch: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n});\n\n// Step 6: Package merge\nconst packageMergeStep = createStep({\n id: 'package-merge',\n description: 'Merge template package.json dependencies into target project',\n inputSchema: PackageMergeInputSchema,\n outputSchema: PackageMergeResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Package merge step starting...');\n const { slug, packageInfo } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n const targetPkgPath = join(targetPath, 'package.json');\n\n let targetPkgRaw = '{}';\n try {\n targetPkgRaw = await readFile(targetPkgPath, 'utf-8');\n } catch {\n console.warn(`No existing package.json at ${targetPkgPath}, creating a new one`);\n }\n\n let targetPkg: any;\n try {\n targetPkg = JSON.parse(targetPkgRaw || '{}');\n } catch (e) {\n throw new Error(\n `Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n\n const ensureObj = (o: any) => (o && typeof o === 'object' ? o : {});\n\n targetPkg.dependencies = ensureObj(targetPkg.dependencies);\n targetPkg.devDependencies = ensureObj(targetPkg.devDependencies);\n targetPkg.peerDependencies = ensureObj(targetPkg.peerDependencies);\n targetPkg.scripts = ensureObj(targetPkg.scripts);\n\n const tplDeps = ensureObj(packageInfo.dependencies);\n const tplDevDeps = ensureObj(packageInfo.devDependencies);\n const tplPeerDeps = ensureObj(packageInfo.peerDependencies);\n const tplScripts = ensureObj(packageInfo.scripts);\n\n const existsAnywhere = (name: string) =>\n name in targetPkg.dependencies || name in targetPkg.devDependencies || name in targetPkg.peerDependencies;\n\n // Merge dependencies: add only if missing everywhere\n for (const [name, ver] of Object.entries(tplDeps)) {\n if (!existsAnywhere(name)) {\n (targetPkg.dependencies as Record<string, string>)[name] = String(ver);\n }\n }\n\n // Merge devDependencies\n for (const [name, ver] of Object.entries(tplDevDeps)) {\n if (!existsAnywhere(name)) {\n (targetPkg.devDependencies as Record<string, string>)[name] = String(ver);\n }\n }\n\n // Merge peerDependencies\n for (const [name, ver] of Object.entries(tplPeerDeps)) {\n if (!(name in targetPkg.peerDependencies)) {\n (targetPkg.peerDependencies as Record<string, string>)[name] = String(ver);\n }\n }\n\n // Merge scripts with prefixed keys to avoid collisions\n const prefix = `template:${slug}:`;\n for (const [name, cmd] of Object.entries(tplScripts)) {\n const newKey = `${prefix}${name}`;\n if (!(newKey in targetPkg.scripts)) {\n (targetPkg.scripts as Record<string, string>)[newKey] = String(cmd);\n }\n }\n\n await writeFile(targetPkgPath, JSON.stringify(targetPkg, null, 2), 'utf-8');\n\n await gitAddAndCommit(targetPath, `feat(template): merge deps for ${slug}`, [targetPkgPath], {\n skipIfNoStaged: true,\n });\n\n return {\n success: true,\n applied: true,\n message: `Successfully merged template dependencies for ${slug}`,\n };\n } catch (error) {\n console.error('Package merge failed:', error);\n return {\n success: false,\n applied: false,\n message: `Package merge failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 7: Install\nconst installStep = createStep({\n id: 'install',\n description: 'Install packages based on merged package.json',\n inputSchema: InstallInputSchema,\n outputSchema: InstallResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Running install step...');\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n // Run install using swpm (no specific packages)\n await spawnSWPM(targetPath, 'install', []);\n\n const lock = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock']\n .map(f => join(targetPath, f))\n .find(f => existsSync(f));\n\n if (lock) {\n await gitAddAndCommit(targetPath, `chore(template): commit lockfile after install`, [lock], {\n skipIfNoStaged: true,\n });\n }\n\n return {\n success: true,\n };\n } catch (error) {\n console.error('Install failed:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 7: Programmatic File Copy Step - copies template files to target project\nconst programmaticFileCopyStep = createStep({\n id: 'programmatic-file-copy',\n description: 'Programmatically copy template files to target project based on ordered units',\n inputSchema: FileCopyInputSchema,\n outputSchema: FileCopyResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Programmatic file copy step starting...');\n const { orderedUnits, templateDir, commitSha, slug } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n const copiedFiles: Array<{\n source: string;\n destination: string;\n unit: { kind: UnitKind; id: string };\n }> = [];\n\n const conflicts: Array<{\n unit: { kind: UnitKind; id: string };\n issue: string;\n sourceFile: string;\n targetFile: string;\n }> = [];\n\n // Analyze target project naming convention first\n const analyzeNamingConvention = async (\n directory: string,\n ): Promise<'camelCase' | 'snake_case' | 'kebab-case' | 'PascalCase' | 'unknown'> => {\n try {\n const files = await readdir(resolve(targetPath, directory), { withFileTypes: true });\n const tsFiles = files.filter(f => f.isFile() && f.name.endsWith('.ts')).map(f => f.name);\n\n if (tsFiles.length === 0) return 'unknown';\n\n // Check for patterns\n const camelCaseCount = tsFiles.filter(f => /^[a-z][a-zA-Z0-9]*\\.ts$/.test(f)).length;\n const snakeCaseCount = tsFiles.filter(f => /^[a-z][a-z0-9_]*\\.ts$/.test(f) && f.includes('_')).length;\n const kebabCaseCount = tsFiles.filter(f => /^[a-z][a-z0-9-]*\\.ts$/.test(f) && f.includes('-')).length;\n const pascalCaseCount = tsFiles.filter(f => /^[A-Z][a-zA-Z0-9]*\\.ts$/.test(f)).length;\n\n const max = Math.max(camelCaseCount, snakeCaseCount, kebabCaseCount, pascalCaseCount);\n if (max === 0) return 'unknown';\n\n if (camelCaseCount === max) return 'camelCase';\n if (snakeCaseCount === max) return 'snake_case';\n if (kebabCaseCount === max) return 'kebab-case';\n if (pascalCaseCount === max) return 'PascalCase';\n\n return 'unknown';\n } catch {\n return 'unknown';\n }\n };\n\n // Convert naming based on convention\n const convertNaming = (name: string, convention: string): string => {\n const baseName = basename(name, extname(name));\n const ext = extname(name);\n\n // Helper: split a name into words by hyphens, underscores, or camelCase boundaries\n const toWords = (s: string): string[] => {\n return (\n s\n .replace(/[-_]/g, ' ')\n // split \"HTTPServer\" -> \"HTTP Server\"\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .split(/\\s+/)\n .filter(Boolean)\n .map(w => w.toLowerCase())\n );\n };\n\n const words = toWords(baseName);\n\n switch (convention) {\n case 'camelCase':\n return words.map((w, i) => (i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1))).join('') + ext;\n case 'snake_case':\n return words.join('_') + ext;\n case 'kebab-case':\n return words.join('-') + ext;\n case 'PascalCase':\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('') + ext;\n default:\n return name;\n }\n };\n\n // Process each unit\n for (const unit of orderedUnits) {\n console.info(`Processing ${unit.kind} unit \"${unit.id}\" from file \"${unit.file}\"`);\n\n // Resolve source file path with fallback logic\n let sourceFile: string;\n let resolvedUnitFile: string;\n\n // Check if unit.file already contains directory structure\n if (unit.file.includes('/')) {\n // unit.file has path structure (e.g., \"src/mastra/agents/weatherAgent.ts\")\n sourceFile = resolve(templateDir, unit.file);\n resolvedUnitFile = unit.file;\n } else {\n // unit.file is just filename (e.g., \"weatherAgent.ts\") - use fallback\n const folderPath =\n AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE[\n unit.kind as keyof typeof AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE\n ];\n if (!folderPath) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Unknown unit kind: ${unit.kind}`,\n sourceFile: unit.file,\n targetFile: 'N/A',\n });\n continue;\n }\n resolvedUnitFile = `${folderPath}/${unit.file}`;\n sourceFile = resolve(templateDir, resolvedUnitFile);\n }\n\n // Check if source file exists\n if (!existsSync(sourceFile)) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Source file not found: ${sourceFile}`,\n sourceFile: resolvedUnitFile,\n targetFile: 'N/A',\n });\n continue;\n }\n\n // Extract target directory from resolved unit file path\n const targetDir = dirname(resolvedUnitFile);\n\n // Analyze target naming convention\n const namingConvention = await analyzeNamingConvention(targetDir);\n console.info(`Detected naming convention in ${targetDir}: ${namingConvention}`);\n\n // Convert unit.id to target filename with proper extension\n // Note: Check if unit.id already includes extension to avoid double extensions\n const hasExtension = extname(unit.id) !== '';\n const baseId = hasExtension ? basename(unit.id, extname(unit.id)) : unit.id;\n const fileExtension = extname(unit.file);\n const convertedFileName =\n namingConvention !== 'unknown'\n ? convertNaming(baseId + fileExtension, namingConvention)\n : baseId + fileExtension;\n\n const targetFile = resolve(targetPath, targetDir, convertedFileName);\n\n // Handle file conflicts with strategy-based resolution\n if (existsSync(targetFile)) {\n const strategy = determineConflictStrategy(unit, targetFile);\n console.info(`File exists: ${convertedFileName}, using strategy: ${strategy}`);\n\n switch (strategy) {\n case 'skip':\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `File exists - skipped: ${convertedFileName}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n console.info(`⏭️ Skipped ${unit.kind} \"${unit.id}\": file already exists`);\n continue;\n\n case 'backup-and-replace':\n try {\n await backupAndReplaceFile(sourceFile, targetFile);\n copiedFiles.push({\n source: sourceFile,\n destination: targetFile,\n unit: { kind: unit.kind, id: unit.id },\n });\n console.info(\n `🔄 Replaced ${unit.kind} \"${unit.id}\": ${unit.file} → ${convertedFileName} (backup created)`,\n );\n continue;\n } catch (backupError) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Failed to backup and replace: ${backupError instanceof Error ? backupError.message : String(backupError)}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n continue;\n }\n\n case 'rename':\n try {\n const uniqueTargetFile = await renameAndCopyFile(sourceFile, targetFile);\n copiedFiles.push({\n source: sourceFile,\n destination: uniqueTargetFile,\n unit: { kind: unit.kind, id: unit.id },\n });\n console.info(`📝 Renamed ${unit.kind} \"${unit.id}\": ${unit.file} → ${basename(uniqueTargetFile)}`);\n continue;\n } catch (renameError) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Failed to rename and copy: ${renameError instanceof Error ? renameError.message : String(renameError)}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n continue;\n }\n\n default:\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Unknown conflict strategy: ${strategy}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n continue;\n }\n }\n\n // Ensure target directory exists\n await mkdir(dirname(targetFile), { recursive: true });\n\n // Copy the file\n try {\n await copyFile(sourceFile, targetFile);\n copiedFiles.push({\n source: sourceFile,\n destination: targetFile,\n unit: { kind: unit.kind, id: unit.id },\n });\n console.info(`✓ Copied ${unit.kind} \"${unit.id}\": ${unit.file} → ${convertedFileName}`);\n } catch (copyError) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Failed to copy file: ${copyError instanceof Error ? copyError.message : String(copyError)}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n }\n }\n\n // Ensure tsconfig.json exists in target by copying from template if available, else generate a minimal one\n try {\n const targetTsconfig = resolve(targetPath, 'tsconfig.json');\n if (!existsSync(targetTsconfig)) {\n const templateTsconfig = resolve(templateDir, 'tsconfig.json');\n if (existsSync(templateTsconfig)) {\n await copyFile(templateTsconfig, targetTsconfig);\n copiedFiles.push({\n source: templateTsconfig,\n destination: targetTsconfig,\n unit: { kind: 'other', id: 'tsconfig.json' },\n });\n console.info('✓ Copied tsconfig.json from template to target');\n } else {\n // Generate a minimal tsconfig.json as a fallback\n const minimalTsconfig = {\n compilerOptions: {\n target: 'ES2020',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: false,\n esModuleInterop: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n outDir: 'dist',\n },\n include: ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'],\n exclude: ['node_modules', 'dist', 'build', '.next', '.output', '.turbo'],\n } as const;\n\n await writeFile(targetTsconfig, JSON.stringify(minimalTsconfig, null, 2), 'utf-8');\n copiedFiles.push({\n source: '[generated tsconfig.json]',\n destination: targetTsconfig,\n unit: { kind: 'other', id: 'tsconfig.json' },\n });\n console.info('✓ Generated minimal tsconfig.json in target');\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'tsconfig.json' },\n issue: `Failed to ensure tsconfig.json: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: 'tsconfig.json',\n targetFile: 'tsconfig.json',\n });\n }\n\n // If the target project has no Mastra index file, copy from template\n try {\n const targetMastraIndex = resolve(targetPath, 'src/mastra/index.ts');\n if (!existsSync(targetMastraIndex)) {\n const templateMastraIndex = resolve(templateDir, 'src/mastra/index.ts');\n if (existsSync(templateMastraIndex)) {\n if (!existsSync(dirname(targetMastraIndex))) {\n await mkdir(dirname(targetMastraIndex), { recursive: true });\n }\n await copyFile(templateMastraIndex, targetMastraIndex);\n copiedFiles.push({\n source: templateMastraIndex,\n destination: targetMastraIndex,\n unit: { kind: 'other', id: 'mastra-index' },\n });\n console.info('✓ Copied Mastra index file from template');\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'mastra-index' },\n issue: `Failed to ensure Mastra index file: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: 'src/mastra/index.ts',\n targetFile: 'src/mastra/index.ts',\n });\n }\n\n // Handle .gitignore file merging\n try {\n const targetGitignore = resolve(targetPath, '.gitignore');\n const templateGitignore = resolve(templateDir, '.gitignore');\n\n const targetExists = existsSync(targetGitignore);\n const templateExists = existsSync(templateGitignore);\n\n if (templateExists) {\n if (!targetExists) {\n // Target has no .gitignore - copy template's completely\n await copyFile(templateGitignore, targetGitignore);\n copiedFiles.push({\n source: templateGitignore,\n destination: targetGitignore,\n unit: { kind: 'other', id: 'gitignore' },\n });\n console.info('✓ Copied .gitignore from template to target');\n } else {\n // Both exist - merge them intelligently\n const targetContent = await readFile(targetGitignore, 'utf-8');\n const templateContent = await readFile(templateGitignore, 'utf-8');\n\n const mergedContent = mergeGitignoreFiles(targetContent, templateContent, slug);\n\n if (mergedContent !== targetContent) {\n const addedLines = mergedContent.split('\\n').length - targetContent.split('\\n').length;\n await writeFile(targetGitignore, mergedContent, 'utf-8');\n copiedFiles.push({\n source: templateGitignore,\n destination: targetGitignore,\n unit: { kind: 'other', id: 'gitignore-merge' },\n });\n console.info(`✓ Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);\n } else {\n console.info('ℹ No new .gitignore entries to add from template');\n }\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'gitignore' },\n issue: `Failed to handle .gitignore file: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: '.gitignore',\n targetFile: '.gitignore',\n });\n }\n\n // Handle .env file merging with template variables\n try {\n const { variables } = inputData;\n if (variables && Object.keys(variables).length > 0) {\n const targetEnv = resolve(targetPath, '.env');\n const targetExists = existsSync(targetEnv);\n\n if (!targetExists) {\n // Target has no .env - create new one with template variables\n const envContent = [\n `# Environment variables for ${slug}`,\n ...Object.entries(variables).map(([key, value]) => `${key}=${value}`),\n ].join('\\n');\n\n await writeFile(targetEnv, envContent, 'utf-8');\n copiedFiles.push({\n source: '[template variables]',\n destination: targetEnv,\n unit: { kind: 'other', id: 'env' },\n });\n console.info(`✓ Created .env file with ${Object.keys(variables).length} template variables`);\n } else {\n // Both exist - merge them intelligently\n const targetContent = await readFile(targetEnv, 'utf-8');\n const mergedContent = mergeEnvFiles(targetContent, variables, slug);\n\n if (mergedContent !== targetContent) {\n const addedLines = mergedContent.split('\\n').length - targetContent.split('\\n').length;\n await writeFile(targetEnv, mergedContent, 'utf-8');\n copiedFiles.push({\n source: '[template variables]',\n destination: targetEnv,\n unit: { kind: 'other', id: 'env-merge' },\n });\n console.info(`✓ Merged new environment variables into existing .env file (${addedLines} new entries)`);\n } else {\n console.info('ℹ No new environment variables to add (all already exist in .env)');\n }\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'env' },\n issue: `Failed to handle .env file: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: '.env',\n targetFile: '.env',\n });\n }\n\n // Commit the copied files\n if (copiedFiles.length > 0) {\n try {\n const fileList = copiedFiles.map(f => f.destination);\n await gitAddAndCommit(\n targetPath,\n `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`,\n fileList,\n { skipIfNoStaged: true },\n );\n console.info(`✓ Committed ${copiedFiles.length} copied files`);\n } catch (commitError) {\n console.warn('Failed to commit copied files:', commitError);\n }\n }\n\n const message = `Programmatic file copy completed. Copied ${copiedFiles.length} files, ${conflicts.length} conflicts detected.`;\n console.info(message);\n\n return {\n success: true,\n copiedFiles,\n conflicts,\n message,\n };\n } catch (error) {\n console.error('Programmatic file copy failed:', error);\n\n return {\n success: false,\n copiedFiles: [],\n conflicts: [],\n message: `Programmatic file copy failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 9: Intelligent merging with AgentBuilder\nconst intelligentMergeStep = createStep({\n id: 'intelligent-merge',\n description: 'Use AgentBuilder to intelligently merge template files',\n inputSchema: IntelligentMergeInputSchema,\n outputSchema: IntelligentMergeResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Intelligent merge step starting...');\n const { conflicts, copiedFiles, commitSha, slug, templateDir, branchName } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n try {\n const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai('gpt-4.1') });\n\n // Create copyFile tool for edge cases\n const copyFileTool = createTool({\n id: 'copy-file',\n description:\n 'Copy a file from template to target project (use only for edge cases - most files are already copied programmatically).',\n inputSchema: z.object({\n sourcePath: z.string().describe('Path to the source file relative to template directory'),\n destinationPath: z.string().describe('Path to the destination file relative to target project'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async input => {\n try {\n const { sourcePath, destinationPath } = input;\n\n // Use templateDir directly from input\n const resolvedSourcePath = resolve(templateDir, sourcePath);\n const resolvedDestinationPath = resolve(targetPath, destinationPath);\n\n if (existsSync(resolvedSourcePath) && !existsSync(dirname(resolvedDestinationPath))) {\n await mkdir(dirname(resolvedDestinationPath), { recursive: true });\n }\n\n await copyFile(resolvedSourcePath, resolvedDestinationPath);\n return {\n success: true,\n message: `Successfully copied file from ${sourcePath} to ${destinationPath}`,\n };\n } catch (err) {\n return {\n success: false,\n message: `Failed to copy file: ${err instanceof Error ? err.message : String(err)}`,\n errorMessage: err instanceof Error ? err.message : String(err),\n };\n }\n },\n });\n\n // Initialize AgentBuilder for merge and registration\n const agentBuilder = new AgentBuilder({\n projectPath: targetPath,\n mode: 'template',\n model,\n instructions: `\nYou are an expert at integrating Mastra template components into existing projects.\n\nCRITICAL CONTEXT:\n- Files have been programmatically copied from template to target project\n- Your job is to handle integration issues, registration, and validation\n\nFILES SUCCESSFULLY COPIED:\n${JSON.stringify(copiedFiles, null, 2)}\n\nCONFLICTS TO RESOLVE:\n${JSON.stringify(conflicts, null, 2)}\n\nCRITICAL INSTRUCTIONS:\n1. **Package management**: NO need to install packages (already handled by package merge step)\n2. **File copying**: Most files are already copied programmatically. Only use copyFile tool for edge cases where additional files are needed for conflict resolution\n\nKEY RESPONSIBILITIES:\n1. Resolve any conflicts from the programmatic copy step\n2. Register components in existing Mastra index file (agents, workflows, networks, mcp-servers)\n3. DO NOT register tools in existing Mastra index file - tools should remain standalone\n4. Copy additional files ONLY if needed for conflict resolution\n\nMASTRA INDEX FILE HANDLING (src/mastra/index.ts):\n1. **Verify the file exists**\n - Call readFile\n - If it fails with ENOENT (or listDirectory shows it missing) -> copyFile the template version to src/mastra/index.ts, then confirm it now exists\n - Always verify after copying that the file exists and is accessible\n\n2. **Edit the file**\n - Always work with the full file content\n - Generate the complete, correct source (imports, anchors, registrations, formatting)\n - Keep existing registrations intact and maintain file structure\n - Ensure proper spacing and organization of new additions\n\n3. **Handle anchors and structure**\n - When generating new content, ensure you do not duplicate existing imports or object entries\n - If required anchors (e.g., agents: {}) are missing, add them while generating the new content\n - Add missing anchors just before the closing brace of the Mastra config\n - Do not restructure or reorder existing anchors and registrations\n\nCRITICAL: ALWAYS use writeFile to update the mastra/index.ts file when needed to register new components.\n\nMASTRA-SPECIFIC REGISTRATION:\n- Agents: Register in existing Mastra index file\n- Workflows: Register in existing Mastra index file\n- Networks: Register in existing Mastra index file\n- MCP servers: Register in existing Mastra index file\n- Tools: Copy to ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool} but DO NOT register in existing Mastra index file\n- If an anchor (e.g., \"agents: {\") is not found, avoid complex restructuring; instead, insert the missing anchor on a new line (e.g., add \"agents: {\" just before the closing brace of the Mastra config) and then proceed with the other registrations.\n\nCONFLICT RESOLUTION AND FILE COPYING:\n- Only copy files if needed to resolve specific conflicts\n- When copying files from template:\n - Ensure you get the right file name and path\n - Verify the destination directory exists\n - Maintain the same relative path structure\n - Only copy files that are actually needed\n- Preserve existing functionality when resolving conflicts\n- Focus on registration and conflict resolution, validation will happen in a later step\n\nTemplate information:\n- Slug: ${slug}\n- Commit: ${commitSha.substring(0, 7)}\n- Branch: ${branchName}\n`,\n tools: {\n copyFile: copyFileTool,\n },\n });\n\n // Create task list for systematic processing\n const tasks = [];\n\n // Add conflict resolution tasks\n conflicts.forEach(conflict => {\n tasks.push({\n id: `conflict-${conflict.unit.kind}-${conflict.unit.id}`,\n content: `Resolve conflict: ${conflict.issue}`,\n status: 'pending' as const,\n priority: 'high' as const,\n notes: `Unit: ${conflict.unit.kind}:${conflict.unit.id}, Issue: ${conflict.issue}, Source: ${conflict.sourceFile}, Target: ${conflict.targetFile}`,\n });\n });\n\n // Add registration tasks for successfully copied files\n const registrableKinds = new Set(['agent', 'workflow', 'network', 'mcp-server']);\n const registrableFiles = copiedFiles.filter(f => registrableKinds.has(f.unit.kind as any));\n const targetMastraIndex = resolve(targetPath, 'src/mastra/index.ts');\n const mastraIndexExists = existsSync(targetMastraIndex);\n console.info(`Mastra index exists: ${mastraIndexExists} at ${targetMastraIndex}`);\n console.info(\n 'Registrable components:',\n registrableFiles.map(f => `${f.unit.kind}:${f.unit.id}`),\n );\n if (registrableFiles.length > 0) {\n tasks.push({\n id: 'register-components',\n content: `Register ${registrableFiles.length} components in existing Mastra index file (src/mastra/index.ts)`,\n status: 'pending' as const,\n priority: 'medium' as const,\n dependencies: conflicts.length > 0 ? conflicts.map(c => `conflict-${c.unit.kind}-${c.unit.id}`) : undefined,\n notes: `Components to register: ${registrableFiles.map(f => `${f.unit.kind}:${f.unit.id}`).join(', ')}`,\n });\n }\n\n // Note: Validation is handled by the dedicated validation step, not here\n\n console.info(`Creating task list with ${tasks.length} tasks...`);\n await AgentBuilderDefaults.manageTaskList({ action: 'create', tasks });\n\n // Log git state before merge operations\n await logGitState(targetPath, 'before intelligent merge');\n\n const prompt = `\nYou need to work through a task list to complete the template integration.\n\nCRITICAL INSTRUCTIONS:\n\n**STEP 1: GET YOUR TASK LIST**\n1. Use manageTaskList tool with action \"list\" to see all pending tasks\n2. Work through tasks in dependency order (complete dependencies first)\n\n**STEP 2: PROCESS EACH TASK SYSTEMATICALLY**\nFor each task:\n1. Use manageTaskList to mark the current task as 'in_progress'\n2. Complete the task according to its requirements\n3. Use manageTaskList to mark the task as 'completed' when done\n4. Continue until all tasks are completed\n\n**TASK TYPES AND REQUIREMENTS:**\n\n**Conflict Resolution Tasks:**\n- Analyze the specific conflict and determine best resolution strategy\n- For file name conflicts: merge content or rename appropriately\n- For missing files: investigate and copy if needed\n- For other issues: apply appropriate fixes\n\n**Component Registration Task:**\n- Update main Mastra instance file to register new components\n- Only register: agents, workflows, networks, mcp-servers\n- DO NOT register tools in main config\n- Ensure proper import paths and naming conventions\n\n**COMMIT STRATEGY:**\n- After resolving conflicts: \"feat(template): resolve conflicts for ${slug}@${commitSha.substring(0, 7)}\"\n- After registration: \"feat(template): register components from ${slug}@${commitSha.substring(0, 7)}\"\n\n**CRITICAL NOTES:**\n- Template source: ${templateDir}\n- Target project: ${targetPath}\n- Focus ONLY on conflict resolution and component registration\n- Use executeCommand for git commits after each task\n- DO NOT perform validation - that's handled by the dedicated validation step\n\nStart by listing your tasks and work through them systematically!\n`;\n\n // Process tasks systematically\n const resolvedModel = await agentBuilder.getModel();\n const isSupported = isSupportedLanguageModel(resolvedModel);\n\n const result = isSupported ? await agentBuilder.stream(prompt) : await agentBuilder.streamLegacy(prompt);\n\n // Extract actual conflict resolution details from agent execution\n const actualResolutions: Array<{\n taskId: string;\n action: string;\n status: string;\n content: string;\n notes?: string;\n }> = [];\n\n for await (const chunk of result.fullStream) {\n if (chunk.type === 'step-finish' || chunk.type === 'step-start') {\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n console.info({\n type: chunk.type,\n msgId: chunkData.messageId,\n });\n } else {\n console.info(JSON.stringify(chunk, null, 2));\n\n // Extract task management tool results\n if (chunk.type === 'tool-result') {\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n if (chunkData.toolName === 'manageTaskList') {\n try {\n const toolResult = chunkData.result;\n if (toolResult.action === 'update' && toolResult.status === 'completed') {\n actualResolutions.push({\n taskId: toolResult.taskId || '',\n action: toolResult.action,\n status: toolResult.status,\n content: toolResult.content || '',\n notes: toolResult.notes,\n });\n console.info(`📋 Task completed: ${toolResult.taskId} - ${toolResult.content}`);\n }\n } catch (parseError) {\n console.warn('Failed to parse task management result:', parseError);\n }\n }\n }\n }\n }\n\n // Log git state after merge operations\n await logGitState(targetPath, 'after intelligent merge');\n\n // Map actual resolutions back to conflicts\n const conflictResolutions = conflicts.map(conflict => {\n const taskId = `conflict-${conflict.unit.kind}-${conflict.unit.id}`;\n const actualResolution = actualResolutions.find(r => r.taskId === taskId);\n\n if (actualResolution) {\n return {\n unit: conflict.unit,\n issue: conflict.issue,\n resolution:\n actualResolution.notes ||\n actualResolution.content ||\n `Completed: ${conflict.unit.kind} ${conflict.unit.id}`,\n actualWork: true,\n };\n } else {\n return {\n unit: conflict.unit,\n issue: conflict.issue,\n resolution: `No specific resolution found for ${conflict.unit.kind} ${conflict.unit.id}`,\n actualWork: false,\n };\n }\n });\n\n await gitAddAndCommit(targetPath, `feat(template): apply intelligent merge for ${slug}`, undefined, {\n skipIfNoStaged: true,\n });\n\n return {\n success: true,\n applied: true,\n message: `Successfully resolved ${conflicts.length} conflicts from template ${slug}`,\n conflictsResolved: conflictResolutions,\n };\n } catch (error) {\n return {\n success: false,\n applied: false,\n message: `Failed to resolve conflicts: ${error instanceof Error ? error.message : String(error)}`,\n conflictsResolved: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 10: Validation and Fix Step - validates merged code and fixes any issues\nconst validationAndFixStep = createStep({\n id: 'validation-and-fix',\n description: 'Validate the merged template code and fix any issues using a specialized agent',\n inputSchema: ValidationFixInputSchema,\n outputSchema: ValidationFixResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Validation and fix step starting...');\n const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n // Skip validation if no changes were made\n const hasChanges = copiedFiles.length > 0 || (conflictsResolved && conflictsResolved.length > 0);\n if (!hasChanges) {\n console.info('⏭️ Skipping validation - no files copied or conflicts resolved');\n return {\n success: true,\n applied: false,\n message: 'No changes to validate - template already integrated or no conflicts resolved',\n validationResults: {\n valid: true,\n errorsFixed: 0,\n remainingErrors: 0,\n },\n };\n }\n\n console.info(\n `📋 Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`,\n );\n\n let currentIteration = 1; // Declare at function scope for error handling\n\n try {\n const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai('gpt-4.1') });\n\n const allTools = await AgentBuilderDefaults.listToolsForMode(targetPath, 'template');\n\n const validationAgent = new Agent({\n id: 'code-validator-fixer',\n name: 'Code Validator Fixer',\n description: 'Specialized agent for validating and fixing template integration issues',\n instructions: `You are a code validation and fixing specialist. Your job is to:\n\n1. **Run comprehensive validation** using the validateCode tool to check for:\n - TypeScript compilation errors\n - ESLint issues\n - Import/export problems\n - Missing dependencies\n - Index file structure and exports\n - Component registration correctness\n - Naming convention compliance\n\n2. **Fix validation errors systematically**:\n - Use readFile to examine files with errors\n - Use multiEdit for simple search-replace fixes (single line changes)\n - Use replaceLines for complex multiline fixes (imports, function signatures, etc.)\n - Use listDirectory to understand project structure when fixing import paths\n - Update file contents to resolve TypeScript and linting issues\n\n3. **Choose the right tool for the job**:\n - multiEdit: Simple replacements, single line changes, small fixes\n - replaceLines: Multiline imports, function signatures, complex code blocks\n - writeFile: ONLY for creating new files (never overwrite existing)\n\n4. **Create missing files ONLY when necessary**:\n - Use writeFile ONLY for creating NEW files that don't exist\n - NEVER overwrite existing files - use multiEdit or replaceLines instead\n - Common cases: missing barrel files (index.ts), missing config files, missing type definitions\n - Always check with readFile first to ensure file doesn't exist\n\n5. **Fix ALL template integration issues**:\n - Fix import path issues in copied files\n - Ensure TypeScript imports and exports are correct\n - Validate integration works properly\n - Fix files copied with new names based on unit IDs\n - Update original template imports that reference old filenames\n - Fix missing imports in index files\n - Fix incorrect file paths in imports\n - Fix type mismatches after integration\n - Fix missing exports in barrel files\n - Use the COPIED FILES mapping below to fix import paths\n - Fix any missing dependencies or module resolution issues\n\n6. **Validate index file structure**:\n - Correct imports for all components\n - Proper anchor structure (agents: {}, etc.)\n - No duplicate registrations\n - Correct export names and paths\n - Proper formatting and organization\n\n7. **Follow naming conventions**:\n Import paths:\n - camelCase: import { myAgent } from './myAgent'\n - snake_case: import { myAgent } from './my_agent'\n - kebab-case: import { myAgent } from './my-agent'\n - PascalCase: import { MyAgent } from './MyAgent'\n\n File names:\n - camelCase: weatherAgent.ts, chatAgent.ts\n - snake_case: weather_agent.ts, chat_agent.ts\n - kebab-case: weather-agent.ts, chat-agent.ts\n - PascalCase: WeatherAgent.ts, ChatAgent.ts\n\n Key Rule: Keep variable/export names unchanged, only adapt file names and import paths\n\n8. **Re-validate after fixes** to ensure all issues are resolved\n\nCRITICAL: Always validate the entire project first to get a complete picture of issues, then fix them systematically, and re-validate to confirm fixes worked.\n\nCRITICAL TOOL SELECTION GUIDE:\n- **multiEdit**: Use for simple string replacements, single-line changes\n Example: changing './oldPath' to './newPath'\n \n- **replaceLines**: Use for multiline fixes, complex code structures\n Example: fixing multiline imports, function signatures, or code blocks\n Usage: replaceLines({ filePath: 'file.ts', startLine: 5, endLine: 8, newContent: 'new multiline content' })\n \n- **writeFile**: ONLY for creating new files that don't exist\n Example: creating missing index.ts barrel files\n\nCRITICAL WRITEFILЕ SAFETY RULES:\n- ONLY use writeFile for creating NEW files that don't exist\n- ALWAYS check with readFile first to verify file doesn't exist\n- NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead\n- Common valid uses: missing index.ts barrel files, missing type definitions, missing config files\n\nCRITICAL IMPORT PATH RESOLUTION:\nThe following files were copied from template with new names:\n${JSON.stringify(copiedFiles, null, 2)}\n\nWhen fixing import errors:\n1. Check if the missing module corresponds to a copied file\n2. Use listDirectory to verify actual filenames in target directories\n3. Update import paths to match the actual copied filenames\n4. Ensure exported variable names match what's being imported\n\nEXAMPLE: If error shows \"Cannot find module './tools/download-csv-tool'\" but a file was copied as \"csv-fetcher-tool.ts\", update the import to \"./tools/csv-fetcher-tool\"\n\n${conflictsResolved ? `CONFLICTS RESOLVED BY INTELLIGENT MERGE:\\n${JSON.stringify(conflictsResolved, null, 2)}\\n` : ''}\n\nINTEGRATED UNITS:\n${JSON.stringify(orderedUnits, null, 2)}\n\nBe thorough and methodical. Always use listDirectory to verify actual file existence before fixing imports.`,\n model,\n tools: {\n validateCode: allTools.validateCode,\n readFile: allTools.readFile,\n writeFile: allTools.writeFile,\n multiEdit: allTools.multiEdit,\n replaceLines: allTools.replaceLines,\n listDirectory: allTools.listDirectory,\n executeCommand: allTools.executeCommand,\n },\n });\n\n console.info('Starting validation and fix agent with internal loop...');\n\n let validationResults = {\n valid: false,\n errorsFixed: 0,\n remainingErrors: 1, // Start with 1 to enter the loop\n iteration: currentIteration,\n lastValidationErrors: [] as any[], // Store the actual error details\n };\n\n // Loop up to maxIterations times or until all errors are fixed\n while (validationResults.remainingErrors > 0 && currentIteration <= maxIterations) {\n console.info(`\\n=== Validation Iteration ${currentIteration} ===`);\n\n const iterationPrompt =\n currentIteration === 1\n ? `Please validate the template integration and fix any errors found in the project at ${targetPath}. The template \"${slug}\" (${commitSha.substring(0, 7)}) was just integrated and may have validation issues that need fixing.\n\nStart by running validateCode with all validation types to get a complete picture of any issues, then systematically fix them.`\n : `Continue validation and fixing for the template integration at ${targetPath}. This is iteration ${currentIteration} of validation.\n\nPrevious iterations may have fixed some issues, so start by re-running validateCode to see the current state, then fix any remaining issues.`;\n\n const resolvedModel = await validationAgent.getModel();\n const isSupported = isSupportedLanguageModel(resolvedModel);\n const output = z.object({ success: z.boolean() });\n const result = isSupported\n ? await tryStreamWithJsonFallback(validationAgent, iterationPrompt, {\n structuredOutput: {\n schema: output,\n },\n })\n : await validationAgent.streamLegacy(iterationPrompt, {\n experimental_output: output as any,\n });\n\n let iterationErrors = 0;\n let previousErrors = validationResults.remainingErrors;\n let lastValidationResult: any = null;\n\n for await (const chunk of result.fullStream) {\n if (chunk.type === 'step-finish' || chunk.type === 'step-start') {\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n console.info({\n type: chunk.type,\n msgId: chunkData.messageId,\n iteration: currentIteration,\n });\n } else {\n console.info(JSON.stringify(chunk, null, 2));\n }\n if (chunk.type === 'tool-result') {\n // Track validation results\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n if (chunkData.toolName === 'validateCode') {\n const toolResult = chunkData.result;\n lastValidationResult = toolResult; // Store the full result\n if (toolResult?.summary) {\n iterationErrors = toolResult.summary.totalErrors || 0;\n console.info(`Iteration ${currentIteration}: Found ${iterationErrors} errors`);\n }\n }\n }\n }\n\n // Update results for this iteration\n validationResults.remainingErrors = iterationErrors;\n validationResults.errorsFixed += Math.max(0, previousErrors - iterationErrors);\n validationResults.valid = iterationErrors === 0;\n validationResults.iteration = currentIteration;\n\n // Store the last validation errors if any remain\n if (iterationErrors > 0 && lastValidationResult?.errors) {\n validationResults.lastValidationErrors = lastValidationResult.errors;\n }\n\n console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);\n\n // Break if no errors or max iterations reached\n if (iterationErrors === 0) {\n console.info(`✅ All validation issues resolved in ${currentIteration} iterations!`);\n break;\n } else if (currentIteration >= maxIterations) {\n console.info(`⚠️ Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);\n break;\n }\n\n currentIteration++;\n }\n\n // Commit the validation fixes\n try {\n await gitAddAndCommit(\n targetPath,\n `fix(template): resolve validation errors for ${slug}@${commitSha.substring(0, 7)}`,\n undefined,\n {\n skipIfNoStaged: true,\n },\n );\n } catch (commitError) {\n console.warn('Failed to commit validation fixes:', commitError);\n }\n\n const success = validationResults.valid;\n\n return {\n success,\n applied: true,\n message: `Validation completed in ${currentIteration} iteration${currentIteration > 1 ? 's' : ''}. ${validationResults.valid ? 'All issues resolved!' : `${validationResults.remainingErrors} issue${validationResults.remainingErrors > 1 ? 's' : ''} remaining`}`,\n validationResults: {\n valid: validationResults.valid,\n errorsFixed: validationResults.errorsFixed,\n remainingErrors: validationResults.remainingErrors,\n errors: validationResults.lastValidationErrors,\n },\n };\n } catch (error) {\n console.error('Validation and fix failed:', error);\n return {\n success: false,\n applied: false,\n message: `Validation and fix failed: ${error instanceof Error ? error.message : String(error)}`,\n validationResults: {\n valid: false,\n errorsFixed: 0,\n remainingErrors: -1,\n },\n error: error instanceof Error ? error.message : String(error),\n };\n } finally {\n // Cleanup template directory\n try {\n await rm(templateDir, { recursive: true, force: true });\n console.info(`✓ Cleaned up template directory: ${templateDir}`);\n } catch (cleanupError) {\n console.warn('Failed to cleanup template directory:', cleanupError);\n }\n }\n },\n});\n\n// Create the complete workflow\nexport const agentBuilderTemplateWorkflow = createWorkflow({\n id: 'agent-builder-template',\n description:\n 'Merges a Mastra template repository into the current project using intelligent AgentBuilder-powered merging',\n inputSchema: AgentBuilderInputSchema,\n outputSchema: ApplyResultSchema,\n steps: [\n cloneTemplateStep,\n analyzePackageStep,\n discoverUnitsStep,\n orderUnitsStep,\n packageMergeStep,\n installStep,\n programmaticFileCopyStep,\n intelligentMergeStep,\n validationAndFixStep,\n ],\n})\n .then(cloneTemplateStep)\n .map(async ({ getStepResult }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n\n // Check for failure in clone step\n if (shouldAbortWorkflow(cloneResult)) {\n throw new Error(`Critical failure in clone step: ${cloneResult.error}`);\n }\n\n return cloneResult;\n })\n .parallel([analyzePackageStep, discoverUnitsStep])\n .map(async ({ getStepResult }) => {\n const analyzeResult = getStepResult(analyzePackageStep);\n const discoverResult = getStepResult(discoverUnitsStep);\n\n // Check for failures in parallel steps\n if (shouldAbortWorkflow(analyzeResult)) {\n throw new Error(`Failure in analyze package step: ${analyzeResult.error || 'Package analysis failed'}`);\n }\n\n if (shouldAbortWorkflow(discoverResult)) {\n throw new Error(`Failure in discover units step: ${discoverResult.error || 'Unit discovery failed'}`);\n }\n\n return discoverResult;\n })\n .then(orderUnitsStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n return {\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n };\n })\n .then(prepareBranchStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const packageResult = getStepResult(analyzePackageStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n return {\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n packageInfo: packageResult,\n };\n })\n .then(packageMergeStep)\n .map(async ({ getInitData }) => {\n const initData = getInitData<AgentBuilderInputSchemaType>();\n return {\n targetPath: initData.targetPath,\n };\n })\n .then(installStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const orderResult = getStepResult(orderUnitsStep);\n const installResult = getStepResult(installStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n\n if (shouldAbortWorkflow(installResult)) {\n throw new Error(`Failure in install step: ${installResult.error || 'Install failed'}`);\n }\n return {\n orderedUnits: orderResult.orderedUnits,\n templateDir: cloneResult.templateDir,\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n variables: initData.variables,\n };\n })\n .then(programmaticFileCopyStep)\n .map(async ({ getStepResult, getInitData }) => {\n const copyResult = getStepResult(programmaticFileCopyStep);\n const cloneResult = getStepResult(cloneTemplateStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n\n return {\n conflicts: copyResult.conflicts,\n copiedFiles: copyResult.copiedFiles,\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n templateDir: cloneResult.templateDir,\n };\n })\n .then(intelligentMergeStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const orderResult = getStepResult(orderUnitsStep);\n const copyResult = getStepResult(programmaticFileCopyStep);\n const mergeResult = getStepResult(intelligentMergeStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n\n return {\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n templateDir: cloneResult.templateDir,\n orderedUnits: orderResult.orderedUnits,\n copiedFiles: copyResult.copiedFiles,\n conflictsResolved: mergeResult.conflictsResolved,\n };\n })\n .then(validationAndFixStep)\n .map(async ({ getStepResult }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const analyzeResult = getStepResult(analyzePackageStep);\n const discoverResult = getStepResult(discoverUnitsStep);\n const orderResult = getStepResult(orderUnitsStep);\n const prepareBranchResult = getStepResult(prepareBranchStep);\n const packageMergeResult = getStepResult(packageMergeStep);\n const installResult = getStepResult(installStep);\n const copyResult = getStepResult(programmaticFileCopyStep);\n const intelligentMergeResult = getStepResult(intelligentMergeStep);\n const validationResult = getStepResult(validationAndFixStep);\n\n const branchName = prepareBranchResult.branchName;\n\n // Aggregate errors from all steps\n const allErrors = [\n cloneResult.error,\n analyzeResult.error,\n discoverResult.error,\n orderResult.error,\n prepareBranchResult.error,\n packageMergeResult.error,\n installResult.error,\n copyResult.error,\n intelligentMergeResult.error,\n validationResult.error,\n ].filter(Boolean);\n\n // Determine overall success based on all step results\n const overallSuccess =\n cloneResult.success !== false &&\n analyzeResult.success !== false &&\n discoverResult.success !== false &&\n orderResult.success !== false &&\n prepareBranchResult.success !== false &&\n packageMergeResult.success !== false &&\n installResult.success !== false &&\n copyResult.success !== false &&\n intelligentMergeResult.success !== false &&\n validationResult.success !== false;\n\n // Create comprehensive message\n const messages = [];\n if (copyResult.copiedFiles?.length > 0) {\n messages.push(`${copyResult.copiedFiles.length} files copied`);\n }\n if (copyResult.conflicts?.length > 0) {\n messages.push(`${copyResult.conflicts.length} conflicts skipped`);\n }\n if (intelligentMergeResult.conflictsResolved?.length > 0) {\n messages.push(`${intelligentMergeResult.conflictsResolved.length} conflicts resolved`);\n }\n if (validationResult.validationResults?.errorsFixed > 0) {\n messages.push(`${validationResult.validationResults.errorsFixed} validation errors fixed`);\n }\n\n if (validationResult.validationResults?.remainingErrors > 0) {\n messages.push(`${validationResult.validationResults.remainingErrors} validation issues remain`);\n }\n\n const comprehensiveMessage =\n messages.length > 0\n ? `Template merge completed: ${messages.join(', ')}`\n : validationResult.message || 'Template merge completed';\n\n return {\n success: overallSuccess,\n applied: validationResult.applied || copyResult.copiedFiles?.length > 0 || false,\n message: comprehensiveMessage,\n validationResults: validationResult.validationResults,\n error: allErrors.length > 0 ? allErrors.join('; ') : undefined,\n errors: allErrors.length > 0 ? allErrors : undefined,\n branchName,\n // Additional debugging info\n stepResults: {\n cloneSuccess: cloneResult.success,\n analyzeSuccess: analyzeResult.success,\n discoverSuccess: discoverResult.success,\n orderSuccess: orderResult.success,\n prepareBranchSuccess: prepareBranchResult.success,\n packageMergeSuccess: packageMergeResult.success,\n installSuccess: installResult.success,\n copySuccess: copyResult.success,\n mergeSuccess: intelligentMergeResult.success,\n validationSuccess: validationResult.success,\n filesCopied: copyResult.copiedFiles?.length || 0,\n conflictsSkipped: copyResult.conflicts?.length || 0,\n conflictsResolved: intelligentMergeResult.conflictsResolved?.length || 0,\n },\n };\n })\n .commit();\n\n// Helper to merge a template by slug\nexport async function mergeTemplateBySlug(slug: string, targetPath?: string) {\n const template = await getMastraTemplate(slug);\n const run = await agentBuilderTemplateWorkflow.createRun();\n return await run.start({\n inputData: {\n repo: template.githubUrl,\n slug: template.slug,\n targetPath,\n },\n });\n}\n\n// Helper function to determine conflict resolution strategy\nconst determineConflictStrategy = (\n _unit: { kind: string; id: string },\n _targetFile: string,\n): 'skip' | 'backup-and-replace' | 'rename' => {\n // For now, always skip conflicts to avoid disrupting existing files\n // TODO: Enable advanced strategies based on user feedback\n return 'skip';\n\n // Future logic (currently disabled):\n // if (['agent', 'workflow', 'network'].includes(unit.kind)) {\n // return 'backup-and-replace';\n // }\n // if (unit.kind === 'tool') {\n // return 'rename';\n // }\n // return 'backup-and-replace';\n};\n\n// Helper function to check if a step result indicates a failure\nconst shouldAbortWorkflow = (stepResult: any): boolean => {\n return stepResult?.success === false || stepResult?.error;\n};\n","import * as z4 from \"zod/v4\";\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/2.0.3/baf9ca0bc6c1e850f5a9c142d47d3731e6921106a5f2b12483df7e7922a48657/node_modules/@ai-sdk/provider/dist/index.mjs\nvar marker$1 = \"vercel.ai.error\";\nvar symbol$1 = Symbol.for(marker$1);\nvar _a$1;\nvar _b$1;\nvar AISDKError = class _AISDKError extends (_b$1 = Error, _a$1 = symbol$1, _b$1) {\n\t/**\n\t* Creates an AI SDK Error.\n\t*\n\t* @param {Object} params - The parameters for creating the error.\n\t* @param {string} params.name - The name of the error.\n\t* @param {string} params.message - The error message.\n\t* @param {unknown} [params.cause] - The underlying cause of the error.\n\t*/\n\tconstructor({ name: name14, message, cause }) {\n\t\tsuper(message);\n\t\tthis[_a$1] = true;\n\t\tthis.name = name14;\n\t\tthis.cause = cause;\n\t}\n\t/**\n\t* Checks if the given error is an AI SDK Error.\n\t* @param {unknown} error - The error to check.\n\t* @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n\t*/\n\tstatic isInstance(error) {\n\t\treturn _AISDKError.hasMarker(error, marker$1);\n\t}\n\tstatic hasMarker(error, marker15) {\n\t\tconst markerSymbol = Symbol.for(marker15);\n\t\treturn error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n\t}\n};\nvar name$1 = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name$1}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2;\nvar _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n\tconstructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {\n\t\tsuper({\n\t\t\tname: name$1,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a2] = true;\n\t\tthis.url = url;\n\t\tthis.requestBodyValues = requestBodyValues;\n\t\tthis.statusCode = statusCode;\n\t\tthis.responseHeaders = responseHeaders;\n\t\tthis.responseBody = responseBody;\n\t\tthis.isRetryable = isRetryable;\n\t\tthis.data = data;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker2);\n\t}\n};\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3;\nvar _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n\tconstructor({ message = \"Empty response body\" } = {}) {\n\t\tsuper({\n\t\t\tname: name2,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a3] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker3);\n\t}\n};\nfunction getErrorMessage$1(error) {\n\tif (error == null) return \"unknown error\";\n\tif (typeof error === \"string\") return error;\n\tif (error instanceof Error) return error.message;\n\treturn JSON.stringify(error);\n}\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4;\nvar _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n\tconstructor({ message, cause, argument }) {\n\t\tsuper({\n\t\t\tname: name3,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a4] = true;\n\t\tthis.argument = argument;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker4);\n\t}\n};\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5;\nvar _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n\tconstructor({ prompt, message, cause }) {\n\t\tsuper({\n\t\t\tname: name4,\n\t\t\tmessage: `Invalid prompt: ${message}`,\n\t\t\tcause\n\t\t});\n\t\tthis[_a5] = true;\n\t\tthis.prompt = prompt;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker5);\n\t}\n};\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6;\nvar _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n\tconstructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {\n\t\tsuper({\n\t\t\tname: name5,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a6] = true;\n\t\tthis.data = data;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker6);\n\t}\n};\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7;\nvar _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n\tconstructor({ text, cause }) {\n\t\tsuper({\n\t\t\tname: name6,\n\t\t\tmessage: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage$1(cause)}`,\n\t\t\tcause\n\t\t});\n\t\tthis[_a7] = true;\n\t\tthis.text = text;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker7);\n\t}\n};\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8;\nvar _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n\tconstructor({ message }) {\n\t\tsuper({\n\t\t\tname: name7,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a8] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker8);\n\t}\n};\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9;\nvar _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n\tconstructor({ message }) {\n\t\tsuper({\n\t\t\tname: name8,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a9] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker9);\n\t}\n};\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10;\nvar _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n\tconstructor({ message = \"No content generated.\" } = {}) {\n\t\tsuper({\n\t\t\tname: name9,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a10] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker10);\n\t}\n};\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11;\nvar _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n\tconstructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {\n\t\tsuper({\n\t\t\tname: errorName,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a11] = true;\n\t\tthis.modelId = modelId;\n\t\tthis.modelType = modelType;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker11);\n\t}\n};\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12;\nvar _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name11,\n\t\t\tmessage: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n\t\t});\n\t\tthis[_a12] = true;\n\t\tthis.provider = options.provider;\n\t\tthis.modelId = options.modelId;\n\t\tthis.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n\t\tthis.values = options.values;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker12);\n\t}\n};\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13;\nvar _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n\tconstructor({ value, cause }) {\n\t\tsuper({\n\t\t\tname: name12,\n\t\t\tmessage: `Type validation failed: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage$1(cause)}`,\n\t\t\tcause\n\t\t});\n\t\tthis[_a13] = true;\n\t\tthis.value = value;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker13);\n\t}\n\t/**\n\t* Wraps an error into a TypeValidationError.\n\t* If the cause is already a TypeValidationError with the same value, it returns the cause.\n\t* Otherwise, it creates a new TypeValidationError.\n\t*\n\t* @param {Object} params - The parameters for wrapping the error.\n\t* @param {unknown} params.value - The value that failed validation.\n\t* @param {unknown} params.cause - The original error or cause of the validation failure.\n\t* @returns {TypeValidationError} A TypeValidationError instance.\n\t*/\n\tstatic wrap({ value, cause }) {\n\t\treturn _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({\n\t\t\tvalue,\n\t\t\tcause\n\t\t});\n\t}\n};\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14;\nvar _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n\tconstructor({ functionality, message = `'${functionality}' functionality not supported.` }) {\n\t\tsuper({\n\t\t\tname: name13,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a14] = true;\n\t\tthis.functionality = functionality;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker14);\n\t}\n};\nfunction isJSONValue(value) {\n\tif (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") return true;\n\tif (Array.isArray(value)) return value.every(isJSONValue);\n\tif (typeof value === \"object\") return Object.entries(value).every(([key, val]) => typeof key === \"string\" && isJSONValue(val));\n\treturn false;\n}\nfunction isJSONArray(value) {\n\treturn Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n\treturn value != null && typeof value === \"object\" && Object.entries(value).every(([key, val]) => typeof key === \"string\" && isJSONValue(val));\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/index.js\nvar ParseError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n\t}\n};\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nfunction noop(_arg) {}\nfunction createParser(callbacks) {\n\tif (typeof callbacks == \"function\") throw new TypeError(\"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\");\n\tconst { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];\n\tlet isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType;\n\tfunction feed(chunk) {\n\t\tif (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n\t\t\tconst trailing2 = processLines(chunk);\n\t\t\ttrailing2 !== \"\" && pendingFragments.push(trailing2);\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n\t\t\tpendingFragments.push(chunk);\n\t\t\treturn;\n\t\t}\n\t\tpendingFragments.push(chunk);\n\t\tconst input = pendingFragments.join(\"\");\n\t\tpendingFragments.length = 0;\n\t\tconst trailing = processLines(input);\n\t\ttrailing !== \"\" && pendingFragments.push(trailing);\n\t}\n\tfunction processLines(chunk) {\n\t\tlet searchIndex = 0;\n\t\tif (chunk.indexOf(\"\\r\") === -1) {\n\t\t\tlet lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\tfor (; lfIndex !== -1;) {\n\t\t\t\tif (searchIndex === lfIndex) {\n\t\t\t\t\tdataLines > 0 && onEvent({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tevent: eventType,\n\t\t\t\t\t\tdata\n\t\t\t\t\t}), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst firstCharCode = chunk.charCodeAt(searchIndex);\n\t\t\t\tif (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n\t\t\t\t\tconst valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n\t\t\t\t\tif (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n\t\t\t\t\t\tonEvent({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tevent: eventType,\n\t\t\t\t\t\t\tdata: value\n\t\t\t\t\t\t}), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tdata = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n\t\t\t\t} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n\t\t\t\tsearchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\t}\n\t\t\treturn chunk.slice(searchIndex);\n\t\t}\n\t\tfor (; searchIndex < chunk.length;) {\n\t\t\tconst crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\tlet lineEnd = -1;\n\t\t\tif (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break;\n\t\t\tparseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n\t\t}\n\t\treturn chunk.slice(searchIndex);\n\t}\n\tfunction parseLine(chunk, start, end) {\n\t\tif (start === end) {\n\t\t\tdispatchEvent();\n\t\t\treturn;\n\t\t}\n\t\tconst firstCharCode = chunk.charCodeAt(start);\n\t\tif (isDataPrefix(chunk, start, firstCharCode)) {\n\t\t\tconst valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n\t\t\tdata = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n\t\t\treturn;\n\t\t}\n\t\tif (isEventPrefix(chunk, start, firstCharCode)) {\n\t\t\teventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n\t\t\treturn;\n\t\t}\n\t\tif (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n\t\t\tconst value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n\t\t\tid = value2.includes(\"\\0\") ? void 0 : value2;\n\t\t\treturn;\n\t\t}\n\t\tif (firstCharCode === 58) {\n\t\t\tif (onComment) {\n\t\t\t\tconst line2 = chunk.slice(start, end);\n\t\t\t\tonComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n\t\tif (fieldSeparatorIndex === -1) {\n\t\t\tprocessField(line, \"\", line);\n\t\t\treturn;\n\t\t}\n\t\tconst field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;\n\t\tprocessField(field, line.slice(fieldSeparatorIndex + offset), line);\n\t}\n\tfunction processField(field, value, line) {\n\t\tswitch (field) {\n\t\t\tcase \"event\":\n\t\t\t\teventType = value || void 0;\n\t\t\t\tbreak;\n\t\t\tcase \"data\":\n\t\t\t\tdata = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n\t\t\t\tbreak;\n\t\t\tcase \"id\":\n\t\t\t\tid = value.includes(\"\\0\") ? void 0 : value;\n\t\t\t\tbreak;\n\t\t\tcase \"retry\":\n\t\t\t\t/^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n\t\t\t\t\ttype: \"invalid-retry\",\n\t\t\t\t\tvalue,\n\t\t\t\t\tline\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tonError(new ParseError(`Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`, {\n\t\t\t\t\ttype: \"unknown-field\",\n\t\t\t\t\tfield,\n\t\t\t\t\tvalue,\n\t\t\t\t\tline\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfunction dispatchEvent() {\n\t\tdataLines > 0 && onEvent({\n\t\t\tid,\n\t\t\tevent: eventType,\n\t\t\tdata\n\t\t}), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n\t}\n\tfunction reset(options = {}) {\n\t\tif (options.consume && pendingFragments.length > 0) {\n\t\t\tconst incompleteLine = pendingFragments.join(\"\");\n\t\t\tparseLine(incompleteLine, 0, incompleteLine.length);\n\t\t}\n\t\tisFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0;\n\t}\n\treturn {\n\t\tfeed,\n\t\treset\n\t};\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n\treturn firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n\treturn firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/stream.js\nvar EventSourceParserStream = class extends TransformStream {\n\tconstructor({ onError, onRetry, onComment } = {}) {\n\t\tlet parser;\n\t\tsuper({\n\t\t\tstart(controller) {\n\t\t\t\tparser = createParser({\n\t\t\t\t\tonEvent: (event) => {\n\t\t\t\t\t\tcontroller.enqueue(event);\n\t\t\t\t\t},\n\t\t\t\t\tonError(error) {\n\t\t\t\t\t\tonError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n\t\t\t\t\t},\n\t\t\t\t\tonRetry,\n\t\t\t\t\tonComment\n\t\t\t\t});\n\t\t\t},\n\t\t\ttransform(chunk) {\n\t\t\t\tparser.feed(chunk);\n\t\t\t}\n\t\t});\n\t}\n};\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/3.0.30/e9b4211ff39fc7a3e20822c4d7a956f48efe6dc14a1458a8044c00988438859a/node_modules/@ai-sdk/provider-utils/dist/index.mjs\nfunction combineHeaders(...headers) {\n\treturn headers.reduce((combinedHeaders, currentHeaders) => ({\n\t\t...combinedHeaders,\n\t\t...currentHeaders != null ? currentHeaders : {}\n\t}), {});\n}\nfunction convertAsyncIteratorToReadableStream(iterator) {\n\tlet cancelled = false;\n\treturn new ReadableStream({\n\t\t/**\n\t\t* Called when the consumer wants to pull more data from the stream.\n\t\t*\n\t\t* @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n\t\t* @returns {Promise<void>}\n\t\t*/\n\t\tasync pull(controller) {\n\t\t\tif (cancelled) return;\n\t\t\ttry {\n\t\t\t\tconst { value, done } = await iterator.next();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t},\n\t\t/**\n\t\t* Called when the consumer cancels the stream.\n\t\t*/\n\t\tasync cancel(reason) {\n\t\t\tcancelled = true;\n\t\t\tif (iterator.return) try {\n\t\t\t\tawait iterator.return(reason);\n\t\t\t} catch (e) {}\n\t\t}\n\t});\n}\nasync function delay(delayInMs, options) {\n\tif (delayInMs == null) return Promise.resolve();\n\tconst signal = options == null ? void 0 : options.abortSignal;\n\treturn new Promise((resolve2, reject) => {\n\t\tif (signal == null ? void 0 : signal.aborted) {\n\t\t\treject(createAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve2();\n\t\t}, delayInMs);\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timeoutId);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(createAbortError());\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort);\n\t});\n}\nfunction createAbortError() {\n\treturn new DOMException(\"Delay was aborted\", \"AbortError\");\n}\nvar DelayedPromise = class {\n\tconstructor() {\n\t\tthis.status = { type: \"pending\" };\n\t\tthis._resolve = void 0;\n\t\tthis._reject = void 0;\n\t}\n\tget promise() {\n\t\tif (this._promise) return this._promise;\n\t\tthis._promise = new Promise((resolve2, reject) => {\n\t\t\tif (this.status.type === \"resolved\") resolve2(this.status.value);\n\t\t\telse if (this.status.type === \"rejected\") reject(this.status.error);\n\t\t\tthis._resolve = resolve2;\n\t\t\tthis._reject = reject;\n\t\t});\n\t\treturn this._promise;\n\t}\n\tresolve(value) {\n\t\tvar _a2;\n\t\tthis.status = {\n\t\t\ttype: \"resolved\",\n\t\t\tvalue\n\t\t};\n\t\tif (this._promise) (_a2 = this._resolve) == null || _a2.call(this, value);\n\t}\n\treject(error) {\n\t\tvar _a2;\n\t\tthis.status = {\n\t\t\ttype: \"rejected\",\n\t\t\terror\n\t\t};\n\t\tif (this._promise) (_a2 = this._reject) == null || _a2.call(this, error);\n\t}\n\tisResolved() {\n\t\treturn this.status.type === \"resolved\";\n\t}\n\tisRejected() {\n\t\treturn this.status.type === \"rejected\";\n\t}\n\tisPending() {\n\t\treturn this.status.type === \"pending\";\n\t}\n};\nfunction extractResponseHeaders(response) {\n\treturn Object.fromEntries([...response.headers]);\n}\nvar name = \"AI_DownloadError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a;\nvar _b;\nvar DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {\n\tconstructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {\n\t\tsuper({\n\t\t\tname,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a] = true;\n\t\tthis.url = url;\n\t\tthis.statusCode = statusCode;\n\t\tthis.statusText = statusText;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker);\n\t}\n};\nasync function cancelResponseBody(response) {\n\tvar _a2;\n\ttry {\n\t\tawait ((_a2 = response.body) == null ? void 0 : _a2.cancel());\n\t} catch (e) {}\n}\nfunction isBrowserRuntime(globalThisAny = globalThis) {\n\treturn globalThisAny.window != null;\n}\nfunction validateDownloadUrl(url) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch (e) {\n\t\tthrow new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `Invalid URL: ${url}`\n\t\t});\n\t}\n\tif (parsed.protocol === \"data:\") return;\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL scheme must be http, https, or data, got ${parsed.protocol}`\n\t});\n\tconst hostname = parsed.hostname.toLowerCase().replace(/\\.+$/, \"\");\n\tif (!hostname) throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL must have a hostname`\n\t});\n\tif (hostname === \"localhost\" || hostname.endsWith(\".local\") || hostname.endsWith(\".localhost\")) throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL with hostname ${hostname} is not allowed`\n\t});\n\tif (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n\t\tif (isPrivateIPv6(hostname.slice(1, -1))) throw new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `URL with IPv6 address ${hostname} is not allowed`\n\t\t});\n\t\treturn;\n\t}\n\tif (isIPv4(hostname)) {\n\t\tif (isPrivateIPv4(hostname)) throw new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `URL with IP address ${hostname} is not allowed`\n\t\t});\n\t\treturn;\n\t}\n}\nfunction isIPv4(hostname) {\n\tconst parts = hostname.split(\".\");\n\tif (parts.length !== 4) return false;\n\treturn parts.every((part) => {\n\t\tconst num = Number(part);\n\t\treturn Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;\n\t});\n}\nfunction isPrivateIPv4(ip) {\n\tconst [a, b, c] = ip.split(\".\").map(Number);\n\tif (a === 0) return true;\n\tif (a === 10) return true;\n\tif (a === 100 && b >= 64 && b <= 127) return true;\n\tif (a === 127) return true;\n\tif (a === 169 && b === 254) return true;\n\tif (a === 172 && b >= 16 && b <= 31) return true;\n\tif (a === 192 && b === 0 && c === 0) return true;\n\tif (a === 192 && b === 168) return true;\n\tif (a === 198 && (b === 18 || b === 19)) return true;\n\tif (a >= 240) return true;\n\treturn false;\n}\nfunction parseIPv6(ip) {\n\tlet address = ip.toLowerCase();\n\tconst zoneIndex = address.indexOf(\"%\");\n\tif (zoneIndex !== -1) address = address.slice(0, zoneIndex);\n\tconst halves = address.split(\"::\");\n\tif (halves.length > 2) return null;\n\tconst toGroups = (segment) => {\n\t\tif (segment === \"\") return [];\n\t\tconst groups = [];\n\t\tconst parts = segment.split(\":\");\n\t\tfor (let i = 0; i < parts.length; i++) {\n\t\t\tconst part = parts[i];\n\t\t\tif (part.includes(\".\")) {\n\t\t\t\tif (i !== parts.length - 1 || !isIPv4(part)) return null;\n\t\t\t\tconst [a, b, c, d] = part.split(\".\").map(Number);\n\t\t\t\tgroups.push(a << 8 | b, c << 8 | d);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n\t\t\tgroups.push(parseInt(part, 16));\n\t\t}\n\t\treturn groups;\n\t};\n\tconst head = toGroups(halves[0]);\n\tif (head === null) return null;\n\tif (halves.length === 2) {\n\t\tconst tail = toGroups(halves[1]);\n\t\tif (tail === null) return null;\n\t\tconst fill = 8 - head.length - tail.length;\n\t\tif (fill < 0) return null;\n\t\treturn [\n\t\t\t...head,\n\t\t\t...new Array(fill).fill(0),\n\t\t\t...tail\n\t\t];\n\t}\n\treturn head.length === 8 ? head : null;\n}\nfunction isPrivateIPv6(ip) {\n\tconst groups = parseIPv6(ip);\n\tif (groups === null) return true;\n\tconst topZero = (count) => groups.slice(0, count).every((group) => group === 0);\n\tif (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;\n\tif ((groups[0] & 65024) === 64512) return true;\n\tif ((groups[0] & 65472) === 65152) return true;\n\tif ((groups[0] & 65472) === 65216) return true;\n\tif ((groups[0] & 65280) === 65280) return true;\n\tif (topZero(6) || topZero(5) && groups[5] === 65535 || topZero(4) && groups[4] === 65535 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 1) return isPrivateIPv4(`${groups[6] >> 8 & 255}.${groups[6] & 255}.${groups[7] >> 8 & 255}.${groups[7] & 255}`);\n\treturn false;\n}\nvar MAX_DOWNLOAD_REDIRECTS = 10;\nasync function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS }) {\n\tconst baseInit = { signal: abortSignal };\n\tif (headers !== void 0) baseInit.headers = headers;\n\tlet currentUrl = url;\n\tfor (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {\n\t\tvalidateDownloadUrl(currentUrl);\n\t\tconst response = await fetch(currentUrl, {\n\t\t\t...baseInit,\n\t\t\tredirect: \"manual\"\n\t\t});\n\t\tif (response.type === \"opaqueredirect\") {\n\t\t\tif (!isBrowserRuntime()) throw new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Redirect from ${currentUrl} could not be validated and was blocked`\n\t\t\t});\n\t\t\treturn await fetch(currentUrl, {\n\t\t\t\t...baseInit,\n\t\t\t\tredirect: \"follow\"\n\t\t\t});\n\t\t}\n\t\tconst location = response.headers.get(\"location\");\n\t\tif (response.status >= 300 && response.status < 400 && location) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tcurrentUrl = new URL(location, currentUrl).toString();\n\t\t\tcontinue;\n\t\t}\n\t\treturn response;\n\t}\n\tthrow new DownloadError({\n\t\turl,\n\t\tmessage: `Too many redirects (max ${maxRedirects})`\n\t});\n}\nvar DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\nasync function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength != null) {\n\t\tconst length = parseInt(contentLength, 10);\n\t\tif (!isNaN(length) && length > maxBytes) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`\n\t\t\t});\n\t\t}\n\t}\n\tconst body = response.body;\n\tif (body == null) return /* @__PURE__ */ new Uint8Array(0);\n\tconst reader = body.getReader();\n\tconst chunks = [];\n\tlet totalBytes = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\ttotalBytes += value.length;\n\t\t\tif (totalBytes > maxBytes) throw new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`\n\t\t\t});\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t}\n\tconst result = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tresult.set(chunk, offset);\n\t\toffset += chunk.length;\n\t}\n\treturn result;\n}\nvar createIdGenerator = ({ prefix, size = 16, alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\", separator = \"-\" } = {}) => {\n\tconst generator = () => {\n\t\tconst alphabetLength = alphabet.length;\n\t\tconst chars = new Array(size);\n\t\tfor (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0];\n\t\treturn chars.join(\"\");\n\t};\n\tif (prefix == null) return generator;\n\tif (alphabet.includes(separator)) throw new InvalidArgumentError({\n\t\targument: \"separator\",\n\t\tmessage: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n\t});\n\treturn () => `${prefix}${separator}${generator()}`;\n};\nvar generateId = createIdGenerator();\nfunction getErrorMessage(error) {\n\tif (error == null) return \"unknown error\";\n\tif (typeof error === \"string\") return error;\n\tif (error instanceof Error) return error.message;\n\treturn JSON.stringify(error);\n}\nfunction isAbortError(error) {\n\treturn (error instanceof Error || error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || error.name === \"TimeoutError\");\n}\nvar FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nfunction handleFetchError({ error, url, requestBodyValues }) {\n\tif (isAbortError(error)) return error;\n\tif (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n\t\tconst cause = error.cause;\n\t\tif (cause != null) return new APICallError({\n\t\t\tmessage: `Cannot connect to API: ${cause.message}`,\n\t\t\tcause,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tisRetryable: true\n\t\t});\n\t}\n\treturn error;\n}\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n\tvar _a2, _b2, _c;\n\tif (globalThisAny.window) return `runtime/browser`;\n\tif ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n\tif ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n\tif (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;\n\treturn \"runtime/unknown\";\n}\nfunction normalizeHeaders(headers) {\n\tif (headers == null) return {};\n\tconst normalized = {};\n\tif (headers instanceof Headers) headers.forEach((value, key) => {\n\t\tnormalized[key.toLowerCase()] = value;\n\t});\n\telse {\n\t\tif (!Array.isArray(headers)) headers = Object.entries(headers);\n\t\tfor (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;\n\t}\n\treturn normalized;\n}\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n\tconst normalizedHeaders = new Headers(normalizeHeaders(headers));\n\tconst currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n\tnormalizedHeaders.set(\"user-agent\", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \"));\n\treturn Object.fromEntries(normalizedHeaders.entries());\n}\nvar VERSION = \"3.0.30\";\nvar getOriginalFetch = () => globalThis.fetch;\nvar getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch() }) => {\n\ttry {\n\t\tconst response = await fetch2(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues: {}\n\t\t});\n\t}\n};\nfunction isUrlSupported({ mediaType, url, supportedUrls }) {\n\turl = url.toLowerCase();\n\tmediaType = mediaType.toLowerCase();\n\treturn Object.entries(supportedUrls).map(([key, value]) => {\n\t\tconst mediaType2 = key.toLowerCase();\n\t\treturn mediaType2 === \"*\" || mediaType2 === \"*/*\" ? {\n\t\t\tmediaTypePrefix: \"\",\n\t\t\tregexes: value\n\t\t} : {\n\t\t\tmediaTypePrefix: mediaType2.replace(/\\*/, \"\"),\n\t\t\tregexes: value\n\t\t};\n\t}).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));\n}\nfunction loadOptionalSetting({ settingValue, environmentVariableName }) {\n\tif (typeof settingValue === \"string\") return settingValue;\n\tif (settingValue != null || typeof process === \"undefined\") return;\n\tsettingValue = process.env[environmentVariableName];\n\tif (settingValue == null || typeof settingValue !== \"string\") return;\n\treturn settingValue;\n}\nvar suspectProtoRx = /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nvar suspectConstructorRx = /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\nfunction _parse(text) {\n\tconst obj = JSON.parse(text);\n\tif (obj === null || typeof obj !== \"object\") return obj;\n\tif (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) return obj;\n\treturn filter(obj);\n}\nfunction filter(obj) {\n\tlet next = [obj];\n\twhile (next.length) {\n\t\tconst nodes = next;\n\t\tnext = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) throw new SyntaxError(\"Object contains forbidden prototype property\");\n\t\t\tif (Object.prototype.hasOwnProperty.call(node, \"constructor\") && node.constructor !== null && typeof node.constructor === \"object\" && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) throw new SyntaxError(\"Object contains forbidden prototype property\");\n\t\t\tfor (const key in node) {\n\t\t\t\tconst value = node[key];\n\t\t\t\tif (value && typeof value === \"object\") next.push(value);\n\t\t\t}\n\t\t}\n\t}\n\treturn obj;\n}\nfunction secureJsonParse(text) {\n\tconst { stackTraceLimit } = Error;\n\ttry {\n\t\tError.stackTraceLimit = 0;\n\t} catch (e) {\n\t\treturn _parse(text);\n\t}\n\ttry {\n\t\treturn _parse(text);\n\t} finally {\n\t\tError.stackTraceLimit = stackTraceLimit;\n\t}\n}\nvar validatorSymbol = /* @__PURE__ */ Symbol.for(\"vercel.ai.validator\");\nfunction validator(validate) {\n\treturn {\n\t\t[validatorSymbol]: true,\n\t\tvalidate\n\t};\n}\nfunction isValidator(value) {\n\treturn typeof value === \"object\" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && \"validate\" in value;\n}\nfunction lazyValidator(createValidator) {\n\tlet validator2;\n\treturn () => {\n\t\tif (validator2 == null) validator2 = createValidator();\n\t\treturn validator2;\n\t};\n}\nfunction asValidator(value) {\n\treturn isValidator(value) ? value : \"~standard\" in value ? standardSchemaValidator(value) : value();\n}\nfunction standardSchemaValidator(standardSchema) {\n\treturn validator(async (value) => {\n\t\tconst result = await standardSchema[\"~standard\"].validate(value);\n\t\treturn result.issues == null ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.value\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: new TypeValidationError({\n\t\t\t\tvalue,\n\t\t\t\tcause: result.issues\n\t\t\t})\n\t\t};\n\t});\n}\nasync function validateTypes({ value, schema }) {\n\tconst result = await safeValidateTypes({\n\t\tvalue,\n\t\tschema\n\t});\n\tif (!result.success) throw TypeValidationError.wrap({\n\t\tvalue,\n\t\tcause: result.error\n\t});\n\treturn result.value;\n}\nasync function safeValidateTypes({ value, schema }) {\n\tconst validator2 = asValidator(schema);\n\ttry {\n\t\tif (validator2.validate == null) return {\n\t\t\tsuccess: true,\n\t\t\tvalue,\n\t\t\trawValue: value\n\t\t};\n\t\tconst result = await validator2.validate(value);\n\t\tif (result.success) return {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.value,\n\t\t\trawValue: value\n\t\t};\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: TypeValidationError.wrap({\n\t\t\t\tvalue,\n\t\t\t\tcause: result.error\n\t\t\t}),\n\t\t\trawValue: value\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: TypeValidationError.wrap({\n\t\t\t\tvalue,\n\t\t\t\tcause: error\n\t\t\t}),\n\t\t\trawValue: value\n\t\t};\n\t}\n}\nasync function parseJSON({ text, schema }) {\n\ttry {\n\t\tconst value = secureJsonParse(text);\n\t\tif (schema == null) return value;\n\t\treturn validateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t} catch (error) {\n\t\tif (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) throw error;\n\t\tthrow new JSONParseError({\n\t\t\ttext,\n\t\t\tcause: error\n\t\t});\n\t}\n}\nasync function safeParseJSON({ text, schema }) {\n\ttry {\n\t\tconst value = secureJsonParse(text);\n\t\tif (schema == null) return {\n\t\t\tsuccess: true,\n\t\t\tvalue,\n\t\t\trawValue: value\n\t\t};\n\t\treturn await safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: JSONParseError.isInstance(error) ? error : new JSONParseError({\n\t\t\t\ttext,\n\t\t\t\tcause: error\n\t\t\t}),\n\t\t\trawValue: void 0\n\t\t};\n\t}\n}\nfunction parseJsonEventStream({ stream, schema }) {\n\treturn stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({ async transform({ data }, controller) {\n\t\tif (data === \"[DONE]\") return;\n\t\tcontroller.enqueue(await safeParseJSON({\n\t\t\ttext: data,\n\t\t\tschema\n\t\t}));\n\t} }));\n}\nvar getOriginalFetch2 = () => globalThis.fetch;\nvar postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi({\n\turl,\n\theaders: {\n\t\t\"Content-Type\": \"application/json\",\n\t\t...headers\n\t},\n\tbody: {\n\t\tcontent: JSON.stringify(body),\n\t\tvalues: body\n\t},\n\tfailedResponseHandler,\n\tsuccessfulResponseHandler,\n\tabortSignal,\n\tfetch: fetch2\n});\nvar postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() }) => {\n\ttry {\n\t\tconst response = await fetch2(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tbody: body.content,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: body.values\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues: body.values\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues: body.values\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues: body.values\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues: body.values\n\t\t});\n\t}\n};\nfunction tool(tool2) {\n\treturn tool2;\n}\nfunction dynamicTool(tool2) {\n\treturn {\n\t\t...tool2,\n\t\ttype: \"dynamic\"\n\t};\n}\nfunction createProviderDefinedToolFactoryWithOutputSchema({ id, name: name2, inputSchema, outputSchema }) {\n\treturn ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({\n\t\ttype: \"provider-defined\",\n\t\tid,\n\t\tname: name2,\n\t\targs,\n\t\tinputSchema,\n\t\toutputSchema,\n\t\texecute,\n\t\ttoModelOutput,\n\t\tonInputStart,\n\t\tonInputDelta,\n\t\tonInputAvailable\n\t});\n}\nasync function resolve(value) {\n\tif (typeof value === \"function\") value = value();\n\treturn Promise.resolve(value);\n}\nvar textDecoder = new TextDecoder();\nasync function readResponseBodyAsText({ response, url }) {\n\treturn textDecoder.decode(await readResponseWithSizeLimit({\n\t\tresponse,\n\t\turl\n\t}));\n}\nvar createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {\n\tconst responseBody = await readResponseBodyAsText({\n\t\tresponse,\n\t\turl\n\t});\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (responseBody.trim() === \"\") return {\n\t\tresponseHeaders,\n\t\tvalue: new APICallError({\n\t\t\tmessage: response.statusText,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tstatusCode: response.status,\n\t\t\tresponseHeaders,\n\t\t\tresponseBody,\n\t\t\tisRetryable: isRetryable == null ? void 0 : isRetryable(response)\n\t\t})\n\t};\n\ttry {\n\t\tconst parsedError = await parseJSON({\n\t\t\ttext: responseBody,\n\t\t\tschema: errorSchema\n\t\t});\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: new APICallError({\n\t\t\t\tmessage: errorToMessage(parsedError),\n\t\t\t\turl,\n\t\t\t\trequestBodyValues,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tresponseHeaders,\n\t\t\t\tresponseBody,\n\t\t\t\tdata: parsedError,\n\t\t\t\tisRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)\n\t\t\t})\n\t\t};\n\t} catch (parseError) {\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: new APICallError({\n\t\t\t\tmessage: response.statusText,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tresponseHeaders,\n\t\t\t\tresponseBody,\n\t\t\t\tisRetryable: isRetryable == null ? void 0 : isRetryable(response)\n\t\t\t})\n\t\t};\n\t}\n};\nvar createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (response.body == null) throw new EmptyResponseBodyError({});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: parseJsonEventStream({\n\t\t\tstream: response.body,\n\t\t\tschema: chunkSchema\n\t\t})\n\t};\n};\nvar createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {\n\tconst responseBody = await readResponseBodyAsText({\n\t\tresponse,\n\t\turl\n\t});\n\tconst parsedResult = await safeParseJSON({\n\t\ttext: responseBody,\n\t\tschema: responseSchema\n\t});\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (!parsedResult.success) throw new APICallError({\n\t\tmessage: \"Invalid JSON response\",\n\t\tcause: parsedResult.error,\n\t\tstatusCode: response.status,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\turl,\n\t\trequestBodyValues\n\t});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: parsedResult.value,\n\t\trawValue: parsedResult.rawValue\n\t};\n};\nvar schemaSymbol = /* @__PURE__ */ Symbol.for(\"vercel.ai.schema\");\nfunction lazySchema(createSchema) {\n\tlet schema;\n\treturn () => {\n\t\tif (schema == null) schema = createSchema();\n\t\treturn schema;\n\t};\n}\nfunction jsonSchema(jsonSchema2, { validate } = {}) {\n\treturn {\n\t\t[schemaSymbol]: true,\n\t\t_type: void 0,\n\t\t[validatorSymbol]: true,\n\t\tget jsonSchema() {\n\t\t\tif (typeof jsonSchema2 === \"function\") jsonSchema2 = jsonSchema2();\n\t\t\treturn jsonSchema2;\n\t\t},\n\t\tvalidate\n\t};\n}\nfunction addAdditionalPropertiesToJsonSchema(jsonSchema2) {\n\tif (jsonSchema2.type === \"object\") {\n\t\tjsonSchema2.additionalProperties = false;\n\t\tconst properties = jsonSchema2.properties;\n\t\tif (properties != null) for (const property in properties) properties[property] = addAdditionalPropertiesToJsonSchema(properties[property]);\n\t}\n\tif (jsonSchema2.type === \"array\" && jsonSchema2.items != null) if (Array.isArray(jsonSchema2.items)) jsonSchema2.items = jsonSchema2.items.map((item) => addAdditionalPropertiesToJsonSchema(item));\n\telse jsonSchema2.items = addAdditionalPropertiesToJsonSchema(jsonSchema2.items);\n\treturn jsonSchema2;\n}\nvar ignoreOverride = /* @__PURE__ */ Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nvar defaultOptions = {\n\tname: void 0,\n\t$refStrategy: \"root\",\n\tbasePath: [\"#\"],\n\teffectStrategy: \"input\",\n\tpipeStrategy: \"all\",\n\tdateStrategy: \"format:date-time\",\n\tmapStrategy: \"entries\",\n\tremoveAdditionalStrategy: \"passthrough\",\n\tallowedAdditionalProperties: true,\n\trejectedAdditionalProperties: false,\n\tdefinitionPath: \"definitions\",\n\tstrictUnions: false,\n\tdefinitions: {},\n\terrorMessages: false,\n\tpatternStrategy: \"escape\",\n\tapplyRegexFlags: false,\n\temailStrategy: \"format:email\",\n\tbase64Strategy: \"contentEncoding:base64\",\n\tnameStrategy: \"ref\"\n};\nvar getDefaultOptions = (options) => typeof options === \"string\" ? {\n\t...defaultOptions,\n\tname: options\n} : {\n\t...defaultOptions,\n\t...options\n};\nfunction parseAnyDef() {\n\treturn {};\n}\nfunction parseArrayDef(def, refs) {\n\tvar _a2, _b2, _c;\n\tconst res = { type: \"array\" };\n\tif (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t});\n\tif (def.minLength) res.minItems = def.minLength.value;\n\tif (def.maxLength) res.maxItems = def.maxLength.value;\n\tif (def.exactLength) {\n\t\tres.minItems = def.exactLength.value;\n\t\tres.maxItems = def.exactLength.value;\n\t}\n\treturn res;\n}\nfunction parseBigintDef(def) {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"int64\"\n\t};\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tif (check.inclusive) res.minimum = check.value;\n\t\t\telse res.exclusiveMinimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (check.inclusive) res.maximum = check.value;\n\t\t\telse res.exclusiveMaximum = check.value;\n\t\t\tbreak;\n\t\tcase \"multipleOf\":\n\t\t\tres.multipleOf = check.value;\n\t\t\tbreak;\n\t}\n\treturn res;\n}\nfunction parseBooleanDef() {\n\treturn { type: \"boolean\" };\n}\nfunction parseBrandedDef(_def, refs) {\n\treturn parseDef(_def.type._def, refs);\n}\nvar parseCatchDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n\tconst strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;\n\tif (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) };\n\tswitch (strategy) {\n\t\tcase \"string\":\n\t\tcase \"format:date-time\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date-time\"\n\t\t};\n\t\tcase \"format:date\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date\"\n\t\t};\n\t\tcase \"integer\": return integerDateParser(def);\n\t}\n}\nvar integerDateParser = (def) => {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"unix-time\"\n\t};\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tres.minimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tres.maximum = check.value;\n\t\t\tbreak;\n\t}\n\treturn res;\n};\nfunction parseDefaultDef(_def, refs) {\n\treturn {\n\t\t...parseDef(_def.innerType._def, refs),\n\t\tdefault: _def.defaultValue()\n\t};\n}\nfunction parseEffectsDef(_def, refs) {\n\treturn refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef();\n}\nfunction parseEnumDef(def) {\n\treturn {\n\t\ttype: \"string\",\n\t\tenum: Array.from(def.values)\n\t};\n}\nvar isJsonSchema7AllOfType = (type) => {\n\tif (\"type\" in type && type.type === \"string\") return false;\n\treturn \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n\tconst allOf = [parseDef(def.left._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t}), parseDef(def.right._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"1\"\n\t\t]\n\t})].filter((x) => !!x);\n\tconst mergedAllOf = [];\n\tallOf.forEach((schema) => {\n\t\tif (isJsonSchema7AllOfType(schema)) mergedAllOf.push(...schema.allOf);\n\t\telse {\n\t\t\tlet nestedSchema = schema;\n\t\t\tif (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n\t\t\t\tconst { additionalProperties, ...rest } = schema;\n\t\t\t\tnestedSchema = rest;\n\t\t\t}\n\t\t\tmergedAllOf.push(nestedSchema);\n\t\t}\n\t});\n\treturn mergedAllOf.length ? { allOf: mergedAllOf } : void 0;\n}\nfunction parseLiteralDef(def) {\n\tconst parsedType = typeof def.value;\n\tif (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") return { type: Array.isArray(def.value) ? \"array\" : \"object\" };\n\treturn {\n\t\ttype: parsedType === \"bigint\" ? \"integer\" : parsedType,\n\t\tconst: def.value\n\t};\n}\nvar emojiRegex = void 0;\nvar zodPatterns = {\n\t/**\n\t* `c` was changed to `[cC]` to replicate /i flag\n\t*/\n\tcuid: /^[cC][^\\s-]{8,}$/,\n\tcuid2: /^[0-9a-z]+$/,\n\tulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n\t/**\n\t* `a-z` was added to replicate /i flag\n\t*/\n\temail: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n\t/**\n\t* Constructed a valid Unicode RegExp\n\t*\n\t* Lazily instantiate since this type of regex isn't supported\n\t* in all envs (e.g. React Native).\n\t*\n\t* See:\n\t* https://github.com/colinhacks/zod/issues/2433\n\t* Fix in Zod:\n\t* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n\t*/\n\temoji: () => {\n\t\tif (emojiRegex === void 0) emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n\t\treturn emojiRegex;\n\t},\n\t/**\n\t* Unused\n\t*/\n\tuuid: /^[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}$/,\n\t/**\n\t* Unused\n\t*/\n\tipv4: /^(?:(?: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])$/,\n\tipv4Cidr: /^(?:(?: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])$/,\n\t/**\n\t* Unused\n\t*/\n\tipv6: /^(([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})))$/,\n\tipv6Cidr: /^(([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])$/,\n\tbase64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n\tbase64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n\tnanoid: /^[a-zA-Z0-9_-]{21}$/,\n\tjwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n\tconst res = { type: \"string\" };\n\tif (def.checks) for (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tres.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tres.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"email\":\n\t\t\tswitch (refs.emailStrategy) {\n\t\t\t\tcase \"format:email\":\n\t\t\t\t\taddFormat(res, \"email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"format:idn-email\":\n\t\t\t\t\taddFormat(res, \"idn-email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\":\n\t\t\t\t\taddPattern(res, zodPatterns.email, check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"url\":\n\t\t\taddFormat(res, \"uri\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"uuid\":\n\t\t\taddFormat(res, \"uuid\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"regex\":\n\t\t\taddPattern(res, check.regex, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid\":\n\t\t\taddPattern(res, zodPatterns.cuid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid2\":\n\t\t\taddPattern(res, zodPatterns.cuid2, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"startsWith\":\n\t\t\taddPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"endsWith\":\n\t\t\taddPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"datetime\":\n\t\t\taddFormat(res, \"date-time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"date\":\n\t\t\taddFormat(res, \"date\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"time\":\n\t\t\taddFormat(res, \"time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"duration\":\n\t\t\taddFormat(res, \"duration\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"length\":\n\t\t\tres.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n\t\t\tres.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"includes\":\n\t\t\taddPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ip\":\n\t\t\tif (check.version !== \"v6\") addFormat(res, \"ipv4\", check.message, refs);\n\t\t\tif (check.version !== \"v4\") addFormat(res, \"ipv6\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64url\":\n\t\t\taddPattern(res, zodPatterns.base64url, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"jwt\":\n\t\t\taddPattern(res, zodPatterns.jwt, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cidr\":\n\t\t\tif (check.version !== \"v6\") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n\t\t\tif (check.version !== \"v4\") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"emoji\":\n\t\t\taddPattern(res, zodPatterns.emoji(), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ulid\":\n\t\t\taddPattern(res, zodPatterns.ulid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64\":\n\t\t\tswitch (refs.base64Strategy) {\n\t\t\t\tcase \"format:binary\":\n\t\t\t\t\taddFormat(res, \"binary\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"contentEncoding:base64\":\n\t\t\t\t\tres.contentEncoding = \"base64\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\":\n\t\t\t\t\taddPattern(res, zodPatterns.base64, check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"nanoid\": addPattern(res, zodPatterns.nanoid, check.message, refs);\n\t\tcase \"toLowerCase\":\n\t\tcase \"toUpperCase\":\n\t\tcase \"trim\": break;\n\t\tdefault:\n\t}\n\treturn res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n\treturn refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nvar ALPHA_NUMERIC = /* @__PURE__ */ new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n\tlet result = \"\";\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (!ALPHA_NUMERIC.has(source[i])) result += \"\\\\\";\n\t\tresult += source[i];\n\t}\n\treturn result;\n}\nfunction addFormat(schema, value, message, refs) {\n\tvar _a2;\n\tif (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {\n\t\tif (!schema.anyOf) schema.anyOf = [];\n\t\tif (schema.format) {\n\t\t\tschema.anyOf.push({ format: schema.format });\n\t\t\tdelete schema.format;\n\t\t}\n\t\tschema.anyOf.push({\n\t\t\tformat: value,\n\t\t\t...message && refs.errorMessages && { errorMessage: { format: message } }\n\t\t});\n\t} else schema.format = value;\n}\nfunction addPattern(schema, regex, message, refs) {\n\tvar _a2;\n\tif (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {\n\t\tif (!schema.allOf) schema.allOf = [];\n\t\tif (schema.pattern) {\n\t\t\tschema.allOf.push({ pattern: schema.pattern });\n\t\t\tdelete schema.pattern;\n\t\t}\n\t\tschema.allOf.push({\n\t\t\tpattern: stringifyRegExpWithFlags(regex, refs),\n\t\t\t...message && refs.errorMessages && { errorMessage: { pattern: message } }\n\t\t});\n\t} else schema.pattern = stringifyRegExpWithFlags(regex, refs);\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n\tvar _a2;\n\tif (!refs.applyRegexFlags || !regex.flags) return regex.source;\n\tconst flags = {\n\t\ti: regex.flags.includes(\"i\"),\n\t\tm: regex.flags.includes(\"m\"),\n\t\ts: regex.flags.includes(\"s\")\n\t};\n\tconst source = flags.i ? regex.source.toLowerCase() : regex.source;\n\tlet pattern = \"\";\n\tlet isEscaped = false;\n\tlet inCharGroup = false;\n\tlet inCharRange = false;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (isEscaped) {\n\t\t\tpattern += source[i];\n\t\t\tisEscaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (flags.i) {\n\t\t\tif (inCharGroup) {\n\t\t\t\tif (source[i].match(/[a-z]/)) {\n\t\t\t\t\tif (inCharRange) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tpattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n\t\t\t\t\t\tinCharRange = false;\n\t\t\t\t\t} else if (source[i + 1] === \"-\" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tinCharRange = true;\n\t\t\t\t\t} else pattern += `${source[i]}${source[i].toUpperCase()}`;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (source[i].match(/[a-z]/)) {\n\t\t\t\tpattern += `[${source[i]}${source[i].toUpperCase()}]`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.m) {\n\t\t\tif (source[i] === \"^\") {\n\t\t\t\tpattern += `(^|(?<=[\\r\n]))`;\n\t\t\t\tcontinue;\n\t\t\t} else if (source[i] === \"$\") {\n\t\t\t\tpattern += `($|(?=[\\r\n]))`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.s && source[i] === \".\") {\n\t\t\tpattern += inCharGroup ? `${source[i]}\\r\n` : `[${source[i]}\\r\n]`;\n\t\t\tcontinue;\n\t\t}\n\t\tpattern += source[i];\n\t\tif (source[i] === \"\\\\\") isEscaped = true;\n\t\telse if (inCharGroup && source[i] === \"]\") inCharGroup = false;\n\t\telse if (!inCharGroup && source[i] === \"[\") inCharGroup = true;\n\t}\n\ttry {\n\t\tnew RegExp(pattern);\n\t} catch (e) {\n\t\tconsole.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n\t\treturn regex.source;\n\t}\n\treturn pattern;\n}\nfunction parseRecordDef(def, refs) {\n\tvar _a2, _b2, _c, _d, _e, _f;\n\tconst schema = {\n\t\ttype: \"object\",\n\t\tadditionalProperties: (_a2 = parseDef(def.valueType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t\t})) != null ? _a2 : refs.allowedAdditionalProperties\n\t};\n\tif (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {\n\t\tconst { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) return {\n\t\t...schema,\n\t\tpropertyNames: { enum: def.keyType._def.values }\n\t};\n\telse 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)) {\n\t\tconst { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t}\n\treturn schema;\n}\nfunction parseMapDef(def, refs) {\n\tif (refs.mapStrategy === \"record\") return parseRecordDef(def, refs);\n\treturn {\n\t\ttype: \"array\",\n\t\tmaxItems: 125,\n\t\titems: {\n\t\t\ttype: \"array\",\n\t\t\titems: [parseDef(def.keyType._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.currentPath,\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"0\"\n\t\t\t\t]\n\t\t\t}) || parseAnyDef(), parseDef(def.valueType._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.currentPath,\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"1\"\n\t\t\t\t]\n\t\t\t}) || parseAnyDef()],\n\t\t\tminItems: 2,\n\t\t\tmaxItems: 2\n\t\t}\n\t};\n}\nfunction parseNativeEnumDef(def) {\n\tconst object = def.values;\n\tconst actualValues = Object.keys(def.values).filter((key) => {\n\t\treturn typeof object[object[key]] !== \"number\";\n\t}).map((key) => object[key]);\n\tconst parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n\treturn {\n\t\ttype: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n\t\tenum: actualValues\n\t};\n}\nfunction parseNeverDef() {\n\treturn { not: parseAnyDef() };\n}\nfunction parseNullDef() {\n\treturn { type: \"null\" };\n}\nvar primitiveMappings = {\n\tZodString: \"string\",\n\tZodNumber: \"number\",\n\tZodBigInt: \"integer\",\n\tZodBoolean: \"boolean\",\n\tZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n\tconst options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\tif (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {\n\t\tconst types = options.reduce((types2, x) => {\n\t\t\tconst type = primitiveMappings[x._def.typeName];\n\t\t\treturn type && !types2.includes(type) ? [...types2, type] : types2;\n\t\t}, []);\n\t\treturn { type: types.length > 1 ? types : types[0] };\n\t} else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n\t\tconst types = options.reduce((acc, x) => {\n\t\t\tconst type = typeof x._def.value;\n\t\t\tswitch (type) {\n\t\t\t\tcase \"string\":\n\t\t\t\tcase \"number\":\n\t\t\t\tcase \"boolean\": return [...acc, type];\n\t\t\t\tcase \"bigint\": return [...acc, \"integer\"];\n\t\t\t\tcase \"object\": if (x._def.value === null) return [...acc, \"null\"];\n\t\t\t\tdefault: return acc;\n\t\t\t}\n\t\t}, []);\n\t\tif (types.length === options.length) {\n\t\t\tconst uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n\t\t\treturn {\n\t\t\t\ttype: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n\t\t\t\tenum: options.reduce((acc, x) => {\n\t\t\t\t\treturn acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n\t\t\t\t}, [])\n\t\t\t};\n\t\t}\n\t} else if (options.every((x) => x._def.typeName === \"ZodEnum\")) return {\n\t\ttype: \"string\",\n\t\tenum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], [])\n\t};\n\treturn asAnyOf(def, refs);\n}\nvar asAnyOf = (def, refs) => {\n\tconst anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t`${i}`\n\t\t]\n\t})).filter((x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0));\n\treturn anyOf.length ? { anyOf } : void 0;\n};\nfunction parseNullableDef(def, refs) {\n\tif ([\n\t\t\"ZodString\",\n\t\t\"ZodNumber\",\n\t\t\"ZodBigInt\",\n\t\t\"ZodBoolean\",\n\t\t\"ZodNull\"\n\t].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings[def.innerType._def.typeName], \"null\"] };\n\tconst base = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\treturn base && { anyOf: [base, { type: \"null\" }] };\n}\nfunction parseNumberDef(def) {\n\tconst res = { type: \"number\" };\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"int\":\n\t\t\tres.type = \"integer\";\n\t\t\tbreak;\n\t\tcase \"min\":\n\t\t\tif (check.inclusive) res.minimum = check.value;\n\t\t\telse res.exclusiveMinimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (check.inclusive) res.maximum = check.value;\n\t\t\telse res.exclusiveMaximum = check.value;\n\t\t\tbreak;\n\t\tcase \"multipleOf\":\n\t\t\tres.multipleOf = check.value;\n\t\t\tbreak;\n\t}\n\treturn res;\n}\nfunction parseObjectDef(def, refs) {\n\tconst result = {\n\t\ttype: \"object\",\n\t\tproperties: {}\n\t};\n\tconst required = [];\n\tconst shape = def.shape();\n\tfor (const propName in shape) {\n\t\tlet propDef = shape[propName];\n\t\tif (propDef === void 0 || propDef._def === void 0) continue;\n\t\tconst propOptional = safeIsOptional(propDef);\n\t\tconst parsedDef = parseDef(propDef._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t],\n\t\t\tpropertyPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t]\n\t\t});\n\t\tif (parsedDef === void 0) continue;\n\t\tresult.properties[propName] = parsedDef;\n\t\tif (!propOptional) required.push(propName);\n\t}\n\tif (required.length) result.required = required;\n\tconst additionalProperties = decideAdditionalProperties(def, refs);\n\tif (additionalProperties !== void 0) result.additionalProperties = additionalProperties;\n\treturn result;\n}\nfunction decideAdditionalProperties(def, refs) {\n\tif (def.catchall._def.typeName !== \"ZodNever\") return parseDef(def.catchall._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t});\n\tswitch (def.unknownKeys) {\n\t\tcase \"passthrough\": return refs.allowedAdditionalProperties;\n\t\tcase \"strict\": return refs.rejectedAdditionalProperties;\n\t\tcase \"strip\": return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n\t}\n}\nfunction safeIsOptional(schema) {\n\ttry {\n\t\treturn schema.isOptional();\n\t} catch (e) {\n\t\treturn true;\n\t}\n}\nvar parseOptionalDef = (def, refs) => {\n\tvar _a2;\n\tif (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) return parseDef(def.innerType._def, refs);\n\tconst innerSchema = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"1\"\n\t\t]\n\t});\n\treturn innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();\n};\nvar parsePipelineDef = (def, refs) => {\n\tif (refs.pipeStrategy === \"input\") return parseDef(def.in._def, refs);\n\telse if (refs.pipeStrategy === \"output\") return parseDef(def.out._def, refs);\n\tconst a = parseDef(def.in._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\treturn { allOf: [a, parseDef(def.out._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\ta ? \"1\" : \"0\"\n\t\t]\n\t})].filter((x) => x !== void 0) };\n};\nfunction parsePromiseDef(def, refs) {\n\treturn parseDef(def.type._def, refs);\n}\nfunction parseSetDef(def, refs) {\n\tconst schema = {\n\t\ttype: \"array\",\n\t\tuniqueItems: true,\n\t\titems: parseDef(def.valueType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t\t})\n\t};\n\tif (def.minSize) schema.minItems = def.minSize.value;\n\tif (def.maxSize) schema.maxItems = def.maxSize.value;\n\treturn schema;\n}\nfunction parseTupleDef(def, refs) {\n\tif (def.rest) return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),\n\t\tadditionalItems: parseDef(def.rest._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalItems\"]\n\t\t})\n\t};\n\telse return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\tmaxItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])\n\t};\n}\nfunction parseUndefinedDef() {\n\treturn { not: parseAnyDef() };\n}\nfunction parseUnknownDef() {\n\treturn parseAnyDef();\n}\nvar parseReadonlyDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\nvar selectParser = (def, typeName, refs) => {\n\tswitch (typeName) {\n\t\tcase ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();\n\t\tcase ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();\n\t\tcase ZodFirstPartyTypeKind.ZodNull: return parseNullDef();\n\t\tcase ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodUnion:\n\t\tcase ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;\n\t\tcase ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodNaN:\n\t\tcase ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();\n\t\tcase ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();\n\t\tcase ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();\n\t\tcase ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodFunction:\n\t\tcase ZodFirstPartyTypeKind.ZodVoid:\n\t\tcase ZodFirstPartyTypeKind.ZodSymbol: return;\n\t\tdefault: return /* @__PURE__ */ ((_) => void 0)(typeName);\n\t}\n};\nvar getRelativePath = (pathA, pathB) => {\n\tlet i = 0;\n\tfor (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;\n\treturn [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\nfunction parseDef(def, refs, forceResolution = false) {\n\tvar _a2;\n\tconst seenItem = refs.seen.get(def);\n\tif (refs.override) {\n\t\tconst overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(refs, def, refs, seenItem, forceResolution);\n\t\tif (overrideResult !== ignoreOverride) return overrideResult;\n\t}\n\tif (seenItem && !forceResolution) {\n\t\tconst seenSchema = get$ref(seenItem, refs);\n\t\tif (seenSchema !== void 0) return seenSchema;\n\t}\n\tconst newItem = {\n\t\tdef,\n\t\tpath: refs.currentPath,\n\t\tjsonSchema: void 0\n\t};\n\trefs.seen.set(def, newItem);\n\tconst jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n\tconst jsonSchema2 = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n\tif (jsonSchema2) addMeta(def, refs, jsonSchema2);\n\tif (refs.postProcess) {\n\t\tconst postProcessResult = refs.postProcess(jsonSchema2, def, refs);\n\t\tnewItem.jsonSchema = jsonSchema2;\n\t\treturn postProcessResult;\n\t}\n\tnewItem.jsonSchema = jsonSchema2;\n\treturn jsonSchema2;\n}\nvar get$ref = (item, refs) => {\n\tswitch (refs.$refStrategy) {\n\t\tcase \"root\": return { $ref: item.path.join(\"/\") };\n\t\tcase \"relative\": return { $ref: getRelativePath(refs.currentPath, item.path) };\n\t\tcase \"none\":\n\t\tcase \"seen\":\n\t\t\tif (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n\t\t\t\tconsole.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n\t\t\t\treturn parseAnyDef();\n\t\t\t}\n\t\t\treturn refs.$refStrategy === \"seen\" ? parseAnyDef() : void 0;\n\t}\n};\nvar addMeta = (def, refs, jsonSchema2) => {\n\tif (def.description) jsonSchema2.description = def.description;\n\treturn jsonSchema2;\n};\nvar getRefs = (options) => {\n\tconst _options = getDefaultOptions(options);\n\tconst currentPath = _options.name !== void 0 ? [\n\t\t..._options.basePath,\n\t\t_options.definitionPath,\n\t\t_options.name\n\t] : _options.basePath;\n\treturn {\n\t\t..._options,\n\t\tcurrentPath,\n\t\tpropertyPath: void 0,\n\t\tseen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [def._def, {\n\t\t\tdef: def._def,\n\t\t\tpath: [\n\t\t\t\t..._options.basePath,\n\t\t\t\t_options.definitionPath,\n\t\t\t\tname2\n\t\t\t],\n\t\t\tjsonSchema: void 0\n\t\t}]))\n\t};\n};\nvar zodToJsonSchema = (schema, options) => {\n\tvar _a2;\n\tconst refs = getRefs(options);\n\tlet definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema2]) => {\n\t\tvar _a3;\n\t\treturn {\n\t\t\t...acc,\n\t\t\t[name3]: (_a3 = parseDef(schema2._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.basePath,\n\t\t\t\t\trefs.definitionPath,\n\t\t\t\t\tname3\n\t\t\t\t]\n\t\t\t}, true)) != null ? _a3 : parseAnyDef()\n\t\t};\n\t}, {}) : void 0;\n\tconst name2 = typeof options === \"string\" ? options : (options == null ? void 0 : options.nameStrategy) === \"title\" ? void 0 : options == null ? void 0 : options.name;\n\tconst main = (_a2 = parseDef(schema._def, name2 === void 0 ? refs : {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname2\n\t\t]\n\t}, false)) != null ? _a2 : parseAnyDef();\n\tconst title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n\tif (title !== void 0) main.title = title;\n\tconst combined = name2 === void 0 ? definitions ? {\n\t\t...main,\n\t\t[refs.definitionPath]: definitions\n\t} : main : {\n\t\t$ref: [\n\t\t\t...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname2\n\t\t].join(\"/\"),\n\t\t[refs.definitionPath]: {\n\t\t\t...definitions,\n\t\t\t[name2]: main\n\t\t}\n\t};\n\tcombined.$schema = \"http://json-schema.org/draft-07/schema#\";\n\treturn combined;\n};\nvar zod_to_json_schema_default = zodToJsonSchema;\nfunction zod3Schema(zodSchema2, options) {\n\tvar _a2;\n\tconst useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n\treturn jsonSchema(() => zod_to_json_schema_default(zodSchema2, { $refStrategy: useReferences ? \"root\" : \"none\" }), { validate: async (value) => {\n\t\tconst result = await zodSchema2.safeParseAsync(value);\n\t\treturn result.success ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.data\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: result.error\n\t\t};\n\t} });\n}\nfunction zod4Schema(zodSchema2, options) {\n\tvar _a2;\n\tconst useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n\treturn jsonSchema(() => addAdditionalPropertiesToJsonSchema(z4.toJSONSchema(zodSchema2, {\n\t\ttarget: \"draft-7\",\n\t\tio: \"input\",\n\t\treused: useReferences ? \"ref\" : \"inline\"\n\t})), { validate: async (value) => {\n\t\tconst result = await z4.safeParseAsync(zodSchema2, value);\n\t\treturn result.success ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.data\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: result.error\n\t\t};\n\t} });\n}\nfunction isZod4Schema(zodSchema2) {\n\treturn \"_zod\" in zodSchema2;\n}\nfunction zodSchema(zodSchema2, options) {\n\tif (isZod4Schema(zodSchema2)) return zod4Schema(zodSchema2, options);\n\telse return zod3Schema(zodSchema2, options);\n}\nfunction isSchema(value) {\n\treturn typeof value === \"object\" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && \"jsonSchema\" in value && \"validate\" in value;\n}\nfunction asSchema(schema) {\n\treturn schema == null ? jsonSchema({\n\t\tproperties: {},\n\t\tadditionalProperties: false\n\t}) : isSchema(schema) ? schema : typeof schema === \"function\" ? schema() : zodSchema(schema);\n}\nvar { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n\tconst latin1string = atob(base64String.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n\treturn Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n\tlet latin1string = \"\";\n\tfor (let i = 0; i < array.length; i++) latin1string += String.fromCodePoint(array[i]);\n\treturn btoa(latin1string);\n}\nfunction withoutTrailingSlash(url) {\n\treturn url == null ? void 0 : url.replace(/\\/$/, \"\");\n}\nfunction isAsyncIterable(obj) {\n\treturn obj != null && typeof obj[Symbol.asyncIterator] === \"function\";\n}\nasync function* executeTool({ execute, input, options }) {\n\tconst result = execute(input, options);\n\tif (isAsyncIterable(result)) {\n\t\tlet lastOutput;\n\t\tfor await (const output of result) {\n\t\t\tlastOutput = output;\n\t\t\tyield {\n\t\t\t\ttype: \"preliminary\",\n\t\t\t\toutput\n\t\t\t};\n\t\t}\n\t\tyield {\n\t\t\ttype: \"final\",\n\t\t\toutput: lastOutput\n\t\t};\n\t} else yield {\n\t\ttype: \"final\",\n\t\toutput: await result\n\t};\n}\n//#endregion\nexport { TypeValidationError as $, parseJsonEventStream as A, zodSchema as B, isAbortError as C, lazyValidator as D, lazySchema as E, safeValidateTypes as F, InvalidPromptError as G, APICallError as H, tool as I, LoadAPIKeyError as J, InvalidResponseDataError as K, validateTypes as L, readResponseWithSizeLimit as M, resolve as N, loadOptionalSetting as O, safeParseJSON as P, TooManyEmbeddingValuesForCallError as Q, withUserAgentSuffix as R, getRuntimeEnvironmentUserAgent as S, jsonSchema as T, EmptyResponseBodyError as U, AISDKError as V, InvalidArgumentError as W, NoContentGeneratedError as X, LoadSettingError as Y, NoSuchModelError as Z, executeTool as _, cancelResponseBody as a, getErrorMessage as b, convertBase64ToUint8Array as c, createIdGenerator as d, UnsupportedFunctionalityError as et, createJsonErrorResponseHandler as f, dynamicTool as g, delay as h, asSchema as i, postJsonToApi as j, normalizeHeaders as k, convertUint8ArrayToBase64 as l, createProviderDefinedToolFactoryWithOutputSchema as m, DelayedPromise as n, isJSONArray as nt, combineHeaders as o, createJsonResponseHandler as p, JSONParseError as q, DownloadError as r, isJSONObject as rt, convertAsyncIteratorToReadableStream as s, DEFAULT_MAX_DOWNLOAD_SIZE as t, getErrorMessage$1 as tt, createEventSourceResponseHandler as u, fetchWithValidatedRedirects as v, isUrlSupported as w, getFromApi as x, generateId as y, withoutTrailingSlash as z };\n\n//# sourceMappingURL=dist-Qv-F35RT.js.map","import { $ as TypeValidationError, A as parseJsonEventStream, B as zodSchema, C as isAbortError, D as lazyValidator, E as lazySchema, F as safeValidateTypes, G as InvalidPromptError, H as APICallError, I as tool, J as LoadAPIKeyError, K as InvalidResponseDataError, L as validateTypes, M as readResponseWithSizeLimit, N as resolve, O as loadOptionalSetting, P as safeParseJSON, Q as TooManyEmbeddingValuesForCallError, R as withUserAgentSuffix, S as getRuntimeEnvironmentUserAgent, T as jsonSchema, U as EmptyResponseBodyError, V as AISDKError, W as InvalidArgumentError$1, X as NoContentGeneratedError, Y as LoadSettingError, Z as NoSuchModelError, _ as executeTool, a as cancelResponseBody, b as getErrorMessage$1, c as convertBase64ToUint8Array, d as createIdGenerator, et as UnsupportedFunctionalityError, f as createJsonErrorResponseHandler, g as dynamicTool, h as delay, i as asSchema, j as postJsonToApi, k as normalizeHeaders, l as convertUint8ArrayToBase64, m as createProviderDefinedToolFactoryWithOutputSchema, n as DelayedPromise, nt as isJSONArray, o as combineHeaders, p as createJsonResponseHandler, q as JSONParseError, r as DownloadError$1, rt as isJSONObject, t as DEFAULT_MAX_DOWNLOAD_SIZE, tt as getErrorMessage, u as createEventSourceResponseHandler, v as fetchWithValidatedRedirects, w as isUrlSupported, x as getFromApi, y as generateId, z as withoutTrailingSlash } from \"./dist-Qv-F35RT.js\";\nimport { z } from \"zod/v4\";\nimport { z as z$1 } from \"zod\";\n//#region ../oidc-stub.ts\nfunction getContext() {\n\treturn { headers: {} };\n}\nasync function getVercelOidcToken() {\n\tif (process.env.VERCEL_OIDC_TOKEN) return process.env.VERCEL_OIDC_TOKEN ?? \"\";\n\tthrow new Error(\"@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.\");\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/gateway/2.0.115/cc0b542b1234e50adce9a27c3c0e8603856024507fe49e4d0b6beff0b082c5aa/node_modules/@ai-sdk/gateway/dist/index.mjs\nvar symbol$1 = Symbol.for(\"vercel.ai.gateway.error\");\nvar _a$1;\nvar _b;\nvar GatewayError = class _GatewayError extends (_b = Error, _a$1 = symbol$1, _b) {\n\tconstructor({ message, statusCode = 500, cause }) {\n\t\tsuper(message);\n\t\tthis[_a$1] = true;\n\t\tthis.statusCode = statusCode;\n\t\tthis.cause = cause;\n\t}\n\t/**\n\t* Checks if the given error is a Gateway Error.\n\t* @param {unknown} error - The error to check.\n\t* @returns {boolean} True if the error is a Gateway Error, false otherwise.\n\t*/\n\tstatic isInstance(error) {\n\t\treturn _GatewayError.hasMarker(error);\n\t}\n\tstatic hasMarker(error) {\n\t\treturn typeof error === \"object\" && error !== null && symbol$1 in error && error[symbol$1] === true;\n\t}\n};\nvar name$1 = \"GatewayAuthenticationError\";\nvar marker2$1 = `vercel.ai.gateway.error.${name$1}`;\nvar symbol2$1 = Symbol.for(marker2$1);\nvar _a2$1;\nvar _b2;\nvar GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2$1 = symbol2$1, _b2) {\n\tconstructor({ message = \"Authentication failed\", statusCode = 401, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a2$1] = true;\n\t\tthis.name = name$1;\n\t\tthis.type = \"authentication_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol2$1 in error;\n\t}\n\t/**\n\t* Creates a contextual error message when authentication fails\n\t*/\n\tstatic createContextualError({ apiKeyProvided, oidcTokenProvided, message = \"Authentication failed\", statusCode = 401, cause }) {\n\t\tlet contextualMessage;\n\t\tif (apiKeyProvided) contextualMessage = `AI Gateway authentication failed: Invalid API key.\n\nCreate a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\n\nProvide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;\n\t\telse if (oidcTokenProvided) contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.\n\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.\n\nAlternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;\n\t\telse contextualMessage = `AI Gateway authentication failed: No authentication provided.\n\nOption 1 - API key:\nCreate an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\nProvide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.\n\nOption 2 - OIDC token:\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;\n\t\treturn new _GatewayAuthenticationError({\n\t\t\tmessage: contextualMessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t}\n};\nvar name2$1 = \"GatewayForbiddenError\";\nvar marker3$1 = `vercel.ai.gateway.error.${name2$1}`;\nvar symbol3$1 = Symbol.for(marker3$1);\nvar forbiddenParamSchema = lazyValidator(() => zodSchema(z.object({ ruleId: z.string() })));\nvar _a3$1;\nvar _b3;\nvar GatewayForbiddenError = class extends (_b3 = GatewayError, _a3$1 = symbol3$1, _b3) {\n\tconstructor({ message = \"Forbidden\", statusCode = 403, cause, ruleId } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a3$1] = true;\n\t\tthis.name = name2$1;\n\t\tthis.type = \"forbidden\";\n\t\tthis.ruleId = ruleId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol3$1 in error;\n\t}\n};\nvar name3$1 = \"GatewayInvalidRequestError\";\nvar marker4$1 = `vercel.ai.gateway.error.${name3$1}`;\nvar symbol4$1 = Symbol.for(marker4$1);\nvar _a4$1;\nvar _b4;\nvar GatewayInvalidRequestError = class extends (_b4 = GatewayError, _a4$1 = symbol4$1, _b4) {\n\tconstructor({ message = \"Invalid request\", statusCode = 400, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a4$1] = true;\n\t\tthis.name = name3$1;\n\t\tthis.type = \"invalid_request_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol4$1 in error;\n\t}\n};\nvar name4$1 = \"GatewayRateLimitError\";\nvar marker5$1 = `vercel.ai.gateway.error.${name4$1}`;\nvar symbol5$1 = Symbol.for(marker5$1);\nvar _a5$1;\nvar _b5;\nvar GatewayRateLimitError = class extends (_b5 = GatewayError, _a5$1 = symbol5$1, _b5) {\n\tconstructor({ message = \"Rate limit exceeded\", statusCode = 429, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a5$1] = true;\n\t\tthis.name = name4$1;\n\t\tthis.type = \"rate_limit_exceeded\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol5$1 in error;\n\t}\n};\nvar name5$1 = \"GatewayModelNotFoundError\";\nvar marker6$1 = `vercel.ai.gateway.error.${name5$1}`;\nvar symbol6$1 = Symbol.for(marker6$1);\nvar modelNotFoundParamSchema = lazyValidator(() => zodSchema(z.object({ modelId: z.string() })));\nvar _a6$1;\nvar _b6;\nvar GatewayModelNotFoundError = class extends (_b6 = GatewayError, _a6$1 = symbol6$1, _b6) {\n\tconstructor({ message = \"Model not found\", statusCode = 404, modelId, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a6$1] = true;\n\t\tthis.name = name5$1;\n\t\tthis.type = \"model_not_found\";\n\t\tthis.modelId = modelId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol6$1 in error;\n\t}\n};\nvar name6$1 = \"GatewayInternalServerError\";\nvar marker7$1 = `vercel.ai.gateway.error.${name6$1}`;\nvar symbol7$1 = Symbol.for(marker7$1);\nvar _a7$1;\nvar _b7;\nvar GatewayInternalServerError = class extends (_b7 = GatewayError, _a7$1 = symbol7$1, _b7) {\n\tconstructor({ message = \"Internal server error\", statusCode = 500, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a7$1] = true;\n\t\tthis.name = name6$1;\n\t\tthis.type = \"internal_server_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol7$1 in error;\n\t}\n};\nvar name7$1 = \"GatewayResponseError\";\nvar marker8$1 = `vercel.ai.gateway.error.${name7$1}`;\nvar symbol8$1 = Symbol.for(marker8$1);\nvar _a8$1;\nvar _b8;\nvar GatewayResponseError = class extends (_b8 = GatewayError, _a8$1 = symbol8$1, _b8) {\n\tconstructor({ message = \"Invalid response from Gateway\", statusCode = 502, response, validationError, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a8$1] = true;\n\t\tthis.name = name7$1;\n\t\tthis.type = \"response_error\";\n\t\tthis.response = response;\n\t\tthis.validationError = validationError;\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol8$1 in error;\n\t}\n};\nasync function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = \"Gateway request failed\", cause, authMethod }) {\n\tconst parseResult = await safeValidateTypes({\n\t\tvalue: response,\n\t\tschema: gatewayErrorResponseSchema\n\t});\n\tif (!parseResult.success) return new GatewayResponseError({\n\t\tmessage: `Invalid error response format: ${defaultMessage}`,\n\t\tstatusCode,\n\t\tresponse,\n\t\tvalidationError: parseResult.error,\n\t\tcause\n\t});\n\tconst validatedResponse = parseResult.value;\n\tconst errorType = validatedResponse.error.type;\n\tconst message = validatedResponse.error.message;\n\tswitch (errorType) {\n\t\tcase \"authentication_error\": return GatewayAuthenticationError.createContextualError({\n\t\t\tapiKeyProvided: authMethod === \"api-key\",\n\t\t\toidcTokenProvided: authMethod === \"oidc\",\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"invalid_request_error\": return new GatewayInvalidRequestError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"rate_limit_exceeded\": return new GatewayRateLimitError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"model_not_found\": {\n\t\t\tconst modelResult = await safeValidateTypes({\n\t\t\t\tvalue: validatedResponse.error.param,\n\t\t\t\tschema: modelNotFoundParamSchema\n\t\t\t});\n\t\t\treturn new GatewayModelNotFoundError({\n\t\t\t\tmessage,\n\t\t\t\tstatusCode,\n\t\t\t\tmodelId: modelResult.success ? modelResult.value.modelId : void 0,\n\t\t\t\tcause\n\t\t\t});\n\t\t}\n\t\tcase \"internal_server_error\": return new GatewayInternalServerError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"forbidden\": {\n\t\t\tconst ruleResult = await safeValidateTypes({\n\t\t\t\tvalue: validatedResponse.error.param,\n\t\t\t\tschema: forbiddenParamSchema\n\t\t\t});\n\t\t\treturn new GatewayForbiddenError({\n\t\t\t\tmessage,\n\t\t\t\tstatusCode,\n\t\t\t\tcause,\n\t\t\t\truleId: ruleResult.success ? ruleResult.value.ruleId : void 0\n\t\t\t});\n\t\t}\n\t\tdefault: return new GatewayInternalServerError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t}\n}\nvar gatewayErrorResponseSchema = lazyValidator(() => zodSchema(z.object({ error: z.object({\n\tmessage: z.string(),\n\ttype: z.string().nullish(),\n\tparam: z.unknown().nullish(),\n\tcode: z.union([z.string(), z.number()]).nullish()\n}) })));\nfunction extractApiCallResponse(error) {\n\tif (error.data !== void 0) return error.data;\n\tif (error.responseBody != null) try {\n\t\treturn JSON.parse(error.responseBody);\n\t} catch (e) {\n\t\treturn error.responseBody;\n\t}\n\treturn {};\n}\nvar name8$1 = \"GatewayTimeoutError\";\nvar marker9$1 = `vercel.ai.gateway.error.${name8$1}`;\nvar symbol9$1 = Symbol.for(marker9$1);\nvar _a9$1;\nvar _b9;\nvar GatewayTimeoutError = class _GatewayTimeoutError extends (_b9 = GatewayError, _a9$1 = symbol9$1, _b9) {\n\tconstructor({ message = \"Request timed out\", statusCode = 408, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a9$1] = true;\n\t\tthis.name = name8$1;\n\t\tthis.type = \"timeout_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol9$1 in error;\n\t}\n\t/**\n\t* Creates a helpful timeout error message with troubleshooting guidance\n\t*/\n\tstatic createTimeoutError({ originalMessage, statusCode = 408, cause }) {\n\t\tconst message = `Gateway request timed out: ${originalMessage}\n\n This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;\n\t\treturn new _GatewayTimeoutError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t}\n};\nfunction isTimeoutError(error) {\n\tif (!(error instanceof Error)) return false;\n\tconst errorCode = error.code;\n\tif (typeof errorCode === \"string\") return [\n\t\t\"UND_ERR_HEADERS_TIMEOUT\",\n\t\t\"UND_ERR_BODY_TIMEOUT\",\n\t\t\"UND_ERR_CONNECT_TIMEOUT\"\n\t].includes(errorCode);\n\treturn false;\n}\nasync function asGatewayError(error, authMethod) {\n\tvar _a10;\n\tif (GatewayError.isInstance(error)) return error;\n\tif (isTimeoutError(error)) return GatewayTimeoutError.createTimeoutError({\n\t\toriginalMessage: error instanceof Error ? error.message : \"Unknown error\",\n\t\tcause: error\n\t});\n\tif (APICallError.isInstance(error)) {\n\t\tif (error.cause && isTimeoutError(error.cause)) return GatewayTimeoutError.createTimeoutError({\n\t\t\toriginalMessage: error.message,\n\t\t\tcause: error\n\t\t});\n\t\treturn await createGatewayErrorFromResponse({\n\t\t\tresponse: extractApiCallResponse(error),\n\t\t\tstatusCode: (_a10 = error.statusCode) != null ? _a10 : 500,\n\t\t\tdefaultMessage: \"Gateway request failed\",\n\t\t\tcause: error,\n\t\t\tauthMethod\n\t\t});\n\t}\n\treturn await createGatewayErrorFromResponse({\n\t\tresponse: {},\n\t\tstatusCode: 500,\n\t\tdefaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : \"Unknown Gateway error\",\n\t\tcause: error,\n\t\tauthMethod\n\t});\n}\nvar GATEWAY_AUTH_METHOD_HEADER = \"ai-gateway-auth-method\";\nasync function parseAuthMethod(headers) {\n\tconst result = await safeValidateTypes({\n\t\tvalue: headers[GATEWAY_AUTH_METHOD_HEADER],\n\t\tschema: gatewayAuthMethodSchema\n\t});\n\treturn result.success ? result.value : void 0;\n}\nvar gatewayAuthMethodSchema = lazyValidator(() => zodSchema(z.union([z.literal(\"api-key\"), z.literal(\"oidc\")])));\nvar KNOWN_MODEL_TYPES = [\n\t\"embedding\",\n\t\"image\",\n\t\"language\"\n];\nvar GatewayFetchMetadata = class {\n\tconstructor(config) {\n\t\tthis.config = config;\n\t}\n\tasync getAvailableModels() {\n\t\ttry {\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${this.config.baseURL}/config`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n\tasync getCredits() {\n\t\ttry {\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${new URL(this.config.baseURL).origin}/v1/credits`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n};\nvar gatewayAvailableModelsResponseSchema = lazyValidator(() => zodSchema(z.object({ models: z.array(z.object({\n\tid: z.string(),\n\tname: z.string(),\n\tdescription: z.string().nullish(),\n\tpricing: z.object({\n\t\tinput: z.string(),\n\t\toutput: z.string(),\n\t\tinput_cache_read: z.string().nullish(),\n\t\tinput_cache_write: z.string().nullish()\n\t}).transform(({ input, output, input_cache_read, input_cache_write }) => ({\n\t\tinput,\n\t\toutput,\n\t\t...input_cache_read ? { cachedInputTokens: input_cache_read } : {},\n\t\t...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}\n\t})).nullish(),\n\tspecification: z.object({\n\t\tspecificationVersion: z.literal(\"v2\"),\n\t\tprovider: z.string(),\n\t\tmodelId: z.string()\n\t}),\n\tmodelType: z.string().nullish()\n})).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType))) })));\nvar gatewayCreditsResponseSchema = lazyValidator(() => zodSchema(z.object({\n\tbalance: z.string(),\n\ttotal_used: z.string()\n}).transform(({ balance, total_used }) => ({\n\tbalance,\n\ttotalUsed: total_used\n}))));\nvar GatewaySpendReport = class {\n\tconstructor(config) {\n\t\tthis.config = config;\n\t}\n\tasync getSpendReport(params) {\n\t\ttry {\n\t\t\tconst baseUrl = new URL(this.config.baseURL);\n\t\t\tconst searchParams = new URLSearchParams();\n\t\t\tsearchParams.set(\"start_date\", params.startDate);\n\t\t\tsearchParams.set(\"end_date\", params.endDate);\n\t\t\tif (params.groupBy) searchParams.set(\"group_by\", params.groupBy);\n\t\t\tif (params.datePart) searchParams.set(\"date_part\", params.datePart);\n\t\t\tif (params.userId) searchParams.set(\"user_id\", params.userId);\n\t\t\tif (params.model) searchParams.set(\"model\", params.model);\n\t\t\tif (params.provider) searchParams.set(\"provider\", params.provider);\n\t\t\tif (params.credentialType) searchParams.set(\"credential_type\", params.credentialType);\n\t\t\tif (params.tags && params.tags.length > 0) searchParams.set(\"tags\", params.tags.join(\",\"));\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n};\nvar gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(z.object({ results: z.array(z.object({\n\tday: z.string().optional(),\n\thour: z.string().optional(),\n\tuser: z.string().optional(),\n\tmodel: z.string().optional(),\n\ttag: z.string().optional(),\n\tprovider: z.string().optional(),\n\tcredential_type: z.enum([\"byok\", \"system\"]).optional(),\n\ttotal_cost: z.number(),\n\tmarket_cost: z.number().optional(),\n\tinput_tokens: z.number().optional(),\n\toutput_tokens: z.number().optional(),\n\tcached_input_tokens: z.number().optional(),\n\tcache_creation_input_tokens: z.number().optional(),\n\treasoning_tokens: z.number().optional(),\n\trequest_count: z.number().optional()\n}).transform(({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({\n\t...rest,\n\t...credential_type !== void 0 ? { credentialType: credential_type } : {},\n\ttotalCost: total_cost,\n\t...market_cost !== void 0 ? { marketCost: market_cost } : {},\n\t...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},\n\t...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},\n\t...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},\n\t...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},\n\t...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},\n\t...request_count !== void 0 ? { requestCount: request_count } : {}\n}))) })));\nvar GatewayGenerationInfoFetcher = class {\n\tconstructor(config) {\n\t\tthis.config = config;\n\t}\n\tasync getGenerationInfo(params) {\n\t\ttry {\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${new URL(this.config.baseURL).origin}/v1/generation?id=${encodeURIComponent(params.id)}`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n};\nvar gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(z.object({ data: z.object({\n\tid: z.string(),\n\ttotal_cost: z.number(),\n\tupstream_inference_cost: z.number(),\n\tusage: z.number(),\n\tcreated_at: z.string(),\n\tmodel: z.string(),\n\tis_byok: z.boolean(),\n\tprovider_name: z.string(),\n\tstreamed: z.boolean(),\n\tfinish_reason: z.string(),\n\tlatency: z.number(),\n\tgeneration_time: z.number(),\n\tnative_tokens_prompt: z.number(),\n\tnative_tokens_completion: z.number(),\n\tnative_tokens_reasoning: z.number(),\n\tnative_tokens_cached: z.number(),\n\tnative_tokens_cache_creation: z.number(),\n\tbillable_web_search_calls: z.number()\n}).transform(({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({\n\t...rest,\n\ttotalCost: total_cost,\n\tupstreamInferenceCost: upstream_inference_cost,\n\tcreatedAt: created_at,\n\tisByok: is_byok,\n\tproviderName: provider_name,\n\tfinishReason: finish_reason,\n\tgenerationTime: generation_time,\n\tpromptTokens: native_tokens_prompt,\n\tcompletionTokens: native_tokens_completion,\n\treasoningTokens: native_tokens_reasoning,\n\tcachedTokens: native_tokens_cached,\n\tcacheCreationTokens: native_tokens_cache_creation,\n\tbillableWebSearchCalls: billable_web_search_calls\n})) }).transform(({ data }) => data)));\nvar GatewayLanguageModel = class {\n\tconstructor(modelId, config) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t\tthis.specificationVersion = \"v2\";\n\t\tthis.supportedUrls = { \"*/*\": [/.*/] };\n\t}\n\tget provider() {\n\t\treturn this.config.provider;\n\t}\n\tasync getArgs(options) {\n\t\tconst { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;\n\t\treturn {\n\t\t\targs: this.maybeEncodeFileParts(optionsWithoutSignal),\n\t\t\twarnings: []\n\t\t};\n\t}\n\tasync doGenerate(options) {\n\t\tconst { args, warnings } = await this.getArgs(options);\n\t\tconst { abortSignal } = options;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: args,\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(z.any()),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...responseBody,\n\t\t\t\trequest: { body: args },\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: responseHeaders,\n\t\t\t\t\tbody: rawResponse\n\t\t\t\t},\n\t\t\t\twarnings\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tasync doStream(options) {\n\t\tconst { args, warnings } = await this.getArgs(options);\n\t\tconst { abortSignal } = options;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { value: response, responseHeaders } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: args,\n\t\t\t\tsuccessfulResponseHandler: createEventSourceResponseHandler(z.any()),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tstream: response.pipeThrough(new TransformStream({\n\t\t\t\t\tstart(controller) {\n\t\t\t\t\t\tif (warnings.length > 0) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"stream-start\",\n\t\t\t\t\t\t\twarnings\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\ttransform(chunk, controller) {\n\t\t\t\t\t\tif (chunk.success) {\n\t\t\t\t\t\t\tconst streamPart = chunk.value;\n\t\t\t\t\t\t\tif (streamPart.type === \"raw\" && !options.includeRawChunks) return;\n\t\t\t\t\t\t\tif (streamPart.type === \"response-metadata\" && streamPart.timestamp && typeof streamPart.timestamp === \"string\") streamPart.timestamp = new Date(streamPart.timestamp);\n\t\t\t\t\t\t\tcontroller.enqueue(streamPart);\n\t\t\t\t\t\t} else controller.error(chunk.error);\n\t\t\t\t\t}\n\t\t\t\t})),\n\t\t\t\trequest: { body: args },\n\t\t\t\tresponse: { headers: responseHeaders }\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tisFilePart(part) {\n\t\treturn part && typeof part === \"object\" && \"type\" in part && part.type === \"file\";\n\t}\n\t/**\n\t* Encodes file parts in the prompt to base64. Mutates the passed options\n\t* instance directly to avoid copying the file data.\n\t* @param options - The options to encode.\n\t* @returns The options with the file parts encoded.\n\t*/\n\tmaybeEncodeFileParts(options) {\n\t\tfor (const message of options.prompt) for (const part of message.content) if (this.isFilePart(part)) {\n\t\t\tconst filePart = part;\n\t\t\tif (filePart.data instanceof Uint8Array) {\n\t\t\t\tconst buffer = Uint8Array.from(filePart.data);\n\t\t\t\tconst base64Data = Buffer.from(buffer).toString(\"base64\");\n\t\t\t\tfilePart.data = new URL(`data:${filePart.mediaType || \"application/octet-stream\"};base64,${base64Data}`);\n\t\t\t}\n\t\t}\n\t\treturn options;\n\t}\n\tgetUrl() {\n\t\treturn `${this.config.baseURL}/language-model`;\n\t}\n\tgetModelConfigHeaders(modelId, streaming) {\n\t\treturn {\n\t\t\t\"ai-language-model-specification-version\": \"2\",\n\t\t\t\"ai-language-model-id\": modelId,\n\t\t\t\"ai-language-model-streaming\": String(streaming)\n\t\t};\n\t}\n};\nvar GatewayEmbeddingModel = class {\n\tconstructor(modelId, config) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t\tthis.specificationVersion = \"v2\";\n\t\tthis.maxEmbeddingsPerCall = 2048;\n\t\tthis.supportsParallelCalls = true;\n\t}\n\tget provider() {\n\t\treturn this.config.provider;\n\t}\n\tasync doEmbed({ values, headers, abortSignal, providerOptions }) {\n\t\tvar _a10;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: {\n\t\t\t\t\tinput: values.length === 1 ? values[0] : values,\n\t\t\t\t\t...providerOptions ? { providerOptions } : {}\n\t\t\t\t},\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tembeddings: responseBody.embeddings,\n\t\t\t\tusage: (_a10 = responseBody.usage) != null ? _a10 : void 0,\n\t\t\t\tproviderMetadata: responseBody.providerMetadata,\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: responseHeaders,\n\t\t\t\t\tbody: rawValue\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tgetUrl() {\n\t\treturn `${this.config.baseURL}/embedding-model`;\n\t}\n\tgetModelConfigHeaders() {\n\t\treturn {\n\t\t\t\"ai-embedding-model-specification-version\": \"2\",\n\t\t\t\"ai-model-id\": this.modelId\n\t\t};\n\t}\n};\nvar gatewayEmbeddingResponseSchema = lazyValidator(() => zodSchema(z.object({\n\tembeddings: z.array(z.array(z.number())),\n\tusage: z.object({ tokens: z.number() }).nullish(),\n\tproviderMetadata: z.record(z.string(), z.record(z.string(), z.unknown())).optional()\n})));\nvar GatewayImageModel = class {\n\tconstructor(modelId, config) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t\tthis.specificationVersion = \"v2\";\n\t\tthis.maxImagesPerCall = Number.MAX_SAFE_INTEGER;\n\t}\n\tget provider() {\n\t\treturn this.config.provider;\n\t}\n\tasync doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) {\n\t\tvar _a10, _b10, _c, _d;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: {\n\t\t\t\t\tprompt,\n\t\t\t\t\tn,\n\t\t\t\t\t...size && { size },\n\t\t\t\t\t...aspectRatio && { aspectRatio },\n\t\t\t\t\t...seed && { seed },\n\t\t\t\t\t...providerOptions && { providerOptions }\n\t\t\t\t},\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\timages: responseBody.images,\n\t\t\t\twarnings: (_a10 = responseBody.warnings) != null ? _a10 : [],\n\t\t\t\tproviderMetadata: responseBody.providerMetadata,\n\t\t\t\tresponse: {\n\t\t\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\t\t\tmodelId: this.modelId,\n\t\t\t\t\theaders: responseHeaders\n\t\t\t\t},\n\t\t\t\t...responseBody.usage != null && { usage: {\n\t\t\t\t\tinputTokens: (_b10 = responseBody.usage.inputTokens) != null ? _b10 : void 0,\n\t\t\t\t\toutputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,\n\t\t\t\t\ttotalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0\n\t\t\t\t} }\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tgetUrl() {\n\t\treturn `${this.config.baseURL}/image-model`;\n\t}\n\tgetModelConfigHeaders() {\n\t\treturn {\n\t\t\t\"ai-image-model-specification-version\": \"2\",\n\t\t\t\"ai-model-id\": this.modelId\n\t\t};\n\t}\n};\nvar providerMetadataEntrySchema = z.object({ images: z.array(z.unknown()).optional() }).catchall(z.unknown());\nvar gatewayImageUsageSchema = z.object({\n\tinputTokens: z.number().nullish(),\n\toutputTokens: z.number().nullish(),\n\ttotalTokens: z.number().nullish()\n});\nvar gatewayImageResponseSchema = z.object({\n\timages: z.array(z.string()),\n\twarnings: z.array(z.object({\n\t\ttype: z.literal(\"other\"),\n\t\tmessage: z.string()\n\t})).optional(),\n\tproviderMetadata: z.record(z.string(), providerMetadataEntrySchema).optional(),\n\tusage: gatewayImageUsageSchema.optional()\n});\nvar parallelSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({\n\tid: \"gateway.parallel_search\",\n\tname: \"parallel_search\",\n\tinputSchema: lazySchema(() => zodSchema(z$1.object({\n\t\tobjective: z$1.string().describe(\"Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters.\"),\n\t\tsearch_queries: z$1.array(z$1.string()).optional().describe(\"Optional search queries to supplement the objective. Maximum 200 characters per query.\"),\n\t\tmode: z$1.enum([\"one-shot\", \"agentic\"]).optional().describe(\"Mode preset: \\\"one-shot\\\" for comprehensive results with longer excerpts (default), \\\"agentic\\\" for concise, token-efficient results for multi-step workflows.\"),\n\t\tmax_results: z$1.number().optional().describe(\"Maximum number of results to return (1-20). Defaults to 10 if not specified.\"),\n\t\tsource_policy: z$1.object({\n\t\t\tinclude_domains: z$1.array(z$1.string()).optional().describe(\"List of domains to include in search results.\"),\n\t\t\texclude_domains: z$1.array(z$1.string()).optional().describe(\"List of domains to exclude from search results.\"),\n\t\t\tafter_date: z$1.string().optional().describe(\"Only include results published after this date (ISO 8601 format).\")\n\t\t}).optional().describe(\"Source policy for controlling which domains to include/exclude and freshness.\"),\n\t\texcerpts: z$1.object({\n\t\t\tmax_chars_per_result: z$1.number().optional().describe(\"Maximum characters per result.\"),\n\t\t\tmax_chars_total: z$1.number().optional().describe(\"Maximum total characters across all results.\")\n\t\t}).optional().describe(\"Excerpt configuration for controlling result length.\"),\n\t\tfetch_policy: z$1.object({ max_age_seconds: z$1.number().optional().describe(\"Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.\") }).optional().describe(\"Fetch policy for controlling content freshness.\")\n\t}))),\n\toutputSchema: lazySchema(() => zodSchema(z$1.union([z$1.object({\n\t\tsearchId: z$1.string(),\n\t\tresults: z$1.array(z$1.object({\n\t\t\turl: z$1.string(),\n\t\t\ttitle: z$1.string(),\n\t\t\texcerpt: z$1.string(),\n\t\t\tpublishDate: z$1.string().nullable().optional(),\n\t\t\trelevanceScore: z$1.number().optional()\n\t\t}))\n\t}), z$1.object({\n\t\terror: z$1.enum([\n\t\t\t\"api_error\",\n\t\t\t\"rate_limit\",\n\t\t\t\"timeout\",\n\t\t\t\"invalid_input\",\n\t\t\t\"configuration_error\",\n\t\t\t\"unknown\"\n\t\t]),\n\t\tstatusCode: z$1.number().optional(),\n\t\tmessage: z$1.string()\n\t})])))\n});\nvar parallelSearch = (config = {}) => parallelSearchToolFactory(config);\nvar perplexitySearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({\n\tid: \"gateway.perplexity_search\",\n\tname: \"perplexity_search\",\n\tinputSchema: lazySchema(() => zodSchema(z$1.object({\n\t\tquery: z$1.union([z$1.string(), z$1.array(z$1.string())]).describe(\"Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries.\"),\n\t\tmax_results: z$1.number().optional().describe(\"Maximum number of search results to return (1-20, default: 10)\"),\n\t\tmax_tokens_per_page: z$1.number().optional().describe(\"Maximum number of tokens to extract per search result page (256-2048, default: 2048)\"),\n\t\tmax_tokens: z$1.number().optional().describe(\"Maximum total tokens across all search results (default: 25000, max: 1000000)\"),\n\t\tcountry: z$1.string().optional().describe(\"Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')\"),\n\t\tsearch_domain_filter: z$1.array(z$1.string()).optional().describe(\"List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']\"),\n\t\tsearch_language_filter: z$1.array(z$1.string()).optional().describe(\"List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']\"),\n\t\tsearch_after_date: z$1.string().optional().describe(\"Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\"),\n\t\tsearch_before_date: z$1.string().optional().describe(\"Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\"),\n\t\tlast_updated_after_filter: z$1.string().optional().describe(\"Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\"),\n\t\tlast_updated_before_filter: z$1.string().optional().describe(\"Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\"),\n\t\tsearch_recency_filter: z$1.enum([\n\t\t\t\"day\",\n\t\t\t\"week\",\n\t\t\t\"month\",\n\t\t\t\"year\"\n\t\t]).optional().describe(\"Filter results by relative time period. Cannot be used with search_after_date or search_before_date.\")\n\t}))),\n\toutputSchema: lazySchema(() => zodSchema(z$1.union([z$1.object({\n\t\tresults: z$1.array(z$1.object({\n\t\t\ttitle: z$1.string(),\n\t\t\turl: z$1.string(),\n\t\t\tsnippet: z$1.string(),\n\t\t\tdate: z$1.string().optional(),\n\t\t\tlastUpdated: z$1.string().optional()\n\t\t})),\n\t\tid: z$1.string()\n\t}), z$1.object({\n\t\terror: z$1.enum([\n\t\t\t\"api_error\",\n\t\t\t\"rate_limit\",\n\t\t\t\"timeout\",\n\t\t\t\"invalid_input\",\n\t\t\t\"unknown\"\n\t\t]),\n\t\tstatusCode: z$1.number().optional(),\n\t\tmessage: z$1.string()\n\t})])))\n});\nvar perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);\nvar gatewayTools = {\n\t/**\n\t* Search the web using Parallel AI's Search API for LLM-optimized excerpts.\n\t*\n\t* Takes a natural language objective and returns relevant excerpts,\n\t* replacing multiple keyword searches with a single call for broad\n\t* or complex queries. Supports different search types for depth vs\n\t* breadth tradeoffs.\n\t*/\n\tparallelSearch,\n\t/**\n\t* Search the web using Perplexity's Search API for real-time information,\n\t* news, research papers, and articles.\n\t*\n\t* Provides ranked search results with advanced filtering options including\n\t* domain, language, date range, and recency filters.\n\t*/\n\tperplexitySearch\n};\nasync function getVercelRequestId() {\n\tvar _a10;\n\treturn (_a10 = getContext().headers) == null ? void 0 : _a10[\"x-vercel-id\"];\n}\nvar VERSION$2 = \"2.0.115\";\nvar AI_GATEWAY_PROTOCOL_VERSION = \"0.0.1\";\nfunction createGatewayProvider(options = {}) {\n\tvar _a10, _b10;\n\tlet pendingMetadata = null;\n\tlet metadataCache = null;\n\tconst cacheRefreshMillis = (_a10 = options.metadataCacheRefreshMillis) != null ? _a10 : 1e3 * 60 * 5;\n\tlet lastFetchTime = 0;\n\tconst baseURL = (_b10 = withoutTrailingSlash(options.baseURL)) != null ? _b10 : \"https://ai-gateway.vercel.sh/v1/ai\";\n\tconst getHeaders = async () => {\n\t\tconst auth = await getGatewayAuthToken(options);\n\t\tif (auth) return withUserAgentSuffix({\n\t\t\tAuthorization: `Bearer ${auth.token}`,\n\t\t\t\"ai-gateway-protocol-version\": AI_GATEWAY_PROTOCOL_VERSION,\n\t\t\t[GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,\n\t\t\t...options.headers\n\t\t}, `ai-sdk/gateway/${VERSION$2}`);\n\t\tthrow GatewayAuthenticationError.createContextualError({\n\t\t\tapiKeyProvided: false,\n\t\t\toidcTokenProvided: false,\n\t\t\tstatusCode: 401\n\t\t});\n\t};\n\tconst createO11yHeaders = () => {\n\t\tconst deploymentId = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_DEPLOYMENT_ID\"\n\t\t});\n\t\tconst environment = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_ENV\"\n\t\t});\n\t\tconst region = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_REGION\"\n\t\t});\n\t\tconst projectId = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_PROJECT_ID\"\n\t\t});\n\t\treturn async () => {\n\t\t\tconst requestId = await getVercelRequestId();\n\t\t\treturn {\n\t\t\t\t...deploymentId && { \"ai-o11y-deployment-id\": deploymentId },\n\t\t\t\t...environment && { \"ai-o11y-environment\": environment },\n\t\t\t\t...region && { \"ai-o11y-region\": region },\n\t\t\t\t...requestId && { \"ai-o11y-request-id\": requestId },\n\t\t\t\t...projectId && { \"ai-o11y-project-id\": projectId }\n\t\t\t};\n\t\t};\n\t};\n\tconst createLanguageModel = (modelId) => {\n\t\treturn new GatewayLanguageModel(modelId, {\n\t\t\tprovider: \"gateway\",\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch,\n\t\t\to11yHeaders: createO11yHeaders()\n\t\t});\n\t};\n\tconst getAvailableModels = async () => {\n\t\tvar _a11, _b11, _c;\n\t\tconst now = (_c = (_b11 = (_a11 = options._internal) == null ? void 0 : _a11.currentDate) == null ? void 0 : _b11.call(_a11).getTime()) != null ? _c : Date.now();\n\t\tif (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {\n\t\t\tlastFetchTime = now;\n\t\t\tpendingMetadata = new GatewayFetchMetadata({\n\t\t\t\tbaseURL,\n\t\t\t\theaders: getHeaders,\n\t\t\t\tfetch: options.fetch\n\t\t\t}).getAvailableModels().then((metadata) => {\n\t\t\t\tmetadataCache = metadata;\n\t\t\t\treturn metadata;\n\t\t\t}).catch(async (error) => {\n\t\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t\t});\n\t\t}\n\t\treturn metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;\n\t};\n\tconst getCredits = async () => {\n\t\treturn new GatewayFetchMetadata({\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch\n\t\t}).getCredits().catch(async (error) => {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t});\n\t};\n\tconst getSpendReport = async (params) => {\n\t\treturn new GatewaySpendReport({\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch\n\t\t}).getSpendReport(params).catch(async (error) => {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t});\n\t};\n\tconst getGenerationInfo = async (params) => {\n\t\treturn new GatewayGenerationInfoFetcher({\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch\n\t\t}).getGenerationInfo(params).catch(async (error) => {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t});\n\t};\n\tconst provider = function(modelId) {\n\t\tif (new.target) throw new Error(\"The Gateway Provider model function cannot be called with the new keyword.\");\n\t\treturn createLanguageModel(modelId);\n\t};\n\tprovider.getAvailableModels = getAvailableModels;\n\tprovider.getCredits = getCredits;\n\tprovider.getSpendReport = getSpendReport;\n\tprovider.getGenerationInfo = getGenerationInfo;\n\tprovider.imageModel = (modelId) => {\n\t\treturn new GatewayImageModel(modelId, {\n\t\t\tprovider: \"gateway\",\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch,\n\t\t\to11yHeaders: createO11yHeaders()\n\t\t});\n\t};\n\tprovider.languageModel = createLanguageModel;\n\tprovider.textEmbeddingModel = (modelId) => {\n\t\treturn new GatewayEmbeddingModel(modelId, {\n\t\t\tprovider: \"gateway\",\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch,\n\t\t\to11yHeaders: createO11yHeaders()\n\t\t});\n\t};\n\tprovider.tools = gatewayTools;\n\treturn provider;\n}\nvar gateway = createGatewayProvider();\nasync function getGatewayAuthToken(options) {\n\tconst apiKey = loadOptionalSetting({\n\t\tsettingValue: options.apiKey,\n\t\tenvironmentVariableName: \"AI_GATEWAY_API_KEY\"\n\t});\n\tif (apiKey) return {\n\t\ttoken: apiKey,\n\t\tauthMethod: \"api-key\"\n\t};\n\ttry {\n\t\treturn {\n\t\t\ttoken: await getVercelOidcToken(),\n\t\t\tauthMethod: \"oidc\"\n\t\t};\n\t} catch (e) {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js\n/** only globals that common to node and browsers are allowed */\nvar _globalThis = typeof globalThis === \"object\" ? globalThis : global;\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/version.js\nvar VERSION$1 = \"1.9.0\";\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/internal/semver.js\nvar re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n/**\n* Create a function to test an API version to see if it is compatible with the provided ownVersion.\n*\n* The returned function has the following semantics:\n* - Exact match is always compatible\n* - Major versions must match exactly\n* - 1.x package cannot use global 2.x package\n* - 2.x package cannot use global 1.x package\n* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n* - Patch and build tag differences are not considered at this time\n*\n* @param ownVersion version which should be checked against\n*/\nfunction _makeCompatibilityCheck(ownVersion) {\n\tvar acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);\n\tvar rejectedVersions = /* @__PURE__ */ new Set();\n\tvar myVersionMatch = ownVersion.match(re);\n\tif (!myVersionMatch) return function() {\n\t\treturn false;\n\t};\n\tvar ownVersionParsed = {\n\t\tmajor: +myVersionMatch[1],\n\t\tminor: +myVersionMatch[2],\n\t\tpatch: +myVersionMatch[3],\n\t\tprerelease: myVersionMatch[4]\n\t};\n\tif (ownVersionParsed.prerelease != null) return function isExactmatch(globalVersion) {\n\t\treturn globalVersion === ownVersion;\n\t};\n\tfunction _reject(v) {\n\t\trejectedVersions.add(v);\n\t\treturn false;\n\t}\n\tfunction _accept(v) {\n\t\tacceptedVersions.add(v);\n\t\treturn true;\n\t}\n\treturn function isCompatible(globalVersion) {\n\t\tif (acceptedVersions.has(globalVersion)) return true;\n\t\tif (rejectedVersions.has(globalVersion)) return false;\n\t\tvar globalVersionMatch = globalVersion.match(re);\n\t\tif (!globalVersionMatch) return _reject(globalVersion);\n\t\tvar globalVersionParsed = {\n\t\t\tmajor: +globalVersionMatch[1],\n\t\t\tminor: +globalVersionMatch[2],\n\t\t\tpatch: +globalVersionMatch[3],\n\t\t\tprerelease: globalVersionMatch[4]\n\t\t};\n\t\tif (globalVersionParsed.prerelease != null) return _reject(globalVersion);\n\t\tif (ownVersionParsed.major !== globalVersionParsed.major) return _reject(globalVersion);\n\t\tif (ownVersionParsed.major === 0) {\n\t\t\tif (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) return _accept(globalVersion);\n\t\t\treturn _reject(globalVersion);\n\t\t}\n\t\tif (ownVersionParsed.minor <= globalVersionParsed.minor) return _accept(globalVersion);\n\t\treturn _reject(globalVersion);\n\t};\n}\n/**\n* Test an API version to see if it is compatible with this API.\n*\n* - Exact match is always compatible\n* - Major versions must match exactly\n* - 1.x package cannot use global 2.x package\n* - 2.x package cannot use global 1.x package\n* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n* - Patch and build tag differences are not considered at this time\n*\n* @param version version of the API requesting an instance of the global API\n*/\nvar isCompatible = _makeCompatibilityCheck(VERSION$1);\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js\nvar major = VERSION$1.split(\".\")[0];\nvar GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\"opentelemetry.js.api.\" + major);\nvar _global = _globalThis;\nfunction registerGlobal(type, instance, diag, allowOverride) {\n\tvar _a;\n\tif (allowOverride === void 0) allowOverride = false;\n\tvar api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: VERSION$1 };\n\tif (!allowOverride && api[type]) {\n\t\tvar err = /* @__PURE__ */ new Error(\"@opentelemetry/api: Attempted duplicate registration of API: \" + type);\n\t\tdiag.error(err.stack || err.message);\n\t\treturn false;\n\t}\n\tif (api.version !== \"1.9.0\") {\n\t\tvar err = /* @__PURE__ */ new Error(\"@opentelemetry/api: Registration of version v\" + api.version + \" for \" + type + \" does not match previously registered API v\" + VERSION$1);\n\t\tdiag.error(err.stack || err.message);\n\t\treturn false;\n\t}\n\tapi[type] = instance;\n\tdiag.debug(\"@opentelemetry/api: Registered a global for \" + type + \" v\" + VERSION$1 + \".\");\n\treturn true;\n}\nfunction getGlobal(type) {\n\tvar _a, _b;\n\tvar globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;\n\tif (!globalVersion || !isCompatible(globalVersion)) return;\n\treturn (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];\n}\nfunction unregisterGlobal(type, diag) {\n\tdiag.debug(\"@opentelemetry/api: Unregistering a global for \" + type + \" v\" + VERSION$1 + \".\");\n\tvar api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\tif (api) delete api[type];\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js\nvar __read$3 = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray$3 = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\n/**\n* Component Logger which is meant to be used as part of any component which\n* will add automatically additional namespace in front of the log message.\n* It will then forward all message to global diag logger\n* @example\n* const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n* cLogger.debug('test');\n* // @opentelemetry/instrumentation-http test\n*/\nvar DiagComponentLogger = function() {\n\tfunction DiagComponentLogger(props) {\n\t\tthis._namespace = props.namespace || \"DiagComponentLogger\";\n\t}\n\tDiagComponentLogger.prototype.debug = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"debug\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.error = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"error\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.info = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"info\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.warn = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"warn\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.verbose = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"verbose\", this._namespace, args);\n\t};\n\treturn DiagComponentLogger;\n}();\nfunction logProxy(funcName, namespace, args) {\n\tvar logger = getGlobal(\"diag\");\n\tif (!logger) return;\n\targs.unshift(namespace);\n\treturn logger[funcName].apply(logger, __spreadArray$3([], __read$3(args), false));\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/diag/types.js\n/**\n* Defines the available internal logging levels for the diagnostic logger, the numeric values\n* of the levels are defined to match the original values from the initial LogLevel to avoid\n* compatibility/migration issues for any implementation that assume the numeric ordering.\n*/\nvar DiagLogLevel;\n(function(DiagLogLevel) {\n\t/** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n\tDiagLogLevel[DiagLogLevel[\"NONE\"] = 0] = \"NONE\";\n\t/** Identifies an error scenario */\n\tDiagLogLevel[DiagLogLevel[\"ERROR\"] = 30] = \"ERROR\";\n\t/** Identifies a warning scenario */\n\tDiagLogLevel[DiagLogLevel[\"WARN\"] = 50] = \"WARN\";\n\t/** General informational log message */\n\tDiagLogLevel[DiagLogLevel[\"INFO\"] = 60] = \"INFO\";\n\t/** General debug log message */\n\tDiagLogLevel[DiagLogLevel[\"DEBUG\"] = 70] = \"DEBUG\";\n\t/**\n\t* Detailed trace level logging should only be used for development, should only be set\n\t* in a development environment.\n\t*/\n\tDiagLogLevel[DiagLogLevel[\"VERBOSE\"] = 80] = \"VERBOSE\";\n\t/** Used to set the logging level to include all logging */\n\tDiagLogLevel[DiagLogLevel[\"ALL\"] = 9999] = \"ALL\";\n})(DiagLogLevel || (DiagLogLevel = {}));\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js\nfunction createLogLevelDiagLogger(maxLevel, logger) {\n\tif (maxLevel < DiagLogLevel.NONE) maxLevel = DiagLogLevel.NONE;\n\telse if (maxLevel > DiagLogLevel.ALL) maxLevel = DiagLogLevel.ALL;\n\tlogger = logger || {};\n\tfunction _filterFunc(funcName, theLevel) {\n\t\tvar theFunc = logger[funcName];\n\t\tif (typeof theFunc === \"function\" && maxLevel >= theLevel) return theFunc.bind(logger);\n\t\treturn function() {};\n\t}\n\treturn {\n\t\terror: _filterFunc(\"error\", DiagLogLevel.ERROR),\n\t\twarn: _filterFunc(\"warn\", DiagLogLevel.WARN),\n\t\tinfo: _filterFunc(\"info\", DiagLogLevel.INFO),\n\t\tdebug: _filterFunc(\"debug\", DiagLogLevel.DEBUG),\n\t\tverbose: _filterFunc(\"verbose\", DiagLogLevel.VERBOSE)\n\t};\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/api/diag.js\nvar __read$2 = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray$2 = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\nvar API_NAME$2 = \"diag\";\n/**\n* Singleton object which represents the entry point to the OpenTelemetry internal\n* diagnostic API\n*/\nvar DiagAPI = function() {\n\t/**\n\t* Private internal constructor\n\t* @private\n\t*/\n\tfunction DiagAPI() {\n\t\tfunction _logProxy(funcName) {\n\t\t\treturn function() {\n\t\t\t\tvar args = [];\n\t\t\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\t\t\tvar logger = getGlobal(\"diag\");\n\t\t\t\tif (!logger) return;\n\t\t\t\treturn logger[funcName].apply(logger, __spreadArray$2([], __read$2(args), false));\n\t\t\t};\n\t\t}\n\t\tvar self = this;\n\t\tvar setLogger = function(logger, optionsOrLogLevel) {\n\t\t\tvar _a, _b, _c;\n\t\t\tif (optionsOrLogLevel === void 0) optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };\n\t\t\tif (logger === self) {\n\t\t\t\tvar err = /* @__PURE__ */ new Error(\"Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation\");\n\t\t\t\tself.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (typeof optionsOrLogLevel === \"number\") optionsOrLogLevel = { logLevel: optionsOrLogLevel };\n\t\t\tvar oldLogger = getGlobal(\"diag\");\n\t\t\tvar newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);\n\t\t\tif (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n\t\t\t\tvar stack = (_c = (/* @__PURE__ */ new Error()).stack) !== null && _c !== void 0 ? _c : \"<failed to generate stacktrace>\";\n\t\t\t\toldLogger.warn(\"Current logger will be overwritten from \" + stack);\n\t\t\t\tnewLogger.warn(\"Current logger will overwrite one already registered from \" + stack);\n\t\t\t}\n\t\t\treturn registerGlobal(\"diag\", newLogger, self, true);\n\t\t};\n\t\tself.setLogger = setLogger;\n\t\tself.disable = function() {\n\t\t\tunregisterGlobal(API_NAME$2, self);\n\t\t};\n\t\tself.createComponentLogger = function(options) {\n\t\t\treturn new DiagComponentLogger(options);\n\t\t};\n\t\tself.verbose = _logProxy(\"verbose\");\n\t\tself.debug = _logProxy(\"debug\");\n\t\tself.info = _logProxy(\"info\");\n\t\tself.warn = _logProxy(\"warn\");\n\t\tself.error = _logProxy(\"error\");\n\t}\n\t/** Get the singleton instance of the DiagAPI API */\n\tDiagAPI.instance = function() {\n\t\tif (!this._instance) this._instance = new DiagAPI();\n\t\treturn this._instance;\n\t};\n\treturn DiagAPI;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/context/context.js\n/** Get a key to uniquely identify a context value */\nfunction createContextKey(description) {\n\treturn Symbol.for(description);\n}\n/** The root context is used as the default parent context when there is no active context */\nvar ROOT_CONTEXT = new (function() {\n\t/**\n\t* Construct a new context which inherits values from an optional parent context.\n\t*\n\t* @param parentContext a context from which to inherit values\n\t*/\n\tfunction BaseContext(parentContext) {\n\t\tvar self = this;\n\t\tself._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();\n\t\tself.getValue = function(key) {\n\t\t\treturn self._currentContext.get(key);\n\t\t};\n\t\tself.setValue = function(key, value) {\n\t\t\tvar context = new BaseContext(self._currentContext);\n\t\t\tcontext._currentContext.set(key, value);\n\t\t\treturn context;\n\t\t};\n\t\tself.deleteValue = function(key) {\n\t\t\tvar context = new BaseContext(self._currentContext);\n\t\t\tcontext._currentContext.delete(key);\n\t\t\treturn context;\n\t\t};\n\t}\n\treturn BaseContext;\n}())();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js\nvar __read$1 = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray$1 = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\nvar NoopContextManager = function() {\n\tfunction NoopContextManager() {}\n\tNoopContextManager.prototype.active = function() {\n\t\treturn ROOT_CONTEXT;\n\t};\n\tNoopContextManager.prototype.with = function(_context, fn, thisArg) {\n\t\tvar args = [];\n\t\tfor (var _i = 3; _i < arguments.length; _i++) args[_i - 3] = arguments[_i];\n\t\treturn fn.call.apply(fn, __spreadArray$1([thisArg], __read$1(args), false));\n\t};\n\tNoopContextManager.prototype.bind = function(_context, target) {\n\t\treturn target;\n\t};\n\tNoopContextManager.prototype.enable = function() {\n\t\treturn this;\n\t};\n\tNoopContextManager.prototype.disable = function() {\n\t\treturn this;\n\t};\n\treturn NoopContextManager;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/api/context.js\nvar __read = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\nvar API_NAME$1 = \"context\";\nvar NOOP_CONTEXT_MANAGER = new NoopContextManager();\n/**\n* Singleton object which represents the entry point to the OpenTelemetry Context API\n*/\nvar ContextAPI = function() {\n\t/** Empty private constructor prevents end users from constructing a new instance of the API */\n\tfunction ContextAPI() {}\n\t/** Get the singleton instance of the Context API */\n\tContextAPI.getInstance = function() {\n\t\tif (!this._instance) this._instance = new ContextAPI();\n\t\treturn this._instance;\n\t};\n\t/**\n\t* Set the current context manager.\n\t*\n\t* @returns true if the context manager was successfully registered, else false\n\t*/\n\tContextAPI.prototype.setGlobalContextManager = function(contextManager) {\n\t\treturn registerGlobal(API_NAME$1, contextManager, DiagAPI.instance());\n\t};\n\t/**\n\t* Get the currently active context\n\t*/\n\tContextAPI.prototype.active = function() {\n\t\treturn this._getContextManager().active();\n\t};\n\t/**\n\t* Execute a function with an active context\n\t*\n\t* @param context context to be active during function execution\n\t* @param fn function to execute in a context\n\t* @param thisArg optional receiver to be used for calling fn\n\t* @param args optional arguments forwarded to fn\n\t*/\n\tContextAPI.prototype.with = function(context, fn, thisArg) {\n\t\tvar _a;\n\t\tvar args = [];\n\t\tfor (var _i = 3; _i < arguments.length; _i++) args[_i - 3] = arguments[_i];\n\t\treturn (_a = this._getContextManager()).with.apply(_a, __spreadArray([\n\t\t\tcontext,\n\t\t\tfn,\n\t\t\tthisArg\n\t\t], __read(args), false));\n\t};\n\t/**\n\t* Bind a context to a target function or event emitter\n\t*\n\t* @param context context to bind to the event emitter or function. Defaults to the currently active context\n\t* @param target function or event emitter to bind\n\t*/\n\tContextAPI.prototype.bind = function(context, target) {\n\t\treturn this._getContextManager().bind(context, target);\n\t};\n\tContextAPI.prototype._getContextManager = function() {\n\t\treturn getGlobal(API_NAME$1) || NOOP_CONTEXT_MANAGER;\n\t};\n\t/** Disable and remove the global context manager */\n\tContextAPI.prototype.disable = function() {\n\t\tthis._getContextManager().disable();\n\t\tunregisterGlobal(API_NAME$1, DiagAPI.instance());\n\t};\n\treturn ContextAPI;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js\nvar TraceFlags;\n(function(TraceFlags) {\n\t/** Represents no flag set. */\n\tTraceFlags[TraceFlags[\"NONE\"] = 0] = \"NONE\";\n\t/** Bit to represent whether trace is sampled in trace flags. */\n\tTraceFlags[TraceFlags[\"SAMPLED\"] = 1] = \"SAMPLED\";\n})(TraceFlags || (TraceFlags = {}));\nvar INVALID_SPAN_CONTEXT = {\n\ttraceId: \"00000000000000000000000000000000\",\n\tspanId: \"0000000000000000\",\n\ttraceFlags: TraceFlags.NONE\n};\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js\n/**\n* The NonRecordingSpan is the default {@link Span} that is used when no Span\n* implementation is available. All operations are no-op including context\n* propagation.\n*/\nvar NonRecordingSpan = function() {\n\tfunction NonRecordingSpan(_spanContext) {\n\t\tif (_spanContext === void 0) _spanContext = INVALID_SPAN_CONTEXT;\n\t\tthis._spanContext = _spanContext;\n\t}\n\tNonRecordingSpan.prototype.spanContext = function() {\n\t\treturn this._spanContext;\n\t};\n\tNonRecordingSpan.prototype.setAttribute = function(_key, _value) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.setAttributes = function(_attributes) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.addEvent = function(_name, _attributes) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.addLink = function(_link) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.addLinks = function(_links) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.setStatus = function(_status) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.updateName = function(_name) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.end = function(_endTime) {};\n\tNonRecordingSpan.prototype.isRecording = function() {\n\t\treturn false;\n\t};\n\tNonRecordingSpan.prototype.recordException = function(_exception, _time) {};\n\treturn NonRecordingSpan;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js\n/**\n* span key\n*/\nvar SPAN_KEY = createContextKey(\"OpenTelemetry Context Key SPAN\");\n/**\n* Return the span if one exists\n*\n* @param context context to get span from\n*/\nfunction getSpan(context) {\n\treturn context.getValue(SPAN_KEY) || void 0;\n}\n/**\n* Gets the span from the current context, if one exists.\n*/\nfunction getActiveSpan() {\n\treturn getSpan(ContextAPI.getInstance().active());\n}\n/**\n* Set the span on a context\n*\n* @param context context to use as parent\n* @param span span to set active\n*/\nfunction setSpan(context, span) {\n\treturn context.setValue(SPAN_KEY, span);\n}\n/**\n* Remove current span stored in the context\n*\n* @param context context to delete span from\n*/\nfunction deleteSpan(context) {\n\treturn context.deleteValue(SPAN_KEY);\n}\n/**\n* Wrap span context in a NoopSpan and set as span in a new\n* context\n*\n* @param context context to set active span on\n* @param spanContext span context to be wrapped\n*/\nfunction setSpanContext(context, spanContext) {\n\treturn setSpan(context, new NonRecordingSpan(spanContext));\n}\n/**\n* Get the span context of the span if it exists.\n*\n* @param context context to get values from\n*/\nfunction getSpanContext(context) {\n\tvar _a;\n\treturn (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js\nvar VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nvar VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\nfunction isValidTraceId(traceId) {\n\treturn VALID_TRACEID_REGEX.test(traceId) && traceId !== \"00000000000000000000000000000000\";\n}\nfunction isValidSpanId(spanId) {\n\treturn VALID_SPANID_REGEX.test(spanId) && spanId !== \"0000000000000000\";\n}\n/**\n* Returns true if this {@link SpanContext} is valid.\n* @return true if this {@link SpanContext} is valid.\n*/\nfunction isSpanContextValid(spanContext) {\n\treturn isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);\n}\n/**\n* Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n*\n* @param spanContext span context to be wrapped\n* @returns a new non-recording {@link Span} with the provided context\n*/\nfunction wrapSpanContext(spanContext) {\n\treturn new NonRecordingSpan(spanContext);\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js\nvar contextApi = ContextAPI.getInstance();\n/**\n* No-op implementations of {@link Tracer}.\n*/\nvar NoopTracer = function() {\n\tfunction NoopTracer() {}\n\tNoopTracer.prototype.startSpan = function(name, options, context) {\n\t\tif (context === void 0) context = contextApi.active();\n\t\tif (Boolean(options === null || options === void 0 ? void 0 : options.root)) return new NonRecordingSpan();\n\t\tvar parentFromContext = context && getSpanContext(context);\n\t\tif (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan(parentFromContext);\n\t\telse return new NonRecordingSpan();\n\t};\n\tNoopTracer.prototype.startActiveSpan = function(name, arg2, arg3, arg4) {\n\t\tvar opts;\n\t\tvar ctx;\n\t\tvar fn;\n\t\tif (arguments.length < 2) return;\n\t\telse if (arguments.length === 2) fn = arg2;\n\t\telse if (arguments.length === 3) {\n\t\t\topts = arg2;\n\t\t\tfn = arg3;\n\t\t} else {\n\t\t\topts = arg2;\n\t\t\tctx = arg3;\n\t\t\tfn = arg4;\n\t\t}\n\t\tvar parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();\n\t\tvar span = this.startSpan(name, opts, parentContext);\n\t\tvar contextWithSpanSet = setSpan(parentContext, span);\n\t\treturn contextApi.with(contextWithSpanSet, fn, void 0, span);\n\t};\n\treturn NoopTracer;\n}();\nfunction isSpanContext(spanContext) {\n\treturn typeof spanContext === \"object\" && typeof spanContext[\"spanId\"] === \"string\" && typeof spanContext[\"traceId\"] === \"string\" && typeof spanContext[\"traceFlags\"] === \"number\";\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js\nvar NOOP_TRACER = new NoopTracer();\n/**\n* Proxy tracer provided by the proxy tracer provider\n*/\nvar ProxyTracer = function() {\n\tfunction ProxyTracer(_provider, name, version, options) {\n\t\tthis._provider = _provider;\n\t\tthis.name = name;\n\t\tthis.version = version;\n\t\tthis.options = options;\n\t}\n\tProxyTracer.prototype.startSpan = function(name, options, context) {\n\t\treturn this._getTracer().startSpan(name, options, context);\n\t};\n\tProxyTracer.prototype.startActiveSpan = function(_name, _options, _context, _fn) {\n\t\tvar tracer = this._getTracer();\n\t\treturn Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n\t};\n\t/**\n\t* Try to get a tracer from the proxy tracer provider.\n\t* If the proxy tracer provider has no delegate, return a noop tracer.\n\t*/\n\tProxyTracer.prototype._getTracer = function() {\n\t\tif (this._delegate) return this._delegate;\n\t\tvar tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);\n\t\tif (!tracer) return NOOP_TRACER;\n\t\tthis._delegate = tracer;\n\t\treturn this._delegate;\n\t};\n\treturn ProxyTracer;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js\nvar NOOP_TRACER_PROVIDER = new (function() {\n\tfunction NoopTracerProvider() {}\n\tNoopTracerProvider.prototype.getTracer = function(_name, _version, _options) {\n\t\treturn new NoopTracer();\n\t};\n\treturn NoopTracerProvider;\n}())();\n/**\n* Tracer provider which provides {@link ProxyTracer}s.\n*\n* Before a delegate is set, tracers provided are NoOp.\n* When a delegate is set, traces are provided from the delegate.\n* When a delegate is set after tracers have already been provided,\n* all tracers already provided will use the provided delegate implementation.\n*/\nvar ProxyTracerProvider = function() {\n\tfunction ProxyTracerProvider() {}\n\t/**\n\t* Get a {@link ProxyTracer}\n\t*/\n\tProxyTracerProvider.prototype.getTracer = function(name, version, options) {\n\t\tvar _a;\n\t\treturn (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);\n\t};\n\tProxyTracerProvider.prototype.getDelegate = function() {\n\t\tvar _a;\n\t\treturn (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;\n\t};\n\t/**\n\t* Set the delegate tracer provider\n\t*/\n\tProxyTracerProvider.prototype.setDelegate = function(delegate) {\n\t\tthis._delegate = delegate;\n\t};\n\tProxyTracerProvider.prototype.getDelegateTracer = function(name, version, options) {\n\t\tvar _a;\n\t\treturn (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);\n\t};\n\treturn ProxyTracerProvider;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/status.js\n/**\n* An enumeration of status codes.\n*/\nvar SpanStatusCode;\n(function(SpanStatusCode) {\n\t/**\n\t* The default status.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"UNSET\"] = 0] = \"UNSET\";\n\t/**\n\t* The operation has been validated by an Application developer or\n\t* Operator to have completed successfully.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"OK\"] = 1] = \"OK\";\n\t/**\n\t* The operation contains an error.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"ERROR\"] = 2] = \"ERROR\";\n})(SpanStatusCode || (SpanStatusCode = {}));\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/api/trace.js\nvar API_NAME = \"trace\";\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace-api.js\n/** Entrypoint for trace API */\nvar trace = function() {\n\t/** Empty private constructor prevents end users from constructing a new instance of the API */\n\tfunction TraceAPI() {\n\t\tthis._proxyTracerProvider = new ProxyTracerProvider();\n\t\tthis.wrapSpanContext = wrapSpanContext;\n\t\tthis.isSpanContextValid = isSpanContextValid;\n\t\tthis.deleteSpan = deleteSpan;\n\t\tthis.getSpan = getSpan;\n\t\tthis.getActiveSpan = getActiveSpan;\n\t\tthis.getSpanContext = getSpanContext;\n\t\tthis.setSpan = setSpan;\n\t\tthis.setSpanContext = setSpanContext;\n\t}\n\t/** Get the singleton instance of the Trace API */\n\tTraceAPI.getInstance = function() {\n\t\tif (!this._instance) this._instance = new TraceAPI();\n\t\treturn this._instance;\n\t};\n\t/**\n\t* Set the current global tracer.\n\t*\n\t* @returns true if the tracer provider was successfully registered, else false\n\t*/\n\tTraceAPI.prototype.setGlobalTracerProvider = function(provider) {\n\t\tvar success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());\n\t\tif (success) this._proxyTracerProvider.setDelegate(provider);\n\t\treturn success;\n\t};\n\t/**\n\t* Returns the global tracer provider.\n\t*/\n\tTraceAPI.prototype.getTracerProvider = function() {\n\t\treturn getGlobal(API_NAME) || this._proxyTracerProvider;\n\t};\n\t/**\n\t* Returns a tracer from the global tracer provider.\n\t*/\n\tTraceAPI.prototype.getTracer = function(name, version) {\n\t\treturn this.getTracerProvider().getTracer(name, version);\n\t};\n\t/** Remove the global tracer provider */\n\tTraceAPI.prototype.disable = function() {\n\t\tunregisterGlobal(API_NAME, DiagAPI.instance());\n\t\tthis._proxyTracerProvider = new ProxyTracerProvider();\n\t};\n\treturn TraceAPI;\n}().getInstance();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ai/5.0.216/5f111889467eb9ee9a591ae874be60ac4bd2e94fa67d32b6bdc9ee9980502377/node_modules/ai/dist/index.mjs\nvar __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n\tfor (var name16 in all) __defProp(target, name16, {\n\t\tget: all[name16],\n\t\tenumerable: true\n\t});\n};\nvar name = \"AI_NoOutputSpecifiedError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a;\nvar NoOutputSpecifiedError = class extends AISDKError {\n\tconstructor({ message = \"No output specified.\" } = {}) {\n\t\tsuper({\n\t\t\tname,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker);\n\t}\n};\n_a = symbol;\nfunction formatWarning(warning) {\n\tconst prefix = \"AI SDK Warning:\";\n\tswitch (warning.type) {\n\t\tcase \"unsupported-setting\": {\n\t\t\tlet message = `${prefix} The \"${warning.setting}\" setting is not supported by this model`;\n\t\t\tif (warning.details) message += ` - ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"unsupported-tool\": {\n\t\t\tlet message = `${prefix} The tool \"${\"name\" in warning.tool ? warning.tool.name : \"unknown tool\"}\" is not supported by this model`;\n\t\t\tif (warning.details) message += ` - ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"other\": return `${prefix} ${warning.message}`;\n\t\tdefault: return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n\t}\n}\nvar FIRST_WARNING_INFO_MESSAGE = \"AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.\";\nvar hasLoggedBefore = false;\nvar logWarnings = (warnings) => {\n\tif (warnings.length === 0) return;\n\tconst logger = globalThis.AI_SDK_LOG_WARNINGS;\n\tif (logger === false) return;\n\tif (typeof logger === \"function\") {\n\t\tlogger(warnings);\n\t\treturn;\n\t}\n\tif (!hasLoggedBefore) {\n\t\thasLoggedBefore = true;\n\t\tconsole.info(FIRST_WARNING_INFO_MESSAGE);\n\t}\n\tfor (const warning of warnings) console.warn(formatWarning(warning));\n};\nvar name2 = \"AI_InvalidArgumentError\";\nvar marker2 = `vercel.ai.error.${name2}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2;\nvar InvalidArgumentError = class extends AISDKError {\n\tconstructor({ parameter, value, message }) {\n\t\tsuper({\n\t\t\tname: name2,\n\t\t\tmessage: `Invalid argument for parameter ${parameter}: ${message}`\n\t\t});\n\t\tthis[_a2] = true;\n\t\tthis.parameter = parameter;\n\t\tthis.value = value;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker2);\n\t}\n};\n_a2 = symbol2;\nvar name3 = \"AI_InvalidStreamPartError\";\nvar marker3 = `vercel.ai.error.${name3}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3;\nvar InvalidStreamPartError = class extends AISDKError {\n\tconstructor({ chunk, message }) {\n\t\tsuper({\n\t\t\tname: name3,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a3] = true;\n\t\tthis.chunk = chunk;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker3);\n\t}\n};\n_a3 = symbol3;\nvar name4 = \"AI_InvalidToolInputError\";\nvar marker4 = `vercel.ai.error.${name4}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4;\nvar InvalidToolInputError = class extends AISDKError {\n\tconstructor({ toolInput, toolName, cause, message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name4,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a4] = true;\n\t\tthis.toolInput = toolInput;\n\t\tthis.toolName = toolName;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker4);\n\t}\n};\n_a4 = symbol4;\nvar name5 = \"AI_NoImageGeneratedError\";\nvar marker5 = `vercel.ai.error.${name5}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5;\nvar NoImageGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No image generated.\", cause, responses }) {\n\t\tsuper({\n\t\t\tname: name5,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a5] = true;\n\t\tthis.responses = responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker5);\n\t}\n};\n_a5 = symbol5;\nvar name6 = \"AI_NoObjectGeneratedError\";\nvar marker6 = `vercel.ai.error.${name6}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6;\nvar NoObjectGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No object generated.\", cause, text: text2, response, usage, finishReason }) {\n\t\tsuper({\n\t\t\tname: name6,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a6] = true;\n\t\tthis.text = text2;\n\t\tthis.response = response;\n\t\tthis.usage = usage;\n\t\tthis.finishReason = finishReason;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker6);\n\t}\n};\n_a6 = symbol6;\nvar name7 = \"AI_NoOutputGeneratedError\";\nvar marker7 = `vercel.ai.error.${name7}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7;\nvar NoOutputGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No output generated.\", cause } = {}) {\n\t\tsuper({\n\t\t\tname: name7,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a7] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker7);\n\t}\n};\n_a7 = symbol7;\nvar NoSpeechGeneratedError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_NoSpeechGeneratedError\",\n\t\t\tmessage: \"No speech audio generated.\"\n\t\t});\n\t\tthis.responses = options.responses;\n\t}\n};\nvar name8 = \"AI_NoSuchToolError\";\nvar marker8 = `vercel.ai.error.${name8}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8;\nvar NoSuchToolError = class extends AISDKError {\n\tconstructor({ toolName, availableTools = void 0, message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? \"No tools are available.\" : `Available tools: ${availableTools.join(\", \")}.`}` }) {\n\t\tsuper({\n\t\t\tname: name8,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a8] = true;\n\t\tthis.toolName = toolName;\n\t\tthis.availableTools = availableTools;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker8);\n\t}\n};\n_a8 = symbol8;\nvar name9 = \"AI_ToolCallRepairError\";\nvar marker9 = `vercel.ai.error.${name9}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9;\nvar ToolCallRepairError = class extends AISDKError {\n\tconstructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name9,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a9] = true;\n\t\tthis.originalError = originalError;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker9);\n\t}\n};\n_a9 = symbol9;\nvar UnsupportedModelVersionError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_UnsupportedModelVersionError\",\n\t\t\tmessage: `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". AI SDK 5 only supports models that implement specification version \"v2\".`\n\t\t});\n\t\tthis.version = options.version;\n\t\tthis.provider = options.provider;\n\t\tthis.modelId = options.modelId;\n\t}\n};\nvar name10 = \"AI_InvalidDataContentError\";\nvar marker10 = `vercel.ai.error.${name10}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10;\nvar InvalidDataContentError = class extends AISDKError {\n\tconstructor({ content, cause, message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.` }) {\n\t\tsuper({\n\t\t\tname: name10,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a10] = true;\n\t\tthis.content = content;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker10);\n\t}\n};\n_a10 = symbol10;\nvar name11 = \"AI_InvalidMessageRoleError\";\nvar marker11 = `vercel.ai.error.${name11}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11;\nvar InvalidMessageRoleError = class extends AISDKError {\n\tconstructor({ role, message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".` }) {\n\t\tsuper({\n\t\t\tname: name11,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a11] = true;\n\t\tthis.role = role;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker11);\n\t}\n};\n_a11 = symbol11;\nvar name12 = \"AI_MessageConversionError\";\nvar marker12 = `vercel.ai.error.${name12}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12;\nvar MessageConversionError = class extends AISDKError {\n\tconstructor({ originalMessage, message }) {\n\t\tsuper({\n\t\t\tname: name12,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a12] = true;\n\t\tthis.originalMessage = originalMessage;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker12);\n\t}\n};\n_a12 = symbol12;\nvar name13 = \"AI_DownloadError\";\nvar marker13 = `vercel.ai.error.${name13}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13;\nvar DownloadError = class extends AISDKError {\n\tconstructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {\n\t\tsuper({\n\t\t\tname: name13,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a13] = true;\n\t\tthis.url = url;\n\t\tthis.statusCode = statusCode;\n\t\tthis.statusText = statusText;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker13);\n\t}\n};\n_a13 = symbol13;\nvar name14 = \"AI_RetryError\";\nvar marker14 = `vercel.ai.error.${name14}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14;\nvar RetryError = class extends AISDKError {\n\tconstructor({ message, reason, errors }) {\n\t\tsuper({\n\t\t\tname: name14,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a14] = true;\n\t\tthis.reason = reason;\n\t\tthis.errors = errors;\n\t\tthis.lastError = errors[errors.length - 1];\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker14);\n\t}\n};\n_a14 = symbol14;\nfunction resolveLanguageModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\t\tversion: model.specificationVersion,\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId\n\t\t});\n\t\treturn model;\n\t}\n\treturn getGlobalProvider().languageModel(model);\n}\nfunction resolveEmbeddingModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\t\tversion: model.specificationVersion,\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId\n\t\t});\n\t\treturn model;\n\t}\n\treturn getGlobalProvider().textEmbeddingModel(model);\n}\nfunction resolveImageModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\t\tversion: model.specificationVersion,\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId\n\t\t});\n\t\treturn model;\n\t}\n\treturn getGlobalProvider().imageModel(model);\n}\nfunction getGlobalProvider() {\n\tvar _a16;\n\treturn (_a16 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a16 : gateway;\n}\nvar imageMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"image/gif\",\n\t\tbytesPrefix: [\n\t\t\t71,\n\t\t\t73,\n\t\t\t70\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/png\",\n\t\tbytesPrefix: [\n\t\t\t137,\n\t\t\t80,\n\t\t\t78,\n\t\t\t71\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/jpeg\",\n\t\tbytesPrefix: [255, 216]\n\t},\n\t{\n\t\tmediaType: \"image/webp\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t69,\n\t\t\t66,\n\t\t\t80\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/bmp\",\n\t\tbytesPrefix: [66, 77]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t73,\n\t\t\t73,\n\t\t\t42,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t77,\n\t\t\t77,\n\t\t\t0,\n\t\t\t42\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/avif\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t32,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t97,\n\t\t\t118,\n\t\t\t105,\n\t\t\t102\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/heic\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t32,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t104,\n\t\t\t101,\n\t\t\t105,\n\t\t\t99\n\t\t]\n\t}\n];\nvar audioMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 251]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 250]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 243]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 242]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 227]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 226]\n\t},\n\t{\n\t\tmediaType: \"audio/wav\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t65,\n\t\t\t86,\n\t\t\t69\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/ogg\",\n\t\tbytesPrefix: [\n\t\t\t79,\n\t\t\t103,\n\t\t\t103,\n\t\t\t83\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/flac\",\n\t\tbytesPrefix: [\n\t\t\t102,\n\t\t\t76,\n\t\t\t97,\n\t\t\t67\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [\n\t\t\t64,\n\t\t\t21,\n\t\t\t0,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/mp4\",\n\t\tbytesPrefix: [\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/webm\",\n\t\tbytesPrefix: [\n\t\t\t26,\n\t\t\t69,\n\t\t\t223,\n\t\t\t163\n\t\t]\n\t}\n];\nvar stripID3 = (data) => {\n\tconst bytes = typeof data === \"string\" ? convertBase64ToUint8Array(data) : data;\n\tconst id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;\n\treturn bytes.slice(id3Size + 10);\n};\nfunction stripID3TagsIfPresent(data) {\n\treturn typeof data === \"string\" && data.startsWith(\"SUQz\") || typeof data !== \"string\" && data.length > 10 && data[0] === 73 && data[1] === 68 && data[2] === 51 ? stripID3(data) : data;\n}\nfunction detectMediaType({ data, signatures }) {\n\tconst processedData = stripID3TagsIfPresent(data);\n\tconst bytes = typeof processedData === \"string\" ? convertBase64ToUint8Array(processedData.substring(0, Math.min(processedData.length, 24))) : processedData;\n\tfor (const signature of signatures) if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) return signature.mediaType;\n}\nvar VERSION = \"5.0.216\";\nvar download = async ({ url, maxBytes, abortSignal }) => {\n\tvar _a16;\n\tconst urlText = url.toString();\n\ttry {\n\t\tconst response = await fetchWithValidatedRedirects({\n\t\t\turl: urlText,\n\t\t\theaders: withUserAgentSuffix({}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tabortSignal\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError$1({\n\t\t\t\turl: urlText,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tstatusText: response.statusText\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tdata: await readResponseWithSizeLimit({\n\t\t\t\tresponse,\n\t\t\t\turl: urlText,\n\t\t\t\tmaxBytes: maxBytes != null ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE\n\t\t\t}),\n\t\t\tmediaType: (_a16 = response.headers.get(\"content-type\")) != null ? _a16 : void 0\n\t\t};\n\t} catch (error) {\n\t\tif (DownloadError$1.isInstance(error)) throw error;\n\t\tthrow new DownloadError$1({\n\t\t\turl: urlText,\n\t\t\tcause: error\n\t\t});\n\t}\n};\nvar createDefaultDownloadFunction = (download2 = download) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : download2(requestedDownload)));\nfunction splitDataUrl(dataUrl) {\n\ttry {\n\t\tconst [header, base64Content] = dataUrl.split(\",\");\n\t\treturn {\n\t\t\tmediaType: header.split(\";\")[0].split(\":\")[1],\n\t\t\tbase64Content\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tmediaType: void 0,\n\t\t\tbase64Content: void 0\n\t\t};\n\t}\n}\nvar dataContentSchema = z.union([\n\tz.string(),\n\tz.instanceof(Uint8Array),\n\tz.instanceof(ArrayBuffer),\n\tz.custom((value) => {\n\t\tvar _a16, _b;\n\t\treturn (_b = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b : false;\n\t}, { message: \"Must be a Buffer\" })\n]);\nfunction convertToLanguageModelV2DataContent(content) {\n\tif (content instanceof Uint8Array) return {\n\t\tdata: content,\n\t\tmediaType: void 0\n\t};\n\tif (content instanceof ArrayBuffer) return {\n\t\tdata: new Uint8Array(content),\n\t\tmediaType: void 0\n\t};\n\tif (typeof content === \"string\") try {\n\t\tcontent = new URL(content);\n\t} catch (error) {}\n\tif (content instanceof URL && content.protocol === \"data:\") {\n\t\tconst { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(content.toString());\n\t\tif (dataUrlMediaType == null || base64Content == null) throw new AISDKError({\n\t\t\tname: \"InvalidDataContentError\",\n\t\t\tmessage: `Invalid data URL format in content ${content.toString()}`\n\t\t});\n\t\treturn {\n\t\t\tdata: base64Content,\n\t\t\tmediaType: dataUrlMediaType\n\t\t};\n\t}\n\treturn {\n\t\tdata: content,\n\t\tmediaType: void 0\n\t};\n}\nfunction convertDataContentToBase64String(content) {\n\tif (typeof content === \"string\") return content;\n\tif (content instanceof ArrayBuffer) return convertUint8ArrayToBase64(new Uint8Array(content));\n\treturn convertUint8ArrayToBase64(content);\n}\nfunction convertDataContentToUint8Array(content) {\n\tif (content instanceof Uint8Array) return content;\n\tif (typeof content === \"string\") try {\n\t\treturn convertBase64ToUint8Array(content);\n\t} catch (error) {\n\t\tthrow new InvalidDataContentError({\n\t\t\tmessage: \"Invalid data content. Content string is not a base64-encoded media.\",\n\t\t\tcontent,\n\t\t\tcause: error\n\t\t});\n\t}\n\tif (content instanceof ArrayBuffer) return new Uint8Array(content);\n\tthrow new InvalidDataContentError({ content });\n}\nasync function convertToLanguageModelPrompt({ prompt, supportedUrls, download: download2 = createDefaultDownloadFunction() }) {\n\tconst downloadedAssets = await downloadAssets(prompt.messages, download2, supportedUrls);\n\treturn [...prompt.system != null ? [{\n\t\trole: \"system\",\n\t\tcontent: prompt.system\n\t}] : [], ...prompt.messages.map((message) => convertToLanguageModelMessage({\n\t\tmessage,\n\t\tdownloadedAssets\n\t}))];\n}\nfunction convertToLanguageModelMessage({ message, downloadedAssets }) {\n\tconst role = message.role;\n\tswitch (role) {\n\t\tcase \"system\": return {\n\t\t\trole: \"system\",\n\t\t\tcontent: message.content,\n\t\t\tproviderOptions: message.providerOptions\n\t\t};\n\t\tcase \"user\":\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\treturn {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== \"text\" || part.text !== \"\"),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\tcase \"assistant\":\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\treturn {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: message.content.filter((part) => part.type !== \"text\" || part.text !== \"\" || part.providerOptions != null).map((part) => {\n\t\t\t\t\tconst providerOptions = part.providerOptions;\n\t\t\t\t\tswitch (part.type) {\n\t\t\t\t\t\tcase \"file\": {\n\t\t\t\t\t\t\tconst { data, mediaType } = convertToLanguageModelV2DataContent(part.data);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\t\t\tmediaType: mediaType != null ? mediaType : part.mediaType,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"reasoning\": return {\n\t\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"text\": return {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-call\": return {\n\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-result\": return {\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\tcase \"tool\": return {\n\t\t\trole: \"tool\",\n\t\t\tcontent: message.content.map((part) => ({\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\toutput: part.output,\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t})),\n\t\t\tproviderOptions: message.providerOptions\n\t\t};\n\t\tdefault: throw new InvalidMessageRoleError({ role });\n\t}\n}\nasync function downloadAssets(messages, download2, supportedUrls) {\n\tconst plannedDownloads = messages.filter((message) => message.role === \"user\").map((message) => message.content).filter((content) => Array.isArray(content)).flat().filter((part) => part.type === \"image\" || part.type === \"file\").map((part) => {\n\t\tvar _a16;\n\t\tconst mediaType = (_a16 = part.mediaType) != null ? _a16 : part.type === \"image\" ? \"image/*\" : void 0;\n\t\tlet data = part.type === \"image\" ? part.image : part.data;\n\t\tif (typeof data === \"string\") try {\n\t\t\tdata = new URL(data);\n\t\t} catch (ignored) {}\n\t\treturn {\n\t\t\tmediaType,\n\t\t\tdata\n\t\t};\n\t}).filter((part) => part.data instanceof URL).map((part) => ({\n\t\turl: part.data,\n\t\tisUrlSupportedByModel: part.mediaType != null && isUrlSupported({\n\t\t\turl: part.data.toString(),\n\t\t\tmediaType: part.mediaType,\n\t\t\tsupportedUrls\n\t\t})\n\t}));\n\tconst downloadedFiles = await download2(plannedDownloads);\n\treturn Object.fromEntries(downloadedFiles.map((file, index) => file == null ? null : [plannedDownloads[index].url.toString(), {\n\t\tdata: file.data,\n\t\tmediaType: file.mediaType\n\t}]).filter((file) => file != null));\n}\nfunction convertPartToLanguageModelPart(part, downloadedAssets) {\n\tvar _a16;\n\tif (part.type === \"text\") return {\n\t\ttype: \"text\",\n\t\ttext: part.text,\n\t\tproviderOptions: part.providerOptions\n\t};\n\tlet originalData;\n\tconst type = part.type;\n\tswitch (type) {\n\t\tcase \"image\":\n\t\t\toriginalData = part.image;\n\t\t\tbreak;\n\t\tcase \"file\":\n\t\t\toriginalData = part.data;\n\t\t\tbreak;\n\t\tdefault: throw new Error(`Unsupported part type: ${type}`);\n\t}\n\tconst { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV2DataContent(originalData);\n\tlet mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;\n\tlet data = convertedData;\n\tif (data instanceof URL) {\n\t\tconst downloadedFile = downloadedAssets[data.toString()];\n\t\tif (downloadedFile) {\n\t\t\tdata = downloadedFile.data;\n\t\t\tmediaType ??= downloadedFile.mediaType;\n\t\t}\n\t}\n\tswitch (type) {\n\t\tcase \"image\":\n\t\t\tif (data instanceof Uint8Array || typeof data === \"string\") mediaType = (_a16 = detectMediaType({\n\t\t\t\tdata,\n\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t})) != null ? _a16 : mediaType;\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType: mediaType != null ? mediaType : \"image/*\",\n\t\t\t\tfilename: void 0,\n\t\t\t\tdata,\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t};\n\t\tcase \"file\":\n\t\t\tif (mediaType == null) throw new Error(`Media type is missing for file part`);\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType,\n\t\t\t\tfilename: part.filename,\n\t\t\t\tdata,\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t};\n\t}\n}\nfunction prepareCallSettings({ maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, seed, stopSequences }) {\n\tif (maxOutputTokens != null) {\n\t\tif (!Number.isInteger(maxOutputTokens)) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be an integer\"\n\t\t});\n\t\tif (maxOutputTokens < 1) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be >= 1\"\n\t\t});\n\t}\n\tif (temperature != null) {\n\t\tif (typeof temperature !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"temperature\",\n\t\t\tvalue: temperature,\n\t\t\tmessage: \"temperature must be a number\"\n\t\t});\n\t}\n\tif (topP != null) {\n\t\tif (typeof topP !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topP\",\n\t\t\tvalue: topP,\n\t\t\tmessage: \"topP must be a number\"\n\t\t});\n\t}\n\tif (topK != null) {\n\t\tif (typeof topK !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topK\",\n\t\t\tvalue: topK,\n\t\t\tmessage: \"topK must be a number\"\n\t\t});\n\t}\n\tif (presencePenalty != null) {\n\t\tif (typeof presencePenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"presencePenalty\",\n\t\t\tvalue: presencePenalty,\n\t\t\tmessage: \"presencePenalty must be a number\"\n\t\t});\n\t}\n\tif (frequencyPenalty != null) {\n\t\tif (typeof frequencyPenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"frequencyPenalty\",\n\t\t\tvalue: frequencyPenalty,\n\t\t\tmessage: \"frequencyPenalty must be a number\"\n\t\t});\n\t}\n\tif (seed != null) {\n\t\tif (!Number.isInteger(seed)) throw new InvalidArgumentError({\n\t\t\tparameter: \"seed\",\n\t\t\tvalue: seed,\n\t\t\tmessage: \"seed must be an integer\"\n\t\t});\n\t}\n\treturn {\n\t\tmaxOutputTokens,\n\t\ttemperature,\n\t\ttopP,\n\t\ttopK,\n\t\tpresencePenalty,\n\t\tfrequencyPenalty,\n\t\tstopSequences,\n\t\tseed\n\t};\n}\nfunction isNonEmptyObject(object2) {\n\treturn object2 != null && Object.keys(object2).length > 0;\n}\nfunction prepareToolsAndToolChoice({ tools, toolChoice, activeTools }) {\n\tif (!isNonEmptyObject(tools)) return {\n\t\ttools: void 0,\n\t\ttoolChoice: void 0\n\t};\n\treturn {\n\t\ttools: (activeTools != null ? Object.entries(tools).filter(([name16]) => activeTools.includes(name16)) : Object.entries(tools)).map(([name16, tool2]) => {\n\t\t\tconst toolType = tool2.type;\n\t\t\tswitch (toolType) {\n\t\t\t\tcase void 0:\n\t\t\t\tcase \"dynamic\":\n\t\t\t\tcase \"function\": return {\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tname: name16,\n\t\t\t\t\tdescription: tool2.description,\n\t\t\t\t\tinputSchema: asSchema(tool2.inputSchema).jsonSchema,\n\t\t\t\t\tproviderOptions: tool2.providerOptions\n\t\t\t\t};\n\t\t\t\tcase \"provider-defined\": return {\n\t\t\t\t\ttype: \"provider-defined\",\n\t\t\t\t\tname: name16,\n\t\t\t\t\tid: tool2.id,\n\t\t\t\t\targs: tool2.args\n\t\t\t\t};\n\t\t\t\tdefault: throw new Error(`Unsupported tool type: ${toolType}`);\n\t\t\t}\n\t\t}),\n\t\ttoolChoice: toolChoice == null ? { type: \"auto\" } : typeof toolChoice === \"string\" ? { type: toolChoice } : {\n\t\t\ttype: \"tool\",\n\t\t\ttoolName: toolChoice.toolName\n\t\t}\n\t};\n}\nvar jsonValueSchema = z.lazy(() => z.union([\n\tz.null(),\n\tz.string(),\n\tz.number(),\n\tz.boolean(),\n\tz.record(z.string(), jsonValueSchema),\n\tz.array(jsonValueSchema)\n]));\nvar providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema));\nvar textPartSchema = z.object({\n\ttype: z.literal(\"text\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar imagePartSchema = z.object({\n\ttype: z.literal(\"image\"),\n\timage: z.union([dataContentSchema, z.instanceof(URL)]),\n\tmediaType: z.string().optional(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar filePartSchema = z.object({\n\ttype: z.literal(\"file\"),\n\tdata: z.union([dataContentSchema, z.instanceof(URL)]),\n\tfilename: z.string().optional(),\n\tmediaType: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar reasoningPartSchema = z.object({\n\ttype: z.literal(\"reasoning\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar toolCallPartSchema = z.object({\n\ttype: z.literal(\"tool-call\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\tinput: z.unknown(),\n\tproviderOptions: providerMetadataSchema.optional(),\n\tproviderExecuted: z.boolean().optional()\n});\nvar outputSchema = z.discriminatedUnion(\"type\", [\n\tz.object({\n\t\ttype: z.literal(\"text\"),\n\t\tvalue: z.string()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"json\"),\n\t\tvalue: jsonValueSchema\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-text\"),\n\t\tvalue: z.string()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-json\"),\n\t\tvalue: jsonValueSchema\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"content\"),\n\t\tvalue: z.array(z.union([z.object({\n\t\t\ttype: z.literal(\"text\"),\n\t\t\ttext: z.string()\n\t\t}), z.object({\n\t\t\ttype: z.literal(\"media\"),\n\t\t\tdata: z.string(),\n\t\t\tmediaType: z.string()\n\t\t})]))\n\t})\n]);\nvar toolResultPartSchema = z.object({\n\ttype: z.literal(\"tool-result\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\toutput: outputSchema,\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar systemModelMessageSchema = z.object({\n\trole: z.literal(\"system\"),\n\tcontent: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreSystemMessageSchema = systemModelMessageSchema;\nvar userModelMessageSchema = z.object({\n\trole: z.literal(\"user\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\timagePartSchema,\n\t\tfilePartSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreUserMessageSchema = userModelMessageSchema;\nvar assistantModelMessageSchema = z.object({\n\trole: z.literal(\"assistant\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\tfilePartSchema,\n\t\treasoningPartSchema,\n\t\ttoolCallPartSchema,\n\t\ttoolResultPartSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreAssistantMessageSchema = assistantModelMessageSchema;\nvar toolModelMessageSchema = z.object({\n\trole: z.literal(\"tool\"),\n\tcontent: z.array(toolResultPartSchema),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreToolMessageSchema = toolModelMessageSchema;\nvar modelMessageSchema = z.union([\n\tsystemModelMessageSchema,\n\tuserModelMessageSchema,\n\tassistantModelMessageSchema,\n\ttoolModelMessageSchema\n]);\nvar coreMessageSchema = modelMessageSchema;\nasync function standardizePrompt({ allowSystemInMessages, system, prompt, messages }) {\n\tif (prompt == null && messages == null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (prompt != null && messages != null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt and messages cannot be defined at the same time\"\n\t});\n\tif (system != null && typeof system !== \"string\") throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"system must be a string\"\n\t});\n\tif (prompt != null && typeof prompt === \"string\") messages = [{\n\t\trole: \"user\",\n\t\tcontent: prompt\n\t}];\n\telse if (prompt != null && Array.isArray(prompt)) messages = prompt;\n\telse if (messages == null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (messages.length === 0) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"messages must not be empty\"\n\t});\n\tif (messages.some((message) => message.role === \"system\")) {\n\t\tif (allowSystemInMessages === false) throw new InvalidPromptError({\n\t\t\tprompt,\n\t\t\tmessage: \"System messages are not allowed in the prompt or messages fields. Use the system option instead.\"\n\t\t});\n\t\tif (allowSystemInMessages === void 0) console.warn(\"AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.\");\n\t}\n\tconst validationResult = await safeValidateTypes({\n\t\tvalue: messages,\n\t\tschema: z.array(modelMessageSchema)\n\t});\n\tif (!validationResult.success) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.\",\n\t\tcause: validationResult.error\n\t});\n\treturn {\n\t\tmessages,\n\t\tsystem\n\t};\n}\nfunction wrapGatewayError(error) {\n\tif (!GatewayAuthenticationError.isInstance(error)) return error;\n\tconst isProductionEnv = (process == null ? void 0 : \"production\") === \"production\";\n\tconst moreInfoURL = \"https://v5.ai-sdk.dev/unauthenticated-ai-gateway\";\n\tif (isProductionEnv) return new AISDKError({\n\t\tname: \"GatewayError\",\n\t\tmessage: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`\n\t});\n\treturn Object.assign(/* @__PURE__ */ new Error(`\\x1B[1m\\x1B[31mUnauthenticated request to AI Gateway.\\x1B[0m\n\nTo authenticate, set the \\x1B[33mAI_GATEWAY_API_KEY\\x1B[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\x1B[34m${moreInfoURL}\\x1B[0m\n\n`), { name: \"GatewayAuthenticationError\" });\n}\nfunction assembleOperationName({ operationId, telemetry }) {\n\treturn {\n\t\t\"operation.name\": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : \"\"}`,\n\t\t\"resource.name\": telemetry == null ? void 0 : telemetry.functionId,\n\t\t\"ai.operationId\": operationId,\n\t\t\"ai.telemetry.functionId\": telemetry == null ? void 0 : telemetry.functionId\n\t};\n}\nfunction getBaseTelemetryAttributes({ model, settings, telemetry, headers }) {\n\tvar _a16;\n\treturn {\n\t\t\"ai.model.provider\": model.provider,\n\t\t\"ai.model.id\": model.modelId,\n\t\t...Object.entries(settings).reduce((attributes, [key, value]) => {\n\t\t\tattributes[`ai.settings.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {}),\n\t\t...Object.entries((_a16 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a16 : {}).reduce((attributes, [key, value]) => {\n\t\t\tattributes[`ai.telemetry.metadata.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {}),\n\t\t...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {\n\t\t\tif (value !== void 0) attributes[`ai.request.headers.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {})\n\t};\n}\nvar noopTracer = {\n\tstartSpan() {\n\t\treturn noopSpan;\n\t},\n\tstartActiveSpan(name16, arg1, arg2, arg3) {\n\t\tif (typeof arg1 === \"function\") return arg1(noopSpan);\n\t\tif (typeof arg2 === \"function\") return arg2(noopSpan);\n\t\tif (typeof arg3 === \"function\") return arg3(noopSpan);\n\t}\n};\nvar noopSpan = {\n\tspanContext() {\n\t\treturn noopSpanContext;\n\t},\n\tsetAttribute() {\n\t\treturn this;\n\t},\n\tsetAttributes() {\n\t\treturn this;\n\t},\n\taddEvent() {\n\t\treturn this;\n\t},\n\taddLink() {\n\t\treturn this;\n\t},\n\taddLinks() {\n\t\treturn this;\n\t},\n\tsetStatus() {\n\t\treturn this;\n\t},\n\tupdateName() {\n\t\treturn this;\n\t},\n\tend() {\n\t\treturn this;\n\t},\n\tisRecording() {\n\t\treturn false;\n\t},\n\trecordException() {\n\t\treturn this;\n\t}\n};\nvar noopSpanContext = {\n\ttraceId: \"\",\n\tspanId: \"\",\n\ttraceFlags: 0\n};\nfunction getTracer({ isEnabled = false, tracer } = {}) {\n\tif (!isEnabled) return noopTracer;\n\tif (tracer) return tracer;\n\treturn trace.getTracer(\"ai\");\n}\nfunction recordSpan({ name: name16, tracer, attributes, fn, endWhenDone = true }) {\n\treturn tracer.startActiveSpan(name16, { attributes }, async (span) => {\n\t\ttry {\n\t\t\tconst result = await fn(span);\n\t\t\tif (endWhenDone) span.end();\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t} finally {\n\t\t\t\tspan.end();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t});\n}\nfunction recordErrorOnSpan(span, error) {\n\tif (error instanceof Error) {\n\t\tspan.recordException({\n\t\t\tname: error.name,\n\t\t\tmessage: error.message,\n\t\t\tstack: error.stack\n\t\t});\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error.message\n\t\t});\n\t} else span.setStatus({ code: SpanStatusCode.ERROR });\n}\nfunction selectTelemetryAttributes({ telemetry, attributes }) {\n\tif ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) return {};\n\treturn Object.entries(attributes).reduce((attributes2, [key, value]) => {\n\t\tif (value == null) return attributes2;\n\t\tif (typeof value === \"object\" && \"input\" in value && typeof value.input === \"function\") {\n\t\t\tif ((telemetry == null ? void 0 : telemetry.recordInputs) === false) return attributes2;\n\t\t\tconst result = value.input();\n\t\t\treturn result == null ? attributes2 : {\n\t\t\t\t...attributes2,\n\t\t\t\t[key]: result\n\t\t\t};\n\t\t}\n\t\tif (typeof value === \"object\" && \"output\" in value && typeof value.output === \"function\") {\n\t\t\tif ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) return attributes2;\n\t\t\tconst result = value.output();\n\t\t\treturn result == null ? attributes2 : {\n\t\t\t\t...attributes2,\n\t\t\t\t[key]: result\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...attributes2,\n\t\t\t[key]: value\n\t\t};\n\t}, {});\n}\nfunction stringifyForTelemetry(prompt) {\n\treturn JSON.stringify(prompt.map((message) => ({\n\t\t...message,\n\t\tcontent: typeof message.content === \"string\" ? message.content : message.content.map((part) => part.type === \"file\" ? {\n\t\t\t...part,\n\t\t\tdata: part.data instanceof Uint8Array ? convertDataContentToBase64String(part.data) : part.data\n\t\t} : part)\n\t})));\n}\nfunction addLanguageModelUsage(usage1, usage2) {\n\treturn {\n\t\tinputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n\t\toutputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n\t\ttotalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n\t\treasoningTokens: addTokenCounts(usage1.reasoningTokens, usage2.reasoningTokens),\n\t\tcachedInputTokens: addTokenCounts(usage1.cachedInputTokens, usage2.cachedInputTokens)\n\t};\n}\nfunction addTokenCounts(tokenCount1, tokenCount2) {\n\treturn tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);\n}\nfunction asArray(value) {\n\treturn value === void 0 ? [] : Array.isArray(value) ? value : [value];\n}\nfunction getRetryDelayInMs({ error, exponentialBackoffDelay }) {\n\tconst headers = error.responseHeaders;\n\tif (!headers) return exponentialBackoffDelay;\n\tlet ms;\n\tconst retryAfterMs = headers[\"retry-after-ms\"];\n\tif (retryAfterMs) {\n\t\tconst timeoutMs = parseFloat(retryAfterMs);\n\t\tif (!Number.isNaN(timeoutMs)) ms = timeoutMs;\n\t}\n\tconst retryAfter = headers[\"retry-after\"];\n\tif (retryAfter && ms === void 0) {\n\t\tconst timeoutSeconds = parseFloat(retryAfter);\n\t\tif (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;\n\t\telse ms = Date.parse(retryAfter) - Date.now();\n\t}\n\tif (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) return ms;\n\treturn exponentialBackoffDelay;\n}\nvar retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal } = {}) => async (f) => _retryWithExponentialBackoff(f, {\n\tmaxRetries,\n\tdelayInMs: initialDelayInMs,\n\tbackoffFactor,\n\tabortSignal\n});\nasync function _retryWithExponentialBackoff(f, { maxRetries, delayInMs, backoffFactor, abortSignal }, errors = []) {\n\ttry {\n\t\treturn await f();\n\t} catch (error) {\n\t\tif (isAbortError(error)) throw error;\n\t\tif (maxRetries === 0) throw error;\n\t\tconst errorMessage = getErrorMessage$1(error);\n\t\tconst newErrors = [...errors, error];\n\t\tconst tryNumber = newErrors.length;\n\t\tif (tryNumber > maxRetries) throw new RetryError({\n\t\t\tmessage: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n\t\t\treason: \"maxRetriesExceeded\",\n\t\t\terrors: newErrors\n\t\t});\n\t\tif (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {\n\t\t\tawait delay(getRetryDelayInMs({\n\t\t\t\terror,\n\t\t\t\texponentialBackoffDelay: delayInMs\n\t\t\t}), { abortSignal });\n\t\t\treturn _retryWithExponentialBackoff(f, {\n\t\t\t\tmaxRetries,\n\t\t\t\tdelayInMs: backoffFactor * delayInMs,\n\t\t\t\tbackoffFactor,\n\t\t\t\tabortSignal\n\t\t\t}, newErrors);\n\t\t}\n\t\tif (tryNumber === 1) throw error;\n\t\tthrow new RetryError({\n\t\t\tmessage: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n\t\t\treason: \"errorNotRetryable\",\n\t\t\terrors: newErrors\n\t\t});\n\t}\n}\nfunction prepareRetries({ maxRetries, abortSignal }) {\n\tif (maxRetries != null) {\n\t\tif (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxRetries\",\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: \"maxRetries must be an integer\"\n\t\t});\n\t\tif (maxRetries < 0) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxRetries\",\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: \"maxRetries must be >= 0\"\n\t\t});\n\t}\n\tconst maxRetriesResult = maxRetries != null ? maxRetries : 2;\n\treturn {\n\t\tmaxRetries: maxRetriesResult,\n\t\tretry: retryWithExponentialBackoffRespectingRetryHeaders({\n\t\t\tmaxRetries: maxRetriesResult,\n\t\t\tabortSignal\n\t\t})\n\t};\n}\nfunction extractTextContent(content) {\n\tconst parts = content.filter((content2) => content2.type === \"text\");\n\tif (parts.length === 0) return;\n\treturn parts.map((content2) => content2.text).join(\"\");\n}\nvar DefaultGeneratedFile = class {\n\tconstructor({ data, mediaType }) {\n\t\tconst isUint8Array = data instanceof Uint8Array;\n\t\tthis.base64Data = isUint8Array ? void 0 : data;\n\t\tthis.uint8ArrayData = isUint8Array ? data : void 0;\n\t\tthis.mediaType = mediaType;\n\t}\n\tget base64() {\n\t\tif (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);\n\t\treturn this.base64Data;\n\t}\n\tget uint8Array() {\n\t\tif (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);\n\t\treturn this.uint8ArrayData;\n\t}\n};\nvar DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {\n\tconstructor(options) {\n\t\tsuper(options);\n\t\tthis.type = \"file\";\n\t}\n};\nasync function parseToolCall({ toolCall, tools, repairToolCall, system, messages }) {\n\ttry {\n\t\tif (tools == null) throw new NoSuchToolError({ toolName: toolCall.toolName });\n\t\ttry {\n\t\t\treturn await doParseToolCall({\n\t\t\t\ttoolCall,\n\t\t\t\ttools\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) throw error;\n\t\t\tlet repairedToolCall = null;\n\t\t\ttry {\n\t\t\t\trepairedToolCall = await repairToolCall({\n\t\t\t\t\ttoolCall,\n\t\t\t\t\ttools,\n\t\t\t\t\tinputSchema: ({ toolName }) => {\n\t\t\t\t\t\tconst { inputSchema } = tools[toolName];\n\t\t\t\t\t\treturn asSchema(inputSchema).jsonSchema;\n\t\t\t\t\t},\n\t\t\t\t\tsystem,\n\t\t\t\t\tmessages,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t} catch (repairError) {\n\t\t\t\tthrow new ToolCallRepairError({\n\t\t\t\t\tcause: repairError,\n\t\t\t\t\toriginalError: error\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (repairedToolCall == null) throw error;\n\t\t\treturn await doParseToolCall({\n\t\t\t\ttoolCall: repairedToolCall,\n\t\t\t\ttools\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tconst parsedInput = await safeParseJSON({ text: toolCall.input });\n\t\tconst input = parsedInput.success ? parsedInput.value : toolCall.input;\n\t\treturn {\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\ttoolName: toolCall.toolName,\n\t\t\tinput,\n\t\t\tdynamic: true,\n\t\t\tinvalid: true,\n\t\t\terror,\n\t\t\tproviderMetadata: toolCall.providerMetadata\n\t\t};\n\t}\n}\nasync function doParseToolCall({ toolCall, tools }) {\n\tconst toolName = toolCall.toolName;\n\tconst tool2 = tools[toolName];\n\tif (tool2 == null) throw new NoSuchToolError({\n\t\ttoolName: toolCall.toolName,\n\t\tavailableTools: Object.keys(tools)\n\t});\n\tconst schema = asSchema(tool2.inputSchema);\n\tconst parseResult = toolCall.input.trim() === \"\" ? await safeValidateTypes({\n\t\tvalue: {},\n\t\tschema\n\t}) : await safeParseJSON({\n\t\ttext: toolCall.input,\n\t\tschema\n\t});\n\tif (parseResult.success === false) throw new InvalidToolInputError({\n\t\ttoolName,\n\t\ttoolInput: toolCall.input,\n\t\tcause: parseResult.error\n\t});\n\treturn tool2.type === \"dynamic\" ? {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata,\n\t\tdynamic: true\n\t} : {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata\n\t};\n}\nvar DefaultStepResult = class {\n\tconstructor({ content, finishReason, usage, warnings, request, response, providerMetadata }) {\n\t\tthis.content = content;\n\t\tthis.finishReason = finishReason;\n\t\tthis.usage = usage;\n\t\tthis.warnings = warnings;\n\t\tthis.request = request;\n\t\tthis.response = response;\n\t\tthis.providerMetadata = providerMetadata;\n\t}\n\tget text() {\n\t\treturn this.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\");\n\t}\n\tget reasoning() {\n\t\treturn this.content.filter((part) => part.type === \"reasoning\");\n\t}\n\tget reasoningText() {\n\t\treturn this.reasoning.length === 0 ? void 0 : this.reasoning.map((part) => part.text).join(\"\");\n\t}\n\tget files() {\n\t\treturn this.content.filter((part) => part.type === \"file\").map((part) => part.file);\n\t}\n\tget sources() {\n\t\treturn this.content.filter((part) => part.type === \"source\");\n\t}\n\tget toolCalls() {\n\t\treturn this.content.filter((part) => part.type === \"tool-call\");\n\t}\n\tget staticToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic !== true);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic === true);\n\t}\n\tget toolResults() {\n\t\treturn this.content.filter((part) => part.type === \"tool-result\");\n\t}\n\tget staticToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic !== true);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic === true);\n\t}\n};\nfunction stepCountIs(stepCount) {\n\treturn ({ steps }) => steps.length === stepCount;\n}\nfunction hasToolCall(toolName) {\n\treturn ({ steps }) => {\n\t\tvar _a16, _b, _c;\n\t\treturn (_c = (_b = (_a16 = steps[steps.length - 1]) == null ? void 0 : _a16.toolCalls) == null ? void 0 : _b.some((toolCall) => toolCall.toolName === toolName)) != null ? _c : false;\n\t};\n}\nasync function isStopConditionMet({ stopConditions, steps }) {\n\treturn (await Promise.all(stopConditions.map((condition) => condition({ steps })))).some((result) => result);\n}\nfunction createToolModelOutput({ output, tool: tool2, errorMode }) {\n\tif (errorMode === \"text\") return {\n\t\ttype: \"error-text\",\n\t\tvalue: getErrorMessage(output)\n\t};\n\telse if (errorMode === \"json\") return {\n\t\ttype: \"error-json\",\n\t\tvalue: toJSONValue(output)\n\t};\n\tif (tool2 == null ? void 0 : tool2.toModelOutput) return tool2.toModelOutput(output);\n\treturn typeof output === \"string\" ? {\n\t\ttype: \"text\",\n\t\tvalue: output\n\t} : {\n\t\ttype: \"json\",\n\t\tvalue: toJSONValue(output)\n\t};\n}\nfunction toJSONValue(value) {\n\treturn value === void 0 ? null : value;\n}\nfunction toResponseMessages({ content: inputContent, tools }) {\n\tconst responseMessages = [];\n\tconst content = inputContent.filter((part) => part.type !== \"source\").filter((part) => (part.type !== \"tool-result\" || part.providerExecuted) && (part.type !== \"tool-error\" || part.providerExecuted)).filter((part) => part.type !== \"text\" || part.text.length > 0).map((part) => {\n\t\tswitch (part.type) {\n\t\t\tcase \"text\": return {\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: part.text,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"reasoning\": return {\n\t\t\t\ttype: \"reasoning\",\n\t\t\t\ttext: part.text,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"file\": return {\n\t\t\t\ttype: \"file\",\n\t\t\t\tdata: part.file.base64,\n\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"tool-call\": return {\n\t\t\t\ttype: \"tool-call\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: part.input,\n\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"tool-result\": return {\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\ttool: tools == null ? void 0 : tools[part.toolName],\n\t\t\t\t\toutput: part.output,\n\t\t\t\t\terrorMode: \"none\"\n\t\t\t\t}),\n\t\t\t\tproviderExecuted: true,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"tool-error\": return {\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\ttool: tools == null ? void 0 : tools[part.toolName],\n\t\t\t\t\toutput: part.error,\n\t\t\t\t\terrorMode: \"json\"\n\t\t\t\t}),\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t}\n\t});\n\tif (content.length > 0) responseMessages.push({\n\t\trole: \"assistant\",\n\t\tcontent\n\t});\n\tconst toolResultContent = inputContent.filter((part) => part.type === \"tool-result\" || part.type === \"tool-error\").filter((part) => !part.providerExecuted).map((toolResult) => ({\n\t\ttype: \"tool-result\",\n\t\ttoolCallId: toolResult.toolCallId,\n\t\ttoolName: toolResult.toolName,\n\t\toutput: createToolModelOutput({\n\t\t\ttool: tools == null ? void 0 : tools[toolResult.toolName],\n\t\t\toutput: toolResult.type === \"tool-result\" ? toolResult.output : toolResult.error,\n\t\t\terrorMode: toolResult.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t}),\n\t\t...toolResult.providerMetadata != null ? { providerOptions: toolResult.providerMetadata } : {}\n\t}));\n\tif (toolResultContent.length > 0) responseMessages.push({\n\t\trole: \"tool\",\n\t\tcontent: toolResultContent\n\t});\n\treturn responseMessages;\n}\nvar originalGenerateId = createIdGenerator({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nasync function generateText$1({ model: modelArg, tools, toolChoice, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, headers, stopWhen = stepCountIs(1), experimental_output: output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools, activeTools = experimental_activeTools, experimental_prepareStep, prepareStep = experimental_prepareStep, experimental_repairToolCall: repairToolCall, experimental_download: download2, experimental_context, _internal: { generateId: generateId3 = originalGenerateId, currentDate = () => /* @__PURE__ */ new Date() } = {}, onStepFinish, ...settings }) {\n\tconst model = resolveLanguageModel(modelArg);\n\tconst stopConditions = asArray(stopWhen);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst callSettings = prepareCallSettings(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: {\n\t\t\t...callSettings,\n\t\t\tmaxRetries\n\t\t}\n\t});\n\tconst initialPrompt = await standardizePrompt({\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages\n\t});\n\tconst tracer = getTracer(telemetry);\n\ttry {\n\t\treturn await recordSpan({\n\t\t\tname: \"ai.generateText\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.generateText\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.model.provider\": model.provider,\n\t\t\t\t\t\"ai.model.id\": model.modelId,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\tvar _a16, _b, _c, _d, _e, _f, _g;\n\t\t\t\tconst callSettings2 = prepareCallSettings(settings);\n\t\t\t\tlet currentModelResponse;\n\t\t\t\tlet clientToolCalls = [];\n\t\t\t\tlet clientToolOutputs = [];\n\t\t\t\tconst responseMessages = [];\n\t\t\t\tconst steps = [];\n\t\t\t\tdo {\n\t\t\t\t\tconst stepInputMessages = [...initialPrompt.messages, ...responseMessages];\n\t\t\t\t\tconst prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsteps,\n\t\t\t\t\t\tstepNumber: steps.length,\n\t\t\t\t\t\tmessages: stepInputMessages\n\t\t\t\t\t}));\n\t\t\t\t\tconst stepModel = resolveLanguageModel((_a16 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a16 : model);\n\t\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\t\tprompt: {\n\t\t\t\t\t\t\tsystem: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n\t\t\t\t\t\t\tmessages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsupportedUrls: await stepModel.supportedUrls,\n\t\t\t\t\t\tdownload: download2\n\t\t\t\t\t});\n\t\t\t\t\tconst { toolChoice: stepToolChoice, tools: stepTools } = prepareToolsAndToolChoice({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\ttoolChoice: (_d = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _d : toolChoice,\n\t\t\t\t\t\tactiveTools: (_e = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _e : activeTools\n\t\t\t\t\t});\n\t\t\t\t\tcurrentModelResponse = await retry(() => {\n\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\t\tname: \"ai.generateText.doGenerate\",\n\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\toperationId: \"ai.generateText.doGenerate\",\n\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\t\"ai.model.provider\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"ai.model.id\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.tools\": { input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2)) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.toolChoice\": { input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0 },\n\t\t\t\t\t\t\t\t\t\"gen_ai.system\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.model\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": settings.frequencyPenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": settings.maxOutputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": settings.presencePenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.stop_sequences\": settings.stopSequences,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.temperature\": (_a17 = settings.temperature) != null ? _a17 : void 0,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_k\": settings.topK,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_p\": settings.topP\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\tfn: async (span2) => {\n\t\t\t\t\t\t\t\tvar _a18, _b2, _c2, _d2, _e2, _f2, _g2, _h;\n\t\t\t\t\t\t\t\tconst result = await stepModel.doGenerate({\n\t\t\t\t\t\t\t\t\t...callSettings2,\n\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\tresponseFormat: output == null ? void 0 : output.responseFormat,\n\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst responseData = {\n\t\t\t\t\t\t\t\t\tid: (_b2 = (_a18 = result.response) == null ? void 0 : _a18.id) != null ? _b2 : generateId3(),\n\t\t\t\t\t\t\t\t\ttimestamp: (_d2 = (_c2 = result.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : currentDate(),\n\t\t\t\t\t\t\t\t\tmodelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,\n\t\t\t\t\t\t\t\t\theaders: (_g2 = result.response) == null ? void 0 : _g2.headers,\n\t\t\t\t\t\t\t\t\tbody: (_h = result.response) == null ? void 0 : _h.body\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tspan2.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": result.finishReason,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.text\": { output: () => extractTextContent(result.content) },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\t\t\t\t\tconst toolCalls = asToolCalls(result.content);\n\t\t\t\t\t\t\t\t\t\t\treturn toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n\t\t\t\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": responseData.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(result.providerMetadata),\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.promptTokens\": result.usage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.completionTokens\": result.usage.outputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [result.finishReason],\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": result.usage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": result.usage.outputTokens\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\t\t\tresponse: responseData\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t\tconst stepToolCalls = await Promise.all(currentModelResponse.content.filter((part) => part.type === \"tool-call\").map((toolCall) => parseToolCall({\n\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tmessages: stepInputMessages\n\t\t\t\t\t})));\n\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\tif (toolCall.invalid) continue;\n\t\t\t\t\t\tconst tool2 = tools[toolCall.toolName];\n\t\t\t\t\t\tif (tool2.onInputStart != null) await tool2.onInputStart({\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.onInputAvailable) != null) await tool2.onInputAvailable({\n\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst invalidToolCalls = stepToolCalls.filter((toolCall) => toolCall.invalid && toolCall.dynamic);\n\t\t\t\t\tclientToolOutputs = [];\n\t\t\t\t\tfor (const toolCall of invalidToolCalls) clientToolOutputs.push({\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\terror: getErrorMessage$1(toolCall.error),\n\t\t\t\t\t\tdynamic: true\n\t\t\t\t\t});\n\t\t\t\t\tclientToolCalls = stepToolCalls.filter((toolCall) => !toolCall.providerExecuted);\n\t\t\t\t\tif (tools != null) clientToolOutputs.push(...await executeTools({\n\t\t\t\t\t\ttoolCalls: clientToolCalls.filter((toolCall) => !toolCall.invalid),\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t}));\n\t\t\t\t\tconst stepContent = asContent({\n\t\t\t\t\t\tcontent: currentModelResponse.content,\n\t\t\t\t\t\ttoolCalls: stepToolCalls,\n\t\t\t\t\t\ttoolOutputs: clientToolOutputs\n\t\t\t\t\t});\n\t\t\t\t\tresponseMessages.push(...toResponseMessages({\n\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\ttools\n\t\t\t\t\t}));\n\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\tfinishReason: currentModelResponse.finishReason,\n\t\t\t\t\t\tusage: currentModelResponse.usage,\n\t\t\t\t\t\twarnings: currentModelResponse.warnings,\n\t\t\t\t\t\tproviderMetadata: currentModelResponse.providerMetadata,\n\t\t\t\t\t\trequest: (_f = currentModelResponse.request) != null ? _f : {},\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t...currentModelResponse.response,\n\t\t\t\t\t\t\tmessages: structuredClone(responseMessages)\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tlogWarnings((_g = currentModelResponse.warnings) != null ? _g : []);\n\t\t\t\t\tsteps.push(currentStepResult);\n\t\t\t\t\tawait (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));\n\t\t\t\t} while (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length && !await isStopConditionMet({\n\t\t\t\t\tstopConditions,\n\t\t\t\t\tsteps\n\t\t\t\t}));\n\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.response.finishReason\": currentModelResponse.finishReason,\n\t\t\t\t\t\t\"ai.response.text\": { output: () => extractTextContent(currentModelResponse.content) },\n\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\tconst toolCalls = asToolCalls(currentModelResponse.content);\n\t\t\t\t\t\t\treturn toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n\t\t\t\t\t\t} },\n\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(currentModelResponse.providerMetadata),\n\t\t\t\t\t\t\"ai.usage.promptTokens\": currentModelResponse.usage.inputTokens,\n\t\t\t\t\t\t\"ai.usage.completionTokens\": currentModelResponse.usage.outputTokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tconst lastStep = steps[steps.length - 1];\n\t\t\t\tlet resolvedOutput;\n\t\t\t\tif (lastStep.finishReason === \"stop\") resolvedOutput = await (output == null ? void 0 : output.parseOutput({ text: lastStep.text }, {\n\t\t\t\t\tresponse: lastStep.response,\n\t\t\t\t\tusage: lastStep.usage,\n\t\t\t\t\tfinishReason: lastStep.finishReason\n\t\t\t\t}));\n\t\t\t\treturn new DefaultGenerateTextResult({\n\t\t\t\t\tsteps,\n\t\t\t\t\tresolvedOutput\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nasync function executeTools({ toolCalls, tools, tracer, telemetry, messages, abortSignal, experimental_context }) {\n\treturn (await Promise.all(toolCalls.map(async ({ toolCallId, toolName, input }) => {\n\t\tconst tool2 = tools[toolName];\n\t\tif ((tool2 == null ? void 0 : tool2.execute) == null) return;\n\t\treturn recordSpan({\n\t\t\tname: \"ai.toolCall\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.toolCall\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t\"ai.toolCall.name\": toolName,\n\t\t\t\t\t\"ai.toolCall.id\": toolCallId,\n\t\t\t\t\t\"ai.toolCall.args\": { output: () => JSON.stringify(input) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst stream = executeTool({\n\t\t\t\t\t\texecute: tool2.execute.bind(tool2),\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tlet output;\n\t\t\t\t\tfor await (const part of stream) if (part.type === \"final\") output = part.output;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: { \"ai.toolCall.result\": { output: () => JSON.stringify(output) } }\n\t\t\t\t\t\t}));\n\t\t\t\t\t} catch (ignored) {}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\toutput,\n\t\t\t\t\t\tdynamic: tool2.type === \"dynamic\"\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tdynamic: tool2.type === \"dynamic\"\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}))).filter((output) => output != null);\n}\nvar DefaultGenerateTextResult = class {\n\tconstructor(options) {\n\t\tthis.steps = options.steps;\n\t\tthis.resolvedOutput = options.resolvedOutput;\n\t}\n\tget finalStep() {\n\t\treturn this.steps[this.steps.length - 1];\n\t}\n\tget content() {\n\t\treturn this.finalStep.content;\n\t}\n\tget text() {\n\t\treturn this.finalStep.text;\n\t}\n\tget files() {\n\t\treturn this.finalStep.files;\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.reasoningText;\n\t}\n\tget reasoning() {\n\t\treturn this.finalStep.reasoning;\n\t}\n\tget toolCalls() {\n\t\treturn this.finalStep.toolCalls;\n\t}\n\tget staticToolCalls() {\n\t\treturn this.finalStep.staticToolCalls;\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.finalStep.dynamicToolCalls;\n\t}\n\tget toolResults() {\n\t\treturn this.finalStep.toolResults;\n\t}\n\tget staticToolResults() {\n\t\treturn this.finalStep.staticToolResults;\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.finalStep.dynamicToolResults;\n\t}\n\tget sources() {\n\t\treturn this.finalStep.sources;\n\t}\n\tget finishReason() {\n\t\treturn this.finalStep.finishReason;\n\t}\n\tget warnings() {\n\t\treturn this.finalStep.warnings;\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.providerMetadata;\n\t}\n\tget response() {\n\t\treturn this.finalStep.response;\n\t}\n\tget request() {\n\t\treturn this.finalStep.request;\n\t}\n\tget usage() {\n\t\treturn this.finalStep.usage;\n\t}\n\tget totalUsage() {\n\t\treturn this.steps.reduce((totalUsage, step) => {\n\t\t\treturn addLanguageModelUsage(totalUsage, step.usage);\n\t\t}, {\n\t\t\tinputTokens: void 0,\n\t\t\toutputTokens: void 0,\n\t\t\ttotalTokens: void 0,\n\t\t\treasoningTokens: void 0,\n\t\t\tcachedInputTokens: void 0\n\t\t});\n\t}\n\tget experimental_output() {\n\t\tif (this.resolvedOutput == null) throw new NoOutputSpecifiedError();\n\t\treturn this.resolvedOutput;\n\t}\n};\nfunction asToolCalls(content) {\n\tconst parts = content.filter((part) => part.type === \"tool-call\");\n\tif (parts.length === 0) return;\n\treturn parts.map((toolCall) => ({\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: toolCall.input\n\t}));\n}\nfunction asContent({ content, toolCalls, toolOutputs }) {\n\treturn [...content.map((part) => {\n\t\tswitch (part.type) {\n\t\t\tcase \"text\":\n\t\t\tcase \"reasoning\":\n\t\t\tcase \"source\": return part;\n\t\t\tcase \"file\": return {\n\t\t\t\ttype: \"file\",\n\t\t\t\tfile: new DefaultGeneratedFile(part)\n\t\t\t};\n\t\t\tcase \"tool-call\": return toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);\n\t\t\tcase \"tool-result\": {\n\t\t\t\tconst toolCall = toolCalls.find((toolCall2) => toolCall2.toolCallId === part.toolCallId);\n\t\t\t\tif (toolCall == null) throw new Error(`Tool call ${part.toolCallId} not found.`);\n\t\t\t\tif (part.isError) return {\n\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\terror: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: toolCall.dynamic\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\toutput: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: toolCall.dynamic\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}), ...toolOutputs];\n}\nfunction prepareHeaders(headers, defaultHeaders) {\n\tconst responseHeaders = new Headers(headers != null ? headers : {});\n\tfor (const [key, value] of Object.entries(defaultHeaders)) if (!responseHeaders.has(key)) responseHeaders.set(key, value);\n\treturn responseHeaders;\n}\nfunction createTextStreamResponse({ status, statusText, headers, textStream }) {\n\treturn new Response(textStream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus: status != null ? status : 200,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" })\n\t});\n}\nfunction writeToServerResponse({ response, status, statusText, headers, stream }) {\n\tconst statusCode = status != null ? status : 200;\n\tif (statusText !== void 0) response.writeHead(statusCode, statusText, headers);\n\telse response.writeHead(statusCode, headers);\n\tconst reader = stream.getReader();\n\tconst read = async () => {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!response.write(value)) await new Promise((resolve2) => {\n\t\t\t\t\tresponse.once(\"drain\", resolve2);\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tresponse.end();\n\t\t}\n\t};\n\tread();\n}\nfunction pipeTextStreamToResponse({ response, status, statusText, headers, textStream }) {\n\twriteToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: Object.fromEntries(prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" }).entries()),\n\t\tstream: textStream.pipeThrough(new TextEncoderStream())\n\t});\n}\nvar JsonToSseTransformStream = class extends TransformStream {\n\tconstructor() {\n\t\tsuper({\n\t\t\ttransform(part, controller) {\n\t\t\t\tcontroller.enqueue(`data: ${JSON.stringify(part)}\n\n`);\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tcontroller.enqueue(\"data: [DONE]\\n\\n\");\n\t\t\t}\n\t\t});\n\t}\n};\nvar UI_MESSAGE_STREAM_HEADERS = {\n\t\"content-type\": \"text/event-stream\",\n\t\"cache-control\": \"no-cache\",\n\tconnection: \"keep-alive\",\n\t\"x-vercel-ai-ui-message-stream\": \"v1\",\n\t\"x-accel-buffering\": \"no\"\n};\nfunction createUIMessageStreamResponse({ status, statusText, headers, stream, consumeSseStream }) {\n\tlet sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\treturn new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)\n\t});\n}\nfunction getResponseUIMessageId({ originalMessages, responseMessageId }) {\n\tif (originalMessages == null) return;\n\tconst lastMessage = originalMessages[originalMessages.length - 1];\n\treturn (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage.id : typeof responseMessageId === \"function\" ? responseMessageId() : responseMessageId;\n}\nvar uiMessageChunkSchema = lazyValidator(() => zodSchema(z.union([\n\tz.strictObject({\n\t\ttype: z.literal(\"text-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"text-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"text-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"error\"),\n\t\terrorText: z.string()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"tool-input-start\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"tool-input-delta\"),\n\t\ttoolCallId: z.string(),\n\t\tinputTextDelta: z.string()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"tool-input-available\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"tool-input-error\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\terrorText: z.string()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"tool-output-available\"),\n\t\ttoolCallId: z.string(),\n\t\toutput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\tpreliminary: z.boolean().optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"tool-output-error\"),\n\t\ttoolCallId: z.string(),\n\t\terrorText: z.string(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"reasoning-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"reasoning-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"reasoning-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"source-url\"),\n\t\tsourceId: z.string(),\n\t\turl: z.string(),\n\t\ttitle: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"source-document\"),\n\t\tsourceId: z.string(),\n\t\tmediaType: z.string(),\n\t\ttitle: z.string(),\n\t\tfilename: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"file\"),\n\t\turl: z.string(),\n\t\tmediaType: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.custom((value) => typeof value === \"string\" && value.startsWith(\"data-\"), { message: \"Type must start with \\\"data-\\\"\" }),\n\t\tid: z.string().optional(),\n\t\tdata: z.unknown(),\n\t\ttransient: z.boolean().optional()\n\t}),\n\tz.strictObject({ type: z.literal(\"start-step\") }),\n\tz.strictObject({ type: z.literal(\"finish-step\") }),\n\tz.strictObject({\n\t\ttype: z.literal(\"start\"),\n\t\tmessageId: z.string().optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.strictObject({\n\t\ttype: z.literal(\"finish\"),\n\t\tfinishReason: z.enum([\n\t\t\t\"stop\",\n\t\t\t\"length\",\n\t\t\t\"content-filter\",\n\t\t\t\"tool-calls\",\n\t\t\t\"error\",\n\t\t\t\"other\",\n\t\t\t\"unknown\"\n\t\t]).optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.strictObject({ type: z.literal(\"abort\") }),\n\tz.strictObject({\n\t\ttype: z.literal(\"message-metadata\"),\n\t\tmessageMetadata: z.unknown()\n\t})\n])));\nfunction isDataUIMessageChunk(chunk) {\n\treturn chunk.type.startsWith(\"data-\");\n}\nfunction createIdMap() {\n\treturn /* @__PURE__ */ Object.create(null);\n}\nfunction mergeObjects(base, overrides) {\n\tif (base === void 0 && overrides === void 0) return;\n\tif (base === void 0) return overrides;\n\tif (overrides === void 0) return base;\n\tconst result = { ...base };\n\tfor (const key in overrides) {\n\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n\t\tif (Object.prototype.hasOwnProperty.call(overrides, key)) {\n\t\t\tconst overridesValue = overrides[key];\n\t\t\tif (overridesValue === void 0) continue;\n\t\t\tconst baseValue = key in base ? base[key] : void 0;\n\t\t\tconst isSourceObject = overridesValue !== null && typeof overridesValue === \"object\" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);\n\t\t\tconst isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === \"object\" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);\n\t\t\tif (isSourceObject && isTargetObject) result[key] = mergeObjects(baseValue, overridesValue);\n\t\t\telse result[key] = overridesValue;\n\t\t}\n\t}\n\treturn result;\n}\nfunction fixJson(input) {\n\tconst stack = [\"ROOT\"];\n\tlet lastValidIndex = -1;\n\tlet literalStart = null;\n\tfunction processValueStart(char, i, swapState) {\n\t\tswitch (char) {\n\t\t\tcase \"\\\"\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_STRING\");\n\t\t\t\tbreak;\n\t\t\tcase \"f\":\n\t\t\tcase \"t\":\n\t\t\tcase \"n\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tliteralStart = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_LITERAL\");\n\t\t\t\tbreak;\n\t\t\tcase \"-\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"0\":\n\t\t\tcase \"1\":\n\t\t\tcase \"2\":\n\t\t\tcase \"3\":\n\t\t\tcase \"4\":\n\t\t\tcase \"5\":\n\t\t\tcase \"6\":\n\t\t\tcase \"7\":\n\t\t\tcase \"8\":\n\t\t\tcase \"9\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"{\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_OBJECT_START\");\n\t\t\t\tbreak;\n\t\t\tcase \"[\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_ARRAY_START\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfunction processAfterObjectValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"}\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfunction processAfterArrayValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"]\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfor (let i = 0; i < input.length; i++) {\n\t\tconst char = input[i];\n\t\tswitch (stack[stack.length - 1]) {\n\t\t\tcase \"ROOT\":\n\t\t\t\tprocessValueStart(char, i, \"FINISH\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \":\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_BEFORE_VALUE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_OBJECT_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\t\tprocessAfterObjectValue(char, i);\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"\\\\\":\n\t\t\t\t\t\tstack.push(\"INSIDE_STRING_ESCAPE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: lastValidIndex = i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING_ESCAPE\":\n\t\t\t\tstack.pop();\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_NUMBER\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"0\":\n\t\t\t\t\tcase \"1\":\n\t\t\t\t\tcase \"2\":\n\t\t\t\t\tcase \"3\":\n\t\t\t\t\tcase \"4\":\n\t\t\t\t\tcase \"5\":\n\t\t\t\t\tcase \"6\":\n\t\t\t\t\tcase \"7\":\n\t\t\t\t\tcase \"8\":\n\t\t\t\t\tcase \"9\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"e\":\n\t\t\t\t\tcase \"E\":\n\t\t\t\t\tcase \"-\":\n\t\t\t\t\tcase \".\": break;\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_LITERAL\": {\n\t\t\t\tconst partialLiteral = input.substring(literalStart, i + 1);\n\t\t\t\tif (!\"false\".startsWith(partialLiteral) && !\"true\".startsWith(partialLiteral) && !\"null\".startsWith(partialLiteral)) {\n\t\t\t\t\tstack.pop();\n\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\telse if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t} else lastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tlet result = input.slice(0, lastValidIndex + 1);\n\tfor (let i = stack.length - 1; i >= 0; i--) switch (stack[i]) {\n\t\tcase \"INSIDE_STRING\":\n\t\t\tresult += \"\\\"\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\tcase \"INSIDE_OBJECT_START\":\n\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\tresult += \"}\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_ARRAY_START\":\n\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\tresult += \"]\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_LITERAL\": {\n\t\t\tconst partialLiteral = input.substring(literalStart, input.length);\n\t\t\tif (\"true\".startsWith(partialLiteral)) result += \"true\".slice(partialLiteral.length);\n\t\t\telse if (\"false\".startsWith(partialLiteral)) result += \"false\".slice(partialLiteral.length);\n\t\t\telse if (\"null\".startsWith(partialLiteral)) result += \"null\".slice(partialLiteral.length);\n\t\t}\n\t}\n\treturn result;\n}\nasync function parsePartialJson(jsonText) {\n\tif (jsonText === void 0) return {\n\t\tvalue: void 0,\n\t\tstate: \"undefined-input\"\n\t};\n\tlet result = await safeParseJSON({ text: jsonText });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"successful-parse\"\n\t};\n\tresult = await safeParseJSON({ text: fixJson(jsonText) });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"repaired-parse\"\n\t};\n\treturn {\n\t\tvalue: void 0,\n\t\tstate: \"failed-parse\"\n\t};\n}\nfunction isDataUIPart(part) {\n\treturn part.type.startsWith(\"data-\");\n}\nfunction isTextUIPart(part) {\n\treturn part.type === \"text\";\n}\nfunction isFileUIPart(part) {\n\treturn part.type === \"file\";\n}\nfunction isReasoningUIPart(part) {\n\treturn part.type === \"reasoning\";\n}\nfunction isToolUIPart(part) {\n\treturn part.type.startsWith(\"tool-\");\n}\nfunction isDynamicToolUIPart(part) {\n\treturn part.type === \"dynamic-tool\";\n}\nfunction isToolOrDynamicToolUIPart(part) {\n\treturn isToolUIPart(part) || isDynamicToolUIPart(part);\n}\nfunction getToolName(part) {\n\treturn part.type.split(\"-\").slice(1).join(\"-\");\n}\nfunction getToolOrDynamicToolName(part) {\n\treturn isDynamicToolUIPart(part) ? part.toolName : getToolName(part);\n}\nfunction createStreamingUIMessageState({ lastMessage, messageId }) {\n\treturn {\n\t\tmessage: (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage : {\n\t\t\tid: messageId,\n\t\t\tmetadata: void 0,\n\t\t\trole: \"assistant\",\n\t\t\tparts: []\n\t\t},\n\t\tactiveTextParts: createIdMap(),\n\t\tactiveReasoningParts: createIdMap(),\n\t\tpartialToolCalls: createIdMap()\n\t};\n}\nfunction processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas, runUpdateMessageJob, onError, onToolCall, onData }) {\n\treturn stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\tawait runUpdateMessageJob(async ({ state, write }) => {\n\t\t\tvar _a16, _b, _c, _d;\n\t\t\tfunction getToolInvocation(toolCallId) {\n\t\t\t\tconst toolInvocation = state.message.parts.filter(isToolUIPart).find((invocation) => invocation.toolCallId === toolCallId);\n\t\t\t\tif (toolInvocation == null) throw new Error(\"tool-output-error must be preceded by a tool-input-available\");\n\t\t\t\treturn toolInvocation;\n\t\t\t}\n\t\t\tfunction getDynamicToolInvocation(toolCallId) {\n\t\t\t\tconst toolInvocation = state.message.parts.filter((part) => part.type === \"dynamic-tool\").find((invocation) => invocation.toolCallId === toolCallId);\n\t\t\t\tif (toolInvocation == null) throw new Error(\"tool-output-error must be preceded by a tool-input-available\");\n\t\t\t\treturn toolInvocation;\n\t\t\t}\n\t\t\tfunction updateToolPart(options) {\n\t\t\t\tvar _a17;\n\t\t\t\tconst part = state.message.parts.find((part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = anyOptions.rawInput;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tanyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;\n\t\t\t\t\tif (anyOptions.providerMetadata != null && part.state === \"input-available\") part.callProviderMetadata = anyOptions.providerMetadata;\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: `tool-${options.toolName}`,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\trawInput: anyOptions.rawInput,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\t...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tfunction updateDynamicToolPart(options) {\n\t\t\t\tvar _a17, _b2;\n\t\t\t\tconst part = state.message.parts.find((part2) => part2.type === \"dynamic-tool\" && part2.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.toolName = options.toolName;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = (_a17 = anyOptions.rawInput) != null ? _a17 : anyPart.rawInput;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tanyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;\n\t\t\t\t\tif (anyOptions.providerMetadata != null && part.state === \"input-available\") part.callProviderMetadata = anyOptions.providerMetadata;\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: \"dynamic-tool\",\n\t\t\t\t\ttoolName: options.toolName,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\t...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tasync function updateMessageMetadata(metadata) {\n\t\t\t\tif (metadata != null) {\n\t\t\t\t\tconst mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;\n\t\t\t\t\tif (messageMetadataSchema != null) await validateTypes({\n\t\t\t\t\t\tvalue: mergedMetadata,\n\t\t\t\t\t\tschema: messageMetadataSchema\n\t\t\t\t\t});\n\t\t\t\t\tstate.message.metadata = mergedMetadata;\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-start\": {\n\t\t\t\t\tconst textPart = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeTextParts[chunk.id] = textPart;\n\t\t\t\t\tstate.message.parts.push(textPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-delta\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\ttextPart.text += chunk.delta;\n\t\t\t\t\ttextPart.providerMetadata = (_a16 = chunk.providerMetadata) != null ? _a16 : textPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-end\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\ttextPart.state = \"done\";\n\t\t\t\t\ttextPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;\n\t\t\t\t\tdelete state.activeTextParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\tconst reasoningPart = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeReasoningParts[chunk.id] = reasoningPart;\n\t\t\t\t\tstate.message.parts.push(reasoningPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-delta\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\treasoningPart.text += chunk.delta;\n\t\t\t\t\treasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-end\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\treasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;\n\t\t\t\t\treasoningPart.state = \"done\";\n\t\t\t\t\tdelete state.activeReasoningParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"file\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\turl: chunk.url\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-url\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-url\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\turl: chunk.url,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-document\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-document\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tfilename: chunk.filename,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\tconst toolInvocations = state.message.parts.filter(isToolUIPart);\n\t\t\t\t\tstate.partialToolCalls[chunk.toolCallId] = {\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tindex: toolInvocations.length,\n\t\t\t\t\t\tdynamic: chunk.dynamic\n\t\t\t\t\t};\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-delta\": {\n\t\t\t\t\tconst partialToolCall = state.partialToolCalls[chunk.toolCallId];\n\t\t\t\t\tpartialToolCall.text += chunk.inputTextDelta;\n\t\t\t\t\tconst { value: partialArgs } = await parsePartialJson(partialToolCall.text);\n\t\t\t\t\tif (partialToolCall.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: partialArgs\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: partialArgs\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-available\":\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tif (onToolCall && !chunk.providerExecuted) await onToolCall({ toolCall: chunk });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-error\":\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\trawInput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-output-available\":\n\t\t\t\t\tif (chunk.dynamic) {\n\t\t\t\t\t\tconst toolInvocation = getDynamicToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateDynamicToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\t\tpreliminary: chunk.preliminary\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: getToolName(toolInvocation),\n\t\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\t\tpreliminary: chunk.preliminary\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-output-error\":\n\t\t\t\t\tif (chunk.dynamic) {\n\t\t\t\t\t\tconst toolInvocation = getDynamicToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateDynamicToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t\t});\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: getToolName(toolInvocation),\n\t\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\trawInput: toolInvocation.rawInput,\n\t\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"start-step\":\n\t\t\t\t\tstate.message.parts.push({ type: \"step-start\" });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish-step\":\n\t\t\t\t\tstate.activeTextParts = createIdMap();\n\t\t\t\t\tstate.activeReasoningParts = createIdMap();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"start\":\n\t\t\t\t\tif (chunk.messageId != null) state.message.id = chunk.messageId;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageId != null || chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tif (chunk.finishReason != null) state.finishReason = chunk.finishReason;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"message-metadata\":\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tonError?.(new Error(chunk.errorText));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: if (isDataUIMessageChunk(chunk)) {\n\t\t\t\t\tif ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) await validateTypes({\n\t\t\t\t\t\tvalue: chunk.data,\n\t\t\t\t\t\tschema: dataPartSchemas[chunk.type]\n\t\t\t\t\t});\n\t\t\t\t\tconst dataChunk = chunk;\n\t\t\t\t\tif (dataChunk.transient) {\n\t\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst existingUIPart = dataChunk.id != null ? state.message.parts.find((chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id) : void 0;\n\t\t\t\t\tif (existingUIPart != null) existingUIPart.data = dataChunk.data;\n\t\t\t\t\telse state.message.parts.push(dataChunk);\n\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\twrite();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk);\n\t\t});\n\t} }));\n}\nfunction handleUIMessageStreamFinish({ messageId, originalMessages = [], onFinish, onError, stream }) {\n\tlet lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];\n\tif ((lastMessage == null ? void 0 : lastMessage.role) !== \"assistant\") lastMessage = void 0;\n\telse messageId = lastMessage.id;\n\tlet isAborted = false;\n\tconst idInjectedStream = stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\tif (chunk.type === \"start\") {\n\t\t\tconst startChunk = chunk;\n\t\t\tif (startChunk.messageId == null && messageId != null) startChunk.messageId = messageId;\n\t\t}\n\t\tif (chunk.type === \"abort\") isAborted = true;\n\t\tcontroller.enqueue(chunk);\n\t} }));\n\tif (onFinish == null) return idInjectedStream;\n\tconst state = createStreamingUIMessageState({\n\t\tlastMessage: lastMessage ? structuredClone(lastMessage) : void 0,\n\t\tmessageId: messageId != null ? messageId : \"\"\n\t});\n\tconst runUpdateMessageJob = async (job) => {\n\t\tawait job({\n\t\t\tstate,\n\t\t\twrite: () => {}\n\t\t});\n\t};\n\tlet finishCalled = false;\n\tconst callOnFinish = async () => {\n\t\tif (finishCalled || !onFinish) return;\n\t\tfinishCalled = true;\n\t\tconst isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n\t\tawait onFinish({\n\t\t\tisAborted,\n\t\t\tisContinuation,\n\t\t\tresponseMessage: state.message,\n\t\t\tmessages: [...isContinuation ? originalMessages.slice(0, -1) : originalMessages, state.message],\n\t\t\tfinishReason: state.finishReason\n\t\t});\n\t};\n\treturn processUIMessageStream({\n\t\tstream: idInjectedStream,\n\t\trunUpdateMessageJob,\n\t\tonError\n\t}).pipeThrough(new TransformStream({\n\t\ttransform(chunk, controller) {\n\t\t\tcontroller.enqueue(chunk);\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait callOnFinish();\n\t\t},\n\t\tasync flush() {\n\t\t\tawait callOnFinish();\n\t\t}\n\t}));\n}\nfunction pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, consumeSseStream }) {\n\tlet sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\twriteToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: Object.fromEntries(prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS).entries()),\n\t\tstream: sseStream.pipeThrough(new TextEncoderStream())\n\t});\n}\nfunction createAsyncIterableStream(source) {\n\tconst stream = source.pipeThrough(new TransformStream());\n\tstream[Symbol.asyncIterator] = function() {\n\t\tconst reader = this.getReader();\n\t\tlet finished = false;\n\t\tasync function cleanup(cancelStream) {\n\t\t\tvar _a16;\n\t\t\tfinished = true;\n\t\t\ttry {\n\t\t\t\tif (cancelStream) await ((_a16 = reader.cancel) == null ? void 0 : _a16.call(reader));\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\treader.releaseLock();\n\t\t\t\t} catch (e) {}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t/**\n\t\t\t* Reads the next chunk from the stream.\n\t\t\t* @returns A promise resolving to the next IteratorResult.\n\t\t\t*/\n\t\t\tasync next() {\n\t\t\t\tif (finished) return {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\tawait cleanup(true);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\tvalue: void 0\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* Called on early exit (e.g., break from for-await).\n\t\t\t* Ensures the stream is cancelled and resources are released.\n\t\t\t* @returns A promise resolving to a completed IteratorResult.\n\t\t\t*/\n\t\t\tasync return() {\n\t\t\t\tawait cleanup(true);\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* Called on early exit with error.\n\t\t\t* Ensures the stream is cancelled and resources are released, then rethrows the error.\n\t\t\t* @param err The error to throw.\n\t\t\t* @returns A promise that rejects with the provided error.\n\t\t\t*/\n\t\t\tasync throw(err) {\n\t\t\t\tawait cleanup(true);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t};\n\treturn stream;\n}\nasync function consumeStream({ stream, onError }) {\n\tconst reader = stream.getReader();\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done } = await reader.read();\n\t\t\tif (done) break;\n\t\t}\n\t} catch (error) {\n\t\tonError?.(error);\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\nfunction createResolvablePromise() {\n\tlet resolve2;\n\tlet reject;\n\treturn {\n\t\tpromise: new Promise((res, rej) => {\n\t\t\tresolve2 = res;\n\t\t\treject = rej;\n\t\t}),\n\t\tresolve: resolve2,\n\t\treject\n\t};\n}\nfunction createStitchableStream() {\n\tlet innerStreamReaders = [];\n\tlet controller = null;\n\tlet isClosed = false;\n\tlet waitForNewStream = createResolvablePromise();\n\tconst terminate = () => {\n\t\tisClosed = true;\n\t\twaitForNewStream.resolve();\n\t\tinnerStreamReaders.forEach((reader) => reader.cancel());\n\t\tinnerStreamReaders = [];\n\t\tcontroller?.close();\n\t};\n\tconst processPull = async () => {\n\t\tif (isClosed && innerStreamReaders.length === 0) {\n\t\t\tcontroller?.close();\n\t\t\treturn;\n\t\t}\n\t\tif (innerStreamReaders.length === 0) {\n\t\t\twaitForNewStream = createResolvablePromise();\n\t\t\tawait waitForNewStream.promise;\n\t\t\treturn processPull();\n\t\t}\n\t\ttry {\n\t\t\tconst { value, done } = await innerStreamReaders[0].read();\n\t\t\tif (done) {\n\t\t\t\tinnerStreamReaders.shift();\n\t\t\t\tif (innerStreamReaders.length > 0) await processPull();\n\t\t\t\telse if (isClosed) controller?.close();\n\t\t\t} else controller?.enqueue(value);\n\t\t} catch (error) {\n\t\t\tcontroller?.error(error);\n\t\t\tinnerStreamReaders.shift();\n\t\t\tterminate();\n\t\t}\n\t};\n\treturn {\n\t\tstream: new ReadableStream({\n\t\t\tstart(controllerParam) {\n\t\t\t\tcontroller = controllerParam;\n\t\t\t},\n\t\t\tpull: processPull,\n\t\t\tasync cancel() {\n\t\t\t\tfor (const reader of innerStreamReaders) await reader.cancel();\n\t\t\t\tinnerStreamReaders = [];\n\t\t\t\tisClosed = true;\n\t\t\t}\n\t\t}),\n\t\taddStream: (innerStream) => {\n\t\t\tif (isClosed) throw new Error(\"Cannot add inner stream: outer stream is closed\");\n\t\t\tinnerStreamReaders.push(innerStream.getReader());\n\t\t\twaitForNewStream.resolve();\n\t\t},\n\t\t/**\n\t\t* Gracefully close the outer stream. This will let the inner streams\n\t\t* finish processing and then close the outer stream.\n\t\t*/\n\t\tclose: () => {\n\t\t\tisClosed = true;\n\t\t\twaitForNewStream.resolve();\n\t\t\tif (innerStreamReaders.length === 0) controller?.close();\n\t\t},\n\t\t/**\n\t\t* Immediately close the outer stream. This will cancel all inner streams\n\t\t* and close the outer stream.\n\t\t*/\n\t\tterminate\n\t};\n}\nfunction now() {\n\tvar _a16, _b;\n\treturn (_b = (_a16 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a16.now()) != null ? _b : Date.now();\n}\nfunction runToolsTransformation({ tools, generatorStream, tracer, telemetry, system, messages, abortSignal, repairToolCall, experimental_context }) {\n\tlet toolResultsStreamController = null;\n\tlet toolResultsStreamClosed = false;\n\tconst toolResultsStream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\ttoolResultsStreamController = controller;\n\t\t},\n\t\tcancel() {\n\t\t\ttoolResultsStreamClosed = true;\n\t\t}\n\t});\n\tfunction enqueueToolResult(chunk) {\n\t\tif (toolResultsStreamClosed) return;\n\t\ttry {\n\t\t\ttoolResultsStreamController.enqueue(chunk);\n\t\t} catch (e) {\n\t\t\ttoolResultsStreamClosed = true;\n\t\t}\n\t}\n\tfunction closeToolResultsStream() {\n\t\tif (toolResultsStreamClosed) return;\n\t\ttoolResultsStreamClosed = true;\n\t\ttry {\n\t\t\ttoolResultsStreamController.close();\n\t\t} catch (e) {}\n\t}\n\tconst outstandingToolResults = /* @__PURE__ */ new Set();\n\tconst toolInputs = /* @__PURE__ */ new Map();\n\tlet canClose = false;\n\tlet finishChunk = void 0;\n\tfunction attemptClose() {\n\t\tif (canClose && outstandingToolResults.size === 0) {\n\t\t\tif (finishChunk != null) enqueueToolResult(finishChunk);\n\t\t\tcloseToolResultsStream();\n\t\t}\n\t}\n\tconst forwardStream = new TransformStream({\n\t\tasync transform(chunk, controller) {\n\t\t\tconst chunkType = chunk.type;\n\t\t\tswitch (chunkType) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\tcase \"text-start\":\n\t\t\t\tcase \"text-delta\":\n\t\t\t\tcase \"text-end\":\n\t\t\t\tcase \"reasoning-start\":\n\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\tcase \"reasoning-end\":\n\t\t\t\tcase \"tool-input-start\":\n\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\tcase \"tool-input-end\":\n\t\t\t\tcase \"source\":\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\tcase \"error\":\n\t\t\t\tcase \"raw\":\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"file\":\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tfile: new DefaultGeneratedFileWithType({\n\t\t\t\t\t\t\tdata: chunk.data,\n\t\t\t\t\t\t\tmediaType: chunk.mediaType\n\t\t\t\t\t\t})\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tfinishChunk = {\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: chunk.finishReason,\n\t\t\t\t\t\tusage: chunk.usage,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-call\":\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst toolCall = await parseToolCall({\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\t\tsystem,\n\t\t\t\t\t\t\tmessages\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontroller.enqueue(toolCall);\n\t\t\t\t\t\tif (toolCall.invalid) {\n\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\terror: getErrorMessage$1(toolCall.error),\n\t\t\t\t\t\t\t\tdynamic: true\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst tool2 = tools[toolCall.toolName];\n\t\t\t\t\t\ttoolInputs.set(toolCall.toolCallId, toolCall.input);\n\t\t\t\t\t\tif (tool2.onInputAvailable != null) await tool2.onInputAvailable({\n\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (tool2.execute != null && toolCall.providerExecuted !== true) {\n\t\t\t\t\t\t\tconst toolExecutionId = generateId();\n\t\t\t\t\t\t\toutstandingToolResults.add(toolExecutionId);\n\t\t\t\t\t\t\trecordSpan({\n\t\t\t\t\t\t\t\tname: \"ai.toolCall\",\n\t\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\t\toperationId: \"ai.toolCall\",\n\t\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t\"ai.toolCall.name\": toolCall.toolName,\n\t\t\t\t\t\t\t\t\t\t\"ai.toolCall.id\": toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\"ai.toolCall.args\": { output: () => JSON.stringify(toolCall.input) }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\t\tfn: async (span) => {\n\t\t\t\t\t\t\t\t\tlet output;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tconst stream = executeTool({\n\t\t\t\t\t\t\t\t\t\t\texecute: tool2.execute.bind(tool2),\n\t\t\t\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tfor await (const part of stream) {\n\t\t\t\t\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\t\t\t\t\t...toolCall,\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t\t\t\t\t\t...part.type === \"preliminary\" && { preliminary: true }\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\tif (part.type === \"final\") output = part.output;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\t\t\t\t...toolCall,\n\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\toutstandingToolResults.delete(toolExecutionId);\n\t\t\t\t\t\t\t\t\t\tattemptClose();\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\toutstandingToolResults.delete(toolExecutionId);\n\t\t\t\t\t\t\t\t\tattemptClose();\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\t\t\tattributes: { \"ai.toolCall.result\": { output: () => JSON.stringify(output) } }\n\t\t\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\t\t} catch (ignored) {}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terror\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-result\": {\n\t\t\t\t\tconst toolName = chunk.toolName;\n\t\t\t\t\tif (chunk.isError) enqueueToolResult({\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput: toolInputs.get(chunk.toolCallId),\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\terror: chunk.result\n\t\t\t\t\t});\n\t\t\t\t\telse controller.enqueue({\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput: toolInputs.get(chunk.toolCallId),\n\t\t\t\t\t\toutput: chunk.result,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: throw new Error(`Unhandled chunk type: ${chunkType}`);\n\t\t\t}\n\t\t},\n\t\tflush() {\n\t\t\tcanClose = true;\n\t\t\tattemptClose();\n\t\t}\n\t});\n\treturn new ReadableStream({ async start(controller) {\n\t\treturn Promise.all([generatorStream.pipeThrough(forwardStream).pipeTo(new WritableStream({\n\t\t\twrite(chunk) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t},\n\t\t\tclose() {}\n\t\t})), toolResultsStream.pipeTo(new WritableStream({\n\t\t\twrite(chunk) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t},\n\t\t\tclose() {\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}))]);\n\t} });\n}\nvar originalGenerateId2 = createIdGenerator({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nfunction streamText$1({ model, tools, toolChoice, system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, headers, stopWhen = stepCountIs(1), experimental_output: output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_activeTools, activeTools = experimental_activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, experimental_download: download2, includeRawChunks = false, onChunk, onError = ({ error }) => {\n\tconsole.error(error);\n}, onFinish, onAbort, onStepFinish, experimental_context, _internal: { now: now2 = now, generateId: generateId3 = originalGenerateId2, currentDate = () => /* @__PURE__ */ new Date() } = {}, ...settings }) {\n\treturn new DefaultStreamTextResult({\n\t\tmodel: resolveLanguageModel(model),\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tabortSignal,\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\ttools,\n\t\ttoolChoice,\n\t\ttransforms: asArray(transform),\n\t\tactiveTools,\n\t\trepairToolCall,\n\t\tstopConditions: asArray(stopWhen),\n\t\toutput,\n\t\tproviderOptions,\n\t\tprepareStep,\n\t\tincludeRawChunks,\n\t\tonChunk,\n\t\tonError,\n\t\tonFinish,\n\t\tonAbort,\n\t\tonStepFinish,\n\t\tnow: now2,\n\t\tcurrentDate,\n\t\tgenerateId: generateId3,\n\t\texperimental_context,\n\t\tdownload: download2\n\t});\n}\nfunction createOutputTransformStream(output) {\n\tif (!output) return new TransformStream({ transform(chunk, controller) {\n\t\tcontroller.enqueue({\n\t\t\tpart: chunk,\n\t\t\tpartialOutput: void 0\n\t\t});\n\t} });\n\tlet firstTextChunkId = void 0;\n\tlet text2 = \"\";\n\tlet textChunk = \"\";\n\tlet lastPublishedJson = \"\";\n\tfunction publishTextChunk({ controller, partialOutput = void 0 }) {\n\t\tcontroller.enqueue({\n\t\t\tpart: {\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tid: firstTextChunkId,\n\t\t\t\ttext: textChunk\n\t\t\t},\n\t\t\tpartialOutput\n\t\t});\n\t\ttextChunk = \"\";\n\t}\n\treturn new TransformStream({ async transform(chunk, controller) {\n\t\tif (chunk.type === \"finish-step\" && textChunk.length > 0) publishTextChunk({ controller });\n\t\tif (chunk.type !== \"text-delta\" && chunk.type !== \"text-start\" && chunk.type !== \"text-end\") {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (firstTextChunkId == null) firstTextChunkId = chunk.id;\n\t\telse if (chunk.id !== firstTextChunkId) {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-start\") {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-end\") {\n\t\t\tif (textChunk.length > 0) publishTextChunk({ controller });\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\ttext2 += chunk.text;\n\t\ttextChunk += chunk.text;\n\t\tconst result = await output.parsePartial({ text: text2 });\n\t\tif (result != null) {\n\t\t\tconst currentJson = JSON.stringify(result.partial);\n\t\t\tif (currentJson !== lastPublishedJson) {\n\t\t\t\tpublishTextChunk({\n\t\t\t\t\tcontroller,\n\t\t\t\t\tpartialOutput: result.partial\n\t\t\t\t});\n\t\t\t\tlastPublishedJson = currentJson;\n\t\t\t}\n\t\t}\n\t} });\n}\nvar DefaultStreamTextResult = class {\n\tconstructor({ model, telemetry, headers, settings, maxRetries: maxRetriesArg, abortSignal, system, prompt, messages, allowSystemInMessages, tools, toolChoice, transforms, activeTools, repairToolCall, stopConditions, output, providerOptions, prepareStep, includeRawChunks, now: now2, currentDate, generateId: generateId3, onChunk, onError, onFinish, onAbort, onStepFinish, experimental_context, download: download2 }) {\n\t\tthis._totalUsage = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tthis._steps = new DelayedPromise();\n\t\tthis.output = output;\n\t\tthis.includeRawChunks = includeRawChunks;\n\t\tthis.tools = tools;\n\t\tlet stepFinish;\n\t\tlet recordedContent = [];\n\t\tconst recordedResponseMessages = [];\n\t\tlet recordedFinishReason = void 0;\n\t\tlet recordedTotalUsage = void 0;\n\t\tlet recordedRequest = {};\n\t\tlet recordedWarnings = [];\n\t\tconst recordedSteps = [];\n\t\tlet rootSpan;\n\t\tlet activeTextContent = createIdMap();\n\t\tlet activeReasoningContent = createIdMap();\n\t\tconst eventProcessor = new TransformStream({\n\t\t\tasync transform(chunk, controller) {\n\t\t\t\tvar _a16, _b, _c, _d;\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tconst { part } = chunk;\n\t\t\t\tif (part.type === \"text-delta\" || part.type === \"reasoning-delta\" || part.type === \"source\" || part.type === \"tool-call\" || part.type === \"tool-result\" || part.type === \"tool-input-start\" || part.type === \"tool-input-delta\" || part.type === \"raw\") await (onChunk == null ? void 0 : onChunk({ chunk: part }));\n\t\t\t\tif (part.type === \"error\") await onError({ error: wrapGatewayError(part.error) });\n\t\t\t\tif (part.type === \"text-start\") {\n\t\t\t\t\tactiveTextContent[part.id] = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeTextContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-delta\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.text += part.text;\n\t\t\t\t\tactiveText.providerMetadata = (_a16 = part.providerMetadata) != null ? _a16 : activeText.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-end\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.providerMetadata = (_b = part.providerMetadata) != null ? _b : activeText.providerMetadata;\n\t\t\t\t\tdelete activeTextContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-start\") {\n\t\t\t\t\tactiveReasoningContent[part.id] = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeReasoningContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-delta\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.text += part.text;\n\t\t\t\t\tactiveReasoning.providerMetadata = (_c = part.providerMetadata) != null ? _c : activeReasoning.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-end\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.providerMetadata = (_d = part.providerMetadata) != null ? _d : activeReasoning.providerMetadata;\n\t\t\t\t\tdelete activeReasoningContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"file\") recordedContent.push({\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tfile: part.file\n\t\t\t\t});\n\t\t\t\tif (part.type === \"source\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-call\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-result\" && !part.preliminary) recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-error\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"start-step\") {\n\t\t\t\t\trecordedContent = [];\n\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\trecordedRequest = part.request;\n\t\t\t\t\trecordedWarnings = part.warnings;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish-step\") {\n\t\t\t\t\tconst stepMessages = toResponseMessages({\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\ttools\n\t\t\t\t\t});\n\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t\t\tusage: part.usage,\n\t\t\t\t\t\twarnings: recordedWarnings,\n\t\t\t\t\t\trequest: recordedRequest,\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t...part.response,\n\t\t\t\t\t\t\tmessages: [...recordedResponseMessages, ...stepMessages]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tawait (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));\n\t\t\t\t\tlogWarnings(recordedWarnings);\n\t\t\t\t\trecordedSteps.push(currentStepResult);\n\t\t\t\t\trecordedContent = [];\n\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\trecordedResponseMessages.push(...stepMessages);\n\t\t\t\t\tstepFinish.resolve();\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish\") {\n\t\t\t\t\trecordedTotalUsage = part.totalUsage;\n\t\t\t\t\trecordedFinishReason = part.finishReason;\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync flush(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tif (recordedSteps.length === 0) {\n\t\t\t\t\t\tconst error = new NoOutputGeneratedError({ message: \"No output generated. Check the stream for errors.\" });\n\t\t\t\t\t\tself._finishReason.reject(error);\n\t\t\t\t\t\tself._totalUsage.reject(error);\n\t\t\t\t\t\tself._steps.reject(error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst finishReason = recordedFinishReason != null ? recordedFinishReason : \"unknown\";\n\t\t\t\t\tconst totalUsage = recordedTotalUsage != null ? recordedTotalUsage : {\n\t\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t\t};\n\t\t\t\t\tself._finishReason.resolve(finishReason);\n\t\t\t\t\tself._totalUsage.resolve(totalUsage);\n\t\t\t\t\tself._steps.resolve(recordedSteps);\n\t\t\t\t\tconst finalStep = recordedSteps[recordedSteps.length - 1];\n\t\t\t\t\tawait (onFinish == null ? void 0 : onFinish({\n\t\t\t\t\t\tfinishReason,\n\t\t\t\t\t\ttotalUsage,\n\t\t\t\t\t\tusage: finalStep.usage,\n\t\t\t\t\t\tcontent: finalStep.content,\n\t\t\t\t\t\ttext: finalStep.text,\n\t\t\t\t\t\treasoningText: finalStep.reasoningText,\n\t\t\t\t\t\treasoning: finalStep.reasoning,\n\t\t\t\t\t\tfiles: finalStep.files,\n\t\t\t\t\t\tsources: finalStep.sources,\n\t\t\t\t\t\ttoolCalls: finalStep.toolCalls,\n\t\t\t\t\t\tstaticToolCalls: finalStep.staticToolCalls,\n\t\t\t\t\t\tdynamicToolCalls: finalStep.dynamicToolCalls,\n\t\t\t\t\t\ttoolResults: finalStep.toolResults,\n\t\t\t\t\t\tstaticToolResults: finalStep.staticToolResults,\n\t\t\t\t\t\tdynamicToolResults: finalStep.dynamicToolResults,\n\t\t\t\t\t\trequest: finalStep.request,\n\t\t\t\t\t\tresponse: finalStep.response,\n\t\t\t\t\t\twarnings: finalStep.warnings,\n\t\t\t\t\t\tproviderMetadata: finalStep.providerMetadata,\n\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t}));\n\t\t\t\t\trootSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\t\"ai.response.text\": { output: () => finalStep.text },\n\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\t\tvar _a16;\n\t\t\t\t\t\t\t\treturn ((_a16 = finalStep.toolCalls) == null ? void 0 : _a16.length) ? JSON.stringify(finalStep.toolCalls) : void 0;\n\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(finalStep.providerMetadata),\n\t\t\t\t\t\t\t\"ai.usage.inputTokens\": totalUsage.inputTokens,\n\t\t\t\t\t\t\t\"ai.usage.outputTokens\": totalUsage.outputTokens,\n\t\t\t\t\t\t\t\"ai.usage.totalTokens\": totalUsage.totalTokens,\n\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": totalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": totalUsage.cachedInputTokens\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t} finally {\n\t\t\t\t\trootSpan.end();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tconst stitchableStream = createStitchableStream();\n\t\tthis.addStream = stitchableStream.addStream;\n\t\tthis.closeStream = stitchableStream.close;\n\t\tconst reader = stitchableStream.stream.getReader();\n\t\tlet stream = new ReadableStream({\n\t\t\tasync start(controller) {\n\t\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\t},\n\t\t\tasync pull(controller) {\n\t\t\t\tfunction abort() {\n\t\t\t\t\tonAbort?.({ steps: recordedSteps });\n\t\t\t\t\tcontroller.enqueue({ type: \"abort\" });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (abortSignal == null ? void 0 : abortSignal.aborted) {\n\t\t\t\t\t\tabort();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isAbortError(error) && (abortSignal == null ? void 0 : abortSignal.aborted)) abort();\n\t\t\t\t\telse controller.error(error);\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel(reason) {\n\t\t\t\treturn stitchableStream.stream.cancel(reason);\n\t\t\t}\n\t\t});\n\t\tfor (const transform of transforms) stream = stream.pipeThrough(transform({\n\t\t\ttools,\n\t\t\tstopStream() {\n\t\t\t\tstitchableStream.terminate();\n\t\t\t}\n\t\t}));\n\t\tthis.baseStream = stream.pipeThrough(createOutputTransformStream(output)).pipeThrough(eventProcessor);\n\t\tconst { maxRetries, retry } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst tracer = getTracer(telemetry);\n\t\tconst callSettings = prepareCallSettings(settings);\n\t\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\t\tmodel,\n\t\t\ttelemetry,\n\t\t\theaders,\n\t\t\tsettings: {\n\t\t\t\t...callSettings,\n\t\t\t\tmaxRetries\n\t\t\t}\n\t\t});\n\t\tconst self = this;\n\t\trecordSpan({\n\t\t\tname: \"ai.streamText\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.streamText\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tendWhenDone: false,\n\t\t\tfn: async (rootSpanArg) => {\n\t\t\t\trootSpan = rootSpanArg;\n\t\t\t\tasync function streamStep({ currentStep, responseMessages, usage }) {\n\t\t\t\t\tvar _a16, _b, _c, _d, _e;\n\t\t\t\t\tconst includeRawChunks2 = self.includeRawChunks;\n\t\t\t\t\tstepFinish = new DelayedPromise();\n\t\t\t\t\tconst initialPrompt = await standardizePrompt({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tallowSystemInMessages\n\t\t\t\t\t});\n\t\t\t\t\tconst stepInputMessages = [...initialPrompt.messages, ...responseMessages];\n\t\t\t\t\tconst prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsteps: recordedSteps,\n\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\tmessages: stepInputMessages\n\t\t\t\t\t}));\n\t\t\t\t\tconst stepModel = resolveLanguageModel((_a16 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a16 : model);\n\t\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\t\tprompt: {\n\t\t\t\t\t\t\tsystem: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n\t\t\t\t\t\t\tmessages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsupportedUrls: await stepModel.supportedUrls,\n\t\t\t\t\t\tdownload: download2\n\t\t\t\t\t});\n\t\t\t\t\tconst { toolChoice: stepToolChoice, tools: stepTools } = prepareToolsAndToolChoice({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\ttoolChoice: (_d = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _d : toolChoice,\n\t\t\t\t\t\tactiveTools: (_e = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _e : activeTools\n\t\t\t\t\t});\n\t\t\t\t\tconst { result: { stream: stream2, response, request }, doStreamSpan, startTimestampMs } = await retry(() => recordSpan({\n\t\t\t\t\t\tname: \"ai.streamText.doStream\",\n\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\toperationId: \"ai.streamText.doStream\",\n\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\"ai.model.provider\": stepModel.provider,\n\t\t\t\t\t\t\t\t\"ai.model.id\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\t\"ai.prompt.tools\": { input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2)) },\n\t\t\t\t\t\t\t\t\"ai.prompt.toolChoice\": { input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0 },\n\t\t\t\t\t\t\t\t\"gen_ai.system\": stepModel.provider,\n\t\t\t\t\t\t\t\t\"gen_ai.request.model\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\t\"gen_ai.request.stop_sequences\": callSettings.stopSequences,\n\t\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\tendWhenDone: false,\n\t\t\t\t\t\tfn: async (doStreamSpan2) => {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tstartTimestampMs: now2(),\n\t\t\t\t\t\t\t\tdoStreamSpan: doStreamSpan2,\n\t\t\t\t\t\t\t\tresult: await stepModel.doStream({\n\t\t\t\t\t\t\t\t\t...callSettings,\n\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\tresponseFormat: output == null ? void 0 : output.responseFormat,\n\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\t\tincludeRawChunks: includeRawChunks2\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\tconst streamWithToolResults = runToolsTransformation({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\tgeneratorStream: stream2,\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t});\n\t\t\t\t\tconst stepRequest = request != null ? request : {};\n\t\t\t\t\tconst stepToolCalls = [];\n\t\t\t\t\tconst stepToolOutputs = [];\n\t\t\t\t\tlet warnings;\n\t\t\t\t\tconst activeToolCallToolNames = {};\n\t\t\t\t\tlet stepFinishReason = \"unknown\";\n\t\t\t\t\tlet stepUsage = {\n\t\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t\t};\n\t\t\t\t\tlet stepProviderMetadata;\n\t\t\t\t\tlet stepFirstChunk = true;\n\t\t\t\t\tlet stepResponse = {\n\t\t\t\t\t\tid: generateId3(),\n\t\t\t\t\t\ttimestamp: currentDate(),\n\t\t\t\t\t\tmodelId: model.modelId\n\t\t\t\t\t};\n\t\t\t\t\tlet activeText = \"\";\n\t\t\t\t\tself.addStream(streamWithToolResults.pipeThrough(new TransformStream({\n\t\t\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\t\t\tvar _a17, _b2, _c2, _d2;\n\t\t\t\t\t\t\tif (chunk.type === \"stream-start\") {\n\t\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (stepFirstChunk) {\n\t\t\t\t\t\t\t\tconst msToFirstChunk = now2() - startTimestampMs;\n\t\t\t\t\t\t\t\tstepFirstChunk = false;\n\t\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.firstChunk\", { \"ai.response.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes({ \"ai.response.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"start-step\",\n\t\t\t\t\t\t\t\t\trequest: stepRequest,\n\t\t\t\t\t\t\t\t\twarnings: warnings != null ? warnings : []\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst chunkType = chunk.type;\n\t\t\t\t\t\t\tswitch (chunkType) {\n\t\t\t\t\t\t\t\tcase \"text-start\":\n\t\t\t\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\t\t\t\tif (chunk.delta.length > 0) {\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\t\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tactiveText += chunk.delta;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"reasoning-start\":\n\t\t\t\t\t\t\t\tcase \"reasoning-end\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-call\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tstepToolCalls.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-result\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tif (!chunk.preliminary) stepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-error\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tstepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\t\t\t\tstepResponse = {\n\t\t\t\t\t\t\t\t\t\tid: (_a17 = chunk.id) != null ? _a17 : stepResponse.id,\n\t\t\t\t\t\t\t\t\t\ttimestamp: (_b2 = chunk.timestamp) != null ? _b2 : stepResponse.timestamp,\n\t\t\t\t\t\t\t\t\t\tmodelId: (_c2 = chunk.modelId) != null ? _c2 : stepResponse.modelId\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"finish\": {\n\t\t\t\t\t\t\t\t\tstepUsage = chunk.usage;\n\t\t\t\t\t\t\t\t\tstepFinishReason = chunk.finishReason;\n\t\t\t\t\t\t\t\t\tstepProviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\t\t\tconst msToFinish = now2() - startTimestampMs;\n\t\t\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.finish\");\n\t\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes({\n\t\t\t\t\t\t\t\t\t\t\"ai.response.msToFinish\": msToFinish,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.avgOutputTokensPerSecond\": 1e3 * ((_d2 = stepUsage.outputTokens) != null ? _d2 : 0) / msToFinish\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"file\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"source\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\t\t\t\t\tactiveToolCallToolNames[chunk.id] = chunk.toolName;\n\t\t\t\t\t\t\t\t\tconst tool2 = tools == null ? void 0 : tools[chunk.toolName];\n\t\t\t\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.onInputStart) != null) await tool2.onInputStart({\n\t\t\t\t\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tdynamic: (tool2 == null ? void 0 : tool2.type) === \"dynamic\"\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"tool-input-end\":\n\t\t\t\t\t\t\t\t\tdelete activeToolCallToolNames[chunk.id];\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-input-delta\": {\n\t\t\t\t\t\t\t\t\tconst toolName = activeToolCallToolNames[chunk.id];\n\t\t\t\t\t\t\t\t\tconst tool2 = tools == null ? void 0 : tools[toolName];\n\t\t\t\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.onInputDelta) != null) await tool2.onInputDelta({\n\t\t\t\t\t\t\t\t\t\tinputTextDelta: chunk.delta,\n\t\t\t\t\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tstepFinishReason = \"error\";\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"raw\":\n\t\t\t\t\t\t\t\t\tif (includeRawChunks2) controller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault: throw new Error(`Unknown chunk type: ${chunkType}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync flush(controller) {\n\t\t\t\t\t\t\tconst stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : void 0;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": stepFinishReason,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.text\": { output: () => activeText },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => stepToolCallsJson },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.id\": stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.model\": stepResponse.modelId,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": stepResponse.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(stepProviderMetadata),\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": stepUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": stepUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": stepUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": stepUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": stepUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [stepFinishReason],\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": stepResponse.modelId,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": stepUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": stepUsage.outputTokens\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t} catch (error) {} finally {\n\t\t\t\t\t\t\t\tdoStreamSpan.end();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"finish-step\",\n\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\tusage: stepUsage,\n\t\t\t\t\t\t\t\tproviderMetadata: stepProviderMetadata,\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...stepResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst combinedUsage = addLanguageModelUsage(usage, stepUsage);\n\t\t\t\t\t\t\tawait stepFinish.promise;\n\t\t\t\t\t\t\tconst clientToolCalls = stepToolCalls.filter((toolCall) => toolCall.providerExecuted !== true);\n\t\t\t\t\t\t\tconst clientToolOutputs = stepToolOutputs.filter((toolOutput) => toolOutput.providerExecuted !== true);\n\t\t\t\t\t\t\tif (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length && !await isStopConditionMet({\n\t\t\t\t\t\t\t\tstopConditions,\n\t\t\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\t\tresponseMessages.push(...toResponseMessages({\n\t\t\t\t\t\t\t\t\tcontent: recordedSteps[recordedSteps.length - 1].content,\n\t\t\t\t\t\t\t\t\ttools\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait streamStep({\n\t\t\t\t\t\t\t\t\t\tcurrentStep: currentStep + 1,\n\t\t\t\t\t\t\t\t\t\tresponseMessages,\n\t\t\t\t\t\t\t\t\t\tusage: combinedUsage\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\t\ttotalUsage: combinedUsage\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})));\n\t\t\t\t}\n\t\t\t\tawait streamStep({\n\t\t\t\t\tcurrentStep: 0,\n\t\t\t\t\tresponseMessages: [],\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tself.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t\tself.closeStream();\n\t\t});\n\t}\n\tget steps() {\n\t\tthis.consumeStream();\n\t\treturn this._steps.promise;\n\t}\n\tget finalStep() {\n\t\treturn this.steps.then((steps) => steps[steps.length - 1]);\n\t}\n\tget content() {\n\t\treturn this.finalStep.then((step) => step.content);\n\t}\n\tget warnings() {\n\t\treturn this.finalStep.then((step) => step.warnings);\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.then((step) => step.providerMetadata);\n\t}\n\tget text() {\n\t\treturn this.finalStep.then((step) => step.text);\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.then((step) => step.reasoningText);\n\t}\n\tget reasoning() {\n\t\treturn this.finalStep.then((step) => step.reasoning);\n\t}\n\tget sources() {\n\t\treturn this.finalStep.then((step) => step.sources);\n\t}\n\tget files() {\n\t\treturn this.finalStep.then((step) => step.files);\n\t}\n\tget toolCalls() {\n\t\treturn this.finalStep.then((step) => step.toolCalls);\n\t}\n\tget staticToolCalls() {\n\t\treturn this.finalStep.then((step) => step.staticToolCalls);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.finalStep.then((step) => step.dynamicToolCalls);\n\t}\n\tget toolResults() {\n\t\treturn this.finalStep.then((step) => step.toolResults);\n\t}\n\tget staticToolResults() {\n\t\treturn this.finalStep.then((step) => step.staticToolResults);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.finalStep.then((step) => step.dynamicToolResults);\n\t}\n\tget usage() {\n\t\treturn this.finalStep.then((step) => step.usage);\n\t}\n\tget request() {\n\t\treturn this.finalStep.then((step) => step.request);\n\t}\n\tget response() {\n\t\treturn this.finalStep.then((step) => step.response);\n\t}\n\tget totalUsage() {\n\t\tthis.consumeStream();\n\t\treturn this._totalUsage.promise;\n\t}\n\tget finishReason() {\n\t\tthis.consumeStream();\n\t\treturn this._finishReason.promise;\n\t}\n\t/**\n\tSplit out a new stream from the original stream.\n\tThe original stream is replaced to allow for further splitting,\n\tsince we do not know how many times the stream will be split.\n\t\n\tNote: this leads to buffering the stream content on the server.\n\tHowever, the LLM results are expected to be small enough to not cause issues.\n\t*/\n\tteeStream() {\n\t\tconst [stream1, stream2] = this.baseStream.tee();\n\t\tthis.baseStream = stream2;\n\t\treturn stream1;\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {\n\t\t\tif (part.type === \"text-delta\") controller.enqueue(part.text);\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {\n\t\t\tcontroller.enqueue(part);\n\t\t} })));\n\t}\n\tasync consumeStream(options) {\n\t\tvar _a16;\n\t\ttry {\n\t\t\tawait consumeStream({\n\t\t\t\tstream: this.fullStream,\n\t\t\t\tonError: options == null ? void 0 : options.onError\n\t\t\t});\n\t\t} catch (error) {\n\t\t\t(_a16 = options == null ? void 0 : options.onError) == null || _a16.call(options, error);\n\t\t}\n\t}\n\tget experimental_partialOutputStream() {\n\t\tif (this.output == null) throw new NoOutputSpecifiedError();\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ partialOutput }, controller) {\n\t\t\tif (partialOutput != null) controller.enqueue(partialOutput);\n\t\t} })));\n\t}\n\ttoUIMessageStream({ originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => \"An error occurred.\" } = {}) {\n\t\tconst responseMessageId = generateMessageId != null ? getResponseUIMessageId({\n\t\t\toriginalMessages,\n\t\t\tresponseMessageId: generateMessageId\n\t\t}) : void 0;\n\t\tconst toolNamesByCallId = {};\n\t\tconst isDynamic = (toolCallId) => {\n\t\t\tvar _a16, _b;\n\t\t\tconst toolName = toolNamesByCallId[toolCallId];\n\t\t\treturn ((_b = (_a16 = this.tools) == null ? void 0 : _a16[toolName]) == null ? void 0 : _b.type) === \"dynamic\" ? true : void 0;\n\t\t};\n\t\treturn createAsyncIterableStream(handleUIMessageStreamFinish({\n\t\t\tstream: this.fullStream.pipeThrough(new TransformStream({ transform: async (part, controller) => {\n\t\t\t\tconst messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });\n\t\t\t\tconst partType = part.type;\n\t\t\t\tswitch (partType) {\n\t\t\t\t\tcase \"text-start\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-start\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\t\t\tif (sendReasoning) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-end\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"file\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\t\t\t\turl: `data:${part.file.mediaType};base64,${part.file.base64}`\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"source\":\n\t\t\t\t\t\tif (sendSources && part.sourceType === \"url\") controller.enqueue({\n\t\t\t\t\t\t\ttype: \"source-url\",\n\t\t\t\t\t\t\tsourceId: part.id,\n\t\t\t\t\t\t\turl: part.url,\n\t\t\t\t\t\t\ttitle: part.title,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (sendSources && part.sourceType === \"document\") controller.enqueue({\n\t\t\t\t\t\t\ttype: \"source-document\",\n\t\t\t\t\t\t\tsourceId: part.id,\n\t\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\t\ttitle: part.title,\n\t\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\t\ttoolNamesByCallId[part.id] = part.toolName;\n\t\t\t\t\t\tconst dynamic = isDynamic(part.id);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-start\",\n\t\t\t\t\t\t\ttoolCallId: part.id,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-delta\",\n\t\t\t\t\t\t\ttoolCallId: part.id,\n\t\t\t\t\t\t\tinputTextDelta: part.delta\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-call\": {\n\t\t\t\t\t\ttoolNamesByCallId[part.toolCallId] = part.toolName;\n\t\t\t\t\t\tconst dynamic = isDynamic(part.toolCallId);\n\t\t\t\t\t\tif (part.invalid) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-error\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\t\t\t\terrorText: onError(part.error)\n\t\t\t\t\t\t});\n\t\t\t\t\t\telse controller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-available\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-result\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part.toolCallId);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-available\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.preliminary != null ? { preliminary: part.preliminary } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-error\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part.toolCallId);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-error\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\terrorText: onError(part.error),\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terrorText: onError(part.error)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"start-step\":\n\t\t\t\t\t\tcontroller.enqueue({ type: \"start-step\" });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"finish-step\":\n\t\t\t\t\t\tcontroller.enqueue({ type: \"finish-step\" });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tif (sendStart) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"start\",\n\t\t\t\t\t\t\t...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},\n\t\t\t\t\t\t\t...responseMessageId != null ? { messageId: responseMessageId } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\tif (sendFinish) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t\t\t\t...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"abort\":\n\t\t\t\t\t\tcontroller.enqueue(part);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-input-end\": break;\n\t\t\t\t\tcase \"raw\": break;\n\t\t\t\t\tdefault: throw new Error(`Unknown chunk type: ${partType}`);\n\t\t\t\t}\n\t\t\t\tif (messageMetadataValue != null && partType !== \"start\" && partType !== \"finish\") controller.enqueue({\n\t\t\t\t\ttype: \"message-metadata\",\n\t\t\t\t\tmessageMetadata: messageMetadataValue\n\t\t\t\t});\n\t\t\t} })),\n\t\t\tmessageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),\n\t\t\toriginalMessages,\n\t\t\tonFinish,\n\t\t\tonError\n\t\t}));\n\t}\n\tpipeUIMessageStreamToResponse(response, { originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\tpipeUIMessageStreamToResponse({\n\t\t\tresponse,\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\tpipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoUIMessageStreamResponse({ originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\treturn createUIMessageStreamResponse({\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\nfunction convertToModelMessages(messages, options) {\n\tconst modelMessages = [];\n\tif (options == null ? void 0 : options.ignoreIncompleteToolCalls) messages = messages.map((message) => ({\n\t\t...message,\n\t\tparts: message.parts.filter((part) => !isToolOrDynamicToolUIPart(part) || part.state !== \"input-streaming\" && part.state !== \"input-available\")\n\t}));\n\tfor (const message of messages) switch (message.role) {\n\t\tcase \"system\": {\n\t\t\tconst textParts = message.parts.filter((part) => part.type === \"text\");\n\t\t\tconst providerMetadata = textParts.reduce((acc, part) => {\n\t\t\t\tif (part.providerMetadata != null) return {\n\t\t\t\t\t...acc,\n\t\t\t\t\t...part.providerMetadata\n\t\t\t\t};\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: textParts.map((part) => part.text).join(\"\"),\n\t\t\t\t...Object.keys(providerMetadata).length > 0 ? { providerOptions: providerMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"user\":\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.parts.map((part) => {\n\t\t\t\t\tvar _a16;\n\t\t\t\t\tif (isTextUIPart(part)) return {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isFileUIPart(part)) return {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.url,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isDataUIPart(part)) return (_a16 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a16.call(options, part);\n\t\t\t\t}).filter((part) => part != null)\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"assistant\":\n\t\t\tif (message.parts != null) {\n\t\t\t\tlet processBlock2 = function() {\n\t\t\t\t\tvar _a16, _b, _c;\n\t\t\t\t\tif (block.length === 0) return;\n\t\t\t\t\tconst content = [];\n\t\t\t\t\tfor (const part of block) if (isTextUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse if (isFileUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.url\n\t\t\t\t\t});\n\t\t\t\t\telse if (isReasoningUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse if (isDynamicToolUIPart(part)) {\n\t\t\t\t\t\tconst toolName = part.toolName;\n\t\t\t\t\t\tif (part.state !== \"input-streaming\") content.push({\n\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (isToolUIPart(part)) {\n\t\t\t\t\t\tconst toolName = getToolName(part);\n\t\t\t\t\t\tif (part.state !== \"input-streaming\") {\n\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\tinput: part.state === \"output-error\" ? (_a16 = part.input) != null ? _a16 : part.rawInput : part.input,\n\t\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\t\t...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (part.providerExecuted === true && (part.state === \"output-available\" || part.state === \"output-error\")) content.push({\n\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\t\t\t\t\toutput: part.state === \"output-error\" ? part.errorText : part.output,\n\t\t\t\t\t\t\t\t\ttool: (_b = options == null ? void 0 : options.tools) == null ? void 0 : _b[toolName],\n\t\t\t\t\t\t\t\t\terrorMode: part.state === \"output-error\" ? \"json\" : \"none\"\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (isDataUIPart(part)) {\n\t\t\t\t\t\tconst dataPart = (_c = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _c.call(options, part);\n\t\t\t\t\t\tif (dataPart != null) content.push(dataPart);\n\t\t\t\t\t} else throw new Error(`Unsupported part: ${part}`);\n\t\t\t\t\tmodelMessages.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent\n\t\t\t\t\t});\n\t\t\t\t\tconst toolParts = block.filter((part) => isToolUIPart(part) && part.providerExecuted !== true || part.type === \"dynamic-tool\");\n\t\t\t\t\tif (toolParts.length > 0) modelMessages.push({\n\t\t\t\t\t\trole: \"tool\",\n\t\t\t\t\t\tcontent: toolParts.map((toolPart) => {\n\t\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\t\tswitch (toolPart.state) {\n\t\t\t\t\t\t\t\tcase \"output-error\":\n\t\t\t\t\t\t\t\tcase \"output-available\": {\n\t\t\t\t\t\t\t\t\tconst toolName = getToolOrDynamicToolName(toolPart);\n\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\t\t\t\t\t\t\toutput: toolPart.state === \"output-error\" ? toolPart.errorText : toolPart.output,\n\t\t\t\t\t\t\t\t\t\t\ttool: (_a17 = options == null ? void 0 : options.tools) == null ? void 0 : _a17[toolName],\n\t\t\t\t\t\t\t\t\t\t\terrorMode: toolPart.state === \"output-error\" ? \"text\" : \"none\"\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tdefault: return null;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}).filter((output) => output != null)\n\t\t\t\t\t});\n\t\t\t\t\tblock = [];\n\t\t\t\t};\n\t\t\t\tlet block = [];\n\t\t\t\tfor (const part of message.parts) if (isTextUIPart(part) || isReasoningUIPart(part) || isFileUIPart(part) || isToolOrDynamicToolUIPart(part) || isDataUIPart(part)) block.push(part);\n\t\t\t\telse if (part.type === \"step-start\") processBlock2();\n\t\t\t\tprocessBlock2();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck = message.role;\n\t\t\tthrow new MessageConversionError({\n\t\t\t\toriginalMessage: message,\n\t\t\t\tmessage: `Unsupported role: ${_exhaustiveCheck}`\n\t\t\t});\n\t\t}\n\t}\n\treturn modelMessages;\n}\nvar convertToCoreMessages = convertToModelMessages;\nvar Agent = class {\n\tconstructor(settings) {\n\t\tthis.settings = settings;\n\t}\n\tget tools() {\n\t\treturn this.settings.tools;\n\t}\n\tasync generate(options) {\n\t\treturn generateText$1({\n\t\t\t...this.settings,\n\t\t\t...options\n\t\t});\n\t}\n\tstream(options) {\n\t\treturn streamText$1({\n\t\t\t...this.settings,\n\t\t\t...options\n\t\t});\n\t}\n\t/**\n\t* Creates a response object that streams UI messages to the client.\n\t*/\n\trespond(options) {\n\t\treturn this.stream({ prompt: convertToModelMessages(options.messages) }).toUIMessageStreamResponse();\n\t}\n};\nasync function embed({ model: modelArg, value, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry }) {\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: { maxRetries }\n\t});\n\tconst tracer = getTracer(telemetry);\n\treturn recordSpan({\n\t\tname: \"ai.embed\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.embed\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\"ai.value\": { input: () => JSON.stringify(value) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async (span) => {\n\t\t\tconst { embedding, usage, response, providerMetadata } = await retry(() => recordSpan({\n\t\t\t\tname: \"ai.embed.doEmbed\",\n\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\toperationId: \"ai.embed.doEmbed\",\n\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\"ai.values\": { input: () => [JSON.stringify(value)] }\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\ttracer,\n\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\tvar _a16;\n\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\tvalues: [value],\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t});\n\t\t\t\t\tconst embedding2 = modelResponse.embeddings[0];\n\t\t\t\t\tconst usage2 = (_a16 = modelResponse.usage) != null ? _a16 : { tokens: NaN };\n\t\t\t\t\tdoEmbedSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => modelResponse.embeddings.map((embedding3) => JSON.stringify(embedding3)) },\n\t\t\t\t\t\t\t\"ai.usage.tokens\": usage2.tokens\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\treturn {\n\t\t\t\t\t\tembedding: embedding2,\n\t\t\t\t\t\tusage: usage2,\n\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}));\n\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t\"ai.embedding\": { output: () => JSON.stringify(embedding) },\n\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t}\n\t\t\t}));\n\t\t\treturn new DefaultEmbedResult({\n\t\t\t\tvalue,\n\t\t\t\tembedding,\n\t\t\t\tusage,\n\t\t\t\tproviderMetadata,\n\t\t\t\tresponse\n\t\t\t});\n\t\t}\n\t});\n}\nvar DefaultEmbedResult = class {\n\tconstructor(options) {\n\t\tthis.value = options.value;\n\t\tthis.embedding = options.embedding;\n\t\tthis.usage = options.usage;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t}\n};\nfunction splitArray(array, chunkSize) {\n\tif (chunkSize <= 0) throw new Error(\"chunkSize must be greater than 0\");\n\tconst result = [];\n\tfor (let i = 0; i < array.length; i += chunkSize) result.push(array.slice(i, i + chunkSize));\n\treturn result;\n}\nasync function embedMany({ model: modelArg, values, maxParallelCalls = Infinity, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry }) {\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: { maxRetries }\n\t});\n\tconst tracer = getTracer(telemetry);\n\treturn recordSpan({\n\t\tname: \"ai.embedMany\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.embedMany\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\"ai.values\": { input: () => values.map((value) => JSON.stringify(value)) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async (span) => {\n\t\t\tvar _a16;\n\t\t\tconst [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([model.maxEmbeddingsPerCall, model.supportsParallelCalls]);\n\t\t\tif (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {\n\t\t\t\tconst { embeddings: embeddings2, usage, response, providerMetadata: providerMetadata2 } = await retry(() => {\n\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\tname: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\"ai.values\": { input: () => values.map((value) => JSON.stringify(value)) }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst embeddings3 = modelResponse.embeddings;\n\t\t\t\t\t\t\tconst usage2 = (_a17 = modelResponse.usage) != null ? _a17 : { tokens: NaN };\n\t\t\t\t\t\t\tdoEmbedSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings3.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\t\t\t\"ai.usage.tokens\": usage2.tokens\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tembeddings: embeddings3,\n\t\t\t\t\t\t\t\tusage: usage2,\n\t\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\t\tvalues,\n\t\t\t\t\tembeddings: embeddings2,\n\t\t\t\t\tusage,\n\t\t\t\t\tproviderMetadata: providerMetadata2,\n\t\t\t\t\tresponses: [response]\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst valueChunks = splitArray(values, maxEmbeddingsPerCall);\n\t\t\tconst embeddings = [];\n\t\t\tconst responses = [];\n\t\t\tlet tokens = 0;\n\t\t\tlet providerMetadata;\n\t\t\tconst parallelChunks = splitArray(valueChunks, supportsParallelCalls ? maxParallelCalls : 1);\n\t\t\tfor (const parallelChunk of parallelChunks) {\n\t\t\t\tconst results = await Promise.all(parallelChunk.map((chunk) => {\n\t\t\t\t\treturn retry(() => {\n\t\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\t\tname: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\t\"ai.values\": { input: () => chunk.map((value) => JSON.stringify(value)) }\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\t\t\tvalues: chunk,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst embeddings2 = modelResponse.embeddings;\n\t\t\t\t\t\t\t\tconst usage = (_a17 = modelResponse.usage) != null ? _a17 : { tokens: NaN };\n\t\t\t\t\t\t\t\tdoEmbedSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tembeddings: embeddings2,\n\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}));\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tembeddings.push(...result.embeddings);\n\t\t\t\t\tresponses.push(result.response);\n\t\t\t\t\ttokens += result.usage.tokens;\n\t\t\t\t\tif (result.providerMetadata) if (!providerMetadata) providerMetadata = { ...result.providerMetadata };\n\t\t\t\t\telse for (const [providerName, metadata] of Object.entries(result.providerMetadata)) providerMetadata[providerName] = {\n\t\t\t\t\t\t...(_a16 = providerMetadata[providerName]) != null ? _a16 : {},\n\t\t\t\t\t\t...metadata\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\"ai.usage.tokens\": tokens\n\t\t\t\t}\n\t\t\t}));\n\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\tvalues,\n\t\t\t\tembeddings,\n\t\t\t\tusage: { tokens },\n\t\t\t\tproviderMetadata,\n\t\t\t\tresponses\n\t\t\t});\n\t\t}\n\t});\n}\nvar DefaultEmbedManyResult = class {\n\tconstructor(options) {\n\t\tthis.values = options.values;\n\t\tthis.embeddings = options.embeddings;\n\t\tthis.usage = options.usage;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.responses = options.responses;\n\t}\n};\nasync function generateImage({ model: modelArg, prompt, n = 1, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tvar _a16;\n\tconst model = resolveImageModel(modelArg);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst maxImagesPerCallWithDefault = (_a16 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a16 : 1;\n\tconst callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n\tconst callImageCounts = Array.from({ length: callCount }, (_, i) => {\n\t\tif (i < callCount - 1) return maxImagesPerCallWithDefault;\n\t\tconst remainder = n % maxImagesPerCallWithDefault;\n\t\treturn remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n\t});\n\tconst results = await Promise.all(callImageCounts.map(async (callImageCount) => retry(() => model.doGenerate({\n\t\tprompt,\n\t\tn: callImageCount,\n\t\tabortSignal,\n\t\theaders: headersWithUserAgent,\n\t\tsize,\n\t\taspectRatio,\n\t\tseed,\n\t\tproviderOptions: providerOptions != null ? providerOptions : {}\n\t}))));\n\tconst images = [];\n\tconst warnings = [];\n\tconst responses = [];\n\tconst providerMetadata = {};\n\tfor (const result of results) {\n\t\timages.push(...result.images.map((image) => {\n\t\t\tvar _a17;\n\t\t\treturn new DefaultGeneratedFile({\n\t\t\t\tdata: image,\n\t\t\t\tmediaType: (_a17 = detectMediaType({\n\t\t\t\t\tdata: image,\n\t\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t\t})) != null ? _a17 : \"image/png\"\n\t\t\t});\n\t\t}));\n\t\twarnings.push(...result.warnings);\n\t\tif (result.providerMetadata) for (const [providerName, metadata] of Object.entries(result.providerMetadata)) if (providerName === \"gateway\") {\n\t\t\tconst currentEntry = providerMetadata[providerName];\n\t\t\tif (currentEntry != null && typeof currentEntry === \"object\") providerMetadata[providerName] = {\n\t\t\t\t...currentEntry,\n\t\t\t\t...metadata\n\t\t\t};\n\t\t\telse providerMetadata[providerName] = metadata;\n\t\t\tconst imagesValue = providerMetadata[providerName].images;\n\t\t\tif (Array.isArray(imagesValue) && imagesValue.length === 0) delete providerMetadata[providerName].images;\n\t\t} else {\n\t\t\tproviderMetadata[providerName] ?? (providerMetadata[providerName] = { images: [] });\n\t\t\tproviderMetadata[providerName].images.push(...result.providerMetadata[providerName].images);\n\t\t}\n\t\tresponses.push(result.response);\n\t}\n\tlogWarnings(warnings);\n\tif (!images.length) throw new NoImageGeneratedError({ responses });\n\treturn new DefaultGenerateImageResult({\n\t\timages,\n\t\twarnings,\n\t\tresponses,\n\t\tproviderMetadata\n\t});\n}\nvar DefaultGenerateImageResult = class {\n\tconstructor(options) {\n\t\tthis.images = options.images;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t}\n\tget image() {\n\t\treturn this.images[0];\n\t}\n};\nasync function invokeModelMaxImagesPerCall(model) {\n\tif (!(model.maxImagesPerCall instanceof Function)) return model.maxImagesPerCall;\n\treturn model.maxImagesPerCall({ modelId: model.modelId });\n}\nfunction extractReasoningContent(content) {\n\tconst parts = content.filter((content2) => content2.type === \"reasoning\");\n\treturn parts.length === 0 ? void 0 : parts.map((content2) => content2.text).join(\"\\n\");\n}\nvar noSchemaOutputStrategy = {\n\ttype: \"no-schema\",\n\tjsonSchema: void 0,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value, context) {\n\t\treturn value === void 0 ? {\n\t\t\tsuccess: false,\n\t\t\terror: new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\ttext: context.text,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t})\n\t\t} : {\n\t\t\tsuccess: true,\n\t\t\tvalue\n\t\t};\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in no-schema mode\" });\n\t}\n};\nvar objectOutputStrategy = (schema) => ({\n\ttype: \"object\",\n\tjsonSchema: schema.jsonSchema,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value) {\n\t\treturn safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in object mode\" });\n\t}\n});\nvar arrayOutputStrategy = (schema) => {\n\tconst { $schema, ...itemSchema } = schema.jsonSchema;\n\treturn {\n\t\ttype: \"array\",\n\t\tjsonSchema: {\n\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\ttype: \"object\",\n\t\t\tproperties: { elements: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: itemSchema\n\t\t\t} },\n\t\t\trequired: [\"elements\"],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tasync validatePartialResult({ value, latestObject, isFirstDelta, isFinalDelta }) {\n\t\t\tvar _a16;\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (let i = 0; i < inputArray.length; i++) {\n\t\t\t\tconst element = inputArray[i];\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (i === inputArray.length - 1 && !isFinalDelta) continue;\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\tconst publishedElementCount = (_a16 = latestObject == null ? void 0 : latestObject.length) != null ? _a16 : 0;\n\t\t\tlet textDelta = \"\";\n\t\t\tif (isFirstDelta) textDelta += \"[\";\n\t\t\tif (publishedElementCount > 0) textDelta += \",\";\n\t\t\ttextDelta += resultArray.slice(publishedElementCount).map((element) => JSON.stringify(element)).join(\",\");\n\t\t\tif (isFinalDelta) textDelta += \"]\";\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: resultArray,\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (const element of inputArray) {\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: resultArray\n\t\t\t};\n\t\t},\n\t\tcreateElementStream(originalStream) {\n\t\t\tlet publishedElements = 0;\n\t\t\treturn createAsyncIterableStream(originalStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\tcase \"object\": {\n\t\t\t\t\t\tconst array = chunk.object;\n\t\t\t\t\t\tfor (; publishedElements < array.length; publishedElements++) controller.enqueue(array[publishedElements]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\tcase \"error\": break;\n\t\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t\t}\n\t\t\t} })));\n\t\t}\n\t};\n};\nvar enumOutputStrategy = (enumValues) => {\n\treturn {\n\t\ttype: \"enum\",\n\t\tjsonSchema: {\n\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\ttype: \"object\",\n\t\t\tproperties: { result: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tenum: enumValues\n\t\t\t} },\n\t\t\trequired: [\"result\"],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\treturn enumValues.includes(result) ? {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: result\n\t\t\t} : {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t},\n\t\tasync validatePartialResult({ value, textDelta }) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\tconst possibleEnumValues = enumValues.filter((enumValue) => enumValue.startsWith(result));\n\t\t\tif (value.result.length === 0 || possibleEnumValues.length === 0) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tcreateElementStream() {\n\t\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in enum mode\" });\n\t\t}\n\t};\n};\nfunction getOutputStrategy({ output, schema, enumValues }) {\n\tswitch (output) {\n\t\tcase \"object\": return objectOutputStrategy(asSchema(schema));\n\t\tcase \"array\": return arrayOutputStrategy(asSchema(schema));\n\t\tcase \"enum\": return enumOutputStrategy(enumValues);\n\t\tcase \"no-schema\": return noSchemaOutputStrategy;\n\t\tdefault: throw new Error(`Unsupported output: ${output}`);\n\t}\n}\nasync function parseAndValidateObjectResult(result, outputStrategy, context) {\n\tconst parseResult = await safeParseJSON({ text: result });\n\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: could not parse the response.\",\n\t\tcause: parseResult.error,\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage,\n\t\tfinishReason: context.finishReason\n\t});\n\tconst validationResult = await outputStrategy.validateFinalResult(parseResult.value, {\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage\n\t});\n\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: response did not match schema.\",\n\t\tcause: validationResult.error,\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage,\n\t\tfinishReason: context.finishReason\n\t});\n\treturn validationResult.value;\n}\nasync function parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, context) {\n\ttry {\n\t\treturn await parseAndValidateObjectResult(result, outputStrategy, context);\n\t} catch (error) {\n\t\tif (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError.isInstance(error.cause) || TypeValidationError.isInstance(error.cause))) {\n\t\t\tconst repairedText = await repairText({\n\t\t\t\ttext: result,\n\t\t\t\terror: error.cause\n\t\t\t});\n\t\t\tif (repairedText === null) throw error;\n\t\t\treturn await parseAndValidateObjectResult(repairedText, outputStrategy, context);\n\t\t}\n\t\tthrow error;\n\t}\n}\nfunction validateObjectGenerationInput({ output, schema, schemaName, schemaDescription, enumValues }) {\n\tif (output != null && output !== \"object\" && output !== \"array\" && output !== \"enum\" && output !== \"no-schema\") throw new InvalidArgumentError({\n\t\tparameter: \"output\",\n\t\tvalue: output,\n\t\tmessage: \"Invalid output type.\"\n\t});\n\tif (output === \"no-schema\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for no-schema output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for no-schema output.\"\n\t\t});\n\t}\n\tif (output === \"object\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is required for object output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for object output.\"\n\t\t});\n\t}\n\tif (output === \"array\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Element schema is required for array output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for array output.\"\n\t\t});\n\t}\n\tif (output === \"enum\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for enum output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for enum output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for enum output.\"\n\t\t});\n\t\tif (enumValues == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are required for enum output.\"\n\t\t});\n\t\tfor (const value of enumValues) if (typeof value !== \"string\") throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue,\n\t\t\tmessage: \"Enum values must be strings.\"\n\t\t});\n\t}\n}\nvar originalGenerateId3 = createIdGenerator({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\nasync function generateObject(options) {\n\tconst { model: modelArg, output = \"object\", system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, headers, experimental_repairText: repairText, experimental_telemetry: telemetry, experimental_download: download2, providerOptions, _internal: { generateId: generateId3 = originalGenerateId3, currentDate = () => /* @__PURE__ */ new Date() } = {}, ...settings } = options;\n\tconst model = resolveLanguageModel(modelArg);\n\tconst enumValues = \"enum\" in options ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst outputStrategy = getOutputStrategy({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tenumValues\n\t});\n\tconst callSettings = prepareCallSettings(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: {\n\t\t\t...callSettings,\n\t\t\tmaxRetries\n\t\t}\n\t});\n\tconst tracer = getTracer(telemetry);\n\ttry {\n\t\treturn await recordSpan({\n\t\t\tname: \"ai.generateObject\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.generateObject\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) },\n\t\t\t\t\t\"ai.schema\": outputStrategy.jsonSchema != null ? { input: () => JSON.stringify(outputStrategy.jsonSchema) } : void 0,\n\t\t\t\t\t\"ai.schema.name\": schemaName,\n\t\t\t\t\t\"ai.schema.description\": schemaDescription,\n\t\t\t\t\t\"ai.settings.output\": outputStrategy.type\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\tvar _a16;\n\t\t\t\tlet result;\n\t\t\t\tlet finishReason;\n\t\t\t\tlet usage;\n\t\t\t\tlet warnings;\n\t\t\t\tlet response;\n\t\t\t\tlet request;\n\t\t\t\tlet resultProviderMetadata;\n\t\t\t\tlet reasoning;\n\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\tprompt: await standardizePrompt({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tallowSystemInMessages\n\t\t\t\t\t}),\n\t\t\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\t\t\tdownload: download2\n\t\t\t\t});\n\t\t\t\tconst generateResult = await retry(() => recordSpan({\n\t\t\t\t\tname: \"ai.generateObject.doGenerate\",\n\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\toperationId: \"ai.generateObject.doGenerate\",\n\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\"gen_ai.system\": model.provider,\n\t\t\t\t\t\t\t\"gen_ai.request.model\": model.modelId,\n\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\ttracer,\n\t\t\t\t\tfn: async (span2) => {\n\t\t\t\t\t\tvar _a17, _b, _c, _d, _e, _f, _g, _h;\n\t\t\t\t\t\tconst result2 = await model.doGenerate({\n\t\t\t\t\t\t\tresponseFormat: {\n\t\t\t\t\t\t\t\ttype: \"json\",\n\t\t\t\t\t\t\t\tschema: outputStrategy.jsonSchema,\n\t\t\t\t\t\t\t\tname: schemaName,\n\t\t\t\t\t\t\t\tdescription: schemaDescription\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...prepareCallSettings(settings),\n\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst responseData = {\n\t\t\t\t\t\t\tid: (_b = (_a17 = result2.response) == null ? void 0 : _a17.id) != null ? _b : generateId3(),\n\t\t\t\t\t\t\ttimestamp: (_d = (_c = result2.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),\n\t\t\t\t\t\t\tmodelId: (_f = (_e = result2.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,\n\t\t\t\t\t\t\theaders: (_g = result2.response) == null ? void 0 : _g.headers,\n\t\t\t\t\t\t\tbody: (_h = result2.response) == null ? void 0 : _h.body\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst text2 = extractTextContent(result2.content);\n\t\t\t\t\t\tconst reasoning2 = extractReasoningContent(result2.content);\n\t\t\t\t\t\tif (text2 === void 0) throw new NoObjectGeneratedError({\n\t\t\t\t\t\t\tmessage: \"No object generated: the model did not return a response.\",\n\t\t\t\t\t\t\tresponse: responseData,\n\t\t\t\t\t\t\tusage: result2.usage,\n\t\t\t\t\t\t\tfinishReason: result2.finishReason\n\t\t\t\t\t\t});\n\t\t\t\t\t\tspan2.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\"ai.response.finishReason\": result2.finishReason,\n\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => text2 },\n\t\t\t\t\t\t\t\t\"ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\"ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\"ai.response.timestamp\": responseData.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(result2.providerMetadata),\n\t\t\t\t\t\t\t\t\"ai.usage.promptTokens\": result2.usage.inputTokens,\n\t\t\t\t\t\t\t\t\"ai.usage.completionTokens\": result2.usage.outputTokens,\n\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [result2.finishReason],\n\t\t\t\t\t\t\t\t\"gen_ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\"gen_ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": result2.usage.inputTokens,\n\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": result2.usage.outputTokens\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}));\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t...result2,\n\t\t\t\t\t\t\tobjectText: text2,\n\t\t\t\t\t\t\treasoning: reasoning2,\n\t\t\t\t\t\t\tresponseData\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tresult = generateResult.objectText;\n\t\t\t\tfinishReason = generateResult.finishReason;\n\t\t\t\tusage = generateResult.usage;\n\t\t\t\twarnings = generateResult.warnings;\n\t\t\t\tresultProviderMetadata = generateResult.providerMetadata;\n\t\t\t\trequest = (_a16 = generateResult.request) != null ? _a16 : {};\n\t\t\t\tresponse = generateResult.responseData;\n\t\t\t\treasoning = generateResult.reasoning;\n\t\t\t\tlogWarnings(warnings);\n\t\t\t\tconst object2 = await parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, {\n\t\t\t\t\tresponse,\n\t\t\t\t\tusage,\n\t\t\t\t\tfinishReason\n\t\t\t\t});\n\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(resultProviderMetadata),\n\t\t\t\t\t\t\"ai.usage.promptTokens\": usage.inputTokens,\n\t\t\t\t\t\t\"ai.usage.completionTokens\": usage.outputTokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\treturn new DefaultGenerateObjectResult({\n\t\t\t\t\tobject: object2,\n\t\t\t\t\treasoning,\n\t\t\t\t\tfinishReason,\n\t\t\t\t\tusage,\n\t\t\t\t\twarnings,\n\t\t\t\t\trequest,\n\t\t\t\t\tresponse,\n\t\t\t\t\tproviderMetadata: resultProviderMetadata\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nvar DefaultGenerateObjectResult = class {\n\tconstructor(options) {\n\t\tthis.object = options.object;\n\t\tthis.finishReason = options.finishReason;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t\tthis.request = options.request;\n\t\tthis.reasoning = options.reasoning;\n\t}\n\ttoJsonResponse(init) {\n\t\tvar _a16;\n\t\treturn new Response(JSON.stringify(this.object), {\n\t\t\tstatus: (_a16 = init == null ? void 0 : init.status) != null ? _a16 : 200,\n\t\t\theaders: prepareHeaders(init == null ? void 0 : init.headers, { \"content-type\": \"application/json; charset=utf-8\" })\n\t\t});\n\t}\n};\nfunction cosineSimilarity(vector1, vector2) {\n\tif (vector1.length !== vector2.length) throw new InvalidArgumentError({\n\t\tparameter: \"vector1,vector2\",\n\t\tvalue: {\n\t\t\tvector1Length: vector1.length,\n\t\t\tvector2Length: vector2.length\n\t\t},\n\t\tmessage: `Vectors must have the same length`\n\t});\n\tconst n = vector1.length;\n\tif (n === 0) return 0;\n\tlet magnitudeSquared1 = 0;\n\tlet magnitudeSquared2 = 0;\n\tlet dotProduct = 0;\n\tfor (let i = 0; i < n; i++) {\n\t\tconst value1 = vector1[i];\n\t\tconst value2 = vector2[i];\n\t\tmagnitudeSquared1 += value1 * value1;\n\t\tmagnitudeSquared2 += value2 * value2;\n\t\tdotProduct += value1 * value2;\n\t}\n\treturn magnitudeSquared1 === 0 || magnitudeSquared2 === 0 ? 0 : dotProduct / (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\nfunction createDownload(options) {\n\treturn ({ url, abortSignal }) => download({\n\t\turl,\n\t\tmaxBytes: options == null ? void 0 : options.maxBytes,\n\t\tabortSignal\n\t});\n}\nfunction getTextFromDataUrl(dataUrl) {\n\tconst [header, base64Content] = dataUrl.split(\",\");\n\tif (header.split(\";\")[0].split(\":\")[1] == null || base64Content == null) throw new Error(\"Invalid data URL format\");\n\ttry {\n\t\treturn window.atob(base64Content);\n\t} catch (error) {\n\t\tthrow new Error(`Error decoding data URL`);\n\t}\n}\nfunction isDeepEqualData(obj1, obj2) {\n\tif (obj1 === obj2) return true;\n\tif (obj1 == null || obj2 == null) return false;\n\tif (typeof obj1 !== \"object\" && typeof obj2 !== \"object\") return obj1 === obj2;\n\tif (obj1.constructor !== obj2.constructor) return false;\n\tif (obj1 instanceof Date && obj2 instanceof Date) return obj1.getTime() === obj2.getTime();\n\tif (Array.isArray(obj1)) {\n\t\tif (obj1.length !== obj2.length) return false;\n\t\tfor (let i = 0; i < obj1.length; i++) if (!isDeepEqualData(obj1[i], obj2[i])) return false;\n\t\treturn true;\n\t}\n\tconst keys1 = Object.keys(obj1);\n\tconst keys2 = Object.keys(obj2);\n\tif (keys1.length !== keys2.length) return false;\n\tfor (const key of keys1) {\n\t\tif (!keys2.includes(key)) return false;\n\t\tif (!isDeepEqualData(obj1[key], obj2[key])) return false;\n\t}\n\treturn true;\n}\nvar SerialJobExecutor = class {\n\tconstructor() {\n\t\tthis.queue = [];\n\t\tthis.isProcessing = false;\n\t}\n\tasync processQueue() {\n\t\tif (this.isProcessing) return;\n\t\tthis.isProcessing = true;\n\t\twhile (this.queue.length > 0) {\n\t\t\tawait this.queue[0]();\n\t\t\tthis.queue.shift();\n\t\t}\n\t\tthis.isProcessing = false;\n\t}\n\tasync run(job) {\n\t\treturn new Promise((resolve2, reject) => {\n\t\t\tthis.queue.push(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait job();\n\t\t\t\t\tresolve2();\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.processQueue();\n\t\t});\n\t}\n};\nfunction simulateReadableStream({ chunks, initialDelayInMs = 0, chunkDelayInMs = 0, _internal }) {\n\tvar _a16;\n\tconst delay2 = (_a16 = _internal == null ? void 0 : _internal.delay) != null ? _a16 : delay;\n\tlet index = 0;\n\treturn new ReadableStream({ async pull(controller) {\n\t\tif (index < chunks.length) {\n\t\t\tawait delay2(index === 0 ? initialDelayInMs : chunkDelayInMs);\n\t\t\tcontroller.enqueue(chunks[index++]);\n\t\t} else controller.close();\n\t} });\n}\nvar originalGenerateId4 = createIdGenerator({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\nfunction streamObject(options) {\n\tconst { model, output = \"object\", system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, headers, experimental_repairText: repairText, experimental_telemetry: telemetry, experimental_download: download2, providerOptions, onError = ({ error }) => {\n\t\tconsole.error(error);\n\t}, onFinish, _internal: { generateId: generateId3 = originalGenerateId4, currentDate = () => /* @__PURE__ */ new Date(), now: now2 = now } = {}, ...settings } = options;\n\tconst enumValues = \"enum\" in options && options.enum ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\treturn new DefaultStreamObjectResult({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tabortSignal,\n\t\toutputStrategy: getOutputStrategy({\n\t\t\toutput,\n\t\t\tschema: inputSchema,\n\t\t\tenumValues\n\t\t}),\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tproviderOptions,\n\t\trepairText,\n\t\tonError,\n\t\tonFinish,\n\t\tdownload: download2,\n\t\tgenerateId: generateId3,\n\t\tcurrentDate,\n\t\tnow: now2\n\t});\n}\nvar DefaultStreamObjectResult = class {\n\tconstructor({ model: modelArg, headers, telemetry, settings, maxRetries: maxRetriesArg, abortSignal, outputStrategy, system, prompt, messages, allowSystemInMessages, schemaName, schemaDescription, providerOptions, repairText, onError, onFinish, download: download2, generateId: generateId3, currentDate, now: now2 }) {\n\t\tthis._object = new DelayedPromise();\n\t\tthis._usage = new DelayedPromise();\n\t\tthis._providerMetadata = new DelayedPromise();\n\t\tthis._warnings = new DelayedPromise();\n\t\tthis._request = new DelayedPromise();\n\t\tthis._response = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tconst model = resolveLanguageModel(modelArg);\n\t\tconst { maxRetries, retry } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst callSettings = prepareCallSettings(settings);\n\t\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\t\tmodel,\n\t\t\ttelemetry,\n\t\t\theaders,\n\t\t\tsettings: {\n\t\t\t\t...callSettings,\n\t\t\t\tmaxRetries\n\t\t\t}\n\t\t});\n\t\tconst tracer = getTracer(telemetry);\n\t\tconst self = this;\n\t\tconst stitchableStream = createStitchableStream();\n\t\tconst eventProcessor = new TransformStream({ transform(chunk, controller) {\n\t\t\tcontroller.enqueue(chunk);\n\t\t\tif (chunk.type === \"error\") onError({ error: wrapGatewayError(chunk.error) });\n\t\t} });\n\t\tthis.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n\t\trecordSpan({\n\t\t\tname: \"ai.streamObject\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.streamObject\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) },\n\t\t\t\t\t\"ai.schema\": outputStrategy.jsonSchema != null ? { input: () => JSON.stringify(outputStrategy.jsonSchema) } : void 0,\n\t\t\t\t\t\"ai.schema.name\": schemaName,\n\t\t\t\t\t\"ai.schema.description\": schemaDescription,\n\t\t\t\t\t\"ai.settings.output\": outputStrategy.type\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tendWhenDone: false,\n\t\t\tfn: async (rootSpan) => {\n\t\t\t\tconst standardizedPrompt = await standardizePrompt({\n\t\t\t\t\tsystem,\n\t\t\t\t\tprompt,\n\t\t\t\t\tmessages,\n\t\t\t\t\tallowSystemInMessages\n\t\t\t\t});\n\t\t\t\tconst callOptions = {\n\t\t\t\t\tresponseFormat: {\n\t\t\t\t\t\ttype: \"json\",\n\t\t\t\t\t\tschema: outputStrategy.jsonSchema,\n\t\t\t\t\t\tname: schemaName,\n\t\t\t\t\t\tdescription: schemaDescription\n\t\t\t\t\t},\n\t\t\t\t\t...prepareCallSettings(settings),\n\t\t\t\t\tprompt: await convertToLanguageModelPrompt({\n\t\t\t\t\t\tprompt: standardizedPrompt,\n\t\t\t\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\t\t\t\tdownload: download2\n\t\t\t\t\t}),\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\theaders,\n\t\t\t\t\tincludeRawChunks: false\n\t\t\t\t};\n\t\t\t\tconst transformer = { transform: (chunk, controller) => {\n\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\t\tcontroller.enqueue(chunk.delta);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\tcase \"stream-start\":\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} };\n\t\t\t\tconst { result: { stream, response, request }, doStreamSpan, startTimestampMs } = await retry(() => recordSpan({\n\t\t\t\t\tname: \"ai.streamObject.doStream\",\n\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\toperationId: \"ai.streamObject.doStream\",\n\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(callOptions.prompt) },\n\t\t\t\t\t\t\t\"gen_ai.system\": model.provider,\n\t\t\t\t\t\t\t\"gen_ai.request.model\": model.modelId,\n\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\ttracer,\n\t\t\t\t\tendWhenDone: false,\n\t\t\t\t\tfn: async (doStreamSpan2) => ({\n\t\t\t\t\t\tstartTimestampMs: now2(),\n\t\t\t\t\t\tdoStreamSpan: doStreamSpan2,\n\t\t\t\t\t\tresult: await model.doStream(callOptions)\n\t\t\t\t\t})\n\t\t\t\t}));\n\t\t\t\tself._request.resolve(request != null ? request : {});\n\t\t\t\tlet warnings;\n\t\t\t\tlet usage = {\n\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t};\n\t\t\t\tlet finishReason;\n\t\t\t\tlet providerMetadata;\n\t\t\t\tlet object2;\n\t\t\t\tlet error;\n\t\t\t\tlet accumulatedText = \"\";\n\t\t\t\tlet textDelta = \"\";\n\t\t\t\tlet fullResponse = {\n\t\t\t\t\tid: generateId3(),\n\t\t\t\t\ttimestamp: currentDate(),\n\t\t\t\t\tmodelId: model.modelId\n\t\t\t\t};\n\t\t\t\tlet latestObjectJson = void 0;\n\t\t\t\tlet latestObject = void 0;\n\t\t\t\tlet isFirstChunk = true;\n\t\t\t\tlet isFirstDelta = true;\n\t\t\t\tconst transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(new TransformStream({\n\t\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\t\tvar _a16, _b, _c;\n\t\t\t\t\t\tif (typeof chunk === \"object\" && chunk.type === \"stream-start\") {\n\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isFirstChunk) {\n\t\t\t\t\t\t\tconst msToFirstChunk = now2() - startTimestampMs;\n\t\t\t\t\t\t\tisFirstChunk = false;\n\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.firstChunk\", { \"ai.stream.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\tdoStreamSpan.setAttributes({ \"ai.stream.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof chunk === \"string\") {\n\t\t\t\t\t\t\taccumulatedText += chunk;\n\t\t\t\t\t\t\ttextDelta += chunk;\n\t\t\t\t\t\t\tconst { value: currentObjectJson, state: parseState } = await parsePartialJson(accumulatedText);\n\t\t\t\t\t\t\tif (currentObjectJson !== void 0 && !isDeepEqualData(latestObjectJson, currentObjectJson)) {\n\t\t\t\t\t\t\t\tconst validationResult = await outputStrategy.validatePartialResult({\n\t\t\t\t\t\t\t\t\tvalue: currentObjectJson,\n\t\t\t\t\t\t\t\t\ttextDelta,\n\t\t\t\t\t\t\t\t\tlatestObject,\n\t\t\t\t\t\t\t\t\tisFirstDelta,\n\t\t\t\t\t\t\t\t\tisFinalDelta: parseState === \"successful-parse\"\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (validationResult.success && !isDeepEqualData(latestObject, validationResult.value.partial)) {\n\t\t\t\t\t\t\t\t\tlatestObjectJson = currentObjectJson;\n\t\t\t\t\t\t\t\t\tlatestObject = validationResult.value.partial;\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\tobject: latestObject\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\t\ttextDelta: validationResult.value.textDelta\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\ttextDelta = \"\";\n\t\t\t\t\t\t\t\t\tisFirstDelta = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\t\t\tfullResponse = {\n\t\t\t\t\t\t\t\t\tid: (_a16 = chunk.id) != null ? _a16 : fullResponse.id,\n\t\t\t\t\t\t\t\t\ttimestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,\n\t\t\t\t\t\t\t\t\tmodelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\t\t\tif (textDelta !== \"\") controller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\ttextDelta\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tfinishReason = chunk.finishReason;\n\t\t\t\t\t\t\t\tusage = chunk.usage;\n\t\t\t\t\t\t\t\tproviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\tresponse: fullResponse\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tlogWarnings(warnings != null ? warnings : []);\n\t\t\t\t\t\t\t\tself._usage.resolve(usage);\n\t\t\t\t\t\t\t\tself._providerMetadata.resolve(providerMetadata);\n\t\t\t\t\t\t\t\tself._warnings.resolve(warnings);\n\t\t\t\t\t\t\t\tself._response.resolve({\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself._finishReason.resolve(finishReason != null ? finishReason : \"unknown\");\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tobject2 = await parseAndValidateObjectResultWithRepair(accumulatedText, outputStrategy, repairText, {\n\t\t\t\t\t\t\t\t\t\tresponse: fullResponse,\n\t\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\t\tfinishReason\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tself._object.resolve(object2);\n\t\t\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\t\t\terror = e;\n\t\t\t\t\t\t\t\t\tself._object.reject(e);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tasync flush(controller) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst finalUsage = usage != null ? usage : {\n\t\t\t\t\t\t\t\tpromptTokens: NaN,\n\t\t\t\t\t\t\t\tcompletionTokens: NaN,\n\t\t\t\t\t\t\t\ttotalTokens: NaN\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tdoStreamSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\t\t\t\"ai.response.id\": fullResponse.id,\n\t\t\t\t\t\t\t\t\t\"ai.response.model\": fullResponse.modelId,\n\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": fullResponse.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(providerMetadata),\n\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": finalUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": finalUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [finishReason],\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": fullResponse.id,\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": fullResponse.modelId,\n\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": finalUsage.outputTokens\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tdoStreamSpan.end();\n\t\t\t\t\t\t\trootSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": finalUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": finalUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(providerMetadata)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tawait (onFinish == null ? void 0 : onFinish({\n\t\t\t\t\t\t\t\tusage: finalUsage,\n\t\t\t\t\t\t\t\tobject: object2,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\t\tproviderMetadata\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t} catch (error2) {\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: error2\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trootSpan.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tstitchableStream.addStream(transformedStream);\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tstitchableStream.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t}).finally(() => {\n\t\t\tstitchableStream.close();\n\t\t});\n\t\tthis.outputStrategy = outputStrategy;\n\t}\n\tget object() {\n\t\treturn this._object.promise;\n\t}\n\tget usage() {\n\t\treturn this._usage.promise;\n\t}\n\tget providerMetadata() {\n\t\treturn this._providerMetadata.promise;\n\t}\n\tget warnings() {\n\t\treturn this._warnings.promise;\n\t}\n\tget request() {\n\t\treturn this._request.promise;\n\t}\n\tget response() {\n\t\treturn this._response.promise;\n\t}\n\tget finishReason() {\n\t\treturn this._finishReason.promise;\n\t}\n\tget partialObjectStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"object\":\n\t\t\t\t\tcontroller.enqueue(chunk.object);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"text-delta\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget elementStream() {\n\t\treturn this.outputStrategy.createElementStream(this.baseStream);\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcontroller.enqueue(chunk.textDelta);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"object\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn createAsyncIterableStream(this.baseStream);\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\tpipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\nvar DefaultGeneratedAudioFile = class extends DefaultGeneratedFile {\n\tconstructor({ data, mediaType }) {\n\t\tsuper({\n\t\t\tdata,\n\t\t\tmediaType\n\t\t});\n\t\tlet format = \"mp3\";\n\t\tif (mediaType) {\n\t\t\tconst mediaTypeParts = mediaType.split(\"/\");\n\t\t\tif (mediaTypeParts.length === 2) {\n\t\t\t\tif (mediaType !== \"audio/mpeg\") format = mediaTypeParts[1];\n\t\t\t}\n\t\t}\n\t\tif (!format) throw new Error(\"Audio format must be provided or determinable from media type\");\n\t\tthis.format = format;\n\t}\n};\nasync function generateSpeech({ model, text: text2, voice, outputFormat, instructions, speed, language, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tvar _a16;\n\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\tversion: model.specificationVersion,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst result = await retry(() => model.doGenerate({\n\t\ttext: text2,\n\t\tvoice,\n\t\toutputFormat,\n\t\tinstructions,\n\t\tspeed,\n\t\tlanguage,\n\t\tabortSignal,\n\t\theaders: headersWithUserAgent,\n\t\tproviderOptions\n\t}));\n\tif (!result.audio || result.audio.length === 0) throw new NoSpeechGeneratedError({ responses: [result.response] });\n\tlogWarnings(result.warnings);\n\treturn new DefaultSpeechResult({\n\t\taudio: new DefaultGeneratedAudioFile({\n\t\t\tdata: result.audio,\n\t\t\tmediaType: (_a16 = detectMediaType({\n\t\t\t\tdata: result.audio,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a16 : \"audio/mp3\"\n\t\t}),\n\t\twarnings: result.warnings,\n\t\tresponses: [result.response],\n\t\tproviderMetadata: result.providerMetadata\n\t});\n}\nvar DefaultSpeechResult = class {\n\tconstructor(options) {\n\t\tvar _a16;\n\t\tthis.audio = options.audio;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = (_a16 = options.providerMetadata) != null ? _a16 : {};\n\t}\n};\nvar output_exports = {};\n__export(output_exports, {\n\tobject: () => object,\n\ttext: () => text\n});\nvar text = () => ({\n\ttype: \"text\",\n\tresponseFormat: { type: \"text\" },\n\tasync parsePartial({ text: text2 }) {\n\t\treturn { partial: text2 };\n\t},\n\tasync parseOutput({ text: text2 }) {\n\t\treturn text2;\n\t}\n});\nvar object = ({ schema: inputSchema }) => {\n\tconst schema = asSchema(inputSchema);\n\treturn {\n\t\ttype: \"object\",\n\t\tresponseFormat: {\n\t\t\ttype: \"json\",\n\t\t\tschema: schema.jsonSchema\n\t\t},\n\t\tasync parsePartial({ text: text2 }) {\n\t\t\tconst result = await parsePartialJson(text2);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": return { partial: result.value };\n\t\t\t\tdefault: {\n\t\t\t\t\tconst _exhaustiveCheck = result.state;\n\t\t\t\t\tthrow new Error(`Unsupported parse state: ${_exhaustiveCheck}`);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync parseOutput({ text: text2 }, context) {\n\t\t\tconst parseResult = await safeParseJSON({ text: text2 });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\tvalue: parseResult.value,\n\t\t\t\tschema\n\t\t\t});\n\t\t\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: validationResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\treturn validationResult.value;\n\t\t}\n\t};\n};\nfunction pruneMessages({ messages, reasoning = \"none\", toolCalls = [], emptyMessages = \"remove\" }) {\n\tif (reasoning === \"all\" || reasoning === \"before-last-message\") messages = messages.map((message, messageIndex) => {\n\t\tif (message.role !== \"assistant\" || typeof message.content === \"string\" || reasoning === \"before-last-message\" && messageIndex === messages.length - 1) return message;\n\t\treturn {\n\t\t\t...message,\n\t\t\tcontent: message.content.filter((part) => part.type !== \"reasoning\")\n\t\t};\n\t});\n\tif (toolCalls === \"none\") toolCalls = [];\n\telse if (toolCalls === \"all\") toolCalls = [{ type: \"all\" }];\n\telse if (toolCalls === \"before-last-message\") toolCalls = [{ type: \"before-last-message\" }];\n\telse if (typeof toolCalls === \"string\") toolCalls = [{ type: toolCalls }];\n\tfor (const toolCall of toolCalls) {\n\t\tconst keepLastMessagesCount = toolCall.type === \"all\" ? void 0 : toolCall.type === \"before-last-message\" ? 1 : Number(toolCall.type.slice(12).slice(0, -9));\n\t\tconst keptToolCallIds = /* @__PURE__ */ new Set();\n\t\tif (keepLastMessagesCount != null) {\n\t\t\tfor (const message of messages.slice(-keepLastMessagesCount)) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\t\tfor (const part of message.content) if (part.type === \"tool-call\" || part.type === \"tool-result\") keptToolCallIds.add(part.toolCallId);\n\t\t\t}\n\t\t}\n\t\tmessages = messages.map((message, messageIndex) => {\n\t\t\tif (message.role !== \"assistant\" && message.role !== \"tool\" || typeof message.content === \"string\" || keepLastMessagesCount && messageIndex >= messages.length - keepLastMessagesCount) return message;\n\t\t\tconst toolCallIdToToolName = {};\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tcontent: message.content.filter((part) => {\n\t\t\t\t\tif (part.type !== \"tool-call\" && part.type !== \"tool-result\") return true;\n\t\t\t\t\tif (part.type === \"tool-call\") toolCallIdToToolName[part.toolCallId] = part.toolName;\n\t\t\t\t\tif ((part.type === \"tool-call\" || part.type === \"tool-result\") && keptToolCallIds.has(part.toolCallId)) return true;\n\t\t\t\t\treturn toolCall.tools != null && !toolCall.tools.includes(part.toolName);\n\t\t\t\t})\n\t\t\t};\n\t\t});\n\t}\n\tif (emptyMessages === \"remove\") messages = messages.filter((message) => message.content.length > 0);\n\treturn messages;\n}\nvar CHUNKING_REGEXPS = {\n\tword: /\\S+\\s+/m,\n\tline: /\\n+/m\n};\nfunction smoothStream({ delayInMs = 10, chunking = \"word\", _internal: { delay: delay2 = delay } = {} } = {}) {\n\tlet detectChunk;\n\tif (typeof chunking === \"function\") detectChunk = (buffer) => {\n\t\tconst match = chunking(buffer);\n\t\tif (match == null) return null;\n\t\tif (!match.length) throw new Error(`Chunking function must return a non-empty string.`);\n\t\tif (!buffer.startsWith(match)) throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`);\n\t\treturn match;\n\t};\n\telse {\n\t\tconst chunkingRegex = typeof chunking === \"string\" ? CHUNKING_REGEXPS[chunking] : chunking;\n\t\tif (chunkingRegex == null) throw new InvalidArgumentError$1({\n\t\t\targument: \"chunking\",\n\t\t\tmessage: `Chunking must be \"word\" or \"line\" or a RegExp. Received: ${chunking}`\n\t\t});\n\t\tdetectChunk = (buffer) => {\n\t\t\tconst match = chunkingRegex.exec(buffer);\n\t\t\tif (!match) return null;\n\t\t\treturn buffer.slice(0, match.index) + (match == null ? void 0 : match[0]);\n\t\t};\n\t}\n\treturn () => {\n\t\tlet buffer = \"\";\n\t\tlet id = \"\";\n\t\treturn new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (chunk.type !== \"text-delta\") {\n\t\t\t\tif (buffer.length > 0) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\ttext: buffer,\n\t\t\t\t\t\tid\n\t\t\t\t\t});\n\t\t\t\t\tbuffer = \"\";\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (chunk.id !== id && buffer.length > 0) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\ttext: buffer,\n\t\t\t\t\tid\n\t\t\t\t});\n\t\t\t\tbuffer = \"\";\n\t\t\t}\n\t\t\tbuffer += chunk.text;\n\t\t\tid = chunk.id;\n\t\t\tlet match;\n\t\t\twhile ((match = detectChunk(buffer)) != null) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\ttext: match,\n\t\t\t\t\tid\n\t\t\t\t});\n\t\t\t\tbuffer = buffer.slice(match.length);\n\t\t\t\tawait delay2(delayInMs);\n\t\t\t}\n\t\t} });\n\t};\n}\nfunction defaultSettingsMiddleware({ settings }) {\n\treturn {\n\t\tmiddlewareVersion: \"v2\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\treturn mergeObjects(settings, params);\n\t\t}\n\t};\n}\nfunction getPotentialStartIndex(text2, searchedText) {\n\tif (searchedText.length === 0) return null;\n\tconst directIndex = text2.indexOf(searchedText);\n\tif (directIndex !== -1) return directIndex;\n\tfor (let i = text2.length - 1; i >= 0; i--) {\n\t\tconst suffix = text2.substring(i);\n\t\tif (searchedText.startsWith(suffix)) return i;\n\t}\n\treturn null;\n}\nfunction extractReasoningMiddleware({ tagName, separator = \"\\n\", startWithReasoning = false }) {\n\tconst openingTag = `<${tagName}>`;\n\tconst closingTag = `</${tagName}>`;\n\treturn {\n\t\tmiddlewareVersion: \"v2\",\n\t\twrapGenerate: async ({ doGenerate }) => {\n\t\t\tconst { content, ...rest } = await doGenerate();\n\t\t\tconst transformedContent = [];\n\t\t\tfor (const part of content) {\n\t\t\t\tif (part.type !== \"text\") {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst text2 = startWithReasoning ? openingTag + part.text : part.text;\n\t\t\t\tconst regexp = new RegExp(`${openingTag}(.*?)${closingTag}`, \"gs\");\n\t\t\t\tconst matches = Array.from(text2.matchAll(regexp));\n\t\t\t\tif (!matches.length) {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst reasoningText = matches.map((match) => match[1]).join(separator);\n\t\t\t\tlet textWithoutReasoning = text2;\n\t\t\t\tfor (let i = matches.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst match = matches[i];\n\t\t\t\t\tconst beforeMatch = textWithoutReasoning.slice(0, match.index);\n\t\t\t\t\tconst afterMatch = textWithoutReasoning.slice(match.index + match[0].length);\n\t\t\t\t\ttextWithoutReasoning = beforeMatch + (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : \"\") + afterMatch;\n\t\t\t\t}\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: reasoningText\n\t\t\t\t});\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: textWithoutReasoning\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: transformedContent,\n\t\t\t\t...rest\n\t\t\t};\n\t\t},\n\t\twrapStream: async ({ doStream }) => {\n\t\t\tconst { stream, ...rest } = await doStream();\n\t\t\tconst reasoningExtractions = createIdMap();\n\t\t\tlet delayedTextStart;\n\t\t\treturn {\n\t\t\t\tstream: stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {\n\t\t\t\t\tif (chunk.type === \"text-start\") {\n\t\t\t\t\t\tdelayedTextStart = chunk;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-end\" && delayedTextStart) {\n\t\t\t\t\t\tcontroller.enqueue(delayedTextStart);\n\t\t\t\t\t\tdelayedTextStart = void 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type !== \"text-delta\") {\n\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (reasoningExtractions[chunk.id] == null) reasoningExtractions[chunk.id] = {\n\t\t\t\t\t\tisFirstReasoning: true,\n\t\t\t\t\t\tisFirstText: true,\n\t\t\t\t\t\tafterSwitch: false,\n\t\t\t\t\t\tisReasoning: startWithReasoning,\n\t\t\t\t\t\tbuffer: \"\",\n\t\t\t\t\t\tidCounter: 0,\n\t\t\t\t\t\ttextId: chunk.id\n\t\t\t\t\t};\n\t\t\t\t\tconst activeExtraction = reasoningExtractions[chunk.id];\n\t\t\t\t\tactiveExtraction.buffer += chunk.delta;\n\t\t\t\t\tfunction publish(text2) {\n\t\t\t\t\t\tif (text2.length > 0) {\n\t\t\t\t\t\t\tconst prefix = activeExtraction.afterSwitch && (activeExtraction.isReasoning ? !activeExtraction.isFirstReasoning : !activeExtraction.isFirstText) ? separator : \"\";\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning && (activeExtraction.afterSwitch || activeExtraction.isFirstReasoning)) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tdelta: prefix + text2,\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (delayedTextStart) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(delayedTextStart);\n\t\t\t\t\t\t\t\t\tdelayedTextStart = void 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tdelta: prefix + text2,\n\t\t\t\t\t\t\t\t\tid: activeExtraction.textId\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = false;\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) activeExtraction.isFirstReasoning = false;\n\t\t\t\t\t\t\telse activeExtraction.isFirstText = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdo {\n\t\t\t\t\t\tconst nextTag = activeExtraction.isReasoning ? closingTag : openingTag;\n\t\t\t\t\t\tconst startIndex = getPotentialStartIndex(activeExtraction.buffer, nextTag);\n\t\t\t\t\t\tif (startIndex == null) {\n\t\t\t\t\t\t\tpublish(activeExtraction.buffer);\n\t\t\t\t\t\t\tactiveExtraction.buffer = \"\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublish(activeExtraction.buffer.slice(0, startIndex));\n\t\t\t\t\t\tif (startIndex + nextTag.length <= activeExtraction.buffer.length) {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex + nextTag.length);\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter++}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tactiveExtraction.isReasoning = !activeExtraction.isReasoning;\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (true);\n\t\t\t\t} })),\n\t\t\t\t...rest\n\t\t\t};\n\t\t}\n\t};\n}\nfunction simulateStreamingMiddleware() {\n\treturn {\n\t\tmiddlewareVersion: \"v2\",\n\t\twrapStream: async ({ doGenerate }) => {\n\t\t\tconst result = await doGenerate();\n\t\t\tlet id = 0;\n\t\t\treturn {\n\t\t\t\tstream: new ReadableStream({ start(controller) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"stream-start\",\n\t\t\t\t\t\twarnings: result.warnings\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"response-metadata\",\n\t\t\t\t\t\t...result.response\n\t\t\t\t\t});\n\t\t\t\t\tfor (const part of result.content) switch (part.type) {\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\tif (part.text.length > 0) {\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"reasoning\":\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tcontroller.enqueue(part);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: result.finishReason,\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\tproviderMetadata: result.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} }),\n\t\t\t\trequest: result.request,\n\t\t\t\tresponse: result.response\n\t\t\t};\n\t\t}\n\t};\n}\nvar wrapLanguageModel = ({ model, middleware: middlewareArg, modelId, providerId }) => {\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nvar doWrap = ({ model, middleware: { transformParams, wrapGenerate, wrapStream, overrideProvider, overrideModelId, overrideSupportedUrls }, modelId, providerId }) => {\n\tvar _a16, _b, _c;\n\tasync function doTransform({ params, type }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\ttype,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\treturn {\n\t\tspecificationVersion: \"v2\",\n\t\tprovider: (_a16 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a16 : model.provider,\n\t\tmodelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n\t\tsupportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,\n\t\tasync doGenerate(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"generate\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => model.doStream(transformedParams);\n\t\t\treturn wrapGenerate ? wrapGenerate({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doGenerate();\n\t\t},\n\t\tasync doStream(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"stream\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => model.doStream(transformedParams);\n\t\t\treturn wrapStream ? wrapStream({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doStream();\n\t\t}\n\t};\n};\nfunction wrapProvider({ provider, languageModelMiddleware }) {\n\treturn {\n\t\tlanguageModel(modelId) {\n\t\t\tlet model = provider.languageModel(modelId);\n\t\t\tmodel = wrapLanguageModel({\n\t\t\t\tmodel,\n\t\t\t\tmiddleware: languageModelMiddleware\n\t\t\t});\n\t\t\treturn model;\n\t\t},\n\t\ttextEmbeddingModel: provider.textEmbeddingModel,\n\t\timageModel: provider.imageModel,\n\t\ttranscriptionModel: provider.transcriptionModel,\n\t\tspeechModel: provider.speechModel\n\t};\n}\nfunction customProvider({ languageModels, textEmbeddingModels, imageModels, transcriptionModels, speechModels, fallbackProvider }) {\n\treturn {\n\t\tlanguageModel(modelId) {\n\t\t\tif (languageModels != null && modelId in languageModels) return languageModels[modelId];\n\t\t\tif (fallbackProvider) return fallbackProvider.languageModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"languageModel\"\n\t\t\t});\n\t\t},\n\t\ttextEmbeddingModel(modelId) {\n\t\t\tif (textEmbeddingModels != null && modelId in textEmbeddingModels) return textEmbeddingModels[modelId];\n\t\t\tif (fallbackProvider) return fallbackProvider.textEmbeddingModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"textEmbeddingModel\"\n\t\t\t});\n\t\t},\n\t\timageModel(modelId) {\n\t\t\tif (imageModels != null && modelId in imageModels) return imageModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.imageModel) return fallbackProvider.imageModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"imageModel\"\n\t\t\t});\n\t\t},\n\t\ttranscriptionModel(modelId) {\n\t\t\tif (transcriptionModels != null && modelId in transcriptionModels) return transcriptionModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.transcriptionModel) return fallbackProvider.transcriptionModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"transcriptionModel\"\n\t\t\t});\n\t\t},\n\t\tspeechModel(modelId) {\n\t\t\tif (speechModels != null && modelId in speechModels) return speechModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.speechModel) return fallbackProvider.speechModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"speechModel\"\n\t\t\t});\n\t\t}\n\t};\n}\nvar experimental_customProvider = customProvider;\nvar name15 = \"AI_NoSuchProviderError\";\nvar marker15 = `vercel.ai.error.${name15}`;\nvar symbol15 = Symbol.for(marker15);\nvar _a15;\nvar NoSuchProviderError = class extends NoSuchModelError {\n\tconstructor({ modelId, modelType, providerId, availableProviders, message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})` }) {\n\t\tsuper({\n\t\t\terrorName: name15,\n\t\t\tmodelId,\n\t\t\tmodelType,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a15] = true;\n\t\tthis.providerId = providerId;\n\t\tthis.availableProviders = availableProviders;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker15);\n\t}\n};\n_a15 = symbol15;\nfunction createProviderRegistry(providers, { separator = \":\", languageModelMiddleware } = {}) {\n\tconst registry = new DefaultProviderRegistry({\n\t\tseparator,\n\t\tlanguageModelMiddleware\n\t});\n\tfor (const [id, provider] of Object.entries(providers)) registry.registerProvider({\n\t\tid,\n\t\tprovider\n\t});\n\treturn registry;\n}\nvar experimental_createProviderRegistry = createProviderRegistry;\nvar DefaultProviderRegistry = class {\n\tconstructor({ separator, languageModelMiddleware }) {\n\t\tthis.providers = {};\n\t\tthis.separator = separator;\n\t\tthis.languageModelMiddleware = languageModelMiddleware;\n\t}\n\tregisterProvider({ id, provider }) {\n\t\tthis.providers[id] = provider;\n\t}\n\tgetProvider(id, modelType) {\n\t\tconst provider = this.providers[id];\n\t\tif (provider == null) throw new NoSuchProviderError({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tproviderId: id,\n\t\t\tavailableProviders: Object.keys(this.providers)\n\t\t});\n\t\treturn provider;\n\t}\n\tsplitId(id, modelType) {\n\t\tconst index = id.indexOf(this.separator);\n\t\tif (index === -1) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tmessage: `Invalid ${modelType} id for registry: ${id} (must be in the format \"providerId${this.separator}modelId\")`\n\t\t});\n\t\treturn [id.slice(0, index), id.slice(index + this.separator.length)];\n\t}\n\tlanguageModel(id) {\n\t\tvar _a16, _b;\n\t\tconst [providerId, modelId] = this.splitId(id, \"languageModel\");\n\t\tlet model = (_b = (_a16 = this.getProvider(providerId, \"languageModel\")).languageModel) == null ? void 0 : _b.call(_a16, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"languageModel\"\n\t\t});\n\t\tif (this.languageModelMiddleware != null) model = wrapLanguageModel({\n\t\t\tmodel,\n\t\t\tmiddleware: this.languageModelMiddleware\n\t\t});\n\t\treturn model;\n\t}\n\ttextEmbeddingModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"textEmbeddingModel\");\n\t\tconst provider = this.getProvider(providerId, \"textEmbeddingModel\");\n\t\tconst model = (_a16 = provider.textEmbeddingModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"textEmbeddingModel\"\n\t\t});\n\t\treturn model;\n\t}\n\timageModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"imageModel\");\n\t\tconst provider = this.getProvider(providerId, \"imageModel\");\n\t\tconst model = (_a16 = provider.imageModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"imageModel\"\n\t\t});\n\t\treturn model;\n\t}\n\ttranscriptionModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"transcriptionModel\");\n\t\tconst provider = this.getProvider(providerId, \"transcriptionModel\");\n\t\tconst model = (_a16 = provider.transcriptionModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"transcriptionModel\"\n\t\t});\n\t\treturn model;\n\t}\n\tspeechModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"speechModel\");\n\t\tconst provider = this.getProvider(providerId, \"speechModel\");\n\t\tconst model = (_a16 = provider.speechModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"speechModel\"\n\t\t});\n\t\treturn model;\n\t}\n};\nvar NoTranscriptGeneratedError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_NoTranscriptGeneratedError\",\n\t\t\tmessage: \"No transcript generated.\"\n\t\t});\n\t\tthis.responses = options.responses;\n\t}\n};\nvar defaultDownload = createDownload();\nasync function transcribe({ model, audio, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn = defaultDownload }) {\n\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\tversion: model.specificationVersion,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst audioData = audio instanceof URL ? (await downloadFn({\n\t\turl: audio,\n\t\tabortSignal\n\t})).data : convertDataContentToUint8Array(audio);\n\tconst result = await retry(() => {\n\t\tvar _a16;\n\t\treturn model.doGenerate({\n\t\t\taudio: audioData,\n\t\t\tabortSignal,\n\t\t\theaders: headersWithUserAgent,\n\t\t\tproviderOptions,\n\t\t\tmediaType: (_a16 = detectMediaType({\n\t\t\t\tdata: audioData,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a16 : \"audio/wav\"\n\t\t});\n\t});\n\tlogWarnings(result.warnings);\n\tif (!result.text) throw new NoTranscriptGeneratedError({ responses: [result.response] });\n\treturn new DefaultTranscriptionResult({\n\t\ttext: result.text,\n\t\tsegments: result.segments,\n\t\tlanguage: result.language,\n\t\tdurationInSeconds: result.durationInSeconds,\n\t\twarnings: result.warnings,\n\t\tresponses: [result.response],\n\t\tproviderMetadata: result.providerMetadata\n\t});\n}\nvar DefaultTranscriptionResult = class {\n\tconstructor(options) {\n\t\tvar _a16;\n\t\tthis.text = options.text;\n\t\tthis.segments = options.segments;\n\t\tthis.language = options.language;\n\t\tthis.durationInSeconds = options.durationInSeconds;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = (_a16 = options.providerMetadata) != null ? _a16 : {};\n\t}\n};\nasync function processTextStream({ stream, onTextPart }) {\n\tconst reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\tawait onTextPart(value);\n\t}\n}\nvar getOriginalFetch = () => fetch;\nasync function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol = \"data\", setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch: fetch2 = getOriginalFetch() }) {\n\tvar _a16;\n\ttry {\n\t\tsetLoading(true);\n\t\tsetError(void 0);\n\t\tconst abortController = new AbortController();\n\t\tsetAbortController(abortController);\n\t\tsetCompletion(\"\");\n\t\tconst response = await fetch2(api, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tprompt,\n\t\t\t\t...body\n\t\t\t}),\n\t\t\tcredentials,\n\t\t\theaders: withUserAgentSuffix({\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tsignal: abortController.signal\n\t\t}).catch((err) => {\n\t\t\tthrow err;\n\t\t});\n\t\tif (!response.ok) throw new Error((_a16 = await response.text()) != null ? _a16 : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\tlet result = \"\";\n\t\tswitch (streamProtocol) {\n\t\t\tcase \"text\":\n\t\t\t\tawait processTextStream({\n\t\t\t\t\tstream: response.body,\n\t\t\t\t\tonTextPart: (chunk) => {\n\t\t\t\t\t\tresult += chunk;\n\t\t\t\t\t\tsetCompletion(result);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"data\":\n\t\t\t\tawait consumeStream({\n\t\t\t\t\tstream: parseJsonEventStream({\n\t\t\t\t\t\tstream: response.body,\n\t\t\t\t\t\tschema: uiMessageChunkSchema\n\t\t\t\t\t}).pipeThrough(new TransformStream({ async transform(part) {\n\t\t\t\t\t\tif (!part.success) throw part.error;\n\t\t\t\t\t\tconst streamPart = part.value;\n\t\t\t\t\t\tif (streamPart.type === \"text-delta\") {\n\t\t\t\t\t\t\tresult += streamPart.delta;\n\t\t\t\t\t\t\tsetCompletion(result);\n\t\t\t\t\t\t} else if (streamPart.type === \"error\") throw new Error(streamPart.errorText);\n\t\t\t\t\t} })),\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unknown stream protocol: ${streamProtocol}`);\n\t\t}\n\t\tif (onFinish) onFinish(prompt, result);\n\t\tsetAbortController(null);\n\t\treturn result;\n\t} catch (err) {\n\t\tif (err.name === \"AbortError\") {\n\t\t\tsetAbortController(null);\n\t\t\treturn null;\n\t\t}\n\t\tif (err instanceof Error) {\n\t\t\tif (onError) onError(err);\n\t\t}\n\t\tsetError(err);\n\t} finally {\n\t\tsetLoading(false);\n\t}\n}\nasync function convertFileListToFileUIParts(files) {\n\tif (files == null) return [];\n\tif (!globalThis.FileList || !(files instanceof globalThis.FileList)) throw new Error(\"FileList is not supported in the current environment\");\n\treturn Promise.all(Array.from(files).map(async (file) => {\n\t\tconst { name: name16, type } = file;\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: type,\n\t\t\tfilename: name16,\n\t\t\turl: await new Promise((resolve2, reject) => {\n\t\t\t\tconst reader = new FileReader();\n\t\t\t\treader.onload = (readerEvent) => {\n\t\t\t\t\tvar _a16;\n\t\t\t\t\tresolve2((_a16 = readerEvent.target) == null ? void 0 : _a16.result);\n\t\t\t\t};\n\t\t\t\treader.onerror = (error) => reject(error);\n\t\t\t\treader.readAsDataURL(file);\n\t\t\t})\n\t\t};\n\t}));\n}\nvar HttpChatTransport = class {\n\tconstructor({ api = \"/api/chat\", credentials, headers, body, fetch: fetch2, prepareSendMessagesRequest, prepareReconnectToStreamRequest }) {\n\t\tthis.api = api;\n\t\tthis.credentials = credentials;\n\t\tthis.headers = headers;\n\t\tthis.body = body;\n\t\tthis.fetch = fetch2;\n\t\tthis.prepareSendMessagesRequest = prepareSendMessagesRequest;\n\t\tthis.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n\t}\n\tasync sendMessages({ abortSignal, ...options }) {\n\t\tvar _a16, _b, _c, _d, _e;\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await ((_a16 = this.prepareSendMessagesRequest) == null ? void 0 : _a16.call(this, {\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t}));\n\t\tconst api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : this.api;\n\t\tconst headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst body = (preparedRequest == null ? void 0 : preparedRequest.body) !== void 0 ? preparedRequest.body : {\n\t\t\t...resolvedBody,\n\t\t\t...options.body,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t};\n\t\tconst credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n\t\tconst response = await ((_d = this.fetch) != null ? _d : globalThis.fetch)(api, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t\tcredentials,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tif (!response.ok) throw new Error((_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\treturn this.processResponseStream(response.body);\n\t}\n\tasync reconnectToStream(options) {\n\t\tvar _a16, _b, _c, _d, _e;\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await ((_a16 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a16.call(this, {\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata\n\t\t}));\n\t\tconst api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : `${this.api}/${options.chatId}/stream`;\n\t\tconst headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n\t\tconst response = await ((_d = this.fetch) != null ? _d : globalThis.fetch)(api, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t\tcredentials\n\t\t});\n\t\tif (response.status === 204) return null;\n\t\tif (!response.ok) throw new Error((_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\treturn this.processResponseStream(response.body);\n\t}\n};\nvar DefaultChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn parseJsonEventStream({\n\t\t\tstream,\n\t\t\tschema: uiMessageChunkSchema\n\t\t}).pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (!chunk.success) throw chunk.error;\n\t\t\tcontroller.enqueue(chunk.value);\n\t\t} }));\n\t}\n};\nvar AbstractChat = class {\n\tconstructor({ generateId: generateId3 = generateId, id = generateId3(), transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {\n\t\tthis.activeResponse = void 0;\n\t\tthis.jobExecutor = new SerialJobExecutor();\n\t\t/**\n\t\t* Appends or replaces a user message to the chat list. This triggers the API call to fetch\n\t\t* the assistant's response.\n\t\t*\n\t\t* If a messageId is provided, the message will be replaced.\n\t\t*/\n\t\tthis.sendMessage = async (message, options) => {\n\t\t\tvar _a16, _b, _c, _d;\n\t\t\tif (message == null) {\n\t\t\t\tawait this.makeRequest({\n\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\tmessageId: (_a16 = this.lastMessage) == null ? void 0 : _a16.id,\n\t\t\t\t\t...options\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet uiMessage;\n\t\t\tif (\"text\" in message || \"files\" in message) uiMessage = { parts: [...Array.isArray(message.files) ? message.files : await convertFileListToFileUIParts(message.files), ...\"text\" in message && message.text != null ? [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: message.text\n\t\t\t}] : []] };\n\t\t\telse uiMessage = message;\n\t\t\tif (message.messageId != null) {\n\t\t\t\tconst messageIndex = this.state.messages.findIndex((m) => m.id === message.messageId);\n\t\t\t\tif (messageIndex === -1) throw new Error(`message with id ${message.messageId} not found`);\n\t\t\t\tif (this.state.messages[messageIndex].role !== \"user\") throw new Error(`message with id ${message.messageId} is not a user message`);\n\t\t\t\tthis.state.messages = this.state.messages.slice(0, messageIndex + 1);\n\t\t\t\tthis.state.replaceMessage(messageIndex, {\n\t\t\t\t\t...uiMessage,\n\t\t\t\t\tid: message.messageId,\n\t\t\t\t\trole: (_b = uiMessage.role) != null ? _b : \"user\",\n\t\t\t\t\tmetadata: message.metadata\n\t\t\t\t});\n\t\t\t} else this.state.pushMessage({\n\t\t\t\t...uiMessage,\n\t\t\t\tid: (_c = uiMessage.id) != null ? _c : this.generateId(),\n\t\t\t\trole: (_d = uiMessage.role) != null ? _d : \"user\",\n\t\t\t\tmetadata: message.metadata\n\t\t\t});\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: message.messageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Regenerate the assistant message with the provided message id.\n\t\t* If no message id is provided, the last assistant message will be regenerated.\n\t\t*/\n\t\tthis.regenerate = async ({ messageId, ...options } = {}) => {\n\t\t\tconst messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);\n\t\t\tif (messageIndex === -1) throw new Error(`message ${messageId} not found`);\n\t\t\tthis.state.messages = this.state.messages.slice(0, this.messages[messageIndex].role === \"assistant\" ? messageIndex : messageIndex + 1);\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"regenerate-message\",\n\t\t\t\tmessageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Attempt to resume an ongoing streaming response.\n\t\t*/\n\t\tthis.resumeStream = async (options = {}) => {\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"resume-stream\",\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Clear the error state and set the status to ready if the chat is in an error state.\n\t\t*/\n\t\tthis.clearError = () => {\n\t\t\tif (this.status === \"error\") {\n\t\t\t\tthis.state.error = void 0;\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t}\n\t\t};\n\t\tthis.addToolOutput = async ({ state = \"output-available\", tool: tool2, toolCallId, output, errorText }) => this.jobExecutor.run(async () => {\n\t\t\tvar _a16, _b;\n\t\t\tconst messages = this.state.messages;\n\t\t\tconst lastMessage = messages[messages.length - 1];\n\t\t\tthis.state.replaceMessage(messages.length - 1, {\n\t\t\t\t...lastMessage,\n\t\t\t\tparts: lastMessage.parts.map((part) => isToolOrDynamicToolUIPart(part) && part.toolCallId === toolCallId ? {\n\t\t\t\t\t...part,\n\t\t\t\t\tstate,\n\t\t\t\t\toutput,\n\t\t\t\t\terrorText\n\t\t\t\t} : part)\n\t\t\t});\n\t\t\tif (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map((part) => isToolOrDynamicToolUIPart(part) && part.toolCallId === toolCallId ? {\n\t\t\t\t...part,\n\t\t\t\tstate,\n\t\t\t\toutput,\n\t\t\t\terrorText\n\t\t\t} : part);\n\t\t\tif (this.status !== \"streaming\" && this.status !== \"submitted\" && ((_a16 = this.sendAutomaticallyWhen) == null ? void 0 : _a16.call(this, { messages: this.state.messages }))) this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: (_b = this.lastMessage) == null ? void 0 : _b.id\n\t\t\t});\n\t\t});\n\t\t/** @deprecated Use addToolOutput */\n\t\tthis.addToolResult = this.addToolOutput;\n\t\t/**\n\t\t* Abort the current request immediately, keep the generated tokens if any.\n\t\t*/\n\t\tthis.stop = async () => {\n\t\t\tvar _a16;\n\t\t\tif (this.status !== \"streaming\" && this.status !== \"submitted\") return;\n\t\t\tif ((_a16 = this.activeResponse) == null ? void 0 : _a16.abortController) this.activeResponse.abortController.abort();\n\t\t};\n\t\tthis.id = id;\n\t\tthis.transport = transport;\n\t\tthis.generateId = generateId3;\n\t\tthis.messageMetadataSchema = messageMetadataSchema;\n\t\tthis.dataPartSchemas = dataPartSchemas;\n\t\tthis.state = state;\n\t\tthis.onError = onError;\n\t\tthis.onToolCall = onToolCall;\n\t\tthis.onFinish = onFinish;\n\t\tthis.onData = onData;\n\t\tthis.sendAutomaticallyWhen = sendAutomaticallyWhen;\n\t}\n\t/**\n\t* Hook status:\n\t*\n\t* - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n\t* - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n\t* - `ready`: The full response has been received and processed; a new user message can be submitted.\n\t* - `error`: An error occurred during the API request, preventing successful completion.\n\t*/\n\tget status() {\n\t\treturn this.state.status;\n\t}\n\tsetStatus({ status, error }) {\n\t\tif (this.status === status) return;\n\t\tthis.state.status = status;\n\t\tthis.state.error = error;\n\t}\n\tget error() {\n\t\treturn this.state.error;\n\t}\n\tget messages() {\n\t\treturn this.state.messages;\n\t}\n\tget lastMessage() {\n\t\treturn this.state.messages[this.state.messages.length - 1];\n\t}\n\tset messages(messages) {\n\t\tthis.state.messages = messages;\n\t}\n\tasync makeRequest({ trigger, metadata, headers, body, messageId }) {\n\t\tvar _a16, _b, _c, _d;\n\t\tthis.setStatus({\n\t\t\tstatus: \"submitted\",\n\t\t\terror: void 0\n\t\t});\n\t\tconst lastMessage = this.lastMessage;\n\t\tlet isAbort = false;\n\t\tlet isDisconnect = false;\n\t\tlet isError = false;\n\t\ttry {\n\t\t\tconst activeResponse = {\n\t\t\t\tstate: createStreamingUIMessageState({\n\t\t\t\t\tlastMessage: this.state.snapshot(lastMessage),\n\t\t\t\t\tmessageId: this.generateId()\n\t\t\t\t}),\n\t\t\t\tabortController: new AbortController()\n\t\t\t};\n\t\t\tactiveResponse.abortController.signal.addEventListener(\"abort\", () => {\n\t\t\t\tisAbort = true;\n\t\t\t});\n\t\t\tthis.activeResponse = activeResponse;\n\t\t\tlet stream;\n\t\t\tif (trigger === \"resume-stream\") {\n\t\t\t\tconst reconnect = await this.transport.reconnectToStream({\n\t\t\t\t\tchatId: this.id,\n\t\t\t\t\tmetadata,\n\t\t\t\t\theaders,\n\t\t\t\t\tbody\n\t\t\t\t});\n\t\t\t\tif (reconnect == null) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstream = reconnect;\n\t\t\t} else stream = await this.transport.sendMessages({\n\t\t\t\tchatId: this.id,\n\t\t\t\tmessages: this.state.messages,\n\t\t\t\tabortSignal: activeResponse.abortController.signal,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\ttrigger,\n\t\t\t\tmessageId\n\t\t\t});\n\t\t\tconst runUpdateMessageJob = (job) => this.jobExecutor.run(() => job({\n\t\t\t\tstate: activeResponse.state,\n\t\t\t\twrite: () => {\n\t\t\t\t\tvar _a17;\n\t\t\t\t\tthis.setStatus({ status: \"streaming\" });\n\t\t\t\t\tif (activeResponse.state.message.id === ((_a17 = this.lastMessage) == null ? void 0 : _a17.id)) this.state.replaceMessage(this.state.messages.length - 1, activeResponse.state.message);\n\t\t\t\t\telse this.state.pushMessage(activeResponse.state.message);\n\t\t\t\t}\n\t\t\t}));\n\t\t\tawait consumeStream({\n\t\t\t\tstream: processUIMessageStream({\n\t\t\t\t\tstream,\n\t\t\t\t\tonToolCall: this.onToolCall,\n\t\t\t\t\tonData: this.onData,\n\t\t\t\t\tmessageMetadataSchema: this.messageMetadataSchema,\n\t\t\t\t\tdataPartSchemas: this.dataPartSchemas,\n\t\t\t\t\trunUpdateMessageJob,\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t} catch (err) {\n\t\t\tif (isAbort || err.name === \"AbortError\") {\n\t\t\t\tisAbort = true;\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tisError = true;\n\t\t\tif (err instanceof TypeError && (err.message.toLowerCase().includes(\"fetch\") || err.message.toLowerCase().includes(\"network\"))) isDisconnect = true;\n\t\t\tif (this.onError && err instanceof Error) this.onError(err);\n\t\t\tthis.setStatus({\n\t\t\t\tstatus: \"error\",\n\t\t\t\terror: err\n\t\t\t});\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\t(_b = this.onFinish) == null || _b.call(this, {\n\t\t\t\t\tmessage: this.activeResponse.state.message,\n\t\t\t\t\tmessages: this.state.messages,\n\t\t\t\t\tisAbort,\n\t\t\t\t\tisDisconnect,\n\t\t\t\t\tisError,\n\t\t\t\t\tfinishReason: (_a16 = this.activeResponse) == null ? void 0 : _a16.state.finishReason\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(err);\n\t\t\t}\n\t\t\tthis.activeResponse = void 0;\n\t\t}\n\t\tif (((_c = this.sendAutomaticallyWhen) == null ? void 0 : _c.call(this, { messages: this.state.messages })) && !isError) await this.makeRequest({\n\t\t\ttrigger: \"submit-message\",\n\t\t\tmessageId: (_d = this.lastMessage) == null ? void 0 : _d.id,\n\t\t\tmetadata,\n\t\t\theaders,\n\t\t\tbody\n\t\t});\n\t}\n};\nfunction lastAssistantMessageIsCompleteWithToolCalls({ messages }) {\n\tconst message = messages[messages.length - 1];\n\tif (!message) return false;\n\tif (message.role !== \"assistant\") return false;\n\tconst lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n\t\treturn part.type === \"step-start\" ? index : lastIndex;\n\t}, -1);\n\tconst lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolOrDynamicToolUIPart).filter((part) => !part.providerExecuted);\n\treturn lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => part.state === \"output-available\" || part.state === \"output-error\");\n}\nfunction transformTextToUiMessageStream({ stream }) {\n\treturn stream.pipeThrough(new TransformStream({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\tcontroller.enqueue({ type: \"start-step\" });\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-start\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t},\n\t\tasync transform(part, controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tid: \"text-1\",\n\t\t\t\tdelta: part\n\t\t\t});\n\t\t},\n\t\tasync flush(controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-end\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t\tcontroller.enqueue({ type: \"finish-step\" });\n\t\t\tcontroller.enqueue({ type: \"finish\" });\n\t\t}\n\t}));\n}\nvar TextStreamChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn transformTextToUiMessageStream({ stream: stream.pipeThrough(new TextDecoderStream()) });\n\t}\n};\nvar uiMessagesSchema = lazyValidator(() => zodSchema(z.array(z.object({\n\tid: z.string(),\n\trole: z.enum([\n\t\t\"system\",\n\t\t\"user\",\n\t\t\"assistant\"\n\t]),\n\tmetadata: z.unknown().optional(),\n\tparts: z.array(z.union([\n\t\tz.object({\n\t\t\ttype: z.literal(\"text\"),\n\t\t\ttext: z.string(),\n\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"reasoning\"),\n\t\t\ttext: z.string(),\n\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"source-url\"),\n\t\t\tsourceId: z.string(),\n\t\t\turl: z.string(),\n\t\t\ttitle: z.string().optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"source-document\"),\n\t\t\tsourceId: z.string(),\n\t\t\tmediaType: z.string(),\n\t\t\ttitle: z.string(),\n\t\t\tfilename: z.string().optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"file\"),\n\t\t\tmediaType: z.string(),\n\t\t\tfilename: z.string().optional(),\n\t\t\turl: z.string(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({ type: z.literal(\"step-start\") }),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"data-\"),\n\t\t\tid: z.string().optional(),\n\t\t\tdata: z.unknown()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\tinput: z.unknown().optional(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-available\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-available\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.unknown(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tpreliminary: z.boolean().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-error\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.string(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-available\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.never().optional(),\n\t\t\t\treason: z.never().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.boolean(),\n\t\t\t\treason: z.string().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-available\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.unknown(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tpreliminary: z.boolean().optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-error\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.string(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(false),\n\t\t\t\treason: z.string().optional()\n\t\t\t})\n\t\t})\n\t]))\n}).superRefine((message, context) => {\n\tif (message.role !== \"assistant\" && message.parts.length === 0) context.addIssue({\n\t\torigin: \"array\",\n\t\tcode: \"too_small\",\n\t\tminimum: 1,\n\t\tinclusive: true,\n\t\tinput: message.parts,\n\t\tpath: [\"parts\"],\n\t\tmessage: \"Message must contain at least one part\"\n\t});\n})).nonempty(\"Messages array must not be empty\")));\nasync function safeValidateUIMessages({ messages, metadataSchema, dataSchemas, tools }) {\n\ttry {\n\t\tif (messages == null) return {\n\t\t\tsuccess: false,\n\t\t\terror: new InvalidArgumentError({\n\t\t\t\tparameter: \"messages\",\n\t\t\t\tvalue: messages,\n\t\t\t\tmessage: \"messages parameter must be provided\"\n\t\t\t})\n\t\t};\n\t\tconst validatedMessages = await validateTypes({\n\t\t\tvalue: messages,\n\t\t\tschema: uiMessagesSchema\n\t\t});\n\t\tif (metadataSchema) for (const message of validatedMessages) await validateTypes({\n\t\t\tvalue: message.metadata,\n\t\t\tschema: metadataSchema\n\t\t});\n\t\tif (dataSchemas) for (const message of validatedMessages) {\n\t\t\tconst dataParts = message.parts.filter((part) => part.type.startsWith(\"data-\"));\n\t\t\tfor (const dataPart of dataParts) {\n\t\t\t\tconst dataName = dataPart.type.slice(5);\n\t\t\t\tconst dataSchema = dataSchemas[dataName];\n\t\t\t\tif (!dataSchema) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\t\tcause: `No data schema found for data part ${dataName}`\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tawait validateTypes({\n\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\tschema: dataSchema\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (tools) for (const message of validatedMessages) {\n\t\t\tconst toolParts = message.parts.filter((part) => part.type.startsWith(\"tool-\"));\n\t\t\tfor (const toolPart of toolParts) {\n\t\t\t\tconst toolName = toolPart.type.slice(5);\n\t\t\t\tconst tool2 = tools[toolName];\n\t\t\t\tif (!tool2) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\t\tcause: `No tool schema found for tool part ${toolName}`\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tif (toolPart.state === \"input-available\" || toolPart.state === \"output-available\" || toolPart.state === \"output-error\") await validateTypes({\n\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\tschema: tool2.inputSchema\n\t\t\t\t});\n\t\t\t\tif (toolPart.state === \"output-available\" && tool2.outputSchema) await validateTypes({\n\t\t\t\t\tvalue: toolPart.output,\n\t\t\t\t\tschema: tool2.outputSchema\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: validatedMessages\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror\n\t\t};\n\t}\n}\nasync function validateUIMessages({ messages, metadataSchema, dataSchemas, tools }) {\n\tconst response = await safeValidateUIMessages({\n\t\tmessages,\n\t\tmetadataSchema,\n\t\tdataSchemas,\n\t\ttools\n\t});\n\tif (!response.success) throw response.error;\n\treturn response.data;\n}\nfunction createUIMessageStream({ execute, onError = () => \"An error occurred.\", originalMessages, onFinish, generateId: generateId3 = generateId }) {\n\tlet controller;\n\tconst ongoingStreamPromises = [];\n\tconst stream = new ReadableStream({ start(controllerArg) {\n\t\tcontroller = controllerArg;\n\t} });\n\tfunction safeEnqueue(data) {\n\t\ttry {\n\t\t\tcontroller.enqueue(data);\n\t\t} catch (error) {}\n\t}\n\ttry {\n\t\tconst result = execute({ writer: {\n\t\t\twrite(part) {\n\t\t\t\tsafeEnqueue(part);\n\t\t\t},\n\t\t\tmerge(streamArg) {\n\t\t\t\tongoingStreamPromises.push((async () => {\n\t\t\t\t\tconst reader = streamArg.getReader();\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) break;\n\t\t\t\t\t\tsafeEnqueue(value);\n\t\t\t\t\t}\n\t\t\t\t})().catch((error) => {\n\t\t\t\t\tsafeEnqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terrorText: onError(error)\n\t\t\t\t\t});\n\t\t\t\t}));\n\t\t\t},\n\t\t\tonError\n\t\t} });\n\t\tif (result) ongoingStreamPromises.push(result.catch((error) => {\n\t\t\tsafeEnqueue({\n\t\t\t\ttype: \"error\",\n\t\t\t\terrorText: onError(error)\n\t\t\t});\n\t\t}));\n\t} catch (error) {\n\t\tsafeEnqueue({\n\t\t\ttype: \"error\",\n\t\t\terrorText: onError(error)\n\t\t});\n\t}\n\tnew Promise(async (resolve2) => {\n\t\twhile (ongoingStreamPromises.length > 0) await ongoingStreamPromises.shift();\n\t\tresolve2();\n\t}).finally(() => {\n\t\ttry {\n\t\t\tcontroller.close();\n\t\t} catch (error) {}\n\t});\n\treturn handleUIMessageStreamFinish({\n\t\tstream,\n\t\tmessageId: generateId3(),\n\t\toriginalMessages,\n\t\tonFinish,\n\t\tonError\n\t});\n}\nfunction readUIMessageStream({ message, stream, onError, terminateOnError = false }) {\n\tvar _a16;\n\tlet controller;\n\tlet hasErrored = false;\n\tconst outputStream = new ReadableStream({ start(controllerParam) {\n\t\tcontroller = controllerParam;\n\t} });\n\tconst state = createStreamingUIMessageState({\n\t\tmessageId: (_a16 = message == null ? void 0 : message.id) != null ? _a16 : \"\",\n\t\tlastMessage: message\n\t});\n\tconst handleError = (error) => {\n\t\tonError?.(error);\n\t\tif (!hasErrored && terminateOnError) {\n\t\t\thasErrored = true;\n\t\t\tcontroller?.error(error);\n\t\t}\n\t};\n\tconsumeStream({\n\t\tstream: processUIMessageStream({\n\t\t\tstream,\n\t\t\trunUpdateMessageJob(job) {\n\t\t\t\treturn job({\n\t\t\t\t\tstate,\n\t\t\t\t\twrite: () => {\n\t\t\t\t\t\tcontroller?.enqueue(structuredClone(state.message));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tonError: handleError\n\t\t}),\n\t\tonError: handleError\n\t}).finally(() => {\n\t\tif (!hasErrored) controller?.close();\n\t});\n\treturn createAsyncIterableStream(outputStream);\n}\n//#endregion\n//#region src/index.ts\nconst generateText = (options) => generateText$1({\n\t...options,\n\tallowSystemInMessages: false\n});\nconst streamText = (options) => streamText$1({\n\t...options,\n\tallowSystemInMessages: false\n});\n//#endregion\nexport { AISDKError, APICallError, AbstractChat, DefaultChatTransport, DownloadError, EmptyResponseBodyError, Agent as Experimental_Agent, HttpChatTransport, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, InvalidResponseDataError, InvalidStreamPartError, InvalidToolInputError, JSONParseError, JsonToSseTransformStream, LoadAPIKeyError, LoadSettingError, MessageConversionError, NoContentGeneratedError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoOutputSpecifiedError, NoSpeechGeneratedError, NoSuchModelError, NoSuchProviderError, NoSuchToolError, output_exports as Output, RetryError, SerialJobExecutor, TextStreamChatTransport, TooManyEmbeddingValuesForCallError, ToolCallRepairError, TypeValidationError, UI_MESSAGE_STREAM_HEADERS, UnsupportedFunctionalityError, UnsupportedModelVersionError, asSchema, assistantModelMessageSchema, callCompletionApi, consumeStream, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createDownload, createGatewayProvider as createGateway, createIdGenerator, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultSettingsMiddleware, dynamicTool, embed, embedMany, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractReasoningMiddleware, gateway, generateId, generateObject, generateText, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, hasToolCall, isDataUIPart, isDeepEqualData, isFileUIPart, isReasoningUIPart, isTextUIPart, isToolOrDynamicToolUIPart, isToolUIPart, jsonSchema, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parseJsonEventStream, parsePartialJson, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, uiMessageChunkSchema, userModelMessageSchema, validateUIMessages, wrapLanguageModel, wrapProvider, zodSchema };\n\n//# sourceMappingURL=index.js.map","import { z } from 'zod';\n\nexport const TaskSchema = z.array(\n z.object({\n id: z.string().describe('Unique task ID using kebab-case'),\n content: z.string().describe('Specific, actionable task description'),\n status: z.enum(['pending', 'in_progress', 'completed', 'blocked']).default('pending'),\n priority: z.enum(['high', 'medium', 'low']).describe('Task priority'),\n dependencies: z.array(z.string()).optional().describe('IDs of tasks this depends on'),\n notes: z.string().describe('Detailed implementation notes and specifics'),\n }),\n);\n\nexport const QuestionSchema = z.array(\n z.object({\n id: z.string().describe('Unique question ID'),\n question: z.string().describe('Clear, specific question for the user'),\n type: z.enum(['choice', 'text', 'boolean']).describe('Type of answer expected'),\n options: z.array(z.string()).optional().describe('Options for choice questions'),\n context: z.string().optional().describe('Additional context or explanation'),\n }),\n);\nexport const PlanningIterationResultSchema = z.object({\n success: z.boolean(),\n tasks: TaskSchema,\n questions: QuestionSchema,\n reasoning: z.string(),\n planComplete: z.boolean(),\n message: z.string(),\n error: z.string().optional(),\n allPreviousQuestions: z.array(z.any()).optional(),\n allPreviousAnswers: z.record(z.string(), z.string()).optional(),\n});\n","/**\n * Prompts and instructions for task planning workflow\n */\n\nexport interface TaskPlanningPrompts {\n planningAgent: {\n instructions: (context: { storedQAPairs: any[] }) => string;\n refinementPrompt: (context: {\n action: string;\n workflowName?: string;\n description?: string;\n requirements?: string;\n discoveredWorkflows: any[];\n projectStructure: any;\n research: any;\n storedQAPairs: any[];\n hasTaskFeedback: boolean;\n userAnswers?: any;\n }) => string;\n initialPrompt: (context: {\n action: string;\n workflowName?: string;\n description?: string;\n requirements?: string;\n discoveredWorkflows: any[];\n projectStructure: any;\n research: any;\n }) => string;\n };\n taskApproval: {\n message: (questionsCount: number) => string;\n approvalMessage: (tasksCount: number) => string;\n };\n}\n\nexport const taskPlanningPrompts: TaskPlanningPrompts = {\n planningAgent: {\n instructions:\n context => `You are a Mastra workflow planning expert. Your task is to create a detailed, executable task plan.\n\nPLANNING RESPONSIBILITIES:\n1. **Analyze Requirements**: Review the user's description and requirements thoroughly\n2. **Identify Decision Points**: Find any choices that require user input (email providers, databases, APIs, etc.)\n3. **Create Specific Tasks**: Generate concrete, actionable tasks with clear implementation notes\n4. **Ask Clarifying Questions**: If any decisions are unclear, formulate specific questions for the user \n- do not ask about package managers\n- Assume the user is going to use zod for validation\n- You do not need to ask questions if you have none\n- NEVER ask questions that have already been answered before\n5. **Incorporate Feedback**: Use any previous answers or feedback to refine the plan\n\n${\n context.storedQAPairs.length > 0\n ? `PREVIOUS QUESTION-ANSWER PAIRS (${context.storedQAPairs.length} total):\\n${context.storedQAPairs\n .map(\n (pair, index) =>\n `${index + 1}. Q: ${pair.question.question}\\n A: ${pair.answer || 'NOT ANSWERED YET'}\\n Type: ${pair.question.type}\\n Asked: ${pair.askedAt}\\n ${pair.answer ? `Answered: ${pair.answeredAt}` : ''}`,\n )\n .join('\\n\\n')}\\n\\nIMPORTANT: DO NOT ASK ANY QUESTIONS THAT HAVE ALREADY BEEN ASKED!`\n : ''\n}\n\nBased on the context and any user answers, create or refine the task plan.`,\n\n refinementPrompt: context => `Refine the existing task plan based on all user answers collected so far. \n\nANSWERED QUESTIONS AND RESPONSES:\n${context.storedQAPairs\n .filter(pair => pair.answer)\n .map(\n (pair, index) =>\n `${index + 1}. Q: ${pair.question.question}\\n A: ${pair.answer}\\n Context: ${pair.question.context || 'None'}`,\n )\n .join('\\n\\n')}\n\nREQUIREMENTS:\n- Action: ${context.action}\n- Workflow Name: ${context.workflowName || 'To be determined'}\n- Description: ${context.description || 'Not specified'}\n- Requirements: ${context.requirements || 'Not specified'}\n\nPROJECT CONTEXT:\n- Discovered Workflows: ${JSON.stringify(context.discoveredWorkflows, null, 2)}\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n- Research: ${JSON.stringify(context.research, null, 2)}\n\n${context.hasTaskFeedback ? `\\nUSER FEEDBACK ON PREVIOUS TASK LIST:\\n${context.userAnswers?.taskFeedback}\\n\\nPLEASE INCORPORATE THIS FEEDBACK INTO THE REFINED TASK LIST.` : ''}\n\nRefine the task list and determine if any additional questions are needed.`,\n\n initialPrompt: context => `Create an initial task plan for ${context.action}ing a Mastra workflow.\n\nREQUIREMENTS:\n- Action: ${context.action}\n- Workflow Name: ${context.workflowName || 'To be determined'}\n- Description: ${context.description || 'Not specified'} \n- Requirements: ${context.requirements || 'Not specified'}\n\nPROJECT CONTEXT:\n- Discovered Workflows: ${JSON.stringify(context.discoveredWorkflows, null, 2)}\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n- Research: ${JSON.stringify(context.research, null, 2)}\n\nCreate specific tasks and identify any questions that need user clarification.`,\n },\n\n taskApproval: {\n message: questionsCount => `Please answer ${questionsCount} question(s) to finalize the workflow plan:`,\n approvalMessage: tasksCount => `Please review and approve the ${tasksCount} task(s) for execution:`,\n },\n};\n","import { z } from 'zod';\nimport { PlanningIterationResultSchema, QuestionSchema, TaskSchema } from '../shared/schema';\n\n// Workflow Builder schemas and types\nexport const WorkflowBuilderInputSchema = z.object({\n workflowName: z.string().optional().describe('Name of the workflow to create or edit'),\n action: z.enum(['create', 'edit']).describe('Action to perform: create new or edit existing workflow'),\n description: z.string().optional().describe('Description of what the workflow should do'),\n requirements: z.string().optional().describe('Detailed requirements for the workflow'),\n projectPath: z.string().optional().describe('Path to the Mastra project (defaults to current directory)'),\n});\n\nexport const DiscoveredWorkflowSchema = z.object({\n name: z.string(),\n file: z.string(),\n description: z.string().optional(),\n inputSchema: z.any().optional(),\n outputSchema: z.any().optional(),\n steps: z.array(z.string()).optional(),\n});\n\nexport const WorkflowDiscoveryResultSchema = z.object({\n success: z.boolean(),\n workflows: z.array(DiscoveredWorkflowSchema),\n mastraIndexExists: z.boolean(),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const ProjectDiscoveryResultSchema = z.object({\n success: z.boolean(),\n structure: z.object({\n hasWorkflowsDir: z.boolean(),\n hasAgentsDir: z.boolean(),\n hasToolsDir: z.boolean(),\n hasMastraIndex: z.boolean(),\n existingWorkflows: z.array(z.string()),\n existingAgents: z.array(z.string()),\n existingTools: z.array(z.string()),\n }),\n dependencies: z.record(z.string(), z.string()),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const WorkflowResearchResultSchema = z.object({\n success: z.boolean(),\n documentation: z.object({\n workflowPatterns: z.array(z.string()),\n stepExamples: z.array(z.string()),\n bestPractices: z.array(z.string()),\n }),\n webResources: z.array(\n z.object({\n title: z.string(),\n url: z.string(),\n snippet: z.string(),\n relevance: z.number(),\n }),\n ),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const TaskManagementResultSchema = z.object({\n success: z.boolean(),\n tasks: TaskSchema,\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const TaskExecutionInputSchema = z.object({\n action: z.enum(['create', 'edit']),\n workflowName: z.string().optional(),\n description: z.string().optional(),\n requirements: z.string().optional(),\n tasks: TaskSchema,\n discoveredWorkflows: z.array(z.any()),\n projectStructure: z.any(),\n research: z.any(),\n projectPath: z.string().optional(),\n});\n\nexport const TaskExecutionSuspendSchema = z.object({\n questions: QuestionSchema,\n currentProgress: z.string(),\n completedTasks: z.array(z.string()),\n message: z.string(),\n});\n\nexport const TaskExecutionResumeSchema = z.object({\n answers: z.array(\n z.object({\n questionId: z.string(),\n answer: z.string(),\n }),\n ),\n});\n\nexport const TaskExecutionResultSchema = z.object({\n success: z.boolean(),\n filesModified: z.array(z.string()),\n validationResults: z.object({\n passed: z.boolean(),\n errors: z.array(z.string()),\n warnings: z.array(z.string()),\n }),\n completedTasks: z.array(z.string()),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const UserClarificationInputSchema = z.object({\n questions: QuestionSchema,\n});\n\nexport const UserClarificationResultSchema = z.object({\n answers: z.record(z.string(), z.string()),\n hasAnswers: z.boolean(),\n});\n\nexport const WorkflowBuilderResultSchema = z.object({\n success: z.boolean(),\n action: z.enum(['create', 'edit']),\n workflowName: z.string().optional(),\n workflowFile: z.string().optional(),\n discovery: WorkflowDiscoveryResultSchema.optional(),\n projectStructure: ProjectDiscoveryResultSchema.optional(),\n research: WorkflowResearchResultSchema.optional(),\n planning: PlanningIterationResultSchema.optional(),\n taskManagement: TaskManagementResultSchema.optional(),\n execution: TaskExecutionResultSchema.optional(),\n needsUserInput: z.boolean().optional(),\n questions: QuestionSchema.optional(),\n message: z.string(),\n nextSteps: z.array(z.string()).optional(),\n error: z.string().optional(),\n});\n\nexport const TaskExecutionIterationInputSchema = (taskLength: number) =>\n z.object({\n status: z\n .enum(['in_progress', 'completed', 'needs_clarification'])\n .describe('Status - only use \"completed\" when ALL remaining tasks are finished'),\n progress: z.string().describe('Current progress description'),\n completedTasks: z\n .array(z.string())\n .describe('List of ALL completed task IDs (including previously completed ones)'),\n totalTasksRequired: z.number().describe(`Total number of tasks that must be completed (should be ${taskLength})`),\n tasksRemaining: z.array(z.string()).describe('List of task IDs that still need to be completed'),\n filesModified: z\n .array(z.string())\n .describe('List of files that were created or modified - use these exact paths for validateCode tool'),\n questions: QuestionSchema.optional().describe('Questions for user if clarification is needed'),\n message: z.string().describe('Summary of work completed or current status'),\n error: z.string().optional().describe('Any errors encountered'),\n });\n","import { z } from 'zod';\nimport { QuestionSchema, TaskSchema } from '../shared/schema';\nimport {\n ProjectDiscoveryResultSchema,\n WorkflowResearchResultSchema,\n DiscoveredWorkflowSchema,\n} from '../workflow-builder/schema';\n\nexport const PlanningIterationInputSchema = z.object({\n action: z.enum(['create', 'edit']),\n workflowName: z.string().optional(),\n description: z.string().optional(),\n requirements: z.string().optional(),\n discoveredWorkflows: z.array(DiscoveredWorkflowSchema),\n projectStructure: ProjectDiscoveryResultSchema,\n research: WorkflowResearchResultSchema,\n\n userAnswers: z.record(z.string(), z.string()).optional(),\n});\n\nexport const PlanningIterationSuspendSchema = z.object({\n questions: QuestionSchema,\n message: z.string(),\n currentPlan: z.object({\n tasks: TaskSchema,\n reasoning: z.string(),\n }),\n});\n\nexport const PlanningIterationResumeSchema = z.object({\n answers: z.record(z.string(), z.string()),\n});\n\nexport const PlanningAgentOutputSchema = z.object({\n tasks: TaskSchema,\n questions: QuestionSchema.optional(),\n reasoning: z.string().describe('Explanation of the plan and any questions'),\n planComplete: z.boolean().describe('Whether the plan is ready for execution (no more questions)'),\n});\n\nexport const TaskApprovalOutputSchema = z.object({\n approved: z.boolean(),\n tasks: TaskSchema,\n message: z.string(),\n userFeedback: z.string().optional(),\n});\n\nexport const TaskApprovalSuspendSchema = z.object({\n taskList: TaskSchema,\n summary: z.string(),\n message: z.string(),\n});\n\nexport const TaskApprovalResumeSchema = z.object({\n approved: z.boolean(),\n modifications: z.string().optional(),\n});\n","import { Agent } from '@mastra/core/agent';\nimport { createWorkflow, createStep } from '@mastra/core/workflows';\nimport type z from 'zod';\nimport { resolveModel } from '../../utils';\nimport { PlanningIterationResultSchema } from '../shared/schema';\nimport { taskPlanningPrompts } from './prompts';\nimport {\n PlanningAgentOutputSchema,\n PlanningIterationInputSchema,\n PlanningIterationResumeSchema,\n PlanningIterationSuspendSchema,\n TaskApprovalOutputSchema,\n TaskApprovalResumeSchema,\n TaskApprovalSuspendSchema,\n} from './schema';\n\ntype PlanningIterationResult = z.infer<typeof PlanningIterationResultSchema>;\n\n// Planning iteration step (with questions and user answers)\nconst planningIterationStep = createStep({\n id: 'planning-iteration',\n description: 'Create or refine task plan with user input',\n inputSchema: PlanningIterationInputSchema,\n outputSchema: PlanningIterationResultSchema,\n suspendSchema: PlanningIterationSuspendSchema,\n resumeSchema: PlanningIterationResumeSchema,\n execute: async ({ inputData, resumeData, suspend, requestContext }) => {\n const {\n action,\n workflowName,\n description,\n requirements,\n discoveredWorkflows,\n projectStructure,\n research,\n userAnswers,\n } = inputData;\n\n console.info('Starting planning iteration...');\n\n // Get or initialize Q&A tracking in request context\n const qaKey = 'workflow-builder-qa';\n let storedQAPairs: Array<{\n question: any;\n answer: string | null;\n askedAt: string;\n answeredAt: string | null;\n }> = requestContext.get(qaKey) || [];\n\n // Process new answers from user input or resume data\n const newAnswers = { ...(userAnswers || {}), ...(resumeData?.answers || {}) };\n\n // console.info('before', storedQAPairs);\n // console.info('newAnswers', newAnswers);\n // Update existing Q&A pairs with new answers\n if (Object.keys(newAnswers).length > 0) {\n storedQAPairs = storedQAPairs.map(pair => {\n const answerValue = newAnswers[pair.question.id];\n if (answerValue) {\n return {\n ...pair,\n answer: String(answerValue) || null,\n answeredAt: new Date().toISOString(),\n };\n }\n return pair;\n });\n\n // Store updated pairs back to request context\n requestContext.set(qaKey, storedQAPairs);\n }\n\n // console.info('after', storedQAPairs);\n\n // console.info(\n // `Current Q&A state: ${storedQAPairs.length} question-answer pairs, ${storedQAPairs.filter(p => p.answer).length} answered`,\n // );\n\n try {\n // const filteredMcpTools = await initializeMcpTools();\n\n const model = await resolveModel({ requestContext });\n\n const planningAgent = new Agent({\n id: 'workflow-planning-agent',\n model,\n instructions: taskPlanningPrompts.planningAgent.instructions({\n storedQAPairs,\n }),\n name: 'Workflow Planning Agent',\n // tools: filteredMcpTools,\n });\n\n // Check if we have user feedback from rejected task list in input data\n const hasTaskFeedback = Boolean(userAnswers && userAnswers.taskFeedback);\n\n const planningPrompt = storedQAPairs.some(pair => pair.answer)\n ? taskPlanningPrompts.planningAgent.refinementPrompt({\n action,\n workflowName,\n description,\n requirements,\n discoveredWorkflows,\n projectStructure,\n research,\n storedQAPairs,\n hasTaskFeedback,\n userAnswers,\n })\n : taskPlanningPrompts.planningAgent.initialPrompt({\n action,\n workflowName,\n description,\n requirements,\n discoveredWorkflows,\n projectStructure,\n research,\n });\n\n const result = await planningAgent.generate(planningPrompt, {\n structuredOutput: {\n schema: PlanningAgentOutputSchema,\n },\n // maxSteps: 15,\n });\n\n const planResult = (await result.object) as unknown as PlanningIterationResult | null;\n if (!planResult) {\n return {\n tasks: [],\n success: false,\n questions: [],\n reasoning: 'Planning agent failed to generate a valid response',\n planComplete: false,\n message: 'Planning failed',\n };\n }\n\n // If we have questions and plan is not complete, suspend for user input\n if (planResult.questions && planResult.questions.length > 0 && !planResult.planComplete) {\n console.info(`Planning needs user clarification: ${planResult.questions.length} questions`);\n\n console.info(planResult.questions);\n\n // Store new questions as Q&A pairs in request context\n const newQAPairs = planResult.questions.map((question: any) => ({\n question,\n answer: null,\n askedAt: new Date().toISOString(),\n answeredAt: null,\n }));\n\n storedQAPairs = [...storedQAPairs, ...newQAPairs];\n requestContext.set(qaKey, storedQAPairs);\n\n console.info(\n `Updated Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter(p => p.answer).length} answered`,\n );\n\n return suspend({\n questions: planResult.questions,\n message: taskPlanningPrompts.taskApproval.message(planResult.questions.length),\n currentPlan: {\n tasks: planResult.tasks,\n reasoning: planResult.reasoning,\n },\n });\n }\n\n // Plan is complete\n console.info(`Planning complete with ${planResult.tasks.length} tasks`);\n\n // Update request context with final state\n requestContext.set(qaKey, storedQAPairs);\n console.info(\n `Final Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter(p => p.answer).length} answered`,\n );\n\n return {\n tasks: planResult.tasks,\n success: true,\n questions: [],\n reasoning: planResult.reasoning,\n planComplete: true,\n message: `Successfully created ${planResult.tasks.length} tasks`,\n allPreviousQuestions: storedQAPairs.map(pair => pair.question),\n allPreviousAnswers: Object.fromEntries(\n storedQAPairs.filter(pair => pair.answer).map(pair => [pair.question.id, pair.answer]),\n ),\n };\n } catch (error) {\n console.error('Planning iteration failed:', error);\n return {\n tasks: [],\n success: false,\n questions: [],\n reasoning: `Planning failed: ${error instanceof Error ? error.message : String(error)}`,\n planComplete: false,\n message: 'Planning iteration failed',\n error: error instanceof Error ? error.message : String(error),\n allPreviousQuestions: storedQAPairs.map(pair => pair.question),\n allPreviousAnswers: Object.fromEntries(\n storedQAPairs.filter(pair => pair.answer).map(pair => [pair.question.id, pair.answer]),\n ),\n };\n }\n },\n});\n\n// Task approval step\nconst taskApprovalStep = createStep({\n id: 'task-approval',\n description: 'Get user approval for the final task list',\n inputSchema: PlanningIterationResultSchema,\n outputSchema: TaskApprovalOutputSchema,\n suspendSchema: TaskApprovalSuspendSchema,\n resumeSchema: TaskApprovalResumeSchema,\n execute: async ({ inputData, resumeData, suspend }) => {\n const { tasks } = inputData;\n\n // If no resume data, suspend for user approval\n if (!resumeData?.approved && resumeData?.approved !== false) {\n console.info(`Requesting user approval for ${tasks.length} tasks`);\n\n const summary = `Task List for Approval:\n\n${tasks.length} tasks planned:\n${tasks.map((task, i) => `${i + 1}. [${task.priority.toUpperCase()}] ${task.content}${task.dependencies?.length ? ` (depends on: ${task.dependencies.join(', ')})` : ''}\\n Notes: ${task.notes || 'None'}`).join('\\n')}`;\n\n return suspend({\n taskList: tasks,\n summary,\n message: taskPlanningPrompts.taskApproval.approvalMessage(tasks.length),\n });\n }\n\n // User responded\n if (resumeData.approved) {\n console.info('Task list approved by user');\n return {\n approved: true,\n tasks,\n message: 'Task list approved, ready for execution',\n };\n } else {\n console.info('Task list rejected by user');\n return {\n approved: false,\n tasks,\n message: 'Task list rejected',\n userFeedback: resumeData.modifications,\n };\n }\n },\n});\n\n// Sub-workflow: Planning and Approval Cycle\nexport const planningAndApprovalWorkflow = createWorkflow({\n id: 'planning-and-approval',\n description: 'Handle iterative planning with questions and task list approval',\n inputSchema: PlanningIterationInputSchema,\n outputSchema: TaskApprovalOutputSchema,\n steps: [planningIterationStep, taskApprovalStep],\n})\n // Step 1: Planning iteration (with questions suspension)\n .dountil(planningIterationStep, async ({ inputData }) => {\n console.info(`Sub-workflow planning check: planComplete=${inputData.planComplete}`);\n return inputData.planComplete === true;\n })\n // Map to approval step input format\n .map(async ({ inputData }) => {\n // After doUntil completes, inputData contains the final result\n return {\n tasks: inputData.tasks || [],\n success: inputData.success || false,\n questions: inputData.questions || [],\n reasoning: inputData.reasoning || '',\n planComplete: inputData.planComplete || false,\n message: inputData.message || '',\n };\n })\n // Step 2: Task list approval\n .then(taskApprovalStep)\n .commit();\n","export const workflowResearch = `\n## 🔍 **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**\n\nBased on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:\n\n### **📋 WORKFLOW FUNDAMENTALS**\n\n**Core Components:**\n- **\\`createWorkflow()\\`**: Main factory function that creates workflow instances\n- **\\`createStep()\\`**: Creates individual workflow steps with typed inputs/outputs \n- **\\`.commit()\\`**: Finalizes workflow definition (REQUIRED to make workflows executable)\n- **Zod schemas**: Used for strict input/output typing and validation\n\n**Basic Structure:**\n\\`\\`\\`typescript\nimport { createWorkflow, createStep } from \"@mastra/core/workflows\";\nimport { z } from \"zod\";\n\nconst workflow = createWorkflow({\n id: \"unique-workflow-id\", // Required: kebab-case recommended\n description: \"What this workflow does\", // Optional but recommended\n inputSchema: z.object({...}), // Required: Defines workflow inputs\n outputSchema: z.object({...}) // Required: Defines final outputs\n})\n .then(step1) // Chain steps sequentially\n .then(step2)\n .commit(); // CRITICAL: Makes workflow executable\n\\`\\`\\`\n\n### **🔧 STEP CREATION PATTERNS**\n\n**Standard Step Definition:**\n\\`\\`\\`typescript\nconst myStep = createStep({\n id: \"step-id\", // Required: unique identifier\n description: \"Step description\", // Recommended for clarity\n inputSchema: z.object({...}), // Required: input validation\n outputSchema: z.object({...}), // Required: output validation\n execute: async ({ inputData, mastra, getStepResult, getInitData }) => {\n // Step logic here\n return { /* matches outputSchema */ };\n }\n});\n\\`\\`\\`\n\n**Execute Function Parameters:**\n- \\`inputData\\`: Validated input matching inputSchema\n- \\`mastra\\`: Access to Mastra instance (agents, tools, other workflows)\n- \\`getStepResult(stepInstance)\\`: Get results from previous steps\n- \\`getInitData()\\`: Access original workflow input data\n- \\`requestContext\\`: Runtime dependency injection context\n- \\`runCount\\`: Number of times this step has run (useful for retries)\n\n### **🔄 CONTROL FLOW METHODS**\n\n**Sequential Execution:**\n- \\`.then(step)\\`: Execute steps one after another\n- Data flows automatically if schemas match\n\n**Parallel Execution:**\n- \\`.parallel([step1, step2])\\`: Run steps simultaneously\n- All parallel steps complete before continuing\n\n**Conditional Logic:**\n- \\`.branch([[condition, step], [condition, step]])\\`: Execute different steps based on conditions\n- Conditions evaluated sequentially, matching steps run in parallel\n\n**Loops:**\n- \\`.dountil(step, condition)\\`: Repeat until condition becomes true\n- \\`.dowhile(step, condition)\\`: Repeat while condition is true \n- \\`.foreach(step, {concurrency: N})\\`: Execute step for each array item\n\n**Data Transformation:**\n- \\`.map(({ inputData, getStepResult, getInitData }) => transformedData)\\`: Transform data between steps\n\n### **⏸️ SUSPEND & RESUME CAPABILITIES**\n\n**For Human-in-the-Loop Workflows:**\n\\`\\`\\`typescript\nconst userInputStep = createStep({\n id: \"user-input\",\n suspendSchema: z.object({}), // Schema for suspension payload\n resumeSchema: z.object({ // Schema for resume data\n userResponse: z.string()\n }),\n execute: async ({ resumeData, suspend }) => {\n if (!resumeData?.userResponse) {\n await suspend({}); // Pause workflow\n return { response: \"\" };\n }\n return { response: resumeData.userResponse };\n }\n});\n\\`\\`\\`\n\n**Resume Workflow:**\n\\`\\`\\`typescript\nconst result = await run.start({ inputData: {...} });\nif (result.status === \"suspended\") {\n await run.resume({\n step: result.suspended[0], // Or specific step ID\n resumeData: { userResponse: \"answer\" }\n });\n}\n\\`\\`\\`\n\n### **🛠️ INTEGRATING AGENTS & TOOLS**\n\n**Using Agents in Steps:**\n\\`\\`\\`typescript\n// Method 1: Agent as step\nconst agentStep = createStep(myAgent);\n\n// Method 2: Call agent in execute function\nconst step = createStep({\n execute: async ({ inputData }) => {\n const result = await myAgent.generate(prompt);\n return { output: result.text };\n }\n});\n\\`\\`\\`\n\n**Using Tools in Steps:**\n\\`\\`\\`typescript\n// Method 1: Tool as step \nconst toolStep = createStep(myTool);\n\n// Method 2: Call tool in execute function\nconst step = createStep({\n execute: async ({ inputData, requestContext }) => {\n const result = await myTool.execute({\n context: inputData,\n requestContext\n });\n return result;\n }\n});\n\\`\\`\\`\n\n### **🗂️ PROJECT ORGANIZATION PATTERNS**\n\n**MANDATORY Workflow Organization:**\nEach workflow MUST be organized in its own dedicated folder with separated concerns:\n\n\\`\\`\\`\nsrc/mastra/workflows/\n├── my-workflow-name/ # Kebab-case folder name\n│ ├── types.ts # All Zod schemas and TypeScript types\n│ ├── steps.ts # All individual step definitions\n│ ├── workflow.ts # Main workflow composition and export\n│ └── utils.ts # Helper functions (if needed)\n├── another-workflow/\n│ ├── types.ts\n│ ├── steps.ts\n│ ├── workflow.ts\n│ └── utils.ts\n└── index.ts # Export all workflows\n\\`\\`\\`\n\n**CRITICAL File Organization Rules:**\n- **ALWAYS create a dedicated folder** for each workflow\n- **Folder names MUST be kebab-case** version of workflow name\n- **types.ts**: Define all input/output schemas, validation types, and interfaces\n- **steps.ts**: Create all individual step definitions using createStep()\n- **workflow.ts**: Compose steps into workflow using createWorkflow() and export the final workflow\n- **utils.ts**: Any helper functions, constants, or utilities (create only if needed)\n- **NEVER put everything in one file** - always separate concerns properly\n\n**Workflow Registration:**\n\\`\\`\\`typescript\n// src/mastra/index.ts\nexport const mastra = new Mastra({\n workflows: {\n sendEmailWorkflow, // Use camelCase for keys\n dataProcessingWorkflow\n },\n storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }), // Required for suspend/resume\n});\n\\`\\`\\`\n\n### **📦 ESSENTIAL DEPENDENCIES**\n\n**Required Packages:**\n\\`\\`\\`json\n{\n \"dependencies\": {\n \"@mastra/core\": \"latest\",\n \"zod\": \"^3.25.67\"\n }\n}\n\\`\\`\\`\n\n**Additional Packages (as needed):**\n- \\`@mastra/libsql\\`: For workflow state persistence\n- \\`@ai-sdk/openai\\`: For AI model integration\n- \\`ai\\`: For AI SDK functionality\n\n### **✅ WORKFLOW BEST PRACTICES**\n\n**Schema Design:**\n- Use descriptive property names in schemas\n- Make schemas as specific as possible (avoid \\`z.any()\\`)\n- Include validation for required business logic\n\n**Error Handling:**\n- Use \\`try/catch\\` blocks in step execute functions\n- Return meaningful error messages\n- Consider using \\`bail()\\` for early successful exits\n\n**Step Organization:**\n- Keep steps focused on single responsibilities\n- Use descriptive step IDs (kebab-case recommended)\n- Create reusable steps for common operations\n\n**Data Flow:**\n- Use \\`.map()\\` when schemas don't align between steps\n- Access previous step results with \\`getStepResult(stepInstance)\\`\n- Use \\`getInitData()\\` to access original workflow input\n\n### **🚀 EXECUTION PATTERNS**\n\n**Running Workflows:**\n\\`\\`\\`typescript\n// Create and start run\nconst run = await workflow.createRun();\nconst result = await run.start({ inputData: {...} });\n\n// Stream execution for real-time monitoring\nconst stream = await run.streamVNext({ inputData: {...} });\nfor await (const chunk of stream) {\n console.log(chunk);\n}\n\n// Watch for events\nrun.watch((event) => console.log(event));\n\\`\\`\\`\n\n**Workflow Status Types:**\n- \\`\"success\"\\`: Completed successfully\n- \\`\"suspended\"\\`: Paused awaiting input\n- \\`\"failed\"\\`: Encountered error\n\n### **🔗 ADVANCED FEATURES**\n\n**Nested Workflows:**\n- Use workflows as steps: \\`.then(otherWorkflow)\\`\n- Enable complex workflow composition\n\n**Request Context:**\n- Pass shared data across all steps\n- Enable dependency injection patterns\n\n**Streaming & Events:**\n- Real-time workflow monitoring\n- Integration with external event systems\n\n**Cloning:**\n- \\`cloneWorkflow(original, {id: \"new-id\"})\\`: Reuse workflow structure\n- \\`cloneStep(original, {id: \"new-id\"})\\`: Reuse step logic\n\nThis comprehensive research provides the foundation for creating robust, maintainable Mastra workflows with proper typing, error handling, and architectural patterns.\n`;\n/**\n * Prompts and instructions for workflow builder agents\n */\n\nexport interface WorkflowBuilderPrompts {\n researchAgent: {\n instructions: string;\n prompt: (context: { projectStructure: any; dependencies: any; hasWorkflowsDir: boolean }) => string;\n };\n executionAgent: {\n instructions: (context: {\n action: string;\n workflowName?: string;\n tasksLength: number;\n currentProjectPath: string;\n discoveredWorkflows: any;\n projectStructure: any;\n research: any;\n tasks: any[];\n resumeData?: any;\n }) => string;\n prompt: (context: { action: string; workflowName?: string; tasks: any[]; resumeData?: any }) => string;\n iterationPrompt: (context: {\n completedTasks: any[];\n pendingTasks: any[];\n workflowName?: string;\n resumeData?: any;\n }) => string;\n };\n validation: {\n instructions: string;\n };\n}\n\nexport const workflowBuilderPrompts: WorkflowBuilderPrompts = {\n researchAgent: {\n instructions: `You are a Mastra workflow research expert. Your task is to gather relevant information about creating Mastra workflows.\n\nRESEARCH OBJECTIVES:\n1. **Core Concepts**: Understand how Mastra workflows work\n2. **Best Practices**: Learn workflow patterns and conventions \n3. **Code Examples**: Find relevant implementation examples\n4. **Technical Details**: Understand schemas, steps, and configuration\n\nUse the available documentation and examples tools to gather comprehensive information about Mastra workflows.`,\n\n prompt: context => `Research everything about Mastra workflows to help create or edit them effectively.\n\nPROJECT CONTEXT:\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n- Dependencies: ${JSON.stringify(context.dependencies, null, 2)}\n- Has Workflows Directory: ${context.hasWorkflowsDir}\n\nFocus on:\n1. How to create workflows using createWorkflow()\n2. How to create and chain workflow steps\n3. Best practices for workflow organization\n4. Common workflow patterns and examples\n5. Schema definitions and types\n6. Error handling and debugging\n\nUse the docs and examples tools to gather comprehensive information.`,\n },\n\n executionAgent: {\n instructions: context => `You are executing a workflow ${context.action} task for: \"${context.workflowName}\"\n\nCRITICAL WORKFLOW EXECUTION REQUIREMENTS:\n1. **EXPLORE PROJECT STRUCTURE FIRST**: Use listDirectory and readFile tools to understand the existing project layout, folder structure, and conventions before creating any files\n2. **FOLLOW PROJECT CONVENTIONS**: Look at existing workflows, agents, and file structures to understand where new files should be placed (typically src/mastra/workflows/, src/mastra/agents/, etc.)\n3. **USE PRE-LOADED TASK LIST**: Your task list has been pre-populated in the taskManager tool. Use taskManager with action 'list' to see all tasks, and action 'update' to mark progress\n4. **COMPLETE EVERY SINGLE TASK**: You MUST complete ALL ${context.tasksLength} tasks that are already in the taskManager. Do not stop until every task is marked as 'completed'\n5. **Follow Task Dependencies**: Execute tasks in the correct order, respecting dependencies\n6. **Request User Input When Needed**: If you encounter choices (like email providers, databases, etc.) that require user decision, return questions for clarification\n7. **STRICT WORKFLOW ORGANIZATION**: When creating or editing workflows, you MUST follow this exact structure\n\nMANDATORY WORKFLOW FOLDER STRUCTURE:\nWhen ${context.action === 'create' ? 'creating a new workflow' : 'editing a workflow'}, you MUST organize files as follows:\n\n📁 src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, '-') || 'new-workflow'}/\n├── 📄 types.ts # All Zod schemas and TypeScript types\n├── 📄 steps.ts # All individual step definitions \n├── 📄 workflow.ts # Main workflow composition and export\n└── 📄 utils.ts # Helper functions (if needed)\n\nCRITICAL FILE ORGANIZATION RULES:\n- **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/\n- **Folder name MUST be kebab-case** version of workflow name\n- **types.ts**: Define all input/output schemas, validation types, and interfaces\n- **steps.ts**: Create all individual step definitions using createStep()\n- **workflow.ts**: Compose steps into workflow using createWorkflow() and export the final workflow\n- **utils.ts**: Any helper functions, constants, or utilities (create only if needed)\n- **NEVER put everything in one file** - always separate concerns properly\n\nCRITICAL COMPLETION REQUIREMENTS: \n- ALWAYS explore the directory structure before creating files to understand where they should go\n- You MUST complete ALL ${context.tasksLength} tasks before returning status='completed'\n- Use taskManager tool with action 'list' to see your current task list and action 'update' to mark tasks as 'in_progress' or 'completed'\n- If you need to make any decisions during implementation (choosing providers, configurations, etc.), return questions for user clarification\n- DO NOT make assumptions about file locations - explore first!\n- You cannot finish until ALL tasks in the taskManager are marked as 'completed'\n\nPROJECT CONTEXT:\n- Action: ${context.action}\n- Workflow Name: ${context.workflowName}\n- Project Path: ${context.currentProjectPath}\n- Discovered Workflows: ${JSON.stringify(context.discoveredWorkflows, null, 2)}\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n\nAVAILABLE RESEARCH:\n${JSON.stringify(context.research, null, 2)}\n\nPRE-LOADED TASK LIST (${context.tasksLength} tasks already in taskManager):\n${context.tasks.map(task => `- ${task.id}: ${task.content} (Priority: ${task.priority})`).join('\\n')}\n\n${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeData.answers, null, 2)}` : ''}\n\nStart by exploring the project structure, then use 'taskManager' with action 'list' to see your pre-loaded tasks, and work through each task systematically.`,\n\n prompt: context =>\n context.resumeData\n ? `Continue working on the task list. The user has provided answers to your questions: ${JSON.stringify(context.resumeData.answers, null, 2)}. \n\nCRITICAL: You must complete ALL ${context.tasks.length} tasks that are pre-loaded in the taskManager. Use the taskManager tool with action 'list' to check your progress and continue with the next tasks. Do not stop until every single task is marked as 'completed'.`\n : `Begin executing the pre-loaded task list to ${context.action} the workflow \"${context.workflowName}\". \n\nCRITICAL REQUIREMENTS:\n- Your ${context.tasks.length} tasks have been PRE-LOADED into the taskManager tool\n- Start by exploring the project directory structure using listDirectory and readFile tools to understand:\n - Where workflows are typically stored (look for src/mastra/workflows/ or similar)\n - What the existing file structure looks like\n - How other workflows are organized and named\n - Where agent files are stored if needed\n- Then use taskManager with action 'list' to see your pre-loaded tasks\n- Use taskManager with action 'update' to mark tasks as 'in_progress' or 'completed'\n\nCRITICAL FILE ORGANIZATION RULES:\n- **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/\n- **Folder name MUST be kebab-case** version of workflow name \n- **NEVER put everything in one file** - separate types, steps, and workflow composition\n- Follow the 4-file structure above for maximum maintainability and clarity\n\n- DO NOT return status='completed' until ALL ${context.tasks.length} tasks are marked as 'completed' in the taskManager\n\nPRE-LOADED TASKS (${context.tasks.length} total tasks in taskManager):\n${context.tasks.map((task, index) => `${index + 1}. [${task.id}] ${task.content}`).join('\\n')}\n\nUse taskManager with action 'list' to see the current status of all tasks. You must complete every single one before finishing.`,\n\n iterationPrompt:\n context => `Continue working on the remaining tasks. You have already completed these tasks: [${context.completedTasks.map(t => t.id).join(', ')}]\n\nREMAINING TASKS TO COMPLETE (${context.pendingTasks.length} tasks):\n${context.pendingTasks.map((task, index) => `${index + 1}. [${task.id}] ${task.content}`).join('\\n')}\n\nCRITICAL: You must complete ALL of these remaining ${context.pendingTasks.length} tasks. Use taskManager with action 'list' to check current status and action 'update' to mark tasks as completed.\n\n${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeData.answers, null, 2)}` : ''}`,\n },\n\n validation: {\n instructions: `CRITICAL VALIDATION INSTRUCTIONS:\n- When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter\n- The tool uses a hybrid validation approach: fast syntax checking → semantic type checking → ESLint\n- This is much faster than full project compilation and only shows errors from your specific files\n- Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })\n- ALWAYS validate after creating or modifying files to ensure they compile correctly`,\n },\n};\n","import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\nimport { AgentBuilderDefaults } from '../../defaults';\n\n// taskManager tool that only allows updates, not creation\nexport const restrictedTaskManager = createTool({\n id: 'task-manager',\n description:\n 'View and update your pre-loaded task list. You can only mark tasks as in_progress or completed, not create new tasks.',\n inputSchema: z.object({\n action: z\n .enum(['list', 'update', 'complete'])\n .describe('List tasks, update status, or mark complete - tasks are pre-loaded'),\n tasks: z\n .array(\n z.object({\n id: z.string().describe('Task ID - must match existing task'),\n content: z.string().optional().describe('Task content (read-only)'),\n status: z.enum(['pending', 'in_progress', 'completed', 'blocked']).describe('Task status'),\n priority: z.enum(['high', 'medium', 'low']).optional().describe('Task priority (read-only)'),\n dependencies: z.array(z.string()).optional().describe('Task dependencies (read-only)'),\n notes: z.string().optional().describe('Additional notes or progress updates'),\n }),\n )\n .optional()\n .describe('Tasks to update (status and notes only)'),\n taskId: z.string().optional().describe('Specific task ID for single task operations'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n tasks: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n status: z.string(),\n priority: z.string(),\n dependencies: z.array(z.string()).optional(),\n notes: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n }),\n ),\n message: z.string(),\n }),\n execute: async input => {\n // Convert to the expected format for manageTaskList\n const adaptedContext = {\n ...input,\n action: input.action,\n tasks: input.tasks?.map(task => ({\n ...task,\n priority: task.priority || ('medium' as const),\n })),\n };\n return await AgentBuilderDefaults.manageTaskList(adaptedContext);\n },\n});\n","import { existsSync } from 'node:fs';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { stepCountIs } from '@internal/ai-sdk-v5';\nimport { Agent } from '@mastra/core/agent';\nimport { createWorkflow, createStep } from '@mastra/core/workflows';\nimport type { z } from 'zod';\nimport { AgentBuilder } from '../../agent';\nimport { AgentBuilderDefaults } from '../../defaults';\nimport { resolveModel } from '../../utils';\nimport { planningAndApprovalWorkflow } from '../task-planning/task-planning';\nimport { workflowBuilderPrompts, workflowResearch as research } from './prompts';\nimport {\n WorkflowBuilderInputSchema,\n WorkflowBuilderResultSchema,\n WorkflowDiscoveryResultSchema,\n ProjectDiscoveryResultSchema,\n WorkflowResearchResultSchema,\n TaskExecutionResultSchema,\n TaskExecutionInputSchema,\n TaskExecutionResumeSchema,\n TaskExecutionSuspendSchema,\n TaskExecutionIterationInputSchema,\n} from './schema';\nimport type { DiscoveredWorkflowSchema } from './schema';\nimport { restrictedTaskManager } from './tools';\n\ntype WorkflowBuilderInputSchemaType = z.infer<typeof WorkflowBuilderInputSchema>;\n\n// Step 1: Always discover existing workflows\nconst workflowDiscoveryStep = createStep({\n id: 'workflow-discovery',\n description: 'Discover existing workflows in the project',\n inputSchema: WorkflowBuilderInputSchema,\n outputSchema: WorkflowDiscoveryResultSchema,\n execute: async ({ inputData, requestContext: _requestContext }) => {\n console.info('Starting workflow discovery...');\n const { projectPath = process.cwd() } = inputData;\n\n try {\n // Check if workflows directory exists\n const workflowsPath = join(projectPath, 'src/mastra/workflows');\n if (!existsSync(workflowsPath)) {\n console.info('No workflows directory found');\n return {\n success: true,\n workflows: [],\n mastraIndexExists: existsSync(join(projectPath, 'src/mastra/index.ts')),\n message: 'No existing workflows found in the project',\n };\n }\n\n // Read workflow files directly\n const workflowFiles = await readdir(workflowsPath);\n const workflows: z.infer<typeof DiscoveredWorkflowSchema>[] = [];\n\n for (const fileName of workflowFiles) {\n if (fileName.endsWith('.ts') && !fileName.endsWith('.test.ts')) {\n const filePath = join(workflowsPath, fileName);\n try {\n const content = await readFile(filePath, 'utf-8');\n\n // Extract basic workflow info\n const nameMatch = content.match(/createWorkflow\\s*\\(\\s*{\\s*id:\\s*['\"]([^'\"]+)['\"]/);\n const descMatch = content.match(/description:\\s*['\"]([^'\"]*)['\"]/);\n\n if (nameMatch && nameMatch[1]) {\n workflows.push({\n name: nameMatch[1],\n file: filePath,\n description: descMatch?.[1] ?? 'No description available',\n });\n }\n } catch (error) {\n console.warn(`Failed to read workflow file ${filePath}:`, error);\n }\n }\n }\n\n console.info(`Discovered ${workflows.length} existing workflows`);\n return {\n success: true,\n workflows,\n mastraIndexExists: existsSync(join(projectPath, 'src/mastra/index.ts')),\n message:\n workflows.length > 0\n ? `Found ${workflows.length} existing workflow(s): ${workflows.map(w => w.name).join(', ')}`\n : 'No existing workflows found in the project',\n };\n } catch (error) {\n console.error('Workflow discovery failed:', error);\n return {\n success: false,\n workflows: [],\n mastraIndexExists: false,\n message: `Workflow discovery failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 2: Always discover project structure\nconst projectDiscoveryStep = createStep({\n id: 'project-discovery',\n description: 'Analyze the project structure and setup',\n inputSchema: WorkflowDiscoveryResultSchema,\n outputSchema: ProjectDiscoveryResultSchema,\n execute: async ({ inputData: _inputData, requestContext: _requestContext }) => {\n console.info('Starting project discovery...');\n\n try {\n // Get project structure - no need for AgentBuilder since we're just checking files\n const projectPath = process.cwd(); // Use current working directory as default\n const projectStructure = {\n hasPackageJson: existsSync(join(projectPath, 'package.json')),\n hasMastraConfig:\n existsSync(join(projectPath, 'mastra.config.js')) || existsSync(join(projectPath, 'mastra.config.ts')),\n hasSrcDirectory: existsSync(join(projectPath, 'src')),\n hasMastraDirectory: existsSync(join(projectPath, 'src/mastra')),\n hasWorkflowsDirectory: existsSync(join(projectPath, 'src/mastra/workflows')),\n hasToolsDirectory: existsSync(join(projectPath, 'src/mastra/tools')),\n hasAgentsDirectory: existsSync(join(projectPath, 'src/mastra/agents')),\n };\n\n // Read package.json if it exists\n let packageInfo = null;\n if (projectStructure.hasPackageJson) {\n try {\n const packageContent = await readFile(join(projectPath, 'package.json'), 'utf-8');\n packageInfo = JSON.parse(packageContent);\n } catch (error) {\n console.warn('Failed to read package.json:', error);\n }\n }\n\n console.info('Project discovery completed');\n return {\n success: true,\n structure: {\n hasWorkflowsDir: projectStructure.hasWorkflowsDirectory,\n hasAgentsDir: projectStructure.hasAgentsDirectory,\n hasToolsDir: projectStructure.hasToolsDirectory,\n hasMastraIndex: existsSync(join(projectPath, 'src/mastra/index.ts')),\n existingWorkflows: [],\n existingAgents: [],\n existingTools: [],\n },\n dependencies: packageInfo?.dependencies || {},\n message: 'Project discovery completed successfully',\n };\n } catch (error) {\n console.error('Project discovery failed:', error);\n return {\n success: false,\n structure: {\n hasWorkflowsDir: false,\n hasAgentsDir: false,\n hasToolsDir: false,\n hasMastraIndex: false,\n existingWorkflows: [],\n existingAgents: [],\n existingTools: [],\n },\n dependencies: {},\n message: 'Project discovery failed',\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\ntype WorkflowResearchResult = z.infer<typeof WorkflowResearchResultSchema>;\n\n// Step 3: Research what is needed to be done\nconst workflowResearchStep = createStep({\n id: 'workflow-research',\n description: 'Research Mastra workflows and gather relevant documentation',\n inputSchema: ProjectDiscoveryResultSchema,\n outputSchema: WorkflowResearchResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Starting workflow research...');\n\n try {\n // const filteredMcpTools = await initializeMcpTools();\n\n const model = await resolveModel({ requestContext });\n\n const researchAgent = new Agent({\n id: 'workflow-research-agent',\n model,\n instructions: workflowBuilderPrompts.researchAgent.instructions,\n name: 'Workflow Research Agent',\n // tools: filteredMcpTools,\n });\n\n const researchPrompt = workflowBuilderPrompts.researchAgent.prompt({\n projectStructure: inputData.structure,\n dependencies: inputData.dependencies,\n hasWorkflowsDir: inputData.structure.hasWorkflowsDir,\n });\n\n const result = await researchAgent.generate(researchPrompt, {\n structuredOutput: {\n schema: WorkflowResearchResultSchema,\n },\n // stopWhen: stepCountIs(10),\n });\n\n const researchResult = (await result.object) as unknown as WorkflowResearchResult | null;\n if (!researchResult) {\n return {\n success: false,\n documentation: {\n workflowPatterns: [],\n stepExamples: [],\n bestPractices: [],\n },\n webResources: [],\n message: 'Research agent failed to generate valid response',\n error: 'Research agent failed to generate valid response',\n };\n }\n\n console.info('Research completed successfully');\n return {\n success: true,\n documentation: {\n workflowPatterns: researchResult.documentation.workflowPatterns,\n stepExamples: researchResult.documentation.stepExamples,\n bestPractices: researchResult.documentation.bestPractices,\n },\n webResources: researchResult.webResources,\n message: 'Research completed successfully',\n };\n } catch (error) {\n console.error('Workflow research failed:', error);\n return {\n success: false,\n documentation: {\n workflowPatterns: [],\n stepExamples: [],\n bestPractices: [],\n },\n webResources: [],\n message: 'Research failed',\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Task execution step remains the same\nconst taskExecutionStep = createStep({\n id: 'task-execution',\n description: 'Execute the approved task list to create or edit the workflow',\n inputSchema: TaskExecutionInputSchema,\n outputSchema: TaskExecutionResultSchema,\n suspendSchema: TaskExecutionSuspendSchema,\n resumeSchema: TaskExecutionResumeSchema,\n execute: async ({ inputData, resumeData, suspend, requestContext }) => {\n const {\n action,\n workflowName,\n description: _description,\n requirements: _requirements,\n tasks,\n discoveredWorkflows,\n projectStructure,\n research,\n projectPath,\n } = inputData;\n\n console.info(`Starting task execution for ${action}ing workflow: ${workflowName}`);\n console.info(`Executing ${tasks.length} tasks using AgentBuilder stream...`);\n\n try {\n const model = await resolveModel({ requestContext });\n const currentProjectPath = projectPath || process.cwd();\n\n // Pre-populate taskManager with the planned tasks\n console.info('Pre-populating taskManager with planned tasks...');\n const taskManagerContext = {\n action: 'create' as const,\n tasks: tasks.map(task => ({\n id: task.id,\n content: task.content,\n status: 'pending' as const,\n priority: task.priority,\n dependencies: task.dependencies,\n notes: task.notes,\n })),\n };\n\n const taskManagerResult = await AgentBuilderDefaults.manageTaskList(taskManagerContext);\n console.info(`Task manager initialized with ${taskManagerResult.tasks.length} tasks`);\n\n if (!taskManagerResult.success) {\n throw new Error(`Failed to initialize task manager: ${taskManagerResult.message}`);\n }\n\n const executionAgent = new AgentBuilder({\n projectPath: currentProjectPath,\n model,\n tools: {\n 'task-manager': restrictedTaskManager,\n },\n instructions: `${workflowBuilderPrompts.executionAgent.instructions({\n action,\n workflowName,\n tasksLength: tasks.length,\n currentProjectPath,\n discoveredWorkflows,\n projectStructure,\n research,\n tasks,\n resumeData,\n })}\n\n${workflowBuilderPrompts.validation.instructions}`,\n });\n\n const executionPrompt = workflowBuilderPrompts.executionAgent.prompt({\n action,\n workflowName,\n tasks,\n resumeData,\n });\n\n const originalInstructions = await executionAgent.getInstructions({ requestContext: requestContext });\n\n const enhancedOptions = {\n stopWhen: stepCountIs(100),\n temperature: 0.3,\n instructions: originalInstructions,\n };\n\n // Loop until all tasks are completed\n let finalResult: any = null;\n let allTasksCompleted = false;\n let iterationCount = 0;\n const maxIterations = 5;\n\n const expectedTaskIds = tasks.map(task => task.id);\n\n while (!allTasksCompleted && iterationCount < maxIterations) {\n iterationCount++;\n\n const currentTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: 'list' });\n const completedTasks = currentTaskStatus.tasks.filter(task => task.status === 'completed');\n const pendingTasks = currentTaskStatus.tasks.filter(task => task.status !== 'completed');\n\n console.info(`\\n=== EXECUTION ITERATION ${iterationCount} ===`);\n console.info(`Completed tasks: ${completedTasks.length}/${expectedTaskIds.length}`);\n console.info(`Remaining tasks: ${pendingTasks.map(t => t.id).join(', ')}`);\n\n // Check if all tasks are completed\n allTasksCompleted = pendingTasks.length === 0;\n\n if (allTasksCompleted) {\n console.info('All tasks completed! Breaking execution loop.');\n break;\n }\n\n // Create prompt for this iteration\n const iterationPrompt =\n iterationCount === 1\n ? executionPrompt\n : `${workflowBuilderPrompts.executionAgent.iterationPrompt({\n completedTasks,\n pendingTasks,\n workflowName,\n resumeData,\n })}\n\n${workflowBuilderPrompts.validation.instructions}`;\n\n const stream = await executionAgent.stream(iterationPrompt, {\n structuredOutput: {\n schema: TaskExecutionIterationInputSchema(tasks.length),\n model,\n },\n ...enhancedOptions,\n });\n\n let finalMessage = '';\n for await (const chunk of stream.fullStream) {\n if (chunk.type === 'text-delta') {\n finalMessage += chunk.payload.text;\n }\n\n if (chunk.type === 'step-finish') {\n console.info(finalMessage);\n finalMessage = '';\n }\n\n if (chunk.type === 'tool-result') {\n console.info(JSON.stringify(chunk, null, 2));\n }\n\n if (chunk.type === 'finish') {\n console.info(chunk);\n }\n }\n\n await stream.consumeStream();\n finalResult = await stream.object;\n\n console.info(`Iteration ${iterationCount} result:`, { finalResult });\n\n if (!finalResult) {\n throw new Error(`No result received from agent execution on iteration ${iterationCount}`);\n }\n\n const postIterationTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: 'list' });\n const postCompletedTasks = postIterationTaskStatus.tasks.filter(task => task.status === 'completed');\n const postPendingTasks = postIterationTaskStatus.tasks.filter(task => task.status !== 'completed');\n\n allTasksCompleted = postPendingTasks.length === 0;\n\n console.info(\n `After iteration ${iterationCount}: ${postCompletedTasks.length}/${expectedTaskIds.length} tasks completed in taskManager`,\n );\n\n // If agent needs clarification, break out and suspend\n if (finalResult.status === 'needs_clarification' && finalResult.questions && finalResult.questions.length > 0) {\n console.info(\n `Agent needs clarification on iteration ${iterationCount}: ${finalResult.questions.length} questions`,\n );\n break;\n }\n\n // If agent claims completed but taskManager shows pending tasks, continue loop\n if (finalResult.status === 'completed' && !allTasksCompleted) {\n console.info(\n `Agent claimed completion but taskManager shows pending tasks: ${postPendingTasks.map(t => t.id).join(', ')}`,\n );\n // Continue to next iteration\n }\n }\n\n if (iterationCount >= maxIterations && !allTasksCompleted) {\n finalResult.error = `Maximum iterations (${maxIterations}) reached but not all tasks completed`;\n finalResult.status = 'in_progress';\n }\n\n if (!finalResult) {\n throw new Error('No result received from agent execution');\n }\n\n // If the agent needs clarification, suspend the workflow\n if (finalResult.status === 'needs_clarification' && finalResult.questions && finalResult.questions.length > 0) {\n console.info(`Agent needs clarification: ${finalResult.questions.length} questions`);\n\n console.info('finalResult', JSON.stringify(finalResult, null, 2));\n return suspend({\n questions: finalResult.questions,\n currentProgress: finalResult.progress,\n completedTasks: finalResult.completedTasks || [],\n message: finalResult.message,\n });\n }\n\n const finalTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: 'list' });\n const finalCompletedTasks = finalTaskStatus.tasks.filter(task => task.status === 'completed');\n const finalPendingTasks = finalTaskStatus.tasks.filter(task => task.status !== 'completed');\n\n const tasksCompleted = finalCompletedTasks.length;\n const tasksExpected = expectedTaskIds.length;\n const finalAllTasksCompleted = finalPendingTasks.length === 0;\n\n const success = finalAllTasksCompleted && !finalResult.error;\n const message = success\n ? `Successfully completed workflow ${action} - all ${tasksExpected} tasks completed after ${iterationCount} iteration(s): ${finalResult.message}`\n : `Workflow execution finished with issues after ${iterationCount} iteration(s): ${finalResult.message}. Completed: ${tasksCompleted}/${tasksExpected} tasks`;\n\n console.info(message);\n\n const missingTasks = finalPendingTasks.map(task => task.id);\n const validationErrors = [];\n\n if (finalResult.error) {\n validationErrors.push(finalResult.error);\n }\n\n if (!finalAllTasksCompleted) {\n validationErrors.push(\n `Incomplete tasks: ${missingTasks.join(', ')} (${tasksCompleted}/${tasksExpected} completed)`,\n );\n }\n\n return {\n success,\n completedTasks: finalCompletedTasks.map(task => task.id),\n filesModified: finalResult.filesModified || [],\n validationResults: {\n passed: success,\n errors: validationErrors,\n warnings: finalAllTasksCompleted ? [] : [`Missing ${missingTasks.length} tasks: ${missingTasks.join(', ')}`],\n },\n message,\n error: finalResult.error,\n };\n } catch (error) {\n console.error('Task execution failed:', error);\n return {\n success: false,\n completedTasks: [],\n filesModified: [],\n validationResults: {\n passed: false,\n errors: [`Task execution failed: ${error instanceof Error ? error.message : String(error)}`],\n warnings: [],\n },\n message: `Task execution failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Main Workflow Builder Workflow\nexport const workflowBuilderWorkflow = createWorkflow({\n id: 'workflow-builder',\n description: 'Create or edit Mastra workflows using AI-powered assistance with iterative planning',\n inputSchema: WorkflowBuilderInputSchema,\n outputSchema: WorkflowBuilderResultSchema,\n steps: [\n workflowDiscoveryStep,\n projectDiscoveryStep,\n workflowResearchStep,\n planningAndApprovalWorkflow,\n taskExecutionStep,\n ],\n})\n // Step 1: Always discover existing workflows\n .then(workflowDiscoveryStep)\n // Step 2: Always discover project structure\n .then(projectDiscoveryStep)\n // Step 3: Research workflows and documentation\n .then(workflowResearchStep)\n // Map research result to planning input format\n .map(async ({ getStepResult, getInitData }) => {\n const initData = getInitData<WorkflowBuilderInputSchemaType>();\n const discoveryResult = getStepResult(workflowDiscoveryStep);\n const projectResult = getStepResult(projectDiscoveryStep);\n // const researchResult = getStepResult(workflowResearchStep);\n\n return {\n action: initData.action,\n workflowName: initData.workflowName,\n description: initData.description,\n requirements: initData.requirements,\n discoveredWorkflows: discoveryResult.workflows,\n projectStructure: projectResult,\n // research: researchResult,\n research,\n\n userAnswers: undefined,\n };\n })\n // Step 4: Planning and Approval Sub-workflow (loops until approved)\n .dountil(planningAndApprovalWorkflow, async ({ inputData }) => {\n // Continue looping until user approves the task list\n console.info(`Sub-workflow check: approved=${inputData.approved}`);\n return inputData.approved === true;\n })\n // Map sub-workflow result to task execution input\n .map(async ({ getStepResult, getInitData }) => {\n const initData = getInitData<WorkflowBuilderInputSchemaType>();\n const discoveryResult = getStepResult(workflowDiscoveryStep);\n const projectResult = getStepResult(projectDiscoveryStep);\n // const researchResult = getStepResult(workflowResearchStep);\n const subWorkflowResult = getStepResult(planningAndApprovalWorkflow);\n\n return {\n action: initData.action,\n workflowName: initData.workflowName,\n description: initData.description,\n requirements: initData.requirements,\n tasks: subWorkflowResult.tasks,\n discoveredWorkflows: discoveryResult.workflows,\n projectStructure: projectResult,\n // research: researchResult,\n research,\n projectPath: initData.projectPath || process.cwd(),\n };\n })\n // Step 5: Execute the approved tasks\n .then(taskExecutionStep)\n .commit();\n","import type { Workflow } from '@mastra/core/workflows';\nimport { agentBuilderTemplateWorkflow } from './template-builder/template-builder';\nimport { workflowBuilderWorkflow } from './workflow-builder/workflow-builder';\n\nexport const agentBuilderWorkflows: Record<string, Workflow<any, any, any, any, any, any>> = {\n 'merge-template': agentBuilderTemplateWorkflow,\n 'workflow-builder': workflowBuilderWorkflow,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAa,aAAa;CAAC;CAAc;CAAQ;CAAY;CAAS;CAAe;CAAW;AAAO;AA0BvG,MAAa,qBAAqB,EAAE,OAAO;CACzC,MAAM,EAAE,KAAK,UAAU;CACvB,IAAI,EAAE,OAAO;CACb,MAAM,EAAE,OAAO;AACjB,CAAC;AAEqC,EAAE,OAAO;CAC7C,MAAM,EAAE,OAAO;CACf,KAAK,EAAE,OAAO,CAAC,CAAC,SAAS;CACzB,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;CACjC,OAAO,EAAE,MAAM,kBAAkB;AACnC,CAAC;AAED,MAAa,0BAA0B,EAAE,OAAO;CAC9C,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,4CAA4C;CACtE,KAAK,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CAC7F,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CAC9F,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,2DAA2D;CACtG,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,2CAA2C;AAC7G,CAAC;AAE8B,EAAE,OAAO;CACtC,MAAM,EAAE,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B;EACrC,kBAAkB;EAElB,UAAA;EAEA,aAAa,KAAA;CACf;AACF,CAAC,CAAC,CAED,QAAQ,6BAA6B,OAAO,EAAE,gBAAgB;CAE7D,QAAQ,KAAK,gCAAgC,UAAU,UAAU;CACjE,OAAO,UAAU,aAAa;AAChC,CAAC,CAAC,CAED,IAAI,OAAO,EAAE,eAAe,kBAAkB;CAC7C,MAAM,WAAW,YAA4C;CAC7D,MAAM,kBAAkB,cAAc,qBAAqB;CAC3D,MAAM,gBAAgB,cAAc,oBAAoB;CAExD,MAAM,oBAAoB,cAAc,2BAA2B;CAEnE,OAAO;EACL,QAAQ,SAAS;EACjB,cAAc,SAAS;EACvB,aAAa,SAAS;EACtB,cAAc,SAAS;EACvB,OAAO,kBAAkB;EACzB,qBAAqB,gBAAgB;EACrC,kBAAkB;EAElB,UAAA;EACA,aAAa,SAAS,eAAe,QAAQ,IAAI;CACnD;AACF,CAAC,CAAC,CAED,KAAK,iBAAiB,CAAC,CACvB,OAAO;;;AC1kBV,MAAa,wBAAgF;CAC3F,kBAAkB;CAClB,oBAAoB;AACtB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["exec","execNodejs","execFile","execFileNodejs","spawn","nodeSpawn","nodeSpawn","execFile","exec","symbol$1","_a$1","name$1","marker2","symbol2","_a2","_b2","name2","marker3","symbol3","_a3","_b3","name3","marker4","symbol4","_a4","_b4","name4","marker5","symbol5","_a5","_b5","name5","marker6","symbol6","_a6","_b6","name6","marker7","symbol7","_a7","_b7","name7","marker8","symbol8","_a8","_b8","name8","marker9","symbol9","_a9","_b9","name9","marker10","symbol10","_a10","name10","marker11","symbol11","_a11","name11","marker12","symbol12","_a12","name12","marker13","symbol13","_a13","name13","marker14","symbol14","_a14","name","marker","symbol","_a","_b","VERSION","resolve","z","resolve","z$1","DownloadError$1"],"sources":["../src/types.ts","../src/utils.ts","../src/defaults.ts","../src/processors/tool-summary.ts","../src/agent/index.ts","../src/workflows/template-builder/template-builder.ts","../../_vendored/ai_v5/dist/dist-BuEMdYEn.js","../../_vendored/ai_v5/dist/index.js","../src/workflows/shared/schema.ts","../src/workflows/task-planning/prompts.ts","../src/workflows/workflow-builder/schema.ts","../src/workflows/task-planning/schema.ts","../src/workflows/task-planning/task-planning.ts","../src/workflows/workflow-builder/prompts.ts","../src/workflows/workflow-builder/tools.ts","../src/workflows/workflow-builder/workflow-builder.ts","../src/workflows/workflow-map.ts"],"sourcesContent":["import type { ToolsInput } from '@mastra/core/agent';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport type { MastraStorage } from '@mastra/core/storage';\nimport type { MastraVector } from '@mastra/core/vector';\nimport { z } from 'zod';\n\n/**\n * Configuration options for the AgentBuilder\n */\nexport interface AgentBuilderConfig {\n /** The language model to use for agent generation */\n model: MastraModelConfig;\n /** Storage provider for memory (optional) */\n storage?: MastraStorage;\n /** Vector provider for memory (optional) */\n vectorProvider?: MastraVector;\n /** Additional tools to include beyond the default set */\n tools?: ToolsInput;\n /** Custom instructions to append to the default system prompt */\n instructions?: string;\n /** Memory configuration options */\n memoryConfig?: {\n maxMessages?: number;\n tokenLimit?: number;\n };\n /** Project path */\n projectPath: string;\n /** Summary model */\n summaryModel?: MastraModelConfig;\n /** Mode */\n mode?: 'template' | 'code-editor';\n}\n\n/**\n * Options for generating agents with AgentBuilder\n */\nexport interface GenerateAgentOptions {\n /** Request Context for the generation */\n requestContext?: any;\n /** Output format preference */\n outputFormat?: 'code' | 'explanation' | 'both';\n}\n\n/**\n * Project management action types\n */\nexport type ProjectAction = 'create' | 'install' | 'upgrade' | 'check';\n\n/**\n * Project types that can be created\n */\nexport type ProjectType = 'standalone' | 'api' | 'nextjs';\n\n/**\n * Package manager options\n */\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn';\n\n/**\n * Validation types for code validation\n */\nexport type ValidationType = 'types' | 'schemas' | 'tests' | 'integration';\n\n// Processing order for units (lower index = higher priority)\nexport const UNIT_KINDS = ['mcp-server', 'tool', 'workflow', 'agent', 'integration', 'network', 'other'] as const;\n\n// Types for the merge template workflow\nexport type UnitKind = (typeof UNIT_KINDS)[number];\n\nexport interface TemplateUnit {\n kind: UnitKind;\n id: string;\n file: string;\n}\n\nexport interface TemplateManifest {\n slug: string;\n ref?: string;\n description?: string;\n units: TemplateUnit[];\n}\n\nexport interface MergePlan {\n slug: string;\n commitSha: string;\n templateDir: string;\n units: TemplateUnit[];\n}\n\n// Schema definitions\nexport const TemplateUnitSchema = z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n file: z.string(),\n});\n\nexport const TemplateManifestSchema = z.object({\n slug: z.string(),\n ref: z.string().optional(),\n description: z.string().optional(),\n units: z.array(TemplateUnitSchema),\n});\n\nexport const AgentBuilderInputSchema = z.object({\n repo: z.string().describe('Git URL or local path of the template repo'),\n ref: z.string().optional().describe('Tag/branch/commit to checkout (defaults to main/master)'),\n slug: z.string().optional().describe('Slug for branch/scripts; defaults to inferred from repo'),\n targetPath: z.string().optional().describe('Project path to merge into; defaults to current directory'),\n variables: z.record(z.string(), z.string()).optional().describe('Environment variables to set in .env file'),\n});\n\nexport const MergePlanSchema = z.object({\n slug: z.string(),\n commitSha: z.string(),\n templateDir: z.string(),\n units: z.array(TemplateUnitSchema),\n});\n\n// File copy schemas and types\nexport const CopiedFileSchema = z.object({\n source: z.string(),\n destination: z.string(),\n unit: z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n }),\n});\n\nexport const ConflictSchema = z.object({\n unit: z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n }),\n issue: z.string(),\n sourceFile: z.string(),\n targetFile: z.string(),\n});\n\nexport const FileCopyInputSchema = z.object({\n orderedUnits: z.array(TemplateUnitSchema),\n templateDir: z.string(),\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n variables: z.record(z.string(), z.string()).optional(),\n});\n\nexport const FileCopyResultSchema = z.object({\n success: z.boolean(),\n copiedFiles: z.array(CopiedFileSchema),\n conflicts: z.array(ConflictSchema),\n message: z.string(),\n error: z.string().optional(),\n});\n\n// Intelligent merge schemas and types\nexport const ConflictResolutionSchema = z.object({\n unit: z.object({\n kind: z.enum(UNIT_KINDS),\n id: z.string(),\n }),\n issue: z.string(),\n resolution: z.string(),\n});\n\nexport const IntelligentMergeInputSchema = z.object({\n conflicts: z.array(ConflictSchema),\n copiedFiles: z.array(CopiedFileSchema),\n templateDir: z.string(),\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n branchName: z.string().optional(),\n});\n\nexport const IntelligentMergeResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n message: z.string(),\n conflictsResolved: z.array(ConflictResolutionSchema),\n error: z.string().optional(),\n});\n\n// Validation schemas and types\nexport const ValidationResultsSchema = z.object({\n valid: z.boolean(),\n errorsFixed: z.number(),\n remainingErrors: z.number(),\n errors: z.array(z.any()).optional(), // Include specific validation errors\n});\n\nexport const ValidationFixInputSchema = z.object({\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n templateDir: z.string(),\n orderedUnits: z.array(TemplateUnitSchema),\n copiedFiles: z.array(CopiedFileSchema),\n conflictsResolved: z.array(ConflictResolutionSchema).optional(),\n maxIterations: z.number().optional().default(5),\n});\n\nexport const ValidationFixResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n message: z.string(),\n validationResults: ValidationResultsSchema,\n error: z.string().optional(),\n});\n\n// Final workflow result schema\nexport const ApplyResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n branchName: z.string().optional(),\n message: z.string(),\n validationResults: ValidationResultsSchema.optional(),\n error: z.string().optional(),\n errors: z.array(z.string()).optional(),\n stepResults: z\n .object({\n cloneSuccess: z.boolean().optional(),\n analyzeSuccess: z.boolean().optional(),\n discoverSuccess: z.boolean().optional(),\n orderSuccess: z.boolean().optional(),\n prepareBranchSuccess: z.boolean().optional(),\n packageMergeSuccess: z.boolean().optional(),\n installSuccess: z.boolean().optional(),\n copySuccess: z.boolean().optional(),\n mergeSuccess: z.boolean().optional(),\n validationSuccess: z.boolean().optional(),\n filesCopied: z.number(),\n conflictsSkipped: z.number(),\n conflictsResolved: z.number(),\n })\n .optional(),\n});\n\nexport const CloneTemplateResultSchema = z.object({\n templateDir: z.string(),\n commitSha: z.string(),\n slug: z.string(),\n success: z.boolean().optional(),\n error: z.string().optional(),\n targetPath: z.string().optional(),\n});\n\n// Package analysis schemas and types\nexport const PackageAnalysisSchema = z.object({\n name: z.string().optional(),\n version: z.string().optional(),\n description: z.string().optional(),\n dependencies: z.record(z.string(), z.string()).optional(),\n devDependencies: z.record(z.string(), z.string()).optional(),\n peerDependencies: z.record(z.string(), z.string()).optional(),\n scripts: z.record(z.string(), z.string()).optional(),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n\n// Discovery step schemas and types\nexport const DiscoveryResultSchema = z.object({\n units: z.array(TemplateUnitSchema),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n\n// Unit ordering schemas and types\nexport const OrderedUnitsSchema = z.object({\n orderedUnits: z.array(TemplateUnitSchema),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n\n// Package merge schemas and types\nexport const PackageMergeInputSchema = z.object({\n commitSha: z.string(),\n slug: z.string(),\n targetPath: z.string().optional(),\n packageInfo: PackageAnalysisSchema,\n});\n\nexport const PackageMergeResultSchema = z.object({\n success: z.boolean(),\n applied: z.boolean(),\n message: z.string(),\n error: z.string().optional(),\n});\n\n// Install schemas and types\nexport const InstallInputSchema = z.object({\n targetPath: z.string().optional().describe('Path to the project to install packages in'),\n});\n\nexport const InstallResultSchema = z.object({\n success: z.boolean(),\n error: z.string().optional(),\n});\n\nexport const PrepareBranchInputSchema = z.object({\n slug: z.string(),\n commitSha: z.string().optional(), // from clone-template if relevant\n targetPath: z.string().optional(),\n});\n\nexport const PrepareBranchResultSchema = z.object({\n branchName: z.string(),\n success: z.boolean().optional(),\n error: z.string().optional(),\n});\n","import { exec as execNodejs, execFile as execFileNodejs, spawn as nodeSpawn } from 'node:child_process';\nimport type { SpawnOptions } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { copyFile, readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, basename, extname, resolve, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { MastraLanguageModel, MastraLegacyLanguageModel } from '@mastra/core/agent';\nimport { ModelRouterLanguageModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { UNIT_KINDS } from './types';\nimport type { UnitKind } from './types';\n\nexport const exec = promisify(execNodejs);\nexport const execFile = promisify(execFileNodejs);\n\n// Helper function to detect if we're in a workspace subfolder\nfunction isInWorkspaceSubfolder(cwd: string): boolean {\n try {\n // First, check if current directory has package.json (it's a package)\n const currentPackageJson = resolve(cwd, 'package.json');\n if (!existsSync(currentPackageJson)) {\n return false; // Not a package, so not a workspace subfolder\n }\n\n // Walk up the directory tree looking for workspace indicators\n let currentDir = cwd;\n let previousDir = '';\n\n // Keep going up until we reach the filesystem root or stop making progress\n while (currentDir !== previousDir && currentDir !== '/') {\n previousDir = currentDir;\n currentDir = dirname(currentDir);\n\n // Skip if we're back at the original directory\n if (currentDir === cwd) {\n continue;\n }\n\n console.info(`Checking for workspace indicators in: ${currentDir}`);\n\n // Check for pnpm workspace\n if (existsSync(resolve(currentDir, 'pnpm-workspace.yaml'))) {\n return true;\n }\n\n // Check for npm/yarn workspaces in package.json\n const parentPackageJson = resolve(currentDir, 'package.json');\n if (existsSync(parentPackageJson)) {\n try {\n const parentPkg = JSON.parse(readFileSync(parentPackageJson, 'utf-8'));\n if (parentPkg.workspaces) {\n return true; // Found workspace config\n }\n } catch {\n // Ignore JSON parse errors\n }\n }\n\n // Check for lerna\n if (existsSync(resolve(currentDir, 'lerna.json'))) {\n return true;\n }\n }\n\n return false;\n } catch (error) {\n console.warn(`Error in workspace detection: ${error}`);\n return false; // Default to false on any error\n }\n}\n\nexport function spawn(command: string, args: string[], options: any) {\n return new Promise((resolve, reject) => {\n const childProcess = nodeSpawn(command, args, {\n stdio: 'inherit', // Enable proper stdio handling\n ...options,\n });\n childProcess.on('error', error => {\n reject(error);\n });\n childProcess.on('close', code => {\n if (code === 0) {\n resolve(void 0);\n } else {\n reject(new Error(`Command failed with exit code ${code}`));\n }\n });\n });\n}\n\n// --- Git environment probes ---\nexport async function isGitInstalled(): Promise<boolean> {\n try {\n await spawnWithOutput('git', ['--version'], {});\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function isInsideGitRepo(cwd: string): Promise<boolean> {\n try {\n if (!(await isGitInstalled())) return false;\n const { stdout } = await spawnWithOutput('git', ['rev-parse', '--is-inside-work-tree'], { cwd });\n return stdout.trim() === 'true';\n } catch {\n return false;\n }\n}\n\n// Variant of spawn that captures stdout and stderr\nexport function spawnWithOutput(\n command: string,\n args: string[],\n options: SpawnOptions,\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolvePromise, rejectPromise) => {\n const childProcess = nodeSpawn(command, args, {\n ...options,\n });\n let stdout = '';\n let stderr = '';\n childProcess.on('error', error => {\n rejectPromise(error);\n });\n childProcess.stdout?.on('data', chunk => {\n process.stdout.write(chunk);\n stdout += chunk?.toString?.() ?? String(chunk);\n });\n childProcess.stderr?.on('data', chunk => {\n stderr += chunk?.toString?.() ?? String(chunk);\n process.stderr.write(chunk);\n });\n childProcess.on('close', code => {\n if (code === 0) {\n resolvePromise({ stdout, stderr, code: code ?? 0 });\n } else {\n const err = new Error(stderr || `Command failed: ${command} ${args.join(' ')}`);\n // @ts-expect-error augment\n err.code = code;\n rejectPromise(err);\n }\n });\n });\n}\n\nexport async function spawnSWPM(cwd: string, command: string, packageNames: string[]) {\n // 1) Try local swpm module resolution/execution\n try {\n console.info('Running install command with swpm');\n const swpmPath = createRequire(import.meta.filename).resolve('swpm');\n await spawn(swpmPath, [command, ...packageNames], { cwd });\n return;\n } catch (e) {\n console.warn('Failed to run install command with swpm', e);\n // ignore and try fallbacks\n }\n\n // 2) Fallback to native package manager based on lock files\n try {\n // Detect package manager from lock files\n let packageManager: string;\n\n if (existsSync(resolve(cwd, 'pnpm-lock.yaml'))) {\n packageManager = 'pnpm';\n } else if (existsSync(resolve(cwd, 'yarn.lock'))) {\n packageManager = 'yarn';\n } else {\n packageManager = 'npm';\n }\n\n // Normalize command\n let nativeCommand = command === 'add' ? 'add' : command === 'install' ? 'install' : command;\n\n // Build args with non-interactive flags for install commands\n const args = [nativeCommand];\n if (nativeCommand === 'install') {\n const inWorkspace = isInWorkspaceSubfolder(cwd);\n if (packageManager === 'pnpm') {\n args.push('--force'); // pnpm install --force\n\n // Check if we're in a workspace subfolder\n if (inWorkspace) {\n args.push('--ignore-workspace');\n }\n } else if (packageManager === 'npm') {\n args.push('--yes'); // npm install --yes\n\n // Check if we're in a workspace subfolder\n if (inWorkspace) {\n args.push('--ignore-workspaces');\n }\n }\n }\n args.push(...packageNames);\n\n console.info(`Falling back to ${packageManager} ${args.join(' ')}`);\n await spawn(packageManager, args, { cwd });\n return;\n } catch (e) {\n console.warn(`Failed to run install command with native package manager: ${e}`);\n }\n\n throw new Error(`Failed to run install command with swpm and native package managers`);\n}\n\n// Utility functions\nexport function kindWeight(kind: UnitKind): number {\n const idx = UNIT_KINDS.indexOf(kind as any);\n return idx === -1 ? UNIT_KINDS.length : idx;\n}\n\n// Utility functions to work with Mastra templates\nexport async function fetchMastraTemplates(): Promise<\n Array<{\n slug: string;\n title: string;\n description: string;\n githubUrl: string;\n tags: string[];\n agents: string[];\n workflows: string[];\n tools: string[];\n }>\n> {\n try {\n const response = await fetch('https://mastra.ai/api/templates.json');\n const data = (await response.json()) as Array<{\n slug: string;\n title: string;\n description: string;\n githubUrl: string;\n tags: string[];\n agents: string[];\n workflows: string[];\n tools: string[];\n }>;\n return data;\n } catch (error) {\n throw new Error(`Failed to fetch Mastra templates: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n// Helper to get a specific template by slug\nexport async function getMastraTemplate(slug: string) {\n const templates = await fetchMastraTemplates();\n const template = templates.find(t => t.slug === slug);\n if (!template) {\n throw new Error(`Template \"${slug}\" not found. Available templates: ${templates.map(t => t.slug).join(', ')}`);\n }\n return template;\n}\n\n// Git commit tracking utility\nexport async function logGitState(targetPath: string, label: string): Promise<void> {\n try {\n // Skip if not a git repo\n if (!(await isInsideGitRepo(targetPath))) return;\n const gitStatusResult = await git(targetPath, 'status', '--porcelain');\n const gitLogResult = await git(targetPath, 'log', '--oneline', '-3');\n const gitCountResult = await git(targetPath, 'rev-list', '--count', 'HEAD');\n\n console.info(`📊 Git state ${label}:`);\n console.info('Status:', gitStatusResult.stdout.trim() || 'Clean working directory');\n console.info('Recent commits:', gitLogResult.stdout.trim());\n console.info('Total commits:', gitCountResult.stdout.trim());\n } catch (gitError) {\n console.warn(`Could not get git state ${label}:`, gitError);\n }\n}\n\n// Generic git runner that captures stdout/stderr\nexport async function git(cwd: string, ...args: string[]): Promise<{ stdout: string; stderr: string }> {\n const { stdout, stderr } = await spawnWithOutput('git', args, { cwd });\n return { stdout: stdout ?? '', stderr: stderr ?? '' };\n}\n\n// Common git helpers\nexport async function gitClone(repo: string, destDir: string, cwd?: string) {\n await git(cwd ?? process.cwd(), 'clone', repo, destDir);\n}\n\nexport async function gitCheckoutRef(cwd: string, ref: string) {\n if (!(await isInsideGitRepo(cwd))) return;\n await git(cwd, 'checkout', ref);\n}\n\nexport async function gitRevParse(cwd: string, rev: string): Promise<string> {\n if (!(await isInsideGitRepo(cwd))) return '';\n const { stdout } = await git(cwd, 'rev-parse', rev);\n return stdout.trim();\n}\n\nexport async function gitAddFiles(cwd: string, files: string[]) {\n if (!files || files.length === 0) return;\n if (!(await isInsideGitRepo(cwd))) return;\n await git(cwd, 'add', ...files);\n}\n\nexport async function gitAddAll(cwd: string) {\n if (!(await isInsideGitRepo(cwd))) return;\n await git(cwd, 'add', '.');\n}\n\nexport async function gitHasStagedChanges(cwd: string): Promise<boolean> {\n if (!(await isInsideGitRepo(cwd))) return false;\n const { stdout } = await git(cwd, 'diff', '--cached', '--name-only');\n return stdout.trim().length > 0;\n}\n\nexport async function gitCommit(\n cwd: string,\n message: string,\n opts?: { allowEmpty?: boolean; skipIfNoStaged?: boolean },\n): Promise<boolean> {\n try {\n if (!(await isInsideGitRepo(cwd))) return false;\n if (opts?.skipIfNoStaged) {\n const has = await gitHasStagedChanges(cwd);\n if (!has) return false;\n }\n const args = ['commit', '-m', message];\n if (opts?.allowEmpty) args.push('--allow-empty');\n await git(cwd, ...args);\n return true;\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (/nothing to commit/i.test(msg) || /no changes added to commit/i.test(msg)) {\n return false;\n }\n throw e;\n }\n}\n\nexport async function gitAddAndCommit(\n cwd: string,\n message: string,\n files?: string[],\n opts?: { allowEmpty?: boolean; skipIfNoStaged?: boolean },\n): Promise<boolean> {\n try {\n if (!(await isInsideGitRepo(cwd))) return false;\n if (files && files.length > 0) {\n await gitAddFiles(cwd, files);\n } else {\n await gitAddAll(cwd);\n }\n return gitCommit(cwd, message, opts);\n } catch (e) {\n console.error(`Failed to add and commit files: ${e instanceof Error ? e.message : String(e)}`);\n return false;\n }\n}\n\nexport async function gitCheckoutBranch(branchName: string, targetPath: string) {\n try {\n if (!(await isInsideGitRepo(targetPath))) return;\n // Try to create new branch using centralized git runner\n await git(targetPath, 'checkout', '-b', branchName);\n console.info(`Created new branch: ${branchName}`);\n } catch (error) {\n // If branch exists, check if we can switch to it or create a unique name\n const errorStr = error instanceof Error ? error.message : String(error);\n if (errorStr.includes('already exists')) {\n try {\n // Try to switch to existing branch\n await git(targetPath, 'checkout', branchName);\n console.info(`Switched to existing branch: ${branchName}`);\n } catch {\n // If can't switch, create a unique branch name\n const timestamp = Date.now().toString().slice(-6);\n const uniqueBranchName = `${branchName}-${timestamp}`;\n await git(targetPath, 'checkout', '-b', uniqueBranchName);\n console.info(`Created unique branch: ${uniqueBranchName}`);\n }\n } else {\n throw error; // Re-throw if it's a different error\n }\n }\n}\n\n// File conflict resolution utilities (for future use)\nexport async function backupAndReplaceFile(sourceFile: string, targetFile: string): Promise<void> {\n // Create backup of existing file\n const backupFile = `${targetFile}.backup-${Date.now()}`;\n await copyFile(targetFile, backupFile);\n console.info(`📦 Created backup: ${basename(backupFile)}`);\n\n // Replace with template file\n await copyFile(sourceFile, targetFile);\n console.info(`🔄 Replaced file with template version (backup created)`);\n}\n\nexport async function renameAndCopyFile(sourceFile: string, targetFile: string): Promise<string> {\n // Find unique filename\n let counter = 1;\n let uniqueTargetFile = targetFile;\n const baseName = basename(targetFile, extname(targetFile));\n const extension = extname(targetFile);\n const directory = dirname(targetFile);\n\n while (existsSync(uniqueTargetFile)) {\n const uniqueName = `${baseName}.template-${counter}${extension}`;\n uniqueTargetFile = resolve(directory, uniqueName);\n counter++;\n }\n\n await copyFile(sourceFile, uniqueTargetFile);\n console.info(`📝 Copied with unique name: ${basename(uniqueTargetFile)}`);\n return uniqueTargetFile;\n}\n\n// Type guard to check if object is a valid language model (V1, V2, or V3)\nexport const isValidMastraLanguageModel = (model: any): model is MastraLanguageModel | MastraLegacyLanguageModel => {\n return model && typeof model === 'object' && typeof model.modelId === 'string';\n};\n\n// Helper function to resolve target path with smart defaults\nexport const resolveTargetPath = (inputData: any, requestContext: any): string => {\n // If explicitly provided, use it\n if (inputData.targetPath) {\n return inputData.targetPath;\n }\n\n // Check request context\n const contextPath = requestContext.get('targetPath');\n if (contextPath) {\n return contextPath;\n }\n\n // Smart resolution logic from prepareAgentBuilderWorkflowInstallation\n const envRoot = process.env.MASTRA_PROJECT_ROOT?.trim();\n if (envRoot) {\n return envRoot;\n }\n\n const cwd = process.cwd();\n const parent = dirname(cwd);\n const grand = dirname(parent);\n\n // Detect when running under `<project>/.mastra/output` and resolve back to project root\n if (basename(cwd) === 'output' && basename(parent) === '.mastra') {\n return grand;\n }\n\n return cwd;\n};\n\n// Helper function to merge .gitignore files intelligently\nexport const mergeGitignoreFiles = (targetContent: string, templateContent: string, templateSlug: string): string => {\n // Normalize line endings and split into lines\n const targetLines = targetContent.replace(/\\r\\n/g, '\\n').split('\\n');\n const templateLines = templateContent.replace(/\\r\\n/g, '\\n').split('\\n');\n\n // Parse existing target entries (normalize for comparison)\n const existingEntries = new Set<string>();\n\n for (const line of targetLines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n // Normalize path for comparison (remove leading ./, handle different separators)\n const normalized = trimmed.replace(/^\\.\\//, '').replace(/\\\\/g, '/');\n existingEntries.add(normalized);\n }\n }\n\n // Extract new entries from template that don't already exist\n const newEntries: string[] = [];\n for (const line of templateLines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n const normalized = trimmed.replace(/^\\.\\//, '').replace(/\\\\/g, '/');\n if (!existingEntries.has(normalized)) {\n // Check for conflicts (e.g., !file vs file)\n const isNegation = normalized.startsWith('!');\n const basePath = isNegation ? normalized.slice(1) : normalized;\n const hasConflict = isNegation ? existingEntries.has(basePath) : existingEntries.has('!' + basePath);\n\n if (!hasConflict) {\n newEntries.push(trimmed);\n } else {\n console.info(`⚠ Skipping conflicting .gitignore rule: ${trimmed} (conflicts with existing rule)`);\n }\n }\n }\n }\n\n // If no new entries, return original content\n if (newEntries.length === 0) {\n return targetContent;\n }\n\n // Build merged content\n const result: string[] = [...targetLines];\n\n // Add a blank line if the file doesn't end with one\n const lastLine = result[result.length - 1];\n if (result.length > 0 && lastLine && lastLine.trim() !== '') {\n result.push('');\n }\n\n // Add template section header\n result.push(`# Added by template: ${templateSlug}`);\n result.push(...newEntries);\n\n return result.join('\\n');\n};\n\n// Helper function to merge .env files intelligently\nexport const mergeEnvFiles = (\n targetContent: string,\n templateVariables: Record<string, string>,\n templateSlug: string,\n): string => {\n // Parse existing target .env file\n const targetLines = targetContent.replace(/\\r\\n/g, '\\n').split('\\n');\n const existingVars = new Set<string>();\n\n // Extract existing variable names (handle comments and empty lines)\n for (const line of targetLines) {\n const trimmed = line.trim();\n if (trimmed && !trimmed.startsWith('#')) {\n const equalIndex = trimmed.indexOf('=');\n if (equalIndex > 0) {\n const varName = trimmed.substring(0, equalIndex).trim();\n existingVars.add(varName);\n }\n }\n }\n\n // Filter out variables that already exist\n const newVars: Array<{ key: string; value: string }> = [];\n for (const [key, value] of Object.entries(templateVariables)) {\n if (!existingVars.has(key)) {\n newVars.push({ key, value });\n } else {\n console.info(`⚠ Skipping existing environment variable: ${key} (already exists in .env)`);\n }\n }\n\n // If no new variables, return original content\n if (newVars.length === 0) {\n return targetContent;\n }\n\n // Build merged content\n const result: string[] = [...targetLines];\n\n // Add a blank line if the file doesn't end with one\n const lastLine = result[result.length - 1];\n if (result.length > 0 && lastLine && lastLine.trim() !== '') {\n result.push('');\n }\n\n // Add template section header\n result.push(`# Added by template: ${templateSlug}`);\n\n // Add new environment variables\n for (const { key, value } of newVars) {\n result.push(`${key}=${value}`);\n }\n\n return result.join('\\n');\n};\n\n// Helper function to detect AI SDK version from package.json\nexport const detectAISDKVersion = async (projectPath: string): Promise<'v1' | 'v2'> => {\n try {\n const packageJsonPath = join(projectPath, 'package.json');\n\n if (!existsSync(packageJsonPath)) {\n console.info('No package.json found, defaulting to v2');\n return 'v2';\n }\n\n const packageContent = await readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageContent);\n\n const allDeps = {\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n ...packageJson.peerDependencies,\n };\n\n // Check individual provider packages for version hints\n const providerPackages = ['@ai-sdk/openai', '@ai-sdk/anthropic', '@ai-sdk/google', '@ai-sdk/groq', '@ai-sdk/xai'];\n for (const pkg of providerPackages) {\n const version = allDeps[pkg];\n if (version) {\n const versionMatch = version.match(/(\\d+)/);\n if (versionMatch) {\n const majorVersion = parseInt(versionMatch[1]);\n if (majorVersion >= 2) {\n console.info(`Detected ${pkg} v${majorVersion} -> using v2 specification`);\n return 'v2';\n } else {\n console.info(`Detected ${pkg} v${majorVersion} -> using v1 specification`);\n return 'v1';\n }\n }\n }\n }\n\n console.info('No AI SDK version detected, defaulting to v2');\n return 'v2';\n } catch (error) {\n console.warn(`Failed to detect AI SDK version: ${error instanceof Error ? error.message : String(error)}`);\n return 'v2';\n }\n};\n\n// Helper function to create model instance based on provider and version\nexport const createModelInstance = async (\n provider: string,\n modelId: string,\n version: 'v1' | 'v2' = 'v2',\n): Promise<MastraLanguageModel | MastraLegacyLanguageModel | ModelRouterLanguageModel | null> => {\n try {\n // Dynamic imports to avoid issues if packages aren't available\n const providerMap = {\n v1: {\n openai: async () => {\n const { openai } = await import('@ai-sdk/openai');\n return openai(modelId);\n },\n anthropic: async () => {\n const { anthropic } = await import('@ai-sdk/anthropic');\n return anthropic(modelId);\n },\n groq: async () => {\n const { groq } = await import('@ai-sdk/groq');\n return groq(modelId);\n },\n xai: async () => {\n const { xai } = await import('@ai-sdk/xai');\n return xai(modelId);\n },\n google: async () => {\n const { google } = await import('@ai-sdk/google');\n return google(modelId);\n },\n },\n };\n\n const providerFn =\n version === `v1`\n ? providerMap[version][provider as keyof (typeof providerMap)[typeof version]]\n : () => new ModelRouterLanguageModel(`${provider}/${modelId}`);\n\n if (!providerFn) {\n console.error(`Unsupported provider: ${provider}`);\n return null;\n }\n\n const modelInstance = await providerFn();\n console.info(`Created ${provider} model instance (${version}): ${modelId}`);\n return modelInstance;\n } catch (error) {\n console.error(`Failed to create model instance: ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n};\n\n// Helper function to resolve model from request context with AI SDK version detection\nexport const resolveModel = async ({\n requestContext,\n defaultModel = 'openai/gpt-4.1',\n projectPath,\n}: {\n requestContext: RequestContext;\n defaultModel?: MastraLanguageModel | MastraLegacyLanguageModel | string;\n projectPath?: string;\n}): Promise<MastraLanguageModel | MastraLegacyLanguageModel> => {\n // First try to get model from request context\n const modelFromContext = requestContext.get('model');\n if (modelFromContext) {\n console.info('Using model from request context');\n // Type check to ensure it's a MastraLanguageModel\n if (isValidMastraLanguageModel(modelFromContext)) {\n return modelFromContext;\n }\n throw new Error(\n 'Invalid model provided. Model must be a MastraLanguageModel instance (e.g., openai(\"gpt-4\"), anthropic(\"claude-3-5-sonnet\"), etc.)',\n );\n }\n\n // Check for selected model info in request context\n const selectedModel = requestContext.get('selectedModel') as { provider: string; modelId: string } | undefined;\n if (selectedModel?.provider && selectedModel?.modelId && projectPath) {\n console.info(`Resolving selected model: ${selectedModel.provider}/${selectedModel.modelId}`);\n\n // Detect AI SDK version from project\n const version = await detectAISDKVersion(projectPath);\n\n // Create model instance with detected version\n const modelInstance = await createModelInstance(selectedModel.provider, selectedModel.modelId, version);\n if (modelInstance) {\n // Store resolved model back in context for other steps to use\n requestContext.set('model', modelInstance);\n return modelInstance;\n }\n }\n\n console.info('Using default model');\n return typeof defaultModel === `string` ? new ModelRouterLanguageModel(defaultModel) : defaultModel;\n};\n","import { spawn as nodeSpawn } from 'node:child_process';\nimport { readFile, writeFile, mkdir, stat, readdir } from 'node:fs/promises';\nimport { join, dirname, relative, isAbsolute, resolve } from 'node:path';\nimport { createTool } from '@mastra/core/tools';\nimport ignore from 'ignore';\nimport { z } from 'zod';\nimport { exec, execFile, spawnSWPM, spawnWithOutput } from './utils';\n\ntype TaskManagerInputType = {\n action: 'create' | 'update' | 'list' | 'complete' | 'remove';\n tasks?: Array<{\n id: string;\n content?: string;\n status: 'pending' | 'in_progress' | 'completed' | 'blocked';\n priority: 'high' | 'medium' | 'low';\n dependencies?: string[];\n notes?: string;\n }>;\n taskId?: string;\n};\n\nexport class AgentBuilderDefaults {\n static DEFAULT_INSTRUCTIONS = (\n projectPath?: string,\n ) => `You are a Mastra Expert Agent, specialized in building production-ready AI applications using the Mastra framework. You excel at creating agents, tools, workflows, and complete applications with real, working implementations.\n\n## Core Identity & Capabilities\n\n**Primary Role:** Transform natural language requirements into working Mastra applications\n**Key Strength:** Deep knowledge of Mastra patterns, conventions, and best practices\n**Output Quality:** Production-ready code that follows Mastra ecosystem standards\n\n## Workflow: The MASTRA Method\n\nFollow this sequence for every coding task:\n\nIF NO PROJECT EXISTS, USE THE MANAGEPROJECT TOOL TO CREATE A NEW PROJECT\n\nDO NOT INCLUDE TODOS IN THE CODE, UNLESS SPECIFICALLY ASKED TO DO SO, CREATE REAL WORLD CODE\n\n### 1. 🔍 **UNDERSTAND** (Information Gathering)\n- **Explore Mastra Docs**: Use docs tools to understand relevant Mastra patterns and APIs\n- **Analyze Project**: Use file exploration to understand existing codebase structure\n- **Web Research**: Search for packages, examples, or solutions when docs are insufficient\n- **Clarify Requirements**: Ask targeted questions only when critical information is missing\n\n### 2. 📋 **PLAN** (Strategy & Design)\n- **Architecture**: Design using Mastra conventions (agents, tools, workflows, memory)\n- **Dependencies**: Identify required packages and Mastra components\n- **Integration**: Plan how to integrate with existing project structure\n- **Validation**: Define how to test and verify the implementation\n\n### 3. 🛠️ **BUILD** (Implementation)\n- **Install First**: Use \\`manageProject\\` tool to install required packages\n- **Follow Patterns**: Implement using established Mastra conventions\n- **Real Code Only**: Build actual working functionality, never mock implementations\n- **Environment Setup**: Create proper .env configuration and documentation\n\n### 4. ✅ **VALIDATE** (Quality Assurance)\n- **Code Validation**: Run \\`validateCode\\` with types and lint checks\n- **Testing**: Execute tests if available\n- **Server Testing**: Use \\`manageServer\\` and \\`httpRequest\\` for API validation\n- **Fix Issues**: Address all errors before completion\n\n## Mastra-Specific Guidelines\n\n### Framework Knowledge\n- **Agents**: Use \\`@mastra/core/agent\\` with proper configuration\n- **Tools**: Create tools with \\`@mastra/core/tools\\` and proper schemas\n- **Memory**: Implement memory with \\`@mastra/memory\\` and appropriate processors\n- **Workflows**: Build workflows with \\`@mastra/core/workflows\\`\n- **Integrations**: Leverage Mastra's extensive integration ecosystem\n\n### Code Standards\n- **TypeScript First**: All code must be properly typed\n- **Zod Schemas**: Use Zod for all data validation\n- **Environment Variables**: Proper .env configuration with examples\n- **Error Handling**: Comprehensive error handling with meaningful messages\n- **Security**: Never expose credentials or sensitive data\n\n### Project Structure\n- Follow Mastra project conventions (\\`src/mastra/\\`, config files)\n- Use proper file organization (agents, tools, workflows in separate directories)\n- Maintain consistent naming conventions\n- Include proper exports and imports\n\n## Communication Style\n\n**Conciseness**: Keep responses focused and actionable\n**Clarity**: Explain complex concepts in simple terms\n**Directness**: State what you're doing and why\n**No Fluff**: Avoid unnecessary explanations or apologies\n\n### Response Format\n1. **Brief Status**: One line stating what you're doing\n2. **Tool Usage**: Execute necessary tools\n3. **Results Summary**: Concise summary of what was accomplished\n4. **Next Steps**: Clear indication of completion or next actions\n\n## Tool Usage Strategy\n\n### File Operations\n- **Project-Relative Paths**: All file paths are resolved relative to the project directory (unless absolute paths are used)\n- **Read First**: Always read files before editing to understand context\n- **Precise Edits**: Use exact text matching for search/replace operations\n- **Batch Operations**: Group related file operations when possible\n\n### Project Management\n- **manageProject**: Use for package installation, project creation, dependency management\n- **validateCode**: Always run after code changes to ensure quality\n- **manageServer**: Use for testing Mastra server functionality\n- **httpRequest**: Test API endpoints and integrations\n\n### Information Gathering\n- **Mastra Docs**: Primary source for Mastra-specific information\n- **Web Search**: Secondary source for packages and external solutions\n- **File Exploration**: Understand existing project structure and patterns\n\n## Error Handling & Recovery\n\n### Validation Failures\n- Fix TypeScript errors immediately\n- Address linting issues systematically\n- Re-validate until clean\n\n### Build Issues\n- Check dependencies and versions\n- Verify Mastra configuration\n- Test in isolation when needed\n\n### Integration Problems\n- Verify API keys and environment setup\n- Test connections independently\n- Debug with logging and error messages\n\n## Security & Best Practices\n\n**Never:**\n- Hard-code API keys or secrets\n- Generate mock or placeholder implementations\n- Skip error handling\n- Ignore TypeScript errors\n- Create insecure code patterns\n- ask for file paths, you should be able to use the provided tools to explore the file system\n\n**Always:**\n- Use environment variables for configuration\n- Implement proper input validation\n- Follow security best practices\n- Create complete, working implementations\n- Test thoroughly before completion\n\n## Output Requirements\n\n### Code Quality\n- ✅ TypeScript compilation passes\n- ✅ ESLint validation passes\n- ✅ Proper error handling implemented\n- ✅ Environment variables configured\n- ✅ Tests included when appropriate\n\n### Documentation\n- ✅ Clear setup instructions\n- ✅ Environment variable documentation\n- ✅ Usage examples provided\n- ✅ API documentation for custom tools\n\n### Integration\n- ✅ Follows Mastra conventions\n- ✅ Integrates with existing project\n- ✅ Proper imports and exports\n- ✅ Compatible with Mastra ecosystem\n\n## Project Context\n\n**Working Directory**: ${projectPath}\n**Focus**: Mastra framework applications\n**Goal**: Production-ready implementations\n\nRemember: You are building real applications, not prototypes. Every implementation should be complete, secure, and ready for production use.\n\n## Enhanced Tool Set\n\nYou have access to an enhanced set of tools based on production coding agent patterns:\n\n### Task Management\n- **taskManager**: Create and track multi-step coding tasks with states (pending, in_progress, completed, blocked). Use this for complex projects that require systematic progress tracking.\n\n### Code Discovery & Analysis\n- **codeAnalyzer**: Analyze codebase structure, discover definitions (functions, classes, interfaces), map dependencies, and understand architectural patterns.\n- **smartSearch**: Intelligent search with context awareness, pattern matching, and relevance scoring.\n\n### Advanced File Operations\n- **readFile**: Read files with optional line ranges, encoding support, metadata\n- **writeFile**: Write files with directory creation\n- **listDirectory**: Directory listing with filtering, recursion, metadata\n- **multiEdit**: Perform multiple search-replace operations across files atomically with backup creation\n- **executeCommand**: Execute shell commands with proper error handling and working directory support\n\n**Important**: All file paths are resolved relative to the project directory unless absolute paths are provided.\n\n### Communication & Workflow\n- **attemptCompletion**: Signal task completion with validation status and confidence metrics.\n\n### Guidelines for Enhanced Tools:\n\n1. **Use taskManager proactively** for any task requiring 3+ steps or complex coordination\n2. **Start with codeAnalyzer** when working with unfamiliar codebases to understand structure\n3. **Use smartSearch** for intelligent pattern discovery across the codebase\n4. **Apply multiEdit** for systematic refactoring across multiple files\n5. **Ask for clarification** when requirements are ambiguous rather than making assumptions\n6. **Signal completion** with comprehensive summaries and validation status\n\nUse the following basic examples to guide your implementation.\n\n<examples>\n### Weather Agent\n\\`\\`\\`\n// ./src/agents/weather-agent.ts\nimport { openai } from '@ai-sdk/openai';\nimport { Agent } from '@mastra/core/agent';\nimport { Memory } from '@mastra/memory';\nimport { LibSQLStore } from '@mastra/libsql';\nimport { weatherTool } from '../tools/weather-tool';\n\nexport const weatherAgent = new Agent({\n id: 'weather-agent',\n name: 'Weather Agent',\n instructions: \\${instructions},\n model: openai('gpt-4o-mini'),\n tools: { weatherTool },\n memory: new Memory({\n storage: new LibSQLStore({\n id: 'mastra-memory-storage',\n url: 'file:../mastra.db', // ask user what database to use, use this as the default\n }),\n }),\n});\n\\`\\`\\`\n\n### Weather Tool\n\\`\\`\\`\n// ./src/tools/weather-tool.ts\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\nimport { getWeather } from '../tools/weather-tool';\n\nexport const weatherTool = createTool({\n id: 'get-weather',\n description: 'Get current weather for a location',\n inputSchema: z.object({\n location: z.string().describe('City name'),\n }),\n outputSchema: z.object({\n temperature: z.number(),\n feelsLike: z.number(),\n humidity: z.number(),\n windSpeed: z.number(),\n windGust: z.number(),\n conditions: z.string(),\n location: z.string(),\n }),\n execute: async (inputData) => {\n return await getWeather(inputData.location);\n },\n});\n\\`\\`\\`\n\n### Weather Workflow\n\\`\\`\\`\n// ./src/workflows/weather-workflow.ts\nimport { createStep, createWorkflow } from '@mastra/core/workflows';\nimport { z } from 'zod';\n\nconst fetchWeather = createStep({\n id: 'fetch-weather',\n description: 'Fetches weather forecast for a given city',\n inputSchema: z.object({\n city: z.string().describe('The city to get the weather for'),\n }),\n outputSchema: forecastSchema,\n execute: async (inputData) => {\n if (!inputData) {\n throw new Error('Input data not found');\n }\n\n const geocodingUrl = \\`https://geocoding-api.open-meteo.com/v1/search?name=\\${encodeURIComponent(inputData.city)}&count=1\\`;\n const geocodingResponse = await fetch(geocodingUrl);\n const geocodingData = (await geocodingResponse.json()) as {\n results: { latitude: number; longitude: number; name: string }[];\n };\n\n if (!geocodingData.results?.[0]) {\n throw new Error(\\`Location '\\${inputData.city}' not found\\`);\n }\n\n const { latitude, longitude, name } = geocodingData.results[0];\n\n const weatherUrl = \\`https://api.open-meteo.com/v1/forecast?latitude=\\${latitude}&longitude=\\${longitude}¤t=precipitation,weathercode&timezone=auto,&hourly=precipitation_probability,temperature_2m\\`\n const response = await fetch(weatherUrl);\n const data = (await response.json()) as {\n current: {\n time: string;\n precipitation: number;\n weathercode: number;\n };\n hourly: {\n precipitation_probability: number[];\n temperature_2m: number[];\n };\n };\n\n const forecast = {\n date: new Date().toISOString(),\n maxTemp: Math.max(...data.hourly.temperature_2m),\n minTemp: Math.min(...data.hourly.temperature_2m),\n condition: getWeatherCondition(data.current.weathercode),\n precipitationChance: data.hourly.precipitation_probability.reduce(\n (acc, curr) => Math.max(acc, curr),\n 0,\n ),\n location: name,\n };\n\n return forecast;\n },\n});\n\nconst planActivities = createStep({\n id: 'plan-activities',\n description: 'Suggests activities based on weather conditions',\n inputSchema: forecastSchema,\n outputSchema: z.object({\n activities: z.string(),\n }),\n execute: async (inputData, context) => {\n const mastra = context?.mastra;\n const forecast = inputData;\n\n if (!forecast) {\n throw new Error('Forecast data not found');\n }\n\n const agent = mastra?.getAgent('weatherAgent');\n if (!agent) {\n throw new Error('Weather agent not found');\n }\n\n const prompt = \\${weatherWorkflowPrompt}\n\n const response = await agent.stream([\n {\n role: 'user',\n content: prompt,\n },\n ]);\n\n let activitiesText = '';\n\n for await (const chunk of response.textStream) {\n process.stdout.write(chunk);\n activitiesText += chunk;\n }\n\n return {\n activities: activitiesText,\n };\n },\n});\n\nconst weatherWorkflow = createWorkflow({\n id: 'weather-workflow',\n inputSchema: z.object({\n city: z.string().describe('The city to get the weather for'),\n }),\n outputSchema: z.object({\n activities: z.string(),\n }),\n})\n .then(fetchWeather)\n .then(planActivities);\n\nweatherWorkflow.commit();\n\\`\\`\\`\nexport { weatherWorkflow };\n\\`\\`\\`\n\n### Mastra instance\n\\`\\`\\`\n// ./src/mastra.ts\n\nimport { Mastra } from '@mastra/core/mastra';\nimport { PinoLogger } from '@mastra/loggers';\nimport { LibSQLStore } from '@mastra/libsql';\nimport { weatherWorkflow } from './workflows/weather-workflow';\nimport { weatherAgent } from './agents/weather-agent';\n\nexport const mastra = new Mastra({\n workflows: { weatherWorkflow },\n agents: { weatherAgent },\n storage: new LibSQLStore({\n id: 'mastra-storage',\n // stores observability, evals, ... into memory storage, if it needs to persist, change to file:../mastra.db\n url: \":memory:\",\n }),\n logger: new PinoLogger({\n name: 'Mastra',\n level: 'info',\n }),\n});\n\\`\\`\\`\n\n</examples>`;\n\n static DEFAULT_MEMORY_CONFIG = {\n lastMessages: 20,\n };\n\n static DEFAULT_FOLDER_STRUCTURE = {\n agent: 'src/mastra/agents',\n workflow: 'src/mastra/workflows',\n tool: 'src/mastra/tools',\n 'mcp-server': 'src/mastra/mcp',\n network: 'src/mastra/networks',\n };\n\n static DEFAULT_TOOLS = async (projectPath: string) => {\n return {\n readFile: createTool({\n id: 'read-file',\n description: 'Read contents of a file with optional line range selection.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to read'),\n startLine: z.number().optional().describe('Starting line number (1-indexed)'),\n endLine: z.number().optional().describe('Ending line number (1-indexed, inclusive)'),\n encoding: z.string().default('utf-8').describe('File encoding'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n content: z.string().optional(),\n lines: z.array(z.string()).optional(),\n metadata: z\n .object({\n size: z.number(),\n totalLines: z.number(),\n encoding: z.string(),\n lastModified: z.string(),\n })\n .optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.readFile({ ...inputData, projectPath });\n },\n }),\n\n writeFile: createTool({\n id: 'write-file',\n description: 'Write content to a file, with options for creating directories.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to write'),\n content: z.string().describe('Content to write to the file'),\n createDirs: z.boolean().default(true).describe(\"Create parent directories if they don't exist\"),\n encoding: z.string().default('utf-8').describe('File encoding'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n filePath: z.string(),\n bytesWritten: z.number().optional(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.writeFile({ ...inputData, projectPath });\n },\n }),\n\n listDirectory: createTool({\n id: 'list-directory',\n description: 'List contents of a directory with filtering and metadata options.',\n inputSchema: z.object({\n path: z.string().describe('Directory path to list'),\n recursive: z.boolean().default(false).describe('List subdirectories recursively'),\n includeHidden: z.boolean().default(false).describe('Include hidden files and directories'),\n pattern: z.string().default('*').describe('Glob pattern to filter files'),\n maxDepth: z.number().default(10).describe('Maximum recursion depth'),\n includeMetadata: z.boolean().default(true).describe('Include file metadata'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n items: z.array(\n z.object({\n name: z.string(),\n path: z.string(),\n type: z.enum(['file', 'directory', 'symlink']),\n size: z.number().optional(),\n lastModified: z.string().optional(),\n permissions: z.string().optional(),\n }),\n ),\n totalItems: z.number(),\n path: z.string(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.listDirectory({ ...inputData, projectPath });\n },\n }),\n\n executeCommand: createTool({\n id: 'execute-command',\n description: 'Execute shell commands with proper error handling and output capture.',\n inputSchema: z.object({\n command: z.string().describe('Shell command to execute'),\n workingDirectory: z.string().optional().describe('Working directory for command execution'),\n timeout: z.number().default(30000).describe('Timeout in milliseconds'),\n captureOutput: z.boolean().default(true).describe('Capture command output'),\n shell: z.string().optional().describe('Shell to use (defaults to system shell)'),\n env: z.record(z.string(), z.string()).optional().describe('Environment variables'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n exitCode: z.number().optional(),\n stdout: z.string().optional(),\n stderr: z.string().optional(),\n command: z.string(),\n workingDirectory: z.string().optional(),\n executionTime: z.number().optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.executeCommand({\n ...inputData,\n workingDirectory: inputData.workingDirectory || projectPath,\n env: inputData.env as Record<string, string> | undefined,\n });\n },\n }),\n // Enhanced Task Management (Critical for complex coding tasks)\n taskManager: createTool({\n id: 'task-manager',\n description:\n 'Create and manage structured task lists for coding sessions. Use this for complex multi-step tasks to track progress and ensure thoroughness.',\n inputSchema: z.object({\n action: z.enum(['create', 'update', 'list', 'complete', 'remove']).describe('Task management action'),\n tasks: z\n .array(\n z.object({\n id: z.string().describe('Unique task identifier'),\n content: z.string().describe('Task description, optional if just updating the status').optional(),\n status: z.enum(['pending', 'in_progress', 'completed', 'blocked']).describe('Task status'),\n priority: z.enum(['high', 'medium', 'low']).default('medium').describe('Task priority'),\n dependencies: z.array(z.string()).optional().describe('IDs of tasks this depends on'),\n notes: z.string().optional().describe('Additional notes or context'),\n }),\n )\n .optional()\n .describe('Tasks to create or update'),\n taskId: z.string().optional().describe('Specific task ID for single task operations'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n tasks: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n status: z.string(),\n priority: z.string(),\n dependencies: z.array(z.string()).optional(),\n notes: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n }),\n ),\n message: z.string(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.manageTaskList(inputData as TaskManagerInputType);\n },\n }),\n\n // Advanced File Operations\n multiEdit: createTool({\n id: 'multi-edit',\n description: 'Perform multiple search-replace operations on one or more files in a single atomic operation.',\n inputSchema: z.object({\n operations: z\n .array(\n z.object({\n filePath: z.string().describe('Path to the file to edit'),\n edits: z\n .array(\n z.object({\n oldString: z.string().describe('Exact text to replace'),\n newString: z.string().describe('Replacement text'),\n replaceAll: z.boolean().default(false).describe('Replace all occurrences'),\n }),\n )\n .describe('List of edit operations for this file'),\n }),\n )\n .describe('File edit operations to perform'),\n createBackup: z.boolean().default(false).describe('Create backup files before editing'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n results: z.array(\n z.object({\n filePath: z.string(),\n editsApplied: z.number(),\n errors: z.array(z.string()),\n backup: z.string().optional(),\n }),\n ),\n message: z.string(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.performMultiEdit({ ...inputData, projectPath });\n },\n }),\n\n replaceLines: createTool({\n id: 'replace-lines',\n description:\n 'Replace specific line ranges in files with new content. IMPORTANT: This tool replaces ENTIRE lines, not partial content within lines. Lines are 1-indexed.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to edit'),\n startLine: z\n .number()\n .describe('Starting line number to replace (1-indexed, inclusive). Count from the first line = 1'),\n endLine: z\n .number()\n .describe(\n 'Ending line number to replace (1-indexed, inclusive). To replace single line, use same number as startLine',\n ),\n newContent: z\n .string()\n .describe(\n 'New content to replace the lines with. Use empty string \"\" to delete lines completely. For multiline content, include \\\\n characters',\n ),\n createBackup: z.boolean().default(false).describe('Create backup file before editing'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n message: z.string(),\n linesReplaced: z.number().optional(),\n backup: z.string().optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.replaceLines({ ...inputData, projectPath });\n },\n }),\n\n // File diagnostics tool to help debug line replacement issues\n showFileLines: createTool({\n id: 'show-file-lines',\n description:\n 'Show specific lines from a file with line numbers. Useful for debugging before using replaceLines.',\n inputSchema: z.object({\n filePath: z.string().describe('Path to the file to examine'),\n startLine: z\n .number()\n .optional()\n .describe('Starting line number to show (1-indexed). If not provided, shows all lines'),\n endLine: z\n .number()\n .optional()\n .describe(\n 'Ending line number to show (1-indexed, inclusive). If not provided but startLine is, shows only that line',\n ),\n context: z.number().default(2).describe('Number of context lines to show before and after the range'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n lines: z.array(\n z.object({\n lineNumber: z.number(),\n content: z.string(),\n isTarget: z.boolean().describe('Whether this line is in the target range'),\n }),\n ),\n totalLines: z.number(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.showFileLines({ ...inputData, projectPath });\n },\n }),\n\n // Enhanced Pattern Search\n smartSearch: createTool({\n id: 'smart-search',\n description: 'Intelligent search across codebase with context awareness and pattern matching.',\n inputSchema: z.object({\n query: z.string().describe('Search query or pattern'),\n type: z.enum(['text', 'regex', 'fuzzy', 'semantic']).default('text').describe('Type of search to perform'),\n scope: z\n .object({\n paths: z.array(z.string()).optional().describe('Specific paths to search'),\n fileTypes: z.array(z.string()).optional().describe('File extensions to include'),\n excludePaths: z.array(z.string()).optional().describe('Paths to exclude'),\n maxResults: z.number().default(50).describe('Maximum number of results'),\n })\n .optional(),\n context: z\n .object({\n beforeLines: z.number().default(2).describe('Lines of context before match'),\n afterLines: z.number().default(2).describe('Lines of context after match'),\n includeDefinitions: z.boolean().default(false).describe('Include function/class definitions'),\n })\n .optional(),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n matches: z.array(\n z.object({\n file: z.string(),\n line: z.number(),\n column: z.number().optional(),\n match: z.string(),\n context: z.object({\n before: z.array(z.string()),\n after: z.array(z.string()),\n }),\n relevance: z.number().optional(),\n }),\n ),\n summary: z.object({\n totalMatches: z.number(),\n filesSearched: z.number(),\n patterns: z.array(z.string()),\n }),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.performSmartSearch(inputData, projectPath);\n },\n }),\n\n validateCode: createTool({\n id: 'validate-code',\n description:\n 'Validates code using a fast hybrid approach: syntax → semantic → lint. RECOMMENDED: Always provide specific files for optimal performance and accuracy.',\n inputSchema: z.object({\n projectPath: z.string().optional().describe('Path to the project to validate (defaults to current project)'),\n validationType: z\n .array(z.enum(['types', 'lint', 'schemas', 'tests', 'build']))\n .describe('Types of validation to perform. Recommended: [\"types\", \"lint\"] for code quality'),\n files: z\n .array(z.string())\n .optional()\n .describe(\n 'RECOMMENDED: Specific files to validate (e.g., files you created/modified). Uses hybrid validation: fast syntax check → semantic types → ESLint. Without files, falls back to slower CLI validation.',\n ),\n }),\n outputSchema: z.object({\n valid: z.boolean(),\n errors: z.array(\n z.object({\n type: z.enum(['typescript', 'eslint', 'schema', 'test', 'build']),\n severity: z.enum(['error', 'warning', 'info']),\n message: z.string(),\n file: z.string().optional(),\n line: z.number().optional(),\n column: z.number().optional(),\n code: z.string().optional(),\n }),\n ),\n summary: z.object({\n totalErrors: z.number(),\n totalWarnings: z.number(),\n validationsPassed: z.array(z.string()),\n validationsFailed: z.array(z.string()),\n }),\n }),\n execute: async inputData => {\n const { projectPath: validationProjectPath, validationType, files } = inputData;\n const targetPath = validationProjectPath || projectPath;\n\n // BEST PRACTICE: Always provide files array for optimal performance\n // Hybrid approach: syntax (1ms) → semantic (100ms) → ESLint (50ms)\n // Without files: falls back to CLI validation (2000ms+)\n\n return await AgentBuilderDefaults.validateCode({\n projectPath: targetPath,\n validationType,\n files,\n });\n },\n }),\n\n // Web Search (replaces MCP web search)\n webSearch: createTool({\n id: 'web-search',\n description: 'Search the web for current information and return structured results.',\n inputSchema: z.object({\n query: z.string().describe('Search query'),\n maxResults: z.number().default(10).describe('Maximum number of results to return'),\n region: z.string().default('us').describe('Search region/country code'),\n language: z.string().default('en').describe('Search language'),\n includeImages: z.boolean().default(false).describe('Include image results'),\n dateRange: z.enum(['day', 'week', 'month', 'year', 'all']).default('all').describe('Date range filter'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n query: z.string(),\n results: z.array(\n z.object({\n title: z.string(),\n url: z.string(),\n snippet: z.string(),\n domain: z.string(),\n publishDate: z.string().optional(),\n relevanceScore: z.number().optional(),\n }),\n ),\n totalResults: z.number(),\n searchTime: z.number(),\n suggestions: z.array(z.string()).optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.webSearch(inputData);\n },\n }),\n\n // Task Completion Signaling\n attemptCompletion: createTool({\n id: 'attempt-completion',\n description: 'Signal that you believe the requested task has been completed and provide a summary.',\n inputSchema: z.object({\n summary: z.string().describe('Summary of what was accomplished'),\n changes: z\n .array(\n z.object({\n type: z.enum(['file_created', 'file_modified', 'file_deleted', 'command_executed', 'dependency_added']),\n description: z.string(),\n path: z.string().optional(),\n }),\n )\n .describe('List of changes made'),\n validation: z\n .object({\n testsRun: z.boolean().default(false),\n buildsSuccessfully: z.boolean().default(false),\n manualTestingRequired: z.boolean().default(false),\n })\n .describe('Validation status'),\n nextSteps: z.array(z.string()).optional().describe('Suggested next steps or follow-up actions'),\n }),\n outputSchema: z.object({\n completionId: z.string(),\n status: z.enum(['completed', 'needs_review', 'needs_testing']),\n summary: z.string(),\n confidence: z.number().min(0).max(100),\n }),\n execute: async inputData => {\n return await AgentBuilderDefaults.signalCompletion(inputData);\n },\n }),\n\n manageProject: createTool({\n id: 'manage-project',\n description:\n 'Handles project management including creating project structures, managing dependencies, and package operations.',\n inputSchema: z.object({\n action: z.enum(['create', 'install', 'upgrade']).describe('The action to perform'),\n features: z\n .array(z.string())\n .optional()\n .describe('Mastra features to include (e.g., [\"agents\", \"memory\", \"workflows\"])'),\n packages: z\n .array(\n z.object({\n name: z.string(),\n version: z.string().optional(),\n }),\n )\n .optional()\n .describe('Packages to install/upgrade'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n installed: z.array(z.string()).optional(),\n upgraded: z.array(z.string()).optional(),\n warnings: z.array(z.string()).optional(),\n message: z.string().optional(),\n details: z.string().optional(),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n const { action, features, packages } = inputData;\n try {\n switch (action) {\n case 'create':\n return await AgentBuilderDefaults.createMastraProject({\n projectName: projectPath,\n features,\n });\n case 'install':\n if (!packages?.length) {\n return {\n success: false,\n message: 'Packages array is required for install action',\n };\n }\n return await AgentBuilderDefaults.installPackages({\n packages,\n projectPath,\n });\n case 'upgrade':\n if (!packages?.length) {\n return {\n success: false,\n message: 'Packages array is required for upgrade action',\n };\n }\n return await AgentBuilderDefaults.upgradePackages({\n packages,\n projectPath,\n });\n default:\n return {\n success: false,\n message: `Unknown action: ${action}`,\n };\n }\n } catch (error) {\n return {\n success: false,\n message: `Error executing ${action}: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n }),\n manageServer: createTool({\n id: 'manage-server',\n description:\n 'Manages the Mastra server - start, stop, restart, and check status, use the terminal tool to make curl requests to the server. There is an openapi spec for the server at http://localhost:{port}/openapi.json',\n inputSchema: z.object({\n action: z.enum(['start', 'stop', 'restart', 'status']).describe('Server management action'),\n port: z.number().optional().default(4200).describe('Port to run the server on'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n status: z.enum(['running', 'stopped', 'starting', 'stopping', 'unknown']),\n pid: z.number().optional(),\n port: z.number().optional(),\n url: z.string().optional(),\n message: z.string().optional(),\n stdout: z.array(z.string()).optional().describe('Server output lines captured during startup'),\n errorMessage: z.string().optional(),\n }),\n execute: async inputData => {\n const { action, port } = inputData;\n try {\n switch (action) {\n case 'start':\n return await AgentBuilderDefaults.startMastraServer({\n port,\n projectPath,\n });\n case 'stop':\n return await AgentBuilderDefaults.stopMastraServer({\n port,\n projectPath,\n });\n case 'restart':\n const stopResult = await AgentBuilderDefaults.stopMastraServer({\n port,\n projectPath,\n });\n if (!stopResult.success) {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Failed to restart: could not stop server on port ${port}`,\n errorMessage: stopResult.errorMessage || 'Unknown stop error',\n };\n }\n await new Promise(resolve => setTimeout(resolve, 500));\n const startResult = await AgentBuilderDefaults.startMastraServer({\n port,\n projectPath,\n });\n if (!startResult.success) {\n return {\n success: false,\n status: 'stopped' as const,\n message: `Failed to restart: server stopped successfully but failed to start on port ${port}`,\n errorMessage: startResult.errorMessage || 'Unknown start error',\n };\n }\n return {\n ...startResult,\n message: `Mastra server restarted successfully on port ${port}`,\n };\n case 'status':\n return await AgentBuilderDefaults.checkMastraServerStatus({\n port,\n projectPath,\n });\n default:\n return {\n success: false,\n status: 'unknown' as const,\n message: `Unknown action: ${action}`,\n };\n }\n } catch (error) {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Error managing server: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n }),\n httpRequest: createTool({\n id: 'http-request',\n description: 'Makes HTTP requests to the Mastra server or external APIs for testing and integration',\n inputSchema: z.object({\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).describe('HTTP method'),\n url: z.string().describe('Full URL or path (if baseUrl provided)'),\n baseUrl: z.string().optional().describe('Base URL for the server (e.g., http://localhost:4200)'),\n headers: z.record(z.string(), z.string()).optional().describe('HTTP headers'),\n body: z.any().optional().describe('Request body (will be JSON stringified if object)'),\n timeout: z.number().optional().default(30000).describe('Request timeout in milliseconds'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n status: z.number().optional(),\n statusText: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n data: z.any().optional(),\n errorMessage: z.string().optional(),\n url: z.string(),\n method: z.string(),\n }),\n execute: async inputData => {\n const { method, url, baseUrl, headers, body, timeout } = inputData;\n try {\n return await AgentBuilderDefaults.makeHttpRequest({\n method,\n url,\n baseUrl,\n headers: headers as Record<string, string> | undefined,\n body,\n timeout,\n });\n } catch (error) {\n return {\n success: false,\n url: baseUrl ? `${baseUrl}${url}` : url,\n method,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n },\n }),\n };\n };\n\n /**\n * Filter tools for template builder mode (excludes web search and other advanced tools)\n */\n static filterToolsForTemplateBuilder(tools: Record<string, any>): Record<string, any> {\n const templateBuilderTools = [\n 'readFile',\n 'writeFile',\n 'listDirectory',\n 'executeCommand',\n 'taskManager',\n 'multiEdit',\n 'replaceLines',\n 'showFileLines',\n 'smartSearch',\n 'validateCode',\n ];\n\n const filtered: Record<string, ReturnType<typeof createTool>> = {};\n for (const toolName of templateBuilderTools) {\n if (tools[toolName]) {\n filtered[toolName] = tools[toolName];\n }\n }\n return filtered;\n }\n\n /**\n * Filter tools for code editor mode (includes all tools)\n */\n static filterToolsForCodeEditor(tools: Record<string, any>): Record<string, any> {\n return tools; // Return all tools for code editor mode\n }\n\n /**\n * Get tools for a specific mode\n */\n static async listToolsForMode(\n projectPath: string,\n mode: 'template' | 'code-editor' = 'code-editor',\n ): Promise<Record<string, any>> {\n const allTools = await AgentBuilderDefaults.DEFAULT_TOOLS(projectPath);\n\n if (mode === 'template') {\n return AgentBuilderDefaults.filterToolsForTemplateBuilder(allTools);\n } else {\n return AgentBuilderDefaults.filterToolsForCodeEditor(allTools);\n }\n }\n\n /**\n * Create a new Mastra project using create-mastra CLI\n */\n static async createMastraProject({ features, projectName }: { features?: string[]; projectName?: string }) {\n try {\n const args = ['pnpx', 'create-mastra@latest', projectName?.replace(/[;&|`$(){}\\[\\]]/g, '') ?? '', '-l', 'openai'];\n if (features && features.length > 0) {\n args.push('--components', features.join(','));\n }\n args.push('--example');\n\n const { stdout, stderr } = await spawnWithOutput(args[0]!, args.slice(1), {});\n\n return {\n success: true,\n projectPath: `./${projectName}`,\n message: `Successfully created Mastra project: ${projectName}.`,\n details: stdout,\n errorMessage: stderr,\n };\n } catch (error) {\n console.error(error);\n return {\n success: false,\n message: `Failed to create project: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Install packages using the detected package manager\n */\n static async installPackages({\n packages,\n projectPath,\n }: {\n packages: Array<{ name: string; version?: string }>;\n projectPath?: string;\n }) {\n try {\n console.info('Installing packages:', JSON.stringify(packages, null, 2));\n\n const packageStrings = packages.map(p => `${p.name}`);\n\n await spawnSWPM(projectPath || '', 'add', packageStrings);\n\n return {\n success: true,\n installed: packageStrings,\n message: `Successfully installed ${packages.length} package(s).`,\n details: '',\n };\n } catch (error) {\n return {\n success: false,\n message: `Failed to install packages: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Upgrade packages using the detected package manager\n */\n static async upgradePackages({\n packages,\n projectPath,\n }: {\n packages?: Array<{ name: string; version?: string }>;\n projectPath?: string;\n }) {\n try {\n console.info('Upgrading specific packages:', JSON.stringify(packages, null, 2));\n\n let packageNames: string[] = [];\n\n if (packages && packages.length > 0) {\n packageNames = packages.map(p => `${p.name}`);\n }\n await spawnSWPM(projectPath || '', 'upgrade', packageNames);\n\n return {\n success: true,\n upgraded: packages?.map(p => p.name) || ['all packages'],\n message: `Packages upgraded successfully.`,\n details: '',\n };\n } catch (error) {\n return {\n success: false,\n message: `Failed to upgrade packages: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Start the Mastra server\n */\n static async startMastraServer({\n port = 4200,\n projectPath,\n env = {},\n }: {\n port?: number;\n projectPath?: string;\n env?: Record<string, string>;\n }) {\n try {\n const serverEnv = { ...process.env, ...env, PORT: port.toString() };\n const execOptions = {\n cwd: projectPath || process.cwd(),\n env: serverEnv,\n };\n\n const serverProcess = nodeSpawn('pnpm', ['run', 'dev'], {\n ...execOptions,\n detached: true,\n stdio: 'pipe',\n });\n\n const stdoutLines: string[] = [];\n\n const serverStarted = new Promise<any>((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(`Server startup timeout after 30 seconds. Output: ${stdoutLines.join('\\n')}`));\n }, 30000);\n\n serverProcess.stdout?.on('data', data => {\n const output = data.toString();\n const lines = output.split('\\n').filter((line: string) => line.trim());\n stdoutLines.push(...lines);\n\n if (output.includes('Mastra API running')) {\n clearTimeout(timeout);\n resolve({\n success: true,\n status: 'running' as const,\n pid: serverProcess.pid,\n port,\n url: `http://localhost:${port}`,\n message: `Mastra server started successfully on port ${port}`,\n stdout: stdoutLines,\n });\n }\n });\n\n serverProcess.stderr?.on('data', data => {\n const errorOutput = data.toString();\n stdoutLines.push(`[STDERR] ${errorOutput}`);\n clearTimeout(timeout);\n reject(new Error(`Server startup failed with error: ${errorOutput}`));\n });\n\n serverProcess.on('error', error => {\n clearTimeout(timeout);\n reject(error);\n });\n\n serverProcess.on('exit', (code, signal) => {\n clearTimeout(timeout);\n if (code !== 0 && code !== null) {\n reject(\n new Error(\n `Server process exited with code ${code}${signal ? ` (signal: ${signal})` : ''}. Output: ${stdoutLines.join('\\n')}`,\n ),\n );\n }\n });\n });\n\n return await serverStarted;\n } catch (error) {\n return {\n success: false,\n status: 'stopped' as const,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Stop the Mastra server\n */\n static async stopMastraServer({ port = 4200, projectPath: _projectPath }: { port?: number; projectPath?: string }) {\n // Validate port to ensure it is a safe integer\n if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535) {\n return {\n success: false,\n status: 'error' as const,\n errorMessage: `Invalid port value: ${String(port)}`,\n };\n }\n try {\n // Run lsof safely without shell interpretation\n const { stdout } = await execFile('lsof', ['-ti', String(port)]);\n // If no output, treat as \"No process found\"\n const effectiveStdout = stdout.trim() ? stdout : 'No process found';\n\n if (!effectiveStdout || effectiveStdout === 'No process found') {\n return {\n success: true,\n status: 'stopped' as const,\n message: `No Mastra server found running on port ${port}`,\n };\n }\n\n const pids = stdout\n .trim()\n .split('\\n')\n .filter((pid: string) => pid.trim());\n const killedPids: number[] = [];\n const failedPids: number[] = [];\n\n for (const pidStr of pids) {\n const pid = parseInt(pidStr.trim());\n if (isNaN(pid)) continue;\n\n try {\n process.kill(pid, 'SIGTERM');\n killedPids.push(pid);\n } catch (e) {\n failedPids.push(pid);\n console.warn(`Failed to kill process ${pid}:`, e);\n }\n }\n\n // If some processes failed to be killed, still report partial success\n // but include warning about failed processes\n\n if (killedPids.length === 0) {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Failed to stop any processes on port ${port}`,\n errorMessage: `Could not kill PIDs: ${failedPids.join(', ')}`,\n };\n }\n\n // Report partial success if some processes were killed but others failed\n if (failedPids.length > 0) {\n console.warn(\n `Killed ${killedPids.length} processes but failed to kill ${failedPids.length} processes: ${failedPids.join(', ')}`,\n );\n }\n\n // Wait a bit and check if processes are still running\n await new Promise(resolve => setTimeout(resolve, 2000));\n\n try {\n const { stdout: checkStdoutRaw } = await execFile('lsof', ['-ti', String(port)]);\n const checkStdout = checkStdoutRaw.trim() ? checkStdoutRaw : 'No process found';\n if (checkStdout && checkStdout !== 'No process found') {\n // Force kill remaining processes\n const remainingPids = checkStdout\n .trim()\n .split('\\n')\n .filter((pid: string) => pid.trim());\n for (const pidStr of remainingPids) {\n const pid = parseInt(pidStr.trim());\n if (!isNaN(pid)) {\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n // ignore\n }\n }\n }\n\n // Final check\n await new Promise(resolve => setTimeout(resolve, 1000));\n const { stdout: finalCheckRaw } = await execFile('lsof', ['-ti', String(port)]);\n const finalCheck = finalCheckRaw.trim() ? finalCheckRaw : 'No process found';\n if (finalCheck && finalCheck !== 'No process found') {\n return {\n success: false,\n status: 'unknown' as const,\n message: `Server processes still running on port ${port} after stop attempts`,\n errorMessage: `Remaining PIDs: ${finalCheck.trim()}`,\n };\n }\n }\n } catch (error) {\n console.warn('Failed to verify server stop:', error);\n }\n\n return {\n success: true,\n status: 'stopped' as const,\n message: `Mastra server stopped successfully (port ${port}). Killed PIDs: ${killedPids.join(', ')}`,\n };\n } catch (error) {\n return {\n success: false,\n status: 'unknown' as const,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Check Mastra server status\n */\n static async checkMastraServerStatus({\n port = 4200,\n projectPath: _projectPath,\n }: {\n port?: number;\n projectPath?: string;\n }) {\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 5000);\n\n const response = await fetch(`http://localhost:${port}/health`, {\n method: 'GET',\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n return {\n success: true,\n status: 'running' as const,\n port,\n url: `http://localhost:${port}`,\n message: 'Mastra server is running and healthy',\n };\n } else {\n return {\n success: false,\n status: 'unknown' as const,\n port,\n message: `Server responding but not healthy (status: ${response.status})`,\n };\n }\n } catch {\n // Check if process exists on port\n try {\n const { stdout } = await execFile('lsof', ['-ti', String(port)]);\n const effectiveStdout = stdout.trim() ? stdout : 'No process found';\n const hasProcess = effectiveStdout && effectiveStdout !== 'No process found';\n\n return {\n success: Boolean(hasProcess),\n status: hasProcess ? ('starting' as const) : ('stopped' as const),\n port,\n message: hasProcess\n ? 'Server process exists but not responding to health checks'\n : 'No server process found on specified port',\n };\n } catch {\n return {\n success: false,\n status: 'stopped' as const,\n port,\n message: 'Server is not running',\n };\n }\n }\n }\n\n // Cache for TypeScript program (lazily loaded)\n private static tsProgram: any | null = null;\n private static programProjectPath: string | null = null;\n\n /**\n * Validate code using hybrid approach: syntax -> types -> lint\n *\n * BEST PRACTICES FOR CODING AGENTS:\n *\n * ✅ RECOMMENDED (Fast & Accurate):\n * validateCode({\n * validationType: ['types', 'lint'],\n * files: ['src/workflows/my-workflow.ts', 'src/components/Button.tsx']\n * })\n *\n * Performance: ~150ms\n * - Syntax check (1ms) - catches 80% of issues instantly\n * - Semantic validation (100ms) - full type checking with dependencies\n * - ESLint (50ms) - style and best practices\n * - Only shows errors from YOUR files\n *\n * ❌ AVOID (Slow & Noisy):\n * validateCode({ validationType: ['types', 'lint'] }) // no files specified\n *\n * Performance: ~2000ms+\n * - Full project CLI validation\n * - Shows errors from all project files (confusing)\n * - Much slower for coding agents\n *\n * @param projectPath - Project root directory (defaults to cwd)\n * @param validationType - ['types', 'lint'] recommended for most use cases\n * @param files - ALWAYS provide this for best performance\n */\n static async validateCode({\n projectPath,\n validationType,\n files,\n }: {\n projectPath?: string;\n validationType: Array<'types' | 'lint' | 'schemas' | 'tests' | 'build'>;\n files?: string[];\n }) {\n const errors: Array<{\n type: 'typescript' | 'eslint' | 'schema' | 'test' | 'build';\n severity: 'error' | 'warning' | 'info';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n const validationsPassed: string[] = [];\n const validationsFailed: string[] = [];\n\n const targetProjectPath = projectPath || process.cwd();\n\n // If no files specified, use legacy CLI-based validation for backward compatibility\n if (!files || files.length === 0) {\n return this.validateCodeCLI({ projectPath, validationType });\n }\n\n // Hybrid validation approach for specific files (default behavior)\n for (const filePath of files) {\n const absolutePath = isAbsolute(filePath) ? filePath : resolve(targetProjectPath, filePath);\n\n try {\n const fileContent = await readFile(absolutePath, 'utf-8');\n const fileResults = await this.validateSingleFileHybrid(\n absolutePath,\n fileContent,\n targetProjectPath,\n validationType,\n );\n\n errors.push(...fileResults.errors);\n\n // Track validation results\n for (const type of validationType) {\n const hasErrors = fileResults.errors.some(e => e.type === type && e.severity === 'error');\n if (hasErrors) {\n if (!validationsFailed.includes(type)) validationsFailed.push(type);\n } else {\n if (!validationsPassed.includes(type)) validationsPassed.push(type);\n }\n }\n } catch (error) {\n errors.push({\n type: 'typescript',\n severity: 'error',\n message: `Failed to read file ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n file: filePath,\n });\n validationsFailed.push('types');\n }\n }\n\n const totalErrors = errors.filter(e => e.severity === 'error').length;\n const totalWarnings = errors.filter(e => e.severity === 'warning').length;\n const isValid = totalErrors === 0;\n\n return {\n valid: isValid,\n errors,\n summary: {\n totalErrors,\n totalWarnings,\n validationsPassed,\n validationsFailed,\n },\n };\n }\n\n /**\n * CLI-based validation for when no specific files are provided\n */\n static async validateCodeCLI({\n projectPath,\n validationType,\n }: {\n projectPath?: string;\n validationType: Array<'types' | 'lint' | 'schemas' | 'tests' | 'build'>;\n }) {\n const errors: Array<{\n type: 'typescript' | 'eslint' | 'schema' | 'test' | 'build';\n severity: 'error' | 'warning' | 'info';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n const validationsPassed: string[] = [];\n const validationsFailed: string[] = [];\n\n const execOptions = { cwd: projectPath };\n\n // TypeScript validation (legacy approach)\n if (validationType.includes('types')) {\n try {\n // Use execFile for safe argument passing to avoid shell interpretation\n const args = ['tsc', '--noEmit'];\n await execFile('npx', args, execOptions);\n validationsPassed.push('types');\n } catch (error: any) {\n let tsOutput = '';\n if (error.stdout) {\n tsOutput = error.stdout;\n } else if (error.stderr) {\n tsOutput = error.stderr;\n } else if (error.message) {\n tsOutput = error.message;\n }\n\n errors.push({\n type: 'typescript',\n severity: 'error',\n message: tsOutput.trim() || `TypeScript validation failed: ${error.message || String(error)}`,\n });\n validationsFailed.push('types');\n }\n }\n\n // ESLint validation\n if (validationType.includes('lint')) {\n try {\n const eslintArgs = ['eslint', '--format', 'json'];\n const { stdout } = await execFile('npx', eslintArgs, execOptions);\n\n if (stdout) {\n const eslintResults = JSON.parse(stdout);\n const eslintErrors = AgentBuilderDefaults.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n\n if (eslintErrors.some(e => e.severity === 'error')) {\n validationsFailed.push('lint');\n } else {\n validationsPassed.push('lint');\n }\n } else {\n validationsPassed.push('lint');\n }\n } catch (error: any) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (errorMessage.includes('\"filePath\"') || errorMessage.includes('messages')) {\n try {\n const eslintResults = JSON.parse(errorMessage);\n const eslintErrors = AgentBuilderDefaults.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n validationsFailed.push('lint');\n } catch {\n errors.push({\n type: 'eslint',\n severity: 'error',\n message: `ESLint validation failed: ${errorMessage}`,\n });\n validationsFailed.push('lint');\n }\n } else {\n validationsPassed.push('lint');\n }\n }\n }\n\n const totalErrors = errors.filter(e => e.severity === 'error').length;\n const totalWarnings = errors.filter(e => e.severity === 'warning').length;\n const isValid = totalErrors === 0;\n\n return {\n valid: isValid,\n errors,\n summary: {\n totalErrors,\n totalWarnings,\n validationsPassed,\n validationsFailed,\n },\n };\n }\n\n /**\n * Hybrid validation for a single file\n */\n static async validateSingleFileHybrid(\n filePath: string,\n fileContent: string,\n projectPath: string,\n validationType: Array<'types' | 'lint' | 'schemas' | 'tests' | 'build'>,\n ) {\n const errors: Array<{\n type: 'typescript' | 'eslint' | 'schema' | 'test' | 'build';\n severity: 'error' | 'warning' | 'info';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n\n // Step 1: Fast syntax validation\n if (validationType.includes('types')) {\n const syntaxErrors = await this.validateSyntaxOnly(fileContent, filePath);\n errors.push(...syntaxErrors);\n\n // Fail fast on syntax errors\n if (syntaxErrors.length > 0) {\n return { errors };\n }\n\n // Step 2: TypeScript semantic validation (if syntax is clean)\n const typeErrors = await this.validateTypesSemantic(filePath, projectPath);\n errors.push(...typeErrors);\n }\n\n // Step 3: ESLint validation (only if no critical errors)\n if (validationType.includes('lint') && !errors.some(e => e.severity === 'error')) {\n const lintErrors = await this.validateESLintSingle(filePath, projectPath);\n errors.push(...lintErrors);\n }\n\n return { errors };\n }\n\n /**\n * Fast syntax-only validation using TypeScript parser\n */\n static async validateSyntaxOnly(fileContent: string, fileName: string) {\n const errors: Array<{\n type: 'typescript';\n severity: 'error';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n }> = [];\n\n try {\n // Dynamically import TypeScript to avoid bundling issues\n const ts = await import('typescript');\n\n const sourceFile = ts.createSourceFile(fileName, fileContent, ts.ScriptTarget.Latest, true);\n\n // Create a minimal program to get syntax diagnostics\n const options: any = {\n allowJs: true,\n checkJs: false,\n noEmit: true,\n };\n\n const host: any = {\n getSourceFile: (name: string) => (name === fileName ? sourceFile : undefined),\n writeFile: () => {},\n getCurrentDirectory: () => '',\n getDirectories: () => [],\n fileExists: (name: string) => name === fileName,\n readFile: (name: string) => (name === fileName ? fileContent : undefined),\n getCanonicalFileName: (name: string) => name,\n useCaseSensitiveFileNames: () => true,\n getNewLine: () => '\\n',\n getDefaultLibFileName: () => 'lib.d.ts',\n };\n\n const program = ts.createProgram([fileName], options, host);\n const diagnostics = program.getSyntacticDiagnostics(sourceFile);\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.start !== undefined) {\n const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start);\n errors.push({\n type: 'typescript',\n severity: 'error',\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n file: fileName,\n line: position.line + 1,\n column: position.character + 1,\n });\n }\n }\n } catch (error) {\n // If TypeScript is not available, fall back to basic validation\n console.warn('TypeScript not available for syntax validation:', error);\n\n // Basic syntax check - look for common syntax errors\n const lines = fileContent.split('\\n');\n const commonErrors = [\n { pattern: /\\bimport\\s+.*\\s+from\\s+['\"\"][^'\"]*$/, message: 'Unterminated import statement' },\n { pattern: /\\{[^}]*$/, message: 'Unclosed brace' },\n { pattern: /\\([^)]*$/, message: 'Unclosed parenthesis' },\n { pattern: /\\[[^\\]]*$/, message: 'Unclosed bracket' },\n ];\n\n lines.forEach((line, index) => {\n commonErrors.forEach(({ pattern, message }) => {\n if (pattern.test(line)) {\n errors.push({\n type: 'typescript',\n severity: 'error',\n message,\n file: fileName,\n line: index + 1,\n });\n }\n });\n });\n }\n\n return errors;\n }\n\n /**\n * TypeScript semantic validation using incremental program\n */\n static async validateTypesSemantic(filePath: string, projectPath: string) {\n const errors: Array<{\n type: 'typescript';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n }> = [];\n\n try {\n // Initialize or reuse TypeScript program\n const program = await this.getOrCreateTSProgram(projectPath);\n if (!program) {\n return errors; // Fallback to no validation if program creation fails\n }\n\n const sourceFile = program.getSourceFile(filePath);\n if (!sourceFile) {\n return errors; // File not in program\n }\n\n const diagnostics = [\n ...program.getSemanticDiagnostics(sourceFile),\n ...program.getSyntacticDiagnostics(sourceFile),\n ];\n\n // Dynamically import TypeScript for diagnostic processing\n const ts = await import('typescript');\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.start !== undefined) {\n const position = sourceFile.getLineAndCharacterOfPosition(diagnostic.start);\n errors.push({\n type: 'typescript',\n severity: diagnostic.category === ts.DiagnosticCategory.Warning ? 'warning' : 'error',\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'),\n file: filePath,\n line: position.line + 1,\n column: position.character + 1,\n });\n }\n }\n } catch (error) {\n // Fallback to no semantic validation on error\n console.warn(`TypeScript semantic validation failed for ${filePath}:`, error);\n }\n\n return errors;\n }\n\n /**\n * ESLint validation for a single file\n */\n static async validateESLintSingle(filePath: string, projectPath: string) {\n const errors: Array<{\n type: 'eslint';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n\n try {\n const { stdout } = await execFile('npx', ['eslint', filePath, '--format', 'json'], { cwd: projectPath });\n\n if (stdout) {\n const eslintResults = JSON.parse(stdout);\n const eslintErrors = this.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n }\n } catch (error: any) {\n // Try to parse error output\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes('\"filePath\"') || errorMessage.includes('messages')) {\n try {\n const eslintResults = JSON.parse(errorMessage);\n const eslintErrors = this.parseESLintErrors(eslintResults);\n errors.push(...eslintErrors);\n } catch {\n // Ignore ESLint errors in hybrid mode for now\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Get or create TypeScript program\n */\n static async getOrCreateTSProgram(projectPath: string): Promise<any | null> {\n // Return cached program if same project\n if (this.tsProgram && this.programProjectPath === projectPath) {\n return this.tsProgram;\n }\n\n try {\n // Dynamically import TypeScript\n const ts = await import('typescript');\n\n const configPath = ts.findConfigFile(projectPath, ts.sys.fileExists, 'tsconfig.json');\n if (!configPath) {\n return null; // No tsconfig found\n }\n\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (configFile.error) {\n return null;\n }\n\n const parsedConfig = ts.parseJsonConfigFileContent(configFile.config, ts.sys, projectPath);\n\n if (parsedConfig.errors.length > 0) {\n return null;\n }\n\n // Create regular program\n this.tsProgram = ts.createProgram({\n rootNames: parsedConfig.fileNames,\n options: parsedConfig.options,\n });\n\n this.programProjectPath = projectPath;\n return this.tsProgram;\n } catch (error) {\n console.warn('Failed to create TypeScript program:', error);\n return null;\n }\n }\n\n // Note: Old filterTypeScriptErrors method removed in favor of hybrid validation approach\n\n /**\n * Parse ESLint errors from JSON output\n */\n static parseESLintErrors(eslintResults: any[]): Array<{\n type: 'eslint';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> {\n const errors: Array<{\n type: 'eslint';\n severity: 'error' | 'warning';\n message: string;\n file?: string;\n line?: number;\n column?: number;\n code?: string;\n }> = [];\n\n for (const result of eslintResults) {\n for (const message of result.messages || []) {\n if (message.message) {\n errors.push({\n type: 'eslint',\n severity: message.severity === 1 ? 'warning' : 'error',\n message: message.message,\n file: result.filePath || undefined,\n line: message.line || undefined,\n column: message.column || undefined,\n code: message.ruleId || undefined,\n });\n }\n }\n }\n\n return errors;\n }\n\n /**\n * Make HTTP request to server or external API\n */\n static async makeHttpRequest({\n method,\n url,\n baseUrl,\n headers = {},\n body,\n timeout = 30000,\n }: {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n url: string;\n baseUrl?: string;\n headers?: Record<string, string>;\n body?: any;\n timeout?: number;\n }) {\n try {\n const fullUrl = baseUrl ? `${baseUrl}${url}` : url;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const requestOptions: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n signal: controller.signal,\n };\n\n if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {\n requestOptions.body = typeof body === 'string' ? body : JSON.stringify(body);\n }\n\n const response = await fetch(fullUrl, requestOptions);\n clearTimeout(timeoutId);\n\n let data: any;\n const contentType = response.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n data = await response.json();\n } else {\n data = await response.text();\n }\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n return {\n success: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: responseHeaders,\n data,\n url: fullUrl,\n method,\n };\n } catch (error) {\n return {\n success: false,\n url: baseUrl ? `${baseUrl}${url}` : url,\n method,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Enhanced task management system for complex coding tasks\n */\n static async manageTaskList(context: {\n action: 'create' | 'update' | 'list' | 'complete' | 'remove';\n tasks?: Array<{\n id: string;\n content?: string;\n status: 'pending' | 'in_progress' | 'completed' | 'blocked';\n priority: 'high' | 'medium' | 'low';\n dependencies?: string[];\n notes?: string;\n }>;\n taskId?: string;\n }) {\n // In-memory task storage (could be enhanced with persistent storage)\n if (!AgentBuilderDefaults.taskStorage) {\n AgentBuilderDefaults.taskStorage = new Map();\n }\n\n // Cleanup old sessions to prevent memory leaks\n // Keep only the last 10 sessions\n const sessions = Array.from(AgentBuilderDefaults.taskStorage.keys());\n if (sessions.length > 10) {\n const sessionsToRemove = sessions.slice(0, sessions.length - 10);\n sessionsToRemove.forEach(session => AgentBuilderDefaults.taskStorage.delete(session));\n }\n\n const sessionId = 'current'; // Could be enhanced with proper session management\n const existingTasks = AgentBuilderDefaults.taskStorage.get(sessionId) || [];\n\n try {\n switch (context.action) {\n case 'create':\n if (!context.tasks?.length) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'No tasks provided for creation',\n };\n }\n\n const newTasks = context.tasks.map(task => ({\n ...task,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n }));\n\n const allTasks = [...existingTasks, ...newTasks];\n AgentBuilderDefaults.taskStorage.set(sessionId, allTasks);\n\n return {\n success: true,\n tasks: allTasks,\n message: `Created ${newTasks.length} new task(s)`,\n };\n\n case 'update':\n if (!context.tasks?.length) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'No tasks provided for update',\n };\n }\n\n const updatedTasks = existingTasks.map(existing => {\n const update = context.tasks!.find(t => t.id === existing.id);\n return update ? { ...existing, ...update, updatedAt: new Date().toISOString() } : existing;\n });\n\n AgentBuilderDefaults.taskStorage.set(sessionId, updatedTasks);\n\n return {\n success: true,\n tasks: updatedTasks,\n message: 'Tasks updated successfully',\n };\n\n case 'complete':\n if (!context.taskId) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'Task ID required for completion',\n };\n }\n\n const completedTasks = existingTasks.map(task =>\n task.id === context.taskId\n ? { ...task, status: 'completed' as const, updatedAt: new Date().toISOString() }\n : task,\n );\n\n AgentBuilderDefaults.taskStorage.set(sessionId, completedTasks);\n\n return {\n success: true,\n tasks: completedTasks,\n message: `Task ${context.taskId} marked as completed`,\n };\n\n case 'remove':\n if (!context.taskId) {\n return {\n success: false,\n tasks: existingTasks,\n message: 'Task ID required for removal',\n };\n }\n\n const filteredTasks = existingTasks.filter(task => task.id !== context.taskId);\n AgentBuilderDefaults.taskStorage.set(sessionId, filteredTasks);\n\n return {\n success: true,\n tasks: filteredTasks,\n message: `Task ${context.taskId} removed`,\n };\n\n case 'list':\n default:\n return {\n success: true,\n tasks: existingTasks,\n message: `Found ${existingTasks.length} task(s)`,\n };\n }\n } catch (error) {\n return {\n success: false,\n tasks: existingTasks,\n message: `Task management error: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Perform multiple edits across files atomically\n */\n static async performMultiEdit(context: {\n operations: Array<{\n filePath: string;\n edits: Array<{\n oldString: string;\n newString: string;\n replaceAll?: boolean;\n }>;\n }>;\n createBackup?: boolean;\n projectPath?: string;\n }) {\n const { operations, createBackup = false, projectPath = process.cwd() } = context;\n const results: Array<{\n filePath: string;\n editsApplied: number;\n errors: string[];\n backup?: string;\n }> = [];\n\n try {\n for (const operation of operations) {\n const filePath = isAbsolute(operation.filePath) ? operation.filePath : join(projectPath, operation.filePath);\n let editsApplied = 0;\n const errors: string[] = [];\n let backup: string | undefined;\n\n try {\n // Create backup if requested\n if (createBackup) {\n const backupPath = `${filePath}.backup.${Date.now()}`;\n const originalContent = await readFile(filePath, 'utf-8');\n await writeFile(backupPath, originalContent, 'utf-8');\n backup = backupPath;\n }\n\n // Read current file content\n let content = await readFile(filePath, 'utf-8');\n\n // Apply each edit\n for (const edit of operation.edits) {\n const { oldString, newString, replaceAll = false } = edit;\n\n if (replaceAll) {\n const regex = new RegExp(oldString.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'g');\n const matches = content.match(regex);\n if (matches) {\n content = content.replace(regex, newString);\n editsApplied += matches.length;\n }\n } else {\n if (content.includes(oldString)) {\n content = content.replace(oldString, newString);\n editsApplied++;\n } else {\n errors.push(`String not found: \"${oldString.substring(0, 50)}${oldString.length > 50 ? '...' : ''}\"`);\n }\n }\n }\n\n // Write updated content back\n await writeFile(filePath, content, 'utf-8');\n } catch (error) {\n errors.push(`File operation error: ${error instanceof Error ? error.message : String(error)}`);\n }\n\n results.push({\n filePath: operation.filePath,\n editsApplied,\n errors,\n backup,\n });\n }\n\n const totalEdits = results.reduce((sum, r) => sum + r.editsApplied, 0);\n const totalErrors = results.reduce((sum, r) => sum + r.errors.length, 0);\n\n return {\n success: totalErrors === 0,\n results,\n message: `Applied ${totalEdits} edits across ${operations.length} files${totalErrors > 0 ? ` with ${totalErrors} errors` : ''}`,\n };\n } catch (error) {\n return {\n success: false,\n results,\n message: `Multi-edit operation failed: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n\n /**\n * Replace specific line ranges in a file with new content\n */\n static async replaceLines(context: {\n filePath: string;\n startLine: number;\n endLine: number;\n newContent: string;\n createBackup?: boolean;\n projectPath?: string;\n }) {\n const { filePath, startLine, endLine, newContent, createBackup = false, projectPath = process.cwd() } = context;\n\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(projectPath, filePath);\n\n // Read current file content\n const content = await readFile(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n // Validate line numbers\n if (startLine < 1 || endLine < 1) {\n return {\n success: false,\n message: `Line numbers must be 1 or greater. Got startLine: ${startLine}, endLine: ${endLine}`,\n errorMessage: 'Invalid line range',\n };\n }\n\n if (startLine > lines.length || endLine > lines.length) {\n return {\n success: false,\n 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}.`,\n errorMessage: 'Invalid line range',\n };\n }\n\n if (startLine > endLine) {\n return {\n success: false,\n message: `Start line (${startLine}) cannot be greater than end line (${endLine}).`,\n errorMessage: 'Invalid line range',\n };\n }\n\n // Create backup if requested\n let backup: string | undefined;\n if (createBackup) {\n const backupPath = `${fullPath}.backup.${Date.now()}`;\n await writeFile(backupPath, content, 'utf-8');\n backup = backupPath;\n }\n\n // Replace the specified line range\n const beforeLines = lines.slice(0, startLine - 1);\n const afterLines = lines.slice(endLine);\n const newLines = newContent ? newContent.split('\\n') : [];\n\n const updatedLines = [...beforeLines, ...newLines, ...afterLines];\n const updatedContent = updatedLines.join('\\n');\n\n // Write updated content back\n await writeFile(fullPath, updatedContent, 'utf-8');\n\n const linesReplaced = endLine - startLine + 1;\n const newLineCount = newLines.length;\n\n return {\n success: true,\n message: `Successfully replaced ${linesReplaced} lines (${startLine}-${endLine}) with ${newLineCount} new lines in ${filePath}`,\n linesReplaced,\n backup,\n };\n } catch (error) {\n return {\n success: false,\n message: `Failed to replace lines: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Show file lines with line numbers for debugging\n */\n static async showFileLines(context: {\n filePath: string;\n startLine?: number;\n endLine?: number;\n context?: number;\n projectPath?: string;\n }) {\n const { filePath, startLine, endLine, context: contextLines = 2, projectPath = process.cwd() } = context;\n\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(projectPath, filePath);\n\n // Read current file content\n const content = await readFile(fullPath, 'utf-8');\n const lines = content.split('\\n');\n\n let targetStart = startLine;\n let targetEnd = endLine;\n\n // If no range specified, show all lines\n if (!targetStart) {\n targetStart = 1;\n targetEnd = lines.length;\n } else if (!targetEnd) {\n targetEnd = targetStart;\n }\n\n // Calculate actual display range with context\n const displayStart = Math.max(1, targetStart - contextLines);\n const displayEnd = Math.min(lines.length, targetEnd + contextLines);\n\n const result = [];\n for (let i = displayStart; i <= displayEnd; i++) {\n const lineIndex = i - 1; // Convert to 0-based for array access\n const isTarget = i >= targetStart && i <= targetEnd;\n\n result.push({\n lineNumber: i,\n content: lineIndex < lines.length ? (lines[lineIndex] ?? '') : '',\n isTarget,\n });\n }\n\n return {\n success: true,\n lines: result,\n totalLines: lines.length,\n message: `Showing lines ${displayStart}-${displayEnd} of ${lines.length} total lines in ${filePath}`,\n };\n } catch (error) {\n return {\n success: false,\n lines: [],\n totalLines: 0,\n message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Signal task completion\n */\n static async signalCompletion(context: {\n summary: string;\n changes: Array<{\n type: 'file_created' | 'file_modified' | 'file_deleted' | 'command_executed' | 'dependency_added';\n description: string;\n path?: string;\n }>;\n validation: {\n testsRun?: boolean;\n buildsSuccessfully?: boolean;\n manualTestingRequired?: boolean;\n };\n nextSteps?: string[];\n }) {\n const completionId = `completion_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n\n // Calculate confidence based on validation status\n let confidence = 70; // Base confidence\n if (context.validation.testsRun) confidence += 15;\n if (context.validation.buildsSuccessfully) confidence += 15;\n if (context.validation.manualTestingRequired) confidence -= 10;\n\n // Determine status\n let status: 'completed' | 'needs_review' | 'needs_testing';\n if (context.validation.testsRun && context.validation.buildsSuccessfully) {\n status = 'completed';\n } else if (context.validation.manualTestingRequired) {\n status = 'needs_testing';\n } else {\n status = 'needs_review';\n }\n\n return {\n completionId,\n status,\n summary: context.summary,\n confidence: Math.min(100, Math.max(0, confidence)),\n };\n }\n\n /**\n * Perform intelligent search with context\n */\n static async performSmartSearch(\n context: {\n query: string;\n type?: 'text' | 'regex' | 'fuzzy' | 'semantic';\n scope?: {\n paths?: string[];\n fileTypes?: string[];\n excludePaths?: string[];\n maxResults?: number;\n };\n context?: {\n beforeLines?: number;\n afterLines?: number;\n includeDefinitions?: boolean;\n };\n },\n projectPath: string,\n ) {\n try {\n const { query, type = 'text', scope = {}, context: searchContext = {} } = context;\n\n const { paths = ['.'], fileTypes = [], excludePaths = [], maxResults = 50 } = scope;\n\n const { beforeLines = 2, afterLines = 2 } = searchContext;\n\n // Build command and arguments array safely\n const rgArgs: string[] = [];\n\n // Add context lines\n if (beforeLines > 0) {\n rgArgs.push('-B', beforeLines.toString());\n }\n if (afterLines > 0) {\n rgArgs.push('-A', afterLines.toString());\n }\n\n // Add line numbers\n rgArgs.push('-n');\n\n // Handle search type\n if (type === 'regex') {\n rgArgs.push('-e');\n } else if (type === 'fuzzy') {\n rgArgs.push('--fixed-strings');\n }\n\n // Add file type filters\n if (fileTypes.length > 0) {\n fileTypes.forEach(ft => {\n rgArgs.push('--type-add', `custom:*.${ft}`, '-t', 'custom');\n });\n }\n\n // Add exclude patterns\n excludePaths.forEach(path => {\n rgArgs.push('--glob', `!${path}`);\n });\n\n // Add max count\n rgArgs.push('-m', maxResults.toString());\n\n // Add the search query and paths\n rgArgs.push(query);\n rgArgs.push(...paths);\n\n // Execute safely using execFile\n const { stdout } = await execFile('rg', rgArgs, {\n cwd: projectPath,\n });\n const lines = stdout.split('\\n').filter((line: string) => line.trim());\n\n const matches: Array<{\n file: string;\n line: number;\n column?: number;\n match: string;\n context: { before: string[]; after: string[] };\n relevance?: number;\n }> = [];\n\n let currentMatch: any = null;\n\n lines.forEach((line: string) => {\n if (line.includes(':') && !line.startsWith('-')) {\n // This is a match line\n const parts = line.split(':');\n if (parts.length >= 3) {\n // Save previous match if exists\n if (currentMatch) {\n matches.push(currentMatch);\n }\n\n currentMatch = {\n file: parts[0] || '',\n line: parseInt(parts[1] || '0'),\n match: parts.slice(2).join(':'),\n context: { before: [], after: [] },\n relevance: type === 'fuzzy' ? Math.random() * 100 : undefined,\n };\n }\n } else if (line.startsWith('-') && currentMatch) {\n // This is a context line\n const contextLine = line.substring(1);\n if (currentMatch.context.before.length < beforeLines) {\n currentMatch.context.before.push(contextLine);\n } else {\n currentMatch.context.after.push(contextLine);\n }\n }\n });\n\n // Add the last match\n if (currentMatch) {\n matches.push(currentMatch);\n }\n\n // Count files searched (approximate)\n const filesSearched = new Set(matches.map(m => m.file)).size;\n\n return {\n success: true,\n matches: matches.slice(0, maxResults),\n summary: {\n totalMatches: matches.length,\n filesSearched,\n patterns: [query],\n },\n };\n } catch {\n return {\n success: false,\n matches: [],\n summary: {\n totalMatches: 0,\n filesSearched: 0,\n patterns: [context.query],\n },\n };\n }\n }\n\n // Static storage properties\n private static taskStorage: Map<string, any[]>;\n private static pendingQuestions: Map<string, any>;\n\n /**\n * Read file contents with optional line range\n */\n static async readFile(context: {\n filePath: string;\n startLine?: number;\n endLine?: number;\n encoding?: string;\n projectPath?: string;\n }) {\n try {\n const { filePath, startLine, endLine, encoding = 'utf-8', projectPath } = context;\n\n // Resolve path relative to project directory if it's not absolute\n const resolvedPath = isAbsolute(filePath) ? filePath : resolve(projectPath || process.cwd(), filePath);\n\n const stats = await stat(resolvedPath);\n const content = await readFile(resolvedPath, { encoding: encoding as BufferEncoding });\n const lines = content.split('\\n');\n\n let resultContent = content;\n let resultLines = lines;\n\n if (startLine !== undefined || endLine !== undefined) {\n const start = Math.max(0, (startLine || 1) - 1);\n const end = endLine !== undefined ? Math.min(lines.length, endLine) : lines.length;\n resultLines = lines.slice(start, end);\n resultContent = resultLines.join('\\n');\n }\n\n return {\n success: true,\n content: resultContent,\n lines: resultLines,\n metadata: {\n size: stats.size,\n totalLines: lines.length,\n encoding,\n lastModified: stats.mtime.toISOString(),\n },\n };\n } catch (error) {\n return {\n success: false,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Write content to file with directory creation and backup options\n */\n static async writeFile(context: {\n filePath: string;\n content: string;\n createDirs?: boolean;\n encoding?: string;\n projectPath?: string;\n }) {\n try {\n const { filePath, content, createDirs = true, encoding = 'utf-8', projectPath } = context;\n\n // Resolve path relative to project directory if it's not absolute\n const resolvedPath = isAbsolute(filePath) ? filePath : resolve(projectPath || process.cwd(), filePath);\n const dir = dirname(resolvedPath);\n\n // Create directories if needed\n if (createDirs) {\n await mkdir(dir, { recursive: true });\n }\n\n // Write the file\n await writeFile(resolvedPath, content, { encoding: encoding as BufferEncoding });\n\n return {\n success: true,\n filePath: resolvedPath,\n bytesWritten: Buffer.byteLength(content, encoding as BufferEncoding),\n message: `Successfully wrote ${Buffer.byteLength(content, encoding as BufferEncoding)} bytes to ${filePath}`,\n };\n } catch (error) {\n return {\n success: false,\n filePath: context.filePath,\n message: `Failed to write file: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * List directory contents with filtering and metadata\n */\n static async listDirectory(context: {\n path: string;\n recursive?: boolean;\n includeHidden?: boolean;\n pattern?: string;\n maxDepth?: number;\n includeMetadata?: boolean;\n projectPath?: string;\n }) {\n try {\n const {\n path,\n recursive = false,\n includeHidden = false,\n pattern,\n maxDepth = 10,\n includeMetadata = true,\n projectPath,\n } = context;\n\n const gitignorePath = join(projectPath || process.cwd(), '.gitignore');\n let gitignoreFilter: ignore.Ignore | undefined;\n\n try {\n const gitignoreContent = await readFile(gitignorePath, 'utf-8');\n gitignoreFilter = ignore().add(gitignoreContent);\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n console.error(`Error reading .gitignore file:`, err);\n }\n // If .gitignore doesn't exist, gitignoreFilter remains undefined, meaning no files are ignored by gitignore.\n }\n\n // Resolve path relative to project directory if it's not absolute\n const resolvedPath = isAbsolute(path) ? path : resolve(projectPath || process.cwd(), path);\n\n const items: Array<{\n name: string;\n path: string;\n type: 'file' | 'directory' | 'symlink';\n size?: number;\n lastModified?: string;\n permissions?: string;\n }> = [];\n\n async function processDirectory(dirPath: string, currentDepth: number = 0) {\n const relativeToProject = relative(projectPath || process.cwd(), dirPath);\n if (gitignoreFilter?.ignores(relativeToProject)) return;\n if (currentDepth > maxDepth) return;\n\n const entries = await readdir(dirPath);\n\n for (const entry of entries) {\n const entryPath = join(dirPath, entry);\n const relativeEntryPath = relative(projectPath || process.cwd(), entryPath);\n if (gitignoreFilter?.ignores(relativeEntryPath)) continue;\n if (!includeHidden && entry.startsWith('.')) continue;\n\n const fullPath = entryPath;\n const relativePath = relative(resolvedPath, fullPath);\n\n if (pattern) {\n // Simple pattern matching\n const regexPattern = pattern.replace(/\\*/g, '.*').replace(/\\?/g, '.');\n if (!new RegExp(regexPattern).test(entry)) continue;\n }\n\n let stats;\n let type: 'file' | 'directory' | 'symlink';\n\n try {\n stats = await stat(fullPath);\n if (stats.isDirectory()) {\n type = 'directory';\n } else if (stats.isSymbolicLink()) {\n type = 'symlink';\n } else {\n type = 'file';\n }\n } catch {\n continue; // Skip entries we can't stat\n }\n\n const item: any = {\n name: entry,\n path: relativePath || entry,\n type,\n };\n\n if (includeMetadata) {\n item.size = stats.size;\n item.lastModified = stats.mtime.toISOString();\n item.permissions = `0${(stats.mode & parseInt('777', 8)).toString(8)}`;\n }\n\n items.push(item);\n\n // Recurse into directories if requested\n if (recursive && type === 'directory') {\n await processDirectory(fullPath, currentDepth + 1);\n }\n }\n }\n\n await processDirectory(resolvedPath);\n\n return {\n success: true,\n items,\n totalItems: items.length,\n path: resolvedPath,\n message: `Listed ${items.length} items in ${resolvedPath}`,\n };\n } catch (error) {\n return {\n success: false,\n items: [],\n totalItems: 0,\n path: context.path,\n message: `Failed to list directory: ${error instanceof Error ? error.message : String(error)}`,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Execute shell commands with proper error handling\n */\n static async executeCommand(context: {\n command: string;\n workingDirectory?: string;\n timeout?: number;\n captureOutput?: boolean;\n shell?: string;\n env?: Record<string, string>;\n }) {\n const startTime = Date.now();\n try {\n const { command, workingDirectory, timeout = 30000, captureOutput = true, shell, env } = context;\n\n const execOptions: any = {\n timeout,\n env: { ...process.env, ...env },\n };\n\n if (workingDirectory) {\n execOptions.cwd = workingDirectory;\n }\n\n if (shell) {\n execOptions.shell = shell;\n }\n\n const { stdout, stderr } = await exec(command, execOptions);\n const executionTime = Date.now() - startTime;\n\n return {\n success: true,\n exitCode: 0,\n stdout: captureOutput ? String(stdout) : undefined,\n stderr: captureOutput ? String(stderr) : undefined,\n command,\n workingDirectory,\n executionTime,\n };\n } catch (error: any) {\n const executionTime = Date.now() - startTime;\n\n return {\n success: false,\n exitCode: error.code || 1,\n stdout: String(error.stdout || ''),\n stderr: String(error.stderr || ''),\n command: context.command,\n workingDirectory: context.workingDirectory,\n executionTime,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /**\n * Web search using a simple search approach\n */\n static async webSearch(context: {\n query: string;\n maxResults?: number;\n region?: string;\n language?: string;\n includeImages?: boolean;\n dateRange?: 'day' | 'week' | 'month' | 'year' | 'all';\n }) {\n try {\n const {\n query,\n maxResults = 10,\n // region = 'us',\n // language = 'en',\n // includeImages = false,\n // dateRange = 'all',\n } = context;\n\n const startTime = Date.now();\n\n // For now, implement a basic search using DuckDuckGo's instant answer API\n // In a real implementation, you'd want to use a proper search API\n const searchUrl = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&skip_disambig=1`;\n\n const response = await fetch(searchUrl);\n const data: any = await response.json();\n\n const results: Array<{\n title: string;\n url: string;\n snippet: string;\n domain: string;\n publishDate?: string;\n relevanceScore?: number;\n }> = [];\n\n // Parse DuckDuckGo results\n if (data.RelatedTopics && Array.isArray(data.RelatedTopics)) {\n for (const topic of data.RelatedTopics.slice(0, maxResults)) {\n if (topic.FirstURL && topic.Text) {\n const url = new URL(topic.FirstURL);\n results.push({\n title: topic.Text.split(' - ')[0] || topic.Text.substring(0, 60),\n url: topic.FirstURL,\n snippet: topic.Text,\n domain: url.hostname,\n relevanceScore: Math.random() * 100, // Placeholder scoring\n });\n }\n }\n }\n\n // Add abstract as first result if available\n if (data.Abstract && data.AbstractURL) {\n const url = new URL(data.AbstractURL);\n results.unshift({\n title: data.Heading || 'Main Result',\n url: data.AbstractURL,\n snippet: data.Abstract,\n domain: url.hostname,\n relevanceScore: 100,\n });\n }\n\n const searchTime = Date.now() - startTime;\n\n return {\n success: true,\n query,\n results: results.slice(0, maxResults),\n totalResults: results.length,\n searchTime,\n suggestions:\n data.RelatedTopics?.slice(maxResults, maxResults + 3)\n ?.map((t: any) => t.Text?.split(' - ')[0] || t.Text?.substring(0, 30))\n .filter(Boolean) || [],\n };\n } catch (error) {\n return {\n success: false,\n query: context.query,\n results: [],\n totalResults: 0,\n searchTime: 0,\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n }\n}\n","import { Agent } from '@mastra/core/agent';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport type { Processor } from '@mastra/core/processors';\n\n/**\n * Summarizes tool calls and caches results to avoid re-summarizing identical calls\n */\nexport class ToolSummaryProcessor implements Processor {\n readonly id = 'tool-summary-processor';\n readonly name = 'ToolSummaryProcessor';\n\n private summaryAgent: Agent;\n private summaryCache: Map<string, string> = new Map();\n\n constructor({ summaryModel }: { summaryModel: MastraModelConfig }) {\n this.summaryAgent = new Agent({\n id: 'tool-summary-agent',\n name: 'Tool Summary Agent',\n description: 'A summary agent that summarizes tool calls and results',\n instructions: 'You are a summary agent that summarizes tool calls and results',\n model: summaryModel,\n });\n }\n\n /**\n * Creates a cache key from tool call arguments\n */\n public createCacheKey(toolCall: any): string {\n if (!toolCall) return 'unknown';\n\n // Create a deterministic key from tool name and arguments\n const toolName = toolCall.toolName || 'unknown';\n const args = toolCall.args || {};\n\n // Sort keys for consistent hashing\n const sortedArgs = Object.keys(args)\n .sort()\n .reduce((result: Record<string, any>, key) => {\n result[key] = args[key];\n return result;\n }, {});\n\n return `${toolName}:${JSON.stringify(sortedArgs)}`;\n }\n\n /**\n * Clears the summary cache\n */\n public clearCache(): void {\n this.summaryCache.clear();\n }\n\n /**\n * Gets cache statistics\n */\n public getCacheStats(): { size: number; keys: string[] } {\n return {\n size: this.summaryCache.size,\n keys: Array.from(this.summaryCache.keys()),\n };\n }\n\n async processInput({\n messages,\n messageList: _messageList,\n }: {\n messages: MastraDBMessage[];\n messageList: MessageList;\n abort: (reason?: string) => never;\n }): Promise<MastraDBMessage[]> {\n // Collect all tool calls that need summarization\n const summaryTasks: Array<{\n message: MastraDBMessage;\n partIndex: number;\n promise: Promise<any>;\n cacheKey: string;\n }> = [];\n\n // First pass: collect all tool results that need summarization\n for (const message of messages) {\n if (message.content.format === 2 && message.content.parts) {\n for (let partIndex = 0; partIndex < message.content.parts.length; partIndex++) {\n const part = message.content.parts[partIndex];\n\n // Check if this is a tool invocation with a result\n if (part && part.type === 'tool-invocation' && part.toolInvocation?.state === 'result') {\n const cacheKey = this.createCacheKey(part.toolInvocation);\n const cachedSummary = this.summaryCache.get(cacheKey);\n\n if (cachedSummary) {\n // Use cached summary - update the tool invocation result\n message.content.parts[partIndex] = {\n type: 'tool-invocation',\n toolInvocation: {\n state: 'result',\n step: part.toolInvocation.step,\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n result: `Tool call summary: ${cachedSummary}`,\n },\n };\n } else {\n // Create a promise for this summary (but don't await yet)\n const summaryPromise = this.summaryAgent.generate(\n `Summarize the following tool call: ${JSON.stringify(part.toolInvocation)}`,\n );\n\n summaryTasks.push({\n message,\n partIndex,\n promise: summaryPromise,\n cacheKey,\n });\n }\n }\n }\n }\n }\n\n // Execute all non-cached summaries in parallel\n if (summaryTasks.length > 0) {\n const summaryResults = await Promise.allSettled(summaryTasks.map(task => task.promise));\n\n // Apply the results back to the content and cache them\n summaryTasks.forEach((task, index) => {\n const result = summaryResults[index];\n if (!result) return;\n\n if (result.status === 'fulfilled') {\n const summaryResult = result.value;\n const summaryText = summaryResult.text;\n\n // Cache the summary for future use\n this.summaryCache.set(task.cacheKey, summaryText);\n\n // Apply to message content\n if (task.message.content.format === 2 && task.message.content.parts) {\n const part = task.message.content.parts[task.partIndex];\n if (part && part.type === 'tool-invocation' && part.toolInvocation?.state === 'result') {\n task.message.content.parts[task.partIndex] = {\n type: 'tool-invocation',\n toolInvocation: {\n state: 'result',\n step: part.toolInvocation.step,\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n result: `Tool call summary: ${summaryText}`,\n },\n };\n }\n }\n } else if (result.status === 'rejected') {\n // Handle failed summary - use fallback or log error\n console.warn(`Failed to generate summary for tool call:`, result.reason);\n }\n });\n }\n\n return messages;\n }\n}\n","import { Agent } from '@mastra/core/agent';\nimport type {\n AiMessageType,\n AgentGenerateOptions,\n AgentStreamOptions,\n AgentExecutionOptions,\n AgentExecutionOptionsBase,\n ToolsInput,\n AgentConfig,\n PublicStructuredOutputOptions,\n} from '@mastra/core/agent';\nimport type { MessageListInput } from '@mastra/core/agent/message-list';\nimport type { CoreMessage } from '@mastra/core/llm';\nimport { InMemoryStore } from '@mastra/core/storage';\nimport type { MastraModelOutput, FullOutput } from '@mastra/core/stream';\nimport { Memory } from '@mastra/memory';\nimport type { InferStandardSchemaOutput, StandardSchemaWithJSON } from '@mastra/schema-compat/schema';\nimport { AgentBuilderDefaults } from '../defaults';\nimport { ToolSummaryProcessor } from '../processors/tool-summary';\nimport type { AgentBuilderConfig, GenerateAgentOptions } from '../types';\n\n// =============================================================================\n// Template Merge Workflow Implementation\n// =============================================================================\n//\n// This workflow implements a comprehensive template merging system that:\n// 1. Clones template repositories at specific refs (tags/commits)\n// 2. Discovers units (agents, workflows, MCP servers/tools) in templates\n// 3. Topologically orders units based on dependencies\n// 4. Analyzes conflicts and creates safety classifications\n// 5. Applies changes with git branching and checkpoints per unit\n//\n// The workflow follows the \"auto-decide vs ask\" principles:\n// - Auto: adding new files, missing deps, appending arrays, new scripts with template:slug:* namespace\n// - Prompt: overwriting files, major upgrades, renaming conflicts, new ports, postInstall commands\n// - Block: removing files, downgrading deps, changing TS target/module, modifying CI/CD secrets\n//\n// Usage with Mastra templates (see https://mastra.ai/api/templates.json):\n// const run = await agentBuilderTemplateWorkflow.createRun();\n// const result = await run.start({\n// inputData: {\n// repo: 'https://github.com/mastra-ai/template-pdf-questions',\n// ref: 'main', // optional\n// targetPath: './my-project', // optional, defaults to cwd\n// }\n// });\n// // The workflow will automatically analyze and merge the template structure\n//\n// =============================================================================\n\nexport class AgentBuilder<TTools extends ToolsInput = ToolsInput, TOutput = undefined> extends Agent<\n 'agent-builder',\n TTools,\n TOutput\n> {\n private builderConfig: AgentBuilderConfig;\n\n /**\n * Constructor for AgentBuilder\n */\n constructor(config: AgentBuilderConfig) {\n const additionalInstructions = config.instructions ? `## Priority Instructions \\n\\n${config.instructions}` : '';\n const combinedInstructions = additionalInstructions + AgentBuilderDefaults.DEFAULT_INSTRUCTIONS(config.projectPath);\n\n // Create Memory with storage for AgentBuilder\n // Use provided storage if available, otherwise fall back to in-memory storage\n const memory = new Memory({\n options: AgentBuilderDefaults.DEFAULT_MEMORY_CONFIG,\n });\n memory.setStorage(config.storage ?? new InMemoryStore());\n\n const agentConfig: AgentConfig<'agent-builder', TTools, TOutput> = {\n id: 'agent-builder',\n name: 'agent-builder',\n description:\n 'An AI agent specialized in generating Mastra agents, tools, and workflows from natural language requirements.',\n instructions: combinedInstructions,\n model: config.model,\n tools: async (): Promise<TTools> => {\n return {\n ...(await AgentBuilderDefaults.listToolsForMode(config.projectPath, config.mode)),\n ...(config.tools || ({} as TTools)),\n } as TTools;\n },\n memory,\n inputProcessors: [\n // use the write to disk processor to debug the agent's context\n // new WriteToDiskProcessor({ prefix: 'before-filter' }),\n new ToolSummaryProcessor({ summaryModel: config.summaryModel || config.model }),\n // new WriteToDiskProcessor({ prefix: 'after-filter' }),\n ],\n };\n\n super(agentConfig);\n this.builderConfig = config;\n }\n\n /**\n * Enhanced generate method with AgentBuilder-specific configuration\n * Overrides the base Agent generate method to provide additional project context\n */\n generateLegacy: Agent['generateLegacy'] = async (\n messages: string | string[] | CoreMessage[] | AiMessageType[],\n generateOptions: (GenerateAgentOptions & AgentGenerateOptions<any, any>) | undefined = {},\n ): Promise<any> => {\n const { maxSteps, ...baseOptions } = generateOptions;\n\n const originalInstructions = await this.getInstructions({ requestContext: generateOptions?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n\n const enhancedContext = [...(baseOptions.context || [])];\n\n const enhancedOptions = {\n ...baseOptions,\n maxSteps: maxSteps || 100, // Higher default for code generation\n temperature: 0.3, // Lower temperature for more consistent code generation\n instructions: enhancedInstructions,\n context: enhancedContext,\n } satisfies AgentGenerateOptions<any, any>;\n\n this.logger.debug('Starting generation with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.generateLegacy(messages, enhancedOptions);\n };\n\n /**\n * Enhanced stream method with AgentBuilder-specific configuration\n * Overrides the base Agent stream method to provide additional project context\n */\n streamLegacy: Agent['streamLegacy'] = async (\n messages: string | string[] | CoreMessage[] | AiMessageType[],\n streamOptions: (GenerateAgentOptions & AgentStreamOptions<any, any>) | undefined = {},\n ): Promise<any> => {\n const { maxSteps, ...baseOptions } = streamOptions;\n\n const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n const enhancedContext = [...(baseOptions.context || [])];\n\n const enhancedOptions = {\n ...baseOptions,\n maxSteps: maxSteps || 100, // Higher default for code generation\n temperature: 0.3, // Lower temperature for more consistent code generation\n instructions: enhancedInstructions,\n context: enhancedContext,\n };\n\n this.logger.debug('Starting streaming with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.streamLegacy(messages, enhancedOptions);\n };\n\n /**\n * Enhanced stream method with AgentBuilder-specific configuration\n * Overrides the base Agent stream method to provide additional project context\n */\n async stream<\n OUTPUT extends StandardSchemaWithJSON<any, any>,\n T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>,\n >(\n messages: MessageListInput,\n streamOptions: AgentExecutionOptionsBase<T> & {\n structuredOutput: PublicStructuredOutputOptions<T>;\n },\n ): Promise<MastraModelOutput<T>>;\n async stream<OUTPUT extends {}>(\n messages: MessageListInput,\n streamOptions: AgentExecutionOptionsBase<OUTPUT> & {\n structuredOutput: PublicStructuredOutputOptions<OUTPUT>;\n },\n ): Promise<MastraModelOutput<OUTPUT>>;\n async stream(\n messages: MessageListInput,\n streamOptions: AgentExecutionOptionsBase<unknown> & {\n structuredOutput?: never;\n },\n ): Promise<MastraModelOutput<TOutput>>;\n async stream(messages: MessageListInput): Promise<MastraModelOutput<TOutput>>;\n async stream<OUTPUT = TOutput>(\n messages: MessageListInput,\n streamOptions?: AgentExecutionOptionsBase<any> & {\n structuredOutput?: PublicStructuredOutputOptions<any>;\n },\n ): Promise<MastraModelOutput<OUTPUT>> {\n const { ...baseOptions } = streamOptions || ({} as AgentExecutionOptions<OUTPUT>);\n\n const originalInstructions = await this.getInstructions({ requestContext: streamOptions?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n const enhancedContext = [...(baseOptions.context || ([] as AgentExecutionOptions<OUTPUT>['context'][]))];\n\n const enhancedOptions = {\n ...baseOptions,\n temperature: 0.3, // Lower temperature for more consistent code generation\n maxSteps: baseOptions?.maxSteps || 100,\n instructions: enhancedInstructions,\n context: enhancedContext,\n } as any;\n\n this.logger.debug('Starting streaming with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.stream(messages, enhancedOptions);\n }\n\n async generate<\n OUTPUT extends StandardSchemaWithJSON<any, any>,\n T extends InferStandardSchemaOutput<OUTPUT> = InferStandardSchemaOutput<OUTPUT>,\n >(\n messages: MessageListInput,\n options: AgentExecutionOptionsBase<T> & {\n structuredOutput: PublicStructuredOutputOptions<T>;\n },\n ): Promise<FullOutput<T>>;\n async generate<OUTPUT extends {}>(\n messages: MessageListInput,\n options: AgentExecutionOptionsBase<OUTPUT> & {\n structuredOutput: PublicStructuredOutputOptions<OUTPUT>;\n },\n ): Promise<FullOutput<OUTPUT>>;\n async generate(\n messages: MessageListInput,\n options: AgentExecutionOptionsBase<unknown> & {\n structuredOutput?: never;\n },\n ): Promise<FullOutput<TOutput>>;\n async generate<OUTPUT = TOutput>(messages: MessageListInput): Promise<FullOutput<OUTPUT>>;\n async generate<OUTPUT = TOutput>(\n messages: MessageListInput,\n options?: AgentExecutionOptionsBase<any> & {\n structuredOutput?: PublicStructuredOutputOptions<any>;\n },\n ): Promise<FullOutput<OUTPUT>> {\n const { ...baseOptions } = options || {};\n\n const originalInstructions = await this.getInstructions({ requestContext: options?.requestContext });\n const additionalInstructions = baseOptions.instructions;\n\n let enhancedInstructions = originalInstructions as string;\n if (additionalInstructions) {\n enhancedInstructions = `${originalInstructions}\\n\\n${additionalInstructions}`;\n }\n const enhancedContext = [...(baseOptions.context || [])];\n\n const enhancedOptions = {\n ...baseOptions,\n temperature: 0.3, // Lower temperature for more consistent code generation\n maxSteps: baseOptions?.maxSteps || 100,\n instructions: enhancedInstructions,\n context: enhancedContext,\n } as any;\n\n this.logger.debug('Starting generation with enhanced context', {\n agent: this.name,\n projectPath: this.builderConfig.projectPath,\n });\n\n return super.generate(messages, enhancedOptions);\n }\n}\n","import { existsSync } from 'node:fs';\nimport { mkdtemp, copyFile, readFile, mkdir, readdir, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join, dirname, resolve, extname, basename } from 'node:path';\nimport { openai } from '@ai-sdk/openai';\nimport {\n Agent,\n tryGenerateWithJsonFallback,\n tryStreamWithJsonFallback,\n isSupportedLanguageModel,\n} from '@mastra/core/agent';\nimport { toStandardSchema } from '@mastra/core/schema';\nimport type { FullOutput } from '@mastra/core/stream';\nimport { createTool } from '@mastra/core/tools';\nimport { createWorkflow, createStep } from '@mastra/core/workflows';\nimport { standardSchemaToJSONSchema } from '@mastra/schema-compat/schema';\nimport { z } from 'zod';\nimport { AgentBuilder } from '../..';\nimport { AgentBuilderDefaults } from '../../defaults';\nimport type { TemplateUnit, UnitKind } from '../../types';\nimport {\n ApplyResultSchema,\n AgentBuilderInputSchema,\n CloneTemplateResultSchema,\n PackageAnalysisSchema,\n DiscoveryResultSchema,\n OrderedUnitsSchema,\n PackageMergeInputSchema,\n PackageMergeResultSchema,\n InstallInputSchema,\n InstallResultSchema,\n FileCopyInputSchema,\n FileCopyResultSchema,\n IntelligentMergeInputSchema,\n IntelligentMergeResultSchema,\n ValidationFixInputSchema,\n ValidationFixResultSchema,\n PrepareBranchInputSchema,\n PrepareBranchResultSchema,\n} from '../../types';\nimport {\n getMastraTemplate,\n kindWeight,\n spawnSWPM,\n logGitState,\n backupAndReplaceFile,\n renameAndCopyFile,\n gitCheckoutBranch,\n gitClone,\n gitCheckoutRef,\n gitRevParse,\n gitAddAndCommit,\n resolveTargetPath,\n mergeGitignoreFiles,\n mergeEnvFiles,\n resolveModel,\n} from '../../utils';\n\ntype AgentBuilderInputSchemaType = z.infer<typeof AgentBuilderInputSchema>;\n\n// Step 1: Clone template to temp directory\nconst cloneTemplateStep = createStep({\n id: 'clone-template',\n description: 'Clone the template repository to a temporary directory at the specified ref',\n inputSchema: AgentBuilderInputSchema,\n outputSchema: CloneTemplateResultSchema,\n execute: async ({ inputData }) => {\n const { repo, ref = 'main', slug, targetPath } = inputData;\n\n if (!repo) {\n throw new Error('Repository URL or path is required');\n }\n\n // Extract slug from repo URL if not provided\n const inferredSlug =\n slug ||\n repo\n .split('/')\n .pop()\n ?.replace(/\\.git$/, '') ||\n 'template';\n\n // Create temporary directory\n const tempDir = await mkdtemp(join(tmpdir(), 'mastra-template-'));\n\n try {\n // Clone repository\n await gitClone(repo, tempDir);\n\n // Checkout specific ref if provided\n if (ref !== 'main' && ref !== 'master') {\n await gitCheckoutRef(tempDir, ref);\n }\n\n // Get commit SHA\n const commitSha = await gitRevParse(tempDir, 'HEAD');\n\n return {\n templateDir: tempDir,\n commitSha: commitSha.trim(),\n slug: inferredSlug,\n success: true,\n targetPath,\n };\n } catch (error) {\n // Cleanup on error\n try {\n await rm(tempDir, { recursive: true, force: true });\n } catch {}\n\n return {\n templateDir: '',\n commitSha: '',\n slug: slug || 'unknown',\n success: false,\n error: `Failed to clone template: ${error instanceof Error ? error.message : String(error)}`,\n targetPath,\n };\n }\n },\n});\n\n// Step 2: Analyze template package.json for dependencies\nconst analyzePackageStep = createStep({\n id: 'analyze-package',\n description: 'Analyze the template package.json to extract dependency information',\n inputSchema: CloneTemplateResultSchema,\n outputSchema: PackageAnalysisSchema,\n execute: async ({ inputData }) => {\n console.info('Analyzing template package.json...');\n const { templateDir } = inputData;\n const packageJsonPath = join(templateDir, 'package.json');\n\n try {\n const packageJsonContent = await readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageJsonContent);\n\n console.info('Template package.json:', JSON.stringify(packageJson, null, 2));\n\n return {\n dependencies: packageJson.dependencies || {},\n devDependencies: packageJson.devDependencies || {},\n peerDependencies: packageJson.peerDependencies || {},\n scripts: packageJson.scripts || {},\n name: packageJson.name || '',\n version: packageJson.version || '',\n description: packageJson.description || '',\n success: true,\n };\n } catch (error) {\n console.warn(`Failed to read template package.json: ${error instanceof Error ? error.message : String(error)}`);\n return {\n dependencies: {},\n devDependencies: {},\n peerDependencies: {},\n scripts: {},\n name: '',\n version: '',\n description: '',\n success: true, // This is a graceful fallback, not a failure\n };\n }\n },\n});\n\n// Step 3: Discover template units by scanning the templates directory\nconst discoverUnitsStep = createStep({\n id: 'discover-units',\n description: 'Discover template units by analyzing the templates directory structure',\n inputSchema: CloneTemplateResultSchema,\n outputSchema: DiscoveryResultSchema,\n execute: async ({ inputData, requestContext }) => {\n const { templateDir } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n const tools = await AgentBuilderDefaults.DEFAULT_TOOLS(templateDir);\n\n console.info('targetPath', targetPath);\n\n const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai('gpt-4.1') });\n\n try {\n const agent = new Agent({\n id: 'mastra-project-discoverer',\n model,\n instructions: `You are an expert at analyzing Mastra projects.\n\nYour task is to scan the provided directory and identify all available units (agents, workflows, tools, MCP servers, networks).\n\nMastra Project Structure Analysis:\n- Each Mastra project has a structure like: ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.agent}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.workflow}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE['mcp-server']}, ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.network}\n- Analyze TypeScript files in each category directory to identify exported units\n\nCRITICAL: YOU MUST USE YOUR TOOLS (readFile, listDirectory) TO DISCOVER THE UNITS IN THE TEMPLATE DIRECTORY.\n\nIMPORTANT - Agent Discovery Rules:\n1. **Multiple Agent Files**: Some templates have separate files for each agent (e.g., evaluationAgent.ts, researchAgent.ts)\n2. **Single File Multiple Agents**: Some files may export multiple agents (look for multiple 'export const' or 'export default' statements)\n3. **Agent Identification**: Look for exported variables that are instances of 'new Agent()' or similar patterns\n4. **Naming Convention**: Agent names should be extracted from the export name (e.g., 'weatherAgent', 'evaluationAgent')\n\nFor each Mastra project directory you analyze:\n1. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.agent} and identify ALL exported agents\n2. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.workflow} and identify ALL exported workflows\n3. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool} and identify ALL exported tools\n4. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE['mcp-server']} and identify ALL exported MCP servers\n5. Scan all TypeScript files in ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.network} and identify ALL exported networks\n6. Scan for any OTHER files in src/mastra that are NOT in the above default folders (e.g., lib/, utils/, types/, etc.) and identify them as 'other' files\n\nIMPORTANT - Naming Consistency Rules:\n- For ALL unit types (including 'other'), the 'name' field should be the filename WITHOUT extension\n- For structured units (agents, workflows, tools, etc.), prefer the actual export name if clearly identifiable\n- use the base filename without extension for the id (e.g., 'util.ts' → name: 'util')\n- use the relative path from the template root for the file (e.g., 'src/mastra/lib/util.ts' → file: 'src/mastra/lib/util.ts')\n\nReturn the actual exported names of the units, as well as the file names.`,\n name: 'Mastra Project Discoverer',\n tools: {\n readFile: tools.readFile,\n listDirectory: tools.listDirectory,\n },\n });\n\n const resolvedModel = await agent.getModel();\n const isSupported = isSupportedLanguageModel(resolvedModel);\n\n const prompt = `Analyze the Mastra project directory structure at \"${templateDir}\".\n\n List directory contents using listDirectory tool, and then analyze each file with readFile tool.\n IMPORTANT:\n - Look inside the actual file content to find export statements like 'export const agentName = new Agent(...)'\n - A single file may contain multiple exports\n - Return the actual exported variable names, as well as the file names\n - If a directory doesn't exist or has no files, return an empty array\n\n Return the analysis in the exact format specified in the output schema.`;\n\n const output = z.object({\n agents: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n workflows: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n tools: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n mcp: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n networks: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n other: z.array(z.object({ name: z.string(), file: z.string() })).optional(),\n });\n\n let result: FullOutput<z.infer<typeof output>>;\n if (isSupported) {\n result = await tryGenerateWithJsonFallback(agent, prompt, {\n structuredOutput: {\n schema: output,\n },\n maxSteps: 100,\n });\n } else {\n const standardSchema = toStandardSchema(output);\n const jsonSchema = standardSchemaToJSONSchema(standardSchema);\n\n result = (await agent.generateLegacy(prompt, {\n experimental_output: jsonSchema,\n maxSteps: 100,\n })) as unknown as FullOutput<z.infer<typeof output>>;\n }\n\n const template = result.object ?? {};\n\n const units: TemplateUnit[] = [];\n\n // Add agents\n template.agents?.forEach((agentId: { name: string; file: string }) => {\n units.push({ kind: 'agent', id: agentId.name, file: agentId.file });\n });\n\n // Add workflows\n template.workflows?.forEach((workflowId: { name: string; file: string }) => {\n units.push({ kind: 'workflow', id: workflowId.name, file: workflowId.file });\n });\n\n // Add tools\n template.tools?.forEach((toolId: { name: string; file: string }) => {\n units.push({ kind: 'tool', id: toolId.name, file: toolId.file });\n });\n\n // Add MCP servers\n template.mcp?.forEach((mcpId: { name: string; file: string }) => {\n units.push({ kind: 'mcp-server', id: mcpId.name, file: mcpId.file });\n });\n\n // Add networks\n template.networks?.forEach((networkId: { name: string; file: string }) => {\n units.push({ kind: 'network', id: networkId.name, file: networkId.file });\n });\n\n // Add other files\n template.other?.forEach((otherId: { name: string; file: string }) => {\n units.push({ kind: 'other', id: otherId.name, file: otherId.file });\n });\n\n console.info('Discovered units:', JSON.stringify(units, null, 2));\n\n if (units.length === 0) {\n throw new Error(`No Mastra units (agents, workflows, tools) found in template.\n Possible causes:\n - Template may not follow standard Mastra structure\n - AI agent couldn't analyze template files (model/token limits)\n - Template is empty or in wrong branch\n\n Debug steps:\n - Check template has files in src/mastra/ directories\n - Try a different branch\n - Check template repository structure manually`);\n }\n\n return {\n units,\n success: true,\n };\n } catch (error) {\n console.error('Failed to discover units:', error);\n return {\n units: [],\n success: false,\n error: `Failed to discover units: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n});\n\n// Step 4: Topological ordering (simplified)\nconst orderUnitsStep = createStep({\n id: 'order-units',\n description: 'Sort units in topological order based on kind weights',\n inputSchema: DiscoveryResultSchema,\n outputSchema: OrderedUnitsSchema,\n execute: async ({ inputData }) => {\n const { units } = inputData;\n\n // Simple sort by kind weight (mcp-servers first, then tools, agents, workflows, integration last)\n const orderedUnits = [...units].sort((a, b) => {\n const aWeight = kindWeight(a.kind);\n const bWeight = kindWeight(b.kind);\n return aWeight - bWeight;\n });\n\n return {\n orderedUnits,\n success: true,\n };\n },\n});\n\n// Step 5: Prepare branch\nconst prepareBranchStep = createStep({\n id: 'prepare-branch',\n description: 'Create or switch to integration branch before modifications',\n inputSchema: PrepareBranchInputSchema,\n outputSchema: PrepareBranchResultSchema,\n execute: async ({ inputData, requestContext }) => {\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n const branchName = `feat/install-template-${inputData.slug}`;\n await gitCheckoutBranch(branchName, targetPath);\n\n return {\n branchName,\n success: true,\n };\n } catch (error) {\n console.error('Failed to prepare branch:', error);\n return {\n branchName: `feat/install-template-${inputData.slug}`, // Return the intended name anyway\n success: false,\n error: `Failed to prepare branch: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n },\n});\n\n// Step 6: Package merge\nconst packageMergeStep = createStep({\n id: 'package-merge',\n description: 'Merge template package.json dependencies into target project',\n inputSchema: PackageMergeInputSchema,\n outputSchema: PackageMergeResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Package merge step starting...');\n const { slug, packageInfo } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n const targetPkgPath = join(targetPath, 'package.json');\n\n let targetPkgRaw = '{}';\n try {\n targetPkgRaw = await readFile(targetPkgPath, 'utf-8');\n } catch {\n console.warn(`No existing package.json at ${targetPkgPath}, creating a new one`);\n }\n\n let targetPkg: any;\n try {\n targetPkg = JSON.parse(targetPkgRaw || '{}');\n } catch (e) {\n throw new Error(\n `Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n\n const ensureObj = (o: any) => (o && typeof o === 'object' ? o : {});\n\n targetPkg.dependencies = ensureObj(targetPkg.dependencies);\n targetPkg.devDependencies = ensureObj(targetPkg.devDependencies);\n targetPkg.peerDependencies = ensureObj(targetPkg.peerDependencies);\n targetPkg.scripts = ensureObj(targetPkg.scripts);\n\n const tplDeps = ensureObj(packageInfo.dependencies);\n const tplDevDeps = ensureObj(packageInfo.devDependencies);\n const tplPeerDeps = ensureObj(packageInfo.peerDependencies);\n const tplScripts = ensureObj(packageInfo.scripts);\n\n const existsAnywhere = (name: string) =>\n name in targetPkg.dependencies || name in targetPkg.devDependencies || name in targetPkg.peerDependencies;\n\n // Merge dependencies: add only if missing everywhere\n for (const [name, ver] of Object.entries(tplDeps)) {\n if (!existsAnywhere(name)) {\n (targetPkg.dependencies as Record<string, string>)[name] = String(ver);\n }\n }\n\n // Merge devDependencies\n for (const [name, ver] of Object.entries(tplDevDeps)) {\n if (!existsAnywhere(name)) {\n (targetPkg.devDependencies as Record<string, string>)[name] = String(ver);\n }\n }\n\n // Merge peerDependencies\n for (const [name, ver] of Object.entries(tplPeerDeps)) {\n if (!(name in targetPkg.peerDependencies)) {\n (targetPkg.peerDependencies as Record<string, string>)[name] = String(ver);\n }\n }\n\n // Merge scripts with prefixed keys to avoid collisions\n const prefix = `template:${slug}:`;\n for (const [name, cmd] of Object.entries(tplScripts)) {\n const newKey = `${prefix}${name}`;\n if (!(newKey in targetPkg.scripts)) {\n (targetPkg.scripts as Record<string, string>)[newKey] = String(cmd);\n }\n }\n\n await writeFile(targetPkgPath, JSON.stringify(targetPkg, null, 2), 'utf-8');\n\n await gitAddAndCommit(targetPath, `feat(template): merge deps for ${slug}`, [targetPkgPath], {\n skipIfNoStaged: true,\n });\n\n return {\n success: true,\n applied: true,\n message: `Successfully merged template dependencies for ${slug}`,\n };\n } catch (error) {\n console.error('Package merge failed:', error);\n return {\n success: false,\n applied: false,\n message: `Package merge failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 7: Install\nconst installStep = createStep({\n id: 'install',\n description: 'Install packages based on merged package.json',\n inputSchema: InstallInputSchema,\n outputSchema: InstallResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Running install step...');\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n // Run install using swpm (no specific packages)\n await spawnSWPM(targetPath, 'install', []);\n\n const lock = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock']\n .map(f => join(targetPath, f))\n .find(f => existsSync(f));\n\n if (lock) {\n await gitAddAndCommit(targetPath, `chore(template): commit lockfile after install`, [lock], {\n skipIfNoStaged: true,\n });\n }\n\n return {\n success: true,\n };\n } catch (error) {\n console.error('Install failed:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 7: Programmatic File Copy Step - copies template files to target project\nconst programmaticFileCopyStep = createStep({\n id: 'programmatic-file-copy',\n description: 'Programmatically copy template files to target project based on ordered units',\n inputSchema: FileCopyInputSchema,\n outputSchema: FileCopyResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Programmatic file copy step starting...');\n const { orderedUnits, templateDir, commitSha, slug } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n try {\n const copiedFiles: Array<{\n source: string;\n destination: string;\n unit: { kind: UnitKind; id: string };\n }> = [];\n\n const conflicts: Array<{\n unit: { kind: UnitKind; id: string };\n issue: string;\n sourceFile: string;\n targetFile: string;\n }> = [];\n\n // Analyze target project naming convention first\n const analyzeNamingConvention = async (\n directory: string,\n ): Promise<'camelCase' | 'snake_case' | 'kebab-case' | 'PascalCase' | 'unknown'> => {\n try {\n const files = await readdir(resolve(targetPath, directory), { withFileTypes: true });\n const tsFiles = files.filter(f => f.isFile() && f.name.endsWith('.ts')).map(f => f.name);\n\n if (tsFiles.length === 0) return 'unknown';\n\n // Check for patterns\n const camelCaseCount = tsFiles.filter(f => /^[a-z][a-zA-Z0-9]*\\.ts$/.test(f)).length;\n const snakeCaseCount = tsFiles.filter(f => /^[a-z][a-z0-9_]*\\.ts$/.test(f) && f.includes('_')).length;\n const kebabCaseCount = tsFiles.filter(f => /^[a-z][a-z0-9-]*\\.ts$/.test(f) && f.includes('-')).length;\n const pascalCaseCount = tsFiles.filter(f => /^[A-Z][a-zA-Z0-9]*\\.ts$/.test(f)).length;\n\n const max = Math.max(camelCaseCount, snakeCaseCount, kebabCaseCount, pascalCaseCount);\n if (max === 0) return 'unknown';\n\n if (camelCaseCount === max) return 'camelCase';\n if (snakeCaseCount === max) return 'snake_case';\n if (kebabCaseCount === max) return 'kebab-case';\n if (pascalCaseCount === max) return 'PascalCase';\n\n return 'unknown';\n } catch {\n return 'unknown';\n }\n };\n\n // Convert naming based on convention\n const convertNaming = (name: string, convention: string): string => {\n const baseName = basename(name, extname(name));\n const ext = extname(name);\n\n // Helper: split a name into words by hyphens, underscores, or camelCase boundaries\n const toWords = (s: string): string[] => {\n return (\n s\n .replace(/[-_]/g, ' ')\n // split \"HTTPServer\" -> \"HTTP Server\"\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .split(/\\s+/)\n .filter(Boolean)\n .map(w => w.toLowerCase())\n );\n };\n\n const words = toWords(baseName);\n\n switch (convention) {\n case 'camelCase':\n return words.map((w, i) => (i === 0 ? w : w.charAt(0).toUpperCase() + w.slice(1))).join('') + ext;\n case 'snake_case':\n return words.join('_') + ext;\n case 'kebab-case':\n return words.join('-') + ext;\n case 'PascalCase':\n return words.map(w => w.charAt(0).toUpperCase() + w.slice(1)).join('') + ext;\n default:\n return name;\n }\n };\n\n // Process each unit\n for (const unit of orderedUnits) {\n console.info(`Processing ${unit.kind} unit \"${unit.id}\" from file \"${unit.file}\"`);\n\n // Resolve source file path with fallback logic\n let sourceFile: string;\n let resolvedUnitFile: string;\n\n // Check if unit.file already contains directory structure\n if (unit.file.includes('/')) {\n // unit.file has path structure (e.g., \"src/mastra/agents/weatherAgent.ts\")\n sourceFile = resolve(templateDir, unit.file);\n resolvedUnitFile = unit.file;\n } else {\n // unit.file is just filename (e.g., \"weatherAgent.ts\") - use fallback\n const folderPath =\n AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE[\n unit.kind as keyof typeof AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE\n ];\n if (!folderPath) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Unknown unit kind: ${unit.kind}`,\n sourceFile: unit.file,\n targetFile: 'N/A',\n });\n continue;\n }\n resolvedUnitFile = `${folderPath}/${unit.file}`;\n sourceFile = resolve(templateDir, resolvedUnitFile);\n }\n\n // Check if source file exists\n if (!existsSync(sourceFile)) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Source file not found: ${sourceFile}`,\n sourceFile: resolvedUnitFile,\n targetFile: 'N/A',\n });\n continue;\n }\n\n // Extract target directory from resolved unit file path\n const targetDir = dirname(resolvedUnitFile);\n\n // Analyze target naming convention\n const namingConvention = await analyzeNamingConvention(targetDir);\n console.info(`Detected naming convention in ${targetDir}: ${namingConvention}`);\n\n // Convert unit.id to target filename with proper extension\n // Note: Check if unit.id already includes extension to avoid double extensions\n const hasExtension = extname(unit.id) !== '';\n const baseId = hasExtension ? basename(unit.id, extname(unit.id)) : unit.id;\n const fileExtension = extname(unit.file);\n const convertedFileName =\n namingConvention !== 'unknown'\n ? convertNaming(baseId + fileExtension, namingConvention)\n : baseId + fileExtension;\n\n const targetFile = resolve(targetPath, targetDir, convertedFileName);\n\n // Handle file conflicts with strategy-based resolution\n if (existsSync(targetFile)) {\n const strategy = determineConflictStrategy(unit, targetFile);\n console.info(`File exists: ${convertedFileName}, using strategy: ${strategy}`);\n\n switch (strategy) {\n case 'skip':\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `File exists - skipped: ${convertedFileName}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n console.info(`⏭️ Skipped ${unit.kind} \"${unit.id}\": file already exists`);\n continue;\n\n case 'backup-and-replace':\n try {\n await backupAndReplaceFile(sourceFile, targetFile);\n copiedFiles.push({\n source: sourceFile,\n destination: targetFile,\n unit: { kind: unit.kind, id: unit.id },\n });\n console.info(\n `🔄 Replaced ${unit.kind} \"${unit.id}\": ${unit.file} → ${convertedFileName} (backup created)`,\n );\n continue;\n } catch (backupError) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Failed to backup and replace: ${backupError instanceof Error ? backupError.message : String(backupError)}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n continue;\n }\n\n case 'rename':\n try {\n const uniqueTargetFile = await renameAndCopyFile(sourceFile, targetFile);\n copiedFiles.push({\n source: sourceFile,\n destination: uniqueTargetFile,\n unit: { kind: unit.kind, id: unit.id },\n });\n console.info(`📝 Renamed ${unit.kind} \"${unit.id}\": ${unit.file} → ${basename(uniqueTargetFile)}`);\n continue;\n } catch (renameError) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Failed to rename and copy: ${renameError instanceof Error ? renameError.message : String(renameError)}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n continue;\n }\n\n default:\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Unknown conflict strategy: ${strategy}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n continue;\n }\n }\n\n // Ensure target directory exists\n await mkdir(dirname(targetFile), { recursive: true });\n\n // Copy the file\n try {\n await copyFile(sourceFile, targetFile);\n copiedFiles.push({\n source: sourceFile,\n destination: targetFile,\n unit: { kind: unit.kind, id: unit.id },\n });\n console.info(`✓ Copied ${unit.kind} \"${unit.id}\": ${unit.file} → ${convertedFileName}`);\n } catch (copyError) {\n conflicts.push({\n unit: { kind: unit.kind, id: unit.id },\n issue: `Failed to copy file: ${copyError instanceof Error ? copyError.message : String(copyError)}`,\n sourceFile: unit.file,\n targetFile: `${targetDir}/${convertedFileName}`,\n });\n }\n }\n\n // Ensure tsconfig.json exists in target by copying from template if available, else generate a minimal one\n try {\n const targetTsconfig = resolve(targetPath, 'tsconfig.json');\n if (!existsSync(targetTsconfig)) {\n const templateTsconfig = resolve(templateDir, 'tsconfig.json');\n if (existsSync(templateTsconfig)) {\n await copyFile(templateTsconfig, targetTsconfig);\n copiedFiles.push({\n source: templateTsconfig,\n destination: targetTsconfig,\n unit: { kind: 'other', id: 'tsconfig.json' },\n });\n console.info('✓ Copied tsconfig.json from template to target');\n } else {\n // Generate a minimal tsconfig.json as a fallback\n const minimalTsconfig = {\n compilerOptions: {\n target: 'ES2020',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: false,\n esModuleInterop: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n outDir: 'dist',\n },\n include: ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'],\n exclude: ['node_modules', 'dist', 'build', '.next', '.output', '.turbo'],\n } as const;\n\n await writeFile(targetTsconfig, JSON.stringify(minimalTsconfig, null, 2), 'utf-8');\n copiedFiles.push({\n source: '[generated tsconfig.json]',\n destination: targetTsconfig,\n unit: { kind: 'other', id: 'tsconfig.json' },\n });\n console.info('✓ Generated minimal tsconfig.json in target');\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'tsconfig.json' },\n issue: `Failed to ensure tsconfig.json: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: 'tsconfig.json',\n targetFile: 'tsconfig.json',\n });\n }\n\n // If the target project has no Mastra index file, copy from template\n try {\n const targetMastraIndex = resolve(targetPath, 'src/mastra/index.ts');\n if (!existsSync(targetMastraIndex)) {\n const templateMastraIndex = resolve(templateDir, 'src/mastra/index.ts');\n if (existsSync(templateMastraIndex)) {\n if (!existsSync(dirname(targetMastraIndex))) {\n await mkdir(dirname(targetMastraIndex), { recursive: true });\n }\n await copyFile(templateMastraIndex, targetMastraIndex);\n copiedFiles.push({\n source: templateMastraIndex,\n destination: targetMastraIndex,\n unit: { kind: 'other', id: 'mastra-index' },\n });\n console.info('✓ Copied Mastra index file from template');\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'mastra-index' },\n issue: `Failed to ensure Mastra index file: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: 'src/mastra/index.ts',\n targetFile: 'src/mastra/index.ts',\n });\n }\n\n // Handle .gitignore file merging\n try {\n const targetGitignore = resolve(targetPath, '.gitignore');\n const templateGitignore = resolve(templateDir, '.gitignore');\n\n const targetExists = existsSync(targetGitignore);\n const templateExists = existsSync(templateGitignore);\n\n if (templateExists) {\n if (!targetExists) {\n // Target has no .gitignore - copy template's completely\n await copyFile(templateGitignore, targetGitignore);\n copiedFiles.push({\n source: templateGitignore,\n destination: targetGitignore,\n unit: { kind: 'other', id: 'gitignore' },\n });\n console.info('✓ Copied .gitignore from template to target');\n } else {\n // Both exist - merge them intelligently\n const targetContent = await readFile(targetGitignore, 'utf-8');\n const templateContent = await readFile(templateGitignore, 'utf-8');\n\n const mergedContent = mergeGitignoreFiles(targetContent, templateContent, slug);\n\n if (mergedContent !== targetContent) {\n const addedLines = mergedContent.split('\\n').length - targetContent.split('\\n').length;\n await writeFile(targetGitignore, mergedContent, 'utf-8');\n copiedFiles.push({\n source: templateGitignore,\n destination: targetGitignore,\n unit: { kind: 'other', id: 'gitignore-merge' },\n });\n console.info(`✓ Merged template .gitignore entries into existing .gitignore (${addedLines} new entries)`);\n } else {\n console.info('ℹ No new .gitignore entries to add from template');\n }\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'gitignore' },\n issue: `Failed to handle .gitignore file: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: '.gitignore',\n targetFile: '.gitignore',\n });\n }\n\n // Handle .env file merging with template variables\n try {\n const { variables } = inputData;\n if (variables && Object.keys(variables).length > 0) {\n const targetEnv = resolve(targetPath, '.env');\n const targetExists = existsSync(targetEnv);\n\n if (!targetExists) {\n // Target has no .env - create new one with template variables\n const envContent = [\n `# Environment variables for ${slug}`,\n ...Object.entries(variables).map(([key, value]) => `${key}=${value}`),\n ].join('\\n');\n\n await writeFile(targetEnv, envContent, 'utf-8');\n copiedFiles.push({\n source: '[template variables]',\n destination: targetEnv,\n unit: { kind: 'other', id: 'env' },\n });\n console.info(`✓ Created .env file with ${Object.keys(variables).length} template variables`);\n } else {\n // Both exist - merge them intelligently\n const targetContent = await readFile(targetEnv, 'utf-8');\n const mergedContent = mergeEnvFiles(targetContent, variables, slug);\n\n if (mergedContent !== targetContent) {\n const addedLines = mergedContent.split('\\n').length - targetContent.split('\\n').length;\n await writeFile(targetEnv, mergedContent, 'utf-8');\n copiedFiles.push({\n source: '[template variables]',\n destination: targetEnv,\n unit: { kind: 'other', id: 'env-merge' },\n });\n console.info(`✓ Merged new environment variables into existing .env file (${addedLines} new entries)`);\n } else {\n console.info('ℹ No new environment variables to add (all already exist in .env)');\n }\n }\n }\n } catch (e) {\n conflicts.push({\n unit: { kind: 'other', id: 'env' },\n issue: `Failed to handle .env file: ${e instanceof Error ? e.message : String(e)}`,\n sourceFile: '.env',\n targetFile: '.env',\n });\n }\n\n // Commit the copied files\n if (copiedFiles.length > 0) {\n try {\n const fileList = copiedFiles.map(f => f.destination);\n await gitAddAndCommit(\n targetPath,\n `feat(template): copy ${copiedFiles.length} files from ${slug}@${commitSha.substring(0, 7)}`,\n fileList,\n { skipIfNoStaged: true },\n );\n console.info(`✓ Committed ${copiedFiles.length} copied files`);\n } catch (commitError) {\n console.warn('Failed to commit copied files:', commitError);\n }\n }\n\n const message = `Programmatic file copy completed. Copied ${copiedFiles.length} files, ${conflicts.length} conflicts detected.`;\n console.info(message);\n\n return {\n success: true,\n copiedFiles,\n conflicts,\n message,\n };\n } catch (error) {\n console.error('Programmatic file copy failed:', error);\n\n return {\n success: false,\n copiedFiles: [],\n conflicts: [],\n message: `Programmatic file copy failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 9: Intelligent merging with AgentBuilder\nconst intelligentMergeStep = createStep({\n id: 'intelligent-merge',\n description: 'Use AgentBuilder to intelligently merge template files',\n inputSchema: IntelligentMergeInputSchema,\n outputSchema: IntelligentMergeResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Intelligent merge step starting...');\n const { conflicts, copiedFiles, commitSha, slug, templateDir, branchName } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n try {\n const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai('gpt-4.1') });\n\n // Create copyFile tool for edge cases\n const copyFileTool = createTool({\n id: 'copy-file',\n description:\n 'Copy a file from template to target project (use only for edge cases - most files are already copied programmatically).',\n inputSchema: z.object({\n sourcePath: z.string().describe('Path to the source file relative to template directory'),\n destinationPath: z.string().describe('Path to the destination file relative to target project'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n message: z.string(),\n errorMessage: z.string().optional(),\n }),\n execute: async input => {\n try {\n const { sourcePath, destinationPath } = input;\n\n // Use templateDir directly from input\n const resolvedSourcePath = resolve(templateDir, sourcePath);\n const resolvedDestinationPath = resolve(targetPath, destinationPath);\n\n if (existsSync(resolvedSourcePath) && !existsSync(dirname(resolvedDestinationPath))) {\n await mkdir(dirname(resolvedDestinationPath), { recursive: true });\n }\n\n await copyFile(resolvedSourcePath, resolvedDestinationPath);\n return {\n success: true,\n message: `Successfully copied file from ${sourcePath} to ${destinationPath}`,\n };\n } catch (err) {\n return {\n success: false,\n message: `Failed to copy file: ${err instanceof Error ? err.message : String(err)}`,\n errorMessage: err instanceof Error ? err.message : String(err),\n };\n }\n },\n });\n\n // Initialize AgentBuilder for merge and registration\n const agentBuilder = new AgentBuilder({\n projectPath: targetPath,\n mode: 'template',\n model,\n instructions: `\nYou are an expert at integrating Mastra template components into existing projects.\n\nCRITICAL CONTEXT:\n- Files have been programmatically copied from template to target project\n- Your job is to handle integration issues, registration, and validation\n\nFILES SUCCESSFULLY COPIED:\n${JSON.stringify(copiedFiles, null, 2)}\n\nCONFLICTS TO RESOLVE:\n${JSON.stringify(conflicts, null, 2)}\n\nCRITICAL INSTRUCTIONS:\n1. **Package management**: NO need to install packages (already handled by package merge step)\n2. **File copying**: Most files are already copied programmatically. Only use copyFile tool for edge cases where additional files are needed for conflict resolution\n\nKEY RESPONSIBILITIES:\n1. Resolve any conflicts from the programmatic copy step\n2. Register components in existing Mastra index file (agents, workflows, networks, mcp-servers)\n3. DO NOT register tools in existing Mastra index file - tools should remain standalone\n4. Copy additional files ONLY if needed for conflict resolution\n\nMASTRA INDEX FILE HANDLING (src/mastra/index.ts):\n1. **Verify the file exists**\n - Call readFile\n - If it fails with ENOENT (or listDirectory shows it missing) -> copyFile the template version to src/mastra/index.ts, then confirm it now exists\n - Always verify after copying that the file exists and is accessible\n\n2. **Edit the file**\n - Always work with the full file content\n - Generate the complete, correct source (imports, anchors, registrations, formatting)\n - Keep existing registrations intact and maintain file structure\n - Ensure proper spacing and organization of new additions\n\n3. **Handle anchors and structure**\n - When generating new content, ensure you do not duplicate existing imports or object entries\n - If required anchors (e.g., agents: {}) are missing, add them while generating the new content\n - Add missing anchors just before the closing brace of the Mastra config\n - Do not restructure or reorder existing anchors and registrations\n\nCRITICAL: ALWAYS use writeFile to update the mastra/index.ts file when needed to register new components.\n\nMASTRA-SPECIFIC REGISTRATION:\n- Agents: Register in existing Mastra index file\n- Workflows: Register in existing Mastra index file\n- Networks: Register in existing Mastra index file\n- MCP servers: Register in existing Mastra index file\n- Tools: Copy to ${AgentBuilderDefaults.DEFAULT_FOLDER_STRUCTURE.tool} but DO NOT register in existing Mastra index file\n- If an anchor (e.g., \"agents: {\") is not found, avoid complex restructuring; instead, insert the missing anchor on a new line (e.g., add \"agents: {\" just before the closing brace of the Mastra config) and then proceed with the other registrations.\n\nCONFLICT RESOLUTION AND FILE COPYING:\n- Only copy files if needed to resolve specific conflicts\n- When copying files from template:\n - Ensure you get the right file name and path\n - Verify the destination directory exists\n - Maintain the same relative path structure\n - Only copy files that are actually needed\n- Preserve existing functionality when resolving conflicts\n- Focus on registration and conflict resolution, validation will happen in a later step\n\nTemplate information:\n- Slug: ${slug}\n- Commit: ${commitSha.substring(0, 7)}\n- Branch: ${branchName}\n`,\n tools: {\n copyFile: copyFileTool,\n },\n });\n\n // Create task list for systematic processing\n const tasks = [];\n\n // Add conflict resolution tasks\n conflicts.forEach(conflict => {\n tasks.push({\n id: `conflict-${conflict.unit.kind}-${conflict.unit.id}`,\n content: `Resolve conflict: ${conflict.issue}`,\n status: 'pending' as const,\n priority: 'high' as const,\n notes: `Unit: ${conflict.unit.kind}:${conflict.unit.id}, Issue: ${conflict.issue}, Source: ${conflict.sourceFile}, Target: ${conflict.targetFile}`,\n });\n });\n\n // Add registration tasks for successfully copied files\n const registrableKinds = new Set(['agent', 'workflow', 'network', 'mcp-server']);\n const registrableFiles = copiedFiles.filter(f => registrableKinds.has(f.unit.kind as any));\n const targetMastraIndex = resolve(targetPath, 'src/mastra/index.ts');\n const mastraIndexExists = existsSync(targetMastraIndex);\n console.info(`Mastra index exists: ${mastraIndexExists} at ${targetMastraIndex}`);\n console.info(\n 'Registrable components:',\n registrableFiles.map(f => `${f.unit.kind}:${f.unit.id}`),\n );\n if (registrableFiles.length > 0) {\n tasks.push({\n id: 'register-components',\n content: `Register ${registrableFiles.length} components in existing Mastra index file (src/mastra/index.ts)`,\n status: 'pending' as const,\n priority: 'medium' as const,\n dependencies: conflicts.length > 0 ? conflicts.map(c => `conflict-${c.unit.kind}-${c.unit.id}`) : undefined,\n notes: `Components to register: ${registrableFiles.map(f => `${f.unit.kind}:${f.unit.id}`).join(', ')}`,\n });\n }\n\n // Note: Validation is handled by the dedicated validation step, not here\n\n console.info(`Creating task list with ${tasks.length} tasks...`);\n await AgentBuilderDefaults.manageTaskList({ action: 'create', tasks });\n\n // Log git state before merge operations\n await logGitState(targetPath, 'before intelligent merge');\n\n const prompt = `\nYou need to work through a task list to complete the template integration.\n\nCRITICAL INSTRUCTIONS:\n\n**STEP 1: GET YOUR TASK LIST**\n1. Use manageTaskList tool with action \"list\" to see all pending tasks\n2. Work through tasks in dependency order (complete dependencies first)\n\n**STEP 2: PROCESS EACH TASK SYSTEMATICALLY**\nFor each task:\n1. Use manageTaskList to mark the current task as 'in_progress'\n2. Complete the task according to its requirements\n3. Use manageTaskList to mark the task as 'completed' when done\n4. Continue until all tasks are completed\n\n**TASK TYPES AND REQUIREMENTS:**\n\n**Conflict Resolution Tasks:**\n- Analyze the specific conflict and determine best resolution strategy\n- For file name conflicts: merge content or rename appropriately\n- For missing files: investigate and copy if needed\n- For other issues: apply appropriate fixes\n\n**Component Registration Task:**\n- Update main Mastra instance file to register new components\n- Only register: agents, workflows, networks, mcp-servers\n- DO NOT register tools in main config\n- Ensure proper import paths and naming conventions\n\n**COMMIT STRATEGY:**\n- After resolving conflicts: \"feat(template): resolve conflicts for ${slug}@${commitSha.substring(0, 7)}\"\n- After registration: \"feat(template): register components from ${slug}@${commitSha.substring(0, 7)}\"\n\n**CRITICAL NOTES:**\n- Template source: ${templateDir}\n- Target project: ${targetPath}\n- Focus ONLY on conflict resolution and component registration\n- Use executeCommand for git commits after each task\n- DO NOT perform validation - that's handled by the dedicated validation step\n\nStart by listing your tasks and work through them systematically!\n`;\n\n // Process tasks systematically\n const resolvedModel = await agentBuilder.getModel();\n const isSupported = isSupportedLanguageModel(resolvedModel);\n\n const result = isSupported ? await agentBuilder.stream(prompt) : await agentBuilder.streamLegacy(prompt);\n\n // Extract actual conflict resolution details from agent execution\n const actualResolutions: Array<{\n taskId: string;\n action: string;\n status: string;\n content: string;\n notes?: string;\n }> = [];\n\n for await (const chunk of result.fullStream) {\n if (chunk.type === 'step-finish' || chunk.type === 'step-start') {\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n console.info({\n type: chunk.type,\n msgId: chunkData.messageId,\n });\n } else {\n console.info(JSON.stringify(chunk, null, 2));\n\n // Extract task management tool results\n if (chunk.type === 'tool-result') {\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n if (chunkData.toolName === 'manageTaskList') {\n try {\n const toolResult = chunkData.result;\n if (toolResult.action === 'update' && toolResult.status === 'completed') {\n actualResolutions.push({\n taskId: toolResult.taskId || '',\n action: toolResult.action,\n status: toolResult.status,\n content: toolResult.content || '',\n notes: toolResult.notes,\n });\n console.info(`📋 Task completed: ${toolResult.taskId} - ${toolResult.content}`);\n }\n } catch (parseError) {\n console.warn('Failed to parse task management result:', parseError);\n }\n }\n }\n }\n }\n\n // Log git state after merge operations\n await logGitState(targetPath, 'after intelligent merge');\n\n // Map actual resolutions back to conflicts\n const conflictResolutions = conflicts.map(conflict => {\n const taskId = `conflict-${conflict.unit.kind}-${conflict.unit.id}`;\n const actualResolution = actualResolutions.find(r => r.taskId === taskId);\n\n if (actualResolution) {\n return {\n unit: conflict.unit,\n issue: conflict.issue,\n resolution:\n actualResolution.notes ||\n actualResolution.content ||\n `Completed: ${conflict.unit.kind} ${conflict.unit.id}`,\n actualWork: true,\n };\n } else {\n return {\n unit: conflict.unit,\n issue: conflict.issue,\n resolution: `No specific resolution found for ${conflict.unit.kind} ${conflict.unit.id}`,\n actualWork: false,\n };\n }\n });\n\n await gitAddAndCommit(targetPath, `feat(template): apply intelligent merge for ${slug}`, undefined, {\n skipIfNoStaged: true,\n });\n\n return {\n success: true,\n applied: true,\n message: `Successfully resolved ${conflicts.length} conflicts from template ${slug}`,\n conflictsResolved: conflictResolutions,\n };\n } catch (error) {\n return {\n success: false,\n applied: false,\n message: `Failed to resolve conflicts: ${error instanceof Error ? error.message : String(error)}`,\n conflictsResolved: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 10: Validation and Fix Step - validates merged code and fixes any issues\nconst validationAndFixStep = createStep({\n id: 'validation-and-fix',\n description: 'Validate the merged template code and fix any issues using a specialized agent',\n inputSchema: ValidationFixInputSchema,\n outputSchema: ValidationFixResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Validation and fix step starting...');\n const { commitSha, slug, orderedUnits, templateDir, copiedFiles, conflictsResolved, maxIterations = 5 } = inputData;\n const targetPath = resolveTargetPath(inputData, requestContext);\n\n // Skip validation if no changes were made\n const hasChanges = copiedFiles.length > 0 || (conflictsResolved && conflictsResolved.length > 0);\n if (!hasChanges) {\n console.info('⏭️ Skipping validation - no files copied or conflicts resolved');\n return {\n success: true,\n applied: false,\n message: 'No changes to validate - template already integrated or no conflicts resolved',\n validationResults: {\n valid: true,\n errorsFixed: 0,\n remainingErrors: 0,\n },\n };\n }\n\n console.info(\n `📋 Changes detected: ${copiedFiles.length} files copied, ${conflictsResolved?.length || 0} conflicts resolved`,\n );\n\n let currentIteration = 1; // Declare at function scope for error handling\n\n try {\n const model = await resolveModel({ requestContext, projectPath: targetPath, defaultModel: openai('gpt-4.1') });\n\n const allTools = await AgentBuilderDefaults.listToolsForMode(targetPath, 'template');\n\n const validationAgent = new Agent({\n id: 'code-validator-fixer',\n name: 'Code Validator Fixer',\n description: 'Specialized agent for validating and fixing template integration issues',\n instructions: `You are a code validation and fixing specialist. Your job is to:\n\n1. **Run comprehensive validation** using the validateCode tool to check for:\n - TypeScript compilation errors\n - ESLint issues\n - Import/export problems\n - Missing dependencies\n - Index file structure and exports\n - Component registration correctness\n - Naming convention compliance\n\n2. **Fix validation errors systematically**:\n - Use readFile to examine files with errors\n - Use multiEdit for simple search-replace fixes (single line changes)\n - Use replaceLines for complex multiline fixes (imports, function signatures, etc.)\n - Use listDirectory to understand project structure when fixing import paths\n - Update file contents to resolve TypeScript and linting issues\n\n3. **Choose the right tool for the job**:\n - multiEdit: Simple replacements, single line changes, small fixes\n - replaceLines: Multiline imports, function signatures, complex code blocks\n - writeFile: ONLY for creating new files (never overwrite existing)\n\n4. **Create missing files ONLY when necessary**:\n - Use writeFile ONLY for creating NEW files that don't exist\n - NEVER overwrite existing files - use multiEdit or replaceLines instead\n - Common cases: missing barrel files (index.ts), missing config files, missing type definitions\n - Always check with readFile first to ensure file doesn't exist\n\n5. **Fix ALL template integration issues**:\n - Fix import path issues in copied files\n - Ensure TypeScript imports and exports are correct\n - Validate integration works properly\n - Fix files copied with new names based on unit IDs\n - Update original template imports that reference old filenames\n - Fix missing imports in index files\n - Fix incorrect file paths in imports\n - Fix type mismatches after integration\n - Fix missing exports in barrel files\n - Use the COPIED FILES mapping below to fix import paths\n - Fix any missing dependencies or module resolution issues\n\n6. **Validate index file structure**:\n - Correct imports for all components\n - Proper anchor structure (agents: {}, etc.)\n - No duplicate registrations\n - Correct export names and paths\n - Proper formatting and organization\n\n7. **Follow naming conventions**:\n Import paths:\n - camelCase: import { myAgent } from './myAgent'\n - snake_case: import { myAgent } from './my_agent'\n - kebab-case: import { myAgent } from './my-agent'\n - PascalCase: import { MyAgent } from './MyAgent'\n\n File names:\n - camelCase: weatherAgent.ts, chatAgent.ts\n - snake_case: weather_agent.ts, chat_agent.ts\n - kebab-case: weather-agent.ts, chat-agent.ts\n - PascalCase: WeatherAgent.ts, ChatAgent.ts\n\n Key Rule: Keep variable/export names unchanged, only adapt file names and import paths\n\n8. **Re-validate after fixes** to ensure all issues are resolved\n\nCRITICAL: Always validate the entire project first to get a complete picture of issues, then fix them systematically, and re-validate to confirm fixes worked.\n\nCRITICAL TOOL SELECTION GUIDE:\n- **multiEdit**: Use for simple string replacements, single-line changes\n Example: changing './oldPath' to './newPath'\n \n- **replaceLines**: Use for multiline fixes, complex code structures\n Example: fixing multiline imports, function signatures, or code blocks\n Usage: replaceLines({ filePath: 'file.ts', startLine: 5, endLine: 8, newContent: 'new multiline content' })\n \n- **writeFile**: ONLY for creating new files that don't exist\n Example: creating missing index.ts barrel files\n\nCRITICAL WRITEFILЕ SAFETY RULES:\n- ONLY use writeFile for creating NEW files that don't exist\n- ALWAYS check with readFile first to verify file doesn't exist\n- NEVER use writeFile to overwrite existing files - use multiEdit or replaceLines instead\n- Common valid uses: missing index.ts barrel files, missing type definitions, missing config files\n\nCRITICAL IMPORT PATH RESOLUTION:\nThe following files were copied from template with new names:\n${JSON.stringify(copiedFiles, null, 2)}\n\nWhen fixing import errors:\n1. Check if the missing module corresponds to a copied file\n2. Use listDirectory to verify actual filenames in target directories\n3. Update import paths to match the actual copied filenames\n4. Ensure exported variable names match what's being imported\n\nEXAMPLE: If error shows \"Cannot find module './tools/download-csv-tool'\" but a file was copied as \"csv-fetcher-tool.ts\", update the import to \"./tools/csv-fetcher-tool\"\n\n${conflictsResolved ? `CONFLICTS RESOLVED BY INTELLIGENT MERGE:\\n${JSON.stringify(conflictsResolved, null, 2)}\\n` : ''}\n\nINTEGRATED UNITS:\n${JSON.stringify(orderedUnits, null, 2)}\n\nBe thorough and methodical. Always use listDirectory to verify actual file existence before fixing imports.`,\n model,\n tools: {\n validateCode: allTools.validateCode,\n readFile: allTools.readFile,\n writeFile: allTools.writeFile,\n multiEdit: allTools.multiEdit,\n replaceLines: allTools.replaceLines,\n listDirectory: allTools.listDirectory,\n executeCommand: allTools.executeCommand,\n },\n });\n\n console.info('Starting validation and fix agent with internal loop...');\n\n let validationResults = {\n valid: false,\n errorsFixed: 0,\n remainingErrors: 1, // Start with 1 to enter the loop\n iteration: currentIteration,\n lastValidationErrors: [] as any[], // Store the actual error details\n };\n\n // Loop up to maxIterations times or until all errors are fixed\n while (validationResults.remainingErrors > 0 && currentIteration <= maxIterations) {\n console.info(`\\n=== Validation Iteration ${currentIteration} ===`);\n\n const iterationPrompt =\n currentIteration === 1\n ? `Please validate the template integration and fix any errors found in the project at ${targetPath}. The template \"${slug}\" (${commitSha.substring(0, 7)}) was just integrated and may have validation issues that need fixing.\n\nStart by running validateCode with all validation types to get a complete picture of any issues, then systematically fix them.`\n : `Continue validation and fixing for the template integration at ${targetPath}. This is iteration ${currentIteration} of validation.\n\nPrevious iterations may have fixed some issues, so start by re-running validateCode to see the current state, then fix any remaining issues.`;\n\n const resolvedModel = await validationAgent.getModel();\n const isSupported = isSupportedLanguageModel(resolvedModel);\n const output = z.object({ success: z.boolean() });\n const result = isSupported\n ? await tryStreamWithJsonFallback(validationAgent, iterationPrompt, {\n structuredOutput: {\n schema: output,\n },\n })\n : await validationAgent.streamLegacy(iterationPrompt, {\n experimental_output: output as any,\n });\n\n let iterationErrors = 0;\n let previousErrors = validationResults.remainingErrors;\n let lastValidationResult: any = null;\n\n for await (const chunk of result.fullStream) {\n if (chunk.type === 'step-finish' || chunk.type === 'step-start') {\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n console.info({\n type: chunk.type,\n msgId: chunkData.messageId,\n iteration: currentIteration,\n });\n } else {\n console.info(JSON.stringify(chunk, null, 2));\n }\n if (chunk.type === 'tool-result') {\n // Track validation results\n const chunkData = 'payload' in chunk ? chunk.payload : chunk;\n if (chunkData.toolName === 'validateCode') {\n const toolResult = chunkData.result;\n lastValidationResult = toolResult; // Store the full result\n if (toolResult?.summary) {\n iterationErrors = toolResult.summary.totalErrors || 0;\n console.info(`Iteration ${currentIteration}: Found ${iterationErrors} errors`);\n }\n }\n }\n }\n\n // Update results for this iteration\n validationResults.remainingErrors = iterationErrors;\n validationResults.errorsFixed += Math.max(0, previousErrors - iterationErrors);\n validationResults.valid = iterationErrors === 0;\n validationResults.iteration = currentIteration;\n\n // Store the last validation errors if any remain\n if (iterationErrors > 0 && lastValidationResult?.errors) {\n validationResults.lastValidationErrors = lastValidationResult.errors;\n }\n\n console.info(`Iteration ${currentIteration} complete: ${iterationErrors} errors remaining`);\n\n // Break if no errors or max iterations reached\n if (iterationErrors === 0) {\n console.info(`✅ All validation issues resolved in ${currentIteration} iterations!`);\n break;\n } else if (currentIteration >= maxIterations) {\n console.info(`⚠️ Max iterations (${maxIterations}) reached. ${iterationErrors} errors still remaining.`);\n break;\n }\n\n currentIteration++;\n }\n\n // Commit the validation fixes\n try {\n await gitAddAndCommit(\n targetPath,\n `fix(template): resolve validation errors for ${slug}@${commitSha.substring(0, 7)}`,\n undefined,\n {\n skipIfNoStaged: true,\n },\n );\n } catch (commitError) {\n console.warn('Failed to commit validation fixes:', commitError);\n }\n\n const success = validationResults.valid;\n\n return {\n success,\n applied: true,\n message: `Validation completed in ${currentIteration} iteration${currentIteration > 1 ? 's' : ''}. ${validationResults.valid ? 'All issues resolved!' : `${validationResults.remainingErrors} issue${validationResults.remainingErrors > 1 ? 's' : ''} remaining`}`,\n validationResults: {\n valid: validationResults.valid,\n errorsFixed: validationResults.errorsFixed,\n remainingErrors: validationResults.remainingErrors,\n errors: validationResults.lastValidationErrors,\n },\n };\n } catch (error) {\n console.error('Validation and fix failed:', error);\n return {\n success: false,\n applied: false,\n message: `Validation and fix failed: ${error instanceof Error ? error.message : String(error)}`,\n validationResults: {\n valid: false,\n errorsFixed: 0,\n remainingErrors: -1,\n },\n error: error instanceof Error ? error.message : String(error),\n };\n } finally {\n // Cleanup template directory\n try {\n await rm(templateDir, { recursive: true, force: true });\n console.info(`✓ Cleaned up template directory: ${templateDir}`);\n } catch (cleanupError) {\n console.warn('Failed to cleanup template directory:', cleanupError);\n }\n }\n },\n});\n\n// Create the complete workflow\nexport const agentBuilderTemplateWorkflow = createWorkflow({\n id: 'agent-builder-template',\n description:\n 'Merges a Mastra template repository into the current project using intelligent AgentBuilder-powered merging',\n inputSchema: AgentBuilderInputSchema,\n outputSchema: ApplyResultSchema,\n steps: [\n cloneTemplateStep,\n analyzePackageStep,\n discoverUnitsStep,\n orderUnitsStep,\n packageMergeStep,\n installStep,\n programmaticFileCopyStep,\n intelligentMergeStep,\n validationAndFixStep,\n ],\n})\n .then(cloneTemplateStep)\n .map(async ({ getStepResult }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n\n // Check for failure in clone step\n if (shouldAbortWorkflow(cloneResult)) {\n throw new Error(`Critical failure in clone step: ${cloneResult.error}`);\n }\n\n return cloneResult;\n })\n .parallel([analyzePackageStep, discoverUnitsStep])\n .map(async ({ getStepResult }) => {\n const analyzeResult = getStepResult(analyzePackageStep);\n const discoverResult = getStepResult(discoverUnitsStep);\n\n // Check for failures in parallel steps\n if (shouldAbortWorkflow(analyzeResult)) {\n throw new Error(`Failure in analyze package step: ${analyzeResult.error || 'Package analysis failed'}`);\n }\n\n if (shouldAbortWorkflow(discoverResult)) {\n throw new Error(`Failure in discover units step: ${discoverResult.error || 'Unit discovery failed'}`);\n }\n\n return discoverResult;\n })\n .then(orderUnitsStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n return {\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n };\n })\n .then(prepareBranchStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const packageResult = getStepResult(analyzePackageStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n return {\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n packageInfo: packageResult,\n };\n })\n .then(packageMergeStep)\n .map(async ({ getInitData }) => {\n const initData = getInitData<AgentBuilderInputSchemaType>();\n return {\n targetPath: initData.targetPath,\n };\n })\n .then(installStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const orderResult = getStepResult(orderUnitsStep);\n const installResult = getStepResult(installStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n\n if (shouldAbortWorkflow(installResult)) {\n throw new Error(`Failure in install step: ${installResult.error || 'Install failed'}`);\n }\n return {\n orderedUnits: orderResult.orderedUnits,\n templateDir: cloneResult.templateDir,\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n variables: initData.variables,\n };\n })\n .then(programmaticFileCopyStep)\n .map(async ({ getStepResult, getInitData }) => {\n const copyResult = getStepResult(programmaticFileCopyStep);\n const cloneResult = getStepResult(cloneTemplateStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n\n return {\n conflicts: copyResult.conflicts,\n copiedFiles: copyResult.copiedFiles,\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n templateDir: cloneResult.templateDir,\n };\n })\n .then(intelligentMergeStep)\n .map(async ({ getStepResult, getInitData }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const orderResult = getStepResult(orderUnitsStep);\n const copyResult = getStepResult(programmaticFileCopyStep);\n const mergeResult = getStepResult(intelligentMergeStep);\n const initData = getInitData<AgentBuilderInputSchemaType>();\n\n return {\n commitSha: cloneResult.commitSha,\n slug: cloneResult.slug,\n targetPath: initData.targetPath,\n templateDir: cloneResult.templateDir,\n orderedUnits: orderResult.orderedUnits,\n copiedFiles: copyResult.copiedFiles,\n conflictsResolved: mergeResult.conflictsResolved,\n };\n })\n .then(validationAndFixStep)\n .map(async ({ getStepResult }) => {\n const cloneResult = getStepResult(cloneTemplateStep);\n const analyzeResult = getStepResult(analyzePackageStep);\n const discoverResult = getStepResult(discoverUnitsStep);\n const orderResult = getStepResult(orderUnitsStep);\n const prepareBranchResult = getStepResult(prepareBranchStep);\n const packageMergeResult = getStepResult(packageMergeStep);\n const installResult = getStepResult(installStep);\n const copyResult = getStepResult(programmaticFileCopyStep);\n const intelligentMergeResult = getStepResult(intelligentMergeStep);\n const validationResult = getStepResult(validationAndFixStep);\n\n const branchName = prepareBranchResult.branchName;\n\n // Aggregate errors from all steps\n const allErrors = [\n cloneResult.error,\n analyzeResult.error,\n discoverResult.error,\n orderResult.error,\n prepareBranchResult.error,\n packageMergeResult.error,\n installResult.error,\n copyResult.error,\n intelligentMergeResult.error,\n validationResult.error,\n ].filter(Boolean);\n\n // Determine overall success based on all step results\n const overallSuccess =\n cloneResult.success !== false &&\n analyzeResult.success !== false &&\n discoverResult.success !== false &&\n orderResult.success !== false &&\n prepareBranchResult.success !== false &&\n packageMergeResult.success !== false &&\n installResult.success !== false &&\n copyResult.success !== false &&\n intelligentMergeResult.success !== false &&\n validationResult.success !== false;\n\n // Create comprehensive message\n const messages = [];\n if (copyResult.copiedFiles?.length > 0) {\n messages.push(`${copyResult.copiedFiles.length} files copied`);\n }\n if (copyResult.conflicts?.length > 0) {\n messages.push(`${copyResult.conflicts.length} conflicts skipped`);\n }\n if (intelligentMergeResult.conflictsResolved?.length > 0) {\n messages.push(`${intelligentMergeResult.conflictsResolved.length} conflicts resolved`);\n }\n if (validationResult.validationResults?.errorsFixed > 0) {\n messages.push(`${validationResult.validationResults.errorsFixed} validation errors fixed`);\n }\n\n if (validationResult.validationResults?.remainingErrors > 0) {\n messages.push(`${validationResult.validationResults.remainingErrors} validation issues remain`);\n }\n\n const comprehensiveMessage =\n messages.length > 0\n ? `Template merge completed: ${messages.join(', ')}`\n : validationResult.message || 'Template merge completed';\n\n return {\n success: overallSuccess,\n applied: validationResult.applied || copyResult.copiedFiles?.length > 0 || false,\n message: comprehensiveMessage,\n validationResults: validationResult.validationResults,\n error: allErrors.length > 0 ? allErrors.join('; ') : undefined,\n errors: allErrors.length > 0 ? allErrors : undefined,\n branchName,\n // Additional debugging info\n stepResults: {\n cloneSuccess: cloneResult.success,\n analyzeSuccess: analyzeResult.success,\n discoverSuccess: discoverResult.success,\n orderSuccess: orderResult.success,\n prepareBranchSuccess: prepareBranchResult.success,\n packageMergeSuccess: packageMergeResult.success,\n installSuccess: installResult.success,\n copySuccess: copyResult.success,\n mergeSuccess: intelligentMergeResult.success,\n validationSuccess: validationResult.success,\n filesCopied: copyResult.copiedFiles?.length || 0,\n conflictsSkipped: copyResult.conflicts?.length || 0,\n conflictsResolved: intelligentMergeResult.conflictsResolved?.length || 0,\n },\n };\n })\n .commit();\n\n// Helper to merge a template by slug\nexport async function mergeTemplateBySlug(slug: string, targetPath?: string) {\n const template = await getMastraTemplate(slug);\n const run = await agentBuilderTemplateWorkflow.createRun();\n return await run.start({\n inputData: {\n repo: template.githubUrl,\n slug: template.slug,\n targetPath,\n },\n });\n}\n\n// Helper function to determine conflict resolution strategy\nconst determineConflictStrategy = (\n _unit: { kind: string; id: string },\n _targetFile: string,\n): 'skip' | 'backup-and-replace' | 'rename' => {\n // For now, always skip conflicts to avoid disrupting existing files\n // TODO: Enable advanced strategies based on user feedback\n return 'skip';\n\n // Future logic (currently disabled):\n // if (['agent', 'workflow', 'network'].includes(unit.kind)) {\n // return 'backup-and-replace';\n // }\n // if (unit.kind === 'tool') {\n // return 'rename';\n // }\n // return 'backup-and-replace';\n};\n\n// Helper function to check if a step result indicates a failure\nconst shouldAbortWorkflow = (stepResult: any): boolean => {\n return stepResult?.success === false || stepResult?.error;\n};\n","import * as z4 from \"zod/v4\";\nimport { ZodFirstPartyTypeKind } from \"zod/v3\";\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/2.0.3/baf9ca0bc6c1e850f5a9c142d47d3731e6921106a5f2b12483df7e7922a48657/node_modules/@ai-sdk/provider/dist/index.mjs\nvar marker$1 = \"vercel.ai.error\";\nvar symbol$1 = Symbol.for(marker$1);\nvar _a$1;\nvar _b$1;\nvar AISDKError = class _AISDKError extends (_b$1 = Error, _a$1 = symbol$1, _b$1) {\n\t/**\n\t* Creates an AI SDK Error.\n\t*\n\t* @param {Object} params - The parameters for creating the error.\n\t* @param {string} params.name - The name of the error.\n\t* @param {string} params.message - The error message.\n\t* @param {unknown} [params.cause] - The underlying cause of the error.\n\t*/\n\tconstructor({ name: name14, message, cause }) {\n\t\tsuper(message);\n\t\tthis[_a$1] = true;\n\t\tthis.name = name14;\n\t\tthis.cause = cause;\n\t}\n\t/**\n\t* Checks if the given error is an AI SDK Error.\n\t* @param {unknown} error - The error to check.\n\t* @returns {boolean} True if the error is an AI SDK Error, false otherwise.\n\t*/\n\tstatic isInstance(error) {\n\t\treturn _AISDKError.hasMarker(error, marker$1);\n\t}\n\tstatic hasMarker(error, marker15) {\n\t\tconst markerSymbol = Symbol.for(marker15);\n\t\treturn error != null && typeof error === \"object\" && markerSymbol in error && typeof error[markerSymbol] === \"boolean\" && error[markerSymbol] === true;\n\t}\n};\nvar name$1 = \"AI_APICallError\";\nvar marker2 = `vercel.ai.error.${name$1}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2;\nvar _b2;\nvar APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) {\n\tconstructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) {\n\t\tsuper({\n\t\t\tname: name$1,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a2] = true;\n\t\tthis.url = url;\n\t\tthis.requestBodyValues = requestBodyValues;\n\t\tthis.statusCode = statusCode;\n\t\tthis.responseHeaders = responseHeaders;\n\t\tthis.responseBody = responseBody;\n\t\tthis.isRetryable = isRetryable;\n\t\tthis.data = data;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker2);\n\t}\n};\nvar name2 = \"AI_EmptyResponseBodyError\";\nvar marker3 = `vercel.ai.error.${name2}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3;\nvar _b3;\nvar EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) {\n\tconstructor({ message = \"Empty response body\" } = {}) {\n\t\tsuper({\n\t\t\tname: name2,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a3] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker3);\n\t}\n};\nfunction getErrorMessage$1(error) {\n\tif (error == null) return \"unknown error\";\n\tif (typeof error === \"string\") return error;\n\tif (error instanceof Error) return error.message;\n\treturn JSON.stringify(error);\n}\nvar name3 = \"AI_InvalidArgumentError\";\nvar marker4 = `vercel.ai.error.${name3}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4;\nvar _b4;\nvar InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) {\n\tconstructor({ message, cause, argument }) {\n\t\tsuper({\n\t\t\tname: name3,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a4] = true;\n\t\tthis.argument = argument;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker4);\n\t}\n};\nvar name4 = \"AI_InvalidPromptError\";\nvar marker5 = `vercel.ai.error.${name4}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5;\nvar _b5;\nvar InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) {\n\tconstructor({ prompt, message, cause }) {\n\t\tsuper({\n\t\t\tname: name4,\n\t\t\tmessage: `Invalid prompt: ${message}`,\n\t\t\tcause\n\t\t});\n\t\tthis[_a5] = true;\n\t\tthis.prompt = prompt;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker5);\n\t}\n};\nvar name5 = \"AI_InvalidResponseDataError\";\nvar marker6 = `vercel.ai.error.${name5}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6;\nvar _b6;\nvar InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) {\n\tconstructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) {\n\t\tsuper({\n\t\t\tname: name5,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a6] = true;\n\t\tthis.data = data;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker6);\n\t}\n};\nvar name6 = \"AI_JSONParseError\";\nvar marker7 = `vercel.ai.error.${name6}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7;\nvar _b7;\nvar JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) {\n\tconstructor({ text, cause }) {\n\t\tsuper({\n\t\t\tname: name6,\n\t\t\tmessage: `JSON parsing failed: Text: ${text}.\nError message: ${getErrorMessage$1(cause)}`,\n\t\t\tcause\n\t\t});\n\t\tthis[_a7] = true;\n\t\tthis.text = text;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker7);\n\t}\n};\nvar name7 = \"AI_LoadAPIKeyError\";\nvar marker8 = `vercel.ai.error.${name7}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8;\nvar _b8;\nvar LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) {\n\tconstructor({ message }) {\n\t\tsuper({\n\t\t\tname: name7,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a8] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker8);\n\t}\n};\nvar name8 = \"AI_LoadSettingError\";\nvar marker9 = `vercel.ai.error.${name8}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9;\nvar _b9;\nvar LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) {\n\tconstructor({ message }) {\n\t\tsuper({\n\t\t\tname: name8,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a9] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker9);\n\t}\n};\nvar name9 = \"AI_NoContentGeneratedError\";\nvar marker10 = `vercel.ai.error.${name9}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10;\nvar _b10;\nvar NoContentGeneratedError = class extends (_b10 = AISDKError, _a10 = symbol10, _b10) {\n\tconstructor({ message = \"No content generated.\" } = {}) {\n\t\tsuper({\n\t\t\tname: name9,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a10] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker10);\n\t}\n};\nvar name10 = \"AI_NoSuchModelError\";\nvar marker11 = `vercel.ai.error.${name10}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11;\nvar _b11;\nvar NoSuchModelError = class extends (_b11 = AISDKError, _a11 = symbol11, _b11) {\n\tconstructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) {\n\t\tsuper({\n\t\t\tname: errorName,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a11] = true;\n\t\tthis.modelId = modelId;\n\t\tthis.modelType = modelType;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker11);\n\t}\n};\nvar name11 = \"AI_TooManyEmbeddingValuesForCallError\";\nvar marker12 = `vercel.ai.error.${name11}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12;\nvar _b12;\nvar TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name11,\n\t\t\tmessage: `Too many values for a single embedding call. The ${options.provider} model \"${options.modelId}\" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`\n\t\t});\n\t\tthis[_a12] = true;\n\t\tthis.provider = options.provider;\n\t\tthis.modelId = options.modelId;\n\t\tthis.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;\n\t\tthis.values = options.values;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker12);\n\t}\n};\nvar name12 = \"AI_TypeValidationError\";\nvar marker13 = `vercel.ai.error.${name12}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13;\nvar _b13;\nvar TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) {\n\tconstructor({ value, cause }) {\n\t\tsuper({\n\t\t\tname: name12,\n\t\t\tmessage: `Type validation failed: Value: ${JSON.stringify(value)}.\nError message: ${getErrorMessage$1(cause)}`,\n\t\t\tcause\n\t\t});\n\t\tthis[_a13] = true;\n\t\tthis.value = value;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker13);\n\t}\n\t/**\n\t* Wraps an error into a TypeValidationError.\n\t* If the cause is already a TypeValidationError with the same value, it returns the cause.\n\t* Otherwise, it creates a new TypeValidationError.\n\t*\n\t* @param {Object} params - The parameters for wrapping the error.\n\t* @param {unknown} params.value - The value that failed validation.\n\t* @param {unknown} params.cause - The original error or cause of the validation failure.\n\t* @returns {TypeValidationError} A TypeValidationError instance.\n\t*/\n\tstatic wrap({ value, cause }) {\n\t\treturn _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({\n\t\t\tvalue,\n\t\t\tcause\n\t\t});\n\t}\n};\nvar name13 = \"AI_UnsupportedFunctionalityError\";\nvar marker14 = `vercel.ai.error.${name13}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14;\nvar _b14;\nvar UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) {\n\tconstructor({ functionality, message = `'${functionality}' functionality not supported.` }) {\n\t\tsuper({\n\t\t\tname: name13,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a14] = true;\n\t\tthis.functionality = functionality;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker14);\n\t}\n};\nfunction isJSONValue(value) {\n\tif (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") return true;\n\tif (Array.isArray(value)) return value.every(isJSONValue);\n\tif (typeof value === \"object\") return Object.entries(value).every(([key, val]) => typeof key === \"string\" && isJSONValue(val));\n\treturn false;\n}\nfunction isJSONArray(value) {\n\treturn Array.isArray(value) && value.every(isJSONValue);\n}\nfunction isJSONObject(value) {\n\treturn value != null && typeof value === \"object\" && Object.entries(value).every(([key, val]) => typeof key === \"string\" && isJSONValue(val));\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/index.js\nvar ParseError = class extends Error {\n\tconstructor(message, options) {\n\t\tsuper(message), this.name = \"ParseError\", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;\n\t}\n};\nconst LF = 10;\nconst CR = 13;\nconst SPACE = 32;\nfunction noop(_arg) {}\nfunction createParser(callbacks) {\n\tif (typeof callbacks == \"function\") throw new TypeError(\"`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?\");\n\tconst { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks, pendingFragments = [];\n\tlet isFirstChunk = !0, id, data = \"\", dataLines = 0, eventType;\n\tfunction feed(chunk) {\n\t\tif (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {\n\t\t\tconst trailing2 = processLines(chunk);\n\t\t\ttrailing2 !== \"\" && pendingFragments.push(trailing2);\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.indexOf(`\n`) === -1 && chunk.indexOf(\"\\r\") === -1) {\n\t\t\tpendingFragments.push(chunk);\n\t\t\treturn;\n\t\t}\n\t\tpendingFragments.push(chunk);\n\t\tconst input = pendingFragments.join(\"\");\n\t\tpendingFragments.length = 0;\n\t\tconst trailing = processLines(input);\n\t\ttrailing !== \"\" && pendingFragments.push(trailing);\n\t}\n\tfunction processLines(chunk) {\n\t\tlet searchIndex = 0;\n\t\tif (chunk.indexOf(\"\\r\") === -1) {\n\t\t\tlet lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\tfor (; lfIndex !== -1;) {\n\t\t\t\tif (searchIndex === lfIndex) {\n\t\t\t\t\tdataLines > 0 && onEvent({\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tevent: eventType,\n\t\t\t\t\t\tdata\n\t\t\t\t\t}), id = void 0, data = \"\", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst firstCharCode = chunk.charCodeAt(searchIndex);\n\t\t\t\tif (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n\t\t\t\t\tconst valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);\n\t\t\t\t\tif (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n\t\t\t\t\t\tonEvent({\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tevent: eventType,\n\t\t\t\t\t\t\tdata: value\n\t\t\t\t\t\t}), id = void 0, data = \"\", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tdata = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n\t\t\t\t} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0 : parseLine(chunk, searchIndex, lfIndex);\n\t\t\t\tsearchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\t}\n\t\t\treturn chunk.slice(searchIndex);\n\t\t}\n\t\tfor (; searchIndex < chunk.length;) {\n\t\t\tconst crIndex = chunk.indexOf(\"\\r\", searchIndex), lfIndex = chunk.indexOf(`\n`, searchIndex);\n\t\t\tlet lineEnd = -1;\n\t\t\tif (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break;\n\t\t\tparseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;\n\t\t}\n\t\treturn chunk.slice(searchIndex);\n\t}\n\tfunction parseLine(chunk, start, end) {\n\t\tif (start === end) {\n\t\t\tdispatchEvent();\n\t\t\treturn;\n\t\t}\n\t\tconst firstCharCode = chunk.charCodeAt(start);\n\t\tif (isDataPrefix(chunk, start, firstCharCode)) {\n\t\t\tconst valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);\n\t\t\tdata = dataLines === 0 ? value2 : `${data}\n${value2}`, dataLines++;\n\t\t\treturn;\n\t\t}\n\t\tif (isEventPrefix(chunk, start, firstCharCode)) {\n\t\t\teventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;\n\t\t\treturn;\n\t\t}\n\t\tif (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {\n\t\t\tconst value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);\n\t\t\tid = value2.includes(\"\\0\") ? void 0 : value2;\n\t\t\treturn;\n\t\t}\n\t\tif (firstCharCode === 58) {\n\t\t\tif (onComment) {\n\t\t\t\tconst line2 = chunk.slice(start, end);\n\t\t\t\tonComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tconst line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(\":\");\n\t\tif (fieldSeparatorIndex === -1) {\n\t\t\tprocessField(line, \"\", line);\n\t\t\treturn;\n\t\t}\n\t\tconst field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;\n\t\tprocessField(field, line.slice(fieldSeparatorIndex + offset), line);\n\t}\n\tfunction processField(field, value, line) {\n\t\tswitch (field) {\n\t\t\tcase \"event\":\n\t\t\t\teventType = value || void 0;\n\t\t\t\tbreak;\n\t\t\tcase \"data\":\n\t\t\t\tdata = dataLines === 0 ? value : `${data}\n${value}`, dataLines++;\n\t\t\t\tbreak;\n\t\t\tcase \"id\":\n\t\t\t\tid = value.includes(\"\\0\") ? void 0 : value;\n\t\t\t\tbreak;\n\t\t\tcase \"retry\":\n\t\t\t\t/^\\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n\t\t\t\t\ttype: \"invalid-retry\",\n\t\t\t\t\tvalue,\n\t\t\t\t\tline\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tonError(new ParseError(`Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}\\u2026` : field}\"`, {\n\t\t\t\t\ttype: \"unknown-field\",\n\t\t\t\t\tfield,\n\t\t\t\t\tvalue,\n\t\t\t\t\tline\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfunction dispatchEvent() {\n\t\tdataLines > 0 && onEvent({\n\t\t\tid,\n\t\t\tevent: eventType,\n\t\t\tdata\n\t\t}), id = void 0, data = \"\", dataLines = 0, eventType = void 0;\n\t}\n\tfunction reset(options = {}) {\n\t\tif (options.consume && pendingFragments.length > 0) {\n\t\t\tconst incompleteLine = pendingFragments.join(\"\");\n\t\t\tparseLine(incompleteLine, 0, incompleteLine.length);\n\t\t}\n\t\tisFirstChunk = !0, id = void 0, data = \"\", dataLines = 0, eventType = void 0, pendingFragments.length = 0;\n\t}\n\treturn {\n\t\tfeed,\n\t\treset\n\t};\n}\nfunction isDataPrefix(chunk, i, firstCharCode) {\n\treturn firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;\n}\nfunction isEventPrefix(chunk, i, firstCharCode) {\n\treturn firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/eventsource-parser/3.0.8/353c45c343d0acc1586e9cb9ff7be48ebf30a434bf7b8c9762d411b79278d167/node_modules/eventsource-parser/dist/stream.js\nvar EventSourceParserStream = class extends TransformStream {\n\tconstructor({ onError, onRetry, onComment } = {}) {\n\t\tlet parser;\n\t\tsuper({\n\t\t\tstart(controller) {\n\t\t\t\tparser = createParser({\n\t\t\t\t\tonEvent: (event) => {\n\t\t\t\t\t\tcontroller.enqueue(event);\n\t\t\t\t\t},\n\t\t\t\t\tonError(error) {\n\t\t\t\t\t\tonError === \"terminate\" ? controller.error(error) : typeof onError == \"function\" && onError(error);\n\t\t\t\t\t},\n\t\t\t\t\tonRetry,\n\t\t\t\t\tonComment\n\t\t\t\t});\n\t\t\t},\n\t\t\ttransform(chunk) {\n\t\t\t\tparser.feed(chunk);\n\t\t\t}\n\t\t});\n\t}\n};\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/3.0.31/ec2b02e652373362f632ec2c411694343ca859aa4cde84046d95e39a09d5a1ac/node_modules/@ai-sdk/provider-utils/dist/index.mjs\nfunction combineHeaders(...headers) {\n\treturn headers.reduce((combinedHeaders, currentHeaders) => ({\n\t\t...combinedHeaders,\n\t\t...currentHeaders != null ? currentHeaders : {}\n\t}), {});\n}\nfunction convertAsyncIteratorToReadableStream(iterator) {\n\tlet cancelled = false;\n\treturn new ReadableStream({\n\t\t/**\n\t\t* Called when the consumer wants to pull more data from the stream.\n\t\t*\n\t\t* @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.\n\t\t* @returns {Promise<void>}\n\t\t*/\n\t\tasync pull(controller) {\n\t\t\tif (cancelled) return;\n\t\t\ttry {\n\t\t\t\tconst { value, done } = await iterator.next();\n\t\t\t\tif (done) controller.close();\n\t\t\t\telse controller.enqueue(value);\n\t\t\t} catch (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t}\n\t\t},\n\t\t/**\n\t\t* Called when the consumer cancels the stream.\n\t\t*/\n\t\tasync cancel(reason) {\n\t\t\tcancelled = true;\n\t\t\tif (iterator.return) try {\n\t\t\t\tawait iterator.return(reason);\n\t\t\t} catch (e) {}\n\t\t}\n\t});\n}\nasync function delay(delayInMs, options) {\n\tif (delayInMs == null) return Promise.resolve();\n\tconst signal = options == null ? void 0 : options.abortSignal;\n\treturn new Promise((resolve2, reject) => {\n\t\tif (signal == null ? void 0 : signal.aborted) {\n\t\t\treject(createAbortError());\n\t\t\treturn;\n\t\t}\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve2();\n\t\t}, delayInMs);\n\t\tconst cleanup = () => {\n\t\t\tclearTimeout(timeoutId);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(createAbortError());\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort);\n\t});\n}\nfunction createAbortError() {\n\treturn new DOMException(\"Delay was aborted\", \"AbortError\");\n}\nvar DelayedPromise = class {\n\tconstructor() {\n\t\tthis.status = { type: \"pending\" };\n\t\tthis._resolve = void 0;\n\t\tthis._reject = void 0;\n\t}\n\tget promise() {\n\t\tif (this._promise) return this._promise;\n\t\tthis._promise = new Promise((resolve2, reject) => {\n\t\t\tif (this.status.type === \"resolved\") resolve2(this.status.value);\n\t\t\telse if (this.status.type === \"rejected\") reject(this.status.error);\n\t\t\tthis._resolve = resolve2;\n\t\t\tthis._reject = reject;\n\t\t});\n\t\treturn this._promise;\n\t}\n\tresolve(value) {\n\t\tvar _a2;\n\t\tthis.status = {\n\t\t\ttype: \"resolved\",\n\t\t\tvalue\n\t\t};\n\t\tif (this._promise) (_a2 = this._resolve) == null || _a2.call(this, value);\n\t}\n\treject(error) {\n\t\tvar _a2;\n\t\tthis.status = {\n\t\t\ttype: \"rejected\",\n\t\t\terror\n\t\t};\n\t\tif (this._promise) (_a2 = this._reject) == null || _a2.call(this, error);\n\t}\n\tisResolved() {\n\t\treturn this.status.type === \"resolved\";\n\t}\n\tisRejected() {\n\t\treturn this.status.type === \"rejected\";\n\t}\n\tisPending() {\n\t\treturn this.status.type === \"pending\";\n\t}\n};\nfunction extractResponseHeaders(response) {\n\treturn Object.fromEntries([...response.headers]);\n}\nvar name = \"AI_DownloadError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a;\nvar _b;\nvar DownloadError = class extends (_b = AISDKError, _a = symbol, _b) {\n\tconstructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {\n\t\tsuper({\n\t\t\tname,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a] = true;\n\t\tthis.url = url;\n\t\tthis.statusCode = statusCode;\n\t\tthis.statusText = statusText;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker);\n\t}\n};\nasync function cancelResponseBody(response) {\n\tvar _a2;\n\ttry {\n\t\tawait ((_a2 = response.body) == null ? void 0 : _a2.cancel());\n\t} catch (e) {}\n}\nfunction isBrowserRuntime(globalThisAny = globalThis) {\n\treturn globalThisAny.window != null;\n}\nfunction validateDownloadUrl(url) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch (e) {\n\t\tthrow new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `Invalid URL: ${url}`\n\t\t});\n\t}\n\tif (parsed.protocol === \"data:\") return;\n\tif (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL scheme must be http, https, or data, got ${parsed.protocol}`\n\t});\n\tconst hostname = parsed.hostname.toLowerCase().replace(/\\.+$/, \"\");\n\tif (!hostname) throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL must have a hostname`\n\t});\n\tif (hostname === \"localhost\" || hostname.endsWith(\".local\") || hostname.endsWith(\".localhost\")) throw new DownloadError({\n\t\turl,\n\t\tmessage: `URL with hostname ${hostname} is not allowed`\n\t});\n\tif (hostname.startsWith(\"[\") && hostname.endsWith(\"]\")) {\n\t\tif (isPrivateIPv6(hostname.slice(1, -1))) throw new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `URL with IPv6 address ${hostname} is not allowed`\n\t\t});\n\t\treturn;\n\t}\n\tif (isIPv4(hostname)) {\n\t\tif (isPrivateIPv4(hostname)) throw new DownloadError({\n\t\t\turl,\n\t\t\tmessage: `URL with IP address ${hostname} is not allowed`\n\t\t});\n\t\treturn;\n\t}\n}\nfunction validateDownloadAddress({ address, family, hostname }) {\n\tif (family === 4 ? !isIPv4(address) || isPrivateIPv4(address) : family === 6 ? isPrivateIPv6(address) : true) throw new DownloadError({\n\t\turl: hostname,\n\t\tmessage: `Hostname ${hostname} resolved to disallowed IP address ${address}`\n\t});\n}\nfunction isIPv4(hostname) {\n\tconst parts = hostname.split(\".\");\n\tif (parts.length !== 4) return false;\n\treturn parts.every((part) => {\n\t\tconst num = Number(part);\n\t\treturn Number.isInteger(num) && num >= 0 && num <= 255 && String(num) === part;\n\t});\n}\nfunction isPrivateIPv4(ip) {\n\tconst [a, b, c] = ip.split(\".\").map(Number);\n\tif (a === 0) return true;\n\tif (a === 10) return true;\n\tif (a === 100 && b >= 64 && b <= 127) return true;\n\tif (a === 127) return true;\n\tif (a === 169 && b === 254) return true;\n\tif (a === 172 && b >= 16 && b <= 31) return true;\n\tif (a === 192 && b === 0 && c === 0) return true;\n\tif (a === 192 && b === 168) return true;\n\tif (a === 198 && (b === 18 || b === 19)) return true;\n\tif (a >= 240) return true;\n\treturn false;\n}\nfunction parseIPv6(ip) {\n\tlet address = ip.toLowerCase();\n\tconst zoneIndex = address.indexOf(\"%\");\n\tif (zoneIndex !== -1) address = address.slice(0, zoneIndex);\n\tconst halves = address.split(\"::\");\n\tif (halves.length > 2) return null;\n\tconst toGroups = (segment) => {\n\t\tif (segment === \"\") return [];\n\t\tconst groups = [];\n\t\tconst parts = segment.split(\":\");\n\t\tfor (let i = 0; i < parts.length; i++) {\n\t\t\tconst part = parts[i];\n\t\t\tif (part.includes(\".\")) {\n\t\t\t\tif (i !== parts.length - 1 || !isIPv4(part)) return null;\n\t\t\t\tconst [a, b, c, d] = part.split(\".\").map(Number);\n\t\t\t\tgroups.push(a << 8 | b, c << 8 | d);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!/^[0-9a-f]{1,4}$/.test(part)) return null;\n\t\t\tgroups.push(parseInt(part, 16));\n\t\t}\n\t\treturn groups;\n\t};\n\tconst head = toGroups(halves[0]);\n\tif (head === null) return null;\n\tif (halves.length === 2) {\n\t\tconst tail = toGroups(halves[1]);\n\t\tif (tail === null) return null;\n\t\tconst fill = 8 - head.length - tail.length;\n\t\tif (fill < 0) return null;\n\t\treturn [\n\t\t\t...head,\n\t\t\t...new Array(fill).fill(0),\n\t\t\t...tail\n\t\t];\n\t}\n\treturn head.length === 8 ? head : null;\n}\nfunction isPrivateIPv6(ip) {\n\tconst groups = parseIPv6(ip);\n\tif (groups === null) return true;\n\tconst topZero = (count) => groups.slice(0, count).every((group) => group === 0);\n\tif (topZero(7) && (groups[7] === 0 || groups[7] === 1)) return true;\n\tif ((groups[0] & 65024) === 64512) return true;\n\tif ((groups[0] & 65472) === 65152) return true;\n\tif ((groups[0] & 65472) === 65216) return true;\n\tif ((groups[0] & 65280) === 65280) return true;\n\tif (topZero(6) || topZero(5) && groups[5] === 65535 || topZero(4) && groups[4] === 65535 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0 || groups[0] === 100 && groups[1] === 65435 && groups[2] === 1) return isPrivateIPv4(`${groups[6] >> 8 & 255}.${groups[6] & 255}.${groups[7] >> 8 & 255}.${groups[7] & 255}`);\n\treturn false;\n}\nfunction createSafeLookup(lookup) {\n\treturn ((hostname, options, callback) => {\n\t\tlookup(hostname, {\n\t\t\t...options,\n\t\t\tall: true\n\t\t}, (error, addresses) => {\n\t\t\tif (error) {\n\t\t\t\tcallback(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst [firstAddress] = addresses;\n\t\t\t\tif (firstAddress == null) throw new Error(`Hostname ${hostname} did not resolve to an address`);\n\t\t\t\tfor (const { address, family } of addresses) validateDownloadAddress({\n\t\t\t\t\taddress,\n\t\t\t\t\tfamily,\n\t\t\t\t\thostname\n\t\t\t\t});\n\t\t\t\tif (options.all === true) callback(null, addresses);\n\t\t\t\telse callback(null, firstAddress.address, firstAddress.family);\n\t\t\t} catch (error2) {\n\t\t\t\tcallback(error2 instanceof Error ? error2 : new Error(String(error2)));\n\t\t\t}\n\t\t});\n\t});\n}\nvar safeNodeFetchPromise;\nvar initialGlobalFetch = globalThis.fetch;\nvar initialGlobalFetchIsNodeDefault = isNodeDefaultFetch(initialGlobalFetch);\nfunction isNodeRuntime() {\n\tvar _a2, _b2;\n\tconst runtimeProcess = globalThis.process;\n\treturn ((_a2 = runtimeProcess == null ? void 0 : runtimeProcess.release) == null ? void 0 : _a2.name) === \"node\" && ((_b2 = runtimeProcess.versions) == null ? void 0 : _b2.bun) == null;\n}\nasync function getDefaultDownloadFetch() {\n\tif (!isNodeRuntime() || !initialGlobalFetchIsNodeDefault || globalThis.fetch !== initialGlobalFetch) return globalThis.fetch;\n\treturn safeNodeFetchPromise != null ? safeNodeFetchPromise : safeNodeFetchPromise = createSafeNodeFetch();\n}\nfunction isNodeDefaultFetch(fetch) {\n\tconst source = Function.prototype.toString.call(fetch);\n\treturn source.includes(\"internal/deps/undici\") || source.includes(\"lazy loading of undici\");\n}\nasync function createSafeNodeFetch() {\n\tconst [{ createRequire }, { lookup }] = await Promise.all([loadNodeModule(\"node:module\"), loadNodeModule(\"node:dns\")]);\n\tconst { Agent, fetch } = createRequire(getCurrentModulePath())(\"undici\");\n\tconst dispatcher = new Agent({ connect: { lookup: createSafeLookup(lookup) } });\n\treturn ((input, init) => fetch(input, {\n\t\t...init,\n\t\tdispatcher\n\t}));\n}\nasync function loadNodeModule(id) {\n\tvar _a2;\n\tconst processWithBuiltins = globalThis.process;\n\tconst builtinModule = (_a2 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a2.call(processWithBuiltins, id);\n\treturn builtinModule == null ? await importNodeModule(id) : builtinModule;\n}\nfunction importNodeModule(id) {\n\treturn import(id);\n}\nfunction getCurrentModulePath() {\n\tconst originalPrepareStackTrace = Error.prepareStackTrace;\n\ttry {\n\t\tError.prepareStackTrace = (_error, callSites) => callSites;\n\t\tconst error = /* @__PURE__ */ new Error(\"Capture current module path\");\n\t\tError.captureStackTrace(error, getCurrentModulePath);\n\t\tconst [caller] = error.stack;\n\t\tconst fileName = caller == null ? void 0 : caller.getFileName();\n\t\tif (fileName == null) throw new Error(\"Unable to determine the current module path\");\n\t\treturn fileName;\n\t} finally {\n\t\tError.prepareStackTrace = originalPrepareStackTrace;\n\t}\n}\nvar MAX_DOWNLOAD_REDIRECTS = 10;\nasync function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects = MAX_DOWNLOAD_REDIRECTS }) {\n\tconst baseInit = { signal: abortSignal };\n\tif (headers !== void 0) baseInit.headers = headers;\n\tlet currentUrl = url;\n\tfor (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {\n\t\tvalidateDownloadUrl(currentUrl);\n\t\tconst fetch = await getDefaultDownloadFetch();\n\t\tconst response = await fetch(currentUrl, {\n\t\t\t...baseInit,\n\t\t\tredirect: \"manual\"\n\t\t});\n\t\tif (response.type === \"opaqueredirect\") {\n\t\t\tif (!isBrowserRuntime()) throw new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Redirect from ${currentUrl} could not be validated and was blocked`\n\t\t\t});\n\t\t\treturn await fetch(currentUrl, {\n\t\t\t\t...baseInit,\n\t\t\t\tredirect: \"follow\"\n\t\t\t});\n\t\t}\n\t\tconst location = response.headers.get(\"location\");\n\t\tif (response.status >= 300 && response.status < 400 && location) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tcurrentUrl = new URL(location, currentUrl).toString();\n\t\t\tcontinue;\n\t\t}\n\t\treturn response;\n\t}\n\tthrow new DownloadError({\n\t\turl,\n\t\tmessage: `Too many redirects (max ${maxRedirects})`\n\t});\n}\nvar DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;\nasync function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {\n\tconst contentLength = response.headers.get(\"content-length\");\n\tif (contentLength != null) {\n\t\tconst length = parseInt(contentLength, 10);\n\t\tif (!isNaN(length) && length > maxBytes) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).`\n\t\t\t});\n\t\t}\n\t}\n\tconst body = response.body;\n\tif (body == null) return /* @__PURE__ */ new Uint8Array(0);\n\tconst reader = body.getReader();\n\tconst chunks = [];\n\tlet totalBytes = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\ttotalBytes += value.length;\n\t\t\tif (totalBytes > maxBytes) throw new DownloadError({\n\t\t\t\turl,\n\t\t\t\tmessage: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.`\n\t\t\t});\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} finally {\n\t\t\treader.releaseLock();\n\t\t}\n\t}\n\tconst result = new Uint8Array(totalBytes);\n\tlet offset = 0;\n\tfor (const chunk of chunks) {\n\t\tresult.set(chunk, offset);\n\t\toffset += chunk.length;\n\t}\n\treturn result;\n}\nvar createIdGenerator = ({ prefix, size = 16, alphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\", separator = \"-\" } = {}) => {\n\tconst generator = () => {\n\t\tconst alphabetLength = alphabet.length;\n\t\tconst chars = new Array(size);\n\t\tfor (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0];\n\t\treturn chars.join(\"\");\n\t};\n\tif (prefix == null) return generator;\n\tif (alphabet.includes(separator)) throw new InvalidArgumentError({\n\t\targument: \"separator\",\n\t\tmessage: `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n\t});\n\treturn () => `${prefix}${separator}${generator()}`;\n};\nvar generateId = createIdGenerator();\nfunction getErrorMessage(error) {\n\tif (error == null) return \"unknown error\";\n\tif (typeof error === \"string\") return error;\n\tif (error instanceof Error) return error.message;\n\treturn JSON.stringify(error);\n}\nfunction isAbortError(error) {\n\treturn (error instanceof Error || error instanceof DOMException) && (error.name === \"AbortError\" || error.name === \"ResponseAborted\" || error.name === \"TimeoutError\");\n}\nvar FETCH_FAILED_ERROR_MESSAGES = [\"fetch failed\", \"failed to fetch\"];\nfunction handleFetchError({ error, url, requestBodyValues }) {\n\tif (isAbortError(error)) return error;\n\tif (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) {\n\t\tconst cause = error.cause;\n\t\tif (cause != null) return new APICallError({\n\t\t\tmessage: `Cannot connect to API: ${cause.message}`,\n\t\t\tcause,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tisRetryable: true\n\t\t});\n\t}\n\treturn error;\n}\nfunction getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) {\n\tvar _a2, _b2, _c;\n\tif (globalThisAny.window) return `runtime/browser`;\n\tif ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`;\n\tif ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`;\n\tif (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`;\n\treturn \"runtime/unknown\";\n}\nfunction normalizeHeaders(headers) {\n\tif (headers == null) return {};\n\tconst normalized = {};\n\tif (headers instanceof Headers) headers.forEach((value, key) => {\n\t\tnormalized[key.toLowerCase()] = value;\n\t});\n\telse {\n\t\tif (!Array.isArray(headers)) headers = Object.entries(headers);\n\t\tfor (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value;\n\t}\n\treturn normalized;\n}\nfunction withUserAgentSuffix(headers, ...userAgentSuffixParts) {\n\tconst normalizedHeaders = new Headers(normalizeHeaders(headers));\n\tconst currentUserAgentHeader = normalizedHeaders.get(\"user-agent\") || \"\";\n\tnormalizedHeaders.set(\"user-agent\", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(\" \"));\n\treturn Object.fromEntries(normalizedHeaders.entries());\n}\nvar VERSION = \"3.0.31\";\nvar getOriginalFetch = () => globalThis.fetch;\nvar getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch() }) => {\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues: {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues: {}\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues: {}\n\t\t});\n\t}\n};\nfunction isUrlSupported({ mediaType, url, supportedUrls }) {\n\turl = url.toLowerCase();\n\tmediaType = mediaType.toLowerCase();\n\treturn Object.entries(supportedUrls).map(([key, value]) => {\n\t\tconst mediaType2 = key.toLowerCase();\n\t\treturn mediaType2 === \"*\" || mediaType2 === \"*/*\" ? {\n\t\t\tmediaTypePrefix: \"\",\n\t\t\tregexes: value\n\t\t} : {\n\t\t\tmediaTypePrefix: mediaType2.replace(/\\*/, \"\"),\n\t\t\tregexes: value\n\t\t};\n\t}).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url));\n}\nfunction loadOptionalSetting({ settingValue, environmentVariableName }) {\n\tif (typeof settingValue === \"string\") return settingValue;\n\tif (settingValue != null || typeof process === \"undefined\") return;\n\tsettingValue = process.env[environmentVariableName];\n\tif (settingValue == null || typeof settingValue !== \"string\") return;\n\treturn settingValue;\n}\nvar suspectProtoRx = /\"(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])(?:p|\\\\u0070)(?:r|\\\\u0072)(?:o|\\\\u006[Ff])(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:_|\\\\u005[Ff])(?:_|\\\\u005[Ff])\"\\s*:/;\nvar suspectConstructorRx = /\"(?:c|\\\\u0063)(?:o|\\\\u006[Ff])(?:n|\\\\u006[Ee])(?:s|\\\\u0073)(?:t|\\\\u0074)(?:r|\\\\u0072)(?:u|\\\\u0075)(?:c|\\\\u0063)(?:t|\\\\u0074)(?:o|\\\\u006[Ff])(?:r|\\\\u0072)\"\\s*:/;\nfunction _parse(text) {\n\tconst obj = JSON.parse(text);\n\tif (obj === null || typeof obj !== \"object\") return obj;\n\tif (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) return obj;\n\treturn filter(obj);\n}\nfunction filter(obj) {\n\tlet next = [obj];\n\twhile (next.length) {\n\t\tconst nodes = next;\n\t\tnext = [];\n\t\tfor (const node of nodes) {\n\t\t\tif (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) throw new SyntaxError(\"Object contains forbidden prototype property\");\n\t\t\tif (Object.prototype.hasOwnProperty.call(node, \"constructor\") && node.constructor !== null && typeof node.constructor === \"object\" && Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")) throw new SyntaxError(\"Object contains forbidden prototype property\");\n\t\t\tfor (const key in node) {\n\t\t\t\tconst value = node[key];\n\t\t\t\tif (value && typeof value === \"object\") next.push(value);\n\t\t\t}\n\t\t}\n\t}\n\treturn obj;\n}\nfunction secureJsonParse(text) {\n\tconst { stackTraceLimit } = Error;\n\ttry {\n\t\tError.stackTraceLimit = 0;\n\t} catch (e) {\n\t\treturn _parse(text);\n\t}\n\ttry {\n\t\treturn _parse(text);\n\t} finally {\n\t\tError.stackTraceLimit = stackTraceLimit;\n\t}\n}\nvar validatorSymbol = /* @__PURE__ */ Symbol.for(\"vercel.ai.validator\");\nfunction validator(validate) {\n\treturn {\n\t\t[validatorSymbol]: true,\n\t\tvalidate\n\t};\n}\nfunction isValidator(value) {\n\treturn typeof value === \"object\" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && \"validate\" in value;\n}\nfunction lazyValidator(createValidator) {\n\tlet validator2;\n\treturn () => {\n\t\tif (validator2 == null) validator2 = createValidator();\n\t\treturn validator2;\n\t};\n}\nfunction asValidator(value) {\n\treturn isValidator(value) ? value : \"~standard\" in value ? standardSchemaValidator(value) : value();\n}\nfunction standardSchemaValidator(standardSchema) {\n\treturn validator(async (value) => {\n\t\tconst result = await standardSchema[\"~standard\"].validate(value);\n\t\treturn result.issues == null ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.value\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: new TypeValidationError({\n\t\t\t\tvalue,\n\t\t\t\tcause: result.issues\n\t\t\t})\n\t\t};\n\t});\n}\nasync function validateTypes({ value, schema }) {\n\tconst result = await safeValidateTypes({\n\t\tvalue,\n\t\tschema\n\t});\n\tif (!result.success) throw TypeValidationError.wrap({\n\t\tvalue,\n\t\tcause: result.error\n\t});\n\treturn result.value;\n}\nasync function safeValidateTypes({ value, schema }) {\n\tconst validator2 = asValidator(schema);\n\ttry {\n\t\tif (validator2.validate == null) return {\n\t\t\tsuccess: true,\n\t\t\tvalue,\n\t\t\trawValue: value\n\t\t};\n\t\tconst result = await validator2.validate(value);\n\t\tif (result.success) return {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.value,\n\t\t\trawValue: value\n\t\t};\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: TypeValidationError.wrap({\n\t\t\t\tvalue,\n\t\t\t\tcause: result.error\n\t\t\t}),\n\t\t\trawValue: value\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: TypeValidationError.wrap({\n\t\t\t\tvalue,\n\t\t\t\tcause: error\n\t\t\t}),\n\t\t\trawValue: value\n\t\t};\n\t}\n}\nasync function parseJSON({ text, schema }) {\n\ttry {\n\t\tconst value = secureJsonParse(text);\n\t\tif (schema == null) return value;\n\t\treturn validateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t} catch (error) {\n\t\tif (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) throw error;\n\t\tthrow new JSONParseError({\n\t\t\ttext,\n\t\t\tcause: error\n\t\t});\n\t}\n}\nasync function safeParseJSON({ text, schema }) {\n\ttry {\n\t\tconst value = secureJsonParse(text);\n\t\tif (schema == null) return {\n\t\t\tsuccess: true,\n\t\t\tvalue,\n\t\t\trawValue: value\n\t\t};\n\t\treturn await safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: JSONParseError.isInstance(error) ? error : new JSONParseError({\n\t\t\t\ttext,\n\t\t\t\tcause: error\n\t\t\t}),\n\t\t\trawValue: void 0\n\t\t};\n\t}\n}\nfunction parseJsonEventStream({ stream, schema }) {\n\treturn stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TransformStream({ async transform({ data }, controller) {\n\t\tif (data === \"[DONE]\") return;\n\t\tcontroller.enqueue(await safeParseJSON({\n\t\t\ttext: data,\n\t\t\tschema\n\t\t}));\n\t} }));\n}\nvar getOriginalFetch2 = () => globalThis.fetch;\nvar postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi({\n\turl,\n\theaders: {\n\t\t\"Content-Type\": \"application/json\",\n\t\t...headers\n\t},\n\tbody: {\n\t\tcontent: JSON.stringify(body),\n\t\tvalues: body\n\t},\n\tfailedResponseHandler,\n\tsuccessfulResponseHandler,\n\tabortSignal,\n\tfetch\n});\nvar postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2() }) => {\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tbody: body.content,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tconst responseHeaders = extractResponseHeaders(response);\n\t\tif (!response.ok) {\n\t\t\tlet errorInformation;\n\t\t\ttry {\n\t\t\t\terrorInformation = await failedResponseHandler({\n\t\t\t\t\tresponse,\n\t\t\t\t\turl,\n\t\t\t\t\trequestBodyValues: body.values\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t\tthrow new APICallError({\n\t\t\t\t\tmessage: \"Failed to process error response\",\n\t\t\t\t\tcause: error,\n\t\t\t\t\tstatusCode: response.status,\n\t\t\t\t\turl,\n\t\t\t\t\tresponseHeaders,\n\t\t\t\t\trequestBodyValues: body.values\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow errorInformation.value;\n\t\t}\n\t\ttry {\n\t\t\treturn await successfulResponseHandler({\n\t\t\t\tresponse,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues: body.values\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tif (isAbortError(error) || APICallError.isInstance(error)) throw error;\n\t\t\t}\n\t\t\tthrow new APICallError({\n\t\t\t\tmessage: \"Failed to process successful response\",\n\t\t\t\tcause: error,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\turl,\n\t\t\t\tresponseHeaders,\n\t\t\t\trequestBodyValues: body.values\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tthrow handleFetchError({\n\t\t\terror,\n\t\t\turl,\n\t\t\trequestBodyValues: body.values\n\t\t});\n\t}\n};\nfunction tool(tool2) {\n\treturn tool2;\n}\nfunction dynamicTool(tool2) {\n\treturn {\n\t\t...tool2,\n\t\ttype: \"dynamic\"\n\t};\n}\nfunction createProviderDefinedToolFactoryWithOutputSchema({ id, name: name2, inputSchema, outputSchema }) {\n\treturn ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({\n\t\ttype: \"provider-defined\",\n\t\tid,\n\t\tname: name2,\n\t\targs,\n\t\tinputSchema,\n\t\toutputSchema,\n\t\texecute,\n\t\ttoModelOutput,\n\t\tonInputStart,\n\t\tonInputDelta,\n\t\tonInputAvailable\n\t});\n}\nasync function resolve(value) {\n\tif (typeof value === \"function\") value = value();\n\treturn Promise.resolve(value);\n}\nvar textDecoder = new TextDecoder();\nasync function readResponseBodyAsText({ response, url }) {\n\treturn textDecoder.decode(await readResponseWithSizeLimit({\n\t\tresponse,\n\t\turl\n\t}));\n}\nvar createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => {\n\tconst responseBody = await readResponseBodyAsText({\n\t\tresponse,\n\t\turl\n\t});\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (responseBody.trim() === \"\") return {\n\t\tresponseHeaders,\n\t\tvalue: new APICallError({\n\t\t\tmessage: response.statusText,\n\t\t\turl,\n\t\t\trequestBodyValues,\n\t\t\tstatusCode: response.status,\n\t\t\tresponseHeaders,\n\t\t\tresponseBody,\n\t\t\tisRetryable: isRetryable == null ? void 0 : isRetryable(response)\n\t\t})\n\t};\n\ttry {\n\t\tconst parsedError = await parseJSON({\n\t\t\ttext: responseBody,\n\t\t\tschema: errorSchema\n\t\t});\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: new APICallError({\n\t\t\t\tmessage: errorToMessage(parsedError),\n\t\t\t\turl,\n\t\t\t\trequestBodyValues,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tresponseHeaders,\n\t\t\t\tresponseBody,\n\t\t\t\tdata: parsedError,\n\t\t\t\tisRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)\n\t\t\t})\n\t\t};\n\t} catch (parseError) {\n\t\treturn {\n\t\t\tresponseHeaders,\n\t\t\tvalue: new APICallError({\n\t\t\t\tmessage: response.statusText,\n\t\t\t\turl,\n\t\t\t\trequestBodyValues,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tresponseHeaders,\n\t\t\t\tresponseBody,\n\t\t\t\tisRetryable: isRetryable == null ? void 0 : isRetryable(response)\n\t\t\t})\n\t\t};\n\t}\n};\nvar createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (response.body == null) throw new EmptyResponseBodyError({});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: parseJsonEventStream({\n\t\t\tstream: response.body,\n\t\t\tschema: chunkSchema\n\t\t})\n\t};\n};\nvar createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {\n\tconst responseBody = await readResponseBodyAsText({\n\t\tresponse,\n\t\turl\n\t});\n\tconst parsedResult = await safeParseJSON({\n\t\ttext: responseBody,\n\t\tschema: responseSchema\n\t});\n\tconst responseHeaders = extractResponseHeaders(response);\n\tif (!parsedResult.success) throw new APICallError({\n\t\tmessage: \"Invalid JSON response\",\n\t\tcause: parsedResult.error,\n\t\tstatusCode: response.status,\n\t\tresponseHeaders,\n\t\tresponseBody,\n\t\turl,\n\t\trequestBodyValues\n\t});\n\treturn {\n\t\tresponseHeaders,\n\t\tvalue: parsedResult.value,\n\t\trawValue: parsedResult.rawValue\n\t};\n};\nvar schemaSymbol = /* @__PURE__ */ Symbol.for(\"vercel.ai.schema\");\nfunction lazySchema(createSchema) {\n\tlet schema;\n\treturn () => {\n\t\tif (schema == null) schema = createSchema();\n\t\treturn schema;\n\t};\n}\nfunction jsonSchema(jsonSchema2, { validate } = {}) {\n\treturn {\n\t\t[schemaSymbol]: true,\n\t\t_type: void 0,\n\t\t[validatorSymbol]: true,\n\t\tget jsonSchema() {\n\t\t\tif (typeof jsonSchema2 === \"function\") jsonSchema2 = jsonSchema2();\n\t\t\treturn jsonSchema2;\n\t\t},\n\t\tvalidate\n\t};\n}\nfunction addAdditionalPropertiesToJsonSchema(jsonSchema2) {\n\tif (jsonSchema2.type === \"object\") {\n\t\tjsonSchema2.additionalProperties = false;\n\t\tconst properties = jsonSchema2.properties;\n\t\tif (properties != null) for (const property in properties) properties[property] = addAdditionalPropertiesToJsonSchema(properties[property]);\n\t}\n\tif (jsonSchema2.type === \"array\" && jsonSchema2.items != null) if (Array.isArray(jsonSchema2.items)) jsonSchema2.items = jsonSchema2.items.map((item) => addAdditionalPropertiesToJsonSchema(item));\n\telse jsonSchema2.items = addAdditionalPropertiesToJsonSchema(jsonSchema2.items);\n\treturn jsonSchema2;\n}\nvar ignoreOverride = /* @__PURE__ */ Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nvar defaultOptions = {\n\tname: void 0,\n\t$refStrategy: \"root\",\n\tbasePath: [\"#\"],\n\teffectStrategy: \"input\",\n\tpipeStrategy: \"all\",\n\tdateStrategy: \"format:date-time\",\n\tmapStrategy: \"entries\",\n\tremoveAdditionalStrategy: \"passthrough\",\n\tallowedAdditionalProperties: true,\n\trejectedAdditionalProperties: false,\n\tdefinitionPath: \"definitions\",\n\tstrictUnions: false,\n\tdefinitions: {},\n\terrorMessages: false,\n\tpatternStrategy: \"escape\",\n\tapplyRegexFlags: false,\n\temailStrategy: \"format:email\",\n\tbase64Strategy: \"contentEncoding:base64\",\n\tnameStrategy: \"ref\"\n};\nvar getDefaultOptions = (options) => typeof options === \"string\" ? {\n\t...defaultOptions,\n\tname: options\n} : {\n\t...defaultOptions,\n\t...options\n};\nfunction parseAnyDef() {\n\treturn {};\n}\nfunction parseArrayDef(def, refs) {\n\tvar _a2, _b2, _c;\n\tconst res = { type: \"array\" };\n\tif (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t});\n\tif (def.minLength) res.minItems = def.minLength.value;\n\tif (def.maxLength) res.maxItems = def.maxLength.value;\n\tif (def.exactLength) {\n\t\tres.minItems = def.exactLength.value;\n\t\tres.maxItems = def.exactLength.value;\n\t}\n\treturn res;\n}\nfunction parseBigintDef(def) {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"int64\"\n\t};\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tif (check.inclusive) res.minimum = check.value;\n\t\t\telse res.exclusiveMinimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (check.inclusive) res.maximum = check.value;\n\t\t\telse res.exclusiveMaximum = check.value;\n\t\t\tbreak;\n\t\tcase \"multipleOf\":\n\t\t\tres.multipleOf = check.value;\n\t\t\tbreak;\n\t}\n\treturn res;\n}\nfunction parseBooleanDef() {\n\treturn { type: \"boolean\" };\n}\nfunction parseBrandedDef(_def, refs) {\n\treturn parseDef(_def.type._def, refs);\n}\nvar parseCatchDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\nfunction parseDateDef(def, refs, overrideDateStrategy) {\n\tconst strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;\n\tif (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) };\n\tswitch (strategy) {\n\t\tcase \"string\":\n\t\tcase \"format:date-time\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date-time\"\n\t\t};\n\t\tcase \"format:date\": return {\n\t\t\ttype: \"string\",\n\t\t\tformat: \"date\"\n\t\t};\n\t\tcase \"integer\": return integerDateParser(def);\n\t}\n}\nvar integerDateParser = (def) => {\n\tconst res = {\n\t\ttype: \"integer\",\n\t\tformat: \"unix-time\"\n\t};\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tres.minimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tres.maximum = check.value;\n\t\t\tbreak;\n\t}\n\treturn res;\n};\nfunction parseDefaultDef(_def, refs) {\n\treturn {\n\t\t...parseDef(_def.innerType._def, refs),\n\t\tdefault: _def.defaultValue()\n\t};\n}\nfunction parseEffectsDef(_def, refs) {\n\treturn refs.effectStrategy === \"input\" ? parseDef(_def.schema._def, refs) : parseAnyDef();\n}\nfunction parseEnumDef(def) {\n\treturn {\n\t\ttype: \"string\",\n\t\tenum: Array.from(def.values)\n\t};\n}\nvar isJsonSchema7AllOfType = (type) => {\n\tif (\"type\" in type && type.type === \"string\") return false;\n\treturn \"allOf\" in type;\n};\nfunction parseIntersectionDef(def, refs) {\n\tconst allOf = [parseDef(def.left._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t}), parseDef(def.right._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"1\"\n\t\t]\n\t})].filter((x) => !!x);\n\tconst mergedAllOf = [];\n\tallOf.forEach((schema) => {\n\t\tif (isJsonSchema7AllOfType(schema)) mergedAllOf.push(...schema.allOf);\n\t\telse {\n\t\t\tlet nestedSchema = schema;\n\t\t\tif (\"additionalProperties\" in schema && schema.additionalProperties === false) {\n\t\t\t\tconst { additionalProperties, ...rest } = schema;\n\t\t\t\tnestedSchema = rest;\n\t\t\t}\n\t\t\tmergedAllOf.push(nestedSchema);\n\t\t}\n\t});\n\treturn mergedAllOf.length ? { allOf: mergedAllOf } : void 0;\n}\nfunction parseLiteralDef(def) {\n\tconst parsedType = typeof def.value;\n\tif (parsedType !== \"bigint\" && parsedType !== \"number\" && parsedType !== \"boolean\" && parsedType !== \"string\") return { type: Array.isArray(def.value) ? \"array\" : \"object\" };\n\treturn {\n\t\ttype: parsedType === \"bigint\" ? \"integer\" : parsedType,\n\t\tconst: def.value\n\t};\n}\nvar emojiRegex = void 0;\nvar zodPatterns = {\n\t/**\n\t* `c` was changed to `[cC]` to replicate /i flag\n\t*/\n\tcuid: /^[cC][^\\s-]{8,}$/,\n\tcuid2: /^[0-9a-z]+$/,\n\tulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n\t/**\n\t* `a-z` was added to replicate /i flag\n\t*/\n\temail: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n\t/**\n\t* Constructed a valid Unicode RegExp\n\t*\n\t* Lazily instantiate since this type of regex isn't supported\n\t* in all envs (e.g. React Native).\n\t*\n\t* See:\n\t* https://github.com/colinhacks/zod/issues/2433\n\t* Fix in Zod:\n\t* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n\t*/\n\temoji: () => {\n\t\tif (emojiRegex === void 0) emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n\t\treturn emojiRegex;\n\t},\n\t/**\n\t* Unused\n\t*/\n\tuuid: /^[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}$/,\n\t/**\n\t* Unused\n\t*/\n\tipv4: /^(?:(?: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])$/,\n\tipv4Cidr: /^(?:(?: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])$/,\n\t/**\n\t* Unused\n\t*/\n\tipv6: /^(([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})))$/,\n\tipv6Cidr: /^(([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])$/,\n\tbase64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n\tbase64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n\tnanoid: /^[a-zA-Z0-9_-]{21}$/,\n\tjwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/\n};\nfunction parseStringDef(def, refs) {\n\tconst res = { type: \"string\" };\n\tif (def.checks) for (const check of def.checks) switch (check.kind) {\n\t\tcase \"min\":\n\t\t\tres.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tres.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"email\":\n\t\t\tswitch (refs.emailStrategy) {\n\t\t\t\tcase \"format:email\":\n\t\t\t\t\taddFormat(res, \"email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"format:idn-email\":\n\t\t\t\t\taddFormat(res, \"idn-email\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\":\n\t\t\t\t\taddPattern(res, zodPatterns.email, check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"url\":\n\t\t\taddFormat(res, \"uri\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"uuid\":\n\t\t\taddFormat(res, \"uuid\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"regex\":\n\t\t\taddPattern(res, check.regex, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid\":\n\t\t\taddPattern(res, zodPatterns.cuid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cuid2\":\n\t\t\taddPattern(res, zodPatterns.cuid2, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"startsWith\":\n\t\t\taddPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"endsWith\":\n\t\t\taddPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"datetime\":\n\t\t\taddFormat(res, \"date-time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"date\":\n\t\t\taddFormat(res, \"date\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"time\":\n\t\t\taddFormat(res, \"time\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"duration\":\n\t\t\taddFormat(res, \"duration\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"length\":\n\t\t\tres.minLength = typeof res.minLength === \"number\" ? Math.max(res.minLength, check.value) : check.value;\n\t\t\tres.maxLength = typeof res.maxLength === \"number\" ? Math.min(res.maxLength, check.value) : check.value;\n\t\t\tbreak;\n\t\tcase \"includes\":\n\t\t\taddPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ip\":\n\t\t\tif (check.version !== \"v6\") addFormat(res, \"ipv4\", check.message, refs);\n\t\t\tif (check.version !== \"v4\") addFormat(res, \"ipv6\", check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64url\":\n\t\t\taddPattern(res, zodPatterns.base64url, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"jwt\":\n\t\t\taddPattern(res, zodPatterns.jwt, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"cidr\":\n\t\t\tif (check.version !== \"v6\") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n\t\t\tif (check.version !== \"v4\") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"emoji\":\n\t\t\taddPattern(res, zodPatterns.emoji(), check.message, refs);\n\t\t\tbreak;\n\t\tcase \"ulid\":\n\t\t\taddPattern(res, zodPatterns.ulid, check.message, refs);\n\t\t\tbreak;\n\t\tcase \"base64\":\n\t\t\tswitch (refs.base64Strategy) {\n\t\t\t\tcase \"format:binary\":\n\t\t\t\t\taddFormat(res, \"binary\", check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"contentEncoding:base64\":\n\t\t\t\t\tres.contentEncoding = \"base64\";\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"pattern:zod\":\n\t\t\t\t\taddPattern(res, zodPatterns.base64, check.message, refs);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"nanoid\": addPattern(res, zodPatterns.nanoid, check.message, refs);\n\t\tcase \"toLowerCase\":\n\t\tcase \"toUpperCase\":\n\t\tcase \"trim\": break;\n\t\tdefault:\n\t}\n\treturn res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n\treturn refs.patternStrategy === \"escape\" ? escapeNonAlphaNumeric(literal) : literal;\n}\nvar ALPHA_NUMERIC = /* @__PURE__ */ new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n\tlet result = \"\";\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (!ALPHA_NUMERIC.has(source[i])) result += \"\\\\\";\n\t\tresult += source[i];\n\t}\n\treturn result;\n}\nfunction addFormat(schema, value, message, refs) {\n\tvar _a2;\n\tif (schema.format || ((_a2 = schema.anyOf) == null ? void 0 : _a2.some((x) => x.format))) {\n\t\tif (!schema.anyOf) schema.anyOf = [];\n\t\tif (schema.format) {\n\t\t\tschema.anyOf.push({ format: schema.format });\n\t\t\tdelete schema.format;\n\t\t}\n\t\tschema.anyOf.push({\n\t\t\tformat: value,\n\t\t\t...message && refs.errorMessages && { errorMessage: { format: message } }\n\t\t});\n\t} else schema.format = value;\n}\nfunction addPattern(schema, regex, message, refs) {\n\tvar _a2;\n\tif (schema.pattern || ((_a2 = schema.allOf) == null ? void 0 : _a2.some((x) => x.pattern))) {\n\t\tif (!schema.allOf) schema.allOf = [];\n\t\tif (schema.pattern) {\n\t\t\tschema.allOf.push({ pattern: schema.pattern });\n\t\t\tdelete schema.pattern;\n\t\t}\n\t\tschema.allOf.push({\n\t\t\tpattern: stringifyRegExpWithFlags(regex, refs),\n\t\t\t...message && refs.errorMessages && { errorMessage: { pattern: message } }\n\t\t});\n\t} else schema.pattern = stringifyRegExpWithFlags(regex, refs);\n}\nfunction stringifyRegExpWithFlags(regex, refs) {\n\tvar _a2;\n\tif (!refs.applyRegexFlags || !regex.flags) return regex.source;\n\tconst flags = {\n\t\ti: regex.flags.includes(\"i\"),\n\t\tm: regex.flags.includes(\"m\"),\n\t\ts: regex.flags.includes(\"s\")\n\t};\n\tconst source = flags.i ? regex.source.toLowerCase() : regex.source;\n\tlet pattern = \"\";\n\tlet isEscaped = false;\n\tlet inCharGroup = false;\n\tlet inCharRange = false;\n\tfor (let i = 0; i < source.length; i++) {\n\t\tif (isEscaped) {\n\t\t\tpattern += source[i];\n\t\t\tisEscaped = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (flags.i) {\n\t\t\tif (inCharGroup) {\n\t\t\t\tif (source[i].match(/[a-z]/)) {\n\t\t\t\t\tif (inCharRange) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tpattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n\t\t\t\t\t\tinCharRange = false;\n\t\t\t\t\t} else if (source[i + 1] === \"-\" && ((_a2 = source[i + 2]) == null ? void 0 : _a2.match(/[a-z]/))) {\n\t\t\t\t\t\tpattern += source[i];\n\t\t\t\t\t\tinCharRange = true;\n\t\t\t\t\t} else pattern += `${source[i]}${source[i].toUpperCase()}`;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else if (source[i].match(/[a-z]/)) {\n\t\t\t\tpattern += `[${source[i]}${source[i].toUpperCase()}]`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.m) {\n\t\t\tif (source[i] === \"^\") {\n\t\t\t\tpattern += `(^|(?<=[\\r\n]))`;\n\t\t\t\tcontinue;\n\t\t\t} else if (source[i] === \"$\") {\n\t\t\t\tpattern += `($|(?=[\\r\n]))`;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (flags.s && source[i] === \".\") {\n\t\t\tpattern += inCharGroup ? `${source[i]}\\r\n` : `[${source[i]}\\r\n]`;\n\t\t\tcontinue;\n\t\t}\n\t\tpattern += source[i];\n\t\tif (source[i] === \"\\\\\") isEscaped = true;\n\t\telse if (inCharGroup && source[i] === \"]\") inCharGroup = false;\n\t\telse if (!inCharGroup && source[i] === \"[\") inCharGroup = true;\n\t}\n\ttry {\n\t\tnew RegExp(pattern);\n\t} catch (e) {\n\t\tconsole.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n\t\treturn regex.source;\n\t}\n\treturn pattern;\n}\nfunction parseRecordDef(def, refs) {\n\tvar _a2, _b2, _c, _d, _e, _f;\n\tconst schema = {\n\t\ttype: \"object\",\n\t\tadditionalProperties: (_a2 = parseDef(def.valueType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t\t})) != null ? _a2 : refs.allowedAdditionalProperties\n\t};\n\tif (((_b2 = def.keyType) == null ? void 0 : _b2._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {\n\t\tconst { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) return {\n\t\t...schema,\n\t\tpropertyNames: { enum: def.keyType._def.values }\n\t};\n\telse 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)) {\n\t\tconst { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);\n\t\treturn {\n\t\t\t...schema,\n\t\t\tpropertyNames: keyType\n\t\t};\n\t}\n\treturn schema;\n}\nfunction parseMapDef(def, refs) {\n\tif (refs.mapStrategy === \"record\") return parseRecordDef(def, refs);\n\treturn {\n\t\ttype: \"array\",\n\t\tmaxItems: 125,\n\t\titems: {\n\t\t\ttype: \"array\",\n\t\t\titems: [parseDef(def.keyType._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.currentPath,\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"0\"\n\t\t\t\t]\n\t\t\t}) || parseAnyDef(), parseDef(def.valueType._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.currentPath,\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"items\",\n\t\t\t\t\t\"1\"\n\t\t\t\t]\n\t\t\t}) || parseAnyDef()],\n\t\t\tminItems: 2,\n\t\t\tmaxItems: 2\n\t\t}\n\t};\n}\nfunction parseNativeEnumDef(def) {\n\tconst object = def.values;\n\tconst actualValues = Object.keys(def.values).filter((key) => {\n\t\treturn typeof object[object[key]] !== \"number\";\n\t}).map((key) => object[key]);\n\tconst parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n\treturn {\n\t\ttype: parsedTypes.length === 1 ? parsedTypes[0] === \"string\" ? \"string\" : \"number\" : [\"string\", \"number\"],\n\t\tenum: actualValues\n\t};\n}\nfunction parseNeverDef() {\n\treturn { not: parseAnyDef() };\n}\nfunction parseNullDef() {\n\treturn { type: \"null\" };\n}\nvar primitiveMappings = {\n\tZodString: \"string\",\n\tZodNumber: \"number\",\n\tZodBigInt: \"integer\",\n\tZodBoolean: \"boolean\",\n\tZodNull: \"null\"\n};\nfunction parseUnionDef(def, refs) {\n\tconst options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n\tif (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {\n\t\tconst types = options.reduce((types2, x) => {\n\t\t\tconst type = primitiveMappings[x._def.typeName];\n\t\t\treturn type && !types2.includes(type) ? [...types2, type] : types2;\n\t\t}, []);\n\t\treturn { type: types.length > 1 ? types : types[0] };\n\t} else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n\t\tconst types = options.reduce((acc, x) => {\n\t\t\tconst type = typeof x._def.value;\n\t\t\tswitch (type) {\n\t\t\t\tcase \"string\":\n\t\t\t\tcase \"number\":\n\t\t\t\tcase \"boolean\": return [...acc, type];\n\t\t\t\tcase \"bigint\": return [...acc, \"integer\"];\n\t\t\t\tcase \"object\": if (x._def.value === null) return [...acc, \"null\"];\n\t\t\t\tdefault: return acc;\n\t\t\t}\n\t\t}, []);\n\t\tif (types.length === options.length) {\n\t\t\tconst uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n\t\t\treturn {\n\t\t\t\ttype: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n\t\t\t\tenum: options.reduce((acc, x) => {\n\t\t\t\t\treturn acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n\t\t\t\t}, [])\n\t\t\t};\n\t\t}\n\t} else if (options.every((x) => x._def.typeName === \"ZodEnum\")) return {\n\t\ttype: \"string\",\n\t\tenum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x2) => !acc.includes(x2))], [])\n\t};\n\treturn asAnyOf(def, refs);\n}\nvar asAnyOf = (def, refs) => {\n\tconst anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t`${i}`\n\t\t]\n\t})).filter((x) => !!x && (!refs.strictUnions || typeof x === \"object\" && Object.keys(x).length > 0));\n\treturn anyOf.length ? { anyOf } : void 0;\n};\nfunction parseNullableDef(def, refs) {\n\tif ([\n\t\t\"ZodString\",\n\t\t\"ZodNumber\",\n\t\t\"ZodBigInt\",\n\t\t\"ZodBoolean\",\n\t\t\"ZodNull\"\n\t].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) return { type: [primitiveMappings[def.innerType._def.typeName], \"null\"] };\n\tconst base = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\treturn base && { anyOf: [base, { type: \"null\" }] };\n}\nfunction parseNumberDef(def) {\n\tconst res = { type: \"number\" };\n\tif (!def.checks) return res;\n\tfor (const check of def.checks) switch (check.kind) {\n\t\tcase \"int\":\n\t\t\tres.type = \"integer\";\n\t\t\tbreak;\n\t\tcase \"min\":\n\t\t\tif (check.inclusive) res.minimum = check.value;\n\t\t\telse res.exclusiveMinimum = check.value;\n\t\t\tbreak;\n\t\tcase \"max\":\n\t\t\tif (check.inclusive) res.maximum = check.value;\n\t\t\telse res.exclusiveMaximum = check.value;\n\t\t\tbreak;\n\t\tcase \"multipleOf\":\n\t\t\tres.multipleOf = check.value;\n\t\t\tbreak;\n\t}\n\treturn res;\n}\nfunction parseObjectDef(def, refs) {\n\tconst result = {\n\t\ttype: \"object\",\n\t\tproperties: {}\n\t};\n\tconst required = [];\n\tconst shape = def.shape();\n\tfor (const propName in shape) {\n\t\tlet propDef = shape[propName];\n\t\tif (propDef === void 0 || propDef._def === void 0) continue;\n\t\tconst propOptional = safeIsOptional(propDef);\n\t\tconst parsedDef = parseDef(propDef._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t],\n\t\t\tpropertyPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"properties\",\n\t\t\t\tpropName\n\t\t\t]\n\t\t});\n\t\tif (parsedDef === void 0) continue;\n\t\tresult.properties[propName] = parsedDef;\n\t\tif (!propOptional) required.push(propName);\n\t}\n\tif (required.length) result.required = required;\n\tconst additionalProperties = decideAdditionalProperties(def, refs);\n\tif (additionalProperties !== void 0) result.additionalProperties = additionalProperties;\n\treturn result;\n}\nfunction decideAdditionalProperties(def, refs) {\n\tif (def.catchall._def.typeName !== \"ZodNever\") return parseDef(def.catchall._def, {\n\t\t...refs,\n\t\tcurrentPath: [...refs.currentPath, \"additionalProperties\"]\n\t});\n\tswitch (def.unknownKeys) {\n\t\tcase \"passthrough\": return refs.allowedAdditionalProperties;\n\t\tcase \"strict\": return refs.rejectedAdditionalProperties;\n\t\tcase \"strip\": return refs.removeAdditionalStrategy === \"strict\" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;\n\t}\n}\nfunction safeIsOptional(schema) {\n\ttry {\n\t\treturn schema.isOptional();\n\t} catch (e) {\n\t\treturn true;\n\t}\n}\nvar parseOptionalDef = (def, refs) => {\n\tvar _a2;\n\tif (refs.currentPath.toString() === ((_a2 = refs.propertyPath) == null ? void 0 : _a2.toString())) return parseDef(def.innerType._def, refs);\n\tconst innerSchema = parseDef(def.innerType._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"anyOf\",\n\t\t\t\"1\"\n\t\t]\n\t});\n\treturn innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();\n};\nvar parsePipelineDef = (def, refs) => {\n\tif (refs.pipeStrategy === \"input\") return parseDef(def.in._def, refs);\n\telse if (refs.pipeStrategy === \"output\") return parseDef(def.out._def, refs);\n\tconst a = parseDef(def.in._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\t\"0\"\n\t\t]\n\t});\n\treturn { allOf: [a, parseDef(def.out._def, {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.currentPath,\n\t\t\t\"allOf\",\n\t\t\ta ? \"1\" : \"0\"\n\t\t]\n\t})].filter((x) => x !== void 0) };\n};\nfunction parsePromiseDef(def, refs) {\n\treturn parseDef(def.type._def, refs);\n}\nfunction parseSetDef(def, refs) {\n\tconst schema = {\n\t\ttype: \"array\",\n\t\tuniqueItems: true,\n\t\titems: parseDef(def.valueType._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"items\"]\n\t\t})\n\t};\n\tif (def.minSize) schema.minItems = def.minSize.value;\n\tif (def.maxSize) schema.maxItems = def.maxSize.value;\n\treturn schema;\n}\nfunction parseTupleDef(def, refs) {\n\tif (def.rest) return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),\n\t\tadditionalItems: parseDef(def.rest._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [...refs.currentPath, \"additionalItems\"]\n\t\t})\n\t};\n\telse return {\n\t\ttype: \"array\",\n\t\tminItems: def.items.length,\n\t\tmaxItems: def.items.length,\n\t\titems: def.items.map((x, i) => parseDef(x._def, {\n\t\t\t...refs,\n\t\t\tcurrentPath: [\n\t\t\t\t...refs.currentPath,\n\t\t\t\t\"items\",\n\t\t\t\t`${i}`\n\t\t\t]\n\t\t})).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])\n\t};\n}\nfunction parseUndefinedDef() {\n\treturn { not: parseAnyDef() };\n}\nfunction parseUnknownDef() {\n\treturn parseAnyDef();\n}\nvar parseReadonlyDef = (def, refs) => {\n\treturn parseDef(def.innerType._def, refs);\n};\nvar selectParser = (def, typeName, refs) => {\n\tswitch (typeName) {\n\t\tcase ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef();\n\t\tcase ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef();\n\t\tcase ZodFirstPartyTypeKind.ZodNull: return parseNullDef();\n\t\tcase ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodUnion:\n\t\tcase ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def);\n\t\tcase ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def;\n\t\tcase ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodNaN:\n\t\tcase ZodFirstPartyTypeKind.ZodNever: return parseNeverDef();\n\t\tcase ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodAny: return parseAnyDef();\n\t\tcase ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef();\n\t\tcase ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs);\n\t\tcase ZodFirstPartyTypeKind.ZodFunction:\n\t\tcase ZodFirstPartyTypeKind.ZodVoid:\n\t\tcase ZodFirstPartyTypeKind.ZodSymbol: return;\n\t\tdefault: return /* @__PURE__ */ ((_) => void 0)(typeName);\n\t}\n};\nvar getRelativePath = (pathA, pathB) => {\n\tlet i = 0;\n\tfor (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break;\n\treturn [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\nfunction parseDef(def, refs, forceResolution = false) {\n\tvar _a2;\n\tconst seenItem = refs.seen.get(def);\n\tif (refs.override) {\n\t\tconst overrideResult = (_a2 = refs.override) == null ? void 0 : _a2.call(refs, def, refs, seenItem, forceResolution);\n\t\tif (overrideResult !== ignoreOverride) return overrideResult;\n\t}\n\tif (seenItem && !forceResolution) {\n\t\tconst seenSchema = get$ref(seenItem, refs);\n\t\tif (seenSchema !== void 0) return seenSchema;\n\t}\n\tconst newItem = {\n\t\tdef,\n\t\tpath: refs.currentPath,\n\t\tjsonSchema: void 0\n\t};\n\trefs.seen.set(def, newItem);\n\tconst jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n\tconst jsonSchema2 = typeof jsonSchemaOrGetter === \"function\" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;\n\tif (jsonSchema2) addMeta(def, refs, jsonSchema2);\n\tif (refs.postProcess) {\n\t\tconst postProcessResult = refs.postProcess(jsonSchema2, def, refs);\n\t\tnewItem.jsonSchema = jsonSchema2;\n\t\treturn postProcessResult;\n\t}\n\tnewItem.jsonSchema = jsonSchema2;\n\treturn jsonSchema2;\n}\nvar get$ref = (item, refs) => {\n\tswitch (refs.$refStrategy) {\n\t\tcase \"root\": return { $ref: item.path.join(\"/\") };\n\t\tcase \"relative\": return { $ref: getRelativePath(refs.currentPath, item.path) };\n\t\tcase \"none\":\n\t\tcase \"seen\":\n\t\t\tif (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {\n\t\t\t\tconsole.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n\t\t\t\treturn parseAnyDef();\n\t\t\t}\n\t\t\treturn refs.$refStrategy === \"seen\" ? parseAnyDef() : void 0;\n\t}\n};\nvar addMeta = (def, refs, jsonSchema2) => {\n\tif (def.description) jsonSchema2.description = def.description;\n\treturn jsonSchema2;\n};\nvar getRefs = (options) => {\n\tconst _options = getDefaultOptions(options);\n\tconst currentPath = _options.name !== void 0 ? [\n\t\t..._options.basePath,\n\t\t_options.definitionPath,\n\t\t_options.name\n\t] : _options.basePath;\n\treturn {\n\t\t..._options,\n\t\tcurrentPath,\n\t\tpropertyPath: void 0,\n\t\tseen: new Map(Object.entries(_options.definitions).map(([name2, def]) => [def._def, {\n\t\t\tdef: def._def,\n\t\t\tpath: [\n\t\t\t\t..._options.basePath,\n\t\t\t\t_options.definitionPath,\n\t\t\t\tname2\n\t\t\t],\n\t\t\tjsonSchema: void 0\n\t\t}]))\n\t};\n};\nvar zodToJsonSchema = (schema, options) => {\n\tvar _a2;\n\tconst refs = getRefs(options);\n\tlet definitions = typeof options === \"object\" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name3, schema2]) => {\n\t\tvar _a3;\n\t\treturn {\n\t\t\t...acc,\n\t\t\t[name3]: (_a3 = parseDef(schema2._def, {\n\t\t\t\t...refs,\n\t\t\t\tcurrentPath: [\n\t\t\t\t\t...refs.basePath,\n\t\t\t\t\trefs.definitionPath,\n\t\t\t\t\tname3\n\t\t\t\t]\n\t\t\t}, true)) != null ? _a3 : parseAnyDef()\n\t\t};\n\t}, {}) : void 0;\n\tconst name2 = typeof options === \"string\" ? options : (options == null ? void 0 : options.nameStrategy) === \"title\" ? void 0 : options == null ? void 0 : options.name;\n\tconst main = (_a2 = parseDef(schema._def, name2 === void 0 ? refs : {\n\t\t...refs,\n\t\tcurrentPath: [\n\t\t\t...refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname2\n\t\t]\n\t}, false)) != null ? _a2 : parseAnyDef();\n\tconst title = typeof options === \"object\" && options.name !== void 0 && options.nameStrategy === \"title\" ? options.name : void 0;\n\tif (title !== void 0) main.title = title;\n\tconst combined = name2 === void 0 ? definitions ? {\n\t\t...main,\n\t\t[refs.definitionPath]: definitions\n\t} : main : {\n\t\t$ref: [\n\t\t\t...refs.$refStrategy === \"relative\" ? [] : refs.basePath,\n\t\t\trefs.definitionPath,\n\t\t\tname2\n\t\t].join(\"/\"),\n\t\t[refs.definitionPath]: {\n\t\t\t...definitions,\n\t\t\t[name2]: main\n\t\t}\n\t};\n\tcombined.$schema = \"http://json-schema.org/draft-07/schema#\";\n\treturn combined;\n};\nvar zod_to_json_schema_default = zodToJsonSchema;\nfunction zod3Schema(zodSchema2, options) {\n\tvar _a2;\n\tconst useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n\treturn jsonSchema(() => zod_to_json_schema_default(zodSchema2, { $refStrategy: useReferences ? \"root\" : \"none\" }), { validate: async (value) => {\n\t\tconst result = await zodSchema2.safeParseAsync(value);\n\t\treturn result.success ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.data\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: result.error\n\t\t};\n\t} });\n}\nfunction zod4Schema(zodSchema2, options) {\n\tvar _a2;\n\tconst useReferences = (_a2 = options == null ? void 0 : options.useReferences) != null ? _a2 : false;\n\treturn jsonSchema(() => addAdditionalPropertiesToJsonSchema(z4.toJSONSchema(zodSchema2, {\n\t\ttarget: \"draft-7\",\n\t\tio: \"input\",\n\t\treused: useReferences ? \"ref\" : \"inline\"\n\t})), { validate: async (value) => {\n\t\tconst result = await z4.safeParseAsync(zodSchema2, value);\n\t\treturn result.success ? {\n\t\t\tsuccess: true,\n\t\t\tvalue: result.data\n\t\t} : {\n\t\t\tsuccess: false,\n\t\t\terror: result.error\n\t\t};\n\t} });\n}\nfunction isZod4Schema(zodSchema2) {\n\treturn \"_zod\" in zodSchema2;\n}\nfunction zodSchema(zodSchema2, options) {\n\tif (isZod4Schema(zodSchema2)) return zod4Schema(zodSchema2, options);\n\telse return zod3Schema(zodSchema2, options);\n}\nfunction isSchema(value) {\n\treturn typeof value === \"object\" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && \"jsonSchema\" in value && \"validate\" in value;\n}\nfunction asSchema(schema) {\n\treturn schema == null ? jsonSchema({\n\t\tproperties: {},\n\t\tadditionalProperties: false\n\t}) : isSchema(schema) ? schema : typeof schema === \"function\" ? schema() : zodSchema(schema);\n}\nvar { btoa, atob } = globalThis;\nfunction convertBase64ToUint8Array(base64String) {\n\tconst latin1string = atob(base64String.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n\treturn Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));\n}\nfunction convertUint8ArrayToBase64(array) {\n\tlet latin1string = \"\";\n\tfor (let i = 0; i < array.length; i++) latin1string += String.fromCodePoint(array[i]);\n\treturn btoa(latin1string);\n}\nfunction withoutTrailingSlash(url) {\n\treturn url == null ? void 0 : url.replace(/\\/$/, \"\");\n}\nfunction isAsyncIterable(obj) {\n\treturn obj != null && typeof obj[Symbol.asyncIterator] === \"function\";\n}\nasync function* executeTool({ execute, input, options }) {\n\tconst result = execute(input, options);\n\tif (isAsyncIterable(result)) {\n\t\tlet lastOutput;\n\t\tfor await (const output of result) {\n\t\t\tlastOutput = output;\n\t\t\tyield {\n\t\t\t\ttype: \"preliminary\",\n\t\t\t\toutput\n\t\t\t};\n\t\t}\n\t\tyield {\n\t\t\ttype: \"final\",\n\t\t\toutput: lastOutput\n\t\t};\n\t} else yield {\n\t\ttype: \"final\",\n\t\toutput: await result\n\t};\n}\n//#endregion\nexport { TypeValidationError as $, parseJsonEventStream as A, zodSchema as B, isAbortError as C, lazyValidator as D, lazySchema as E, safeValidateTypes as F, InvalidPromptError as G, APICallError as H, tool as I, LoadAPIKeyError as J, InvalidResponseDataError as K, validateTypes as L, readResponseWithSizeLimit as M, resolve as N, loadOptionalSetting as O, safeParseJSON as P, TooManyEmbeddingValuesForCallError as Q, withUserAgentSuffix as R, getRuntimeEnvironmentUserAgent as S, jsonSchema as T, EmptyResponseBodyError as U, AISDKError as V, InvalidArgumentError as W, NoContentGeneratedError as X, LoadSettingError as Y, NoSuchModelError as Z, executeTool as _, cancelResponseBody as a, getErrorMessage as b, convertBase64ToUint8Array as c, createIdGenerator as d, UnsupportedFunctionalityError as et, createJsonErrorResponseHandler as f, dynamicTool as g, delay as h, asSchema as i, postJsonToApi as j, normalizeHeaders as k, convertUint8ArrayToBase64 as l, createProviderDefinedToolFactoryWithOutputSchema as m, DelayedPromise as n, isJSONArray as nt, combineHeaders as o, createJsonResponseHandler as p, JSONParseError as q, DownloadError as r, isJSONObject as rt, convertAsyncIteratorToReadableStream as s, DEFAULT_MAX_DOWNLOAD_SIZE as t, getErrorMessage$1 as tt, createEventSourceResponseHandler as u, fetchWithValidatedRedirects as v, isUrlSupported as w, getFromApi as x, generateId as y, withoutTrailingSlash as z };\n\n//# sourceMappingURL=dist-BuEMdYEn.js.map","import { $ as TypeValidationError, A as parseJsonEventStream, B as zodSchema, C as isAbortError, D as lazyValidator, E as lazySchema, F as safeValidateTypes, G as InvalidPromptError, H as APICallError, I as tool, J as LoadAPIKeyError, K as InvalidResponseDataError, L as validateTypes, M as readResponseWithSizeLimit, N as resolve, O as loadOptionalSetting, P as safeParseJSON, Q as TooManyEmbeddingValuesForCallError, R as withUserAgentSuffix, S as getRuntimeEnvironmentUserAgent, T as jsonSchema, U as EmptyResponseBodyError, V as AISDKError, W as InvalidArgumentError$1, X as NoContentGeneratedError, Y as LoadSettingError, Z as NoSuchModelError, _ as executeTool, a as cancelResponseBody, b as getErrorMessage$1, c as convertBase64ToUint8Array, d as createIdGenerator, et as UnsupportedFunctionalityError, f as createJsonErrorResponseHandler, g as dynamicTool, h as delay, i as asSchema, j as postJsonToApi, k as normalizeHeaders, l as convertUint8ArrayToBase64, m as createProviderDefinedToolFactoryWithOutputSchema, n as DelayedPromise, nt as isJSONArray, o as combineHeaders, p as createJsonResponseHandler, q as JSONParseError, r as DownloadError$1, rt as isJSONObject, t as DEFAULT_MAX_DOWNLOAD_SIZE, tt as getErrorMessage, u as createEventSourceResponseHandler, v as fetchWithValidatedRedirects, w as isUrlSupported, x as getFromApi, y as generateId, z as withoutTrailingSlash } from \"./dist-BuEMdYEn.js\";\nimport { z } from \"zod/v4\";\nimport { z as z$1 } from \"zod\";\n//#region ../oidc-stub.ts\nfunction getContext() {\n\treturn { headers: {} };\n}\nasync function getVercelOidcToken() {\n\tif (process.env.VERCEL_OIDC_TOKEN) return process.env.VERCEL_OIDC_TOKEN ?? \"\";\n\tthrow new Error(\"@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.\");\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/gateway/2.0.125/570e5bb8a04f885e313d986de9394e40f0058ac9bf50dfc56c5a5022cf33eeb5/node_modules/@ai-sdk/gateway/dist/index.mjs\nvar symbol$1 = Symbol.for(\"vercel.ai.gateway.error\");\nvar _a$1;\nvar _b;\nvar GatewayError = class _GatewayError extends (_b = Error, _a$1 = symbol$1, _b) {\n\tconstructor({ message, statusCode = 500, cause }) {\n\t\tsuper(message);\n\t\tthis[_a$1] = true;\n\t\tthis.statusCode = statusCode;\n\t\tthis.cause = cause;\n\t}\n\t/**\n\t* Checks if the given error is a Gateway Error.\n\t* @param {unknown} error - The error to check.\n\t* @returns {boolean} True if the error is a Gateway Error, false otherwise.\n\t*/\n\tstatic isInstance(error) {\n\t\treturn _GatewayError.hasMarker(error);\n\t}\n\tstatic hasMarker(error) {\n\t\treturn typeof error === \"object\" && error !== null && symbol$1 in error && error[symbol$1] === true;\n\t}\n};\nvar name$1 = \"GatewayAuthenticationError\";\nvar marker2$1 = `vercel.ai.gateway.error.${name$1}`;\nvar symbol2$1 = Symbol.for(marker2$1);\nvar _a2$1;\nvar _b2;\nvar GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2$1 = symbol2$1, _b2) {\n\tconstructor({ message = \"Authentication failed\", statusCode = 401, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a2$1] = true;\n\t\tthis.name = name$1;\n\t\tthis.type = \"authentication_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol2$1 in error;\n\t}\n\t/**\n\t* Creates a contextual error message when authentication fails\n\t*/\n\tstatic createContextualError({ apiKeyProvided, oidcTokenProvided, message = \"Authentication failed\", statusCode = 401, cause }) {\n\t\tlet contextualMessage;\n\t\tif (apiKeyProvided) contextualMessage = `AI Gateway authentication failed: Invalid API key.\n\nCreate a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\n\nProvide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;\n\t\telse if (oidcTokenProvided) contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.\n\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.\n\nAlternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;\n\t\telse contextualMessage = `AI Gateway authentication failed: No authentication provided.\n\nOption 1 - API key:\nCreate an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys\nProvide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.\n\nOption 2 - OIDC token:\nRun 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;\n\t\treturn new _GatewayAuthenticationError({\n\t\t\tmessage: contextualMessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t}\n};\nvar name2$1 = \"GatewayForbiddenError\";\nvar marker3$1 = `vercel.ai.gateway.error.${name2$1}`;\nvar symbol3$1 = Symbol.for(marker3$1);\nvar forbiddenParamSchema = lazyValidator(() => zodSchema(z.object({ ruleId: z.string() })));\nvar _a3$1;\nvar _b3;\nvar GatewayForbiddenError = class extends (_b3 = GatewayError, _a3$1 = symbol3$1, _b3) {\n\tconstructor({ message = \"Forbidden\", statusCode = 403, cause, ruleId } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a3$1] = true;\n\t\tthis.name = name2$1;\n\t\tthis.type = \"forbidden\";\n\t\tthis.ruleId = ruleId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol3$1 in error;\n\t}\n};\nvar name3$1 = \"GatewayInvalidRequestError\";\nvar marker4$1 = `vercel.ai.gateway.error.${name3$1}`;\nvar symbol4$1 = Symbol.for(marker4$1);\nvar _a4$1;\nvar _b4;\nvar GatewayInvalidRequestError = class extends (_b4 = GatewayError, _a4$1 = symbol4$1, _b4) {\n\tconstructor({ message = \"Invalid request\", statusCode = 400, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a4$1] = true;\n\t\tthis.name = name3$1;\n\t\tthis.type = \"invalid_request_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol4$1 in error;\n\t}\n};\nvar name4$1 = \"GatewayRateLimitError\";\nvar marker5$1 = `vercel.ai.gateway.error.${name4$1}`;\nvar symbol5$1 = Symbol.for(marker5$1);\nvar _a5$1;\nvar _b5;\nvar GatewayRateLimitError = class extends (_b5 = GatewayError, _a5$1 = symbol5$1, _b5) {\n\tconstructor({ message = \"Rate limit exceeded\", statusCode = 429, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a5$1] = true;\n\t\tthis.name = name4$1;\n\t\tthis.type = \"rate_limit_exceeded\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol5$1 in error;\n\t}\n};\nvar name5$1 = \"GatewayModelNotFoundError\";\nvar marker6$1 = `vercel.ai.gateway.error.${name5$1}`;\nvar symbol6$1 = Symbol.for(marker6$1);\nvar modelNotFoundParamSchema = lazyValidator(() => zodSchema(z.object({ modelId: z.string() })));\nvar _a6$1;\nvar _b6;\nvar GatewayModelNotFoundError = class extends (_b6 = GatewayError, _a6$1 = symbol6$1, _b6) {\n\tconstructor({ message = \"Model not found\", statusCode = 404, modelId, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a6$1] = true;\n\t\tthis.name = name5$1;\n\t\tthis.type = \"model_not_found\";\n\t\tthis.modelId = modelId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol6$1 in error;\n\t}\n};\nvar name6$1 = \"GatewayInternalServerError\";\nvar marker7$1 = `vercel.ai.gateway.error.${name6$1}`;\nvar symbol7$1 = Symbol.for(marker7$1);\nvar _a7$1;\nvar _b7;\nvar GatewayInternalServerError = class extends (_b7 = GatewayError, _a7$1 = symbol7$1, _b7) {\n\tconstructor({ message = \"Internal server error\", statusCode = 500, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a7$1] = true;\n\t\tthis.name = name6$1;\n\t\tthis.type = \"internal_server_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol7$1 in error;\n\t}\n};\nvar name7$1 = \"GatewayResponseError\";\nvar marker8$1 = `vercel.ai.gateway.error.${name7$1}`;\nvar symbol8$1 = Symbol.for(marker8$1);\nvar _a8$1;\nvar _b8;\nvar GatewayResponseError = class extends (_b8 = GatewayError, _a8$1 = symbol8$1, _b8) {\n\tconstructor({ message = \"Invalid response from Gateway\", statusCode = 502, response, validationError, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a8$1] = true;\n\t\tthis.name = name7$1;\n\t\tthis.type = \"response_error\";\n\t\tthis.response = response;\n\t\tthis.validationError = validationError;\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol8$1 in error;\n\t}\n};\nasync function createGatewayErrorFromResponse({ response, statusCode, defaultMessage = \"Gateway request failed\", cause, authMethod }) {\n\tconst parseResult = await safeValidateTypes({\n\t\tvalue: response,\n\t\tschema: gatewayErrorResponseSchema\n\t});\n\tif (!parseResult.success) return new GatewayResponseError({\n\t\tmessage: `Invalid error response format: ${defaultMessage}`,\n\t\tstatusCode,\n\t\tresponse,\n\t\tvalidationError: parseResult.error,\n\t\tcause\n\t});\n\tconst validatedResponse = parseResult.value;\n\tconst errorType = validatedResponse.error.type;\n\tconst message = validatedResponse.error.message;\n\tswitch (errorType) {\n\t\tcase \"authentication_error\": return GatewayAuthenticationError.createContextualError({\n\t\t\tapiKeyProvided: authMethod === \"api-key\",\n\t\t\toidcTokenProvided: authMethod === \"oidc\",\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"invalid_request_error\": return new GatewayInvalidRequestError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"rate_limit_exceeded\": return new GatewayRateLimitError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"model_not_found\": {\n\t\t\tconst modelResult = await safeValidateTypes({\n\t\t\t\tvalue: validatedResponse.error.param,\n\t\t\t\tschema: modelNotFoundParamSchema\n\t\t\t});\n\t\t\treturn new GatewayModelNotFoundError({\n\t\t\t\tmessage,\n\t\t\t\tstatusCode,\n\t\t\t\tmodelId: modelResult.success ? modelResult.value.modelId : void 0,\n\t\t\t\tcause\n\t\t\t});\n\t\t}\n\t\tcase \"internal_server_error\": return new GatewayInternalServerError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tcase \"forbidden\": {\n\t\t\tconst ruleResult = await safeValidateTypes({\n\t\t\t\tvalue: validatedResponse.error.param,\n\t\t\t\tschema: forbiddenParamSchema\n\t\t\t});\n\t\t\treturn new GatewayForbiddenError({\n\t\t\t\tmessage,\n\t\t\t\tstatusCode,\n\t\t\t\tcause,\n\t\t\t\truleId: ruleResult.success ? ruleResult.value.ruleId : void 0\n\t\t\t});\n\t\t}\n\t\tdefault: return new GatewayInternalServerError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t}\n}\nvar gatewayErrorResponseSchema = lazyValidator(() => zodSchema(z.object({ error: z.object({\n\tmessage: z.string(),\n\ttype: z.string().nullish(),\n\tparam: z.unknown().nullish(),\n\tcode: z.union([z.string(), z.number()]).nullish()\n}) })));\nfunction extractApiCallResponse(error) {\n\tif (error.data !== void 0) return error.data;\n\tif (error.responseBody != null) try {\n\t\treturn JSON.parse(error.responseBody);\n\t} catch (e) {\n\t\treturn error.responseBody;\n\t}\n\treturn {};\n}\nvar name8$1 = \"GatewayTimeoutError\";\nvar marker9$1 = `vercel.ai.gateway.error.${name8$1}`;\nvar symbol9$1 = Symbol.for(marker9$1);\nvar _a9$1;\nvar _b9;\nvar GatewayTimeoutError = class _GatewayTimeoutError extends (_b9 = GatewayError, _a9$1 = symbol9$1, _b9) {\n\tconstructor({ message = \"Request timed out\", statusCode = 408, cause } = {}) {\n\t\tsuper({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t\tthis[_a9$1] = true;\n\t\tthis.name = name8$1;\n\t\tthis.type = \"timeout_error\";\n\t}\n\tstatic isInstance(error) {\n\t\treturn GatewayError.hasMarker(error) && symbol9$1 in error;\n\t}\n\t/**\n\t* Creates a helpful timeout error message with troubleshooting guidance\n\t*/\n\tstatic createTimeoutError({ originalMessage, statusCode = 408, cause }) {\n\t\tconst message = `Gateway request timed out: ${originalMessage}\n\n This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;\n\t\treturn new _GatewayTimeoutError({\n\t\t\tmessage,\n\t\t\tstatusCode,\n\t\t\tcause\n\t\t});\n\t}\n};\nfunction isTimeoutError(error) {\n\tif (!(error instanceof Error)) return false;\n\tconst errorCode = error.code;\n\tif (typeof errorCode === \"string\") return [\n\t\t\"UND_ERR_HEADERS_TIMEOUT\",\n\t\t\"UND_ERR_BODY_TIMEOUT\",\n\t\t\"UND_ERR_CONNECT_TIMEOUT\"\n\t].includes(errorCode);\n\treturn false;\n}\nasync function asGatewayError(error, authMethod) {\n\tvar _a10;\n\tif (GatewayError.isInstance(error)) return error;\n\tif (isTimeoutError(error)) return GatewayTimeoutError.createTimeoutError({\n\t\toriginalMessage: error instanceof Error ? error.message : \"Unknown error\",\n\t\tcause: error\n\t});\n\tif (APICallError.isInstance(error)) {\n\t\tif (error.cause && isTimeoutError(error.cause)) return GatewayTimeoutError.createTimeoutError({\n\t\t\toriginalMessage: error.message,\n\t\t\tcause: error\n\t\t});\n\t\treturn await createGatewayErrorFromResponse({\n\t\t\tresponse: extractApiCallResponse(error),\n\t\t\tstatusCode: (_a10 = error.statusCode) != null ? _a10 : 500,\n\t\t\tdefaultMessage: \"Gateway request failed\",\n\t\t\tcause: error,\n\t\t\tauthMethod\n\t\t});\n\t}\n\treturn await createGatewayErrorFromResponse({\n\t\tresponse: {},\n\t\tstatusCode: 500,\n\t\tdefaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : \"Unknown Gateway error\",\n\t\tcause: error,\n\t\tauthMethod\n\t});\n}\nvar GATEWAY_AUTH_METHOD_HEADER = \"ai-gateway-auth-method\";\nasync function parseAuthMethod(headers) {\n\tconst result = await safeValidateTypes({\n\t\tvalue: headers[GATEWAY_AUTH_METHOD_HEADER],\n\t\tschema: gatewayAuthMethodSchema\n\t});\n\treturn result.success ? result.value : void 0;\n}\nvar gatewayAuthMethodSchema = lazyValidator(() => zodSchema(z.union([z.literal(\"api-key\"), z.literal(\"oidc\")])));\nvar KNOWN_MODEL_TYPES = [\n\t\"embedding\",\n\t\"image\",\n\t\"language\"\n];\nvar GatewayFetchMetadata = class {\n\tconstructor(config) {\n\t\tthis.config = config;\n\t}\n\tasync getAvailableModels() {\n\t\ttry {\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${this.config.baseURL}/config`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayAvailableModelsResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n\tasync getCredits() {\n\t\ttry {\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${new URL(this.config.baseURL).origin}/v1/credits`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayCreditsResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n};\nvar gatewayAvailableModelsResponseSchema = lazyValidator(() => zodSchema(z.object({ models: z.array(z.object({\n\tid: z.string(),\n\tname: z.string(),\n\tdescription: z.string().nullish(),\n\tpricing: z.object({\n\t\tinput: z.string(),\n\t\toutput: z.string(),\n\t\tinput_cache_read: z.string().nullish(),\n\t\tinput_cache_write: z.string().nullish()\n\t}).transform(({ input, output, input_cache_read, input_cache_write }) => ({\n\t\tinput,\n\t\toutput,\n\t\t...input_cache_read ? { cachedInputTokens: input_cache_read } : {},\n\t\t...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}\n\t})).nullish(),\n\tspecification: z.object({\n\t\tspecificationVersion: z.literal(\"v2\"),\n\t\tprovider: z.string(),\n\t\tmodelId: z.string()\n\t}),\n\tmodelType: z.string().nullish()\n})).transform((models) => models.filter((m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType))) })));\nvar gatewayCreditsResponseSchema = lazyValidator(() => zodSchema(z.object({\n\tbalance: z.string(),\n\ttotal_used: z.string()\n}).transform(({ balance, total_used }) => ({\n\tbalance,\n\ttotalUsed: total_used\n}))));\nvar GatewaySpendReport = class {\n\tconstructor(config) {\n\t\tthis.config = config;\n\t}\n\tasync getSpendReport(params) {\n\t\ttry {\n\t\t\tconst baseUrl = new URL(this.config.baseURL);\n\t\t\tconst searchParams = new URLSearchParams();\n\t\t\tsearchParams.set(\"start_date\", params.startDate);\n\t\t\tsearchParams.set(\"end_date\", params.endDate);\n\t\t\tif (params.groupBy) searchParams.set(\"group_by\", params.groupBy);\n\t\t\tif (params.datePart) searchParams.set(\"date_part\", params.datePart);\n\t\t\tif (params.userId) searchParams.set(\"user_id\", params.userId);\n\t\t\tif (params.model) searchParams.set(\"model\", params.model);\n\t\t\tif (params.provider) searchParams.set(\"provider\", params.provider);\n\t\t\tif (params.credentialType) searchParams.set(\"credential_type\", params.credentialType);\n\t\t\tif (params.tags && params.tags.length > 0) searchParams.set(\"tags\", params.tags.join(\",\"));\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewaySpendReportResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n};\nvar gatewaySpendReportResponseSchema = lazySchema(() => zodSchema(z.object({ results: z.array(z.object({\n\tday: z.string().optional(),\n\thour: z.string().optional(),\n\tuser: z.string().optional(),\n\tmodel: z.string().optional(),\n\ttag: z.string().optional(),\n\tprovider: z.string().optional(),\n\tcredential_type: z.enum([\"byok\", \"system\"]).optional(),\n\ttotal_cost: z.number(),\n\tmarket_cost: z.number().optional(),\n\tinput_tokens: z.number().optional(),\n\toutput_tokens: z.number().optional(),\n\tcached_input_tokens: z.number().optional(),\n\tcache_creation_input_tokens: z.number().optional(),\n\treasoning_tokens: z.number().optional(),\n\trequest_count: z.number().optional()\n}).transform(({ credential_type, total_cost, market_cost, input_tokens, output_tokens, cached_input_tokens, cache_creation_input_tokens, reasoning_tokens, request_count, ...rest }) => ({\n\t...rest,\n\t...credential_type !== void 0 ? { credentialType: credential_type } : {},\n\ttotalCost: total_cost,\n\t...market_cost !== void 0 ? { marketCost: market_cost } : {},\n\t...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},\n\t...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},\n\t...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},\n\t...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},\n\t...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},\n\t...request_count !== void 0 ? { requestCount: request_count } : {}\n}))) })));\nvar GatewayGenerationInfoFetcher = class {\n\tconstructor(config) {\n\t\tthis.config = config;\n\t}\n\tasync getGenerationInfo(params) {\n\t\ttry {\n\t\t\tconst { value } = await getFromApi({\n\t\t\t\turl: `${new URL(this.config.baseURL).origin}/v1/generation?id=${encodeURIComponent(params.id)}`,\n\t\t\t\theaders: await resolve(this.config.headers()),\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayGenerationInfoResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn value;\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error);\n\t\t}\n\t}\n};\nvar gatewayGenerationInfoResponseSchema = lazySchema(() => zodSchema(z.object({ data: z.object({\n\tid: z.string(),\n\ttotal_cost: z.number(),\n\tupstream_inference_cost: z.number(),\n\tusage: z.number(),\n\tcreated_at: z.string(),\n\tmodel: z.string(),\n\tis_byok: z.boolean(),\n\tprovider_name: z.string(),\n\tstreamed: z.boolean(),\n\tfinish_reason: z.string(),\n\tlatency: z.number(),\n\tgeneration_time: z.number(),\n\tnative_tokens_prompt: z.number(),\n\tnative_tokens_completion: z.number(),\n\tnative_tokens_reasoning: z.number(),\n\tnative_tokens_cached: z.number(),\n\tnative_tokens_cache_creation: z.number(),\n\tbillable_web_search_calls: z.number()\n}).transform(({ total_cost, upstream_inference_cost, created_at, is_byok, provider_name, finish_reason, generation_time, native_tokens_prompt, native_tokens_completion, native_tokens_reasoning, native_tokens_cached, native_tokens_cache_creation, billable_web_search_calls, ...rest }) => ({\n\t...rest,\n\ttotalCost: total_cost,\n\tupstreamInferenceCost: upstream_inference_cost,\n\tcreatedAt: created_at,\n\tisByok: is_byok,\n\tproviderName: provider_name,\n\tfinishReason: finish_reason,\n\tgenerationTime: generation_time,\n\tpromptTokens: native_tokens_prompt,\n\tcompletionTokens: native_tokens_completion,\n\treasoningTokens: native_tokens_reasoning,\n\tcachedTokens: native_tokens_cached,\n\tcacheCreationTokens: native_tokens_cache_creation,\n\tbillableWebSearchCalls: billable_web_search_calls\n})) }).transform(({ data }) => data)));\nvar GatewayLanguageModel = class {\n\tconstructor(modelId, config) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t\tthis.specificationVersion = \"v2\";\n\t\tthis.supportedUrls = { \"*/*\": [/.*/] };\n\t}\n\tget provider() {\n\t\treturn this.config.provider;\n\t}\n\tasync getArgs(options) {\n\t\tconst { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;\n\t\treturn {\n\t\t\targs: this.maybeEncodeFileParts(optionsWithoutSignal),\n\t\t\twarnings: []\n\t\t};\n\t}\n\tasync doGenerate(options) {\n\t\tconst { args, warnings } = await this.getArgs(options);\n\t\tconst { abortSignal } = options;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { responseHeaders, value: responseBody, rawValue: rawResponse } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, false), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: args,\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(z.any()),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...responseBody,\n\t\t\t\trequest: { body: args },\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: responseHeaders,\n\t\t\t\t\tbody: rawResponse\n\t\t\t\t},\n\t\t\t\twarnings\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tasync doStream(options) {\n\t\tconst { args, warnings } = await this.getArgs(options);\n\t\tconst { abortSignal } = options;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { value: response, responseHeaders } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, options.headers, this.getModelConfigHeaders(this.modelId, true), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: args,\n\t\t\t\tsuccessfulResponseHandler: createEventSourceResponseHandler(z.any()),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tstream: response.pipeThrough(new TransformStream({\n\t\t\t\t\tstart(controller) {\n\t\t\t\t\t\tif (warnings.length > 0) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"stream-start\",\n\t\t\t\t\t\t\twarnings\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t\ttransform(chunk, controller) {\n\t\t\t\t\t\tif (chunk.success) {\n\t\t\t\t\t\t\tconst streamPart = chunk.value;\n\t\t\t\t\t\t\tif (streamPart.type === \"raw\" && !options.includeRawChunks) return;\n\t\t\t\t\t\t\tif (streamPart.type === \"response-metadata\" && streamPart.timestamp && typeof streamPart.timestamp === \"string\") streamPart.timestamp = new Date(streamPart.timestamp);\n\t\t\t\t\t\t\tcontroller.enqueue(streamPart);\n\t\t\t\t\t\t} else controller.error(chunk.error);\n\t\t\t\t\t}\n\t\t\t\t})),\n\t\t\t\trequest: { body: args },\n\t\t\t\tresponse: { headers: responseHeaders }\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tisFilePart(part) {\n\t\treturn part && typeof part === \"object\" && \"type\" in part && part.type === \"file\";\n\t}\n\t/**\n\t* Encodes file parts in the prompt to base64. Mutates the passed options\n\t* instance directly to avoid copying the file data.\n\t* @param options - The options to encode.\n\t* @returns The options with the file parts encoded.\n\t*/\n\tmaybeEncodeFileParts(options) {\n\t\tfor (const message of options.prompt) for (const part of message.content) if (this.isFilePart(part)) {\n\t\t\tconst filePart = part;\n\t\t\tif (filePart.data instanceof Uint8Array) {\n\t\t\t\tconst buffer = Uint8Array.from(filePart.data);\n\t\t\t\tconst base64Data = Buffer.from(buffer).toString(\"base64\");\n\t\t\t\tfilePart.data = new URL(`data:${filePart.mediaType || \"application/octet-stream\"};base64,${base64Data}`);\n\t\t\t}\n\t\t}\n\t\treturn options;\n\t}\n\tgetUrl() {\n\t\treturn `${this.config.baseURL}/language-model`;\n\t}\n\tgetModelConfigHeaders(modelId, streaming) {\n\t\treturn {\n\t\t\t\"ai-language-model-specification-version\": \"2\",\n\t\t\t\"ai-language-model-id\": modelId,\n\t\t\t\"ai-language-model-streaming\": String(streaming)\n\t\t};\n\t}\n};\nvar GatewayEmbeddingModel = class {\n\tconstructor(modelId, config) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t\tthis.specificationVersion = \"v2\";\n\t\tthis.maxEmbeddingsPerCall = 2048;\n\t\tthis.supportsParallelCalls = true;\n\t}\n\tget provider() {\n\t\treturn this.config.provider;\n\t}\n\tasync doEmbed({ values, headers, abortSignal, providerOptions }) {\n\t\tvar _a10;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: {\n\t\t\t\t\tinput: values.length === 1 ? values[0] : values,\n\t\t\t\t\t...providerOptions ? { providerOptions } : {}\n\t\t\t\t},\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayEmbeddingResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tembeddings: responseBody.embeddings,\n\t\t\t\tusage: (_a10 = responseBody.usage) != null ? _a10 : void 0,\n\t\t\t\tproviderMetadata: responseBody.providerMetadata,\n\t\t\t\tresponse: {\n\t\t\t\t\theaders: responseHeaders,\n\t\t\t\t\tbody: rawValue\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tgetUrl() {\n\t\treturn `${this.config.baseURL}/embedding-model`;\n\t}\n\tgetModelConfigHeaders() {\n\t\treturn {\n\t\t\t\"ai-embedding-model-specification-version\": \"2\",\n\t\t\t\"ai-model-id\": this.modelId\n\t\t};\n\t}\n};\nvar gatewayEmbeddingResponseSchema = lazyValidator(() => zodSchema(z.object({\n\tembeddings: z.array(z.array(z.number())),\n\tusage: z.object({ tokens: z.number() }).nullish(),\n\tproviderMetadata: z.record(z.string(), z.record(z.string(), z.unknown())).optional()\n})));\nvar GatewayImageModel = class {\n\tconstructor(modelId, config) {\n\t\tthis.modelId = modelId;\n\t\tthis.config = config;\n\t\tthis.specificationVersion = \"v2\";\n\t\tthis.maxImagesPerCall = Number.MAX_SAFE_INTEGER;\n\t}\n\tget provider() {\n\t\treturn this.config.provider;\n\t}\n\tasync doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal }) {\n\t\tvar _a10, _b10, _c, _d;\n\t\tconst resolvedHeaders = await resolve(this.config.headers());\n\t\ttry {\n\t\t\tconst { responseHeaders, value: responseBody, rawValue } = await postJsonToApi({\n\t\t\t\turl: this.getUrl(),\n\t\t\t\theaders: combineHeaders(resolvedHeaders, headers != null ? headers : {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders)),\n\t\t\t\tbody: {\n\t\t\t\t\tprompt,\n\t\t\t\t\tn,\n\t\t\t\t\t...size && { size },\n\t\t\t\t\t...aspectRatio && { aspectRatio },\n\t\t\t\t\t...seed && { seed },\n\t\t\t\t\t...providerOptions && { providerOptions }\n\t\t\t\t},\n\t\t\t\tsuccessfulResponseHandler: createJsonResponseHandler(gatewayImageResponseSchema),\n\t\t\t\tfailedResponseHandler: createJsonErrorResponseHandler({\n\t\t\t\t\terrorSchema: z.any(),\n\t\t\t\t\terrorToMessage: (data) => data\n\t\t\t\t}),\n\t\t\t\t...abortSignal && { abortSignal },\n\t\t\t\tfetch: this.config.fetch\n\t\t\t});\n\t\t\treturn {\n\t\t\t\timages: responseBody.images,\n\t\t\t\twarnings: (_a10 = responseBody.warnings) != null ? _a10 : [],\n\t\t\t\tproviderMetadata: responseBody.providerMetadata,\n\t\t\t\tresponse: {\n\t\t\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\t\t\tmodelId: this.modelId,\n\t\t\t\t\theaders: responseHeaders\n\t\t\t\t},\n\t\t\t\t...responseBody.usage != null && { usage: {\n\t\t\t\t\tinputTokens: (_b10 = responseBody.usage.inputTokens) != null ? _b10 : void 0,\n\t\t\t\t\toutputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,\n\t\t\t\t\ttotalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0\n\t\t\t\t} }\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(resolvedHeaders));\n\t\t}\n\t}\n\tgetUrl() {\n\t\treturn `${this.config.baseURL}/image-model`;\n\t}\n\tgetModelConfigHeaders() {\n\t\treturn {\n\t\t\t\"ai-image-model-specification-version\": \"2\",\n\t\t\t\"ai-model-id\": this.modelId\n\t\t};\n\t}\n};\nvar providerMetadataEntrySchema = z.object({ images: z.array(z.unknown()).optional() }).catchall(z.unknown());\nvar gatewayImageUsageSchema = z.object({\n\tinputTokens: z.number().nullish(),\n\toutputTokens: z.number().nullish(),\n\ttotalTokens: z.number().nullish()\n});\nvar gatewayImageResponseSchema = z.object({\n\timages: z.array(z.string()),\n\twarnings: z.array(z.object({\n\t\ttype: z.literal(\"other\"),\n\t\tmessage: z.string()\n\t})).optional(),\n\tproviderMetadata: z.record(z.string(), providerMetadataEntrySchema).optional(),\n\tusage: gatewayImageUsageSchema.optional()\n});\nvar parallelSearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({\n\tid: \"gateway.parallel_search\",\n\tname: \"parallel_search\",\n\tinputSchema: lazySchema(() => zodSchema(z$1.object({\n\t\tobjective: z$1.string().describe(\"Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters.\"),\n\t\tsearch_queries: z$1.array(z$1.string()).optional().describe(\"Optional search queries to supplement the objective. Maximum 200 characters per query.\"),\n\t\tmode: z$1.enum([\"one-shot\", \"agentic\"]).optional().describe(\"Mode preset: \\\"one-shot\\\" for comprehensive results with longer excerpts (default), \\\"agentic\\\" for concise, token-efficient results for multi-step workflows.\"),\n\t\tmax_results: z$1.number().optional().describe(\"Maximum number of results to return (1-20). Defaults to 10 if not specified.\"),\n\t\tsource_policy: z$1.object({\n\t\t\tinclude_domains: z$1.array(z$1.string()).optional().describe(\"List of domains to include in search results.\"),\n\t\t\texclude_domains: z$1.array(z$1.string()).optional().describe(\"List of domains to exclude from search results.\"),\n\t\t\tafter_date: z$1.string().optional().describe(\"Only include results published after this date (ISO 8601 format).\")\n\t\t}).optional().describe(\"Source policy for controlling which domains to include/exclude and freshness.\"),\n\t\texcerpts: z$1.object({\n\t\t\tmax_chars_per_result: z$1.number().optional().describe(\"Maximum characters per result.\"),\n\t\t\tmax_chars_total: z$1.number().optional().describe(\"Maximum total characters across all results.\")\n\t\t}).optional().describe(\"Excerpt configuration for controlling result length.\"),\n\t\tfetch_policy: z$1.object({ max_age_seconds: z$1.number().optional().describe(\"Maximum age in seconds for cached content. Set to 0 to always fetch fresh content.\") }).optional().describe(\"Fetch policy for controlling content freshness.\")\n\t}))),\n\toutputSchema: lazySchema(() => zodSchema(z$1.union([z$1.object({\n\t\tsearchId: z$1.string(),\n\t\tresults: z$1.array(z$1.object({\n\t\t\turl: z$1.string(),\n\t\t\ttitle: z$1.string(),\n\t\t\texcerpt: z$1.string(),\n\t\t\tpublishDate: z$1.string().nullable().optional(),\n\t\t\trelevanceScore: z$1.number().optional()\n\t\t}))\n\t}), z$1.object({\n\t\terror: z$1.enum([\n\t\t\t\"api_error\",\n\t\t\t\"rate_limit\",\n\t\t\t\"timeout\",\n\t\t\t\"invalid_input\",\n\t\t\t\"configuration_error\",\n\t\t\t\"unknown\"\n\t\t]),\n\t\tstatusCode: z$1.number().optional(),\n\t\tmessage: z$1.string()\n\t})])))\n});\nvar parallelSearch = (config = {}) => parallelSearchToolFactory(config);\nvar perplexitySearchToolFactory = createProviderDefinedToolFactoryWithOutputSchema({\n\tid: \"gateway.perplexity_search\",\n\tname: \"perplexity_search\",\n\tinputSchema: lazySchema(() => zodSchema(z$1.object({\n\t\tquery: z$1.union([z$1.string(), z$1.array(z$1.string())]).describe(\"Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries.\"),\n\t\tmax_results: z$1.number().optional().describe(\"Maximum number of search results to return (1-20, default: 10)\"),\n\t\tmax_tokens_per_page: z$1.number().optional().describe(\"Maximum number of tokens to extract per search result page (256-2048, default: 2048)\"),\n\t\tmax_tokens: z$1.number().optional().describe(\"Maximum total tokens across all search results (default: 25000, max: 1000000)\"),\n\t\tcountry: z$1.string().optional().describe(\"Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')\"),\n\t\tsearch_domain_filter: z$1.array(z$1.string()).optional().describe(\"List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']\"),\n\t\tsearch_language_filter: z$1.array(z$1.string()).optional().describe(\"List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']\"),\n\t\tsearch_after_date: z$1.string().optional().describe(\"Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\"),\n\t\tsearch_before_date: z$1.string().optional().describe(\"Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\"),\n\t\tlast_updated_after_filter: z$1.string().optional().describe(\"Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter.\"),\n\t\tlast_updated_before_filter: z$1.string().optional().describe(\"Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter.\"),\n\t\tsearch_recency_filter: z$1.enum([\n\t\t\t\"day\",\n\t\t\t\"week\",\n\t\t\t\"month\",\n\t\t\t\"year\"\n\t\t]).optional().describe(\"Filter results by relative time period. Cannot be used with search_after_date or search_before_date.\")\n\t}))),\n\toutputSchema: lazySchema(() => zodSchema(z$1.union([z$1.object({\n\t\tresults: z$1.array(z$1.object({\n\t\t\ttitle: z$1.string(),\n\t\t\turl: z$1.string(),\n\t\t\tsnippet: z$1.string(),\n\t\t\tdate: z$1.string().optional(),\n\t\t\tlastUpdated: z$1.string().optional()\n\t\t})),\n\t\tid: z$1.string()\n\t}), z$1.object({\n\t\terror: z$1.enum([\n\t\t\t\"api_error\",\n\t\t\t\"rate_limit\",\n\t\t\t\"timeout\",\n\t\t\t\"invalid_input\",\n\t\t\t\"unknown\"\n\t\t]),\n\t\tstatusCode: z$1.number().optional(),\n\t\tmessage: z$1.string()\n\t})])))\n});\nvar perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);\nvar gatewayTools = {\n\t/**\n\t* Search the web using Parallel AI's Search API for LLM-optimized excerpts.\n\t*\n\t* Takes a natural language objective and returns relevant excerpts,\n\t* replacing multiple keyword searches with a single call for broad\n\t* or complex queries. Supports different search types for depth vs\n\t* breadth tradeoffs.\n\t*/\n\tparallelSearch,\n\t/**\n\t* Search the web using Perplexity's Search API for real-time information,\n\t* news, research papers, and articles.\n\t*\n\t* Provides ranked search results with advanced filtering options including\n\t* domain, language, date range, and recency filters.\n\t*/\n\tperplexitySearch\n};\nasync function getVercelRequestId() {\n\tvar _a10;\n\treturn (_a10 = getContext().headers) == null ? void 0 : _a10[\"x-vercel-id\"];\n}\nvar VERSION$2 = \"2.0.125\";\nvar AI_GATEWAY_PROTOCOL_VERSION = \"0.0.1\";\nfunction createGatewayProvider(options = {}) {\n\tvar _a10, _b10;\n\tlet pendingMetadata = null;\n\tlet metadataCache = null;\n\tconst cacheRefreshMillis = (_a10 = options.metadataCacheRefreshMillis) != null ? _a10 : 1e3 * 60 * 5;\n\tlet lastFetchTime = 0;\n\tconst baseURL = (_b10 = withoutTrailingSlash(options.baseURL)) != null ? _b10 : \"https://ai-gateway.vercel.sh/v1/ai\";\n\tconst getHeaders = async () => {\n\t\tconst auth = await getGatewayAuthToken(options);\n\t\tif (auth) return withUserAgentSuffix({\n\t\t\tAuthorization: `Bearer ${auth.token}`,\n\t\t\t\"ai-gateway-protocol-version\": AI_GATEWAY_PROTOCOL_VERSION,\n\t\t\t[GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,\n\t\t\t...options.headers\n\t\t}, `ai-sdk/gateway/${VERSION$2}`);\n\t\tthrow GatewayAuthenticationError.createContextualError({\n\t\t\tapiKeyProvided: false,\n\t\t\toidcTokenProvided: false,\n\t\t\tstatusCode: 401\n\t\t});\n\t};\n\tconst createO11yHeaders = () => {\n\t\tconst deploymentId = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_DEPLOYMENT_ID\"\n\t\t});\n\t\tconst environment = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_ENV\"\n\t\t});\n\t\tconst region = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_REGION\"\n\t\t});\n\t\tconst projectId = loadOptionalSetting({\n\t\t\tsettingValue: void 0,\n\t\t\tenvironmentVariableName: \"VERCEL_PROJECT_ID\"\n\t\t});\n\t\treturn async () => {\n\t\t\tconst requestId = await getVercelRequestId();\n\t\t\treturn {\n\t\t\t\t...deploymentId && { \"ai-o11y-deployment-id\": deploymentId },\n\t\t\t\t...environment && { \"ai-o11y-environment\": environment },\n\t\t\t\t...region && { \"ai-o11y-region\": region },\n\t\t\t\t...requestId && { \"ai-o11y-request-id\": requestId },\n\t\t\t\t...projectId && { \"ai-o11y-project-id\": projectId }\n\t\t\t};\n\t\t};\n\t};\n\tconst createLanguageModel = (modelId) => {\n\t\treturn new GatewayLanguageModel(modelId, {\n\t\t\tprovider: \"gateway\",\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch,\n\t\t\to11yHeaders: createO11yHeaders()\n\t\t});\n\t};\n\tconst getAvailableModels = async () => {\n\t\tvar _a11, _b11, _c;\n\t\tconst now = (_c = (_b11 = (_a11 = options._internal) == null ? void 0 : _a11.currentDate) == null ? void 0 : _b11.call(_a11).getTime()) != null ? _c : Date.now();\n\t\tif (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {\n\t\t\tlastFetchTime = now;\n\t\t\tpendingMetadata = new GatewayFetchMetadata({\n\t\t\t\tbaseURL,\n\t\t\t\theaders: getHeaders,\n\t\t\t\tfetch: options.fetch\n\t\t\t}).getAvailableModels().then((metadata) => {\n\t\t\t\tmetadataCache = metadata;\n\t\t\t\treturn metadata;\n\t\t\t}).catch(async (error) => {\n\t\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t\t});\n\t\t}\n\t\treturn metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;\n\t};\n\tconst getCredits = async () => {\n\t\treturn new GatewayFetchMetadata({\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch\n\t\t}).getCredits().catch(async (error) => {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t});\n\t};\n\tconst getSpendReport = async (params) => {\n\t\treturn new GatewaySpendReport({\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch\n\t\t}).getSpendReport(params).catch(async (error) => {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t});\n\t};\n\tconst getGenerationInfo = async (params) => {\n\t\treturn new GatewayGenerationInfoFetcher({\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch\n\t\t}).getGenerationInfo(params).catch(async (error) => {\n\t\t\tthrow await asGatewayError(error, await parseAuthMethod(await getHeaders()));\n\t\t});\n\t};\n\tconst provider = function(modelId) {\n\t\tif (new.target) throw new Error(\"The Gateway Provider model function cannot be called with the new keyword.\");\n\t\treturn createLanguageModel(modelId);\n\t};\n\tprovider.getAvailableModels = getAvailableModels;\n\tprovider.getCredits = getCredits;\n\tprovider.getSpendReport = getSpendReport;\n\tprovider.getGenerationInfo = getGenerationInfo;\n\tprovider.imageModel = (modelId) => {\n\t\treturn new GatewayImageModel(modelId, {\n\t\t\tprovider: \"gateway\",\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch,\n\t\t\to11yHeaders: createO11yHeaders()\n\t\t});\n\t};\n\tprovider.languageModel = createLanguageModel;\n\tprovider.textEmbeddingModel = (modelId) => {\n\t\treturn new GatewayEmbeddingModel(modelId, {\n\t\t\tprovider: \"gateway\",\n\t\t\tbaseURL,\n\t\t\theaders: getHeaders,\n\t\t\tfetch: options.fetch,\n\t\t\to11yHeaders: createO11yHeaders()\n\t\t});\n\t};\n\tprovider.tools = gatewayTools;\n\treturn provider;\n}\nvar gateway = createGatewayProvider();\nasync function getGatewayAuthToken(options) {\n\tconst apiKey = loadOptionalSetting({\n\t\tsettingValue: options.apiKey,\n\t\tenvironmentVariableName: \"AI_GATEWAY_API_KEY\"\n\t});\n\tif (apiKey) return {\n\t\ttoken: apiKey,\n\t\tauthMethod: \"api-key\"\n\t};\n\ttry {\n\t\treturn {\n\t\t\ttoken: await getVercelOidcToken(),\n\t\t\tauthMethod: \"oidc\"\n\t\t};\n\t} catch (e) {\n\t\treturn null;\n\t}\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js\n/** only globals that common to node and browsers are allowed */\nvar _globalThis = typeof globalThis === \"object\" ? globalThis : global;\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/version.js\nvar VERSION$1 = \"1.9.0\";\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/internal/semver.js\nvar re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n/**\n* Create a function to test an API version to see if it is compatible with the provided ownVersion.\n*\n* The returned function has the following semantics:\n* - Exact match is always compatible\n* - Major versions must match exactly\n* - 1.x package cannot use global 2.x package\n* - 2.x package cannot use global 1.x package\n* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n* - Patch and build tag differences are not considered at this time\n*\n* @param ownVersion version which should be checked against\n*/\nfunction _makeCompatibilityCheck(ownVersion) {\n\tvar acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);\n\tvar rejectedVersions = /* @__PURE__ */ new Set();\n\tvar myVersionMatch = ownVersion.match(re);\n\tif (!myVersionMatch) return function() {\n\t\treturn false;\n\t};\n\tvar ownVersionParsed = {\n\t\tmajor: +myVersionMatch[1],\n\t\tminor: +myVersionMatch[2],\n\t\tpatch: +myVersionMatch[3],\n\t\tprerelease: myVersionMatch[4]\n\t};\n\tif (ownVersionParsed.prerelease != null) return function isExactmatch(globalVersion) {\n\t\treturn globalVersion === ownVersion;\n\t};\n\tfunction _reject(v) {\n\t\trejectedVersions.add(v);\n\t\treturn false;\n\t}\n\tfunction _accept(v) {\n\t\tacceptedVersions.add(v);\n\t\treturn true;\n\t}\n\treturn function isCompatible(globalVersion) {\n\t\tif (acceptedVersions.has(globalVersion)) return true;\n\t\tif (rejectedVersions.has(globalVersion)) return false;\n\t\tvar globalVersionMatch = globalVersion.match(re);\n\t\tif (!globalVersionMatch) return _reject(globalVersion);\n\t\tvar globalVersionParsed = {\n\t\t\tmajor: +globalVersionMatch[1],\n\t\t\tminor: +globalVersionMatch[2],\n\t\t\tpatch: +globalVersionMatch[3],\n\t\t\tprerelease: globalVersionMatch[4]\n\t\t};\n\t\tif (globalVersionParsed.prerelease != null) return _reject(globalVersion);\n\t\tif (ownVersionParsed.major !== globalVersionParsed.major) return _reject(globalVersion);\n\t\tif (ownVersionParsed.major === 0) {\n\t\t\tif (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) return _accept(globalVersion);\n\t\t\treturn _reject(globalVersion);\n\t\t}\n\t\tif (ownVersionParsed.minor <= globalVersionParsed.minor) return _accept(globalVersion);\n\t\treturn _reject(globalVersion);\n\t};\n}\n/**\n* Test an API version to see if it is compatible with this API.\n*\n* - Exact match is always compatible\n* - Major versions must match exactly\n* - 1.x package cannot use global 2.x package\n* - 2.x package cannot use global 1.x package\n* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n* - Patch and build tag differences are not considered at this time\n*\n* @param version version of the API requesting an instance of the global API\n*/\nvar isCompatible = _makeCompatibilityCheck(VERSION$1);\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js\nvar major = VERSION$1.split(\".\")[0];\nvar GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\"opentelemetry.js.api.\" + major);\nvar _global = _globalThis;\nfunction registerGlobal(type, instance, diag, allowOverride) {\n\tvar _a;\n\tif (allowOverride === void 0) allowOverride = false;\n\tvar api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: VERSION$1 };\n\tif (!allowOverride && api[type]) {\n\t\tvar err = /* @__PURE__ */ new Error(\"@opentelemetry/api: Attempted duplicate registration of API: \" + type);\n\t\tdiag.error(err.stack || err.message);\n\t\treturn false;\n\t}\n\tif (api.version !== \"1.9.0\") {\n\t\tvar err = /* @__PURE__ */ new Error(\"@opentelemetry/api: Registration of version v\" + api.version + \" for \" + type + \" does not match previously registered API v\" + VERSION$1);\n\t\tdiag.error(err.stack || err.message);\n\t\treturn false;\n\t}\n\tapi[type] = instance;\n\tdiag.debug(\"@opentelemetry/api: Registered a global for \" + type + \" v\" + VERSION$1 + \".\");\n\treturn true;\n}\nfunction getGlobal(type) {\n\tvar _a, _b;\n\tvar globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;\n\tif (!globalVersion || !isCompatible(globalVersion)) return;\n\treturn (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];\n}\nfunction unregisterGlobal(type, diag) {\n\tdiag.debug(\"@opentelemetry/api: Unregistering a global for \" + type + \" v\" + VERSION$1 + \".\");\n\tvar api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\tif (api) delete api[type];\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js\nvar __read$3 = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray$3 = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\n/**\n* Component Logger which is meant to be used as part of any component which\n* will add automatically additional namespace in front of the log message.\n* It will then forward all message to global diag logger\n* @example\n* const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n* cLogger.debug('test');\n* // @opentelemetry/instrumentation-http test\n*/\nvar DiagComponentLogger = function() {\n\tfunction DiagComponentLogger(props) {\n\t\tthis._namespace = props.namespace || \"DiagComponentLogger\";\n\t}\n\tDiagComponentLogger.prototype.debug = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"debug\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.error = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"error\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.info = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"info\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.warn = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"warn\", this._namespace, args);\n\t};\n\tDiagComponentLogger.prototype.verbose = function() {\n\t\tvar args = [];\n\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\treturn logProxy(\"verbose\", this._namespace, args);\n\t};\n\treturn DiagComponentLogger;\n}();\nfunction logProxy(funcName, namespace, args) {\n\tvar logger = getGlobal(\"diag\");\n\tif (!logger) return;\n\targs.unshift(namespace);\n\treturn logger[funcName].apply(logger, __spreadArray$3([], __read$3(args), false));\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/diag/types.js\n/**\n* Defines the available internal logging levels for the diagnostic logger, the numeric values\n* of the levels are defined to match the original values from the initial LogLevel to avoid\n* compatibility/migration issues for any implementation that assume the numeric ordering.\n*/\nvar DiagLogLevel;\n(function(DiagLogLevel) {\n\t/** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n\tDiagLogLevel[DiagLogLevel[\"NONE\"] = 0] = \"NONE\";\n\t/** Identifies an error scenario */\n\tDiagLogLevel[DiagLogLevel[\"ERROR\"] = 30] = \"ERROR\";\n\t/** Identifies a warning scenario */\n\tDiagLogLevel[DiagLogLevel[\"WARN\"] = 50] = \"WARN\";\n\t/** General informational log message */\n\tDiagLogLevel[DiagLogLevel[\"INFO\"] = 60] = \"INFO\";\n\t/** General debug log message */\n\tDiagLogLevel[DiagLogLevel[\"DEBUG\"] = 70] = \"DEBUG\";\n\t/**\n\t* Detailed trace level logging should only be used for development, should only be set\n\t* in a development environment.\n\t*/\n\tDiagLogLevel[DiagLogLevel[\"VERBOSE\"] = 80] = \"VERBOSE\";\n\t/** Used to set the logging level to include all logging */\n\tDiagLogLevel[DiagLogLevel[\"ALL\"] = 9999] = \"ALL\";\n})(DiagLogLevel || (DiagLogLevel = {}));\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js\nfunction createLogLevelDiagLogger(maxLevel, logger) {\n\tif (maxLevel < DiagLogLevel.NONE) maxLevel = DiagLogLevel.NONE;\n\telse if (maxLevel > DiagLogLevel.ALL) maxLevel = DiagLogLevel.ALL;\n\tlogger = logger || {};\n\tfunction _filterFunc(funcName, theLevel) {\n\t\tvar theFunc = logger[funcName];\n\t\tif (typeof theFunc === \"function\" && maxLevel >= theLevel) return theFunc.bind(logger);\n\t\treturn function() {};\n\t}\n\treturn {\n\t\terror: _filterFunc(\"error\", DiagLogLevel.ERROR),\n\t\twarn: _filterFunc(\"warn\", DiagLogLevel.WARN),\n\t\tinfo: _filterFunc(\"info\", DiagLogLevel.INFO),\n\t\tdebug: _filterFunc(\"debug\", DiagLogLevel.DEBUG),\n\t\tverbose: _filterFunc(\"verbose\", DiagLogLevel.VERBOSE)\n\t};\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/api/diag.js\nvar __read$2 = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray$2 = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\nvar API_NAME$2 = \"diag\";\n/**\n* Singleton object which represents the entry point to the OpenTelemetry internal\n* diagnostic API\n*/\nvar DiagAPI = function() {\n\t/**\n\t* Private internal constructor\n\t* @private\n\t*/\n\tfunction DiagAPI() {\n\t\tfunction _logProxy(funcName) {\n\t\t\treturn function() {\n\t\t\t\tvar args = [];\n\t\t\t\tfor (var _i = 0; _i < arguments.length; _i++) args[_i] = arguments[_i];\n\t\t\t\tvar logger = getGlobal(\"diag\");\n\t\t\t\tif (!logger) return;\n\t\t\t\treturn logger[funcName].apply(logger, __spreadArray$2([], __read$2(args), false));\n\t\t\t};\n\t\t}\n\t\tvar self = this;\n\t\tvar setLogger = function(logger, optionsOrLogLevel) {\n\t\t\tvar _a, _b, _c;\n\t\t\tif (optionsOrLogLevel === void 0) optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };\n\t\t\tif (logger === self) {\n\t\t\t\tvar err = /* @__PURE__ */ new Error(\"Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation\");\n\t\t\t\tself.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (typeof optionsOrLogLevel === \"number\") optionsOrLogLevel = { logLevel: optionsOrLogLevel };\n\t\t\tvar oldLogger = getGlobal(\"diag\");\n\t\t\tvar newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);\n\t\t\tif (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n\t\t\t\tvar stack = (_c = (/* @__PURE__ */ new Error()).stack) !== null && _c !== void 0 ? _c : \"<failed to generate stacktrace>\";\n\t\t\t\toldLogger.warn(\"Current logger will be overwritten from \" + stack);\n\t\t\t\tnewLogger.warn(\"Current logger will overwrite one already registered from \" + stack);\n\t\t\t}\n\t\t\treturn registerGlobal(\"diag\", newLogger, self, true);\n\t\t};\n\t\tself.setLogger = setLogger;\n\t\tself.disable = function() {\n\t\t\tunregisterGlobal(API_NAME$2, self);\n\t\t};\n\t\tself.createComponentLogger = function(options) {\n\t\t\treturn new DiagComponentLogger(options);\n\t\t};\n\t\tself.verbose = _logProxy(\"verbose\");\n\t\tself.debug = _logProxy(\"debug\");\n\t\tself.info = _logProxy(\"info\");\n\t\tself.warn = _logProxy(\"warn\");\n\t\tself.error = _logProxy(\"error\");\n\t}\n\t/** Get the singleton instance of the DiagAPI API */\n\tDiagAPI.instance = function() {\n\t\tif (!this._instance) this._instance = new DiagAPI();\n\t\treturn this._instance;\n\t};\n\treturn DiagAPI;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/context/context.js\n/** Get a key to uniquely identify a context value */\nfunction createContextKey(description) {\n\treturn Symbol.for(description);\n}\n/** The root context is used as the default parent context when there is no active context */\nvar ROOT_CONTEXT = new (function() {\n\t/**\n\t* Construct a new context which inherits values from an optional parent context.\n\t*\n\t* @param parentContext a context from which to inherit values\n\t*/\n\tfunction BaseContext(parentContext) {\n\t\tvar self = this;\n\t\tself._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();\n\t\tself.getValue = function(key) {\n\t\t\treturn self._currentContext.get(key);\n\t\t};\n\t\tself.setValue = function(key, value) {\n\t\t\tvar context = new BaseContext(self._currentContext);\n\t\t\tcontext._currentContext.set(key, value);\n\t\t\treturn context;\n\t\t};\n\t\tself.deleteValue = function(key) {\n\t\t\tvar context = new BaseContext(self._currentContext);\n\t\t\tcontext._currentContext.delete(key);\n\t\t\treturn context;\n\t\t};\n\t}\n\treturn BaseContext;\n}())();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js\nvar __read$1 = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray$1 = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\nvar NoopContextManager = function() {\n\tfunction NoopContextManager() {}\n\tNoopContextManager.prototype.active = function() {\n\t\treturn ROOT_CONTEXT;\n\t};\n\tNoopContextManager.prototype.with = function(_context, fn, thisArg) {\n\t\tvar args = [];\n\t\tfor (var _i = 3; _i < arguments.length; _i++) args[_i - 3] = arguments[_i];\n\t\treturn fn.call.apply(fn, __spreadArray$1([thisArg], __read$1(args), false));\n\t};\n\tNoopContextManager.prototype.bind = function(_context, target) {\n\t\treturn target;\n\t};\n\tNoopContextManager.prototype.enable = function() {\n\t\treturn this;\n\t};\n\tNoopContextManager.prototype.disable = function() {\n\t\treturn this;\n\t};\n\treturn NoopContextManager;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/api/context.js\nvar __read = function(o, n) {\n\tvar m = typeof Symbol === \"function\" && o[Symbol.iterator];\n\tif (!m) return o;\n\tvar i = m.call(o), r, ar = [], e;\n\ttry {\n\t\twhile ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n\t} catch (error) {\n\t\te = { error };\n\t} finally {\n\t\ttry {\n\t\t\tif (r && !r.done && (m = i[\"return\"])) m.call(i);\n\t\t} finally {\n\t\t\tif (e) throw e.error;\n\t\t}\n\t}\n\treturn ar;\n};\nvar __spreadArray = function(to, from, pack) {\n\tif (pack || arguments.length === 2) {\n\t\tfor (var i = 0, l = from.length, ar; i < l; i++) if (ar || !(i in from)) {\n\t\t\tif (!ar) ar = Array.prototype.slice.call(from, 0, i);\n\t\t\tar[i] = from[i];\n\t\t}\n\t}\n\treturn to.concat(ar || Array.prototype.slice.call(from));\n};\nvar API_NAME$1 = \"context\";\nvar NOOP_CONTEXT_MANAGER = new NoopContextManager();\n/**\n* Singleton object which represents the entry point to the OpenTelemetry Context API\n*/\nvar ContextAPI = function() {\n\t/** Empty private constructor prevents end users from constructing a new instance of the API */\n\tfunction ContextAPI() {}\n\t/** Get the singleton instance of the Context API */\n\tContextAPI.getInstance = function() {\n\t\tif (!this._instance) this._instance = new ContextAPI();\n\t\treturn this._instance;\n\t};\n\t/**\n\t* Set the current context manager.\n\t*\n\t* @returns true if the context manager was successfully registered, else false\n\t*/\n\tContextAPI.prototype.setGlobalContextManager = function(contextManager) {\n\t\treturn registerGlobal(API_NAME$1, contextManager, DiagAPI.instance());\n\t};\n\t/**\n\t* Get the currently active context\n\t*/\n\tContextAPI.prototype.active = function() {\n\t\treturn this._getContextManager().active();\n\t};\n\t/**\n\t* Execute a function with an active context\n\t*\n\t* @param context context to be active during function execution\n\t* @param fn function to execute in a context\n\t* @param thisArg optional receiver to be used for calling fn\n\t* @param args optional arguments forwarded to fn\n\t*/\n\tContextAPI.prototype.with = function(context, fn, thisArg) {\n\t\tvar _a;\n\t\tvar args = [];\n\t\tfor (var _i = 3; _i < arguments.length; _i++) args[_i - 3] = arguments[_i];\n\t\treturn (_a = this._getContextManager()).with.apply(_a, __spreadArray([\n\t\t\tcontext,\n\t\t\tfn,\n\t\t\tthisArg\n\t\t], __read(args), false));\n\t};\n\t/**\n\t* Bind a context to a target function or event emitter\n\t*\n\t* @param context context to bind to the event emitter or function. Defaults to the currently active context\n\t* @param target function or event emitter to bind\n\t*/\n\tContextAPI.prototype.bind = function(context, target) {\n\t\treturn this._getContextManager().bind(context, target);\n\t};\n\tContextAPI.prototype._getContextManager = function() {\n\t\treturn getGlobal(API_NAME$1) || NOOP_CONTEXT_MANAGER;\n\t};\n\t/** Disable and remove the global context manager */\n\tContextAPI.prototype.disable = function() {\n\t\tthis._getContextManager().disable();\n\t\tunregisterGlobal(API_NAME$1, DiagAPI.instance());\n\t};\n\treturn ContextAPI;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js\nvar TraceFlags;\n(function(TraceFlags) {\n\t/** Represents no flag set. */\n\tTraceFlags[TraceFlags[\"NONE\"] = 0] = \"NONE\";\n\t/** Bit to represent whether trace is sampled in trace flags. */\n\tTraceFlags[TraceFlags[\"SAMPLED\"] = 1] = \"SAMPLED\";\n})(TraceFlags || (TraceFlags = {}));\nvar INVALID_SPAN_CONTEXT = {\n\ttraceId: \"00000000000000000000000000000000\",\n\tspanId: \"0000000000000000\",\n\ttraceFlags: TraceFlags.NONE\n};\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js\n/**\n* The NonRecordingSpan is the default {@link Span} that is used when no Span\n* implementation is available. All operations are no-op including context\n* propagation.\n*/\nvar NonRecordingSpan = function() {\n\tfunction NonRecordingSpan(_spanContext) {\n\t\tif (_spanContext === void 0) _spanContext = INVALID_SPAN_CONTEXT;\n\t\tthis._spanContext = _spanContext;\n\t}\n\tNonRecordingSpan.prototype.spanContext = function() {\n\t\treturn this._spanContext;\n\t};\n\tNonRecordingSpan.prototype.setAttribute = function(_key, _value) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.setAttributes = function(_attributes) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.addEvent = function(_name, _attributes) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.addLink = function(_link) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.addLinks = function(_links) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.setStatus = function(_status) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.updateName = function(_name) {\n\t\treturn this;\n\t};\n\tNonRecordingSpan.prototype.end = function(_endTime) {};\n\tNonRecordingSpan.prototype.isRecording = function() {\n\t\treturn false;\n\t};\n\tNonRecordingSpan.prototype.recordException = function(_exception, _time) {};\n\treturn NonRecordingSpan;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js\n/**\n* span key\n*/\nvar SPAN_KEY = createContextKey(\"OpenTelemetry Context Key SPAN\");\n/**\n* Return the span if one exists\n*\n* @param context context to get span from\n*/\nfunction getSpan(context) {\n\treturn context.getValue(SPAN_KEY) || void 0;\n}\n/**\n* Gets the span from the current context, if one exists.\n*/\nfunction getActiveSpan() {\n\treturn getSpan(ContextAPI.getInstance().active());\n}\n/**\n* Set the span on a context\n*\n* @param context context to use as parent\n* @param span span to set active\n*/\nfunction setSpan(context, span) {\n\treturn context.setValue(SPAN_KEY, span);\n}\n/**\n* Remove current span stored in the context\n*\n* @param context context to delete span from\n*/\nfunction deleteSpan(context) {\n\treturn context.deleteValue(SPAN_KEY);\n}\n/**\n* Wrap span context in a NoopSpan and set as span in a new\n* context\n*\n* @param context context to set active span on\n* @param spanContext span context to be wrapped\n*/\nfunction setSpanContext(context, spanContext) {\n\treturn setSpan(context, new NonRecordingSpan(spanContext));\n}\n/**\n* Get the span context of the span if it exists.\n*\n* @param context context to get values from\n*/\nfunction getSpanContext(context) {\n\tvar _a;\n\treturn (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js\nvar VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;\nvar VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;\nfunction isValidTraceId(traceId) {\n\treturn VALID_TRACEID_REGEX.test(traceId) && traceId !== \"00000000000000000000000000000000\";\n}\nfunction isValidSpanId(spanId) {\n\treturn VALID_SPANID_REGEX.test(spanId) && spanId !== \"0000000000000000\";\n}\n/**\n* Returns true if this {@link SpanContext} is valid.\n* @return true if this {@link SpanContext} is valid.\n*/\nfunction isSpanContextValid(spanContext) {\n\treturn isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);\n}\n/**\n* Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n*\n* @param spanContext span context to be wrapped\n* @returns a new non-recording {@link Span} with the provided context\n*/\nfunction wrapSpanContext(spanContext) {\n\treturn new NonRecordingSpan(spanContext);\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js\nvar contextApi = ContextAPI.getInstance();\n/**\n* No-op implementations of {@link Tracer}.\n*/\nvar NoopTracer = function() {\n\tfunction NoopTracer() {}\n\tNoopTracer.prototype.startSpan = function(name, options, context) {\n\t\tif (context === void 0) context = contextApi.active();\n\t\tif (Boolean(options === null || options === void 0 ? void 0 : options.root)) return new NonRecordingSpan();\n\t\tvar parentFromContext = context && getSpanContext(context);\n\t\tif (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan(parentFromContext);\n\t\telse return new NonRecordingSpan();\n\t};\n\tNoopTracer.prototype.startActiveSpan = function(name, arg2, arg3, arg4) {\n\t\tvar opts;\n\t\tvar ctx;\n\t\tvar fn;\n\t\tif (arguments.length < 2) return;\n\t\telse if (arguments.length === 2) fn = arg2;\n\t\telse if (arguments.length === 3) {\n\t\t\topts = arg2;\n\t\t\tfn = arg3;\n\t\t} else {\n\t\t\topts = arg2;\n\t\t\tctx = arg3;\n\t\t\tfn = arg4;\n\t\t}\n\t\tvar parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();\n\t\tvar span = this.startSpan(name, opts, parentContext);\n\t\tvar contextWithSpanSet = setSpan(parentContext, span);\n\t\treturn contextApi.with(contextWithSpanSet, fn, void 0, span);\n\t};\n\treturn NoopTracer;\n}();\nfunction isSpanContext(spanContext) {\n\treturn typeof spanContext === \"object\" && typeof spanContext[\"spanId\"] === \"string\" && typeof spanContext[\"traceId\"] === \"string\" && typeof spanContext[\"traceFlags\"] === \"number\";\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js\nvar NOOP_TRACER = new NoopTracer();\n/**\n* Proxy tracer provided by the proxy tracer provider\n*/\nvar ProxyTracer = function() {\n\tfunction ProxyTracer(_provider, name, version, options) {\n\t\tthis._provider = _provider;\n\t\tthis.name = name;\n\t\tthis.version = version;\n\t\tthis.options = options;\n\t}\n\tProxyTracer.prototype.startSpan = function(name, options, context) {\n\t\treturn this._getTracer().startSpan(name, options, context);\n\t};\n\tProxyTracer.prototype.startActiveSpan = function(_name, _options, _context, _fn) {\n\t\tvar tracer = this._getTracer();\n\t\treturn Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n\t};\n\t/**\n\t* Try to get a tracer from the proxy tracer provider.\n\t* If the proxy tracer provider has no delegate, return a noop tracer.\n\t*/\n\tProxyTracer.prototype._getTracer = function() {\n\t\tif (this._delegate) return this._delegate;\n\t\tvar tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);\n\t\tif (!tracer) return NOOP_TRACER;\n\t\tthis._delegate = tracer;\n\t\treturn this._delegate;\n\t};\n\treturn ProxyTracer;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js\nvar NOOP_TRACER_PROVIDER = new (function() {\n\tfunction NoopTracerProvider() {}\n\tNoopTracerProvider.prototype.getTracer = function(_name, _version, _options) {\n\t\treturn new NoopTracer();\n\t};\n\treturn NoopTracerProvider;\n}())();\n/**\n* Tracer provider which provides {@link ProxyTracer}s.\n*\n* Before a delegate is set, tracers provided are NoOp.\n* When a delegate is set, traces are provided from the delegate.\n* When a delegate is set after tracers have already been provided,\n* all tracers already provided will use the provided delegate implementation.\n*/\nvar ProxyTracerProvider = function() {\n\tfunction ProxyTracerProvider() {}\n\t/**\n\t* Get a {@link ProxyTracer}\n\t*/\n\tProxyTracerProvider.prototype.getTracer = function(name, version, options) {\n\t\tvar _a;\n\t\treturn (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);\n\t};\n\tProxyTracerProvider.prototype.getDelegate = function() {\n\t\tvar _a;\n\t\treturn (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;\n\t};\n\t/**\n\t* Set the delegate tracer provider\n\t*/\n\tProxyTracerProvider.prototype.setDelegate = function(delegate) {\n\t\tthis._delegate = delegate;\n\t};\n\tProxyTracerProvider.prototype.getDelegateTracer = function(name, version, options) {\n\t\tvar _a;\n\t\treturn (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);\n\t};\n\treturn ProxyTracerProvider;\n}();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace/status.js\n/**\n* An enumeration of status codes.\n*/\nvar SpanStatusCode;\n(function(SpanStatusCode) {\n\t/**\n\t* The default status.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"UNSET\"] = 0] = \"UNSET\";\n\t/**\n\t* The operation has been validated by an Application developer or\n\t* Operator to have completed successfully.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"OK\"] = 1] = \"OK\";\n\t/**\n\t* The operation contains an error.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"ERROR\"] = 2] = \"ERROR\";\n})(SpanStatusCode || (SpanStatusCode = {}));\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/api/trace.js\nvar API_NAME = \"trace\";\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.0/ee469078ed078052a7533b2805abc7686d72155c80f67e8929d9d1ae6c630f05/node_modules/@opentelemetry/api/build/esm/trace-api.js\n/** Entrypoint for trace API */\nvar trace = function() {\n\t/** Empty private constructor prevents end users from constructing a new instance of the API */\n\tfunction TraceAPI() {\n\t\tthis._proxyTracerProvider = new ProxyTracerProvider();\n\t\tthis.wrapSpanContext = wrapSpanContext;\n\t\tthis.isSpanContextValid = isSpanContextValid;\n\t\tthis.deleteSpan = deleteSpan;\n\t\tthis.getSpan = getSpan;\n\t\tthis.getActiveSpan = getActiveSpan;\n\t\tthis.getSpanContext = getSpanContext;\n\t\tthis.setSpan = setSpan;\n\t\tthis.setSpanContext = setSpanContext;\n\t}\n\t/** Get the singleton instance of the Trace API */\n\tTraceAPI.getInstance = function() {\n\t\tif (!this._instance) this._instance = new TraceAPI();\n\t\treturn this._instance;\n\t};\n\t/**\n\t* Set the current global tracer.\n\t*\n\t* @returns true if the tracer provider was successfully registered, else false\n\t*/\n\tTraceAPI.prototype.setGlobalTracerProvider = function(provider) {\n\t\tvar success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());\n\t\tif (success) this._proxyTracerProvider.setDelegate(provider);\n\t\treturn success;\n\t};\n\t/**\n\t* Returns the global tracer provider.\n\t*/\n\tTraceAPI.prototype.getTracerProvider = function() {\n\t\treturn getGlobal(API_NAME) || this._proxyTracerProvider;\n\t};\n\t/**\n\t* Returns a tracer from the global tracer provider.\n\t*/\n\tTraceAPI.prototype.getTracer = function(name, version) {\n\t\treturn this.getTracerProvider().getTracer(name, version);\n\t};\n\t/** Remove the global tracer provider */\n\tTraceAPI.prototype.disable = function() {\n\t\tunregisterGlobal(API_NAME, DiagAPI.instance());\n\t\tthis._proxyTracerProvider = new ProxyTracerProvider();\n\t};\n\treturn TraceAPI;\n}().getInstance();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ai/5.0.226/fac8217dc8d34e85b5f38a8cc71c59a1b2ae6d9f27e0dd1e2738a30e54e8ae3c/node_modules/ai/dist/index.mjs\nvar __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n\tfor (var name16 in all) __defProp(target, name16, {\n\t\tget: all[name16],\n\t\tenumerable: true\n\t});\n};\nvar name = \"AI_NoOutputSpecifiedError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a;\nvar NoOutputSpecifiedError = class extends AISDKError {\n\tconstructor({ message = \"No output specified.\" } = {}) {\n\t\tsuper({\n\t\t\tname,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker);\n\t}\n};\n_a = symbol;\nfunction formatWarning(warning) {\n\tconst prefix = \"AI SDK Warning:\";\n\tswitch (warning.type) {\n\t\tcase \"unsupported-setting\": {\n\t\t\tlet message = `${prefix} The \"${warning.setting}\" setting is not supported by this model`;\n\t\t\tif (warning.details) message += ` - ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"unsupported-tool\": {\n\t\t\tlet message = `${prefix} The tool \"${\"name\" in warning.tool ? warning.tool.name : \"unknown tool\"}\" is not supported by this model`;\n\t\t\tif (warning.details) message += ` - ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"other\": return `${prefix} ${warning.message}`;\n\t\tdefault: return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n\t}\n}\nvar FIRST_WARNING_INFO_MESSAGE = \"AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.\";\nvar hasLoggedBefore = false;\nfunction emitWarning({ message, type }) {\n\tif (typeof process !== \"undefined\" && typeof process.emitWarning === \"function\") process.emitWarning(message, { type });\n\telse console.warn(message);\n}\nvar logWarnings = (warnings) => {\n\tif (warnings.length === 0) return;\n\tconst logger = globalThis.AI_SDK_LOG_WARNINGS;\n\tif (logger === false) return;\n\tif (typeof logger === \"function\") {\n\t\tlogger(warnings);\n\t\treturn;\n\t}\n\tif (!hasLoggedBefore) {\n\t\thasLoggedBefore = true;\n\t\temitWarning({\n\t\t\tmessage: FIRST_WARNING_INFO_MESSAGE,\n\t\t\ttype: \"Warning\"\n\t\t});\n\t}\n\tfor (const warning of warnings) emitWarning({\n\t\tmessage: formatWarning(warning),\n\t\ttype: \"Warning\"\n\t});\n};\nvar name2 = \"AI_InvalidArgumentError\";\nvar marker2 = `vercel.ai.error.${name2}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2;\nvar InvalidArgumentError = class extends AISDKError {\n\tconstructor({ parameter, value, message }) {\n\t\tsuper({\n\t\t\tname: name2,\n\t\t\tmessage: `Invalid argument for parameter ${parameter}: ${message}`\n\t\t});\n\t\tthis[_a2] = true;\n\t\tthis.parameter = parameter;\n\t\tthis.value = value;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker2);\n\t}\n};\n_a2 = symbol2;\nvar name3 = \"AI_InvalidStreamPartError\";\nvar marker3 = `vercel.ai.error.${name3}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3;\nvar InvalidStreamPartError = class extends AISDKError {\n\tconstructor({ chunk, message }) {\n\t\tsuper({\n\t\t\tname: name3,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a3] = true;\n\t\tthis.chunk = chunk;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker3);\n\t}\n};\n_a3 = symbol3;\nvar name4 = \"AI_InvalidToolInputError\";\nvar marker4 = `vercel.ai.error.${name4}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4;\nvar InvalidToolInputError = class extends AISDKError {\n\tconstructor({ toolInput, toolName, cause, message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name4,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a4] = true;\n\t\tthis.toolInput = toolInput;\n\t\tthis.toolName = toolName;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker4);\n\t}\n};\n_a4 = symbol4;\nvar name5 = \"AI_NoImageGeneratedError\";\nvar marker5 = `vercel.ai.error.${name5}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5;\nvar NoImageGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No image generated.\", cause, responses }) {\n\t\tsuper({\n\t\t\tname: name5,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a5] = true;\n\t\tthis.responses = responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker5);\n\t}\n};\n_a5 = symbol5;\nvar name6 = \"AI_NoObjectGeneratedError\";\nvar marker6 = `vercel.ai.error.${name6}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6;\nvar NoObjectGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No object generated.\", cause, text: text2, response, usage, finishReason }) {\n\t\tsuper({\n\t\t\tname: name6,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a6] = true;\n\t\tthis.text = text2;\n\t\tthis.response = response;\n\t\tthis.usage = usage;\n\t\tthis.finishReason = finishReason;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker6);\n\t}\n};\n_a6 = symbol6;\nvar name7 = \"AI_NoOutputGeneratedError\";\nvar marker7 = `vercel.ai.error.${name7}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7;\nvar NoOutputGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No output generated.\", cause } = {}) {\n\t\tsuper({\n\t\t\tname: name7,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a7] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker7);\n\t}\n};\n_a7 = symbol7;\nvar NoSpeechGeneratedError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_NoSpeechGeneratedError\",\n\t\t\tmessage: \"No speech audio generated.\"\n\t\t});\n\t\tthis.responses = options.responses;\n\t}\n};\nvar name8 = \"AI_NoSuchToolError\";\nvar marker8 = `vercel.ai.error.${name8}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8;\nvar NoSuchToolError = class extends AISDKError {\n\tconstructor({ toolName, availableTools = void 0, message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? \"No tools are available.\" : `Available tools: ${availableTools.join(\", \")}.`}` }) {\n\t\tsuper({\n\t\t\tname: name8,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a8] = true;\n\t\tthis.toolName = toolName;\n\t\tthis.availableTools = availableTools;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker8);\n\t}\n};\n_a8 = symbol8;\nvar name9 = \"AI_ToolCallRepairError\";\nvar marker9 = `vercel.ai.error.${name9}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9;\nvar ToolCallRepairError = class extends AISDKError {\n\tconstructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name9,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a9] = true;\n\t\tthis.originalError = originalError;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker9);\n\t}\n};\n_a9 = symbol9;\nvar UnsupportedModelVersionError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_UnsupportedModelVersionError\",\n\t\t\tmessage: `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". AI SDK 5 only supports models that implement specification version \"v2\".`\n\t\t});\n\t\tthis.version = options.version;\n\t\tthis.provider = options.provider;\n\t\tthis.modelId = options.modelId;\n\t}\n};\nvar name10 = \"AI_InvalidDataContentError\";\nvar marker10 = `vercel.ai.error.${name10}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10;\nvar InvalidDataContentError = class extends AISDKError {\n\tconstructor({ content, cause, message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.` }) {\n\t\tsuper({\n\t\t\tname: name10,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a10] = true;\n\t\tthis.content = content;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker10);\n\t}\n};\n_a10 = symbol10;\nvar name11 = \"AI_InvalidMessageRoleError\";\nvar marker11 = `vercel.ai.error.${name11}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11;\nvar InvalidMessageRoleError = class extends AISDKError {\n\tconstructor({ role, message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".` }) {\n\t\tsuper({\n\t\t\tname: name11,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a11] = true;\n\t\tthis.role = role;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker11);\n\t}\n};\n_a11 = symbol11;\nvar name12 = \"AI_MessageConversionError\";\nvar marker12 = `vercel.ai.error.${name12}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12;\nvar MessageConversionError = class extends AISDKError {\n\tconstructor({ originalMessage, message }) {\n\t\tsuper({\n\t\t\tname: name12,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a12] = true;\n\t\tthis.originalMessage = originalMessage;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker12);\n\t}\n};\n_a12 = symbol12;\nvar name13 = \"AI_DownloadError\";\nvar marker13 = `vercel.ai.error.${name13}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13;\nvar DownloadError = class extends AISDKError {\n\tconstructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) {\n\t\tsuper({\n\t\t\tname: name13,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a13] = true;\n\t\tthis.url = url;\n\t\tthis.statusCode = statusCode;\n\t\tthis.statusText = statusText;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker13);\n\t}\n};\n_a13 = symbol13;\nvar name14 = \"AI_RetryError\";\nvar marker14 = `vercel.ai.error.${name14}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14;\nvar RetryError = class extends AISDKError {\n\tconstructor({ message, reason, errors }) {\n\t\tsuper({\n\t\t\tname: name14,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a14] = true;\n\t\tthis.reason = reason;\n\t\tthis.errors = errors;\n\t\tthis.lastError = errors[errors.length - 1];\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker14);\n\t}\n};\n_a14 = symbol14;\nfunction resolveLanguageModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\t\tversion: model.specificationVersion,\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId\n\t\t});\n\t\treturn model;\n\t}\n\treturn getGlobalProvider().languageModel(model);\n}\nfunction resolveEmbeddingModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\t\tversion: model.specificationVersion,\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId\n\t\t});\n\t\treturn model;\n\t}\n\treturn getGlobalProvider().textEmbeddingModel(model);\n}\nfunction resolveImageModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\t\tversion: model.specificationVersion,\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId\n\t\t});\n\t\treturn model;\n\t}\n\treturn getGlobalProvider().imageModel(model);\n}\nfunction getGlobalProvider() {\n\tvar _a16;\n\treturn (_a16 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a16 : gateway;\n}\nvar imageMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"image/gif\",\n\t\tbytesPrefix: [\n\t\t\t71,\n\t\t\t73,\n\t\t\t70\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/png\",\n\t\tbytesPrefix: [\n\t\t\t137,\n\t\t\t80,\n\t\t\t78,\n\t\t\t71\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/jpeg\",\n\t\tbytesPrefix: [255, 216]\n\t},\n\t{\n\t\tmediaType: \"image/webp\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t69,\n\t\t\t66,\n\t\t\t80\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/bmp\",\n\t\tbytesPrefix: [66, 77]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t73,\n\t\t\t73,\n\t\t\t42,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t77,\n\t\t\t77,\n\t\t\t0,\n\t\t\t42\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/avif\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t32,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t97,\n\t\t\t118,\n\t\t\t105,\n\t\t\t102\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/heic\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t32,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t104,\n\t\t\t101,\n\t\t\t105,\n\t\t\t99\n\t\t]\n\t}\n];\nvar audioMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 251]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 250]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 243]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 242]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 227]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 226]\n\t},\n\t{\n\t\tmediaType: \"audio/wav\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t65,\n\t\t\t86,\n\t\t\t69\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/ogg\",\n\t\tbytesPrefix: [\n\t\t\t79,\n\t\t\t103,\n\t\t\t103,\n\t\t\t83\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/flac\",\n\t\tbytesPrefix: [\n\t\t\t102,\n\t\t\t76,\n\t\t\t97,\n\t\t\t67\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [\n\t\t\t64,\n\t\t\t21,\n\t\t\t0,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/mp4\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\tnull,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/webm\",\n\t\tbytesPrefix: [\n\t\t\t26,\n\t\t\t69,\n\t\t\t223,\n\t\t\t163\n\t\t]\n\t}\n];\nvar DEFAULT_SNIFF_BYTES = 18;\nvar ID3_SCAN_BYTES = 131084;\nfunction decodePrefix(data, maxBytes) {\n\tif (typeof data !== \"string\") return data.length > maxBytes ? data.subarray(0, maxBytes) : data;\n\tconst maxChars = Math.ceil(maxBytes / 3) * 4;\n\tconst bytes = convertBase64ToUint8Array(data.substring(0, Math.min(data.length, maxChars)));\n\treturn bytes.length > maxBytes ? bytes.subarray(0, maxBytes) : bytes;\n}\nfunction hasID3(bytes) {\n\treturn bytes.length > 10 && bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51;\n}\nvar stripID3 = (bytes) => {\n\tconst id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;\n\treturn bytes.subarray(id3Size + 10);\n};\nfunction detectMediaType({ data, signatures }) {\n\tlet bytes = decodePrefix(data, DEFAULT_SNIFF_BYTES);\n\tif (hasID3(bytes)) bytes = stripID3(decodePrefix(data, ID3_SCAN_BYTES));\n\tfor (const signature of signatures) if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) return signature.mediaType;\n}\nvar VERSION = \"5.0.226\";\nvar download = async ({ url, maxBytes, abortSignal }) => {\n\tvar _a16;\n\tconst urlText = url.toString();\n\ttry {\n\t\tconst response = await fetchWithValidatedRedirects({\n\t\t\turl: urlText,\n\t\t\theaders: withUserAgentSuffix({}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tabortSignal\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError$1({\n\t\t\t\turl: urlText,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tstatusText: response.statusText\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tdata: await readResponseWithSizeLimit({\n\t\t\t\tresponse,\n\t\t\t\turl: urlText,\n\t\t\t\tmaxBytes: maxBytes != null ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE\n\t\t\t}),\n\t\t\tmediaType: (_a16 = response.headers.get(\"content-type\")) != null ? _a16 : void 0\n\t\t};\n\t} catch (error) {\n\t\tif (DownloadError$1.isInstance(error)) throw error;\n\t\tthrow new DownloadError$1({\n\t\t\turl: urlText,\n\t\t\tcause: error\n\t\t});\n\t}\n};\nvar createDefaultDownloadFunction = (download2 = download) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : download2(requestedDownload)));\nfunction splitDataUrl(dataUrl) {\n\ttry {\n\t\tconst [header, base64Content] = dataUrl.split(\",\");\n\t\treturn {\n\t\t\tmediaType: header.split(\";\")[0].split(\":\")[1],\n\t\t\tbase64Content\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tmediaType: void 0,\n\t\t\tbase64Content: void 0\n\t\t};\n\t}\n}\nvar dataContentSchema = z.union([\n\tz.string(),\n\tz.instanceof(Uint8Array),\n\tz.instanceof(ArrayBuffer),\n\tz.custom((value) => {\n\t\tvar _a16, _b;\n\t\treturn (_b = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b : false;\n\t}, { message: \"Must be a Buffer\" })\n]);\nfunction convertToLanguageModelV2DataContent(content) {\n\tif (content instanceof Uint8Array) return {\n\t\tdata: content,\n\t\tmediaType: void 0\n\t};\n\tif (content instanceof ArrayBuffer) return {\n\t\tdata: new Uint8Array(content),\n\t\tmediaType: void 0\n\t};\n\tif (typeof content === \"string\") try {\n\t\tcontent = new URL(content);\n\t} catch (error) {}\n\tif (content instanceof URL && content.protocol === \"data:\") {\n\t\tconst { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(content.toString());\n\t\tif (dataUrlMediaType == null || base64Content == null) throw new AISDKError({\n\t\t\tname: \"InvalidDataContentError\",\n\t\t\tmessage: `Invalid data URL format in content ${content.toString()}`\n\t\t});\n\t\treturn {\n\t\t\tdata: base64Content,\n\t\t\tmediaType: dataUrlMediaType\n\t\t};\n\t}\n\treturn {\n\t\tdata: content,\n\t\tmediaType: void 0\n\t};\n}\nfunction convertDataContentToBase64String(content) {\n\tif (typeof content === \"string\") return content;\n\tif (content instanceof ArrayBuffer) return convertUint8ArrayToBase64(new Uint8Array(content));\n\treturn convertUint8ArrayToBase64(content);\n}\nfunction convertDataContentToUint8Array(content) {\n\tif (content instanceof Uint8Array) return content;\n\tif (typeof content === \"string\") try {\n\t\treturn convertBase64ToUint8Array(content);\n\t} catch (error) {\n\t\tthrow new InvalidDataContentError({\n\t\t\tmessage: \"Invalid data content. Content string is not a base64-encoded media.\",\n\t\t\tcontent,\n\t\t\tcause: error\n\t\t});\n\t}\n\tif (content instanceof ArrayBuffer) return new Uint8Array(content);\n\tthrow new InvalidDataContentError({ content });\n}\nasync function convertToLanguageModelPrompt({ prompt, supportedUrls, download: download2 = createDefaultDownloadFunction() }) {\n\tconst downloadedAssets = await downloadAssets(prompt.messages, download2, supportedUrls);\n\treturn [...prompt.system != null ? [{\n\t\trole: \"system\",\n\t\tcontent: prompt.system\n\t}] : [], ...prompt.messages.map((message) => convertToLanguageModelMessage({\n\t\tmessage,\n\t\tdownloadedAssets\n\t}))];\n}\nfunction convertToLanguageModelMessage({ message, downloadedAssets }) {\n\tconst role = message.role;\n\tswitch (role) {\n\t\tcase \"system\": return {\n\t\t\trole: \"system\",\n\t\t\tcontent: message.content,\n\t\t\tproviderOptions: message.providerOptions\n\t\t};\n\t\tcase \"user\":\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\treturn {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== \"text\" || part.text !== \"\"),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\tcase \"assistant\":\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\treturn {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: message.content.filter((part) => part.type !== \"text\" || part.text !== \"\" || part.providerOptions != null).map((part) => {\n\t\t\t\t\tconst providerOptions = part.providerOptions;\n\t\t\t\t\tswitch (part.type) {\n\t\t\t\t\t\tcase \"file\": {\n\t\t\t\t\t\t\tconst { data, mediaType } = convertToLanguageModelV2DataContent(part.data);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\t\t\tmediaType: mediaType != null ? mediaType : part.mediaType,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"reasoning\": return {\n\t\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"text\": return {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-call\": return {\n\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-result\": return {\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\tcase \"tool\": return {\n\t\t\trole: \"tool\",\n\t\t\tcontent: message.content.map((part) => ({\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\toutput: part.output,\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t})),\n\t\t\tproviderOptions: message.providerOptions\n\t\t};\n\t\tdefault: throw new InvalidMessageRoleError({ role });\n\t}\n}\nasync function downloadAssets(messages, download2, supportedUrls) {\n\tconst plannedDownloads = messages.filter((message) => message.role === \"user\").map((message) => message.content).filter((content) => Array.isArray(content)).flat().filter((part) => part.type === \"image\" || part.type === \"file\").map((part) => {\n\t\tvar _a16;\n\t\tconst mediaType = (_a16 = part.mediaType) != null ? _a16 : part.type === \"image\" ? \"image/*\" : void 0;\n\t\tlet data = part.type === \"image\" ? part.image : part.data;\n\t\tif (typeof data === \"string\") try {\n\t\t\tdata = new URL(data);\n\t\t} catch (ignored) {}\n\t\treturn {\n\t\t\tmediaType,\n\t\t\tdata\n\t\t};\n\t}).filter((part) => part.data instanceof URL).map((part) => ({\n\t\turl: part.data,\n\t\tisUrlSupportedByModel: part.mediaType != null && isUrlSupported({\n\t\t\turl: part.data.toString(),\n\t\t\tmediaType: part.mediaType,\n\t\t\tsupportedUrls\n\t\t})\n\t}));\n\tconst downloadedFiles = await download2(plannedDownloads);\n\treturn Object.fromEntries(downloadedFiles.map((file, index) => file == null ? null : [plannedDownloads[index].url.toString(), {\n\t\tdata: file.data,\n\t\tmediaType: file.mediaType\n\t}]).filter((file) => file != null));\n}\nfunction convertPartToLanguageModelPart(part, downloadedAssets) {\n\tvar _a16;\n\tif (part.type === \"text\") return {\n\t\ttype: \"text\",\n\t\ttext: part.text,\n\t\tproviderOptions: part.providerOptions\n\t};\n\tlet originalData;\n\tconst type = part.type;\n\tswitch (type) {\n\t\tcase \"image\":\n\t\t\toriginalData = part.image;\n\t\t\tbreak;\n\t\tcase \"file\":\n\t\t\toriginalData = part.data;\n\t\t\tbreak;\n\t\tdefault: throw new Error(`Unsupported part type: ${type}`);\n\t}\n\tconst { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV2DataContent(originalData);\n\tlet mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;\n\tlet data = convertedData;\n\tif (data instanceof URL) {\n\t\tconst downloadedFile = downloadedAssets[data.toString()];\n\t\tif (downloadedFile) {\n\t\t\tdata = downloadedFile.data;\n\t\t\tmediaType ??= downloadedFile.mediaType;\n\t\t}\n\t}\n\tswitch (type) {\n\t\tcase \"image\":\n\t\t\tif (data instanceof Uint8Array || typeof data === \"string\") mediaType = (_a16 = detectMediaType({\n\t\t\t\tdata,\n\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t})) != null ? _a16 : mediaType;\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType: mediaType != null ? mediaType : \"image/*\",\n\t\t\t\tfilename: void 0,\n\t\t\t\tdata,\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t};\n\t\tcase \"file\":\n\t\t\tif (mediaType == null) throw new Error(`Media type is missing for file part`);\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType,\n\t\t\t\tfilename: part.filename,\n\t\t\t\tdata,\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t};\n\t}\n}\nfunction prepareCallSettings({ maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, seed, stopSequences }) {\n\tif (maxOutputTokens != null) {\n\t\tif (!Number.isInteger(maxOutputTokens)) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be an integer\"\n\t\t});\n\t\tif (maxOutputTokens < 1) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be >= 1\"\n\t\t});\n\t}\n\tif (temperature != null) {\n\t\tif (typeof temperature !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"temperature\",\n\t\t\tvalue: temperature,\n\t\t\tmessage: \"temperature must be a number\"\n\t\t});\n\t}\n\tif (topP != null) {\n\t\tif (typeof topP !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topP\",\n\t\t\tvalue: topP,\n\t\t\tmessage: \"topP must be a number\"\n\t\t});\n\t}\n\tif (topK != null) {\n\t\tif (typeof topK !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topK\",\n\t\t\tvalue: topK,\n\t\t\tmessage: \"topK must be a number\"\n\t\t});\n\t}\n\tif (presencePenalty != null) {\n\t\tif (typeof presencePenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"presencePenalty\",\n\t\t\tvalue: presencePenalty,\n\t\t\tmessage: \"presencePenalty must be a number\"\n\t\t});\n\t}\n\tif (frequencyPenalty != null) {\n\t\tif (typeof frequencyPenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"frequencyPenalty\",\n\t\t\tvalue: frequencyPenalty,\n\t\t\tmessage: \"frequencyPenalty must be a number\"\n\t\t});\n\t}\n\tif (seed != null) {\n\t\tif (!Number.isInteger(seed)) throw new InvalidArgumentError({\n\t\t\tparameter: \"seed\",\n\t\t\tvalue: seed,\n\t\t\tmessage: \"seed must be an integer\"\n\t\t});\n\t}\n\treturn {\n\t\tmaxOutputTokens,\n\t\ttemperature,\n\t\ttopP,\n\t\ttopK,\n\t\tpresencePenalty,\n\t\tfrequencyPenalty,\n\t\tstopSequences,\n\t\tseed\n\t};\n}\nfunction isNonEmptyObject(object2) {\n\treturn object2 != null && Object.keys(object2).length > 0;\n}\nfunction prepareToolsAndToolChoice({ tools, toolChoice, activeTools }) {\n\tif (!isNonEmptyObject(tools)) return {\n\t\ttools: void 0,\n\t\ttoolChoice: void 0\n\t};\n\treturn {\n\t\ttools: (activeTools != null ? Object.entries(tools).filter(([name16]) => activeTools.includes(name16)) : Object.entries(tools)).map(([name16, tool2]) => {\n\t\t\tconst toolType = tool2.type;\n\t\t\tswitch (toolType) {\n\t\t\t\tcase void 0:\n\t\t\t\tcase \"dynamic\":\n\t\t\t\tcase \"function\": return {\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tname: name16,\n\t\t\t\t\tdescription: tool2.description,\n\t\t\t\t\tinputSchema: asSchema(tool2.inputSchema).jsonSchema,\n\t\t\t\t\tproviderOptions: tool2.providerOptions\n\t\t\t\t};\n\t\t\t\tcase \"provider-defined\": return {\n\t\t\t\t\ttype: \"provider-defined\",\n\t\t\t\t\tname: name16,\n\t\t\t\t\tid: tool2.id,\n\t\t\t\t\targs: tool2.args\n\t\t\t\t};\n\t\t\t\tdefault: throw new Error(`Unsupported tool type: ${toolType}`);\n\t\t\t}\n\t\t}),\n\t\ttoolChoice: toolChoice == null ? { type: \"auto\" } : typeof toolChoice === \"string\" ? { type: toolChoice } : {\n\t\t\ttype: \"tool\",\n\t\t\ttoolName: toolChoice.toolName\n\t\t}\n\t};\n}\nvar jsonValueSchema = z.lazy(() => z.union([\n\tz.null(),\n\tz.string(),\n\tz.number(),\n\tz.boolean(),\n\tz.record(z.string(), jsonValueSchema),\n\tz.array(jsonValueSchema)\n]));\nvar providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema));\nvar textPartSchema = z.object({\n\ttype: z.literal(\"text\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar imagePartSchema = z.object({\n\ttype: z.literal(\"image\"),\n\timage: z.union([dataContentSchema, z.instanceof(URL)]),\n\tmediaType: z.string().optional(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar filePartSchema = z.object({\n\ttype: z.literal(\"file\"),\n\tdata: z.union([dataContentSchema, z.instanceof(URL)]),\n\tfilename: z.string().optional(),\n\tmediaType: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar reasoningPartSchema = z.object({\n\ttype: z.literal(\"reasoning\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar toolCallPartSchema = z.object({\n\ttype: z.literal(\"tool-call\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\tinput: z.unknown(),\n\tproviderOptions: providerMetadataSchema.optional(),\n\tproviderExecuted: z.boolean().optional()\n});\nvar outputSchema = z.discriminatedUnion(\"type\", [\n\tz.object({\n\t\ttype: z.literal(\"text\"),\n\t\tvalue: z.string()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"json\"),\n\t\tvalue: jsonValueSchema\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-text\"),\n\t\tvalue: z.string()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-json\"),\n\t\tvalue: jsonValueSchema\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"content\"),\n\t\tvalue: z.array(z.union([z.object({\n\t\t\ttype: z.literal(\"text\"),\n\t\t\ttext: z.string()\n\t\t}), z.object({\n\t\t\ttype: z.literal(\"media\"),\n\t\t\tdata: z.string(),\n\t\t\tmediaType: z.string()\n\t\t})]))\n\t})\n]);\nvar toolResultPartSchema = z.object({\n\ttype: z.literal(\"tool-result\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\toutput: outputSchema,\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar systemModelMessageSchema = z.object({\n\trole: z.literal(\"system\"),\n\tcontent: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreSystemMessageSchema = systemModelMessageSchema;\nvar userModelMessageSchema = z.object({\n\trole: z.literal(\"user\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\timagePartSchema,\n\t\tfilePartSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreUserMessageSchema = userModelMessageSchema;\nvar assistantModelMessageSchema = z.object({\n\trole: z.literal(\"assistant\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\tfilePartSchema,\n\t\treasoningPartSchema,\n\t\ttoolCallPartSchema,\n\t\ttoolResultPartSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreAssistantMessageSchema = assistantModelMessageSchema;\nvar toolModelMessageSchema = z.object({\n\trole: z.literal(\"tool\"),\n\tcontent: z.array(toolResultPartSchema),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar coreToolMessageSchema = toolModelMessageSchema;\nvar modelMessageSchema = z.union([\n\tsystemModelMessageSchema,\n\tuserModelMessageSchema,\n\tassistantModelMessageSchema,\n\ttoolModelMessageSchema\n]);\nvar coreMessageSchema = modelMessageSchema;\nasync function standardizePrompt({ allowSystemInMessages, system, prompt, messages }) {\n\tif (prompt == null && messages == null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (prompt != null && messages != null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt and messages cannot be defined at the same time\"\n\t});\n\tif (system != null && typeof system !== \"string\") throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"system must be a string\"\n\t});\n\tif (prompt != null && typeof prompt === \"string\") messages = [{\n\t\trole: \"user\",\n\t\tcontent: prompt\n\t}];\n\telse if (prompt != null && Array.isArray(prompt)) messages = prompt;\n\telse if (messages == null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (messages.length === 0) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"messages must not be empty\"\n\t});\n\tif (messages.some((message) => message.role === \"system\")) {\n\t\tif (allowSystemInMessages === false) throw new InvalidPromptError({\n\t\t\tprompt,\n\t\t\tmessage: \"System messages are not allowed in the prompt or messages fields. Use the system option instead.\"\n\t\t});\n\t\tif (allowSystemInMessages === void 0) console.warn(\"AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.\");\n\t}\n\tconst validationResult = await safeValidateTypes({\n\t\tvalue: messages,\n\t\tschema: z.array(modelMessageSchema)\n\t});\n\tif (!validationResult.success) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.\",\n\t\tcause: validationResult.error\n\t});\n\treturn {\n\t\tmessages,\n\t\tsystem\n\t};\n}\nfunction wrapGatewayError(error) {\n\tif (!GatewayAuthenticationError.isInstance(error)) return error;\n\tconst isProductionEnv = (process == null ? void 0 : \"production\") === \"production\";\n\tconst moreInfoURL = \"https://v5.ai-sdk.dev/unauthenticated-ai-gateway\";\n\tif (isProductionEnv) return new AISDKError({\n\t\tname: \"GatewayError\",\n\t\tmessage: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`\n\t});\n\treturn Object.assign(/* @__PURE__ */ new Error(`\\x1B[1m\\x1B[31mUnauthenticated request to AI Gateway.\\x1B[0m\n\nTo authenticate, set the \\x1B[33mAI_GATEWAY_API_KEY\\x1B[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\x1B[34m${moreInfoURL}\\x1B[0m\n\n`), { name: \"GatewayAuthenticationError\" });\n}\nfunction assembleOperationName({ operationId, telemetry }) {\n\treturn {\n\t\t\"operation.name\": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : \"\"}`,\n\t\t\"resource.name\": telemetry == null ? void 0 : telemetry.functionId,\n\t\t\"ai.operationId\": operationId,\n\t\t\"ai.telemetry.functionId\": telemetry == null ? void 0 : telemetry.functionId\n\t};\n}\nfunction getBaseTelemetryAttributes({ model, settings, telemetry, headers }) {\n\tvar _a16;\n\treturn {\n\t\t\"ai.model.provider\": model.provider,\n\t\t\"ai.model.id\": model.modelId,\n\t\t...Object.entries(settings).reduce((attributes, [key, value]) => {\n\t\t\tattributes[`ai.settings.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {}),\n\t\t...Object.entries((_a16 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a16 : {}).reduce((attributes, [key, value]) => {\n\t\t\tattributes[`ai.telemetry.metadata.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {}),\n\t\t...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {\n\t\t\tif (value !== void 0) attributes[`ai.request.headers.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {})\n\t};\n}\nvar noopTracer = {\n\tstartSpan() {\n\t\treturn noopSpan;\n\t},\n\tstartActiveSpan(name16, arg1, arg2, arg3) {\n\t\tif (typeof arg1 === \"function\") return arg1(noopSpan);\n\t\tif (typeof arg2 === \"function\") return arg2(noopSpan);\n\t\tif (typeof arg3 === \"function\") return arg3(noopSpan);\n\t}\n};\nvar noopSpan = {\n\tspanContext() {\n\t\treturn noopSpanContext;\n\t},\n\tsetAttribute() {\n\t\treturn this;\n\t},\n\tsetAttributes() {\n\t\treturn this;\n\t},\n\taddEvent() {\n\t\treturn this;\n\t},\n\taddLink() {\n\t\treturn this;\n\t},\n\taddLinks() {\n\t\treturn this;\n\t},\n\tsetStatus() {\n\t\treturn this;\n\t},\n\tupdateName() {\n\t\treturn this;\n\t},\n\tend() {\n\t\treturn this;\n\t},\n\tisRecording() {\n\t\treturn false;\n\t},\n\trecordException() {\n\t\treturn this;\n\t}\n};\nvar noopSpanContext = {\n\ttraceId: \"\",\n\tspanId: \"\",\n\ttraceFlags: 0\n};\nfunction getTracer({ isEnabled = false, tracer } = {}) {\n\tif (!isEnabled) return noopTracer;\n\tif (tracer) return tracer;\n\treturn trace.getTracer(\"ai\");\n}\nfunction recordSpan({ name: name16, tracer, attributes, fn, endWhenDone = true }) {\n\treturn tracer.startActiveSpan(name16, { attributes }, async (span) => {\n\t\ttry {\n\t\t\tconst result = await fn(span);\n\t\t\tif (endWhenDone) span.end();\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t} finally {\n\t\t\t\tspan.end();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t});\n}\nfunction recordErrorOnSpan(span, error) {\n\tif (error instanceof Error) {\n\t\tspan.recordException({\n\t\t\tname: error.name,\n\t\t\tmessage: error.message,\n\t\t\tstack: error.stack\n\t\t});\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error.message\n\t\t});\n\t} else span.setStatus({ code: SpanStatusCode.ERROR });\n}\nfunction selectTelemetryAttributes({ telemetry, attributes }) {\n\tif ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) return {};\n\treturn Object.entries(attributes).reduce((attributes2, [key, value]) => {\n\t\tif (value == null) return attributes2;\n\t\tif (typeof value === \"object\" && \"input\" in value && typeof value.input === \"function\") {\n\t\t\tif ((telemetry == null ? void 0 : telemetry.recordInputs) === false) return attributes2;\n\t\t\tconst result = value.input();\n\t\t\treturn result == null ? attributes2 : {\n\t\t\t\t...attributes2,\n\t\t\t\t[key]: result\n\t\t\t};\n\t\t}\n\t\tif (typeof value === \"object\" && \"output\" in value && typeof value.output === \"function\") {\n\t\t\tif ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) return attributes2;\n\t\t\tconst result = value.output();\n\t\t\treturn result == null ? attributes2 : {\n\t\t\t\t...attributes2,\n\t\t\t\t[key]: result\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...attributes2,\n\t\t\t[key]: value\n\t\t};\n\t}, {});\n}\nfunction stringifyForTelemetry(prompt) {\n\treturn JSON.stringify(prompt.map((message) => ({\n\t\t...message,\n\t\tcontent: typeof message.content === \"string\" ? message.content : message.content.map((part) => part.type === \"file\" ? {\n\t\t\t...part,\n\t\t\tdata: part.data instanceof Uint8Array ? convertDataContentToBase64String(part.data) : part.data\n\t\t} : part)\n\t})));\n}\nfunction addLanguageModelUsage(usage1, usage2) {\n\treturn {\n\t\tinputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n\t\toutputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n\t\ttotalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n\t\treasoningTokens: addTokenCounts(usage1.reasoningTokens, usage2.reasoningTokens),\n\t\tcachedInputTokens: addTokenCounts(usage1.cachedInputTokens, usage2.cachedInputTokens)\n\t};\n}\nfunction addTokenCounts(tokenCount1, tokenCount2) {\n\treturn tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);\n}\nfunction asArray(value) {\n\treturn value === void 0 ? [] : Array.isArray(value) ? value : [value];\n}\nfunction getRetryDelayInMs({ error, exponentialBackoffDelay }) {\n\tconst headers = error.responseHeaders;\n\tif (!headers) return exponentialBackoffDelay;\n\tlet ms;\n\tconst retryAfterMs = headers[\"retry-after-ms\"];\n\tif (retryAfterMs) {\n\t\tconst timeoutMs = parseFloat(retryAfterMs);\n\t\tif (!Number.isNaN(timeoutMs)) ms = timeoutMs;\n\t}\n\tconst retryAfter = headers[\"retry-after\"];\n\tif (retryAfter && ms === void 0) {\n\t\tconst timeoutSeconds = parseFloat(retryAfter);\n\t\tif (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;\n\t\telse ms = Date.parse(retryAfter) - Date.now();\n\t}\n\tif (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 60 * 1e3 || ms < exponentialBackoffDelay)) return ms;\n\treturn exponentialBackoffDelay;\n}\nvar retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal } = {}) => async (f) => _retryWithExponentialBackoff(f, {\n\tmaxRetries,\n\tdelayInMs: initialDelayInMs,\n\tbackoffFactor,\n\tabortSignal\n});\nasync function _retryWithExponentialBackoff(f, { maxRetries, delayInMs, backoffFactor, abortSignal }, errors = []) {\n\ttry {\n\t\treturn await f();\n\t} catch (error) {\n\t\tif (isAbortError(error)) throw error;\n\t\tif (maxRetries === 0) throw error;\n\t\tconst errorMessage = getErrorMessage$1(error);\n\t\tconst newErrors = [...errors, error];\n\t\tconst tryNumber = newErrors.length;\n\t\tif (tryNumber > maxRetries) throw new RetryError({\n\t\t\tmessage: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n\t\t\treason: \"maxRetriesExceeded\",\n\t\t\terrors: newErrors\n\t\t});\n\t\tif (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {\n\t\t\tawait delay(getRetryDelayInMs({\n\t\t\t\terror,\n\t\t\t\texponentialBackoffDelay: delayInMs\n\t\t\t}), { abortSignal });\n\t\t\treturn _retryWithExponentialBackoff(f, {\n\t\t\t\tmaxRetries,\n\t\t\t\tdelayInMs: backoffFactor * delayInMs,\n\t\t\t\tbackoffFactor,\n\t\t\t\tabortSignal\n\t\t\t}, newErrors);\n\t\t}\n\t\tif (tryNumber === 1) throw error;\n\t\tthrow new RetryError({\n\t\t\tmessage: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n\t\t\treason: \"errorNotRetryable\",\n\t\t\terrors: newErrors\n\t\t});\n\t}\n}\nfunction prepareRetries({ maxRetries, abortSignal }) {\n\tif (maxRetries != null) {\n\t\tif (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxRetries\",\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: \"maxRetries must be an integer\"\n\t\t});\n\t\tif (maxRetries < 0) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxRetries\",\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: \"maxRetries must be >= 0\"\n\t\t});\n\t}\n\tconst maxRetriesResult = maxRetries != null ? maxRetries : 2;\n\treturn {\n\t\tmaxRetries: maxRetriesResult,\n\t\tretry: retryWithExponentialBackoffRespectingRetryHeaders({\n\t\t\tmaxRetries: maxRetriesResult,\n\t\t\tabortSignal\n\t\t})\n\t};\n}\nfunction extractTextContent(content) {\n\tconst parts = content.filter((content2) => content2.type === \"text\");\n\tif (parts.length === 0) return;\n\treturn parts.map((content2) => content2.text).join(\"\");\n}\nfunction filterActiveTools({ tools, activeTools }) {\n\tif (tools == null || activeTools == null) return tools;\n\treturn Object.fromEntries(Object.entries(tools).filter(([name16]) => activeTools.includes(name16)));\n}\nvar DefaultGeneratedFile = class {\n\tconstructor({ data, mediaType }) {\n\t\tconst isUint8Array = data instanceof Uint8Array;\n\t\tthis.base64Data = isUint8Array ? void 0 : data;\n\t\tthis.uint8ArrayData = isUint8Array ? data : void 0;\n\t\tthis.mediaType = mediaType;\n\t}\n\tget base64() {\n\t\tif (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);\n\t\treturn this.base64Data;\n\t}\n\tget uint8Array() {\n\t\tif (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);\n\t\treturn this.uint8ArrayData;\n\t}\n};\nvar DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {\n\tconstructor(options) {\n\t\tsuper(options);\n\t\tthis.type = \"file\";\n\t}\n};\nasync function parseToolCall({ toolCall, tools, repairToolCall, system, messages }) {\n\ttry {\n\t\tif (tools == null) throw new NoSuchToolError({ toolName: toolCall.toolName });\n\t\ttry {\n\t\t\treturn await doParseToolCall({\n\t\t\t\ttoolCall,\n\t\t\t\ttools\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) throw error;\n\t\t\tlet repairedToolCall = null;\n\t\t\ttry {\n\t\t\t\trepairedToolCall = await repairToolCall({\n\t\t\t\t\ttoolCall,\n\t\t\t\t\ttools,\n\t\t\t\t\tinputSchema: ({ toolName }) => {\n\t\t\t\t\t\tconst { inputSchema } = tools[toolName];\n\t\t\t\t\t\treturn asSchema(inputSchema).jsonSchema;\n\t\t\t\t\t},\n\t\t\t\t\tsystem,\n\t\t\t\t\tmessages,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t} catch (repairError) {\n\t\t\t\tthrow new ToolCallRepairError({\n\t\t\t\t\tcause: repairError,\n\t\t\t\t\toriginalError: error\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (repairedToolCall == null) throw error;\n\t\t\treturn await doParseToolCall({\n\t\t\t\ttoolCall: repairedToolCall,\n\t\t\t\ttools\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tconst parsedInput = await safeParseJSON({ text: toolCall.input });\n\t\tconst input = parsedInput.success ? parsedInput.value : toolCall.input;\n\t\treturn {\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\ttoolName: toolCall.toolName,\n\t\t\tinput,\n\t\t\tdynamic: true,\n\t\t\tinvalid: true,\n\t\t\terror,\n\t\t\tproviderMetadata: toolCall.providerMetadata\n\t\t};\n\t}\n}\nasync function doParseToolCall({ toolCall, tools }) {\n\tconst toolName = toolCall.toolName;\n\tconst tool2 = tools[toolName];\n\tif (tool2 == null) throw new NoSuchToolError({\n\t\ttoolName: toolCall.toolName,\n\t\tavailableTools: Object.keys(tools)\n\t});\n\tconst schema = asSchema(tool2.inputSchema);\n\tconst parseResult = toolCall.input.trim() === \"\" ? await safeValidateTypes({\n\t\tvalue: {},\n\t\tschema\n\t}) : await safeParseJSON({\n\t\ttext: toolCall.input,\n\t\tschema\n\t});\n\tif (parseResult.success === false) throw new InvalidToolInputError({\n\t\ttoolName,\n\t\ttoolInput: toolCall.input,\n\t\tcause: parseResult.error\n\t});\n\treturn tool2.type === \"dynamic\" ? {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata,\n\t\tdynamic: true\n\t} : {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata\n\t};\n}\nvar DefaultStepResult = class {\n\tconstructor({ content, finishReason, usage, warnings, request, response, providerMetadata }) {\n\t\tthis.content = content;\n\t\tthis.finishReason = finishReason;\n\t\tthis.usage = usage;\n\t\tthis.warnings = warnings;\n\t\tthis.request = request;\n\t\tthis.response = response;\n\t\tthis.providerMetadata = providerMetadata;\n\t}\n\tget text() {\n\t\treturn this.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\");\n\t}\n\tget reasoning() {\n\t\treturn this.content.filter((part) => part.type === \"reasoning\");\n\t}\n\tget reasoningText() {\n\t\treturn this.reasoning.length === 0 ? void 0 : this.reasoning.map((part) => part.text).join(\"\");\n\t}\n\tget files() {\n\t\treturn this.content.filter((part) => part.type === \"file\").map((part) => part.file);\n\t}\n\tget sources() {\n\t\treturn this.content.filter((part) => part.type === \"source\");\n\t}\n\tget toolCalls() {\n\t\treturn this.content.filter((part) => part.type === \"tool-call\");\n\t}\n\tget staticToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic !== true);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic === true);\n\t}\n\tget toolResults() {\n\t\treturn this.content.filter((part) => part.type === \"tool-result\");\n\t}\n\tget staticToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic !== true);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic === true);\n\t}\n};\nfunction stepCountIs(stepCount) {\n\treturn ({ steps }) => steps.length === stepCount;\n}\nfunction hasToolCall(toolName) {\n\treturn ({ steps }) => {\n\t\tvar _a16, _b, _c;\n\t\treturn (_c = (_b = (_a16 = steps[steps.length - 1]) == null ? void 0 : _a16.toolCalls) == null ? void 0 : _b.some((toolCall) => toolCall.toolName === toolName)) != null ? _c : false;\n\t};\n}\nasync function isStopConditionMet({ stopConditions, steps }) {\n\treturn (await Promise.all(stopConditions.map((condition) => condition({ steps })))).some((result) => result);\n}\nfunction createToolModelOutput({ output, tool: tool2, errorMode }) {\n\tif (errorMode === \"text\") return {\n\t\ttype: \"error-text\",\n\t\tvalue: getErrorMessage(output)\n\t};\n\telse if (errorMode === \"json\") return {\n\t\ttype: \"error-json\",\n\t\tvalue: toJSONValue(output)\n\t};\n\tif (tool2 == null ? void 0 : tool2.toModelOutput) return tool2.toModelOutput(output);\n\treturn typeof output === \"string\" ? {\n\t\ttype: \"text\",\n\t\tvalue: output\n\t} : {\n\t\ttype: \"json\",\n\t\tvalue: toJSONValue(output)\n\t};\n}\nfunction toJSONValue(value) {\n\treturn value === void 0 ? null : value;\n}\nfunction toResponseMessages({ content: inputContent, tools }) {\n\tconst responseMessages = [];\n\tconst content = inputContent.filter((part) => part.type !== \"source\").filter((part) => (part.type !== \"tool-result\" || part.providerExecuted) && (part.type !== \"tool-error\" || part.providerExecuted)).filter((part) => part.type !== \"text\" || part.text.length > 0).map((part) => {\n\t\tswitch (part.type) {\n\t\t\tcase \"text\": return {\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: part.text,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"reasoning\": return {\n\t\t\t\ttype: \"reasoning\",\n\t\t\t\ttext: part.text,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"file\": return {\n\t\t\t\ttype: \"file\",\n\t\t\t\tdata: part.file.base64,\n\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"tool-call\": return {\n\t\t\t\ttype: \"tool-call\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: part.input,\n\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"tool-result\": return {\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\ttool: tools == null ? void 0 : tools[part.toolName],\n\t\t\t\t\toutput: part.output,\n\t\t\t\t\terrorMode: \"none\"\n\t\t\t\t}),\n\t\t\t\tproviderExecuted: true,\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t\tcase \"tool-error\": return {\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\ttool: tools == null ? void 0 : tools[part.toolName],\n\t\t\t\t\toutput: part.error,\n\t\t\t\t\terrorMode: \"json\"\n\t\t\t\t}),\n\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t};\n\t\t}\n\t});\n\tif (content.length > 0) responseMessages.push({\n\t\trole: \"assistant\",\n\t\tcontent\n\t});\n\tconst toolResultContent = inputContent.filter((part) => part.type === \"tool-result\" || part.type === \"tool-error\").filter((part) => !part.providerExecuted).map((toolResult) => ({\n\t\ttype: \"tool-result\",\n\t\ttoolCallId: toolResult.toolCallId,\n\t\ttoolName: toolResult.toolName,\n\t\toutput: createToolModelOutput({\n\t\t\ttool: tools == null ? void 0 : tools[toolResult.toolName],\n\t\t\toutput: toolResult.type === \"tool-result\" ? toolResult.output : toolResult.error,\n\t\t\terrorMode: toolResult.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t}),\n\t\t...toolResult.providerMetadata != null ? { providerOptions: toolResult.providerMetadata } : {}\n\t}));\n\tif (toolResultContent.length > 0) responseMessages.push({\n\t\trole: \"tool\",\n\t\tcontent: toolResultContent\n\t});\n\treturn responseMessages;\n}\nvar originalGenerateId = createIdGenerator({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nasync function generateText$1({ model: modelArg, tools, toolChoice, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, headers, stopWhen = stepCountIs(1), experimental_output: output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools, activeTools = experimental_activeTools, experimental_prepareStep, prepareStep = experimental_prepareStep, experimental_repairToolCall: repairToolCall, experimental_download: download2, experimental_context, _internal: { generateId: generateId3 = originalGenerateId, currentDate = () => /* @__PURE__ */ new Date() } = {}, onStepFinish, ...settings }) {\n\tconst model = resolveLanguageModel(modelArg);\n\tconst stopConditions = asArray(stopWhen);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst callSettings = prepareCallSettings(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: {\n\t\t\t...callSettings,\n\t\t\tmaxRetries\n\t\t}\n\t});\n\tconst initialPrompt = await standardizePrompt({\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages\n\t});\n\tconst tracer = getTracer(telemetry);\n\ttry {\n\t\treturn await recordSpan({\n\t\t\tname: \"ai.generateText\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.generateText\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.model.provider\": model.provider,\n\t\t\t\t\t\"ai.model.id\": model.modelId,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\tvar _a16, _b, _c, _d, _e, _f, _g;\n\t\t\t\tconst callSettings2 = prepareCallSettings(settings);\n\t\t\t\tlet currentModelResponse;\n\t\t\t\tlet clientToolCalls = [];\n\t\t\t\tlet clientToolOutputs = [];\n\t\t\t\tconst responseMessages = [];\n\t\t\t\tconst steps = [];\n\t\t\t\tdo {\n\t\t\t\t\tif (steps.length > 0) abortSignal?.throwIfAborted();\n\t\t\t\t\tconst stepInputMessages = [...initialPrompt.messages, ...responseMessages];\n\t\t\t\t\tconst prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsteps,\n\t\t\t\t\t\tstepNumber: steps.length,\n\t\t\t\t\t\tmessages: stepInputMessages\n\t\t\t\t\t}));\n\t\t\t\t\tconst stepModel = resolveLanguageModel((_a16 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a16 : model);\n\t\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\t\tprompt: {\n\t\t\t\t\t\t\tsystem: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n\t\t\t\t\t\t\tmessages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsupportedUrls: await stepModel.supportedUrls,\n\t\t\t\t\t\tdownload: download2\n\t\t\t\t\t});\n\t\t\t\t\tconst stepActiveTools = (_d = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _d : activeTools;\n\t\t\t\t\tconst stepToolSet = filterActiveTools({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t});\n\t\t\t\t\tconst { toolChoice: stepToolChoice, tools: stepTools } = prepareToolsAndToolChoice({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\ttoolChoice: (_e = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _e : toolChoice,\n\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t});\n\t\t\t\t\tcurrentModelResponse = await retry(() => {\n\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\t\tname: \"ai.generateText.doGenerate\",\n\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\toperationId: \"ai.generateText.doGenerate\",\n\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\t\"ai.model.provider\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"ai.model.id\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.tools\": { input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2)) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.toolChoice\": { input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0 },\n\t\t\t\t\t\t\t\t\t\"gen_ai.system\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.model\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": settings.frequencyPenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": settings.maxOutputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": settings.presencePenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.stop_sequences\": settings.stopSequences,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.temperature\": (_a17 = settings.temperature) != null ? _a17 : void 0,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_k\": settings.topK,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_p\": settings.topP\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\tfn: async (span2) => {\n\t\t\t\t\t\t\t\tvar _a18, _b2, _c2, _d2, _e2, _f2, _g2, _h;\n\t\t\t\t\t\t\t\tconst result = await stepModel.doGenerate({\n\t\t\t\t\t\t\t\t\t...callSettings2,\n\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\tresponseFormat: output == null ? void 0 : output.responseFormat,\n\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst responseData = {\n\t\t\t\t\t\t\t\t\tid: (_b2 = (_a18 = result.response) == null ? void 0 : _a18.id) != null ? _b2 : generateId3(),\n\t\t\t\t\t\t\t\t\ttimestamp: (_d2 = (_c2 = result.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : currentDate(),\n\t\t\t\t\t\t\t\t\tmodelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,\n\t\t\t\t\t\t\t\t\theaders: (_g2 = result.response) == null ? void 0 : _g2.headers,\n\t\t\t\t\t\t\t\t\tbody: (_h = result.response) == null ? void 0 : _h.body\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tspan2.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": result.finishReason,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.text\": { output: () => extractTextContent(result.content) },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\t\t\t\t\tconst toolCalls = asToolCalls(result.content);\n\t\t\t\t\t\t\t\t\t\t\treturn toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n\t\t\t\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": responseData.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(result.providerMetadata),\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.promptTokens\": result.usage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.completionTokens\": result.usage.outputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [result.finishReason],\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": result.usage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": result.usage.outputTokens\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\t\t\tresponse: responseData\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t\tconst stepToolCalls = await Promise.all(currentModelResponse.content.filter((part) => part.type === \"tool-call\").map((toolCall) => parseToolCall({\n\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\ttools: stepToolSet,\n\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tmessages: stepInputMessages\n\t\t\t\t\t})));\n\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\tif (toolCall.invalid) continue;\n\t\t\t\t\t\tconst tool2 = stepToolSet[toolCall.toolName];\n\t\t\t\t\t\tif (tool2.onInputStart != null) await tool2.onInputStart({\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.onInputAvailable) != null) await tool2.onInputAvailable({\n\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst invalidToolCalls = stepToolCalls.filter((toolCall) => toolCall.invalid && toolCall.dynamic);\n\t\t\t\t\tclientToolOutputs = [];\n\t\t\t\t\tfor (const toolCall of invalidToolCalls) clientToolOutputs.push({\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\terror: getErrorMessage$1(toolCall.error),\n\t\t\t\t\t\tdynamic: true\n\t\t\t\t\t});\n\t\t\t\t\tclientToolCalls = stepToolCalls.filter((toolCall) => !toolCall.providerExecuted);\n\t\t\t\t\tif (stepToolSet != null) clientToolOutputs.push(...await executeTools({\n\t\t\t\t\t\ttoolCalls: clientToolCalls.filter((toolCall) => !toolCall.invalid),\n\t\t\t\t\t\ttools: stepToolSet,\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t}));\n\t\t\t\t\tconst stepContent = asContent({\n\t\t\t\t\t\tcontent: currentModelResponse.content,\n\t\t\t\t\t\ttoolCalls: stepToolCalls,\n\t\t\t\t\t\ttoolOutputs: clientToolOutputs\n\t\t\t\t\t});\n\t\t\t\t\tresponseMessages.push(...toResponseMessages({\n\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\ttools: stepToolSet\n\t\t\t\t\t}));\n\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\tfinishReason: currentModelResponse.finishReason,\n\t\t\t\t\t\tusage: currentModelResponse.usage,\n\t\t\t\t\t\twarnings: currentModelResponse.warnings,\n\t\t\t\t\t\tproviderMetadata: currentModelResponse.providerMetadata,\n\t\t\t\t\t\trequest: (_f = currentModelResponse.request) != null ? _f : {},\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t...currentModelResponse.response,\n\t\t\t\t\t\t\tmessages: structuredClone(responseMessages)\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tlogWarnings((_g = currentModelResponse.warnings) != null ? _g : []);\n\t\t\t\t\tsteps.push(currentStepResult);\n\t\t\t\t\tawait (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));\n\t\t\t\t} while (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length && !await isStopConditionMet({\n\t\t\t\t\tstopConditions,\n\t\t\t\t\tsteps\n\t\t\t\t}));\n\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.response.finishReason\": currentModelResponse.finishReason,\n\t\t\t\t\t\t\"ai.response.text\": { output: () => extractTextContent(currentModelResponse.content) },\n\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\tconst toolCalls = asToolCalls(currentModelResponse.content);\n\t\t\t\t\t\t\treturn toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n\t\t\t\t\t\t} },\n\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(currentModelResponse.providerMetadata),\n\t\t\t\t\t\t\"ai.usage.promptTokens\": currentModelResponse.usage.inputTokens,\n\t\t\t\t\t\t\"ai.usage.completionTokens\": currentModelResponse.usage.outputTokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tconst lastStep = steps[steps.length - 1];\n\t\t\t\tlet resolvedOutput;\n\t\t\t\tif (lastStep.finishReason === \"stop\") resolvedOutput = await (output == null ? void 0 : output.parseOutput({ text: lastStep.text }, {\n\t\t\t\t\tresponse: lastStep.response,\n\t\t\t\t\tusage: lastStep.usage,\n\t\t\t\t\tfinishReason: lastStep.finishReason\n\t\t\t\t}));\n\t\t\t\treturn new DefaultGenerateTextResult({\n\t\t\t\t\tsteps,\n\t\t\t\t\tresolvedOutput\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nasync function executeTools({ toolCalls, tools, tracer, telemetry, messages, abortSignal, experimental_context }) {\n\treturn (await Promise.all(toolCalls.map(async ({ toolCallId, toolName, input }) => {\n\t\tconst tool2 = tools[toolName];\n\t\tif ((tool2 == null ? void 0 : tool2.execute) == null) return;\n\t\treturn recordSpan({\n\t\t\tname: \"ai.toolCall\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.toolCall\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t\"ai.toolCall.name\": toolName,\n\t\t\t\t\t\"ai.toolCall.id\": toolCallId,\n\t\t\t\t\t\"ai.toolCall.args\": { output: () => JSON.stringify(input) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst stream = executeTool({\n\t\t\t\t\t\texecute: tool2.execute.bind(tool2),\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tlet output;\n\t\t\t\t\tfor await (const part of stream) if (part.type === \"final\") output = part.output;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: { \"ai.toolCall.result\": { output: () => JSON.stringify(output) } }\n\t\t\t\t\t\t}));\n\t\t\t\t\t} catch (ignored) {}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\toutput,\n\t\t\t\t\t\tdynamic: tool2.type === \"dynamic\"\n\t\t\t\t\t};\n\t\t\t\t} catch (error) {\n\t\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tdynamic: tool2.type === \"dynamic\"\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}))).filter((output) => output != null);\n}\nvar DefaultGenerateTextResult = class {\n\tconstructor(options) {\n\t\tthis.steps = options.steps;\n\t\tthis.resolvedOutput = options.resolvedOutput;\n\t}\n\tget finalStep() {\n\t\treturn this.steps[this.steps.length - 1];\n\t}\n\tget content() {\n\t\treturn this.finalStep.content;\n\t}\n\tget text() {\n\t\treturn this.finalStep.text;\n\t}\n\tget files() {\n\t\treturn this.finalStep.files;\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.reasoningText;\n\t}\n\tget reasoning() {\n\t\treturn this.finalStep.reasoning;\n\t}\n\tget toolCalls() {\n\t\treturn this.finalStep.toolCalls;\n\t}\n\tget staticToolCalls() {\n\t\treturn this.finalStep.staticToolCalls;\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.finalStep.dynamicToolCalls;\n\t}\n\tget toolResults() {\n\t\treturn this.finalStep.toolResults;\n\t}\n\tget staticToolResults() {\n\t\treturn this.finalStep.staticToolResults;\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.finalStep.dynamicToolResults;\n\t}\n\tget sources() {\n\t\treturn this.finalStep.sources;\n\t}\n\tget finishReason() {\n\t\treturn this.finalStep.finishReason;\n\t}\n\tget warnings() {\n\t\treturn this.finalStep.warnings;\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.providerMetadata;\n\t}\n\tget response() {\n\t\treturn this.finalStep.response;\n\t}\n\tget request() {\n\t\treturn this.finalStep.request;\n\t}\n\tget usage() {\n\t\treturn this.finalStep.usage;\n\t}\n\tget totalUsage() {\n\t\treturn this.steps.reduce((totalUsage, step) => {\n\t\t\treturn addLanguageModelUsage(totalUsage, step.usage);\n\t\t}, {\n\t\t\tinputTokens: void 0,\n\t\t\toutputTokens: void 0,\n\t\t\ttotalTokens: void 0,\n\t\t\treasoningTokens: void 0,\n\t\t\tcachedInputTokens: void 0\n\t\t});\n\t}\n\tget experimental_output() {\n\t\tif (this.resolvedOutput == null) throw new NoOutputSpecifiedError();\n\t\treturn this.resolvedOutput;\n\t}\n};\nfunction asToolCalls(content) {\n\tconst parts = content.filter((part) => part.type === \"tool-call\");\n\tif (parts.length === 0) return;\n\treturn parts.map((toolCall) => ({\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: toolCall.input\n\t}));\n}\nfunction asContent({ content, toolCalls, toolOutputs }) {\n\treturn [...content.map((part) => {\n\t\tswitch (part.type) {\n\t\t\tcase \"text\":\n\t\t\tcase \"reasoning\":\n\t\t\tcase \"source\": return part;\n\t\t\tcase \"file\": return {\n\t\t\t\ttype: \"file\",\n\t\t\t\tfile: new DefaultGeneratedFile(part)\n\t\t\t};\n\t\t\tcase \"tool-call\": return toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId);\n\t\t\tcase \"tool-result\": {\n\t\t\t\tconst toolCall = toolCalls.find((toolCall2) => toolCall2.toolCallId === part.toolCallId);\n\t\t\t\tif (toolCall == null) throw new Error(`Tool call ${part.toolCallId} not found.`);\n\t\t\t\tif (part.isError) return {\n\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\terror: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: toolCall.dynamic\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\toutput: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: toolCall.dynamic\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}), ...toolOutputs];\n}\nfunction prepareHeaders(headers, defaultHeaders) {\n\tconst responseHeaders = new Headers(headers != null ? headers : {});\n\tfor (const [key, value] of Object.entries(defaultHeaders)) if (!responseHeaders.has(key)) responseHeaders.set(key, value);\n\treturn responseHeaders;\n}\nfunction createTextStreamResponse({ status, statusText, headers, textStream }) {\n\treturn new Response(textStream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus: status != null ? status : 200,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" })\n\t});\n}\nfunction writeToServerResponse({ response, status, statusText, headers, stream }) {\n\tconst statusCode = status != null ? status : 200;\n\tif (statusText !== void 0) response.writeHead(statusCode, statusText, headers);\n\telse response.writeHead(statusCode, headers);\n\tconst reader = stream.getReader();\n\tconst read = async () => {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tif (!response.write(value)) await new Promise((resolve2) => {\n\t\t\t\t\tresponse.once(\"drain\", resolve2);\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tresponse.end();\n\t\t}\n\t};\n\treturn read();\n}\nfunction pipeTextStreamToResponse({ response, status, statusText, headers, textStream }) {\n\treturn writeToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: Object.fromEntries(prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" }).entries()),\n\t\tstream: textStream.pipeThrough(new TextEncoderStream())\n\t});\n}\nvar JsonToSseTransformStream = class extends TransformStream {\n\tconstructor() {\n\t\tsuper({\n\t\t\ttransform(part, controller) {\n\t\t\t\tcontroller.enqueue(`data: ${JSON.stringify(part)}\n\n`);\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tcontroller.enqueue(\"data: [DONE]\\n\\n\");\n\t\t\t}\n\t\t});\n\t}\n};\nvar UI_MESSAGE_STREAM_HEADERS = {\n\t\"content-type\": \"text/event-stream\",\n\t\"cache-control\": \"no-cache\",\n\tconnection: \"keep-alive\",\n\t\"x-vercel-ai-ui-message-stream\": \"v1\",\n\t\"x-accel-buffering\": \"no\"\n};\nfunction createUIMessageStreamResponse({ status, statusText, headers, stream, consumeSseStream }) {\n\tlet sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\treturn new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)\n\t});\n}\nfunction getResponseUIMessageId({ originalMessages, responseMessageId }) {\n\tif (originalMessages == null) return;\n\tconst lastMessage = originalMessages[originalMessages.length - 1];\n\treturn (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage.id : typeof responseMessageId === \"function\" ? responseMessageId() : responseMessageId;\n}\nvar uiMessageChunkSchema = lazyValidator(() => zodSchema(z.union([\n\tz.looseObject({\n\t\ttype: z.literal(\"text-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"text-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"text-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"error\"),\n\t\terrorText: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-start\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-delta\"),\n\t\ttoolCallId: z.string(),\n\t\tinputTextDelta: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-available\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-error\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\terrorText: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-available\"),\n\t\ttoolCallId: z.string(),\n\t\toutput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\tpreliminary: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-error\"),\n\t\ttoolCallId: z.string(),\n\t\terrorText: z.string(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"source-url\"),\n\t\tsourceId: z.string(),\n\t\turl: z.string(),\n\t\ttitle: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"source-document\"),\n\t\tsourceId: z.string(),\n\t\tmediaType: z.string(),\n\t\ttitle: z.string(),\n\t\tfilename: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"file\"),\n\t\turl: z.string(),\n\t\tmediaType: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.custom((value) => typeof value === \"string\" && value.startsWith(\"data-\"), { message: \"Type must start with \\\"data-\\\"\" }),\n\t\tid: z.string().optional(),\n\t\tdata: z.unknown(),\n\t\ttransient: z.boolean().optional()\n\t}),\n\tz.looseObject({ type: z.literal(\"start-step\") }),\n\tz.looseObject({ type: z.literal(\"finish-step\") }),\n\tz.looseObject({\n\t\ttype: z.literal(\"start\"),\n\t\tmessageId: z.string().optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"finish\"),\n\t\tfinishReason: z.enum([\n\t\t\t\"stop\",\n\t\t\t\"length\",\n\t\t\t\"content-filter\",\n\t\t\t\"tool-calls\",\n\t\t\t\"error\",\n\t\t\t\"other\",\n\t\t\t\"unknown\"\n\t\t]).optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.looseObject({ type: z.literal(\"abort\") }),\n\tz.looseObject({\n\t\ttype: z.literal(\"message-metadata\"),\n\t\tmessageMetadata: z.unknown()\n\t})\n])));\nfunction isDataUIMessageChunk(chunk) {\n\treturn chunk.type.startsWith(\"data-\");\n}\nfunction createIdMap() {\n\treturn /* @__PURE__ */ Object.create(null);\n}\nfunction mergeObjects(base, overrides) {\n\tif (base === void 0 && overrides === void 0) return;\n\tif (base === void 0) return overrides;\n\tif (overrides === void 0) return base;\n\tconst result = { ...base };\n\tfor (const key in overrides) {\n\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n\t\tif (Object.prototype.hasOwnProperty.call(overrides, key)) {\n\t\t\tconst overridesValue = overrides[key];\n\t\t\tif (overridesValue === void 0) continue;\n\t\t\tconst baseValue = key in base ? base[key] : void 0;\n\t\t\tconst isSourceObject = overridesValue !== null && typeof overridesValue === \"object\" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);\n\t\t\tconst isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === \"object\" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);\n\t\t\tif (isSourceObject && isTargetObject) result[key] = mergeObjects(baseValue, overridesValue);\n\t\t\telse result[key] = overridesValue;\n\t\t}\n\t}\n\treturn result;\n}\nfunction fixJson(input) {\n\tconst stack = [\"ROOT\"];\n\tlet lastValidIndex = -1;\n\tlet literalStart = null;\n\tfunction processValueStart(char, i, swapState) {\n\t\tswitch (char) {\n\t\t\tcase \"\\\"\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_STRING\");\n\t\t\t\tbreak;\n\t\t\tcase \"f\":\n\t\t\tcase \"t\":\n\t\t\tcase \"n\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tliteralStart = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_LITERAL\");\n\t\t\t\tbreak;\n\t\t\tcase \"-\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"0\":\n\t\t\tcase \"1\":\n\t\t\tcase \"2\":\n\t\t\tcase \"3\":\n\t\t\tcase \"4\":\n\t\t\tcase \"5\":\n\t\t\tcase \"6\":\n\t\t\tcase \"7\":\n\t\t\tcase \"8\":\n\t\t\tcase \"9\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"{\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_OBJECT_START\");\n\t\t\t\tbreak;\n\t\t\tcase \"[\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_ARRAY_START\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfunction processAfterObjectValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"}\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfunction processAfterArrayValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"]\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tfor (let i = 0; i < input.length; i++) {\n\t\tconst char = input[i];\n\t\tswitch (stack[stack.length - 1]) {\n\t\t\tcase \"ROOT\":\n\t\t\t\tprocessValueStart(char, i, \"FINISH\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \":\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_BEFORE_VALUE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_OBJECT_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\t\tprocessAfterObjectValue(char, i);\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"\\\\\":\n\t\t\t\t\t\tstack.push(\"INSIDE_STRING_ESCAPE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: lastValidIndex = i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING_ESCAPE\":\n\t\t\t\tstack.pop();\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_NUMBER\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"0\":\n\t\t\t\t\tcase \"1\":\n\t\t\t\t\tcase \"2\":\n\t\t\t\t\tcase \"3\":\n\t\t\t\t\tcase \"4\":\n\t\t\t\t\tcase \"5\":\n\t\t\t\t\tcase \"6\":\n\t\t\t\t\tcase \"7\":\n\t\t\t\t\tcase \"8\":\n\t\t\t\t\tcase \"9\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"e\":\n\t\t\t\t\tcase \"E\":\n\t\t\t\t\tcase \"-\":\n\t\t\t\t\tcase \".\": break;\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_LITERAL\": {\n\t\t\t\tconst partialLiteral = input.substring(literalStart, i + 1);\n\t\t\t\tif (!\"false\".startsWith(partialLiteral) && !\"true\".startsWith(partialLiteral) && !\"null\".startsWith(partialLiteral)) {\n\t\t\t\t\tstack.pop();\n\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\telse if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t} else lastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tlet result = input.slice(0, lastValidIndex + 1);\n\tfor (let i = stack.length - 1; i >= 0; i--) switch (stack[i]) {\n\t\tcase \"INSIDE_STRING\":\n\t\t\tresult += \"\\\"\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\tcase \"INSIDE_OBJECT_START\":\n\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\tresult += \"}\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_ARRAY_START\":\n\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\tresult += \"]\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_LITERAL\": {\n\t\t\tconst partialLiteral = input.substring(literalStart, input.length);\n\t\t\tif (\"true\".startsWith(partialLiteral)) result += \"true\".slice(partialLiteral.length);\n\t\t\telse if (\"false\".startsWith(partialLiteral)) result += \"false\".slice(partialLiteral.length);\n\t\t\telse if (\"null\".startsWith(partialLiteral)) result += \"null\".slice(partialLiteral.length);\n\t\t}\n\t}\n\treturn result;\n}\nasync function parsePartialJson(jsonText) {\n\tif (jsonText === void 0) return {\n\t\tvalue: void 0,\n\t\tstate: \"undefined-input\"\n\t};\n\tlet result = await safeParseJSON({ text: jsonText });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"successful-parse\"\n\t};\n\tresult = await safeParseJSON({ text: fixJson(jsonText) });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"repaired-parse\"\n\t};\n\treturn {\n\t\tvalue: void 0,\n\t\tstate: \"failed-parse\"\n\t};\n}\nfunction isDataUIPart(part) {\n\treturn part.type.startsWith(\"data-\");\n}\nfunction isTextUIPart(part) {\n\treturn part.type === \"text\";\n}\nfunction isFileUIPart(part) {\n\treturn part.type === \"file\";\n}\nfunction isReasoningUIPart(part) {\n\treturn part.type === \"reasoning\";\n}\nfunction isToolUIPart(part) {\n\treturn part.type.startsWith(\"tool-\");\n}\nfunction isDynamicToolUIPart(part) {\n\treturn part.type === \"dynamic-tool\";\n}\nfunction isToolOrDynamicToolUIPart(part) {\n\treturn isToolUIPart(part) || isDynamicToolUIPart(part);\n}\nfunction getToolName(part) {\n\treturn part.type.split(\"-\").slice(1).join(\"-\");\n}\nfunction getToolOrDynamicToolName(part) {\n\treturn isDynamicToolUIPart(part) ? part.toolName : getToolName(part);\n}\nfunction createStreamingUIMessageState({ lastMessage, messageId }) {\n\treturn {\n\t\tmessage: (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage : {\n\t\t\tid: messageId,\n\t\t\tmetadata: void 0,\n\t\t\trole: \"assistant\",\n\t\t\tparts: []\n\t\t},\n\t\tactiveTextParts: createIdMap(),\n\t\tactiveReasoningParts: createIdMap(),\n\t\tpartialToolCalls: createIdMap()\n\t};\n}\nfunction processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas, runUpdateMessageJob, onError, onToolCall, onData }) {\n\treturn stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\tawait runUpdateMessageJob(async ({ state, write }) => {\n\t\t\tvar _a16, _b, _c, _d;\n\t\t\tfunction getCurrentStepParts() {\n\t\t\t\tconst parts = state.message.parts;\n\t\t\t\tlet currentStepStartIndex = parts.length - 1;\n\t\t\t\twhile (currentStepStartIndex >= 0 && parts[currentStepStartIndex].type !== \"step-start\") currentStepStartIndex--;\n\t\t\t\treturn parts.slice(currentStepStartIndex + 1);\n\t\t\t}\n\t\t\tfunction getCurrentStepToolInvocations() {\n\t\t\t\treturn getCurrentStepParts().filter(isToolUIPart);\n\t\t\t}\n\t\t\tfunction getToolInvocation(toolCallId) {\n\t\t\t\tlet toolInvocation = getCurrentStepToolInvocations().find((invocation) => invocation.toolCallId === toolCallId);\n\t\t\t\tif (toolInvocation == null) {\n\t\t\t\t\tconst parts = state.message.parts;\n\t\t\t\t\tfor (let i = parts.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tconst part = parts[i];\n\t\t\t\t\t\tif (isToolUIPart(part) && part.toolCallId === toolCallId) {\n\t\t\t\t\t\t\ttoolInvocation = part;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (toolInvocation == null) throw new Error(\"tool-output-error must be preceded by a tool-input-available\");\n\t\t\t\treturn toolInvocation;\n\t\t\t}\n\t\t\tfunction getDynamicToolInvocation(toolCallId) {\n\t\t\t\tlet toolInvocation = getCurrentStepParts().filter((part) => part.type === \"dynamic-tool\").find((invocation) => invocation.toolCallId === toolCallId);\n\t\t\t\tif (toolInvocation == null) {\n\t\t\t\t\tconst parts = state.message.parts;\n\t\t\t\t\tfor (let i = parts.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tconst part = parts[i];\n\t\t\t\t\t\tif (part.type === \"dynamic-tool\" && part.toolCallId === toolCallId) {\n\t\t\t\t\t\t\ttoolInvocation = part;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (toolInvocation == null) throw new Error(\"tool-output-error must be preceded by a tool-input-available\");\n\t\t\t\treturn toolInvocation;\n\t\t\t}\n\t\t\tfunction updateToolPart(options, existingPart) {\n\t\t\t\tvar _a17;\n\t\t\t\tconst part = existingPart != null ? existingPart : getCurrentStepParts().find((part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = anyOptions.rawInput;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tanyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;\n\t\t\t\t\tif (anyOptions.providerMetadata != null && part.state === \"input-available\") part.callProviderMetadata = anyOptions.providerMetadata;\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: `tool-${options.toolName}`,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\trawInput: anyOptions.rawInput,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\t...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tfunction updateDynamicToolPart(options, existingPart) {\n\t\t\t\tvar _a17, _b2;\n\t\t\t\tconst part = existingPart != null ? existingPart : getCurrentStepParts().find((part2) => part2.type === \"dynamic-tool\" && part2.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.toolName = options.toolName;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = (_a17 = anyOptions.rawInput) != null ? _a17 : anyPart.rawInput;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tanyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;\n\t\t\t\t\tif (anyOptions.providerMetadata != null && part.state === \"input-available\") part.callProviderMetadata = anyOptions.providerMetadata;\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: \"dynamic-tool\",\n\t\t\t\t\ttoolName: options.toolName,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\t...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tasync function updateMessageMetadata(metadata) {\n\t\t\t\tif (metadata != null) {\n\t\t\t\t\tconst mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;\n\t\t\t\t\tif (messageMetadataSchema != null) await validateTypes({\n\t\t\t\t\t\tvalue: mergedMetadata,\n\t\t\t\t\t\tschema: messageMetadataSchema\n\t\t\t\t\t});\n\t\t\t\t\tstate.message.metadata = mergedMetadata;\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-start\": {\n\t\t\t\t\tconst textPart = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeTextParts[chunk.id] = textPart;\n\t\t\t\t\tstate.message.parts.push(textPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-delta\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\ttextPart.text += chunk.delta;\n\t\t\t\t\ttextPart.providerMetadata = (_a16 = chunk.providerMetadata) != null ? _a16 : textPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-end\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\ttextPart.state = \"done\";\n\t\t\t\t\ttextPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;\n\t\t\t\t\tdelete state.activeTextParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\tconst reasoningPart = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeReasoningParts[chunk.id] = reasoningPart;\n\t\t\t\t\tstate.message.parts.push(reasoningPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-delta\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\treasoningPart.text += chunk.delta;\n\t\t\t\t\treasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-end\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\treasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;\n\t\t\t\t\treasoningPart.state = \"done\";\n\t\t\t\t\tdelete state.activeReasoningParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"file\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\turl: chunk.url\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-url\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-url\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\turl: chunk.url,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-document\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-document\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tfilename: chunk.filename,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\tconst toolInvocations = getCurrentStepParts().filter(isToolUIPart);\n\t\t\t\t\tstate.partialToolCalls[chunk.toolCallId] = {\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tindex: toolInvocations.length,\n\t\t\t\t\t\tdynamic: chunk.dynamic\n\t\t\t\t\t};\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-delta\": {\n\t\t\t\t\tconst partialToolCall = state.partialToolCalls[chunk.toolCallId];\n\t\t\t\t\tpartialToolCall.text += chunk.inputTextDelta;\n\t\t\t\t\tconst { value: partialArgs } = await parsePartialJson(partialToolCall.text);\n\t\t\t\t\tif (partialToolCall.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: partialArgs\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinput: partialArgs\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-available\":\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tif (onToolCall && !chunk.providerExecuted) await onToolCall({ toolCall: chunk });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-error\":\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\trawInput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-output-available\":\n\t\t\t\t\tif (chunk.dynamic) {\n\t\t\t\t\t\tconst toolInvocation = getDynamicToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateDynamicToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\t\tpreliminary: chunk.preliminary\n\t\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: getToolName(toolInvocation),\n\t\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\t\tpreliminary: chunk.preliminary\n\t\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\t}\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-output-error\":\n\t\t\t\t\tif (chunk.dynamic) {\n\t\t\t\t\t\tconst toolInvocation = getDynamicToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateDynamicToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\t\tupdateToolPart({\n\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\ttoolName: getToolName(toolInvocation),\n\t\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\t\trawInput: toolInvocation.rawInput,\n\t\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\t}\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"start-step\":\n\t\t\t\t\tstate.message.parts.push({ type: \"step-start\" });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish-step\":\n\t\t\t\t\tstate.activeTextParts = createIdMap();\n\t\t\t\t\tstate.activeReasoningParts = createIdMap();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"start\":\n\t\t\t\t\tif (chunk.messageId != null) state.message.id = chunk.messageId;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageId != null || chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tif (chunk.finishReason != null) state.finishReason = chunk.finishReason;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"message-metadata\":\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tonError?.(new Error(chunk.errorText));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: if (isDataUIMessageChunk(chunk)) {\n\t\t\t\t\tif ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) await validateTypes({\n\t\t\t\t\t\tvalue: chunk.data,\n\t\t\t\t\t\tschema: dataPartSchemas[chunk.type]\n\t\t\t\t\t});\n\t\t\t\t\tconst dataChunk = chunk;\n\t\t\t\t\tif (dataChunk.transient) {\n\t\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst existingUIPart = dataChunk.id != null ? state.message.parts.find((chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id) : void 0;\n\t\t\t\t\tif (existingUIPart != null) existingUIPart.data = dataChunk.data;\n\t\t\t\t\telse state.message.parts.push(dataChunk);\n\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\twrite();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk);\n\t\t});\n\t} }));\n}\nfunction handleUIMessageStreamFinish({ messageId, originalMessages = [], onFinish, onError, stream }) {\n\tlet lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];\n\tif ((lastMessage == null ? void 0 : lastMessage.role) !== \"assistant\") lastMessage = void 0;\n\telse messageId = lastMessage.id;\n\tlet isAborted = false;\n\tconst idInjectedStream = stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\tif (chunk.type === \"start\") {\n\t\t\tconst startChunk = chunk;\n\t\t\tif (startChunk.messageId == null && messageId != null) startChunk.messageId = messageId;\n\t\t}\n\t\tif (chunk.type === \"abort\") isAborted = true;\n\t\tcontroller.enqueue(chunk);\n\t} }));\n\tif (onFinish == null) return idInjectedStream;\n\tconst state = createStreamingUIMessageState({\n\t\tlastMessage: lastMessage ? structuredClone(lastMessage) : void 0,\n\t\tmessageId: messageId != null ? messageId : \"\"\n\t});\n\tconst runUpdateMessageJob = async (job) => {\n\t\tawait job({\n\t\t\tstate,\n\t\t\twrite: () => {}\n\t\t});\n\t};\n\tlet finishCalled = false;\n\tconst callOnFinish = async () => {\n\t\tif (finishCalled || !onFinish) return;\n\t\tfinishCalled = true;\n\t\tconst isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n\t\tawait onFinish({\n\t\t\tisAborted,\n\t\t\tisContinuation,\n\t\t\tresponseMessage: state.message,\n\t\t\tmessages: [...isContinuation ? originalMessages.slice(0, -1) : originalMessages, state.message],\n\t\t\tfinishReason: state.finishReason\n\t\t});\n\t};\n\treturn processUIMessageStream({\n\t\tstream: idInjectedStream,\n\t\trunUpdateMessageJob,\n\t\tonError\n\t}).pipeThrough(new TransformStream({\n\t\ttransform(chunk, controller) {\n\t\t\tcontroller.enqueue(chunk);\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait callOnFinish();\n\t\t},\n\t\tasync flush() {\n\t\t\tawait callOnFinish();\n\t\t}\n\t}));\n}\nfunction pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, consumeSseStream }) {\n\tlet sseStream = stream.pipeThrough(new JsonToSseTransformStream());\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\treturn writeToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: Object.fromEntries(prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS).entries()),\n\t\tstream: sseStream.pipeThrough(new TextEncoderStream())\n\t});\n}\nfunction createAsyncIterableStream(source) {\n\tconst stream = source.pipeThrough(new TransformStream());\n\tstream[Symbol.asyncIterator] = function() {\n\t\tconst reader = this.getReader();\n\t\tlet finished = false;\n\t\tasync function cleanup(cancelStream) {\n\t\t\tvar _a16;\n\t\t\tfinished = true;\n\t\t\ttry {\n\t\t\t\tif (cancelStream) await ((_a16 = reader.cancel) == null ? void 0 : _a16.call(reader));\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\treader.releaseLock();\n\t\t\t\t} catch (e) {}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t/**\n\t\t\t* Reads the next chunk from the stream.\n\t\t\t* @returns A promise resolving to the next IteratorResult.\n\t\t\t*/\n\t\t\tasync next() {\n\t\t\t\tif (finished) return {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\tawait cleanup(true);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\tvalue: void 0\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* Called on early exit (e.g., break from for-await).\n\t\t\t* Ensures the stream is cancelled and resources are released.\n\t\t\t* @returns A promise resolving to a completed IteratorResult.\n\t\t\t*/\n\t\t\tasync return() {\n\t\t\t\tawait cleanup(true);\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* Called on early exit with error.\n\t\t\t* Ensures the stream is cancelled and resources are released, then rethrows the error.\n\t\t\t* @param err The error to throw.\n\t\t\t* @returns A promise that rejects with the provided error.\n\t\t\t*/\n\t\t\tasync throw(err) {\n\t\t\t\tawait cleanup(true);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t};\n\treturn stream;\n}\nasync function consumeStream({ stream, onError }) {\n\tconst reader = stream.getReader();\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done } = await reader.read();\n\t\t\tif (done) break;\n\t\t}\n\t} catch (error) {\n\t\tonError?.(error);\n\t} finally {\n\t\treader.releaseLock();\n\t}\n}\nfunction createResolvablePromise() {\n\tlet resolve2;\n\tlet reject;\n\treturn {\n\t\tpromise: new Promise((res, rej) => {\n\t\t\tresolve2 = res;\n\t\t\treject = rej;\n\t\t}),\n\t\tresolve: resolve2,\n\t\treject\n\t};\n}\nfunction createStitchableStream() {\n\tlet innerStreamReaders = [];\n\tlet controller = null;\n\tlet isClosed = false;\n\tlet waitForNewStream = createResolvablePromise();\n\tconst terminate = () => {\n\t\tisClosed = true;\n\t\twaitForNewStream.resolve();\n\t\tinnerStreamReaders.forEach((reader) => reader.cancel());\n\t\tinnerStreamReaders = [];\n\t\tcontroller?.close();\n\t};\n\tconst processPull = async () => {\n\t\tif (isClosed && innerStreamReaders.length === 0) {\n\t\t\tcontroller?.close();\n\t\t\treturn;\n\t\t}\n\t\tif (innerStreamReaders.length === 0) {\n\t\t\twaitForNewStream = createResolvablePromise();\n\t\t\tawait waitForNewStream.promise;\n\t\t\treturn processPull();\n\t\t}\n\t\ttry {\n\t\t\tconst { value, done } = await innerStreamReaders[0].read();\n\t\t\tif (done) {\n\t\t\t\tinnerStreamReaders.shift();\n\t\t\t\tif (innerStreamReaders.length > 0) await processPull();\n\t\t\t\telse if (isClosed) controller?.close();\n\t\t\t} else controller?.enqueue(value);\n\t\t} catch (error) {\n\t\t\tcontroller?.error(error);\n\t\t\tinnerStreamReaders.shift();\n\t\t\tterminate();\n\t\t}\n\t};\n\treturn {\n\t\tstream: new ReadableStream({\n\t\t\tstart(controllerParam) {\n\t\t\t\tcontroller = controllerParam;\n\t\t\t},\n\t\t\tpull: processPull,\n\t\t\tasync cancel() {\n\t\t\t\tfor (const reader of innerStreamReaders) await reader.cancel();\n\t\t\t\tinnerStreamReaders = [];\n\t\t\t\tisClosed = true;\n\t\t\t}\n\t\t}),\n\t\taddStream: (innerStream) => {\n\t\t\tif (isClosed) throw new Error(\"Cannot add inner stream: outer stream is closed\");\n\t\t\tinnerStreamReaders.push(innerStream.getReader());\n\t\t\twaitForNewStream.resolve();\n\t\t},\n\t\t/**\n\t\t* Gracefully close the outer stream. This will let the inner streams\n\t\t* finish processing and then close the outer stream.\n\t\t*/\n\t\tclose: () => {\n\t\t\tisClosed = true;\n\t\t\twaitForNewStream.resolve();\n\t\t\tif (innerStreamReaders.length === 0) controller?.close();\n\t\t},\n\t\t/**\n\t\t* Immediately close the outer stream. This will cancel all inner streams\n\t\t* and close the outer stream.\n\t\t*/\n\t\tterminate\n\t};\n}\nfunction now() {\n\tvar _a16, _b;\n\treturn (_b = (_a16 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a16.now()) != null ? _b : Date.now();\n}\nfunction runToolsTransformation({ tools, generatorStream, tracer, telemetry, system, messages, abortSignal, repairToolCall, experimental_context }) {\n\tlet toolResultsStreamController = null;\n\tlet toolResultsStreamClosed = false;\n\tconst toolResultsStream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\ttoolResultsStreamController = controller;\n\t\t},\n\t\tcancel() {\n\t\t\ttoolResultsStreamClosed = true;\n\t\t}\n\t});\n\tfunction enqueueToolResult(chunk) {\n\t\tif (toolResultsStreamClosed) return;\n\t\ttry {\n\t\t\ttoolResultsStreamController.enqueue(chunk);\n\t\t} catch (e) {\n\t\t\ttoolResultsStreamClosed = true;\n\t\t}\n\t}\n\tfunction closeToolResultsStream() {\n\t\tif (toolResultsStreamClosed) return;\n\t\ttoolResultsStreamClosed = true;\n\t\ttry {\n\t\t\ttoolResultsStreamController.close();\n\t\t} catch (e) {}\n\t}\n\tconst outstandingToolResults = /* @__PURE__ */ new Set();\n\tconst toolInputs = /* @__PURE__ */ new Map();\n\tlet canClose = false;\n\tlet finishChunk = void 0;\n\tfunction attemptClose() {\n\t\tif (canClose && outstandingToolResults.size === 0) {\n\t\t\tif (finishChunk != null) enqueueToolResult(finishChunk);\n\t\t\tcloseToolResultsStream();\n\t\t}\n\t}\n\tconst forwardStream = new TransformStream({\n\t\tasync transform(chunk, controller) {\n\t\t\tconst chunkType = chunk.type;\n\t\t\tswitch (chunkType) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\tcase \"text-start\":\n\t\t\t\tcase \"text-delta\":\n\t\t\t\tcase \"text-end\":\n\t\t\t\tcase \"reasoning-start\":\n\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\tcase \"reasoning-end\":\n\t\t\t\tcase \"tool-input-start\":\n\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\tcase \"tool-input-end\":\n\t\t\t\tcase \"source\":\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\tcase \"error\":\n\t\t\t\tcase \"raw\":\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"file\":\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tfile: new DefaultGeneratedFileWithType({\n\t\t\t\t\t\t\tdata: chunk.data,\n\t\t\t\t\t\t\tmediaType: chunk.mediaType\n\t\t\t\t\t\t})\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tfinishChunk = {\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: chunk.finishReason,\n\t\t\t\t\t\tusage: chunk.usage,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-call\":\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst toolCall = await parseToolCall({\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\t\tsystem,\n\t\t\t\t\t\t\tmessages\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontroller.enqueue(toolCall);\n\t\t\t\t\t\tif (toolCall.invalid) {\n\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\terror: getErrorMessage$1(toolCall.error),\n\t\t\t\t\t\t\t\tdynamic: true\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst tool2 = tools[toolCall.toolName];\n\t\t\t\t\t\ttoolInputs.set(toolCall.toolCallId, toolCall.input);\n\t\t\t\t\t\tif (tool2.onInputAvailable != null) await tool2.onInputAvailable({\n\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (tool2.execute != null && toolCall.providerExecuted !== true) {\n\t\t\t\t\t\t\tconst toolExecutionId = generateId();\n\t\t\t\t\t\t\toutstandingToolResults.add(toolExecutionId);\n\t\t\t\t\t\t\trecordSpan({\n\t\t\t\t\t\t\t\tname: \"ai.toolCall\",\n\t\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\t\toperationId: \"ai.toolCall\",\n\t\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t\"ai.toolCall.name\": toolCall.toolName,\n\t\t\t\t\t\t\t\t\t\t\"ai.toolCall.id\": toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\"ai.toolCall.args\": { output: () => JSON.stringify(toolCall.input) }\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\t\tfn: async (span) => {\n\t\t\t\t\t\t\t\t\tlet output;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tconst stream = executeTool({\n\t\t\t\t\t\t\t\t\t\t\texecute: tool2.execute.bind(tool2),\n\t\t\t\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\t\t\t\toptions: {\n\t\t\t\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tfor await (const part of stream) {\n\t\t\t\t\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\t\t\t\t\t...toolCall,\n\t\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t\t\t\t\t\t...part.type === \"preliminary\" && { preliminary: true }\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\tif (part.type === \"final\") output = part.output;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\t\t\t\t...toolCall,\n\t\t\t\t\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\toutstandingToolResults.delete(toolExecutionId);\n\t\t\t\t\t\t\t\t\t\tattemptClose();\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\toutstandingToolResults.delete(toolExecutionId);\n\t\t\t\t\t\t\t\t\tattemptClose();\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\t\t\tattributes: { \"ai.toolCall.result\": { output: () => JSON.stringify(output) } }\n\t\t\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\t\t} catch (ignored) {}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terror\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-result\": {\n\t\t\t\t\tconst toolName = chunk.toolName;\n\t\t\t\t\tif (chunk.isError) enqueueToolResult({\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput: toolInputs.get(chunk.toolCallId),\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\terror: chunk.result\n\t\t\t\t\t});\n\t\t\t\t\telse controller.enqueue({\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput: toolInputs.get(chunk.toolCallId),\n\t\t\t\t\t\toutput: chunk.result,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: throw new Error(`Unhandled chunk type: ${chunkType}`);\n\t\t\t}\n\t\t},\n\t\tflush() {\n\t\t\tcanClose = true;\n\t\t\tattemptClose();\n\t\t}\n\t});\n\treturn new ReadableStream({ async start(controller) {\n\t\treturn Promise.all([generatorStream.pipeThrough(forwardStream).pipeTo(new WritableStream({\n\t\t\twrite(chunk) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t},\n\t\t\tclose() {}\n\t\t})), toolResultsStream.pipeTo(new WritableStream({\n\t\t\twrite(chunk) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t},\n\t\t\tclose() {\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}))]);\n\t} });\n}\nvar originalGenerateId2 = createIdGenerator({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nfunction streamText$1({ model, tools, toolChoice, system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, headers, stopWhen = stepCountIs(1), experimental_output: output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_activeTools, activeTools = experimental_activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, experimental_download: download2, includeRawChunks = false, onChunk, onError = ({ error }) => {\n\tconsole.error(error);\n}, onFinish, onAbort, onStepFinish, experimental_context, _internal: { now: now2 = now, generateId: generateId3 = originalGenerateId2, currentDate = () => /* @__PURE__ */ new Date() } = {}, ...settings }) {\n\treturn new DefaultStreamTextResult({\n\t\tmodel: resolveLanguageModel(model),\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tabortSignal,\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\ttools,\n\t\ttoolChoice,\n\t\ttransforms: asArray(transform),\n\t\tactiveTools,\n\t\trepairToolCall,\n\t\tstopConditions: asArray(stopWhen),\n\t\toutput,\n\t\tproviderOptions,\n\t\tprepareStep,\n\t\tincludeRawChunks,\n\t\tonChunk,\n\t\tonError,\n\t\tonFinish,\n\t\tonAbort,\n\t\tonStepFinish,\n\t\tnow: now2,\n\t\tcurrentDate,\n\t\tgenerateId: generateId3,\n\t\texperimental_context,\n\t\tdownload: download2\n\t});\n}\nfunction createOutputTransformStream(output) {\n\tif (!output) return new TransformStream({ transform(chunk, controller) {\n\t\tcontroller.enqueue({\n\t\t\tpart: chunk,\n\t\t\tpartialOutput: void 0\n\t\t});\n\t} });\n\tlet firstTextChunkId = void 0;\n\tlet text2 = \"\";\n\tlet textChunk = \"\";\n\tlet lastPublishedJson = \"\";\n\tfunction publishTextChunk({ controller, partialOutput = void 0 }) {\n\t\tcontroller.enqueue({\n\t\t\tpart: {\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tid: firstTextChunkId,\n\t\t\t\ttext: textChunk\n\t\t\t},\n\t\t\tpartialOutput\n\t\t});\n\t\ttextChunk = \"\";\n\t}\n\treturn new TransformStream({ async transform(chunk, controller) {\n\t\tif (chunk.type === \"finish-step\" && textChunk.length > 0) publishTextChunk({ controller });\n\t\tif (chunk.type !== \"text-delta\" && chunk.type !== \"text-start\" && chunk.type !== \"text-end\") {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (firstTextChunkId == null) firstTextChunkId = chunk.id;\n\t\telse if (chunk.id !== firstTextChunkId) {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-start\") {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-end\") {\n\t\t\tif (textChunk.length > 0) publishTextChunk({ controller });\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\ttext2 += chunk.text;\n\t\ttextChunk += chunk.text;\n\t\tif (chunk.text.length === 0 && chunk.providerMetadata != null) {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst result = await output.parsePartial({ text: text2 });\n\t\tif (result != null) {\n\t\t\tconst currentJson = JSON.stringify(result.partial);\n\t\t\tif (currentJson !== lastPublishedJson) {\n\t\t\t\tpublishTextChunk({\n\t\t\t\t\tcontroller,\n\t\t\t\t\tpartialOutput: result.partial\n\t\t\t\t});\n\t\t\t\tlastPublishedJson = currentJson;\n\t\t\t}\n\t\t}\n\t} });\n}\nvar DefaultStreamTextResult = class {\n\tconstructor({ model, telemetry, headers, settings, maxRetries: maxRetriesArg, abortSignal, system, prompt, messages, allowSystemInMessages, tools, toolChoice, transforms, activeTools, repairToolCall, stopConditions, output, providerOptions, prepareStep, includeRawChunks, now: now2, currentDate, generateId: generateId3, onChunk, onError, onFinish, onAbort, onStepFinish, experimental_context, download: download2 }) {\n\t\tthis._totalUsage = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tthis._steps = new DelayedPromise();\n\t\tthis.output = output;\n\t\tthis.includeRawChunks = includeRawChunks;\n\t\tthis.tools = tools;\n\t\tlet stepFinish;\n\t\tlet recordedContent = [];\n\t\tconst recordedResponseMessages = [];\n\t\tlet recordedFinishReason = void 0;\n\t\tlet recordedTotalUsage = void 0;\n\t\tlet recordedRequest = {};\n\t\tlet recordedWarnings = [];\n\t\tconst recordedSteps = [];\n\t\tlet currentStepToolSet = tools;\n\t\tlet rootSpan;\n\t\tlet activeTextContent = createIdMap();\n\t\tlet activeReasoningContent = createIdMap();\n\t\tconst eventProcessor = new TransformStream({\n\t\t\tasync transform(chunk, controller) {\n\t\t\t\tvar _a16, _b, _c, _d;\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tconst { part } = chunk;\n\t\t\t\tif (part.type === \"text-delta\" || part.type === \"reasoning-delta\" || part.type === \"source\" || part.type === \"tool-call\" || part.type === \"tool-result\" || part.type === \"tool-input-start\" || part.type === \"tool-input-delta\" || part.type === \"raw\") await (onChunk == null ? void 0 : onChunk({ chunk: part }));\n\t\t\t\tif (part.type === \"error\") await onError({ error: wrapGatewayError(part.error) });\n\t\t\t\tif (part.type === \"text-start\") {\n\t\t\t\t\tactiveTextContent[part.id] = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeTextContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-delta\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.text += part.text;\n\t\t\t\t\tactiveText.providerMetadata = (_a16 = part.providerMetadata) != null ? _a16 : activeText.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-end\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.providerMetadata = (_b = part.providerMetadata) != null ? _b : activeText.providerMetadata;\n\t\t\t\t\tdelete activeTextContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-start\") {\n\t\t\t\t\tactiveReasoningContent[part.id] = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeReasoningContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-delta\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.text += part.text;\n\t\t\t\t\tactiveReasoning.providerMetadata = (_c = part.providerMetadata) != null ? _c : activeReasoning.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-end\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.providerMetadata = (_d = part.providerMetadata) != null ? _d : activeReasoning.providerMetadata;\n\t\t\t\t\tdelete activeReasoningContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"file\") recordedContent.push({\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tfile: part.file\n\t\t\t\t});\n\t\t\t\tif (part.type === \"source\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-call\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-result\" && !part.preliminary) recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-error\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"start-step\") {\n\t\t\t\t\trecordedContent = [];\n\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\trecordedRequest = part.request;\n\t\t\t\t\trecordedWarnings = part.warnings;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish-step\") {\n\t\t\t\t\tconst stepMessages = toResponseMessages({\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\ttools: currentStepToolSet\n\t\t\t\t\t});\n\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t\t\tusage: part.usage,\n\t\t\t\t\t\twarnings: recordedWarnings,\n\t\t\t\t\t\trequest: recordedRequest,\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t...part.response,\n\t\t\t\t\t\t\tmessages: [...recordedResponseMessages, ...stepMessages]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tawait (onStepFinish == null ? void 0 : onStepFinish(currentStepResult));\n\t\t\t\t\tlogWarnings(recordedWarnings);\n\t\t\t\t\trecordedSteps.push(currentStepResult);\n\t\t\t\t\trecordedContent = [];\n\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\trecordedResponseMessages.push(...stepMessages);\n\t\t\t\t\tstepFinish.resolve();\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish\") {\n\t\t\t\t\trecordedTotalUsage = part.totalUsage;\n\t\t\t\t\trecordedFinishReason = part.finishReason;\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync flush(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tif (recordedSteps.length === 0) {\n\t\t\t\t\t\tconst error = new NoOutputGeneratedError({ message: \"No output generated. Check the stream for errors.\" });\n\t\t\t\t\t\tself._finishReason.reject(error);\n\t\t\t\t\t\tself._totalUsage.reject(error);\n\t\t\t\t\t\tself._steps.reject(error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst finishReason = recordedFinishReason != null ? recordedFinishReason : \"unknown\";\n\t\t\t\t\tconst totalUsage = recordedTotalUsage != null ? recordedTotalUsage : {\n\t\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t\t};\n\t\t\t\t\tself._finishReason.resolve(finishReason);\n\t\t\t\t\tself._totalUsage.resolve(totalUsage);\n\t\t\t\t\tself._steps.resolve(recordedSteps);\n\t\t\t\t\tconst finalStep = recordedSteps[recordedSteps.length - 1];\n\t\t\t\t\tawait (onFinish == null ? void 0 : onFinish({\n\t\t\t\t\t\tfinishReason,\n\t\t\t\t\t\ttotalUsage,\n\t\t\t\t\t\tusage: finalStep.usage,\n\t\t\t\t\t\tcontent: finalStep.content,\n\t\t\t\t\t\ttext: finalStep.text,\n\t\t\t\t\t\treasoningText: finalStep.reasoningText,\n\t\t\t\t\t\treasoning: finalStep.reasoning,\n\t\t\t\t\t\tfiles: finalStep.files,\n\t\t\t\t\t\tsources: finalStep.sources,\n\t\t\t\t\t\ttoolCalls: finalStep.toolCalls,\n\t\t\t\t\t\tstaticToolCalls: finalStep.staticToolCalls,\n\t\t\t\t\t\tdynamicToolCalls: finalStep.dynamicToolCalls,\n\t\t\t\t\t\ttoolResults: finalStep.toolResults,\n\t\t\t\t\t\tstaticToolResults: finalStep.staticToolResults,\n\t\t\t\t\t\tdynamicToolResults: finalStep.dynamicToolResults,\n\t\t\t\t\t\trequest: finalStep.request,\n\t\t\t\t\t\tresponse: finalStep.response,\n\t\t\t\t\t\twarnings: finalStep.warnings,\n\t\t\t\t\t\tproviderMetadata: finalStep.providerMetadata,\n\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t}));\n\t\t\t\t\trootSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\t\"ai.response.text\": { output: () => finalStep.text },\n\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\t\tvar _a16;\n\t\t\t\t\t\t\t\treturn ((_a16 = finalStep.toolCalls) == null ? void 0 : _a16.length) ? JSON.stringify(finalStep.toolCalls) : void 0;\n\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(finalStep.providerMetadata),\n\t\t\t\t\t\t\t\"ai.usage.inputTokens\": totalUsage.inputTokens,\n\t\t\t\t\t\t\t\"ai.usage.outputTokens\": totalUsage.outputTokens,\n\t\t\t\t\t\t\t\"ai.usage.totalTokens\": totalUsage.totalTokens,\n\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": totalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": totalUsage.cachedInputTokens\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t} finally {\n\t\t\t\t\trootSpan.end();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tconst stitchableStream = createStitchableStream();\n\t\tthis.addStream = stitchableStream.addStream;\n\t\tthis.closeStream = stitchableStream.close;\n\t\tconst reader = stitchableStream.stream.getReader();\n\t\tlet stream = new ReadableStream({\n\t\t\tasync start(controller) {\n\t\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\t},\n\t\t\tasync pull(controller) {\n\t\t\t\tfunction abort() {\n\t\t\t\t\tonAbort?.({ steps: recordedSteps });\n\t\t\t\t\tcontroller.enqueue({ type: \"abort\" });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (abortSignal == null ? void 0 : abortSignal.aborted) {\n\t\t\t\t\t\tabort();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isAbortError(error) && (abortSignal == null ? void 0 : abortSignal.aborted)) abort();\n\t\t\t\t\telse controller.error(error);\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel(reason) {\n\t\t\t\treturn stitchableStream.stream.cancel(reason);\n\t\t\t}\n\t\t});\n\t\tfor (const transform of transforms) stream = stream.pipeThrough(transform({\n\t\t\ttools,\n\t\t\tstopStream() {\n\t\t\t\tstitchableStream.terminate();\n\t\t\t}\n\t\t}));\n\t\tthis.baseStream = stream.pipeThrough(createOutputTransformStream(output)).pipeThrough(eventProcessor);\n\t\tconst { maxRetries, retry } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst tracer = getTracer(telemetry);\n\t\tconst callSettings = prepareCallSettings(settings);\n\t\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\t\tmodel,\n\t\t\ttelemetry,\n\t\t\theaders,\n\t\t\tsettings: {\n\t\t\t\t...callSettings,\n\t\t\t\tmaxRetries\n\t\t\t}\n\t\t});\n\t\tconst self = this;\n\t\trecordSpan({\n\t\t\tname: \"ai.streamText\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.streamText\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tendWhenDone: false,\n\t\t\tfn: async (rootSpanArg) => {\n\t\t\t\trootSpan = rootSpanArg;\n\t\t\t\tasync function streamStep({ currentStep, responseMessages, usage }) {\n\t\t\t\t\tvar _a16, _b, _c, _d, _e;\n\t\t\t\t\tconst includeRawChunks2 = self.includeRawChunks;\n\t\t\t\t\tstepFinish = new DelayedPromise();\n\t\t\t\t\tconst initialPrompt = await standardizePrompt({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tallowSystemInMessages\n\t\t\t\t\t});\n\t\t\t\t\tconst stepInputMessages = [...initialPrompt.messages, ...responseMessages];\n\t\t\t\t\tconst prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tsteps: recordedSteps,\n\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\tmessages: stepInputMessages\n\t\t\t\t\t}));\n\t\t\t\t\tconst stepModel = resolveLanguageModel((_a16 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a16 : model);\n\t\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\t\tprompt: {\n\t\t\t\t\t\t\tsystem: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n\t\t\t\t\t\t\tmessages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsupportedUrls: await stepModel.supportedUrls,\n\t\t\t\t\t\tdownload: download2\n\t\t\t\t\t});\n\t\t\t\t\tconst stepActiveTools = (_d = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _d : activeTools;\n\t\t\t\t\tconst stepToolSet = filterActiveTools({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t});\n\t\t\t\t\tcurrentStepToolSet = stepToolSet;\n\t\t\t\t\tconst { toolChoice: stepToolChoice, tools: stepTools } = prepareToolsAndToolChoice({\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\ttoolChoice: (_e = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _e : toolChoice,\n\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t});\n\t\t\t\t\tconst { result: { stream: stream2, response, request }, doStreamSpan, startTimestampMs } = await retry(() => recordSpan({\n\t\t\t\t\t\tname: \"ai.streamText.doStream\",\n\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\toperationId: \"ai.streamText.doStream\",\n\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\"ai.model.provider\": stepModel.provider,\n\t\t\t\t\t\t\t\t\"ai.model.id\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\t\"ai.prompt.tools\": { input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2)) },\n\t\t\t\t\t\t\t\t\"ai.prompt.toolChoice\": { input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0 },\n\t\t\t\t\t\t\t\t\"gen_ai.system\": stepModel.provider,\n\t\t\t\t\t\t\t\t\"gen_ai.request.model\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\t\"gen_ai.request.stop_sequences\": callSettings.stopSequences,\n\t\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\tendWhenDone: false,\n\t\t\t\t\t\tfn: async (doStreamSpan2) => {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tstartTimestampMs: now2(),\n\t\t\t\t\t\t\t\tdoStreamSpan: doStreamSpan2,\n\t\t\t\t\t\t\t\tresult: await stepModel.doStream({\n\t\t\t\t\t\t\t\t\t...callSettings,\n\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\tresponseFormat: output == null ? void 0 : output.responseFormat,\n\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\t\tincludeRawChunks: includeRawChunks2\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\tconst streamWithToolResults = runToolsTransformation({\n\t\t\t\t\t\ttools: stepToolSet,\n\t\t\t\t\t\tgeneratorStream: stream2,\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t});\n\t\t\t\t\tconst stepRequest = request != null ? request : {};\n\t\t\t\t\tconst stepToolCalls = [];\n\t\t\t\t\tconst stepToolOutputs = [];\n\t\t\t\t\tlet warnings;\n\t\t\t\t\tconst activeToolCallToolNames = {};\n\t\t\t\t\tlet stepFinishReason = \"unknown\";\n\t\t\t\t\tlet stepUsage = {\n\t\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t\t};\n\t\t\t\t\tlet stepProviderMetadata;\n\t\t\t\t\tlet stepFirstChunk = true;\n\t\t\t\t\tlet stepResponse = {\n\t\t\t\t\t\tid: generateId3(),\n\t\t\t\t\t\ttimestamp: currentDate(),\n\t\t\t\t\t\tmodelId: model.modelId\n\t\t\t\t\t};\n\t\t\t\t\tlet activeText = \"\";\n\t\t\t\t\tself.addStream(streamWithToolResults.pipeThrough(new TransformStream({\n\t\t\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\t\t\tvar _a17, _b2, _c2, _d2;\n\t\t\t\t\t\t\tif (chunk.type === \"stream-start\") {\n\t\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (stepFirstChunk) {\n\t\t\t\t\t\t\t\tconst msToFirstChunk = now2() - startTimestampMs;\n\t\t\t\t\t\t\t\tstepFirstChunk = false;\n\t\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.firstChunk\", { \"ai.response.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes({ \"ai.response.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"start-step\",\n\t\t\t\t\t\t\t\t\trequest: stepRequest,\n\t\t\t\t\t\t\t\t\twarnings: warnings != null ? warnings : []\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst chunkType = chunk.type;\n\t\t\t\t\t\t\tswitch (chunkType) {\n\t\t\t\t\t\t\t\tcase \"text-start\":\n\t\t\t\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\t\t\t\tif (chunk.delta.length > 0 || chunk.providerMetadata != null) {\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\t\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tactiveText += chunk.delta;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"reasoning-start\":\n\t\t\t\t\t\t\t\tcase \"reasoning-end\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-call\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tstepToolCalls.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-result\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tif (!chunk.preliminary) stepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-error\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tstepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\t\t\t\tstepResponse = {\n\t\t\t\t\t\t\t\t\t\tid: (_a17 = chunk.id) != null ? _a17 : stepResponse.id,\n\t\t\t\t\t\t\t\t\t\ttimestamp: (_b2 = chunk.timestamp) != null ? _b2 : stepResponse.timestamp,\n\t\t\t\t\t\t\t\t\t\tmodelId: (_c2 = chunk.modelId) != null ? _c2 : stepResponse.modelId\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"finish\": {\n\t\t\t\t\t\t\t\t\tstepUsage = chunk.usage;\n\t\t\t\t\t\t\t\t\tstepFinishReason = chunk.finishReason;\n\t\t\t\t\t\t\t\t\tstepProviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\t\t\tconst msToFinish = now2() - startTimestampMs;\n\t\t\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.finish\");\n\t\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes({\n\t\t\t\t\t\t\t\t\t\t\"ai.response.msToFinish\": msToFinish,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.avgOutputTokensPerSecond\": 1e3 * ((_d2 = stepUsage.outputTokens) != null ? _d2 : 0) / msToFinish\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"file\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"source\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\t\t\t\t\tactiveToolCallToolNames[chunk.id] = chunk.toolName;\n\t\t\t\t\t\t\t\t\tconst tool2 = stepToolSet == null ? void 0 : stepToolSet[chunk.toolName];\n\t\t\t\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.onInputStart) != null) await tool2.onInputStart({\n\t\t\t\t\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\tdynamic: (tool2 == null ? void 0 : tool2.type) === \"dynamic\"\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"tool-input-end\":\n\t\t\t\t\t\t\t\t\tdelete activeToolCallToolNames[chunk.id];\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"tool-input-delta\": {\n\t\t\t\t\t\t\t\t\tconst toolName = activeToolCallToolNames[chunk.id];\n\t\t\t\t\t\t\t\t\tconst tool2 = stepToolSet == null ? void 0 : stepToolSet[toolName];\n\t\t\t\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.onInputDelta) != null) await tool2.onInputDelta({\n\t\t\t\t\t\t\t\t\t\tinputTextDelta: chunk.delta,\n\t\t\t\t\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tstepFinishReason = \"error\";\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"raw\":\n\t\t\t\t\t\t\t\t\tif (includeRawChunks2) controller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tdefault: throw new Error(`Unknown chunk type: ${chunkType}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\tasync flush(controller) {\n\t\t\t\t\t\t\tconst stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : void 0;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": stepFinishReason,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.text\": { output: () => activeText },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => stepToolCallsJson },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.id\": stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.model\": stepResponse.modelId,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": stepResponse.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(stepProviderMetadata),\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": stepUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": stepUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": stepUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": stepUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": stepUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [stepFinishReason],\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": stepResponse.modelId,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": stepUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": stepUsage.outputTokens\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t} catch (error) {} finally {\n\t\t\t\t\t\t\t\tdoStreamSpan.end();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"finish-step\",\n\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\tusage: stepUsage,\n\t\t\t\t\t\t\t\tproviderMetadata: stepProviderMetadata,\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...stepResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst combinedUsage = addLanguageModelUsage(usage, stepUsage);\n\t\t\t\t\t\t\tawait stepFinish.promise;\n\t\t\t\t\t\t\tconst clientToolCalls = stepToolCalls.filter((toolCall) => toolCall.providerExecuted !== true);\n\t\t\t\t\t\t\tconst clientToolOutputs = stepToolOutputs.filter((toolOutput) => toolOutput.providerExecuted !== true);\n\t\t\t\t\t\t\tif (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length && !await isStopConditionMet({\n\t\t\t\t\t\t\t\tstopConditions,\n\t\t\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\t\tresponseMessages.push(...toResponseMessages({\n\t\t\t\t\t\t\t\t\tcontent: recordedSteps[recordedSteps.length - 1].content,\n\t\t\t\t\t\t\t\t\ttools: stepToolSet\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait streamStep({\n\t\t\t\t\t\t\t\t\t\tcurrentStep: currentStep + 1,\n\t\t\t\t\t\t\t\t\t\tresponseMessages,\n\t\t\t\t\t\t\t\t\t\tusage: combinedUsage\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\t\ttotalUsage: combinedUsage\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})));\n\t\t\t\t}\n\t\t\t\tawait streamStep({\n\t\t\t\t\tcurrentStep: 0,\n\t\t\t\t\tresponseMessages: [],\n\t\t\t\t\tusage: {\n\t\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tself.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t\tself.closeStream();\n\t\t});\n\t}\n\tget steps() {\n\t\tthis.consumeStream();\n\t\treturn this._steps.promise;\n\t}\n\tget finalStep() {\n\t\treturn this.steps.then((steps) => steps[steps.length - 1]);\n\t}\n\tget content() {\n\t\treturn this.finalStep.then((step) => step.content);\n\t}\n\tget warnings() {\n\t\treturn this.finalStep.then((step) => step.warnings);\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.then((step) => step.providerMetadata);\n\t}\n\tget text() {\n\t\treturn this.finalStep.then((step) => step.text);\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.then((step) => step.reasoningText);\n\t}\n\tget reasoning() {\n\t\treturn this.finalStep.then((step) => step.reasoning);\n\t}\n\tget sources() {\n\t\treturn this.finalStep.then((step) => step.sources);\n\t}\n\tget files() {\n\t\treturn this.finalStep.then((step) => step.files);\n\t}\n\tget toolCalls() {\n\t\treturn this.finalStep.then((step) => step.toolCalls);\n\t}\n\tget staticToolCalls() {\n\t\treturn this.finalStep.then((step) => step.staticToolCalls);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.finalStep.then((step) => step.dynamicToolCalls);\n\t}\n\tget toolResults() {\n\t\treturn this.finalStep.then((step) => step.toolResults);\n\t}\n\tget staticToolResults() {\n\t\treturn this.finalStep.then((step) => step.staticToolResults);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.finalStep.then((step) => step.dynamicToolResults);\n\t}\n\tget usage() {\n\t\treturn this.finalStep.then((step) => step.usage);\n\t}\n\tget request() {\n\t\treturn this.finalStep.then((step) => step.request);\n\t}\n\tget response() {\n\t\treturn this.finalStep.then((step) => step.response);\n\t}\n\tget totalUsage() {\n\t\tthis.consumeStream();\n\t\treturn this._totalUsage.promise;\n\t}\n\tget finishReason() {\n\t\tthis.consumeStream();\n\t\treturn this._finishReason.promise;\n\t}\n\t/**\n\tSplit out a new stream from the original stream.\n\tThe original stream is replaced to allow for further splitting,\n\tsince we do not know how many times the stream will be split.\n\t\n\tNote: this leads to buffering the stream content on the server.\n\tHowever, the LLM results are expected to be small enough to not cause issues.\n\t*/\n\tteeStream() {\n\t\tconst [stream1, stream2] = this.baseStream.tee();\n\t\tthis.baseStream = stream2;\n\t\treturn stream1;\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {\n\t\t\tif (part.type === \"text-delta\") controller.enqueue(part.text);\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {\n\t\t\tcontroller.enqueue(part);\n\t\t} })));\n\t}\n\tasync consumeStream(options) {\n\t\tvar _a16;\n\t\ttry {\n\t\t\tawait consumeStream({\n\t\t\t\tstream: this.fullStream,\n\t\t\t\tonError: options == null ? void 0 : options.onError\n\t\t\t});\n\t\t} catch (error) {\n\t\t\t(_a16 = options == null ? void 0 : options.onError) == null || _a16.call(options, error);\n\t\t}\n\t}\n\tget experimental_partialOutputStream() {\n\t\tif (this.output == null) throw new NoOutputSpecifiedError();\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ partialOutput }, controller) {\n\t\t\tif (partialOutput != null) controller.enqueue(partialOutput);\n\t\t} })));\n\t}\n\ttoUIMessageStream({ originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => \"An error occurred.\" } = {}) {\n\t\tconst responseMessageId = generateMessageId != null ? getResponseUIMessageId({\n\t\t\toriginalMessages,\n\t\t\tresponseMessageId: generateMessageId\n\t\t}) : void 0;\n\t\tconst toolNamesByCallId = {};\n\t\tconst isDynamic = (toolCallId) => {\n\t\t\tvar _a16, _b;\n\t\t\tconst toolName = toolNamesByCallId[toolCallId];\n\t\t\treturn ((_b = (_a16 = this.tools) == null ? void 0 : _a16[toolName]) == null ? void 0 : _b.type) === \"dynamic\" ? true : void 0;\n\t\t};\n\t\treturn createAsyncIterableStream(handleUIMessageStreamFinish({\n\t\t\tstream: this.fullStream.pipeThrough(new TransformStream({ transform: async (part, controller) => {\n\t\t\t\tconst messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });\n\t\t\t\tconst partType = part.type;\n\t\t\t\tswitch (partType) {\n\t\t\t\t\tcase \"text-start\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-start\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\t\t\tif (sendReasoning) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-end\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"file\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\t\t\t\turl: `data:${part.file.mediaType};base64,${part.file.base64}`\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"source\":\n\t\t\t\t\t\tif (sendSources && part.sourceType === \"url\") controller.enqueue({\n\t\t\t\t\t\t\ttype: \"source-url\",\n\t\t\t\t\t\t\tsourceId: part.id,\n\t\t\t\t\t\t\turl: part.url,\n\t\t\t\t\t\t\ttitle: part.title,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (sendSources && part.sourceType === \"document\") controller.enqueue({\n\t\t\t\t\t\t\ttype: \"source-document\",\n\t\t\t\t\t\t\tsourceId: part.id,\n\t\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\t\ttitle: part.title,\n\t\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\t\ttoolNamesByCallId[part.id] = part.toolName;\n\t\t\t\t\t\tconst dynamic = isDynamic(part.id);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-start\",\n\t\t\t\t\t\t\ttoolCallId: part.id,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-delta\",\n\t\t\t\t\t\t\ttoolCallId: part.id,\n\t\t\t\t\t\t\tinputTextDelta: part.delta\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-call\": {\n\t\t\t\t\t\ttoolNamesByCallId[part.toolCallId] = part.toolName;\n\t\t\t\t\t\tconst dynamic = isDynamic(part.toolCallId);\n\t\t\t\t\t\tif (part.invalid) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-error\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\t\t\t\terrorText: onError(part.error)\n\t\t\t\t\t\t});\n\t\t\t\t\t\telse controller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-available\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-result\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part.toolCallId);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-available\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.preliminary != null ? { preliminary: part.preliminary } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-error\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part.toolCallId);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-error\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\terrorText: onError(part.error),\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terrorText: onError(part.error)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"start-step\":\n\t\t\t\t\t\tcontroller.enqueue({ type: \"start-step\" });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"finish-step\":\n\t\t\t\t\t\tcontroller.enqueue({ type: \"finish-step\" });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tif (sendStart) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"start\",\n\t\t\t\t\t\t\t...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},\n\t\t\t\t\t\t\t...responseMessageId != null ? { messageId: responseMessageId } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\tif (sendFinish) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t\t\t\t...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"abort\":\n\t\t\t\t\t\tcontroller.enqueue(part);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-input-end\": break;\n\t\t\t\t\tcase \"raw\": break;\n\t\t\t\t\tdefault: throw new Error(`Unknown chunk type: ${partType}`);\n\t\t\t\t}\n\t\t\t\tif (messageMetadataValue != null && partType !== \"start\" && partType !== \"finish\") controller.enqueue({\n\t\t\t\t\ttype: \"message-metadata\",\n\t\t\t\t\tmessageMetadata: messageMetadataValue\n\t\t\t\t});\n\t\t\t} })),\n\t\t\tmessageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),\n\t\t\toriginalMessages,\n\t\t\tonFinish,\n\t\t\tonError\n\t\t}));\n\t}\n\tpipeUIMessageStreamToResponse(response, { originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\treturn pipeUIMessageStreamToResponse({\n\t\t\tresponse,\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\treturn pipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoUIMessageStreamResponse({ originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\treturn createUIMessageStreamResponse({\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\nfunction convertToModelMessages(messages, options) {\n\tconst modelMessages = [];\n\tif (options == null ? void 0 : options.ignoreIncompleteToolCalls) messages = messages.map((message) => ({\n\t\t...message,\n\t\tparts: message.parts.filter((part) => !isToolOrDynamicToolUIPart(part) || part.state !== \"input-streaming\" && part.state !== \"input-available\")\n\t}));\n\tfor (const message of messages) switch (message.role) {\n\t\tcase \"system\": {\n\t\t\tconst textParts = message.parts.filter((part) => part.type === \"text\");\n\t\t\tconst providerMetadata = textParts.reduce((acc, part) => {\n\t\t\t\tif (part.providerMetadata != null) return {\n\t\t\t\t\t...acc,\n\t\t\t\t\t...part.providerMetadata\n\t\t\t\t};\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: textParts.map((part) => part.text).join(\"\"),\n\t\t\t\t...Object.keys(providerMetadata).length > 0 ? { providerOptions: providerMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"user\":\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.parts.map((part) => {\n\t\t\t\t\tvar _a16;\n\t\t\t\t\tif (isTextUIPart(part)) return {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isFileUIPart(part)) return {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.url,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isDataUIPart(part)) return (_a16 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a16.call(options, part);\n\t\t\t\t}).filter((part) => part != null)\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"assistant\":\n\t\t\tif (message.parts != null) {\n\t\t\t\tlet processBlock2 = function() {\n\t\t\t\t\tvar _a16, _b, _c;\n\t\t\t\t\tif (block.length === 0) return;\n\t\t\t\t\tconst content = [];\n\t\t\t\t\tfor (const part of block) if (isTextUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse if (isFileUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.url\n\t\t\t\t\t});\n\t\t\t\t\telse if (isReasoningUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse if (isDynamicToolUIPart(part)) {\n\t\t\t\t\t\tconst toolName = part.toolName;\n\t\t\t\t\t\tif (part.state !== \"input-streaming\") content.push({\n\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t} else if (isToolUIPart(part)) {\n\t\t\t\t\t\tconst toolName = getToolName(part);\n\t\t\t\t\t\tif (part.state !== \"input-streaming\") {\n\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\tinput: part.state === \"output-error\" ? (_a16 = part.input) != null ? _a16 : part.rawInput : part.input,\n\t\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\t\t...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (part.providerExecuted === true && (part.state === \"output-available\" || part.state === \"output-error\")) content.push({\n\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\t\t\t\t\toutput: part.state === \"output-error\" ? part.errorText : part.output,\n\t\t\t\t\t\t\t\t\ttool: (_b = options == null ? void 0 : options.tools) == null ? void 0 : _b[toolName],\n\t\t\t\t\t\t\t\t\terrorMode: part.state === \"output-error\" ? \"json\" : \"none\"\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (isDataUIPart(part)) {\n\t\t\t\t\t\tconst dataPart = (_c = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _c.call(options, part);\n\t\t\t\t\t\tif (dataPart != null) content.push(dataPart);\n\t\t\t\t\t} else throw new Error(`Unsupported part: ${part}`);\n\t\t\t\t\tmodelMessages.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent\n\t\t\t\t\t});\n\t\t\t\t\tconst toolParts = block.filter((part) => isToolUIPart(part) && part.providerExecuted !== true || part.type === \"dynamic-tool\");\n\t\t\t\t\tif (toolParts.length > 0) modelMessages.push({\n\t\t\t\t\t\trole: \"tool\",\n\t\t\t\t\t\tcontent: toolParts.map((toolPart) => {\n\t\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\t\tswitch (toolPart.state) {\n\t\t\t\t\t\t\t\tcase \"output-error\":\n\t\t\t\t\t\t\t\tcase \"output-available\": {\n\t\t\t\t\t\t\t\t\tconst toolName = getToolOrDynamicToolName(toolPart);\n\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\toutput: createToolModelOutput({\n\t\t\t\t\t\t\t\t\t\t\toutput: toolPart.state === \"output-error\" ? toolPart.errorText : toolPart.output,\n\t\t\t\t\t\t\t\t\t\t\ttool: (_a17 = options == null ? void 0 : options.tools) == null ? void 0 : _a17[toolName],\n\t\t\t\t\t\t\t\t\t\t\terrorMode: toolPart.state === \"output-error\" ? \"text\" : \"none\"\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tdefault: return null;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}).filter((output) => output != null)\n\t\t\t\t\t});\n\t\t\t\t\tblock = [];\n\t\t\t\t};\n\t\t\t\tlet block = [];\n\t\t\t\tfor (const part of message.parts) if (isTextUIPart(part) || isReasoningUIPart(part) || isFileUIPart(part) || isToolOrDynamicToolUIPart(part) || isDataUIPart(part)) block.push(part);\n\t\t\t\telse if (part.type === \"step-start\") processBlock2();\n\t\t\t\tprocessBlock2();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck = message.role;\n\t\t\tthrow new MessageConversionError({\n\t\t\t\toriginalMessage: message,\n\t\t\t\tmessage: `Unsupported role: ${_exhaustiveCheck}`\n\t\t\t});\n\t\t}\n\t}\n\treturn modelMessages;\n}\nvar convertToCoreMessages = convertToModelMessages;\nvar Agent = class {\n\tconstructor(settings) {\n\t\tthis.settings = settings;\n\t}\n\tget tools() {\n\t\treturn this.settings.tools;\n\t}\n\tasync generate(options) {\n\t\treturn generateText$1({\n\t\t\t...this.settings,\n\t\t\t...options\n\t\t});\n\t}\n\tstream(options) {\n\t\treturn streamText$1({\n\t\t\t...this.settings,\n\t\t\t...options\n\t\t});\n\t}\n\t/**\n\t* Creates a response object that streams UI messages to the client.\n\t*/\n\trespond(options) {\n\t\treturn this.stream({ prompt: convertToModelMessages(options.messages) }).toUIMessageStreamResponse();\n\t}\n};\nasync function embed({ model: modelArg, value, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry }) {\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: { maxRetries }\n\t});\n\tconst tracer = getTracer(telemetry);\n\treturn recordSpan({\n\t\tname: \"ai.embed\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.embed\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\"ai.value\": { input: () => JSON.stringify(value) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async (span) => {\n\t\t\tconst { embedding, usage, response, providerMetadata } = await retry(() => recordSpan({\n\t\t\t\tname: \"ai.embed.doEmbed\",\n\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\toperationId: \"ai.embed.doEmbed\",\n\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\"ai.values\": { input: () => [JSON.stringify(value)] }\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\ttracer,\n\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\tvar _a16;\n\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\tvalues: [value],\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t});\n\t\t\t\t\tconst embedding2 = modelResponse.embeddings[0];\n\t\t\t\t\tconst usage2 = (_a16 = modelResponse.usage) != null ? _a16 : { tokens: NaN };\n\t\t\t\t\tdoEmbedSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => modelResponse.embeddings.map((embedding3) => JSON.stringify(embedding3)) },\n\t\t\t\t\t\t\t\"ai.usage.tokens\": usage2.tokens\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\treturn {\n\t\t\t\t\t\tembedding: embedding2,\n\t\t\t\t\t\tusage: usage2,\n\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}));\n\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t\"ai.embedding\": { output: () => JSON.stringify(embedding) },\n\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t}\n\t\t\t}));\n\t\t\treturn new DefaultEmbedResult({\n\t\t\t\tvalue,\n\t\t\t\tembedding,\n\t\t\t\tusage,\n\t\t\t\tproviderMetadata,\n\t\t\t\tresponse\n\t\t\t});\n\t\t}\n\t});\n}\nvar DefaultEmbedResult = class {\n\tconstructor(options) {\n\t\tthis.value = options.value;\n\t\tthis.embedding = options.embedding;\n\t\tthis.usage = options.usage;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t}\n};\nfunction splitArray(array, chunkSize) {\n\tif (chunkSize <= 0) throw new Error(\"chunkSize must be greater than 0\");\n\tconst result = [];\n\tfor (let i = 0; i < array.length; i += chunkSize) result.push(array.slice(i, i + chunkSize));\n\treturn result;\n}\nasync function embedMany({ model: modelArg, values, maxParallelCalls = Infinity, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry }) {\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: { maxRetries }\n\t});\n\tconst tracer = getTracer(telemetry);\n\treturn recordSpan({\n\t\tname: \"ai.embedMany\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.embedMany\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\"ai.values\": { input: () => values.map((value) => JSON.stringify(value)) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async (span) => {\n\t\t\tvar _a16;\n\t\t\tconst [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([model.maxEmbeddingsPerCall, model.supportsParallelCalls]);\n\t\t\tif (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {\n\t\t\t\tconst { embeddings: embeddings2, usage, response, providerMetadata: providerMetadata2 } = await retry(() => {\n\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\tname: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\"ai.values\": { input: () => values.map((value) => JSON.stringify(value)) }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst embeddings3 = modelResponse.embeddings;\n\t\t\t\t\t\t\tconst usage2 = (_a17 = modelResponse.usage) != null ? _a17 : { tokens: NaN };\n\t\t\t\t\t\t\tdoEmbedSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings3.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\t\t\t\"ai.usage.tokens\": usage2.tokens\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tembeddings: embeddings3,\n\t\t\t\t\t\t\t\tusage: usage2,\n\t\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\t\tvalues,\n\t\t\t\t\tembeddings: embeddings2,\n\t\t\t\t\tusage,\n\t\t\t\t\tproviderMetadata: providerMetadata2,\n\t\t\t\t\tresponses: [response]\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst valueChunks = splitArray(values, maxEmbeddingsPerCall);\n\t\t\tconst embeddings = [];\n\t\t\tconst responses = [];\n\t\t\tlet tokens = 0;\n\t\t\tlet providerMetadata;\n\t\t\tconst parallelChunks = splitArray(valueChunks, supportsParallelCalls ? maxParallelCalls : 1);\n\t\t\tfor (const parallelChunk of parallelChunks) {\n\t\t\t\tconst results = await Promise.all(parallelChunk.map((chunk) => {\n\t\t\t\t\treturn retry(() => {\n\t\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\t\tname: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\t\"ai.values\": { input: () => chunk.map((value) => JSON.stringify(value)) }\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\t\t\t\tvar _a17;\n\t\t\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\t\t\tvalues: chunk,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst embeddings2 = modelResponse.embeddings;\n\t\t\t\t\t\t\t\tconst usage = (_a17 = modelResponse.usage) != null ? _a17 : { tokens: NaN };\n\t\t\t\t\t\t\t\tdoEmbedSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tembeddings: embeddings2,\n\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}));\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tembeddings.push(...result.embeddings);\n\t\t\t\t\tresponses.push(result.response);\n\t\t\t\t\ttokens += result.usage.tokens;\n\t\t\t\t\tif (result.providerMetadata) if (!providerMetadata) providerMetadata = { ...result.providerMetadata };\n\t\t\t\t\telse for (const [providerName, metadata] of Object.entries(result.providerMetadata)) providerMetadata[providerName] = {\n\t\t\t\t\t\t...(_a16 = providerMetadata[providerName]) != null ? _a16 : {},\n\t\t\t\t\t\t...metadata\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\"ai.usage.tokens\": tokens\n\t\t\t\t}\n\t\t\t}));\n\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\tvalues,\n\t\t\t\tembeddings,\n\t\t\t\tusage: { tokens },\n\t\t\t\tproviderMetadata,\n\t\t\t\tresponses\n\t\t\t});\n\t\t}\n\t});\n}\nvar DefaultEmbedManyResult = class {\n\tconstructor(options) {\n\t\tthis.values = options.values;\n\t\tthis.embeddings = options.embeddings;\n\t\tthis.usage = options.usage;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.responses = options.responses;\n\t}\n};\nasync function generateImage({ model: modelArg, prompt, n = 1, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tvar _a16;\n\tconst model = resolveImageModel(modelArg);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst maxImagesPerCallWithDefault = (_a16 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a16 : 1;\n\tconst callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n\tconst callImageCounts = Array.from({ length: callCount }, (_, i) => {\n\t\tif (i < callCount - 1) return maxImagesPerCallWithDefault;\n\t\tconst remainder = n % maxImagesPerCallWithDefault;\n\t\treturn remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n\t});\n\tconst results = await Promise.all(callImageCounts.map(async (callImageCount) => retry(() => model.doGenerate({\n\t\tprompt,\n\t\tn: callImageCount,\n\t\tabortSignal,\n\t\theaders: headersWithUserAgent,\n\t\tsize,\n\t\taspectRatio,\n\t\tseed,\n\t\tproviderOptions: providerOptions != null ? providerOptions : {}\n\t}))));\n\tconst images = [];\n\tconst warnings = [];\n\tconst responses = [];\n\tconst providerMetadata = {};\n\tfor (const result of results) {\n\t\timages.push(...result.images.map((image) => {\n\t\t\tvar _a17;\n\t\t\treturn new DefaultGeneratedFile({\n\t\t\t\tdata: image,\n\t\t\t\tmediaType: (_a17 = detectMediaType({\n\t\t\t\t\tdata: image,\n\t\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t\t})) != null ? _a17 : \"image/png\"\n\t\t\t});\n\t\t}));\n\t\twarnings.push(...result.warnings);\n\t\tif (result.providerMetadata) for (const [providerName, metadata] of Object.entries(result.providerMetadata)) if (providerName === \"gateway\") {\n\t\t\tconst currentEntry = providerMetadata[providerName];\n\t\t\tif (currentEntry != null && typeof currentEntry === \"object\") providerMetadata[providerName] = {\n\t\t\t\t...currentEntry,\n\t\t\t\t...metadata\n\t\t\t};\n\t\t\telse providerMetadata[providerName] = metadata;\n\t\t\tconst imagesValue = providerMetadata[providerName].images;\n\t\t\tif (Array.isArray(imagesValue) && imagesValue.length === 0) delete providerMetadata[providerName].images;\n\t\t} else {\n\t\t\tproviderMetadata[providerName] ?? (providerMetadata[providerName] = { images: [] });\n\t\t\tproviderMetadata[providerName].images.push(...result.providerMetadata[providerName].images);\n\t\t}\n\t\tresponses.push(result.response);\n\t}\n\tlogWarnings(warnings);\n\tif (!images.length) throw new NoImageGeneratedError({ responses });\n\treturn new DefaultGenerateImageResult({\n\t\timages,\n\t\twarnings,\n\t\tresponses,\n\t\tproviderMetadata\n\t});\n}\nvar DefaultGenerateImageResult = class {\n\tconstructor(options) {\n\t\tthis.images = options.images;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t}\n\tget image() {\n\t\treturn this.images[0];\n\t}\n};\nasync function invokeModelMaxImagesPerCall(model) {\n\tif (!(model.maxImagesPerCall instanceof Function)) return model.maxImagesPerCall;\n\treturn model.maxImagesPerCall({ modelId: model.modelId });\n}\nfunction extractReasoningContent(content) {\n\tconst parts = content.filter((content2) => content2.type === \"reasoning\");\n\treturn parts.length === 0 ? void 0 : parts.map((content2) => content2.text).join(\"\\n\");\n}\nvar noSchemaOutputStrategy = {\n\ttype: \"no-schema\",\n\tjsonSchema: void 0,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value, context) {\n\t\treturn value === void 0 ? {\n\t\t\tsuccess: false,\n\t\t\terror: new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\ttext: context.text,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t})\n\t\t} : {\n\t\t\tsuccess: true,\n\t\t\tvalue\n\t\t};\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in no-schema mode\" });\n\t}\n};\nvar objectOutputStrategy = (schema) => ({\n\ttype: \"object\",\n\tjsonSchema: schema.jsonSchema,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value) {\n\t\treturn safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in object mode\" });\n\t}\n});\nvar arrayOutputStrategy = (schema) => {\n\tconst { $schema, ...itemSchema } = schema.jsonSchema;\n\treturn {\n\t\ttype: \"array\",\n\t\tjsonSchema: {\n\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\ttype: \"object\",\n\t\t\tproperties: { elements: {\n\t\t\t\ttype: \"array\",\n\t\t\t\titems: itemSchema\n\t\t\t} },\n\t\t\trequired: [\"elements\"],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tasync validatePartialResult({ value, latestObject, isFirstDelta, isFinalDelta }) {\n\t\t\tvar _a16;\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (let i = 0; i < inputArray.length; i++) {\n\t\t\t\tconst element = inputArray[i];\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (i === inputArray.length - 1 && !isFinalDelta) continue;\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\tconst publishedElementCount = (_a16 = latestObject == null ? void 0 : latestObject.length) != null ? _a16 : 0;\n\t\t\tlet textDelta = \"\";\n\t\t\tif (isFirstDelta) textDelta += \"[\";\n\t\t\tif (publishedElementCount > 0) textDelta += \",\";\n\t\t\ttextDelta += resultArray.slice(publishedElementCount).map((element) => JSON.stringify(element)).join(\",\");\n\t\t\tif (isFinalDelta) textDelta += \"]\";\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: resultArray,\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (const element of inputArray) {\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: resultArray\n\t\t\t};\n\t\t},\n\t\tcreateElementStream(originalStream) {\n\t\t\tlet publishedElements = 0;\n\t\t\treturn createAsyncIterableStream(originalStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\tcase \"object\": {\n\t\t\t\t\t\tconst array = chunk.object;\n\t\t\t\t\t\tfor (; publishedElements < array.length; publishedElements++) controller.enqueue(array[publishedElements]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\tcase \"error\": break;\n\t\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t\t}\n\t\t\t} })));\n\t\t}\n\t};\n};\nvar enumOutputStrategy = (enumValues) => {\n\treturn {\n\t\ttype: \"enum\",\n\t\tjsonSchema: {\n\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\ttype: \"object\",\n\t\t\tproperties: { result: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tenum: enumValues\n\t\t\t} },\n\t\t\trequired: [\"result\"],\n\t\t\tadditionalProperties: false\n\t\t},\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\treturn enumValues.includes(result) ? {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: result\n\t\t\t} : {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t},\n\t\tasync validatePartialResult({ value, textDelta }) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\tconst possibleEnumValues = enumValues.filter((enumValue) => enumValue.startsWith(result));\n\t\t\tif (value.result.length === 0 || possibleEnumValues.length === 0) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tcreateElementStream() {\n\t\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in enum mode\" });\n\t\t}\n\t};\n};\nfunction getOutputStrategy({ output, schema, enumValues }) {\n\tswitch (output) {\n\t\tcase \"object\": return objectOutputStrategy(asSchema(schema));\n\t\tcase \"array\": return arrayOutputStrategy(asSchema(schema));\n\t\tcase \"enum\": return enumOutputStrategy(enumValues);\n\t\tcase \"no-schema\": return noSchemaOutputStrategy;\n\t\tdefault: throw new Error(`Unsupported output: ${output}`);\n\t}\n}\nasync function parseAndValidateObjectResult(result, outputStrategy, context) {\n\tconst parseResult = await safeParseJSON({ text: result });\n\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: could not parse the response.\",\n\t\tcause: parseResult.error,\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage,\n\t\tfinishReason: context.finishReason\n\t});\n\tconst validationResult = await outputStrategy.validateFinalResult(parseResult.value, {\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage\n\t});\n\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: response did not match schema.\",\n\t\tcause: validationResult.error,\n\t\ttext: result,\n\t\tresponse: context.response,\n\t\tusage: context.usage,\n\t\tfinishReason: context.finishReason\n\t});\n\treturn validationResult.value;\n}\nasync function parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, context) {\n\ttry {\n\t\treturn await parseAndValidateObjectResult(result, outputStrategy, context);\n\t} catch (error) {\n\t\tif (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError.isInstance(error.cause) || TypeValidationError.isInstance(error.cause))) {\n\t\t\tconst repairedText = await repairText({\n\t\t\t\ttext: result,\n\t\t\t\terror: error.cause\n\t\t\t});\n\t\t\tif (repairedText === null) throw error;\n\t\t\treturn await parseAndValidateObjectResult(repairedText, outputStrategy, context);\n\t\t}\n\t\tthrow error;\n\t}\n}\nfunction validateObjectGenerationInput({ output, schema, schemaName, schemaDescription, enumValues }) {\n\tif (output != null && output !== \"object\" && output !== \"array\" && output !== \"enum\" && output !== \"no-schema\") throw new InvalidArgumentError({\n\t\tparameter: \"output\",\n\t\tvalue: output,\n\t\tmessage: \"Invalid output type.\"\n\t});\n\tif (output === \"no-schema\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for no-schema output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for no-schema output.\"\n\t\t});\n\t}\n\tif (output === \"object\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is required for object output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for object output.\"\n\t\t});\n\t}\n\tif (output === \"array\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Element schema is required for array output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for array output.\"\n\t\t});\n\t}\n\tif (output === \"enum\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for enum output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for enum output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for enum output.\"\n\t\t});\n\t\tif (enumValues == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are required for enum output.\"\n\t\t});\n\t\tfor (const value of enumValues) if (typeof value !== \"string\") throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue,\n\t\t\tmessage: \"Enum values must be strings.\"\n\t\t});\n\t}\n}\nvar originalGenerateId3 = createIdGenerator({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\nasync function generateObject(options) {\n\tconst { model: modelArg, output = \"object\", system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, headers, experimental_repairText: repairText, experimental_telemetry: telemetry, experimental_download: download2, providerOptions, _internal: { generateId: generateId3 = originalGenerateId3, currentDate = () => /* @__PURE__ */ new Date() } = {}, ...settings } = options;\n\tconst model = resolveLanguageModel(modelArg);\n\tconst enumValues = \"enum\" in options ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst outputStrategy = getOutputStrategy({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tenumValues\n\t});\n\tconst callSettings = prepareCallSettings(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: {\n\t\t\t...callSettings,\n\t\t\tmaxRetries\n\t\t}\n\t});\n\tconst tracer = getTracer(telemetry);\n\ttry {\n\t\treturn await recordSpan({\n\t\t\tname: \"ai.generateObject\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.generateObject\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) },\n\t\t\t\t\t\"ai.schema\": outputStrategy.jsonSchema != null ? { input: () => JSON.stringify(outputStrategy.jsonSchema) } : void 0,\n\t\t\t\t\t\"ai.schema.name\": schemaName,\n\t\t\t\t\t\"ai.schema.description\": schemaDescription,\n\t\t\t\t\t\"ai.settings.output\": outputStrategy.type\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\tvar _a16;\n\t\t\t\tlet result;\n\t\t\t\tlet finishReason;\n\t\t\t\tlet usage;\n\t\t\t\tlet warnings;\n\t\t\t\tlet response;\n\t\t\t\tlet request;\n\t\t\t\tlet resultProviderMetadata;\n\t\t\t\tlet reasoning;\n\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\tprompt: await standardizePrompt({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tallowSystemInMessages\n\t\t\t\t\t}),\n\t\t\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\t\t\tdownload: download2\n\t\t\t\t});\n\t\t\t\tconst generateResult = await retry(() => recordSpan({\n\t\t\t\t\tname: \"ai.generateObject.doGenerate\",\n\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\toperationId: \"ai.generateObject.doGenerate\",\n\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\"gen_ai.system\": model.provider,\n\t\t\t\t\t\t\t\"gen_ai.request.model\": model.modelId,\n\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\ttracer,\n\t\t\t\t\tfn: async (span2) => {\n\t\t\t\t\t\tvar _a17, _b, _c, _d, _e, _f, _g, _h;\n\t\t\t\t\t\tconst result2 = await model.doGenerate({\n\t\t\t\t\t\t\tresponseFormat: {\n\t\t\t\t\t\t\t\ttype: \"json\",\n\t\t\t\t\t\t\t\tschema: outputStrategy.jsonSchema,\n\t\t\t\t\t\t\t\tname: schemaName,\n\t\t\t\t\t\t\t\tdescription: schemaDescription\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...prepareCallSettings(settings),\n\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst responseData = {\n\t\t\t\t\t\t\tid: (_b = (_a17 = result2.response) == null ? void 0 : _a17.id) != null ? _b : generateId3(),\n\t\t\t\t\t\t\ttimestamp: (_d = (_c = result2.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),\n\t\t\t\t\t\t\tmodelId: (_f = (_e = result2.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,\n\t\t\t\t\t\t\theaders: (_g = result2.response) == null ? void 0 : _g.headers,\n\t\t\t\t\t\t\tbody: (_h = result2.response) == null ? void 0 : _h.body\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst text2 = extractTextContent(result2.content);\n\t\t\t\t\t\tconst reasoning2 = extractReasoningContent(result2.content);\n\t\t\t\t\t\tif (text2 === void 0) throw new NoObjectGeneratedError({\n\t\t\t\t\t\t\tmessage: \"No object generated: the model did not return a response.\",\n\t\t\t\t\t\t\tresponse: responseData,\n\t\t\t\t\t\t\tusage: result2.usage,\n\t\t\t\t\t\t\tfinishReason: result2.finishReason\n\t\t\t\t\t\t});\n\t\t\t\t\t\tspan2.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\"ai.response.finishReason\": result2.finishReason,\n\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => text2 },\n\t\t\t\t\t\t\t\t\"ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\"ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\"ai.response.timestamp\": responseData.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(result2.providerMetadata),\n\t\t\t\t\t\t\t\t\"ai.usage.promptTokens\": result2.usage.inputTokens,\n\t\t\t\t\t\t\t\t\"ai.usage.completionTokens\": result2.usage.outputTokens,\n\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [result2.finishReason],\n\t\t\t\t\t\t\t\t\"gen_ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\"gen_ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": result2.usage.inputTokens,\n\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": result2.usage.outputTokens\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}));\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t...result2,\n\t\t\t\t\t\t\tobjectText: text2,\n\t\t\t\t\t\t\treasoning: reasoning2,\n\t\t\t\t\t\t\tresponseData\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tresult = generateResult.objectText;\n\t\t\t\tfinishReason = generateResult.finishReason;\n\t\t\t\tusage = generateResult.usage;\n\t\t\t\twarnings = generateResult.warnings;\n\t\t\t\tresultProviderMetadata = generateResult.providerMetadata;\n\t\t\t\trequest = (_a16 = generateResult.request) != null ? _a16 : {};\n\t\t\t\tresponse = generateResult.responseData;\n\t\t\t\treasoning = generateResult.reasoning;\n\t\t\t\tlogWarnings(warnings);\n\t\t\t\tconst object2 = await parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, {\n\t\t\t\t\tresponse,\n\t\t\t\t\tusage,\n\t\t\t\t\tfinishReason\n\t\t\t\t});\n\t\t\t\tspan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(resultProviderMetadata),\n\t\t\t\t\t\t\"ai.usage.promptTokens\": usage.inputTokens,\n\t\t\t\t\t\t\"ai.usage.completionTokens\": usage.outputTokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\treturn new DefaultGenerateObjectResult({\n\t\t\t\t\tobject: object2,\n\t\t\t\t\treasoning,\n\t\t\t\t\tfinishReason,\n\t\t\t\t\tusage,\n\t\t\t\t\twarnings,\n\t\t\t\t\trequest,\n\t\t\t\t\tresponse,\n\t\t\t\t\tproviderMetadata: resultProviderMetadata\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nvar DefaultGenerateObjectResult = class {\n\tconstructor(options) {\n\t\tthis.object = options.object;\n\t\tthis.finishReason = options.finishReason;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t\tthis.request = options.request;\n\t\tthis.reasoning = options.reasoning;\n\t}\n\ttoJsonResponse(init) {\n\t\tvar _a16;\n\t\treturn new Response(JSON.stringify(this.object), {\n\t\t\tstatus: (_a16 = init == null ? void 0 : init.status) != null ? _a16 : 200,\n\t\t\theaders: prepareHeaders(init == null ? void 0 : init.headers, { \"content-type\": \"application/json; charset=utf-8\" })\n\t\t});\n\t}\n};\nfunction cosineSimilarity(vector1, vector2) {\n\tif (vector1.length !== vector2.length) throw new InvalidArgumentError({\n\t\tparameter: \"vector1,vector2\",\n\t\tvalue: {\n\t\t\tvector1Length: vector1.length,\n\t\t\tvector2Length: vector2.length\n\t\t},\n\t\tmessage: `Vectors must have the same length`\n\t});\n\tconst n = vector1.length;\n\tif (n === 0) return 0;\n\tlet magnitudeSquared1 = 0;\n\tlet magnitudeSquared2 = 0;\n\tlet dotProduct = 0;\n\tfor (let i = 0; i < n; i++) {\n\t\tconst value1 = vector1[i];\n\t\tconst value2 = vector2[i];\n\t\tmagnitudeSquared1 += value1 * value1;\n\t\tmagnitudeSquared2 += value2 * value2;\n\t\tdotProduct += value1 * value2;\n\t}\n\treturn magnitudeSquared1 === 0 || magnitudeSquared2 === 0 ? 0 : dotProduct / (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\nfunction createDownload(options) {\n\treturn ({ url, abortSignal }) => download({\n\t\turl,\n\t\tmaxBytes: options == null ? void 0 : options.maxBytes,\n\t\tabortSignal\n\t});\n}\nfunction getTextFromDataUrl(dataUrl) {\n\tconst [header, base64Content] = dataUrl.split(\",\");\n\tif (header.split(\";\")[0].split(\":\")[1] == null || base64Content == null) throw new Error(\"Invalid data URL format\");\n\ttry {\n\t\treturn window.atob(base64Content);\n\t} catch (error) {\n\t\tthrow new Error(`Error decoding data URL`);\n\t}\n}\nfunction isDeepEqualData(obj1, obj2) {\n\tif (obj1 === obj2) return true;\n\tif (obj1 == null || obj2 == null) return false;\n\tif (typeof obj1 !== \"object\" && typeof obj2 !== \"object\") return obj1 === obj2;\n\tif (obj1.constructor !== obj2.constructor) return false;\n\tif (obj1 instanceof Date && obj2 instanceof Date) return obj1.getTime() === obj2.getTime();\n\tif (Array.isArray(obj1)) {\n\t\tif (obj1.length !== obj2.length) return false;\n\t\tfor (let i = 0; i < obj1.length; i++) if (!isDeepEqualData(obj1[i], obj2[i])) return false;\n\t\treturn true;\n\t}\n\tconst keys1 = Object.keys(obj1);\n\tconst keys2 = Object.keys(obj2);\n\tif (keys1.length !== keys2.length) return false;\n\tfor (const key of keys1) {\n\t\tif (!keys2.includes(key)) return false;\n\t\tif (!isDeepEqualData(obj1[key], obj2[key])) return false;\n\t}\n\treturn true;\n}\nvar SerialJobExecutor = class {\n\tconstructor() {\n\t\tthis.queue = [];\n\t\tthis.isProcessing = false;\n\t}\n\tasync processQueue() {\n\t\tif (this.isProcessing) return;\n\t\tthis.isProcessing = true;\n\t\twhile (this.queue.length > 0) {\n\t\t\tawait this.queue[0]();\n\t\t\tthis.queue.shift();\n\t\t}\n\t\tthis.isProcessing = false;\n\t}\n\tasync run(job) {\n\t\treturn new Promise((resolve2, reject) => {\n\t\t\tthis.queue.push(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait job();\n\t\t\t\t\tresolve2();\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.processQueue();\n\t\t});\n\t}\n};\nfunction simulateReadableStream({ chunks, initialDelayInMs = 0, chunkDelayInMs = 0, _internal }) {\n\tvar _a16;\n\tconst delay2 = (_a16 = _internal == null ? void 0 : _internal.delay) != null ? _a16 : delay;\n\tlet index = 0;\n\treturn new ReadableStream({ async pull(controller) {\n\t\tif (index < chunks.length) {\n\t\t\tawait delay2(index === 0 ? initialDelayInMs : chunkDelayInMs);\n\t\t\tcontroller.enqueue(chunks[index++]);\n\t\t} else controller.close();\n\t} });\n}\nvar originalGenerateId4 = createIdGenerator({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\nfunction streamObject(options) {\n\tconst { model, output = \"object\", system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, headers, experimental_repairText: repairText, experimental_telemetry: telemetry, experimental_download: download2, providerOptions, onError = ({ error }) => {\n\t\tconsole.error(error);\n\t}, onFinish, _internal: { generateId: generateId3 = originalGenerateId4, currentDate = () => /* @__PURE__ */ new Date(), now: now2 = now } = {}, ...settings } = options;\n\tconst enumValues = \"enum\" in options && options.enum ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\treturn new DefaultStreamObjectResult({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tabortSignal,\n\t\toutputStrategy: getOutputStrategy({\n\t\t\toutput,\n\t\t\tschema: inputSchema,\n\t\t\tenumValues\n\t\t}),\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tproviderOptions,\n\t\trepairText,\n\t\tonError,\n\t\tonFinish,\n\t\tdownload: download2,\n\t\tgenerateId: generateId3,\n\t\tcurrentDate,\n\t\tnow: now2\n\t});\n}\nvar DefaultStreamObjectResult = class {\n\tconstructor({ model: modelArg, headers, telemetry, settings, maxRetries: maxRetriesArg, abortSignal, outputStrategy, system, prompt, messages, allowSystemInMessages, schemaName, schemaDescription, providerOptions, repairText, onError, onFinish, download: download2, generateId: generateId3, currentDate, now: now2 }) {\n\t\tthis._object = new DelayedPromise();\n\t\tthis._usage = new DelayedPromise();\n\t\tthis._providerMetadata = new DelayedPromise();\n\t\tthis._warnings = new DelayedPromise();\n\t\tthis._request = new DelayedPromise();\n\t\tthis._response = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tconst model = resolveLanguageModel(modelArg);\n\t\tconst { maxRetries, retry } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst callSettings = prepareCallSettings(settings);\n\t\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\t\tmodel,\n\t\t\ttelemetry,\n\t\t\theaders,\n\t\t\tsettings: {\n\t\t\t\t...callSettings,\n\t\t\t\tmaxRetries\n\t\t\t}\n\t\t});\n\t\tconst tracer = getTracer(telemetry);\n\t\tconst self = this;\n\t\tconst stitchableStream = createStitchableStream();\n\t\tconst eventProcessor = new TransformStream({ transform(chunk, controller) {\n\t\t\tcontroller.enqueue(chunk);\n\t\t\tif (chunk.type === \"error\") onError({ error: wrapGatewayError(chunk.error) });\n\t\t} });\n\t\tthis.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n\t\trecordSpan({\n\t\t\tname: \"ai.streamObject\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.streamObject\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) },\n\t\t\t\t\t\"ai.schema\": outputStrategy.jsonSchema != null ? { input: () => JSON.stringify(outputStrategy.jsonSchema) } : void 0,\n\t\t\t\t\t\"ai.schema.name\": schemaName,\n\t\t\t\t\t\"ai.schema.description\": schemaDescription,\n\t\t\t\t\t\"ai.settings.output\": outputStrategy.type\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tendWhenDone: false,\n\t\t\tfn: async (rootSpan) => {\n\t\t\t\tconst standardizedPrompt = await standardizePrompt({\n\t\t\t\t\tsystem,\n\t\t\t\t\tprompt,\n\t\t\t\t\tmessages,\n\t\t\t\t\tallowSystemInMessages\n\t\t\t\t});\n\t\t\t\tconst callOptions = {\n\t\t\t\t\tresponseFormat: {\n\t\t\t\t\t\ttype: \"json\",\n\t\t\t\t\t\tschema: outputStrategy.jsonSchema,\n\t\t\t\t\t\tname: schemaName,\n\t\t\t\t\t\tdescription: schemaDescription\n\t\t\t\t\t},\n\t\t\t\t\t...prepareCallSettings(settings),\n\t\t\t\t\tprompt: await convertToLanguageModelPrompt({\n\t\t\t\t\t\tprompt: standardizedPrompt,\n\t\t\t\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\t\t\t\tdownload: download2\n\t\t\t\t\t}),\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\theaders,\n\t\t\t\t\tincludeRawChunks: false\n\t\t\t\t};\n\t\t\t\tconst transformer = { transform: (chunk, controller) => {\n\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\t\tcontroller.enqueue(chunk.delta);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\tcase \"stream-start\":\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} };\n\t\t\t\tconst { result: { stream, response, request }, doStreamSpan, startTimestampMs } = await retry(() => recordSpan({\n\t\t\t\t\tname: \"ai.streamObject.doStream\",\n\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\toperationId: \"ai.streamObject.doStream\",\n\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(callOptions.prompt) },\n\t\t\t\t\t\t\t\"gen_ai.system\": model.provider,\n\t\t\t\t\t\t\t\"gen_ai.request.model\": model.modelId,\n\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\ttracer,\n\t\t\t\t\tendWhenDone: false,\n\t\t\t\t\tfn: async (doStreamSpan2) => ({\n\t\t\t\t\t\tstartTimestampMs: now2(),\n\t\t\t\t\t\tdoStreamSpan: doStreamSpan2,\n\t\t\t\t\t\tresult: await model.doStream(callOptions)\n\t\t\t\t\t})\n\t\t\t\t}));\n\t\t\t\tself._request.resolve(request != null ? request : {});\n\t\t\t\tlet warnings;\n\t\t\t\tlet usage = {\n\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\ttotalTokens: void 0\n\t\t\t\t};\n\t\t\t\tlet finishReason;\n\t\t\t\tlet providerMetadata;\n\t\t\t\tlet object2;\n\t\t\t\tlet error;\n\t\t\t\tlet accumulatedText = \"\";\n\t\t\t\tlet textDelta = \"\";\n\t\t\t\tlet fullResponse = {\n\t\t\t\t\tid: generateId3(),\n\t\t\t\t\ttimestamp: currentDate(),\n\t\t\t\t\tmodelId: model.modelId\n\t\t\t\t};\n\t\t\t\tlet latestObjectJson = void 0;\n\t\t\t\tlet latestObject = void 0;\n\t\t\t\tlet isFirstChunk = true;\n\t\t\t\tlet isFirstDelta = true;\n\t\t\t\tconst transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(new TransformStream({\n\t\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\t\tvar _a16, _b, _c;\n\t\t\t\t\t\tif (typeof chunk === \"object\" && chunk.type === \"stream-start\") {\n\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isFirstChunk) {\n\t\t\t\t\t\t\tconst msToFirstChunk = now2() - startTimestampMs;\n\t\t\t\t\t\t\tisFirstChunk = false;\n\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.firstChunk\", { \"ai.stream.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\tdoStreamSpan.setAttributes({ \"ai.stream.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof chunk === \"string\") {\n\t\t\t\t\t\t\taccumulatedText += chunk;\n\t\t\t\t\t\t\ttextDelta += chunk;\n\t\t\t\t\t\t\tconst { value: currentObjectJson, state: parseState } = await parsePartialJson(accumulatedText);\n\t\t\t\t\t\t\tif (currentObjectJson !== void 0 && !isDeepEqualData(latestObjectJson, currentObjectJson)) {\n\t\t\t\t\t\t\t\tconst validationResult = await outputStrategy.validatePartialResult({\n\t\t\t\t\t\t\t\t\tvalue: currentObjectJson,\n\t\t\t\t\t\t\t\t\ttextDelta,\n\t\t\t\t\t\t\t\t\tlatestObject,\n\t\t\t\t\t\t\t\t\tisFirstDelta,\n\t\t\t\t\t\t\t\t\tisFinalDelta: parseState === \"successful-parse\"\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (validationResult.success && !isDeepEqualData(latestObject, validationResult.value.partial)) {\n\t\t\t\t\t\t\t\t\tlatestObjectJson = currentObjectJson;\n\t\t\t\t\t\t\t\t\tlatestObject = validationResult.value.partial;\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\tobject: latestObject\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\t\ttextDelta: validationResult.value.textDelta\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\ttextDelta = \"\";\n\t\t\t\t\t\t\t\t\tisFirstDelta = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\t\t\tfullResponse = {\n\t\t\t\t\t\t\t\t\tid: (_a16 = chunk.id) != null ? _a16 : fullResponse.id,\n\t\t\t\t\t\t\t\t\ttimestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,\n\t\t\t\t\t\t\t\t\tmodelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\t\t\tif (textDelta !== \"\") controller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\ttextDelta\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tfinishReason = chunk.finishReason;\n\t\t\t\t\t\t\t\tusage = chunk.usage;\n\t\t\t\t\t\t\t\tproviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\tresponse: fullResponse\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tlogWarnings(warnings != null ? warnings : []);\n\t\t\t\t\t\t\t\tself._usage.resolve(usage);\n\t\t\t\t\t\t\t\tself._providerMetadata.resolve(providerMetadata);\n\t\t\t\t\t\t\t\tself._warnings.resolve(warnings);\n\t\t\t\t\t\t\t\tself._response.resolve({\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself._finishReason.resolve(finishReason != null ? finishReason : \"unknown\");\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tobject2 = await parseAndValidateObjectResultWithRepair(accumulatedText, outputStrategy, repairText, {\n\t\t\t\t\t\t\t\t\t\tresponse: fullResponse,\n\t\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\t\tfinishReason\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tself._object.resolve(object2);\n\t\t\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\t\t\terror = e;\n\t\t\t\t\t\t\t\t\tself._object.reject(e);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tasync flush(controller) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst finalUsage = usage != null ? usage : {\n\t\t\t\t\t\t\t\tpromptTokens: NaN,\n\t\t\t\t\t\t\t\tcompletionTokens: NaN,\n\t\t\t\t\t\t\t\ttotalTokens: NaN\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tdoStreamSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\t\t\t\"ai.response.id\": fullResponse.id,\n\t\t\t\t\t\t\t\t\t\"ai.response.model\": fullResponse.modelId,\n\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": fullResponse.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(providerMetadata),\n\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": finalUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": finalUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [finishReason],\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": fullResponse.id,\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": fullResponse.modelId,\n\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": finalUsage.outputTokens\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tdoStreamSpan.end();\n\t\t\t\t\t\t\trootSpan.setAttributes(selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": finalUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": finalUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(providerMetadata)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tawait (onFinish == null ? void 0 : onFinish({\n\t\t\t\t\t\t\t\tusage: finalUsage,\n\t\t\t\t\t\t\t\tobject: object2,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\t\tproviderMetadata\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t} catch (error2) {\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: error2\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trootSpan.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tstitchableStream.addStream(transformedStream);\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tstitchableStream.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t}).finally(() => {\n\t\t\tstitchableStream.close();\n\t\t});\n\t\tthis.outputStrategy = outputStrategy;\n\t}\n\tget object() {\n\t\treturn this._object.promise;\n\t}\n\tget usage() {\n\t\treturn this._usage.promise;\n\t}\n\tget providerMetadata() {\n\t\treturn this._providerMetadata.promise;\n\t}\n\tget warnings() {\n\t\treturn this._warnings.promise;\n\t}\n\tget request() {\n\t\treturn this._request.promise;\n\t}\n\tget response() {\n\t\treturn this._response.promise;\n\t}\n\tget finishReason() {\n\t\treturn this._finishReason.promise;\n\t}\n\tget partialObjectStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"object\":\n\t\t\t\t\tcontroller.enqueue(chunk.object);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"text-delta\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget elementStream() {\n\t\treturn this.outputStrategy.createElementStream(this.baseStream);\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcontroller.enqueue(chunk.textDelta);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"object\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn createAsyncIterableStream(this.baseStream);\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\treturn pipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\nvar DefaultGeneratedAudioFile = class extends DefaultGeneratedFile {\n\tconstructor({ data, mediaType }) {\n\t\tsuper({\n\t\t\tdata,\n\t\t\tmediaType\n\t\t});\n\t\tlet format = \"mp3\";\n\t\tif (mediaType) {\n\t\t\tconst mediaTypeParts = mediaType.split(\"/\");\n\t\t\tif (mediaTypeParts.length === 2) {\n\t\t\t\tif (mediaType !== \"audio/mpeg\") format = mediaTypeParts[1];\n\t\t\t}\n\t\t}\n\t\tif (!format) throw new Error(\"Audio format must be provided or determinable from media type\");\n\t\tthis.format = format;\n\t}\n};\nasync function generateSpeech({ model, text: text2, voice, outputFormat, instructions, speed, language, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tvar _a16;\n\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\tversion: model.specificationVersion,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst result = await retry(() => model.doGenerate({\n\t\ttext: text2,\n\t\tvoice,\n\t\toutputFormat,\n\t\tinstructions,\n\t\tspeed,\n\t\tlanguage,\n\t\tabortSignal,\n\t\theaders: headersWithUserAgent,\n\t\tproviderOptions\n\t}));\n\tif (!result.audio || result.audio.length === 0) throw new NoSpeechGeneratedError({ responses: [result.response] });\n\tlogWarnings(result.warnings);\n\treturn new DefaultSpeechResult({\n\t\taudio: new DefaultGeneratedAudioFile({\n\t\t\tdata: result.audio,\n\t\t\tmediaType: (_a16 = detectMediaType({\n\t\t\t\tdata: result.audio,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a16 : \"audio/mp3\"\n\t\t}),\n\t\twarnings: result.warnings,\n\t\tresponses: [result.response],\n\t\tproviderMetadata: result.providerMetadata\n\t});\n}\nvar DefaultSpeechResult = class {\n\tconstructor(options) {\n\t\tvar _a16;\n\t\tthis.audio = options.audio;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = (_a16 = options.providerMetadata) != null ? _a16 : {};\n\t}\n};\nvar output_exports = {};\n__export(output_exports, {\n\tobject: () => object,\n\ttext: () => text\n});\nvar text = () => ({\n\ttype: \"text\",\n\tresponseFormat: { type: \"text\" },\n\tasync parsePartial({ text: text2 }) {\n\t\treturn { partial: text2 };\n\t},\n\tasync parseOutput({ text: text2 }) {\n\t\treturn text2;\n\t}\n});\nvar object = ({ schema: inputSchema }) => {\n\tconst schema = asSchema(inputSchema);\n\treturn {\n\t\ttype: \"object\",\n\t\tresponseFormat: {\n\t\t\ttype: \"json\",\n\t\t\tschema: schema.jsonSchema\n\t\t},\n\t\tasync parsePartial({ text: text2 }) {\n\t\t\tconst result = await parsePartialJson(text2);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": return { partial: result.value };\n\t\t\t\tdefault: {\n\t\t\t\t\tconst _exhaustiveCheck = result.state;\n\t\t\t\t\tthrow new Error(`Unsupported parse state: ${_exhaustiveCheck}`);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tasync parseOutput({ text: text2 }, context) {\n\t\t\tconst parseResult = await safeParseJSON({ text: text2 });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\tvalue: parseResult.value,\n\t\t\t\tschema\n\t\t\t});\n\t\t\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: validationResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context.response,\n\t\t\t\tusage: context.usage,\n\t\t\t\tfinishReason: context.finishReason\n\t\t\t});\n\t\t\treturn validationResult.value;\n\t\t}\n\t};\n};\nfunction pruneMessages({ messages, reasoning = \"none\", toolCalls = [], emptyMessages = \"remove\" }) {\n\tif (reasoning === \"all\" || reasoning === \"before-last-message\") messages = messages.map((message, messageIndex) => {\n\t\tif (message.role !== \"assistant\" || typeof message.content === \"string\" || reasoning === \"before-last-message\" && messageIndex === messages.length - 1) return message;\n\t\treturn {\n\t\t\t...message,\n\t\t\tcontent: message.content.filter((part) => part.type !== \"reasoning\")\n\t\t};\n\t});\n\tif (toolCalls === \"none\") toolCalls = [];\n\telse if (toolCalls === \"all\") toolCalls = [{ type: \"all\" }];\n\telse if (toolCalls === \"before-last-message\") toolCalls = [{ type: \"before-last-message\" }];\n\telse if (typeof toolCalls === \"string\") toolCalls = [{ type: toolCalls }];\n\tfor (const toolCall of toolCalls) {\n\t\tconst keepLastMessagesCount = toolCall.type === \"all\" ? void 0 : toolCall.type === \"before-last-message\" ? 1 : Number(toolCall.type.slice(12).slice(0, -9));\n\t\tconst keptToolCallIds = /* @__PURE__ */ new Set();\n\t\tif (keepLastMessagesCount != null) {\n\t\t\tfor (const message of messages.slice(-keepLastMessagesCount)) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\t\tfor (const part of message.content) if (part.type === \"tool-call\" || part.type === \"tool-result\") keptToolCallIds.add(part.toolCallId);\n\t\t\t}\n\t\t}\n\t\tmessages = messages.map((message, messageIndex) => {\n\t\t\tif (message.role !== \"assistant\" && message.role !== \"tool\" || typeof message.content === \"string\" || keepLastMessagesCount && messageIndex >= messages.length - keepLastMessagesCount) return message;\n\t\t\tconst toolCallIdToToolName = {};\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tcontent: message.content.filter((part) => {\n\t\t\t\t\tif (part.type !== \"tool-call\" && part.type !== \"tool-result\") return true;\n\t\t\t\t\tif (part.type === \"tool-call\") toolCallIdToToolName[part.toolCallId] = part.toolName;\n\t\t\t\t\tif ((part.type === \"tool-call\" || part.type === \"tool-result\") && keptToolCallIds.has(part.toolCallId)) return true;\n\t\t\t\t\treturn toolCall.tools != null && !toolCall.tools.includes(part.toolName);\n\t\t\t\t})\n\t\t\t};\n\t\t});\n\t}\n\tif (emptyMessages === \"remove\") messages = messages.filter((message) => message.content.length > 0);\n\treturn messages;\n}\nvar CHUNKING_REGEXPS = {\n\tword: /\\S+\\s+/m,\n\tline: /\\n+/m\n};\nfunction smoothStream({ delayInMs = 10, chunking = \"word\", _internal: { delay: delay2 = delay } = {} } = {}) {\n\tlet detectChunk;\n\tif (typeof chunking === \"function\") detectChunk = (buffer) => {\n\t\tconst match = chunking(buffer);\n\t\tif (match == null) return null;\n\t\tif (!match.length) throw new Error(`Chunking function must return a non-empty string.`);\n\t\tif (!buffer.startsWith(match)) throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`);\n\t\treturn match;\n\t};\n\telse {\n\t\tconst chunkingRegex = typeof chunking === \"string\" ? CHUNKING_REGEXPS[chunking] : chunking;\n\t\tif (chunkingRegex == null) throw new InvalidArgumentError$1({\n\t\t\targument: \"chunking\",\n\t\t\tmessage: `Chunking must be \"word\" or \"line\" or a RegExp. Received: ${chunking}`\n\t\t});\n\t\tdetectChunk = (buffer) => {\n\t\t\tconst match = chunkingRegex.exec(buffer);\n\t\t\tif (!match) return null;\n\t\t\treturn buffer.slice(0, match.index) + (match == null ? void 0 : match[0]);\n\t\t};\n\t}\n\treturn () => {\n\t\tlet buffer = \"\";\n\t\tlet id = \"\";\n\t\treturn new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (chunk.type !== \"text-delta\") {\n\t\t\t\tif (buffer.length > 0) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\ttext: buffer,\n\t\t\t\t\t\tid\n\t\t\t\t\t});\n\t\t\t\t\tbuffer = \"\";\n\t\t\t\t}\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (chunk.id !== id && buffer.length > 0) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\ttext: buffer,\n\t\t\t\t\tid\n\t\t\t\t});\n\t\t\t\tbuffer = \"\";\n\t\t\t}\n\t\t\tbuffer += chunk.text;\n\t\t\tid = chunk.id;\n\t\t\tlet match;\n\t\t\twhile ((match = detectChunk(buffer)) != null) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\ttext: match,\n\t\t\t\t\tid\n\t\t\t\t});\n\t\t\t\tbuffer = buffer.slice(match.length);\n\t\t\t\tawait delay2(delayInMs);\n\t\t\t}\n\t\t} });\n\t};\n}\nfunction defaultSettingsMiddleware({ settings }) {\n\treturn {\n\t\tmiddlewareVersion: \"v2\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\treturn mergeObjects(settings, params);\n\t\t}\n\t};\n}\nfunction getPotentialStartIndex(text2, searchedText) {\n\tif (searchedText.length === 0) return null;\n\tconst directIndex = text2.indexOf(searchedText);\n\tif (directIndex !== -1) return directIndex;\n\tfor (let i = text2.length - 1; i >= 0; i--) {\n\t\tconst suffix = text2.substring(i);\n\t\tif (searchedText.startsWith(suffix)) return i;\n\t}\n\treturn null;\n}\nfunction extractReasoningMiddleware({ tagName, separator = \"\\n\", startWithReasoning = false }) {\n\tconst openingTag = `<${tagName}>`;\n\tconst closingTag = `</${tagName}>`;\n\treturn {\n\t\tmiddlewareVersion: \"v2\",\n\t\twrapGenerate: async ({ doGenerate }) => {\n\t\t\tconst { content, ...rest } = await doGenerate();\n\t\t\tconst transformedContent = [];\n\t\t\tfor (const part of content) {\n\t\t\t\tif (part.type !== \"text\") {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst text2 = startWithReasoning ? openingTag + part.text : part.text;\n\t\t\t\tconst regexp = new RegExp(`${openingTag}(.*?)${closingTag}`, \"gs\");\n\t\t\t\tconst matches = Array.from(text2.matchAll(regexp));\n\t\t\t\tif (!matches.length) {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst reasoningText = matches.map((match) => match[1]).join(separator);\n\t\t\t\tlet textWithoutReasoning = text2;\n\t\t\t\tfor (let i = matches.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst match = matches[i];\n\t\t\t\t\tconst beforeMatch = textWithoutReasoning.slice(0, match.index);\n\t\t\t\t\tconst afterMatch = textWithoutReasoning.slice(match.index + match[0].length);\n\t\t\t\t\ttextWithoutReasoning = beforeMatch + (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : \"\") + afterMatch;\n\t\t\t\t}\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: reasoningText\n\t\t\t\t});\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: textWithoutReasoning\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: transformedContent,\n\t\t\t\t...rest\n\t\t\t};\n\t\t},\n\t\twrapStream: async ({ doStream }) => {\n\t\t\tconst { stream, ...rest } = await doStream();\n\t\t\tconst reasoningExtractions = createIdMap();\n\t\t\tlet delayedTextStart;\n\t\t\treturn {\n\t\t\t\tstream: stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {\n\t\t\t\t\tif (chunk.type === \"text-start\") {\n\t\t\t\t\t\tdelayedTextStart = chunk;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-end\" && delayedTextStart) {\n\t\t\t\t\t\tcontroller.enqueue(delayedTextStart);\n\t\t\t\t\t\tdelayedTextStart = void 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type !== \"text-delta\") {\n\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (reasoningExtractions[chunk.id] == null) reasoningExtractions[chunk.id] = {\n\t\t\t\t\t\tisFirstReasoning: true,\n\t\t\t\t\t\tisFirstText: true,\n\t\t\t\t\t\tafterSwitch: false,\n\t\t\t\t\t\tisReasoning: startWithReasoning,\n\t\t\t\t\t\tbuffer: \"\",\n\t\t\t\t\t\tidCounter: 0,\n\t\t\t\t\t\ttextId: chunk.id\n\t\t\t\t\t};\n\t\t\t\t\tconst activeExtraction = reasoningExtractions[chunk.id];\n\t\t\t\t\tactiveExtraction.buffer += chunk.delta;\n\t\t\t\t\tfunction publish(text2) {\n\t\t\t\t\t\tif (text2.length > 0) {\n\t\t\t\t\t\t\tconst prefix = activeExtraction.afterSwitch && (activeExtraction.isReasoning ? !activeExtraction.isFirstReasoning : !activeExtraction.isFirstText) ? separator : \"\";\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning && (activeExtraction.afterSwitch || activeExtraction.isFirstReasoning)) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tdelta: prefix + text2,\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (delayedTextStart) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(delayedTextStart);\n\t\t\t\t\t\t\t\t\tdelayedTextStart = void 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tdelta: prefix + text2,\n\t\t\t\t\t\t\t\t\tid: activeExtraction.textId\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = false;\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) activeExtraction.isFirstReasoning = false;\n\t\t\t\t\t\t\telse activeExtraction.isFirstText = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdo {\n\t\t\t\t\t\tconst nextTag = activeExtraction.isReasoning ? closingTag : openingTag;\n\t\t\t\t\t\tconst startIndex = getPotentialStartIndex(activeExtraction.buffer, nextTag);\n\t\t\t\t\t\tif (startIndex == null) {\n\t\t\t\t\t\t\tpublish(activeExtraction.buffer);\n\t\t\t\t\t\t\tactiveExtraction.buffer = \"\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublish(activeExtraction.buffer.slice(0, startIndex));\n\t\t\t\t\t\tif (startIndex + nextTag.length <= activeExtraction.buffer.length) {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex + nextTag.length);\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter++}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tactiveExtraction.isReasoning = !activeExtraction.isReasoning;\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (true);\n\t\t\t\t} })),\n\t\t\t\t...rest\n\t\t\t};\n\t\t}\n\t};\n}\nfunction simulateStreamingMiddleware() {\n\treturn {\n\t\tmiddlewareVersion: \"v2\",\n\t\twrapStream: async ({ doGenerate }) => {\n\t\t\tconst result = await doGenerate();\n\t\t\tlet id = 0;\n\t\t\treturn {\n\t\t\t\tstream: new ReadableStream({ start(controller) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"stream-start\",\n\t\t\t\t\t\twarnings: result.warnings\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"response-metadata\",\n\t\t\t\t\t\t...result.response\n\t\t\t\t\t});\n\t\t\t\t\tfor (const part of result.content) switch (part.type) {\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\tif (part.text.length > 0) {\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"reasoning\":\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tcontroller.enqueue(part);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: result.finishReason,\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\tproviderMetadata: result.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} }),\n\t\t\t\trequest: result.request,\n\t\t\t\tresponse: result.response\n\t\t\t};\n\t\t}\n\t};\n}\nvar wrapLanguageModel = ({ model, middleware: middlewareArg, modelId, providerId }) => {\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nvar doWrap = ({ model, middleware: { transformParams, wrapGenerate, wrapStream, overrideProvider, overrideModelId, overrideSupportedUrls }, modelId, providerId }) => {\n\tvar _a16, _b, _c;\n\tasync function doTransform({ params, type }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\ttype,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\treturn {\n\t\tspecificationVersion: \"v2\",\n\t\tprovider: (_a16 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a16 : model.provider,\n\t\tmodelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n\t\tsupportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,\n\t\tasync doGenerate(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"generate\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => model.doStream(transformedParams);\n\t\t\treturn wrapGenerate ? wrapGenerate({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doGenerate();\n\t\t},\n\t\tasync doStream(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"stream\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => model.doStream(transformedParams);\n\t\t\treturn wrapStream ? wrapStream({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doStream();\n\t\t}\n\t};\n};\nfunction wrapProvider({ provider, languageModelMiddleware }) {\n\treturn {\n\t\tlanguageModel(modelId) {\n\t\t\tlet model = provider.languageModel(modelId);\n\t\t\tmodel = wrapLanguageModel({\n\t\t\t\tmodel,\n\t\t\t\tmiddleware: languageModelMiddleware\n\t\t\t});\n\t\t\treturn model;\n\t\t},\n\t\ttextEmbeddingModel: provider.textEmbeddingModel,\n\t\timageModel: provider.imageModel,\n\t\ttranscriptionModel: provider.transcriptionModel,\n\t\tspeechModel: provider.speechModel\n\t};\n}\nfunction customProvider({ languageModels, textEmbeddingModels, imageModels, transcriptionModels, speechModels, fallbackProvider }) {\n\treturn {\n\t\tlanguageModel(modelId) {\n\t\t\tif (languageModels != null && modelId in languageModels) return languageModels[modelId];\n\t\t\tif (fallbackProvider) return fallbackProvider.languageModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"languageModel\"\n\t\t\t});\n\t\t},\n\t\ttextEmbeddingModel(modelId) {\n\t\t\tif (textEmbeddingModels != null && modelId in textEmbeddingModels) return textEmbeddingModels[modelId];\n\t\t\tif (fallbackProvider) return fallbackProvider.textEmbeddingModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"textEmbeddingModel\"\n\t\t\t});\n\t\t},\n\t\timageModel(modelId) {\n\t\t\tif (imageModels != null && modelId in imageModels) return imageModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.imageModel) return fallbackProvider.imageModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"imageModel\"\n\t\t\t});\n\t\t},\n\t\ttranscriptionModel(modelId) {\n\t\t\tif (transcriptionModels != null && modelId in transcriptionModels) return transcriptionModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.transcriptionModel) return fallbackProvider.transcriptionModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"transcriptionModel\"\n\t\t\t});\n\t\t},\n\t\tspeechModel(modelId) {\n\t\t\tif (speechModels != null && modelId in speechModels) return speechModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.speechModel) return fallbackProvider.speechModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"speechModel\"\n\t\t\t});\n\t\t}\n\t};\n}\nvar experimental_customProvider = customProvider;\nvar name15 = \"AI_NoSuchProviderError\";\nvar marker15 = `vercel.ai.error.${name15}`;\nvar symbol15 = Symbol.for(marker15);\nvar _a15;\nvar NoSuchProviderError = class extends NoSuchModelError {\n\tconstructor({ modelId, modelType, providerId, availableProviders, message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})` }) {\n\t\tsuper({\n\t\t\terrorName: name15,\n\t\t\tmodelId,\n\t\t\tmodelType,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a15] = true;\n\t\tthis.providerId = providerId;\n\t\tthis.availableProviders = availableProviders;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker15);\n\t}\n};\n_a15 = symbol15;\nfunction createProviderRegistry(providers, { separator = \":\", languageModelMiddleware } = {}) {\n\tconst registry = new DefaultProviderRegistry({\n\t\tseparator,\n\t\tlanguageModelMiddleware\n\t});\n\tfor (const [id, provider] of Object.entries(providers)) registry.registerProvider({\n\t\tid,\n\t\tprovider\n\t});\n\treturn registry;\n}\nvar experimental_createProviderRegistry = createProviderRegistry;\nvar DefaultProviderRegistry = class {\n\tconstructor({ separator, languageModelMiddleware }) {\n\t\tthis.providers = {};\n\t\tthis.separator = separator;\n\t\tthis.languageModelMiddleware = languageModelMiddleware;\n\t}\n\tregisterProvider({ id, provider }) {\n\t\tthis.providers[id] = provider;\n\t}\n\tgetProvider(id, modelType) {\n\t\tconst provider = this.providers[id];\n\t\tif (provider == null) throw new NoSuchProviderError({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tproviderId: id,\n\t\t\tavailableProviders: Object.keys(this.providers)\n\t\t});\n\t\treturn provider;\n\t}\n\tsplitId(id, modelType) {\n\t\tconst index = id.indexOf(this.separator);\n\t\tif (index === -1) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tmessage: `Invalid ${modelType} id for registry: ${id} (must be in the format \"providerId${this.separator}modelId\")`\n\t\t});\n\t\treturn [id.slice(0, index), id.slice(index + this.separator.length)];\n\t}\n\tlanguageModel(id) {\n\t\tvar _a16, _b;\n\t\tconst [providerId, modelId] = this.splitId(id, \"languageModel\");\n\t\tlet model = (_b = (_a16 = this.getProvider(providerId, \"languageModel\")).languageModel) == null ? void 0 : _b.call(_a16, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"languageModel\"\n\t\t});\n\t\tif (this.languageModelMiddleware != null) model = wrapLanguageModel({\n\t\t\tmodel,\n\t\t\tmiddleware: this.languageModelMiddleware\n\t\t});\n\t\treturn model;\n\t}\n\ttextEmbeddingModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"textEmbeddingModel\");\n\t\tconst provider = this.getProvider(providerId, \"textEmbeddingModel\");\n\t\tconst model = (_a16 = provider.textEmbeddingModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"textEmbeddingModel\"\n\t\t});\n\t\treturn model;\n\t}\n\timageModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"imageModel\");\n\t\tconst provider = this.getProvider(providerId, \"imageModel\");\n\t\tconst model = (_a16 = provider.imageModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"imageModel\"\n\t\t});\n\t\treturn model;\n\t}\n\ttranscriptionModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"transcriptionModel\");\n\t\tconst provider = this.getProvider(providerId, \"transcriptionModel\");\n\t\tconst model = (_a16 = provider.transcriptionModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"transcriptionModel\"\n\t\t});\n\t\treturn model;\n\t}\n\tspeechModel(id) {\n\t\tvar _a16;\n\t\tconst [providerId, modelId] = this.splitId(id, \"speechModel\");\n\t\tconst provider = this.getProvider(providerId, \"speechModel\");\n\t\tconst model = (_a16 = provider.speechModel) == null ? void 0 : _a16.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"speechModel\"\n\t\t});\n\t\treturn model;\n\t}\n};\nvar NoTranscriptGeneratedError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_NoTranscriptGeneratedError\",\n\t\t\tmessage: \"No transcript generated.\"\n\t\t});\n\t\tthis.responses = options.responses;\n\t}\n};\nvar defaultDownload = createDownload();\nasync function transcribe({ model, audio, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn = defaultDownload }) {\n\tif (model.specificationVersion !== \"v2\") throw new UnsupportedModelVersionError({\n\t\tversion: model.specificationVersion,\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst audioData = audio instanceof URL ? (await downloadFn({\n\t\turl: audio,\n\t\tabortSignal\n\t})).data : convertDataContentToUint8Array(audio);\n\tconst result = await retry(() => {\n\t\tvar _a16;\n\t\treturn model.doGenerate({\n\t\t\taudio: audioData,\n\t\t\tabortSignal,\n\t\t\theaders: headersWithUserAgent,\n\t\t\tproviderOptions,\n\t\t\tmediaType: (_a16 = detectMediaType({\n\t\t\t\tdata: audioData,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a16 : \"audio/wav\"\n\t\t});\n\t});\n\tlogWarnings(result.warnings);\n\tif (!result.text) throw new NoTranscriptGeneratedError({ responses: [result.response] });\n\treturn new DefaultTranscriptionResult({\n\t\ttext: result.text,\n\t\tsegments: result.segments,\n\t\tlanguage: result.language,\n\t\tdurationInSeconds: result.durationInSeconds,\n\t\twarnings: result.warnings,\n\t\tresponses: [result.response],\n\t\tproviderMetadata: result.providerMetadata\n\t});\n}\nvar DefaultTranscriptionResult = class {\n\tconstructor(options) {\n\t\tvar _a16;\n\t\tthis.text = options.text;\n\t\tthis.segments = options.segments;\n\t\tthis.language = options.language;\n\t\tthis.durationInSeconds = options.durationInSeconds;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = (_a16 = options.providerMetadata) != null ? _a16 : {};\n\t}\n};\nasync function processTextStream({ stream, onTextPart }) {\n\tconst reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\tawait onTextPart(value);\n\t}\n}\nvar getOriginalFetch = () => fetch;\nasync function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol = \"data\", setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch: fetch2 = getOriginalFetch() }) {\n\tvar _a16;\n\ttry {\n\t\tsetLoading(true);\n\t\tsetError(void 0);\n\t\tconst abortController = new AbortController();\n\t\tsetAbortController(abortController);\n\t\tsetCompletion(\"\");\n\t\tconst response = await fetch2(api, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tprompt,\n\t\t\t\t...body\n\t\t\t}),\n\t\t\tcredentials,\n\t\t\theaders: withUserAgentSuffix({\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tsignal: abortController.signal\n\t\t}).catch((err) => {\n\t\t\tthrow err;\n\t\t});\n\t\tif (!response.ok) throw new Error((_a16 = await response.text()) != null ? _a16 : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\tlet result = \"\";\n\t\tswitch (streamProtocol) {\n\t\t\tcase \"text\":\n\t\t\t\tawait processTextStream({\n\t\t\t\t\tstream: response.body,\n\t\t\t\t\tonTextPart: (chunk) => {\n\t\t\t\t\t\tresult += chunk;\n\t\t\t\t\t\tsetCompletion(result);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"data\":\n\t\t\t\tawait consumeStream({\n\t\t\t\t\tstream: parseJsonEventStream({\n\t\t\t\t\t\tstream: response.body,\n\t\t\t\t\t\tschema: uiMessageChunkSchema\n\t\t\t\t\t}).pipeThrough(new TransformStream({ async transform(part) {\n\t\t\t\t\t\tif (!part.success) throw part.error;\n\t\t\t\t\t\tconst streamPart = part.value;\n\t\t\t\t\t\tif (streamPart.type === \"text-delta\") {\n\t\t\t\t\t\t\tresult += streamPart.delta;\n\t\t\t\t\t\t\tsetCompletion(result);\n\t\t\t\t\t\t} else if (streamPart.type === \"error\") throw new Error(streamPart.errorText);\n\t\t\t\t\t} })),\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unknown stream protocol: ${streamProtocol}`);\n\t\t}\n\t\tif (onFinish) onFinish(prompt, result);\n\t\tsetAbortController(null);\n\t\treturn result;\n\t} catch (err) {\n\t\tif (err.name === \"AbortError\") {\n\t\t\tsetAbortController(null);\n\t\t\treturn null;\n\t\t}\n\t\tif (err instanceof Error) {\n\t\t\tif (onError) onError(err);\n\t\t}\n\t\tsetError(err);\n\t} finally {\n\t\tsetLoading(false);\n\t}\n}\nasync function convertFileListToFileUIParts(files) {\n\tif (files == null) return [];\n\tif (!globalThis.FileList || !(files instanceof globalThis.FileList)) throw new Error(\"FileList is not supported in the current environment\");\n\treturn Promise.all(Array.from(files).map(async (file) => {\n\t\tconst { name: name16, type } = file;\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: type,\n\t\t\tfilename: name16,\n\t\t\turl: await new Promise((resolve2, reject) => {\n\t\t\t\tconst reader = new FileReader();\n\t\t\t\treader.onload = (readerEvent) => {\n\t\t\t\t\tvar _a16;\n\t\t\t\t\tresolve2((_a16 = readerEvent.target) == null ? void 0 : _a16.result);\n\t\t\t\t};\n\t\t\t\treader.onerror = (error) => reject(error);\n\t\t\t\treader.readAsDataURL(file);\n\t\t\t})\n\t\t};\n\t}));\n}\nvar HttpChatTransport = class {\n\tconstructor({ api = \"/api/chat\", credentials, headers, body, fetch: fetch2, prepareSendMessagesRequest, prepareReconnectToStreamRequest }) {\n\t\tthis.api = api;\n\t\tthis.credentials = credentials;\n\t\tthis.headers = headers;\n\t\tthis.body = body;\n\t\tthis.fetch = fetch2;\n\t\tthis.prepareSendMessagesRequest = prepareSendMessagesRequest;\n\t\tthis.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n\t}\n\tasync sendMessages({ abortSignal, ...options }) {\n\t\tvar _a16, _b, _c, _d, _e;\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await ((_a16 = this.prepareSendMessagesRequest) == null ? void 0 : _a16.call(this, {\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t}));\n\t\tconst api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : this.api;\n\t\tconst headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst body = (preparedRequest == null ? void 0 : preparedRequest.body) !== void 0 ? preparedRequest.body : {\n\t\t\t...resolvedBody,\n\t\t\t...options.body,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t};\n\t\tconst credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n\t\tconst response = await ((_d = this.fetch) != null ? _d : globalThis.fetch)(api, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t\tcredentials,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tif (!response.ok) throw new Error((_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\treturn this.processResponseStream(response.body);\n\t}\n\tasync reconnectToStream(options) {\n\t\tvar _a16, _b, _c, _d, _e;\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await ((_a16 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a16.call(this, {\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata\n\t\t}));\n\t\tconst api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : `${this.api}/${options.chatId}/stream`;\n\t\tconst headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n\t\tconst response = await ((_d = this.fetch) != null ? _d : globalThis.fetch)(api, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t\tcredentials\n\t\t});\n\t\tif (response.status === 204) return null;\n\t\tif (!response.ok) throw new Error((_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\treturn this.processResponseStream(response.body);\n\t}\n};\nvar DefaultChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn parseJsonEventStream({\n\t\t\tstream,\n\t\t\tschema: uiMessageChunkSchema\n\t\t}).pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (!chunk.success) throw chunk.error;\n\t\t\tcontroller.enqueue(chunk.value);\n\t\t} }));\n\t}\n};\nvar AbstractChat = class {\n\tconstructor({ generateId: generateId3 = generateId, id = generateId3(), transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {\n\t\tthis.activeResponse = void 0;\n\t\tthis.jobExecutor = new SerialJobExecutor();\n\t\t/**\n\t\t* Appends or replaces a user message to the chat list. This triggers the API call to fetch\n\t\t* the assistant's response.\n\t\t*\n\t\t* If a messageId is provided, the message will be replaced.\n\t\t*/\n\t\tthis.sendMessage = async (message, options) => {\n\t\t\tvar _a16, _b, _c, _d;\n\t\t\tif (message == null) {\n\t\t\t\tawait this.makeRequest({\n\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\tmessageId: (_a16 = this.lastMessage) == null ? void 0 : _a16.id,\n\t\t\t\t\t...options\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet uiMessage;\n\t\t\tif (\"text\" in message || \"files\" in message) uiMessage = { parts: [...Array.isArray(message.files) ? message.files : await convertFileListToFileUIParts(message.files), ...\"text\" in message && message.text != null ? [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: message.text\n\t\t\t}] : []] };\n\t\t\telse uiMessage = message;\n\t\t\tif (message.messageId != null) {\n\t\t\t\tconst messageIndex = this.state.messages.findIndex((m) => m.id === message.messageId);\n\t\t\t\tif (messageIndex === -1) throw new Error(`message with id ${message.messageId} not found`);\n\t\t\t\tif (this.state.messages[messageIndex].role !== \"user\") throw new Error(`message with id ${message.messageId} is not a user message`);\n\t\t\t\tthis.state.messages = this.state.messages.slice(0, messageIndex + 1);\n\t\t\t\tthis.state.replaceMessage(messageIndex, {\n\t\t\t\t\t...uiMessage,\n\t\t\t\t\tid: message.messageId,\n\t\t\t\t\trole: (_b = uiMessage.role) != null ? _b : \"user\",\n\t\t\t\t\tmetadata: message.metadata\n\t\t\t\t});\n\t\t\t} else this.state.pushMessage({\n\t\t\t\t...uiMessage,\n\t\t\t\tid: (_c = uiMessage.id) != null ? _c : this.generateId(),\n\t\t\t\trole: (_d = uiMessage.role) != null ? _d : \"user\",\n\t\t\t\tmetadata: message.metadata\n\t\t\t});\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: message.messageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Regenerate the assistant message with the provided message id.\n\t\t* If no message id is provided, the last assistant message will be regenerated.\n\t\t*/\n\t\tthis.regenerate = async ({ messageId, ...options } = {}) => {\n\t\t\tconst messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);\n\t\t\tif (messageIndex === -1) throw new Error(`message ${messageId} not found`);\n\t\t\tthis.state.messages = this.state.messages.slice(0, this.messages[messageIndex].role === \"assistant\" ? messageIndex : messageIndex + 1);\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"regenerate-message\",\n\t\t\t\tmessageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Attempt to resume an ongoing streaming response.\n\t\t*/\n\t\tthis.resumeStream = async (options = {}) => {\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"resume-stream\",\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Clear the error state and set the status to ready if the chat is in an error state.\n\t\t*/\n\t\tthis.clearError = () => {\n\t\t\tif (this.status === \"error\") {\n\t\t\t\tthis.state.error = void 0;\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t}\n\t\t};\n\t\tthis.addToolOutput = async ({ state = \"output-available\", tool: tool2, toolCallId, output, errorText }) => this.jobExecutor.run(async () => {\n\t\t\tvar _a16, _b;\n\t\t\tconst messages = this.state.messages;\n\t\t\tconst lastMessage = messages[messages.length - 1];\n\t\t\tthis.state.replaceMessage(messages.length - 1, {\n\t\t\t\t...lastMessage,\n\t\t\t\tparts: lastMessage.parts.map((part) => isToolOrDynamicToolUIPart(part) && part.toolCallId === toolCallId ? {\n\t\t\t\t\t...part,\n\t\t\t\t\tstate,\n\t\t\t\t\toutput,\n\t\t\t\t\terrorText\n\t\t\t\t} : part)\n\t\t\t});\n\t\t\tif (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map((part) => isToolOrDynamicToolUIPart(part) && part.toolCallId === toolCallId ? {\n\t\t\t\t...part,\n\t\t\t\tstate,\n\t\t\t\toutput,\n\t\t\t\terrorText\n\t\t\t} : part);\n\t\t\tif (this.status !== \"streaming\" && this.status !== \"submitted\" && ((_a16 = this.sendAutomaticallyWhen) == null ? void 0 : _a16.call(this, { messages: this.state.messages }))) this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: (_b = this.lastMessage) == null ? void 0 : _b.id\n\t\t\t});\n\t\t});\n\t\t/** @deprecated Use addToolOutput */\n\t\tthis.addToolResult = this.addToolOutput;\n\t\t/**\n\t\t* Abort the current request immediately, keep the generated tokens if any.\n\t\t*/\n\t\tthis.stop = async () => {\n\t\t\tvar _a16;\n\t\t\tif (this.status !== \"streaming\" && this.status !== \"submitted\") return;\n\t\t\tif ((_a16 = this.activeResponse) == null ? void 0 : _a16.abortController) this.activeResponse.abortController.abort();\n\t\t};\n\t\tthis.id = id;\n\t\tthis.transport = transport;\n\t\tthis.generateId = generateId3;\n\t\tthis.messageMetadataSchema = messageMetadataSchema;\n\t\tthis.dataPartSchemas = dataPartSchemas;\n\t\tthis.state = state;\n\t\tthis.onError = onError;\n\t\tthis.onToolCall = onToolCall;\n\t\tthis.onFinish = onFinish;\n\t\tthis.onData = onData;\n\t\tthis.sendAutomaticallyWhen = sendAutomaticallyWhen;\n\t}\n\t/**\n\t* Hook status:\n\t*\n\t* - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n\t* - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n\t* - `ready`: The full response has been received and processed; a new user message can be submitted.\n\t* - `error`: An error occurred during the API request, preventing successful completion.\n\t*/\n\tget status() {\n\t\treturn this.state.status;\n\t}\n\tsetStatus({ status, error }) {\n\t\tif (this.status === status) return;\n\t\tthis.state.status = status;\n\t\tthis.state.error = error;\n\t}\n\tget error() {\n\t\treturn this.state.error;\n\t}\n\tget messages() {\n\t\treturn this.state.messages;\n\t}\n\tget lastMessage() {\n\t\treturn this.state.messages[this.state.messages.length - 1];\n\t}\n\tset messages(messages) {\n\t\tthis.state.messages = messages;\n\t}\n\tasync makeRequest({ trigger, metadata, headers, body, messageId }) {\n\t\tvar _a16, _b, _c;\n\t\tthis.setStatus({\n\t\t\tstatus: \"submitted\",\n\t\t\terror: void 0\n\t\t});\n\t\tconst lastMessage = this.lastMessage;\n\t\tlet isAbort = false;\n\t\tlet isDisconnect = false;\n\t\tlet isError = false;\n\t\tlet activeResponse;\n\t\ttry {\n\t\t\tconst response = {\n\t\t\t\tstate: createStreamingUIMessageState({\n\t\t\t\t\tlastMessage: this.state.snapshot(lastMessage),\n\t\t\t\t\tmessageId: this.generateId()\n\t\t\t\t}),\n\t\t\t\tabortController: new AbortController()\n\t\t\t};\n\t\t\tactiveResponse = response;\n\t\t\tresponse.abortController.signal.addEventListener(\"abort\", () => {\n\t\t\t\tisAbort = true;\n\t\t\t});\n\t\t\tthis.activeResponse = response;\n\t\t\tlet stream;\n\t\t\tif (trigger === \"resume-stream\") {\n\t\t\t\tconst reconnect = await this.transport.reconnectToStream({\n\t\t\t\t\tchatId: this.id,\n\t\t\t\t\tmetadata,\n\t\t\t\t\theaders,\n\t\t\t\t\tbody\n\t\t\t\t});\n\t\t\t\tif (reconnect == null) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tstream = reconnect;\n\t\t\t} else stream = await this.transport.sendMessages({\n\t\t\t\tchatId: this.id,\n\t\t\t\tmessages: this.state.messages,\n\t\t\t\tabortSignal: response.abortController.signal,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\ttrigger,\n\t\t\t\tmessageId\n\t\t\t});\n\t\t\tconst runUpdateMessageJob = (job) => this.jobExecutor.run(() => job({\n\t\t\t\tstate: response.state,\n\t\t\t\twrite: () => {\n\t\t\t\t\tvar _a17;\n\t\t\t\t\tthis.setStatus({ status: \"streaming\" });\n\t\t\t\t\tif (response.state.message.id === ((_a17 = this.lastMessage) == null ? void 0 : _a17.id)) this.state.replaceMessage(this.state.messages.length - 1, response.state.message);\n\t\t\t\t\telse this.state.pushMessage(response.state.message);\n\t\t\t\t}\n\t\t\t}));\n\t\t\tawait consumeStream({\n\t\t\t\tstream: processUIMessageStream({\n\t\t\t\t\tstream,\n\t\t\t\t\tonToolCall: this.onToolCall,\n\t\t\t\t\tonData: this.onData,\n\t\t\t\t\tmessageMetadataSchema: this.messageMetadataSchema,\n\t\t\t\t\tdataPartSchemas: this.dataPartSchemas,\n\t\t\t\t\trunUpdateMessageJob,\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t} catch (err) {\n\t\t\tif (isAbort || err.name === \"AbortError\") {\n\t\t\t\tisAbort = true;\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tisError = true;\n\t\t\tif (err instanceof TypeError && (err.message.toLowerCase().includes(\"fetch\") || err.message.toLowerCase().includes(\"network\"))) isDisconnect = true;\n\t\t\tif (this.onError && err instanceof Error) this.onError(err);\n\t\t\tthis.setStatus({\n\t\t\t\tstatus: \"error\",\n\t\t\t\terror: err\n\t\t\t});\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (activeResponse) (_a16 = this.onFinish) == null || _a16.call(this, {\n\t\t\t\t\tmessage: activeResponse.state.message,\n\t\t\t\t\tmessages: this.state.messages,\n\t\t\t\t\tisAbort,\n\t\t\t\t\tisDisconnect,\n\t\t\t\t\tisError,\n\t\t\t\t\tfinishReason: activeResponse.state.finishReason\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(err);\n\t\t\t}\n\t\t\tif (this.activeResponse === activeResponse) this.activeResponse = void 0;\n\t\t}\n\t\tif (((_b = this.sendAutomaticallyWhen) == null ? void 0 : _b.call(this, { messages: this.state.messages })) && !isError) await this.makeRequest({\n\t\t\ttrigger: \"submit-message\",\n\t\t\tmessageId: (_c = this.lastMessage) == null ? void 0 : _c.id,\n\t\t\tmetadata,\n\t\t\theaders,\n\t\t\tbody\n\t\t});\n\t}\n};\nfunction lastAssistantMessageIsCompleteWithToolCalls({ messages }) {\n\tconst message = messages[messages.length - 1];\n\tif (!message) return false;\n\tif (message.role !== \"assistant\") return false;\n\tconst lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n\t\treturn part.type === \"step-start\" ? index : lastIndex;\n\t}, -1);\n\tconst lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolOrDynamicToolUIPart).filter((part) => !part.providerExecuted);\n\treturn lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => part.state === \"output-available\" || part.state === \"output-error\");\n}\nfunction transformTextToUiMessageStream({ stream }) {\n\treturn stream.pipeThrough(new TransformStream({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\tcontroller.enqueue({ type: \"start-step\" });\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-start\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t},\n\t\tasync transform(part, controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tid: \"text-1\",\n\t\t\t\tdelta: part\n\t\t\t});\n\t\t},\n\t\tasync flush(controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-end\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t\tcontroller.enqueue({ type: \"finish-step\" });\n\t\t\tcontroller.enqueue({ type: \"finish\" });\n\t\t}\n\t}));\n}\nvar TextStreamChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn transformTextToUiMessageStream({ stream: stream.pipeThrough(new TextDecoderStream()) });\n\t}\n};\nvar uiMessagesSchema = lazyValidator(() => zodSchema(z.array(z.object({\n\tid: z.string(),\n\trole: z.enum([\n\t\t\"system\",\n\t\t\"user\",\n\t\t\"assistant\"\n\t]),\n\tmetadata: z.unknown().optional(),\n\tparts: z.array(z.union([\n\t\tz.object({\n\t\t\ttype: z.literal(\"text\"),\n\t\t\ttext: z.string(),\n\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"reasoning\"),\n\t\t\ttext: z.string(),\n\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"source-url\"),\n\t\t\tsourceId: z.string(),\n\t\t\turl: z.string(),\n\t\t\ttitle: z.string().optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"source-document\"),\n\t\t\tsourceId: z.string(),\n\t\t\tmediaType: z.string(),\n\t\t\ttitle: z.string(),\n\t\t\tfilename: z.string().optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"file\"),\n\t\t\tmediaType: z.string(),\n\t\t\tfilename: z.string().optional(),\n\t\t\turl: z.string(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({ type: z.literal(\"step-start\") }),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"data-\"),\n\t\t\tid: z.string().optional(),\n\t\t\tdata: z.unknown()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\tinput: z.unknown().optional(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-available\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-available\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.unknown(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tpreliminary: z.boolean().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-error\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.string(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"input-available\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.never().optional(),\n\t\t\t\treason: z.never().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.boolean(),\n\t\t\t\treason: z.string().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-available\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.unknown(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tpreliminary: z.boolean().optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-error\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.string(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(false),\n\t\t\t\treason: z.string().optional()\n\t\t\t})\n\t\t})\n\t]))\n}).superRefine((message, context) => {\n\tif (message.role !== \"assistant\" && message.parts.length === 0) context.addIssue({\n\t\torigin: \"array\",\n\t\tcode: \"too_small\",\n\t\tminimum: 1,\n\t\tinclusive: true,\n\t\tinput: message.parts,\n\t\tpath: [\"parts\"],\n\t\tmessage: \"Message must contain at least one part\"\n\t});\n})).nonempty(\"Messages array must not be empty\")));\nasync function safeValidateUIMessages({ messages, metadataSchema, dataSchemas, tools }) {\n\ttry {\n\t\tif (messages == null) return {\n\t\t\tsuccess: false,\n\t\t\terror: new InvalidArgumentError({\n\t\t\t\tparameter: \"messages\",\n\t\t\t\tvalue: messages,\n\t\t\t\tmessage: \"messages parameter must be provided\"\n\t\t\t})\n\t\t};\n\t\tconst validatedMessages = await validateTypes({\n\t\t\tvalue: messages,\n\t\t\tschema: uiMessagesSchema\n\t\t});\n\t\tif (metadataSchema) for (const message of validatedMessages) await validateTypes({\n\t\t\tvalue: message.metadata,\n\t\t\tschema: metadataSchema\n\t\t});\n\t\tif (dataSchemas) for (const message of validatedMessages) {\n\t\t\tconst dataParts = message.parts.filter((part) => part.type.startsWith(\"data-\"));\n\t\t\tfor (const dataPart of dataParts) {\n\t\t\t\tconst dataName = dataPart.type.slice(5);\n\t\t\t\tconst dataSchema = dataSchemas[dataName];\n\t\t\t\tif (!dataSchema) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\t\tcause: `No data schema found for data part ${dataName}`\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tawait validateTypes({\n\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\tschema: dataSchema\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (tools) for (const message of validatedMessages) {\n\t\t\tconst toolParts = message.parts.filter((part) => part.type.startsWith(\"tool-\"));\n\t\t\tfor (const toolPart of toolParts) {\n\t\t\t\tconst toolName = toolPart.type.slice(5);\n\t\t\t\tconst tool2 = tools[toolName];\n\t\t\t\tif (!tool2) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\t\tcause: `No tool schema found for tool part ${toolName}`\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tif (toolPart.state === \"input-available\" || toolPart.state === \"output-available\" || toolPart.state === \"output-error\") await validateTypes({\n\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\tschema: tool2.inputSchema\n\t\t\t\t});\n\t\t\t\tif (toolPart.state === \"output-available\" && tool2.outputSchema) await validateTypes({\n\t\t\t\t\tvalue: toolPart.output,\n\t\t\t\t\tschema: tool2.outputSchema\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: validatedMessages\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror\n\t\t};\n\t}\n}\nasync function validateUIMessages({ messages, metadataSchema, dataSchemas, tools }) {\n\tconst response = await safeValidateUIMessages({\n\t\tmessages,\n\t\tmetadataSchema,\n\t\tdataSchemas,\n\t\ttools\n\t});\n\tif (!response.success) throw response.error;\n\treturn response.data;\n}\nfunction createUIMessageStream({ execute, onError = () => \"An error occurred.\", originalMessages, onFinish, generateId: generateId3 = generateId }) {\n\tlet controller;\n\tconst ongoingStreamPromises = [];\n\tconst stream = new ReadableStream({ start(controllerArg) {\n\t\tcontroller = controllerArg;\n\t} });\n\tfunction safeEnqueue(data) {\n\t\ttry {\n\t\t\tcontroller.enqueue(data);\n\t\t} catch (error) {}\n\t}\n\ttry {\n\t\tconst result = execute({ writer: {\n\t\t\twrite(part) {\n\t\t\t\tsafeEnqueue(part);\n\t\t\t},\n\t\t\tmerge(streamArg) {\n\t\t\t\tongoingStreamPromises.push((async () => {\n\t\t\t\t\tconst reader = streamArg.getReader();\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) break;\n\t\t\t\t\t\tsafeEnqueue(value);\n\t\t\t\t\t}\n\t\t\t\t})().catch((error) => {\n\t\t\t\t\tsafeEnqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terrorText: onError(error)\n\t\t\t\t\t});\n\t\t\t\t}));\n\t\t\t},\n\t\t\tonError\n\t\t} });\n\t\tif (result) ongoingStreamPromises.push(result.catch((error) => {\n\t\t\tsafeEnqueue({\n\t\t\t\ttype: \"error\",\n\t\t\t\terrorText: onError(error)\n\t\t\t});\n\t\t}));\n\t} catch (error) {\n\t\tsafeEnqueue({\n\t\t\ttype: \"error\",\n\t\t\terrorText: onError(error)\n\t\t});\n\t}\n\tnew Promise(async (resolve2) => {\n\t\twhile (ongoingStreamPromises.length > 0) await ongoingStreamPromises.shift();\n\t\tresolve2();\n\t}).finally(() => {\n\t\ttry {\n\t\t\tcontroller.close();\n\t\t} catch (error) {}\n\t});\n\treturn handleUIMessageStreamFinish({\n\t\tstream,\n\t\tmessageId: generateId3(),\n\t\toriginalMessages,\n\t\tonFinish,\n\t\tonError\n\t});\n}\nfunction readUIMessageStream({ message, stream, onError, terminateOnError = false }) {\n\tvar _a16;\n\tlet controller;\n\tlet hasErrored = false;\n\tconst outputStream = new ReadableStream({ start(controllerParam) {\n\t\tcontroller = controllerParam;\n\t} });\n\tconst state = createStreamingUIMessageState({\n\t\tmessageId: (_a16 = message == null ? void 0 : message.id) != null ? _a16 : \"\",\n\t\tlastMessage: message\n\t});\n\tconst handleError = (error) => {\n\t\tonError?.(error);\n\t\tif (!hasErrored && terminateOnError) {\n\t\t\thasErrored = true;\n\t\t\tcontroller?.error(error);\n\t\t}\n\t};\n\tconsumeStream({\n\t\tstream: processUIMessageStream({\n\t\t\tstream,\n\t\t\trunUpdateMessageJob(job) {\n\t\t\t\treturn job({\n\t\t\t\t\tstate,\n\t\t\t\t\twrite: () => {\n\t\t\t\t\t\tcontroller?.enqueue(structuredClone(state.message));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tonError: handleError\n\t\t}),\n\t\tonError: handleError\n\t}).finally(() => {\n\t\tif (!hasErrored) controller?.close();\n\t});\n\treturn createAsyncIterableStream(outputStream);\n}\n//#endregion\n//#region src/index.ts\nconst generateText = (options) => generateText$1({\n\t...options,\n\tallowSystemInMessages: false\n});\nconst streamText = (options) => streamText$1({\n\t...options,\n\tallowSystemInMessages: false\n});\n//#endregion\nexport { AISDKError, APICallError, AbstractChat, DefaultChatTransport, DownloadError, EmptyResponseBodyError, Agent as Experimental_Agent, HttpChatTransport, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, InvalidResponseDataError, InvalidStreamPartError, InvalidToolInputError, JSONParseError, JsonToSseTransformStream, LoadAPIKeyError, LoadSettingError, MessageConversionError, NoContentGeneratedError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoOutputSpecifiedError, NoSpeechGeneratedError, NoSuchModelError, NoSuchProviderError, NoSuchToolError, output_exports as Output, RetryError, SerialJobExecutor, TextStreamChatTransport, TooManyEmbeddingValuesForCallError, ToolCallRepairError, TypeValidationError, UI_MESSAGE_STREAM_HEADERS, UnsupportedFunctionalityError, UnsupportedModelVersionError, asSchema, assistantModelMessageSchema, callCompletionApi, consumeStream, convertFileListToFileUIParts, convertToCoreMessages, convertToModelMessages, coreAssistantMessageSchema, coreMessageSchema, coreSystemMessageSchema, coreToolMessageSchema, coreUserMessageSchema, cosineSimilarity, createDownload, createGatewayProvider as createGateway, createIdGenerator, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultSettingsMiddleware, dynamicTool, embed, embedMany, experimental_createProviderRegistry, experimental_customProvider, generateImage as experimental_generateImage, generateSpeech as experimental_generateSpeech, transcribe as experimental_transcribe, extractReasoningMiddleware, gateway, generateId, generateObject, generateText, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, hasToolCall, isDataUIPart, isDeepEqualData, isFileUIPart, isReasoningUIPart, isTextUIPart, isToolOrDynamicToolUIPart, isToolUIPart, jsonSchema, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parseJsonEventStream, parsePartialJson, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, uiMessageChunkSchema, userModelMessageSchema, validateUIMessages, wrapLanguageModel, wrapProvider, zodSchema };\n\n//# sourceMappingURL=index.js.map","import { z } from 'zod';\n\nexport const TaskSchema = z.array(\n z.object({\n id: z.string().describe('Unique task ID using kebab-case'),\n content: z.string().describe('Specific, actionable task description'),\n status: z.enum(['pending', 'in_progress', 'completed', 'blocked']).default('pending'),\n priority: z.enum(['high', 'medium', 'low']).describe('Task priority'),\n dependencies: z.array(z.string()).optional().describe('IDs of tasks this depends on'),\n notes: z.string().describe('Detailed implementation notes and specifics'),\n }),\n);\n\nexport const QuestionSchema = z.array(\n z.object({\n id: z.string().describe('Unique question ID'),\n question: z.string().describe('Clear, specific question for the user'),\n type: z.enum(['choice', 'text', 'boolean']).describe('Type of answer expected'),\n options: z.array(z.string()).optional().describe('Options for choice questions'),\n context: z.string().optional().describe('Additional context or explanation'),\n }),\n);\nexport const PlanningIterationResultSchema = z.object({\n success: z.boolean(),\n tasks: TaskSchema,\n questions: QuestionSchema,\n reasoning: z.string(),\n planComplete: z.boolean(),\n message: z.string(),\n error: z.string().optional(),\n allPreviousQuestions: z.array(z.any()).optional(),\n allPreviousAnswers: z.record(z.string(), z.string()).optional(),\n});\n","/**\n * Prompts and instructions for task planning workflow\n */\n\nexport interface TaskPlanningPrompts {\n planningAgent: {\n instructions: (context: { storedQAPairs: any[] }) => string;\n refinementPrompt: (context: {\n action: string;\n workflowName?: string;\n description?: string;\n requirements?: string;\n discoveredWorkflows: any[];\n projectStructure: any;\n research: any;\n storedQAPairs: any[];\n hasTaskFeedback: boolean;\n userAnswers?: any;\n }) => string;\n initialPrompt: (context: {\n action: string;\n workflowName?: string;\n description?: string;\n requirements?: string;\n discoveredWorkflows: any[];\n projectStructure: any;\n research: any;\n }) => string;\n };\n taskApproval: {\n message: (questionsCount: number) => string;\n approvalMessage: (tasksCount: number) => string;\n };\n}\n\nexport const taskPlanningPrompts: TaskPlanningPrompts = {\n planningAgent: {\n instructions:\n context => `You are a Mastra workflow planning expert. Your task is to create a detailed, executable task plan.\n\nPLANNING RESPONSIBILITIES:\n1. **Analyze Requirements**: Review the user's description and requirements thoroughly\n2. **Identify Decision Points**: Find any choices that require user input (email providers, databases, APIs, etc.)\n3. **Create Specific Tasks**: Generate concrete, actionable tasks with clear implementation notes\n4. **Ask Clarifying Questions**: If any decisions are unclear, formulate specific questions for the user \n- do not ask about package managers\n- Assume the user is going to use zod for validation\n- You do not need to ask questions if you have none\n- NEVER ask questions that have already been answered before\n5. **Incorporate Feedback**: Use any previous answers or feedback to refine the plan\n\n${\n context.storedQAPairs.length > 0\n ? `PREVIOUS QUESTION-ANSWER PAIRS (${context.storedQAPairs.length} total):\\n${context.storedQAPairs\n .map(\n (pair, index) =>\n `${index + 1}. Q: ${pair.question.question}\\n A: ${pair.answer || 'NOT ANSWERED YET'}\\n Type: ${pair.question.type}\\n Asked: ${pair.askedAt}\\n ${pair.answer ? `Answered: ${pair.answeredAt}` : ''}`,\n )\n .join('\\n\\n')}\\n\\nIMPORTANT: DO NOT ASK ANY QUESTIONS THAT HAVE ALREADY BEEN ASKED!`\n : ''\n}\n\nBased on the context and any user answers, create or refine the task plan.`,\n\n refinementPrompt: context => `Refine the existing task plan based on all user answers collected so far. \n\nANSWERED QUESTIONS AND RESPONSES:\n${context.storedQAPairs\n .filter(pair => pair.answer)\n .map(\n (pair, index) =>\n `${index + 1}. Q: ${pair.question.question}\\n A: ${pair.answer}\\n Context: ${pair.question.context || 'None'}`,\n )\n .join('\\n\\n')}\n\nREQUIREMENTS:\n- Action: ${context.action}\n- Workflow Name: ${context.workflowName || 'To be determined'}\n- Description: ${context.description || 'Not specified'}\n- Requirements: ${context.requirements || 'Not specified'}\n\nPROJECT CONTEXT:\n- Discovered Workflows: ${JSON.stringify(context.discoveredWorkflows, null, 2)}\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n- Research: ${JSON.stringify(context.research, null, 2)}\n\n${context.hasTaskFeedback ? `\\nUSER FEEDBACK ON PREVIOUS TASK LIST:\\n${context.userAnswers?.taskFeedback}\\n\\nPLEASE INCORPORATE THIS FEEDBACK INTO THE REFINED TASK LIST.` : ''}\n\nRefine the task list and determine if any additional questions are needed.`,\n\n initialPrompt: context => `Create an initial task plan for ${context.action}ing a Mastra workflow.\n\nREQUIREMENTS:\n- Action: ${context.action}\n- Workflow Name: ${context.workflowName || 'To be determined'}\n- Description: ${context.description || 'Not specified'} \n- Requirements: ${context.requirements || 'Not specified'}\n\nPROJECT CONTEXT:\n- Discovered Workflows: ${JSON.stringify(context.discoveredWorkflows, null, 2)}\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n- Research: ${JSON.stringify(context.research, null, 2)}\n\nCreate specific tasks and identify any questions that need user clarification.`,\n },\n\n taskApproval: {\n message: questionsCount => `Please answer ${questionsCount} question(s) to finalize the workflow plan:`,\n approvalMessage: tasksCount => `Please review and approve the ${tasksCount} task(s) for execution:`,\n },\n};\n","import { z } from 'zod';\nimport { PlanningIterationResultSchema, QuestionSchema, TaskSchema } from '../shared/schema';\n\n// Workflow Builder schemas and types\nexport const WorkflowBuilderInputSchema = z.object({\n workflowName: z.string().optional().describe('Name of the workflow to create or edit'),\n action: z.enum(['create', 'edit']).describe('Action to perform: create new or edit existing workflow'),\n description: z.string().optional().describe('Description of what the workflow should do'),\n requirements: z.string().optional().describe('Detailed requirements for the workflow'),\n projectPath: z.string().optional().describe('Path to the Mastra project (defaults to current directory)'),\n});\n\nexport const DiscoveredWorkflowSchema = z.object({\n name: z.string(),\n file: z.string(),\n description: z.string().optional(),\n inputSchema: z.any().optional(),\n outputSchema: z.any().optional(),\n steps: z.array(z.string()).optional(),\n});\n\nexport const WorkflowDiscoveryResultSchema = z.object({\n success: z.boolean(),\n workflows: z.array(DiscoveredWorkflowSchema),\n mastraIndexExists: z.boolean(),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const ProjectDiscoveryResultSchema = z.object({\n success: z.boolean(),\n structure: z.object({\n hasWorkflowsDir: z.boolean(),\n hasAgentsDir: z.boolean(),\n hasToolsDir: z.boolean(),\n hasMastraIndex: z.boolean(),\n existingWorkflows: z.array(z.string()),\n existingAgents: z.array(z.string()),\n existingTools: z.array(z.string()),\n }),\n dependencies: z.record(z.string(), z.string()),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const WorkflowResearchResultSchema = z.object({\n success: z.boolean(),\n documentation: z.object({\n workflowPatterns: z.array(z.string()),\n stepExamples: z.array(z.string()),\n bestPractices: z.array(z.string()),\n }),\n webResources: z.array(\n z.object({\n title: z.string(),\n url: z.string(),\n snippet: z.string(),\n relevance: z.number(),\n }),\n ),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const TaskManagementResultSchema = z.object({\n success: z.boolean(),\n tasks: TaskSchema,\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const TaskExecutionInputSchema = z.object({\n action: z.enum(['create', 'edit']),\n workflowName: z.string().optional(),\n description: z.string().optional(),\n requirements: z.string().optional(),\n tasks: TaskSchema,\n discoveredWorkflows: z.array(z.any()),\n projectStructure: z.any(),\n research: z.any(),\n projectPath: z.string().optional(),\n});\n\nexport const TaskExecutionSuspendSchema = z.object({\n questions: QuestionSchema,\n currentProgress: z.string(),\n completedTasks: z.array(z.string()),\n message: z.string(),\n});\n\nexport const TaskExecutionResumeSchema = z.object({\n answers: z.array(\n z.object({\n questionId: z.string(),\n answer: z.string(),\n }),\n ),\n});\n\nexport const TaskExecutionResultSchema = z.object({\n success: z.boolean(),\n filesModified: z.array(z.string()),\n validationResults: z.object({\n passed: z.boolean(),\n errors: z.array(z.string()),\n warnings: z.array(z.string()),\n }),\n completedTasks: z.array(z.string()),\n message: z.string(),\n error: z.string().optional(),\n});\n\nexport const UserClarificationInputSchema = z.object({\n questions: QuestionSchema,\n});\n\nexport const UserClarificationResultSchema = z.object({\n answers: z.record(z.string(), z.string()),\n hasAnswers: z.boolean(),\n});\n\nexport const WorkflowBuilderResultSchema = z.object({\n success: z.boolean(),\n action: z.enum(['create', 'edit']),\n workflowName: z.string().optional(),\n workflowFile: z.string().optional(),\n discovery: WorkflowDiscoveryResultSchema.optional(),\n projectStructure: ProjectDiscoveryResultSchema.optional(),\n research: WorkflowResearchResultSchema.optional(),\n planning: PlanningIterationResultSchema.optional(),\n taskManagement: TaskManagementResultSchema.optional(),\n execution: TaskExecutionResultSchema.optional(),\n needsUserInput: z.boolean().optional(),\n questions: QuestionSchema.optional(),\n message: z.string(),\n nextSteps: z.array(z.string()).optional(),\n error: z.string().optional(),\n});\n\nexport const TaskExecutionIterationInputSchema = (taskLength: number) =>\n z.object({\n status: z\n .enum(['in_progress', 'completed', 'needs_clarification'])\n .describe('Status - only use \"completed\" when ALL remaining tasks are finished'),\n progress: z.string().describe('Current progress description'),\n completedTasks: z\n .array(z.string())\n .describe('List of ALL completed task IDs (including previously completed ones)'),\n totalTasksRequired: z.number().describe(`Total number of tasks that must be completed (should be ${taskLength})`),\n tasksRemaining: z.array(z.string()).describe('List of task IDs that still need to be completed'),\n filesModified: z\n .array(z.string())\n .describe('List of files that were created or modified - use these exact paths for validateCode tool'),\n questions: QuestionSchema.optional().describe('Questions for user if clarification is needed'),\n message: z.string().describe('Summary of work completed or current status'),\n error: z.string().optional().describe('Any errors encountered'),\n });\n","import { z } from 'zod';\nimport { QuestionSchema, TaskSchema } from '../shared/schema';\nimport {\n ProjectDiscoveryResultSchema,\n WorkflowResearchResultSchema,\n DiscoveredWorkflowSchema,\n} from '../workflow-builder/schema';\n\nexport const PlanningIterationInputSchema = z.object({\n action: z.enum(['create', 'edit']),\n workflowName: z.string().optional(),\n description: z.string().optional(),\n requirements: z.string().optional(),\n discoveredWorkflows: z.array(DiscoveredWorkflowSchema),\n projectStructure: ProjectDiscoveryResultSchema,\n research: WorkflowResearchResultSchema,\n\n userAnswers: z.record(z.string(), z.string()).optional(),\n});\n\nexport const PlanningIterationSuspendSchema = z.object({\n questions: QuestionSchema,\n message: z.string(),\n currentPlan: z.object({\n tasks: TaskSchema,\n reasoning: z.string(),\n }),\n});\n\nexport const PlanningIterationResumeSchema = z.object({\n answers: z.record(z.string(), z.string()),\n});\n\nexport const PlanningAgentOutputSchema = z.object({\n tasks: TaskSchema,\n questions: QuestionSchema.optional(),\n reasoning: z.string().describe('Explanation of the plan and any questions'),\n planComplete: z.boolean().describe('Whether the plan is ready for execution (no more questions)'),\n});\n\nexport const TaskApprovalOutputSchema = z.object({\n approved: z.boolean(),\n tasks: TaskSchema,\n message: z.string(),\n userFeedback: z.string().optional(),\n});\n\nexport const TaskApprovalSuspendSchema = z.object({\n taskList: TaskSchema,\n summary: z.string(),\n message: z.string(),\n});\n\nexport const TaskApprovalResumeSchema = z.object({\n approved: z.boolean(),\n modifications: z.string().optional(),\n});\n","import { Agent } from '@mastra/core/agent';\nimport { createWorkflow, createStep } from '@mastra/core/workflows';\nimport type z from 'zod';\nimport { resolveModel } from '../../utils';\nimport { PlanningIterationResultSchema } from '../shared/schema';\nimport { taskPlanningPrompts } from './prompts';\nimport {\n PlanningAgentOutputSchema,\n PlanningIterationInputSchema,\n PlanningIterationResumeSchema,\n PlanningIterationSuspendSchema,\n TaskApprovalOutputSchema,\n TaskApprovalResumeSchema,\n TaskApprovalSuspendSchema,\n} from './schema';\n\ntype PlanningIterationResult = z.infer<typeof PlanningIterationResultSchema>;\n\n// Planning iteration step (with questions and user answers)\nconst planningIterationStep = createStep({\n id: 'planning-iteration',\n description: 'Create or refine task plan with user input',\n inputSchema: PlanningIterationInputSchema,\n outputSchema: PlanningIterationResultSchema,\n suspendSchema: PlanningIterationSuspendSchema,\n resumeSchema: PlanningIterationResumeSchema,\n execute: async ({ inputData, resumeData, suspend, requestContext }) => {\n const {\n action,\n workflowName,\n description,\n requirements,\n discoveredWorkflows,\n projectStructure,\n research,\n userAnswers,\n } = inputData;\n\n console.info('Starting planning iteration...');\n\n // Get or initialize Q&A tracking in request context\n const qaKey = 'workflow-builder-qa';\n let storedQAPairs: Array<{\n question: any;\n answer: string | null;\n askedAt: string;\n answeredAt: string | null;\n }> = requestContext.get(qaKey) || [];\n\n // Process new answers from user input or resume data\n const newAnswers = { ...(userAnswers || {}), ...(resumeData?.answers || {}) };\n\n // console.info('before', storedQAPairs);\n // console.info('newAnswers', newAnswers);\n // Update existing Q&A pairs with new answers\n if (Object.keys(newAnswers).length > 0) {\n storedQAPairs = storedQAPairs.map(pair => {\n const answerValue = newAnswers[pair.question.id];\n if (answerValue) {\n return {\n ...pair,\n answer: String(answerValue) || null,\n answeredAt: new Date().toISOString(),\n };\n }\n return pair;\n });\n\n // Store updated pairs back to request context\n requestContext.set(qaKey, storedQAPairs);\n }\n\n // console.info('after', storedQAPairs);\n\n // console.info(\n // `Current Q&A state: ${storedQAPairs.length} question-answer pairs, ${storedQAPairs.filter(p => p.answer).length} answered`,\n // );\n\n try {\n // const filteredMcpTools = await initializeMcpTools();\n\n const model = await resolveModel({ requestContext });\n\n const planningAgent = new Agent({\n id: 'workflow-planning-agent',\n model,\n instructions: taskPlanningPrompts.planningAgent.instructions({\n storedQAPairs,\n }),\n name: 'Workflow Planning Agent',\n // tools: filteredMcpTools,\n });\n\n // Check if we have user feedback from rejected task list in input data\n const hasTaskFeedback = Boolean(userAnswers && userAnswers.taskFeedback);\n\n const planningPrompt = storedQAPairs.some(pair => pair.answer)\n ? taskPlanningPrompts.planningAgent.refinementPrompt({\n action,\n workflowName,\n description,\n requirements,\n discoveredWorkflows,\n projectStructure,\n research,\n storedQAPairs,\n hasTaskFeedback,\n userAnswers,\n })\n : taskPlanningPrompts.planningAgent.initialPrompt({\n action,\n workflowName,\n description,\n requirements,\n discoveredWorkflows,\n projectStructure,\n research,\n });\n\n const result = await planningAgent.generate(planningPrompt, {\n structuredOutput: {\n schema: PlanningAgentOutputSchema,\n },\n // maxSteps: 15,\n });\n\n const planResult = (await result.object) as unknown as PlanningIterationResult | null;\n if (!planResult) {\n return {\n tasks: [],\n success: false,\n questions: [],\n reasoning: 'Planning agent failed to generate a valid response',\n planComplete: false,\n message: 'Planning failed',\n };\n }\n\n // If we have questions and plan is not complete, suspend for user input\n if (planResult.questions && planResult.questions.length > 0 && !planResult.planComplete) {\n console.info(`Planning needs user clarification: ${planResult.questions.length} questions`);\n\n console.info(planResult.questions);\n\n // Store new questions as Q&A pairs in request context\n const newQAPairs = planResult.questions.map((question: any) => ({\n question,\n answer: null,\n askedAt: new Date().toISOString(),\n answeredAt: null,\n }));\n\n storedQAPairs = [...storedQAPairs, ...newQAPairs];\n requestContext.set(qaKey, storedQAPairs);\n\n console.info(\n `Updated Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter(p => p.answer).length} answered`,\n );\n\n return suspend({\n questions: planResult.questions,\n message: taskPlanningPrompts.taskApproval.message(planResult.questions.length),\n currentPlan: {\n tasks: planResult.tasks,\n reasoning: planResult.reasoning,\n },\n });\n }\n\n // Plan is complete\n console.info(`Planning complete with ${planResult.tasks.length} tasks`);\n\n // Update request context with final state\n requestContext.set(qaKey, storedQAPairs);\n console.info(\n `Final Q&A state: ${storedQAPairs.length} total question-answer pairs, ${storedQAPairs.filter(p => p.answer).length} answered`,\n );\n\n return {\n tasks: planResult.tasks,\n success: true,\n questions: [],\n reasoning: planResult.reasoning,\n planComplete: true,\n message: `Successfully created ${planResult.tasks.length} tasks`,\n allPreviousQuestions: storedQAPairs.map(pair => pair.question),\n allPreviousAnswers: Object.fromEntries(\n storedQAPairs.filter(pair => pair.answer).map(pair => [pair.question.id, pair.answer]),\n ),\n };\n } catch (error) {\n console.error('Planning iteration failed:', error);\n return {\n tasks: [],\n success: false,\n questions: [],\n reasoning: `Planning failed: ${error instanceof Error ? error.message : String(error)}`,\n planComplete: false,\n message: 'Planning iteration failed',\n error: error instanceof Error ? error.message : String(error),\n allPreviousQuestions: storedQAPairs.map(pair => pair.question),\n allPreviousAnswers: Object.fromEntries(\n storedQAPairs.filter(pair => pair.answer).map(pair => [pair.question.id, pair.answer]),\n ),\n };\n }\n },\n});\n\n// Task approval step\nconst taskApprovalStep = createStep({\n id: 'task-approval',\n description: 'Get user approval for the final task list',\n inputSchema: PlanningIterationResultSchema,\n outputSchema: TaskApprovalOutputSchema,\n suspendSchema: TaskApprovalSuspendSchema,\n resumeSchema: TaskApprovalResumeSchema,\n execute: async ({ inputData, resumeData, suspend }) => {\n const { tasks } = inputData;\n\n // If no resume data, suspend for user approval\n if (!resumeData?.approved && resumeData?.approved !== false) {\n console.info(`Requesting user approval for ${tasks.length} tasks`);\n\n const summary = `Task List for Approval:\n\n${tasks.length} tasks planned:\n${tasks.map((task, i) => `${i + 1}. [${task.priority.toUpperCase()}] ${task.content}${task.dependencies?.length ? ` (depends on: ${task.dependencies.join(', ')})` : ''}\\n Notes: ${task.notes || 'None'}`).join('\\n')}`;\n\n return suspend({\n taskList: tasks,\n summary,\n message: taskPlanningPrompts.taskApproval.approvalMessage(tasks.length),\n });\n }\n\n // User responded\n if (resumeData.approved) {\n console.info('Task list approved by user');\n return {\n approved: true,\n tasks,\n message: 'Task list approved, ready for execution',\n };\n } else {\n console.info('Task list rejected by user');\n return {\n approved: false,\n tasks,\n message: 'Task list rejected',\n userFeedback: resumeData.modifications,\n };\n }\n },\n});\n\n// Sub-workflow: Planning and Approval Cycle\nexport const planningAndApprovalWorkflow = createWorkflow({\n id: 'planning-and-approval',\n description: 'Handle iterative planning with questions and task list approval',\n inputSchema: PlanningIterationInputSchema,\n outputSchema: TaskApprovalOutputSchema,\n steps: [planningIterationStep, taskApprovalStep],\n})\n // Step 1: Planning iteration (with questions suspension)\n .dountil(planningIterationStep, async ({ inputData }) => {\n console.info(`Sub-workflow planning check: planComplete=${inputData.planComplete}`);\n return inputData.planComplete === true;\n })\n // Map to approval step input format\n .map(async ({ inputData }) => {\n // After doUntil completes, inputData contains the final result\n return {\n tasks: inputData.tasks || [],\n success: inputData.success || false,\n questions: inputData.questions || [],\n reasoning: inputData.reasoning || '',\n planComplete: inputData.planComplete || false,\n message: inputData.message || '',\n };\n })\n // Step 2: Task list approval\n .then(taskApprovalStep)\n .commit();\n","export const workflowResearch = `\n## 🔍 **COMPREHENSIVE MASTRA WORKFLOW RESEARCH SUMMARY**\n\nBased on extensive research of Mastra documentation and examples, here's essential information for building effective Mastra workflows:\n\n### **📋 WORKFLOW FUNDAMENTALS**\n\n**Core Components:**\n- **\\`createWorkflow()\\`**: Main factory function that creates workflow instances\n- **\\`createStep()\\`**: Creates individual workflow steps with typed inputs/outputs \n- **\\`.commit()\\`**: Finalizes workflow definition (REQUIRED to make workflows executable)\n- **Zod schemas**: Used for strict input/output typing and validation\n\n**Basic Structure:**\n\\`\\`\\`typescript\nimport { createWorkflow, createStep } from \"@mastra/core/workflows\";\nimport { z } from \"zod\";\n\nconst workflow = createWorkflow({\n id: \"unique-workflow-id\", // Required: kebab-case recommended\n description: \"What this workflow does\", // Optional but recommended\n inputSchema: z.object({...}), // Required: Defines workflow inputs\n outputSchema: z.object({...}) // Required: Defines final outputs\n})\n .then(step1) // Chain steps sequentially\n .then(step2)\n .commit(); // CRITICAL: Makes workflow executable\n\\`\\`\\`\n\n### **🔧 STEP CREATION PATTERNS**\n\n**Standard Step Definition:**\n\\`\\`\\`typescript\nconst myStep = createStep({\n id: \"step-id\", // Required: unique identifier\n description: \"Step description\", // Recommended for clarity\n inputSchema: z.object({...}), // Required: input validation\n outputSchema: z.object({...}), // Required: output validation\n execute: async ({ inputData, mastra, getStepResult, getInitData }) => {\n // Step logic here\n return { /* matches outputSchema */ };\n }\n});\n\\`\\`\\`\n\n**Execute Function Parameters:**\n- \\`inputData\\`: Validated input matching inputSchema\n- \\`mastra\\`: Access to Mastra instance (agents, tools, other workflows)\n- \\`getStepResult(stepInstance)\\`: Get results from previous steps\n- \\`getInitData()\\`: Access original workflow input data\n- \\`requestContext\\`: Runtime dependency injection context\n- \\`runCount\\`: Number of times this step has run (useful for retries)\n\n### **🔄 CONTROL FLOW METHODS**\n\n**Sequential Execution:**\n- \\`.then(step)\\`: Execute steps one after another\n- Data flows automatically if schemas match\n\n**Parallel Execution:**\n- \\`.parallel([step1, step2])\\`: Run steps simultaneously\n- All parallel steps complete before continuing\n\n**Conditional Logic:**\n- \\`.branch([[condition, step], [condition, step]])\\`: Execute different steps based on conditions\n- Conditions evaluated sequentially, matching steps run in parallel\n\n**Loops:**\n- \\`.dountil(step, condition)\\`: Repeat until condition becomes true\n- \\`.dowhile(step, condition)\\`: Repeat while condition is true \n- \\`.foreach(step, {concurrency: N})\\`: Execute step for each array item\n\n**Data Transformation:**\n- \\`.map(({ inputData, getStepResult, getInitData }) => transformedData)\\`: Transform data between steps\n\n### **⏸️ SUSPEND & RESUME CAPABILITIES**\n\n**For Human-in-the-Loop Workflows:**\n\\`\\`\\`typescript\nconst userInputStep = createStep({\n id: \"user-input\",\n suspendSchema: z.object({}), // Schema for suspension payload\n resumeSchema: z.object({ // Schema for resume data\n userResponse: z.string()\n }),\n execute: async ({ resumeData, suspend }) => {\n if (!resumeData?.userResponse) {\n await suspend({}); // Pause workflow\n return { response: \"\" };\n }\n return { response: resumeData.userResponse };\n }\n});\n\\`\\`\\`\n\n**Resume Workflow:**\n\\`\\`\\`typescript\nconst result = await run.start({ inputData: {...} });\nif (result.status === \"suspended\") {\n await run.resume({\n step: result.suspended[0], // Or specific step ID\n resumeData: { userResponse: \"answer\" }\n });\n}\n\\`\\`\\`\n\n### **🛠️ INTEGRATING AGENTS & TOOLS**\n\n**Using Agents in Steps:**\n\\`\\`\\`typescript\n// Method 1: Agent as step\nconst agentStep = createStep(myAgent);\n\n// Method 2: Call agent in execute function\nconst step = createStep({\n execute: async ({ inputData }) => {\n const result = await myAgent.generate(prompt);\n return { output: result.text };\n }\n});\n\\`\\`\\`\n\n**Using Tools in Steps:**\n\\`\\`\\`typescript\n// Method 1: Tool as step \nconst toolStep = createStep(myTool);\n\n// Method 2: Call tool in execute function\nconst step = createStep({\n execute: async ({ inputData, requestContext }) => {\n const result = await myTool.execute({\n context: inputData,\n requestContext\n });\n return result;\n }\n});\n\\`\\`\\`\n\n### **🗂️ PROJECT ORGANIZATION PATTERNS**\n\n**MANDATORY Workflow Organization:**\nEach workflow MUST be organized in its own dedicated folder with separated concerns:\n\n\\`\\`\\`\nsrc/mastra/workflows/\n├── my-workflow-name/ # Kebab-case folder name\n│ ├── types.ts # All Zod schemas and TypeScript types\n│ ├── steps.ts # All individual step definitions\n│ ├── workflow.ts # Main workflow composition and export\n│ └── utils.ts # Helper functions (if needed)\n├── another-workflow/\n│ ├── types.ts\n│ ├── steps.ts\n│ ├── workflow.ts\n│ └── utils.ts\n└── index.ts # Export all workflows\n\\`\\`\\`\n\n**CRITICAL File Organization Rules:**\n- **ALWAYS create a dedicated folder** for each workflow\n- **Folder names MUST be kebab-case** version of workflow name\n- **types.ts**: Define all input/output schemas, validation types, and interfaces\n- **steps.ts**: Create all individual step definitions using createStep()\n- **workflow.ts**: Compose steps into workflow using createWorkflow() and export the final workflow\n- **utils.ts**: Any helper functions, constants, or utilities (create only if needed)\n- **NEVER put everything in one file** - always separate concerns properly\n\n**Workflow Registration:**\n\\`\\`\\`typescript\n// src/mastra/index.ts\nexport const mastra = new Mastra({\n workflows: {\n sendEmailWorkflow, // Use camelCase for keys\n dataProcessingWorkflow\n },\n storage: new LibSQLStore({ id: 'mastra-storage', url: 'file:./mastra.db' }), // Required for suspend/resume\n});\n\\`\\`\\`\n\n### **📦 ESSENTIAL DEPENDENCIES**\n\n**Required Packages:**\n\\`\\`\\`json\n{\n \"dependencies\": {\n \"@mastra/core\": \"latest\",\n \"zod\": \"^3.25.67\"\n }\n}\n\\`\\`\\`\n\n**Additional Packages (as needed):**\n- \\`@mastra/libsql\\`: For workflow state persistence\n- \\`@ai-sdk/openai\\`: For AI model integration\n- \\`ai\\`: For AI SDK functionality\n\n### **✅ WORKFLOW BEST PRACTICES**\n\n**Schema Design:**\n- Use descriptive property names in schemas\n- Make schemas as specific as possible (avoid \\`z.any()\\`)\n- Include validation for required business logic\n\n**Error Handling:**\n- Use \\`try/catch\\` blocks in step execute functions\n- Return meaningful error messages\n- Consider using \\`bail()\\` for early successful exits\n\n**Step Organization:**\n- Keep steps focused on single responsibilities\n- Use descriptive step IDs (kebab-case recommended)\n- Create reusable steps for common operations\n\n**Data Flow:**\n- Use \\`.map()\\` when schemas don't align between steps\n- Access previous step results with \\`getStepResult(stepInstance)\\`\n- Use \\`getInitData()\\` to access original workflow input\n\n### **🚀 EXECUTION PATTERNS**\n\n**Running Workflows:**\n\\`\\`\\`typescript\n// Create and start run\nconst run = await workflow.createRun();\nconst result = await run.start({ inputData: {...} });\n\n// Stream execution for real-time monitoring\nconst stream = await run.streamVNext({ inputData: {...} });\nfor await (const chunk of stream) {\n console.log(chunk);\n}\n\n// Watch for events\nrun.watch((event) => console.log(event));\n\\`\\`\\`\n\n**Workflow Status Types:**\n- \\`\"success\"\\`: Completed successfully\n- \\`\"suspended\"\\`: Paused awaiting input\n- \\`\"failed\"\\`: Encountered error\n\n### **🔗 ADVANCED FEATURES**\n\n**Nested Workflows:**\n- Use workflows as steps: \\`.then(otherWorkflow)\\`\n- Enable complex workflow composition\n\n**Request Context:**\n- Pass shared data across all steps\n- Enable dependency injection patterns\n\n**Streaming & Events:**\n- Real-time workflow monitoring\n- Integration with external event systems\n\n**Cloning:**\n- \\`cloneWorkflow(original, {id: \"new-id\"})\\`: Reuse workflow structure\n- \\`cloneStep(original, {id: \"new-id\"})\\`: Reuse step logic\n\nThis comprehensive research provides the foundation for creating robust, maintainable Mastra workflows with proper typing, error handling, and architectural patterns.\n`;\n/**\n * Prompts and instructions for workflow builder agents\n */\n\nexport interface WorkflowBuilderPrompts {\n researchAgent: {\n instructions: string;\n prompt: (context: { projectStructure: any; dependencies: any; hasWorkflowsDir: boolean }) => string;\n };\n executionAgent: {\n instructions: (context: {\n action: string;\n workflowName?: string;\n tasksLength: number;\n currentProjectPath: string;\n discoveredWorkflows: any;\n projectStructure: any;\n research: any;\n tasks: any[];\n resumeData?: any;\n }) => string;\n prompt: (context: { action: string; workflowName?: string; tasks: any[]; resumeData?: any }) => string;\n iterationPrompt: (context: {\n completedTasks: any[];\n pendingTasks: any[];\n workflowName?: string;\n resumeData?: any;\n }) => string;\n };\n validation: {\n instructions: string;\n };\n}\n\nexport const workflowBuilderPrompts: WorkflowBuilderPrompts = {\n researchAgent: {\n instructions: `You are a Mastra workflow research expert. Your task is to gather relevant information about creating Mastra workflows.\n\nRESEARCH OBJECTIVES:\n1. **Core Concepts**: Understand how Mastra workflows work\n2. **Best Practices**: Learn workflow patterns and conventions \n3. **Code Examples**: Find relevant implementation examples\n4. **Technical Details**: Understand schemas, steps, and configuration\n\nUse the available documentation and examples tools to gather comprehensive information about Mastra workflows.`,\n\n prompt: context => `Research everything about Mastra workflows to help create or edit them effectively.\n\nPROJECT CONTEXT:\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n- Dependencies: ${JSON.stringify(context.dependencies, null, 2)}\n- Has Workflows Directory: ${context.hasWorkflowsDir}\n\nFocus on:\n1. How to create workflows using createWorkflow()\n2. How to create and chain workflow steps\n3. Best practices for workflow organization\n4. Common workflow patterns and examples\n5. Schema definitions and types\n6. Error handling and debugging\n\nUse the docs and examples tools to gather comprehensive information.`,\n },\n\n executionAgent: {\n instructions: context => `You are executing a workflow ${context.action} task for: \"${context.workflowName}\"\n\nCRITICAL WORKFLOW EXECUTION REQUIREMENTS:\n1. **EXPLORE PROJECT STRUCTURE FIRST**: Use listDirectory and readFile tools to understand the existing project layout, folder structure, and conventions before creating any files\n2. **FOLLOW PROJECT CONVENTIONS**: Look at existing workflows, agents, and file structures to understand where new files should be placed (typically src/mastra/workflows/, src/mastra/agents/, etc.)\n3. **USE PRE-LOADED TASK LIST**: Your task list has been pre-populated in the taskManager tool. Use taskManager with action 'list' to see all tasks, and action 'update' to mark progress\n4. **COMPLETE EVERY SINGLE TASK**: You MUST complete ALL ${context.tasksLength} tasks that are already in the taskManager. Do not stop until every task is marked as 'completed'\n5. **Follow Task Dependencies**: Execute tasks in the correct order, respecting dependencies\n6. **Request User Input When Needed**: If you encounter choices (like email providers, databases, etc.) that require user decision, return questions for clarification\n7. **STRICT WORKFLOW ORGANIZATION**: When creating or editing workflows, you MUST follow this exact structure\n\nMANDATORY WORKFLOW FOLDER STRUCTURE:\nWhen ${context.action === 'create' ? 'creating a new workflow' : 'editing a workflow'}, you MUST organize files as follows:\n\n📁 src/mastra/workflows/${context.workflowName?.toLowerCase().replace(/[^a-z0-9]/g, '-') || 'new-workflow'}/\n├── 📄 types.ts # All Zod schemas and TypeScript types\n├── 📄 steps.ts # All individual step definitions \n├── 📄 workflow.ts # Main workflow composition and export\n└── 📄 utils.ts # Helper functions (if needed)\n\nCRITICAL FILE ORGANIZATION RULES:\n- **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/\n- **Folder name MUST be kebab-case** version of workflow name\n- **types.ts**: Define all input/output schemas, validation types, and interfaces\n- **steps.ts**: Create all individual step definitions using createStep()\n- **workflow.ts**: Compose steps into workflow using createWorkflow() and export the final workflow\n- **utils.ts**: Any helper functions, constants, or utilities (create only if needed)\n- **NEVER put everything in one file** - always separate concerns properly\n\nCRITICAL COMPLETION REQUIREMENTS: \n- ALWAYS explore the directory structure before creating files to understand where they should go\n- You MUST complete ALL ${context.tasksLength} tasks before returning status='completed'\n- Use taskManager tool with action 'list' to see your current task list and action 'update' to mark tasks as 'in_progress' or 'completed'\n- If you need to make any decisions during implementation (choosing providers, configurations, etc.), return questions for user clarification\n- DO NOT make assumptions about file locations - explore first!\n- You cannot finish until ALL tasks in the taskManager are marked as 'completed'\n\nPROJECT CONTEXT:\n- Action: ${context.action}\n- Workflow Name: ${context.workflowName}\n- Project Path: ${context.currentProjectPath}\n- Discovered Workflows: ${JSON.stringify(context.discoveredWorkflows, null, 2)}\n- Project Structure: ${JSON.stringify(context.projectStructure, null, 2)}\n\nAVAILABLE RESEARCH:\n${JSON.stringify(context.research, null, 2)}\n\nPRE-LOADED TASK LIST (${context.tasksLength} tasks already in taskManager):\n${context.tasks.map(task => `- ${task.id}: ${task.content} (Priority: ${task.priority})`).join('\\n')}\n\n${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeData.answers, null, 2)}` : ''}\n\nStart by exploring the project structure, then use 'taskManager' with action 'list' to see your pre-loaded tasks, and work through each task systematically.`,\n\n prompt: context =>\n context.resumeData\n ? `Continue working on the task list. The user has provided answers to your questions: ${JSON.stringify(context.resumeData.answers, null, 2)}. \n\nCRITICAL: You must complete ALL ${context.tasks.length} tasks that are pre-loaded in the taskManager. Use the taskManager tool with action 'list' to check your progress and continue with the next tasks. Do not stop until every single task is marked as 'completed'.`\n : `Begin executing the pre-loaded task list to ${context.action} the workflow \"${context.workflowName}\". \n\nCRITICAL REQUIREMENTS:\n- Your ${context.tasks.length} tasks have been PRE-LOADED into the taskManager tool\n- Start by exploring the project directory structure using listDirectory and readFile tools to understand:\n - Where workflows are typically stored (look for src/mastra/workflows/ or similar)\n - What the existing file structure looks like\n - How other workflows are organized and named\n - Where agent files are stored if needed\n- Then use taskManager with action 'list' to see your pre-loaded tasks\n- Use taskManager with action 'update' to mark tasks as 'in_progress' or 'completed'\n\nCRITICAL FILE ORGANIZATION RULES:\n- **ALWAYS create a dedicated folder** for the workflow in src/mastra/workflows/\n- **Folder name MUST be kebab-case** version of workflow name \n- **NEVER put everything in one file** - separate types, steps, and workflow composition\n- Follow the 4-file structure above for maximum maintainability and clarity\n\n- DO NOT return status='completed' until ALL ${context.tasks.length} tasks are marked as 'completed' in the taskManager\n\nPRE-LOADED TASKS (${context.tasks.length} total tasks in taskManager):\n${context.tasks.map((task, index) => `${index + 1}. [${task.id}] ${task.content}`).join('\\n')}\n\nUse taskManager with action 'list' to see the current status of all tasks. You must complete every single one before finishing.`,\n\n iterationPrompt:\n context => `Continue working on the remaining tasks. You have already completed these tasks: [${context.completedTasks.map(t => t.id).join(', ')}]\n\nREMAINING TASKS TO COMPLETE (${context.pendingTasks.length} tasks):\n${context.pendingTasks.map((task, index) => `${index + 1}. [${task.id}] ${task.content}`).join('\\n')}\n\nCRITICAL: You must complete ALL of these remaining ${context.pendingTasks.length} tasks. Use taskManager with action 'list' to check current status and action 'update' to mark tasks as completed.\n\n${context.resumeData ? `USER PROVIDED ANSWERS: ${JSON.stringify(context.resumeData.answers, null, 2)}` : ''}`,\n },\n\n validation: {\n instructions: `CRITICAL VALIDATION INSTRUCTIONS:\n- When using the validateCode tool, ALWAYS pass the specific files you created or modified using the 'files' parameter\n- The tool uses a hybrid validation approach: fast syntax checking → semantic type checking → ESLint\n- This is much faster than full project compilation and only shows errors from your specific files\n- Example: validateCode({ validationType: ['types', 'lint'], files: ['src/workflows/my-workflow.ts', 'src/agents/my-agent.ts'] })\n- ALWAYS validate after creating or modifying files to ensure they compile correctly`,\n },\n};\n","import { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\nimport { AgentBuilderDefaults } from '../../defaults';\n\n// taskManager tool that only allows updates, not creation\nexport const restrictedTaskManager = createTool({\n id: 'task-manager',\n description:\n 'View and update your pre-loaded task list. You can only mark tasks as in_progress or completed, not create new tasks.',\n inputSchema: z.object({\n action: z\n .enum(['list', 'update', 'complete'])\n .describe('List tasks, update status, or mark complete - tasks are pre-loaded'),\n tasks: z\n .array(\n z.object({\n id: z.string().describe('Task ID - must match existing task'),\n content: z.string().optional().describe('Task content (read-only)'),\n status: z.enum(['pending', 'in_progress', 'completed', 'blocked']).describe('Task status'),\n priority: z.enum(['high', 'medium', 'low']).optional().describe('Task priority (read-only)'),\n dependencies: z.array(z.string()).optional().describe('Task dependencies (read-only)'),\n notes: z.string().optional().describe('Additional notes or progress updates'),\n }),\n )\n .optional()\n .describe('Tasks to update (status and notes only)'),\n taskId: z.string().optional().describe('Specific task ID for single task operations'),\n }),\n outputSchema: z.object({\n success: z.boolean(),\n tasks: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n status: z.string(),\n priority: z.string(),\n dependencies: z.array(z.string()).optional(),\n notes: z.string().optional(),\n createdAt: z.string(),\n updatedAt: z.string(),\n }),\n ),\n message: z.string(),\n }),\n execute: async input => {\n // Convert to the expected format for manageTaskList\n const adaptedContext = {\n ...input,\n action: input.action,\n tasks: input.tasks?.map(task => ({\n ...task,\n priority: task.priority || ('medium' as const),\n })),\n };\n return await AgentBuilderDefaults.manageTaskList(adaptedContext);\n },\n});\n","import { existsSync } from 'node:fs';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { stepCountIs } from '@internal/ai-sdk-v5';\nimport { Agent } from '@mastra/core/agent';\nimport { createWorkflow, createStep } from '@mastra/core/workflows';\nimport type { z } from 'zod';\nimport { AgentBuilder } from '../../agent';\nimport { AgentBuilderDefaults } from '../../defaults';\nimport { resolveModel } from '../../utils';\nimport { planningAndApprovalWorkflow } from '../task-planning/task-planning';\nimport { workflowBuilderPrompts, workflowResearch as research } from './prompts';\nimport {\n WorkflowBuilderInputSchema,\n WorkflowBuilderResultSchema,\n WorkflowDiscoveryResultSchema,\n ProjectDiscoveryResultSchema,\n WorkflowResearchResultSchema,\n TaskExecutionResultSchema,\n TaskExecutionInputSchema,\n TaskExecutionResumeSchema,\n TaskExecutionSuspendSchema,\n TaskExecutionIterationInputSchema,\n} from './schema';\nimport type { DiscoveredWorkflowSchema } from './schema';\nimport { restrictedTaskManager } from './tools';\n\ntype WorkflowBuilderInputSchemaType = z.infer<typeof WorkflowBuilderInputSchema>;\n\n// Step 1: Always discover existing workflows\nconst workflowDiscoveryStep = createStep({\n id: 'workflow-discovery',\n description: 'Discover existing workflows in the project',\n inputSchema: WorkflowBuilderInputSchema,\n outputSchema: WorkflowDiscoveryResultSchema,\n execute: async ({ inputData, requestContext: _requestContext }) => {\n console.info('Starting workflow discovery...');\n const { projectPath = process.cwd() } = inputData;\n\n try {\n // Check if workflows directory exists\n const workflowsPath = join(projectPath, 'src/mastra/workflows');\n if (!existsSync(workflowsPath)) {\n console.info('No workflows directory found');\n return {\n success: true,\n workflows: [],\n mastraIndexExists: existsSync(join(projectPath, 'src/mastra/index.ts')),\n message: 'No existing workflows found in the project',\n };\n }\n\n // Read workflow files directly\n const workflowFiles = await readdir(workflowsPath);\n const workflows: z.infer<typeof DiscoveredWorkflowSchema>[] = [];\n\n for (const fileName of workflowFiles) {\n if (fileName.endsWith('.ts') && !fileName.endsWith('.test.ts')) {\n const filePath = join(workflowsPath, fileName);\n try {\n const content = await readFile(filePath, 'utf-8');\n\n // Extract basic workflow info\n const nameMatch = content.match(/createWorkflow\\s*\\(\\s*{\\s*id:\\s*['\"]([^'\"]+)['\"]/);\n const descMatch = content.match(/description:\\s*['\"]([^'\"]*)['\"]/);\n\n if (nameMatch && nameMatch[1]) {\n workflows.push({\n name: nameMatch[1],\n file: filePath,\n description: descMatch?.[1] ?? 'No description available',\n });\n }\n } catch (error) {\n console.warn(`Failed to read workflow file ${filePath}:`, error);\n }\n }\n }\n\n console.info(`Discovered ${workflows.length} existing workflows`);\n return {\n success: true,\n workflows,\n mastraIndexExists: existsSync(join(projectPath, 'src/mastra/index.ts')),\n message:\n workflows.length > 0\n ? `Found ${workflows.length} existing workflow(s): ${workflows.map(w => w.name).join(', ')}`\n : 'No existing workflows found in the project',\n };\n } catch (error) {\n console.error('Workflow discovery failed:', error);\n return {\n success: false,\n workflows: [],\n mastraIndexExists: false,\n message: `Workflow discovery failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Step 2: Always discover project structure\nconst projectDiscoveryStep = createStep({\n id: 'project-discovery',\n description: 'Analyze the project structure and setup',\n inputSchema: WorkflowDiscoveryResultSchema,\n outputSchema: ProjectDiscoveryResultSchema,\n execute: async ({ inputData: _inputData, requestContext: _requestContext }) => {\n console.info('Starting project discovery...');\n\n try {\n // Get project structure - no need for AgentBuilder since we're just checking files\n const projectPath = process.cwd(); // Use current working directory as default\n const projectStructure = {\n hasPackageJson: existsSync(join(projectPath, 'package.json')),\n hasMastraConfig:\n existsSync(join(projectPath, 'mastra.config.js')) || existsSync(join(projectPath, 'mastra.config.ts')),\n hasSrcDirectory: existsSync(join(projectPath, 'src')),\n hasMastraDirectory: existsSync(join(projectPath, 'src/mastra')),\n hasWorkflowsDirectory: existsSync(join(projectPath, 'src/mastra/workflows')),\n hasToolsDirectory: existsSync(join(projectPath, 'src/mastra/tools')),\n hasAgentsDirectory: existsSync(join(projectPath, 'src/mastra/agents')),\n };\n\n // Read package.json if it exists\n let packageInfo = null;\n if (projectStructure.hasPackageJson) {\n try {\n const packageContent = await readFile(join(projectPath, 'package.json'), 'utf-8');\n packageInfo = JSON.parse(packageContent);\n } catch (error) {\n console.warn('Failed to read package.json:', error);\n }\n }\n\n console.info('Project discovery completed');\n return {\n success: true,\n structure: {\n hasWorkflowsDir: projectStructure.hasWorkflowsDirectory,\n hasAgentsDir: projectStructure.hasAgentsDirectory,\n hasToolsDir: projectStructure.hasToolsDirectory,\n hasMastraIndex: existsSync(join(projectPath, 'src/mastra/index.ts')),\n existingWorkflows: [],\n existingAgents: [],\n existingTools: [],\n },\n dependencies: packageInfo?.dependencies || {},\n message: 'Project discovery completed successfully',\n };\n } catch (error) {\n console.error('Project discovery failed:', error);\n return {\n success: false,\n structure: {\n hasWorkflowsDir: false,\n hasAgentsDir: false,\n hasToolsDir: false,\n hasMastraIndex: false,\n existingWorkflows: [],\n existingAgents: [],\n existingTools: [],\n },\n dependencies: {},\n message: 'Project discovery failed',\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\ntype WorkflowResearchResult = z.infer<typeof WorkflowResearchResultSchema>;\n\n// Step 3: Research what is needed to be done\nconst workflowResearchStep = createStep({\n id: 'workflow-research',\n description: 'Research Mastra workflows and gather relevant documentation',\n inputSchema: ProjectDiscoveryResultSchema,\n outputSchema: WorkflowResearchResultSchema,\n execute: async ({ inputData, requestContext }) => {\n console.info('Starting workflow research...');\n\n try {\n // const filteredMcpTools = await initializeMcpTools();\n\n const model = await resolveModel({ requestContext });\n\n const researchAgent = new Agent({\n id: 'workflow-research-agent',\n model,\n instructions: workflowBuilderPrompts.researchAgent.instructions,\n name: 'Workflow Research Agent',\n // tools: filteredMcpTools,\n });\n\n const researchPrompt = workflowBuilderPrompts.researchAgent.prompt({\n projectStructure: inputData.structure,\n dependencies: inputData.dependencies,\n hasWorkflowsDir: inputData.structure.hasWorkflowsDir,\n });\n\n const result = await researchAgent.generate(researchPrompt, {\n structuredOutput: {\n schema: WorkflowResearchResultSchema,\n },\n // stopWhen: stepCountIs(10),\n });\n\n const researchResult = (await result.object) as unknown as WorkflowResearchResult | null;\n if (!researchResult) {\n return {\n success: false,\n documentation: {\n workflowPatterns: [],\n stepExamples: [],\n bestPractices: [],\n },\n webResources: [],\n message: 'Research agent failed to generate valid response',\n error: 'Research agent failed to generate valid response',\n };\n }\n\n console.info('Research completed successfully');\n return {\n success: true,\n documentation: {\n workflowPatterns: researchResult.documentation.workflowPatterns,\n stepExamples: researchResult.documentation.stepExamples,\n bestPractices: researchResult.documentation.bestPractices,\n },\n webResources: researchResult.webResources,\n message: 'Research completed successfully',\n };\n } catch (error) {\n console.error('Workflow research failed:', error);\n return {\n success: false,\n documentation: {\n workflowPatterns: [],\n stepExamples: [],\n bestPractices: [],\n },\n webResources: [],\n message: 'Research failed',\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Task execution step remains the same\nconst taskExecutionStep = createStep({\n id: 'task-execution',\n description: 'Execute the approved task list to create or edit the workflow',\n inputSchema: TaskExecutionInputSchema,\n outputSchema: TaskExecutionResultSchema,\n suspendSchema: TaskExecutionSuspendSchema,\n resumeSchema: TaskExecutionResumeSchema,\n execute: async ({ inputData, resumeData, suspend, requestContext }) => {\n const {\n action,\n workflowName,\n description: _description,\n requirements: _requirements,\n tasks,\n discoveredWorkflows,\n projectStructure,\n research,\n projectPath,\n } = inputData;\n\n console.info(`Starting task execution for ${action}ing workflow: ${workflowName}`);\n console.info(`Executing ${tasks.length} tasks using AgentBuilder stream...`);\n\n try {\n const model = await resolveModel({ requestContext });\n const currentProjectPath = projectPath || process.cwd();\n\n // Pre-populate taskManager with the planned tasks\n console.info('Pre-populating taskManager with planned tasks...');\n const taskManagerContext = {\n action: 'create' as const,\n tasks: tasks.map(task => ({\n id: task.id,\n content: task.content,\n status: 'pending' as const,\n priority: task.priority,\n dependencies: task.dependencies,\n notes: task.notes,\n })),\n };\n\n const taskManagerResult = await AgentBuilderDefaults.manageTaskList(taskManagerContext);\n console.info(`Task manager initialized with ${taskManagerResult.tasks.length} tasks`);\n\n if (!taskManagerResult.success) {\n throw new Error(`Failed to initialize task manager: ${taskManagerResult.message}`);\n }\n\n const executionAgent = new AgentBuilder({\n projectPath: currentProjectPath,\n model,\n tools: {\n 'task-manager': restrictedTaskManager,\n },\n instructions: `${workflowBuilderPrompts.executionAgent.instructions({\n action,\n workflowName,\n tasksLength: tasks.length,\n currentProjectPath,\n discoveredWorkflows,\n projectStructure,\n research,\n tasks,\n resumeData,\n })}\n\n${workflowBuilderPrompts.validation.instructions}`,\n });\n\n const executionPrompt = workflowBuilderPrompts.executionAgent.prompt({\n action,\n workflowName,\n tasks,\n resumeData,\n });\n\n const originalInstructions = await executionAgent.getInstructions({ requestContext: requestContext });\n\n const enhancedOptions = {\n stopWhen: stepCountIs(100),\n temperature: 0.3,\n instructions: originalInstructions,\n };\n\n // Loop until all tasks are completed\n let finalResult: any = null;\n let allTasksCompleted = false;\n let iterationCount = 0;\n const maxIterations = 5;\n\n const expectedTaskIds = tasks.map(task => task.id);\n\n while (!allTasksCompleted && iterationCount < maxIterations) {\n iterationCount++;\n\n const currentTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: 'list' });\n const completedTasks = currentTaskStatus.tasks.filter(task => task.status === 'completed');\n const pendingTasks = currentTaskStatus.tasks.filter(task => task.status !== 'completed');\n\n console.info(`\\n=== EXECUTION ITERATION ${iterationCount} ===`);\n console.info(`Completed tasks: ${completedTasks.length}/${expectedTaskIds.length}`);\n console.info(`Remaining tasks: ${pendingTasks.map(t => t.id).join(', ')}`);\n\n // Check if all tasks are completed\n allTasksCompleted = pendingTasks.length === 0;\n\n if (allTasksCompleted) {\n console.info('All tasks completed! Breaking execution loop.');\n break;\n }\n\n // Create prompt for this iteration\n const iterationPrompt =\n iterationCount === 1\n ? executionPrompt\n : `${workflowBuilderPrompts.executionAgent.iterationPrompt({\n completedTasks,\n pendingTasks,\n workflowName,\n resumeData,\n })}\n\n${workflowBuilderPrompts.validation.instructions}`;\n\n const stream = await executionAgent.stream(iterationPrompt, {\n structuredOutput: {\n schema: TaskExecutionIterationInputSchema(tasks.length),\n model,\n },\n ...enhancedOptions,\n });\n\n let finalMessage = '';\n for await (const chunk of stream.fullStream) {\n if (chunk.type === 'text-delta') {\n finalMessage += chunk.payload.text;\n }\n\n if (chunk.type === 'step-finish') {\n console.info(finalMessage);\n finalMessage = '';\n }\n\n if (chunk.type === 'tool-result') {\n console.info(JSON.stringify(chunk, null, 2));\n }\n\n if (chunk.type === 'finish') {\n console.info(chunk);\n }\n }\n\n await stream.consumeStream();\n finalResult = await stream.object;\n\n console.info(`Iteration ${iterationCount} result:`, { finalResult });\n\n if (!finalResult) {\n throw new Error(`No result received from agent execution on iteration ${iterationCount}`);\n }\n\n const postIterationTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: 'list' });\n const postCompletedTasks = postIterationTaskStatus.tasks.filter(task => task.status === 'completed');\n const postPendingTasks = postIterationTaskStatus.tasks.filter(task => task.status !== 'completed');\n\n allTasksCompleted = postPendingTasks.length === 0;\n\n console.info(\n `After iteration ${iterationCount}: ${postCompletedTasks.length}/${expectedTaskIds.length} tasks completed in taskManager`,\n );\n\n // If agent needs clarification, break out and suspend\n if (finalResult.status === 'needs_clarification' && finalResult.questions && finalResult.questions.length > 0) {\n console.info(\n `Agent needs clarification on iteration ${iterationCount}: ${finalResult.questions.length} questions`,\n );\n break;\n }\n\n // If agent claims completed but taskManager shows pending tasks, continue loop\n if (finalResult.status === 'completed' && !allTasksCompleted) {\n console.info(\n `Agent claimed completion but taskManager shows pending tasks: ${postPendingTasks.map(t => t.id).join(', ')}`,\n );\n // Continue to next iteration\n }\n }\n\n if (iterationCount >= maxIterations && !allTasksCompleted) {\n finalResult.error = `Maximum iterations (${maxIterations}) reached but not all tasks completed`;\n finalResult.status = 'in_progress';\n }\n\n if (!finalResult) {\n throw new Error('No result received from agent execution');\n }\n\n // If the agent needs clarification, suspend the workflow\n if (finalResult.status === 'needs_clarification' && finalResult.questions && finalResult.questions.length > 0) {\n console.info(`Agent needs clarification: ${finalResult.questions.length} questions`);\n\n console.info('finalResult', JSON.stringify(finalResult, null, 2));\n return suspend({\n questions: finalResult.questions,\n currentProgress: finalResult.progress,\n completedTasks: finalResult.completedTasks || [],\n message: finalResult.message,\n });\n }\n\n const finalTaskStatus = await AgentBuilderDefaults.manageTaskList({ action: 'list' });\n const finalCompletedTasks = finalTaskStatus.tasks.filter(task => task.status === 'completed');\n const finalPendingTasks = finalTaskStatus.tasks.filter(task => task.status !== 'completed');\n\n const tasksCompleted = finalCompletedTasks.length;\n const tasksExpected = expectedTaskIds.length;\n const finalAllTasksCompleted = finalPendingTasks.length === 0;\n\n const success = finalAllTasksCompleted && !finalResult.error;\n const message = success\n ? `Successfully completed workflow ${action} - all ${tasksExpected} tasks completed after ${iterationCount} iteration(s): ${finalResult.message}`\n : `Workflow execution finished with issues after ${iterationCount} iteration(s): ${finalResult.message}. Completed: ${tasksCompleted}/${tasksExpected} tasks`;\n\n console.info(message);\n\n const missingTasks = finalPendingTasks.map(task => task.id);\n const validationErrors = [];\n\n if (finalResult.error) {\n validationErrors.push(finalResult.error);\n }\n\n if (!finalAllTasksCompleted) {\n validationErrors.push(\n `Incomplete tasks: ${missingTasks.join(', ')} (${tasksCompleted}/${tasksExpected} completed)`,\n );\n }\n\n return {\n success,\n completedTasks: finalCompletedTasks.map(task => task.id),\n filesModified: finalResult.filesModified || [],\n validationResults: {\n passed: success,\n errors: validationErrors,\n warnings: finalAllTasksCompleted ? [] : [`Missing ${missingTasks.length} tasks: ${missingTasks.join(', ')}`],\n },\n message,\n error: finalResult.error,\n };\n } catch (error) {\n console.error('Task execution failed:', error);\n return {\n success: false,\n completedTasks: [],\n filesModified: [],\n validationResults: {\n passed: false,\n errors: [`Task execution failed: ${error instanceof Error ? error.message : String(error)}`],\n warnings: [],\n },\n message: `Task execution failed: ${error instanceof Error ? error.message : String(error)}`,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n});\n\n// Main Workflow Builder Workflow\nexport const workflowBuilderWorkflow = createWorkflow({\n id: 'workflow-builder',\n description: 'Create or edit Mastra workflows using AI-powered assistance with iterative planning',\n inputSchema: WorkflowBuilderInputSchema,\n outputSchema: WorkflowBuilderResultSchema,\n steps: [\n workflowDiscoveryStep,\n projectDiscoveryStep,\n workflowResearchStep,\n planningAndApprovalWorkflow,\n taskExecutionStep,\n ],\n})\n // Step 1: Always discover existing workflows\n .then(workflowDiscoveryStep)\n // Step 2: Always discover project structure\n .then(projectDiscoveryStep)\n // Step 3: Research workflows and documentation\n .then(workflowResearchStep)\n // Map research result to planning input format\n .map(async ({ getStepResult, getInitData }) => {\n const initData = getInitData<WorkflowBuilderInputSchemaType>();\n const discoveryResult = getStepResult(workflowDiscoveryStep);\n const projectResult = getStepResult(projectDiscoveryStep);\n // const researchResult = getStepResult(workflowResearchStep);\n\n return {\n action: initData.action,\n workflowName: initData.workflowName,\n description: initData.description,\n requirements: initData.requirements,\n discoveredWorkflows: discoveryResult.workflows,\n projectStructure: projectResult,\n // research: researchResult,\n research,\n\n userAnswers: undefined,\n };\n })\n // Step 4: Planning and Approval Sub-workflow (loops until approved)\n .dountil(planningAndApprovalWorkflow, async ({ inputData }) => {\n // Continue looping until user approves the task list\n console.info(`Sub-workflow check: approved=${inputData.approved}`);\n return inputData.approved === true;\n })\n // Map sub-workflow result to task execution input\n .map(async ({ getStepResult, getInitData }) => {\n const initData = getInitData<WorkflowBuilderInputSchemaType>();\n const discoveryResult = getStepResult(workflowDiscoveryStep);\n const projectResult = getStepResult(projectDiscoveryStep);\n // const researchResult = getStepResult(workflowResearchStep);\n const subWorkflowResult = getStepResult(planningAndApprovalWorkflow);\n\n return {\n action: initData.action,\n workflowName: initData.workflowName,\n description: initData.description,\n requirements: initData.requirements,\n tasks: subWorkflowResult.tasks,\n discoveredWorkflows: discoveryResult.workflows,\n projectStructure: projectResult,\n // research: researchResult,\n research,\n projectPath: initData.projectPath || process.cwd(),\n };\n })\n // Step 5: Execute the approved tasks\n .then(taskExecutionStep)\n .commit();\n","import type { Workflow } from '@mastra/core/workflows';\nimport { agentBuilderTemplateWorkflow } from './template-builder/template-builder';\nimport { workflowBuilderWorkflow } from './workflow-builder/workflow-builder';\n\nexport const agentBuilderWorkflows: Record<string, Workflow<any, any, any, any, any, any>> = {\n 'merge-template': agentBuilderTemplateWorkflow,\n 'workflow-builder': workflowBuilderWorkflow,\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAa,aAAa;CAAC;CAAc;CAAQ;CAAY;CAAS;CAAe;CAAW;AAAO;AA0BvG,MAAa,qBAAqB,EAAE,OAAO;CACzC,MAAM,EAAE,KAAK,UAAU;CACvB,IAAI,EAAE,OAAO;CACb,MAAM,EAAE,OAAO;AACjB,CAAC;AAEqC,EAAE,OAAO;CAC7C,MAAM,EAAE,OAAO;CACf,KAAK,EAAE,OAAO,CAAC,CAAC,SAAS;CACzB,aAAa,EAAE,OAAO,CAAC,CAAC,SAAS;CACjC,OAAO,EAAE,MAAM,kBAAkB;AACnC,CAAC;AAED,MAAa,0BAA0B,EAAE,OAAO;CAC9C,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,4CAA4C;CACtE,KAAK,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CAC7F,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CAC9F,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,2DAA2D;CACtG,WAAW,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,2CAA2C;AAC7G,CAAC;AAE8B,EAAE,OAAO;CACtC,MAAM,EAAE,OAAO;CACf,WAAW,EAAE,OAAO;CACpB,aAAa,EAAE,OAAO;CACtB,OAAO,EAAE,MAAM,kBAAkB;AACnC,CAAC;AAGD,MAAa,mBAAmB,EAAE,OAAO;CACvC,QAAQ,EAAE,OAAO;CACjB,aAAa,EAAE,OAAO;CACtB,MAAM,EAAE,OAAO;EACb,MAAM,EAAE,KAAK,UAAU;EACvB,IAAI,EAAE,OAAO;CACf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