@juspay/neurolink 12.2.0 → 12.2.2
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 +3 -3
- package/dist/browser/neurolink.min.js +3 -3
- package/dist/constants/enums.d.ts +7 -11
- package/dist/constants/enums.js +6 -10
- package/dist/factories/providerDescriptors.js +1 -1
- package/dist/providers/openaiChatCompletionsClient.js +6 -1
- package/dist/providers/openaiCompatCatalog.js +4 -9
- package/dist/utils/modelChoices.js +4 -9
- package/package.json +1 -1
|
@@ -11,7 +11,7 @@ Add to your .env file:
|
|
|
11
11
|
${e.envVarName}=your_key_here
|
|
12
12
|
|
|
13
13
|
\u{1F527} Step 3: Restart Application
|
|
14
|
-
Restart your application to load the new environment variables.`}function zi(e,t){return process.env[e]||t}function kF(e,t){return e?e.some(r=>typeof r=="string"?!!t[r]:r.every(n=>!!t[n])):!1}function gcr(){const e=Ucr(),t=Bcr(),r=["\u{1F511} Option 1: API Key Authentication (Recommended for developers)","1. Visit: https://console.anthropic.com/","2. Sign in or create an account","3. Go to API Keys section","4. Create a new API key","5. Set ANTHROPIC_API_KEY in your .env file"],n=["","\u{1F510} Option 2: OAuth Authentication (For Claude Pro/Max subscribers)","1. Set ANTHROPIC_AUTH_METHOD=oauth in your .env file","2. Set ANTHROPIC_SUBSCRIPTION_TIER to your tier (free, pro, max)","3. Run the OAuth flow to obtain tokens, or set pre-configured tokens:"," - ANTHROPIC_OAUTH_TOKEN=your_access_token"," - ANTHROPIC_OAUTH_REFRESH_TOKEN=your_refresh_token (optional)","","\u{1F4CB} Available Subscription Tiers:"," - free: Free tier with limited usage"," - pro: Claude Pro ($20/month) - Extended usage limits"," - max: Claude Max - Highest usage limits"," - api: API-based access (pay-per-use)"],o=e==="oauth"?[...n.slice(1),"",...r]:[...r,...n];return{providerName:"Anthropic",envVarName:e==="oauth"?"ANTHROPIC_OAUTH_TOKEN":"ANTHROPIC_API_KEY",setupUrl:e==="oauth"?"https://claude.ai/settings":"https://console.anthropic.com/",description:e==="oauth"?`Anthropic OAuth Token (${t} tier)`:"Anthropic API Key",instructions:o,fallbackEnvVars:e==="oauth"?["ANTHROPIC_API_KEY"]:["ANTHROPIC_OAUTH_TOKEN","CLAUDE_OAUTH_TOKEN","ANTHROPIC_OAUTH_ACCESS_TOKEN"]}}function ycr(){return{providerName:"OPENAI",envVarName:"OPENAI_API_KEY",setupUrl:"https://platform.openai.com/api-keys",description:"Credentials",instructions:["1. Visit: https://platform.openai.com/api-keys","2. Create new API key","3. Copy the key"]}}function vcr(){return{providerName:"HuggingFace",envVarName:"HUGGINGFACE_API_KEY",setupUrl:"https://huggingface.co/settings/tokens",description:"Credentials",instructions:["1. Visit: https://huggingface.co/settings/tokens","2. Create new API token","3. Copy the token"],fallbackEnvVars:["HF_TOKEN"]}}function _cr(){return{providerName:"Mistral",envVarName:"MISTRAL_API_KEY",setupUrl:"https://console.mistral.ai/",description:"API key",instructions:["1. Visit: https://console.mistral.ai/","2. Create or sign in to your account","3. Generate a new API key"]}}function wcr(){return{providerName:"Azure OpenAI",envVarName:"AZURE_OPENAI_API_KEY",setupUrl:"https://portal.azure.com/",description:"Azure OpenAI API Key",instructions:["1. Visit: https://portal.azure.com/","2. Create or access Azure OpenAI resource","3. Get API key from Keys and Endpoint section"]}}function bcr(){return{providerName:"Azure OpenAI",envVarName:"AZURE_OPENAI_ENDPOINT",setupUrl:"https://portal.azure.com/",description:"Azure OpenAI Endpoint",instructions:["1. Visit: https://portal.azure.com/","2. Access your Azure OpenAI resource","3. Copy endpoint URL from Keys and Endpoint section"]}}function Tcr(){return{providerName:"DeepSeek",envVarName:"DEEPSEEK_API_KEY",setupUrl:"https://platform.deepseek.com/api_keys",description:"API key",instructions:["1. Visit: https://platform.deepseek.com/api_keys","2. Create or sign in to your DeepSeek account","3. Generate a new API key","4. Set DEEPSEEK_API_KEY in your .env file"]}}function Ecr(){return{providerName:"NVIDIA NIM",envVarName:"NVIDIA_NIM_API_KEY",setupUrl:"https://build.nvidia.com/settings/api-keys",description:"API key",instructions:["1. Visit: https://build.nvidia.com/","2. Sign in with your NVIDIA developer account","3. Open Settings \u2192 API Keys","4. Generate a new API key (Bearer token)","5. Set NVIDIA_NIM_API_KEY in your .env file"]}}function Scr(){return{providerName:"xAI",envVarName:"XAI_API_KEY",setupUrl:"https://console.x.ai/",description:"API key",instructions:["1. Visit: https://console.x.ai/","2. Sign in with your xAI account","3. Create an API key","4. Set XAI_API_KEY in your .env file"]}}function Ccr(){return{providerName:"Cerebras",envVarName:"CEREBRAS_API_KEY",setupUrl:"https://cloud.cerebras.ai",description:"API key",instructions:["1. Visit: https://cloud.cerebras.ai","2. Sign in or create a free Cerebras account","3. Create an API key under API Keys","4. Set CEREBRAS_API_KEY in your .env file"]}}function kcr(){return{providerName:"Groq",envVarName:"GROQ_API_KEY",setupUrl:"https://console.groq.com/keys",description:"API key",instructions:["1. Visit: https://console.groq.com/keys","2. Sign in to your Groq account","3. Create a new API key","4. Set GROQ_API_KEY in your .env file"]}}function xcr(){return{providerName:"Cohere",envVarName:"COHERE_API_KEY",setupUrl:"https://dashboard.cohere.com/api-keys",description:"API key",instructions:["1. Visit: https://dashboard.cohere.com/api-keys","2. Sign in to your Cohere account","3. Create a new API key","4. Set COHERE_API_KEY in your .env file"]}}function Acr(){return{providerName:"Replicate",envVarName:"REPLICATE_API_TOKEN",setupUrl:"https://replicate.com/account/api-tokens",description:"API token",instructions:["1. Visit: https://replicate.com/account/api-tokens","2. Sign in to your Replicate account","3. Create a new API token","4. Set REPLICATE_API_TOKEN in your .env file"]}}function Icr(){return{providerName:"Together AI",envVarName:"TOGETHER_API_KEY",setupUrl:"https://api.together.xyz/settings/api-keys",description:"API key",instructions:["1. Visit: https://api.together.xyz/settings/api-keys","2. Sign in to your Together AI account","3. Create a new API key","4. Set TOGETHER_API_KEY in your .env file"]}}function Rcr(){return{providerName:"Fireworks AI",envVarName:"FIREWORKS_API_KEY",setupUrl:"https://fireworks.ai/account/api-keys",description:"API key",instructions:["1. Visit: https://fireworks.ai/account/api-keys","2. Sign in to your Fireworks AI account","3. Create a new API key","4. Set FIREWORKS_API_KEY in your .env file"]}}function Pcr(){return{providerName:"Perplexity",envVarName:"PERPLEXITY_API_KEY",setupUrl:"https://www.perplexity.ai/settings/api",description:"API key",instructions:["1. Visit: https://www.perplexity.ai/settings/api","2. Sign in to your Perplexity account","3. Create a new API key (Sonar tier)","4. Set PERPLEXITY_API_KEY in your .env file"]}}function Mcr(){return{providerName:"Voyage AI",envVarName:"VOYAGE_API_KEY",setupUrl:"https://dash.voyageai.com/api-keys",description:"API key",instructions:["1. Visit: https://dash.voyageai.com/api-keys","2. Sign in to your Voyage AI account","3. Create a new API key","4. Set VOYAGE_API_KEY in your .env file"]}}function Dcr(){return{providerName:"Jina AI",envVarName:"JINA_API_KEY",setupUrl:"https://jina.ai/?sui=apikey",description:"API key",instructions:["1. Visit: https://jina.ai/?sui=apikey","2. Sign in / create account","3. Copy your API key","4. Set JINA_API_KEY in your .env file"]}}function Ocr(){return{providerName:"Ideogram",envVarName:"IDEOGRAM_API_KEY",setupUrl:"https://developer.ideogram.ai/",description:"API key",instructions:["1. Visit: https://developer.ideogram.ai/","2. Sign in / create account","3. Generate a new API key","4. Set IDEOGRAM_API_KEY in your .env file"]}}function Ncr(){return{providerName:"Recraft",envVarName:"RECRAFT_API_KEY",setupUrl:"https://www.recraft.ai/api",description:"API token",instructions:["1. Visit: https://www.recraft.ai/api","2. Sign in / create account","3. Create an API token","4. Set RECRAFT_API_KEY in your .env file"]}}function Lcr(){return{providerName:"Cloudflare Workers AI",envVarName:"CLOUDFLARE_API_KEY",setupUrl:"https://dash.cloudflare.com/profile/api-tokens",description:"API token (Workers AI Read+Write scope)",instructions:["1. Visit: https://dash.cloudflare.com/profile/api-tokens","2. Create a token with 'Workers AI: Read + Write' scope","3. Set CLOUDFLARE_API_KEY in your .env file","4. Also set CLOUDFLARE_ACCOUNT_ID (find it in the dashboard URL or under 'Account ID')"]}}function $cr(){return{providerName:"Google Vertex AI",envVarName:"GOOGLE_CLOUD_PROJECT_ID",setupUrl:"https://console.cloud.google.com/",description:"Google Cloud Credentials",instructions:["1. Visit: https://console.cloud.google.com/","2. Create or select a project","3. Enable Vertex AI API","4. Set up authentication"],fallbackEnvVars:["VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"]}}function Fcr(){return{providerName:"Google Vertex AI",envVarName:"GOOGLE_APPLICATION_CREDENTIALS",setupUrl:"https://console.cloud.google.com/",description:"Google Cloud authentication",instructions:["\u{1F527} Option 1: Service Account Key File","GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json","","\u{1F527} Option 2: Service Account Key (Base64)","GOOGLE_SERVICE_ACCOUNT_KEY=base64_encoded_key","","\u{1F527} Option 3: Individual Credentials","GOOGLE_AUTH_CLIENT_EMAIL=your-service-account@project.iam.gserviceaccount.com","GOOGLE_AUTH_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----..."],fallbackEnvVars:["GOOGLE_SERVICE_ACCOUNT_KEY"]}}function Ucr(){return process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase()==="oauth"?"oauth":"api_key"}function Bcr(){switch(process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase()){case"free":return"free";case"pro":return"pro";case"max":return"max";case"max_5":return"max_5";case"max_20":return"max_20";default:return"api"}}function zcr(e,t){const r=t?.apiKey?.trim(),n=r&&r.length>0?r:Bi(e.configOptions);if(e.computedBaseURL){const{envVar:a,missingValueMessage:l,build:c}=e.computedBaseURL,u=t?.baseURL?.trim();if(u&&u.length>0)return{apiKey:n,baseURL:u};const d=(t?.accountId??process.env[a]??"").trim();if(!d)throw new Error(l);return{apiKey:n,baseURL:c(d)}}const o=t?.baseURL?.trim(),s=e.baseURLEnvVar?process.env[e.baseURLEnvVar]?.trim():void 0,i=(o&&o.length>0?o:void 0)??(s&&s.length>0?s:void 0)??e.defaultBaseURL;if(!i)throw new Error(`${e.providerName}: no base URL. Set one in credentials`+(e.baseURLEnvVar?`, set ${e.baseURLEnvVar}`:"")+", or give the catalog entry a defaultBaseURL.");return{apiKey:n,baseURL:i}}var ia,Dh,xF,Yo=S({"src/lib/utils/providerConfig.ts"(){"use strict";ia={openai:/^sk-[A-Za-z0-9]{48,}$/,anthropic:/^sk-ant-[A-Za-z0-9\-_]{95,}$/,"google-ai":/^AIza[A-Za-z0-9\-_]{35}$/,huggingface:/^hf_[A-Za-z0-9]{37}$/,mistral:/^[A-Za-z0-9]{32}$/,azure:/^[A-Za-z0-9]{32}$/,aws:/^[A-Z0-9]{20}$/,bedrock:/^[A-Z0-9]{20}$/},Dh={OPENAI_MIN:48,ANTHROPIC_MIN:95,HUGGINGFACE_EXACT:37,AZURE_MIN:32,MISTRAL_EXACT:32,AWS_ACCESS_KEY:20,GOOGLE_AI_EXACT:39},xF={MIN_LENGTH:6,MAX_LENGTH:30,PATTERN:/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/}}}),Cd,Zr,WA,By=S({"src/lib/factories/providerDescriptors.ts"(){"use strict";Yo(),Cd=[{name:"bedrock",defaultHealthSweepPriority:5,autoSelectPreference:7,aliases:["aws"],credentialsKey:"bedrock",envVars:{apiKey:"AWS_ACCESS_KEY_ID",extraRequired:["AWS_SECRET_ACCESS_KEY"],model:"BEDROCK_MODEL"},defaultModel:"",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.aws.amazon.com/iam/",timeouts:{generateMs:45e3,streamMs:12e4},autoSelectPriority:7,apiKeyFormatPattern:ia.bedrock,credentialsResolvedExternally:!0},{name:"openai",defaultHealthSweepPriority:4,autoSelectPreference:3,aliases:["gpt","chatgpt"],credentialsKey:"openai",envVars:{apiKey:"OPENAI_API_KEY",baseURL:"OPENAI_BASE_URL"},defaultModel:"gpt-4o-mini",toolSupport:"native",localRuntime:!1,healthCheck:"models-probe",setupUrl:"https://platform.openai.com/api-keys",timeouts:{generateMs:3e4,streamMs:12e4},autoSelectPriority:5,apiKeyFormatPattern:ia.openai},{name:"openai-compatible",aliases:["vllm","compatible"],credentialsKey:"openaiCompatible",envVars:{apiKey:"OPENAI_COMPATIBLE_API_KEY",baseURL:"OPENAI_COMPATIBLE_BASE_URL",model:"OPENAI_COMPATIBLE_MODEL"},defaultModel:"",toolSupport:"native",localRuntime:!1,healthCheck:"env-only"},{name:"openrouter",aliases:["or"],credentialsKey:"openrouter",envVars:{apiKey:"OPENROUTER_API_KEY",baseURL:"OPENROUTER_BASE_URL",model:"OPENROUTER_MODEL"},defaultModel:"anthropic/claude-sonnet-4.5",toolSupport:"model-dependent",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://openrouter.ai/keys"},{name:"vertex",defaultHealthSweepPriority:1,autoSelectPreference:5,aliases:["googleVertex"],credentialsKey:"vertex",envVars:{apiKey:"GOOGLE_CLOUD_PROJECT_ID",fallbacks:["VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"],extraRequired:["GOOGLE_APPLICATION_CREDENTIALS"],extraRequiredFallbacks:["GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK","GOOGLE_SERVICE_ACCOUNT_KEY",["GOOGLE_AUTH_CLIENT_EMAIL","GOOGLE_AUTH_PRIVATE_KEY"]]},defaultModel:"claude-sonnet-4-6",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.cloud.google.com/",timeouts:{generateMs:6e4,streamMs:12e4},autoSelectPriority:3,credentialsResolvedExternally:!0},{name:"anthropic",defaultHealthSweepPriority:3,autoSelectPreference:4,aliases:["claude"],credentialsKey:"anthropic",envVars:{apiKey:"ANTHROPIC_API_KEY",fallbacks:["ANTHROPIC_OAUTH_TOKEN","CLAUDE_OAUTH_TOKEN","ANTHROPIC_OAUTH_ACCESS_TOKEN"],baseURL:"ANTHROPIC_BASE_URL"},defaultModel:"claude-sonnet-4-6",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.anthropic.com/settings/keys",timeouts:{generateMs:6e4,streamMs:12e4},autoSelectPriority:6,apiKeyFormatPattern:ia.anthropic},{name:"azure",defaultHealthSweepPriority:6,autoSelectPreference:8,aliases:["azureOpenai"],credentialsKey:"azure",envVars:{apiKey:"AZURE_OPENAI_API_KEY",extraRequired:["AZURE_OPENAI_ENDPOINT"],model:"AZURE_MODEL",modelFallbacks:["AZURE_OPENAI_MODEL","AZURE_OPENAI_DEPLOYMENT","AZURE_OPENAI_DEPLOYMENT_ID"]},defaultModel:"gpt-4o-mini",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://portal.azure.com/",timeouts:{generateMs:3e4,streamMs:12e4},autoSelectPriority:8,apiKeyFormatPattern:ia.azure},{name:"google-ai",defaultHealthSweepPriority:2,autoSelectPreference:6,aliases:["googleAiStudio","google","gemini","google-ai-studio"],credentialsKey:"googleAiStudio",envVars:{apiKey:"GOOGLE_AI_API_KEY",fallbacks:["GOOGLE_GENERATIVE_AI_API_KEY"],baseURL:"GOOGLE_AI_BASE_URL"},defaultModel:"gemini-2.5-flash",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://aistudio.google.com/apikey",timeouts:{generateMs:3e4,streamMs:12e4},autoSelectPriority:4,apiKeyFormatPattern:ia["google-ai"]},{name:"huggingface",aliases:["hf"],credentialsKey:"huggingFace",envVars:{apiKey:"HUGGINGFACE_API_KEY",fallbacks:["HF_TOKEN"],baseURL:"HUGGINGFACE_BASE_URL",model:"HUGGINGFACE_MODEL"},defaultModel:"Qwen/Qwen2.5-72B-Instruct",toolSupport:"model-dependent",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://huggingface.co/settings/tokens",timeouts:{generateMs:12e4,streamMs:12e4},autoSelectPriority:10,apiKeyFormatPattern:ia.huggingface},{name:"ollama",defaultHealthSweepPriority:8,autoSelectPreference:2,aliases:["local"],credentialsKey:"ollama",envVars:{baseURL:"OLLAMA_BASE_URL",baseURLFallbacks:["OLLAMA_API_BASE"],model:"OLLAMA_MODEL",optional:!0},defaultModel:"llama3.2:latest",toolSupport:"model-dependent",localRuntime:!0,healthCheck:"models-probe",setupUrl:"https://ollama.com/download",timeouts:{generateMs:3e5,streamMs:12e4},autoSelectPriority:2},{name:"mistral",aliases:[],credentialsKey:"mistral",envVars:{apiKey:"MISTRAL_API_KEY",baseURL:"MISTRAL_BASE_URL"},defaultModel:"mistral-large-latest",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.mistral.ai/api-keys",timeouts:{generateMs:45e3,streamMs:12e4},autoSelectPriority:9,apiKeyFormatPattern:ia.mistral},{name:"litellm",defaultHealthSweepPriority:7,autoSelectPreference:1,aliases:[],credentialsKey:"litellm",envVars:{apiKey:"LITELLM_API_KEY",baseURL:"LITELLM_BASE_URL",model:"LITELLM_MODEL",optional:!0},defaultModel:"openai/gpt-4o-mini",toolSupport:"native",localRuntime:!1,healthCheck:"models-probe",setupUrl:"https://docs.litellm.ai/docs/proxy/quick_start",timeouts:{generateMs:3e5,streamMs:12e4},autoSelectPriority:1,credentialsResolvedExternally:!0},{name:"sagemaker",aliases:["aws-sagemaker"],credentialsKey:"sagemaker",envVars:{apiKey:"AWS_ACCESS_KEY_ID",extraRequired:["AWS_SECRET_ACCESS_KEY"],model:"SAGEMAKER_MODEL",modelFallbacks:["SAGEMAKER_MODEL_NAME","SAGEMAKER_DEFAULT_ENDPOINT","SAGEMAKER_ENDPOINT_NAME"],baseURL:"SAGEMAKER_ENDPOINT"},defaultModel:"sagemaker-model",toolSupport:"native",localRuntime:!1,healthCheck:"live-generate",setupUrl:"https://console.aws.amazon.com/iam/",apiKeyFormatPattern:ia.aws},{name:"deepseek",aliases:["ds"],credentialsKey:"deepseek",envVars:{apiKey:"DEEPSEEK_API_KEY",baseURL:"DEEPSEEK_BASE_URL",model:"DEEPSEEK_MODEL"},defaultModel:"deepseek-chat",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://platform.deepseek.com/api_keys"},{name:"nvidia-nim",aliases:["nvidia","nim"],credentialsKey:"nvidiaNim",envVars:{apiKey:"NVIDIA_NIM_API_KEY",baseURL:"NVIDIA_NIM_BASE_URL",model:"NVIDIA_NIM_MODEL"},defaultModel:"meta/llama-3.3-70b-instruct",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://build.nvidia.com/settings/api-keys"},{name:"lm-studio",aliases:["lmstudio","lms"],credentialsKey:"lmStudio",envVars:{baseURL:"LM_STUDIO_BASE_URL",model:"LM_STUDIO_MODEL",optional:!0},defaultModel:"",toolSupport:"native",localRuntime:!0,healthCheck:"env-only",setupUrl:"https://lmstudio.ai/"},{name:"llamacpp",aliases:["llama.cpp","llama-cpp"],credentialsKey:"llamacpp",envVars:{baseURL:"LLAMACPP_BASE_URL",model:"LLAMACPP_MODEL",optional:!0},defaultModel:"",toolSupport:"native",localRuntime:!0,healthCheck:"env-only",setupUrl:"https://github.com/ggerganov/llama.cpp"},{name:"xai",aliases:["grok"],credentialsKey:"xai",envVars:{apiKey:"XAI_API_KEY",baseURL:"XAI_BASE_URL",model:"XAI_MODEL"},defaultModel:"grok-3",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.x.ai/"},{name:"cerebras",aliases:[],credentialsKey:"cerebras",envVars:{apiKey:"CEREBRAS_API_KEY",baseURL:"CEREBRAS_BASE_URL",model:"CEREBRAS_MODEL"},defaultModel:"llama-3.3-70b",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://cloud.cerebras.ai"},{name:"groq",aliases:[],credentialsKey:"groq",envVars:{apiKey:"GROQ_API_KEY",baseURL:"GROQ_BASE_URL",model:"GROQ_MODEL"},defaultModel:"llama-3.3-70b-versatile",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.groq.com/keys"},{name:"cohere",aliases:[],credentialsKey:"cohere",envVars:{apiKey:"COHERE_API_KEY",baseURL:"COHERE_BASE_URL",model:"COHERE_MODEL"},defaultModel:"command-r-plus-08-2024",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://dashboard.cohere.com/api-keys"},{name:"together-ai",aliases:["together"],credentialsKey:"together",envVars:{apiKey:"TOGETHER_API_KEY",baseURL:"TOGETHER_BASE_URL",model:"TOGETHER_MODEL"},defaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://api.together.xyz/settings/api-keys"},{name:"fireworks",aliases:[],credentialsKey:"fireworks",envVars:{apiKey:"FIREWORKS_API_KEY",baseURL:"FIREWORKS_BASE_URL",model:"FIREWORKS_MODEL"},defaultModel:"accounts/fireworks/models/deepseek-v4-pro",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://fireworks.ai/account/api-keys"},{name:"perplexity",aliases:["pplx"],credentialsKey:"perplexity",envVars:{apiKey:"PERPLEXITY_API_KEY",baseURL:"PERPLEXITY_BASE_URL",model:"PERPLEXITY_MODEL"},defaultModel:"sonar",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://www.perplexity.ai/settings/api"},{name:"cloudflare",aliases:["workers-ai","cf-ai"],credentialsKey:"cloudflare",envVars:{apiKey:"CLOUDFLARE_API_KEY",extraRequired:["CLOUDFLARE_ACCOUNT_ID"],model:"CLOUDFLARE_MODEL"},defaultModel:"@cf/meta/llama-3.3-70b-instruct-fp8-fast",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://dash.cloudflare.com/profile/api-tokens"},{name:"replicate",aliases:[],credentialsKey:"replicate",envVars:{apiKey:"REPLICATE_API_TOKEN",model:"REPLICATE_MODEL"},defaultModel:"meta/meta-llama-3-70b-instruct",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://replicate.com/account/api-tokens"},{name:"voyage",aliases:["voyage-ai"],credentialsKey:"voyage",envVars:{apiKey:"VOYAGE_API_KEY",baseURL:"VOYAGE_BASE_URL",model:"VOYAGE_MODEL"},defaultModel:"voyage-3.5",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://dash.voyageai.com/api-keys"},{name:"jina",aliases:["jina-ai"],credentialsKey:"jina",envVars:{apiKey:"JINA_API_KEY",baseURL:"JINA_BASE_URL",model:"JINA_MODEL"},defaultModel:"jina-embeddings-v3",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://jina.ai/?sui=apikey"},{name:"stability",aliases:["stability-ai","sd"],credentialsKey:"stability",envVars:{apiKey:"STABILITY_API_KEY",baseURL:"STABILITY_BASE_URL",model:"STABILITY_MODEL"},defaultModel:"stable-image-ultra",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://platform.stability.ai/account/keys"},{name:"ideogram",aliases:[],credentialsKey:"ideogram",envVars:{apiKey:"IDEOGRAM_API_KEY",baseURL:"IDEOGRAM_BASE_URL",model:"IDEOGRAM_MODEL"},defaultModel:"V_3",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://developer.ideogram.ai/"},{name:"recraft",aliases:[],credentialsKey:"recraft",envVars:{apiKey:"RECRAFT_API_KEY",baseURL:"RECRAFT_BASE_URL",model:"RECRAFT_MODEL"},defaultModel:"recraftv3",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://www.recraft.ai/api"}],Zr=new Map(Cd.map(e=>[e.name,e])),WA=new Map(Cd.flatMap(e=>[[e.name.toLowerCase(),e.name],...e.aliases.map(t=>[t.toLowerCase(),e.name])]))}}),AF={};he(AF,{ProviderFactory:()=>Ur,createAIProvider:()=>jcr,resolveCredentialKey:()=>due});function due(e){const t=e.toLowerCase();return Ur.getDescriptor(t)?.credentialsKey??t}async function jcr(e,t,r){return await Ur.createProvider(e,t,void 0,void 0,r)}var Ur,aa=S({"src/lib/factories/providerFactory.ts"(){"use strict";q(),By(),Ur=class Ti{static providers=new Map;static initialized=!1;static registerProvider(t,r,n,o=[],s){const i={constructor:r,defaultModel:n,aliases:o,descriptor:s};Ti.providers.set(t.toLowerCase(),i),o.forEach(a=>{Ti.providers.set(a.toLowerCase(),i)}),f.debug(`Registered provider: ${t} with model ${n||"from-env"}`)}static async createProvider(t,r,n,o,s){const i=t||process.env.NEUROLINK_PROVIDER||process.env.AI_PROVIDER||"vertex",a=i.toLowerCase(),l=Ti.providers.get(a);if(!l)throw new Error(`Unknown provider: ${i}. Available providers: ${Ti.getAvailableProviders().join(", ")}`);let c=r;c||(i.toLowerCase().includes("vertex")?c=process.env.VERTEX_MODEL||"gemini-2.5-flash":i.toLowerCase().includes("bedrock")&&(c=process.env.BEDROCK_MODEL||process.env.BEDROCK_MODEL_ID),c=c||l.defaultModel);const u=due(a),d=s?s[u]:void 0;try{if(typeof l.constructor!="function")throw new Error(`Invalid constructor for provider ${t}: not a function`);const m=l.constructor(c,i,n,o,d);return m instanceof Promise?await m:m}catch(m){throw f.error(`Failed to create provider ${i}:`,m),new Error(`Failed to create provider ${i}: ${m}`,{cause:m})}}static hasProvider(t){return Ti.providers.has(t.toLowerCase())}static getAvailableProviders(){return Array.from(Ti.providers.keys()).filter((t,r,n)=>n.indexOf(t)===r)}static getProviderInfo(t){return Ti.providers.get(t.toLowerCase())}static getDescriptor(t){const r=t.toLowerCase(),n=WA.get(r);if(n){const o=Zr.get(n);if(o)return o}return Ti.providers.get(r)?.descriptor}static getAllDescriptors(){return Cd}static normalizeProviderName(t){const r=t.toLowerCase();if(Ti.providers.has(r))return r;const n=WA.get(r);if(n&&Ti.providers.has(n))return n;for(const[o,s]of Ti.providers.entries())if(s.aliases?.includes(r))return o;return null}static clearRegistrations(){Ti.providers.clear(),Ti.initialized=!1}static ensureInitialized(){Ti.initialized||(Ti.initializeDefaultProviders(),Ti.initialized=!0)}static initializeDefaultProviders(){f.debug("BaseProvider factory pattern ready - providers registered by ProviderRegistry")}static async createBestProvider(t,r,n,o,s){return await Ti.createProvider(t,r,o,void 0,s)}}}}),qcr=S({"src/lib/types/enums.ts"(){"use strict"}}),Gcr=S({"src/lib/types/action.ts"(){"use strict"}}),pue,IF,mue,RF=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/Options.js"(){pue=Symbol("Let zodToJsonSchema decide on which parser to use"),IF={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},mue=e=>typeof e=="string"?{...IF,name:e}:{...IF,...e}}}),hue,fue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/Refs.js"(){RF(),hue=e=>{const t=mue(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}}}});function gue(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function zr(e,t,r,n,o){e[t]=r,gue(e,t,n,o)}var Oh=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/errorMessages.js"(){}}),PF,MF=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js"(){PF=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")}}}),Ar,yue,ht,kd,KA=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/util.js"(){(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(const a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(const i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Ar||(Ar={})),(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(yue||(yue={})),ht=Ar.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kd=e=>{switch(typeof e){case"undefined":return ht.undefined;case"string":return ht.string;case"number":return Number.isNaN(e)?ht.nan:ht.number;case"boolean":return ht.boolean;case"function":return ht.function;case"bigint":return ht.bigint;case"symbol":return ht.symbol;case"object":return Array.isArray(e)?ht.array:e===null?ht.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ht.promise:typeof Map<"u"&&e instanceof Map?ht.map:typeof Set<"u"&&e instanceof Set?ht.set:typeof Date<"u"&&e instanceof Date?ht.date:ht.object;default:return ht.unknown}}}}),Ke,$c,DF=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/ZodError.js"(){KA(),Ke=Ar.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$c=class wlr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof wlr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ar.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r=Object.create(null),n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}},$c.create=e=>new $c(e)}}),vue,zy,_ue=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/locales/en.js"(){DF(),KA(),vue=(e,t)=>{let r;switch(e.code){case Ke.invalid_type:e.received===ht.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case Ke.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ar.jsonStringifyReplacer)}`;break;case Ke.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ar.joinValues(e.keys,", ")}`;break;case Ke.invalid_union:r="Invalid input";break;case Ke.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ar.joinValues(e.options)}`;break;case Ke.invalid_enum_value:r=`Invalid enum value. Expected ${Ar.joinValues(e.options)}, received '${e.received}'`;break;case Ke.invalid_arguments:r="Invalid function arguments";break;case Ke.invalid_return_type:r="Invalid function return type";break;case Ke.invalid_date:r="Invalid date";break;case Ke.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Ar.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case Ke.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case Ke.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case Ke.custom:r="Invalid input";break;case Ke.invalid_intersection_types:r="Intersection results could not be merged";break;case Ke.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Ke.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ar.assertNever(e)}return{message:r}},zy=vue}});function OF(){return wue}var wue,NF=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/errors.js"(){_ue(),wue=zy}});function at(e,t){const r=OF(),n=JA({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===zy?void 0:zy].filter(o=>!!o)});e.common.issues.push(n)}var JA,Oa,Nt,jy,la,LF,$F,Nh,gb,bue=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/parseUtil.js"(){NF(),_ue(),JA=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Oa=class blr{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return Nt;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return blr.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return Nt;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}},Nt=Object.freeze({status:"aborted"}),jy=e=>({status:"dirty",value:e}),la=e=>({status:"valid",value:e}),LF=e=>e.status==="aborted",$F=e=>e.status==="dirty",Nh=e=>e.status==="valid",gb=e=>typeof Promise<"u"&&e instanceof Promise}}),Hcr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/typeAliases.js"(){}}),bt,Vcr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/errorUtil.js"(){(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(bt||(bt={}))}});function tr(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{const{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:o}}function Tue(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Wcr(e){return new RegExp(`^${Tue(e)}$`)}function Kcr(e){let t=`${zF}T${Tue(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Jcr(e,t){return!!((t==="v4"||!t)&&Due.test(e)||(t==="v6"||!t)&&Nue.test(e))}function Ycr(e,t){if(!Iue.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Zcr(e,t){return!!((t==="v4"||!t)&&Oue.test(e)||(t==="v6"||!t)&&Lue.test(e))}function Xcr(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function qy(e){if(e instanceof Kl){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=$u.create(qy(n))}return new Kl({...e._def,shape:()=>t})}else return e instanceof $h?new $h({...e._def,type:qy(e.element)}):e instanceof $u?$u.create(qy(e.unwrap())):e instanceof Zp?Zp.create(qy(e.unwrap())):e instanceof Yp?Yp.create(e.items.map(t=>qy(t))):e}function FF(e,t){const r=kd(e),n=kd(t);if(e===t)return{valid:!0,data:e};if(r===ht.object&&n===ht.object){const o=Ar.objectKeys(t),s=Ar.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(const a of s){const l=FF(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(r===ht.array&&n===ht.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const i=e[s],a=t[s],l=FF(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ht.date&&n===ht.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function Eue(e,t){return new Sb({values:e,typeName:De.ZodEnum,...tr(t)})}var Fc,UF,pr,Sue,Cue,kue,xue,Aue,Iue,Rue,Pue,Mue,BF,Due,Oue,Nue,Lue,$ue,Fue,zF,Uue,yb,YA,ZA,XA,QA,eI,vb,_b,tI,Lh,xd,rI,$h,Kl,wb,Nu,Bue,bb,Yp,zue,nI,oI,jue,Tb,Eb,Sb,Cb,Gy,Lu,$u,Zp,kb,xb,sI,jF,qF,Ab,Qcr,De,eur,tur,rur,nur,our,sur,iur,aur,lur,cur,uur,dur,pur,mur,hur,fur,gur,yur,vur,_ur,wur,bur,Tur,Eur,Sur,Cur,kur,xur,Aur,Iur,Rur,Pur,Mur,Dur,Our=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/types.js"(){DF(),NF(),Vcr(),bue(),KA(),Fc=class{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},UF=(e,t)=>{if(Nh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new $c(e.common.issues);return this._error=r,this._error}}},pr=class{get description(){return this._def.description}_getType(e){return kd(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:kd(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oa,ctx:{common:e.parent.common,data:e.data,parsedType:kd(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(gb(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kd(e)},n=this._parseSync({data:e,path:r.path,parent:r});return UF(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kd(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Nh(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Nh(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kd(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(gb(n)?n:Promise.resolve(n));return UF(r,o)}refine(e,t){const r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,o)=>{const s=e(n),i=()=>o.addIssue({code:Ke.custom,...r(n)});return typeof Promise<"u"&&s instanceof Promise?s.then(a=>a?!0:(i(),!1)):s?!0:(i(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new Lu({schema:this,typeName:De.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return $u.create(this,this._def)}nullable(){return Zp.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $h.create(this)}promise(){return Gy.create(this,this._def)}or(e){return wb.create([this,e],this._def)}and(e){return bb.create(this,e,this._def)}transform(e){return new Lu({...tr(this._def),schema:this,typeName:De.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new kb({...tr(this._def),innerType:this,defaultValue:t,typeName:De.ZodDefault})}brand(){return new jF({typeName:De.ZodBranded,type:this,...tr(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new xb({...tr(this._def),innerType:this,catchValue:t,typeName:De.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return qF.create(this,e)}readonly(){return Ab.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Sue=/^c[^\s-]{8,}$/i,Cue=/^[0-9a-z]+$/,kue=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xue=/^[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}$/i,Aue=/^[a-z0-9_-]{21}$/i,Iue=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rue=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Pue=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Mue="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Due=/^(?:(?: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])$/,Oue=/^(?:(?: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])$/,Nue=/^(([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]))$/,Lue=/^(([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])$/,$ue=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fue=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zF="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Uue=new RegExp(`^${zF}$`),yb=class IA extends pr{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ht.string){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_type,expected:ht.string,received:s.parsedType}),Nt}const n=new Oa;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?at(o,{code:Ke.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&at(o,{code:Ke.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Pue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"email",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")BF||(BF=new RegExp(Mue,"u")),BF.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"emoji",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")xue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"uuid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Aue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"nanoid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Sue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"cuid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Cue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"cuid2",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")kue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"ulid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),at(o,{validation:"url",code:Ke.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"regex",code:Ke.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Kcr(s).test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Uue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Wcr(s).test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Rue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"duration",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Jcr(t.data,s.version)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"ip",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Ycr(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"jwt",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Zcr(t.data,s.version)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"cidr",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?$ue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"base64",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Fue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"base64url",code:Ke.invalid_string,message:s.message}),n.dirty()):Ar.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:Ke.invalid_string,...bt.errToObj(n)})}_addCheck(t){return new IA({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...bt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...bt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...bt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...bt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...bt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...bt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...bt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...bt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...bt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...bt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...bt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...bt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...bt.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...bt.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...bt.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...bt.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...bt.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...bt.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...bt.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...bt.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...bt.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...bt.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...bt.errToObj(r)})}nonempty(t){return this.min(1,bt.errToObj(t))}trim(){return new IA({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new IA({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new IA({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}},yb.create=e=>new yb({checks:[],typeName:De.ZodString,coerce:e?.coerce??!1,...tr(e)}),YA=class lce extends pr{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ht.number){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_type,expected:ht.number,received:s.parsedType}),Nt}let n;const o=new Oa;for(const s of this._def.checks)s.kind==="int"?Ar.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Xcr(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.not_finite,message:s.message}),o.dirty()):Ar.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,bt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,bt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,bt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,bt.toString(r))}setLimit(t,r,n,o){return new lce({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:bt.toString(o)}]})}_addCheck(t){return new lce({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:bt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:bt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:bt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:bt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:bt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:bt.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:bt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:bt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:bt.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Ar.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}},YA.create=e=>new YA({checks:[],typeName:De.ZodNumber,coerce:e?.coerce||!1,...tr(e)}),ZA=class cce extends pr{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ht.bigint)return this._getInvalidInput(t);let n;const o=new Oa;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Ar.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return at(r,{code:Ke.invalid_type,expected:ht.bigint,received:r.parsedType}),Nt}gte(t,r){return this.setLimit("min",t,!0,bt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,bt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,bt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,bt.toString(r))}setLimit(t,r,n,o){return new cce({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:bt.toString(o)}]})}_addCheck(t){return new cce({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:bt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:bt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:bt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:bt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:bt.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}},ZA.create=e=>new ZA({checks:[],typeName:De.ZodBigInt,coerce:e?.coerce??!1,...tr(e)}),XA=class extends pr{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ht.boolean){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.boolean,received:r.parsedType}),Nt}return la(e.data)}},XA.create=e=>new XA({typeName:De.ZodBoolean,coerce:e?.coerce||!1,...tr(e)}),QA=class Tlr extends pr{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ht.date){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_type,expected:ht.date,received:s.parsedType}),Nt}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_date}),Nt}const n=new Oa;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ar.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Tlr({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:bt.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:bt.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}},QA.create=e=>new QA({checks:[],coerce:e?.coerce||!1,typeName:De.ZodDate,...tr(e)}),eI=class extends pr{_parse(e){if(this._getType(e)!==ht.symbol){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.symbol,received:r.parsedType}),Nt}return la(e.data)}},eI.create=e=>new eI({typeName:De.ZodSymbol,...tr(e)}),vb=class extends pr{_parse(e){if(this._getType(e)!==ht.undefined){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.undefined,received:r.parsedType}),Nt}return la(e.data)}},vb.create=e=>new vb({typeName:De.ZodUndefined,...tr(e)}),_b=class extends pr{_parse(e){if(this._getType(e)!==ht.null){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.null,received:r.parsedType}),Nt}return la(e.data)}},_b.create=e=>new _b({typeName:De.ZodNull,...tr(e)}),tI=class extends pr{constructor(){super(...arguments),this._any=!0}_parse(e){return la(e.data)}},tI.create=e=>new tI({typeName:De.ZodAny,...tr(e)}),Lh=class extends pr{constructor(){super(...arguments),this._unknown=!0}_parse(e){return la(e.data)}},Lh.create=e=>new Lh({typeName:De.ZodUnknown,...tr(e)}),xd=class extends pr{_parse(e){const t=this._getOrReturnCtx(e);return at(t,{code:Ke.invalid_type,expected:ht.never,received:t.parsedType}),Nt}},xd.create=e=>new xd({typeName:De.ZodNever,...tr(e)}),rI=class extends pr{_parse(e){if(this._getType(e)!==ht.undefined){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.void,received:r.parsedType}),Nt}return la(e.data)}},rI.create=e=>new rI({typeName:De.ZodVoid,...tr(e)}),$h=class dF extends pr{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ht.array)return at(r,{code:Ke.invalid_type,expected:ht.array,received:r.parsedType}),Nt;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(at(r,{code:i?Ke.too_big:Ke.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(at(r,{code:Ke.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(at(r,{code:Ke.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Fc(r,i,r.path,a)))).then(i=>Oa.mergeArray(n,i));const s=[...r.data].map((i,a)=>o.type._parseSync(new Fc(r,i,r.path,a)));return Oa.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new dF({...this._def,minLength:{value:t,message:bt.toString(r)}})}max(t,r){return new dF({...this._def,maxLength:{value:t,message:bt.toString(r)}})}length(t,r){return new dF({...this._def,exactLength:{value:t,message:bt.toString(r)}})}nonempty(t){return this.min(1,t)}},$h.create=(e,t)=>new $h({type:e,minLength:null,maxLength:null,exactLength:null,typeName:De.ZodArray,...tr(t)}),Kl=class Pu extends pr{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=Ar.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ht.object){const c=this._getOrReturnCtx(t);return at(c,{code:Ke.invalid_type,expected:ht.object,received:c.parsedType}),Nt}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof xd&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||a.push(c);const l=[];for(const c of i){const u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Fc(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof xd){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(at(o,{code:Ke.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Fc(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const d=await u.key,m=await u.value;c.push({key:d,value:m,alwaysSet:u.alwaysSet})}return c}).then(c=>Oa.mergeObjectSync(n,c)):Oa.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return bt.errToObj,new Pu({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:bt.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Pu({...this._def,unknownKeys:"strip"})}passthrough(){return new Pu({...this._def,unknownKeys:"passthrough"})}extend(t){return new Pu({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Pu({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:De.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new Pu({...this._def,catchall:t})}pick(t){const r={};for(const n of Ar.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Pu({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ar.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new Pu({...this._def,shape:()=>r})}deepPartial(){return qy(this)}partial(t){const r={};for(const n of Ar.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new Pu({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ar.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof $u;)s=s._def.innerType;r[n]=s}return new Pu({...this._def,shape:()=>r})}keyof(){return Eue(Ar.objectKeys(this.shape))}},Kl.create=(e,t)=>new Kl({shape:()=>e,unknownKeys:"strip",catchall:xd.create(),typeName:De.ZodObject,...tr(t)}),Kl.strictCreate=(e,t)=>new Kl({shape:()=>e,unknownKeys:"strict",catchall:xd.create(),typeName:De.ZodObject,...tr(t)}),Kl.lazycreate=(e,t)=>new Kl({shape:e,unknownKeys:"strip",catchall:xd.create(),typeName:De.ZodObject,...tr(t)}),wb=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function n(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;const s=o.map(i=>new $c(i.ctx.common.issues));return at(t,{code:Ke.invalid_union,unionErrors:s}),Nt}if(t.common.async)return Promise.all(r.map(async o=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(n);{let o;const s=[];for(const a of r){const l={...t,common:{...t.common,issues:[]},parent:null},c=a._parseSync({data:t.data,path:t.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!o&&(o={result:c,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const i=s.map(a=>new $c(a));return at(t,{code:Ke.invalid_union,unionErrors:i}),Nt}}get options(){return this._def.options}},wb.create=(e,t)=>new wb({options:e,typeName:De.ZodUnion,...tr(t)}),Nu=e=>e instanceof Tb?Nu(e.schema):e instanceof Lu?Nu(e.innerType()):e instanceof Eb?[e.value]:e instanceof Sb?e.options:e instanceof Cb?Ar.objectValues(e.enum):e instanceof kb?Nu(e._def.innerType):e instanceof vb?[void 0]:e instanceof _b?[null]:e instanceof $u?[void 0,...Nu(e.unwrap())]:e instanceof Zp?[null,...Nu(e.unwrap())]:e instanceof jF||e instanceof Ab?Nu(e.unwrap()):e instanceof xb?Nu(e._def.innerType):[],Bue=class Elr extends pr{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ht.object)return at(r,{code:Ke.invalid_type,expected:ht.object,received:r.parsedType}),Nt;const n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(at(r,{code:Ke.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Nt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){const o=new Map;for(const s of r){const i=Nu(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new Elr({typeName:De.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...tr(n)})}},bb=class extends pr{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(o,s)=>{if(LF(o)||LF(s))return Nt;const i=FF(o.value,s.value);return i.valid?(($F(o)||$F(s))&&t.dirty(),{status:t.value,value:i.data}):(at(r,{code:Ke.invalid_intersection_types}),Nt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,s])=>n(o,s)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}},bb.create=(e,t,r)=>new bb({left:e,right:t,typeName:De.ZodIntersection,...tr(r)}),Yp=class Slr extends pr{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ht.array)return at(n,{code:Ke.invalid_type,expected:ht.array,received:n.parsedType}),Nt;if(n.data.length<this._def.items.length)return at(n,{code:Ke.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Nt;!this._def.rest&&n.data.length>this._def.items.length&&(at(n,{code:Ke.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Fc(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Oa.mergeArray(r,i)):Oa.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new Slr({...this._def,rest:t})}},Yp.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Yp({items:e,typeName:De.ZodTuple,rest:null,...tr(t)})},zue=class uce extends pr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ht.object)return at(n,{code:Ke.invalid_type,expected:ht.object,received:n.parsedType}),Nt;const o=[],s=this._def.keyType,i=this._def.valueType;for(const a in n.data)o.push({key:s._parse(new Fc(n,a,n.path,a)),value:i._parse(new Fc(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Oa.mergeObjectAsync(r,o):Oa.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof pr?new uce({keyType:t,valueType:r,typeName:De.ZodRecord,...tr(n)}):new uce({keyType:yb.create(),valueType:t,typeName:De.ZodRecord,...tr(r)})}},nI=class extends pr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ht.map)return at(r,{code:Ke.invalid_type,expected:ht.map,received:r.parsedType}),Nt;const n=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([i,a],l)=>({key:n._parse(new Fc(r,i,r.path,[l,"key"])),value:o._parse(new Fc(r,a,r.path,[l,"value"]))}));if(r.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const a of s){const l=await a.key,c=await a.value;if(l.status==="aborted"||c.status==="aborted")return Nt;(l.status==="dirty"||c.status==="dirty")&&t.dirty(),i.set(l.value,c.value)}return{status:t.value,value:i}})}else{const i=new Map;for(const a of s){const l=a.key,c=a.value;if(l.status==="aborted"||c.status==="aborted")return Nt;(l.status==="dirty"||c.status==="dirty")&&t.dirty(),i.set(l.value,c.value)}return{status:t.value,value:i}}}},nI.create=(e,t,r)=>new nI({valueType:t,keyType:e,typeName:De.ZodMap,...tr(r)}),oI=class dce extends pr{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ht.set)return at(n,{code:Ke.invalid_type,expected:ht.set,received:n.parsedType}),Nt;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(at(n,{code:Ke.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(at(n,{code:Ke.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function i(l){const c=new Set;for(const u of l){if(u.status==="aborted")return Nt;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>s._parse(new Fc(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,r){return new dce({...this._def,minSize:{value:t,message:bt.toString(r)}})}max(t,r){return new dce({...this._def,maxSize:{value:t,message:bt.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}},oI.create=(e,t)=>new oI({valueType:e,minSize:null,maxSize:null,typeName:De.ZodSet,...tr(t)}),jue=class pF extends pr{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ht.function)return at(r,{code:Ke.invalid_type,expected:ht.function,received:r.parsedType}),Nt;function n(a,l){return JA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,OF(),zy].filter(c=>!!c),issueData:{code:Ke.invalid_arguments,argumentsError:l}})}function o(a,l){return JA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,OF(),zy].filter(c=>!!c),issueData:{code:Ke.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Gy){const a=this;return la(async function(...l){const c=new $c([]),u=await a._def.args.parseAsync(l,s).catch(h=>{throw c.addIssue(n(l,h)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw c.addIssue(o(d,h)),c})})}else{const a=this;return la(function(...l){const c=a._def.args.safeParse(l,s);if(!c.success)throw new $c([n(l,c.error)]);const u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new $c([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new pF({...this._def,args:Yp.create(t).rest(Lh.create())})}returns(t){return new pF({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new pF({args:t||Yp.create([]).rest(Lh.create()),returns:r||Lh.create(),typeName:De.ZodFunction,...tr(n)})}},Tb=class extends pr{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}},Tb.create=(e,t)=>new Tb({getter:e,typeName:De.ZodLazy,...tr(t)}),Eb=class extends pr{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return at(t,{received:t.data,code:Ke.invalid_literal,expected:this._def.value}),Nt}return{status:"valid",value:e.data}}get value(){return this._def.value}},Eb.create=(e,t)=>new Eb({value:e,typeName:De.ZodLiteral,...tr(t)}),Sb=class pce extends pr{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return at(r,{expected:Ar.joinValues(n),received:r.parsedType,code:Ke.invalid_type}),Nt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return at(r,{received:r.data,code:Ke.invalid_enum_value,options:n}),Nt}return la(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return pce.create(t,{...this._def,...r})}exclude(t,r=this._def){return pce.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}},Sb.create=Eue,Cb=class extends pr{_parse(e){const t=Ar.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ht.string&&r.parsedType!==ht.number){const n=Ar.objectValues(t);return at(r,{expected:Ar.joinValues(n),received:r.parsedType,code:Ke.invalid_type}),Nt}if(this._cache||(this._cache=new Set(Ar.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=Ar.objectValues(t);return at(r,{received:r.data,code:Ke.invalid_enum_value,options:n}),Nt}return la(e.data)}get enum(){return this._def.values}},Cb.create=(e,t)=>new Cb({values:e,typeName:De.ZodNativeEnum,...tr(t)}),Gy=class extends pr{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ht.promise&&t.common.async===!1)return at(t,{code:Ke.invalid_type,expected:ht.promise,received:t.parsedType}),Nt;const r=t.parsedType===ht.promise?t.data:Promise.resolve(t.data);return la(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}},Gy.create=(e,t)=>new Gy({type:e,typeName:De.ZodPromise,...tr(t)}),Lu=class extends pr{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===De.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:s=>{at(r,s),s.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){const s=n.transform(r.data,o);if(r.common.async)return Promise.resolve(s).then(async i=>{if(t.value==="aborted")return Nt;const a=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return a.status==="aborted"?Nt:a.status==="dirty"||t.value==="dirty"?jy(a.value):a});{if(t.value==="aborted")return Nt;const i=this._def.schema._parseSync({data:s,path:r.path,parent:r});return i.status==="aborted"?Nt:i.status==="dirty"||t.value==="dirty"?jy(i.value):i}}if(n.type==="refinement"){const s=i=>{const a=n.refinement(i,o);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Nt:(i.status==="dirty"&&t.dirty(),s(i.value),{status:t.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?Nt:(i.status==="dirty"&&t.dirty(),s(i.value).then(()=>({status:t.value,value:i.value}))))}if(n.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Nh(s))return Nt;const i=n.transform(s.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Nh(s)?Promise.resolve(n.transform(s.value,o)).then(i=>({status:t.value,value:i})):Nt);Ar.assertNever(n)}},Lu.create=(e,t,r)=>new Lu({schema:e,typeName:De.ZodEffects,effect:t,...tr(r)}),Lu.createWithPreprocess=(e,t,r)=>new Lu({schema:t,effect:{type:"preprocess",transform:e},typeName:De.ZodEffects,...tr(r)}),$u=class extends pr{_parse(e){return this._getType(e)===ht.undefined?la(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},$u.create=(e,t)=>new $u({innerType:e,typeName:De.ZodOptional,...tr(t)}),Zp=class extends pr{_parse(e){return this._getType(e)===ht.null?la(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},Zp.create=(e,t)=>new Zp({innerType:e,typeName:De.ZodNullable,...tr(t)}),kb=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ht.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}},kb.create=(e,t)=>new kb({innerType:e,typeName:De.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...tr(t)}),xb=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return gb(n)?n.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new $c(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new $c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}},xb.create=(e,t)=>new xb({innerType:e,typeName:De.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...tr(t)}),sI=class extends pr{_parse(e){if(this._getType(e)!==ht.nan){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.nan,received:r.parsedType}),Nt}return{status:"valid",value:e.data}}},sI.create=e=>new sI({typeName:De.ZodNaN,...tr(e)}),jF=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},qF=class Clr extends pr{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Nt:s.status==="dirty"?(r.dirty(),jy(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Nt:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new Clr({in:t,out:r,typeName:De.ZodPipeline})}},Ab=class extends pr{_parse(e){const t=this._def.innerType._parse(e),r=n=>(Nh(n)&&(n.value=Object.freeze(n.value)),n);return gb(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}},Ab.create=(e,t)=>new Ab({innerType:e,typeName:De.ZodReadonly,...tr(t)}),Qcr={object:Kl.lazycreate},(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(De||(De={})),eur=yb.create,tur=YA.create,rur=sI.create,nur=ZA.create,our=XA.create,sur=QA.create,iur=eI.create,aur=vb.create,lur=_b.create,cur=tI.create,uur=Lh.create,dur=xd.create,pur=rI.create,mur=$h.create,hur=Kl.create,fur=Kl.strictCreate,gur=wb.create,yur=Bue.create,vur=bb.create,_ur=Yp.create,wur=zue.create,bur=nI.create,Tur=oI.create,Eur=jue.create,Sur=Tb.create,Cur=Eb.create,kur=Sb.create,xur=Cb.create,Aur=Gy.create,Iur=Lu.create,Rur=$u.create,Pur=Zp.create,Mur=Lu.createWithPreprocess,Dur=qF.create}}),que=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/external.js"(){NF(),bue(),Hcr(),KA(),Our(),DF()}}),Fh=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/index.js"(){que(),que()}});function Na(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?PF(t,e.currentPath):t.join("/")}}var Uc=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/any.js"(){MF()}});function Nur(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==De.ZodAny&&(r.items=Nr(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&zr(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&zr(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(zr(r,"minItems",e.exactLength.value,e.exactLength.message,t),zr(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}var Gue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/array.js"(){Fh(),Oh(),Ps()}});function Lur(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?zr(r,"minimum",n.value,n.message,t):zr(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),zr(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?zr(r,"maximum",n.value,n.message,t):zr(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),zr(r,"maximum",n.value,n.message,t));break;case"multipleOf":zr(r,"multipleOf",n.value,n.message,t);break}return r}var Hue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"(){Oh()}});function $ur(){return{type:"boolean"}}var Vue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"(){}});function Wue(e,t){return Nr(e.type._def,t)}var GF=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"(){Ps()}}),Kue,Jue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"(){Ps(),Kue=(e,t)=>Nr(e.innerType._def,t)}});function Yue(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Yue(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Zue(e,t)}}var Zue,Xue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/date.js"(){Oh(),Zue=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":zr(r,"minimum",n.value,n.message,t);break;case"max":zr(r,"maximum",n.value,n.message,t);break}return r}}});function Fur(e,t){return{...Nr(e.innerType._def,t),default:e.defaultValue()}}var Que=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/default.js"(){Ps()}});function Uur(e,t){return t.effectStrategy==="input"?Nr(e.schema._def,t):Na(t)}var ede=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"(){Ps(),Uc()}});function Bur(e){return{type:"string",enum:Array.from(e.values)}}var tde=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"(){}});function zur(e,t){const r=[Nr(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Nr(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return r.forEach(s=>{if(rde(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var rde,nde=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"(){Ps(),rde=e=>"type"in e&&e.type==="string"?!1:"allOf"in e}});function jur(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var ode=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"(){}});function sde(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":zr(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":zr(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Bc(r,"email",n.message,t);break;case"format:idn-email":Bc(r,"idn-email",n.message,t);break;case"pattern:zod":ca(r,Jl.email,n.message,t);break}break;case"url":Bc(r,"uri",n.message,t);break;case"uuid":Bc(r,"uuid",n.message,t);break;case"regex":ca(r,n.regex,n.message,t);break;case"cuid":ca(r,Jl.cuid,n.message,t);break;case"cuid2":ca(r,Jl.cuid2,n.message,t);break;case"startsWith":ca(r,RegExp(`^${HF(n.value,t)}`),n.message,t);break;case"endsWith":ca(r,RegExp(`${HF(n.value,t)}$`),n.message,t);break;case"datetime":Bc(r,"date-time",n.message,t);break;case"date":Bc(r,"date",n.message,t);break;case"time":Bc(r,"time",n.message,t);break;case"duration":Bc(r,"duration",n.message,t);break;case"length":zr(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),zr(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{ca(r,RegExp(HF(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Bc(r,"ipv4",n.message,t),n.version!=="v4"&&Bc(r,"ipv6",n.message,t);break}case"base64url":ca(r,Jl.base64url,n.message,t);break;case"jwt":ca(r,Jl.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&ca(r,Jl.ipv4Cidr,n.message,t),n.version!=="v4"&&ca(r,Jl.ipv6Cidr,n.message,t);break}case"emoji":ca(r,Jl.emoji(),n.message,t);break;case"ulid":{ca(r,Jl.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Bc(r,"binary",n.message,t);break}case"contentEncoding:base64":{zr(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{ca(r,Jl.base64,n.message,t);break}}break}case"nanoid":ca(r,Jl.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function HF(e,t){return t.patternStrategy==="escape"?qur(e):e}function qur(e){let t="";for(let r=0;r<e.length;r++)ade.has(e[r])||(t+="\\"),t+=e[r];return t}function Bc(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):zr(e,"format",t,r,n)}function ca(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:ide(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):zr(e,"pattern",ide(t,n),r,n)}function ide(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let o="",s=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
|
|
14
|
+
Restart your application to load the new environment variables.`}function zi(e,t){return process.env[e]||t}function kF(e,t){return e?e.some(r=>typeof r=="string"?!!t[r]:r.every(n=>!!t[n])):!1}function gcr(){const e=Ucr(),t=Bcr(),r=["\u{1F511} Option 1: API Key Authentication (Recommended for developers)","1. Visit: https://console.anthropic.com/","2. Sign in or create an account","3. Go to API Keys section","4. Create a new API key","5. Set ANTHROPIC_API_KEY in your .env file"],n=["","\u{1F510} Option 2: OAuth Authentication (For Claude Pro/Max subscribers)","1. Set ANTHROPIC_AUTH_METHOD=oauth in your .env file","2. Set ANTHROPIC_SUBSCRIPTION_TIER to your tier (free, pro, max)","3. Run the OAuth flow to obtain tokens, or set pre-configured tokens:"," - ANTHROPIC_OAUTH_TOKEN=your_access_token"," - ANTHROPIC_OAUTH_REFRESH_TOKEN=your_refresh_token (optional)","","\u{1F4CB} Available Subscription Tiers:"," - free: Free tier with limited usage"," - pro: Claude Pro ($20/month) - Extended usage limits"," - max: Claude Max - Highest usage limits"," - api: API-based access (pay-per-use)"],o=e==="oauth"?[...n.slice(1),"",...r]:[...r,...n];return{providerName:"Anthropic",envVarName:e==="oauth"?"ANTHROPIC_OAUTH_TOKEN":"ANTHROPIC_API_KEY",setupUrl:e==="oauth"?"https://claude.ai/settings":"https://console.anthropic.com/",description:e==="oauth"?`Anthropic OAuth Token (${t} tier)`:"Anthropic API Key",instructions:o,fallbackEnvVars:e==="oauth"?["ANTHROPIC_API_KEY"]:["ANTHROPIC_OAUTH_TOKEN","CLAUDE_OAUTH_TOKEN","ANTHROPIC_OAUTH_ACCESS_TOKEN"]}}function ycr(){return{providerName:"OPENAI",envVarName:"OPENAI_API_KEY",setupUrl:"https://platform.openai.com/api-keys",description:"Credentials",instructions:["1. Visit: https://platform.openai.com/api-keys","2. Create new API key","3. Copy the key"]}}function vcr(){return{providerName:"HuggingFace",envVarName:"HUGGINGFACE_API_KEY",setupUrl:"https://huggingface.co/settings/tokens",description:"Credentials",instructions:["1. Visit: https://huggingface.co/settings/tokens","2. Create new API token","3. Copy the token"],fallbackEnvVars:["HF_TOKEN"]}}function _cr(){return{providerName:"Mistral",envVarName:"MISTRAL_API_KEY",setupUrl:"https://console.mistral.ai/",description:"API key",instructions:["1. Visit: https://console.mistral.ai/","2. Create or sign in to your account","3. Generate a new API key"]}}function wcr(){return{providerName:"Azure OpenAI",envVarName:"AZURE_OPENAI_API_KEY",setupUrl:"https://portal.azure.com/",description:"Azure OpenAI API Key",instructions:["1. Visit: https://portal.azure.com/","2. Create or access Azure OpenAI resource","3. Get API key from Keys and Endpoint section"]}}function bcr(){return{providerName:"Azure OpenAI",envVarName:"AZURE_OPENAI_ENDPOINT",setupUrl:"https://portal.azure.com/",description:"Azure OpenAI Endpoint",instructions:["1. Visit: https://portal.azure.com/","2. Access your Azure OpenAI resource","3. Copy endpoint URL from Keys and Endpoint section"]}}function Tcr(){return{providerName:"DeepSeek",envVarName:"DEEPSEEK_API_KEY",setupUrl:"https://platform.deepseek.com/api_keys",description:"API key",instructions:["1. Visit: https://platform.deepseek.com/api_keys","2. Create or sign in to your DeepSeek account","3. Generate a new API key","4. Set DEEPSEEK_API_KEY in your .env file"]}}function Ecr(){return{providerName:"NVIDIA NIM",envVarName:"NVIDIA_NIM_API_KEY",setupUrl:"https://build.nvidia.com/settings/api-keys",description:"API key",instructions:["1. Visit: https://build.nvidia.com/","2. Sign in with your NVIDIA developer account","3. Open Settings \u2192 API Keys","4. Generate a new API key (Bearer token)","5. Set NVIDIA_NIM_API_KEY in your .env file"]}}function Scr(){return{providerName:"xAI",envVarName:"XAI_API_KEY",setupUrl:"https://console.x.ai/",description:"API key",instructions:["1. Visit: https://console.x.ai/","2. Sign in with your xAI account","3. Create an API key","4. Set XAI_API_KEY in your .env file"]}}function Ccr(){return{providerName:"Cerebras",envVarName:"CEREBRAS_API_KEY",setupUrl:"https://cloud.cerebras.ai",description:"API key",instructions:["1. Visit: https://cloud.cerebras.ai","2. Sign in or create a free Cerebras account","3. Create an API key under API Keys","4. Set CEREBRAS_API_KEY in your .env file"]}}function kcr(){return{providerName:"Groq",envVarName:"GROQ_API_KEY",setupUrl:"https://console.groq.com/keys",description:"API key",instructions:["1. Visit: https://console.groq.com/keys","2. Sign in to your Groq account","3. Create a new API key","4. Set GROQ_API_KEY in your .env file"]}}function xcr(){return{providerName:"Cohere",envVarName:"COHERE_API_KEY",setupUrl:"https://dashboard.cohere.com/api-keys",description:"API key",instructions:["1. Visit: https://dashboard.cohere.com/api-keys","2. Sign in to your Cohere account","3. Create a new API key","4. Set COHERE_API_KEY in your .env file"]}}function Acr(){return{providerName:"Replicate",envVarName:"REPLICATE_API_TOKEN",setupUrl:"https://replicate.com/account/api-tokens",description:"API token",instructions:["1. Visit: https://replicate.com/account/api-tokens","2. Sign in to your Replicate account","3. Create a new API token","4. Set REPLICATE_API_TOKEN in your .env file"]}}function Icr(){return{providerName:"Together AI",envVarName:"TOGETHER_API_KEY",setupUrl:"https://api.together.xyz/settings/api-keys",description:"API key",instructions:["1. Visit: https://api.together.xyz/settings/api-keys","2. Sign in to your Together AI account","3. Create a new API key","4. Set TOGETHER_API_KEY in your .env file"]}}function Rcr(){return{providerName:"Fireworks AI",envVarName:"FIREWORKS_API_KEY",setupUrl:"https://fireworks.ai/account/api-keys",description:"API key",instructions:["1. Visit: https://fireworks.ai/account/api-keys","2. Sign in to your Fireworks AI account","3. Create a new API key","4. Set FIREWORKS_API_KEY in your .env file"]}}function Pcr(){return{providerName:"Perplexity",envVarName:"PERPLEXITY_API_KEY",setupUrl:"https://www.perplexity.ai/settings/api",description:"API key",instructions:["1. Visit: https://www.perplexity.ai/settings/api","2. Sign in to your Perplexity account","3. Create a new API key (Sonar tier)","4. Set PERPLEXITY_API_KEY in your .env file"]}}function Mcr(){return{providerName:"Voyage AI",envVarName:"VOYAGE_API_KEY",setupUrl:"https://dash.voyageai.com/api-keys",description:"API key",instructions:["1. Visit: https://dash.voyageai.com/api-keys","2. Sign in to your Voyage AI account","3. Create a new API key","4. Set VOYAGE_API_KEY in your .env file"]}}function Dcr(){return{providerName:"Jina AI",envVarName:"JINA_API_KEY",setupUrl:"https://jina.ai/?sui=apikey",description:"API key",instructions:["1. Visit: https://jina.ai/?sui=apikey","2. Sign in / create account","3. Copy your API key","4. Set JINA_API_KEY in your .env file"]}}function Ocr(){return{providerName:"Ideogram",envVarName:"IDEOGRAM_API_KEY",setupUrl:"https://developer.ideogram.ai/",description:"API key",instructions:["1. Visit: https://developer.ideogram.ai/","2. Sign in / create account","3. Generate a new API key","4. Set IDEOGRAM_API_KEY in your .env file"]}}function Ncr(){return{providerName:"Recraft",envVarName:"RECRAFT_API_KEY",setupUrl:"https://www.recraft.ai/api",description:"API token",instructions:["1. Visit: https://www.recraft.ai/api","2. Sign in / create account","3. Create an API token","4. Set RECRAFT_API_KEY in your .env file"]}}function Lcr(){return{providerName:"Cloudflare Workers AI",envVarName:"CLOUDFLARE_API_KEY",setupUrl:"https://dash.cloudflare.com/profile/api-tokens",description:"API token (Workers AI Read+Write scope)",instructions:["1. Visit: https://dash.cloudflare.com/profile/api-tokens","2. Create a token with 'Workers AI: Read + Write' scope","3. Set CLOUDFLARE_API_KEY in your .env file","4. Also set CLOUDFLARE_ACCOUNT_ID (find it in the dashboard URL or under 'Account ID')"]}}function $cr(){return{providerName:"Google Vertex AI",envVarName:"GOOGLE_CLOUD_PROJECT_ID",setupUrl:"https://console.cloud.google.com/",description:"Google Cloud Credentials",instructions:["1. Visit: https://console.cloud.google.com/","2. Create or select a project","3. Enable Vertex AI API","4. Set up authentication"],fallbackEnvVars:["VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"]}}function Fcr(){return{providerName:"Google Vertex AI",envVarName:"GOOGLE_APPLICATION_CREDENTIALS",setupUrl:"https://console.cloud.google.com/",description:"Google Cloud authentication",instructions:["\u{1F527} Option 1: Service Account Key File","GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json","","\u{1F527} Option 2: Service Account Key (Base64)","GOOGLE_SERVICE_ACCOUNT_KEY=base64_encoded_key","","\u{1F527} Option 3: Individual Credentials","GOOGLE_AUTH_CLIENT_EMAIL=your-service-account@project.iam.gserviceaccount.com","GOOGLE_AUTH_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----..."],fallbackEnvVars:["GOOGLE_SERVICE_ACCOUNT_KEY"]}}function Ucr(){return process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase()==="oauth"?"oauth":"api_key"}function Bcr(){switch(process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase()){case"free":return"free";case"pro":return"pro";case"max":return"max";case"max_5":return"max_5";case"max_20":return"max_20";default:return"api"}}function zcr(e,t){const r=t?.apiKey?.trim(),n=r&&r.length>0?r:Bi(e.configOptions);if(e.computedBaseURL){const{envVar:a,missingValueMessage:l,build:c}=e.computedBaseURL,u=t?.baseURL?.trim();if(u&&u.length>0)return{apiKey:n,baseURL:u};const d=(t?.accountId??process.env[a]??"").trim();if(!d)throw new Error(l);return{apiKey:n,baseURL:c(d)}}const o=t?.baseURL?.trim(),s=e.baseURLEnvVar?process.env[e.baseURLEnvVar]?.trim():void 0,i=(o&&o.length>0?o:void 0)??(s&&s.length>0?s:void 0)??e.defaultBaseURL;if(!i)throw new Error(`${e.providerName}: no base URL. Set one in credentials`+(e.baseURLEnvVar?`, set ${e.baseURLEnvVar}`:"")+", or give the catalog entry a defaultBaseURL.");return{apiKey:n,baseURL:i}}var ia,Dh,xF,Yo=S({"src/lib/utils/providerConfig.ts"(){"use strict";ia={openai:/^sk-[A-Za-z0-9]{48,}$/,anthropic:/^sk-ant-[A-Za-z0-9\-_]{95,}$/,"google-ai":/^AIza[A-Za-z0-9\-_]{35}$/,huggingface:/^hf_[A-Za-z0-9]{37}$/,mistral:/^[A-Za-z0-9]{32}$/,azure:/^[A-Za-z0-9]{32}$/,aws:/^[A-Z0-9]{20}$/,bedrock:/^[A-Z0-9]{20}$/},Dh={OPENAI_MIN:48,ANTHROPIC_MIN:95,HUGGINGFACE_EXACT:37,AZURE_MIN:32,MISTRAL_EXACT:32,AWS_ACCESS_KEY:20,GOOGLE_AI_EXACT:39},xF={MIN_LENGTH:6,MAX_LENGTH:30,PATTERN:/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/}}}),Cd,Zr,WA,By=S({"src/lib/factories/providerDescriptors.ts"(){"use strict";Yo(),Cd=[{name:"bedrock",defaultHealthSweepPriority:5,autoSelectPreference:7,aliases:["aws"],credentialsKey:"bedrock",envVars:{apiKey:"AWS_ACCESS_KEY_ID",extraRequired:["AWS_SECRET_ACCESS_KEY"],model:"BEDROCK_MODEL"},defaultModel:"",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.aws.amazon.com/iam/",timeouts:{generateMs:45e3,streamMs:12e4},autoSelectPriority:7,apiKeyFormatPattern:ia.bedrock,credentialsResolvedExternally:!0},{name:"openai",defaultHealthSweepPriority:4,autoSelectPreference:3,aliases:["gpt","chatgpt"],credentialsKey:"openai",envVars:{apiKey:"OPENAI_API_KEY",baseURL:"OPENAI_BASE_URL"},defaultModel:"gpt-4o-mini",toolSupport:"native",localRuntime:!1,healthCheck:"models-probe",setupUrl:"https://platform.openai.com/api-keys",timeouts:{generateMs:3e4,streamMs:12e4},autoSelectPriority:5,apiKeyFormatPattern:ia.openai},{name:"openai-compatible",aliases:["vllm","compatible"],credentialsKey:"openaiCompatible",envVars:{apiKey:"OPENAI_COMPATIBLE_API_KEY",baseURL:"OPENAI_COMPATIBLE_BASE_URL",model:"OPENAI_COMPATIBLE_MODEL"},defaultModel:"",toolSupport:"native",localRuntime:!1,healthCheck:"env-only"},{name:"openrouter",aliases:["or"],credentialsKey:"openrouter",envVars:{apiKey:"OPENROUTER_API_KEY",baseURL:"OPENROUTER_BASE_URL",model:"OPENROUTER_MODEL"},defaultModel:"anthropic/claude-sonnet-4.5",toolSupport:"model-dependent",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://openrouter.ai/keys"},{name:"vertex",defaultHealthSweepPriority:1,autoSelectPreference:5,aliases:["googleVertex"],credentialsKey:"vertex",envVars:{apiKey:"GOOGLE_CLOUD_PROJECT_ID",fallbacks:["VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"],extraRequired:["GOOGLE_APPLICATION_CREDENTIALS"],extraRequiredFallbacks:["GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK","GOOGLE_SERVICE_ACCOUNT_KEY",["GOOGLE_AUTH_CLIENT_EMAIL","GOOGLE_AUTH_PRIVATE_KEY"]]},defaultModel:"claude-sonnet-4-6",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.cloud.google.com/",timeouts:{generateMs:6e4,streamMs:12e4},autoSelectPriority:3,credentialsResolvedExternally:!0},{name:"anthropic",defaultHealthSweepPriority:3,autoSelectPreference:4,aliases:["claude"],credentialsKey:"anthropic",envVars:{apiKey:"ANTHROPIC_API_KEY",fallbacks:["ANTHROPIC_OAUTH_TOKEN","CLAUDE_OAUTH_TOKEN","ANTHROPIC_OAUTH_ACCESS_TOKEN"],baseURL:"ANTHROPIC_BASE_URL"},defaultModel:"claude-sonnet-4-6",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.anthropic.com/settings/keys",timeouts:{generateMs:6e4,streamMs:12e4},autoSelectPriority:6,apiKeyFormatPattern:ia.anthropic},{name:"azure",defaultHealthSweepPriority:6,autoSelectPreference:8,aliases:["azureOpenai"],credentialsKey:"azure",envVars:{apiKey:"AZURE_OPENAI_API_KEY",extraRequired:["AZURE_OPENAI_ENDPOINT"],model:"AZURE_MODEL",modelFallbacks:["AZURE_OPENAI_MODEL","AZURE_OPENAI_DEPLOYMENT","AZURE_OPENAI_DEPLOYMENT_ID"]},defaultModel:"gpt-4o-mini",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://portal.azure.com/",timeouts:{generateMs:3e4,streamMs:12e4},autoSelectPriority:8,apiKeyFormatPattern:ia.azure},{name:"google-ai",defaultHealthSweepPriority:2,autoSelectPreference:6,aliases:["googleAiStudio","google","gemini","google-ai-studio"],credentialsKey:"googleAiStudio",envVars:{apiKey:"GOOGLE_AI_API_KEY",fallbacks:["GOOGLE_GENERATIVE_AI_API_KEY"],baseURL:"GOOGLE_AI_BASE_URL"},defaultModel:"gemini-2.5-flash",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://aistudio.google.com/apikey",timeouts:{generateMs:3e4,streamMs:12e4},autoSelectPriority:4,apiKeyFormatPattern:ia["google-ai"]},{name:"huggingface",aliases:["hf"],credentialsKey:"huggingFace",envVars:{apiKey:"HUGGINGFACE_API_KEY",fallbacks:["HF_TOKEN"],baseURL:"HUGGINGFACE_BASE_URL",model:"HUGGINGFACE_MODEL"},defaultModel:"Qwen/Qwen2.5-72B-Instruct",toolSupport:"model-dependent",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://huggingface.co/settings/tokens",timeouts:{generateMs:12e4,streamMs:12e4},autoSelectPriority:10,apiKeyFormatPattern:ia.huggingface},{name:"ollama",defaultHealthSweepPriority:8,autoSelectPreference:2,aliases:["local"],credentialsKey:"ollama",envVars:{baseURL:"OLLAMA_BASE_URL",baseURLFallbacks:["OLLAMA_API_BASE"],model:"OLLAMA_MODEL",optional:!0},defaultModel:"llama3.2:latest",toolSupport:"model-dependent",localRuntime:!0,healthCheck:"models-probe",setupUrl:"https://ollama.com/download",timeouts:{generateMs:3e5,streamMs:12e4},autoSelectPriority:2},{name:"mistral",aliases:[],credentialsKey:"mistral",envVars:{apiKey:"MISTRAL_API_KEY",baseURL:"MISTRAL_BASE_URL"},defaultModel:"mistral-large-latest",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.mistral.ai/api-keys",timeouts:{generateMs:45e3,streamMs:12e4},autoSelectPriority:9,apiKeyFormatPattern:ia.mistral},{name:"litellm",defaultHealthSweepPriority:7,autoSelectPreference:1,aliases:[],credentialsKey:"litellm",envVars:{apiKey:"LITELLM_API_KEY",baseURL:"LITELLM_BASE_URL",model:"LITELLM_MODEL",optional:!0},defaultModel:"openai/gpt-4o-mini",toolSupport:"native",localRuntime:!1,healthCheck:"models-probe",setupUrl:"https://docs.litellm.ai/docs/proxy/quick_start",timeouts:{generateMs:3e5,streamMs:12e4},autoSelectPriority:1,credentialsResolvedExternally:!0},{name:"sagemaker",aliases:["aws-sagemaker"],credentialsKey:"sagemaker",envVars:{apiKey:"AWS_ACCESS_KEY_ID",extraRequired:["AWS_SECRET_ACCESS_KEY"],model:"SAGEMAKER_MODEL",modelFallbacks:["SAGEMAKER_MODEL_NAME","SAGEMAKER_DEFAULT_ENDPOINT","SAGEMAKER_ENDPOINT_NAME"],baseURL:"SAGEMAKER_ENDPOINT"},defaultModel:"sagemaker-model",toolSupport:"native",localRuntime:!1,healthCheck:"live-generate",setupUrl:"https://console.aws.amazon.com/iam/",apiKeyFormatPattern:ia.aws},{name:"deepseek",aliases:["ds"],credentialsKey:"deepseek",envVars:{apiKey:"DEEPSEEK_API_KEY",baseURL:"DEEPSEEK_BASE_URL",model:"DEEPSEEK_MODEL"},defaultModel:"deepseek-chat",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://platform.deepseek.com/api_keys"},{name:"nvidia-nim",aliases:["nvidia","nim"],credentialsKey:"nvidiaNim",envVars:{apiKey:"NVIDIA_NIM_API_KEY",baseURL:"NVIDIA_NIM_BASE_URL",model:"NVIDIA_NIM_MODEL"},defaultModel:"meta/llama-3.3-70b-instruct",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://build.nvidia.com/settings/api-keys"},{name:"lm-studio",aliases:["lmstudio","lms"],credentialsKey:"lmStudio",envVars:{baseURL:"LM_STUDIO_BASE_URL",model:"LM_STUDIO_MODEL",optional:!0},defaultModel:"",toolSupport:"native",localRuntime:!0,healthCheck:"env-only",setupUrl:"https://lmstudio.ai/"},{name:"llamacpp",aliases:["llama.cpp","llama-cpp"],credentialsKey:"llamacpp",envVars:{baseURL:"LLAMACPP_BASE_URL",model:"LLAMACPP_MODEL",optional:!0},defaultModel:"",toolSupport:"native",localRuntime:!0,healthCheck:"env-only",setupUrl:"https://github.com/ggerganov/llama.cpp"},{name:"xai",aliases:["grok"],credentialsKey:"xai",envVars:{apiKey:"XAI_API_KEY",baseURL:"XAI_BASE_URL",model:"XAI_MODEL"},defaultModel:"grok-3",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.x.ai/"},{name:"cerebras",aliases:[],credentialsKey:"cerebras",envVars:{apiKey:"CEREBRAS_API_KEY",baseURL:"CEREBRAS_BASE_URL",model:"CEREBRAS_MODEL"},defaultModel:"gpt-oss-120b",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://cloud.cerebras.ai"},{name:"groq",aliases:[],credentialsKey:"groq",envVars:{apiKey:"GROQ_API_KEY",baseURL:"GROQ_BASE_URL",model:"GROQ_MODEL"},defaultModel:"llama-3.3-70b-versatile",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://console.groq.com/keys"},{name:"cohere",aliases:[],credentialsKey:"cohere",envVars:{apiKey:"COHERE_API_KEY",baseURL:"COHERE_BASE_URL",model:"COHERE_MODEL"},defaultModel:"command-r-plus-08-2024",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://dashboard.cohere.com/api-keys"},{name:"together-ai",aliases:["together"],credentialsKey:"together",envVars:{apiKey:"TOGETHER_API_KEY",baseURL:"TOGETHER_BASE_URL",model:"TOGETHER_MODEL"},defaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://api.together.xyz/settings/api-keys"},{name:"fireworks",aliases:[],credentialsKey:"fireworks",envVars:{apiKey:"FIREWORKS_API_KEY",baseURL:"FIREWORKS_BASE_URL",model:"FIREWORKS_MODEL"},defaultModel:"accounts/fireworks/models/deepseek-v4-pro",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://fireworks.ai/account/api-keys"},{name:"perplexity",aliases:["pplx"],credentialsKey:"perplexity",envVars:{apiKey:"PERPLEXITY_API_KEY",baseURL:"PERPLEXITY_BASE_URL",model:"PERPLEXITY_MODEL"},defaultModel:"sonar",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://www.perplexity.ai/settings/api"},{name:"cloudflare",aliases:["workers-ai","cf-ai"],credentialsKey:"cloudflare",envVars:{apiKey:"CLOUDFLARE_API_KEY",extraRequired:["CLOUDFLARE_ACCOUNT_ID"],model:"CLOUDFLARE_MODEL"},defaultModel:"@cf/meta/llama-3.3-70b-instruct-fp8-fast",toolSupport:"native",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://dash.cloudflare.com/profile/api-tokens"},{name:"replicate",aliases:[],credentialsKey:"replicate",envVars:{apiKey:"REPLICATE_API_TOKEN",model:"REPLICATE_MODEL"},defaultModel:"meta/meta-llama-3-70b-instruct",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://replicate.com/account/api-tokens"},{name:"voyage",aliases:["voyage-ai"],credentialsKey:"voyage",envVars:{apiKey:"VOYAGE_API_KEY",baseURL:"VOYAGE_BASE_URL",model:"VOYAGE_MODEL"},defaultModel:"voyage-3.5",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://dash.voyageai.com/api-keys"},{name:"jina",aliases:["jina-ai"],credentialsKey:"jina",envVars:{apiKey:"JINA_API_KEY",baseURL:"JINA_BASE_URL",model:"JINA_MODEL"},defaultModel:"jina-embeddings-v3",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://jina.ai/?sui=apikey"},{name:"stability",aliases:["stability-ai","sd"],credentialsKey:"stability",envVars:{apiKey:"STABILITY_API_KEY",baseURL:"STABILITY_BASE_URL",model:"STABILITY_MODEL"},defaultModel:"stable-image-ultra",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://platform.stability.ai/account/keys"},{name:"ideogram",aliases:[],credentialsKey:"ideogram",envVars:{apiKey:"IDEOGRAM_API_KEY",baseURL:"IDEOGRAM_BASE_URL",model:"IDEOGRAM_MODEL"},defaultModel:"V_3",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://developer.ideogram.ai/"},{name:"recraft",aliases:[],credentialsKey:"recraft",envVars:{apiKey:"RECRAFT_API_KEY",baseURL:"RECRAFT_BASE_URL",model:"RECRAFT_MODEL"},defaultModel:"recraftv3",toolSupport:"none",localRuntime:!1,healthCheck:"env-only",setupUrl:"https://www.recraft.ai/api"}],Zr=new Map(Cd.map(e=>[e.name,e])),WA=new Map(Cd.flatMap(e=>[[e.name.toLowerCase(),e.name],...e.aliases.map(t=>[t.toLowerCase(),e.name])]))}}),AF={};he(AF,{ProviderFactory:()=>Ur,createAIProvider:()=>jcr,resolveCredentialKey:()=>due});function due(e){const t=e.toLowerCase();return Ur.getDescriptor(t)?.credentialsKey??t}async function jcr(e,t,r){return await Ur.createProvider(e,t,void 0,void 0,r)}var Ur,aa=S({"src/lib/factories/providerFactory.ts"(){"use strict";q(),By(),Ur=class Ti{static providers=new Map;static initialized=!1;static registerProvider(t,r,n,o=[],s){const i={constructor:r,defaultModel:n,aliases:o,descriptor:s};Ti.providers.set(t.toLowerCase(),i),o.forEach(a=>{Ti.providers.set(a.toLowerCase(),i)}),f.debug(`Registered provider: ${t} with model ${n||"from-env"}`)}static async createProvider(t,r,n,o,s){const i=t||process.env.NEUROLINK_PROVIDER||process.env.AI_PROVIDER||"vertex",a=i.toLowerCase(),l=Ti.providers.get(a);if(!l)throw new Error(`Unknown provider: ${i}. Available providers: ${Ti.getAvailableProviders().join(", ")}`);let c=r;c||(i.toLowerCase().includes("vertex")?c=process.env.VERTEX_MODEL||"gemini-2.5-flash":i.toLowerCase().includes("bedrock")&&(c=process.env.BEDROCK_MODEL||process.env.BEDROCK_MODEL_ID),c=c||l.defaultModel);const u=due(a),d=s?s[u]:void 0;try{if(typeof l.constructor!="function")throw new Error(`Invalid constructor for provider ${t}: not a function`);const m=l.constructor(c,i,n,o,d);return m instanceof Promise?await m:m}catch(m){throw f.error(`Failed to create provider ${i}:`,m),new Error(`Failed to create provider ${i}: ${m}`,{cause:m})}}static hasProvider(t){return Ti.providers.has(t.toLowerCase())}static getAvailableProviders(){return Array.from(Ti.providers.keys()).filter((t,r,n)=>n.indexOf(t)===r)}static getProviderInfo(t){return Ti.providers.get(t.toLowerCase())}static getDescriptor(t){const r=t.toLowerCase(),n=WA.get(r);if(n){const o=Zr.get(n);if(o)return o}return Ti.providers.get(r)?.descriptor}static getAllDescriptors(){return Cd}static normalizeProviderName(t){const r=t.toLowerCase();if(Ti.providers.has(r))return r;const n=WA.get(r);if(n&&Ti.providers.has(n))return n;for(const[o,s]of Ti.providers.entries())if(s.aliases?.includes(r))return o;return null}static clearRegistrations(){Ti.providers.clear(),Ti.initialized=!1}static ensureInitialized(){Ti.initialized||(Ti.initializeDefaultProviders(),Ti.initialized=!0)}static initializeDefaultProviders(){f.debug("BaseProvider factory pattern ready - providers registered by ProviderRegistry")}static async createBestProvider(t,r,n,o,s){return await Ti.createProvider(t,r,o,void 0,s)}}}}),qcr=S({"src/lib/types/enums.ts"(){"use strict"}}),Gcr=S({"src/lib/types/action.ts"(){"use strict"}}),pue,IF,mue,RF=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/Options.js"(){pue=Symbol("Let zodToJsonSchema decide on which parser to use"),IF={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},mue=e=>typeof e=="string"?{...IF,name:e}:{...IF,...e}}}),hue,fue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/Refs.js"(){RF(),hue=e=>{const t=mue(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}}}});function gue(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function zr(e,t,r,n,o){e[t]=r,gue(e,t,n,o)}var Oh=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/errorMessages.js"(){}}),PF,MF=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js"(){PF=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")}}}),Ar,yue,ht,kd,KA=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/util.js"(){(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{const s={};for(const i of o)s[i]=i;return s},e.getValidEnumValues=o=>{const s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(const a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(const i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Ar||(Ar={})),(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(yue||(yue={})),ht=Ar.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kd=e=>{switch(typeof e){case"undefined":return ht.undefined;case"string":return ht.string;case"number":return Number.isNaN(e)?ht.nan:ht.number;case"boolean":return ht.boolean;case"function":return ht.function;case"bigint":return ht.bigint;case"symbol":return ht.symbol;case"object":return Array.isArray(e)?ht.array:e===null?ht.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ht.promise:typeof Map<"u"&&e instanceof Map?ht.map:typeof Set<"u"&&e instanceof Set?ht.set:typeof Date<"u"&&e instanceof Date?ht.date:ht.object;default:return ht.unknown}}}}),Ke,$c,DF=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/ZodError.js"(){KA(),Ke=Ar.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$c=class wlr extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){const r=t||function(s){return s.message},n={_errors:[]},o=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,l=0;for(;l<i.path.length;){const c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(r(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),n}static assert(t){if(!(t instanceof wlr))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ar.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){const r=Object.create(null),n=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];r[s]=r[s]||[],r[s].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}},$c.create=e=>new $c(e)}}),vue,zy,_ue=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/locales/en.js"(){DF(),KA(),vue=(e,t)=>{let r;switch(e.code){case Ke.invalid_type:e.received===ht.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case Ke.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ar.jsonStringifyReplacer)}`;break;case Ke.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ar.joinValues(e.keys,", ")}`;break;case Ke.invalid_union:r="Invalid input";break;case Ke.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ar.joinValues(e.options)}`;break;case Ke.invalid_enum_value:r=`Invalid enum value. Expected ${Ar.joinValues(e.options)}, received '${e.received}'`;break;case Ke.invalid_arguments:r="Invalid function arguments";break;case Ke.invalid_return_type:r="Invalid function return type";break;case Ke.invalid_date:r="Invalid date";break;case Ke.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Ar.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case Ke.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case Ke.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case Ke.custom:r="Invalid input";break;case Ke.invalid_intersection_types:r="Intersection results could not be merged";break;case Ke.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case Ke.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ar.assertNever(e)}return{message:r}},zy=vue}});function OF(){return wue}var wue,NF=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/errors.js"(){_ue(),wue=zy}});function at(e,t){const r=OF(),n=JA({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===zy?void 0:zy].filter(o=>!!o)});e.common.issues.push(n)}var JA,Oa,Nt,jy,la,LF,$F,Nh,gb,bue=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/parseUtil.js"(){NF(),_ue(),JA=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="";const l=n.filter(c=>!!c).slice().reverse();for(const c of l)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Oa=class blr{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){const n=[];for(const o of r){if(o.status==="aborted")return Nt;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){const n=[];for(const o of r){const s=await o.key,i=await o.value;n.push({key:s,value:i})}return blr.mergeObjectSync(t,n)}static mergeObjectSync(t,r){const n={};for(const o of r){const{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return Nt;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:t.value,value:n}}},Nt=Object.freeze({status:"aborted"}),jy=e=>({status:"dirty",value:e}),la=e=>({status:"valid",value:e}),LF=e=>e.status==="aborted",$F=e=>e.status==="dirty",Nh=e=>e.status==="valid",gb=e=>typeof Promise<"u"&&e instanceof Promise}}),Hcr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/typeAliases.js"(){}}),bt,Vcr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/helpers/errorUtil.js"(){(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(bt||(bt={}))}});function tr(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{const{message:l}=e;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??r??a.defaultError}},description:o}}function Tue(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Wcr(e){return new RegExp(`^${Tue(e)}$`)}function Kcr(e){let t=`${zF}T${Tue(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Jcr(e,t){return!!((t==="v4"||!t)&&Due.test(e)||(t==="v6"||!t)&&Nue.test(e))}function Ycr(e,t){if(!Iue.test(e))return!1;try{const[r]=e.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Zcr(e,t){return!!((t==="v4"||!t)&&Oue.test(e)||(t==="v6"||!t)&&Lue.test(e))}function Xcr(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function qy(e){if(e instanceof Kl){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=$u.create(qy(n))}return new Kl({...e._def,shape:()=>t})}else return e instanceof $h?new $h({...e._def,type:qy(e.element)}):e instanceof $u?$u.create(qy(e.unwrap())):e instanceof Zp?Zp.create(qy(e.unwrap())):e instanceof Yp?Yp.create(e.items.map(t=>qy(t))):e}function FF(e,t){const r=kd(e),n=kd(t);if(e===t)return{valid:!0,data:e};if(r===ht.object&&n===ht.object){const o=Ar.objectKeys(t),s=Ar.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(const a of s){const l=FF(e[a],t[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(r===ht.array&&n===ht.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let s=0;s<e.length;s++){const i=e[s],a=t[s],l=FF(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return r===ht.date&&n===ht.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}function Eue(e,t){return new Sb({values:e,typeName:De.ZodEnum,...tr(t)})}var Fc,UF,pr,Sue,Cue,kue,xue,Aue,Iue,Rue,Pue,Mue,BF,Due,Oue,Nue,Lue,$ue,Fue,zF,Uue,yb,YA,ZA,XA,QA,eI,vb,_b,tI,Lh,xd,rI,$h,Kl,wb,Nu,Bue,bb,Yp,zue,nI,oI,jue,Tb,Eb,Sb,Cb,Gy,Lu,$u,Zp,kb,xb,sI,jF,qF,Ab,Qcr,De,eur,tur,rur,nur,our,sur,iur,aur,lur,cur,uur,dur,pur,mur,hur,fur,gur,yur,vur,_ur,wur,bur,Tur,Eur,Sur,Cur,kur,xur,Aur,Iur,Rur,Pur,Mur,Dur,Our=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/types.js"(){DF(),NF(),Vcr(),bue(),KA(),Fc=class{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},UF=(e,t)=>{if(Nh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new $c(e.common.issues);return this._error=r,this._error}}},pr=class{get description(){return this._def.description}_getType(e){return kd(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:kd(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Oa,ctx:{common:e.parent.common,data:e.data,parsedType:kd(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(gb(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kd(e)},n=this._parseSync({data:e,path:r.path,parent:r});return UF(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kd(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return Nh(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>Nh(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kd(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(gb(n)?n:Promise.resolve(n));return UF(r,o)}refine(e,t){const r=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,o)=>{const s=e(n),i=()=>o.addIssue({code:Ke.custom,...r(n)});return typeof Promise<"u"&&s instanceof Promise?s.then(a=>a?!0:(i(),!1)):s?!0:(i(),!1)})}refinement(e,t){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof t=="function"?t(r,n):t),!1))}_refinement(e){return new Lu({schema:this,typeName:De.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return $u.create(this,this._def)}nullable(){return Zp.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $h.create(this)}promise(){return Gy.create(this,this._def)}or(e){return wb.create([this,e],this._def)}and(e){return bb.create(this,e,this._def)}transform(e){return new Lu({...tr(this._def),schema:this,typeName:De.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new kb({...tr(this._def),innerType:this,defaultValue:t,typeName:De.ZodDefault})}brand(){return new jF({typeName:De.ZodBranded,type:this,...tr(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new xb({...tr(this._def),innerType:this,catchValue:t,typeName:De.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return qF.create(this,e)}readonly(){return Ab.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Sue=/^c[^\s-]{8,}$/i,Cue=/^[0-9a-z]+$/,kue=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xue=/^[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}$/i,Aue=/^[a-z0-9_-]{21}$/i,Iue=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rue=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Pue=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Mue="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Due=/^(?:(?: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])$/,Oue=/^(?:(?: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])$/,Nue=/^(([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]))$/,Lue=/^(([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])$/,$ue=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Fue=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zF="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Uue=new RegExp(`^${zF}$`),yb=class IA extends pr{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ht.string){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_type,expected:ht.string,received:s.parsedType}),Nt}const n=new Oa;let o;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?at(o,{code:Ke.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&at(o,{code:Ke.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Pue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"email",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")BF||(BF=new RegExp(Mue,"u")),BF.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"emoji",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")xue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"uuid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Aue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"nanoid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Sue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"cuid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Cue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"cuid2",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")kue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"ulid",code:Ke.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),at(o,{validation:"url",code:Ke.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"regex",code:Ke.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Kcr(s).test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Uue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Wcr(s).test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Rue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"duration",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Jcr(t.data,s.version)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"ip",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?Ycr(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"jwt",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Zcr(t.data,s.version)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"cidr",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?$ue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"base64",code:Ke.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?Fue.test(t.data)||(o=this._getOrReturnCtx(t,o),at(o,{validation:"base64url",code:Ke.invalid_string,message:s.message}),n.dirty()):Ar.assertNever(s);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:Ke.invalid_string,...bt.errToObj(n)})}_addCheck(t){return new IA({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...bt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...bt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...bt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...bt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...bt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...bt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...bt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...bt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...bt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...bt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...bt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...bt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...bt.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...bt.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...bt.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...bt.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...bt.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...bt.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...bt.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...bt.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...bt.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...bt.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...bt.errToObj(r)})}nonempty(t){return this.min(1,bt.errToObj(t))}trim(){return new IA({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new IA({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new IA({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}},yb.create=e=>new yb({checks:[],typeName:De.ZodString,coerce:e?.coerce??!1,...tr(e)}),YA=class lce extends pr{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ht.number){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_type,expected:ht.number,received:s.parsedType}),Nt}let n;const o=new Oa;for(const s of this._def.checks)s.kind==="int"?Ar.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Xcr(t.data,s.value)!==0&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.not_finite,message:s.message}),o.dirty()):Ar.assertNever(s);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,bt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,bt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,bt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,bt.toString(r))}setLimit(t,r,n,o){return new lce({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:bt.toString(o)}]})}_addCheck(t){return new lce({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:bt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:bt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:bt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:bt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:bt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:bt.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:bt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:bt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:bt.toString(t)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Ar.isInteger(t.value))}get isFinite(){let t=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}},YA.create=e=>new YA({checks:[],typeName:De.ZodNumber,coerce:e?.coerce||!1,...tr(e)}),ZA=class cce extends pr{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ht.bigint)return this._getInvalidInput(t);let n;const o=new Oa;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),at(n,{code:Ke.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Ar.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){const r=this._getOrReturnCtx(t);return at(r,{code:Ke.invalid_type,expected:ht.bigint,received:r.parsedType}),Nt}gte(t,r){return this.setLimit("min",t,!0,bt.toString(r))}gt(t,r){return this.setLimit("min",t,!1,bt.toString(r))}lte(t,r){return this.setLimit("max",t,!0,bt.toString(r))}lt(t,r){return this.setLimit("max",t,!1,bt.toString(r))}setLimit(t,r,n,o){return new cce({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:bt.toString(o)}]})}_addCheck(t){return new cce({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:bt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:bt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:bt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:bt.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:bt.toString(r)})}get minValue(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}},ZA.create=e=>new ZA({checks:[],typeName:De.ZodBigInt,coerce:e?.coerce??!1,...tr(e)}),XA=class extends pr{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ht.boolean){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.boolean,received:r.parsedType}),Nt}return la(e.data)}},XA.create=e=>new XA({typeName:De.ZodBoolean,coerce:e?.coerce||!1,...tr(e)}),QA=class Tlr extends pr{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ht.date){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_type,expected:ht.date,received:s.parsedType}),Nt}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return at(s,{code:Ke.invalid_date}),Nt}const n=new Oa;let o;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),at(o,{code:Ke.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Ar.assertNever(s);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Tlr({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:bt.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:bt.toString(r)})}get minDate(){let t=null;for(const r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}},QA.create=e=>new QA({checks:[],coerce:e?.coerce||!1,typeName:De.ZodDate,...tr(e)}),eI=class extends pr{_parse(e){if(this._getType(e)!==ht.symbol){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.symbol,received:r.parsedType}),Nt}return la(e.data)}},eI.create=e=>new eI({typeName:De.ZodSymbol,...tr(e)}),vb=class extends pr{_parse(e){if(this._getType(e)!==ht.undefined){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.undefined,received:r.parsedType}),Nt}return la(e.data)}},vb.create=e=>new vb({typeName:De.ZodUndefined,...tr(e)}),_b=class extends pr{_parse(e){if(this._getType(e)!==ht.null){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.null,received:r.parsedType}),Nt}return la(e.data)}},_b.create=e=>new _b({typeName:De.ZodNull,...tr(e)}),tI=class extends pr{constructor(){super(...arguments),this._any=!0}_parse(e){return la(e.data)}},tI.create=e=>new tI({typeName:De.ZodAny,...tr(e)}),Lh=class extends pr{constructor(){super(...arguments),this._unknown=!0}_parse(e){return la(e.data)}},Lh.create=e=>new Lh({typeName:De.ZodUnknown,...tr(e)}),xd=class extends pr{_parse(e){const t=this._getOrReturnCtx(e);return at(t,{code:Ke.invalid_type,expected:ht.never,received:t.parsedType}),Nt}},xd.create=e=>new xd({typeName:De.ZodNever,...tr(e)}),rI=class extends pr{_parse(e){if(this._getType(e)!==ht.undefined){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.void,received:r.parsedType}),Nt}return la(e.data)}},rI.create=e=>new rI({typeName:De.ZodVoid,...tr(e)}),$h=class dF extends pr{_parse(t){const{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==ht.array)return at(r,{code:Ke.invalid_type,expected:ht.array,received:r.parsedType}),Nt;if(o.exactLength!==null){const i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(at(r,{code:i?Ke.too_big:Ke.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(at(r,{code:Ke.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(at(r,{code:Ke.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Fc(r,i,r.path,a)))).then(i=>Oa.mergeArray(n,i));const s=[...r.data].map((i,a)=>o.type._parseSync(new Fc(r,i,r.path,a)));return Oa.mergeArray(n,s)}get element(){return this._def.type}min(t,r){return new dF({...this._def,minLength:{value:t,message:bt.toString(r)}})}max(t,r){return new dF({...this._def,maxLength:{value:t,message:bt.toString(r)}})}length(t,r){return new dF({...this._def,exactLength:{value:t,message:bt.toString(r)}})}nonempty(t){return this.min(1,t)}},$h.create=(e,t)=>new $h({type:e,minLength:null,maxLength:null,exactLength:null,typeName:De.ZodArray,...tr(t)}),Kl=class Pu extends pr{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),r=Ar.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==ht.object){const c=this._getOrReturnCtx(t);return at(c,{code:Ke.invalid_type,expected:ht.object,received:c.parsedType}),Nt}const{status:n,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof xd&&this._def.unknownKeys==="strip"))for(const c in o.data)i.includes(c)||a.push(c);const l=[];for(const c of i){const u=s[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Fc(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof xd){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(at(o,{code:Ke.unrecognized_keys,keys:a}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Fc(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const d=await u.key,m=await u.value;c.push({key:d,value:m,alwaysSet:u.alwaysSet})}return c}).then(c=>Oa.mergeObjectSync(n,c)):Oa.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return bt.errToObj,new Pu({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{const o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:bt.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Pu({...this._def,unknownKeys:"strip"})}passthrough(){return new Pu({...this._def,unknownKeys:"passthrough"})}extend(t){return new Pu({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Pu({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:De.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new Pu({...this._def,catchall:t})}pick(t){const r={};for(const n of Ar.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Pu({...this._def,shape:()=>r})}omit(t){const r={};for(const n of Ar.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new Pu({...this._def,shape:()=>r})}deepPartial(){return qy(this)}partial(t){const r={};for(const n of Ar.objectKeys(this.shape)){const o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new Pu({...this._def,shape:()=>r})}required(t){const r={};for(const n of Ar.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof $u;)s=s._def.innerType;r[n]=s}return new Pu({...this._def,shape:()=>r})}keyof(){return Eue(Ar.objectKeys(this.shape))}},Kl.create=(e,t)=>new Kl({shape:()=>e,unknownKeys:"strip",catchall:xd.create(),typeName:De.ZodObject,...tr(t)}),Kl.strictCreate=(e,t)=>new Kl({shape:()=>e,unknownKeys:"strict",catchall:xd.create(),typeName:De.ZodObject,...tr(t)}),Kl.lazycreate=(e,t)=>new Kl({shape:e,unknownKeys:"strip",catchall:xd.create(),typeName:De.ZodObject,...tr(t)}),wb=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function n(o){for(const i of o)if(i.result.status==="valid")return i.result;for(const i of o)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;const s=o.map(i=>new $c(i.ctx.common.issues));return at(t,{code:Ke.invalid_union,unionErrors:s}),Nt}if(t.common.async)return Promise.all(r.map(async o=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(n);{let o;const s=[];for(const a of r){const l={...t,common:{...t.common,issues:[]},parent:null},c=a._parseSync({data:t.data,path:t.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!o&&(o={result:c,ctx:l}),l.common.issues.length&&s.push(l.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;const i=s.map(a=>new $c(a));return at(t,{code:Ke.invalid_union,unionErrors:i}),Nt}}get options(){return this._def.options}},wb.create=(e,t)=>new wb({options:e,typeName:De.ZodUnion,...tr(t)}),Nu=e=>e instanceof Tb?Nu(e.schema):e instanceof Lu?Nu(e.innerType()):e instanceof Eb?[e.value]:e instanceof Sb?e.options:e instanceof Cb?Ar.objectValues(e.enum):e instanceof kb?Nu(e._def.innerType):e instanceof vb?[void 0]:e instanceof _b?[null]:e instanceof $u?[void 0,...Nu(e.unwrap())]:e instanceof Zp?[null,...Nu(e.unwrap())]:e instanceof jF||e instanceof Ab?Nu(e.unwrap()):e instanceof xb?Nu(e._def.innerType):[],Bue=class Elr extends pr{_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ht.object)return at(r,{code:Ke.invalid_type,expected:ht.object,received:r.parsedType}),Nt;const n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(at(r,{code:Ke.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Nt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){const o=new Map;for(const s of r){const i=Nu(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new Elr({typeName:De.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...tr(n)})}},bb=class extends pr{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(o,s)=>{if(LF(o)||LF(s))return Nt;const i=FF(o.value,s.value);return i.valid?(($F(o)||$F(s))&&t.dirty(),{status:t.value,value:i.data}):(at(r,{code:Ke.invalid_intersection_types}),Nt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,s])=>n(o,s)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}},bb.create=(e,t,r)=>new bb({left:e,right:t,typeName:De.ZodIntersection,...tr(r)}),Yp=class Slr extends pr{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ht.array)return at(n,{code:Ke.invalid_type,expected:ht.array,received:n.parsedType}),Nt;if(n.data.length<this._def.items.length)return at(n,{code:Ke.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Nt;!this._def.rest&&n.data.length>this._def.items.length&&(at(n,{code:Ke.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Fc(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Oa.mergeArray(r,i)):Oa.mergeArray(r,s)}get items(){return this._def.items}rest(t){return new Slr({...this._def,rest:t})}},Yp.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Yp({items:e,typeName:De.ZodTuple,rest:null,...tr(t)})},zue=class uce extends pr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ht.object)return at(n,{code:Ke.invalid_type,expected:ht.object,received:n.parsedType}),Nt;const o=[],s=this._def.keyType,i=this._def.valueType;for(const a in n.data)o.push({key:s._parse(new Fc(n,a,n.path,a)),value:i._parse(new Fc(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Oa.mergeObjectAsync(r,o):Oa.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof pr?new uce({keyType:t,valueType:r,typeName:De.ZodRecord,...tr(n)}):new uce({keyType:yb.create(),valueType:t,typeName:De.ZodRecord,...tr(r)})}},nI=class extends pr{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ht.map)return at(r,{code:Ke.invalid_type,expected:ht.map,received:r.parsedType}),Nt;const n=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([i,a],l)=>({key:n._parse(new Fc(r,i,r.path,[l,"key"])),value:o._parse(new Fc(r,a,r.path,[l,"value"]))}));if(r.common.async){const i=new Map;return Promise.resolve().then(async()=>{for(const a of s){const l=await a.key,c=await a.value;if(l.status==="aborted"||c.status==="aborted")return Nt;(l.status==="dirty"||c.status==="dirty")&&t.dirty(),i.set(l.value,c.value)}return{status:t.value,value:i}})}else{const i=new Map;for(const a of s){const l=a.key,c=a.value;if(l.status==="aborted"||c.status==="aborted")return Nt;(l.status==="dirty"||c.status==="dirty")&&t.dirty(),i.set(l.value,c.value)}return{status:t.value,value:i}}}},nI.create=(e,t,r)=>new nI({valueType:t,keyType:e,typeName:De.ZodMap,...tr(r)}),oI=class dce extends pr{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==ht.set)return at(n,{code:Ke.invalid_type,expected:ht.set,received:n.parsedType}),Nt;const o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(at(n,{code:Ke.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(at(n,{code:Ke.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());const s=this._def.valueType;function i(l){const c=new Set;for(const u of l){if(u.status==="aborted")return Nt;u.status==="dirty"&&r.dirty(),c.add(u.value)}return{status:r.value,value:c}}const a=[...n.data.values()].map((l,c)=>s._parse(new Fc(n,l,n.path,c)));return n.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(t,r){return new dce({...this._def,minSize:{value:t,message:bt.toString(r)}})}max(t,r){return new dce({...this._def,maxSize:{value:t,message:bt.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}},oI.create=(e,t)=>new oI({valueType:e,minSize:null,maxSize:null,typeName:De.ZodSet,...tr(t)}),jue=class pF extends pr{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:r}=this._processInputParams(t);if(r.parsedType!==ht.function)return at(r,{code:Ke.invalid_type,expected:ht.function,received:r.parsedType}),Nt;function n(a,l){return JA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,OF(),zy].filter(c=>!!c),issueData:{code:Ke.invalid_arguments,argumentsError:l}})}function o(a,l){return JA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,OF(),zy].filter(c=>!!c),issueData:{code:Ke.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Gy){const a=this;return la(async function(...l){const c=new $c([]),u=await a._def.args.parseAsync(l,s).catch(h=>{throw c.addIssue(n(l,h)),c}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,s).catch(h=>{throw c.addIssue(o(d,h)),c})})}else{const a=this;return la(function(...l){const c=a._def.args.safeParse(l,s);if(!c.success)throw new $c([n(l,c.error)]);const u=Reflect.apply(i,this,c.data),d=a._def.returns.safeParse(u,s);if(!d.success)throw new $c([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new pF({...this._def,args:Yp.create(t).rest(Lh.create())})}returns(t){return new pF({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new pF({args:t||Yp.create([]).rest(Lh.create()),returns:r||Lh.create(),typeName:De.ZodFunction,...tr(n)})}},Tb=class extends pr{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}},Tb.create=(e,t)=>new Tb({getter:e,typeName:De.ZodLazy,...tr(t)}),Eb=class extends pr{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return at(t,{received:t.data,code:Ke.invalid_literal,expected:this._def.value}),Nt}return{status:"valid",value:e.data}}get value(){return this._def.value}},Eb.create=(e,t)=>new Eb({value:e,typeName:De.ZodLiteral,...tr(t)}),Sb=class pce extends pr{_parse(t){if(typeof t.data!="string"){const r=this._getOrReturnCtx(t),n=this._def.values;return at(r,{expected:Ar.joinValues(n),received:r.parsedType,code:Ke.invalid_type}),Nt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const r=this._getOrReturnCtx(t),n=this._def.values;return at(r,{received:r.data,code:Ke.invalid_enum_value,options:n}),Nt}return la(t.data)}get options(){return this._def.values}get enum(){const t={};for(const r of this._def.values)t[r]=r;return t}get Values(){const t={};for(const r of this._def.values)t[r]=r;return t}get Enum(){const t={};for(const r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return pce.create(t,{...this._def,...r})}exclude(t,r=this._def){return pce.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}},Sb.create=Eue,Cb=class extends pr{_parse(e){const t=Ar.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ht.string&&r.parsedType!==ht.number){const n=Ar.objectValues(t);return at(r,{expected:Ar.joinValues(n),received:r.parsedType,code:Ke.invalid_type}),Nt}if(this._cache||(this._cache=new Set(Ar.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const n=Ar.objectValues(t);return at(r,{received:r.data,code:Ke.invalid_enum_value,options:n}),Nt}return la(e.data)}get enum(){return this._def.values}},Cb.create=(e,t)=>new Cb({values:e,typeName:De.ZodNativeEnum,...tr(t)}),Gy=class extends pr{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ht.promise&&t.common.async===!1)return at(t,{code:Ke.invalid_type,expected:ht.promise,received:t.parsedType}),Nt;const r=t.parsedType===ht.promise?t.data:Promise.resolve(t.data);return la(r.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}},Gy.create=(e,t)=>new Gy({type:e,typeName:De.ZodPromise,...tr(t)}),Lu=class extends pr{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===De.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:s=>{at(r,s),s.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){const s=n.transform(r.data,o);if(r.common.async)return Promise.resolve(s).then(async i=>{if(t.value==="aborted")return Nt;const a=await this._def.schema._parseAsync({data:i,path:r.path,parent:r});return a.status==="aborted"?Nt:a.status==="dirty"||t.value==="dirty"?jy(a.value):a});{if(t.value==="aborted")return Nt;const i=this._def.schema._parseSync({data:s,path:r.path,parent:r});return i.status==="aborted"?Nt:i.status==="dirty"||t.value==="dirty"?jy(i.value):i}}if(n.type==="refinement"){const s=i=>{const a=n.refinement(i,o);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Nt:(i.status==="dirty"&&t.dirty(),s(i.value),{status:t.value,value:i.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>i.status==="aborted"?Nt:(i.status==="dirty"&&t.dirty(),s(i.value).then(()=>({status:t.value,value:i.value}))))}if(n.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Nh(s))return Nt;const i=n.transform(s.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Nh(s)?Promise.resolve(n.transform(s.value,o)).then(i=>({status:t.value,value:i})):Nt);Ar.assertNever(n)}},Lu.create=(e,t,r)=>new Lu({schema:e,typeName:De.ZodEffects,effect:t,...tr(r)}),Lu.createWithPreprocess=(e,t,r)=>new Lu({schema:t,effect:{type:"preprocess",transform:e},typeName:De.ZodEffects,...tr(r)}),$u=class extends pr{_parse(e){return this._getType(e)===ht.undefined?la(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},$u.create=(e,t)=>new $u({innerType:e,typeName:De.ZodOptional,...tr(t)}),Zp=class extends pr{_parse(e){return this._getType(e)===ht.null?la(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},Zp.create=(e,t)=>new Zp({innerType:e,typeName:De.ZodNullable,...tr(t)}),kb=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ht.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}},kb.create=(e,t)=>new kb({innerType:e,typeName:De.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...tr(t)}),xb=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return gb(n)?n.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new $c(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new $c(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}},xb.create=(e,t)=>new xb({innerType:e,typeName:De.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...tr(t)}),sI=class extends pr{_parse(e){if(this._getType(e)!==ht.nan){const r=this._getOrReturnCtx(e);return at(r,{code:Ke.invalid_type,expected:ht.nan,received:r.parsedType}),Nt}return{status:"valid",value:e.data}}},sI.create=e=>new sI({typeName:De.ZodNaN,...tr(e)}),jF=class extends pr{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},qF=class Clr extends pr{_parse(t){const{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Nt:s.status==="dirty"?(r.dirty(),jy(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Nt:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new Clr({in:t,out:r,typeName:De.ZodPipeline})}},Ab=class extends pr{_parse(e){const t=this._def.innerType._parse(e),r=n=>(Nh(n)&&(n.value=Object.freeze(n.value)),n);return gb(t)?t.then(n=>r(n)):r(t)}unwrap(){return this._def.innerType}},Ab.create=(e,t)=>new Ab({innerType:e,typeName:De.ZodReadonly,...tr(t)}),Qcr={object:Kl.lazycreate},(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(De||(De={})),eur=yb.create,tur=YA.create,rur=sI.create,nur=ZA.create,our=XA.create,sur=QA.create,iur=eI.create,aur=vb.create,lur=_b.create,cur=tI.create,uur=Lh.create,dur=xd.create,pur=rI.create,mur=$h.create,hur=Kl.create,fur=Kl.strictCreate,gur=wb.create,yur=Bue.create,vur=bb.create,_ur=Yp.create,wur=zue.create,bur=nI.create,Tur=oI.create,Eur=jue.create,Sur=Tb.create,Cur=Eb.create,kur=Sb.create,xur=Cb.create,Aur=Gy.create,Iur=Lu.create,Rur=$u.create,Pur=Zp.create,Mur=Lu.createWithPreprocess,Dur=qF.create}}),que=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/external.js"(){NF(),bue(),Hcr(),KA(),Our(),DF()}}),Fh=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v3/index.js"(){que(),que()}});function Na(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?PF(t,e.currentPath):t.join("/")}}var Uc=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/any.js"(){MF()}});function Nur(e,t){const r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==De.ZodAny&&(r.items=Nr(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&zr(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&zr(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(zr(r,"minItems",e.exactLength.value,e.exactLength.message,t),zr(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}var Gue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/array.js"(){Fh(),Oh(),Ps()}});function Lur(e,t){const r={type:"integer",format:"int64"};if(!e.checks)return r;for(const n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?zr(r,"minimum",n.value,n.message,t):zr(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),zr(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?zr(r,"maximum",n.value,n.message,t):zr(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),zr(r,"maximum",n.value,n.message,t));break;case"multipleOf":zr(r,"multipleOf",n.value,n.message,t);break}return r}var Hue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"(){Oh()}});function $ur(){return{type:"boolean"}}var Vue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"(){}});function Wue(e,t){return Nr(e.type._def,t)}var GF=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"(){Ps()}}),Kue,Jue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"(){Ps(),Kue=(e,t)=>Nr(e.innerType._def,t)}});function Yue(e,t,r){const n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Yue(e,t,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Zue(e,t)}}var Zue,Xue=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/date.js"(){Oh(),Zue=(e,t)=>{const r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(const n of e.checks)switch(n.kind){case"min":zr(r,"minimum",n.value,n.message,t);break;case"max":zr(r,"maximum",n.value,n.message,t);break}return r}}});function Fur(e,t){return{...Nr(e.innerType._def,t),default:e.defaultValue()}}var Que=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/default.js"(){Ps()}});function Uur(e,t){return t.effectStrategy==="input"?Nr(e.schema._def,t):Na(t)}var ede=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"(){Ps(),Uc()}});function Bur(e){return{type:"string",enum:Array.from(e.values)}}var tde=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"(){}});function zur(e,t){const r=[Nr(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Nr(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const o=[];return r.forEach(s=>{if(rde(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:a,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var rde,nde=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"(){Ps(),rde=e=>"type"in e&&e.type==="string"?!1:"allOf"in e}});function jur(e,t){const r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var ode=S({"node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.3.6/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"(){}});function sde(e,t){const r={type:"string"};if(e.checks)for(const n of e.checks)switch(n.kind){case"min":zr(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":zr(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":Bc(r,"email",n.message,t);break;case"format:idn-email":Bc(r,"idn-email",n.message,t);break;case"pattern:zod":ca(r,Jl.email,n.message,t);break}break;case"url":Bc(r,"uri",n.message,t);break;case"uuid":Bc(r,"uuid",n.message,t);break;case"regex":ca(r,n.regex,n.message,t);break;case"cuid":ca(r,Jl.cuid,n.message,t);break;case"cuid2":ca(r,Jl.cuid2,n.message,t);break;case"startsWith":ca(r,RegExp(`^${HF(n.value,t)}`),n.message,t);break;case"endsWith":ca(r,RegExp(`${HF(n.value,t)}$`),n.message,t);break;case"datetime":Bc(r,"date-time",n.message,t);break;case"date":Bc(r,"date",n.message,t);break;case"time":Bc(r,"time",n.message,t);break;case"duration":Bc(r,"duration",n.message,t);break;case"length":zr(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),zr(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{ca(r,RegExp(HF(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&Bc(r,"ipv4",n.message,t),n.version!=="v4"&&Bc(r,"ipv6",n.message,t);break}case"base64url":ca(r,Jl.base64url,n.message,t);break;case"jwt":ca(r,Jl.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&ca(r,Jl.ipv4Cidr,n.message,t),n.version!=="v4"&&ca(r,Jl.ipv6Cidr,n.message,t);break}case"emoji":ca(r,Jl.emoji(),n.message,t);break;case"ulid":{ca(r,Jl.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{Bc(r,"binary",n.message,t);break}case"contentEncoding:base64":{zr(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{ca(r,Jl.base64,n.message,t);break}}break}case"nanoid":ca(r,Jl.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function HF(e,t){return t.patternStrategy==="escape"?qur(e):e}function qur(e){let t="";for(let r=0;r<e.length;r++)ade.has(e[r])||(t+="\\"),t+=e[r];return t}function Bc(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):zr(e,"format",t,r,n)}function ca(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:ide(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):zr(e,"pattern",ide(t,n),r,n)}function ide(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.source;let o="",s=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
|
|
15
15
|
]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
|
|
16
16
|
]))`;continue}}if(r.s&&n[l]==="."){o+=i?`${n[l]}\r
|
|
17
17
|
`:`[${n[l]}\r
|
|
@@ -113,7 +113,7 @@ Learn more: \x1B[34m${r}\x1B[0m
|
|
|
113
113
|
|
|
114
114
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
115
115
|
|
|
116
|
-
`)}})}},pq={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"},yvr=We(()=>Ve(p.union([p.strictObject({type:p.literal("text-start"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("text-delta"),id:p.string(),delta:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("text-end"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("error"),errorText:p.string()}),p.strictObject({type:p.literal("tool-input-start"),toolCallId:p.string(),toolName:p.string(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),title:p.string().optional()}),p.strictObject({type:p.literal("tool-input-delta"),toolCallId:p.string(),inputTextDelta:p.string()}),p.strictObject({type:p.literal("tool-input-available"),toolCallId:p.string(),toolName:p.string(),input:p.unknown(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),title:p.string().optional()}),p.strictObject({type:p.literal("tool-input-error"),toolCallId:p.string(),toolName:p.string(),input:p.unknown(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),errorText:p.string(),title:p.string().optional()}),p.strictObject({type:p.literal("tool-approval-request"),approvalId:p.string(),toolCallId:p.string()}),p.strictObject({type:p.literal("tool-output-available"),toolCallId:p.string(),output:p.unknown(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),preliminary:p.boolean().optional()}),p.strictObject({type:p.literal("tool-output-error"),toolCallId:p.string(),errorText:p.string(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional()}),p.strictObject({type:p.literal("tool-output-denied"),toolCallId:p.string()}),p.strictObject({type:p.literal("reasoning-start"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("reasoning-delta"),id:p.string(),delta:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("reasoning-end"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("source-url"),sourceId:p.string(),url:p.string(),title:p.string().optional(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("source-document"),sourceId:p.string(),mediaType:p.string(),title:p.string(),filename:p.string().optional(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("file"),url:p.string(),mediaType:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.custom(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:p.string().optional(),data:p.unknown(),transient:p.boolean().optional()}),p.strictObject({type:p.literal("start-step")}),p.strictObject({type:p.literal("finish-step")}),p.strictObject({type:p.literal("start"),messageId:p.string().optional(),messageMetadata:p.unknown().optional()}),p.strictObject({type:p.literal("finish"),finishReason:p.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:p.unknown().optional()}),p.strictObject({type:p.literal("abort"),reason:p.string().optional()}),p.strictObject({type:p.literal("message-metadata"),messageMetadata:p.unknown()})]))),Kxe=Ev({prefix:"aitxt",size:24}),Jxe=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:i,stepAbortController:a,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:d,messages:m,tools:h,toolChoice:g,transforms:y,activeTools:v,repairToolCall:_,stopConditions:b,output:T,providerOptions:k,prepareStep:A,includeRawChunks:I,now:P,generateId:R,timeout:x,stopWhen:O,originalAbortSignal:N,onChunk:M,onError:D,onFinish:L,onAbort:$,onStepFinish:U,onStart:j,onStepStart:B,onToolCallStart:z,onToolCallFinish:J,experimental_context:Y,download:ie,include:ce}){this._totalUsage=new gl,this._finishReason=new gl,this._rawFinishReason=new gl,this._steps=new gl,this.outputSpecification=T,this.includeRawChunks=I,this.tools=h;const G=QCe()(t?.integrations);let K,Ce=[];const be=[];let ge,H,se,ye={},Q=[];const me=[],$e=new Map;let Se,ne={},Fe={};const ae=new TransformStream({async transform(Ee,ke){var fe,F,te,Ie;ke.enqueue(Ee);const{part:ee}=Ee;if((ee.type==="text-delta"||ee.type==="reasoning-delta"||ee.type==="source"||ee.type==="tool-call"||ee.type==="tool-result"||ee.type==="tool-input-start"||ee.type==="tool-input-delta"||ee.type==="raw")&&await M?.({chunk:ee}),ee.type==="error"&&await D({error:M1(ee.error)}),ee.type==="text-start"&&(ne[ee.id]={type:"text",text:"",providerMetadata:ee.providerMetadata},Ce.push(ne[ee.id])),ee.type==="text-delta"){const ue=ne[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}ue.text+=ee.text,ue.providerMetadata=(fe=ee.providerMetadata)!=null?fe:ue.providerMetadata}if(ee.type==="text-end"){const ue=ne[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}ue.providerMetadata=(F=ee.providerMetadata)!=null?F:ue.providerMetadata,delete ne[ee.id]}if(ee.type==="reasoning-start"&&(Fe[ee.id]={type:"reasoning",text:"",providerMetadata:ee.providerMetadata},Ce.push(Fe[ee.id])),ee.type==="reasoning-delta"){const ue=Fe[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}ue.text+=ee.text,ue.providerMetadata=(te=ee.providerMetadata)!=null?te:ue.providerMetadata}if(ee.type==="reasoning-end"){const ue=Fe[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}ue.providerMetadata=(Ie=ee.providerMetadata)!=null?Ie:ue.providerMetadata,delete Fe[ee.id]}if(ee.type==="file"&&Ce.push({type:"file",file:ee.file,...ee.providerMetadata!=null?{providerMetadata:ee.providerMetadata}:{}}),ee.type==="source"&&Ce.push(ee),ee.type==="tool-call"&&Ce.push(ee),ee.type==="tool-result"&&!ee.preliminary&&Ce.push(ee),ee.type==="tool-approval-request"&&Ce.push(ee),ee.type==="tool-error"&&Ce.push(ee),ee.type==="start-step"&&(Ce=[],Fe={},ne={},ye=ee.request,Q=ee.warnings),ee.type==="finish-step"){const ue=await Ej({content:Ce,tools:h}),Ae=new uq({stepNumber:me.length,model:W,...ve,experimental_context:Y,content:Ce,finishReason:ee.finishReason,rawFinishReason:ee.rawFinishReason,usage:ee.usage,warnings:Q,request:ye,response:{...ee.response,messages:[...be,...ue]},providerMetadata:ee.providerMetadata});await Vc({event:Ae,callbacks:[U,G.onStepFinish]}),Bu({warnings:Q,provider:W.provider,model:W.modelId}),me.push(Ae),be.push(...ue),K.resolve()}ee.type==="finish"&&(se=ee.totalUsage,ge=ee.finishReason,H=ee.rawFinishReason)},async flush(Ee){var ke,fe,F,te,Ie,ee,ue;try{if(me.length===0){const Be=s?.aborted?s.reason:new ac({message:"No output generated. Check the stream for errors."});C._finishReason.reject(Be),C._rawFinishReason.reject(Be),C._totalUsage.reject(Be),C._steps.reject(Be);return}const Ae=ge??"other",Pe=se??O1();C._finishReason.resolve(Ae),C._rawFinishReason.resolve(H),C._totalUsage.resolve(Pe),C._steps.resolve(me);const Ue=me[me.length-1];await Vc({event:{stepNumber:Ue.stepNumber,model:Ue.model,functionId:Ue.functionId,metadata:Ue.metadata,experimental_context:Ue.experimental_context,finishReason:Ue.finishReason,rawFinishReason:Ue.rawFinishReason,totalUsage:Pe,usage:Ue.usage,content:Ue.content,text:Ue.text,reasoningText:Ue.reasoningText,reasoning:Ue.reasoning,files:Ue.files,sources:Ue.sources,toolCalls:Ue.toolCalls,staticToolCalls:Ue.staticToolCalls,dynamicToolCalls:Ue.dynamicToolCalls,toolResults:Ue.toolResults,staticToolResults:Ue.staticToolResults,dynamicToolResults:Ue.dynamicToolResults,request:Ue.request,response:Ue.response,warnings:Ue.warnings,providerMetadata:Ue.providerMetadata,steps:me},callbacks:[L,G.onFinish]}),Se.setAttributes(await $r({telemetry:t,attributes:{"ai.response.finishReason":Ae,"ai.response.text":{output:()=>Ue.text},"ai.response.reasoning":{output:()=>Ue.reasoningText},"ai.response.toolCalls":{output:()=>{var Be;return(Be=Ue.toolCalls)!=null&&Be.length?JSON.stringify(Ue.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Ue.providerMetadata),"ai.usage.inputTokens":Pe.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ke=Pe.inputTokenDetails)==null?void 0:ke.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(fe=Pe.inputTokenDetails)==null?void 0:fe.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(F=Pe.inputTokenDetails)==null?void 0:F.cacheWriteTokens,"ai.usage.outputTokens":Pe.outputTokens,"ai.usage.outputTokenDetails.textTokens":(te=Pe.outputTokenDetails)==null?void 0:te.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ie=Pe.outputTokenDetails)==null?void 0:Ie.reasoningTokens,"ai.usage.totalTokens":Pe.totalTokens,"ai.usage.reasoningTokens":(ee=Pe.outputTokenDetails)==null?void 0:ee.reasoningTokens,"ai.usage.cachedInputTokens":(ue=Pe.inputTokenDetails)==null?void 0:ue.cacheReadTokens}}))}catch(Ae){Ee.error(Ae)}finally{Se.end()}}}),oe=yke();this.addStream=oe.addStream,this.closeStream=oe.close;const pe=oe.stream.getReader();let X=new ReadableStream({async start(Ee){Ee.enqueue({type:"start"})},async pull(Ee){function ke(){$?.({steps:me}),Ee.enqueue({type:"abort",...s?.reason!==void 0?{reason:Zh(s.reason)}:{}}),Ee.close()}try{const{done:fe,value:F}=await pe.read();if(fe){Ee.close();return}if(s?.aborted){ke();return}Ee.enqueue(F)}catch(fe){Xh(fe)&&s?.aborted?ke():Ee.error(fe)}},cancel(Ee){return oe.stream.cancel(Ee)}});for(const Ee of y)X=X.pipeThrough(Ee({tools:h,stopStream(){oe.terminate()}}));this.baseStream=X.pipeThrough(lvr(T??UT())).pipeThrough(ae);const{maxRetries:Z,retry:_e}=nf({maxRetries:o,abortSignal:s}),Re=kv(t),we=rf(n),Je=Cv({model:e,telemetry:t,headers:r,settings:{...we,maxRetries:Z}}),C=this,W={provider:e.provider,modelId:e.modelId},ve={functionId:t?.functionId,metadata:t?.metadata};ja({name:"ai.streamText",attributes:$r({telemetry:t,attributes:{...za({operationId:"ai.streamText",telemetry:t}),...Je,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:d,messages:m})}}}),tracer:Re,endWhenDone:!1,fn:async Ee=>{Se=Ee;const ke=await P1({system:u,prompt:d,messages:m});await Vc({event:{model:W,system:u,prompt:d,messages:m,tools:h,toolChoice:g,activeTools:v,maxOutputTokens:we.maxOutputTokens,temperature:we.temperature,topP:we.topP,topK:we.topK,presencePenalty:we.presencePenalty,frequencyPenalty:we.frequencyPenalty,stopSequences:we.stopSequences,seed:we.seed,maxRetries:Z,timeout:x,headers:r,providerOptions:k,stopWhen:O,output:T,abortSignal:N,include:ce,...ve,experimental_context:Y},callbacks:[j,G.onStart]});const fe=ke.messages,F=[],{approvedToolApprovals:te,deniedToolApprovals:Ie}=rke({messages:fe});if(Ie.length>0||te.length>0){const ue=[...te,...Ie].filter(Ge=>Ge.toolCall.providerExecuted),Ae=te.filter(Ge=>!Ge.toolCall.providerExecuted),Pe=Ie.filter(Ge=>!Ge.toolCall.providerExecuted),Ue=Ie.filter(Ge=>Ge.toolCall.providerExecuted);let Be;const mt=new ReadableStream({start(Ge){Be=Ge}});C.addStream(mt);try{for(const ft of[...Pe,...Ue])Be?.enqueue({type:"tool-output-denied",toolCallId:ft.toolCall.toolCallId,toolName:ft.toolCall.toolName});const Ge=[];if(await Promise.all(Ae.map(async ft=>{const Ot=await _j({toolCall:ft.toolCall,tools:h,tracer:Re,telemetry:t,messages:fe,abortSignal:s,experimental_context:Y,stepNumber:me.length,model:W,onToolCallStart:[z,G.onToolCallStart],onToolCallFinish:[J,G.onToolCallFinish],onPreliminaryToolResult:mn=>{Be?.enqueue(mn)}});Ot!=null&&(Be?.enqueue(Ot),Ge.push(Ot))})),ue.length>0&&F.push({role:"tool",content:ue.map(ft=>({type:"tool-approval-response",approvalId:ft.approvalResponse.approvalId,approved:ft.approvalResponse.approved,reason:ft.approvalResponse.reason,providerExecuted:!0}))}),Ge.length>0||Pe.length>0){const ft=[];for(const Ot of Ge)ft.push({type:"tool-result",toolCallId:Ot.toolCallId,toolName:Ot.toolName,output:await OT({toolCallId:Ot.toolCallId,input:Ot.input,tool:h?.[Ot.toolName],output:Ot.type==="tool-result"?Ot.output:Ot.error,errorMode:Ot.type==="tool-error"?"text":"none"})});for(const Ot of Pe)ft.push({type:"tool-result",toolCallId:Ot.toolCall.toolCallId,toolName:Ot.toolCall.toolName,output:{type:"execution-denied",reason:Ot.approvalResponse.reason}});F.push({role:"tool",content:ft})}}finally{Be?.close()}}be.push(...F);async function ee({currentStep:ue,responseMessages:Ae,usage:Pe}){var Ue,Be,mt,Ge,ft,Ot,mn,zo,Vt;const Da=C.includeRawChunks,Hp=i!=null?setTimeout(()=>a.abort(),i):void 0;let Sd;function LA(){l!=null&&(Sd!=null&&clearTimeout(Sd),Sd=setTimeout(()=>c.abort(),l))}function Ih(){Sd!=null&&(clearTimeout(Sd),Sd=void 0)}function Ny(){Hp!=null&&clearTimeout(Hp)}try{K=new gl;const Vp=[...fe,...Ae],is=await A?.({model:e,steps:me,stepNumber:me.length,messages:Vp,experimental_context:Y}),Lc=Sv((Ue=is?.model)!=null?Ue:e),Wp={provider:Lc.provider,modelId:Lc.modelId},Ly=await R1({prompt:{system:(Be=is?.system)!=null?Be:ke.system,messages:(mt=is?.messages)!=null?mt:Vp},supportedUrls:await Lc.supportedUrls,download:ie}),$A=(Ge=is?.activeTools)!=null?Ge:v,{toolChoice:Rh,tools:nb}=await ZCe({tools:h,toolChoice:(ft=is?.toolChoice)!=null?ft:g,activeTools:$A});Y=(Ot=is?.experimental_context)!=null?Ot:Y;const fF=(mn=is?.messages)!=null?mn:Vp,gF=(zo=is?.system)!=null?zo:ke.system,ob=N1(k,is?.providerOptions);await Vc({event:{stepNumber:me.length,model:Wp,system:gF,messages:fF,tools:h,toolChoice:Rh,activeTools:$A,steps:[...me],providerOptions:ob,timeout:x,headers:r,stopWhen:O,output:T,abortSignal:N,include:ce,...ve,experimental_context:Y},callbacks:[B,G.onStepStart]});const{result:{stream:ur,response:Ui,request:Ph},doStreamSpan:ul,startTimestampMs:sb}=await _e(()=>ja({name:"ai.streamText.doStream",attributes:$r({telemetry:t,attributes:{...za({operationId:"ai.streamText.doStream",telemetry:t}),...Je,"ai.model.provider":Lc.provider,"ai.model.id":Lc.modelId,"ai.prompt.messages":{input:()=>D1(Ly)},"ai.prompt.tools":{input:()=>nb?.map(Pt=>JSON.stringify(Pt))},"ai.prompt.toolChoice":{input:()=>Rh!=null?JSON.stringify(Rh):void 0},"gen_ai.system":Lc.provider,"gen_ai.request.model":Lc.modelId,"gen_ai.request.frequency_penalty":we.frequencyPenalty,"gen_ai.request.max_tokens":we.maxOutputTokens,"gen_ai.request.presence_penalty":we.presencePenalty,"gen_ai.request.stop_sequences":we.stopSequences,"gen_ai.request.temperature":we.temperature,"gen_ai.request.top_k":we.topK,"gen_ai.request.top_p":we.topP}}),tracer:Re,endWhenDone:!1,fn:async Pt=>({startTimestampMs:P(),doStreamSpan:Pt,result:await Lc.doStream({...we,tools:nb,toolChoice:Rh,responseFormat:await T?.responseFormat,prompt:Ly,providerOptions:ob,abortSignal:s,headers:r,includeRawChunks:Da})})})),FA=avr({tools:h,generatorStream:ur,tracer:Re,telemetry:t,system:u,messages:Vp,repairToolCall:_,abortSignal:s,experimental_context:Y,generateId:R,stepNumber:me.length,model:Wp,onToolCallStart:[z,G.onToolCallStart],onToolCallFinish:[J,G.onToolCallFinish]}),UA=(Vt=ce?.requestBody)==null||Vt?Ph??{}:{...Ph,body:void 0},Kp=[],Jp=[];let $y;const Yr={};let dl="other",ib,Is=O1(),Sce,Cce=!0,Ou={id:R(),timestamp:new Date,modelId:W.modelId},lcr="";C.addStream(FA.pipeThrough(new TransformStream({async transform(Pt,Zs){var ab,lb,cb,ub,db;if(LA(),Pt.type==="stream-start"){$y=Pt.warnings;return}if(Cce){const Rs=P()-sb;Cce=!1,ul.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Rs}),ul.setAttributes({"ai.response.msToFirstChunk":Rs}),Zs.enqueue({type:"start-step",request:UA,warnings:$y??[]})}const pb=Pt.type;switch(pb){case"tool-approval-request":case"text-start":case"text-end":{Zs.enqueue(Pt);break}case"text-delta":{Pt.delta.length>0&&(Zs.enqueue({type:"text-delta",id:Pt.id,text:Pt.delta,providerMetadata:Pt.providerMetadata}),lcr+=Pt.delta);break}case"reasoning-start":case"reasoning-end":{Zs.enqueue(Pt);break}case"reasoning-delta":{Zs.enqueue({type:"reasoning-delta",id:Pt.id,text:Pt.delta,providerMetadata:Pt.providerMetadata});break}case"tool-call":{Zs.enqueue(Pt),Kp.push(Pt);break}case"tool-result":{Zs.enqueue(Pt),Pt.preliminary||Jp.push(Pt);break}case"tool-error":{Zs.enqueue(Pt),Jp.push(Pt);break}case"response-metadata":{Ou={id:(ab=Pt.id)!=null?ab:Ou.id,timestamp:(lb=Pt.timestamp)!=null?lb:Ou.timestamp,modelId:(cb=Pt.modelId)!=null?cb:Ou.modelId};break}case"finish":{Is=Pt.usage,dl=Pt.finishReason,ib=Pt.rawFinishReason,Sce=Pt.providerMetadata;const Rs=P()-sb;ul.addEvent("ai.stream.finish"),ul.setAttributes({"ai.response.msToFinish":Rs,"ai.response.avgOutputTokensPerSecond":1e3*((ub=Is.outputTokens)!=null?ub:0)/Rs});break}case"file":{Zs.enqueue(Pt);break}case"source":{Zs.enqueue(Pt);break}case"tool-input-start":{Yr[Pt.id]=Pt.toolName;const Rs=h?.[Pt.toolName];Rs?.onInputStart!=null&&await Rs.onInputStart({toolCallId:Pt.id,messages:Vp,abortSignal:s,experimental_context:Y}),Zs.enqueue({...Pt,dynamic:(db=Pt.dynamic)!=null?db:Rs?.type==="dynamic",title:Rs?.title});break}case"tool-input-end":{delete Yr[Pt.id],Zs.enqueue(Pt);break}case"tool-input-delta":{const Rs=Yr[Pt.id],Fy=h?.[Rs];Fy?.onInputDelta!=null&&await Fy.onInputDelta({inputTextDelta:Pt.delta,toolCallId:Pt.id,messages:Vp,abortSignal:s,experimental_context:Y}),Zs.enqueue(Pt);break}case"error":{Zs.enqueue(Pt),dl="error";break}case"raw":{Da&&Zs.enqueue(Pt);break}default:{const Rs=pb;throw new Error(`Unknown chunk type: ${Rs}`)}}},async flush(Pt){var Zs,ab,lb,cb,ub,db,pb;const Rs=Kp.length>0?JSON.stringify(Kp):void 0;try{ul.setAttributes(await $r({telemetry:t,attributes:{"ai.response.finishReason":dl,"ai.response.toolCalls":{output:()=>Rs},"ai.response.id":Ou.id,"ai.response.model":Ou.modelId,"ai.response.timestamp":Ou.timestamp.toISOString(),"ai.usage.inputTokens":Is.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Zs=Is.inputTokenDetails)==null?void 0:Zs.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(ab=Is.inputTokenDetails)==null?void 0:ab.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(lb=Is.inputTokenDetails)==null?void 0:lb.cacheWriteTokens,"ai.usage.outputTokens":Is.outputTokens,"ai.usage.outputTokenDetails.textTokens":(cb=Is.outputTokenDetails)==null?void 0:cb.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(ub=Is.outputTokenDetails)==null?void 0:ub.reasoningTokens,"ai.usage.totalTokens":Is.totalTokens,"ai.usage.reasoningTokens":(db=Is.outputTokenDetails)==null?void 0:db.reasoningTokens,"ai.usage.cachedInputTokens":(pb=Is.inputTokenDetails)==null?void 0:pb.cacheReadTokens,"gen_ai.response.finish_reasons":[dl],"gen_ai.response.id":Ou.id,"gen_ai.response.model":Ou.modelId,"gen_ai.usage.input_tokens":Is.inputTokens,"gen_ai.usage.output_tokens":Is.outputTokens}}))}catch{}Pt.enqueue({type:"finish-step",finishReason:dl,rawFinishReason:ib,usage:Is,providerMetadata:Sce,response:{...Ou,headers:Ui?.headers}});const Fy=eke(Pe,Is);await K.promise;const yF=me[me.length-1];try{ul.setAttributes(await $r({telemetry:t,attributes:{"ai.response.text":{output:()=>yF.text},"ai.response.reasoning":{output:()=>yF.reasoningText},"ai.response.providerMetadata":JSON.stringify(yF.providerMetadata)}}))}catch{}finally{ul.end()}const kce=Kp.filter(Ei=>Ei.providerExecuted!==!0),ccr=Jp.filter(Ei=>Ei.providerExecuted!==!0);for(const Ei of Kp){if(Ei.providerExecuted!==!0)continue;const vF=h?.[Ei.toolName];vF?.type==="provider"&&vF.supportsDeferredResults&&(Jp.some(_F=>(_F.type==="tool-result"||_F.type==="tool-error")&&_F.toolCallId===Ei.toolCallId)||$e.set(Ei.toolCallId,{toolName:Ei.toolName}))}for(const Ei of Jp)(Ei.type==="tool-result"||Ei.type==="tool-error")&&$e.delete(Ei.toolCallId);if(Ny(),Ih(),(kce.length>0&&ccr.length===kce.length||$e.size>0)&&!await ake({stopConditions:b,steps:me})){Ae.push(...await Ej({content:me[me.length-1].content,tools:h}));try{await ee({currentStep:ue+1,responseMessages:Ae,usage:Fy})}catch(Ei){Pt.enqueue({type:"error",error:Ei}),C.closeStream()}}else Pt.enqueue({type:"finish",finishReason:dl,rawFinishReason:ib,totalUsage:Fy}),C.closeStream()}})))}finally{Ny(),Ih()}}await ee({currentStep:0,responseMessages:F,usage:O1()})}}).catch(Ee=>{C.addStream(new ReadableStream({start(ke){ke.enqueue({type:"error",error:Ee}),ke.close()}})),C.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ud(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ud(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await ivr({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Ud(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new Zo({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Ud(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:UT()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:i=!0,sendFinish:a=!0,onError:l=Zh}={}){const c=t!=null?Qyr({originalMessages:e,responseMessageId:t}):void 0,u=m=>{var h;const g=(h=this.tools)==null?void 0:h[m.toolName];return g==null?m.dynamic:g?.type==="dynamic"?!0:void 0},d=this.fullStream.pipeThrough(new TransformStream({transform:async(m,h)=>{const g=n?.({part:m}),y=m.type;switch(y){case"text-start":{h.enqueue({type:"text-start",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:m.id,delta:m.text,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"reasoning-delta":{o&&h.enqueue({type:"reasoning-delta",id:m.id,delta:m.text,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:m.file.mediaType,url:`data:${m.file.mediaType};base64,${m.file.base64}`,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"source":{s&&m.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:m.id,url:m.url,title:m.title,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}}),s&&m.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:m.id,mediaType:m.mediaType,title:m.title,filename:m.filename,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"tool-input-start":{const v=u(m);h.enqueue({type:"tool-input-start",toolCallId:m.id,toolName:m.toolName,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{},...m.title!=null?{title:m.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:m.id,inputTextDelta:m.delta});break}case"tool-call":{const v=u(m);m.invalid?h.enqueue({type:"tool-input-error",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{},errorText:l(m.error),...m.title!=null?{title:m.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{},...m.title!=null?{title:m.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:m.approvalId,toolCallId:m.toolCall.toolCallId});break}case"tool-result":{const v=u(m);h.enqueue({type:"tool-output-available",toolCallId:m.toolCallId,output:m.output,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...m.preliminary!=null?{preliminary:m.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{const v=u(m);h.enqueue({type:"tool-output-error",toolCallId:m.toolCallId,errorText:m.providerExecuted?typeof m.error=="string"?m.error:JSON.stringify(m.error):l(m.error),...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:m.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:l(m.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{i&&h.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&h.enqueue({type:"finish",finishReason:m.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{h.enqueue(m);break}case"tool-input-end":break;case"raw":break;default:{const v=y;throw new Error(`Unknown chunk type: ${v}`)}}g!=null&&y!=="start"&&y!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:g})}}));return Ud(ovr({stream:d,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c,...u}={}){svr({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){mke({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l,...c}={}){return Xyr({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l}),...c})}toTextStreamResponse(e){return dke({textStream:this.textStream,...e})}},vvr=We(()=>Ve(p.array(p.object({id:p.string(),role:p.enum(["system","user","assistant"]),metadata:p.unknown().optional(),parts:p.array(p.union([p.object({type:p.literal("text"),text:p.string(),state:p.enum(["streaming","done"]).optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("reasoning"),text:p.string(),state:p.enum(["streaming","done"]).optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("source-url"),sourceId:p.string(),url:p.string(),title:p.string().optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("source-document"),sourceId:p.string(),mediaType:p.string(),title:p.string(),filename:p.string().optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("file"),mediaType:p.string(),filename:p.string().optional(),url:p.string(),providerMetadata:wt.optional()}),p.object({type:p.literal("step-start")}),p.object({type:p.string().startsWith("data-"),id:p.string().optional(),data:p.unknown()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("input-streaming"),input:p.unknown().optional(),providerExecuted:p.boolean().optional(),callProviderMetadata:wt.optional(),output:p.never().optional(),errorText:p.never().optional(),approval:p.never().optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("input-available"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.never().optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("approval-requested"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.never().optional(),reason:p.never().optional()})}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("approval-responded"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.boolean(),reason:p.string().optional()})}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("output-available"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.unknown(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),preliminary:p.boolean().optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("output-error"),input:p.unknown(),rawInput:p.unknown().optional(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.string(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("output-denied"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!1),reason:p.string().optional()})}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("input-streaming"),providerExecuted:p.boolean().optional(),callProviderMetadata:wt.optional(),input:p.unknown().optional(),output:p.never().optional(),errorText:p.never().optional(),approval:p.never().optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("input-available"),providerExecuted:p.boolean().optional(),input:p.unknown(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.never().optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("approval-requested"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.never().optional(),reason:p.never().optional()})}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("approval-responded"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.boolean(),reason:p.string().optional()})}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("output-available"),providerExecuted:p.boolean().optional(),input:p.unknown(),output:p.unknown(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),preliminary:p.boolean().optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("output-error"),providerExecuted:p.boolean().optional(),input:p.unknown(),rawInput:p.unknown().optional(),output:p.never().optional(),errorText:p.string(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("output-denied"),providerExecuted:p.boolean().optional(),input:p.unknown(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!1),reason:p.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty"))),Yxe=class{constructor(e){this.value=e.value,this.embedding=e.embedding,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response}},mq=class{constructor(e){this.values=e.values,this.embeddings=e.embeddings,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.responses=e.responses}},Zxe={type:"no-schema",jsonSchema:async()=>{},async validatePartialResult({value:e,textDelta:t}){return{success:!0,value:{partial:e,textDelta:t}}},async validateFinalResult(e,t){return e===void 0?{success:!1,error:new ki({message:"No object generated: response did not match schema.",text:t.text,response:t.response,usage:t.usage,finishReason:t.finishReason})}:{success:!0,value:e}},createElementStream(){throw new Zo({functionality:"element streams in no-schema mode"})}},Xxe=e=>({type:"object",jsonSchema:async()=>await e.jsonSchema,async validatePartialResult({value:t,textDelta:r}){return{success:!0,value:{partial:t,textDelta:r}}},async validateFinalResult(t){return Ba({value:t,schema:e})},createElementStream(){throw new Zo({functionality:"element streams in object mode"})}}),Qxe=e=>({type:"array",jsonSchema:async()=>{const{$schema:t,...r}=await e.jsonSchema;return{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:r}},required:["elements"],additionalProperties:!1}},async validatePartialResult({value:t,latestObject:r,isFirstDelta:n,isFinalDelta:o}){var s;if(!d1(t)||!Gge(t.elements))return{success:!1,error:new da({value:t,cause:"value must be an object that contains an array of elements"})};const i=t.elements,a=[];for(let u=0;u<i.length;u++){const d=i[u],m=await Ba({value:d,schema:e});if(!(u===i.length-1&&!o)){if(!m.success)return m;a.push(m.value)}}const l=(s=r?.length)!=null?s:0;let c="";return n&&(c+="["),l>0&&(c+=","),c+=a.slice(l).map(u=>JSON.stringify(u)).join(","),o&&(c+="]"),{success:!0,value:{partial:a,textDelta:c}}},async validateFinalResult(t){if(!d1(t)||!Gge(t.elements))return{success:!1,error:new da({value:t,cause:"value must be an object that contains an array of elements"})};const r=t.elements;for(const n of r){const o=await Ba({value:n,schema:e});if(!o.success)return o}return{success:!0,value:r}},createElementStream(t){let r=0;return Ud(t.pipeThrough(new TransformStream({transform(n,o){switch(n.type){case"object":{const s=n.object;for(;r<s.length;r++)o.enqueue(s[r]);break}case"text-delta":case"finish":case"error":break;default:{const s=n;throw new Error(`Unsupported chunk type: ${s}`)}}}})))}}),eAe=e=>({type:"enum",jsonSchema:async()=>({$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1}),async validateFinalResult(t){if(!d1(t)||typeof t.result!="string")return{success:!1,error:new da({value:t,cause:'value must be an object that contains a string in the "result" property.'})};const r=t.result;return e.includes(r)?{success:!0,value:r}:{success:!1,error:new da({value:t,cause:"value must be a string in the enum"})}},async validatePartialResult({value:t,textDelta:r}){if(!d1(t)||typeof t.result!="string")return{success:!1,error:new da({value:t,cause:'value must be an object that contains a string in the "result" property.'})};const n=t.result,o=e.filter(s=>s.startsWith(n));return t.result.length===0||o.length===0?{success:!1,error:new da({value:t,cause:"value must be a string in the enum"})}:{success:!0,value:{partial:o.length>1?n:o[0],textDelta:r}}},createElementStream(){throw new Zo({functionality:"element streams in enum mode"})}}),tAe=Ev({prefix:"aiobj",size:24}),rAe=class{constructor(e){this.object=e.object,this.finishReason=e.finishReason,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response,this.request=e.request,this.reasoning=e.reasoning}toJsonResponse(e){var t;return new Response(JSON.stringify(this.object),{status:(t=e?.status)!=null?t:200,headers:$T(e?.headers,{"content-type":"application/json; charset=utf-8"})})}},nAe=Ev({prefix:"aiobj",size:24}),oAe=class{constructor({model:e,headers:t,telemetry:r,settings:n,maxRetries:o,abortSignal:s,outputStrategy:i,system:a,prompt:l,messages:c,schemaName:u,schemaDescription:d,providerOptions:m,repairText:h,onError:g,onFinish:y,download:v,generateId:_,currentDate:b,now:T}){this._object=new gl,this._usage=new gl,this._providerMetadata=new gl,this._warnings=new gl,this._request=new gl,this._response=new gl,this._finishReason=new gl;const k=Sv(e),{maxRetries:A,retry:I}=nf({maxRetries:o,abortSignal:s}),P=rf(n),R=Cv({model:k,telemetry:r,headers:t,settings:{...P,maxRetries:A}}),x=kv(r),O=this,N=yke(),M=new TransformStream({transform(D,L){L.enqueue(D),D.type==="error"&&g({error:M1(D.error)})}});this.baseStream=N.stream.pipeThrough(M),ja({name:"ai.streamObject",attributes:$r({telemetry:r,attributes:{...za({operationId:"ai.streamObject",telemetry:r}),...R,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:l,messages:c})},"ai.schema":{input:async()=>JSON.stringify(await i.jsonSchema())},"ai.schema.name":u,"ai.schema.description":d,"ai.settings.output":i.type}}),tracer:x,endWhenDone:!1,fn:async D=>{const L=await P1({system:a,prompt:l,messages:c}),$={responseFormat:{type:"json",schema:await i.jsonSchema(),name:u,description:d},...rf(n),prompt:await R1({prompt:L,supportedUrls:await k.supportedUrls,download:v}),providerOptions:m,abortSignal:s,headers:t,includeRawChunks:!1},U={transform:(Se,ne)=>{switch(Se.type){case"text-delta":ne.enqueue(Se.delta);break;case"response-metadata":case"finish":case"error":case"stream-start":ne.enqueue(Se);break}}},{result:{stream:j,response:B,request:z},doStreamSpan:J,startTimestampMs:Y}=await I(()=>ja({name:"ai.streamObject.doStream",attributes:$r({telemetry:r,attributes:{...za({operationId:"ai.streamObject.doStream",telemetry:r}),...R,"ai.prompt.messages":{input:()=>D1($.prompt)},"gen_ai.system":k.provider,"gen_ai.request.model":k.modelId,"gen_ai.request.frequency_penalty":P.frequencyPenalty,"gen_ai.request.max_tokens":P.maxOutputTokens,"gen_ai.request.presence_penalty":P.presencePenalty,"gen_ai.request.temperature":P.temperature,"gen_ai.request.top_k":P.topK,"gen_ai.request.top_p":P.topP}}),tracer:x,endWhenDone:!1,fn:async Se=>({startTimestampMs:T(),doStreamSpan:Se,result:await k.doStream($)})}));O._request.resolve(z??{});let ie,ce=O1(),re,G,K,Ce,be="",ge="",H={id:_(),timestamp:b(),modelId:k.modelId},se,ye,Q=!0,me=!0;const $e=j.pipeThrough(new TransformStream(U)).pipeThrough(new TransformStream({async transform(Se,ne){var Fe,ae,oe;if(typeof Se=="object"&&Se.type==="stream-start"){ie=Se.warnings;return}if(Q){const pe=T()-Y;Q=!1,J.addEvent("ai.stream.firstChunk",{"ai.stream.msToFirstChunk":pe}),J.setAttributes({"ai.stream.msToFirstChunk":pe})}if(typeof Se=="string"){be+=Se,ge+=Se;const{value:pe,state:X}=await Av(be);if(pe!==void 0&&!L1(se,pe)){const Z=await i.validatePartialResult({value:pe,textDelta:ge,latestObject:ye,isFirstDelta:me,isFinalDelta:X==="successful-parse"});Z.success&&!L1(ye,Z.value.partial)&&(se=pe,ye=Z.value.partial,ne.enqueue({type:"object",object:ye}),ne.enqueue({type:"text-delta",textDelta:Z.value.textDelta}),ge="",me=!1)}return}switch(Se.type){case"response-metadata":{H={id:(Fe=Se.id)!=null?Fe:H.id,timestamp:(ae=Se.timestamp)!=null?ae:H.timestamp,modelId:(oe=Se.modelId)!=null?oe:H.modelId};break}case"finish":{ge!==""&&ne.enqueue({type:"text-delta",textDelta:ge}),re=Se.finishReason.unified,ce=xv(Se.usage),G=Se.providerMetadata,ne.enqueue({...Se,finishReason:Se.finishReason.unified,usage:ce,response:H}),Bu({warnings:ie??[],provider:k.provider,model:k.modelId}),O._usage.resolve(ce),O._providerMetadata.resolve(G),O._warnings.resolve(ie),O._response.resolve({...H,headers:B?.headers}),O._finishReason.resolve(re??"other");try{K=await Tke(be,i,h,{response:H,usage:ce,finishReason:re}),O._object.resolve(K)}catch(pe){Ce=pe,O._object.reject(pe)}break}default:{ne.enqueue(Se);break}}},async flush(Se){try{const ne=ce??{promptTokens:NaN,completionTokens:NaN,totalTokens:NaN};J.setAttributes(await $r({telemetry:r,attributes:{"ai.response.finishReason":re,"ai.response.object":{output:()=>JSON.stringify(K)},"ai.response.id":H.id,"ai.response.model":H.modelId,"ai.response.timestamp":H.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(G),"ai.usage.inputTokens":ne.inputTokens,"ai.usage.outputTokens":ne.outputTokens,"ai.usage.totalTokens":ne.totalTokens,"ai.usage.reasoningTokens":ne.reasoningTokens,"ai.usage.cachedInputTokens":ne.cachedInputTokens,"gen_ai.response.finish_reasons":[re],"gen_ai.response.id":H.id,"gen_ai.response.model":H.modelId,"gen_ai.usage.input_tokens":ne.inputTokens,"gen_ai.usage.output_tokens":ne.outputTokens}})),J.end(),D.setAttributes(await $r({telemetry:r,attributes:{"ai.usage.inputTokens":ne.inputTokens,"ai.usage.outputTokens":ne.outputTokens,"ai.usage.totalTokens":ne.totalTokens,"ai.usage.reasoningTokens":ne.reasoningTokens,"ai.usage.cachedInputTokens":ne.cachedInputTokens,"ai.response.object":{output:()=>JSON.stringify(K)},"ai.response.providerMetadata":JSON.stringify(G)}})),await y?.({usage:ne,object:K,error:Ce,response:{...H,headers:B?.headers},warnings:ie,providerMetadata:G})}catch(ne){Se.enqueue({type:"error",error:ne})}finally{D.end()}}}));N.addStream($e)}}).catch(D=>{N.addStream(new ReadableStream({start(L){L.enqueue({type:"error",error:D}),L.close()}}))}).finally(()=>{N.close()}),this.outputStrategy=i}get object(){return this._object.promise}get usage(){return this._usage.promise}get providerMetadata(){return this._providerMetadata.promise}get warnings(){return this._warnings.promise}get request(){return this._request.promise}get response(){return this._response.promise}get finishReason(){return this._finishReason.promise}get partialObjectStream(){return Ud(this.baseStream.pipeThrough(new TransformStream({transform(e,t){switch(e.type){case"object":t.enqueue(e.object);break;case"text-delta":case"finish":case"error":break;default:{const r=e;throw new Error(`Unsupported chunk type: ${r}`)}}}})))}get elementStream(){return this.outputStrategy.createElementStream(this.baseStream)}get textStream(){return Ud(this.baseStream.pipeThrough(new TransformStream({transform(e,t){switch(e.type){case"text-delta":t.enqueue(e.textDelta);break;case"object":case"finish":case"error":break;default:{const r=e;throw new Error(`Unsupported chunk type: ${r}`)}}}})))}get fullStream(){return Ud(this.baseStream)}pipeTextStreamToResponse(e,t){mke({response:e,textStream:this.textStream,...t})}toTextStreamResponse(e){return dke({textStream:this.textStream,...e})}},_vr=Cke(),hq=({model:e,middleware:t,modelId:r,providerId:n})=>[...gm(t)].reverse().reduce((o,s)=>sAe({model:o,middleware:s,modelId:r,providerId:n}),e),sAe=({model:e,middleware:{transformParams:t,wrapGenerate:r,wrapStream:n,overrideProvider:o,overrideModelId:s,overrideSupportedUrls:i},modelId:a,providerId:l})=>{var c,u,d;async function m({params:h,type:g}){return t?await t({params:h,type:g,model:e}):h}return{specificationVersion:"v3",provider:(c=l??o?.({model:e}))!=null?c:e.provider,modelId:(u=a??s?.({model:e}))!=null?u:e.modelId,supportedUrls:(d=i?.({model:e}))!=null?d:e.supportedUrls,async doGenerate(h){const g=await m({params:h,type:"generate"}),y=async()=>e.doGenerate(g);return r?r({doGenerate:y,doStream:async()=>e.doStream(g),params:g,model:e}):y()},async doStream(h){const g=await m({params:h,type:"stream"}),y=async()=>e.doGenerate(g),v=async()=>e.doStream(g);return n?n({doGenerate:y,doStream:v,params:g,model:e}):v()}}},iAe="AI_NoSuchProviderError",aAe=`vercel.ai.error.${iAe}`,lAe=Symbol.for(aAe),wvr=lAe,cAe=Cke(),uAe=class{constructor(e){var t;this.text=e.text,this.segments=e.segments,this.language=e.language,this.durationInSeconds=e.durationInSeconds,this.warnings=e.warnings,this.responses=e.responses,this.providerMetadata=(t=e.providerMetadata)!=null?t:{}}}}}),dAe={};he(dAe,{APICallError:()=>Gr,InvalidToolInputError:()=>Iv,NoObjectGeneratedError:()=>ki,NoOutputGeneratedError:()=>ac,NoSuchToolError:()=>Rv});var Bd=S({"src/lib/utils/generationErrors.ts"(){"use strict";fq(),Rt()}});function gq(e,t){if("get"in e&&typeof e.get=="function")return e.get(t);const r=t.toLowerCase();for(const[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o;return null}function BT(e){const t=gq(e,"Retry-After");if(t){const n=parseInt(t,10);if(!Number.isNaN(n))return Math.max(0,n*1e3);const o=new Date(t);if(!Number.isNaN(o.getTime()))return Math.max(0,o.getTime()-Date.now())}const r=gq(e,"X-RateLimit-Reset");if(r){const n=parseInt(r,10);if(!Number.isNaN(n)){const o=n>1e12?n:n*1e3;return Math.max(0,o-Date.now())}}if(gq(e,"X-RateLimit-Remaining")==="0")return 1e3}var yq=S({"src/lib/utils/retryAfter.ts"(){"use strict"}});function zT(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;const r=t.$metadata;if(typeof r=="object"&&r!==null){const n=r.httpStatusCode;if(typeof n=="number")return n}}function pAe(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.retryAfterMs=="number"&&Number.isFinite(t.retryAfterMs))return t.retryAfterMs;for(const r of[t.headers,t.responseHeaders])if(r&&typeof r=="object"){const n=BT(r);if(n!==void 0)return n}}function mAe(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.type==="insufficient_quota")return!0;if(typeof t.responseBody=="string")try{return JSON.parse(t.responseBody)?.error?.type==="insufficient_quota"}catch{return!1}return!1}function bvr(e){if(mAe(e))return!1;if(Gr.isInstance(e))return e.isRetryable;if(e instanceof Ne)return e.retriable;const t=zT(e);return t!==void 0?t===429||t>=500:!1}function hAe(e){return Gr.isInstance(e)?e.statusCode:zT(e)}function Tvr(e){if(Gr.isInstance(e)&&e.responseHeaders){const t=BT(e.responseHeaders);if(t!==void 0)return t}return e instanceof Ne&&e.retryAfterMs!==void 0&&Number.isFinite(e.retryAfterMs)?e.retryAfterMs:pAe(e)}async function Mv(e,t,r,n=yAe){for(let o=0;o<=U1;o++)try{const s=await e();return t?.setAttribute("gen_ai.provider.total_attempts",o+1),o>0&&f.info(`[providerRetry] ${r} succeeded after ${o+1} attempts`),s}catch(s){const i=bvr(s),a=hAe(s),l=s instanceof Error?s.message:String(s);if(!i||o===U1)throw t?.setAttribute("gen_ai.provider.total_attempts",o+1),o>0&&t?.setAttribute("gen_ai.provider.retries_exhausted",!0),f.warn(`[providerRetry] ${r} failed (non-retryable or retries exhausted)`,{attempt:o+1,retryable:i,statusCode:a,error:l}),s;const c=Tvr(s);if(c!==void 0&&c>vq){t?.setAttribute("gen_ai.provider.total_attempts",o+1),t?.addEvent("gen_ai.provider.retry_suppressed",{"retry.after_ms":c,...a!==void 0&&{"retry.status_code":a}});try{Object.assign(s,{isRetryable:!1,retryAfterMs:c})}catch{}throw f.warn(`[providerRetry] ${r} not retrying \u2014 server requested a ${Math.round(c/1e3)}s wait (cap ${vq/1e3}s); surfacing for fallback`,{attempt:o+1,retryAfterMs:c,statusCode:a}),s}const u=(c===void 0?void 0:Math.max(0,c))??Math.max(fAe*Math.pow(2,o),gAe);t?.addEvent("gen_ai.provider.retry",{"retry.attempt":o+1,"retry.delay_ms":u,...a!==void 0&&{"retry.status_code":a},"retry.error":l.slice(0,256)}),f.warn(`[providerRetry] ${r} retrying after ${a||"unknown"} error`,{attempt:o+1,maxRetries:U1,delayMs:u,statusCode:a,error:l}),await n(u)}throw new Error(`[providerRetry] ${r} exhausted all retries`)}var U1,fAe,gAe,vq,yAe,ym=S({"src/lib/utils/providerRetry.ts"(){"use strict";er(),ct(),q(),Bd(),yq(),U1=2,fAe=1e3,gAe=1e4,vq=6e4,yAe=e=>new Promise(t=>setTimeout(t,e))}}),_q,vAe=S({"src/lib/constants/networkErrorCodes.ts"(){"use strict";_q=new Set(["ECONNRESET","ETIMEDOUT","ECONNREFUSED","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"])}}),jT={};he(jT,{AsyncLocalStorage:()=>LAe,Buffer:()=>ARe,Channel:()=>yRe,DatabaseSync:()=>xRe,Duplex:()=>FAe,EventEmitter:()=>NAe,Http2ServerRequest:()=>DRe,Http2ServerResponse:()=>ORe,Interface:()=>kRe,MIMEType:()=>BRe,PassThrough:()=>UAe,PerformanceObserver:()=>hRe,Readable:()=>bq,ReadableStream:()=>BAe,Resolver:()=>pRe,TextDecoder:()=>Sq,TextEncoder:()=>GT,Transform:()=>$Ae,URL:()=>QIe,URLSearchParams:()=>eRe,Worker:()=>bRe,Writable:()=>Tq,access:()=>hIe,appendFile:()=>WAe,appendFileSync:()=>TAe,arch:()=>MIe,arrayBuffer:()=>NRe,basename:()=>AAe,builtinModules:()=>JIe,callbackify:()=>aRe,channel:()=>gRe,chmodSync:()=>VAe,clearInterval:()=>URe,clearTimeout:()=>$Re,closeSync:()=>ZAe,connect:()=>LIe,constants:()=>IRe,copyFileSync:()=>JAe,cpSync:()=>EAe,cpus:()=>AIe,createConnection:()=>$Ie,createGunzip:()=>GIe,createGzip:()=>HIe,createHash:()=>Kc,createHmac:()=>wq,createInterface:()=>CRe,createReadStream:()=>aIe,createRequire:()=>KIe,createServer:()=>SAe,createWriteStream:()=>iIe,debug:()=>sRe,debuglog:()=>Eq,default:()=>_Ae,deflateSync:()=>UIe,deprecate:()=>iRe,deserialize:()=>wRe,dirname:()=>xAe,exec:()=>wIe,execFile:()=>TIe,execFileSync:()=>EIe,execSync:()=>bIe,existsSync:()=>qAe,extname:()=>IAe,fileURLToPath:()=>tRe,finished:()=>jAe,format:()=>XIe,freemem:()=>IIe,fstatSync:()=>XAe,get:()=>NIe,gunzip:()=>qIe,gunzipSync:()=>BIe,gzip:()=>jIe,gzipSync:()=>zIe,hasSubscribers:()=>vRe,homedir:()=>CIe,hostname:()=>xIe,inflateSync:()=>FIe,inherits:()=>nRe,inspect:()=>qT,isAbsolute:()=>PAe,isBuiltin:()=>YIe,isDeepStrictEqual:()=>lRe,isIP:()=>MRe,isIPv4:()=>PRe,isIPv6:()=>RRe,isMainThread:()=>TRe,join:()=>CAe,lookup:()=>dRe,mkdir:()=>uIe,mkdirSync:()=>QAe,monitorEventLoopDelay:()=>fRe,normalize:()=>OAe,ok:()=>VIe,open:()=>yIe,openSync:()=>YAe,parentPort:()=>ERe,parse:()=>ZIe,pathToFileURL:()=>rRe,performance:()=>mRe,pipeline:()=>zAe,platform:()=>SIe,posix:()=>DAe,promises:()=>wAe,promisify:()=>oRe,randomBytes:()=>af,randomUUID:()=>st,readFile:()=>lIe,readFileSync:()=>GAe,readdir:()=>pIe,readdirSync:()=>tIe,realpath:()=>vIe,realpathSync:()=>KAe,relative:()=>RAe,release:()=>DIe,rename:()=>fIe,renameSync:()=>nIe,request:()=>OIe,resolve:()=>kAe,rm:()=>gIe,rmSync:()=>sIe,rmdirSync:()=>oIe,sep:()=>MAe,serialize:()=>_Re,setInterval:()=>FRe,setTimeout:()=>LRe,spawn:()=>_Ie,stat:()=>dIe,statSync:()=>eIe,strict:()=>WIe,tmpdir:()=>kIe,toUSVString:()=>cRe,totalmem:()=>RIe,type:()=>PIe,types:()=>uRe,unlink:()=>mIe,unlinkSync:()=>rIe,webcrypto:()=>bAe,workerData:()=>SRe,writeFile:()=>cIe,writeFileSync:()=>HAe});var ho,In,_Ae,wAe,Kc,wq,af,st,bAe,TAe,EAe,SAe,CAe,kAe,xAe,AAe,IAe,RAe,PAe,MAe,DAe,OAe,NAe,LAe,bq,Tq,$Ae,FAe,UAe,BAe,zAe,jAe,qAe,GAe,HAe,VAe,WAe,KAe,JAe,YAe,ZAe,XAe,QAe,eIe,tIe,rIe,nIe,oIe,sIe,iIe,aIe,lIe,cIe,uIe,dIe,pIe,mIe,hIe,fIe,gIe,yIe,vIe,_Ie,wIe,bIe,TIe,EIe,SIe,CIe,kIe,xIe,AIe,IIe,RIe,PIe,MIe,DIe,OIe,NIe,LIe,$Ie,FIe,UIe,BIe,zIe,jIe,qIe,GIe,HIe,VIe,WIe,KIe,JIe,YIe,ZIe,XIe,QIe,eRe,tRe,rRe,nRe,oRe,Eq,sRe,qT,iRe,aRe,lRe,cRe,uRe,Sq,GT,dRe,pRe,mRe,hRe,fRe,gRe,yRe,vRe,_Re,wRe,bRe,TRe,ERe,SRe,CRe,kRe,xRe,ARe,IRe,RRe,PRe,MRe,DRe,ORe,NRe,Cq,LRe,$Re,FRe,URe,BRe,Ft=S({"node-stub:crypto"(){ho=()=>{},In=async()=>{},_Ae={},wAe={readFile:In,writeFile:In,mkdir:In,stat:In,readdir:In,unlink:In,access:In,rm:In,rename:In},Kc=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new GT().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},wq=(e,t)=>Kc(e),af=e=>new Uint8Array(e||32),st=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),bAe=globalThis.crypto,TAe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},EAe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},SAe=()=>({listen:ho,close:ho,on:ho}),CAe=(...e)=>e.join("/"),kAe=(...e)=>e.join("/"),xAe=e=>e||"",AAe=e=>e?.split?.("/")?.pop?.()||"",IAe=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},RAe=(e,t)=>t||"",PAe=()=>!1,MAe="/",DAe={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},OAe=e=>e,NAe=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},LAe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},bq=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Tq=class{write(){return!0}end(){}on(){return this}destroy(){}},$Ae=class{push(){}on(){return this}},FAe=class{on(){return this}},UAe=class{pipe(){return this}on(){return this}},BAe=globalThis.ReadableStream||class{},zAe=ho,jAe=ho,qAe=()=>!1,GAe=()=>"",HAe=ho,VAe=ho,WAe=In,KAe=e=>e,JAe=ho,YAe=()=>0,ZAe=ho,XAe=()=>({}),QAe=ho,eIe=()=>({}),tIe=()=>[],rIe=ho,nIe=ho,oIe=ho,sIe=ho,iIe=()=>new Tq,aIe=()=>new bq,lIe=In,cIe=In,uIe=In,dIe=In,pIe=In,mIe=In,hIe=In,fIe=In,gIe=In,yIe=async()=>({stat:In,readFile:In,close:In,read:In,write:In}),vIe=async e=>e,_Ie=()=>({on:ho,stdout:{on:ho},stderr:{on:ho},kill:ho}),wIe=(e,t)=>t?.(null,"",""),bIe=()=>"",TIe=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},EIe=()=>"",SIe="browser",CIe=()=>"/",kIe=()=>"/tmp",xIe=()=>"browser",AIe=()=>[{}],IIe=()=>0,RIe=()=>0,PIe=()=>"Browser",MIe=()=>"wasm",DIe=()=>"0",OIe=()=>({}),NIe=()=>({}),LIe=()=>({}),$Ie=()=>({}),FIe=()=>new Uint8Array,UIe=()=>new Uint8Array,BIe=()=>new Uint8Array,zIe=()=>new Uint8Array,jIe=(e,t)=>t?.(null,e),qIe=(e,t)=>t?.(null,e),GIe=()=>({}),HIe=()=>({}),VIe=ho,WIe={},KIe=()=>()=>({}),JIe=[],YIe=()=>!1,ZIe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),XIe=()=>"",QIe=globalThis.URL,eRe=globalThis.URLSearchParams,tRe=e=>typeof e=="string"?e.replace("file://",""):e,rRe=e=>new globalThis.URL("file://"+e),nRe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},oRe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),Eq=e=>{const t=(...r)=>{};return t.enabled=!1,t},sRe=Eq,qT=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},qT.custom=Symbol.for("nodejs.util.inspect.custom"),qT.colors={},qT.styles={},iRe=e=>e,aRe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},lRe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),cRe=e=>String(e),uRe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},Sq=globalThis.TextDecoder,GT=globalThis.TextEncoder,dRe=(e,t)=>t?.(null,"127.0.0.1",4),pRe=class{},mRe=globalThis.performance||{now:()=>Date.now()},hRe=class{observe(){}disconnect(){}},fRe=()=>({enable:ho,disable:ho,percentile:()=>0}),gRe=()=>({}),yRe=class{},vRe=()=>!1,_Re=()=>new Uint8Array,wRe=ho,bRe=class{},TRe=!0,ERe=null,SRe=null,CRe=()=>({}),kRe=class{},xRe=class{},ARe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new GT().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new GT().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Sq().decode(this)}},IRe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},RRe=()=>!1,PRe=()=>!1,MRe=()=>0,DRe=class{},ORe=class{},NRe=async()=>new ArrayBuffer(0),Cq=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),LRe=(...e)=>Cq(globalThis.setTimeout(...e)),$Re=globalThis.clearTimeout,FRe=(...e)=>Cq(globalThis.setInterval(...e)),URe=globalThis.clearInterval,BRe=class{constructor(e){this.type=e}toString(){return this.type}}}});function fo(e,t=500){return e&&e.slice(0,t).replace(HRe,"***")}function Dv(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return"[content too large to serialize]"}}function B1(e,t=1e4){try{const r=JSON.stringify(e);return r===void 0?String(e):r.length>t?`${r.slice(0,t)}\u2026[truncated ${r.length-t} chars]`:r}catch(r){return`[unserializable: ${r instanceof Error?r.message:String(r)}]`}}function Xn(e){return e.replace(/\/\/[^/\s"'<>]*@/g,"//***@").replace(/\/\/(?:(?!\/\/)[^\s"'<>])*@/g,"//***@")}function un(e){const t=r=>r.length>200?`${r.slice(0,200)}\u2026`:r;try{const r=new URL(e);return t(`${r.protocol}//${r.host}${r.pathname}`)}catch{const r=e.split(/[?#]/)[0];return t(Xn(r))}}function Evr(e){KRe.forEach(t=>e.searchParams.delete(t))}function Svr(e){const t=[],r=[];for(const[o,s]of e.searchParams.entries())WRe.includes(o.toLowerCase())&&(t.push(`${o.toLowerCase()}=${s}`),r.push(o));return t.length===0?"":(r.forEach(o=>e.searchParams.delete(o)),t.sort(),`\0auth=${Kc("sha256").update(t.join("&")).digest("hex").slice(0,16)}`)}function zRe(e){try{const t=new URL(e);Evr(t);const r=Svr(t);return t.toString()+r}catch{return e}}function z1(e){return e.replace(/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>)]+/g,t=>un(t))}function jRe(e,t){const r=Vi(t);return e.split(Ld(t)).join(r).split(t).join(r)}function vm(e,t){const r=s=>{const i=z1(s);return t?.filePath?jRe(i,t.filePath):i};if(!(e instanceof Error))return new Error(r(String(e)));const n=new Error(r(e.message));n.name=e.name;const o=e.code;return o!==void 0&&(n.code=o),n}function j1(e,t=1e3){const r=new WeakSet,n=o=>{if(o==null)return o;if(typeof o=="string")return fo(o,t);if(typeof o!="object")return o;if(r.has(o))return"[Circular]";if(r.add(o),Array.isArray(o))return o.map(n);const s={};for(const[i,a]of Object.entries(o))VRe.some(l=>l.toLowerCase()===i.toLowerCase())?s[i]="***":s[i]=n(a);return s};return n(e)}var qRe,GRe,HRe,VRe,WRe,KRe,_r=S({"src/lib/utils/logSanitize.ts"(){"use strict";Ft(),Lr(),qRe=["sk","pk","r8","gsk","xai","tgp","fw","pplx","pa","jina","fish"],GRe=qRe.join("|"),HRe=new RegExp(`\\bBearer\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bToken\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bBasic\\s+[A-Za-z0-9+/=]{12,}\\b|\\b(?:${GRe})[_\\-][A-Za-z0-9_\\-\\.]{8,}\\b|\\b(?:api[_-]?key|access[_-]?token|secret[_-]?key|refresh[_-]?token)\\s*[:=]\\s*['"]?[^\\s,;'"&]+`,"gi"),VRe=["apikey","api_key","apiKey","access_token","accessToken","refresh_token","refreshToken","secret","secretkey","secret_key","secretKey","password","authorization","oauth","oauthToken","credentials","authContext","authToken","sessionToken","serviceAccountKey","secretAccessKey","userEmail"],WRe=["token","signature","x-amz-signature","x-amz-credential","x-amz-security-token","awsaccesskeyid","expires","sig","se","sp","sr","sv","x-goog-signature","x-goog-credential","x-goog-algorithm","x-goog-date","x-goog-expires","x-goog-signedheaders"],KRe=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","fbclid","gclid","_ga"]}});function Cvr(e){const t=[],r=new Set;let n=e;for(;n&&typeof n=="object"&&!r.has(n)&&t.length<YRe;){r.add(n);const o=n;t.push(o),n=o.cause}return t}function JRe(e,t){for(const r of e)if(typeof r[t]=="string")return r[t]}function kvr(e,t,r){const n=Cvr(e),o=n[0],s=typeof o?.message=="string"?o.message:e instanceof Error?e.message:"Unknown error",i=n[n.length-1],a=typeof i?.message=="string"?z1(i.message):void 0,l=a&&a!==s?`${s}: ${a}`:s;let c;for(const u of n)if(c=zT(u),c!==void 0)break;return{error:e,message:l,statusCode:c,errorName:JRe(n,"name"),errorCode:JRe(n,"code"),provider:t,modelName:r}}function Ki(e,t,r,n){if(e instanceof Od)return new jo(`Request timed out: ${e.message}`,r);const o=kvr(e,r,n),s=t.find(a=>a.match(o));if(!s)return new _t(`${r} error: ${o.message}`,r);const i=typeof s.message=="function"?s.message(o):s.message;return new s.errorClass(i,r)}var YRe,Qo,xi=S({"src/lib/utils/errorClassifier.ts"(){"use strict";yt(),Ua(),ym(),vAe(),_r(),YRe=5,Qo=[{match:e=>e.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized|invalid_api_key/i.test(e.message),errorClass:sr,message:e=>`Invalid ${e.provider} API key. Please check your credentials.`},{match:e=>e.statusCode===429||/rate limit/i.test(e.message),errorClass:Xs,message:e=>`${e.provider} rate limit exceeded. Please try again later.`},{match:e=>e.statusCode===404||/model_not_found|model not found/i.test(e.message),errorClass:co,message:e=>e.modelName?`${e.provider} model '${e.modelName}' not found.`:`${e.provider} model not found.`},{match:e=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network|connection/i.test(e.message)||e.errorCode!==void 0&&_q.has(e.errorCode),errorClass:jo,message:e=>`Connection error: ${e.message}`},{match:e=>e.statusCode!==void 0&&e.statusCode>=500&&e.statusCode<=599||/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(e.message),errorClass:_t,message:e=>`${e.provider} server error: ${e.message}`}]}});function xvr(e){return`https://api.cloudflare.com/client/v4/accounts/${e}/ai/v1`}var ZRe,Avr=S({"src/lib/providers/openaiCompatCatalog.ts"(){"use strict";yt(),xi(),Yo(),ZRe=[{providerName:"cerebras",aliases:["cerebras"],apiKeyEnvVar:"CEREBRAS_API_KEY",baseURLEnvVar:"CEREBRAS_BASE_URL",defaultBaseURL:"https://api.cerebras.ai/v1",configOptions:Ccr(),modelEnvVar:"CEREBRAS_MODEL",defaultModel:"llama-3.3-70b",registryDefaultModel:"llama-3.3-70b",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"llama3.1-8b",fallbackModels:["llama-3.3-70b","llama3.1-8b","qwen-3-32b","gpt-oss-120b"],errorRules:[{match:e=>e.statusCode===401||/wrong_api_key|Wrong API Key|invalid_api_key/i.test(e.message),errorClass:sr,message:"Invalid Cerebras API key. Check CEREBRAS_API_KEY. Get one at https://cloud.cerebras.ai"},...Qo]},{providerName:"groq",aliases:["groq"],apiKeyEnvVar:"GROQ_API_KEY",baseURLEnvVar:"GROQ_BASE_URL",defaultBaseURL:"https://api.groq.com/openai/v1",configOptions:kcr(),modelEnvVar:"GROQ_MODEL",defaultModel:"llama-3.3-70b-versatile",registryDefaultModel:"llama-3.3-70b-versatile",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"llama-3.1-8b-instant",fallbackModels:["llama-3.3-70b-versatile","llama-3.1-8b-instant","gemma2-9b-it","mixtral-8x7b-32768","llama-3.2-90b-vision-preview","llama-3.2-11b-vision-preview"],timeoutErrorClass:_t,errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication|invalid_api_key/i.test(e.message),errorClass:sr,message:"Invalid Groq API key. Check GROQ_API_KEY. Get one at https://console.groq.com/keys"},{match:e=>/model_decommissioned/i.test(e.message),errorClass:co,message:e=>`Groq model '${e.modelName}' was decommissioned. Pick a current model from https://console.groq.com/docs/models.`},...Qo]},{providerName:"xai",aliases:["xai","grok"],apiKeyEnvVar:"XAI_API_KEY",baseURLEnvVar:"XAI_BASE_URL",defaultBaseURL:"https://api.x.ai/v1",configOptions:Scr(),modelEnvVar:"XAI_MODEL",defaultModel:"grok-3",registryDefaultModel:"grok-3",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"grok-3-mini",fallbackModels:["grok-3","grok-3-mini","grok-2-latest","grok-2-vision-latest","grok-beta"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication|invalid_api_key/i.test(e.message),errorClass:sr,message:"Invalid xAI API key. Please check your XAI_API_KEY environment variable. Get one at https://console.x.ai/"},{match:e=>/insufficient_quota|quota exceeded/i.test(e.message),errorClass:_t,message:"xAI account has insufficient quota. Top up at https://console.x.ai/"},...Qo]},{providerName:"together-ai",aliases:["together-ai","together"],apiKeyEnvVar:"TOGETHER_API_KEY",baseURLEnvVar:"TOGETHER_BASE_URL",defaultBaseURL:"https://api.together.xyz/v1",configOptions:Icr(),modelEnvVar:"TOGETHER_MODEL",defaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo",registryDefaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",fallbackModels:["meta-llama/Llama-3.3-70B-Instruct-Turbo","meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo","meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo","meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo","mistralai/Mixtral-8x22B-Instruct-v0.1","Qwen/Qwen2.5-72B-Instruct-Turbo","deepseek-ai/DeepSeek-R1","deepseek-ai/DeepSeek-V3"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Together AI API key. Get one at https://api.together.xyz/settings/api-keys"},...Qo]},{providerName:"fireworks",aliases:["fireworks"],apiKeyEnvVar:"FIREWORKS_API_KEY",baseURLEnvVar:"FIREWORKS_BASE_URL",defaultBaseURL:"https://api.fireworks.ai/inference/v1",configOptions:Rcr(),modelEnvVar:"FIREWORKS_MODEL",defaultModel:"accounts/fireworks/models/deepseek-v4-pro",registryDefaultModel:"accounts/fireworks/models/deepseek-v4-pro",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"accounts/fireworks/models/deepseek-v4-pro",fallbackModels:["accounts/fireworks/models/deepseek-v4-pro","accounts/fireworks/models/glm-5p1","accounts/fireworks/models/glm-5","accounts/fireworks/models/kimi-k2p6","accounts/fireworks/models/kimi-k2p5","accounts/fireworks/models/gpt-oss-120b"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Fireworks API key. Get one at https://fireworks.ai/account/api-keys"},...Qo]},{providerName:"perplexity",aliases:["perplexity","pplx"],apiKeyEnvVar:"PERPLEXITY_API_KEY",baseURLEnvVar:"PERPLEXITY_BASE_URL",defaultBaseURL:"https://api.perplexity.ai",configOptions:Pcr(),modelEnvVar:"PERPLEXITY_MODEL",defaultModel:"sonar",registryDefaultModel:"sonar",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"gpt-3.5-turbo",fallbackModels:["sonar","sonar-pro","sonar-reasoning","sonar-reasoning-pro","sonar-deep-research"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Perplexity API key. Get one at https://www.perplexity.ai/settings/api"},...Qo]},{providerName:"mistral",aliases:["mistral"],apiKeyEnvVar:"MISTRAL_API_KEY",baseURLEnvVar:"MISTRAL_BASE_URL",defaultBaseURL:"https://api.mistral.ai/v1",configOptions:_cr(),modelEnvVar:"MISTRAL_MODEL",defaultModel:"mistral-small-2506",registryDefaultModel:"mistral-large-latest",registryDefaultModelChecksEnvVar:!1,fallbackModelName:"mistral-small-2506",fallbackModels:["mistral-small-2506","mistral-large-latest"],errorRules:[{match:e=>e.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized/i.test(e.message),errorClass:sr,message:"Invalid Mistral API key. Please check your MISTRAL_API_KEY environment variable."},...Qo]},{providerName:"cloudflare",aliases:["cloudflare","workers-ai","cf-ai"],apiKeyEnvVar:"CLOUDFLARE_API_KEY",computedBaseURL:{envVar:"CLOUDFLARE_ACCOUNT_ID",missingValueMessage:"CLOUDFLARE_ACCOUNT_ID is required (or pass credentials.cloudflare.accountId). Get the account id from https://dash.cloudflare.com/",build:xvr},configOptions:Lcr(),modelEnvVar:"CLOUDFLARE_MODEL",defaultModel:"@cf/meta/llama-3.3-70b-instruct-fp8-fast",registryDefaultModel:"@cf/meta/llama-3.3-70b-instruct-fp8-fast",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"@cf/meta/llama-3.1-8b-instruct-fast",fallbackModels:["@cf/meta/llama-3.3-70b-instruct-fp8-fast","@cf/meta/llama-3.1-70b-instruct","@cf/meta/llama-3.1-8b-instruct-fast","@cf/meta/llama-3.2-11b-vision-instruct","@cf/mistral/mistral-7b-instruct-v0.2","@cf/qwen/qwen1.5-14b-chat-awq"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Cloudflare API key. Use a token with Workers AI Read+Write scope. Get one at https://dash.cloudflare.com/profile/api-tokens"},...Qo]}]}});function Ov(e){const t=[];for(const r of zd)r.kind===e&&(t.push(r.name),r.aliases&&t.push(...r.aliases));return t}function Ivr(e){const t=zd.find(r=>r.kind===e);if(!t)throw new Error(`No media handler catalog entries registered for kind "${e}"`);return t.name}var zd,Nv=S({"src/lib/factories/mediaHandlerCatalog.ts"(){"use strict";zd=[{kind:"tts",name:"google-ai",aliases:["vertex"]},{kind:"tts",name:"openai-tts"},{kind:"tts",name:"elevenlabs",aliases:["elevenlabs-tts"]},{kind:"tts",name:"azure-tts"},{kind:"tts",name:"fish-audio"},{kind:"tts",name:"cartesia"},{kind:"stt",name:"whisper",aliases:["openai-stt"]},{kind:"stt",name:"deepgram"},{kind:"stt",name:"google-stt"},{kind:"stt",name:"azure-stt"},{kind:"realtime",name:"openai-realtime"},{kind:"realtime",name:"gemini-live"},{kind:"video",name:"vertex"},{kind:"video",name:"kling"},{kind:"video",name:"runway"},{kind:"video",name:"replicate"},{kind:"avatar",name:"d-id"},{kind:"avatar",name:"replicate",aliases:["musetalk"]},{kind:"avatar",name:"heygen"},{kind:"music",name:"beatoven"},{kind:"music",name:"replicate",aliases:["musicgen"]},{kind:"music",name:"elevenlabs-music",aliases:["elevenlabs-sound"]},{kind:"music",name:"lyria"}]}}),XRe={};he(XRe,{AsyncLocalStorage:()=>_1e,Buffer:()=>cMe,Channel:()=>XPe,DatabaseSync:()=>lMe,Duplex:()=>b1e,EventEmitter:()=>v1e,Http2ServerRequest:()=>hMe,Http2ServerResponse:()=>fMe,Interface:()=>aMe,MIMEType:()=>bMe,PassThrough:()=>T1e,PerformanceObserver:()=>JPe,Readable:()=>xq,ReadableStream:()=>E1e,Resolver:()=>WPe,TextDecoder:()=>Mq,TextEncoder:()=>VT,Transform:()=>w1e,URL:()=>OPe,URLSearchParams:()=>NPe,Worker:()=>rMe,Writable:()=>Aq,access:()=>Z1e,appendFile:()=>R1e,appendFileSync:()=>s1e,arch:()=>mPe,arrayBuffer:()=>gMe,basename:()=>d1e,builtinModules:()=>RPe,callbackify:()=>jPe,channel:()=>ZPe,chmodSync:()=>I1e,clearInterval:()=>wMe,clearTimeout:()=>vMe,closeSync:()=>O1e,connect:()=>yPe,constants:()=>uMe,copyFileSync:()=>M1e,cpSync:()=>i1e,cpus:()=>cPe,createConnection:()=>vPe,createGunzip:()=>CPe,createGzip:()=>kPe,createHash:()=>kq,createHmac:()=>t1e,createInterface:()=>iMe,createReadStream:()=>G1e,createRequire:()=>IPe,createServer:()=>a1e,createWriteStream:()=>q1e,debug:()=>BPe,debuglog:()=>Pq,default:()=>QRe,deflateSync:()=>wPe,deprecate:()=>zPe,deserialize:()=>tMe,dirname:()=>u1e,exec:()=>rPe,execFile:()=>Rq,execFileSync:()=>oPe,execSync:()=>nPe,existsSync:()=>k1e,extname:()=>p1e,fileURLToPath:()=>LPe,finished:()=>C1e,format:()=>DPe,freemem:()=>uPe,fstatSync:()=>N1e,get:()=>gPe,gunzip:()=>SPe,gunzipSync:()=>bPe,gzip:()=>EPe,gzipSync:()=>TPe,hasSubscribers:()=>QPe,homedir:()=>iPe,hostname:()=>lPe,inflateSync:()=>_Pe,inherits:()=>FPe,inspect:()=>HT,isAbsolute:()=>h1e,isBuiltin:()=>PPe,isDeepStrictEqual:()=>qPe,isIP:()=>mMe,isIPv4:()=>pMe,isIPv6:()=>dMe,isMainThread:()=>nMe,join:()=>l1e,lookup:()=>VPe,mkdir:()=>W1e,mkdirSync:()=>L1e,monitorEventLoopDelay:()=>YPe,normalize:()=>y1e,ok:()=>xPe,open:()=>ePe,openSync:()=>D1e,parentPort:()=>oMe,parse:()=>MPe,pathToFileURL:()=>$Pe,performance:()=>KPe,pipeline:()=>S1e,platform:()=>sPe,posix:()=>g1e,promises:()=>e1e,promisify:()=>UPe,randomBytes:()=>r1e,randomUUID:()=>n1e,readFile:()=>H1e,readFileSync:()=>x1e,readdir:()=>J1e,readdirSync:()=>F1e,realpath:()=>tPe,realpathSync:()=>P1e,relative:()=>m1e,release:()=>hPe,rename:()=>X1e,renameSync:()=>B1e,request:()=>fPe,resolve:()=>c1e,rm:()=>Q1e,rmSync:()=>j1e,rmdirSync:()=>z1e,sep:()=>f1e,serialize:()=>eMe,setInterval:()=>_Me,setTimeout:()=>yMe,spawn:()=>Iq,stat:()=>K1e,statSync:()=>$1e,strict:()=>APe,tmpdir:()=>aPe,toUSVString:()=>GPe,totalmem:()=>dPe,type:()=>pPe,types:()=>HPe,unlink:()=>Y1e,unlinkSync:()=>U1e,webcrypto:()=>o1e,workerData:()=>sMe,writeFile:()=>V1e,writeFileSync:()=>A1e});var go,Rn,QRe,e1e,kq,t1e,r1e,n1e,o1e,s1e,i1e,a1e,l1e,c1e,u1e,d1e,p1e,m1e,h1e,f1e,g1e,y1e,v1e,_1e,xq,Aq,w1e,b1e,T1e,E1e,S1e,C1e,k1e,x1e,A1e,I1e,R1e,P1e,M1e,D1e,O1e,N1e,L1e,$1e,F1e,U1e,B1e,z1e,j1e,q1e,G1e,H1e,V1e,W1e,K1e,J1e,Y1e,Z1e,X1e,Q1e,ePe,tPe,Iq,rPe,nPe,Rq,oPe,sPe,iPe,aPe,lPe,cPe,uPe,dPe,pPe,mPe,hPe,fPe,gPe,yPe,vPe,_Pe,wPe,bPe,TPe,EPe,SPe,CPe,kPe,xPe,APe,IPe,RPe,PPe,MPe,DPe,OPe,NPe,LPe,$Pe,FPe,UPe,Pq,BPe,HT,zPe,jPe,qPe,GPe,HPe,Mq,VT,VPe,WPe,KPe,JPe,YPe,ZPe,XPe,QPe,eMe,tMe,rMe,nMe,oMe,sMe,iMe,aMe,lMe,cMe,uMe,dMe,pMe,mMe,hMe,fMe,gMe,Dq,yMe,vMe,_Me,wMe,bMe,Oq=S({"node-stub:child_process"(){go=()=>{},Rn=async()=>{},QRe={},e1e={readFile:Rn,writeFile:Rn,mkdir:Rn,stat:Rn,readdir:Rn,unlink:Rn,access:Rn,rm:Rn,rename:Rn},kq=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new VT().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},t1e=(e,t)=>kq(e),r1e=e=>new Uint8Array(e||32),n1e=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),o1e=globalThis.crypto,s1e=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},i1e=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},a1e=()=>({listen:go,close:go,on:go}),l1e=(...e)=>e.join("/"),c1e=(...e)=>e.join("/"),u1e=e=>e||"",d1e=e=>e?.split?.("/")?.pop?.()||"",p1e=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},m1e=(e,t)=>t||"",h1e=()=>!1,f1e="/",g1e={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},y1e=e=>e,v1e=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},_1e=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},xq=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Aq=class{write(){return!0}end(){}on(){return this}destroy(){}},w1e=class{push(){}on(){return this}},b1e=class{on(){return this}},T1e=class{pipe(){return this}on(){return this}},E1e=globalThis.ReadableStream||class{},S1e=go,C1e=go,k1e=()=>!1,x1e=()=>"",A1e=go,I1e=go,R1e=Rn,P1e=e=>e,M1e=go,D1e=()=>0,O1e=go,N1e=()=>({}),L1e=go,$1e=()=>({}),F1e=()=>[],U1e=go,B1e=go,z1e=go,j1e=go,q1e=()=>new Aq,G1e=()=>new xq,H1e=Rn,V1e=Rn,W1e=Rn,K1e=Rn,J1e=Rn,Y1e=Rn,Z1e=Rn,X1e=Rn,Q1e=Rn,ePe=async()=>({stat:Rn,readFile:Rn,close:Rn,read:Rn,write:Rn}),tPe=async e=>e,Iq=()=>({on:go,stdout:{on:go},stderr:{on:go},kill:go}),rPe=(e,t)=>t?.(null,"",""),nPe=()=>"",Rq=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},oPe=()=>"",sPe="browser",iPe=()=>"/",aPe=()=>"/tmp",lPe=()=>"browser",cPe=()=>[{}],uPe=()=>0,dPe=()=>0,pPe=()=>"Browser",mPe=()=>"wasm",hPe=()=>"0",fPe=()=>({}),gPe=()=>({}),yPe=()=>({}),vPe=()=>({}),_Pe=()=>new Uint8Array,wPe=()=>new Uint8Array,bPe=()=>new Uint8Array,TPe=()=>new Uint8Array,EPe=(e,t)=>t?.(null,e),SPe=(e,t)=>t?.(null,e),CPe=()=>({}),kPe=()=>({}),xPe=go,APe={},IPe=()=>()=>({}),RPe=[],PPe=()=>!1,MPe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),DPe=()=>"",OPe=globalThis.URL,NPe=globalThis.URLSearchParams,LPe=e=>typeof e=="string"?e.replace("file://",""):e,$Pe=e=>new globalThis.URL("file://"+e),FPe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},UPe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),Pq=e=>{const t=(...r)=>{};return t.enabled=!1,t},BPe=Pq,HT=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},HT.custom=Symbol.for("nodejs.util.inspect.custom"),HT.colors={},HT.styles={},zPe=e=>e,jPe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},qPe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),GPe=e=>String(e),HPe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},Mq=globalThis.TextDecoder,VT=globalThis.TextEncoder,VPe=(e,t)=>t?.(null,"127.0.0.1",4),WPe=class{},KPe=globalThis.performance||{now:()=>Date.now()},JPe=class{observe(){}disconnect(){}},YPe=()=>({enable:go,disable:go,percentile:()=>0}),ZPe=()=>({}),XPe=class{},QPe=()=>!1,eMe=()=>new Uint8Array,tMe=go,rMe=class{},nMe=!0,oMe=null,sMe=null,iMe=()=>({}),aMe=class{},lMe=class{},cMe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new VT().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new VT().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Mq().decode(this)}},uMe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},dMe=()=>!1,pMe=()=>!1,mMe=()=>0,hMe=class{},fMe=class{},gMe=async()=>new ArrayBuffer(0),Dq=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),yMe=(...e)=>Dq(globalThis.setTimeout(...e)),vMe=globalThis.clearTimeout,_Me=(...e)=>Dq(globalThis.setInterval(...e)),wMe=globalThis.clearInterval,bMe=class{constructor(e){this.type=e}toString(){return this.type}}}}),lf,Ns,TMe,Rvr,Pvr,Mvr,Dvr,Ovr,Nvr,Lvr,$vr,Fvr,Uvr,Bvr,zvr,jvr,qvr,Gvr,Hvr,Vvr,Wvr,Kvr,Jvr,Yvr,Zvr,Xvr,Qvr,e0r,t0r,r0r,n0r,o0r,s0r,i0r,a0r,l0r,c0r,u0r,d0r,p0r,m0r,h0r,f0r,g0r,y0r,v0r,_0r,w0r,b0r,T0r=S({"npm-stub:csv-parser"(){lf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:lf.get}):new Proxy(function(...r){return new Proxy({},{get:lf.get})},{get:lf.get,apply(r,n,o){return new Proxy({},{get:lf.get})},construct(r,n){return new Proxy({},{get:lf.get})}})}},Ns=new Proxy({},lf),TMe=Ns,{BedrockClient:Rvr,ListFoundationModelsCommand:Pvr,BedrockRuntimeClient:Mvr,ConverseCommand:Dvr,ConverseStreamCommand:Ovr,ImageFormat:Nvr,InvokeModelCommand:Lvr}=Ns,{SageMakerRuntimeClient:$vr,InvokeEndpointCommand:Fvr,InvokeEndpointWithResponseStreamCommand:Uvr}=Ns,{GoogleAuth:Bvr,VertexAI:zvr,TextToSpeechClient:jvr}=Ns,{Webhook:qvr}=Ns,{Hippocampus:Gvr,HippocampusConfig:Hvr}=Ns,{createClient:Vvr}=Ns,{Queue:Wvr,Worker:Kvr,Job:Jvr,QueueScheduler:Yvr,FlowProducer:Zvr}=Ns,{Cron:Xvr}=Ns,{parseBuffer:Qvr,selectCover:e0r}=Ns,{extractRawText:t0r,convertToHtml:r0r}=Ns,{Hono:n0r}=Ns,{cors:o0r,HTTPException:s0r,logger:i0r,secureHeaders:a0r,streamSSE:l0r,timeout:c0r}=Ns,u0r=globalThis.fetch,d0r=globalThis.Request,p0r=globalThis.Response,m0r=globalThis.Headers,h0r=globalThis.FormData,f0r=globalThis.File,g0r=globalThis.Blob,y0r=Ns.Agent,v0r=Ns.Pool,_0r=Ns.Client,w0r=Ns.Dispatcher,b0r=Ns.MockAgent}}),cf,Ls,zu,E0r,S0r,C0r,k0r,x0r,A0r,I0r,R0r,P0r,M0r,D0r,O0r,N0r,L0r,$0r,F0r,U0r,B0r,z0r,j0r,q0r,G0r,H0r,V0r,W0r,K0r,J0r,Y0r,Z0r,X0r,Q0r,e_r,t_r,r_r,n_r,o_r,s_r,i_r,a_r,l_r,c_r,u_r,d_r,p_r,m_r,h_r,EMe=S({"npm-stub:iconv-lite"(){cf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:cf.get}):new Proxy(function(...r){return new Proxy({},{get:cf.get})},{get:cf.get,apply(r,n,o){return new Proxy({},{get:cf.get})},construct(r,n){return new Proxy({},{get:cf.get})}})}},Ls=new Proxy({},cf),zu=Ls,{BedrockClient:E0r,ListFoundationModelsCommand:S0r,BedrockRuntimeClient:C0r,ConverseCommand:k0r,ConverseStreamCommand:x0r,ImageFormat:A0r,InvokeModelCommand:I0r}=Ls,{SageMakerRuntimeClient:R0r,InvokeEndpointCommand:P0r,InvokeEndpointWithResponseStreamCommand:M0r}=Ls,{GoogleAuth:D0r,VertexAI:O0r,TextToSpeechClient:N0r}=Ls,{Webhook:L0r}=Ls,{Hippocampus:$0r,HippocampusConfig:F0r}=Ls,{createClient:U0r}=Ls,{Queue:B0r,Worker:z0r,Job:j0r,QueueScheduler:q0r,FlowProducer:G0r}=Ls,{Cron:H0r}=Ls,{parseBuffer:V0r,selectCover:W0r}=Ls,{extractRawText:K0r,convertToHtml:J0r}=Ls,{Hono:Y0r}=Ls,{cors:Z0r,HTTPException:X0r,logger:Q0r,secureHeaders:e_r,streamSSE:t_r,timeout:r_r}=Ls,n_r=globalThis.fetch,o_r=globalThis.Request,s_r=globalThis.Response,i_r=globalThis.Headers,a_r=globalThis.FormData,l_r=globalThis.File,c_r=globalThis.Blob,u_r=Ls.Agent,d_r=Ls.Pool,p_r=Ls.Client,m_r=Ls.Dispatcher,h_r=Ls.MockAgent}}),Lv={};he(Lv,{AsyncLocalStorage:()=>GMe,Buffer:()=>L4e,Channel:()=>C4e,DatabaseSync:()=>N4e,Duplex:()=>VMe,EventEmitter:()=>qMe,Http2ServerRequest:()=>z4e,Http2ServerResponse:()=>j4e,Interface:()=>O4e,MIMEType:()=>K4e,PassThrough:()=>WMe,PerformanceObserver:()=>T4e,Readable:()=>_m,ReadableStream:()=>KMe,Resolver:()=>w4e,TextDecoder:()=>Fq,TextEncoder:()=>KT,Transform:()=>HMe,URL:()=>a4e,URLSearchParams:()=>l4e,Worker:()=>I4e,Writable:()=>Lq,access:()=>TDe,appendFile:()=>tDe,appendFileSync:()=>RMe,arch:()=>BDe,arrayBuffer:()=>q4e,basename:()=>LMe,builtinModules:()=>n4e,callbackify:()=>f4e,channel:()=>S4e,chmodSync:()=>eDe,clearInterval:()=>W4e,clearTimeout:()=>H4e,closeSync:()=>sDe,connect:()=>GDe,constants:()=>$4e,copyFileSync:()=>nDe,cpSync:()=>PMe,cpus:()=>LDe,createConnection:()=>HDe,createGunzip:()=>XDe,createGzip:()=>QDe,createHash:()=>Nq,createHmac:()=>kMe,createInterface:()=>D4e,createReadStream:()=>fDe,createRequire:()=>r4e,createServer:()=>MMe,createWriteStream:()=>hDe,debug:()=>m4e,debuglog:()=>$q,default:()=>SMe,deflateSync:()=>WDe,deprecate:()=>h4e,deserialize:()=>A4e,dirname:()=>NMe,exec:()=>ADe,execFile:()=>RDe,execFileSync:()=>PDe,execSync:()=>IDe,existsSync:()=>ZMe,extname:()=>$Me,fileURLToPath:()=>c4e,finished:()=>YMe,format:()=>i4e,freemem:()=>$De,fstatSync:()=>iDe,get:()=>qDe,gunzip:()=>ZDe,gunzipSync:()=>KDe,gzip:()=>YDe,gzipSync:()=>JDe,hasSubscribers:()=>k4e,homedir:()=>DDe,hostname:()=>NDe,inflateSync:()=>VDe,inherits:()=>d4e,inspect:()=>WT,isAbsolute:()=>UMe,isBuiltin:()=>o4e,isDeepStrictEqual:()=>g4e,isIP:()=>B4e,isIPv4:()=>U4e,isIPv6:()=>F4e,isMainThread:()=>R4e,join:()=>DMe,lookup:()=>_4e,mkdir:()=>vDe,mkdirSync:()=>aDe,monitorEventLoopDelay:()=>E4e,normalize:()=>jMe,ok:()=>e4e,open:()=>CDe,openSync:()=>oDe,parentPort:()=>P4e,parse:()=>s4e,pathToFileURL:()=>u4e,performance:()=>b4e,pipeline:()=>JMe,platform:()=>MDe,posix:()=>zMe,promises:()=>CMe,promisify:()=>p4e,randomBytes:()=>xMe,randomUUID:()=>AMe,readFile:()=>gDe,readFileSync:()=>XMe,readdir:()=>wDe,readdirSync:()=>cDe,realpath:()=>kDe,realpathSync:()=>rDe,relative:()=>FMe,release:()=>zDe,rename:()=>EDe,renameSync:()=>dDe,request:()=>jDe,resolve:()=>OMe,rm:()=>SDe,rmSync:()=>mDe,rmdirSync:()=>pDe,sep:()=>BMe,serialize:()=>x4e,setInterval:()=>V4e,setTimeout:()=>G4e,spawn:()=>xDe,stat:()=>_De,statSync:()=>lDe,strict:()=>t4e,tmpdir:()=>ODe,toUSVString:()=>y4e,totalmem:()=>FDe,type:()=>UDe,types:()=>v4e,unlink:()=>bDe,unlinkSync:()=>uDe,webcrypto:()=>IMe,workerData:()=>M4e,writeFile:()=>yDe,writeFileSync:()=>QMe});var yo,Pn,SMe,CMe,Nq,kMe,xMe,AMe,IMe,RMe,PMe,MMe,DMe,OMe,NMe,LMe,$Me,FMe,UMe,BMe,zMe,jMe,qMe,GMe,_m,Lq,HMe,VMe,WMe,KMe,JMe,YMe,ZMe,XMe,QMe,eDe,tDe,rDe,nDe,oDe,sDe,iDe,aDe,lDe,cDe,uDe,dDe,pDe,mDe,hDe,fDe,gDe,yDe,vDe,_De,wDe,bDe,TDe,EDe,SDe,CDe,kDe,xDe,ADe,IDe,RDe,PDe,MDe,DDe,ODe,NDe,LDe,$De,FDe,UDe,BDe,zDe,jDe,qDe,GDe,HDe,VDe,WDe,KDe,JDe,YDe,ZDe,XDe,QDe,e4e,t4e,r4e,n4e,o4e,s4e,i4e,a4e,l4e,c4e,u4e,d4e,p4e,$q,m4e,WT,h4e,f4e,g4e,y4e,v4e,Fq,KT,_4e,w4e,b4e,T4e,E4e,S4e,C4e,k4e,x4e,A4e,I4e,R4e,P4e,M4e,D4e,O4e,N4e,L4e,$4e,F4e,U4e,B4e,z4e,j4e,q4e,Uq,G4e,H4e,V4e,W4e,K4e,uf=S({"node-stub:stream"(){yo=()=>{},Pn=async()=>{},SMe={},CMe={readFile:Pn,writeFile:Pn,mkdir:Pn,stat:Pn,readdir:Pn,unlink:Pn,access:Pn,rm:Pn,rename:Pn},Nq=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new KT().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},kMe=(e,t)=>Nq(e),xMe=e=>new Uint8Array(e||32),AMe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),IMe=globalThis.crypto,RMe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},PMe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},MMe=()=>({listen:yo,close:yo,on:yo}),DMe=(...e)=>e.join("/"),OMe=(...e)=>e.join("/"),NMe=e=>e||"",LMe=e=>e?.split?.("/")?.pop?.()||"",$Me=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},FMe=(e,t)=>t||"",UMe=()=>!1,BMe="/",zMe={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},jMe=e=>e,qMe=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},GMe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},_m=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Lq=class{write(){return!0}end(){}on(){return this}destroy(){}},HMe=class{push(){}on(){return this}},VMe=class{on(){return this}},WMe=class{pipe(){return this}on(){return this}},KMe=globalThis.ReadableStream||class{},JMe=yo,YMe=yo,ZMe=()=>!1,XMe=()=>"",QMe=yo,eDe=yo,tDe=Pn,rDe=e=>e,nDe=yo,oDe=()=>0,sDe=yo,iDe=()=>({}),aDe=yo,lDe=()=>({}),cDe=()=>[],uDe=yo,dDe=yo,pDe=yo,mDe=yo,hDe=()=>new Lq,fDe=()=>new _m,gDe=Pn,yDe=Pn,vDe=Pn,_De=Pn,wDe=Pn,bDe=Pn,TDe=Pn,EDe=Pn,SDe=Pn,CDe=async()=>({stat:Pn,readFile:Pn,close:Pn,read:Pn,write:Pn}),kDe=async e=>e,xDe=()=>({on:yo,stdout:{on:yo},stderr:{on:yo},kill:yo}),ADe=(e,t)=>t?.(null,"",""),IDe=()=>"",RDe=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},PDe=()=>"",MDe="browser",DDe=()=>"/",ODe=()=>"/tmp",NDe=()=>"browser",LDe=()=>[{}],$De=()=>0,FDe=()=>0,UDe=()=>"Browser",BDe=()=>"wasm",zDe=()=>"0",jDe=()=>({}),qDe=()=>({}),GDe=()=>({}),HDe=()=>({}),VDe=()=>new Uint8Array,WDe=()=>new Uint8Array,KDe=()=>new Uint8Array,JDe=()=>new Uint8Array,YDe=(e,t)=>t?.(null,e),ZDe=(e,t)=>t?.(null,e),XDe=()=>({}),QDe=()=>({}),e4e=yo,t4e={},r4e=()=>()=>({}),n4e=[],o4e=()=>!1,s4e=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),i4e=()=>"",a4e=globalThis.URL,l4e=globalThis.URLSearchParams,c4e=e=>typeof e=="string"?e.replace("file://",""):e,u4e=e=>new globalThis.URL("file://"+e),d4e=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},p4e=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),$q=e=>{const t=(...r)=>{};return t.enabled=!1,t},m4e=$q,WT=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},WT.custom=Symbol.for("nodejs.util.inspect.custom"),WT.colors={},WT.styles={},h4e=e=>e,f4e=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},g4e=(e,t)=>JSON.stringify(e)===JSON.stringify(t),y4e=e=>String(e),v4e={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},Fq=globalThis.TextDecoder,KT=globalThis.TextEncoder,_4e=(e,t)=>t?.(null,"127.0.0.1",4),w4e=class{},b4e=globalThis.performance||{now:()=>Date.now()},T4e=class{observe(){}disconnect(){}},E4e=()=>({enable:yo,disable:yo,percentile:()=>0}),S4e=()=>({}),C4e=class{},k4e=()=>!1,x4e=()=>new Uint8Array,A4e=yo,I4e=class{},R4e=!0,P4e=null,M4e=null,D4e=()=>({}),O4e=class{},N4e=class{},L4e=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new KT().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new KT().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Fq().decode(this)}},$4e={F_OK:0,R_OK:4,W_OK:2,X_OK:1},F4e=()=>!1,U4e=()=>!1,B4e=()=>0,z4e=class{},j4e=class{},q4e=async()=>new ArrayBuffer(0),Uq=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),G4e=(...e)=>Uq(globalThis.setTimeout(...e)),H4e=globalThis.clearTimeout,V4e=(...e)=>Uq(globalThis.setInterval(...e)),W4e=globalThis.clearInterval,K4e=class{constructor(e){this.type=e}toString(){return this.type}}}});function df(e,t=","){const r=[];let n="",o=!1;for(let s=0;s<e.length;s++){const i=e[s];if(i==='"'){if(o&&e[s+1]==='"'){n+='"',s++;continue}o=!o}else i===t&&!o?(r.push(n),n=""):n+=i}return r.push(n),r}function f_r(e,t=","){return df(e,t).length}function q1(e,t){const r=e.filter(a=>a.trim()!=="").slice(0,5);if(r.length===0)return",";const n=t?.toLowerCase().replace(/^\./,""),o=n==="tsv"?" ":n==="psv"?"|":void 0;let s=",",i=-1;for(const a of Bq){const l=r.map(m=>f_r(m,a)),c=l[0];if(c<=1)continue;const u=l.every(m=>m===c),d=(a===o?1e3:0)+(u?100:0)+c+(a===","?.5:0);d>i&&(i=d,s=a)}return i<0&&o?o:s}var Bq,J4e=S({"src/lib/utils/csvUtils.ts"(){"use strict";Bq=[","," ",";","|"]}});function G1(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ar(e){return typeof e=="object"&&e!==null}function g_r(e){return e==null}var pf=S({"src/lib/utils/typeUtils.ts"(){"use strict"}}),mf,$s,Y4e,y_r,v_r,__r,w_r,b_r,T_r,E_r,S_r,C_r,k_r,x_r,A_r,I_r,R_r,P_r,M_r,D_r,O_r,N_r,L_r,$_r,F_r,U_r,B_r,z_r,j_r,q_r,G_r,H_r,V_r,W_r,K_r,J_r,Y_r,Z_r,X_r,Q_r,ewr,twr,rwr,nwr,owr,swr,iwr,awr,lwr,cwr=S({"npm-stub:chardet"(){mf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:mf.get}):new Proxy(function(...r){return new Proxy({},{get:mf.get})},{get:mf.get,apply(r,n,o){return new Proxy({},{get:mf.get})},construct(r,n){return new Proxy({},{get:mf.get})}})}},$s=new Proxy({},mf),Y4e=$s,{BedrockClient:y_r,ListFoundationModelsCommand:v_r,BedrockRuntimeClient:__r,ConverseCommand:w_r,ConverseStreamCommand:b_r,ImageFormat:T_r,InvokeModelCommand:E_r}=$s,{SageMakerRuntimeClient:S_r,InvokeEndpointCommand:C_r,InvokeEndpointWithResponseStreamCommand:k_r}=$s,{GoogleAuth:x_r,VertexAI:A_r,TextToSpeechClient:I_r}=$s,{Webhook:R_r}=$s,{Hippocampus:P_r,HippocampusConfig:M_r}=$s,{createClient:D_r}=$s,{Queue:O_r,Worker:N_r,Job:L_r,QueueScheduler:$_r,FlowProducer:F_r}=$s,{Cron:U_r}=$s,{parseBuffer:B_r,selectCover:z_r}=$s,{extractRawText:j_r,convertToHtml:q_r}=$s,{Hono:G_r}=$s,{cors:H_r,HTTPException:V_r,logger:W_r,secureHeaders:K_r,streamSSE:J_r,timeout:Y_r}=$s,Z_r=globalThis.fetch,X_r=globalThis.Request,Q_r=globalThis.Response,ewr=globalThis.Headers,twr=globalThis.FormData,rwr=globalThis.File,nwr=globalThis.Blob,owr=$s.Agent,swr=$s.Pool,iwr=$s.Client,awr=$s.Dispatcher,lwr=$s.MockAgent}});function JT(e){return e.charCodeAt(0)===65279?e.slice(1):e}function uwr(e){return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?"utf-8":e.length>=2&&e[0]===255&&e[1]===254?"utf-16le":e.length>=2&&e[0]===254&&e[1]===255?"utf-16be":null}function dwr(e){if(!e)return null;const t=e.toLowerCase().replace(/[^a-z0-9]/g,""),n={utf8:"utf-8",utf16le:"utf-16le",utf16be:"utf-16be",ascii:"utf-8",windows1252:"windows-1252",iso88591:"latin1",latin1:"latin1",iso88592:"iso-8859-2",windows1251:"windows-1251",koi8r:"koi8-r",gb18030:"gb18030",big5:"big5",shiftjis:"shift_jis",euckr:"euc-kr",eucjp:"euc-jp"}[t]??e;return zu.encodingExists(n)?n:null}function zq(e,t,r=!0){if(t&&zu.encodingExists(t))return{text:JT(zu.decode(e,t)),encoding:t,confidence:100};t&&!zu.encodingExists(t)&&f.warn(`[textEncoding] Unsupported encoding override "${t}"; falling back to detection.`);const n=uwr(e);if(n)return{text:JT(zu.decode(e,n)),encoding:n,confidence:100};let o=!0;for(let a=0;a<e.length;a++)if(e[a]>=128){o=!1;break}if(o)return{text:JT(zu.decode(e,"utf-8")),encoding:"utf-8",confidence:r?100:60};let s=null;try{s=Y4e.detect(e)}catch(a){f.debug(`[textEncoding] chardet failed: ${String(a)}`)}const i=dwr(s);return i?{text:JT(zu.decode(e,i)),encoding:i,confidence:i==="utf-8"?100:80}:{text:JT(zu.decode(e,"utf-8")),encoding:"utf-8",confidence:0}}var pwr=S({"src/lib/utils/textEncoding.ts"(){"use strict";cwr(),EMe(),q()}});async function zt(e,t,r){let n;const o=new Promise((s,i)=>{n=setTimeout(()=>{i(new wm(r||`Operation timed out after ${t}ms`,t))},t)});try{return await Promise.race([e,o])}finally{n!==void 0&&clearTimeout(n)}}async function Z4e(e,t){if(!t||typeof t.addEventListener!="function")return e;const r=()=>{const n=new Error("Operation aborted");return n.name="AbortError",n};return t.aborted?(e.catch(()=>{}),Promise.reject(r())):new Promise((n,o)=>{const s=()=>{e.catch(()=>{}),o(r())};t.addEventListener("abort",s,{once:!0}),e.then(i=>{t.removeEventListener("abort",s),n(i)},i=>{t.removeEventListener("abort",s),o(i)})})}async function H1(e,t,r){return zt(e(),t,r)}var wm,yn=S({"src/lib/utils/async/withTimeout.ts"(){"use strict";wm=class Mlr extends Error{constructor(t,r){super(t),this.timeoutMs=r,this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,Mlr)}timeoutMs}}});function mwr(e){const t=[];return!e||e.trim()===""?(t.push("Empty or blank column name"),t):(e!==e.trim()&&t.push("Leading or trailing whitespace"),/^\d/.test(e)&&t.push("Starts with a number"),/[^a-zA-Z0-9_\- ]/.test(e)&&t.push("Contains special characters"),e.length>64&&t.push("Name exceeds 64 characters"),/\s{2,}/.test(e)&&t.push("Contains multiple consecutive spaces"),t)}function X4e(e,t="snake_case",r=0){let o=(e??"").trim().split(/[^A-Za-z0-9]+/).filter(i=>i.length>0),s=o.join("_");return s===""?(s=`col_${r+1}`,o=[s]):/^[0-9]/.test(s)&&(s=`col_${s}`,o=s.split("_").filter(i=>i.length>0)),t==="camelCase"?o.map((i,a)=>a===0?i.charAt(0).toLowerCase()+i.slice(1):i.charAt(0).toUpperCase()+i.slice(1)).join(""):o.map(i=>i.toLowerCase()).join("_")}function Q4e(e){const t=new Set;return e.map(r=>{if(!t.has(r))return t.add(r),r;let n=2,o=`${r}_${n}`;for(;t.has(o);)n++,o=`${r}_${n}`;return t.add(o),o})}function eOe(e,t){const r=Q4e(e.map((o,s)=>X4e(o,t,s))),n=e.map((o,s)=>({original:o,sanitized:r[s]})).filter(o=>o.original!==o.sanitized);return{sanitized:r,mapping:n}}function hwr(e){return!G1(e)||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string"||t===void 0)}function fwr(e,t){if(!hwr(e))throw xe.csvRowInvalid(`[CSVProcessor] Invalid CSV row ${t}: expected a string-keyed object with string values, got ${Array.isArray(e)?"array":typeof e}`,t)}function YT(e){return Object.keys(e).length===0?!0:Object.values(e).every(r=>r===""||typeof r=="string"&&r.trim()==="")}function gwr(e,t){if(e.trim()==="")return!0;const r=df(e,t);if(r.length===0)return!0;const n=Object.create(null);for(let o=0;o<r.length;o++)n[`c${o}`]=r[o];return YT(n)}function jq(e){const t=[`[CSVProcessor] CSV ${e.stage==="read"?"file read":"parsing"} failed after ${e.count} row(s)`];return e.location&&t.push(`(${e.location})`),t.push(`: ${e.cause}`),t.push(typeof e.headerCount=="number"?`| headerCount: ${e.headerCount}`:"| headerCount: unknown (failed before headers were parsed)"),typeof e.bytesRead=="number"&&t.push(`| bytesRead: ${e.bytesRead}`),typeof e.lastRowColumnCount=="number"&&t.push(`| lastRow columns: ${e.lastRowColumnCount}`),t.push("| Expected RFC 4180 CSV (comma-separated, double-quote escaped)"),t.join(" ")}function qq(e){if(e===""||e===null||e===void 0)return"empty";const t=e.trim();if(t==="")return"empty";if(uOe.has(t.toLowerCase()))return"boolean";if(lOe.test(t))return"integer";if(cOe.test(t))return"float";if(iOe.test(t))return"email";if(aOe.test(t))return"url";for(const r of Wq)if(r.regex.test(t))return"datetime";for(const r of Vq)if(r.regex.test(t))return"date";return"string"}function ywr(e){const t=e.trim();for(const r of Wq)if(r.regex.test(t))return r.format;for(const r of Vq)if(r.regex.test(t))return r.format}function vwr(e){const t=e.filter(i=>i!=="empty");if(t.length===0)return{type:"empty",confidence:100};const r=new Map;for(const i of t)r.set(i,(r.get(i)||0)+1);let n="string",o=0;for(const[i,a]of r)a>o&&(o=a,n=i);const s=Math.round(o/t.length*100);if(r.has("integer")&&r.has("float")&&r.size===2){const i=(r.get("integer")||0)+(r.get("float")||0);return{type:"number",confidence:Math.round(i/t.length*100)}}return s<70&&r.size>1?{type:"mixed",confidence:s}:{type:n,confidence:s}}function _wr(e,t,r){const n=[],o=new Set,s=[];let i=0,a;for(const v of r){const _=v?.trim()??"";if(_===""){i++,n.push("empty");continue}o.add(_);const b=qq(_);if(n.push(b),b==="integer"||b==="float"){const T=parseFloat(_);isNaN(T)||s.push(T)}(b==="date"||b==="datetime")&&!a&&(a=ywr(_))}const{type:l,confidence:c}=vwr(n),u=Array.from(o).slice(0,5);let d,m,h;s.length>0&&(d=Math.min(...s),m=Math.max(...s),h=Math.round(s.reduce((v,_)=>v+_,0)/s.length*100)/100);const g=mwr(e),y={name:e,index:t,detectedType:l,typeConfidence:c,nullCount:i,uniqueCount:o.size,sampleValues:u};return d!==void 0&&(y.minValue=d),m!==void 0&&(y.maxValue=m),h!==void 0&&(y.avgValue=h),a&&(y.dateFormat=a),g.length>0&&(y.nameIssues=g),y}function wwr(e,t){const r=[];for(const n of e){const o=t>0?n.nullCount/t:0;o>.2&&r.push({column:n.name,type:"high_null_rate",message:`Column has ${Math.round(o*100)}% empty/null values (${n.nullCount} of ${t} rows)`,severity:o>.5?"warning":"info",affectedRows:n.nullCount}),n.nameIssues&&n.nameIssues.length>0&&r.push({column:n.name,type:"invalid_name",message:`Column name issues: ${n.nameIssues.join(", ")}`,severity:n.name.trim()===""?"error":"warning"}),(n.detectedType==="mixed"||n.typeConfidence<70)&&r.push({column:n.name,type:"mixed_types",message:`Column has inconsistent data types (${n.typeConfidence}% confidence for ${n.detectedType})`,severity:"warning"}),t>10&&n.uniqueCount===1&&n.nullCount===0&&r.push({column:n.name,type:"duplicates",message:`All ${t} rows have the same value`,severity:"info",affectedRows:t}),n.detectedType==="empty"&&r.push({column:n.name,type:"empty_values",message:"Column is entirely empty",severity:"warning",affectedRows:t})}return r}function bwr(e,t,r){if(e.length===0||r===0)return 0;let n=100;for(const l of t)switch(l.severity){case"error":n-=15;break;case"warning":n-=8;break;case"info":n-=3;break}const o=e.reduce((l,c)=>l+c.nullCount,0),s=e.length*r,i=s>0?o/s:0;n-=Math.round(i*30);const a=e.reduce((l,c)=>l+c.typeConfidence,0)/e.length;return a<80&&(n-=Math.round((80-a)/2)),Math.max(0,Math.min(100,n))}function tOe(e){const t=Math.max(0,Math.min(100,e));return Math.round((100+t)/2)}function rOe(e){if(e.length===0)return{columnMetadata:[],dataQualityWarnings:[],dataQualityScore:0};const t=Object.keys(e[0]),r=[];for(let s=0;s<t.length;s++){const i=t[s],a=e.map(l=>String(l[i]??""));r.push(_wr(i,s,a))}const n=wwr(r,e.length),o=bwr(r,n,e.length);return{columnMetadata:r,dataQualityWarnings:n,dataQualityScore:o}}function nOe(e,t){if(e.length===0)return!1;let r=0;for(const a of e){const l=a?.trim()??"";if(l==="")continue;qq(l)==="string"&&r++}const n=e.filter(a=>a?.trim()).length;if(n===0)return!1;const o=r/n,i=new Set(e.map(a=>a?.trim().toLowerCase())).size===e.length;if(t&&t.length>0){const a=Object.values(t[0]||{}).map(u=>String(u??""));let l=0;for(const u of a)qq(u?.trim()??"")==="string"&&l++;const c=a.length>0?l/a.length:0;if(o>.7&&c<o-.2)return!0}return o>=.7&&i}function Gq(e){return e.charCodeAt(0)===65279?e.slice(1):e}function oOe(e){let t=0,r=!1;for(let n=0;n<e.length;n++){const o=e[n];if(o==='"'){if(r&&e[n+1]==='"'){n++;continue}r=!r}else o===","&&!r&&t++}return t}function Twr(e){if(!e[0]||e.length<2)return!1;const t=e[0].trim(),r=e[1].trim();if(t.match(/^sep=/i))return!0;if(Ewr(r))return!1;const n=oOe(t),o=oOe(r);return n===0&&o>0?!0:o>0&&n!==o}function Ewr(e){const t=e.trim();return t===""?!0:/^[\s,;\t|]+$/.test(t)&&/[,;\t|]/.test(t)}function ZT(e){if(!Twr(e))return{dataLines:e,hasMetadataLine:!1};const t=e[0]?.trim().match(/^sep=(.)/i)?.[1],r=t&&Bq.includes(t)?t:void 0;return{dataLines:e.slice(1),hasMetadataLine:!0,explicitDelimiter:r}}function $v(e){const t=[];let r="",n=!1;for(let o=0;o<e.length;o++){const s=e[o];if(s==='"'){if(n&&e[o+1]==='"'){r+='""',o++;continue}n=!n,r+=s}else!n&&(s===`
|
|
116
|
+
`)}})}},pq={"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive","x-vercel-ai-ui-message-stream":"v1","x-accel-buffering":"no"},yvr=We(()=>Ve(p.union([p.strictObject({type:p.literal("text-start"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("text-delta"),id:p.string(),delta:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("text-end"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("error"),errorText:p.string()}),p.strictObject({type:p.literal("tool-input-start"),toolCallId:p.string(),toolName:p.string(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),title:p.string().optional()}),p.strictObject({type:p.literal("tool-input-delta"),toolCallId:p.string(),inputTextDelta:p.string()}),p.strictObject({type:p.literal("tool-input-available"),toolCallId:p.string(),toolName:p.string(),input:p.unknown(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),title:p.string().optional()}),p.strictObject({type:p.literal("tool-input-error"),toolCallId:p.string(),toolName:p.string(),input:p.unknown(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),errorText:p.string(),title:p.string().optional()}),p.strictObject({type:p.literal("tool-approval-request"),approvalId:p.string(),toolCallId:p.string()}),p.strictObject({type:p.literal("tool-output-available"),toolCallId:p.string(),output:p.unknown(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional(),preliminary:p.boolean().optional()}),p.strictObject({type:p.literal("tool-output-error"),toolCallId:p.string(),errorText:p.string(),providerExecuted:p.boolean().optional(),providerMetadata:wt.optional(),dynamic:p.boolean().optional()}),p.strictObject({type:p.literal("tool-output-denied"),toolCallId:p.string()}),p.strictObject({type:p.literal("reasoning-start"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("reasoning-delta"),id:p.string(),delta:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("reasoning-end"),id:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("source-url"),sourceId:p.string(),url:p.string(),title:p.string().optional(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("source-document"),sourceId:p.string(),mediaType:p.string(),title:p.string(),filename:p.string().optional(),providerMetadata:wt.optional()}),p.strictObject({type:p.literal("file"),url:p.string(),mediaType:p.string(),providerMetadata:wt.optional()}),p.strictObject({type:p.custom(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:p.string().optional(),data:p.unknown(),transient:p.boolean().optional()}),p.strictObject({type:p.literal("start-step")}),p.strictObject({type:p.literal("finish-step")}),p.strictObject({type:p.literal("start"),messageId:p.string().optional(),messageMetadata:p.unknown().optional()}),p.strictObject({type:p.literal("finish"),finishReason:p.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:p.unknown().optional()}),p.strictObject({type:p.literal("abort"),reason:p.string().optional()}),p.strictObject({type:p.literal("message-metadata"),messageMetadata:p.unknown()})]))),Kxe=Ev({prefix:"aitxt",size:24}),Jxe=class{constructor({model:e,telemetry:t,headers:r,settings:n,maxRetries:o,abortSignal:s,stepTimeoutMs:i,stepAbortController:a,chunkTimeoutMs:l,chunkAbortController:c,system:u,prompt:d,messages:m,tools:h,toolChoice:g,transforms:y,activeTools:v,repairToolCall:_,stopConditions:b,output:T,providerOptions:k,prepareStep:A,includeRawChunks:I,now:P,generateId:R,timeout:x,stopWhen:O,originalAbortSignal:N,onChunk:M,onError:D,onFinish:L,onAbort:$,onStepFinish:U,onStart:j,onStepStart:B,onToolCallStart:z,onToolCallFinish:J,experimental_context:Y,download:ie,include:ce}){this._totalUsage=new gl,this._finishReason=new gl,this._rawFinishReason=new gl,this._steps=new gl,this.outputSpecification=T,this.includeRawChunks=I,this.tools=h;const G=QCe()(t?.integrations);let K,Ce=[];const be=[];let ge,H,se,ye={},Q=[];const me=[],$e=new Map;let Se,ne={},Fe={};const ae=new TransformStream({async transform(Ee,ke){var fe,F,te,Ie;ke.enqueue(Ee);const{part:ee}=Ee;if((ee.type==="text-delta"||ee.type==="reasoning-delta"||ee.type==="source"||ee.type==="tool-call"||ee.type==="tool-result"||ee.type==="tool-input-start"||ee.type==="tool-input-delta"||ee.type==="raw")&&await M?.({chunk:ee}),ee.type==="error"&&await D({error:M1(ee.error)}),ee.type==="text-start"&&(ne[ee.id]={type:"text",text:"",providerMetadata:ee.providerMetadata},Ce.push(ne[ee.id])),ee.type==="text-delta"){const ue=ne[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}ue.text+=ee.text,ue.providerMetadata=(fe=ee.providerMetadata)!=null?fe:ue.providerMetadata}if(ee.type==="text-end"){const ue=ne[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`text part ${ee.id} not found`},partialOutput:void 0});return}ue.providerMetadata=(F=ee.providerMetadata)!=null?F:ue.providerMetadata,delete ne[ee.id]}if(ee.type==="reasoning-start"&&(Fe[ee.id]={type:"reasoning",text:"",providerMetadata:ee.providerMetadata},Ce.push(Fe[ee.id])),ee.type==="reasoning-delta"){const ue=Fe[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}ue.text+=ee.text,ue.providerMetadata=(te=ee.providerMetadata)!=null?te:ue.providerMetadata}if(ee.type==="reasoning-end"){const ue=Fe[ee.id];if(ue==null){ke.enqueue({part:{type:"error",error:`reasoning part ${ee.id} not found`},partialOutput:void 0});return}ue.providerMetadata=(Ie=ee.providerMetadata)!=null?Ie:ue.providerMetadata,delete Fe[ee.id]}if(ee.type==="file"&&Ce.push({type:"file",file:ee.file,...ee.providerMetadata!=null?{providerMetadata:ee.providerMetadata}:{}}),ee.type==="source"&&Ce.push(ee),ee.type==="tool-call"&&Ce.push(ee),ee.type==="tool-result"&&!ee.preliminary&&Ce.push(ee),ee.type==="tool-approval-request"&&Ce.push(ee),ee.type==="tool-error"&&Ce.push(ee),ee.type==="start-step"&&(Ce=[],Fe={},ne={},ye=ee.request,Q=ee.warnings),ee.type==="finish-step"){const ue=await Ej({content:Ce,tools:h}),Ae=new uq({stepNumber:me.length,model:W,...ve,experimental_context:Y,content:Ce,finishReason:ee.finishReason,rawFinishReason:ee.rawFinishReason,usage:ee.usage,warnings:Q,request:ye,response:{...ee.response,messages:[...be,...ue]},providerMetadata:ee.providerMetadata});await Vc({event:Ae,callbacks:[U,G.onStepFinish]}),Bu({warnings:Q,provider:W.provider,model:W.modelId}),me.push(Ae),be.push(...ue),K.resolve()}ee.type==="finish"&&(se=ee.totalUsage,ge=ee.finishReason,H=ee.rawFinishReason)},async flush(Ee){var ke,fe,F,te,Ie,ee,ue;try{if(me.length===0){const Be=s?.aborted?s.reason:new ac({message:"No output generated. Check the stream for errors."});C._finishReason.reject(Be),C._rawFinishReason.reject(Be),C._totalUsage.reject(Be),C._steps.reject(Be);return}const Ae=ge??"other",Pe=se??O1();C._finishReason.resolve(Ae),C._rawFinishReason.resolve(H),C._totalUsage.resolve(Pe),C._steps.resolve(me);const Ue=me[me.length-1];await Vc({event:{stepNumber:Ue.stepNumber,model:Ue.model,functionId:Ue.functionId,metadata:Ue.metadata,experimental_context:Ue.experimental_context,finishReason:Ue.finishReason,rawFinishReason:Ue.rawFinishReason,totalUsage:Pe,usage:Ue.usage,content:Ue.content,text:Ue.text,reasoningText:Ue.reasoningText,reasoning:Ue.reasoning,files:Ue.files,sources:Ue.sources,toolCalls:Ue.toolCalls,staticToolCalls:Ue.staticToolCalls,dynamicToolCalls:Ue.dynamicToolCalls,toolResults:Ue.toolResults,staticToolResults:Ue.staticToolResults,dynamicToolResults:Ue.dynamicToolResults,request:Ue.request,response:Ue.response,warnings:Ue.warnings,providerMetadata:Ue.providerMetadata,steps:me},callbacks:[L,G.onFinish]}),Se.setAttributes(await $r({telemetry:t,attributes:{"ai.response.finishReason":Ae,"ai.response.text":{output:()=>Ue.text},"ai.response.reasoning":{output:()=>Ue.reasoningText},"ai.response.toolCalls":{output:()=>{var Be;return(Be=Ue.toolCalls)!=null&&Be.length?JSON.stringify(Ue.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(Ue.providerMetadata),"ai.usage.inputTokens":Pe.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(ke=Pe.inputTokenDetails)==null?void 0:ke.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(fe=Pe.inputTokenDetails)==null?void 0:fe.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(F=Pe.inputTokenDetails)==null?void 0:F.cacheWriteTokens,"ai.usage.outputTokens":Pe.outputTokens,"ai.usage.outputTokenDetails.textTokens":(te=Pe.outputTokenDetails)==null?void 0:te.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(Ie=Pe.outputTokenDetails)==null?void 0:Ie.reasoningTokens,"ai.usage.totalTokens":Pe.totalTokens,"ai.usage.reasoningTokens":(ee=Pe.outputTokenDetails)==null?void 0:ee.reasoningTokens,"ai.usage.cachedInputTokens":(ue=Pe.inputTokenDetails)==null?void 0:ue.cacheReadTokens}}))}catch(Ae){Ee.error(Ae)}finally{Se.end()}}}),oe=yke();this.addStream=oe.addStream,this.closeStream=oe.close;const pe=oe.stream.getReader();let X=new ReadableStream({async start(Ee){Ee.enqueue({type:"start"})},async pull(Ee){function ke(){$?.({steps:me}),Ee.enqueue({type:"abort",...s?.reason!==void 0?{reason:Zh(s.reason)}:{}}),Ee.close()}try{const{done:fe,value:F}=await pe.read();if(fe){Ee.close();return}if(s?.aborted){ke();return}Ee.enqueue(F)}catch(fe){Xh(fe)&&s?.aborted?ke():Ee.error(fe)}},cancel(Ee){return oe.stream.cancel(Ee)}});for(const Ee of y)X=X.pipeThrough(Ee({tools:h,stopStream(){oe.terminate()}}));this.baseStream=X.pipeThrough(lvr(T??UT())).pipeThrough(ae);const{maxRetries:Z,retry:_e}=nf({maxRetries:o,abortSignal:s}),Re=kv(t),we=rf(n),Je=Cv({model:e,telemetry:t,headers:r,settings:{...we,maxRetries:Z}}),C=this,W={provider:e.provider,modelId:e.modelId},ve={functionId:t?.functionId,metadata:t?.metadata};ja({name:"ai.streamText",attributes:$r({telemetry:t,attributes:{...za({operationId:"ai.streamText",telemetry:t}),...Je,"ai.prompt":{input:()=>JSON.stringify({system:u,prompt:d,messages:m})}}}),tracer:Re,endWhenDone:!1,fn:async Ee=>{Se=Ee;const ke=await P1({system:u,prompt:d,messages:m});await Vc({event:{model:W,system:u,prompt:d,messages:m,tools:h,toolChoice:g,activeTools:v,maxOutputTokens:we.maxOutputTokens,temperature:we.temperature,topP:we.topP,topK:we.topK,presencePenalty:we.presencePenalty,frequencyPenalty:we.frequencyPenalty,stopSequences:we.stopSequences,seed:we.seed,maxRetries:Z,timeout:x,headers:r,providerOptions:k,stopWhen:O,output:T,abortSignal:N,include:ce,...ve,experimental_context:Y},callbacks:[j,G.onStart]});const fe=ke.messages,F=[],{approvedToolApprovals:te,deniedToolApprovals:Ie}=rke({messages:fe});if(Ie.length>0||te.length>0){const ue=[...te,...Ie].filter(Ge=>Ge.toolCall.providerExecuted),Ae=te.filter(Ge=>!Ge.toolCall.providerExecuted),Pe=Ie.filter(Ge=>!Ge.toolCall.providerExecuted),Ue=Ie.filter(Ge=>Ge.toolCall.providerExecuted);let Be;const mt=new ReadableStream({start(Ge){Be=Ge}});C.addStream(mt);try{for(const ft of[...Pe,...Ue])Be?.enqueue({type:"tool-output-denied",toolCallId:ft.toolCall.toolCallId,toolName:ft.toolCall.toolName});const Ge=[];if(await Promise.all(Ae.map(async ft=>{const Ot=await _j({toolCall:ft.toolCall,tools:h,tracer:Re,telemetry:t,messages:fe,abortSignal:s,experimental_context:Y,stepNumber:me.length,model:W,onToolCallStart:[z,G.onToolCallStart],onToolCallFinish:[J,G.onToolCallFinish],onPreliminaryToolResult:mn=>{Be?.enqueue(mn)}});Ot!=null&&(Be?.enqueue(Ot),Ge.push(Ot))})),ue.length>0&&F.push({role:"tool",content:ue.map(ft=>({type:"tool-approval-response",approvalId:ft.approvalResponse.approvalId,approved:ft.approvalResponse.approved,reason:ft.approvalResponse.reason,providerExecuted:!0}))}),Ge.length>0||Pe.length>0){const ft=[];for(const Ot of Ge)ft.push({type:"tool-result",toolCallId:Ot.toolCallId,toolName:Ot.toolName,output:await OT({toolCallId:Ot.toolCallId,input:Ot.input,tool:h?.[Ot.toolName],output:Ot.type==="tool-result"?Ot.output:Ot.error,errorMode:Ot.type==="tool-error"?"text":"none"})});for(const Ot of Pe)ft.push({type:"tool-result",toolCallId:Ot.toolCall.toolCallId,toolName:Ot.toolCall.toolName,output:{type:"execution-denied",reason:Ot.approvalResponse.reason}});F.push({role:"tool",content:ft})}}finally{Be?.close()}}be.push(...F);async function ee({currentStep:ue,responseMessages:Ae,usage:Pe}){var Ue,Be,mt,Ge,ft,Ot,mn,zo,Vt;const Da=C.includeRawChunks,Hp=i!=null?setTimeout(()=>a.abort(),i):void 0;let Sd;function LA(){l!=null&&(Sd!=null&&clearTimeout(Sd),Sd=setTimeout(()=>c.abort(),l))}function Ih(){Sd!=null&&(clearTimeout(Sd),Sd=void 0)}function Ny(){Hp!=null&&clearTimeout(Hp)}try{K=new gl;const Vp=[...fe,...Ae],is=await A?.({model:e,steps:me,stepNumber:me.length,messages:Vp,experimental_context:Y}),Lc=Sv((Ue=is?.model)!=null?Ue:e),Wp={provider:Lc.provider,modelId:Lc.modelId},Ly=await R1({prompt:{system:(Be=is?.system)!=null?Be:ke.system,messages:(mt=is?.messages)!=null?mt:Vp},supportedUrls:await Lc.supportedUrls,download:ie}),$A=(Ge=is?.activeTools)!=null?Ge:v,{toolChoice:Rh,tools:nb}=await ZCe({tools:h,toolChoice:(ft=is?.toolChoice)!=null?ft:g,activeTools:$A});Y=(Ot=is?.experimental_context)!=null?Ot:Y;const fF=(mn=is?.messages)!=null?mn:Vp,gF=(zo=is?.system)!=null?zo:ke.system,ob=N1(k,is?.providerOptions);await Vc({event:{stepNumber:me.length,model:Wp,system:gF,messages:fF,tools:h,toolChoice:Rh,activeTools:$A,steps:[...me],providerOptions:ob,timeout:x,headers:r,stopWhen:O,output:T,abortSignal:N,include:ce,...ve,experimental_context:Y},callbacks:[B,G.onStepStart]});const{result:{stream:ur,response:Ui,request:Ph},doStreamSpan:ul,startTimestampMs:sb}=await _e(()=>ja({name:"ai.streamText.doStream",attributes:$r({telemetry:t,attributes:{...za({operationId:"ai.streamText.doStream",telemetry:t}),...Je,"ai.model.provider":Lc.provider,"ai.model.id":Lc.modelId,"ai.prompt.messages":{input:()=>D1(Ly)},"ai.prompt.tools":{input:()=>nb?.map(Pt=>JSON.stringify(Pt))},"ai.prompt.toolChoice":{input:()=>Rh!=null?JSON.stringify(Rh):void 0},"gen_ai.system":Lc.provider,"gen_ai.request.model":Lc.modelId,"gen_ai.request.frequency_penalty":we.frequencyPenalty,"gen_ai.request.max_tokens":we.maxOutputTokens,"gen_ai.request.presence_penalty":we.presencePenalty,"gen_ai.request.stop_sequences":we.stopSequences,"gen_ai.request.temperature":we.temperature,"gen_ai.request.top_k":we.topK,"gen_ai.request.top_p":we.topP}}),tracer:Re,endWhenDone:!1,fn:async Pt=>({startTimestampMs:P(),doStreamSpan:Pt,result:await Lc.doStream({...we,tools:nb,toolChoice:Rh,responseFormat:await T?.responseFormat,prompt:Ly,providerOptions:ob,abortSignal:s,headers:r,includeRawChunks:Da})})})),FA=avr({tools:h,generatorStream:ur,tracer:Re,telemetry:t,system:u,messages:Vp,repairToolCall:_,abortSignal:s,experimental_context:Y,generateId:R,stepNumber:me.length,model:Wp,onToolCallStart:[z,G.onToolCallStart],onToolCallFinish:[J,G.onToolCallFinish]}),UA=(Vt=ce?.requestBody)==null||Vt?Ph??{}:{...Ph,body:void 0},Kp=[],Jp=[];let $y;const Yr={};let dl="other",ib,Is=O1(),Sce,Cce=!0,Ou={id:R(),timestamp:new Date,modelId:W.modelId},lcr="";C.addStream(FA.pipeThrough(new TransformStream({async transform(Pt,Zs){var ab,lb,cb,ub,db;if(LA(),Pt.type==="stream-start"){$y=Pt.warnings;return}if(Cce){const Rs=P()-sb;Cce=!1,ul.addEvent("ai.stream.firstChunk",{"ai.response.msToFirstChunk":Rs}),ul.setAttributes({"ai.response.msToFirstChunk":Rs}),Zs.enqueue({type:"start-step",request:UA,warnings:$y??[]})}const pb=Pt.type;switch(pb){case"tool-approval-request":case"text-start":case"text-end":{Zs.enqueue(Pt);break}case"text-delta":{Pt.delta.length>0&&(Zs.enqueue({type:"text-delta",id:Pt.id,text:Pt.delta,providerMetadata:Pt.providerMetadata}),lcr+=Pt.delta);break}case"reasoning-start":case"reasoning-end":{Zs.enqueue(Pt);break}case"reasoning-delta":{Zs.enqueue({type:"reasoning-delta",id:Pt.id,text:Pt.delta,providerMetadata:Pt.providerMetadata});break}case"tool-call":{Zs.enqueue(Pt),Kp.push(Pt);break}case"tool-result":{Zs.enqueue(Pt),Pt.preliminary||Jp.push(Pt);break}case"tool-error":{Zs.enqueue(Pt),Jp.push(Pt);break}case"response-metadata":{Ou={id:(ab=Pt.id)!=null?ab:Ou.id,timestamp:(lb=Pt.timestamp)!=null?lb:Ou.timestamp,modelId:(cb=Pt.modelId)!=null?cb:Ou.modelId};break}case"finish":{Is=Pt.usage,dl=Pt.finishReason,ib=Pt.rawFinishReason,Sce=Pt.providerMetadata;const Rs=P()-sb;ul.addEvent("ai.stream.finish"),ul.setAttributes({"ai.response.msToFinish":Rs,"ai.response.avgOutputTokensPerSecond":1e3*((ub=Is.outputTokens)!=null?ub:0)/Rs});break}case"file":{Zs.enqueue(Pt);break}case"source":{Zs.enqueue(Pt);break}case"tool-input-start":{Yr[Pt.id]=Pt.toolName;const Rs=h?.[Pt.toolName];Rs?.onInputStart!=null&&await Rs.onInputStart({toolCallId:Pt.id,messages:Vp,abortSignal:s,experimental_context:Y}),Zs.enqueue({...Pt,dynamic:(db=Pt.dynamic)!=null?db:Rs?.type==="dynamic",title:Rs?.title});break}case"tool-input-end":{delete Yr[Pt.id],Zs.enqueue(Pt);break}case"tool-input-delta":{const Rs=Yr[Pt.id],Fy=h?.[Rs];Fy?.onInputDelta!=null&&await Fy.onInputDelta({inputTextDelta:Pt.delta,toolCallId:Pt.id,messages:Vp,abortSignal:s,experimental_context:Y}),Zs.enqueue(Pt);break}case"error":{Zs.enqueue(Pt),dl="error";break}case"raw":{Da&&Zs.enqueue(Pt);break}default:{const Rs=pb;throw new Error(`Unknown chunk type: ${Rs}`)}}},async flush(Pt){var Zs,ab,lb,cb,ub,db,pb;const Rs=Kp.length>0?JSON.stringify(Kp):void 0;try{ul.setAttributes(await $r({telemetry:t,attributes:{"ai.response.finishReason":dl,"ai.response.toolCalls":{output:()=>Rs},"ai.response.id":Ou.id,"ai.response.model":Ou.modelId,"ai.response.timestamp":Ou.timestamp.toISOString(),"ai.usage.inputTokens":Is.inputTokens,"ai.usage.inputTokenDetails.noCacheTokens":(Zs=Is.inputTokenDetails)==null?void 0:Zs.noCacheTokens,"ai.usage.inputTokenDetails.cacheReadTokens":(ab=Is.inputTokenDetails)==null?void 0:ab.cacheReadTokens,"ai.usage.inputTokenDetails.cacheWriteTokens":(lb=Is.inputTokenDetails)==null?void 0:lb.cacheWriteTokens,"ai.usage.outputTokens":Is.outputTokens,"ai.usage.outputTokenDetails.textTokens":(cb=Is.outputTokenDetails)==null?void 0:cb.textTokens,"ai.usage.outputTokenDetails.reasoningTokens":(ub=Is.outputTokenDetails)==null?void 0:ub.reasoningTokens,"ai.usage.totalTokens":Is.totalTokens,"ai.usage.reasoningTokens":(db=Is.outputTokenDetails)==null?void 0:db.reasoningTokens,"ai.usage.cachedInputTokens":(pb=Is.inputTokenDetails)==null?void 0:pb.cacheReadTokens,"gen_ai.response.finish_reasons":[dl],"gen_ai.response.id":Ou.id,"gen_ai.response.model":Ou.modelId,"gen_ai.usage.input_tokens":Is.inputTokens,"gen_ai.usage.output_tokens":Is.outputTokens}}))}catch{}Pt.enqueue({type:"finish-step",finishReason:dl,rawFinishReason:ib,usage:Is,providerMetadata:Sce,response:{...Ou,headers:Ui?.headers}});const Fy=eke(Pe,Is);await K.promise;const yF=me[me.length-1];try{ul.setAttributes(await $r({telemetry:t,attributes:{"ai.response.text":{output:()=>yF.text},"ai.response.reasoning":{output:()=>yF.reasoningText},"ai.response.providerMetadata":JSON.stringify(yF.providerMetadata)}}))}catch{}finally{ul.end()}const kce=Kp.filter(Ei=>Ei.providerExecuted!==!0),ccr=Jp.filter(Ei=>Ei.providerExecuted!==!0);for(const Ei of Kp){if(Ei.providerExecuted!==!0)continue;const vF=h?.[Ei.toolName];vF?.type==="provider"&&vF.supportsDeferredResults&&(Jp.some(_F=>(_F.type==="tool-result"||_F.type==="tool-error")&&_F.toolCallId===Ei.toolCallId)||$e.set(Ei.toolCallId,{toolName:Ei.toolName}))}for(const Ei of Jp)(Ei.type==="tool-result"||Ei.type==="tool-error")&&$e.delete(Ei.toolCallId);if(Ny(),Ih(),(kce.length>0&&ccr.length===kce.length||$e.size>0)&&!await ake({stopConditions:b,steps:me})){Ae.push(...await Ej({content:me[me.length-1].content,tools:h}));try{await ee({currentStep:ue+1,responseMessages:Ae,usage:Fy})}catch(Ei){Pt.enqueue({type:"error",error:Ei}),C.closeStream()}}else Pt.enqueue({type:"finish",finishReason:dl,rawFinishReason:ib,totalUsage:Fy}),C.closeStream()}})))}finally{Ny(),Ih()}}await ee({currentStep:0,responseMessages:F,usage:O1()})}}).catch(Ee=>{C.addStream(new ReadableStream({start(ke){ke.enqueue({type:"error",error:Ee}),ke.close()}})),C.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}get rawFinishReason(){return this.consumeStream(),this._rawFinishReason.promise}teeStream(){const[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return Ud(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type==="text-delta"&&t.enqueue(e.text)}})))}get fullStream(){return Ud(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await ivr({stream:this.fullStream,onError:e?.onError})}catch(r){(t=e?.onError)==null||t.call(e,r)}}get experimental_partialOutputStream(){return this.partialOutputStream}get partialOutputStream(){return Ud(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}get elementStream(){var e,t,r;const n=(e=this.outputSpecification)==null?void 0:e.createElementStreamTransform();if(n==null)throw new Zo({functionality:`element streams in ${(r=(t=this.outputSpecification)==null?void 0:t.name)!=null?r:"text"} mode`});return Ud(this.teeStream().pipeThrough(n))}get output(){return this.finalStep.then(e=>{var t;return((t=this.outputSpecification)!=null?t:UT()).parseCompleteOutput({text:e.text},{response:e.response,usage:e.usage,finishReason:e.finishReason})})}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o=!0,sendSources:s=!1,sendStart:i=!0,sendFinish:a=!0,onError:l=Zh}={}){const c=t!=null?Qyr({originalMessages:e,responseMessageId:t}):void 0,u=m=>{var h;const g=(h=this.tools)==null?void 0:h[m.toolName];return g==null?m.dynamic:g?.type==="dynamic"?!0:void 0},d=this.fullStream.pipeThrough(new TransformStream({transform:async(m,h)=>{const g=n?.({part:m}),y=m.type;switch(y){case"text-start":{h.enqueue({type:"text-start",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"text-delta":{h.enqueue({type:"text-delta",id:m.id,delta:m.text,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"text-end":{h.enqueue({type:"text-end",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"reasoning-start":{h.enqueue({type:"reasoning-start",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"reasoning-delta":{o&&h.enqueue({type:"reasoning-delta",id:m.id,delta:m.text,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"reasoning-end":{h.enqueue({type:"reasoning-end",id:m.id,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"file":{h.enqueue({type:"file",mediaType:m.file.mediaType,url:`data:${m.file.mediaType};base64,${m.file.base64}`,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"source":{s&&m.sourceType==="url"&&h.enqueue({type:"source-url",sourceId:m.id,url:m.url,title:m.title,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}}),s&&m.sourceType==="document"&&h.enqueue({type:"source-document",sourceId:m.id,mediaType:m.mediaType,title:m.title,filename:m.filename,...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{}});break}case"tool-input-start":{const v=u(m);h.enqueue({type:"tool-input-start",toolCallId:m.id,toolName:m.toolName,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{},...m.title!=null?{title:m.title}:{}});break}case"tool-input-delta":{h.enqueue({type:"tool-input-delta",toolCallId:m.id,inputTextDelta:m.delta});break}case"tool-call":{const v=u(m);m.invalid?h.enqueue({type:"tool-input-error",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{},errorText:l(m.error),...m.title!=null?{title:m.title}:{}}):h.enqueue({type:"tool-input-available",toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{},...m.title!=null?{title:m.title}:{}});break}case"tool-approval-request":{h.enqueue({type:"tool-approval-request",approvalId:m.approvalId,toolCallId:m.toolCall.toolCallId});break}case"tool-result":{const v=u(m);h.enqueue({type:"tool-output-available",toolCallId:m.toolCallId,output:m.output,...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...m.preliminary!=null?{preliminary:m.preliminary}:{},...v!=null?{dynamic:v}:{}});break}case"tool-error":{const v=u(m);h.enqueue({type:"tool-output-error",toolCallId:m.toolCallId,errorText:m.providerExecuted?typeof m.error=="string"?m.error:JSON.stringify(m.error):l(m.error),...m.providerExecuted!=null?{providerExecuted:m.providerExecuted}:{},...m.providerMetadata!=null?{providerMetadata:m.providerMetadata}:{},...v!=null?{dynamic:v}:{}});break}case"tool-output-denied":{h.enqueue({type:"tool-output-denied",toolCallId:m.toolCallId});break}case"error":{h.enqueue({type:"error",errorText:l(m.error)});break}case"start-step":{h.enqueue({type:"start-step"});break}case"finish-step":{h.enqueue({type:"finish-step"});break}case"start":{i&&h.enqueue({type:"start",...g!=null?{messageMetadata:g}:{},...c!=null?{messageId:c}:{}});break}case"finish":{a&&h.enqueue({type:"finish",finishReason:m.finishReason,...g!=null?{messageMetadata:g}:{}});break}case"abort":{h.enqueue(m);break}case"tool-input-end":break;case"raw":break;default:{const v=y;throw new Error(`Unknown chunk type: ${v}`)}}g!=null&&y!=="start"&&y!=="finish"&&h.enqueue({type:"message-metadata",messageMetadata:g})}}));return Ud(ovr({stream:d,messageId:c??t?.(),originalMessages:e,onFinish:r,onError:l}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c,...u}={}){svr({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:r,onFinish:n,messageMetadata:o,sendReasoning:s,sendSources:i,sendFinish:a,sendStart:l,onError:c}),...u})}pipeTextStreamToResponse(e,t){mke({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l,...c}={}){return Xyr({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:r,messageMetadata:n,sendReasoning:o,sendSources:s,sendFinish:i,sendStart:a,onError:l}),...c})}toTextStreamResponse(e){return dke({textStream:this.textStream,...e})}},vvr=We(()=>Ve(p.array(p.object({id:p.string(),role:p.enum(["system","user","assistant"]),metadata:p.unknown().optional(),parts:p.array(p.union([p.object({type:p.literal("text"),text:p.string(),state:p.enum(["streaming","done"]).optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("reasoning"),text:p.string(),state:p.enum(["streaming","done"]).optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("source-url"),sourceId:p.string(),url:p.string(),title:p.string().optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("source-document"),sourceId:p.string(),mediaType:p.string(),title:p.string(),filename:p.string().optional(),providerMetadata:wt.optional()}),p.object({type:p.literal("file"),mediaType:p.string(),filename:p.string().optional(),url:p.string(),providerMetadata:wt.optional()}),p.object({type:p.literal("step-start")}),p.object({type:p.string().startsWith("data-"),id:p.string().optional(),data:p.unknown()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("input-streaming"),input:p.unknown().optional(),providerExecuted:p.boolean().optional(),callProviderMetadata:wt.optional(),output:p.never().optional(),errorText:p.never().optional(),approval:p.never().optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("input-available"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.never().optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("approval-requested"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.never().optional(),reason:p.never().optional()})}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("approval-responded"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.boolean(),reason:p.string().optional()})}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("output-available"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.unknown(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),preliminary:p.boolean().optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("output-error"),input:p.unknown(),rawInput:p.unknown().optional(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.string(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.literal("dynamic-tool"),toolName:p.string(),toolCallId:p.string(),state:p.literal("output-denied"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!1),reason:p.string().optional()})}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("input-streaming"),providerExecuted:p.boolean().optional(),callProviderMetadata:wt.optional(),input:p.unknown().optional(),output:p.never().optional(),errorText:p.never().optional(),approval:p.never().optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("input-available"),providerExecuted:p.boolean().optional(),input:p.unknown(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.never().optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("approval-requested"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.never().optional(),reason:p.never().optional()})}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("approval-responded"),input:p.unknown(),providerExecuted:p.boolean().optional(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.boolean(),reason:p.string().optional()})}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("output-available"),providerExecuted:p.boolean().optional(),input:p.unknown(),output:p.unknown(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),preliminary:p.boolean().optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("output-error"),providerExecuted:p.boolean().optional(),input:p.unknown(),rawInput:p.unknown().optional(),output:p.never().optional(),errorText:p.string(),callProviderMetadata:wt.optional(),resultProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!0),reason:p.string().optional()}).optional()}),p.object({type:p.string().startsWith("tool-"),toolCallId:p.string(),state:p.literal("output-denied"),providerExecuted:p.boolean().optional(),input:p.unknown(),output:p.never().optional(),errorText:p.never().optional(),callProviderMetadata:wt.optional(),approval:p.object({id:p.string(),approved:p.literal(!1),reason:p.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty"))),Yxe=class{constructor(e){this.value=e.value,this.embedding=e.embedding,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response}},mq=class{constructor(e){this.values=e.values,this.embeddings=e.embeddings,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.responses=e.responses}},Zxe={type:"no-schema",jsonSchema:async()=>{},async validatePartialResult({value:e,textDelta:t}){return{success:!0,value:{partial:e,textDelta:t}}},async validateFinalResult(e,t){return e===void 0?{success:!1,error:new ki({message:"No object generated: response did not match schema.",text:t.text,response:t.response,usage:t.usage,finishReason:t.finishReason})}:{success:!0,value:e}},createElementStream(){throw new Zo({functionality:"element streams in no-schema mode"})}},Xxe=e=>({type:"object",jsonSchema:async()=>await e.jsonSchema,async validatePartialResult({value:t,textDelta:r}){return{success:!0,value:{partial:t,textDelta:r}}},async validateFinalResult(t){return Ba({value:t,schema:e})},createElementStream(){throw new Zo({functionality:"element streams in object mode"})}}),Qxe=e=>({type:"array",jsonSchema:async()=>{const{$schema:t,...r}=await e.jsonSchema;return{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:r}},required:["elements"],additionalProperties:!1}},async validatePartialResult({value:t,latestObject:r,isFirstDelta:n,isFinalDelta:o}){var s;if(!d1(t)||!Gge(t.elements))return{success:!1,error:new da({value:t,cause:"value must be an object that contains an array of elements"})};const i=t.elements,a=[];for(let u=0;u<i.length;u++){const d=i[u],m=await Ba({value:d,schema:e});if(!(u===i.length-1&&!o)){if(!m.success)return m;a.push(m.value)}}const l=(s=r?.length)!=null?s:0;let c="";return n&&(c+="["),l>0&&(c+=","),c+=a.slice(l).map(u=>JSON.stringify(u)).join(","),o&&(c+="]"),{success:!0,value:{partial:a,textDelta:c}}},async validateFinalResult(t){if(!d1(t)||!Gge(t.elements))return{success:!1,error:new da({value:t,cause:"value must be an object that contains an array of elements"})};const r=t.elements;for(const n of r){const o=await Ba({value:n,schema:e});if(!o.success)return o}return{success:!0,value:r}},createElementStream(t){let r=0;return Ud(t.pipeThrough(new TransformStream({transform(n,o){switch(n.type){case"object":{const s=n.object;for(;r<s.length;r++)o.enqueue(s[r]);break}case"text-delta":case"finish":case"error":break;default:{const s=n;throw new Error(`Unsupported chunk type: ${s}`)}}}})))}}),eAe=e=>({type:"enum",jsonSchema:async()=>({$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:e}},required:["result"],additionalProperties:!1}),async validateFinalResult(t){if(!d1(t)||typeof t.result!="string")return{success:!1,error:new da({value:t,cause:'value must be an object that contains a string in the "result" property.'})};const r=t.result;return e.includes(r)?{success:!0,value:r}:{success:!1,error:new da({value:t,cause:"value must be a string in the enum"})}},async validatePartialResult({value:t,textDelta:r}){if(!d1(t)||typeof t.result!="string")return{success:!1,error:new da({value:t,cause:'value must be an object that contains a string in the "result" property.'})};const n=t.result,o=e.filter(s=>s.startsWith(n));return t.result.length===0||o.length===0?{success:!1,error:new da({value:t,cause:"value must be a string in the enum"})}:{success:!0,value:{partial:o.length>1?n:o[0],textDelta:r}}},createElementStream(){throw new Zo({functionality:"element streams in enum mode"})}}),tAe=Ev({prefix:"aiobj",size:24}),rAe=class{constructor(e){this.object=e.object,this.finishReason=e.finishReason,this.usage=e.usage,this.warnings=e.warnings,this.providerMetadata=e.providerMetadata,this.response=e.response,this.request=e.request,this.reasoning=e.reasoning}toJsonResponse(e){var t;return new Response(JSON.stringify(this.object),{status:(t=e?.status)!=null?t:200,headers:$T(e?.headers,{"content-type":"application/json; charset=utf-8"})})}},nAe=Ev({prefix:"aiobj",size:24}),oAe=class{constructor({model:e,headers:t,telemetry:r,settings:n,maxRetries:o,abortSignal:s,outputStrategy:i,system:a,prompt:l,messages:c,schemaName:u,schemaDescription:d,providerOptions:m,repairText:h,onError:g,onFinish:y,download:v,generateId:_,currentDate:b,now:T}){this._object=new gl,this._usage=new gl,this._providerMetadata=new gl,this._warnings=new gl,this._request=new gl,this._response=new gl,this._finishReason=new gl;const k=Sv(e),{maxRetries:A,retry:I}=nf({maxRetries:o,abortSignal:s}),P=rf(n),R=Cv({model:k,telemetry:r,headers:t,settings:{...P,maxRetries:A}}),x=kv(r),O=this,N=yke(),M=new TransformStream({transform(D,L){L.enqueue(D),D.type==="error"&&g({error:M1(D.error)})}});this.baseStream=N.stream.pipeThrough(M),ja({name:"ai.streamObject",attributes:$r({telemetry:r,attributes:{...za({operationId:"ai.streamObject",telemetry:r}),...R,"ai.prompt":{input:()=>JSON.stringify({system:a,prompt:l,messages:c})},"ai.schema":{input:async()=>JSON.stringify(await i.jsonSchema())},"ai.schema.name":u,"ai.schema.description":d,"ai.settings.output":i.type}}),tracer:x,endWhenDone:!1,fn:async D=>{const L=await P1({system:a,prompt:l,messages:c}),$={responseFormat:{type:"json",schema:await i.jsonSchema(),name:u,description:d},...rf(n),prompt:await R1({prompt:L,supportedUrls:await k.supportedUrls,download:v}),providerOptions:m,abortSignal:s,headers:t,includeRawChunks:!1},U={transform:(Se,ne)=>{switch(Se.type){case"text-delta":ne.enqueue(Se.delta);break;case"response-metadata":case"finish":case"error":case"stream-start":ne.enqueue(Se);break}}},{result:{stream:j,response:B,request:z},doStreamSpan:J,startTimestampMs:Y}=await I(()=>ja({name:"ai.streamObject.doStream",attributes:$r({telemetry:r,attributes:{...za({operationId:"ai.streamObject.doStream",telemetry:r}),...R,"ai.prompt.messages":{input:()=>D1($.prompt)},"gen_ai.system":k.provider,"gen_ai.request.model":k.modelId,"gen_ai.request.frequency_penalty":P.frequencyPenalty,"gen_ai.request.max_tokens":P.maxOutputTokens,"gen_ai.request.presence_penalty":P.presencePenalty,"gen_ai.request.temperature":P.temperature,"gen_ai.request.top_k":P.topK,"gen_ai.request.top_p":P.topP}}),tracer:x,endWhenDone:!1,fn:async Se=>({startTimestampMs:T(),doStreamSpan:Se,result:await k.doStream($)})}));O._request.resolve(z??{});let ie,ce=O1(),re,G,K,Ce,be="",ge="",H={id:_(),timestamp:b(),modelId:k.modelId},se,ye,Q=!0,me=!0;const $e=j.pipeThrough(new TransformStream(U)).pipeThrough(new TransformStream({async transform(Se,ne){var Fe,ae,oe;if(typeof Se=="object"&&Se.type==="stream-start"){ie=Se.warnings;return}if(Q){const pe=T()-Y;Q=!1,J.addEvent("ai.stream.firstChunk",{"ai.stream.msToFirstChunk":pe}),J.setAttributes({"ai.stream.msToFirstChunk":pe})}if(typeof Se=="string"){be+=Se,ge+=Se;const{value:pe,state:X}=await Av(be);if(pe!==void 0&&!L1(se,pe)){const Z=await i.validatePartialResult({value:pe,textDelta:ge,latestObject:ye,isFirstDelta:me,isFinalDelta:X==="successful-parse"});Z.success&&!L1(ye,Z.value.partial)&&(se=pe,ye=Z.value.partial,ne.enqueue({type:"object",object:ye}),ne.enqueue({type:"text-delta",textDelta:Z.value.textDelta}),ge="",me=!1)}return}switch(Se.type){case"response-metadata":{H={id:(Fe=Se.id)!=null?Fe:H.id,timestamp:(ae=Se.timestamp)!=null?ae:H.timestamp,modelId:(oe=Se.modelId)!=null?oe:H.modelId};break}case"finish":{ge!==""&&ne.enqueue({type:"text-delta",textDelta:ge}),re=Se.finishReason.unified,ce=xv(Se.usage),G=Se.providerMetadata,ne.enqueue({...Se,finishReason:Se.finishReason.unified,usage:ce,response:H}),Bu({warnings:ie??[],provider:k.provider,model:k.modelId}),O._usage.resolve(ce),O._providerMetadata.resolve(G),O._warnings.resolve(ie),O._response.resolve({...H,headers:B?.headers}),O._finishReason.resolve(re??"other");try{K=await Tke(be,i,h,{response:H,usage:ce,finishReason:re}),O._object.resolve(K)}catch(pe){Ce=pe,O._object.reject(pe)}break}default:{ne.enqueue(Se);break}}},async flush(Se){try{const ne=ce??{promptTokens:NaN,completionTokens:NaN,totalTokens:NaN};J.setAttributes(await $r({telemetry:r,attributes:{"ai.response.finishReason":re,"ai.response.object":{output:()=>JSON.stringify(K)},"ai.response.id":H.id,"ai.response.model":H.modelId,"ai.response.timestamp":H.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(G),"ai.usage.inputTokens":ne.inputTokens,"ai.usage.outputTokens":ne.outputTokens,"ai.usage.totalTokens":ne.totalTokens,"ai.usage.reasoningTokens":ne.reasoningTokens,"ai.usage.cachedInputTokens":ne.cachedInputTokens,"gen_ai.response.finish_reasons":[re],"gen_ai.response.id":H.id,"gen_ai.response.model":H.modelId,"gen_ai.usage.input_tokens":ne.inputTokens,"gen_ai.usage.output_tokens":ne.outputTokens}})),J.end(),D.setAttributes(await $r({telemetry:r,attributes:{"ai.usage.inputTokens":ne.inputTokens,"ai.usage.outputTokens":ne.outputTokens,"ai.usage.totalTokens":ne.totalTokens,"ai.usage.reasoningTokens":ne.reasoningTokens,"ai.usage.cachedInputTokens":ne.cachedInputTokens,"ai.response.object":{output:()=>JSON.stringify(K)},"ai.response.providerMetadata":JSON.stringify(G)}})),await y?.({usage:ne,object:K,error:Ce,response:{...H,headers:B?.headers},warnings:ie,providerMetadata:G})}catch(ne){Se.enqueue({type:"error",error:ne})}finally{D.end()}}}));N.addStream($e)}}).catch(D=>{N.addStream(new ReadableStream({start(L){L.enqueue({type:"error",error:D}),L.close()}}))}).finally(()=>{N.close()}),this.outputStrategy=i}get object(){return this._object.promise}get usage(){return this._usage.promise}get providerMetadata(){return this._providerMetadata.promise}get warnings(){return this._warnings.promise}get request(){return this._request.promise}get response(){return this._response.promise}get finishReason(){return this._finishReason.promise}get partialObjectStream(){return Ud(this.baseStream.pipeThrough(new TransformStream({transform(e,t){switch(e.type){case"object":t.enqueue(e.object);break;case"text-delta":case"finish":case"error":break;default:{const r=e;throw new Error(`Unsupported chunk type: ${r}`)}}}})))}get elementStream(){return this.outputStrategy.createElementStream(this.baseStream)}get textStream(){return Ud(this.baseStream.pipeThrough(new TransformStream({transform(e,t){switch(e.type){case"text-delta":t.enqueue(e.textDelta);break;case"object":case"finish":case"error":break;default:{const r=e;throw new Error(`Unsupported chunk type: ${r}`)}}}})))}get fullStream(){return Ud(this.baseStream)}pipeTextStreamToResponse(e,t){mke({response:e,textStream:this.textStream,...t})}toTextStreamResponse(e){return dke({textStream:this.textStream,...e})}},_vr=Cke(),hq=({model:e,middleware:t,modelId:r,providerId:n})=>[...gm(t)].reverse().reduce((o,s)=>sAe({model:o,middleware:s,modelId:r,providerId:n}),e),sAe=({model:e,middleware:{transformParams:t,wrapGenerate:r,wrapStream:n,overrideProvider:o,overrideModelId:s,overrideSupportedUrls:i},modelId:a,providerId:l})=>{var c,u,d;async function m({params:h,type:g}){return t?await t({params:h,type:g,model:e}):h}return{specificationVersion:"v3",provider:(c=l??o?.({model:e}))!=null?c:e.provider,modelId:(u=a??s?.({model:e}))!=null?u:e.modelId,supportedUrls:(d=i?.({model:e}))!=null?d:e.supportedUrls,async doGenerate(h){const g=await m({params:h,type:"generate"}),y=async()=>e.doGenerate(g);return r?r({doGenerate:y,doStream:async()=>e.doStream(g),params:g,model:e}):y()},async doStream(h){const g=await m({params:h,type:"stream"}),y=async()=>e.doGenerate(g),v=async()=>e.doStream(g);return n?n({doGenerate:y,doStream:v,params:g,model:e}):v()}}},iAe="AI_NoSuchProviderError",aAe=`vercel.ai.error.${iAe}`,lAe=Symbol.for(aAe),wvr=lAe,cAe=Cke(),uAe=class{constructor(e){var t;this.text=e.text,this.segments=e.segments,this.language=e.language,this.durationInSeconds=e.durationInSeconds,this.warnings=e.warnings,this.responses=e.responses,this.providerMetadata=(t=e.providerMetadata)!=null?t:{}}}}}),dAe={};he(dAe,{APICallError:()=>Gr,InvalidToolInputError:()=>Iv,NoObjectGeneratedError:()=>ki,NoOutputGeneratedError:()=>ac,NoSuchToolError:()=>Rv});var Bd=S({"src/lib/utils/generationErrors.ts"(){"use strict";fq(),Rt()}});function gq(e,t){if("get"in e&&typeof e.get=="function")return e.get(t);const r=t.toLowerCase();for(const[n,o]of Object.entries(e))if(n.toLowerCase()===r)return o;return null}function BT(e){const t=gq(e,"Retry-After");if(t){const n=parseInt(t,10);if(!Number.isNaN(n))return Math.max(0,n*1e3);const o=new Date(t);if(!Number.isNaN(o.getTime()))return Math.max(0,o.getTime()-Date.now())}const r=gq(e,"X-RateLimit-Reset");if(r){const n=parseInt(r,10);if(!Number.isNaN(n)){const o=n>1e12?n:n*1e3;return Math.max(0,o-Date.now())}}if(gq(e,"X-RateLimit-Remaining")==="0")return 1e3}var yq=S({"src/lib/utils/retryAfter.ts"(){"use strict"}});function zT(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;const r=t.$metadata;if(typeof r=="object"&&r!==null){const n=r.httpStatusCode;if(typeof n=="number")return n}}function pAe(e){if(!e||typeof e!="object")return;const t=e;if(typeof t.retryAfterMs=="number"&&Number.isFinite(t.retryAfterMs))return t.retryAfterMs;for(const r of[t.headers,t.responseHeaders])if(r&&typeof r=="object"){const n=BT(r);if(n!==void 0)return n}}function mAe(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.type==="insufficient_quota")return!0;if(typeof t.responseBody=="string")try{return JSON.parse(t.responseBody)?.error?.type==="insufficient_quota"}catch{return!1}return!1}function bvr(e){if(mAe(e))return!1;if(Gr.isInstance(e))return e.isRetryable;if(e instanceof Ne)return e.retriable;const t=zT(e);return t!==void 0?t===429||t>=500:!1}function hAe(e){return Gr.isInstance(e)?e.statusCode:zT(e)}function Tvr(e){if(Gr.isInstance(e)&&e.responseHeaders){const t=BT(e.responseHeaders);if(t!==void 0)return t}return e instanceof Ne&&e.retryAfterMs!==void 0&&Number.isFinite(e.retryAfterMs)?e.retryAfterMs:pAe(e)}async function Mv(e,t,r,n=yAe){for(let o=0;o<=U1;o++)try{const s=await e();return t?.setAttribute("gen_ai.provider.total_attempts",o+1),o>0&&f.info(`[providerRetry] ${r} succeeded after ${o+1} attempts`),s}catch(s){const i=bvr(s),a=hAe(s),l=s instanceof Error?s.message:String(s);if(!i||o===U1)throw t?.setAttribute("gen_ai.provider.total_attempts",o+1),o>0&&t?.setAttribute("gen_ai.provider.retries_exhausted",!0),f.warn(`[providerRetry] ${r} failed (non-retryable or retries exhausted)`,{attempt:o+1,retryable:i,statusCode:a,error:l}),s;const c=Tvr(s);if(c!==void 0&&c>vq){t?.setAttribute("gen_ai.provider.total_attempts",o+1),t?.addEvent("gen_ai.provider.retry_suppressed",{"retry.after_ms":c,...a!==void 0&&{"retry.status_code":a}});try{Object.assign(s,{isRetryable:!1,retryAfterMs:c})}catch{}throw f.warn(`[providerRetry] ${r} not retrying \u2014 server requested a ${Math.round(c/1e3)}s wait (cap ${vq/1e3}s); surfacing for fallback`,{attempt:o+1,retryAfterMs:c,statusCode:a}),s}const u=(c===void 0?void 0:Math.max(0,c))??Math.max(fAe*Math.pow(2,o),gAe);t?.addEvent("gen_ai.provider.retry",{"retry.attempt":o+1,"retry.delay_ms":u,...a!==void 0&&{"retry.status_code":a},"retry.error":l.slice(0,256)}),f.warn(`[providerRetry] ${r} retrying after ${a||"unknown"} error`,{attempt:o+1,maxRetries:U1,delayMs:u,statusCode:a,error:l}),await n(u)}throw new Error(`[providerRetry] ${r} exhausted all retries`)}var U1,fAe,gAe,vq,yAe,ym=S({"src/lib/utils/providerRetry.ts"(){"use strict";er(),ct(),q(),Bd(),yq(),U1=2,fAe=1e3,gAe=1e4,vq=6e4,yAe=e=>new Promise(t=>setTimeout(t,e))}}),_q,vAe=S({"src/lib/constants/networkErrorCodes.ts"(){"use strict";_q=new Set(["ECONNRESET","ETIMEDOUT","ECONNREFUSED","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"])}}),jT={};he(jT,{AsyncLocalStorage:()=>LAe,Buffer:()=>ARe,Channel:()=>yRe,DatabaseSync:()=>xRe,Duplex:()=>FAe,EventEmitter:()=>NAe,Http2ServerRequest:()=>DRe,Http2ServerResponse:()=>ORe,Interface:()=>kRe,MIMEType:()=>BRe,PassThrough:()=>UAe,PerformanceObserver:()=>hRe,Readable:()=>bq,ReadableStream:()=>BAe,Resolver:()=>pRe,TextDecoder:()=>Sq,TextEncoder:()=>GT,Transform:()=>$Ae,URL:()=>QIe,URLSearchParams:()=>eRe,Worker:()=>bRe,Writable:()=>Tq,access:()=>hIe,appendFile:()=>WAe,appendFileSync:()=>TAe,arch:()=>MIe,arrayBuffer:()=>NRe,basename:()=>AAe,builtinModules:()=>JIe,callbackify:()=>aRe,channel:()=>gRe,chmodSync:()=>VAe,clearInterval:()=>URe,clearTimeout:()=>$Re,closeSync:()=>ZAe,connect:()=>LIe,constants:()=>IRe,copyFileSync:()=>JAe,cpSync:()=>EAe,cpus:()=>AIe,createConnection:()=>$Ie,createGunzip:()=>GIe,createGzip:()=>HIe,createHash:()=>Kc,createHmac:()=>wq,createInterface:()=>CRe,createReadStream:()=>aIe,createRequire:()=>KIe,createServer:()=>SAe,createWriteStream:()=>iIe,debug:()=>sRe,debuglog:()=>Eq,default:()=>_Ae,deflateSync:()=>UIe,deprecate:()=>iRe,deserialize:()=>wRe,dirname:()=>xAe,exec:()=>wIe,execFile:()=>TIe,execFileSync:()=>EIe,execSync:()=>bIe,existsSync:()=>qAe,extname:()=>IAe,fileURLToPath:()=>tRe,finished:()=>jAe,format:()=>XIe,freemem:()=>IIe,fstatSync:()=>XAe,get:()=>NIe,gunzip:()=>qIe,gunzipSync:()=>BIe,gzip:()=>jIe,gzipSync:()=>zIe,hasSubscribers:()=>vRe,homedir:()=>CIe,hostname:()=>xIe,inflateSync:()=>FIe,inherits:()=>nRe,inspect:()=>qT,isAbsolute:()=>PAe,isBuiltin:()=>YIe,isDeepStrictEqual:()=>lRe,isIP:()=>MRe,isIPv4:()=>PRe,isIPv6:()=>RRe,isMainThread:()=>TRe,join:()=>CAe,lookup:()=>dRe,mkdir:()=>uIe,mkdirSync:()=>QAe,monitorEventLoopDelay:()=>fRe,normalize:()=>OAe,ok:()=>VIe,open:()=>yIe,openSync:()=>YAe,parentPort:()=>ERe,parse:()=>ZIe,pathToFileURL:()=>rRe,performance:()=>mRe,pipeline:()=>zAe,platform:()=>SIe,posix:()=>DAe,promises:()=>wAe,promisify:()=>oRe,randomBytes:()=>af,randomUUID:()=>st,readFile:()=>lIe,readFileSync:()=>GAe,readdir:()=>pIe,readdirSync:()=>tIe,realpath:()=>vIe,realpathSync:()=>KAe,relative:()=>RAe,release:()=>DIe,rename:()=>fIe,renameSync:()=>nIe,request:()=>OIe,resolve:()=>kAe,rm:()=>gIe,rmSync:()=>sIe,rmdirSync:()=>oIe,sep:()=>MAe,serialize:()=>_Re,setInterval:()=>FRe,setTimeout:()=>LRe,spawn:()=>_Ie,stat:()=>dIe,statSync:()=>eIe,strict:()=>WIe,tmpdir:()=>kIe,toUSVString:()=>cRe,totalmem:()=>RIe,type:()=>PIe,types:()=>uRe,unlink:()=>mIe,unlinkSync:()=>rIe,webcrypto:()=>bAe,workerData:()=>SRe,writeFile:()=>cIe,writeFileSync:()=>HAe});var ho,In,_Ae,wAe,Kc,wq,af,st,bAe,TAe,EAe,SAe,CAe,kAe,xAe,AAe,IAe,RAe,PAe,MAe,DAe,OAe,NAe,LAe,bq,Tq,$Ae,FAe,UAe,BAe,zAe,jAe,qAe,GAe,HAe,VAe,WAe,KAe,JAe,YAe,ZAe,XAe,QAe,eIe,tIe,rIe,nIe,oIe,sIe,iIe,aIe,lIe,cIe,uIe,dIe,pIe,mIe,hIe,fIe,gIe,yIe,vIe,_Ie,wIe,bIe,TIe,EIe,SIe,CIe,kIe,xIe,AIe,IIe,RIe,PIe,MIe,DIe,OIe,NIe,LIe,$Ie,FIe,UIe,BIe,zIe,jIe,qIe,GIe,HIe,VIe,WIe,KIe,JIe,YIe,ZIe,XIe,QIe,eRe,tRe,rRe,nRe,oRe,Eq,sRe,qT,iRe,aRe,lRe,cRe,uRe,Sq,GT,dRe,pRe,mRe,hRe,fRe,gRe,yRe,vRe,_Re,wRe,bRe,TRe,ERe,SRe,CRe,kRe,xRe,ARe,IRe,RRe,PRe,MRe,DRe,ORe,NRe,Cq,LRe,$Re,FRe,URe,BRe,Ft=S({"node-stub:crypto"(){ho=()=>{},In=async()=>{},_Ae={},wAe={readFile:In,writeFile:In,mkdir:In,stat:In,readdir:In,unlink:In,access:In,rm:In,rename:In},Kc=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new GT().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},wq=(e,t)=>Kc(e),af=e=>new Uint8Array(e||32),st=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),bAe=globalThis.crypto,TAe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},EAe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},SAe=()=>({listen:ho,close:ho,on:ho}),CAe=(...e)=>e.join("/"),kAe=(...e)=>e.join("/"),xAe=e=>e||"",AAe=e=>e?.split?.("/")?.pop?.()||"",IAe=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},RAe=(e,t)=>t||"",PAe=()=>!1,MAe="/",DAe={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},OAe=e=>e,NAe=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},LAe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},bq=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Tq=class{write(){return!0}end(){}on(){return this}destroy(){}},$Ae=class{push(){}on(){return this}},FAe=class{on(){return this}},UAe=class{pipe(){return this}on(){return this}},BAe=globalThis.ReadableStream||class{},zAe=ho,jAe=ho,qAe=()=>!1,GAe=()=>"",HAe=ho,VAe=ho,WAe=In,KAe=e=>e,JAe=ho,YAe=()=>0,ZAe=ho,XAe=()=>({}),QAe=ho,eIe=()=>({}),tIe=()=>[],rIe=ho,nIe=ho,oIe=ho,sIe=ho,iIe=()=>new Tq,aIe=()=>new bq,lIe=In,cIe=In,uIe=In,dIe=In,pIe=In,mIe=In,hIe=In,fIe=In,gIe=In,yIe=async()=>({stat:In,readFile:In,close:In,read:In,write:In}),vIe=async e=>e,_Ie=()=>({on:ho,stdout:{on:ho},stderr:{on:ho},kill:ho}),wIe=(e,t)=>t?.(null,"",""),bIe=()=>"",TIe=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},EIe=()=>"",SIe="browser",CIe=()=>"/",kIe=()=>"/tmp",xIe=()=>"browser",AIe=()=>[{}],IIe=()=>0,RIe=()=>0,PIe=()=>"Browser",MIe=()=>"wasm",DIe=()=>"0",OIe=()=>({}),NIe=()=>({}),LIe=()=>({}),$Ie=()=>({}),FIe=()=>new Uint8Array,UIe=()=>new Uint8Array,BIe=()=>new Uint8Array,zIe=()=>new Uint8Array,jIe=(e,t)=>t?.(null,e),qIe=(e,t)=>t?.(null,e),GIe=()=>({}),HIe=()=>({}),VIe=ho,WIe={},KIe=()=>()=>({}),JIe=[],YIe=()=>!1,ZIe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),XIe=()=>"",QIe=globalThis.URL,eRe=globalThis.URLSearchParams,tRe=e=>typeof e=="string"?e.replace("file://",""):e,rRe=e=>new globalThis.URL("file://"+e),nRe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},oRe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),Eq=e=>{const t=(...r)=>{};return t.enabled=!1,t},sRe=Eq,qT=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},qT.custom=Symbol.for("nodejs.util.inspect.custom"),qT.colors={},qT.styles={},iRe=e=>e,aRe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},lRe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),cRe=e=>String(e),uRe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},Sq=globalThis.TextDecoder,GT=globalThis.TextEncoder,dRe=(e,t)=>t?.(null,"127.0.0.1",4),pRe=class{},mRe=globalThis.performance||{now:()=>Date.now()},hRe=class{observe(){}disconnect(){}},fRe=()=>({enable:ho,disable:ho,percentile:()=>0}),gRe=()=>({}),yRe=class{},vRe=()=>!1,_Re=()=>new Uint8Array,wRe=ho,bRe=class{},TRe=!0,ERe=null,SRe=null,CRe=()=>({}),kRe=class{},xRe=class{},ARe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new GT().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new GT().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Sq().decode(this)}},IRe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},RRe=()=>!1,PRe=()=>!1,MRe=()=>0,DRe=class{},ORe=class{},NRe=async()=>new ArrayBuffer(0),Cq=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),LRe=(...e)=>Cq(globalThis.setTimeout(...e)),$Re=globalThis.clearTimeout,FRe=(...e)=>Cq(globalThis.setInterval(...e)),URe=globalThis.clearInterval,BRe=class{constructor(e){this.type=e}toString(){return this.type}}}});function fo(e,t=500){return e&&e.slice(0,t).replace(HRe,"***")}function Dv(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return"[content too large to serialize]"}}function B1(e,t=1e4){try{const r=JSON.stringify(e);return r===void 0?String(e):r.length>t?`${r.slice(0,t)}\u2026[truncated ${r.length-t} chars]`:r}catch(r){return`[unserializable: ${r instanceof Error?r.message:String(r)}]`}}function Xn(e){return e.replace(/\/\/[^/\s"'<>]*@/g,"//***@").replace(/\/\/(?:(?!\/\/)[^\s"'<>])*@/g,"//***@")}function un(e){const t=r=>r.length>200?`${r.slice(0,200)}\u2026`:r;try{const r=new URL(e);return t(`${r.protocol}//${r.host}${r.pathname}`)}catch{const r=e.split(/[?#]/)[0];return t(Xn(r))}}function Evr(e){KRe.forEach(t=>e.searchParams.delete(t))}function Svr(e){const t=[],r=[];for(const[o,s]of e.searchParams.entries())WRe.includes(o.toLowerCase())&&(t.push(`${o.toLowerCase()}=${s}`),r.push(o));return t.length===0?"":(r.forEach(o=>e.searchParams.delete(o)),t.sort(),`\0auth=${Kc("sha256").update(t.join("&")).digest("hex").slice(0,16)}`)}function zRe(e){try{const t=new URL(e);Evr(t);const r=Svr(t);return t.toString()+r}catch{return e}}function z1(e){return e.replace(/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>)]+/g,t=>un(t))}function jRe(e,t){const r=Vi(t);return e.split(Ld(t)).join(r).split(t).join(r)}function vm(e,t){const r=s=>{const i=z1(s);return t?.filePath?jRe(i,t.filePath):i};if(!(e instanceof Error))return new Error(r(String(e)));const n=new Error(r(e.message));n.name=e.name;const o=e.code;return o!==void 0&&(n.code=o),n}function j1(e,t=1e3){const r=new WeakSet,n=o=>{if(o==null)return o;if(typeof o=="string")return fo(o,t);if(typeof o!="object")return o;if(r.has(o))return"[Circular]";if(r.add(o),Array.isArray(o))return o.map(n);const s={};for(const[i,a]of Object.entries(o))VRe.some(l=>l.toLowerCase()===i.toLowerCase())?s[i]="***":s[i]=n(a);return s};return n(e)}var qRe,GRe,HRe,VRe,WRe,KRe,_r=S({"src/lib/utils/logSanitize.ts"(){"use strict";Ft(),Lr(),qRe=["sk","pk","r8","gsk","xai","tgp","fw","pplx","pa","jina","fish"],GRe=qRe.join("|"),HRe=new RegExp(`\\bBearer\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bToken\\s+[A-Za-z0-9_\\-\\.]{8,}\\b|\\bBasic\\s+[A-Za-z0-9+/=]{12,}\\b|\\b(?:${GRe})[_\\-][A-Za-z0-9_\\-\\.]{8,}\\b|\\b(?:api[_-]?key|access[_-]?token|secret[_-]?key|refresh[_-]?token)\\s*[:=]\\s*['"]?[^\\s,;'"&]+`,"gi"),VRe=["apikey","api_key","apiKey","access_token","accessToken","refresh_token","refreshToken","secret","secretkey","secret_key","secretKey","password","authorization","oauth","oauthToken","credentials","authContext","authToken","sessionToken","serviceAccountKey","secretAccessKey","userEmail"],WRe=["token","signature","x-amz-signature","x-amz-credential","x-amz-security-token","awsaccesskeyid","expires","sig","se","sp","sr","sv","x-goog-signature","x-goog-credential","x-goog-algorithm","x-goog-date","x-goog-expires","x-goog-signedheaders"],KRe=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","fbclid","gclid","_ga"]}});function Cvr(e){const t=[],r=new Set;let n=e;for(;n&&typeof n=="object"&&!r.has(n)&&t.length<YRe;){r.add(n);const o=n;t.push(o),n=o.cause}return t}function JRe(e,t){for(const r of e)if(typeof r[t]=="string")return r[t]}function kvr(e,t,r){const n=Cvr(e),o=n[0],s=typeof o?.message=="string"?o.message:e instanceof Error?e.message:"Unknown error",i=n[n.length-1],a=typeof i?.message=="string"?z1(i.message):void 0,l=a&&a!==s?`${s}: ${a}`:s;let c;for(const u of n)if(c=zT(u),c!==void 0)break;return{error:e,message:l,statusCode:c,errorName:JRe(n,"name"),errorCode:JRe(n,"code"),provider:t,modelName:r}}function Ki(e,t,r,n){if(e instanceof Od)return new jo(`Request timed out: ${e.message}`,r);const o=kvr(e,r,n),s=t.find(a=>a.match(o));if(!s)return new _t(`${r} error: ${o.message}`,r);const i=typeof s.message=="function"?s.message(o):s.message;return new s.errorClass(i,r)}var YRe,Qo,xi=S({"src/lib/utils/errorClassifier.ts"(){"use strict";yt(),Ua(),ym(),vAe(),_r(),YRe=5,Qo=[{match:e=>e.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized|invalid_api_key/i.test(e.message),errorClass:sr,message:e=>`Invalid ${e.provider} API key. Please check your credentials.`},{match:e=>e.statusCode===429||/rate limit/i.test(e.message),errorClass:Xs,message:e=>`${e.provider} rate limit exceeded. Please try again later.`},{match:e=>e.statusCode===404||/model_not_found|model not found/i.test(e.message),errorClass:co,message:e=>e.modelName?`${e.provider} model '${e.modelName}' not found.`:`${e.provider} model not found.`},{match:e=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network|connection/i.test(e.message)||e.errorCode!==void 0&&_q.has(e.errorCode),errorClass:jo,message:e=>`Connection error: ${e.message}`},{match:e=>e.statusCode!==void 0&&e.statusCode>=500&&e.statusCode<=599||/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(e.message),errorClass:_t,message:e=>`${e.provider} server error: ${e.message}`}]}});function xvr(e){return`https://api.cloudflare.com/client/v4/accounts/${e}/ai/v1`}var ZRe,Avr=S({"src/lib/providers/openaiCompatCatalog.ts"(){"use strict";yt(),xi(),Yo(),ZRe=[{providerName:"cerebras",aliases:["cerebras"],apiKeyEnvVar:"CEREBRAS_API_KEY",baseURLEnvVar:"CEREBRAS_BASE_URL",defaultBaseURL:"https://api.cerebras.ai/v1",configOptions:Ccr(),modelEnvVar:"CEREBRAS_MODEL",defaultModel:"gpt-oss-120b",registryDefaultModel:"gpt-oss-120b",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"gemma-4-31b",fallbackModels:["gpt-oss-120b","gemma-4-31b"],errorRules:[{match:e=>e.statusCode===401||/wrong_api_key|Wrong API Key|invalid_api_key/i.test(e.message),errorClass:sr,message:"Invalid Cerebras API key. Check CEREBRAS_API_KEY. Get one at https://cloud.cerebras.ai"},...Qo]},{providerName:"groq",aliases:["groq"],apiKeyEnvVar:"GROQ_API_KEY",baseURLEnvVar:"GROQ_BASE_URL",defaultBaseURL:"https://api.groq.com/openai/v1",configOptions:kcr(),modelEnvVar:"GROQ_MODEL",defaultModel:"llama-3.3-70b-versatile",registryDefaultModel:"llama-3.3-70b-versatile",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"llama-3.1-8b-instant",fallbackModels:["llama-3.3-70b-versatile","llama-3.1-8b-instant","gemma2-9b-it","mixtral-8x7b-32768","llama-3.2-90b-vision-preview","llama-3.2-11b-vision-preview"],timeoutErrorClass:_t,errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication|invalid_api_key/i.test(e.message),errorClass:sr,message:"Invalid Groq API key. Check GROQ_API_KEY. Get one at https://console.groq.com/keys"},{match:e=>/model_decommissioned/i.test(e.message),errorClass:co,message:e=>`Groq model '${e.modelName}' was decommissioned. Pick a current model from https://console.groq.com/docs/models.`},...Qo]},{providerName:"xai",aliases:["xai","grok"],apiKeyEnvVar:"XAI_API_KEY",baseURLEnvVar:"XAI_BASE_URL",defaultBaseURL:"https://api.x.ai/v1",configOptions:Scr(),modelEnvVar:"XAI_MODEL",defaultModel:"grok-3",registryDefaultModel:"grok-3",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"grok-3-mini",fallbackModels:["grok-3","grok-3-mini","grok-2-latest","grok-2-vision-latest","grok-beta"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication|invalid_api_key/i.test(e.message),errorClass:sr,message:"Invalid xAI API key. Please check your XAI_API_KEY environment variable. Get one at https://console.x.ai/"},{match:e=>/insufficient_quota|quota exceeded/i.test(e.message),errorClass:_t,message:"xAI account has insufficient quota. Top up at https://console.x.ai/"},...Qo]},{providerName:"together-ai",aliases:["together-ai","together"],apiKeyEnvVar:"TOGETHER_API_KEY",baseURLEnvVar:"TOGETHER_BASE_URL",defaultBaseURL:"https://api.together.xyz/v1",configOptions:Icr(),modelEnvVar:"TOGETHER_MODEL",defaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo",registryDefaultModel:"meta-llama/Llama-3.3-70B-Instruct-Turbo",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",fallbackModels:["meta-llama/Llama-3.3-70B-Instruct-Turbo","meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo","meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo","meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo","mistralai/Mixtral-8x22B-Instruct-v0.1","Qwen/Qwen2.5-72B-Instruct-Turbo","deepseek-ai/DeepSeek-R1","deepseek-ai/DeepSeek-V3"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Together AI API key. Get one at https://api.together.xyz/settings/api-keys"},...Qo]},{providerName:"fireworks",aliases:["fireworks"],apiKeyEnvVar:"FIREWORKS_API_KEY",baseURLEnvVar:"FIREWORKS_BASE_URL",defaultBaseURL:"https://api.fireworks.ai/inference/v1",configOptions:Rcr(),modelEnvVar:"FIREWORKS_MODEL",defaultModel:"accounts/fireworks/models/deepseek-v4-pro",registryDefaultModel:"accounts/fireworks/models/deepseek-v4-pro",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"accounts/fireworks/models/deepseek-v4-pro",fallbackModels:["accounts/fireworks/models/deepseek-v4-pro","accounts/fireworks/models/glm-5p1","accounts/fireworks/models/glm-5","accounts/fireworks/models/kimi-k2p6","accounts/fireworks/models/kimi-k2p5","accounts/fireworks/models/gpt-oss-120b"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Fireworks API key. Get one at https://fireworks.ai/account/api-keys"},...Qo]},{providerName:"perplexity",aliases:["perplexity","pplx"],apiKeyEnvVar:"PERPLEXITY_API_KEY",baseURLEnvVar:"PERPLEXITY_BASE_URL",defaultBaseURL:"https://api.perplexity.ai",configOptions:Pcr(),modelEnvVar:"PERPLEXITY_MODEL",defaultModel:"sonar",registryDefaultModel:"sonar",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"gpt-3.5-turbo",fallbackModels:["sonar","sonar-pro","sonar-reasoning","sonar-reasoning-pro","sonar-deep-research"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Perplexity API key. Get one at https://www.perplexity.ai/settings/api"},...Qo]},{providerName:"mistral",aliases:["mistral"],apiKeyEnvVar:"MISTRAL_API_KEY",baseURLEnvVar:"MISTRAL_BASE_URL",defaultBaseURL:"https://api.mistral.ai/v1",configOptions:_cr(),modelEnvVar:"MISTRAL_MODEL",defaultModel:"mistral-small-2506",registryDefaultModel:"mistral-large-latest",registryDefaultModelChecksEnvVar:!1,fallbackModelName:"mistral-small-2506",fallbackModels:["mistral-small-2506","mistral-large-latest"],errorRules:[{match:e=>e.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized/i.test(e.message),errorClass:sr,message:"Invalid Mistral API key. Please check your MISTRAL_API_KEY environment variable."},...Qo]},{providerName:"cloudflare",aliases:["cloudflare","workers-ai","cf-ai"],apiKeyEnvVar:"CLOUDFLARE_API_KEY",computedBaseURL:{envVar:"CLOUDFLARE_ACCOUNT_ID",missingValueMessage:"CLOUDFLARE_ACCOUNT_ID is required (or pass credentials.cloudflare.accountId). Get the account id from https://dash.cloudflare.com/",build:xvr},configOptions:Lcr(),modelEnvVar:"CLOUDFLARE_MODEL",defaultModel:"@cf/meta/llama-3.3-70b-instruct-fp8-fast",registryDefaultModel:"@cf/meta/llama-3.3-70b-instruct-fp8-fast",registryDefaultModelChecksEnvVar:!0,fallbackModelName:"@cf/meta/llama-3.1-8b-instruct-fast",fallbackModels:["@cf/meta/llama-3.3-70b-instruct-fp8-fast","@cf/meta/llama-3.1-70b-instruct","@cf/meta/llama-3.1-8b-instruct-fast","@cf/meta/llama-3.2-11b-vision-instruct","@cf/mistral/mistral-7b-instruct-v0.2","@cf/qwen/qwen1.5-14b-chat-awq"],errorRules:[{match:e=>e.statusCode===401||/Invalid API key|Authentication/i.test(e.message),errorClass:sr,message:"Invalid Cloudflare API key. Use a token with Workers AI Read+Write scope. Get one at https://dash.cloudflare.com/profile/api-tokens"},...Qo]}]}});function Ov(e){const t=[];for(const r of zd)r.kind===e&&(t.push(r.name),r.aliases&&t.push(...r.aliases));return t}function Ivr(e){const t=zd.find(r=>r.kind===e);if(!t)throw new Error(`No media handler catalog entries registered for kind "${e}"`);return t.name}var zd,Nv=S({"src/lib/factories/mediaHandlerCatalog.ts"(){"use strict";zd=[{kind:"tts",name:"google-ai",aliases:["vertex"]},{kind:"tts",name:"openai-tts"},{kind:"tts",name:"elevenlabs",aliases:["elevenlabs-tts"]},{kind:"tts",name:"azure-tts"},{kind:"tts",name:"fish-audio"},{kind:"tts",name:"cartesia"},{kind:"stt",name:"whisper",aliases:["openai-stt"]},{kind:"stt",name:"deepgram"},{kind:"stt",name:"google-stt"},{kind:"stt",name:"azure-stt"},{kind:"realtime",name:"openai-realtime"},{kind:"realtime",name:"gemini-live"},{kind:"video",name:"vertex"},{kind:"video",name:"kling"},{kind:"video",name:"runway"},{kind:"video",name:"replicate"},{kind:"avatar",name:"d-id"},{kind:"avatar",name:"replicate",aliases:["musetalk"]},{kind:"avatar",name:"heygen"},{kind:"music",name:"beatoven"},{kind:"music",name:"replicate",aliases:["musicgen"]},{kind:"music",name:"elevenlabs-music",aliases:["elevenlabs-sound"]},{kind:"music",name:"lyria"}]}}),XRe={};he(XRe,{AsyncLocalStorage:()=>_1e,Buffer:()=>cMe,Channel:()=>XPe,DatabaseSync:()=>lMe,Duplex:()=>b1e,EventEmitter:()=>v1e,Http2ServerRequest:()=>hMe,Http2ServerResponse:()=>fMe,Interface:()=>aMe,MIMEType:()=>bMe,PassThrough:()=>T1e,PerformanceObserver:()=>JPe,Readable:()=>xq,ReadableStream:()=>E1e,Resolver:()=>WPe,TextDecoder:()=>Mq,TextEncoder:()=>VT,Transform:()=>w1e,URL:()=>OPe,URLSearchParams:()=>NPe,Worker:()=>rMe,Writable:()=>Aq,access:()=>Z1e,appendFile:()=>R1e,appendFileSync:()=>s1e,arch:()=>mPe,arrayBuffer:()=>gMe,basename:()=>d1e,builtinModules:()=>RPe,callbackify:()=>jPe,channel:()=>ZPe,chmodSync:()=>I1e,clearInterval:()=>wMe,clearTimeout:()=>vMe,closeSync:()=>O1e,connect:()=>yPe,constants:()=>uMe,copyFileSync:()=>M1e,cpSync:()=>i1e,cpus:()=>cPe,createConnection:()=>vPe,createGunzip:()=>CPe,createGzip:()=>kPe,createHash:()=>kq,createHmac:()=>t1e,createInterface:()=>iMe,createReadStream:()=>G1e,createRequire:()=>IPe,createServer:()=>a1e,createWriteStream:()=>q1e,debug:()=>BPe,debuglog:()=>Pq,default:()=>QRe,deflateSync:()=>wPe,deprecate:()=>zPe,deserialize:()=>tMe,dirname:()=>u1e,exec:()=>rPe,execFile:()=>Rq,execFileSync:()=>oPe,execSync:()=>nPe,existsSync:()=>k1e,extname:()=>p1e,fileURLToPath:()=>LPe,finished:()=>C1e,format:()=>DPe,freemem:()=>uPe,fstatSync:()=>N1e,get:()=>gPe,gunzip:()=>SPe,gunzipSync:()=>bPe,gzip:()=>EPe,gzipSync:()=>TPe,hasSubscribers:()=>QPe,homedir:()=>iPe,hostname:()=>lPe,inflateSync:()=>_Pe,inherits:()=>FPe,inspect:()=>HT,isAbsolute:()=>h1e,isBuiltin:()=>PPe,isDeepStrictEqual:()=>qPe,isIP:()=>mMe,isIPv4:()=>pMe,isIPv6:()=>dMe,isMainThread:()=>nMe,join:()=>l1e,lookup:()=>VPe,mkdir:()=>W1e,mkdirSync:()=>L1e,monitorEventLoopDelay:()=>YPe,normalize:()=>y1e,ok:()=>xPe,open:()=>ePe,openSync:()=>D1e,parentPort:()=>oMe,parse:()=>MPe,pathToFileURL:()=>$Pe,performance:()=>KPe,pipeline:()=>S1e,platform:()=>sPe,posix:()=>g1e,promises:()=>e1e,promisify:()=>UPe,randomBytes:()=>r1e,randomUUID:()=>n1e,readFile:()=>H1e,readFileSync:()=>x1e,readdir:()=>J1e,readdirSync:()=>F1e,realpath:()=>tPe,realpathSync:()=>P1e,relative:()=>m1e,release:()=>hPe,rename:()=>X1e,renameSync:()=>B1e,request:()=>fPe,resolve:()=>c1e,rm:()=>Q1e,rmSync:()=>j1e,rmdirSync:()=>z1e,sep:()=>f1e,serialize:()=>eMe,setInterval:()=>_Me,setTimeout:()=>yMe,spawn:()=>Iq,stat:()=>K1e,statSync:()=>$1e,strict:()=>APe,tmpdir:()=>aPe,toUSVString:()=>GPe,totalmem:()=>dPe,type:()=>pPe,types:()=>HPe,unlink:()=>Y1e,unlinkSync:()=>U1e,webcrypto:()=>o1e,workerData:()=>sMe,writeFile:()=>V1e,writeFileSync:()=>A1e});var go,Rn,QRe,e1e,kq,t1e,r1e,n1e,o1e,s1e,i1e,a1e,l1e,c1e,u1e,d1e,p1e,m1e,h1e,f1e,g1e,y1e,v1e,_1e,xq,Aq,w1e,b1e,T1e,E1e,S1e,C1e,k1e,x1e,A1e,I1e,R1e,P1e,M1e,D1e,O1e,N1e,L1e,$1e,F1e,U1e,B1e,z1e,j1e,q1e,G1e,H1e,V1e,W1e,K1e,J1e,Y1e,Z1e,X1e,Q1e,ePe,tPe,Iq,rPe,nPe,Rq,oPe,sPe,iPe,aPe,lPe,cPe,uPe,dPe,pPe,mPe,hPe,fPe,gPe,yPe,vPe,_Pe,wPe,bPe,TPe,EPe,SPe,CPe,kPe,xPe,APe,IPe,RPe,PPe,MPe,DPe,OPe,NPe,LPe,$Pe,FPe,UPe,Pq,BPe,HT,zPe,jPe,qPe,GPe,HPe,Mq,VT,VPe,WPe,KPe,JPe,YPe,ZPe,XPe,QPe,eMe,tMe,rMe,nMe,oMe,sMe,iMe,aMe,lMe,cMe,uMe,dMe,pMe,mMe,hMe,fMe,gMe,Dq,yMe,vMe,_Me,wMe,bMe,Oq=S({"node-stub:child_process"(){go=()=>{},Rn=async()=>{},QRe={},e1e={readFile:Rn,writeFile:Rn,mkdir:Rn,stat:Rn,readdir:Rn,unlink:Rn,access:Rn,rm:Rn,rename:Rn},kq=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new VT().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},t1e=(e,t)=>kq(e),r1e=e=>new Uint8Array(e||32),n1e=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),o1e=globalThis.crypto,s1e=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},i1e=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},a1e=()=>({listen:go,close:go,on:go}),l1e=(...e)=>e.join("/"),c1e=(...e)=>e.join("/"),u1e=e=>e||"",d1e=e=>e?.split?.("/")?.pop?.()||"",p1e=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},m1e=(e,t)=>t||"",h1e=()=>!1,f1e="/",g1e={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},y1e=e=>e,v1e=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},_1e=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},xq=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Aq=class{write(){return!0}end(){}on(){return this}destroy(){}},w1e=class{push(){}on(){return this}},b1e=class{on(){return this}},T1e=class{pipe(){return this}on(){return this}},E1e=globalThis.ReadableStream||class{},S1e=go,C1e=go,k1e=()=>!1,x1e=()=>"",A1e=go,I1e=go,R1e=Rn,P1e=e=>e,M1e=go,D1e=()=>0,O1e=go,N1e=()=>({}),L1e=go,$1e=()=>({}),F1e=()=>[],U1e=go,B1e=go,z1e=go,j1e=go,q1e=()=>new Aq,G1e=()=>new xq,H1e=Rn,V1e=Rn,W1e=Rn,K1e=Rn,J1e=Rn,Y1e=Rn,Z1e=Rn,X1e=Rn,Q1e=Rn,ePe=async()=>({stat:Rn,readFile:Rn,close:Rn,read:Rn,write:Rn}),tPe=async e=>e,Iq=()=>({on:go,stdout:{on:go},stderr:{on:go},kill:go}),rPe=(e,t)=>t?.(null,"",""),nPe=()=>"",Rq=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},oPe=()=>"",sPe="browser",iPe=()=>"/",aPe=()=>"/tmp",lPe=()=>"browser",cPe=()=>[{}],uPe=()=>0,dPe=()=>0,pPe=()=>"Browser",mPe=()=>"wasm",hPe=()=>"0",fPe=()=>({}),gPe=()=>({}),yPe=()=>({}),vPe=()=>({}),_Pe=()=>new Uint8Array,wPe=()=>new Uint8Array,bPe=()=>new Uint8Array,TPe=()=>new Uint8Array,EPe=(e,t)=>t?.(null,e),SPe=(e,t)=>t?.(null,e),CPe=()=>({}),kPe=()=>({}),xPe=go,APe={},IPe=()=>()=>({}),RPe=[],PPe=()=>!1,MPe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),DPe=()=>"",OPe=globalThis.URL,NPe=globalThis.URLSearchParams,LPe=e=>typeof e=="string"?e.replace("file://",""):e,$Pe=e=>new globalThis.URL("file://"+e),FPe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},UPe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),Pq=e=>{const t=(...r)=>{};return t.enabled=!1,t},BPe=Pq,HT=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},HT.custom=Symbol.for("nodejs.util.inspect.custom"),HT.colors={},HT.styles={},zPe=e=>e,jPe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},qPe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),GPe=e=>String(e),HPe={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},Mq=globalThis.TextDecoder,VT=globalThis.TextEncoder,VPe=(e,t)=>t?.(null,"127.0.0.1",4),WPe=class{},KPe=globalThis.performance||{now:()=>Date.now()},JPe=class{observe(){}disconnect(){}},YPe=()=>({enable:go,disable:go,percentile:()=>0}),ZPe=()=>({}),XPe=class{},QPe=()=>!1,eMe=()=>new Uint8Array,tMe=go,rMe=class{},nMe=!0,oMe=null,sMe=null,iMe=()=>({}),aMe=class{},lMe=class{},cMe=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new VT().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new VT().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Mq().decode(this)}},uMe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},dMe=()=>!1,pMe=()=>!1,mMe=()=>0,hMe=class{},fMe=class{},gMe=async()=>new ArrayBuffer(0),Dq=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),yMe=(...e)=>Dq(globalThis.setTimeout(...e)),vMe=globalThis.clearTimeout,_Me=(...e)=>Dq(globalThis.setInterval(...e)),wMe=globalThis.clearInterval,bMe=class{constructor(e){this.type=e}toString(){return this.type}}}}),lf,Ns,TMe,Rvr,Pvr,Mvr,Dvr,Ovr,Nvr,Lvr,$vr,Fvr,Uvr,Bvr,zvr,jvr,qvr,Gvr,Hvr,Vvr,Wvr,Kvr,Jvr,Yvr,Zvr,Xvr,Qvr,e0r,t0r,r0r,n0r,o0r,s0r,i0r,a0r,l0r,c0r,u0r,d0r,p0r,m0r,h0r,f0r,g0r,y0r,v0r,_0r,w0r,b0r,T0r=S({"npm-stub:csv-parser"(){lf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:lf.get}):new Proxy(function(...r){return new Proxy({},{get:lf.get})},{get:lf.get,apply(r,n,o){return new Proxy({},{get:lf.get})},construct(r,n){return new Proxy({},{get:lf.get})}})}},Ns=new Proxy({},lf),TMe=Ns,{BedrockClient:Rvr,ListFoundationModelsCommand:Pvr,BedrockRuntimeClient:Mvr,ConverseCommand:Dvr,ConverseStreamCommand:Ovr,ImageFormat:Nvr,InvokeModelCommand:Lvr}=Ns,{SageMakerRuntimeClient:$vr,InvokeEndpointCommand:Fvr,InvokeEndpointWithResponseStreamCommand:Uvr}=Ns,{GoogleAuth:Bvr,VertexAI:zvr,TextToSpeechClient:jvr}=Ns,{Webhook:qvr}=Ns,{Hippocampus:Gvr,HippocampusConfig:Hvr}=Ns,{createClient:Vvr}=Ns,{Queue:Wvr,Worker:Kvr,Job:Jvr,QueueScheduler:Yvr,FlowProducer:Zvr}=Ns,{Cron:Xvr}=Ns,{parseBuffer:Qvr,selectCover:e0r}=Ns,{extractRawText:t0r,convertToHtml:r0r}=Ns,{Hono:n0r}=Ns,{cors:o0r,HTTPException:s0r,logger:i0r,secureHeaders:a0r,streamSSE:l0r,timeout:c0r}=Ns,u0r=globalThis.fetch,d0r=globalThis.Request,p0r=globalThis.Response,m0r=globalThis.Headers,h0r=globalThis.FormData,f0r=globalThis.File,g0r=globalThis.Blob,y0r=Ns.Agent,v0r=Ns.Pool,_0r=Ns.Client,w0r=Ns.Dispatcher,b0r=Ns.MockAgent}}),cf,Ls,zu,E0r,S0r,C0r,k0r,x0r,A0r,I0r,R0r,P0r,M0r,D0r,O0r,N0r,L0r,$0r,F0r,U0r,B0r,z0r,j0r,q0r,G0r,H0r,V0r,W0r,K0r,J0r,Y0r,Z0r,X0r,Q0r,e_r,t_r,r_r,n_r,o_r,s_r,i_r,a_r,l_r,c_r,u_r,d_r,p_r,m_r,h_r,EMe=S({"npm-stub:iconv-lite"(){cf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:cf.get}):new Proxy(function(...r){return new Proxy({},{get:cf.get})},{get:cf.get,apply(r,n,o){return new Proxy({},{get:cf.get})},construct(r,n){return new Proxy({},{get:cf.get})}})}},Ls=new Proxy({},cf),zu=Ls,{BedrockClient:E0r,ListFoundationModelsCommand:S0r,BedrockRuntimeClient:C0r,ConverseCommand:k0r,ConverseStreamCommand:x0r,ImageFormat:A0r,InvokeModelCommand:I0r}=Ls,{SageMakerRuntimeClient:R0r,InvokeEndpointCommand:P0r,InvokeEndpointWithResponseStreamCommand:M0r}=Ls,{GoogleAuth:D0r,VertexAI:O0r,TextToSpeechClient:N0r}=Ls,{Webhook:L0r}=Ls,{Hippocampus:$0r,HippocampusConfig:F0r}=Ls,{createClient:U0r}=Ls,{Queue:B0r,Worker:z0r,Job:j0r,QueueScheduler:q0r,FlowProducer:G0r}=Ls,{Cron:H0r}=Ls,{parseBuffer:V0r,selectCover:W0r}=Ls,{extractRawText:K0r,convertToHtml:J0r}=Ls,{Hono:Y0r}=Ls,{cors:Z0r,HTTPException:X0r,logger:Q0r,secureHeaders:e_r,streamSSE:t_r,timeout:r_r}=Ls,n_r=globalThis.fetch,o_r=globalThis.Request,s_r=globalThis.Response,i_r=globalThis.Headers,a_r=globalThis.FormData,l_r=globalThis.File,c_r=globalThis.Blob,u_r=Ls.Agent,d_r=Ls.Pool,p_r=Ls.Client,m_r=Ls.Dispatcher,h_r=Ls.MockAgent}}),Lv={};he(Lv,{AsyncLocalStorage:()=>GMe,Buffer:()=>L4e,Channel:()=>C4e,DatabaseSync:()=>N4e,Duplex:()=>VMe,EventEmitter:()=>qMe,Http2ServerRequest:()=>z4e,Http2ServerResponse:()=>j4e,Interface:()=>O4e,MIMEType:()=>K4e,PassThrough:()=>WMe,PerformanceObserver:()=>T4e,Readable:()=>_m,ReadableStream:()=>KMe,Resolver:()=>w4e,TextDecoder:()=>Fq,TextEncoder:()=>KT,Transform:()=>HMe,URL:()=>a4e,URLSearchParams:()=>l4e,Worker:()=>I4e,Writable:()=>Lq,access:()=>TDe,appendFile:()=>tDe,appendFileSync:()=>RMe,arch:()=>BDe,arrayBuffer:()=>q4e,basename:()=>LMe,builtinModules:()=>n4e,callbackify:()=>f4e,channel:()=>S4e,chmodSync:()=>eDe,clearInterval:()=>W4e,clearTimeout:()=>H4e,closeSync:()=>sDe,connect:()=>GDe,constants:()=>$4e,copyFileSync:()=>nDe,cpSync:()=>PMe,cpus:()=>LDe,createConnection:()=>HDe,createGunzip:()=>XDe,createGzip:()=>QDe,createHash:()=>Nq,createHmac:()=>kMe,createInterface:()=>D4e,createReadStream:()=>fDe,createRequire:()=>r4e,createServer:()=>MMe,createWriteStream:()=>hDe,debug:()=>m4e,debuglog:()=>$q,default:()=>SMe,deflateSync:()=>WDe,deprecate:()=>h4e,deserialize:()=>A4e,dirname:()=>NMe,exec:()=>ADe,execFile:()=>RDe,execFileSync:()=>PDe,execSync:()=>IDe,existsSync:()=>ZMe,extname:()=>$Me,fileURLToPath:()=>c4e,finished:()=>YMe,format:()=>i4e,freemem:()=>$De,fstatSync:()=>iDe,get:()=>qDe,gunzip:()=>ZDe,gunzipSync:()=>KDe,gzip:()=>YDe,gzipSync:()=>JDe,hasSubscribers:()=>k4e,homedir:()=>DDe,hostname:()=>NDe,inflateSync:()=>VDe,inherits:()=>d4e,inspect:()=>WT,isAbsolute:()=>UMe,isBuiltin:()=>o4e,isDeepStrictEqual:()=>g4e,isIP:()=>B4e,isIPv4:()=>U4e,isIPv6:()=>F4e,isMainThread:()=>R4e,join:()=>DMe,lookup:()=>_4e,mkdir:()=>vDe,mkdirSync:()=>aDe,monitorEventLoopDelay:()=>E4e,normalize:()=>jMe,ok:()=>e4e,open:()=>CDe,openSync:()=>oDe,parentPort:()=>P4e,parse:()=>s4e,pathToFileURL:()=>u4e,performance:()=>b4e,pipeline:()=>JMe,platform:()=>MDe,posix:()=>zMe,promises:()=>CMe,promisify:()=>p4e,randomBytes:()=>xMe,randomUUID:()=>AMe,readFile:()=>gDe,readFileSync:()=>XMe,readdir:()=>wDe,readdirSync:()=>cDe,realpath:()=>kDe,realpathSync:()=>rDe,relative:()=>FMe,release:()=>zDe,rename:()=>EDe,renameSync:()=>dDe,request:()=>jDe,resolve:()=>OMe,rm:()=>SDe,rmSync:()=>mDe,rmdirSync:()=>pDe,sep:()=>BMe,serialize:()=>x4e,setInterval:()=>V4e,setTimeout:()=>G4e,spawn:()=>xDe,stat:()=>_De,statSync:()=>lDe,strict:()=>t4e,tmpdir:()=>ODe,toUSVString:()=>y4e,totalmem:()=>FDe,type:()=>UDe,types:()=>v4e,unlink:()=>bDe,unlinkSync:()=>uDe,webcrypto:()=>IMe,workerData:()=>M4e,writeFile:()=>yDe,writeFileSync:()=>QMe});var yo,Pn,SMe,CMe,Nq,kMe,xMe,AMe,IMe,RMe,PMe,MMe,DMe,OMe,NMe,LMe,$Me,FMe,UMe,BMe,zMe,jMe,qMe,GMe,_m,Lq,HMe,VMe,WMe,KMe,JMe,YMe,ZMe,XMe,QMe,eDe,tDe,rDe,nDe,oDe,sDe,iDe,aDe,lDe,cDe,uDe,dDe,pDe,mDe,hDe,fDe,gDe,yDe,vDe,_De,wDe,bDe,TDe,EDe,SDe,CDe,kDe,xDe,ADe,IDe,RDe,PDe,MDe,DDe,ODe,NDe,LDe,$De,FDe,UDe,BDe,zDe,jDe,qDe,GDe,HDe,VDe,WDe,KDe,JDe,YDe,ZDe,XDe,QDe,e4e,t4e,r4e,n4e,o4e,s4e,i4e,a4e,l4e,c4e,u4e,d4e,p4e,$q,m4e,WT,h4e,f4e,g4e,y4e,v4e,Fq,KT,_4e,w4e,b4e,T4e,E4e,S4e,C4e,k4e,x4e,A4e,I4e,R4e,P4e,M4e,D4e,O4e,N4e,L4e,$4e,F4e,U4e,B4e,z4e,j4e,q4e,Uq,G4e,H4e,V4e,W4e,K4e,uf=S({"node-stub:stream"(){yo=()=>{},Pn=async()=>{},SMe={},CMe={readFile:Pn,writeFile:Pn,mkdir:Pn,stat:Pn,readdir:Pn,unlink:Pn,access:Pn,rm:Pn,rename:Pn},Nq=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new KT().encode(r):r),this},digest(r){let n=0;for(const s of t)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;const o=(n>>>0).toString(16).padStart(8,"0");return r==="hex"?o:r==="base64"?btoa(o):o}}},kMe=(e,t)=>Nq(e),xMe=e=>new Uint8Array(e||32),AMe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),IMe=globalThis.crypto,RMe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},PMe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},MMe=()=>({listen:yo,close:yo,on:yo}),DMe=(...e)=>e.join("/"),OMe=(...e)=>e.join("/"),NMe=e=>e||"",LMe=e=>e?.split?.("/")?.pop?.()||"",$Me=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},FMe=(e,t)=>t||"",UMe=()=>!1,BMe="/",zMe={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},jMe=e=>e,qMe=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},GMe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},_m=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Lq=class{write(){return!0}end(){}on(){return this}destroy(){}},HMe=class{push(){}on(){return this}},VMe=class{on(){return this}},WMe=class{pipe(){return this}on(){return this}},KMe=globalThis.ReadableStream||class{},JMe=yo,YMe=yo,ZMe=()=>!1,XMe=()=>"",QMe=yo,eDe=yo,tDe=Pn,rDe=e=>e,nDe=yo,oDe=()=>0,sDe=yo,iDe=()=>({}),aDe=yo,lDe=()=>({}),cDe=()=>[],uDe=yo,dDe=yo,pDe=yo,mDe=yo,hDe=()=>new Lq,fDe=()=>new _m,gDe=Pn,yDe=Pn,vDe=Pn,_De=Pn,wDe=Pn,bDe=Pn,TDe=Pn,EDe=Pn,SDe=Pn,CDe=async()=>({stat:Pn,readFile:Pn,close:Pn,read:Pn,write:Pn}),kDe=async e=>e,xDe=()=>({on:yo,stdout:{on:yo},stderr:{on:yo},kill:yo}),ADe=(e,t)=>t?.(null,"",""),IDe=()=>"",RDe=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},PDe=()=>"",MDe="browser",DDe=()=>"/",ODe=()=>"/tmp",NDe=()=>"browser",LDe=()=>[{}],$De=()=>0,FDe=()=>0,UDe=()=>"Browser",BDe=()=>"wasm",zDe=()=>"0",jDe=()=>({}),qDe=()=>({}),GDe=()=>({}),HDe=()=>({}),VDe=()=>new Uint8Array,WDe=()=>new Uint8Array,KDe=()=>new Uint8Array,JDe=()=>new Uint8Array,YDe=(e,t)=>t?.(null,e),ZDe=(e,t)=>t?.(null,e),XDe=()=>({}),QDe=()=>({}),e4e=yo,t4e={},r4e=()=>()=>({}),n4e=[],o4e=()=>!1,s4e=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),i4e=()=>"",a4e=globalThis.URL,l4e=globalThis.URLSearchParams,c4e=e=>typeof e=="string"?e.replace("file://",""):e,u4e=e=>new globalThis.URL("file://"+e),d4e=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},p4e=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),$q=e=>{const t=(...r)=>{};return t.enabled=!1,t},m4e=$q,WT=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},WT.custom=Symbol.for("nodejs.util.inspect.custom"),WT.colors={},WT.styles={},h4e=e=>e,f4e=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},g4e=(e,t)=>JSON.stringify(e)===JSON.stringify(t),y4e=e=>String(e),v4e={isPromise:e=>e instanceof Promise,isDate:e=>e instanceof Date,isRegExp:e=>e instanceof RegExp,isNativeError:e=>e instanceof Error,isArrayBuffer:e=>e instanceof ArrayBuffer,isTypedArray:e=>ArrayBuffer.isView(e),isUint8Array:e=>e instanceof Uint8Array,isProxy:()=>!1},Fq=globalThis.TextDecoder,KT=globalThis.TextEncoder,_4e=(e,t)=>t?.(null,"127.0.0.1",4),w4e=class{},b4e=globalThis.performance||{now:()=>Date.now()},T4e=class{observe(){}disconnect(){}},E4e=()=>({enable:yo,disable:yo,percentile:()=>0}),S4e=()=>({}),C4e=class{},k4e=()=>!1,x4e=()=>new Uint8Array,A4e=yo,I4e=class{},R4e=!0,P4e=null,M4e=null,D4e=()=>({}),O4e=class{},N4e=class{},L4e=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new KT().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new KT().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new Fq().decode(this)}},$4e={F_OK:0,R_OK:4,W_OK:2,X_OK:1},F4e=()=>!1,U4e=()=>!1,B4e=()=>0,z4e=class{},j4e=class{},q4e=async()=>new ArrayBuffer(0),Uq=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),G4e=(...e)=>Uq(globalThis.setTimeout(...e)),H4e=globalThis.clearTimeout,V4e=(...e)=>Uq(globalThis.setInterval(...e)),W4e=globalThis.clearInterval,K4e=class{constructor(e){this.type=e}toString(){return this.type}}}});function df(e,t=","){const r=[];let n="",o=!1;for(let s=0;s<e.length;s++){const i=e[s];if(i==='"'){if(o&&e[s+1]==='"'){n+='"',s++;continue}o=!o}else i===t&&!o?(r.push(n),n=""):n+=i}return r.push(n),r}function f_r(e,t=","){return df(e,t).length}function q1(e,t){const r=e.filter(a=>a.trim()!=="").slice(0,5);if(r.length===0)return",";const n=t?.toLowerCase().replace(/^\./,""),o=n==="tsv"?" ":n==="psv"?"|":void 0;let s=",",i=-1;for(const a of Bq){const l=r.map(m=>f_r(m,a)),c=l[0];if(c<=1)continue;const u=l.every(m=>m===c),d=(a===o?1e3:0)+(u?100:0)+c+(a===","?.5:0);d>i&&(i=d,s=a)}return i<0&&o?o:s}var Bq,J4e=S({"src/lib/utils/csvUtils.ts"(){"use strict";Bq=[","," ",";","|"]}});function G1(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ar(e){return typeof e=="object"&&e!==null}function g_r(e){return e==null}var pf=S({"src/lib/utils/typeUtils.ts"(){"use strict"}}),mf,$s,Y4e,y_r,v_r,__r,w_r,b_r,T_r,E_r,S_r,C_r,k_r,x_r,A_r,I_r,R_r,P_r,M_r,D_r,O_r,N_r,L_r,$_r,F_r,U_r,B_r,z_r,j_r,q_r,G_r,H_r,V_r,W_r,K_r,J_r,Y_r,Z_r,X_r,Q_r,ewr,twr,rwr,nwr,owr,swr,iwr,awr,lwr,cwr=S({"npm-stub:chardet"(){mf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:mf.get}):new Proxy(function(...r){return new Proxy({},{get:mf.get})},{get:mf.get,apply(r,n,o){return new Proxy({},{get:mf.get})},construct(r,n){return new Proxy({},{get:mf.get})}})}},$s=new Proxy({},mf),Y4e=$s,{BedrockClient:y_r,ListFoundationModelsCommand:v_r,BedrockRuntimeClient:__r,ConverseCommand:w_r,ConverseStreamCommand:b_r,ImageFormat:T_r,InvokeModelCommand:E_r}=$s,{SageMakerRuntimeClient:S_r,InvokeEndpointCommand:C_r,InvokeEndpointWithResponseStreamCommand:k_r}=$s,{GoogleAuth:x_r,VertexAI:A_r,TextToSpeechClient:I_r}=$s,{Webhook:R_r}=$s,{Hippocampus:P_r,HippocampusConfig:M_r}=$s,{createClient:D_r}=$s,{Queue:O_r,Worker:N_r,Job:L_r,QueueScheduler:$_r,FlowProducer:F_r}=$s,{Cron:U_r}=$s,{parseBuffer:B_r,selectCover:z_r}=$s,{extractRawText:j_r,convertToHtml:q_r}=$s,{Hono:G_r}=$s,{cors:H_r,HTTPException:V_r,logger:W_r,secureHeaders:K_r,streamSSE:J_r,timeout:Y_r}=$s,Z_r=globalThis.fetch,X_r=globalThis.Request,Q_r=globalThis.Response,ewr=globalThis.Headers,twr=globalThis.FormData,rwr=globalThis.File,nwr=globalThis.Blob,owr=$s.Agent,swr=$s.Pool,iwr=$s.Client,awr=$s.Dispatcher,lwr=$s.MockAgent}});function JT(e){return e.charCodeAt(0)===65279?e.slice(1):e}function uwr(e){return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?"utf-8":e.length>=2&&e[0]===255&&e[1]===254?"utf-16le":e.length>=2&&e[0]===254&&e[1]===255?"utf-16be":null}function dwr(e){if(!e)return null;const t=e.toLowerCase().replace(/[^a-z0-9]/g,""),n={utf8:"utf-8",utf16le:"utf-16le",utf16be:"utf-16be",ascii:"utf-8",windows1252:"windows-1252",iso88591:"latin1",latin1:"latin1",iso88592:"iso-8859-2",windows1251:"windows-1251",koi8r:"koi8-r",gb18030:"gb18030",big5:"big5",shiftjis:"shift_jis",euckr:"euc-kr",eucjp:"euc-jp"}[t]??e;return zu.encodingExists(n)?n:null}function zq(e,t,r=!0){if(t&&zu.encodingExists(t))return{text:JT(zu.decode(e,t)),encoding:t,confidence:100};t&&!zu.encodingExists(t)&&f.warn(`[textEncoding] Unsupported encoding override "${t}"; falling back to detection.`);const n=uwr(e);if(n)return{text:JT(zu.decode(e,n)),encoding:n,confidence:100};let o=!0;for(let a=0;a<e.length;a++)if(e[a]>=128){o=!1;break}if(o)return{text:JT(zu.decode(e,"utf-8")),encoding:"utf-8",confidence:r?100:60};let s=null;try{s=Y4e.detect(e)}catch(a){f.debug(`[textEncoding] chardet failed: ${String(a)}`)}const i=dwr(s);return i?{text:JT(zu.decode(e,i)),encoding:i,confidence:i==="utf-8"?100:80}:{text:JT(zu.decode(e,"utf-8")),encoding:"utf-8",confidence:0}}var pwr=S({"src/lib/utils/textEncoding.ts"(){"use strict";cwr(),EMe(),q()}});async function zt(e,t,r){let n;const o=new Promise((s,i)=>{n=setTimeout(()=>{i(new wm(r||`Operation timed out after ${t}ms`,t))},t)});try{return await Promise.race([e,o])}finally{n!==void 0&&clearTimeout(n)}}async function Z4e(e,t){if(!t||typeof t.addEventListener!="function")return e;const r=()=>{const n=new Error("Operation aborted");return n.name="AbortError",n};return t.aborted?(e.catch(()=>{}),Promise.reject(r())):new Promise((n,o)=>{const s=()=>{e.catch(()=>{}),o(r())};t.addEventListener("abort",s,{once:!0}),e.then(i=>{t.removeEventListener("abort",s),n(i)},i=>{t.removeEventListener("abort",s),o(i)})})}async function H1(e,t,r){return zt(e(),t,r)}var wm,yn=S({"src/lib/utils/async/withTimeout.ts"(){"use strict";wm=class Mlr extends Error{constructor(t,r){super(t),this.timeoutMs=r,this.name="TimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,Mlr)}timeoutMs}}});function mwr(e){const t=[];return!e||e.trim()===""?(t.push("Empty or blank column name"),t):(e!==e.trim()&&t.push("Leading or trailing whitespace"),/^\d/.test(e)&&t.push("Starts with a number"),/[^a-zA-Z0-9_\- ]/.test(e)&&t.push("Contains special characters"),e.length>64&&t.push("Name exceeds 64 characters"),/\s{2,}/.test(e)&&t.push("Contains multiple consecutive spaces"),t)}function X4e(e,t="snake_case",r=0){let o=(e??"").trim().split(/[^A-Za-z0-9]+/).filter(i=>i.length>0),s=o.join("_");return s===""?(s=`col_${r+1}`,o=[s]):/^[0-9]/.test(s)&&(s=`col_${s}`,o=s.split("_").filter(i=>i.length>0)),t==="camelCase"?o.map((i,a)=>a===0?i.charAt(0).toLowerCase()+i.slice(1):i.charAt(0).toUpperCase()+i.slice(1)).join(""):o.map(i=>i.toLowerCase()).join("_")}function Q4e(e){const t=new Set;return e.map(r=>{if(!t.has(r))return t.add(r),r;let n=2,o=`${r}_${n}`;for(;t.has(o);)n++,o=`${r}_${n}`;return t.add(o),o})}function eOe(e,t){const r=Q4e(e.map((o,s)=>X4e(o,t,s))),n=e.map((o,s)=>({original:o,sanitized:r[s]})).filter(o=>o.original!==o.sanitized);return{sanitized:r,mapping:n}}function hwr(e){return!G1(e)||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string"||t===void 0)}function fwr(e,t){if(!hwr(e))throw xe.csvRowInvalid(`[CSVProcessor] Invalid CSV row ${t}: expected a string-keyed object with string values, got ${Array.isArray(e)?"array":typeof e}`,t)}function YT(e){return Object.keys(e).length===0?!0:Object.values(e).every(r=>r===""||typeof r=="string"&&r.trim()==="")}function gwr(e,t){if(e.trim()==="")return!0;const r=df(e,t);if(r.length===0)return!0;const n=Object.create(null);for(let o=0;o<r.length;o++)n[`c${o}`]=r[o];return YT(n)}function jq(e){const t=[`[CSVProcessor] CSV ${e.stage==="read"?"file read":"parsing"} failed after ${e.count} row(s)`];return e.location&&t.push(`(${e.location})`),t.push(`: ${e.cause}`),t.push(typeof e.headerCount=="number"?`| headerCount: ${e.headerCount}`:"| headerCount: unknown (failed before headers were parsed)"),typeof e.bytesRead=="number"&&t.push(`| bytesRead: ${e.bytesRead}`),typeof e.lastRowColumnCount=="number"&&t.push(`| lastRow columns: ${e.lastRowColumnCount}`),t.push("| Expected RFC 4180 CSV (comma-separated, double-quote escaped)"),t.join(" ")}function qq(e){if(e===""||e===null||e===void 0)return"empty";const t=e.trim();if(t==="")return"empty";if(uOe.has(t.toLowerCase()))return"boolean";if(lOe.test(t))return"integer";if(cOe.test(t))return"float";if(iOe.test(t))return"email";if(aOe.test(t))return"url";for(const r of Wq)if(r.regex.test(t))return"datetime";for(const r of Vq)if(r.regex.test(t))return"date";return"string"}function ywr(e){const t=e.trim();for(const r of Wq)if(r.regex.test(t))return r.format;for(const r of Vq)if(r.regex.test(t))return r.format}function vwr(e){const t=e.filter(i=>i!=="empty");if(t.length===0)return{type:"empty",confidence:100};const r=new Map;for(const i of t)r.set(i,(r.get(i)||0)+1);let n="string",o=0;for(const[i,a]of r)a>o&&(o=a,n=i);const s=Math.round(o/t.length*100);if(r.has("integer")&&r.has("float")&&r.size===2){const i=(r.get("integer")||0)+(r.get("float")||0);return{type:"number",confidence:Math.round(i/t.length*100)}}return s<70&&r.size>1?{type:"mixed",confidence:s}:{type:n,confidence:s}}function _wr(e,t,r){const n=[],o=new Set,s=[];let i=0,a;for(const v of r){const _=v?.trim()??"";if(_===""){i++,n.push("empty");continue}o.add(_);const b=qq(_);if(n.push(b),b==="integer"||b==="float"){const T=parseFloat(_);isNaN(T)||s.push(T)}(b==="date"||b==="datetime")&&!a&&(a=ywr(_))}const{type:l,confidence:c}=vwr(n),u=Array.from(o).slice(0,5);let d,m,h;s.length>0&&(d=Math.min(...s),m=Math.max(...s),h=Math.round(s.reduce((v,_)=>v+_,0)/s.length*100)/100);const g=mwr(e),y={name:e,index:t,detectedType:l,typeConfidence:c,nullCount:i,uniqueCount:o.size,sampleValues:u};return d!==void 0&&(y.minValue=d),m!==void 0&&(y.maxValue=m),h!==void 0&&(y.avgValue=h),a&&(y.dateFormat=a),g.length>0&&(y.nameIssues=g),y}function wwr(e,t){const r=[];for(const n of e){const o=t>0?n.nullCount/t:0;o>.2&&r.push({column:n.name,type:"high_null_rate",message:`Column has ${Math.round(o*100)}% empty/null values (${n.nullCount} of ${t} rows)`,severity:o>.5?"warning":"info",affectedRows:n.nullCount}),n.nameIssues&&n.nameIssues.length>0&&r.push({column:n.name,type:"invalid_name",message:`Column name issues: ${n.nameIssues.join(", ")}`,severity:n.name.trim()===""?"error":"warning"}),(n.detectedType==="mixed"||n.typeConfidence<70)&&r.push({column:n.name,type:"mixed_types",message:`Column has inconsistent data types (${n.typeConfidence}% confidence for ${n.detectedType})`,severity:"warning"}),t>10&&n.uniqueCount===1&&n.nullCount===0&&r.push({column:n.name,type:"duplicates",message:`All ${t} rows have the same value`,severity:"info",affectedRows:t}),n.detectedType==="empty"&&r.push({column:n.name,type:"empty_values",message:"Column is entirely empty",severity:"warning",affectedRows:t})}return r}function bwr(e,t,r){if(e.length===0||r===0)return 0;let n=100;for(const l of t)switch(l.severity){case"error":n-=15;break;case"warning":n-=8;break;case"info":n-=3;break}const o=e.reduce((l,c)=>l+c.nullCount,0),s=e.length*r,i=s>0?o/s:0;n-=Math.round(i*30);const a=e.reduce((l,c)=>l+c.typeConfidence,0)/e.length;return a<80&&(n-=Math.round((80-a)/2)),Math.max(0,Math.min(100,n))}function tOe(e){const t=Math.max(0,Math.min(100,e));return Math.round((100+t)/2)}function rOe(e){if(e.length===0)return{columnMetadata:[],dataQualityWarnings:[],dataQualityScore:0};const t=Object.keys(e[0]),r=[];for(let s=0;s<t.length;s++){const i=t[s],a=e.map(l=>String(l[i]??""));r.push(_wr(i,s,a))}const n=wwr(r,e.length),o=bwr(r,n,e.length);return{columnMetadata:r,dataQualityWarnings:n,dataQualityScore:o}}function nOe(e,t){if(e.length===0)return!1;let r=0;for(const a of e){const l=a?.trim()??"";if(l==="")continue;qq(l)==="string"&&r++}const n=e.filter(a=>a?.trim()).length;if(n===0)return!1;const o=r/n,i=new Set(e.map(a=>a?.trim().toLowerCase())).size===e.length;if(t&&t.length>0){const a=Object.values(t[0]||{}).map(u=>String(u??""));let l=0;for(const u of a)qq(u?.trim()??"")==="string"&&l++;const c=a.length>0?l/a.length:0;if(o>.7&&c<o-.2)return!0}return o>=.7&&i}function Gq(e){return e.charCodeAt(0)===65279?e.slice(1):e}function oOe(e){let t=0,r=!1;for(let n=0;n<e.length;n++){const o=e[n];if(o==='"'){if(r&&e[n+1]==='"'){n++;continue}r=!r}else o===","&&!r&&t++}return t}function Twr(e){if(!e[0]||e.length<2)return!1;const t=e[0].trim(),r=e[1].trim();if(t.match(/^sep=/i))return!0;if(Ewr(r))return!1;const n=oOe(t),o=oOe(r);return n===0&&o>0?!0:o>0&&n!==o}function Ewr(e){const t=e.trim();return t===""?!0:/^[\s,;\t|]+$/.test(t)&&/[,;\t|]/.test(t)}function ZT(e){if(!Twr(e))return{dataLines:e,hasMetadataLine:!1};const t=e[0]?.trim().match(/^sep=(.)/i)?.[1],r=t&&Bq.includes(t)?t:void 0;return{dataLines:e.slice(1),hasMetadataLine:!0,explicitDelimiter:r}}function $v(e){const t=[];let r="",n=!1;for(let o=0;o<e.length;o++){const s=e[o];if(s==='"'){if(n&&e[o+1]==='"'){r+='""',o++;continue}n=!n,r+=s}else!n&&(s===`
|
|
117
117
|
`||s==="\r")?(s==="\r"&&e[o+1]===`
|
|
118
118
|
`&&o++,t.push(r),r=""):r+=s}return t.push(r),t}var sOe,V1,Hq,Vq,Wq,iOe,aOe,lOe,cOe,uOe,XT,Kq=S({"src/lib/utils/csvProcessor.ts"(){"use strict";T0r(),EMe(),uf(),Lr(),q(),J4e(),pf(),pwr(),ct(),yn(),sOe=10*1024*1024,V1=3e4,Hq=3e5,Vq=[{regex:/^\d{4}-\d{2}-\d{2}$/,format:"YYYY-MM-DD"},{regex:/^\d{2}\/\d{2}\/\d{4}$/,format:"MM/DD/YYYY"},{regex:/^\d{2}-\d{2}-\d{4}$/,format:"DD-MM-YYYY"},{regex:/^\d{2}\.\d{2}\.\d{4}$/,format:"DD.MM.YYYY"},{regex:/^\d{4}\/\d{2}\/\d{2}$/,format:"YYYY/MM/DD"}],Wq=[{regex:/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/,format:"ISO8601"},{regex:/^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}/,format:"MM/DD/YYYY HH:mm"}],iOe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,aOe=/^(https?:\/\/|www\.)[^\s]+$/i,lOe=/^-?\d+$/,cOe=/^-?\d+\.\d+$/,uOe=new Set(["true","false","yes","no","1","0","t","f","y","n"]),XT=class{static async process(e,t){const{maxRows:r=1e3,formatStyle:n="raw",includeHeaders:o=!0,sampleDataFormat:s="json",extension:i=null,encoding:a,sanitizeColumnNames:l=!1,columnNameCase:c="snake_case",parseTimeoutMs:u=V1,skipEmptyLines:d=!0}=t||{},m=Math.max(1,Math.min(1e4,r));f.debug("[CSVProcessor] Starting CSV processing",{contentSize:e.length,formatStyle:n,maxRows:m,includeHeaders:o,skipEmptyLines:d});const{text:h,encoding:g,confidence:y}=zq(e,a),v=$v(h),{dataLines:_,hasMetadataLine:b,explicitDelimiter:T}=ZT(v),k=T??q1(_,i??void 0);if(n==="raw"){b&&f.debug("[CSVProcessor] Detected metadata line, skipping first line");const G=_,K=G[0]??"",Ce=G.slice(1),be=d?Ce.filter(Z=>!gwr(Z,k)):Ce,ge=be.slice(0,m),H=G.length===0?[]:[K,...ge];let se;if(l&&H.length>0){const Z=df(H[0]||"",k),{sanitized:_e,mapping:Re}=eOe(Z,c);H[0]=_e.join(k),se=Re.length>0?Re:void 0}const ye=H.join(`
|
|
119
119
|
`),Q=df(H[0]||"",k),me=ge.length,$e=be.length,Se=me<$e;Se&&f.warn(`[CSVProcessor] CSV data truncated: showing ${me} of ${$e} rows (limit: ${m})`),f.debug(`[CSVProcessor] raw format: ${me} rows (original: ${$e}) \u2192 ${ye.length} chars`,{formatStyle:"raw",originalSize:h.length,limitedSize:ye.length}),f.info("[CSVProcessor] \u2705 Processed CSV file",{formatStyle:"raw",rowCount:me,columnCount:Q.length,truncated:Se});const ne=Math.min(me,500),{rows:Fe,timedOut:ae}=await this.streamParse(_m.from([H.join(`
|
|
@@ -1060,7 +1060,7 @@ ${s}
|
|
|
1060
1060
|
|
|
1061
1061
|
Based on this analysis, provide your response.`;f.debug("[VideoAnalysis] Formatting via Claude",{userTextLength:i.length,analysisLength:s.length});const u=await LT({model:n,system:t.systemPrompt,messages:[{role:"user",content:c}],maxOutputTokens:t.maxTokens||8192,temperature:.3,abortSignal:t.abortSignal,experimental_telemetry:this.telemetryHandler?.getTelemetryConfig(t,"generate")});a=u.text,l=t0(u.totalUsage??u.usage),f.debug("[VideoAnalysis] Claude formatting complete",{formattedLength:a.length,usage:l})}catch(c){f.warn("[VideoAnalysis] Claude formatting failed, using raw Gemini output",{error:c instanceof Error?c.message:String(c)})}return this.enhanceResult({content:a,provider:t.provider??this.providerName,model:this.modelName,usage:l},t,o)}async executeStandardGenerateFlow(t,r,n,o,s){const i=Zr.get(this.providerName)?.timeouts?.generateMs,a=t.timeout??Math.max(i??0,18e4),l=rc(a,this.providerName,"generate"),c=o1(t.abortSignal,l?.controller.signal),u=c?{...t,abortSignal:c}:t;let d;try{d=await this.executeGeneration(n,o,s,u)}finally{l?.cleanup()}this.analyzeAIResponse(d),this.logGenerationComplete(d);const m=Date.now()-r,{toolsUsed:h,toolExecutions:g}=this.extractToolInformation(d),y=gM(t,g);let v=this.formatEnhancedResult(d,s,h,y,t);return await this.recordPerformanceMetrics(v.usage,m),v=await this.synthesizeAIResponseIfNeeded(v,t),await this.enhanceResult(v,t,r)}async synthesizeAIResponseIfNeeded(t,r){if(!r.tts?.enabled||!r.tts?.useAiResponse)return t;const n=r.tts,o=t.content,s=n.provider??r.provider??this.providerName;if(!o||!s)return f.warn("TTS synthesis skipped despite being enabled",{provider:this.providerName,hasAiResponse:!!o,aiResponseLength:o?.length??0,hasProvider:!!s,ttsConfig:{enabled:r.tts?.enabled,useAiResponse:r.tts?.useAiResponse},reason:o?"Provider is missing":"AI response is empty or undefined"}),{...t,ttsMetadata:{attempted:!1,success:!1}};const i=Date.now(),a=this.getTimeout(r);try{const l=await H1(()=>tu.synthesize(o,s,n),a,`TTS synthesis timed out after ${a}ms for provider "${s}"`);return{...t,audio:l,ttsMetadata:{attempted:!0,success:!0,latency:Date.now()-i}}}catch(l){const c=Date.now()-i,u=this.getTTSErrorDetails(l);return this.telemetryHandler.recordTTSFailure(s,u,c),f.error("TTS synthesis failed in Mode 2 (AI response synthesis):",l),{...t,ttsMetadata:{attempted:!0,success:!1,error:u,latency:c}}}}getTTSErrorDetails(t){const r=vm(t).message;return t instanceof wm?{code:Gt.SYNTHESIS_FAILED,message:r,retriable:!0}:t instanceof Ne?{code:t.code,message:r,retriable:t.retriable}:{code:Gt.SYNTHESIS_FAILED,message:r}}async generateText(t){const r=t.prompt||t.input?.text;if(!r||typeof r!="string"||r.trim()==="")throw new Error("GenerateText options must include prompt or input.text as a non-empty string");const n=await this.generate(t);if(!n)throw new Error("Generation failed: No result returned");return{content:n.content||"",provider:n.provider||this.providerName,model:n.model||this.modelName,usage:n.usage||{input:0,output:0,total:0},responseTime:0,toolsUsed:n.toolsUsed||[],toolExecutions:n.toolExecutions?.map(o=>({toolName:o.toolName,executionTime:o.durationMs,success:!o.isError})),enhancedWithTools:!!(n.toolsUsed&&n.toolsUsed.length>0),analytics:n.analytics,evaluation:n.evaluation,audio:n.audio,reasoning:n.reasoning,reasoningTokens:n.reasoningTokens}}async embed(t,r){throw f.warn(`embed() called on ${this.providerName} which does not have a native implementation`,{textLength:t.length}),new Error(`Embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}async embedMany(t,r){throw f.warn(`embedMany() called on ${this.providerName} which does not have a native implementation`,{count:t.length}),new Error(`Batch embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, googleAiStudio, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), gemini-embedding-001 (Google AI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}getDefaultEmbeddingModel(){}getToolCallRepairFn(t){if(!t?.disableToolCallRepair)return(async(...r)=>{const{createToolCallRepair:n}=await Promise.resolve().then(()=>(o9(),r9));return n()(...r)})}async executeStream(t,r){if(!this.doStream)throw new Ne({code:Xe.INVALID_CONFIGURATION,message:`${this.providerName} cannot stream: it neither implements doStream() nor overrides executeStream()`,category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}});const n=Date.now(),{stream:o,finishReason:s,usage:i,warnings:a}=await this.doStream(t);a?.length&&f.warn(`[${this.providerName}] doStream reported warnings`,{provider:this.providerName,count:a.length});const l={startTime:n,streamId:`${this.providerName}-${n}`},c=(async()=>{const[u,d]=await Promise.all([s,i]);return l.finishReason=u,l.rawFinishReason=u,r0(this.providerName,this.modelName||this.getDefaultModel(),{usage:{input:d.inputTokens,output:d.outputTokens,total:d.inputTokens+d.outputTokens},stopReason:u},Date.now()-n,{streamingMode:!0})})();return{stream:o,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:c,metadata:l}}async getAISDKModelWithMiddleware(t={}){const r=await this.getAISDKModel();f.debug(`Retrieved base model for ${this.providerName}`,{provider:this.providerName,model:this.modelName,hasMiddlewareConfig:!!this.middlewareOptions,timestamp:Date.now()});const n=this.extractMiddlewareOptions(t);if(f.debug("Middleware extraction result",{provider:this.providerName,model:this.modelName,middlewareOptions:n}),!n)return r;try{f.debug(`Applying middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,middlewareOptions:n});const o=new b7(n),s=o.createContext(this.providerName,this.modelName,t,{sessionId:this.sessionId,userId:this.userId}),i=o.applyMiddleware(r,s,n);return f.debug(`Applied middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,hasMiddleware:!0}),i}catch(o){return f.warn(`Failed to apply middleware to ${this.providerName}, using base model`,{error:o instanceof Error?o.message:String(o)}),r}}extractMiddlewareOptions(t){return this.utilities.extractMiddlewareOptions(t)}isZodSchema(t){return this.utilities.isZodSchema(t)}async convertToolResult(t){return this.utilities.convertToolResult(t)}fixSchemaForOpenAIStrictMode(t){return this.utilities.fixSchemaForOpenAIStrictMode(t)}async getAllTools(){return this.toolsManager.getAllTools()}async calculateActualCost(t){return this.telemetryHandler.calculateActualCost(t)}createPermissiveZodSchema(){return this.utilities.createPermissiveZodSchema()}setSessionContext(t,r){this.sessionId=t,this.userId=r,this.toolsManager.setSessionContext(t,r)}classifyStreamError(t){const r=t instanceof Error?t:new Error(String(t));return U_t(r)||r instanceof _t||zT(r)===void 0?r:this.handleProviderError(r)}handleProviderError(t){if(qr(t))return t instanceof Error?t:new DOMException("The operation was aborted","AbortError");if(t instanceof Error&&U_t(t))return t;const r=this.formatProviderError(t);if(t&&typeof t=="object"&&r!==t){const n=t,o=r,s=zT(t);if(s!==void 0&&o.statusCode===void 0&&(o.statusCode=s),typeof n.isRetryable=="boolean"&&o.isRetryable===void 0&&(o.isRetryable=n.isRetryable),o.retryAfterMs===void 0){const i=pAe(t);i!==void 0&&(o.retryAfterMs=i)}}UE(t)&&ZP(r);try{const n=vt.getSpan(Er.active());if(n){let o="provider_error";const s=r?.constructor?.name??"";s==="RateLimitError"?o="rate_limit":s==="AuthenticationError"?o="auth_failure":s==="NetworkError"?o="network":s==="InvalidModelError"?o="invalid_model":s==="TimeoutError"&&(o="timeout"),n.setAttribute("error.type",o),r instanceof Error&&n.setAttribute("error.message",r.message.substring(0,500))}}catch{}return DDr(r),r}async executeImageGeneration(t){throw new Error(`Image generation is not supported by the ${this.providerName} provider or the selected model.`)}async executeWithTimeout(t,r){const n=this.getTimeout(r),o=rc(n,this.providerName,r.operationType||"generate");try{return o?await Promise.race([t(),new Promise((s,i)=>{o.controller.signal.addEventListener("abort",()=>{i(new Od(`${this.providerName} operation timed out`,o.timeoutMs,this.providerName,r.operationType||"generate"))})})]):await t()}finally{o?.cleanup()}}validateStreamOptions(t){this.streamHandler.validateStreamOptions(t)}createTextStream(t,r){return this.streamHandler.createTextStream(t,r)}createStreamResult(t,r={}){return this.streamHandler.createStreamResult(t,r)}async createStreamAnalytics(t,r,n){return this.streamHandler.createStreamAnalytics(t,r,n)}handleCommonErrors(t){return this.utilities.handleCommonErrors(t)}setupToolExecutor(t,r){this.toolsManager.setupToolExecutor(t,r)}normalizeTextOptions(t){return this.utilities.normalizeTextOptions(t)}normalizeStreamOptions(t){return this.utilities.normalizeStreamOptions(t)}async enhanceResult(t,r,n){const o=Date.now()-n,s=t.imageOutput;let i={...t};if(r.enableAnalytics)try{const a=await this.createAnalytics(t,o,r);i={...i,analytics:a,imageOutput:s}}catch(a){f.warn(`Analytics creation failed for ${this.providerName}:`,a)}if(r.enableEvaluation)try{const a=await this.createEvaluation(t,r);i={...i,evaluation:a,imageOutput:s}}catch(a){f.warn(`Evaluation creation failed for ${this.providerName}:`,a)}return s&&(i.imageOutput=s),i}async handleVideoGeneration(t,r){const{VideoProcessor:n,VideoError:o,VIDEO_ERROR_CODES:s}=await Promise.resolve().then(()=>(Hm(),S_t)),{validateVideoGenerationInput:i,validateImageForVideo:a,validateDirectorModeInput:l}=await Promise.resolve().then(()=>(eg(),rvt)),{ErrorFactory:c}=await Promise.resolve().then(()=>(ct(),ST)),u={input:t.input||{text:t.prompt||""},output:t.output,provider:t.provider,model:t.model};if(u.input?.segments&&Array.isArray(u.input.segments)&&u.input.segments.length>0){const x=u.input.segments,O=l(u);if(!O.isValid)throw c.invalidParameters("director-mode",new Error(O.errors.map(Y=>Y.message).join("; ")),{errors:O.errors});if(O.warnings.length>0)for(const Y of O.warnings)f.warn(`Director Mode warning: ${Y}`);const{executeDirectorPipeline:N,DIRECTOR_PIPELINE_TIMEOUT_MS:M}=await Promise.resolve().then(()=>(MDr(),I_t)),D=t.timeout??M,L=await this.executeWithTimeout(()=>N(x,u.output?.video??{},u.output?.director??{},t.region),{timeout:D,operationType:"generate"}),$=u.input.segments.map(Y=>Y.prompt).join(" \u2192 "),U=L.metadata?.segmentCount??u.input.segments.length,j=L.metadata?.transitionCount??Math.max(0,U-1),B=L.metadata?.duration??0,J={content:`${$} \u2014 duration: ${B}s, segments: ${U}, transitions: ${j}`,provider:"vertex",model:t.model||"veo-3.1-generate-001",usage:{input:0,output:0,total:0},video:L};return await this.enhanceResult(J,t,r)}const d=i(u);if(!d.isValid)throw c.invalidParameters("video-generation",new Error(d.errors.map(x=>x.message).join("; ")),{errors:d.errors});if(d.warnings.length>0)for(const x of d.warnings)f.warn(`Video generation warning: ${x}`);const m=t.input?.images?.[0];if(!m)throw new o({code:s.INVALID_INPUT,message:"Video generation requires an input image. Provide via input.images array.",retriable:!1,context:{field:"input.images"}});const h=15e3;let g;if(typeof m=="string")if(m.startsWith("http://")||m.startsWith("https://")){f.debug("Fetching image from URL for video generation",{url:m.substring(0,100)});let x;try{x=await this.executeWithTimeout(()=>fetch(m),{timeout:h,operationType:"generate"})}catch(O){throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${O instanceof Error?O.message:"Request timed out"}`,retriable:!0,context:{url:m,timeout:h},originalError:O instanceof Error?O:void 0})}if(!x.ok)throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${x.status} ${x.statusText}`,retriable:x.status>=500,context:{url:m,status:x.status}});g=Buffer.from(await x.arrayBuffer())}else{f.debug("Reading image from path for video generation",{path:m});const x=await Promise.resolve().then(()=>(Kr(),i0));try{g=await this.executeWithTimeout(()=>x.readFile(m),{timeout:h,operationType:"generate"})}catch(O){throw new o({code:s.INVALID_INPUT,message:`Failed to read image file: ${O instanceof Error?O.message:String(O)}`,retriable:!1,context:{path:m,timeout:h},originalError:O instanceof Error?O:void 0})}}else if(Buffer.isBuffer(m))g=m;else if(typeof m=="object"&&"data"in m){const x=m.data;if(typeof x=="string")g=Buffer.from(x,"base64");else if(Buffer.isBuffer(x))g=x;else throw new o({code:s.INVALID_INPUT,message:"ImageWithAltText.data must be a base64 string or Buffer.",retriable:!1,context:{field:"input.images[0].data",type:typeof x}})}else throw new o({code:s.INVALID_INPUT,message:"Invalid image input type. Provide Buffer, path string, URL, or ImageWithAltText.",retriable:!1,context:{field:"input.images[0]",type:typeof m}});const y=a(g);if(y)throw c.invalidParameters("video-generation",new Error(y.message),{field:"input.images[0]",validation:y});const v=t.prompt||t.input?.text||"",_=t.output?.video?.provider??Ivr("video");if(!n.supports(_))throw new o({code:s.PROVIDER_NOT_SUPPORTED,message:`Video provider "${_}" is not registered. Available: ${n.listProviders().join(", ")}`,retriable:!1,context:{provider:_,available:n.listProviders()}});const T=t.output?.video?.model??t.model??(_==="vertex"?"veo-3.1-generate-001":void 0);f.info("Starting video generation",{provider:_,...T?{model:T}:{},promptLength:v.length,imageSize:g.length,resolution:t.output?.video?.resolution||"720p",duration:t.output?.video?.length||6});const k=t.timeout??6e5,A=t.output?.video?.abortSignal??t.abortSignal,I=await this.executeWithTimeout(()=>n.generate(_,{...t.output?.video??{},image:g,prompt:v,region:t.region,abortSignal:A}),{timeout:k,operationType:"generate"}),P=I.metadata?.model??T??(_==="vertex"?"veo-3.1-generate-001":"unknown");f.info("Video generation complete",{provider:_,model:P,videoSize:I.data.length,duration:I.metadata?.duration,processingTime:I.metadata?.processingTime});const R={content:v,provider:_,model:P,usage:{input:0,output:0,total:0},video:I};return await this.enhanceResult(R,t,r)}async createAnalytics(t,r,n){return this.telemetryHandler.createAnalytics(t,r,n.context)}async createEvaluation(t,r){return this.telemetryHandler.createEvaluation(t,r)}validateOptions(t){this.utilities.validateOptions(t)}getProviderInfo(){return this.utilities.getProviderInfo()}getTimeout(t){return this.utilities.getTimeout(t)}async handleToolExecutionStorage(t,r,n,o){return this.telemetryHandler.handleToolExecutionStorage(t,r,n,o)}static chunkPrompt(t,r=9e5,n=100){if(t.length<=r)return[t];const o=[];let s=0;for(;s<t.length;){const i=Math.min(s+r,t.length);if(o.push(t.slice(s,i)),i>=t.length)break;const a=i-n;a<=s?s=i:s=Math.max(a,0)}return o}}}});async function ig(e,t){try{await e}catch(r){f.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var EJ=S({"src/lib/utils/drainDetachedPump.ts"(){"use strict";q()}}),P0=S({"src/lib/utils/async/index.ts"(){"use strict";yn()}});function M0(e,t,r){return async(n,o)=>{const s=()=>Promise.resolve(t(n,o)),i=r.withToolSpan,a=i?()=>i(e,s):s;r.onProgress?.();try{const l=r.abortSignal?Z4e(a(),r.abortSignal):a();return await(r.toolTimeoutMs===void 0?l:zt(l,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var SJ=S({"src/lib/core/toolExecutionGuards.ts"(){"use strict";P0()}});function CJ(e){if(!(!e?.enabled&&!e?.thinkingLevel))return{includeThoughts:!0,thinkingLevel:e.thinkingLevel??B_t}}var B_t,z_t=S({"src/lib/utils/thinkingConfig.ts"(){"use strict";B_t="high"}});function ODr(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function NDr(e){if(J_t.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>c4&&(t=t.slice(0,c4)),t}function LDr(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,s=`${e.slice(0,c4-n.length)}${n}`;if(!t(s))return s;r++}}function Vm(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],s=o.filter(c=>c.type!=="null"&&c.type!=="undefined");if(s.length===1){const c=Vm({...s[0]});return c.nullable=!0,e.description&&(c.description=e.description),c}const i=s.map(c=>c.type||"unknown").join(" | "),a={type:"string"},l=e.description?`${e.description} (accepts: ${i})`:`Value as string (accepts: ${i})`;return a.description=l,o.some(c=>c.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const s={};for(const[i,a]of Object.entries(o))a&&typeof a=="object"?s[i]=Vm(a):s[i]=a;t[n]=s}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(s=>s&&typeof s=="object"?Vm(s):s):t[n]=Vm(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>Vm(n))),t.not&&typeof t.not=="object"&&(t.not=Vm(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=Vm(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function j_t(e,t){const r=[],n=new O0,o=[],s=[],i=new Set(t??[]),a=new Map;for(const[l,c]of Object.entries(e))try{const u=NDr(l),d=LDr(u,g=>i.has(g));a.set(d,l),d!==l&&s.push({from:l,to:d});const m={name:d,description:c.description||`Tool: ${d}`},h=c;if(h.parameters||c.inputSchema){let g;const y=h.parameters||c.inputSchema;sV(y)?g=js(y,"openApi3"):typeof y=="object"?g=y:g={type:"object",properties:{}},g.jsonSchema&&typeof g.jsonSchema=="object"&&!g.type&&(g=g.jsonSchema),m.parametersJsonSchema=Vm(dn(g))}r.push(m),i.add(d),c.execute&&n.set(m.name,c.execute)}catch(u){o.push(l),f.error(`[buildNativeToolDeclarations] Failed to convert tool "${l}":`,u)}return o.length>0&&f.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),s.length>0&&f.warn(`[buildNativeToolDeclarations] ${s.length} tool name(s) sanitized for Google's function-name regex: ${s.map(l=>`"${l.from}" -> "${l.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function n4(e,t,r){const n={},o=(s,i)=>r?M0(s,i,r):async(a,l)=>i(a,l);if(e){for(const[s,i]of e.originalNameMap){const a=e.executeMap.get(s);a&&(n[i]={execute:o(i,a)})}return n}for(const[s,i]of Object.entries(t??{})){const a=i?.execute;a&&(n[s]={execute:o(s,a)})}return n}function $Dr(e,t){if(!e)return[];const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([s])=>!r.has(s));if(n.length===0)return[];const o=j_t(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[s,i]of o.originalNameMap)t.originalNameMap.set(s,i);for(const[s,i]of o.executeMap)t.executeMap.set(s,i);return f.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([s])=>s).join(", ")}`),n.map(([s])=>s)}function q_t(e,t){const r=eu("google-ai",e.model,{temperature:e.temperature??1},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=CJ(e.thinkingConfig);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function G_t(e){const t=e||Ai;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),AJ):Math.min(Ai,AJ)}function kJ(e){switch(e){case"MAX_TOKENS":return"length";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"IMAGE_SAFETY":return"content-filter";default:return"stop"}}function FDr(e,t){return t?e?`${e}
|
|
1062
1062
|
${t}`:t:e}async function UDr(e,t){const r=[],n=[];let o=0,s=0,i=0,a=0,l;for await(const c of e){const u=c,m=u.candidates?.[0],h=m?.finishReason;typeof h=="string"&&(l=h);const g=m?.content;if(g&&Array.isArray(g.parts))for(const v of g.parts)r.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.text});c.functionCalls&&n.push(...c.functionCalls);const y=u.usageMetadata;y&&(o=Math.max(o,y.promptTokenCount||0),s=Math.max(s,y.candidatesTokenCount||0),i=Math.max(i,y.cachedContentTokenCount||0),a=Math.max(a,y.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:l,inputTokens:o,outputTokens:s,cacheReadTokens:i,reasoningTokens:a}}function o4(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r!=null&&typeof r=="object"&&"thoughtSignature"in r&&typeof r.thoughtSignature=="string")return r.thoughtSignature}}function BDr(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function H_t(e,t,r,n,o){return t>=r&&!n?(f.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||Km(r,0)):n}function Wm(e){if(!e)return!1;const t=e;return t.name==="AbortError"||typeof t.message=="string"&&/abort/i.test(t.message)||typeof DOMException<"u"&&e instanceof DOMException&&t.code===20}function Km(e,t){return`${t>0?`I gathered information across ${t} tool call${t===1?"":"s"} but `:"I "}reached the ${e}-step limit for a single turn before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function _c(e){return`${e>0?`I gathered information across ${e} tool call${e===1?"":"s"} but `:"I "}had to stop because the gathered material filled this turn's context window before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function V_t(e){const t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/60),n=t%60;return r>0?`${r}m ${n}s`:`${n}s`}function zDr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${V_t(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function jDr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop because this turn made no progress for ${V_t(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function qDr(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function s4(e){return"NOTE: processing time for this turn is nearly up. Consolidate what you have and "+(e?"call final_result with your best answer now.":"provide your final answer now.")}function i4(e){return e.timedOut?"time-limit":e.stalled?"stalled":e.wasAborted?"aborted":e.contextCappedWithoutAnswer?"context-cap":e.cappedWithoutAnswer?"step-cap":e.finishReason==="error"?"provider-error":"completed"}function a4(e){const t=Date.now(),r=u=>u!==void 0&&Number.isFinite(u)&&u>0,n=r(e.turnTimeoutMs)?e.turnTimeoutMs:r(e.defaultTurnTimeoutMs)?e.defaultTurnTimeoutMs:void 0,o=r(e.turnTimeoutMs)?e.wrapupTimeLeadMs??D7:void 0;let s=!1,i=!1,a=t,l,c;if(n!==void 0&&(l=setTimeout(()=>{s=!0,e.onDeadline("timeout")},n),l.unref?.()),r(e.stallTimeoutMs)){const u=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);c=setInterval(()=>{!i&&!s&&Date.now()-a>=u&&(i=!0,e.onDeadline("stall"))},d),c.unref?.()}return{get timedOut(){return s},get stalled(){return i},get expired(){return s||i},get turnTimeoutMs(){return n},elapsedMs(){return Date.now()-t},noteProgress(){a=Date.now()},shouldNudgeWrapup(){if(n===void 0||o===void 0)return!1;const u=n-(Date.now()-t);return u>0&&u<=o},dispose(){l&&clearTimeout(l),c&&clearInterval(c)}}}function D0(e,t=eM){const r=Math.floor(e*t);let n=0,o=0;return{get thresholdTokens(){return r},get projectedNextPromptTokens(){return n+o},noteUsage(s,i){s>0&&(n=s,o=Math.max(0,i))},noteAppendedChars(s){s>0&&(o+=Math.ceil(s/4))},resetAfterReclaim(){n=0,o=0},shouldStop(){return n>0&&n+o>=r}}}function GDr(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function W_t(e){const t=js(e,"openApi3"),r=dn(t);return r.$schema&&delete r.$schema,Ii(r)}function l4(e,t){if(!t||t.length===0)return;const r=new Map,n=[];let o=0;const s=a=>`${o}:${a??"undefined"}`,i=a=>{const l=s(a),c=r.get(l);if(c)return c;const u={type:"tool_step",callParts:[],resultParts:[]};return r.set(l,u),n.push(u),u};for(const a of t){if(a.role==="tool_call"){const u=i(a.metadata?.stepIndex),d={functionCall:{name:a.tool||"unknown",args:a.args||{}}};a.metadata?.thoughtSignature&&(d.thoughtSignature=a.metadata.thoughtSignature),u.callParts.push(d);continue}if(a.role==="tool_result"){const u=i(a.metadata?.stepIndex);let d;try{d=a.content!==void 0&&a.content!==null?{result:JSON.parse(a.content)}:{result:"success"}}catch{d={result:a.content??"success"}}u.resultParts.push({functionResponse:{name:a.tool||"unknown",response:d}});continue}const l=a.role==="assistant"?"model":a.role;if(l!=="user"&&l!=="model"||!a.content||a.content.trim().length===0)continue;o++;const c={text:a.content};a.metadata?.thoughtSignature&&(c.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:l,parts:[c]})}for(const a of n){if(a.type==="regular"){e.push({role:a.role,parts:a.parts});continue}if(a.callParts.length===0){a.resultParts.length>0&&f.debug("[GoogleNativeGemini3] Dropping orphan tool_result segment with no matching tool_call rows",{resultCount:a.resultParts.length});continue}e.push({role:"model",parts:a.callParts}),a.resultParts.length>0&&e.push({role:"user",parts:a.resultParts})}}async function xJ(e,t,r="[GeminiNative]"){if(!(!t||t.length===0))for(const n of t){const o=n.filename.split(/[\\/]/).pop()??n.filename,s=o.lastIndexOf("."),i=s>0?o.slice(s):".bin",a=await Oyt(n.buffer,n.mimeType,i);if(IK(a.mimeType)){f.warn(`${r} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}e.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),f.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function K_t(e,t,r="[GeminiNative]"){const o=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){f.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const s of e.pdfFiles){let i;typeof s=="string"?Zi(s)?i=Xi(s):i=Buffer.from(s,"base64"):i=s,o.push({inlineData:{mimeType:"application/pdf",data:i.toString("base64")}})}}if(e?.images&&e.images.length>0){f.debug(`${r} Processing ${e.images.length} image(s)`);for(const s of e.images){const i=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s;let a,l="image/jpeg";if(typeof i=="string")if(Zi(i)){a=Xi(i);const c=h0(i).toLowerCase();c===".png"?l="image/png":c===".gif"?l="image/gif":c===".webp"&&(l="image/webp")}else if(i.startsWith("data:")){const c=i.match(/^data:([^;]+);base64,(.+)$/);if(c)l=c[1],a=Buffer.from(c[2],"base64");else continue}else if(i.startsWith("http://")||i.startsWith("https://"))try{const c=await fetch(i);if(!c.ok){f.warn(`${r} Image fetch failed: ${c.status} ${c.statusText}, skipping`,{url:i});continue}const u=await c.arrayBuffer();a=Buffer.from(u);const d=c.headers.get("content-type");d&&d.startsWith("image/")&&(l=d.split(";")[0])}catch(c){f.warn(`${r} Image URL fetch threw, skipping: ${c instanceof Error?c.message:String(c)}`,{url:i});continue}else a=Buffer.from(i,"base64");else a=i;a&&o.push({inlineData:{mimeType:l,data:a.toString("base64")}})}}return await xJ(o,e?.nativeAudioFiles,r),o}var O0,J_t,c4,AJ,u4=S({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";Ho(),to(),rr(),es(),$yt(),q(),SJ(),Am(),Yi(),z_t(),O0=class extends Map{resultCache=new Map;get(e){const t=super.get(e);if(!t)return t;const r=this.resultCache;return async(o,s)=>{const i=`${e}::${ODr(o)}`;if(r.has(i))return f.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),r.get(i);const a=await t(o,s);return r.set(i,a),a}}},J_t=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,c4=128,AJ=100}});function d4(e){const t=n=>e.declarations?.originalNameMap?.get(n)??n,r=n=>{const o=e.declarations?.originalNameMap;if(!o)return n;for(const[s,i]of o)if(i===n)return s;return n};return{providerLabel:e.providerLabel,maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},buildStepRequest(n,o){const s=e.declarations?$Dr(e.liveTools,e.declarations):[];return{raw:e.buildRequest(n,o),...s.length>0?{hydratedToolNames:s}:{}}},...e.planReclaim?{planReclaim:(n,o)=>e.planReclaim?.(n,o)}:{},...e.enableMalformedRetry&&e.buildMalformedRetryNote?{isMalformedStep:n=>n.toolCalls.length===0&&!n.text&&n.rawStopReason==="MALFORMED_FUNCTION_CALL",buildMalformedRetryNote:e.buildMalformedRetryNote}:{},resolveToolOnMiss:n=>{const s=xV(e.liveTools,n)?.execute;if(!s)return;const i=e.declarations?.executeMap;let a=s;return i&&(i.set(n,s),a=i.get(n)??s),{execute:e.toolGuards?M0(n,a,e.toolGuards):(async(c,u)=>a(c,u))}},async executeStep(n,o,s){const i=await e.sendStep(n.raw,s),a=e.collectStep?await e.collectStep(i,o):await UDr(i,{push:h=>o.push(h)});e.noteUsage?.(a.inputTokens,a.outputTokens);const l=BDr(a.rawResponseParts),c=a.stepFunctionCalls.map((h,g)=>({id:`${e.providerLabel}_${g}_${h.name}`,name:t(h.name),args:h.args})),u=e.finalResultToolName?c.find(h=>h.name===e.finalResultToolName):void 0,d=u?[]:c,m=u?JSON.stringify(u.args):l;return u&&e.onTerminalResult?.(m),{text:m,toolCalls:d,usage:{inputTokens:a.inputTokens,outputTokens:a.outputTokens,...a.cacheReadTokens?{cacheReadTokens:a.cacheReadTokens}:{},...a.reasoningTokens?{reasoningTokens:a.reasoningTokens}:{}},rawStopReason:a.finishReason,raw:{rawResponseParts:a.rawResponseParts,stepFunctionCalls:a.stepFunctionCalls}}},buildToolResultMessages(n,o,s,i){const a=[...n];return GDr(a,o.raw.rawResponseParts,o.raw.stepFunctionCalls),a.push({role:"user",parts:s.map(l=>({functionResponse:{name:r(l.name),response:l.error?l.output:{result:l.output}}}))}),a},mapFinishReason(n,o){const s=kJ(n);return o&&s==="stop"?"tool-calls":s}}}var Y_t=S({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";SJ(),sS(),u4()}});function N0(){const e=[];let t=!1,r,n=!1,o=null;function s(){if(o){const d=o;o=null,d()}}function i(d){t||(e.push(d),s())}function a(){t=!0,s()}function l(d){t=!0,r=d,n=!0,s()}let c=0;async function*u(){try{for(;;)if(c<e.length)yield e[c++],c>1024&&c*2>=e.length&&(e.splice(0,c),c=0);else if(t){if(n)throw r instanceof Error?r:new Error(String(r));return}else await new Promise(d=>{o=d})}finally{t=!0,e.length=0,o?.()}}return{push:i,close:a,error:l,iterable:u()}}var L0=S({"src/lib/core/streamChannel.ts"(){"use strict"}});function HDr(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:(e.cacheReadTokens??0)+(t.cacheReadTokens??0)||void 0,cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)||void 0,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0)||void 0,cacheWrite5mTokens:(e.cacheWrite5mTokens??0)+(t.cacheWrite5mTokens??0)||void 0,cacheWrite1hTokens:(e.cacheWrite1hTokens??0)+(t.cacheWrite1hTokens??0)||void 0}}async function VDr(e){const{calls:t,adapter:r,tools:n,failedTools:o,abortSignal:s}=e,i=[],a=[],l=[];let c=!1;for(const u of t){if(s.aborted){c=!0;break}l.push(u);const d=r.toolFailureBreaker,m=d?o.get(u.name):void 0;if(d&&m&&m.count>=d.maxRetries){const y={error:`TOOL_PERMANENTLY_FAILED: "${u.name}" has failed ${m.count} times. Last error: ${m.lastError}.`,status:"permanently_failed",do_not_retry:!0};i.push({...u,output:y,error:y.error,permanentlyFailed:!0}),a.push({id:u.id,name:u.name,input:u.args,output:y,error:y.error});continue}const h=n?.[u.name];let g=h;if(!h?.execute){const y=r.resolveToolOnMiss?.(u.name);y&&(g=y,o.delete(u.name))}if(!g?.execute){const y=d?{error:`TOOL_NOT_FOUND: "${u.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${u.name}`};i.push({...u,output:y,error:y.error,permanentlyFailed:!!d}),a.push({id:u.id,name:u.name,input:u.args,output:y,error:y.error});continue}try{const y=await g.execute(u.args,{toolCallId:u.id,abortSignal:s}),v=d?.classifyResultFailure?.(y);if(d)if(v){const _=o.get(u.name)??{count:0,lastError:""};_.count++,_.lastError=v,o.set(u.name,_)}else d.consecutive&&o.delete(u.name);i.push({...u,output:y}),a.push({id:u.id,name:u.name,input:u.args,output:y})}catch(y){const v=y instanceof Error?y.message:String(y);if(d){const b=o.get(u.name)??{count:0,lastError:""};b.count++,b.lastError=v,o.set(u.name,b)}const _={error:v,status:"failed"};i.push({...u,output:_,error:v}),a.push({id:u.id,name:u.name,input:u.args,output:_,error:v})}}return{toolResults:i,executions:a,dispatched:l,abortedMidBatch:c}}function op(e,t,r){const n=N0(),o=new AbortController,s=()=>o.abort();r.abortSignal?.addEventListener("abort",s),r.abortSignal?.aborted&&o.abort();const i=new Map;let a=!1;const l=(async()=>{let c=t,u={inputTokens:0,outputTokens:0},d="",m="",h;const g=[],y=[];let v=!1;try{for(let b=0;b<e.maxSteps&&!o.signal.aborted;b++){if(e.planReclaim){const O=e.planReclaim(c,b);if(O?.conversation!==void 0&&(c=O.conversation),O?.stop)break}const T=e.buildStepRequest(c,b);for(const O of T.hydratedToolNames??[])i.delete(O);let k=!1;const A={push:O=>{k=!0,n.push(O)}};let I;try{I=await Mv(async()=>{k=!1;try{return await e.executeStep(T,A,o.signal)}catch(O){throw k?new IJ(O):O}},r.span,`${e.providerLabel}.step`)}catch(O){throw O instanceof IJ?O.cause:O}if(u=HDr(u,I.usage),h=I.rawStopReason,m=I.text||m,e.isMalformedStep?.(I)&&!a&&!o.signal.aborted){a=!0,f.warn(`[${e.providerLabel}] Malformed function call at step ${b+1}/${e.maxSteps}; retrying once.`),c=e.buildMalformedRetryNote?.(c,b)??c;continue}if(I.toolCalls.length===0){d=I.text||d;break}b===e.maxSteps-1&&(v=!0);const P=await VDr({calls:I.toolCalls,adapter:e,tools:r.tools,failedTools:i,abortSignal:o.signal}),R=P.toolResults;if(g.push(...P.dispatched),y.push(...P.executions),P.abortedMidBatch)break;c=e.buildToolResultMessages(c,I,R,b)}const _=e.mapFinishReason(h,v);return{text:d||(v?m:""),toolCalls:g,toolExecutions:y,usage:u,finishReason:_,rawStopReason:h,conversation:c}}catch(_){throw n.error(_),_}finally{n.close(),r.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:l}}var IJ,p4=S({"src/lib/core/loopEngine.ts"(){"use strict";L0(),q(),ym(),IJ=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function WDr(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function KDr(e,t,r){const n=[];let o=t;for(;o<r;){if(!WDr(e[o])){o++;continue}const s=o;for(;o<e.length&&e[o].kind==="toolCall";)o++;for(;o<e.length&&e[o].kind==="toolResult";)o++;if(o>r)break;n.push({start:s,end:o})}return n}function RJ(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=eM,lowWaterRatio:s=Z_t,protectedTailCount:i=X_t,calibration:a=1}=t,l=a>0?a:1,c=Math.floor(r*o/l),u=Math.floor(r*s/l);let d=n;for(const _ of e)d+=_.tokens;if(d<=c)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const m=1,h=Math.max(m,e.length-i),g=[],y=new Set;for(let _=m;_<h&&d>u;_++){const b=e[_];if(b.kind!=="toolResult"||b.previewTokens===void 0)continue;const T=b.tokens-b.previewTokens;T<=0||(g.push(_),d-=T)}if(d>u){const _=KDr(e,m,h);for(const b of _){if(d<=u)break;for(let T=b.start;T<b.end;T++){const k=e[T],A=g.includes(T)?k.previewTokens??k.tokens:k.tokens;d-=A,y.add(T)}}}const v=g.filter(_=>!y.has(_));return{fire:v.length>0||y.size>0,truncate:v,drop:[...y].sort((_,b)=>_-b),projectedTokens:d}}var Z_t,X_t,PJ=S({"src/lib/context/loopGuardCore.ts"(){"use strict";es(),Z_t=.6,X_t=4}});function Q_t(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function ewt(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function JDr(e){return ewt(e,"functionResponse")}function MJ(e){const{preview:t}=pc(e,{maxBytes:DJ,maxLines:rwt});return t}function YDr(e,t){return mr(Q_t(e.parts),t)+xl}function ZDr(e,t){return e.map(r=>{const n=YDr(r,t);if(JDr(r)){const o=Q_t(r.parts),s=o.length>DJ?mr(MJ(o),t)+xl:n;return{kind:"toolResult",tokens:n,...s<n?{previewTokens:s}:{}}}return ewt(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function twt(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:s}=e,i=ZDr(t,o);let a=1;if(s&&s>0){const c=n+i.reduce((u,d)=>u+d.tokens,0);c>0&&(a=Math.min(3,Math.max(1,s/c)))}const l=RJ(i,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(l.fire)return f.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:l.truncate.length,contentsDropped:l.drop.length,projectedTokens:l.projectedTokens,calibration:a}),l}var DJ,rwt,OJ,nwt=S({"src/lib/context/geminiLoopGuard.ts"(){"use strict";si(),Pf(),PJ(),q(),DJ=2048,rwt=60,OJ="[Earlier tool exchanges were removed to fit the context window.]"}}),owt=S({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";u4()}}),sp,swt=S({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";sp=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function $0(e,t){if(t==="functionDeclarations")return j_t(e);const r=Object.entries(e??{});if(r.length!==0)return r.map(([n,o])=>{const s=o,i=s.inputSchema??s.parameters,a=i?js(i):{type:"object",properties:{}},l=sp(o);return{name:n,...s.description?{description:s.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var NJ=S({"src/lib/core/nativeToolFormat.ts"(){"use strict";u4(),swt(),Yi()}});function XDr(e,t){try{const[r,n]=t.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;const s=c=>{const u=c.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},i=s(e),a=s(r),l=-1<<32-o>>>0;return(i&l)===(a&l)}catch{return!1}}function QDr(e,t){const r=t||process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;try{const n=new URL(e),o=n.hostname.toLowerCase(),s=n.port||(n.protocol==="https:"?"443":"80"),i=r.split(",").map(a=>a.trim()).filter(Boolean);for(const a of i){const l=a.toLowerCase();if(l==="*")return!0;if(l.startsWith(".")){const c=l.slice(1);if(o.endsWith(c)||o===c)return!0}else if(l.includes(":")){const[c,u]=l.split(":");if(o===c&&s===u)return!0}else if(l.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&XDr(o,l))return!0}else if(o===l)return!0}return!1}catch(n){return f.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:e,error:n}),!1}}var e4r=S({"src/lib/proxy/utils/noProxyUtils.ts"(){"use strict";q()}});async function t4r(){try{return(await Promise.resolve().then(()=>(qm(),eJ))).getLangfuseContext?.()}catch{return}}function r4r(e,t){const r=new Headers(e instanceof Request?e.headers:void 0);if(t?.headers){const n=new Headers(t.headers);for(const[o,s]of n.entries())r.set(o,s)}return r}async function iwt(e,t){const r={};Uy.inject(Er.active(),r);const n=await t4r();if(n?.sessionId&&(r["x-neurolink-session-id"]=n.sessionId),n?.userId&&(r["x-neurolink-user-id"]=n.userId),n?.conversationId&&(r["x-neurolink-conversation-id"]=n.conversationId),Object.keys(r).length===0)return t??{};const o=r4r(e,t);for(const[s,i]of Object.entries(r))o.has(s)||o.set(s,i);return{...t,headers:o}}function n4r(e){try{const t=typeof e=="string"?e:e instanceof URL?e.href:e.url;return new URL(t).hostname}catch{return"[unknown]"}}function o4r(e){let t=e;for(let r=0;r<5&&t;r++){const n=t;if(n.code&&_q.has(n.code)||n.message?.includes("socket hang up")||n.message?.includes("network socket disconnected")||n.message?.includes("other side closed"))return!0;t=n.cause}return!1}async function awt(e,t,r=3,n=500){const o=n4r(e);return pwt.startActiveSpan("neurolink.http.fetchWithRetry",async s=>{s.setAttribute("http.request.max_retries",r),s.setAttribute("http.request.hostname",o),s.setAttribute("http.request.method",t?.method||"GET");let i=0;try{for(let a=0;a<=r;a++){i=a+1;try{const l=await fetch(e,t);return s.setAttribute("http.request.total_attempts",i),s.setAttribute("http.response.status_code",l.status),s.setStatus({code:qe.OK}),l}catch(l){const c=o4r(l),u=l;if(!c||a===r)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:qe.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),s.recordException(l instanceof Error?l:new Error(String(l))),l;const d=n*Math.pow(2,a);s.addEvent("http.request.retry",{"retry.attempt":a+1,"retry.delay_ms":d,"retry.error":(u?.code||u?.message||String(l)).slice(0,256)}),f.debug(`[fetchWithRetry] Transient error (${u?.code||u?.message}), retrying in ${d}ms (attempt ${a+1}/${r})`),await new Promise(m=>setTimeout(m,d))}}throw new Error("fetchWithRetry exhausted")}finally{s.end()}})}function lwt(e){if(!e)return{parsed:null,size:0,type:"empty"};if(typeof e=="string")try{return{parsed:JSON.parse(e),size:e.length,type:"json"}}catch{return{parsed:e,size:e.length,type:"text"}}return e instanceof ArrayBuffer?{parsed:"[ArrayBuffer]",size:e.byteLength,type:"arraybuffer"}:e instanceof Uint8Array?{parsed:"[Uint8Array]",size:e.length,type:"uint8array"}:{parsed:"[Stream]",size:-1,type:"stream"}}async function LJ(e){const t={};e.headers.forEach((r,n)=>{t[n]=mwt.has(n.toLowerCase())?`${r.substring(0,4)}***`:r});try{const n=await e.clone().text();try{return{parsed:JSON.parse(n),size:n.length,type:"json",headers:t}}catch{return{parsed:n,size:n.length,type:"text",headers:t}}}catch{return{parsed:"[unable to read body]",size:-1,type:"error",headers:t}}}function s4r(e){try{const t=new URL(e),r={protocol:t.protocol,hostname:t.hostname,port:parseInt(t.port)||cwt(t.protocol),cleanUrl:`${t.protocol}//${t.hostname}:${t.port||cwt(t.protocol)}`};return t.username&&t.password&&(r.auth={username:decodeURIComponent(t.username),password:decodeURIComponent(t.password)}),r}catch(t){let r;try{const n=new URL(e);n.username="",n.password="",r=n.toString()}catch{r="[invalid-url]"}throw f.error("[Proxy] Failed to parse proxy URL",{proxyUrl:r,error:t}),new Error(`Invalid proxy URL: ${r}`,{cause:t})}}function cwt(e){switch(e){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function i4r(e){if(QDr(e))return f.debug("[Proxy] Bypassing proxy due to NO_PROXY",{targetUrl:e}),null;try{const t=new URL(e),r=process.env.HTTPS_PROXY||process.env.https_proxy,n=process.env.HTTP_PROXY||process.env.http_proxy,o=process.env.ALL_PROXY||process.env.all_proxy,s=process.env.SOCKS_PROXY||process.env.socks_proxy;return t.protocol==="https:"&&r?r:t.protocol==="http:"&&n?n:o||s||null}catch(t){return f.warn("[Proxy] Error selecting proxy URL",{targetUrl:e,error:t}),null}}async function a4r(e){const t=s4r(e);switch(f.debug("[Proxy] Creating proxy agent",{protocol:t.protocol,hostname:t.hostname,port:t.port,hasAuth:!!t.auth}),t.protocol){case"http:":case"https:":{const{ProxyAgent:r}=await Promise.resolve().then(()=>(Ff(),m9));return new r(e)}case"socks4:":case"socks5:":throw new Error("SOCKS proxy support requires 'proxy-agent' package. Install it with: npm install proxy-agent");default:throw new Error(`Unsupported proxy protocol: ${t.protocol}`)}}function Ta(e){return F0(e)??"NOT_SET"}function uwt(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function l4r(){return async(e,t)=>{const r=await iwt(e,t),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=uwt(e);if(f.shouldLog("debug")){const{size:i,type:a}=lwt(r?.body);f.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:s,method:r?.method||"POST",bodySize:i,bodyType:a})}try{const i=await awt(e,r);if(f.shouldLog("debug")){const{parsed:a,size:l,type:c,headers:u}=await LJ(i);f.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:s,status:i.status,statusText:i.statusText,durationMs:Date.now()-o,contentLength:l,hasContent:!!a,bodyType:c,responseHeaders:u})}return i}catch(i){throw f.debug("[Observability] HTTP request failed",{requestId:n,url:s,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-o}),i}}}async function c4r(e,t,r){const{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=r;t=await iwt(e,t);const l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=uwt(e);if(f.shouldLog("debug")){const{size:h,type:g}=lwt(t?.body);f.debug("[Observability] HTTP request to LLM provider",{requestId:l,url:u,method:t?.method||"POST",bodySize:h,bodyType:g})}f.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:l,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:Ta(o),httpsProxy:Ta(n),allProxy:Ta(s),socksProxy:Ta(i),noProxy:a||"NOT_SET",initMethod:t?.method||"GET"});const d=e instanceof Request?e.clone():null;try{const h=i4r(u);if(h){const g=new URL(u);f.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:l,targetUrl:u,urlHostname:g.hostname,urlProtocol:g.protocol,urlPort:g.port,selectedProxyUrl:Ta(h),timestamp:new Date().toISOString()}),f.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:Ta(h),targetHostname:g.hostname,targetProtocol:g.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});const y=globalThis;y.__NL_PROXY_AGENT_CACHE__||(y.__NL_PROXY_AGENT_CACHE__=new Map);const v=y.__NL_PROXY_AGENT_CACHE__,_=uE("sha256").update(F0(h)??h).digest("hex"),b=v.get(_)||await a4r(h);v.set(_,b),f.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:l,hasDispatcher:!!b,dispatcherType:typeof b,dispatcherConstructor:b?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let T,k={...t};e instanceof Request?(T=e.url,k={method:e.method,headers:e.headers,body:e.body,...t}):T=e;const I=await(await Promise.resolve().then(()=>(Ff(),m9))).fetch(T,{...k,dispatcher:b});if(f.shouldLog("debug")){const{parsed:P,size:R,type:x,headers:O}=await LJ(I);f.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:I?.status,statusText:I?.statusText,durationMs:Date.now()-c,contentLength:R,hasContent:!!P,bodyType:x,proxied:!0,responseHeaders:O})}return f.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:l,responseStatus:I?.status,responseOk:I?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),I}}catch(h){const g=h instanceof Error?h.message:String(h);f.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:g,durationMs:Date.now()-c}),f.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:l,error:g,errorType:h instanceof Error?h.constructor.name:typeof h,willFallback:!0,timestamp:new Date().toISOString()}),f.warn(`[Proxy Fetch] Enhanced proxy failed (${g}), falling back to direct connection`)}f.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:l,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});const m=e instanceof Request?d??e:e;try{const h=await awt(m,t);if(f.shouldLog("debug")){const{parsed:g,size:y,type:v,headers:_}=await LJ(h);f.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:h.status,statusText:h.statusText,durationMs:Date.now()-c,contentLength:y,hasContent:!!g,bodyType:v,proxied:!1,responseHeaders:_})}return h}catch(h){const g=h instanceof Error?h.message:String(h);throw f.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:g,durationMs:Date.now()-c}),h}}function u4r(e){return async(t,r)=>c4r(t,r,e)}function Bt(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy,s={httpsProxy:e,httpProxy:t,allProxy:r,socksProxy:n,noProxy:o};if(f.shouldLog("debug")){const i=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,l)=>{const c=process.env[l]||"NOT_SET";return a[l]=l.toLowerCase()==="no_proxy"?c:Ta(c),a},{});f.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:Ta(t),httpsProxy:Ta(e),allProxy:Ta(r),socksProxy:Ta(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:i,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!e&&!t&&!r&&!n?(f.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),l4r()):(f.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),f.debug(`[Proxy Fetch] HTTP_PROXY: ${Ta(t)}`),f.debug(`[Proxy Fetch] HTTPS_PROXY: ${Ta(e)}`),f.debug(`[Proxy Fetch] ALL_PROXY: ${Ta(r)}`),f.debug(`[Proxy Fetch] SOCKS_PROXY: ${Ta(n)}`),f.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),u4r(s))}function F0(e){if(!e)return null;try{const t=new URL(e);return(t.username||t.password)&&(t.username="***",t.password="***"),t.toString()}catch{return"[invalid-url]"}}function d4r(){const e=process.env.HTTPS_PROXY||process.env.https_proxy,t=process.env.HTTP_PROXY||process.env.http_proxy,r=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy;return{enabled:!!(e||t||r||n),httpProxy:F0(t),httpsProxy:F0(e),allProxy:F0(r),socksProxy:F0(n),noProxy:o||null,method:"enhanced-proxy-agent",capabilities:["HTTP/HTTPS Proxy","SOCKS4/SOCKS5 Proxy","Proxy Authentication","NO_PROXY Bypass","CIDR Range Matching","Wildcard Domain Matching"]}}function dwt(e){$J||!d4r().enabled||($J=!0,f.warn(`[${e}] A proxy is configured, but the @google/genai SDK provides no way to route its requests through it (HttpOptions has no 'fetch', and GoogleGenAIOptions accepts none). Requests from this provider go direct.`))}var pwt,mwt,$J,no=S({"src/lib/proxy/proxyFetch.ts"(){"use strict";q(),er(),yr(),e4r(),Ho(),vAe(),pwt=He.http,mwt=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"]),$J=!1}});async function U0(e,t){const n=(await Promise.resolve().then(()=>(cE(),Fv))).GoogleGenAI;if(!n)throw new Ne({code:Xe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const o=n;return dwt("GoogleAIStudio"),new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{}}})}function hwt(e,t,r){const n=twt({contents:e,availableInputTokens:ou("googleAiStudio",t),provider:"googleAiStudio",...r?{observedPromptTokens:r}:{}});if(!n)return!1;const o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(s.has(a)&&Array.isArray(l.parts)){i.push({...l,parts:l.parts.map(c=>{const u=c;if(!u.functionResponse)return c;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?c:{functionResponse:{name:u.functionResponse.name,response:{result:MJ(d)}}}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:OJ}]})}return e.length=0,e.push(...i),!0}var fwt,p4r=S({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";vc(),es(),RD(),Cl(),yt(),ct(),q(),EJ(),Y_t(),p4(),es(),WV(),nwt(),Ju(),Ua(),P0(),si(),Wd(),vM(),owt(),L0(),NJ(),no(),fwt=class extends Il{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,f.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new Ne({code:Xe.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof Od)return new jo(e.message,this.providerName);const t=e,r=typeof t?.message=="string"?t.message:"Unknown error",n=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return r.includes("API_KEY_INVALID")||r.includes("Invalid API key")||n===401?new sr("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):r.includes("RATE_LIMIT_EXCEEDED")||r.includes("rate limit")||r.includes("429")||n===429?new Xs("Google AI rate limit exceeded. Please try again later.",this.providerName):n===404||n===void 0&&(r.includes("model not found")||r.includes("Model not found"))?new co(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):r.includes("ECONNRESET")||r.includes("ENOTFOUND")||r.includes("ETIMEDOUT")||r.includes("ECONNREFUSED")||r.includes("network")||r.includes("connection")?new jo(`Connection error: ${r}`,this.providerName):r.includes("500")||r.includes("502")||r.includes("503")||r.includes("504")||r.includes("server error")||r.includes("Internal Server Error")||n&&n>=500&&n<600?new _t(`Google AI server error: ${r}. Please try again later.`,this.providerName):new _t(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){await qS(e.input);const t=e.prompt||e.input?.text||"",r=e.model||this.modelName,n=Date.now(),o=this.getApiKey();f.info("\u{1F3A8} Starting Google AI Studio image generation",{model:r,prompt:t.substring(0,100),provider:this.providerName});let s;try{s=await U0(o,this.getBaseURL())}catch{throw new sr("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{const i=await Promise.all((e.input?.images||[]).map(async d=>{if(typeof d=="object"&&"url"in d){const g=d.url;if(g.startsWith("http")){const _=await fetch(g);if(!_.ok)throw new Error(`Failed to fetch image from ${g}: ${_.status} ${_.statusText}`);const b=await _.arrayBuffer(),T=Buffer.from(b),k=this.detectImageType(T);return f.debug(`Downloaded and detected image MIME type: ${k}`),{inlineData:{mimeType:k,data:T.toString("base64")}}}const y=Buffer.from(g,"base64");return{inlineData:{mimeType:this.detectImageType(y),data:y.toString("base64")}}}if(typeof d=="string"&&d.startsWith("http")){const g=await fetch(d);if(!g.ok)throw new Error(`Failed to fetch image from ${d}: ${g.status} ${g.statusText}`);const y=await g.arrayBuffer(),v=Buffer.from(y),_=this.detectImageType(v);return f.debug(`Downloaded and detected image MIME type: ${_}`),{inlineData:{mimeType:_,data:v.toString("base64")}}}const m=Buffer.isBuffer(d)?d:typeof d=="string"?Buffer.from(d,"base64"):Buffer.from(""),h=this.detectImageType(m);return f.debug(`Detected image MIME type: ${h}`),{inlineData:{mimeType:h,data:m.toString("base64")}}})),a=[{role:"user",parts:[{text:t},...i]}],l={responseModalities:["IMAGE","TEXT"]};f.debug("Starting image generation request",{model:r,contentParts:a[0].parts.length,responseModalities:l.responseModalities});let c=null,u="";try{const d=await s.models.generateContentStream({model:r,contents:a,config:l});for await(const m of d){f.debug("Received chunk",{hasCandidate:!!m.candidates?.[0],hasContent:!!m.candidates?.[0]?.content,hasParts:!!m.candidates?.[0]?.content?.parts});const h=m.candidates?.[0];if(h?.content?.parts)for(const g of h.content.parts){if("inlineData"in g&&g.inlineData?.data){const y=g.inlineData.data;c=y;const v=g.inlineData.mimeType||"image/png";f.info("Image generation successful",{model:r,mimeType:v,dataLength:y.length,responseTime:Date.now()-n});const _={content:`Generated image using ${r} (${v})`,imageOutput:{base64:y},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(_,e,n)}"text"in g&&g.text&&(u+=g.text,f.debug("Received text content",{text:g.text.substring(0,100)}))}}}catch(d){f.debug("Streaming failed, trying non-streaming approach",{error:d instanceof Error?d.message:String(d)})}if(!c){f.debug("Trying non-streaming approach");const m=(await s.models.generateContent({model:r,contents:a,config:l})).candidates?.[0];if(m?.content?.parts)for(const h of m.content.parts){if("inlineData"in h&&h.inlineData?.data){const g=h.inlineData.data;c=g;const y=h.inlineData.mimeType||"image/png";f.info("Image generation successful (non-streaming)",{model:r,mimeType:y,dataLength:g.length,responseTime:Date.now()-n});const v={content:`Generated image using ${r} (${y})`,imageOutput:{base64:g},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(v,e,n)}"text"in h&&h.text&&(u+=h.text)}}throw f.warn("No image data found in response",{model:r,prompt:t.substring(0,100),hasTextContent:!!u,textContent:u.substring(0,200)}),new _t(u||`Image generation completed but no image data was returned. This may indicate an issue with the model "${r}" or the prompt: "${t}". Please try again or use a different model.`,this.providerName)}catch(i){throw f.error("Image generation failed",{error:i instanceof Error?i.message:String(i),model:r,prompt:t.substring(0,100)}),this.handleProviderError(i)}}detectImageType(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}estimateTokenCount(e){return mr(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&OK(e.input),e.input?.files&&e.input.files.length>0)try{await NK(e,100*1024*1024,this.providerName)}catch(t){f.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await qS(e.input)}async executeStream(e,t){const r=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);const n=!!(t||e.output?.format==="json"||e.schema),o=!e.disableTools&&this.supportsTools()&&!n,s=e.tools||{};let i={...e,tools:s};const a=e.output?.format==="json"||e.schema,l=VV(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);return a&&l&&(f.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),i={...i,disableTools:!0,tools:{}}),o&&!i.disableTools&&i.tools&&Object.keys(i.tools).length>0&&f.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(i.tools??{}).length}),this.executeNativeGemini3Stream(i)}async executeNativeGemini3Stream(e){const t=e.model||this.modelName;return MUe({name:"neurolink.provider.stream",tracer:He.provider,attributes:{[Me.GEN_AI_SYSTEM]:"google-ai",[Me.GEN_AI_MODEL]:t,[Me.GEN_AI_OPERATION]:"stream",[Me.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=rc(o,this.providerName,"stream");{const i=this.getApiKey(),a=await U0(i,this.getBaseURL());f.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=[];l4(l,e.conversationMessages);const c=await K_t(e.input,e.input.text,"[GoogleAIStudio:stream]");l.push({role:"user",parts:c});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const O=$0(e.tools,"functionDeclarations");d=O,u=O.toolsConfig,f.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(N=>N.name)})}const m=!u&&(e.output?.format==="json"||!!e.schema),h=m&&e.schema?W_t(e.schema):void 0,g=q_t({...e,model:t,wantsJsonOutput:m,responseSchema:h},u),y=G_t(e.maxSteps),v=o1(e.abortSignal,s?.controller.signal),_=N0(),b=[],T=[];let k,A;const I=new Promise((O,N)=>{k=O,A=N}),P={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0};(async()=>{let O="",N=0,M=0,D=0,L=0,$=0;const U=D0(Kd("googleAiStudio",t));try{const j=d4({providerLabel:"GoogleAIStudio",maxSteps:y,toolFailureBreaker:{maxRetries:Sf},liveTools:e.tools??{},...d?{declarations:d}:{},buildRequest:be=>({model:t,contents:be,config:g,...v?{httpOptions:{signal:v}}:{}}),sendStep:async be=>a.models.generateContentStream(be),noteUsage:(be,ge)=>{U.noteUsage(be,ge)},planReclaim:(be,ge)=>{if(ge!==0&&!U.shouldStop())return;const H=[...be];if(hwt(H,t,U.projectedNextPromptTokens))return U.resetAfterReclaim(),{conversation:H}}}),B={...j,buildToolResultMessages:(be,ge,H,se)=>{$=se+1;for(const Q of ge.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":Q.name,"tool.step":$});O=ge.text||O;for(const Q of ge.toolCalls)b.push({toolName:Q.name,args:Q.args});for(const Q of H)T.push({name:Q.name,input:Q.args,output:Q.output});if(H.length>0){const Q=o4(ge.raw.rawResponseParts);zt(this.handleToolExecutionStorage(ge.toolCalls.map((me,$e)=>({toolName:me.name,args:me.args,...$e===0&&Q?{thoughtSignature:Q}:{},stepIndex:$})),H.map(me=>({toolName:me.name,output:me.output,stepIndex:$})),e,new Date),Cf,"tool storage write timed out").catch(me=>{f.warn("[GoogleAIStudio] Failed to store native tool executions",{error:me instanceof Error?me.message:String(me)})})}const ye=j.buildToolResultMessages(be,ge,H,se);try{const Q=ye[ye.length-1];U.noteAppendedChars(JSON.stringify(Q?.parts??[]).length)}catch{}return ye}},z=n4(d,e.tools),{stream:J,resultPromise:Y}=op(B,l,{tools:z,...v?{abortSignal:v}:{}}),ie=(async()=>{for await(const be of J)_.push(be)})();let ce;try{ce=await Y}catch(be){throw await ig(ie,"GoogleAIStudio"),f.error("[GoogleAIStudio] Native SDK error",be),this.handleProviderError(be)}await ie,N+=ce.usage.inputTokens,M+=ce.usage.outputTokens,D+=ce.usage.cacheReadTokens??0,L+=ce.usage.reasoningTokens??0;const re=ce.toolCalls.length===0||ce.finishReason!=="tool-calls",G=$>=y&&!re;if(G){const be=H_t("[GoogleAIStudio]",$,y,"",O);be&&_.push({content:be})}const K=Date.now()-n;P.responseTime=K,P.totalToolExecutions=b.length,r.setAttribute(Me.GEN_AI_INPUT_TOKENS,N),r.setAttribute(Me.GEN_AI_OUTPUT_TOKENS,M),r.setAttribute(Me.GEN_AI_FINISH_REASON,G?"max_steps":"stop");const Ce=Math.max(0,N-D);k({provider:this.providerName,model:t,tokenUsage:{input:Ce,output:M+L,total:Ce+D+M+L,...D>0?{cacheReadTokens:D}:{},...L>0?{reasoning:L}:{}},requestDuration:K,timestamp:new Date().toISOString()}),_.close()}catch(j){_.error(j),A(j)}finally{s?.cleanup()}})().catch(()=>{});const x={stream:_.iterable,provider:this.providerName,model:t,toolCalls:b,analytics:I,metadata:P};return Object.defineProperty(x,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>b.map(O=>O.toolName)}),Object.defineProperty(x,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>mM(T)}),x}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return gE({name:"neurolink.provider.generate",tracer:He.provider,attributes:{[Me.GEN_AI_SYSTEM]:"google-ai",[Me.GEN_AI_MODEL]:t,[Me.GEN_AI_OPERATION]:"generate",[Me.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=rc(o,this.providerName,"generate");try{const i=this.getApiKey(),a=await U0(i,this.getBaseURL());f.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=e.input?.text||e.prompt||"",c=[];l4(c,e.conversationMessages);const u=await K_t(e.input,l,"[GoogleAIStudio:generate]");c.push({role:"user",parts:u});let d,m;const h=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=VV(this.providerName,t,h,Object.keys(e.tools||{}).length);if(g&&y&&f.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),h&&!(g&&y)){const G=e.tools||{};if(Object.keys(G).length>0){const K=$0(G,"functionDeclarations");m=K,d=K.toolsConfig,f.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:d[0].functionDeclarations.length,toolNames:d[0].functionDeclarations.map(Ce=>Ce.name)})}}const v=!d&&g,_=v&&e.schema?W_t(e.schema):void 0,b=q_t({...e,model:t,wantsJsonOutput:v,responseSchema:_},d),T=o1(e.abortSignal,s?.controller.signal),k=G_t(e.maxSteps);let A="",I="",P=0,R=0,x=0,O=0;const N=[],M=[];let D=0;const L=D0(Kd("googleAiStudio",t)),$=d4({providerLabel:"GoogleAIStudio",maxSteps:k,toolFailureBreaker:{maxRetries:Sf},liveTools:e.tools??{},...m?{declarations:m}:{},buildRequest:G=>({model:t,contents:G,config:b,...T?{httpOptions:{signal:T}}:{}}),sendStep:async G=>a.models.generateContentStream(G),noteUsage:(G,K)=>{L.noteUsage(G,K)},planReclaim:(G,K)=>{if(K!==0&&!L.shouldStop())return;const Ce=[...G];if(hwt(Ce,t,L.projectedNextPromptTokens))return L.resetAfterReclaim(),{conversation:Ce}}}),U={...$,buildToolResultMessages:(G,K,Ce,be)=>{D=be+1;for(const H of K.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":H.name,"tool.step":D}),N.push({toolName:H.name,args:H.args});I=K.text||I;for(const H of Ce)M.push({name:H.name,input:H.args,output:H.output});if(Ce.length>0){const H=o4(K.raw.rawResponseParts);zt(this.handleToolExecutionStorage(K.toolCalls.map((se,ye)=>({toolName:se.name,args:se.args,...ye===0&&H?{thoughtSignature:H}:{},stepIndex:D})),Ce.map(se=>({toolName:se.name,output:se.output,stepIndex:D})),e,new Date),Cf,"tool storage write timed out").catch(se=>{f.warn("[GoogleAIStudio] Failed to store native tool executions",{error:se instanceof Error?se.message:String(se)})})}const ge=$.buildToolResultMessages(G,K,Ce,be);try{const H=ge[ge.length-1];L.noteAppendedChars(JSON.stringify(H?.parts??[]).length)}catch{}return ge}},j=n4(m,e.tools),{stream:B,resultPromise:z}=op(U,c,{tools:j,...T?{abortSignal:T}:{}}),J=(async()=>{for await(const G of B);})();let Y;try{Y=await z}catch(G){throw await ig(J,"GoogleAIStudio"),f.error("[GoogleAIStudio] Native SDK generate error",G),this.handleProviderError(G)}await J,P+=Y.usage.inputTokens,R+=Y.usage.outputTokens,x+=Y.usage.cacheReadTokens??0,O+=Y.usage.reasoningTokens??0,A=Y.text,A=H_t("[GoogleAIStudio]",D,k,A,I);const ie=Date.now()-n;r.setAttribute(Me.GEN_AI_INPUT_TOKENS,P),r.setAttribute(Me.GEN_AI_OUTPUT_TOKENS,R),r.setAttribute(Me.GEN_AI_FINISH_REASON,D>=k?"max_steps":"stop");const ce=Math.max(0,P-x),re={content:A,provider:this.providerName,model:t,usage:{input:ce,output:R+O,total:ce+x+R+O,...x>0?{cacheReadTokens:x}:{},...O>0?{reasoning:O}:{}},...O>0&&{reasoningTokens:O},responseTime:ie,toolsUsed:N.map(G=>G.toolName),toolExecutions:gM(e,M),enhancedWithTools:N.length>0};return this.enhanceResult(re,e,n)}finally{s?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(BE.some(u=>r.toLowerCase().startsWith(u.toLowerCase())))return f.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return f.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:r}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);const o=t.disableTools?{}:await this.getToolsForStream(t);let s={...t,tools:o};(t.output?.format==="json"||t.schema)&&s.tools&&Object.keys(s.tools).length>0&&!s.disableTools&&(f.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),s={...s,disableTools:!0,tools:{}}),!s.disableTools&&s.tools&&Object.keys(s.tools).length>0&&f.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length});const l=Date.now(),c=s.input?.text||s.prompt||"";try{let u=await gt({name:"neurolink.executeGeneration",tracer:He.provider,attributes:{[Me.GEN_AI_SYSTEM]:this.providerName,[Me.GEN_AI_MODEL]:r,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(s));return u=await this.synthesizeAIResponseIfNeeded(u,t),this.emitPipelineBGenerationEvent(r,u,l,!0,void 0,c),u}catch(u){throw this.emitPipelineBGenerationEvent(r,null,l,!1,u,c),u}}emitPipelineBGenerationEvent(e,t,r,n,o,s){const i=this.neurolink?.getEventEmitter();if(!i)return;const a=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),i.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),prompt:s||"",result:{content:t?.content||"",usage:a,model:e,provider:this.providerName,finishReason:n?"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async executeAudioStreamViaGeminiLive(e){const t=Date.now(),r=this.getApiKey();let n;try{n=await U0(r,this.getBaseURL())}catch{throw new sr("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}const o=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",s=[];let i=null,a=!1;const l=d=>{if(!a){if(d.type==="audio"&&i){const m=i;i=null,m({value:{type:"audio",audio:d.audio},done:!1});return}s.push(d)}},c=await n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async d=>{try{const m=d?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(m?.data){const g={data:Buffer.from(String(m.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};l({type:"audio",audio:g})}d?.serverContent?.interrupted}catch(m){l({type:"error",error:m})}},onerror:d=>{l({type:"error",error:d})},onclose:d=>{l({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}});return(async()=>{try{const d=e.input?.audio;if(!d){f.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}for await(const m of d.frames){if(!m||m.byteLength===0){try{c.sendInput?await c.sendInput({event:"flush"}):c.sendRealtimeInput&&await c.sendRealtimeInput({event:"flush"})}catch(y){f.debug("[GeminiLive] flush control failed (non-fatal)",{error:y instanceof Error?y.message:String(y)})}continue}const h=m.toString("base64"),g=`audio/pcm;rate=${d.sampleRateHz||16e3}`;await c.sendRealtimeInput?.({media:{data:h,mimeType:g}})}try{c.sendInput?await c.sendInput({event:"flush"}):c.sendRealtimeInput&&await c.sendRealtimeInput({event:"flush"})}catch(m){f.debug("[GeminiLive] final flush failed (non-fatal)",{error:m instanceof Error?m.message:String(m)})}}catch(d){l({type:"error",error:d})}})().catch(()=>{}),{stream:{[Symbol.asyncIterator](){return{async next(){if(s.length>0){const d=s.shift();if(!d)return{value:void 0,done:!0};if(d.type==="audio")return{value:{type:"audio",audio:d.audio},done:!1};if(d.type==="end")return a=!0,{value:void 0,done:!0};if(d.type==="error")throw a=!0,d.error instanceof Error?d.error:new Error(String(d.error))}return a?{value:void 0,done:!0}:await new Promise(d=>{i=d})}}}},provider:this.providerName,model:o,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";f.debug("Generating embedding",{provider:this.providerName,model:r,textLength:e.length});try{const n=this.getApiKey(),i=(await(await U0(n,this.getBaseURL())).models.embedContent({model:r,contents:[e]})).embeddings?.[0]?.values;if(!i)throw new _t("No embedding returned from Google AI",this.providerName);return f.debug("Embedding generated successfully",{provider:this.providerName,model:r,embeddingDimension:i.length}),i}catch(n){throw f.error("Embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,textLength:e.length}),this.handleProviderError(n)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";f.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=this.getApiKey(),i=((await(await U0(n,this.getBaseURL())).models.embedContent({model:r,contents:e})).embeddings||[]).map(a=>a.values||[]);return f.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:i.length,embeddingDimension:i[0]?.length}),i}catch(n){throw f.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}getApiKey(){const e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new sr("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){const e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}}}),gwt={};he(gwt,{GoogleAIStudioProvider:()=>fwt});var m4r=S({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";p4r()}});async function ip(e,t,r){const n=parseInt(e.headers.get("content-length")??"0",10);if(n>0&&n>t)throw new Error(`${r} download too large: ${n} bytes (max ${t})`);const o=Buffer.from(await e.arrayBuffer());if(o.length>t)throw new Error(`${r} download exceeded size cap after fetch: ${o.length} bytes (max ${t})`);return o}var ag,lg,cg,Rl=S({"src/lib/utils/sizeGuard.ts"(){"use strict";ag=256*1024*1024,lg=50*1024*1024,cg=25*1024*1024}}),h4r,f4r,g4r,y4r,m4,ywt,FJ,UJ,v4r,_4r,w4r,b4r,T4r=S({"node-stub:node:dns/promises"(){h4r=globalThis.crypto,f4r=globalThis.ReadableStream||class{},g4r=globalThis.URL,y4r=globalThis.URLSearchParams,m4=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},m4.custom=Symbol.for("nodejs.util.inspect.custom"),m4.colors={},m4.styles={},ywt=globalThis.TextDecoder,FJ=globalThis.TextEncoder,UJ=(e,t)=>t?.(null,"127.0.0.1",4),v4r=globalThis.performance||{now:()=>Date.now()},_4r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new FJ().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new FJ().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new ywt().decode(this)}},w4r=globalThis.clearTimeout,b4r=globalThis.clearInterval}}),E4r,S4r,C4r,k4r,h4,vwt,BJ,x4r,A4r,_wt,I4r,R4r,P4r=S({"node-stub:node:net"(){E4r=globalThis.crypto,S4r=globalThis.ReadableStream||class{},C4r=globalThis.URL,k4r=globalThis.URLSearchParams,h4=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},h4.custom=Symbol.for("nodejs.util.inspect.custom"),h4.colors={},h4.styles={},vwt=globalThis.TextDecoder,BJ=globalThis.TextEncoder,x4r=globalThis.performance||{now:()=>Date.now()},A4r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new BJ().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new BJ().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new vwt().decode(this)}},_wt=()=>0,I4r=globalThis.clearTimeout,R4r=globalThis.clearInterval}});function M4r(e){return e.length===0?null:/^0x[0-9a-f]+$/i.test(e)?parseInt(e.slice(2),16):e.length>1&&e.startsWith("0")&&/^0[0-7]+$/.test(e)?parseInt(e.slice(1),8):/^\d+$/.test(e)?parseInt(e,10):null}function f4(e){if(e.length===0)return null;const t=e.split(".");if(t.length===4){const r=t.map(M4r);return r.some(n=>n===null||n<0||n>255)?null:r.join(".")}if(t.length===1){let r;if(/^0x[0-9a-f]+$/i.test(e))r=parseInt(e.slice(2),16);else if(/^\d+$/.test(e))r=parseInt(e,10);else return null;return Number.isNaN(r)||r<0||r>4294967295?null:[r>>>24&255,r>>>16&255,r>>>8&255,r&255].join(".")}return null}function wwt(e){if(_wt(e)!==6)return null;const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);let r;if(t){const n=f4(t[1]);if(!n)return null;const o=n.split(".").map(a=>parseInt(a,10)),s=(o[0]<<8|o[1]).toString(16),i=(o[2]<<8|o[3]).toString(16);r=["0","0","0","0","0","ffff",s,i]}else{const[n,o=""]=e.split("::"),s=n?n.split(":"):[],i=o?o.split(":"):[],a=8-s.length-i.length;if(a<0)return null;r=[...s,...Array(a).fill("0"),...i]}return r.length!==8?null:r.map(n=>n.toLowerCase().padStart(4,"0")).join(":")}function bwt(e){const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return f4(t[1]);const r=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(r){const n=parseInt(r[1],16),o=parseInt(r[2],16);return Number.isNaN(n)||Number.isNaN(o)||n>65535||o>65535?null:[n>>8&255,n&255,o>>8&255,o&255].join(".")}return null}function Twt(e){const[t,r,n,o]=e.split(".").map(s=>parseInt(s,10));return(t<<24|r<<16|n<<8|o)>>>0}function tC(e){const t=Twt(e);for(const[r,n]of xwt){const o=Twt(r),s=n===0?0:4294967295<<32-n>>>0;if((t&s)===(o&s))return!0}return!1}function Ewt(e){return Awt.some(t=>t.length===39?e===t:e.startsWith(t))}function Swt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function Cwt(e){const t=f4(e);if(t)return tC(t)?`IPv4 ${e} \u2192 ${t} is in a blocked range`:null;if(e.includes(":")){const r=bwt(e);if(r)return tC(r)?`IPv4-mapped IPv6 ${e} \u2192 ${r} is in a blocked range`:null;const n=wwt(e);return n?Ewt(n)?`IPv6 ${e} is in a blocked range`:null:`IPv6 ${e} could not be parsed`}return"not-an-ip"}async function ug(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=Swt(t.hostname).toLowerCase(),n=Cwt(r);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);await kwt(e,r)}}async function kwt(e,t){const[r,n]=await Promise.allSettled([UJ(t,{family:4,all:!0}),UJ(t,{family:6,all:!0})]),o=[],s=[];let i=!1;if(r.status==="fulfilled"){i=!0;for(const a of r.value)o.push(a.address)}if(n.status==="fulfilled"){i=!0;for(const a of n.value)s.push(a.address)}if(!i){const a=r.status==="rejected"?r.reason instanceof Error?r.reason.message:String(r.reason):"ok",l=n.status==="rejected"?n.reason instanceof Error?n.reason.message:String(n.reason):"ok";throw new Error(`URL "${e}" rejected: hostname ${t} could not be resolved (A: ${a}; AAAA: ${l})`)}for(const a of o)if(tC(a))throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv4 in blocked range)`);for(const a of s){const l=Cwt(a.toLowerCase());if(l&&l!=="not-an-ip")throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv6 ${l})`)}return{v4:o,v6:s}}async function D4r(e){let t;try{t=new URL(e)}catch{throw new Error(`Invalid URL: "${e}"`)}if(t.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${t.protocol}//" in "${e}"`);const r=Swt(t.hostname).toLowerCase(),n=f4(r);if(n){if(tC(n))throw new Error(`URL "${e}" rejected: IPv4 ${r} \u2192 ${n} is in a blocked range`);return{url:e,ip:n,family:4,addresses:[{ip:n,family:4}]}}if(r.includes(":")){const l=bwt(r);if(l){if(tC(l))throw new Error(`URL "${e}" rejected: IPv4-mapped IPv6 ${r} \u2192 ${l} is in a blocked range`);return{url:e,ip:l,family:4,addresses:[{ip:l,family:4}]}}const c=wwt(r);if(!c)throw new Error(`URL "${e}" rejected: IPv6 ${r} could not be parsed`);if(Ewt(c))throw new Error(`URL "${e}" rejected: IPv6 ${r} is in a blocked range`);return{url:e,ip:r,family:6,addresses:[{ip:r,family:6}]}}const{v4:o,v6:s}=await kwt(e,r),i=[...o.map(l=>({ip:l,family:4})),...s.map(l=>({ip:l,family:6}))],a=i[0];if(!a)throw new Error(`URL "${e}" rejected: hostname ${r} resolved to an empty address set`);return{url:e,ip:a.ip,family:a.family,addresses:i}}var xwt,Awt,dg=S({"src/lib/utils/ssrfGuard.ts"(){"use strict";T4r(),P4r(),xwt=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.0.0.0",24],["192.168.0.0",16],["198.18.0.0",15],["100.100.100.200",32],["224.0.0.0",4],["240.0.0.0",4]],Awt=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]}}),Iwt={};he(Iwt,{createAnnotatedTool:()=>Pwt,filterToolsByAnnotations:()=>Owt,getAnnotationSummary:()=>Nwt,getToolSafetyLevel:()=>Dwt,inferAnnotations:()=>ap,isSafeToRetry:()=>jJ,mergeAnnotations:()=>zJ,requiresConfirmation:()=>Mwt,validateAnnotations:()=>Rwt});function ap(e){const t=e.name,r=e.description.toLowerCase(),n={},o=(c,u)=>new RegExp(`\\b${u}\\b`,"i").test(c)?!0:c.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(m=>m===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(c=>o(r,c)||o(t,c))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(c=>o(r,c)||o(t,c))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(c=>o(r,c)||o(t,c))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(c=>o(r,c)||o(t,c))?n.complexity="complex":r.length>100?n.complexity="medium":n.complexity="simple",n}function zJ(...e){const t={};for(const r of e)if(r){const n=t.tags?[...t.tags]:[];if(Object.assign(t,r),n.length>0||r.tags){const o=r.tags??[];t.tags=[...new Set([...n,...o])]}}return t}function Rwt(e){const t=[];if(e.readOnlyHint&&e.destructiveHint&&t.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),e.rateLimitHint!==void 0&&(e.rateLimitHint<0||!Number.isFinite(e.rateLimitHint))&&t.push("rateLimitHint must be a non-negative number"),e.estimatedDuration!==void 0&&(e.estimatedDuration<0||!Number.isFinite(e.estimatedDuration))&&t.push("estimatedDuration must be a non-negative number"),e.costHint!==void 0&&(e.costHint<0||!Number.isFinite(e.costHint))&&t.push("costHint must be a non-negative number"),e.tags){for(const r of e.tags)if(typeof r!="string"||r.length===0){t.push("All tags must be non-empty strings");break}}return t}function Pwt(e){const t=ap(e),r=zJ(t,e.annotations);return{...e,annotations:r}}function Mwt(e){return!!(e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)}function jJ(e){return!!(e.annotations?.idempotentHint||e.annotations?.readOnlyHint)}function Dwt(e){return e.annotations?.destructiveHint?"dangerous":e.annotations?.readOnlyHint?"safe":(e.annotations?.idempotentHint,"moderate")}function Owt(e,t){return e.filter(r=>{const n=r.annotations??{};return t(n)})}function Nwt(e){const t=[];return e.title&&t.push(e.title),e.readOnlyHint&&t.push("read-only"),e.destructiveHint&&t.push("DESTRUCTIVE"),e.idempotentHint&&t.push("idempotent"),e.requiresConfirmation&&t.push("requires confirmation"),e.complexity&&t.push(`${e.complexity} complexity`),e.estimatedDuration!==void 0&&t.push(`~${e.estimatedDuration}ms`),e.tags?.length&&t.push(`tags: ${e.tags.join(", ")}`),t.length>0?`[${t.join(" | ")}]`:"[no annotations]"}var rC=S({"src/lib/mcp/toolAnnotations.ts"(){"use strict"}}),qJ={};he(qJ,{TOOL_COMPATIBILITY:()=>WJ,batchConvertToMCP:()=>Fwt,batchConvertToNeuroLink:()=>Uwt,createToolFromFunction:()=>Bwt,mcpProtocolToolToServerTool:()=>Lwt,mcpToolToNeuroLink:()=>HJ,neuroLinkToolToMCP:()=>GJ,sanitizeToolName:()=>VJ,serverToolToMCPProtocol:()=>$wt,validateToolName:()=>zwt});function GJ(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=t,i=s?`${s}_${e.name}`:e.name,a=r?ap({name:e.name,description:e.description}):{},l={...n,...a};e.tags?.length&&(l.tags=[...new Set([...l.tags??[],...e.tags])]);const c=e.parameters??{type:"object",properties:{}},u=o?{...e.metadata}:{};return e.category&&(u.category=e.category),e.isAsync!==void 0&&(u.isAsync=e.isAsync),{name:i,description:e.description,inputSchema:c,annotations:l,execute:e.execute,metadata:u}}function HJ(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Lwt(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,s=e.annotations??{},i=n?ap({name:e.name,description:e.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function $wt(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function Fwt(e,t={}){return e.map(r=>GJ(r,t))}function Uwt(e,t={}){return e.map(r=>HJ(r,t))}function Bwt(e,t,r,n){const o=ap({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await zt(r(s,i),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function zwt(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function VJ(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var WJ,g4=S({"src/lib/mcp/toolConverter.ts"(){"use strict";rC(),yn(),WJ={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}}}),Ja,KJ,y4,JJ,iu,nC,YJ,jwt,qwt,ZJ,XJ,Gwt,Hwt,Vwt,Wwt,Kwt,QJ,Jwt,eY,tY,oC,rY,Ywt,Jm=S({"src/lib/providers/openaiChatCompletionsClient.ts"(){"use strict";cz(),g4(),Am(),Yi(),si(),Ja=e=>e.replace(/\/+$/,""),KJ=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,y4=(e,t)=>{if(e.every(o=>KJ.test(o)&&!t?.has(o)))return;const r=new Map,n=new Map;for(const o of e){let s=KJ.test(o)?o:VJ(o);if(n.has(s)||t?.has(s)){let i=2,a;do{const l=`_${i}`;a=`${s.slice(0,64-l.length)}${l}`,i++}while(n.has(a)||t?.has(a));s=a}r.set(o,s),n.set(s,o)}return{toWire:r,fromWire:n}},JJ=(e,t,r)=>{let n=0;for(const o of e){const s=typeof o.content=="string"?o.content:iu(o.content);n+=mr(s,r)+xl;const i=o.tool_calls;i&&(n+=mr(iu(i),r))}return t&&t.length>0&&(n+=mr(iu(t),r)),n},iu=e=>{try{return JSON.stringify(e??"")}catch{return String(e??"")}},nC=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return"{}"}},YJ=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e!="object")return String(e);const t=e;switch(t.type){case"text":return typeof t.value=="string"?t.value:iu(t.value);case"json":return iu(t.value);case"execution-denied":return`Tool execution denied${t.reason?`: ${t.reason}`:""}`;case"error-text":return typeof t.value=="string"?t.value:iu(t.value);case"error-json":return iu(t.value);case"content":return Array.isArray(t.value)?t.value.map(r=>r&&typeof r=="object"&&r.type==="text"?String(r.text??""):"").filter(r=>r.length>0).join(`
|
|
1063
|
-
`):"";default:return iu(e)}},jwt=e=>{if(typeof e=="string")return e.startsWith("data:")||/^https?:\/\//i.test(e)?e:`data:image/png;base64,${e}`;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return`data:image/png;base64,${Buffer.from(e).toString("base64")}`},qwt=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return iu(e);const t=[];for(const r of e){if(typeof r=="string"){t.push({type:"text",text:r});continue}if(!r||typeof r!="object")continue;const n=r;if(n.type==="text")t.push({type:"text",text:r.text??""});else if(n.type==="image"||n.type==="image_url"){const o=r.image??r.data??r.url,s=jwt(o);s&&t.push({type:"image_url",image_url:{url:s}})}}return t.length===1&&t[0].type==="text"?t[0].text:t},ZJ=(e,t)=>{const r=[];for(const n of e)switch(n.role){case"system":r.push({role:"system",content:typeof n.content=="string"?n.content:iu(n.content)});break;case"user":r.push({role:"user",content:qwt(n.content)});break;case"assistant":{const o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(const l of o)if(l&&typeof l=="object"){const c=l;if(c.type==="text")s.push({type:"text",text:l.text??""});else if(c.type==="tool-call"){const u=l,d=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:t?.get(d)??d,arguments:nC(u.input)}})}}else typeof l=="string"&&s.push({type:"text",text:l});const a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;r.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(const o of n.content){if(!o||typeof o!="object")continue;const s=o;s.type==="tool-result"&&r.push({role:"tool",tool_call_id:s.toolCallId??"",content:YJ(s.output)})}else typeof n.content=="string"&&r.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return r},XJ=(e,t)=>{const r=Object.entries(e);if(r.length===0)return;const n=[];for(const[o,s]of r){const i=s,a=i.inputSchema??i.parameters,l=a?hGe(js(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:t?.get(o)??o,...i.description?{description:i.description}:{},parameters:l}})}return n},Gwt=(e,t)=>{if(!e||e.length===0)return;const r=[];for(const n of e)n.type==="function"&&r.push({type:"function",function:{name:t?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:hGe(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return r.length>0?r:void 0},Hwt=(e,t)=>{switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:t?.get(e.toolName)??e.toolName}}}},Vwt=e=>e.type==="text"?{type:"text"}:e.schema?{type:"json_schema",json_schema:{name:e.name??"response",schema:e.schema,...e.description?{description:e.description}:{},strict:!0}}:{type:"json_object"},Wwt=(e,t)=>{if(e){if(e==="auto"||e==="none"||e==="required")return e;if(typeof e=="object"&&e!==null){const r=e;if(r.type==="tool"&&r.toolName)return{type:"function",function:{name:t?.get(r.toolName)??r.toolName}}}}},Kwt=e=>e.some(t=>{const r=t.content;return typeof r=="string"?/\bjson\b/i.test(r):Array.isArray(r)?r.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),QJ=e=>e.response_format?.type==="json_object"&&!Kwt(e.messages)?{...e,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...e.messages]}:e,Jwt=e=>/^(o\d|gpt-5)/i.test(e.replace(/^.*\//,"")),eY=e=>{const{modelId:t,messages:r,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=e,l={model:t,messages:r,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(l.max_tokens=n.maxTokens);const c=eu("openai-compatible",t,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return c.temperature!==void 0&&(l.temperature=c.temperature),c.topP!==void 0&&(l.top_p=c.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(l.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(l.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(l.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(l.stop=n.stopSequences),o&&(l.tools=o),s!==void 0&&(l.tool_choice=s),a&&(l.response_format=a),n.extraBody&&Object.assign(l,n.extraBody),l},tY=async(e,t,r)=>{const n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder;let s;const a=iz({onEvent:c=>{const u=c.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(y){s=y instanceof Error?y:new Error(String(y));return}d.usage&&(n.usage=d.usage),d.id&&!n.id&&(n.id=d.id),d.model&&!n.model&&(n.model=d.model);const m=d.choices?.[0];if(!m)return;const h=m.delta;h?.content&&(n.text+=h.content,t(h.content));const g=h?.reasoning_content||h?.reasoning;if(g&&(n.reasoning+=g,r?.(g)),h?.tool_calls)for(const y of h.tool_calls){let v=n.toolCalls.get(y.index);v?y.id&&(v.id=y.id):(v={id:y.id??`call_${y.index}_${Date.now()}`,name:y.function?.name??"",argsBuffered:""},n.toolCalls.set(y.index,v)),y.function?.name&&(v.name=y.function.name),y.function?.arguments&&(v.argsBuffered+=y.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),l=e.getReader();try{for(;;){const{done:c,value:u}=await l.read();if(c)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{l.releaseLock()}if(s)throw s;return n},oC=async(e,t,r)=>{let n,o;try{n=await r.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}const s=o?.error?.message??`OpenAI-compatible request failed with status ${r.status}`,i=new Error(s);return i.statusCode=r.status,i.responseHeaders=Object.fromEntries([...r.headers.entries()].filter(([a])=>{const l=a.toLowerCase();return l==="retry-after"||l.startsWith("x-ratelimit-")})),i.url=e,i.requestBody={model:t.model,stream:t.stream===!0,tool_count:t.tools?.length??0},n!==void 0&&(i.responseBody=n),i},rY=()=>{let e=()=>{};const t=new Promise(o=>{e=o});let r=()=>{};const n=new Promise(o=>{r=o});return{usagePromise:t,finishPromise:n,resolveUsage:e,resolveFinish:r}},Ywt=(e,t)=>{if(!e)return t;if(!t)return e;const r=(e.prompt_tokens_details?.cached_tokens??0)+(t.prompt_tokens_details?.cached_tokens??0),n=(e.completion_tokens_details?.reasoning_tokens??0)+(t.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(e.prompt_tokens??0)+(t.prompt_tokens??0),completion_tokens:(e.completion_tokens??0)+(t.completion_tokens??0),total_tokens:o(e)+o(t),...r>0?{prompt_tokens_details:{cached_tokens:r}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}}});function v4(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function O4r(e,t){let r=v4(e.content);return e.role==="assistant"&&e.tool_calls&&(r+=v4(e.tool_calls)),mr(r,t)+xl}function N4r(e,t){if(e.role!=="tool")return;const r=v4(e.content),n={maxBytes:nY,maxLines:oY};if(!u7e(r,n))return;const{preview:o}=pc(r,n);return mr(o,t)+xl}function L4r(e,t){return e.map(r=>{const n=O4r(r,t);if(r.role==="tool"){const o=N4r(r,t);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return r.role==="assistant"&&r.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function $4r(e){const{conversation:t,availableInputTokens:r,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=e,l=L4r(t,o),c=n+l.reduce((y,v)=>y+v.tokens,0);let u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));const d=RJ(l,{availableInputTokens:r,fixedOverheadTokens:n,calibration:u});if(!d.fire){a?.(c);return}const m=new Set(d.truncate),h=new Set(d.drop),g=[];for(let y=0;y<t.length;y++){if(h.has(y))continue;const v=t[y];if(m.has(y)&&v.role==="tool"){const{preview:_}=pc(v4(v.content),{maxBytes:nY,maxLines:oY});g.push({...v,content:_});continue}g.push(v)}if(h.size>0){let y=g.findIndex(v=>v.role==="tool"||v.role==="assistant"&&v.tool_calls);y<0&&(y=Math.min(1,g.length)),g.splice(y,0,{role:"user",content:Zwt})}return f.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:t.length,messagesAfter:g.length,toolOutputsTruncated:d.truncate.length,messagesDropped:d.drop.length,projectedTokens:d.projectedTokens,calibration:u}),a?.(d.projectedTokens),g}var nY,oY,Zwt,F4r=S({"src/lib/context/openaiCompatLoopGuard.ts"(){"use strict";si(),Pf(),PJ(),q(),nY=2048,oY=60,Zwt="[Earlier tool exchanges were removed to fit the context window.]"}});function sY(e){const t=aY(e);return t?lY.some(({patterns:r})=>r.some(n=>n.test(t))):!1}function U4r(e){const t=aY(e);if(!t)return null;for(const{provider:r,patterns:n}of lY)if(n.some(o=>o.test(t)))return r;return null}function iY(e){const t=aY(e);if(!t||t.length>2e3)return null;const r=t.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=t.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(r&&n)return{actualTokens:parseInt(r[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};const o=t.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){const a=t.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}const s=t.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};const i=t.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function aY(e){if(!e)return null;if(typeof e=="string")return e;if(e instanceof Error){const t=e.message,r=e?.cause;return r instanceof Error?`${t} ${r.message}`:t}if(typeof e=="object"){const t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const r=t.error;if(typeof r.message=="string")return r.message}}return null}var lY,Xwt=S({"src/lib/context/errorDetection.ts"(){"use strict";lY=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]}}),Ya,Qwt=S({"src/lib/context/errors.ts"(){"use strict";Ya=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}}}),ebt,cY,tbt=S({"src/lib/core/streamAnalytics.ts"(){"use strict";XE(),q(),JE(),Bd(),ebt=class{async collectUsage(e){try{const t=await e.usage;return t?t0(t):(f.debug("No usage data available from stream result"),rqe())}catch(t){return ac.isInstance(t)?f.debug("No output generated from stream \u2014 returning empty usage"):f.warn("Failed to collect usage from stream result",{error:t}),rqe()}}async collectMetadata(e){try{const[t,r]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:r}}catch(t){return ac.isInstance(t)?f.debug("No output generated from stream \u2014 returning default metadata"):f.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,r,n,o){try{const[s,i]=await Promise.all([this.collectUsage(r),this.collectMetadata(r)]),[a,l,c,u]=await Promise.all([Promise.resolve(r.text).catch(()=>""),Promise.resolve(r.finishReason).catch(()=>"error"),Promise.resolve(r.toolResults||[]).catch(()=>[]),Promise.resolve(r.toolCalls||[]).catch(()=>[])]);return r0(e,t,{usage:s,content:a,response:i,finishReason:l,toolResults:c,toolCalls:u},n,{...o,streamingMode:!0,responseId:i.id,finishReason:l})}catch(s){return f.error("Failed to create analytics from stream result",{provider:e,model:t,error:s instanceof Error?s.message:String(s)}),r0(e,t,{usage:{input:0,output:0,total:0}},n,{...o,streamingMode:!0,analyticsError:!0})}}cleanup(){const e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},cY=new ebt}});function rbt(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}var nbt=S({"src/lib/utils/toolChoice.ts"(){"use strict"}}),_4,Za,Pl=S({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";er(),Ju(),F4r(),Xwt(),Qwt(),vc(),es(),tbt(),no(),q(),_r(),Bd(),JK(),Ua(),OV(),nbt(),Wd(),ym(),sS(),Jm(),L0(),_4=512,Za=class extends Il{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=XHe(this.providerName,e);let s=t;o!==void 0&&(s===void 0||s>o)&&(s!==void 0&&f.debug(`${this.providerName}: clamping max_tokens ${s} to the advertised ${e} output ceiling ${o}`),s=o);const i=NIr(this.providerName,e);if(i!==void 0){const a=JJ(r,n,this.providerName),l=i-a-_4;if(l<=0)throw new Ya(`Estimated input (${a} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${i} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:a,availableTokens:Math.max(0,i-_4),stagesUsed:[],breakdown:{}});s!==void 0&&s>l&&(f.warn(`${this.providerName}: max_tokens ${s} cannot fit the ${e} window (${i}) with ~${a} input tokens \u2014 re-fitting to ${l}`),s=l)}return s}correctBodyAfterContextOverflow(e,t){if(!sY(t))return;const r=iY(t)??iY(t.responseBody);if(!r||r.budgetTokens<=0)return;ZHe(this.providerName,e.model,r.budgetTokens);const n=typeof e.max_tokens=="number"?e.max_tokens:r.requestedOutputTokens;if(n===void 0||r.actualTokens<=0)return;const o=r.budgetTokens-r.actualTokens-_4;if(!(o<=0||o>=n))return f.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:r.budgetTokens,inputTokens:r.actualTokens,previousMaxTokens:n,refitMaxTokens:o}),{...e,max_tokens:o}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ja(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{const t=`${Ja(this.config.baseURL)}/models`,n=await Bt()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return n.ok?!!(await n.json().catch(()=>null))?.data?.some(s=>typeof s?.id=="string"&&s.id.trim().length>0):!1}catch(t){return f.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:Xn(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){const e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;const e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{const r=await this.getAvailableModels();if(r.length>0)return this.resolvedModel=r[0],this.refreshHandlersForModel(r[0]),f.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){f.warn("Model auto-discovery failed, using fallback:",r)}return this.getFallbackModelName()}const t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){const t=this.getChatCompletionsURL(e),r=Bt(),n=this.getAuthHeaders.bind(this),o=this.providerName,s=this.adjustBuildBodyOptions.bind(this),i=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),l=this.adjustBodyAfter400.bind(this),c=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),m=this.useStreamingWireForGenerate.bind(this),h=g=>this.getTimeout(g??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async g=>{const y=y4((g.tools??[]).filter(z=>z.type==="function").map(z=>z.name)),v=ZJ(g.prompt,y?.toWire),_=Array.isArray(g.tools)&&g.tools.length>0,b=g.responseFormat&&!(_&&d())?i(Vwt(g.responseFormat),e):void 0,T=Gwt(g.tools,y?.toWire),k=u(e,g.maxOutputTokens,v,T),A=m(),I=QJ(a(eY({modelId:e,messages:v,options:s(e,{maxTokens:k,temperature:g.temperature,topP:g.topP,presencePenalty:g.presencePenalty,frequencyPenalty:g.frequencyPenalty,seed:g.seed,stopSequences:g.stopSequences}),tools:T,...g.toolChoice?{toolChoice:Hwt(g.toolChoice,y?.toWire)}:{},streaming:A,...b?{responseFormat:b}:{}}),e)),P=g.providerOptions?.neurolink?.timeoutMs,R=rc(typeof P=="number"?P:h(g),o,"generate"),{signal:x,dispose:O}=Dgr(g.abortSignal,R?.controller.signal);let N,M=A;try{let z=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(I),...x?{signal:x}:{}});if(!z.ok){const J=await oC(t,I,z),Y=J;let ie=z.status===400?(()=>{const ce=c(I,Y);return l(ce??I,Y)??ce})():void 0;if(!ie&&A&&z.status===400&&/stream/i.test(Y.responseBody??"")){const{stream:ce,stream_options:re,...G}=I;ie=G,M=!1}if(!ie)throw J;if(z=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(ie),...x?{signal:x}:{}}),!z.ok)throw await oC(t,ie,z)}if(M){if(!z.body)throw new Error(`${o}: streaming generate response had no body`);const J=R?z.body.pipeThrough(new TransformStream({transform(ie,ce){R.reset(),ce.enqueue(ie)}})):z.body,Y=await tY(J,()=>{});N={...Y.id?{id:Y.id}:{},...Y.model?{model:Y.model}:{},choices:[{index:0,message:{role:"assistant",content:Y.text.length>0?Y.text:null,...Y.reasoning?{reasoning:Y.reasoning}:{},...Y.toolCalls.size>0?{tool_calls:[...Y.toolCalls.values()].map(ie=>({id:ie.id,type:"function",function:{name:ie.name,arguments:ie.argsBuffered}}))}:{}},finish_reason:Y.finishReason??"stop"}],...Y.usage?{usage:Y.usage}:{}}}else N=await z.json()}finally{R?.cleanup(),O()}const D=N.choices?.[0],L=(typeof D?.message?.content=="string"?D.message.content:"")??"",$=[],U=D?.message?.reasoning_content||D?.message?.reasoning;typeof U=="string"&&U.length>0&&$.push({type:"reasoning",text:U}),L.length>0&&$.push({type:"text",text:L});for(const z of D?.message?.tool_calls??[])$.push({type:"tool-call",toolCallId:z.id,toolName:y?.fromWire.get(z.function.name)??z.function.name,input:z.function.arguments??""});const j=D?.finish_reason;return{content:$,finishReason:{unified:j==="length"?"length":j==="tool_calls"||j==="function_call"?"tool-calls":j==="content_filter"?"content-filter":"stop",raw:j??"stop"},usage:{inputTokens:{total:N.usage?.prompt_tokens,noCache:N.usage?.prompt_tokens!==void 0&&N.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,N.usage.prompt_tokens-N.usage.prompt_tokens_details.cached_tokens):N.usage?.prompt_tokens,cacheRead:N.usage?.prompt_tokens!==void 0&&N.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(N.usage.prompt_tokens_details.cached_tokens,N.usage.prompt_tokens):N.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:N.usage?.completion_tokens,text:N.usage?.completion_tokens!==void 0&&N.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,N.usage.completion_tokens-N.usage.completion_tokens_details.reasoning_tokens):N.usage?.completion_tokens,reasoning:N.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:I},response:{...N.id?{id:N.id}:{},...N.model?{modelId:N.model}:{},headers:{},body:N}}},doStream:()=>{throw new Error(`${o}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=rc(n,this.providerName,"stream"),s=new AbortController,i=zge([e.abortSignal,o?.controller.signal,s.signal]).signal;let a,l,c,u,d,m;try{a=await this.resolveModelName();const $=!e.disableTools&&this.supportsTools();l=$?e.tools||await this.getAllTools():{},c=$?y4(Object.keys(l)):void 0,u=$?XJ(l,c?.toWire):void 0,d=Wwt(rbt(e,l,$),c?.toWire);const U=await this.buildMessagesForStream(e);m=ZJ(U,c?.toWire)}catch($){throw o?.cleanup(),$}const h=this.getChatCompletionsURL(a),g=Bt(),y=e.maxSteps||Ai,v=this.neurolink?.getEventEmitter(),_=[],b=[],{usagePromise:T,finishPromise:k,resolveUsage:A,resolveFinish:I}=rY(),P=N0(),R=this.onStreamStart(a),x=this.runStreamLoop({maxSteps:y,modelId:a,url:h,fetchImpl:g,abortSignal:i,options:e,conversation:m,openAITools:u,openAIToolChoice:d,toolsRecord:l,toolNameFromWire:c?.fromWire,emitter:v,toolsUsed:_,toolExecutionSummaries:b,pushChunk:P.push,closeChannel:P.close,resolveUsage:A,resolveFinish:I});let O;const N=$=>{O=$};R?.onUsage&&T.then(R.onUsage).catch(()=>{}),R?.onFinish&&k.then($=>R.onFinish?.($,O)).catch(()=>{});const M=this.providerName,L={stream:async function*(){let $=0;try{for await(const U of P.iterable)"content"in U&&typeof U.content=="string"&&U.content.length>0&&$++,yield U;if(await x,$===0&&_.length===0){f.warn(`${M}: Stream produced no output \u2014 emitting enriched sentinel`);const U=new ac({message:"Stream produced no output"}),j=await tg(U,void 0,O);rg(j),yield j}}catch(U){if(ac.isInstance(U)){const B=await tg(U,void 0,O);rg(B),yield B;return}const j=await tg(U,void 0,O);throw rg(j),yield j,U}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:a,analytics:cY.createAnalytics(this.providerName,a,{textStream:(async function*(){})(),usage:T,finishReason:k},Date.now()-r,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:_,metadata:{startTime:r,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(L,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>mM(b.map($=>({toolName:$.toolName,input:$.input,output:$.output,duration:$.endTime.getTime()-$.startTime.getTime()})))}),x.finally(()=>o?.cleanup()).catch($=>{N($)}),L}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:l,openAIToolChoice:c,toolsRecord:u,toolNameFromWire:d,emitter:m,toolsUsed:h,toolExecutionSummaries:g,pushChunk:y,closeChannel:v,resolveUsage:_,resolveFinish:b}=e;let T=null,k;const A=()=>{const I=k?.prompt_tokens??0,P=k?.completion_tokens??0,R=Math.min(k?.prompt_tokens_details?.cached_tokens??0,I),x=Math.min(Math.max(0,k?.completion_tokens_details?.reasoning_tokens??0),P);return{promptTokens:I-R,completionTokens:P,totalTokens:k?.total_tokens||I+P,...R>0?{cacheReadTokens:R}:{},...x>0?{reasoningTokens:x}:{}}};try{let I=d,P,R;for(let x=0;x<t;x++){if(l){const M=new Set(l.map(L=>I?.get(L.function.name)??L.function.name)),D=Object.fromEntries(Object.entries(u).filter(([L])=>!M.has(L)));if(Object.keys(D).length>0){const L=y4(Object.keys(D),new Set(l.map($=>$.function.name)));if(L){I??=new Map;for(const[$,U]of L.fromWire)I.set($,U)}l.push(...XJ(D,L?.toWire)??[]),f.info(`${this.providerName}: ${Object.keys(D).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(D).join(", ")}`)}}const O=$4r({conversation:a,availableInputTokens:ou(this.providerName,r,i.maxTokens??void 0),fixedOverheadTokens:JJ([],l,this.providerName),provider:this.providerName,observedPromptTokens:P,previousSentEstimate:R,onSentEstimate:M=>{R=M}});O&&(a.length=0,a.push(...O));const N=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:l,openAIToolChoice:c,pushChunk:y});if(P=N.usage?.prompt_tokens,T=N.finishReason,N.usage&&(k=Ywt(k,N.usage)),N.toolCalls.size===0)break;await this.executeToolBatch({stepResult:N,conversation:a,toolsRecord:u,toolNameFromWire:I,emitter:m,toolsUsed:h,toolExecutionSummaries:g,options:i})}return _(A()),b(T??"stop"),v(),{finishReason:T??"stop",usage:k}}catch(I){throw f.error(`${this.providerName}: Stream error`,{error:I instanceof Error?I.message:String(I)}),_(A()),b("error"),v(),I}}async streamOneStep(e){const t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),r=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,n=QJ(this.adjustRequestBody(eY({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,r),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),o=async()=>{const i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(n),...e.abortSignal?{signal:e.abortSignal}:{}});if(!i.ok)throw await oC(e.url,n,i);return i};let s;try{s=await Mv(o,vt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(i){const a=i,l=a.statusCode===400?(()=>{const c=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(c??n,a)??c})():void 0;if(!l)throw a;if(s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(l),...e.abortSignal?{signal:e.abortSignal}:{}}),!s.ok)throw await oC(e.url,l,s)}if(!s.body)throw new Error(`${this.providerName}: stream response had no body`);return tY(s.body,i=>{e.pushChunk({content:i})},i=>{e.pushChunk({content:"",reasoning:i})})}async executeToolBatch(e){const{stepResult:t,conversation:r,toolsRecord:n,toolNameFromWire:o,emitter:s,toolsUsed:i,toolExecutionSummaries:a,options:l}=e,c=[];for(const[,d]of t.toolCalls)c.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});r.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:c});for(const[,d]of t.toolCalls){const m=new Date;let h;try{h=JSON.parse(d.argsBuffered||"{}")}catch{h=d.argsBuffered}let g,y;const v=o?.get(d.name)??d.name,_=n[v]??kV(n,v);if(s?.emit("tool:start",{toolName:v,toolCallId:d.id,input:h}),!_||typeof _.execute!="function")y=`Tool '${v}' is not registered.`,g={error:y};else try{g=await _.execute(h,{})}catch(T){y=T instanceof Error?T.message:String(T),g={error:y}}const b=new Date;i.push(v),a.push({toolCallId:d.id,toolName:v,input:h,output:g,...y?{error:y}:{},startTime:m,endTime:b}),r.push({role:"tool",tool_call_id:d.id,content:YJ(g)})}const u=a.slice(-t.toolCalls.size);DV(s,u.map(d=>({toolName:d.toolName,output:d.output,...d.error?{error:d.error}:{}})));try{await this.handleToolExecutionStorage(u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,output:d.output})),u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,output:d.output})),l,new Date)}catch(d){f.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{const e=`${Ja(this.config.baseURL)}/models`;f.debug(`Fetching available models from: ${e}`);const t=Bt(),r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)return f.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const s=await o.json();if(!s.data||!Array.isArray(s.data))return f.warn("Invalid models response format"),this.getFallbackModels();const i=s.data.map(a=>a.id).filter(Boolean);return f.shouldLog("debug")&&f.debug(`Discovered ${i.length} models:`,i),i.length>0?i:this.getFallbackModels()}catch(e){return f.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),uY,obt,sbt,ibt,abt,lbt,B4r=S({"src/lib/providers/openAI/client.ts"(){"use strict";er(),no(),yt(),q(),_r(),uc(),xi(),Yo(),Rl(),dg(),Ua(),Jm(),Pl(),ym(),uY="https://api.openai.com/v1",obt=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??uY;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ja(n.toString())}catch{}return r},sbt=()=>Bi(ycr()),ibt=()=>zi("OPENAI_MODEL","gpt-4o"),abt=vt.getTracer("neurolink.provider.openai"),lbt=class extends Za{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:sbt(),i=obt(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:i,apiKey:s}),f.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Xn(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return ibt()}formatProviderError(e){const t=e,r=t?.type&&typeof t.type=="string"?t.type:void 0,n=[{match:o=>o.statusCode===401||r==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(o.message),errorClass:sr,message:o=>/Incorrect API key|Invalid API key/i.test(o.message)?o.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:o=>mAe(o.error),errorClass:_t,message:"OpenAI quota exhausted \u2014 this will not resolve by retrying. Check your plan and billing details at https://platform.openai.com/account/billing"},{match:o=>o.statusCode===429||r==="rate_limit_error"||/rate limit/i.test(o.message),errorClass:Xs,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:co,message:o=>`Model not found: ${o.modelName}`},...Qo];return Ki(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=abt.startSpan("neurolink.provider.streamText",{kind:Br.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}});let r=!1;const n=()=>{r||(r=!0,t.end())};return{onUsage:o=>{t.setAttribute("gen_ai.usage.input_tokens",o.promptTokens+(o.cacheReadTokens??0)+(o.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",o.completionTokens);const s=Ga(this.providerName,e,{input:o.promptTokens,output:o.completionTokens,total:o.totalTokens,...o.cacheReadTokens?{cacheReadTokens:o.cacheReadTokens}:{},...o.cacheCreationTokens?{cacheCreationTokens:o.cacheCreationTokens}:{}});s&&s>0&&t.setAttribute("neurolink.cost",s)},onFinish:(o,s)=>{t.setAttribute("gen_ai.response.finish_reason",o||"unknown"),o==="error"&&t.setStatus({code:qe.ERROR,message:s instanceof Error?s.message:String(s??"stream error")}),n()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){const r=t||this.getDefaultEmbeddingModel();f.debug("Generating embedding",{provider:this.providerName,model:r,textLength:e.length});try{const[n]=await this.callEmbeddings(r,[e],"embed");return f.debug("Embedding generated successfully",{provider:this.providerName,model:r,embeddingDimension:n.length}),n}catch(n){throw f.error("Embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,textLength:e.length}),this.handleProviderError(n)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();f.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return f.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw f.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}async callEmbeddings(e,t,r){const n=`${Ja(this.config.baseURL)}/embeddings`,o=Bt(),s=rc(3e4,this.providerName,"generate");try{const i=await o(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...s?.controller.signal?{signal:s.controller.signal}:{}});if(!i.ok){const c=await i.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${i.status}`,d;if(c)try{const m=JSON.parse(c);m.error?.message&&(u=m.error.message),d=m.error?.type}catch{}throw Object.assign(new Error(u),{status:i.status,type:d})}const l=((await i.json()).data??[]).map(c=>c.embedding).filter(c=>Array.isArray(c));if(l.length===0)throw new _t(`OpenAI ${r} returned no embeddings`,this.providerName);return l}finally{s?.cleanup()}}async executeImageGeneration(e){const t=Date.now(),r=e.prompt??e.input?.text??"";if(!r.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");const n=e.model??this.modelName,o=Ja(this.config.baseURL??uY),s=e,i=s.size??this.aspectRatioToOpenAISize(s.aspectRatio,n),a=s.numberOfImages??1;let l;n==="gpt-image-1"||n.startsWith("dall-e-3")?l=1:n.startsWith("dall-e-2")?l=Math.min(Math.max(a,1),10):l=1;const u={model:n,prompt:r,n:l,size:i};n==="gpt-image-1"?s.quality&&(u.quality=s.quality):n.startsWith("dall-e-3")?(u.response_format="b64_json",s.quality&&(u.quality=s.quality),s.style&&(u.style=s.style)):u.response_format="b64_json";const d=12e4,m=new AbortController,h=setTimeout(()=>m.abort(),d);let g;try{g=await Bt()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:m.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:T}):T}finally{clearTimeout(h)}if(!g.ok){const T=await g.text();throw new Error(`OpenAI image generation failed: ${g.status} \u2014 ${T}`)}const v=(await g.json()).data?.[0];if(!v)throw new Error("OpenAI image generation returned no images");let _=v.b64_json;if(!_&&v.url){await ug(v.url);const T=Bt(),k=new AbortController,A=setTimeout(()=>k.abort(),6e4);let I;try{I=await T(v.url,{signal:k.signal})}catch(R){throw R instanceof Error&&R.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:R}):R}finally{clearTimeout(A)}if(!I.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${v.url} (${I.status})`);_=(await ip(I,cg,"OpenAI image fallback")).toString("base64")}if(!_)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const b=Date.now()-t;return f.info(`[OpenAIProvider] Generated image (${_.length} base64 chars) in ${b}ms \u2014 model ${n}`),{content:v.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:_}}}aspectRatioToOpenAISize(e,t){return t==="gpt-image-1"?e==="16:9"||e==="3:2"?"1536x1024":e==="9:16"||e==="2:3"?"1024x1536":"1024x1024":t.startsWith("dall-e-3")?e==="16:9"||e==="3:2"?"1792x1024":e==="9:16"||e==="2:3"?"1024x1792":"1024x1024":"1024x1024"}}}}),cbt={};he(cbt,{OpenAIProvider:()=>lbt});var z4r=S({"src/lib/providers/openAI/index.ts"(){"use strict";B4r()}});function je(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function V(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var Ml=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),sC,dY=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){sC=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return sC=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}}});function B0(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var iC,z0=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){iC=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}}}),pt,Qi,wc,j0,pY,ubt,mY,hY,fY,gY,yY,vY,_Y,wY,oo=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){z0(),pt=class extends Error{},Qi=class vce extends pt{constructor(t,r,n,o,s){super(`${vce.makeMessage(t,r,n)}`),this.status=t,this.headers=o,this.requestID=o?.get("request-id"),this.error=r,this.type=s??null}static makeMessage(t,r,n){const o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,r,n,o){if(!t||!o)return new j0({message:n,cause:iC(r)});const s=r,i=s?.error?.type;return t===400?new mY(t,s,n,o,i):t===401?new hY(t,s,n,o,i):t===403?new fY(t,s,n,o,i):t===404?new gY(t,s,n,o,i):t===409?new yY(t,s,n,o,i):t===422?new vY(t,s,n,o,i):t===429?new _Y(t,s,n,o,i):t>=500?new wY(t,s,n,o,i):new vce(t,s,n,o,i)}},wc=class extends Qi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},j0=class extends Qi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},pY=class extends j0{constructor({message:e}={}){super({message:e??"Request timed out."})}},ubt=class extends pt{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},mY=class extends Qi{},hY=class extends Qi{},fY=class extends Qi{},gY=class extends Qi{},yY=class extends Qi{},vY=class extends Qi{},_Y=class extends Qi{},wY=class extends Qi{}}});function bY(e){return typeof e!="object"?{}:e??{}}function dbt(e){if(!e)return!0;for(const t in e)return!1;return!0}function j4r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var pbt,mbt,Ea,TY,hbt,EY,lp=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){oo(),pbt=/^[a-z][a-z0-9+.-]*:/i,mbt=e=>pbt.test(e),Ea=e=>(Ea=Array.isArray,Ea(e)),TY=Ea,hbt=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new pt(`${e} must be an integer`);if(t<0)throw new pt(`${e} must be a positive integer`);return t},EY=e=>{try{return JSON.parse(e)}catch{return}}}}),Ym,aC=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){Ym=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const n=()=>{clearTimeout(o),r()},o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}}),cp,w4=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){cp="0.102.0"}});function q4r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function G4r(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const n=r.exec(navigator.userAgent);if(n){const o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${s}.${i}`}}}return null}var fbt,gbt,SY,CY,ybt,b4,kY=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){w4(),fbt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",gbt=()=>{const e=q4r();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":CY(Deno.build.os),"X-Stainless-Arch":SY(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":CY(globalThis.process.platform??"unknown"),"X-Stainless-Arch":SY(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=G4r();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},SY=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",CY=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),b4=()=>ybt??(ybt=gbt())}});function H4r(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function vbt(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function _bt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return vbt({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function xY(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){const r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function V4r(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var lC=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),wbt,W4r=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){wbt=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),AY,IY,RY,bbt,Tbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){AY="RFC3986",IY=e=>String(e),RY={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:IY},bbt="RFC1738"}});function K4r(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Ebt(e,t){if(Ea(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var T4,au,E4,Sbt,J4r=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){Tbt(),lp(),T4=(e,t)=>(T4=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),T4(e,t)),au=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),E4=1024,Sbt=(e,t,r,n,o)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=E4){const l=s.length>=E4?s.slice(a,a+E4):s,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===bbt&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=au[d];continue}if(d<2048){c[c.length]=au[192|d>>6]+au[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=au[224|d>>12]+au[128|d>>6&63]+au[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=au[240|d>>18]+au[128|d>>12&63]+au[128|d>>6&63]+au[128|d&63]}i+=c.join("")}return i}}});function Y4r(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function Cbt(e,t,r,n,o,s,i,a,l,c,u,d,m,h,g,y,v,_){let b=e,T=_,k=0,A=!1;for(;(T=T.get(S4))!==void 0&&!A;){const O=T.get(e);if(k+=1,typeof O<"u"){if(O===k)throw new RangeError("Cyclic object value");A=!0}typeof T.get(S4)>"u"&&(k=0)}if(typeof c=="function"?b=c(t,b):b instanceof Date?b=m?.(b):r==="comma"&&Ea(b)&&(b=Ebt(b,function(O){return O instanceof Date?m?.(O):O})),b===null){if(s)return l&&!y?l(t,Ts.encoder,v,"key",h):t;b=""}if(Y4r(b)||K4r(b)){if(l){const O=y?t:l(t,Ts.encoder,v,"key",h);return[g?.(O)+"="+g?.(l(b,Ts.encoder,v,"value",h))]}return[g?.(t)+"="+g?.(String(b))]}const I=[];if(typeof b>"u")return I;let P;if(r==="comma"&&Ea(b))y&&l&&(b=Ebt(b,l)),P=[{value:b.length>0?b.join(",")||null:void 0}];else if(Ea(c))P=c;else{const O=Object.keys(b);P=u?O.sort(u):O}const R=a?String(t).replace(/\./g,"%2E"):String(t),x=n&&Ea(b)&&b.length===1?R+"[]":R;if(o&&Ea(b)&&b.length===0)return x+"[]";for(let O=0;O<P.length;++O){const N=P[O],M=typeof N=="object"&&typeof N.value<"u"?N.value:b[N];if(i&&M===null)continue;const D=d&&a?N.replace(/\./g,"%2E"):N,L=Ea(b)?typeof r=="function"?r(x,D):x:x+(d?"."+D:"["+D+"]");_.set(e,k);const $=new WeakMap;$.set(S4,_),MY(I,Cbt(M,L,r,n,o,s,i,a,r==="comma"&&y&&Ea(b)?null:l,c,u,d,m,h,g,y,v,$))}return I}function Z4r(e=Ts){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||Ts.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=AY;if(typeof e.format<"u"){if(!T4(RY,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=RY[r];let o=Ts.filter;(typeof e.filter=="function"||Ea(e.filter))&&(o=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in PY?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=Ts.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:Ts.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:Ts.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:Ts.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ts.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?Ts.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Ts.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:Ts.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:Ts.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Ts.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Ts.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Ts.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ts.strictNullHandling}}function X4r(e,t={}){let r=e;const n=Z4r(t);let o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Ea(n.filter)&&(s=n.filter,o=s);const i=[];if(typeof r!="object"||r===null)return"";const a=PY[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const c=new WeakMap;for(let m=0;m<o.length;++m){const h=o[m];n.skipNulls&&r[h]===null||MY(i,Cbt(r[h],h,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=i.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var PY,MY,kbt,Ts,S4,Q4r=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){J4r(),Tbt(),lp(),PY={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},MY=function(e,t){Array.prototype.push.apply(e,Ea(t)?t:[t])},Ts={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Sbt,encodeValuesOnly:!1,format:AY,formatter:IY,indices:!1,serializeDate(e){return(kbt??(kbt=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},S4={}}});function eOr(e){return X4r(e,{arrayFormat:"brackets"})}var xbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){Q4r()}});function Abt(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new _n(`Invalid token endpoint base URL "${e}": ${n}`)}if(t.protocol==="https:")return;const r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(r==="localhost"||r==="127.0.0.1"||r==="::1")))throw new _n(`Refusing to send credential over non-https token endpoint "${e}"`)}async function Ibt(e,t){const r=await tOr(e);let n;try{n=JSON.parse(r)}catch{throw new _n(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,bc(r),t)}if(!n.access_token)throw new _n(`Token endpoint response missing access_token: ${JSON.stringify(bc(n))}`,e.status,bc(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new _n(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,bc(n),t);return n}function bc(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=k4?e:e.slice(0,k4)+`... <${e.length-k4} more chars>`}return JSON.stringify(bc(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))$bt.has(r)&&(t[r]=n);return t}return null}async function Rbt(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(to(),Jd));let n=e,o;try{n=await r.promises.realpath(e),o=await r.promises.stat(n)}catch{return}const s=o.mode&511;if(s&18)throw new _n(`Credentials file at ${n} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(s&36)throw new _n(`Credentials file at ${n} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&t(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Pbt(e,t){const r=await Promise.resolve().then(()=>(to(),Jd)),o=(await Promise.resolve().then(()=>(rr(),Pm))).dirname(e);await r.promises.mkdir(o,{recursive:!0,mode:448});const s=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const i=await r.promises.open(s,"w",384);try{await i.writeFile(JSON.stringify(t,null,2)),await i.sync()}finally{await i.close()}await r.promises.rename(s,e)}catch(i){throw await r.promises.unlink(s).catch(()=>{}),i}try{const i=await r.promises.open(o,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function tOr(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;for(;;){const{done:s,value:i}=await t.read();if(s)break;if(n+i.length>OY){const a=OY-n;a>0&&r.push(i.subarray(0,a)),await t.cancel();break}r.push(i),n+=i.length}let o;if(r.length===1)o=r[0];else{o=new Uint8Array(r.reduce((i,a)=>i+a.length,0));let s=0;for(const i of r)o.set(i,s),s+=i.length}return new TextDecoder("utf-8").decode(o)}var Mbt,Dbt,DY,cC,Obt,Nbt,C4,Lbt,OY,k4,$bt,_n,uC=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){oo(),Mbt="urn:ietf:params:oauth:grant-type:jwt-bearer",Dbt="refresh_token",DY="/v1/oauth/token",cC="oauth-2025-04-20",Obt="oidc-federation-2026-04-01",Nbt=120,C4=30,Lbt=5,OY=1<<20,k4=2e3,$bt=new Set(["error","error_description","error_uri"]),_n=class extends pt{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function pg(){return Math.floor(Date.now()/1e3)}var x4=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),Fbt,rOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){uC(),x4(),Fbt=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const r=t.expiresAt-pg();return r>Nbt?t.token:r>C4?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||pg()-this.lastAdvisoryError<Lbt||this.doRefresh().catch(e=>{this.lastAdvisoryError=pg(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}}}),Pr,A4=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Pr=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}});function nOr(e){let t=0;for(const o of e)t+=o.length;const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function NY(e){let t;return(Bbt??(t=new globalThis.TextEncoder,Bbt=t.encode.bind(t)))(e)}function Ubt(e){let t;return(zbt??(t=new globalThis.TextDecoder,zbt=t.decode.bind(t)))(e)}var Bbt,zbt,LY=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),oOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){oo(),LY()}});function dC(){}function I4(e,t,r){return!t||pC[e]>pC[r]?dC:t[e].bind(t)}function so(e){const t=e.logger,r=e.logLevel??"off";if(!t)return jbt;const n=FY.get(t);if(n&&n[0]===r)return n[1];const o={error:I4("error",t,r),warn:I4("warn",t,r),info:I4("info",t,r),debug:I4("debug",t,r)};return FY.set(t,[r,o]),o}var pC,$Y,jbt,FY,up,Zm=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){lp(),pC={off:0,error:200,warn:300,info:400,debug:500},$Y=(e,t,r)=>{if(e){if(j4r(pC,e))return e;so(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(pC))}`)}},jbt={error:dC,warn:dC,info:dC,debug:dC},FY=new WeakMap,up=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}}),qbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){lp(),oOr(),A4(),Zm(),dY(),aC(),xbt()}});function Gbt(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!Hbt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var UY,Hbt,Vbt,Wbt,R4,Kbt,BY,Jbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){kY(),qbt(),UY="1.0",Hbt=/^[A-Za-z0-9_.-]+$/,Vbt=async e=>{var t,r;const n=await R4();if(n===null)return null;const o=e??await BY();if(o===null)return null;Gbt(o);const s=await Promise.resolve().then(()=>(to(),Jd)),a=(await Promise.resolve().then(()=>(rr(),Pm))).join(n,"configs",`${o}.json`);let l;try{l=await s.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);l=null}if(l===null){const d=Pr("ANTHROPIC_ORGANIZATION_ID"),m=Pr("ANTHROPIC_IDENTITY_TOKEN_FILE"),h=Pr("ANTHROPIC_FEDERATION_RULE_ID");return h&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Pr("ANTHROPIC_WORKSPACE_ID"),base_url:Pr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:h,service_account_id:Pr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Pr("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=Pr("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=Pr("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=Pr("ANTHROPIC_BASE_URL")),(t=c.authentication).scope??(t.scope=Pr("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){const d=Pr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(c.authentication.identity_token={source:"file",path:d})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=Pr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=c.authentication).service_account_id??(r.service_account_id=Pr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},Wbt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await R4();if(!r)return null;const n=t??await BY();return n?(Gbt(n),(await Promise.resolve().then(()=>(rr(),Pm))).join(r,"credentials",`${n}.json`)):null},R4=async()=>{if(!Kbt())return null;const e=await Promise.resolve().then(()=>(rr(),Pm)),t=Pr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(b4()["X-Stainless-OS"]==="Windows"){const s=Pr("APPDATA");if(s)return e.join(s,"Anthropic");const i=Pr("USERPROFILE");return i?e.join(i,"AppData","Roaming","Anthropic"):null}const n=Pr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Pr("HOME");return o?e.join(o,".config","anthropic"):null},Kbt=()=>{const e=b4()["X-Stainless-Runtime"];return e==="node"||e==="deno"},BY=async()=>{const e=await R4();if(!e)return null;const t=Pr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(to(),Jd)),o=(await Promise.resolve().then(()=>(rr(),Pm))).join(e,"active_config");try{return(await r.promises.readFile(o,"utf-8")).trim()||"default"}catch(s){if(s?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${s}`);return"default"}}}});function Ybt(e){if(!e)throw new pt("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(to(),Jd));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new pt(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new pt(`Identity token file at ${e} is empty`);return n}}function sOr(e){if(!e)throw new pt("Identity token value is empty");return()=>e}var iOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){oo()}});function aOr(e){return async()=>{Abt(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new _n(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:Mbt,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(r.service_account_id=e.serviceAccountId),e.workspaceId&&(r.workspace_id=e.workspaceId);const n=`${e.baseURL}${DY}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${cC},${Obt}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${cp} oidcFederationProvider`},body:JSON.stringify(r)})}catch(l){throw new _n(`Failed to reach token endpoint ${n}: ${l}`)}const s=o.headers.get("Request-Id");if(!o.ok){const l=await o.text().catch(()=>""),c=bc(l);let u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new _n(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${c}${u}`,o.status,c,s)}const i=await Ibt(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new _n(`Token endpoint response missing required fields: ${JSON.stringify(bc(i))}`,o.status,bc(i),s);return{token:i.access_token,expiresAt:pg()+a}}}var lOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){uC(),x4(),w4()}});function cOr(e){return async t=>{const r=await Promise.resolve().then(()=>(to(),Jd));await Rbt(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(v){throw new _n(`Credentials file not found at ${e.credentialsPath}: ${v}`)}let o;try{o=JSON.parse(n)}catch(v){throw new _n(`Credentials file at ${e.credentialsPath} is not valid JSON: ${v}`)}const s=o.access_token;if(!s)throw new _n(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const i=o.expires_at;if(!t?.forceRefresh&&(i==null||pg()<i-C4))return{token:s,expiresAt:i??null};const a=o.refresh_token;if(!e.clientId||!a)throw new _n(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);Abt(e.baseURL);const l={grant_type:Dbt,refresh_token:a,client_id:e.clientId},c=`${e.baseURL}${DY}`;let u;try{u=await e.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":cC,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${cp} userOAuthProvider`},body:JSON.stringify(l)})}catch(v){throw new _n(`User OAuth refresh failed to reach token endpoint: ${v}`)}const d=u.headers.get("Request-Id");if(!u.ok){const v=await u.text().catch(()=>"");throw new _n(`User OAuth refresh failed (HTTP ${u.status}): ${bc(v)}`,u.status,bc(v),d)}const m=await Ibt(u,d),h=Number(m.expires_in);if(!Number.isFinite(h))throw new _n(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(bc(m))}`,u.status,bc(m),d);const g=pg()+h,y=m.refresh_token||a;return await Pbt(e.credentialsPath,{...o,version:UY,type:"oauth_token",access_token:m.access_token,expires_at:g,refresh_token:y}),{token:m.access_token,expiresAt:g}}}var uOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){Jbt(),uC(),x4(),w4()}});function Zbt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=pOr(e,r,n,t),s={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(s["anthropic-workspace-id"]=e.workspace_id),{provider:o,extraHeaders:s,baseURL:e.base_url||void 0}}async function dOr(e,t){const r=await Vbt(t);if(!r)return null;const{config:n,fromFile:o}=r,s=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await Wbt(n,t)??void 0}};return Zbt(s,e)}function pOr(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,s=mOr(o);if(!s)throw new _n("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new _n("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new _n("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const i=aOr({identityTokenProvider:s,federationRuleId:o.federation_rule_id,organizationId:e.organization_id,serviceAccountId:o.service_account_id,workspaceId:e.workspace_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent});return t?hOr(i,t,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!t)throw new _n("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return cOr({credentialsPath:t,clientId:e.authentication.client_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const o=e.authentication.type;throw new _n(`authentication.type "${o}" is not a known authentication type`)}}}function mOr(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new _n(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new _n('identity_token.source "file" requires a non-empty path');return Ybt(e.identity_token.path)}const t=Pr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return Ybt(t);const r=Pr("ANTHROPIC_IDENTITY_TOKEN");return r?sOr(r):null}function hOr(e,t,r,n){return async o=>{const s=await Promise.resolve().then(()=>(to(),Jd));await Rbt(t,n);let i;try{const l=await s.promises.readFile(t,"utf-8");i=JSON.parse(l);const c=i?.access_token;if(c&&!o?.forceRefresh){const u=i?.expires_at;if(u==null||pg()<u-C4)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&r?.(l)}const a=await e(o);try{await Pbt(t,{...i??{},version:UY,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){r?.(l)}return a}}var fOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){A4(),Jbt(),uC(),x4(),iOr(),lOr(),uOr()}});function gOr(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function yOr(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var Dl,Ol,q0,Xbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){Ml(),LY(),q0=class{constructor(){Dl.set(this,void 0),Ol.set(this,void 0),je(this,Dl,new Uint8Array,"f"),je(this,Ol,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?NY(e):e;je(this,Dl,nOr([V(this,Dl,"f"),t]),"f");const r=[];let n;for(;(n=gOr(V(this,Dl,"f"),V(this,Ol,"f")))!=null;){if(n.carriage&&V(this,Ol,"f")==null){je(this,Ol,n.index,"f");continue}if(V(this,Ol,"f")!=null&&(n.index!==V(this,Ol,"f")+1||n.carriage)){r.push(Ubt(V(this,Dl,"f").subarray(0,V(this,Ol,"f")-1))),je(this,Dl,V(this,Dl,"f").subarray(V(this,Ol,"f")),"f"),je(this,Ol,null,"f");continue}const o=V(this,Ol,"f")!==null?n.preceding-1:n.preceding,s=Ubt(V(this,Dl,"f").subarray(0,o));r.push(s),je(this,Dl,V(this,Dl,"f").subarray(n.index),"f"),je(this,Ol,null,"f")}return r}flush(){return V(this,Dl,"f").length?this.decode(`
|
|
1063
|
+
`):"";default:return iu(e)}},jwt=e=>{if(typeof e=="string")return e.startsWith("data:")||/^https?:\/\//i.test(e)?e:`data:image/png;base64,${e}`;if(e instanceof URL)return e.toString();if(e instanceof Uint8Array)return`data:image/png;base64,${Buffer.from(e).toString("base64")}`},qwt=e=>{if(typeof e=="string")return e;if(!Array.isArray(e))return iu(e);const t=[];for(const r of e){if(typeof r=="string"){t.push({type:"text",text:r});continue}if(!r||typeof r!="object")continue;const n=r;if(n.type==="text")t.push({type:"text",text:r.text??""});else if(n.type==="image"||n.type==="image_url"){const o=r.image??r.data??r.url,s=jwt(o);s&&t.push({type:"image_url",image_url:{url:s}})}}return t.length===1&&t[0].type==="text"?t[0].text:t},ZJ=(e,t)=>{const r=[];for(const n of e)switch(n.role){case"system":r.push({role:"system",content:typeof n.content=="string"?n.content:iu(n.content)});break;case"user":r.push({role:"user",content:qwt(n.content)});break;case"assistant":{const o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(const l of o)if(l&&typeof l=="object"){const c=l;if(c.type==="text")s.push({type:"text",text:l.text??""});else if(c.type==="tool-call"){const u=l,d=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:t?.get(d)??d,arguments:nC(u.input)}})}}else typeof l=="string"&&s.push({type:"text",text:l});const a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;r.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(const o of n.content){if(!o||typeof o!="object")continue;const s=o;s.type==="tool-result"&&r.push({role:"tool",tool_call_id:s.toolCallId??"",content:YJ(s.output)})}else typeof n.content=="string"&&r.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return r},XJ=(e,t)=>{const r=Object.entries(e);if(r.length===0)return;const n=[];for(const[o,s]of r){const i=s,a=i.inputSchema??i.parameters,l=a?hGe(js(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:t?.get(o)??o,...i.description?{description:i.description}:{},parameters:l}})}return n},Gwt=(e,t)=>{if(!e||e.length===0)return;const r=[];for(const n of e)n.type==="function"&&r.push({type:"function",function:{name:t?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:hGe(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return r.length>0?r:void 0},Hwt=(e,t)=>{switch(e.type){case"auto":case"none":case"required":return e.type;case"tool":return{type:"function",function:{name:t?.get(e.toolName)??e.toolName}}}},Vwt=e=>e.type==="text"?{type:"text"}:e.schema?{type:"json_schema",json_schema:{name:e.name??"response",schema:e.schema,...e.description?{description:e.description}:{},strict:!0}}:{type:"json_object"},Wwt=(e,t)=>{if(e){if(e==="auto"||e==="none"||e==="required")return e;if(typeof e=="object"&&e!==null){const r=e;if(r.type==="tool"&&r.toolName)return{type:"function",function:{name:t?.get(r.toolName)??r.toolName}}}}},Kwt=e=>e.some(t=>{const r=t.content;return typeof r=="string"?/\bjson\b/i.test(r):Array.isArray(r)?r.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),QJ=e=>e.response_format?.type==="json_object"&&!Kwt(e.messages)?{...e,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...e.messages]}:e,Jwt=e=>/^(o\d|gpt-5)/i.test(e.replace(/^.*\//,"")),eY=e=>{const{modelId:t,messages:r,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=e,l={model:t,messages:r,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(l.max_tokens=n.maxTokens);const c=eu("openai-compatible",t,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return c.temperature!==void 0&&(l.temperature=c.temperature),c.topP!==void 0&&(l.top_p=c.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(l.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(l.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(l.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(l.stop=n.stopSequences),o&&(l.tools=o),s!==void 0&&o&&o.length>0&&(l.tool_choice=s),a&&(l.response_format=a),n.extraBody&&Object.assign(l,n.extraBody),l},tY=async(e,t,r)=>{const n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder;let s;const a=iz({onEvent:c=>{const u=c.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(y){s=y instanceof Error?y:new Error(String(y));return}d.usage&&(n.usage=d.usage),d.id&&!n.id&&(n.id=d.id),d.model&&!n.model&&(n.model=d.model);const m=d.choices?.[0];if(!m)return;const h=m.delta;h?.content&&(n.text+=h.content,t(h.content));const g=h?.reasoning_content||h?.reasoning;if(g&&(n.reasoning+=g,r?.(g)),h?.tool_calls)for(const y of h.tool_calls){let v=n.toolCalls.get(y.index);v?y.id&&(v.id=y.id):(v={id:y.id??`call_${y.index}_${Date.now()}`,name:y.function?.name??"",argsBuffered:""},n.toolCalls.set(y.index,v)),y.function?.name&&(v.name=y.function.name),y.function?.arguments&&(v.argsBuffered+=y.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),l=e.getReader();try{for(;;){const{done:c,value:u}=await l.read();if(c)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{l.releaseLock()}if(s)throw s;return n},oC=async(e,t,r)=>{let n,o;try{n=await r.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}const s=o?.error?.message??`OpenAI-compatible request failed with status ${r.status}`,i=new Error(s);return i.statusCode=r.status,i.responseHeaders=Object.fromEntries([...r.headers.entries()].filter(([a])=>{const l=a.toLowerCase();return l==="retry-after"||l.startsWith("x-ratelimit-")})),i.url=e,i.requestBody={model:t.model,stream:t.stream===!0,tool_count:t.tools?.length??0},n!==void 0&&(i.responseBody=n),i},rY=()=>{let e=()=>{};const t=new Promise(o=>{e=o});let r=()=>{};const n=new Promise(o=>{r=o});return{usagePromise:t,finishPromise:n,resolveUsage:e,resolveFinish:r}},Ywt=(e,t)=>{if(!e)return t;if(!t)return e;const r=(e.prompt_tokens_details?.cached_tokens??0)+(t.prompt_tokens_details?.cached_tokens??0),n=(e.completion_tokens_details?.reasoning_tokens??0)+(t.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(e.prompt_tokens??0)+(t.prompt_tokens??0),completion_tokens:(e.completion_tokens??0)+(t.completion_tokens??0),total_tokens:o(e)+o(t),...r>0?{prompt_tokens_details:{cached_tokens:r}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}}});function v4(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function O4r(e,t){let r=v4(e.content);return e.role==="assistant"&&e.tool_calls&&(r+=v4(e.tool_calls)),mr(r,t)+xl}function N4r(e,t){if(e.role!=="tool")return;const r=v4(e.content),n={maxBytes:nY,maxLines:oY};if(!u7e(r,n))return;const{preview:o}=pc(r,n);return mr(o,t)+xl}function L4r(e,t){return e.map(r=>{const n=O4r(r,t);if(r.role==="tool"){const o=N4r(r,t);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return r.role==="assistant"&&r.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function $4r(e){const{conversation:t,availableInputTokens:r,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=e,l=L4r(t,o),c=n+l.reduce((y,v)=>y+v.tokens,0);let u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));const d=RJ(l,{availableInputTokens:r,fixedOverheadTokens:n,calibration:u});if(!d.fire){a?.(c);return}const m=new Set(d.truncate),h=new Set(d.drop),g=[];for(let y=0;y<t.length;y++){if(h.has(y))continue;const v=t[y];if(m.has(y)&&v.role==="tool"){const{preview:_}=pc(v4(v.content),{maxBytes:nY,maxLines:oY});g.push({...v,content:_});continue}g.push(v)}if(h.size>0){let y=g.findIndex(v=>v.role==="tool"||v.role==="assistant"&&v.tool_calls);y<0&&(y=Math.min(1,g.length)),g.splice(y,0,{role:"user",content:Zwt})}return f.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:t.length,messagesAfter:g.length,toolOutputsTruncated:d.truncate.length,messagesDropped:d.drop.length,projectedTokens:d.projectedTokens,calibration:u}),a?.(d.projectedTokens),g}var nY,oY,Zwt,F4r=S({"src/lib/context/openaiCompatLoopGuard.ts"(){"use strict";si(),Pf(),PJ(),q(),nY=2048,oY=60,Zwt="[Earlier tool exchanges were removed to fit the context window.]"}});function sY(e){const t=aY(e);return t?lY.some(({patterns:r})=>r.some(n=>n.test(t))):!1}function U4r(e){const t=aY(e);if(!t)return null;for(const{provider:r,patterns:n}of lY)if(n.some(o=>o.test(t)))return r;return null}function iY(e){const t=aY(e);if(!t||t.length>2e3)return null;const r=t.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=t.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(r&&n)return{actualTokens:parseInt(r[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};const o=t.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){const a=t.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}const s=t.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};const i=t.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function aY(e){if(!e)return null;if(typeof e=="string")return e;if(e instanceof Error){const t=e.message,r=e?.cause;return r instanceof Error?`${t} ${r.message}`:t}if(typeof e=="object"){const t=e;if(typeof t.message=="string")return t.message;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const r=t.error;if(typeof r.message=="string")return r.message}}return null}var lY,Xwt=S({"src/lib/context/errorDetection.ts"(){"use strict";lY=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]}}),Ya,Qwt=S({"src/lib/context/errors.ts"(){"use strict";Ya=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}}}),ebt,cY,tbt=S({"src/lib/core/streamAnalytics.ts"(){"use strict";XE(),q(),JE(),Bd(),ebt=class{async collectUsage(e){try{const t=await e.usage;return t?t0(t):(f.debug("No usage data available from stream result"),rqe())}catch(t){return ac.isInstance(t)?f.debug("No output generated from stream \u2014 returning empty usage"):f.warn("Failed to collect usage from stream result",{error:t}),rqe()}}async collectMetadata(e){try{const[t,r]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:r}}catch(t){return ac.isInstance(t)?f.debug("No output generated from stream \u2014 returning default metadata"):f.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,r,n,o){try{const[s,i]=await Promise.all([this.collectUsage(r),this.collectMetadata(r)]),[a,l,c,u]=await Promise.all([Promise.resolve(r.text).catch(()=>""),Promise.resolve(r.finishReason).catch(()=>"error"),Promise.resolve(r.toolResults||[]).catch(()=>[]),Promise.resolve(r.toolCalls||[]).catch(()=>[])]);return r0(e,t,{usage:s,content:a,response:i,finishReason:l,toolResults:c,toolCalls:u},n,{...o,streamingMode:!0,responseId:i.id,finishReason:l})}catch(s){return f.error("Failed to create analytics from stream result",{provider:e,model:t,error:s instanceof Error?s.message:String(s)}),r0(e,t,{usage:{input:0,output:0,total:0}},n,{...o,streamingMode:!0,analyticsError:!0})}}cleanup(){const e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},cY=new ebt}});function rbt(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}var nbt=S({"src/lib/utils/toolChoice.ts"(){"use strict"}}),_4,Za,Pl=S({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";er(),Ju(),F4r(),Xwt(),Qwt(),vc(),es(),tbt(),no(),q(),_r(),Bd(),JK(),Ua(),OV(),nbt(),Wd(),ym(),sS(),Jm(),L0(),_4=512,Za=class extends Il{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=XHe(this.providerName,e);let s=t;o!==void 0&&(s===void 0||s>o)&&(s!==void 0&&f.debug(`${this.providerName}: clamping max_tokens ${s} to the advertised ${e} output ceiling ${o}`),s=o);const i=NIr(this.providerName,e);if(i!==void 0){const a=JJ(r,n,this.providerName),l=i-a-_4;if(l<=0)throw new Ya(`Estimated input (${a} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${i} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:a,availableTokens:Math.max(0,i-_4),stagesUsed:[],breakdown:{}});s!==void 0&&s>l&&(f.warn(`${this.providerName}: max_tokens ${s} cannot fit the ${e} window (${i}) with ~${a} input tokens \u2014 re-fitting to ${l}`),s=l)}return s}correctBodyAfterContextOverflow(e,t){if(!sY(t))return;const r=iY(t)??iY(t.responseBody);if(!r||r.budgetTokens<=0)return;ZHe(this.providerName,e.model,r.budgetTokens);const n=typeof e.max_tokens=="number"?e.max_tokens:r.requestedOutputTokens;if(n===void 0||r.actualTokens<=0)return;const o=r.budgetTokens-r.actualTokens-_4;if(!(o<=0||o>=n))return f.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:r.budgetTokens,inputTokens:r.actualTokens,previousMaxTokens:n,refitMaxTokens:o}),{...e,max_tokens:o}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ja(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{const t=`${Ja(this.config.baseURL)}/models`,n=await Bt()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return n.ok?!!(await n.json().catch(()=>null))?.data?.some(s=>typeof s?.id=="string"&&s.id.trim().length>0):!1}catch(t){return f.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:Xn(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){const e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;const e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{const r=await this.getAvailableModels();if(r.length>0)return this.resolvedModel=r[0],this.refreshHandlersForModel(r[0]),f.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){f.warn("Model auto-discovery failed, using fallback:",r)}return this.getFallbackModelName()}const t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){const t=this.getChatCompletionsURL(e),r=Bt(),n=this.getAuthHeaders.bind(this),o=this.providerName,s=this.adjustBuildBodyOptions.bind(this),i=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),l=this.adjustBodyAfter400.bind(this),c=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),m=this.useStreamingWireForGenerate.bind(this),h=g=>this.getTimeout(g??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async g=>{const y=y4((g.tools??[]).filter(z=>z.type==="function").map(z=>z.name)),v=ZJ(g.prompt,y?.toWire),_=Array.isArray(g.tools)&&g.tools.length>0,b=g.responseFormat&&!(_&&d())?i(Vwt(g.responseFormat),e):void 0,T=Gwt(g.tools,y?.toWire),k=u(e,g.maxOutputTokens,v,T),A=m(),I=QJ(a(eY({modelId:e,messages:v,options:s(e,{maxTokens:k,temperature:g.temperature,topP:g.topP,presencePenalty:g.presencePenalty,frequencyPenalty:g.frequencyPenalty,seed:g.seed,stopSequences:g.stopSequences}),tools:T,...g.toolChoice?{toolChoice:Hwt(g.toolChoice,y?.toWire)}:{},streaming:A,...b?{responseFormat:b}:{}}),e)),P=g.providerOptions?.neurolink?.timeoutMs,R=rc(typeof P=="number"?P:h(g),o,"generate"),{signal:x,dispose:O}=Dgr(g.abortSignal,R?.controller.signal);let N,M=A;try{let z=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(I),...x?{signal:x}:{}});if(!z.ok){const J=await oC(t,I,z),Y=J;let ie=z.status===400?(()=>{const ce=c(I,Y);return l(ce??I,Y)??ce})():void 0;if(!ie&&A&&z.status===400&&/stream/i.test(Y.responseBody??"")){const{stream:ce,stream_options:re,...G}=I;ie=G,M=!1}if(!ie)throw J;if(z=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(ie),...x?{signal:x}:{}}),!z.ok)throw await oC(t,ie,z)}if(M){if(!z.body)throw new Error(`${o}: streaming generate response had no body`);const J=R?z.body.pipeThrough(new TransformStream({transform(ie,ce){R.reset(),ce.enqueue(ie)}})):z.body,Y=await tY(J,()=>{});N={...Y.id?{id:Y.id}:{},...Y.model?{model:Y.model}:{},choices:[{index:0,message:{role:"assistant",content:Y.text.length>0?Y.text:null,...Y.reasoning?{reasoning:Y.reasoning}:{},...Y.toolCalls.size>0?{tool_calls:[...Y.toolCalls.values()].map(ie=>({id:ie.id,type:"function",function:{name:ie.name,arguments:ie.argsBuffered}}))}:{}},finish_reason:Y.finishReason??"stop"}],...Y.usage?{usage:Y.usage}:{}}}else N=await z.json()}finally{R?.cleanup(),O()}const D=N.choices?.[0],L=(typeof D?.message?.content=="string"?D.message.content:"")??"",$=[],U=D?.message?.reasoning_content||D?.message?.reasoning;typeof U=="string"&&U.length>0&&$.push({type:"reasoning",text:U}),L.length>0&&$.push({type:"text",text:L});for(const z of D?.message?.tool_calls??[])$.push({type:"tool-call",toolCallId:z.id,toolName:y?.fromWire.get(z.function.name)??z.function.name,input:z.function.arguments??""});const j=D?.finish_reason;return{content:$,finishReason:{unified:j==="length"?"length":j==="tool_calls"||j==="function_call"?"tool-calls":j==="content_filter"?"content-filter":"stop",raw:j??"stop"},usage:{inputTokens:{total:N.usage?.prompt_tokens,noCache:N.usage?.prompt_tokens!==void 0&&N.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,N.usage.prompt_tokens-N.usage.prompt_tokens_details.cached_tokens):N.usage?.prompt_tokens,cacheRead:N.usage?.prompt_tokens!==void 0&&N.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(N.usage.prompt_tokens_details.cached_tokens,N.usage.prompt_tokens):N.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:N.usage?.completion_tokens,text:N.usage?.completion_tokens!==void 0&&N.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,N.usage.completion_tokens-N.usage.completion_tokens_details.reasoning_tokens):N.usage?.completion_tokens,reasoning:N.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:I},response:{...N.id?{id:N.id}:{},...N.model?{modelId:N.model}:{},headers:{},body:N}}},doStream:()=>{throw new Error(`${o}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=rc(n,this.providerName,"stream"),s=new AbortController,i=zge([e.abortSignal,o?.controller.signal,s.signal]).signal;let a,l,c,u,d,m;try{a=await this.resolveModelName();const $=!e.disableTools&&this.supportsTools();l=$?e.tools||await this.getAllTools():{},c=$?y4(Object.keys(l)):void 0,u=$?XJ(l,c?.toWire):void 0,d=Wwt(rbt(e,l,$),c?.toWire);const U=await this.buildMessagesForStream(e);m=ZJ(U,c?.toWire)}catch($){throw o?.cleanup(),$}const h=this.getChatCompletionsURL(a),g=Bt(),y=e.maxSteps||Ai,v=this.neurolink?.getEventEmitter(),_=[],b=[],{usagePromise:T,finishPromise:k,resolveUsage:A,resolveFinish:I}=rY(),P=N0(),R=this.onStreamStart(a),x=this.runStreamLoop({maxSteps:y,modelId:a,url:h,fetchImpl:g,abortSignal:i,options:e,conversation:m,openAITools:u,openAIToolChoice:d,toolsRecord:l,toolNameFromWire:c?.fromWire,emitter:v,toolsUsed:_,toolExecutionSummaries:b,pushChunk:P.push,closeChannel:P.close,resolveUsage:A,resolveFinish:I});let O;const N=$=>{O=$};R?.onUsage&&T.then(R.onUsage).catch(()=>{}),R?.onFinish&&k.then($=>R.onFinish?.($,O)).catch(()=>{});const M=this.providerName,L={stream:async function*(){let $=0;try{for await(const U of P.iterable)"content"in U&&typeof U.content=="string"&&U.content.length>0&&$++,yield U;if(await x,$===0&&_.length===0){f.warn(`${M}: Stream produced no output \u2014 emitting enriched sentinel`);const U=new ac({message:"Stream produced no output"}),j=await tg(U,void 0,O);rg(j),yield j}}catch(U){if(ac.isInstance(U)){const B=await tg(U,void 0,O);rg(B),yield B;return}const j=await tg(U,void 0,O);throw rg(j),yield j,U}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:a,analytics:cY.createAnalytics(this.providerName,a,{textStream:(async function*(){})(),usage:T,finishReason:k},Date.now()-r,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:_,metadata:{startTime:r,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(L,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>mM(b.map($=>({toolName:$.toolName,input:$.input,output:$.output,duration:$.endTime.getTime()-$.startTime.getTime()})))}),x.finally(()=>o?.cleanup()).catch($=>{N($)}),L}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:l,openAIToolChoice:c,toolsRecord:u,toolNameFromWire:d,emitter:m,toolsUsed:h,toolExecutionSummaries:g,pushChunk:y,closeChannel:v,resolveUsage:_,resolveFinish:b}=e;let T=null,k;const A=()=>{const I=k?.prompt_tokens??0,P=k?.completion_tokens??0,R=Math.min(k?.prompt_tokens_details?.cached_tokens??0,I),x=Math.min(Math.max(0,k?.completion_tokens_details?.reasoning_tokens??0),P);return{promptTokens:I-R,completionTokens:P,totalTokens:k?.total_tokens||I+P,...R>0?{cacheReadTokens:R}:{},...x>0?{reasoningTokens:x}:{}}};try{let I=d,P,R;for(let x=0;x<t;x++){if(l){const M=new Set(l.map(L=>I?.get(L.function.name)??L.function.name)),D=Object.fromEntries(Object.entries(u).filter(([L])=>!M.has(L)));if(Object.keys(D).length>0){const L=y4(Object.keys(D),new Set(l.map($=>$.function.name)));if(L){I??=new Map;for(const[$,U]of L.fromWire)I.set($,U)}l.push(...XJ(D,L?.toWire)??[]),f.info(`${this.providerName}: ${Object.keys(D).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(D).join(", ")}`)}}const O=$4r({conversation:a,availableInputTokens:ou(this.providerName,r,i.maxTokens??void 0),fixedOverheadTokens:JJ([],l,this.providerName),provider:this.providerName,observedPromptTokens:P,previousSentEstimate:R,onSentEstimate:M=>{R=M}});O&&(a.length=0,a.push(...O));const N=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:l,openAIToolChoice:c,pushChunk:y});if(P=N.usage?.prompt_tokens,T=N.finishReason,N.usage&&(k=Ywt(k,N.usage)),N.toolCalls.size===0)break;await this.executeToolBatch({stepResult:N,conversation:a,toolsRecord:u,toolNameFromWire:I,emitter:m,toolsUsed:h,toolExecutionSummaries:g,options:i})}return _(A()),b(T??"stop"),v(),{finishReason:T??"stop",usage:k}}catch(I){throw f.error(`${this.providerName}: Stream error`,{error:I instanceof Error?I.message:String(I)}),_(A()),b("error"),v(),I}}async streamOneStep(e){const t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),r=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,n=QJ(this.adjustRequestBody(eY({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,r),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),o=async()=>{const i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(n),...e.abortSignal?{signal:e.abortSignal}:{}});if(!i.ok)throw await oC(e.url,n,i);return i};let s;try{s=await Mv(o,vt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(i){const a=i,l=a.statusCode===400?(()=>{const c=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(c??n,a)??c})():void 0;if(!l)throw a;if(s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(l),...e.abortSignal?{signal:e.abortSignal}:{}}),!s.ok)throw await oC(e.url,l,s)}if(!s.body)throw new Error(`${this.providerName}: stream response had no body`);return tY(s.body,i=>{e.pushChunk({content:i})},i=>{e.pushChunk({content:"",reasoning:i})})}async executeToolBatch(e){const{stepResult:t,conversation:r,toolsRecord:n,toolNameFromWire:o,emitter:s,toolsUsed:i,toolExecutionSummaries:a,options:l}=e,c=[];for(const[,d]of t.toolCalls)c.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});r.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:c});for(const[,d]of t.toolCalls){const m=new Date;let h;try{h=JSON.parse(d.argsBuffered||"{}")}catch{h=d.argsBuffered}let g,y;const v=o?.get(d.name)??d.name,_=n[v]??kV(n,v);if(s?.emit("tool:start",{toolName:v,toolCallId:d.id,input:h}),!_||typeof _.execute!="function")y=`Tool '${v}' is not registered.`,g={error:y};else try{g=await _.execute(h,{})}catch(T){y=T instanceof Error?T.message:String(T),g={error:y}}const b=new Date;i.push(v),a.push({toolCallId:d.id,toolName:v,input:h,output:g,...y?{error:y}:{},startTime:m,endTime:b}),r.push({role:"tool",tool_call_id:d.id,content:YJ(g)})}const u=a.slice(-t.toolCalls.size);DV(s,u.map(d=>({toolName:d.toolName,output:d.output,...d.error?{error:d.error}:{}})));try{await this.handleToolExecutionStorage(u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,input:d.input,output:d.output})),u.map(d=>({toolCallId:d.toolCallId,toolName:d.toolName,output:d.output})),l,new Date)}catch(d){f.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{const e=`${Ja(this.config.baseURL)}/models`;f.debug(`Fetching available models from: ${e}`);const t=Bt(),r=new AbortController,n=setTimeout(()=>r.abort(),5e3),o=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:r.signal});if(clearTimeout(n),!o.ok)return f.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const s=await o.json();if(!s.data||!Array.isArray(s.data))return f.warn("Invalid models response format"),this.getFallbackModels();const i=s.data.map(a=>a.id).filter(Boolean);return f.shouldLog("debug")&&f.debug(`Discovered ${i.length} models:`,i),i.length>0?i:this.getFallbackModels()}catch(e){return f.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),uY,obt,sbt,ibt,abt,lbt,B4r=S({"src/lib/providers/openAI/client.ts"(){"use strict";er(),no(),yt(),q(),_r(),uc(),xi(),Yo(),Rl(),dg(),Ua(),Jm(),Pl(),ym(),uY="https://api.openai.com/v1",obt=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??uY;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ja(n.toString())}catch{}return r},sbt=()=>Bi(ycr()),ibt=()=>zi("OPENAI_MODEL","gpt-4o"),abt=vt.getTracer("neurolink.provider.openai"),lbt=class extends Za{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:sbt(),i=obt(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:i,apiKey:s}),f.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Xn(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return ibt()}formatProviderError(e){const t=e,r=t?.type&&typeof t.type=="string"?t.type:void 0,n=[{match:o=>o.statusCode===401||r==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(o.message),errorClass:sr,message:o=>/Incorrect API key|Invalid API key/i.test(o.message)?o.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:o=>mAe(o.error),errorClass:_t,message:"OpenAI quota exhausted \u2014 this will not resolve by retrying. Check your plan and billing details at https://platform.openai.com/account/billing"},{match:o=>o.statusCode===429||r==="rate_limit_error"||/rate limit/i.test(o.message),errorClass:Xs,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:co,message:o=>`Model not found: ${o.modelName}`},...Qo];return Ki(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=abt.startSpan("neurolink.provider.streamText",{kind:Br.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}});let r=!1;const n=()=>{r||(r=!0,t.end())};return{onUsage:o=>{t.setAttribute("gen_ai.usage.input_tokens",o.promptTokens+(o.cacheReadTokens??0)+(o.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",o.completionTokens);const s=Ga(this.providerName,e,{input:o.promptTokens,output:o.completionTokens,total:o.totalTokens,...o.cacheReadTokens?{cacheReadTokens:o.cacheReadTokens}:{},...o.cacheCreationTokens?{cacheCreationTokens:o.cacheCreationTokens}:{}});s&&s>0&&t.setAttribute("neurolink.cost",s)},onFinish:(o,s)=>{t.setAttribute("gen_ai.response.finish_reason",o||"unknown"),o==="error"&&t.setStatus({code:qe.ERROR,message:s instanceof Error?s.message:String(s??"stream error")}),n()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){const r=t||this.getDefaultEmbeddingModel();f.debug("Generating embedding",{provider:this.providerName,model:r,textLength:e.length});try{const[n]=await this.callEmbeddings(r,[e],"embed");return f.debug("Embedding generated successfully",{provider:this.providerName,model:r,embeddingDimension:n.length}),n}catch(n){throw f.error("Embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,textLength:e.length}),this.handleProviderError(n)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();f.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return f.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw f.error("Batch embedding generation failed",{error:n instanceof Error?n.message:String(n),model:r,count:e.length}),this.handleProviderError(n)}}async callEmbeddings(e,t,r){const n=`${Ja(this.config.baseURL)}/embeddings`,o=Bt(),s=rc(3e4,this.providerName,"generate");try{const i=await o(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...s?.controller.signal?{signal:s.controller.signal}:{}});if(!i.ok){const c=await i.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${i.status}`,d;if(c)try{const m=JSON.parse(c);m.error?.message&&(u=m.error.message),d=m.error?.type}catch{}throw Object.assign(new Error(u),{status:i.status,type:d})}const l=((await i.json()).data??[]).map(c=>c.embedding).filter(c=>Array.isArray(c));if(l.length===0)throw new _t(`OpenAI ${r} returned no embeddings`,this.providerName);return l}finally{s?.cleanup()}}async executeImageGeneration(e){const t=Date.now(),r=e.prompt??e.input?.text??"";if(!r.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");const n=e.model??this.modelName,o=Ja(this.config.baseURL??uY),s=e,i=s.size??this.aspectRatioToOpenAISize(s.aspectRatio,n),a=s.numberOfImages??1;let l;n==="gpt-image-1"||n.startsWith("dall-e-3")?l=1:n.startsWith("dall-e-2")?l=Math.min(Math.max(a,1),10):l=1;const u={model:n,prompt:r,n:l,size:i};n==="gpt-image-1"?s.quality&&(u.quality=s.quality):n.startsWith("dall-e-3")?(u.response_format="b64_json",s.quality&&(u.quality=s.quality),s.style&&(u.style=s.style)):u.response_format="b64_json";const d=12e4,m=new AbortController,h=setTimeout(()=>m.abort(),d);let g;try{g=await Bt()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:m.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:T}):T}finally{clearTimeout(h)}if(!g.ok){const T=await g.text();throw new Error(`OpenAI image generation failed: ${g.status} \u2014 ${T}`)}const v=(await g.json()).data?.[0];if(!v)throw new Error("OpenAI image generation returned no images");let _=v.b64_json;if(!_&&v.url){await ug(v.url);const T=Bt(),k=new AbortController,A=setTimeout(()=>k.abort(),6e4);let I;try{I=await T(v.url,{signal:k.signal})}catch(R){throw R instanceof Error&&R.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:R}):R}finally{clearTimeout(A)}if(!I.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${v.url} (${I.status})`);_=(await ip(I,cg,"OpenAI image fallback")).toString("base64")}if(!_)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const b=Date.now()-t;return f.info(`[OpenAIProvider] Generated image (${_.length} base64 chars) in ${b}ms \u2014 model ${n}`),{content:v.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:_}}}aspectRatioToOpenAISize(e,t){return t==="gpt-image-1"?e==="16:9"||e==="3:2"?"1536x1024":e==="9:16"||e==="2:3"?"1024x1536":"1024x1024":t.startsWith("dall-e-3")?e==="16:9"||e==="3:2"?"1792x1024":e==="9:16"||e==="2:3"?"1024x1792":"1024x1024":"1024x1024"}}}}),cbt={};he(cbt,{OpenAIProvider:()=>lbt});var z4r=S({"src/lib/providers/openAI/index.ts"(){"use strict";B4r()}});function je(e,t,r,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!o:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(e,r):o?o.value=r:t.set(e,r),r}function V(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var Ml=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),sC,dY=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){sC=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return sC=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))}}});function B0(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var iC,z0=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){iC=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)}}}),pt,Qi,wc,j0,pY,ubt,mY,hY,fY,gY,yY,vY,_Y,wY,oo=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){z0(),pt=class extends Error{},Qi=class vce extends pt{constructor(t,r,n,o,s){super(`${vce.makeMessage(t,r,n)}`),this.status=t,this.headers=o,this.requestID=o?.get("request-id"),this.error=r,this.type=s??null}static makeMessage(t,r,n){const o=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,r,n,o){if(!t||!o)return new j0({message:n,cause:iC(r)});const s=r,i=s?.error?.type;return t===400?new mY(t,s,n,o,i):t===401?new hY(t,s,n,o,i):t===403?new fY(t,s,n,o,i):t===404?new gY(t,s,n,o,i):t===409?new yY(t,s,n,o,i):t===422?new vY(t,s,n,o,i):t===429?new _Y(t,s,n,o,i):t>=500?new wY(t,s,n,o,i):new vce(t,s,n,o,i)}},wc=class extends Qi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},j0=class extends Qi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},pY=class extends j0{constructor({message:e}={}){super({message:e??"Request timed out."})}},ubt=class extends pt{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},mY=class extends Qi{},hY=class extends Qi{},fY=class extends Qi{},gY=class extends Qi{},yY=class extends Qi{},vY=class extends Qi{},_Y=class extends Qi{},wY=class extends Qi{}}});function bY(e){return typeof e!="object"?{}:e??{}}function dbt(e){if(!e)return!0;for(const t in e)return!1;return!0}function j4r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var pbt,mbt,Ea,TY,hbt,EY,lp=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){oo(),pbt=/^[a-z][a-z0-9+.-]*:/i,mbt=e=>pbt.test(e),Ea=e=>(Ea=Array.isArray,Ea(e)),TY=Ea,hbt=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new pt(`${e} must be an integer`);if(t<0)throw new pt(`${e} must be a positive integer`);return t},EY=e=>{try{return JSON.parse(e)}catch{return}}}}),Ym,aC=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){Ym=(e,t)=>new Promise(r=>{if(t?.aborted)return r();const n=()=>{clearTimeout(o),r()},o=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}}),cp,w4=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){cp="0.102.0"}});function q4r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function G4r(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:r}of e){const n=r.exec(navigator.userAgent);if(n){const o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${s}.${i}`}}}return null}var fbt,gbt,SY,CY,ybt,b4,kY=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){w4(),fbt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",gbt=()=>{const e=q4r();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":CY(Deno.build.os),"X-Stainless-Arch":SY(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":CY(globalThis.process.platform??"unknown"),"X-Stainless-Arch":SY(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=G4r();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cp,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},SY=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",CY=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),b4=()=>ybt??(ybt=gbt())}});function H4r(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function vbt(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function _bt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return vbt({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function xY(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){const r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function V4r(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}const t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var lC=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),wbt,W4r=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){wbt=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),AY,IY,RY,bbt,Tbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){AY="RFC3986",IY=e=>String(e),RY={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:IY},bbt="RFC1738"}});function K4r(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Ebt(e,t){if(Ea(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var T4,au,E4,Sbt,J4r=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){Tbt(),lp(),T4=(e,t)=>(T4=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),T4(e,t)),au=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),E4=1024,Sbt=(e,t,r,n,o)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=E4){const l=s.length>=E4?s.slice(a,a+E4):s,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===bbt&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=au[d];continue}if(d<2048){c[c.length]=au[192|d>>6]+au[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=au[224|d>>12]+au[128|d>>6&63]+au[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=au[240|d>>18]+au[128|d>>12&63]+au[128|d>>6&63]+au[128|d&63]}i+=c.join("")}return i}}});function Y4r(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function Cbt(e,t,r,n,o,s,i,a,l,c,u,d,m,h,g,y,v,_){let b=e,T=_,k=0,A=!1;for(;(T=T.get(S4))!==void 0&&!A;){const O=T.get(e);if(k+=1,typeof O<"u"){if(O===k)throw new RangeError("Cyclic object value");A=!0}typeof T.get(S4)>"u"&&(k=0)}if(typeof c=="function"?b=c(t,b):b instanceof Date?b=m?.(b):r==="comma"&&Ea(b)&&(b=Ebt(b,function(O){return O instanceof Date?m?.(O):O})),b===null){if(s)return l&&!y?l(t,Ts.encoder,v,"key",h):t;b=""}if(Y4r(b)||K4r(b)){if(l){const O=y?t:l(t,Ts.encoder,v,"key",h);return[g?.(O)+"="+g?.(l(b,Ts.encoder,v,"value",h))]}return[g?.(t)+"="+g?.(String(b))]}const I=[];if(typeof b>"u")return I;let P;if(r==="comma"&&Ea(b))y&&l&&(b=Ebt(b,l)),P=[{value:b.length>0?b.join(",")||null:void 0}];else if(Ea(c))P=c;else{const O=Object.keys(b);P=u?O.sort(u):O}const R=a?String(t).replace(/\./g,"%2E"):String(t),x=n&&Ea(b)&&b.length===1?R+"[]":R;if(o&&Ea(b)&&b.length===0)return x+"[]";for(let O=0;O<P.length;++O){const N=P[O],M=typeof N=="object"&&typeof N.value<"u"?N.value:b[N];if(i&&M===null)continue;const D=d&&a?N.replace(/\./g,"%2E"):N,L=Ea(b)?typeof r=="function"?r(x,D):x:x+(d?"."+D:"["+D+"]");_.set(e,k);const $=new WeakMap;$.set(S4,_),MY(I,Cbt(M,L,r,n,o,s,i,a,r==="comma"&&y&&Ea(b)?null:l,c,u,d,m,h,g,y,v,$))}return I}function Z4r(e=Ts){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||Ts.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=AY;if(typeof e.format<"u"){if(!T4(RY,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=RY[r];let o=Ts.filter;(typeof e.filter=="function"||Ea(e.filter))&&(o=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in PY?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=Ts.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:Ts.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:Ts.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:Ts.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Ts.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?Ts.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Ts.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:Ts.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:Ts.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Ts.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Ts.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Ts.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Ts.strictNullHandling}}function X4r(e,t={}){let r=e;const n=Z4r(t);let o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Ea(n.filter)&&(s=n.filter,o=s);const i=[];if(typeof r!="object"||r===null)return"";const a=PY[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const c=new WeakMap;for(let m=0;m<o.length;++m){const h=o[m];n.skipNulls&&r[h]===null||MY(i,Cbt(r[h],h,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=i.join(n.delimiter);let d=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var PY,MY,kbt,Ts,S4,Q4r=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){J4r(),Tbt(),lp(),PY={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},MY=function(e,t){Array.prototype.push.apply(e,Ea(t)?t:[t])},Ts={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Sbt,encodeValuesOnly:!1,format:AY,formatter:IY,indices:!1,serializeDate(e){return(kbt??(kbt=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},S4={}}});function eOr(e){return X4r(e,{arrayFormat:"brackets"})}var xbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){Q4r()}});function Abt(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new _n(`Invalid token endpoint base URL "${e}": ${n}`)}if(t.protocol==="https:")return;const r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(t.protocol==="http:"&&(r==="localhost"||r==="127.0.0.1"||r==="::1")))throw new _n(`Refusing to send credential over non-https token endpoint "${e}"`)}async function Ibt(e,t){const r=await tOr(e);let n;try{n=JSON.parse(r)}catch{throw new _n(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,bc(r),t)}if(!n.access_token)throw new _n(`Token endpoint response missing access_token: ${JSON.stringify(bc(n))}`,e.status,bc(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new _n(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,bc(n),t);return n}function bc(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=k4?e:e.slice(0,k4)+`... <${e.length-k4} more chars>`}return JSON.stringify(bc(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))$bt.has(r)&&(t[r]=n);return t}return null}async function Rbt(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(to(),Jd));let n=e,o;try{n=await r.promises.realpath(e),o=await r.promises.stat(n)}catch{return}const s=o.mode&511;if(s&18)throw new _n(`Credentials file at ${n} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(s&36)throw new _n(`Credentials file at ${n} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&t(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function Pbt(e,t){const r=await Promise.resolve().then(()=>(to(),Jd)),o=(await Promise.resolve().then(()=>(rr(),Pm))).dirname(e);await r.promises.mkdir(o,{recursive:!0,mode:448});const s=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{const i=await r.promises.open(s,"w",384);try{await i.writeFile(JSON.stringify(t,null,2)),await i.sync()}finally{await i.close()}await r.promises.rename(s,e)}catch(i){throw await r.promises.unlink(s).catch(()=>{}),i}try{const i=await r.promises.open(o,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function tOr(e){if(!e.body)return"";const t=e.body.getReader(),r=[];let n=0;for(;;){const{done:s,value:i}=await t.read();if(s)break;if(n+i.length>OY){const a=OY-n;a>0&&r.push(i.subarray(0,a)),await t.cancel();break}r.push(i),n+=i.length}let o;if(r.length===1)o=r[0];else{o=new Uint8Array(r.reduce((i,a)=>i+a.length,0));let s=0;for(const i of r)o.set(i,s),s+=i.length}return new TextDecoder("utf-8").decode(o)}var Mbt,Dbt,DY,cC,Obt,Nbt,C4,Lbt,OY,k4,$bt,_n,uC=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){oo(),Mbt="urn:ietf:params:oauth:grant-type:jwt-bearer",Dbt="refresh_token",DY="/v1/oauth/token",cC="oauth-2025-04-20",Obt="oidc-federation-2026-04-01",Nbt=120,C4=30,Lbt=5,OY=1<<20,k4=2e3,$bt=new Set(["error","error_description","error_uri"]),_n=class extends pt{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function pg(){return Math.floor(Date.now()/1e3)}var x4=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),Fbt,rOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){uC(),x4(),Fbt=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){const e=this.nextForce;this.nextForce=!1;const t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;const r=t.expiresAt-pg();return r>Nbt?t.token:r>C4?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||pg()-this.lastAdvisoryError<Lbt||this.doRefresh().catch(e=>{this.lastAdvisoryError=pg(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}}}),Pr,A4=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Pr=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0}}});function nOr(e){let t=0;for(const o of e)t+=o.length;const r=new Uint8Array(t);let n=0;for(const o of e)r.set(o,n),n+=o.length;return r}function NY(e){let t;return(Bbt??(t=new globalThis.TextEncoder,Bbt=t.encode.bind(t)))(e)}function Ubt(e){let t;return(zbt??(t=new globalThis.TextDecoder,zbt=t.decode.bind(t)))(e)}var Bbt,zbt,LY=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),oOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){oo(),LY()}});function dC(){}function I4(e,t,r){return!t||pC[e]>pC[r]?dC:t[e].bind(t)}function so(e){const t=e.logger,r=e.logLevel??"off";if(!t)return jbt;const n=FY.get(t);if(n&&n[0]===r)return n[1];const o={error:I4("error",t,r),warn:I4("warn",t,r),info:I4("info",t,r),debug:I4("debug",t,r)};return FY.set(t,[r,o]),o}var pC,$Y,jbt,FY,up,Zm=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){lp(),pC={off:0,error:200,warn:300,info:400,debug:500},$Y=(e,t,r)=>{if(e){if(j4r(pC,e))return e;so(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(pC))}`)}},jbt={error:dC,warn:dC,info:dC,debug:dC},FY=new WeakMap,up=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}}),qbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){lp(),oOr(),A4(),Zm(),dY(),aC(),xbt()}});function Gbt(e){if(!e)throw new Error("profile name is empty");if(e==="."||e==="..")throw new Error(`profile name "${e}" is not allowed`);if(e.includes("/")||e.includes("\\"))throw new Error(`profile name "${e}" must not contain path separators`);if(!Hbt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var UY,Hbt,Vbt,Wbt,R4,Kbt,BY,Jbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){kY(),qbt(),UY="1.0",Hbt=/^[A-Za-z0-9_.-]+$/,Vbt=async e=>{var t,r;const n=await R4();if(n===null)return null;const o=e??await BY();if(o===null)return null;Gbt(o);const s=await Promise.resolve().then(()=>(to(),Jd)),a=(await Promise.resolve().then(()=>(rr(),Pm))).join(n,"configs",`${o}.json`);let l;try{l=await s.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);l=null}if(l===null){const d=Pr("ANTHROPIC_ORGANIZATION_ID"),m=Pr("ANTHROPIC_IDENTITY_TOKEN_FILE"),h=Pr("ANTHROPIC_FEDERATION_RULE_ID");return h&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Pr("ANTHROPIC_WORKSPACE_ID"),base_url:Pr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:h,service_account_id:Pr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Pr("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=Pr("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=Pr("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=Pr("ANTHROPIC_BASE_URL")),(t=c.authentication).scope??(t.scope=Pr("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){const d=Pr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(c.authentication.identity_token={source:"file",path:d})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=Pr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=c.authentication).service_account_id??(r.service_account_id=Pr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},Wbt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await R4();if(!r)return null;const n=t??await BY();return n?(Gbt(n),(await Promise.resolve().then(()=>(rr(),Pm))).join(r,"credentials",`${n}.json`)):null},R4=async()=>{if(!Kbt())return null;const e=await Promise.resolve().then(()=>(rr(),Pm)),t=Pr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(b4()["X-Stainless-OS"]==="Windows"){const s=Pr("APPDATA");if(s)return e.join(s,"Anthropic");const i=Pr("USERPROFILE");return i?e.join(i,"AppData","Roaming","Anthropic"):null}const n=Pr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Pr("HOME");return o?e.join(o,".config","anthropic"):null},Kbt=()=>{const e=b4()["X-Stainless-Runtime"];return e==="node"||e==="deno"},BY=async()=>{const e=await R4();if(!e)return null;const t=Pr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(to(),Jd)),o=(await Promise.resolve().then(()=>(rr(),Pm))).join(e,"active_config");try{return(await r.promises.readFile(o,"utf-8")).trim()||"default"}catch(s){if(s?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${s}`);return"default"}}}});function Ybt(e){if(!e)throw new pt("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(to(),Jd));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new pt(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new pt(`Identity token file at ${e} is empty`);return n}}function sOr(e){if(!e)throw new pt("Identity token value is empty");return()=>e}var iOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){oo()}});function aOr(e){return async()=>{Abt(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new _n(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:Mbt,assertion:t,federation_rule_id:e.federationRuleId,organization_id:e.organizationId};e.serviceAccountId&&(r.service_account_id=e.serviceAccountId),e.workspaceId&&(r.workspace_id=e.workspaceId);const n=`${e.baseURL}${DY}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${cC},${Obt}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${cp} oidcFederationProvider`},body:JSON.stringify(r)})}catch(l){throw new _n(`Failed to reach token endpoint ${n}: ${l}`)}const s=o.headers.get("Request-Id");if(!o.ok){const l=await o.text().catch(()=>""),c=bc(l);let u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${e.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new _n(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${c}${u}`,o.status,c,s)}const i=await Ibt(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new _n(`Token endpoint response missing required fields: ${JSON.stringify(bc(i))}`,o.status,bc(i),s);return{token:i.access_token,expiresAt:pg()+a}}}var lOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){uC(),x4(),w4()}});function cOr(e){return async t=>{const r=await Promise.resolve().then(()=>(to(),Jd));await Rbt(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(v){throw new _n(`Credentials file not found at ${e.credentialsPath}: ${v}`)}let o;try{o=JSON.parse(n)}catch(v){throw new _n(`Credentials file at ${e.credentialsPath} is not valid JSON: ${v}`)}const s=o.access_token;if(!s)throw new _n(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const i=o.expires_at;if(!t?.forceRefresh&&(i==null||pg()<i-C4))return{token:s,expiresAt:i??null};const a=o.refresh_token;if(!e.clientId||!a)throw new _n(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);Abt(e.baseURL);const l={grant_type:Dbt,refresh_token:a,client_id:e.clientId},c=`${e.baseURL}${DY}`;let u;try{u=await e.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":cC,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${cp} userOAuthProvider`},body:JSON.stringify(l)})}catch(v){throw new _n(`User OAuth refresh failed to reach token endpoint: ${v}`)}const d=u.headers.get("Request-Id");if(!u.ok){const v=await u.text().catch(()=>"");throw new _n(`User OAuth refresh failed (HTTP ${u.status}): ${bc(v)}`,u.status,bc(v),d)}const m=await Ibt(u,d),h=Number(m.expires_in);if(!Number.isFinite(h))throw new _n(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(bc(m))}`,u.status,bc(m),d);const g=pg()+h,y=m.refresh_token||a;return await Pbt(e.credentialsPath,{...o,version:UY,type:"oauth_token",access_token:m.access_token,expires_at:g,refresh_token:y}),{token:m.access_token,expiresAt:g}}}var uOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){Jbt(),uC(),x4(),w4()}});function Zbt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=pOr(e,r,n,t),s={};return e.workspace_id&&e.authentication.type==="user_oauth"&&(s["anthropic-workspace-id"]=e.workspace_id),{provider:o,extraHeaders:s,baseURL:e.base_url||void 0}}async function dOr(e,t){const r=await Vbt(t);if(!r)return null;const{config:n,fromFile:o}=r,s=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await Wbt(n,t)??void 0}};return Zbt(s,e)}function pOr(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,s=mOr(o);if(!s)throw new _n("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new _n("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!e.organization_id)throw new _n("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const i=aOr({identityTokenProvider:s,federationRuleId:o.federation_rule_id,organizationId:e.organization_id,serviceAccountId:o.service_account_id,workspaceId:e.workspace_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent});return t?hOr(i,t,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!t)throw new _n("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return cOr({credentialsPath:t,clientId:e.authentication.client_id,baseURL:r,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{const o=e.authentication.type;throw new _n(`authentication.type "${o}" is not a known authentication type`)}}}function mOr(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new _n(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new _n('identity_token.source "file" requires a non-empty path');return Ybt(e.identity_token.path)}const t=Pr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return Ybt(t);const r=Pr("ANTHROPIC_IDENTITY_TOKEN");return r?sOr(r):null}function hOr(e,t,r,n){return async o=>{const s=await Promise.resolve().then(()=>(to(),Jd));await Rbt(t,n);let i;try{const l=await s.promises.readFile(t,"utf-8");i=JSON.parse(l);const c=i?.access_token;if(c&&!o?.forceRefresh){const u=i?.expires_at;if(u==null||pg()<u-C4)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&r?.(l)}const a=await e(o);try{await Pbt(t,{...i??{},version:UY,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){r?.(l)}return a}}var fOr=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){A4(),Jbt(),uC(),x4(),iOr(),lOr(),uOr()}});function gOr(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function yOr(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}var Dl,Ol,q0,Xbt=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){Ml(),LY(),q0=class{constructor(){Dl.set(this,void 0),Ol.set(this,void 0),je(this,Dl,new Uint8Array,"f"),je(this,Ol,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?NY(e):e;je(this,Dl,nOr([V(this,Dl,"f"),t]),"f");const r=[];let n;for(;(n=gOr(V(this,Dl,"f"),V(this,Ol,"f")))!=null;){if(n.carriage&&V(this,Ol,"f")==null){je(this,Ol,n.index,"f");continue}if(V(this,Ol,"f")!=null&&(n.index!==V(this,Ol,"f")+1||n.carriage)){r.push(Ubt(V(this,Dl,"f").subarray(0,V(this,Ol,"f")-1))),je(this,Dl,V(this,Dl,"f").subarray(V(this,Ol,"f")),"f"),je(this,Ol,null,"f");continue}const o=V(this,Ol,"f")!==null?n.preceding-1:n.preceding,s=Ubt(V(this,Dl,"f").subarray(0,o));r.push(s),je(this,Dl,V(this,Dl,"f").subarray(n.index),"f"),je(this,Ol,null,"f")}return r}flush(){return V(this,Dl,"f").length?this.decode(`
|
|
1064
1064
|
`):[]}},Dl=new WeakMap,Ol=new WeakMap,q0.NEWLINE_CHARS=new Set([`
|
|
1065
1065
|
`,"\r"]),q0.NEWLINE_REGEXP=/\r\n|[\n\r]/g}});async function*vOr(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new pt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new pt("Attempted to iterate over a response with no body");const r=new Qbt,n=new q0,o=xY(e.body);for await(const s of _Or(o))for(const i of n.decode(s)){const a=r.decode(i);a&&(yield a)}for(const s of n.flush()){const i=r.decode(s);i&&(yield i)}}async function*_Or(e){let t=new Uint8Array;for await(const r of e){if(r==null)continue;const n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?NY(r):r;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let s;for(;(s=yOr(t))!==-1;)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}function wOr(e,t){const r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var mC,mg,Qbt,zY=S({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/streaming.mjs"(){Ml(),oo(),lC(),Xbt(),lC(),z0(),lp(),LY(),Zm(),oo(),mg=class OA{constructor(t,r,n){this.iterator=t,mC.set(this,void 0),this.controller=r,je(this,mC,n,"f")}static fromSSEResponse(t,r,n){let o=!1;const s=n?so(n):console;async function*i(){if(o)throw new pt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const l of vOr(t,r)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw s.error("Could not parse message into JSON:",l.data),s.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated")try{yield JSON.parse(l.data)}catch(c){throw s.error("Could not parse message into JSON:",l.data),s.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){const c=EY(l.data)??l.data,u=c?.error?.type;throw new Qi(void 0,c,void 0,t.headers,u)}}a=!0}catch(l){if(B0(l))return;throw l}finally{a||r.abort()}}return new OA(i,r,n)}static fromReadableStream(t,r,n){let o=!1;async function*s(){const a=new q0,l=xY(t);for await(const c of l)for(const u of a.decode(c))yield u;for(const c of a.flush())yield c}async function*i(){if(o)throw new pt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const l of s())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(B0(l))return;throw l}finally{a||r.abort()}}return new OA(i,r,n)}[(mC=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],r=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){const i=n.next();t.push(i),r.push(i)}return s.shift()}});return[new OA(()=>o(t),this.controller,V(this,mC,"f")),new OA(()=>o(r),this.controller,V(this,mC,"f"))]}toReadableStream(){const t=this;let r;return vbt({async start(){r=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:s}=await r.next();if(s)return n.close();const i=NY(JSON.stringify(o)+`
|
|
1066
1066
|
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}},Qbt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
|