@juspay/neurolink 12.34.1 → 12.34.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.
|
@@ -78,10 +78,10 @@ ${e.envVarName}=your_key_here
|
|
|
78
78
|
\u{1F527} Step 3: Restart Application
|
|
79
79
|
Restart your application to load the new environment variables.`}function _i(e,t){return process.env[e]||t}function Aq(e,t){return e?e.some(r=>typeof r=="string"?!!t[r]:r.every(n=>!!t[n])):!1}function RCr(){const e=GCr(),t=jCr(),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 PCr(){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 MCr(){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 OCr(){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 DCr(){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 NCr(){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 LCr(){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 FCr(){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 $Cr(){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 UCr(){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 BCr(){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 zCr(){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 qCr(){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 GCr(){return process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase()==="oauth"?"oauth":"api_key"}function jCr(){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 HCr(e,t){const r=t?.apiKey?.trim(),n=r&&r.length>0?r:fa(e.configOptions);if(e.computedBaseURL){const{envVar:a,missingValueMessage:c,build:l}=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(c);return{apiKey:n,baseURL:l(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 Ga,kh,kq,ts=b({"src/lib/utils/providerConfig.ts"(){"use strict";Ga={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}$/},kh={OPENAI_MIN:48,ANTHROPIC_MIN:95,HUGGINGFACE_EXACT:37,AZURE_MIN:32,MISTRAL_EXACT:32,AWS_ACCESS_KEY:20,GOOGLE_AI_EXACT:39},kq={MIN_LENGTH:6,MAX_LENGTH:30,PATTERN:/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/}}});function VCr(e){const t=e.wire.apiKeyFallbackEnvVars?.length?{fallbacks:[...e.wire.apiKeyFallbackEnvVars]}:{},r=e.wire.baseURLTemplate?{apiKey:uu(e,"apiKey"),...t,extraRequired:[`${e.id.toUpperCase().replace(/-/g,"_")}_${(e.wire.extraCredentials?.[0]??"accountId").replace(/([A-Z])/g,"_$1").toUpperCase()}`],model:uu(e,"model")}:{apiKey:uu(e,"apiKey"),...t,baseURL:uu(e,"baseURL"),model:uu(e,"model")};return{name:e.id,aliases:e.aliases,credentialsKey:CCr(e),envVars:r,defaultModel:e.models.registryDefaultModel??e.models.default,toolSupport:e.capabilities.tools==="model-dependent"?"model-dependent":e.capabilities.tools?"native":"none",localRuntime:!1,healthCheck:"env-only",setupUrl:e.setup.url,...e.setup.apiKeyFormat?{apiKeyFormatPattern:new RegExp(e.setup.apiKeyFormat)}:{},...e.timeouts?{timeouts:e.timeouts}:{},...e.autoSelectPriority!==void 0?{autoSelectPriority:e.autoSelectPriority}:{}}}function WCr(){return o0().map(VCr)}function KCr(e,t){const r=a=>typeof a=="string"&&a.trim()!=="",n=a=>a!==void 0&&r(process.env[a]),o=e.credentialsKey?t?.[e.credentialsKey]:void 0,s=[e.envVars.apiKey,...e.envVars.fallbacks??[]].some(n)||r(o?.apiKey)||r(o?.gatewayApiKey),i=(e.envVars.extraRequired??[]).every(a=>n(a)||a===e.envVars.baseURL&&r(o?.baseURL));return s&&i}function K1(e){return PS.find(t=>KCr(t,e))?.name}function JCr(){return PS.map(e=>{const t=[e.envVars.apiKey,...e.envVars.fallbacks??[]].filter(n=>typeof n=="string"&&n!==""),r=e.envVars.extraRequired??[];return`${[t.join(" or "),...r].join(" and ")} for ${e.name}`}).join(", or ")}var d_e,pl,Ar,xh,PS,Cc=b({"src/lib/factories/providerDescriptors.ts"(){"use strict";ts(),s0(),ut(),d_e=[{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:Ga.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:Ga.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:Ga.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:Ga.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:Ga["google-ai"]},{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:"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:Ga.aws},{name:"nvidia-nim",aliases:["nvidia","nim"],credentialsKey:"nvidiaNim",envVars:{apiKey:"NVIDIA_NIM_API_KEY",baseURL:"NVIDIA_NIM_BASE_URL",model:"NVIDIA_NIM_MODEL"},defaultModel:"openai/gpt-oss-20b",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:"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:"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"},{name:"typesafe",aliases:["jev","typesafe-ai"],credentialsKey:"typesafe",envVars:{apiKey:"TYPESAFE_API_KEY",fallbacks:["AI_GATEWAY_API_KEY"],baseURL:"TYPESAFE_BASE_URL",model:"TYPESAFE_MODEL"},defaultModel:"jev-latest",inferenceKinds:["decide"],toolSupport:"none",localRuntime:!1,healthCheck:"env-only",timeouts:{decideMs:5e3},setupUrl:"https://console.typesafe.ai/keys"},{name:"laya",aliases:[],credentialsKey:"laya",envVars:{apiKey:"LAYA_API_KEY",baseURL:"LAYA_BASE_URL",extraRequired:["LAYA_BASE_URL"],model:"LAYA_MODEL"},defaultModel:"typed-decisions",inferenceKinds:["decide"],toolSupport:"none",localRuntime:!1,healthCheck:"env-only",timeouts:{decideMs:5e3},decisionLimits:{maxStateTokens:320,maxQuestions:64,nonAsciiTokensPerChar:1.5,models:{"typed-decisions":{maxStateTokens:768},multilingual:{maxStateTokens:768,nonAsciiTokensPerChar:.6},english:{maxStateTokens:320},auto:{maxStateTokens:320}}},setupUrl:"https://github.com/NandhaKishorM/laya"}],pl=[...d_e,...WCr()],Ar=new Map(pl.map(e=>[e.name,e])),xh=new Map(pl.flatMap(e=>[[e.name.toLowerCase(),e.name],...e.aliases.map(t=>[t.toLowerCase(),e.name])])),PS=pl.filter(e=>(e.inferenceKinds??gS).includes("decide"))}}),J1,xq=b({"src/lib/models/manifests/anthropic.ts"(){"use strict";J1={defaultContextWindow:2e5,familyRules:[{pattern:/claude-(?:opus|sonnet|haiku)-(?:[4-9]|\d{2,})/i,patch:{vision:!0}},{pattern:/claude-(?:fable|mythos)-\d/i,patch:{vision:!0}}],models:{"claude-opus-5-5":{aliases:["opus-5.5"],displayName:"Claude Opus 5.5",contextWindow:1e6,maxOutputTokens:128e3,vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,samplingParams:!1},"claude-fable-5-1":{aliases:["fable-5.1"],displayName:"Claude Fable 5.1",contextWindow:1e6,maxOutputTokens:128e3,vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,samplingParams:!1},"claude-sonnet-5":{aliases:["sonnet-5","claude-sonnet"],displayName:"Claude Sonnet 5",contextWindow:1e6,maxOutputTokens:128e3,vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,samplingParams:!1},"claude-opus-4-6":{aliases:["opus-4.6","claude-opus-latest"],displayName:"Claude Opus 4.6",contextWindow:1e6,maxOutputTokens:32e3,pricingPerMTok:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"claude-sonnet-4-6":{aliases:["sonnet-4.6"],displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64e3,pricingPerMTok:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"claude-opus-4-5-20251101":{aliases:["claude-opus-4-5","opus-4.5"],displayName:"Claude Opus 4.5",contextWindow:2e5,maxOutputTokens:32e3,pricingPerMTok:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},category:"reasoning"}},"claude-sonnet-4-5-20250929":{aliases:["claude-sonnet-4-5","sonnet-4.5"],displayName:"Claude Sonnet 4.5",contextWindow:2e5,maxOutputTokens:64e3,pricingPerMTok:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:10,creative:9,analysis:9,conversation:9,reasoning:10,translation:8,summarization:8},category:"coding"}},"claude-haiku-4-5-20251001":{aliases:["claude-haiku-4-5","haiku-4.5","claude-4-5-haiku"],displayName:"Claude 4.5 Haiku",contextWindow:2e5,maxOutputTokens:64e3,pricingPerMTok:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"fast",quality:"high",accuracy:"high"},useCases:{coding:8,creative:8,analysis:8,conversation:9,reasoning:8,translation:8,summarization:9},category:"general"}},"claude-opus-4-1-20250805":{aliases:["claude-opus-4-1","opus-4.1"],displayName:"Claude Opus 4.1",contextWindow:2e5,maxOutputTokens:32e3,pricingPerMTok:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"claude-opus-4-20250514":{aliases:["claude-opus-4"],displayName:"Claude Opus 4",contextWindow:2e5,maxOutputTokens:32e3,pricingPerMTok:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"claude-sonnet-4-20250514":{aliases:["claude-sonnet-4"],displayName:"Claude Sonnet 4",contextWindow:2e5,maxOutputTokens:64e3,pricingPerMTok:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"claude-3-7-sonnet-20250219":{aliases:["claude-3-7-sonnet"],displayName:"Claude 3.7 Sonnet",contextWindow:2e5,maxOutputTokens:64e3,pricingPerMTok:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"claude-3-5-sonnet-20241022":{aliases:["claude-3-5-sonnet"],displayName:"Claude 3.5 Sonnet",contextWindow:2e5,maxOutputTokens:8192,pricingPerMTok:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},vision:!0,functionCalling:!0,reasoning:!1,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:10,creative:9,analysis:9,conversation:9,reasoning:10,translation:8,summarization:8},category:"coding"}},"claude-3-5-haiku-20241022":{aliases:["claude-3-5-haiku"],displayName:"Claude 3.5 Haiku",contextWindow:2e5,maxOutputTokens:8192,pricingPerMTok:{input:.8,output:4,cacheRead:.08,cacheWrite:1},vision:!1,functionCalling:!0,reasoning:!1,jsonMode:!0,curated:{performance:{speed:"fast",quality:"high",accuracy:"high"},useCases:{coding:8,creative:7,analysis:8,conversation:8,reasoning:8,translation:8,summarization:9},category:"general"}},"claude-3-opus-20240229":{aliases:["claude-3-opus"],displayName:"Claude 3 Opus",contextWindow:2e5,maxOutputTokens:4096,pricingPerMTok:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},vision:!0,functionCalling:!0,reasoning:!1,jsonMode:!0},"claude-3-sonnet-20240229":{aliases:["claude-3-sonnet"],displayName:"Claude 3 Sonnet",contextWindow:2e5,maxOutputTokens:4096,pricingPerMTok:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},vision:!0,functionCalling:!0,reasoning:!1,jsonMode:!0},"claude-3-haiku-20240307":{aliases:["claude-3-haiku"],displayName:"Claude 3 Haiku",contextWindow:2e5,maxOutputTokens:4096,pricingPerMTok:{input:.25,output:1.25,cacheRead:.025,cacheWrite:.3125},vision:!0,functionCalling:!0,reasoning:!1,jsonMode:!0}}}}}),Iq,m_e=b({"src/lib/models/manifests/openai.ts"(){"use strict";Iq={defaultContextWindow:128e3,models:{"gpt-4o":{aliases:["gpt4o","gpt-4-omni","openai-flagship"],displayName:"GPT-4 Omni",contextWindow:128e3,maxOutputTokens:4096,pricingPerMTok:{input:2.5,output:10,cacheRead:.625},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:9,creative:8,analysis:9,conversation:9,reasoning:9,translation:8,summarization:8},category:"general"}},"gpt-4o-mini":{aliases:["gpt4o-mini","gpt-4-mini","fastest","cheap"],displayName:"GPT-4 Omni Mini",contextWindow:128e3,maxOutputTokens:16384,pricingPerMTok:{input:.15,output:.6,cacheRead:.0375},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"fast",quality:"high",accuracy:"high"},useCases:{coding:8,creative:7,analysis:8,conversation:8,reasoning:8,translation:8,summarization:9},category:"general"}},"gpt-5":{aliases:["gpt5","gpt-5-flagship","openai-latest"],displayName:"GPT-5",contextWindow:4e5,maxOutputTokens:32768,pricingPerMTok:{input:1.25,output:10,cacheRead:.3125},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:10,creative:10,analysis:10,conversation:10,reasoning:10,translation:9,summarization:9},category:"reasoning"}},"gpt-5-mini":{aliases:["gpt5-mini","gpt-5-fast"],displayName:"GPT-5 Mini",contextWindow:4e5,maxOutputTokens:16384,pricingPerMTok:{input:.25,output:2,cacheRead:.0625},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"fast",quality:"high",accuracy:"high"},useCases:{coding:8,creative:8,analysis:8,conversation:9,reasoning:8,translation:8,summarization:9},category:"general"}},o3:{aliases:["o3-reasoning","o3-thinking"],displayName:"O3",contextWindow:2e5,maxOutputTokens:1e5,pricingPerMTok:{input:2,output:8,cacheRead:.5},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"slow",quality:"high",accuracy:"high"},useCases:{coding:10,creative:8,analysis:10,conversation:7,reasoning:10,translation:7,summarization:8},category:"reasoning"}},"o3-mini":{aliases:["o3-mini-reasoning"],displayName:"O3 Mini",contextWindow:2e5,maxOutputTokens:65536,pricingPerMTok:{input:1.1,output:4.4,cacheRead:.275},vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:9,creative:6,analysis:9,conversation:7,reasoning:9,translation:6,summarization:7},category:"reasoning"}},"gpt-5-nano":{aliases:["gpt5-nano","gpt-5-cheapest"],displayName:"GPT-5 Nano",contextWindow:4e5,maxOutputTokens:128e3,pricingPerMTok:{input:.05,output:.4,cacheRead:.0125},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"fast",quality:"medium",accuracy:"medium"},useCases:{coding:6,creative:6,analysis:6,conversation:8,reasoning:6,translation:7,summarization:8},category:"general"}},"gpt-5.2":{aliases:["gpt52","gpt-5.2-thinking","openai-latest-reasoning"],displayName:"GPT-5.2 Thinking",contextWindow:4e5,maxOutputTokens:64e3,pricingPerMTok:{input:1.75,output:14,cacheRead:.4375},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},category:"reasoning"}},"gpt-5.2-chat-latest":{aliases:["gpt52-chat","gpt-5.2-instant","gpt52-fast"],displayName:"GPT-5.2 Instant",contextWindow:128e3,maxOutputTokens:32e3,pricingPerMTok:{input:1.75,output:14,cacheRead:.4375},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"fast",quality:"high",accuracy:"high"},useCases:{coding:9,creative:9,analysis:9,conversation:10,reasoning:9,translation:9,summarization:9},category:"general"}},"gpt-5.2-pro":{aliases:["gpt52-pro","gpt-5.2-professional","openai-science"],displayName:"GPT-5.2 Pro",contextWindow:4e5,maxOutputTokens:128e3,pricingPerMTok:{input:1.75,output:14,cacheRead:.4375},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"slow",quality:"high",accuracy:"high"},useCases:{coding:10,creative:9,analysis:10,conversation:8,reasoning:10,translation:9,summarization:9},category:"reasoning"}},"gpt-4.1":{aliases:["gpt-4.1","gpt41","million-context"],displayName:"GPT-4.1",contextWindow:1047576,maxOutputTokens:128e3,pricingPerMTok:{input:2,output:8,cacheRead:.5},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:10,creative:8,analysis:9,conversation:8,reasoning:9,translation:8,summarization:9},category:"coding"}},"gpt-4.1-mini":{aliases:["gpt-4.1-mini","gpt41-mini"],displayName:"GPT-4.1 Mini",contextWindow:1047576,maxOutputTokens:128e3,pricingPerMTok:{input:.4,output:1.6,cacheRead:.1},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"fast",quality:"high",accuracy:"high"},useCases:{coding:9,creative:7,analysis:8,conversation:8,reasoning:8,translation:8,summarization:9},category:"coding"}},"gpt-4.1-nano":{aliases:["gpt-4.1-nano","gpt41-nano"],displayName:"GPT-4.1 Nano",contextWindow:1047576,maxOutputTokens:128e3,pricingPerMTok:{input:.1,output:.4,cacheRead:.025},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"fast",quality:"medium",accuracy:"medium"},useCases:{coding:7,creative:6,analysis:7,conversation:7,reasoning:7,translation:7,summarization:8},category:"coding"}},"o3-pro":{aliases:["o3-pro","o3-professional"],displayName:"O3 Pro",contextWindow:2e5,maxOutputTokens:1e5,pricingPerMTok:{input:2,output:8,cacheRead:.5},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"slow",quality:"high",accuracy:"high"},useCases:{coding:10,creative:7,analysis:10,conversation:6,reasoning:10,translation:6,summarization:7},category:"reasoning"}},"o4-mini":{aliases:["o4-mini","o4-fast"],displayName:"O4 Mini",contextWindow:2e5,maxOutputTokens:1e5,pricingPerMTok:{input:1.1,output:4.4,cacheRead:.275},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:9,creative:6,analysis:9,conversation:7,reasoning:10,translation:6,summarization:7},category:"reasoning"}},o1:{aliases:["o1-full","o1-premium"],displayName:"O1",contextWindow:2e5,maxOutputTokens:32768,pricingPerMTok:{input:15,output:60,cacheRead:3.75},vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"slow",quality:"high",accuracy:"high"},useCases:{coding:10,creative:7,analysis:10,conversation:6,reasoning:10,translation:6,summarization:7},category:"reasoning"}},"o1-mini":{aliases:["o1-mini","o1-budget"],displayName:"O1 Mini",contextWindow:128e3,maxOutputTokens:65536,pricingPerMTok:{input:.55,output:2.2,cacheRead:.1375},vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:8,creative:5,analysis:8,conversation:6,reasoning:8,translation:5,summarization:6},category:"reasoning"}},"gpt-4":{aliases:["gpt4","gpt-4-base"],displayName:"GPT-4",contextWindow:8192,maxOutputTokens:4096,pricingPerMTok:{input:30,output:60},vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"slow",quality:"high",accuracy:"high"},useCases:{coding:8,creative:8,analysis:8,conversation:8,reasoning:8,translation:8,summarization:8},category:"general"}},"gpt-4-turbo":{aliases:["gpt4-turbo","gpt-4-turbo-preview"],displayName:"GPT-4 Turbo",contextWindow:128e3,maxOutputTokens:4096,pricingPerMTok:{input:10,output:30},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0,curated:{performance:{speed:"medium",quality:"high",accuracy:"high"},useCases:{coding:8,creative:8,analysis:9,conversation:8,reasoning:8,translation:8,summarization:8},category:"general"}},"gpt-3.5-turbo":{aliases:["gpt35","gpt-3.5","chatgpt"],displayName:"GPT-3.5 Turbo",contextWindow:16385,maxOutputTokens:4096,pricingPerMTok:{input:.5,output:1},vision:!1,functionCalling:!0,reasoning:!1,jsonMode:!0,curated:{performance:{speed:"fast",quality:"medium",accuracy:"medium"},useCases:{coding:6,creative:6,analysis:6,conversation:7,reasoning:5,translation:7,summarization:7},category:"general"}}}}}}),Rq,p_e=b({"src/lib/models/manifests/google-ai.ts"(){"use strict";Rq={defaultContextWindow:1048576,models:{"gemini-2.5-pro":{aliases:["gemini-pro","google-flagship","best-analysis"],displayName:"Gemini 2.5 Pro",contextWindow:2097152,maxOutputTokens:8192,pricingPerMTok:{input:1.25,output:10},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"gemini-2.5-flash":{aliases:["gemini-flash","google-fast","best-value"],displayName:"Gemini 2.5 Flash",contextWindow:1048576,maxOutputTokens:8192,pricingPerMTok:{input:.3,output:2.5},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0}}}}}),Pq,h_e=b({"src/lib/models/manifests/vertex.ts"(){"use strict";Pq={defaultContextWindow:1048576,models:{_default:{aliases:[],contextWindow:1048576,maxOutputTokens:64e3,vision:!0,functionCalling:!0}}}}}),Mq,f_e=b({"src/lib/models/manifests/bedrock.ts"(){"use strict";Mq={defaultContextWindow:2e5,models:{"amazon.nova-premier-v1:0":{aliases:["nova-premier","aws-flagship"],displayName:"Amazon Nova Premier",contextWindow:1e6,maxOutputTokens:25e3,vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!1},"amazon.nova-pro-v1:0":{aliases:["nova-pro","aws-balanced"],displayName:"Amazon Nova Pro",contextWindow:3e5,maxOutputTokens:5e3,vision:!0,functionCalling:!0,reasoning:!1,jsonMode:!1},"amazon.nova-lite-v1:0":{aliases:["nova-lite","aws-lite","aws-cheap"],displayName:"Amazon Nova Lite",contextWindow:3e5,maxOutputTokens:5e3,vision:!0,functionCalling:!0,reasoning:!1,jsonMode:!1},"anthropic.claude-opus-4-5-20251101-v1:0":{aliases:["bedrock-claude-4.5-opus","bedrock-claude-flagship"],displayName:"Claude 4.5 Opus (Bedrock)",contextWindow:2e5,maxOutputTokens:64e3,pricingPerMTok:{input:5,output:25},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"meta.llama4-maverick-17b-instruct-v1:0":{aliases:["bedrock-llama4","bedrock-llama-maverick"],displayName:"Llama 4 Maverick (Bedrock)",contextWindow:1e6,maxOutputTokens:8192,vision:!0,functionCalling:!0,reasoning:!1,jsonMode:!1}}}}}),Oq,g_e=b({"src/lib/models/manifests/azure.ts"(){"use strict";Oq={defaultContextWindow:128e3,models:{"gpt-5.1":{aliases:["azure-gpt-5.1","gpt51-azure","azure-flagship"],displayName:"GPT-5.1 (Azure)",contextWindow:3e5,maxOutputTokens:64e3,pricingPerMTok:{input:.625,output:5},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"gpt-5.1-chat":{aliases:["azure-gpt-5.1-chat","gpt51-chat-azure"],displayName:"GPT-5.1 Chat (Azure)",contextWindow:3e5,maxOutputTokens:32e3,pricingPerMTok:{input:.625,output:5},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"gpt-5.1-codex":{aliases:["azure-gpt-5.1-codex","gpt51-codex-azure","azure-code"],displayName:"GPT-5.1 Codex (Azure)",contextWindow:3e5,maxOutputTokens:64e3,pricingPerMTok:{input:1.25,output:10},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"gpt-5.1-codex-mini":{aliases:["azure-gpt-5.1-codex-mini","gpt51-codex-mini-azure"],displayName:"GPT-5.1 Codex Mini (Azure)",contextWindow:2e5,maxOutputTokens:32e3,pricingPerMTok:{input:1.25,output:10},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"gpt-5.1-codex-max":{aliases:["azure-gpt-5.1-codex-max","gpt51-codex-max-azure","azure-enterprise"],displayName:"GPT-5.1 Codex Max (Azure)",contextWindow:5e5,maxOutputTokens:128e3,pricingPerMTok:{input:1.25,output:10},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"gpt-5-pro":{aliases:["azure-gpt-5-pro","gpt5-pro-azure"],displayName:"GPT-5 Pro (Azure)",contextWindow:256e3,maxOutputTokens:64e3,pricingPerMTok:{input:1.25,output:10},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"gpt-5-turbo":{aliases:["azure-gpt-5-turbo","gpt5-turbo-azure"],displayName:"GPT-5 Turbo (Azure)",contextWindow:2e5,maxOutputTokens:32768,pricingPerMTok:{input:1.25,output:10},vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0}}}}}),Dq,y_e=b({"src/lib/models/manifests/mistral.ts"(){"use strict";Dq={defaultContextWindow:128e3,models:{"mistral-large-latest":{aliases:["mistral-large","mistral-flagship"],displayName:"Mistral Large",contextWindow:131072,maxOutputTokens:8192,pricingPerMTok:{input:2,output:6},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"mistral-small-latest":{aliases:["mistral-small","mistral-cheap"],displayName:"Mistral Small",contextWindow:32768,maxOutputTokens:8192,pricingPerMTok:{input:.2,output:.6},vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"codestral-latest":{aliases:["codestral","mistral-code"],displayName:"Codestral",contextWindow:32768,maxOutputTokens:8192,pricingPerMTok:{input:.3,output:.9},vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0},"pixtral-large":{aliases:["pixtral","mistral-vision"],displayName:"Pixtral Large",contextWindow:131072,maxOutputTokens:8192,vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0}}}}}),Nq,v_e=b({"src/lib/models/manifests/ollama.ts"(){"use strict";Nq={defaultContextWindow:128e3,models:{"llama4:latest":{aliases:["llama4","llama4-local"],displayName:"Llama 4",contextWindow:131072,maxOutputTokens:8192,vision:!0,functionCalling:!0,reasoning:!0,jsonMode:!0},"llama3.3:latest":{aliases:["llama3.3","llama3.3-local"],displayName:"Llama 3.3",contextWindow:131072,maxOutputTokens:8192,vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0},"llama3.2:latest":{aliases:["llama3.2","llama","local","offline"],displayName:"Llama 3.2 Latest",contextWindow:131072,maxOutputTokens:8192,vision:!1,functionCalling:!1,reasoning:!0,jsonMode:!1},"deepseek-r1:70b":{aliases:["deepseek-r1","deepseek-reasoning","local-reasoning"],displayName:"DeepSeek-R1 70B",contextWindow:65536,maxOutputTokens:8192,vision:!1,functionCalling:!1,reasoning:!0,jsonMode:!1},"qwen3:72b":{aliases:["qwen3","qwen3-72b-local"],displayName:"Qwen 3 72B",contextWindow:131072,maxOutputTokens:8192,vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0},"mistral-large:latest":{aliases:["mistral-large-local"],displayName:"Mistral Large (Local)",contextWindow:131072,maxOutputTokens:8192,vision:!1,functionCalling:!0,reasoning:!0,jsonMode:!0}}}}}),Lq,T_e=b({"src/lib/models/manifests/litellm.ts"(){"use strict";Lq={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:128e3,vision:!1,functionCalling:!1}}}}});function YCr(e){if(!e)return!1;for(const t of MS){if(e===t)return!0;const r=e.indexOf(t);if(r===-1)continue;const n=r===0?"":e[r-1],o=e[r+t.length]??"",s=i=>i===""||/[-_:./@]/.test(i);if(s(n)&&s(o))return!0}return!1}function Ih(e){return e===null?null:e??w_e}function ld(e){const t={};for(const[r,n]of Object.entries(e.models))r!=="_default"&&(t[r]=n.maxOutputTokens);return t}var MS,Fq,$q,Bs,Rh,OS,w_e,E_e,Y1,S_e,Ph,Es,Uq,zs,ga,b_e,XCr,Lo=b({"src/lib/core/constants.ts"(){"use strict";xq(),m_e(),p_e(),h_e(),f_e(),g_e(),y_e(),v_e(),T_e(),MS=["gemini-3-pro-image-preview","gemini-2.5-flash-image","gemini-3.1-flash-image-preview","stable-image-ultra","stable-image-core","sd3.5-large","sd3.5-large-turbo","sd3.5-medium","V_1","V_1_TURBO","V_2","V_2_TURBO","V_2A","V_2A_TURBO","V_3","recraftv3","recraftv2","gpt-image-1","dall-e-3","dall-e-2","black-forest-labs/flux","stability-ai/sdxl","stability-ai/stable-diffusion"],Fq=[...MS,"gemini-3.1-pro-preview","gemini-3.1-flash-lite-preview","gemini-3.1-pro-preview-customtools","gemini-3-pro-preview","gemini-3-pro-preview-11-2025","gemini-3-pro-latest","gemini-3-flash-preview"],$q=.7,Bs=200,Rh=2,OS=3e5,w_e=3e5,E_e=12e4,Y1=.85,S_e=3e4,Ph=5e3,Es={min:1,max:500,default:Bs},Uq={anthropic:{default:64e3,...ld(J1)},openai:{default:128e3,...ld(Iq)},"google-ai":{default:64e3,...ld(Rq)},vertex:{default:64e3,...ld(Pq)},bedrock:{default:64e3,...ld(Mq)},azure:{default:128e3,...ld(Oq)},mistral:{default:128e3,...ld(Dq)},ollama:{default:64e3,...ld(Nq)},litellm:{default:128e3,...ld(Lq)},default:64e3},zs={MAX_SIZE_MB:20,DEFAULT_MAX_PAGES:20,MAX_SCALE:10,MIN_SCALE:.1,DEFAULT_SCALE:1.5,PAGE_COUNT_TIMEOUT_MS:5e3,DEFAULT_MAX_CANVAS_PIXELS:16777216,MIN_EFFECTIVE_SCALE:.1},ga={MAX_PROMPT_LENGTH:1e6,HIGH_MEMORY_THRESHOLD:100,LONG_TIMEOUT_WARNING:3e5,DEFAULT_CONCURRENCY_LIMIT:3,MAX_CONCURRENCY_LIMIT:5,DEFAULT_RETRY_ATTEMPTS:3,DEFAULT_INITIAL_DELAY:1e3,DEFAULT_MAX_DELAY:3e4,DEFAULT_BACKOFF_MULTIPLIER:2},b_e=15e3,XCr={maxTokens:(()=>{if(!process.env.NEUROLINK_DEFAULT_MAX_TOKENS)return;const e=parseInt(process.env.NEUROLINK_DEFAULT_MAX_TOKENS,10);return Number.isFinite(e)?e:void 0})(),temperature:process.env.NEUROLINK_DEFAULT_TEMPERATURE?(()=>{const e=parseFloat(process.env.NEUROLINK_DEFAULT_TEMPERATURE);return Number.isFinite(e)?e:$q})():$q}}}),__e,ZCr=b({"src/lib/models/manifests/openai-compatible.ts"(){"use strict";__e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),C_e,QCr=b({"src/lib/models/manifests/openrouter.ts"(){"use strict";C_e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),A_e,eAr=b({"src/lib/models/manifests/huggingface.ts"(){"use strict";A_e={defaultContextWindow:32e3,models:{_default:{aliases:[],contextWindow:32e3,maxOutputTokens:32e3,vision:!1,functionCalling:!0}}}}}),k_e,tAr=b({"src/lib/models/manifests/sagemaker.ts"(){"use strict";k_e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),x_e,rAr=b({"src/lib/models/manifests/deepseek.ts"(){"use strict";x_e={defaultContextWindow:1048576,models:{_default:{aliases:[],contextWindow:1048576,maxOutputTokens:393216,vision:!1,functionCalling:!1}}}}}),I_e,nAr=b({"src/lib/models/manifests/nvidia-nim.ts"(){"use strict";I_e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),R_e,oAr=b({"src/lib/models/manifests/lm-studio.ts"(){"use strict";R_e={defaultContextWindow:8192,models:{_default:{aliases:[],contextWindow:8192,maxOutputTokens:8192,vision:!1,functionCalling:!1}}}}}),P_e,sAr=b({"src/lib/models/manifests/llamacpp.ts"(){"use strict";P_e={defaultContextWindow:8192,models:{_default:{aliases:[],contextWindow:8192,maxOutputTokens:8192,vision:!1,functionCalling:!1}}}}}),M_e,iAr=b({"src/lib/models/manifests/xai.ts"(){"use strict";M_e={defaultContextWindow:131072,models:{_default:{aliases:[],contextWindow:131072,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),O_e,aAr=b({"src/lib/models/manifests/groq.ts"(){"use strict";O_e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),D_e,cAr=b({"src/lib/models/manifests/typesafe.ts"(){"use strict";D_e={defaultContextWindow:33e3,models:{_default:{aliases:["jev"],contextWindow:33e3,maxOutputTokens:1024,vision:!1,functionCalling:!1},"jev-latest":{aliases:["jev"],displayName:"Jev (latest)",contextWindow:33e3,maxOutputTokens:1024,vision:!1,functionCalling:!1},"jev-preview":{aliases:[],displayName:"Jev (preview)",contextWindow:33e3,maxOutputTokens:1024,vision:!1,functionCalling:!1}}}}}),N_e,lAr=b({"src/lib/models/manifests/laya.ts"(){"use strict";N_e={defaultContextWindow:1024,models:{_default:{aliases:[],contextWindow:1024,maxOutputTokens:256,vision:!1,functionCalling:!1},"typed-decisions":{aliases:[],displayName:"Laya (typed decisions)",contextWindow:1024,maxOutputTokens:256,vision:!1,functionCalling:!1},multilingual:{aliases:[],displayName:"Laya (multilingual)",contextWindow:1024,maxOutputTokens:256,vision:!1,functionCalling:!1},english:{aliases:[],displayName:"Laya (English)",contextWindow:512,maxOutputTokens:256,vision:!1,functionCalling:!1},auto:{aliases:[],displayName:"Laya (routed by language)",contextWindow:512,maxOutputTokens:256,vision:!1,functionCalling:!1}}}}}),L_e,uAr=b({"src/lib/models/manifests/cohere.ts"(){"use strict";L_e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),F_e,dAr=b({"src/lib/models/manifests/together-ai.ts"(){"use strict";F_e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),$_e,mAr=b({"src/lib/models/manifests/fireworks.ts"(){"use strict";$_e={defaultContextWindow:128e3,models:{_default:{aliases:[],contextWindow:128e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),U_e,pAr=b({"src/lib/models/manifests/perplexity.ts"(){"use strict";U_e={defaultContextWindow:127e3,models:{_default:{aliases:[],contextWindow:127e3,maxOutputTokens:64e3,vision:!1,functionCalling:!1}}}}}),B_e,hAr=b({"src/lib/models/manifests/cloudflare.ts"(){"use strict";B_e={defaultContextWindow:8192,models:{_default:{aliases:[],contextWindow:8192,maxOutputTokens:8192,vision:!1,functionCalling:!1}}}}}),z_e,fAr=b({"src/lib/models/manifests/replicate.ts"(){"use strict";z_e={defaultContextWindow:32768,models:{_default:{aliases:[],contextWindow:32768,maxOutputTokens:32768,vision:!1,functionCalling:!1}}}}}),q_e,gAr=b({"src/lib/models/manifests/voyage.ts"(){"use strict";q_e={defaultContextWindow:32e3,models:{_default:{aliases:[],contextWindow:32e3,maxOutputTokens:32e3,vision:!1,functionCalling:!1}}}}}),G_e,yAr=b({"src/lib/models/manifests/jina.ts"(){"use strict";G_e={defaultContextWindow:8192,models:{_default:{aliases:[],contextWindow:8192,maxOutputTokens:8192,vision:!1,functionCalling:!1}}}}}),j_e,vAr=b({"src/lib/models/manifests/stability.ts"(){"use strict";j_e={defaultContextWindow:2e3,models:{_default:{aliases:[],contextWindow:2e3,maxOutputTokens:2e3,vision:!1,functionCalling:!1}}}}}),H_e,TAr=b({"src/lib/models/manifests/ideogram.ts"(){"use strict";H_e={defaultContextWindow:2e3,models:{_default:{aliases:[],contextWindow:2e3,maxOutputTokens:2e3,vision:!1,functionCalling:!1}}}}}),V_e,wAr=b({"src/lib/models/manifests/recraft.ts"(){"use strict";V_e={defaultContextWindow:2e3,models:{_default:{aliases:[],contextWindow:2e3,maxOutputTokens:2e3,vision:!1,functionCalling:!1}}}}});function EAr(e){const t=e.capabilities.tools===!0,r=Object.fromEntries(Object.entries(e.models.catalog).map(([n,o])=>[n,{aliases:[],contextWindow:o.contextWindow??e.models.defaultContextWindow,maxOutputTokens:e.models.defaultMaxOutputTokens,vision:o.vision,functionCalling:t}]));return{defaultContextWindow:e.models.defaultContextWindow,models:{_default:{aliases:[],contextWindow:e.models.defaultContextWindow,maxOutputTokens:e.models.defaultMaxOutputTokens,vision:!1,functionCalling:t},...r}}}function W_e(e){return NS[e]}function K_e(){return Object.keys(NS)}function DS(e,t,r){if(!e.familyRules)return r;let n=r;for(const o of e.familyRules)o.pattern.test(t)&&(n={...n,...o.patch});return n}function Bq(e,t){const r=NS[e];if(!r)return;const n=r.models[t];if(n)return DS(r,t,n);const o=Object.entries(r.models).find(([s,i])=>s!=="_default"&&i.aliases.includes(t));if(o)return DS(r,t,o[1])}function SAr(e,t){const r=NS[e];if(!r)return;const n=r.models[t];if(n)return DS(r,t,n);const o=Object.entries(r.models).find(([a,c])=>a!=="_default"&&c.aliases.includes(t));if(o)return DS(r,t,o[1]);const i=Object.keys(r.models).filter(a=>a!=="_default").sort((a,c)=>c.length-a.length).find(a=>t.startsWith(a));if(i)return DS(r,t,r.models[i])}var zq,NS,X1=b({"src/lib/models/manifestRegistry.ts"(){"use strict";s0(),xq(),m_e(),g_e(),f_e(),v_e(),y_e(),p_e(),ZCr(),QCr(),h_e(),eAr(),T_e(),tAr(),rAr(),nAr(),oAr(),sAr(),iAr(),aAr(),cAr(),lAr(),uAr(),dAr(),mAr(),pAr(),hAr(),fAr(),gAr(),yAr(),vAr(),TAr(),wAr(),zq=e=>{const t=o0().find(r=>r.id===e);if(!t)throw new Error(`No catalog JSON entry found for provider "${e}"`);return EAr(t)},NS={anthropic:J1,openai:Iq,azure:Oq,bedrock:Mq,ollama:Nq,mistral:Dq,"google-ai":Rq,"openai-compatible":__e,openrouter:C_e,vertex:Pq,huggingface:A_e,litellm:Lq,sagemaker:k_e,deepseek:x_e,"nvidia-nim":I_e,"lm-studio":R_e,llamacpp:P_e,xai:M_e,groq:O_e,typesafe:D_e,laya:N_e,cerebras:zq("cerebras"),sambanova:zq("sambanova"),cohere:L_e,"together-ai":F_e,fireworks:$_e,perplexity:U_e,cloudflare:B_e,replicate:z_e,voyage:q_e,jina:G_e,stability:j_e,ideogram:H_e,recraft:V_e}}}),J_e={};ee(J_e,{MODEL_ALIASES:()=>du,MODEL_REGISTRY:()=>ya,USE_CASE_RECOMMENDATIONS:()=>Gq,calculateCost:()=>rCe,formatModelForDisplay:()=>AAr,getAllModels:()=>qm,getAvailableProviders:()=>tCe,getModelById:()=>X_e,getModelsByProvider:()=>eCe,modelSupports:()=>Z_e,modelSupportsSamplingParams:()=>Q_e,resolveProviderModelAlias:()=>CAr,resolveSamplingParams:()=>hl});function bAr(e){return/mini|nano|haiku|flash|lite/i.test(e)?"fast":/opus|^o1|^o3|-pro$/i.test(e)?"slow":"medium"}function Y_e(e){return e.reasoning?"high":"medium"}function _Ar(){const e={};for(const t of K_e()){const r=W_e(t);if(r)for(const[n,o]of Object.entries(r.models)){if(n==="_default"||!o.pricingPerMTok)continue;if(e[n]){p.debug(`[modelRegistry] Manifest id collision: "${n}" already derived from ${e[n].provider}; keeping first, skipping ${t}`);continue}const s=o.reasoning?9:6,i=qq[n];e[n]={id:n,name:o.displayName??n,provider:t,description:o.displayName??n,capabilities:{vision:o.vision,functionCalling:o.functionCalling,codeGeneration:!0,reasoning:o.reasoning??!1,multimodal:o.vision||o.nativeAudio===!0,streaming:!0,jsonMode:o.jsonMode??!1,samplingParams:o.samplingParams},pricing:{inputCostPer1K:o.pricingPerMTok.input/1e3,outputCostPer1K:o.pricingPerMTok.output/1e3,currency:"USD"},performance:o.curated?.performance??{speed:bAr(n),quality:Y_e(o),accuracy:Y_e(o)},limits:{maxContextTokens:o.contextWindow,maxOutputTokens:o.maxOutputTokens,...i?.limits?.maxRequestsPerMinute!==void 0?{maxRequestsPerMinute:i.limits.maxRequestsPerMinute}:{}},useCases:o.curated?.useCases??{coding:o.functionCalling?8:5,creative:o.vision?7:6,analysis:s,conversation:7,reasoning:s,translation:6,summarization:7},aliases:o.aliases,deprecated:i?.deprecated??!1,...i?.releaseDate!==void 0?{releaseDate:i.releaseDate}:{},isLocal:t==="ollama"||t==="lm-studio"||t==="llamacpp",category:o.curated?.category??(o.reasoning?"reasoning":"general")}}}return e}function qm(){return Object.values(ya)}function X_e(e){return ya[e]}function CAr(e,t){const r=t.toLowerCase();if(ya[t]||ya[r])return null;const n=du[r];if(!n)return null;const o=ya[n];return!o||o.provider!==e.toLowerCase()?null:o.id}function Z_e(e,t,r){const n=r.toLowerCase(),o=du[n]??n,s=ya[o];return!s||s.provider!==t.toLowerCase()?!0:s.capabilities[e]??!0}function Q_e(e,t){const r=(t??"").toLowerCase();if(!r)return!0;const n=du[r]??r,o=ya[n];return o&&o.provider===e.toLowerCase()&&o.capabilities.samplingParams!==void 0?o.capabilities.samplingParams:!nCe.some(s=>s.test(n)||s.test(r))}function hl(e,t,r,n){return Q_e(e,t)?r:((r.temperature!==void 0||r.topP!==void 0)&&p.debug(`[ModelRegistry] Stripping sampling params for ${e}/${t} at ${n} \u2014 model rejects temperature/topP`,{provider:e,model:t,site:n,hadTemperature:r.temperature!==void 0,hadTopP:r.topP!==void 0}),{})}function eCe(e){return Object.values(ya).filter(t=>t.provider===e)}function tCe(){return K_e()}function rCe(e,t,r){const n=t/1e3*e.pricing.inputCostPer1K,o=r/1e3*e.pricing.outputCostPer1K;return n+o}function AAr(e){const t={id:e.id,name:e.name,provider:e.provider,description:e.description,category:e.category,capabilities:Object.entries(e.capabilities).filter(([r,n])=>n).map(([r])=>r),pricing:{input:`$${e.pricing.inputCostPer1K.toFixed(6)}/1K tokens`,output:`$${e.pricing.outputCostPer1K.toFixed(6)}/1K tokens`},performance:{speed:e.performance.speed,quality:e.performance.quality,accuracy:e.performance.accuracy},contextSize:`${(e.limits.maxContextTokens/1e3).toFixed(0)}K tokens`,maxOutput:`${(e.limits.maxOutputTokens/1e3).toFixed(0)}K tokens`,aliases:e.aliases};return e.releaseDate&&(t.releaseDate=e.releaseDate),t}var qq,ya,du,Gq,nCe,ud=b({"src/lib/models/modelRegistry.ts"(){"use strict";ut(),z(),X1(),qq={"gpt-4o":{id:"gpt-4o",name:"GPT-4 Omni",provider:"openai",description:"Most capable OpenAI model with vision and advanced reasoning",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.005,outputCostPer1K:.015,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:128e3,maxOutputTokens:4096,maxRequestsPerMinute:500},useCases:{coding:9,creative:8,analysis:9,conversation:9,reasoning:9,translation:8,summarization:8},aliases:["gpt4o","gpt-4-omni","openai-flagship"],deprecated:!1,isLocal:!1,releaseDate:"2024-05-13",category:"general"},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4 Omni Mini",provider:"openai",description:"Fast and cost-effective model with strong performance",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:15e-5,outputCostPer1K:6e-4,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:128e3,maxOutputTokens:16384,maxRequestsPerMinute:1e3},useCases:{coding:8,creative:7,analysis:8,conversation:8,reasoning:8,translation:8,summarization:9},aliases:["gpt4o-mini","gpt-4-mini","fastest","cheap"],deprecated:!1,isLocal:!1,releaseDate:"2024-07-18",category:"general"},"gpt-5":{id:"gpt-5",name:"GPT-5",provider:"openai",description:"OpenAI's most advanced model with breakthrough reasoning and multimodal capabilities",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.01,outputCostPer1K:.03,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:256e3,maxOutputTokens:32768,maxRequestsPerMinute:200},useCases:{coding:10,creative:10,analysis:10,conversation:10,reasoning:10,translation:9,summarization:9},aliases:["gpt5","gpt-5-flagship","openai-latest"],deprecated:!1,isLocal:!1,releaseDate:"2025-08-07",category:"reasoning"},"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",provider:"openai",description:"Fast and efficient GPT-5 variant for everyday tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.002,outputCostPer1K:.006,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:128e3,maxOutputTokens:16384,maxRequestsPerMinute:500},useCases:{coding:8,creative:8,analysis:8,conversation:9,reasoning:8,translation:8,summarization:9},aliases:["gpt5-mini","gpt-5-fast"],deprecated:!1,isLocal:!1,releaseDate:"2025-08-07",category:"general"},o3:{id:"o3",name:"O3",provider:"openai",description:"Advanced reasoning model with extended thinking capabilities for complex tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.015,outputCostPer1K:.06,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:1e5,maxRequestsPerMinute:100},useCases:{coding:10,creative:8,analysis:10,conversation:7,reasoning:10,translation:7,summarization:8},aliases:["o3-reasoning","o3-thinking"],deprecated:!1,isLocal:!1,releaseDate:"2025-01-31",category:"reasoning"},"o3-mini":{id:"o3-mini",name:"O3 Mini",provider:"openai",description:"Cost-effective reasoning model with strong logical capabilities",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.003,outputCostPer1K:.012,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:65536,maxRequestsPerMinute:200},useCases:{coding:9,creative:6,analysis:9,conversation:7,reasoning:9,translation:6,summarization:7},aliases:["o3-mini-reasoning"],deprecated:!1,isLocal:!1,releaseDate:"2025-01-31",category:"reasoning"},"gpt-5-nano":{id:"gpt-5-nano",name:"GPT-5 Nano",provider:"openai",description:"Fastest and most cost-effective GPT-5 variant for simple tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:5e-5,outputCostPer1K:4e-4,currency:"USD"},performance:{speed:"fast",quality:"medium",accuracy:"medium"},limits:{maxContextTokens:272e3,maxOutputTokens:128e3,maxRequestsPerMinute:2e3},useCases:{coding:6,creative:6,analysis:6,conversation:8,reasoning:6,translation:7,summarization:8},aliases:["gpt5-nano","gpt-5-cheapest"],deprecated:!1,isLocal:!1,releaseDate:"2025-08-07",category:"general"},"gpt-5.2":{id:"gpt-5.2",name:"GPT-5.2 Thinking",provider:"openai",description:"OpenAI's latest flagship model with deep reasoning capabilities, 100% on AIME 2025, 80% SWE-bench Verified",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.00175,outputCostPer1K:.014,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:256e3,maxOutputTokens:64e3,maxRequestsPerMinute:150},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["gpt52","gpt-5.2-thinking","openai-latest-reasoning"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-11",category:"reasoning"},"gpt-5.2-chat-latest":{id:"gpt-5.2-chat-latest",name:"GPT-5.2 Instant",provider:"openai",description:"Fast everyday model for quick tasks with excellent performance across all domains",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.00175,outputCostPer1K:.014,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:256e3,maxOutputTokens:32e3,maxRequestsPerMinute:300},useCases:{coding:9,creative:9,analysis:9,conversation:10,reasoning:9,translation:9,summarization:9},aliases:["gpt52-chat","gpt-5.2-instant","gpt52-fast"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-11",category:"general"},"gpt-5.2-pro":{id:"gpt-5.2-pro",name:"GPT-5.2 Pro",provider:"openai",description:"Highest quality model for science, math, and complex problem-solving with 92.4% GPQA Diamond performance",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.021,outputCostPer1K:.168,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:256e3,maxOutputTokens:128e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:9,analysis:10,conversation:8,reasoning:10,translation:9,summarization:9},aliases:["gpt52-pro","gpt-5.2-professional","openai-science"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-11",category:"reasoning"},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",provider:"openai",description:"Advanced coding model with 1 million token context window",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.002,outputCostPer1K:.008,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:200},useCases:{coding:10,creative:8,analysis:9,conversation:8,reasoning:9,translation:8,summarization:9},aliases:["gpt-4.1","gpt41","million-context"],deprecated:!1,isLocal:!1,releaseDate:"2025-04-14",category:"coding"},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",provider:"openai",description:"Fast GPT-4.1 variant with 1M context for efficient coding",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:4e-4,outputCostPer1K:.0016,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:500},useCases:{coding:9,creative:7,analysis:8,conversation:8,reasoning:8,translation:8,summarization:9},aliases:["gpt-4.1-mini","gpt41-mini"],deprecated:!1,isLocal:!1,releaseDate:"2025-04-14",category:"coding"},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",provider:"openai",description:"Most cost-effective GPT-4.1 variant with 1M context",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:1e-4,outputCostPer1K:4e-4,currency:"USD"},performance:{speed:"fast",quality:"medium",accuracy:"medium"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:1e3},useCases:{coding:7,creative:6,analysis:7,conversation:7,reasoning:7,translation:7,summarization:8},aliases:["gpt-4.1-nano","gpt41-nano"],deprecated:!1,isLocal:!1,releaseDate:"2025-04-14",category:"coding"},"o3-pro":{id:"o3-pro",name:"O3 Pro",provider:"openai",description:"Most powerful reasoning model for complex scientific and coding tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.03,outputCostPer1K:.12,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:1e5,maxRequestsPerMinute:50},useCases:{coding:10,creative:7,analysis:10,conversation:6,reasoning:10,translation:6,summarization:7},aliases:["o3-pro","o3-professional"],deprecated:!1,isLocal:!1,releaseDate:"2025-04-16",category:"reasoning"},"o4-mini":{id:"o4-mini",name:"O4 Mini",provider:"openai",description:"Fast reasoning model optimized for math, coding, and visual tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.003,outputCostPer1K:.012,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:1e5,maxRequestsPerMinute:200},useCases:{coding:9,creative:6,analysis:9,conversation:7,reasoning:10,translation:6,summarization:7},aliases:["o4-mini","o4-fast"],deprecated:!1,isLocal:!1,releaseDate:"2025-04-16",category:"reasoning"},o1:{id:"o1",name:"O1",provider:"openai",description:"Premium reasoning model with highest capability for mission-critical tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.15,outputCostPer1K:.6,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:128e3,maxOutputTokens:32768,maxRequestsPerMinute:50},useCases:{coding:10,creative:7,analysis:10,conversation:6,reasoning:10,translation:6,summarization:7},aliases:["o1-full","o1-premium"],deprecated:!1,isLocal:!1,releaseDate:"2024-09-12",category:"reasoning"},"o1-preview":{id:"o1-preview",name:"O1 Preview",provider:"openai",description:"Preview version of O1 reasoning model",capabilities:{vision:!1,functionCalling:!1,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.015,outputCostPer1K:.06,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:128e3,maxOutputTokens:32768,maxRequestsPerMinute:100},useCases:{coding:9,creative:6,analysis:9,conversation:6,reasoning:9,translation:5,summarization:6},aliases:["o1-preview"],deprecated:!1,isLocal:!1,releaseDate:"2024-09-12",category:"reasoning"},"o1-mini":{id:"o1-mini",name:"O1 Mini",provider:"openai",description:"Cost-effective O1 variant with strong reasoning capabilities",capabilities:{vision:!1,functionCalling:!1,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.003,outputCostPer1K:.012,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:128e3,maxOutputTokens:65536,maxRequestsPerMinute:200},useCases:{coding:8,creative:5,analysis:8,conversation:6,reasoning:8,translation:5,summarization:6},aliases:["o1-mini","o1-budget"],deprecated:!1,isLocal:!1,releaseDate:"2024-09-12",category:"reasoning"},"gpt-4":{id:"gpt-4",name:"GPT-4",provider:"openai",description:"Previous generation flagship model (legacy)",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.03,outputCostPer1K:.06,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:8192,maxOutputTokens:4096,maxRequestsPerMinute:200},useCases:{coding:8,creative:8,analysis:8,conversation:8,reasoning:8,translation:8,summarization:8},aliases:["gpt4","gpt-4-base"],deprecated:!0,isLocal:!1,releaseDate:"2023-03-14",category:"general"},"gpt-4-turbo":{id:"gpt-4-turbo",name:"GPT-4 Turbo",provider:"openai",description:"Faster GPT-4 variant with extended context (legacy)",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.01,outputCostPer1K:.03,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:128e3,maxOutputTokens:4096,maxRequestsPerMinute:500},useCases:{coding:8,creative:8,analysis:9,conversation:8,reasoning:8,translation:8,summarization:8},aliases:["gpt4-turbo","gpt-4-turbo-preview"],deprecated:!0,isLocal:!1,releaseDate:"2024-04-09",category:"general"},"gpt-3.5-turbo":{id:"gpt-3.5-turbo",name:"GPT-3.5 Turbo",provider:"openai",description:"Fast and cost-effective model for simpler tasks (legacy)",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!1,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:5e-4,outputCostPer1K:.0015,currency:"USD"},performance:{speed:"fast",quality:"medium",accuracy:"medium"},limits:{maxContextTokens:16385,maxOutputTokens:4096,maxRequestsPerMinute:3500},useCases:{coding:6,creative:6,analysis:6,conversation:7,reasoning:5,translation:7,summarization:7},aliases:["gpt35","gpt-3.5","chatgpt"],deprecated:!0,isLocal:!1,releaseDate:"2023-03-01",category:"general"},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",provider:"google-ai",description:"Google's most capable multimodal model with large context window",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.00125,outputCostPer1K:.005,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:2097152,maxOutputTokens:8192,maxRequestsPerMinute:360},useCases:{coding:9,creative:8,analysis:10,conversation:8,reasoning:9,translation:9,summarization:9},aliases:["gemini-pro","google-flagship","best-analysis"],deprecated:!1,isLocal:!1,releaseDate:"2024-12-11",category:"reasoning"},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",provider:"google-ai",description:"Fast and efficient multimodal model with large context",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:75e-6,outputCostPer1K:3e-4,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:1048576,maxOutputTokens:8192,maxRequestsPerMinute:1e3},useCases:{coding:8,creative:7,analysis:9,conversation:8,reasoning:8,translation:8,summarization:9},aliases:["gemini-flash","google-fast","best-value"],deprecated:!1,isLocal:!1,releaseDate:"2024-12-11",category:"general"},"claude-opus-4-5-20251101":{id:"claude-opus-4-5-20251101",name:"Claude Opus 4.5",provider:"anthropic",description:"Anthropic's most capable model with exceptional reasoning, coding, and multimodal capabilities",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.005,outputCostPer1K:.025,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:64e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["claude-4.5-opus","opus-4.5","anthropic-flagship"],deprecated:!1,isLocal:!1,releaseDate:"2025-11-24",category:"reasoning"},"claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",provider:"anthropic",description:"For complex agentic coding and enterprise work",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.005,outputCostPer1K:.025,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["opus-5","claude-opus-latest"],deprecated:!1,isLocal:!1,releaseDate:"2026-07-24",category:"reasoning"},"claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",provider:"anthropic",description:"The best combination of speed and intelligence",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.002,outputCostPer1K:.01,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:50},useCases:{coding:9,creative:9,analysis:9,conversation:9,reasoning:9,translation:9,summarization:9},aliases:["sonnet-5","claude-sonnet-latest"],deprecated:!1,isLocal:!1,releaseDate:"2026-06-30",category:"general"},"claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",provider:"anthropic",description:"Next-generation intelligence for long-running agents",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.01,outputCostPer1K:.05,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["fable-5"],deprecated:!1,isLocal:!1,releaseDate:"2026-06-09",category:"reasoning"},"claude-opus-4-8":{id:"claude-opus-4-8",name:"Claude Opus 4.8",provider:"anthropic",description:"Anthropic Opus 4.8, superseded by Claude Opus 5",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.005,outputCostPer1K:.025,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:9,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["opus-4.8"],deprecated:!1,isLocal:!1,releaseDate:"2026-05-28",category:"reasoning"},"claude-opus-4-7":{id:"claude-opus-4-7",name:"Claude Opus 4.7",provider:"anthropic",description:"Anthropic Opus 4.7, superseded by Claude Opus 4.8",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.005,outputCostPer1K:.025,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:1e6,maxOutputTokens:128e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:9,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["opus-4.7"],deprecated:!1,isLocal:!1,releaseDate:"2026-04-16",category:"reasoning"},"claude-sonnet-4-5-20250929":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",provider:"anthropic",description:"Balanced Claude model with excellent performance across all tasks including vision and reasoning",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.003,outputCostPer1K:.015,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:64e3,maxRequestsPerMinute:100},useCases:{coding:10,creative:9,analysis:9,conversation:9,reasoning:10,translation:8,summarization:8},aliases:["claude-4.5-sonnet","sonnet-4.5"],deprecated:!1,isLocal:!1,releaseDate:"2025-09-29",category:"coding"},"claude-haiku-4-5-20251001":{id:"claude-haiku-4-5-20251001",name:"Claude 4.5 Haiku",provider:"anthropic",description:"Latest fast and efficient Claude model with vision support",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.001,outputCostPer1K:.005,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:64e3,maxRequestsPerMinute:100},useCases:{coding:8,creative:8,analysis:8,conversation:9,reasoning:8,translation:8,summarization:9},aliases:["claude-4.5-haiku","claude-haiku-latest","haiku-4.5"],deprecated:!1,isLocal:!1,releaseDate:"2025-10-15",category:"general"},"claude-3-5-sonnet-20241022":{id:"claude-3-5-sonnet-20241022",name:"Claude 3.5 Sonnet",provider:"anthropic",description:"Anthropic's most capable model with excellent reasoning and coding",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.003,outputCostPer1K:.015,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:8192,maxRequestsPerMinute:50},useCases:{coding:10,creative:9,analysis:9,conversation:9,reasoning:10,translation:8,summarization:8},aliases:["claude-3.5-sonnet","claude-sonnet","best-coding","claude-latest"],deprecated:!1,isLocal:!1,releaseDate:"2024-10-22",category:"coding"},"claude-3-5-haiku-20241022":{id:"claude-3-5-haiku-20241022",name:"Claude 3.5 Haiku",provider:"anthropic",description:"Fast and efficient Claude model for quick tasks",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.001,outputCostPer1K:.005,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:8192,maxRequestsPerMinute:100},useCases:{coding:8,creative:7,analysis:8,conversation:8,reasoning:8,translation:8,summarization:9},aliases:["claude-3.5-haiku","claude-haiku","claude-fast"],deprecated:!1,isLocal:!1,releaseDate:"2024-10-22",category:"general"},"mistral-large-latest":{id:"mistral-large-latest",name:"Mistral Large",provider:"mistral",description:"Mistral's flagship model with excellent reasoning and multilingual capabilities",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.002,outputCostPer1K:.006,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:131072,maxOutputTokens:8192,maxRequestsPerMinute:100},useCases:{coding:9,creative:8,analysis:9,conversation:8,reasoning:9,translation:9,summarization:8},aliases:["mistral-large","mistral-flagship"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-01",category:"reasoning"},"mistral-small-latest":{id:"mistral-small-latest",name:"Mistral Small",provider:"mistral",description:"Efficient model for simple tasks and cost-sensitive applications",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.001,outputCostPer1K:.003,currency:"USD"},performance:{speed:"fast",quality:"medium",accuracy:"medium"},limits:{maxContextTokens:32768,maxOutputTokens:8192,maxRequestsPerMinute:200},useCases:{coding:6,creative:6,analysis:7,conversation:7,reasoning:6,translation:7,summarization:7},aliases:["mistral-small","mistral-cheap"],deprecated:!1,isLocal:!1,releaseDate:"2024-02-26",category:"general"},"codestral-latest":{id:"codestral-latest",name:"Codestral",provider:"mistral",description:"Specialized code generation model trained on 80+ programming languages",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.001,outputCostPer1K:.003,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:32768,maxOutputTokens:8192,maxRequestsPerMinute:200},useCases:{coding:10,creative:5,analysis:7,conversation:5,reasoning:8,translation:5,summarization:6},aliases:["codestral","mistral-code"],deprecated:!1,isLocal:!1,releaseDate:"2024-05-29",category:"coding"},"pixtral-large":{id:"pixtral-large",name:"Pixtral Large",provider:"mistral",description:"Multimodal vision-language model for image understanding",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.002,outputCostPer1K:.006,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:131072,maxOutputTokens:8192,maxRequestsPerMinute:100},useCases:{coding:8,creative:8,analysis:9,conversation:7,reasoning:8,translation:7,summarization:8},aliases:["pixtral","mistral-vision"],deprecated:!0,isLocal:!1,releaseDate:"2024-09-01",category:"vision"},"llama4:latest":{id:"llama4:latest",name:"Llama 4",provider:"ollama",description:"Latest Llama 4 with multimodal vision and tool capabilities, runs locally",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:0,outputCostPer1K:0,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:131072,maxOutputTokens:8192},useCases:{coding:9,creative:8,analysis:9,conversation:8,reasoning:9,translation:8,summarization:8},aliases:["llama4","llama4-local"],deprecated:!1,isLocal:!0,releaseDate:"2025-04-01",category:"reasoning"},"llama3.3:latest":{id:"llama3.3:latest",name:"Llama 3.3",provider:"ollama",description:"High-performance Llama 3.3 for local inference",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:0,outputCostPer1K:0,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:131072,maxOutputTokens:8192},useCases:{coding:8,creative:8,analysis:8,conversation:8,reasoning:8,translation:8,summarization:8},aliases:["llama3.3","llama3.3-local"],deprecated:!1,isLocal:!0,releaseDate:"2024-12-01",category:"general"},"llama3.2:latest":{id:"llama3.2:latest",name:"Llama 3.2 Latest",provider:"ollama",description:"Local Llama model for private, offline AI generation",capabilities:{vision:!1,functionCalling:!1,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:0,outputCostPer1K:0,currency:"USD"},performance:{speed:"fast",quality:"medium",accuracy:"medium"},limits:{maxContextTokens:131072,maxOutputTokens:8192},useCases:{coding:6,creative:7,analysis:6,conversation:7,reasoning:6,translation:6,summarization:6},aliases:["llama3.2","llama","local","offline"],deprecated:!1,isLocal:!0,releaseDate:"2024-09-25",category:"general"},"deepseek-r1:70b":{id:"deepseek-r1:70b",name:"DeepSeek-R1 70B",provider:"ollama",description:"State-of-the-art reasoning model rivaling OpenAI O1, runs locally",capabilities:{vision:!1,functionCalling:!1,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:0,outputCostPer1K:0,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:65536,maxOutputTokens:8192},useCases:{coding:10,creative:7,analysis:10,conversation:6,reasoning:10,translation:7,summarization:7},aliases:["deepseek-r1","deepseek-reasoning","local-reasoning"],deprecated:!1,isLocal:!0,releaseDate:"2025-01-20",category:"reasoning"},"qwen3:72b":{id:"qwen3:72b",name:"Qwen 3 72B",provider:"ollama",description:"Advanced reasoning and multilingual model from Alibaba",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:0,outputCostPer1K:0,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:131072,maxOutputTokens:8192},useCases:{coding:9,creative:8,analysis:9,conversation:8,reasoning:9,translation:9,summarization:8},aliases:["qwen3","qwen3-72b-local"],deprecated:!1,isLocal:!0,releaseDate:"2025-04-01",category:"reasoning"},"mistral-large:latest":{id:"mistral-large:latest",name:"Mistral Large (Local)",provider:"ollama",description:"Mistral Large model for local inference",capabilities:{vision:!1,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!1,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:0,outputCostPer1K:0,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:131072,maxOutputTokens:8192},useCases:{coding:8,creative:8,analysis:8,conversation:8,reasoning:8,translation:9,summarization:8},aliases:["mistral-large-local"],deprecated:!1,isLocal:!0,releaseDate:"2024-02-26",category:"general"},"amazon.nova-premier-v1:0":{id:"amazon.nova-premier-v1:0",name:"Amazon Nova Premier",provider:"bedrock",description:"Amazon's most capable foundation model with advanced multimodal capabilities",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.0025,outputCostPer1K:.0125,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:3e5,maxOutputTokens:5e3,maxRequestsPerMinute:100},useCases:{coding:9,creative:9,analysis:10,conversation:8,reasoning:9,translation:8,summarization:9},aliases:["nova-premier","aws-flagship"],deprecated:!1,isLocal:!1,releaseDate:"2025-01-01",category:"reasoning"},"amazon.nova-pro-v1:0":{id:"amazon.nova-pro-v1:0",name:"Amazon Nova Pro",provider:"bedrock",description:"Highly capable multimodal model balancing accuracy and speed",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:8e-4,outputCostPer1K:.0032,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:3e5,maxOutputTokens:5e3,maxRequestsPerMinute:200},useCases:{coding:8,creative:8,analysis:9,conversation:8,reasoning:8,translation:8,summarization:9},aliases:["nova-pro","aws-balanced"],deprecated:!1,isLocal:!1,releaseDate:"2024-12-03",category:"general"},"amazon.nova-lite-v1:0":{id:"amazon.nova-lite-v1:0",name:"Amazon Nova Lite",provider:"bedrock",description:"Fast and cost-effective multimodal model optimized for everyday tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:6e-5,outputCostPer1K:24e-5,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:3e5,maxOutputTokens:5e3,maxRequestsPerMinute:500},useCases:{coding:7,creative:7,analysis:8,conversation:8,reasoning:7,translation:8,summarization:9},aliases:["nova-lite","aws-lite","aws-cheap"],deprecated:!1,isLocal:!1,releaseDate:"2024-12-03",category:"general"},"anthropic.claude-opus-4-5-20251101-v1:0":{id:"anthropic.claude-opus-4-5-20251101-v1:0",name:"Claude 4.5 Opus (Bedrock)",provider:"bedrock",description:"Anthropic's most capable model available on Bedrock for enterprise workloads",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!1},pricing:{inputCostPer1K:.015,outputCostPer1K:.075,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:64e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["bedrock-claude-4.5-opus","bedrock-claude-flagship"],deprecated:!1,isLocal:!1,releaseDate:"2025-11-24",category:"reasoning"},"meta.llama4-maverick-17b-instruct-v1:0":{id:"meta.llama4-maverick-17b-instruct-v1:0",name:"Llama 4 Maverick (Bedrock)",provider:"bedrock",description:"Meta's latest Llama 4 model with vision on Bedrock",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:19e-5,outputCostPer1K:55e-5,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:131072,maxOutputTokens:8192,maxRequestsPerMinute:200},useCases:{coding:8,creative:8,analysis:8,conversation:8,reasoning:8,translation:8,summarization:8},aliases:["bedrock-llama4","bedrock-llama-maverick"],deprecated:!1,isLocal:!1,releaseDate:"2025-04-01",category:"general"},"gpt-5.1":{id:"gpt-5.1",name:"GPT-5.1 (Azure)",provider:"azure",description:"Azure's latest GPT-5.1 flagship model with enhanced reasoning and multimodal capabilities",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.015,outputCostPer1K:.045,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:3e5,maxOutputTokens:64e3,maxRequestsPerMinute:100},useCases:{coding:10,creative:10,analysis:10,conversation:10,reasoning:10,translation:9,summarization:9},aliases:["azure-gpt-5.1","gpt51-azure","azure-flagship"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-01",category:"reasoning"},"gpt-5.1-chat":{id:"gpt-5.1-chat",name:"GPT-5.1 Chat (Azure)",provider:"azure",description:"Azure GPT-5.1 optimized for conversational interactions",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.012,outputCostPer1K:.036,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:3e5,maxOutputTokens:32e3,maxRequestsPerMinute:150},useCases:{coding:8,creative:9,analysis:9,conversation:10,reasoning:9,translation:9,summarization:9},aliases:["azure-gpt-5.1-chat","gpt51-chat-azure"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-01",category:"general"},"gpt-5.1-codex":{id:"gpt-5.1-codex",name:"GPT-5.1 Codex (Azure)",provider:"azure",description:"Azure GPT-5.1 specialized for code generation and software development",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.012,outputCostPer1K:.036,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:3e5,maxOutputTokens:64e3,maxRequestsPerMinute:100},useCases:{coding:10,creative:7,analysis:9,conversation:7,reasoning:10,translation:7,summarization:8},aliases:["azure-gpt-5.1-codex","gpt51-codex-azure","azure-code"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-01",category:"coding"},"gpt-5.1-codex-mini":{id:"gpt-5.1-codex-mini",name:"GPT-5.1 Codex Mini (Azure)",provider:"azure",description:"Fast and efficient Azure code model for quick development tasks",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.003,outputCostPer1K:.009,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:32e3,maxRequestsPerMinute:300},useCases:{coding:9,creative:6,analysis:8,conversation:7,reasoning:8,translation:6,summarization:7},aliases:["azure-gpt-5.1-codex-mini","gpt51-codex-mini-azure"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-01",category:"coding"},"gpt-5.1-codex-max":{id:"gpt-5.1-codex-max",name:"GPT-5.1 Codex Max (Azure)",provider:"azure",description:"Azure's most powerful code model for complex enterprise development",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.025,outputCostPer1K:.075,currency:"USD"},performance:{speed:"slow",quality:"high",accuracy:"high"},limits:{maxContextTokens:5e5,maxOutputTokens:128e3,maxRequestsPerMinute:50},useCases:{coding:10,creative:8,analysis:10,conversation:7,reasoning:10,translation:7,summarization:8},aliases:["azure-gpt-5.1-codex-max","gpt51-codex-max-azure","azure-enterprise"],deprecated:!1,isLocal:!1,releaseDate:"2025-12-01",category:"coding"},"gpt-5-pro":{id:"gpt-5-pro",name:"GPT-5 Pro (Azure)",provider:"azure",description:"Azure GPT-5 Pro with enhanced enterprise features",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.02,outputCostPer1K:.06,currency:"USD"},performance:{speed:"medium",quality:"high",accuracy:"high"},limits:{maxContextTokens:256e3,maxOutputTokens:64e3,maxRequestsPerMinute:100},useCases:{coding:10,creative:10,analysis:10,conversation:9,reasoning:10,translation:9,summarization:9},aliases:["azure-gpt-5-pro","gpt5-pro-azure"],deprecated:!1,isLocal:!1,releaseDate:"2025-08-07",category:"reasoning"},"gpt-5-turbo":{id:"gpt-5-turbo",name:"GPT-5 Turbo (Azure)",provider:"azure",description:"Azure GPT-5 Turbo optimized for fast responses",capabilities:{vision:!0,functionCalling:!0,codeGeneration:!0,reasoning:!0,multimodal:!0,streaming:!0,jsonMode:!0},pricing:{inputCostPer1K:.008,outputCostPer1K:.024,currency:"USD"},performance:{speed:"fast",quality:"high",accuracy:"high"},limits:{maxContextTokens:2e5,maxOutputTokens:32768,maxRequestsPerMinute:300},useCases:{coding:9,creative:9,analysis:9,conversation:9,reasoning:9,translation:9,summarization:9},aliases:["azure-gpt-5-turbo","gpt5-turbo-azure"],deprecated:!0,isLocal:!1,releaseDate:"2025-08-07",category:"general"}},ya={...qq,..._Ar()},du={},Object.values(ya).forEach(e=>{e.aliases.forEach(t=>{du[t.toLowerCase()]=e.id})}),Object.entries(O1).forEach(([e,t])=>{du[e.toLowerCase().replace(/_/g,"-")]=t}),du.local="llama3.2:latest",Gq={coding:["gpt-5.2-pro","claude-opus-4-5-20251101","gpt-5.2","codestral-latest","claude-sonnet-4-5-20250929"],creative:["gpt-5.2","claude-opus-4-5-20251101","gpt-5","gemini-2.5-pro"],analysis:["gpt-5.2-pro","gemini-2.5-pro","claude-opus-4-5-20251101","o3","amazon.nova-premier-v1:0"],conversation:["gpt-5.2-chat-latest","gpt-5","claude-sonnet-4-5-20250929","gpt-4o"],reasoning:["gpt-5.2-pro","gpt-5.2","o3","claude-opus-4-5-20251101","gemini-2.5-pro","deepseek-r1:70b"],translation:["gemini-2.5-pro","mistral-large-latest","gpt-5"],summarization:["gemini-2.5-flash","gpt-5-mini","claude-haiku-4-5-20251001"],"cost-effective":["gemini-2.5-flash","gpt-4o-mini","mistral-small-latest","amazon.nova-lite-v1:0"],"high-quality":["gpt-5.2-pro","gpt-5.2","claude-opus-4-5-20251101","gemini-2.5-pro"],fast:["gpt-5.2-chat-latest","gpt-5-mini","gemini-2.5-flash","claude-haiku-4-5-20251001","o3-mini"],local:["llama4:latest","deepseek-r1:70b","qwen3:72b","llama3.3:latest"],multimodal:["gpt-5.2","gpt-5.2-pro","claude-opus-4-5-20251101","gemini-2.5-pro","amazon.nova-premier-v1:0"]},nCe=[/sonnet[-_.]?5(?![0-9])/i,/opus[-_.]?4[-_.]?(?:[7-9]|\d{2,})(?![0-9])/i,/opus[-_.]?5(?![0-9])/i,/fable/i,/mythos/i]}}),Z1={};ee(Z1,{ProviderFactory:()=>kr,createAIProvider:()=>kAr,resolveCredentialKey:()=>oCe});function oCe(e){const t=e.toLowerCase();return kr.getDescriptor(t)?.credentialsKey??t}async function kAr(e,t,r){return await kr.createProvider(e,t,void 0,void 0,r)}var kr,Ci=b({"src/lib/factories/providerFactory.ts"(){"use strict";z(),Bme(),Cc(),kr=class ys{static providers=new Map;static initialized=!1;static registerProvider(t,r,n,o=[],s){const i={constructor:r,defaultModel:n,aliases:o,descriptor:s};ys.providers.set(t.toLowerCase(),i),o.forEach(a=>{ys.providers.set(a.toLowerCase(),i)}),p.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(),c=ys.providers.get(a);if(!c)throw new Error(ys.describeUnresolvableProvider(i));try{let l=r;if(l){const{resolveProviderModelAlias:f}=await Promise.resolve().then(()=>(ud(),J_e)),g=ys.getDescriptor(a)?.name??a,y=f(g,l);y&&(p.debug("[ProviderFactory] Resolved model alias",{provider:g,requested:l,resolved:y}),l=y)}l||(i.toLowerCase().includes("vertex")?l=process.env.VERTEX_MODEL||"gemini-2.5-flash":i.toLowerCase().includes("bedrock")&&(l=process.env.BEDROCK_MODEL||process.env.BEDROCK_MODEL_ID),l=l||c.defaultModel);const u=oCe(a),d=s?s[u]:void 0;if(typeof c.constructor!="function")throw new Error(`Invalid constructor for provider ${t}: not a function`);const m=c.constructor(l,i,n,o,d);return m instanceof Promise?await m:m}catch(l){throw p.error(`Failed to create provider ${i}:`,l),new Error(`Failed to create provider ${i}: ${l}`,{cause:l})}}static hasProvider(t){return ys.providers.has(t.toLowerCase())}static describeUnresolvableProvider(t){const r=ys.getAvailableProviders();if(r.length===0)return`Cannot resolve provider "${t}": no providers are registered yet. ProviderRegistry.registerAllProviders() has not completed, so every name is unresolvable at this point \u2014 this is a lifecycle problem, not a bad name.`;const n=Array.from(new Set(r.map(c=>xh.get(c)??c))).sort(),o=r.filter(c=>{const l=xh.get(c);return l!==void 0&&l!==c}).sort(),s=xh.get(t.toLowerCase());if(s)return`Provider "${t}" is a recognised provider (${s}) but is not registered in this factory, so it cannot be constructed. Registered providers: ${n.join(", ")}.`;const i=X0r(t,[...n,...o]),a=i.length>0?` Did you mean: ${i.join(", ")}?`:"";return`Unknown provider: "${t}".${a} Valid providers: ${n.join(", ")}. Accepted aliases: ${o.join(", ")}.`}static getAvailableProviders(){return Array.from(ys.providers.keys()).filter((t,r,n)=>n.indexOf(t)===r)}static getProviderInfo(t){return ys.providers.get(t.toLowerCase())}static getDescriptor(t){const r=t.toLowerCase(),n=xh.get(r);if(n){const o=Ar.get(n);if(o)return o}return ys.providers.get(r)?.descriptor}static getAllDescriptors(){return pl}static normalizeProviderName(t){const r=t.toLowerCase();if(ys.providers.has(r))return r;const n=xh.get(r);if(n&&ys.providers.has(n))return n;for(const[o,s]of ys.providers.entries())if(s.aliases?.includes(r))return o;return null}static clearRegistrations(){ys.providers.clear(),ys.initialized=!1}static ensureInitialized(){ys.initialized||(ys.initializeDefaultProviders(),ys.initialized=!0)}static initializeDefaultProviders(){p.debug("BaseProvider factory pattern ready - providers registered by ProviderRegistry")}static async createBestProvider(t,r,n,o,s){return await ys.createProvider(t,r,o,void 0,s)}}}}),sCe,xAr=b({"src/lib/providers/openaiCompatCatalog.ts"(){"use strict";s0(),sCe=xCr()}});function i0(e){const t=[];for(const r of dd)r.kind===e&&(t.push(r.name),r.aliases&&t.push(...r.aliases));return t}function IAr(e){const t=dd.find(r=>r.kind===e);if(!t)throw new Error(`No media handler catalog entries registered for kind "${e}"`);return t.name}var dd,a0=b({"src/lib/factories/mediaHandlerCatalog.ts"(){"use strict";dd=[{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"}]}}),mu={};ee(mu,{Agent:()=>pCe,AsyncLocalStorage:()=>kCe,Buffer:()=>hke,Channel:()=>nke,DatabaseSync:()=>pke,Duplex:()=>ICe,EventEmitter:()=>ACe,Http2ServerRequest:()=>vke,Http2ServerResponse:()=>Tke,Interface:()=>mke,MIMEType:()=>Cke,PassThrough:()=>RCe,PerformanceObserver:()=>eke,Readable:()=>Hq,ReadableStream:()=>PCe,Resolver:()=>ZAe,STATUS_CODES:()=>EAe,TextDecoder:()=>Zq,TextEncoder:()=>FS,Transform:()=>xCe,URL:()=>UAe,URLSearchParams:()=>BAe,Worker:()=>ake,Writable:()=>Vq,access:()=>QCe,appendFile:()=>UCe,appendFileSync:()=>uCe,arch:()=>yAe,arrayBuffer:()=>wke,availableParallelism:()=>LCe,basename:()=>TCe,builtinModules:()=>NAe,callbackify:()=>WAe,channel:()=>rke,chmod:()=>NCe,chmodSync:()=>DCe,clearInterval:()=>_ke,clearTimeout:()=>Ske,closeSync:()=>tP,connect:()=>SAe,constants:()=>$S,copyFileSync:()=>zCe,cpSync:()=>dCe,cpus:()=>pAe,createConnection:()=>bAe,createGunzip:()=>RAe,createGzip:()=>PAe,createHash:()=>jq,createHmac:()=>iCe,createInterface:()=>dke,createReadStream:()=>Mh,createRequire:()=>DAe,createServer:()=>mCe,createWriteStream:()=>Yq,debug:()=>HAe,debuglog:()=>Xq,default:()=>Fo,deflateSync:()=>CAe,deprecate:()=>VAe,deserialize:()=>ike,dirname:()=>vCe,exec:()=>sAe,execFile:()=>aAe,execFileSync:()=>cAe,execSync:()=>iAe,existsSync:()=>Gs,extname:()=>wCe,fileURLToPath:()=>zAe,finished:()=>OCe,format:()=>$Ae,freemem:()=>hAe,fstatSync:()=>qCe,get:()=>wAe,gunzip:()=>IAe,gunzipSync:()=>AAe,gzip:()=>xAe,gzipSync:()=>kAe,hasSubscribers:()=>oke,homedir:()=>uAe,hostname:()=>mAe,inflateSync:()=>_Ae,inherits:()=>GAe,inspect:()=>LS,isAbsolute:()=>SCe,isBuiltin:()=>LAe,isDeepStrictEqual:()=>KAe,isIP:()=>yke,isIPv4:()=>gke,isIPv6:()=>fke,isMainThread:()=>cke,join:()=>gCe,loadavg:()=>FCe,lookup:()=>XAe,lstatSync:()=>GCe,mkdir:()=>JCe,mkdirSync:()=>Wq,monitorEventLoopDelay:()=>tke,normalize:()=>CCe,ok:()=>MAe,open:()=>rAe,openSync:()=>eP,parentPort:()=>lke,parse:()=>FAe,pathToFileURL:()=>qAe,performance:()=>QAe,pipeline:()=>MCe,platform:()=>lAe,posix:()=>_Ce,promises:()=>qs,promisify:()=>jAe,randomBytes:()=>aCe,randomUUID:()=>cCe,readFile:()=>WCe,readFileSync:()=>md,readdir:()=>XCe,readdirSync:()=>Kq,realpath:()=>nAe,realpathSync:()=>BCe,relative:()=>ECe,release:()=>vAe,rename:()=>eAe,renameSync:()=>Jq,request:()=>TAe,resolve:()=>yCe,rm:()=>tAe,rmSync:()=>VCe,rmdirSync:()=>HCe,sep:()=>bCe,serialize:()=>ske,setImmediate:()=>$Ce,setInterval:()=>bke,setTimeout:()=>Eke,spawn:()=>oAe,stat:()=>YCe,statSync:()=>pd,strict:()=>OAe,tmpdir:()=>dAe,toUSVString:()=>JAe,totalmem:()=>fAe,type:()=>gAe,types:()=>YAe,unlink:()=>ZCe,unlinkSync:()=>jCe,validateHeaderName:()=>hCe,validateHeaderValue:()=>fCe,webcrypto:()=>lCe,workerData:()=>uke,writeFile:()=>KCe,writeFileSync:()=>Q1});var Gn,nn,Fo,qs,jq,iCe,aCe,cCe,lCe,uCe,dCe,mCe,pCe,hCe,fCe,gCe,yCe,vCe,TCe,wCe,ECe,SCe,bCe,_Ce,CCe,ACe,kCe,Hq,Vq,xCe,ICe,RCe,PCe,MCe,OCe,Gs,md,Q1,DCe,NCe,LCe,FCe,$Ce,UCe,BCe,zCe,eP,tP,qCe,Wq,pd,GCe,Kq,jCe,Jq,HCe,VCe,Yq,Mh,WCe,KCe,JCe,YCe,XCe,ZCe,QCe,eAe,tAe,rAe,nAe,oAe,sAe,iAe,aAe,cAe,lAe,uAe,dAe,mAe,pAe,hAe,fAe,gAe,yAe,vAe,TAe,wAe,EAe,SAe,bAe,_Ae,CAe,AAe,kAe,xAe,IAe,RAe,PAe,MAe,OAe,DAe,NAe,LAe,FAe,$Ae,UAe,BAe,zAe,qAe,GAe,jAe,Xq,HAe,LS,VAe,WAe,KAe,JAe,YAe,Zq,FS,XAe,ZAe,QAe,eke,tke,rke,nke,oke,ske,ike,ake,cke,lke,uke,dke,mke,pke,hke,$S,fke,gke,yke,vke,Tke,wke,Qq,Eke,Ske,bke,_ke,Cke,on=b({"node-stub:fs"(){Gn=()=>{},nn=async()=>{},Fo={},qs={readFile:nn,writeFile:nn,mkdir:nn,stat:nn,readdir:nn,unlink:nn,access:nn,rm:nn,rename:nn},jq=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new FS().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}}},iCe=(e,t)=>jq(e),aCe=e=>new Uint8Array(e||32),cCe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),lCe=globalThis.crypto,uCe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},dCe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},mCe=()=>({listen:Gn,close:Gn,on:Gn}),pCe=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},hCe=Gn,fCe=Gn,gCe=(...e)=>e.join("/"),yCe=(...e)=>e.join("/"),vCe=e=>e||"",TCe=e=>e?.split?.("/")?.pop?.()||"",wCe=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},ECe=(e,t)=>t||"",SCe=()=>!1,bCe="/",_Ce={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},CCe=e=>e,ACe=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},kCe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},Hq=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Vq=class{write(){return!0}end(){}on(){return this}destroy(){}},xCe=class{push(){}on(){return this}},ICe=class{on(){return this}},RCe=class{pipe(){return this}on(){return this}},PCe=globalThis.ReadableStream||class{},MCe=Gn,OCe=Gn,Gs=()=>!1,md=()=>"",Q1=Gn,DCe=Gn,NCe=nn,LCe=()=>1,FCe=()=>[0,0,0],$Ce=nn,UCe=nn,BCe=e=>e,zCe=Gn,eP=()=>0,tP=Gn,qCe=()=>({}),Wq=Gn,pd=()=>({}),GCe=()=>({isSymbolicLink:()=>!1}),Kq=()=>[],jCe=Gn,Jq=Gn,HCe=Gn,VCe=Gn,Yq=()=>new Vq,Mh=()=>new Hq,WCe=nn,KCe=nn,JCe=nn,YCe=nn,XCe=nn,ZCe=nn,QCe=nn,eAe=nn,tAe=nn,rAe=async()=>({stat:nn,readFile:nn,close:nn,read:nn,write:nn}),nAe=async e=>e,oAe=()=>({on:Gn,stdout:{on:Gn},stderr:{on:Gn},kill:Gn}),sAe=(e,t)=>t?.(null,"",""),iAe=()=>"",aAe=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},cAe=()=>"",lAe="browser",uAe=()=>"/",dAe=()=>"/tmp",mAe=()=>"browser",pAe=()=>[{}],hAe=()=>0,fAe=()=>0,gAe=()=>"Browser",yAe=()=>"wasm",vAe=()=>"0",TAe=()=>({}),wAe=()=>({}),EAe={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},SAe=()=>({}),bAe=()=>({}),_Ae=()=>new Uint8Array,CAe=()=>new Uint8Array,AAe=()=>new Uint8Array,kAe=()=>new Uint8Array,xAe=(e,t)=>t?.(null,e),IAe=(e,t)=>t?.(null,e),RAe=()=>({}),PAe=()=>({}),MAe=Gn,OAe={},DAe=()=>()=>({}),NAe=[],LAe=()=>!1,FAe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),$Ae=()=>"",UAe=globalThis.URL,BAe=globalThis.URLSearchParams,zAe=e=>typeof e=="string"?e.replace("file://",""):e,qAe=e=>new globalThis.URL("file://"+e),GAe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},jAe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),Xq=e=>{const t=(...r)=>{};return t.enabled=!1,t},HAe=Xq,LS=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},LS.custom=Symbol.for("nodejs.util.inspect.custom"),LS.colors={},LS.styles={},VAe=e=>e,WAe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},KAe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),JAe=e=>String(e),YAe={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},Zq=globalThis.TextDecoder,FS=globalThis.TextEncoder,XAe=(e,t)=>t?.(null,"127.0.0.1",4),ZAe=class{},QAe=globalThis.performance||{now:()=>Date.now()},eke=class{observe(){}disconnect(){}},tke=()=>({enable:Gn,disable:Gn,percentile:()=>0}),rke=()=>({}),nke=class{},oke=()=>!1,ske=()=>new Uint8Array,ike=Gn,ake=class{},cke=!0,lke=null,uke=null,dke=()=>({}),mke=class{},pke=class{},hke=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 FS().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 FS().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 Zq().decode(this)}},$S={F_OK:0,R_OK:4,W_OK:2,X_OK:1},fke=()=>!1,gke=()=>!1,yke=()=>0,vke=class{},Tke=class{},wke=async()=>new ArrayBuffer(0),Qq=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Eke=(...e)=>Qq(globalThis.setTimeout(...e)),Ske=globalThis.clearTimeout,bke=(...e)=>Qq(globalThis.setInterval(...e)),_ke=globalThis.clearInterval,Cke=class{constructor(e){this.type=e}toString(){return this.type}}}}),Ake={};ee(Ake,{Agent:()=>Lke,AsyncLocalStorage:()=>Yke,Buffer:()=>WIe,Channel:()=>LIe,DatabaseSync:()=>VIe,Duplex:()=>Zke,EventEmitter:()=>Jke,Http2ServerRequest:()=>ZIe,Http2ServerResponse:()=>QIe,Interface:()=>HIe,MIMEType:()=>sRe,PassThrough:()=>Qke,PerformanceObserver:()=>OIe,Readable:()=>tG,ReadableStream:()=>exe,Resolver:()=>PIe,STATUS_CODES:()=>eIe,TextDecoder:()=>sG,TextEncoder:()=>BS,Transform:()=>Xke,URL:()=>vIe,URLSearchParams:()=>TIe,Worker:()=>BIe,Writable:()=>rG,access:()=>Oxe,appendFile:()=>dxe,appendFileSync:()=>Oke,arch:()=>Yxe,arrayBuffer:()=>eRe,availableParallelism:()=>cxe,basename:()=>qke,builtinModules:()=>hIe,callbackify:()=>AIe,channel:()=>NIe,chmod:()=>axe,chmodSync:()=>ixe,clearInterval:()=>oRe,clearTimeout:()=>rRe,closeSync:()=>fxe,connect:()=>tIe,constants:()=>KIe,copyFileSync:()=>pxe,cpSync:()=>Dke,cpus:()=>Vxe,createConnection:()=>rIe,createGunzip:()=>lIe,createGzip:()=>uIe,createHash:()=>eG,createHmac:()=>Ike,createInterface:()=>jIe,createReadStream:()=>Axe,createRequire:()=>pIe,createServer:()=>Nke,createWriteStream:()=>Cxe,debug:()=>_Ie,debuglog:()=>oG,default:()=>kke,deflateSync:()=>oIe,deprecate:()=>CIe,deserialize:()=>UIe,dirname:()=>zke,exec:()=>Uxe,execFile:()=>nG,execFileSync:()=>zxe,execSync:()=>Bxe,existsSync:()=>nxe,extname:()=>Gke,fileURLToPath:()=>wIe,finished:()=>rxe,format:()=>yIe,freemem:()=>Wxe,fstatSync:()=>gxe,get:()=>Qxe,gunzip:()=>cIe,gunzipSync:()=>sIe,gzip:()=>aIe,gzipSync:()=>iIe,hasSubscribers:()=>FIe,homedir:()=>Gxe,hostname:()=>Hxe,inflateSync:()=>nIe,inherits:()=>SIe,inspect:()=>US,isAbsolute:()=>Hke,isBuiltin:()=>fIe,isDeepStrictEqual:()=>kIe,isIP:()=>XIe,isIPv4:()=>YIe,isIPv6:()=>JIe,isMainThread:()=>zIe,join:()=>Uke,loadavg:()=>lxe,lookup:()=>RIe,lstatSync:()=>Txe,mkdir:()=>Ixe,mkdirSync:()=>yxe,monitorEventLoopDelay:()=>DIe,normalize:()=>Kke,ok:()=>dIe,open:()=>Lxe,openSync:()=>hxe,parentPort:()=>qIe,parse:()=>gIe,pathToFileURL:()=>EIe,performance:()=>MIe,pipeline:()=>txe,platform:()=>qxe,posix:()=>Wke,promises:()=>xke,promisify:()=>bIe,randomBytes:()=>Rke,randomUUID:()=>Pke,readFile:()=>kxe,readFileSync:()=>oxe,readdir:()=>Pxe,readdirSync:()=>wxe,realpath:()=>Fxe,realpathSync:()=>mxe,relative:()=>jke,release:()=>Xxe,rename:()=>Dxe,renameSync:()=>Sxe,request:()=>Zxe,resolve:()=>Bke,rm:()=>Nxe,rmSync:()=>_xe,rmdirSync:()=>bxe,sep:()=>Vke,serialize:()=>$Ie,setImmediate:()=>uxe,setInterval:()=>nRe,setTimeout:()=>tRe,spawn:()=>$xe,stat:()=>Rxe,statSync:()=>vxe,strict:()=>mIe,tmpdir:()=>jxe,toUSVString:()=>xIe,totalmem:()=>Kxe,type:()=>Jxe,types:()=>IIe,unlink:()=>Mxe,unlinkSync:()=>Exe,validateHeaderName:()=>Fke,validateHeaderValue:()=>$ke,webcrypto:()=>Mke,workerData:()=>GIe,writeFile:()=>xxe,writeFileSync:()=>sxe});var jn,sn,kke,xke,eG,Ike,Rke,Pke,Mke,Oke,Dke,Nke,Lke,Fke,$ke,Uke,Bke,zke,qke,Gke,jke,Hke,Vke,Wke,Kke,Jke,Yke,tG,rG,Xke,Zke,Qke,exe,txe,rxe,nxe,oxe,sxe,ixe,axe,cxe,lxe,uxe,dxe,mxe,pxe,hxe,fxe,gxe,yxe,vxe,Txe,wxe,Exe,Sxe,bxe,_xe,Cxe,Axe,kxe,xxe,Ixe,Rxe,Pxe,Mxe,Oxe,Dxe,Nxe,Lxe,Fxe,$xe,Uxe,Bxe,nG,zxe,qxe,Gxe,jxe,Hxe,Vxe,Wxe,Kxe,Jxe,Yxe,Xxe,Zxe,Qxe,eIe,tIe,rIe,nIe,oIe,sIe,iIe,aIe,cIe,lIe,uIe,dIe,mIe,pIe,hIe,fIe,gIe,yIe,vIe,TIe,wIe,EIe,SIe,bIe,oG,_Ie,US,CIe,AIe,kIe,xIe,IIe,sG,BS,RIe,PIe,MIe,OIe,DIe,NIe,LIe,FIe,$Ie,UIe,BIe,zIe,qIe,GIe,jIe,HIe,VIe,WIe,KIe,JIe,YIe,XIe,ZIe,QIe,eRe,iG,tRe,rRe,nRe,oRe,sRe,iRe=b({"node-stub:child_process"(){jn=()=>{},sn=async()=>{},kke={},xke={readFile:sn,writeFile:sn,mkdir:sn,stat:sn,readdir:sn,unlink:sn,access:sn,rm:sn,rename:sn},eG=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new BS().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}}},Ike=(e,t)=>eG(e),Rke=e=>new Uint8Array(e||32),Pke=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),Mke=globalThis.crypto,Oke=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},Dke=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},Nke=()=>({listen:jn,close:jn,on:jn}),Lke=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},Fke=jn,$ke=jn,Uke=(...e)=>e.join("/"),Bke=(...e)=>e.join("/"),zke=e=>e||"",qke=e=>e?.split?.("/")?.pop?.()||"",Gke=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},jke=(e,t)=>t||"",Hke=()=>!1,Vke="/",Wke={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},Kke=e=>e,Jke=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},Yke=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},tG=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},rG=class{write(){return!0}end(){}on(){return this}destroy(){}},Xke=class{push(){}on(){return this}},Zke=class{on(){return this}},Qke=class{pipe(){return this}on(){return this}},exe=globalThis.ReadableStream||class{},txe=jn,rxe=jn,nxe=()=>!1,oxe=()=>"",sxe=jn,ixe=jn,axe=sn,cxe=()=>1,lxe=()=>[0,0,0],uxe=sn,dxe=sn,mxe=e=>e,pxe=jn,hxe=()=>0,fxe=jn,gxe=()=>({}),yxe=jn,vxe=()=>({}),Txe=()=>({isSymbolicLink:()=>!1}),wxe=()=>[],Exe=jn,Sxe=jn,bxe=jn,_xe=jn,Cxe=()=>new rG,Axe=()=>new tG,kxe=sn,xxe=sn,Ixe=sn,Rxe=sn,Pxe=sn,Mxe=sn,Oxe=sn,Dxe=sn,Nxe=sn,Lxe=async()=>({stat:sn,readFile:sn,close:sn,read:sn,write:sn}),Fxe=async e=>e,$xe=()=>({on:jn,stdout:{on:jn},stderr:{on:jn},kill:jn}),Uxe=(e,t)=>t?.(null,"",""),Bxe=()=>"",nG=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},zxe=()=>"",qxe="browser",Gxe=()=>"/",jxe=()=>"/tmp",Hxe=()=>"browser",Vxe=()=>[{}],Wxe=()=>0,Kxe=()=>0,Jxe=()=>"Browser",Yxe=()=>"wasm",Xxe=()=>"0",Zxe=()=>({}),Qxe=()=>({}),eIe={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},tIe=()=>({}),rIe=()=>({}),nIe=()=>new Uint8Array,oIe=()=>new Uint8Array,sIe=()=>new Uint8Array,iIe=()=>new Uint8Array,aIe=(e,t)=>t?.(null,e),cIe=(e,t)=>t?.(null,e),lIe=()=>({}),uIe=()=>({}),dIe=jn,mIe={},pIe=()=>()=>({}),hIe=[],fIe=()=>!1,gIe=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),yIe=()=>"",vIe=globalThis.URL,TIe=globalThis.URLSearchParams,wIe=e=>typeof e=="string"?e.replace("file://",""):e,EIe=e=>new globalThis.URL("file://"+e),SIe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},bIe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),oG=e=>{const t=(...r)=>{};return t.enabled=!1,t},_Ie=oG,US=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},US.custom=Symbol.for("nodejs.util.inspect.custom"),US.colors={},US.styles={},CIe=e=>e,AIe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},kIe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),xIe=e=>String(e),IIe={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},sG=globalThis.TextDecoder,BS=globalThis.TextEncoder,RIe=(e,t)=>t?.(null,"127.0.0.1",4),PIe=class{},MIe=globalThis.performance||{now:()=>Date.now()},OIe=class{observe(){}disconnect(){}},DIe=()=>({enable:jn,disable:jn,percentile:()=>0}),NIe=()=>({}),LIe=class{},FIe=()=>!1,$Ie=()=>new Uint8Array,UIe=jn,BIe=class{},zIe=!0,qIe=null,GIe=null,jIe=()=>({}),HIe=class{},VIe=class{},WIe=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 BS().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 BS().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 sG().decode(this)}},KIe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},JIe=()=>!1,YIe=()=>!1,XIe=()=>0,ZIe=class{},QIe=class{},eRe=async()=>new ArrayBuffer(0),iG=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),tRe=(...e)=>iG(globalThis.setTimeout(...e)),rRe=globalThis.clearTimeout,nRe=(...e)=>iG(globalThis.setInterval(...e)),oRe=globalThis.clearInterval,sRe=class{constructor(e){this.type=e}toString(){return this.type}}}}),Oh,Ss,aRe,RAr,PAr,MAr,OAr,DAr,NAr,LAr,FAr,$Ar,UAr,BAr,zAr,qAr,GAr,jAr,HAr,VAr,WAr,KAr,JAr,YAr,XAr,ZAr,QAr,ekr,tkr,rkr,nkr,okr,skr,ikr,akr,ckr,lkr,ukr,dkr,mkr,pkr,hkr,fkr,gkr,ykr,vkr,Tkr,wkr,Ekr,Skr=b({"npm-stub:csv-parser"(){Oh={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Oh.get}):new Proxy(function(...r){return new Proxy({},{get:Oh.get})},{get:Oh.get,apply(r,n,o){return new Proxy({},{get:Oh.get})},construct(r,n){return new Proxy({},{get:Oh.get})}})}},Ss=new Proxy({},Oh),aRe=Ss,{BedrockClient:RAr,ListFoundationModelsCommand:PAr,BedrockRuntimeClient:MAr,ConverseCommand:OAr,ConverseStreamCommand:DAr,ImageFormat:NAr,InvokeModelCommand:LAr}=Ss,{SageMakerRuntimeClient:FAr,InvokeEndpointCommand:$Ar,InvokeEndpointWithResponseStreamCommand:UAr}=Ss,{GoogleAuth:BAr,VertexAI:zAr,TextToSpeechClient:qAr}=Ss,{Webhook:GAr}=Ss,{Hippocampus:jAr,HippocampusConfig:HAr}=Ss,{createClient:VAr}=Ss,{Queue:WAr,Worker:KAr,Job:JAr,QueueScheduler:YAr,FlowProducer:XAr}=Ss,{Cron:ZAr}=Ss,{parseBuffer:QAr,selectCover:ekr}=Ss,{extractRawText:tkr,convertToHtml:rkr}=Ss,{Hono:nkr}=Ss,{cors:okr,HTTPException:skr,logger:ikr,secureHeaders:akr,streamSSE:ckr,timeout:lkr}=Ss,ukr=globalThis.fetch,dkr=globalThis.Request,mkr=globalThis.Response,pkr=globalThis.Headers,hkr=globalThis.FormData,fkr=globalThis.File,gkr=globalThis.Blob,ykr=Ss.Agent,vkr=Ss.Pool,Tkr=Ss.Client,wkr=Ss.Dispatcher,Ekr=Ss.MockAgent}}),Dh,bs,pu,bkr,_kr,Ckr,Akr,kkr,xkr,Ikr,Rkr,Pkr,Mkr,Okr,Dkr,Nkr,Lkr,Fkr,$kr,Ukr,Bkr,zkr,qkr,Gkr,jkr,Hkr,Vkr,Wkr,Kkr,Jkr,Ykr,Xkr,Zkr,Qkr,exr,txr,rxr,nxr,oxr,sxr,ixr,axr,cxr,lxr,uxr,dxr,mxr,pxr,hxr,cRe=b({"npm-stub:iconv-lite"(){Dh={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Dh.get}):new Proxy(function(...r){return new Proxy({},{get:Dh.get})},{get:Dh.get,apply(r,n,o){return new Proxy({},{get:Dh.get})},construct(r,n){return new Proxy({},{get:Dh.get})}})}},bs=new Proxy({},Dh),pu=bs,{BedrockClient:bkr,ListFoundationModelsCommand:_kr,BedrockRuntimeClient:Ckr,ConverseCommand:Akr,ConverseStreamCommand:kkr,ImageFormat:xkr,InvokeModelCommand:Ikr}=bs,{SageMakerRuntimeClient:Rkr,InvokeEndpointCommand:Pkr,InvokeEndpointWithResponseStreamCommand:Mkr}=bs,{GoogleAuth:Okr,VertexAI:Dkr,TextToSpeechClient:Nkr}=bs,{Webhook:Lkr}=bs,{Hippocampus:Fkr,HippocampusConfig:$kr}=bs,{createClient:Ukr}=bs,{Queue:Bkr,Worker:zkr,Job:qkr,QueueScheduler:Gkr,FlowProducer:jkr}=bs,{Cron:Hkr}=bs,{parseBuffer:Vkr,selectCover:Wkr}=bs,{extractRawText:Kkr,convertToHtml:Jkr}=bs,{Hono:Ykr}=bs,{cors:Xkr,HTTPException:Zkr,logger:Qkr,secureHeaders:exr,streamSSE:txr,timeout:rxr}=bs,nxr=globalThis.fetch,oxr=globalThis.Request,sxr=globalThis.Response,ixr=globalThis.Headers,axr=globalThis.FormData,cxr=globalThis.File,lxr=globalThis.Blob,uxr=bs.Agent,dxr=bs.Pool,mxr=bs.Client,pxr=bs.Dispatcher,hxr=bs.MockAgent}}),c0={};ee(c0,{Agent:()=>vRe,AsyncLocalStorage:()=>MRe,Buffer:()=>RPe,Channel:()=>TPe,DatabaseSync:()=>IPe,Duplex:()=>DRe,EventEmitter:()=>PRe,Http2ServerRequest:()=>NPe,Http2ServerResponse:()=>LPe,Interface:()=>xPe,MIMEType:()=>qPe,PassThrough:()=>NRe,PerformanceObserver:()=>gPe,Readable:()=>Gm,ReadableStream:()=>LRe,Resolver:()=>hPe,STATUS_CODES:()=>F1e,TextDecoder:()=>uG,TextEncoder:()=>qS,Transform:()=>ORe,URL:()=>tPe,URLSearchParams:()=>rPe,Worker:()=>bPe,Writable:()=>cG,access:()=>f1e,appendFile:()=>WRe,appendFileSync:()=>fRe,arch:()=>O1e,arrayBuffer:()=>FPe,availableParallelism:()=>jRe,basename:()=>_Re,builtinModules:()=>X1e,callbackify:()=>lPe,channel:()=>vPe,chmod:()=>GRe,chmodSync:()=>qRe,clearInterval:()=>zPe,clearTimeout:()=>UPe,closeSync:()=>XRe,connect:()=>$1e,constants:()=>PPe,copyFileSync:()=>JRe,cpSync:()=>gRe,cpus:()=>I1e,createConnection:()=>U1e,createGunzip:()=>V1e,createGzip:()=>W1e,createHash:()=>aG,createHmac:()=>dRe,createInterface:()=>kPe,createReadStream:()=>c1e,createRequire:()=>Y1e,createServer:()=>yRe,createWriteStream:()=>a1e,debug:()=>aPe,debuglog:()=>lG,default:()=>lRe,deflateSync:()=>z1e,deprecate:()=>cPe,deserialize:()=>SPe,dirname:()=>bRe,exec:()=>E1e,execFile:()=>b1e,execFileSync:()=>_1e,execSync:()=>S1e,existsSync:()=>URe,extname:()=>CRe,fileURLToPath:()=>nPe,finished:()=>$Re,format:()=>ePe,freemem:()=>R1e,fstatSync:()=>ZRe,get:()=>L1e,gunzip:()=>H1e,gunzipSync:()=>q1e,gzip:()=>j1e,gzipSync:()=>G1e,hasSubscribers:()=>wPe,homedir:()=>A1e,hostname:()=>x1e,inflateSync:()=>B1e,inherits:()=>sPe,inspect:()=>zS,isAbsolute:()=>kRe,isBuiltin:()=>Z1e,isDeepStrictEqual:()=>uPe,isIP:()=>DPe,isIPv4:()=>OPe,isIPv6:()=>MPe,isMainThread:()=>_Pe,join:()=>ERe,loadavg:()=>HRe,lookup:()=>pPe,lstatSync:()=>t1e,mkdir:()=>d1e,mkdirSync:()=>QRe,monitorEventLoopDelay:()=>yPe,normalize:()=>RRe,ok:()=>K1e,open:()=>v1e,openSync:()=>YRe,parentPort:()=>CPe,parse:()=>Q1e,pathToFileURL:()=>oPe,performance:()=>fPe,pipeline:()=>FRe,platform:()=>C1e,posix:()=>IRe,promises:()=>uRe,promisify:()=>iPe,randomBytes:()=>mRe,randomUUID:()=>pRe,readFile:()=>l1e,readFileSync:()=>BRe,readdir:()=>p1e,readdirSync:()=>r1e,realpath:()=>T1e,realpathSync:()=>KRe,relative:()=>ARe,release:()=>D1e,rename:()=>g1e,renameSync:()=>o1e,request:()=>N1e,resolve:()=>SRe,rm:()=>y1e,rmSync:()=>i1e,rmdirSync:()=>s1e,sep:()=>xRe,serialize:()=>EPe,setImmediate:()=>VRe,setInterval:()=>BPe,setTimeout:()=>$Pe,spawn:()=>w1e,stat:()=>m1e,statSync:()=>e1e,strict:()=>J1e,tmpdir:()=>k1e,toUSVString:()=>dPe,totalmem:()=>P1e,type:()=>M1e,types:()=>mPe,unlink:()=>h1e,unlinkSync:()=>n1e,validateHeaderName:()=>TRe,validateHeaderValue:()=>wRe,webcrypto:()=>hRe,workerData:()=>APe,writeFile:()=>u1e,writeFileSync:()=>zRe});var Hn,an,lRe,uRe,aG,dRe,mRe,pRe,hRe,fRe,gRe,yRe,vRe,TRe,wRe,ERe,SRe,bRe,_Re,CRe,ARe,kRe,xRe,IRe,RRe,PRe,MRe,Gm,cG,ORe,DRe,NRe,LRe,FRe,$Re,URe,BRe,zRe,qRe,GRe,jRe,HRe,VRe,WRe,KRe,JRe,YRe,XRe,ZRe,QRe,e1e,t1e,r1e,n1e,o1e,s1e,i1e,a1e,c1e,l1e,u1e,d1e,m1e,p1e,h1e,f1e,g1e,y1e,v1e,T1e,w1e,E1e,S1e,b1e,_1e,C1e,A1e,k1e,x1e,I1e,R1e,P1e,M1e,O1e,D1e,N1e,L1e,F1e,$1e,U1e,B1e,z1e,q1e,G1e,j1e,H1e,V1e,W1e,K1e,J1e,Y1e,X1e,Z1e,Q1e,ePe,tPe,rPe,nPe,oPe,sPe,iPe,lG,aPe,zS,cPe,lPe,uPe,dPe,mPe,uG,qS,pPe,hPe,fPe,gPe,yPe,vPe,TPe,wPe,EPe,SPe,bPe,_Pe,CPe,APe,kPe,xPe,IPe,RPe,PPe,MPe,OPe,DPe,NPe,LPe,FPe,dG,$Pe,UPe,BPe,zPe,qPe,Nh=b({"node-stub:stream"(){Hn=()=>{},an=async()=>{},lRe={},uRe={readFile:an,writeFile:an,mkdir:an,stat:an,readdir:an,unlink:an,access:an,rm:an,rename:an},aG=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new qS().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}}},dRe=(e,t)=>aG(e),mRe=e=>new Uint8Array(e||32),pRe=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),hRe=globalThis.crypto,fRe=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},gRe=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},yRe=()=>({listen:Hn,close:Hn,on:Hn}),vRe=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},TRe=Hn,wRe=Hn,ERe=(...e)=>e.join("/"),SRe=(...e)=>e.join("/"),bRe=e=>e||"",_Re=e=>e?.split?.("/")?.pop?.()||"",CRe=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},ARe=(e,t)=>t||"",kRe=()=>!1,xRe="/",IRe={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},RRe=e=>e,PRe=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},MRe=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},Gm=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},cG=class{write(){return!0}end(){}on(){return this}destroy(){}},ORe=class{push(){}on(){return this}},DRe=class{on(){return this}},NRe=class{pipe(){return this}on(){return this}},LRe=globalThis.ReadableStream||class{},FRe=Hn,$Re=Hn,URe=()=>!1,BRe=()=>"",zRe=Hn,qRe=Hn,GRe=an,jRe=()=>1,HRe=()=>[0,0,0],VRe=an,WRe=an,KRe=e=>e,JRe=Hn,YRe=()=>0,XRe=Hn,ZRe=()=>({}),QRe=Hn,e1e=()=>({}),t1e=()=>({isSymbolicLink:()=>!1}),r1e=()=>[],n1e=Hn,o1e=Hn,s1e=Hn,i1e=Hn,a1e=()=>new cG,c1e=()=>new Gm,l1e=an,u1e=an,d1e=an,m1e=an,p1e=an,h1e=an,f1e=an,g1e=an,y1e=an,v1e=async()=>({stat:an,readFile:an,close:an,read:an,write:an}),T1e=async e=>e,w1e=()=>({on:Hn,stdout:{on:Hn},stderr:{on:Hn},kill:Hn}),E1e=(e,t)=>t?.(null,"",""),S1e=()=>"",b1e=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},_1e=()=>"",C1e="browser",A1e=()=>"/",k1e=()=>"/tmp",x1e=()=>"browser",I1e=()=>[{}],R1e=()=>0,P1e=()=>0,M1e=()=>"Browser",O1e=()=>"wasm",D1e=()=>"0",N1e=()=>({}),L1e=()=>({}),F1e={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},$1e=()=>({}),U1e=()=>({}),B1e=()=>new Uint8Array,z1e=()=>new Uint8Array,q1e=()=>new Uint8Array,G1e=()=>new Uint8Array,j1e=(e,t)=>t?.(null,e),H1e=(e,t)=>t?.(null,e),V1e=()=>({}),W1e=()=>({}),K1e=Hn,J1e={},Y1e=()=>()=>({}),X1e=[],Z1e=()=>!1,Q1e=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),ePe=()=>"",tPe=globalThis.URL,rPe=globalThis.URLSearchParams,nPe=e=>typeof e=="string"?e.replace("file://",""):e,oPe=e=>new globalThis.URL("file://"+e),sPe=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},iPe=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),lG=e=>{const t=(...r)=>{};return t.enabled=!1,t},aPe=lG,zS=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},zS.custom=Symbol.for("nodejs.util.inspect.custom"),zS.colors={},zS.styles={},cPe=e=>e,lPe=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},uPe=(e,t)=>JSON.stringify(e)===JSON.stringify(t),dPe=e=>String(e),mPe={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},uG=globalThis.TextDecoder,qS=globalThis.TextEncoder,pPe=(e,t)=>t?.(null,"127.0.0.1",4),hPe=class{},fPe=globalThis.performance||{now:()=>Date.now()},gPe=class{observe(){}disconnect(){}},yPe=()=>({enable:Hn,disable:Hn,percentile:()=>0}),vPe=()=>({}),TPe=class{},wPe=()=>!1,EPe=()=>new Uint8Array,SPe=Hn,bPe=class{},_Pe=!0,CPe=null,APe=null,kPe=()=>({}),xPe=class{},IPe=class{},RPe=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 qS().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 qS().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 uG().decode(this)}},PPe={F_OK:0,R_OK:4,W_OK:2,X_OK:1},MPe=()=>!1,OPe=()=>!1,DPe=()=>0,NPe=class{},LPe=class{},FPe=async()=>new ArrayBuffer(0),dG=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),$Pe=(...e)=>dG(globalThis.setTimeout(...e)),UPe=globalThis.clearTimeout,BPe=(...e)=>dG(globalThis.setInterval(...e)),zPe=globalThis.clearInterval,qPe=class{constructor(e){this.type=e}toString(){return this.type}}}});function Lh(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 fxr(e,t=","){return Lh(e,t).length}function rP(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 mG){const c=r.map(m=>fxr(m,a)),l=c[0];if(l<=1)continue;const u=c.every(m=>m===l),d=(a===o?1e3:0)+(u?100:0)+l+(a===","?.5:0);d>i&&(i=d,s=a)}return i<0&&o?o:s}var mG,GPe=b({"src/lib/utils/csvUtils.ts"(){"use strict";mG=[","," ",";","|"]}});function nP(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zt(e){return typeof e=="object"&&e!==null}function gxr(e){return e==null}var Fh=b({"src/lib/utils/typeUtils.ts"(){"use strict"}}),$h,_s,jPe,yxr,vxr,Txr,wxr,Exr,Sxr,bxr,_xr,Cxr,Axr,kxr,xxr,Ixr,Rxr,Pxr,Mxr,Oxr,Dxr,Nxr,Lxr,Fxr,$xr,Uxr,Bxr,zxr,qxr,Gxr,jxr,Hxr,Vxr,Wxr,Kxr,Jxr,Yxr,Xxr,Zxr,Qxr,eIr,tIr,rIr,nIr,oIr,sIr,iIr,aIr,cIr,lIr=b({"npm-stub:chardet"(){$h={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:$h.get}):new Proxy(function(...r){return new Proxy({},{get:$h.get})},{get:$h.get,apply(r,n,o){return new Proxy({},{get:$h.get})},construct(r,n){return new Proxy({},{get:$h.get})}})}},_s=new Proxy({},$h),jPe=_s,{BedrockClient:yxr,ListFoundationModelsCommand:vxr,BedrockRuntimeClient:Txr,ConverseCommand:wxr,ConverseStreamCommand:Exr,ImageFormat:Sxr,InvokeModelCommand:bxr}=_s,{SageMakerRuntimeClient:_xr,InvokeEndpointCommand:Cxr,InvokeEndpointWithResponseStreamCommand:Axr}=_s,{GoogleAuth:kxr,VertexAI:xxr,TextToSpeechClient:Ixr}=_s,{Webhook:Rxr}=_s,{Hippocampus:Pxr,HippocampusConfig:Mxr}=_s,{createClient:Oxr}=_s,{Queue:Dxr,Worker:Nxr,Job:Lxr,QueueScheduler:Fxr,FlowProducer:$xr}=_s,{Cron:Uxr}=_s,{parseBuffer:Bxr,selectCover:zxr}=_s,{extractRawText:qxr,convertToHtml:Gxr}=_s,{Hono:jxr}=_s,{cors:Hxr,HTTPException:Vxr,logger:Wxr,secureHeaders:Kxr,streamSSE:Jxr,timeout:Yxr}=_s,Xxr=globalThis.fetch,Zxr=globalThis.Request,Qxr=globalThis.Response,eIr=globalThis.Headers,tIr=globalThis.FormData,rIr=globalThis.File,nIr=globalThis.Blob,oIr=_s.Agent,sIr=_s.Pool,iIr=_s.Client,aIr=_s.Dispatcher,cIr=_s.MockAgent}});function GS(e){return e.charCodeAt(0)===65279?e.slice(1):e}function uIr(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 dIr(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 pu.encodingExists(n)?n:null}function pG(e,t,r=!0){if(t&&pu.encodingExists(t))return{text:GS(pu.decode(e,t)),encoding:t,confidence:100};t&&!pu.encodingExists(t)&&p.warn(`[textEncoding] Unsupported encoding override "${t}"; falling back to detection.`);const n=uIr(e);if(n)return{text:GS(pu.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:GS(pu.decode(e,"utf-8")),encoding:"utf-8",confidence:r?100:60};let s=null;try{s=jPe.detect(e)}catch(a){p.debug(`[textEncoding] chardet failed: ${String(a)}`)}const i=dIr(s);return i?{text:GS(pu.decode(e,i)),encoding:i,confidence:i==="utf-8"?100:80}:{text:GS(pu.decode(e,"utf-8")),encoding:"utf-8",confidence:0}}var mIr=b({"src/lib/utils/textEncoding.ts"(){"use strict";lIr(),cRe(),z()}});function pIr(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 HPe(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 hG(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 VPe(e,t){const r=hG(e.map((o,s)=>HPe(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 hIr(e){return!nP(e)||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string"||t===void 0)}function fIr(e,t){if(!hIr(e))throw pe.csvRowInvalid(`[CSVProcessor] Invalid CSV row ${t}: expected a string-keyed object with string values, got ${Array.isArray(e)?"array":typeof e}`,t)}function jS(e){return Object.keys(e).length===0?!0:Object.values(e).every(r=>r===""||typeof r=="string"&&r.trim()==="")}function gIr(e,t){if(e.trim()==="")return!0;const r=Lh(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 jS(n)}function fG(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 gG(e){if(e===""||e===null||e===void 0)return"empty";const t=e.trim();if(t==="")return"empty";if(rMe.has(t.toLowerCase()))return"boolean";if(eMe.test(t))return"integer";if(tMe.test(t))return"float";if(ZPe.test(t))return"email";if(QPe.test(t))return"url";for(const r of wG)if(r.regex.test(t))return"datetime";for(const r of TG)if(r.regex.test(t))return"date";return"string"}function yIr(e){const t=e.trim();for(const r of wG)if(r.regex.test(t))return r.format;for(const r of TG)if(r.regex.test(t))return r.format}function vIr(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 TIr(e,t,r){const n=[],o=new Set,s=[];let i=0,a;for(const y of r){const v=y?.trim()??"";if(v===""){i++,n.push("empty");continue}o.add(v);const w=gG(v);if(n.push(w),w==="integer"||w==="float"){const E=parseFloat(v);isNaN(E)||s.push(E)}(w==="date"||w==="datetime")&&!a&&(a=yIr(v))}const{type:c,confidence:l}=vIr(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((y,v)=>y+v,0)/s.length*100)/100);const f=pIr(e),g={name:e,index:t,detectedType:c,typeConfidence:l,nullCount:i,uniqueCount:o.size,sampleValues:u};return d!==void 0&&(g.minValue=d),m!==void 0&&(g.maxValue=m),h!==void 0&&(g.avgValue=h),a&&(g.dateFormat=a),f.length>0&&(g.nameIssues=f),g}function wIr(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 EIr(e,t,r){if(e.length===0||r===0)return 0;let n=100;for(const c of t)switch(c.severity){case"error":n-=15;break;case"warning":n-=8;break;case"info":n-=3;break}const o=e.reduce((c,l)=>c+l.nullCount,0),s=e.length*r,i=s>0?o/s:0;n-=Math.round(i*30);const a=e.reduce((c,l)=>c+l.typeConfidence,0)/e.length;return a<80&&(n-=Math.round((80-a)/2)),Math.max(0,Math.min(100,n))}function WPe(e){const t=Math.max(0,Math.min(100,e));return Math.round((100+t)/2)}function KPe(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(c=>String(c[i]??""));r.push(TIr(i,s,a))}const n=wIr(r,e.length),o=EIr(r,n,e.length);return{columnMetadata:r,dataQualityWarnings:n,dataQualityScore:o}}function JPe(e,t){if(e.length===0)return!1;let r=0;for(const a of e){const c=a?.trim()??"";if(c==="")continue;gG(c)==="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 c=0;for(const u of a)gG(u?.trim()??"")==="string"&&c++;const l=a.length>0?c/a.length:0;if(o>.7&&l<o-.2)return!0}return o>=.7&&i}function yG(e){return e.charCodeAt(0)===65279?e.slice(1):e}function YPe(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 SIr(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(bIr(r))return!1;const n=YPe(t),o=YPe(r);return n===0&&o>0?!0:o>0&&n!==o}function bIr(e){const t=e.trim();return t===""?!0:/^[\s,;\t|]+$/.test(t)&&/[,;\t|]/.test(t)}function HS(e){if(!SIr(e))return{dataLines:e,hasMetadataLine:!1};const t=e[0]?.trim().match(/^sep=(.)/i)?.[1],r=t&&mG.includes(t)?t:void 0;return{dataLines:e.slice(1),hasMetadataLine:!0,explicitDelimiter:r}}function l0(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===`
|
|
80
80
|
`||s==="\r")?(s==="\r"&&e[o+1]===`
|
|
81
|
-
`&&o++,t.push(r),r=""):r+=s}return t.push(r),t}var XPe,oP,vG,TG,wG,ZPe,QPe,eMe,tMe,rMe,VS,sP=b({"src/lib/utils/csvProcessor.ts"(){"use strict";Skr(),cRe(),Nh(),hr(),z(),GPe(),Fh(),mIr(),Ze(),Lr(),XPe=10*1024*1024,oP=3e4,vG=3e5,TG=[{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"}],wG=[{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"}],ZPe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,QPe=/^(https?:\/\/|www\.)[^\s]+$/i,eMe=/^-?\d+$/,tMe=/^-?\d+\.\d+$/,rMe=new Set(["true","false","yes","no","1","0","t","f","y","n"]),VS=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:c=!1,columnNameCase:l="snake_case",parseTimeoutMs:u=oP,skipEmptyLines:d=!0}=t||{},m=Math.max(1,Math.min(1e4,r));p.debug("[CSVProcessor] Starting CSV processing",{contentSize:e.length,formatStyle:n,maxRows:m,includeHeaders:o,skipEmptyLines:d});const{text:h,encoding:f,confidence:g}=pG(e,a),y=l0(h),{dataLines:v,hasMetadataLine:w,explicitDelimiter:E}=HS(y),_=E??rP(v,i??void 0);if(n==="raw"){w&&p.debug("[CSVProcessor] Detected metadata line, skipping first line");const Ee=v,le=Ee[0]??"",ae=Ee.slice(1),Pe=d?ae.filter(Z=>!gIr(Z,_)):ae,
|
|
82
|
-
`),De=Lh(Te[0]||"",_),Ye=
|
|
83
|
-
`)]),void 0,{maxRows:
|
|
84
|
-
`)]),void 0,{maxRows:m,skipLines:0,timeoutMs:u,delimiter:_,skipEmptyRows:d}),R=C.filter(Ee=>!Ee||typeof Ee!="object"?!1:d?!jS(Ee):!0),I=R.find(Ee=>Ee&&typeof Ee=="object"&&!jS(Ee)),P=(k&&k.length>0?[...k]:void 0)??(I?Object.keys(I):void 0)??(R[0]?Object.keys(R[0]):[])??[];let O;const U=new Map;let M=P,F=P.length===0?R:R.map(Ee=>{const le=Object.create(null);for(const ae of P)le[ae]=typeof Ee[ae]=="string"?Ee[ae]:"";return le});if(c&&P.length>0){const Ee=P,{sanitized:le,mapping:ae}=VPe(Ee,l);Ee.forEach((Pe,
|
|
81
|
+
`&&o++,t.push(r),r=""):r+=s}return t.push(r),t}var XPe,oP,vG,TG,wG,ZPe,QPe,eMe,tMe,rMe,VS,sP=b({"src/lib/utils/csvProcessor.ts"(){"use strict";Skr(),cRe(),Nh(),hr(),z(),GPe(),Fh(),mIr(),Ze(),Lr(),XPe=10*1024*1024,oP=3e4,vG=3e5,TG=[{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"}],wG=[{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"}],ZPe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,QPe=/^(https?:\/\/|www\.)[^\s]+$/i,eMe=/^-?\d+$/,tMe=/^-?\d+\.\d+$/,rMe=new Set(["true","false","yes","no","1","0","t","f","y","n"]),VS=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:c=!1,columnNameCase:l="snake_case",parseTimeoutMs:u=oP,skipEmptyLines:d=!0}=t||{},m=Math.max(1,Math.min(1e4,r));p.debug("[CSVProcessor] Starting CSV processing",{contentSize:e.length,formatStyle:n,maxRows:m,includeHeaders:o,skipEmptyLines:d});const{text:h,encoding:f,confidence:g}=pG(e,a),y=l0(h),{dataLines:v,hasMetadataLine:w,explicitDelimiter:E}=HS(y),_=E??rP(v,i??void 0);if(n==="raw"){w&&p.debug("[CSVProcessor] Detected metadata line, skipping first line");const Ee=v,le=Ee[0]??"",ae=Ee.slice(1),Pe=d?ae.filter(Z=>!gIr(Z,_)):ae,ke=Pe.slice(0,m),Te=Ee.length===0?[]:[le,...ke];let he;if(c&&Te.length>0){const Z=Lh(Te[0]||"",_),{sanitized:ie,mapping:W}=VPe(Z,l);Te[0]=ie.join(_),he=W.length>0?W:void 0}const Oe=Te.join(`
|
|
82
|
+
`),De=Lh(Te[0]||"",_),Ye=ke.length,gt=Pe.length,$e=Ye<gt;$e&&p.warn(`[CSVProcessor] CSV data truncated: showing ${Ye} of ${gt} rows (limit: ${m})`),p.debug(`[CSVProcessor] raw format: ${Ye} rows (original: ${gt}) \u2192 ${Oe.length} chars`,{formatStyle:"raw",originalSize:h.length,limitedSize:Oe.length}),p.info("[CSVProcessor] \u2705 Processed CSV file",{formatStyle:"raw",rowCount:Ye,columnCount:De.length,truncated:$e});const Ie=Math.min(Ye,500),{rows:ve,timedOut:J}=await this.streamParse(Gm.from([Te.join(`
|
|
83
|
+
`)]),void 0,{maxRows:Ie,skipLines:0,timeoutMs:u,delimiter:_,skipEmptyRows:d}),{columnMetadata:V,dataQualityWarnings:se,dataQualityScore:oe}=KPe(ve);return se.length>0&&p.debug("[CSVProcessor] Data quality warnings detected",{warningCount:se.length,score:oe}),{type:"csv",content:Oe,mimeType:"text/csv",metadata:{confidence:WPe(oe),size:e.length,rowCount:Ye,totalLines:Te.length,columnCount:De.length,extension:i,columnMetadata:V,dataQualityWarnings:se,dataQualityScore:oe,hasHeaders:JPe(De,void 0),detectedDelimiter:_,detectedEncoding:f,encodingConfidence:g,...he?{columnNameMapping:he}:{},...J?{parseTimedOut:!0}:{}}}}p.debug("[CSVProcessor] Parsing CSV for structured format conversion",{formatStyle:n,maxRows:m});const{rows:C,timedOut:A,headers:k}=await this.streamParse(Gm.from([v.join(`
|
|
84
|
+
`)]),void 0,{maxRows:m,skipLines:0,timeoutMs:u,delimiter:_,skipEmptyRows:d}),R=C.filter(Ee=>!Ee||typeof Ee!="object"?!1:d?!jS(Ee):!0),I=R.find(Ee=>Ee&&typeof Ee=="object"&&!jS(Ee)),P=(k&&k.length>0?[...k]:void 0)??(I?Object.keys(I):void 0)??(R[0]?Object.keys(R[0]):[])??[];let O;const U=new Map;let M=P,F=P.length===0?R:R.map(Ee=>{const le=Object.create(null);for(const ae of P)le[ae]=typeof Ee[ae]=="string"?Ee[ae]:"";return le});if(c&&P.length>0){const Ee=P,{sanitized:le,mapping:ae}=VPe(Ee,l);Ee.forEach((Pe,ke)=>{Pe!==le[ke]&&U.set(le[ke],Pe)}),F=F.map(Pe=>{const ke=Object.create(null);return Ee.forEach((Te,he)=>{ke[le[he]]=Pe[Te]??""}),ke}),O=ae.length>0?ae:void 0,M=le}const N=F.length,L=M.length,q=M.some(Ee=>!Ee||Ee.trim()===""),B=F.filter(Ee=>!jS(Ee)),H=(B.length>0?B:F).slice(0,3),G=this.formatSampleData(H,s,o,M);q&&p.warn("[CSVProcessor] CSV contains empty or blank column headers",{columnNames:M}),N===0&&p.warn("[CSVProcessor] CSV file contains no data rows");const{columnMetadata:X,dataQualityWarnings:ce,dataQualityScore:Q}=KPe(B.length>0?B:F);if(U.size>0)for(const Ee of X){const le=U.get(Ee.name);le&&(Ee.originalName=le)}ce.length>0&&p.debug("[CSVProcessor] Data quality warnings detected",{warningCount:ce.length,score:Q}),p.debug(`[CSVProcessor] Converting ${N} rows to ${n} format`);const Ae=this.formatForLLM(F,n,o,M);return p.info("[CSVProcessor] \u2705 Processed CSV file",{formatStyle:n,rowCount:N,columnCount:L,outputLength:Ae.length,hasEmptyColumns:q,dataQualityScore:Q}),{type:"csv",content:Ae,mimeType:"text/csv",metadata:{confidence:WPe(Q),size:e.length,rowCount:N,columnCount:L,columnNames:M,sampleData:G,hasEmptyColumns:q,extension:i,columnMetadata:X,dataQualityWarnings:ce,dataQualityScore:Q,hasHeaders:JPe(M,B.length>0?B:F),detectedDelimiter:_,detectedEncoding:f,encodingConfidence:g,...O?{columnNameMapping:O}:{},...A?{parseTimedOut:!0}:{}}}}static detectDelimiter(e,t){const{dataLines:r,explicitDelimiter:n}=HS(l0(yG(e)));return n??rP(r,t)}static async parseCSVFile(e,t=1e3,r=vG){const{rows:n}=await this.parseCSVFileWithMeta(e,t,r);return n}static async parseCSVFileWithMeta(e,t=1e3,r=vG,n){if(typeof e!="string"||e.trim().length===0)throw pe.csvInvalidInput("CSVProcessor.parseCSVFile: filePath must be a non-empty string");const o=Math.max(1,Math.min(1e4,t)),s=await Promise.resolve().then(()=>(on(),mu)),i=Date.now(),a=()=>Math.max(0,r-(Date.now()-i));p.debug("[CSVProcessor] Starting file parsing",{filePath:e,maxRows:o});try{await s.promises.access(e,s.constants.R_OK)}catch(u){throw pe.csvFileAccessFailed(`[CSVProcessor] Failed to open CSV file (${e}): ${u instanceof Error?u.message:String(u)}`,e,u instanceof Error?u:void 0)}const c=s.createReadStream(e);let l;try{l=await Ct(this.prepareFileSource(c,n,ws(e)),a(),"[CSVProcessor] Timed out preparing CSV file source")}catch(u){if(c.destroy(),u instanceof ad)return p.warn(`[CSVProcessor] Prepare phase exceeded the ${r}ms parse budget for ${e}; returning an empty partial result`),{rows:[],timedOut:!0};throw pe.csvParseFailed(fG({stage:"read",count:0,location:e,cause:u instanceof Error?u.message:String(u)}),{filePath:e},u instanceof Error?u:void 0)}return this.streamParse(l.source,c,{maxRows:o,skipLines:l.skipLines,timeoutMs:a(),location:e,delimiter:l.delimiter})}static prepareFileSource(e,t,r){return new Promise((n,o)=>{const i=[];let a=0,c=!1;const l=()=>{e.removeListener("data",d),e.removeListener("end",m),e.removeListener("error",h)},u=f=>{const{dataLines:g,hasMetadataLine:y,explicitDelimiter:v}=HS(l0(f)),w=v??rP(g,r);return{hasMetadataLine:y,dataLines:g,delimiter:w}},d=f=>{i.push(f),a+=f.length;const g=Buffer.concat(i),{text:y,encoding:v}=pG(g,t,!1);if(l0(y).length>=2||a>=65536){if(c)return;c=!0,l();const{hasMetadataLine:w,delimiter:E}=u(y);e.pause(),e.unshift(g);const _=pu.decodeStream(v);e.on("error",C=>_.destroy(C)),n({source:e.pipe(_),skipLines:w?1:0,delimiter:E})}},m=()=>{if(c)return;c=!0,l();const f=Buffer.concat(i),{text:g}=pG(f,t),{hasMetadataLine:y,dataLines:v,delimiter:w}=u(g),E=y?v.join(`
|
|
85
85
|
`):g;n({source:Gm.from([E]),skipLines:0,delimiter:w})},h=f=>{c||(c=!0,l(),o(f))};e.on("data",d),e.on("end",m),e.on("error",h)})}static async parseCSVString(e,t=1e3,r=oP){const{rows:n}=await this.parseCSVStringWithMeta(e,t,r);return n}static async parseCSVStringWithMeta(e,t=1e3,r=oP){if(typeof e!="string"||e.trim().length===0)throw pe.csvInvalidInput("CSVProcessor.parseCSVString: csvString must be a non-empty string");const n=yG(e),o=Math.max(1,Math.min(1e4,t));p.debug("[CSVProcessor] Starting string parsing",{inputLength:n.length,maxRows:o});const s=l0(n),{dataLines:i,hasMetadataLine:a,explicitDelimiter:c}=HS(s),l=c??rP(i);a&&p.debug("[CSVProcessor] Detected metadata line in string, skipping");const u=i.join(`
|
|
86
86
|
`);if(u.trim().length===0)throw pe.csvInvalidInput("CSVProcessor.parseCSVString: csvString must be a non-empty string");return this.streamParse(Gm.from([u]),void 0,{maxRows:o,skipLines:0,timeoutMs:r,delimiter:l})}static streamParse(e,t,r){return new Promise((n,o)=>{const s=[];let i=0,a=!1,c,l;const u=Date.now(),d=aRe({separator:r.delimiter??",",maxRowBytes:XPe,...r.skipLines>0?{skipLines:r.skipLines}:{}}),m=()=>{e.destroy(),t?.destroy(),d.destroy()},h=g=>{a||(a=!0,clearTimeout(f),g())},f=setTimeout(()=>{h(()=>{p.warn(`[CSVProcessor] Parse timed out after ${Date.now()-u}ms with ${s.length} partial row(s)`),m(),n({rows:s,timedOut:!0,headers:c})})},r.timeoutMs);typeof f.unref=="function"&&f.unref(),d.on("headers",g=>{c=g}),e.on("error",g=>{h(()=>{m(),o(pe.csvParseFailed(fG({stage:"read",count:i,headerCount:c?.length,lastRowColumnCount:l,location:r.location,cause:g.message}),{location:r.location,rowCount:i},g))})}),e.pipe(d).on("data",g=>{try{fIr(g,i+1)}catch(y){h(()=>{m(),o(y)});return}r.skipEmptyRows&&jS(g)||(l=Object.keys(g).length,s.push(g),i++,i>=r.maxRows&&(p.debug(`[CSVProcessor] Reached row limit ${r.maxRows}, stopping parse`),h(()=>{m(),n({rows:s,timedOut:!1,headers:c})})))}).on("end",()=>{h(()=>{p.debug(`[CSVProcessor] Parsing complete: ${s.length} rows parsed`),n({rows:s,timedOut:!1,headers:c})})}).on("error",g=>{h(()=>{m(),p.error("[CSVProcessor] Parsing failed:",g),o(pe.csvParseFailed(fG({stage:"parse",count:i,headerCount:c?.length,lastRowColumnCount:l,location:r.location,cause:g.message}),{location:r.location,rowCount:i},g))})})})}static formatForLLM(e,t,r,n){return e.length===0?"CSV file is empty or contains no data.":t==="json"?JSON.stringify(e,null,2):this.toMarkdownTable(e,r,n)}static toMarkdownTable(e,t,r){if(e.length===0)return"CSV file is empty or contains no data.";const n=r&&r.length>0?r:Object.keys(e[0]??{});if(n.length===0)return"CSV file is empty or contains no data.";const o=i=>i.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\r\n|\n|\r/g," ");let s="";return t&&(s="| "+n.map(o).join(" | ")+` |
|
|
87
87
|
`,s+="|"+n.map(()=>" --- ").join("|")+`|
|
|
@@ -1011,10 +1011,10 @@ Reasoning: [Provide a detailed explanation of your evaluation, explaining why yo
|
|
|
1011
1011
|
|
|
1012
1012
|
[... ${C} bytes omitted. Use ${OJ} tool to access full output ...]
|
|
1013
1013
|
|
|
1014
|
-
`:typeof t.notice=="function"?t.notice(C):t.notice,E=(C,A)=>Math.max(0,c-Buffer.byteLength(C,"utf-8")-Buffer.byteLength(A,"utf-8"));let _=w(E(f,g));for(let C=0;C<2;C++){const A=Buffer.byteLength(f,"utf-8")+Buffer.byteLength(_,"utf-8")+Buffer.byteLength(g,"utf-8")-r;if(A<=0)break;const k=Buffer.from(g,"utf-8"),R=Math.min(A,k.length);g=k.subarray(R).toString("utf-8");const I=A-R;if(I>0){const P=Buffer.from(f,"utf-8");f=P.subarray(0,Math.max(0,P.length-I)).toString("utf-8")}_=w(E(f,g))}return Buffer.byteLength(f,"utf-8")+Buffer.byteLength(_,"utf-8")+Buffer.byteLength(g,"utf-8")>r?{preview:o3r(_,r),truncated:!0,originalSize:c}:{preview:f+_+g,truncated:!0,originalSize:c}}var OO,MJ,jbt,OJ,Hbt,Lf=b({"src/lib/context/toolOutputLimits.ts"(){"use strict";OO=50*1024,MJ=2e3,jbt=.25,OJ="retrieve_context",Hbt=.75}});function iv(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let o=0;o<n;o++)if(!iv(e[o],t[o]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;const n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(const i of n)if(!iv(e[i],t[i]))return!1;return!0}return e===t}var Vbt=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js"(){}});function Dc(e){return encodeURI(Wbt(e))}function Wbt(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var DJ=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/pointer.js"(){}});function lp(e,t=Object.create(null),r=$J,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e.$id||e.id;if(s){const i=new URL(s,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",n===""?r=i:lp(e,t,r))}}else if(e!==!0&&e!==!1)return t;const o=r.href+(n?"#"+n:"");if(t[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){const s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){const s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){const s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(FJ[s])continue;const i=`${n}/${Dc(s)}`,a=e[s];if(Array.isArray(a)){if(NJ[s]){const c=a.length;for(let l=0;l<c;l++)lp(a[l],t,r,`${i}/${l}`)}}else if(LJ[s])for(let c in a)lp(a[c],t,r,`${i}/${Dc(c)}`);else lp(a,t,r,i)}return t}var Kbt,NJ,LJ,FJ,$J,UJ=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/dereference.js"(){DJ(),Kbt={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},NJ={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},LJ={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},FJ={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},$J=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")}});function Au(e){return e.test.bind(e)}function s3r(e){return e%4===0&&(e%100!==0||e%400===0)}function Jbt(e){const t=e.match(Xbt);if(!t)return!1;const r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&s3r(r)?29:Zbt[n])}function Ybt(e,t){const r=t.match(Qbt);if(!r)return!1;const n=+r[1],o=+r[2],s=+r[3],i=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!e||i)}function i3r(e){const t=e.split(m_t);return t.length==2&&Jbt(t[0])&&Ybt(!0,t[1])}function a3r(e){return p_t.test(e)&&h_t.test(e)}function c3r(e){if(f_t.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var Xbt,Zbt,Qbt,e_t,t_t,r_t,n_t,o_t,s_t,i_t,a_t,c_t,l_t,u_t,d_t,DO,m_t,p_t,h_t,f_t,g_t=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/format.js"(){Xbt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Zbt=[0,31,28,31,30,31,30,31,31,30,31,30,31],Qbt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,e_t=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,t_t=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,r_t=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,n_t=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,o_t=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,s_t=/^(?:\/(?:[^~/]|~0|~1)*)*$/,i_t=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,a_t=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,c_t=e=>{if(e[0]==='"')return!1;const[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},l_t=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,u_t=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,d_t=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),DO={date:Jbt,time:Ybt.bind(void 0,!1),"date-time":i3r,duration:d_t,uri:a3r,"uri-reference":Au(t_t),"uri-template":Au(r_t),url:Au(n_t),email:c_t,hostname:Au(e_t),ipv4:Au(l_t),ipv6:Au(u_t),regex:c3r,uuid:Au(o_t),"json-pointer":Au(s_t),"json-pointer-uri-fragment":Au(i_t),"relative-json-pointer":Au(a_t)},m_t=/t|\s/i,p_t=/\/|:/,h_t=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,f_t=/[^\\]\\Z/}}),BJ,l3r=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/types.js"(){(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(BJ||(BJ={}))}});function y_t(e){let t=0,r=e.length,n=0,o;for(;n<r;)t++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=e.charCodeAt(n),(o&64512)==56320&&n++);return t}var v_t=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js"(){}});function Eo(e,t,r="2019-09",n=lp(t),o=!0,s=null,i="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const l=typeof e;let u;switch(l){case"boolean":case"number":case"string":u=l;break;case"object":e===null?u="null":Array.isArray(e)?u="array":u="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}const{$ref:d,$recursiveRef:m,$recursiveAnchor:h,type:f,const:g,enum:y,required:v,not:w,anyOf:E,allOf:_,oneOf:C,if:A,then:k,else:R,format:I,properties:P,patternProperties:O,additionalProperties:U,unevaluatedProperties:M,minProperties:F,maxProperties:N,propertyNames:L,dependentRequired:q,dependentSchemas:B,dependencies:H,prefixItems:G,items:X,additionalItems:ce,unevaluatedItems:Q,contains:Ie,minContains:Ee,maxContains:le,minItems:ae,maxItems:Pe,uniqueItems:Ae,minimum:Te,maximum:he,exclusiveMinimum:Oe,exclusiveMaximum:De,multipleOf:Ye,minLength:gt,maxLength:$e,pattern:xe,__absolute_ref__:ve,__absolute_recursive_ref__:J}=t,V=[];if(h===!0&&s===null&&(s=t),m==="#"){const oe=s===null?n[J]:s,Z=`${a}/$recursiveRef`,ie=Eo(e,s===null?t:s,r,n,o,oe,i,Z,c);ie.valid||V.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:Z,error:"A subschema had errors."},...ie.errors)}if(d!==void 0){const Z=n[ve||d];if(Z===void 0){let re=`Unresolved $ref "${d}".`;throw ve&&ve!==d&&(re+=` Absolute URI "${ve}".`),re+=`
|
|
1014
|
+
`:typeof t.notice=="function"?t.notice(C):t.notice,E=(C,A)=>Math.max(0,c-Buffer.byteLength(C,"utf-8")-Buffer.byteLength(A,"utf-8"));let _=w(E(f,g));for(let C=0;C<2;C++){const A=Buffer.byteLength(f,"utf-8")+Buffer.byteLength(_,"utf-8")+Buffer.byteLength(g,"utf-8")-r;if(A<=0)break;const k=Buffer.from(g,"utf-8"),R=Math.min(A,k.length);g=k.subarray(R).toString("utf-8");const I=A-R;if(I>0){const P=Buffer.from(f,"utf-8");f=P.subarray(0,Math.max(0,P.length-I)).toString("utf-8")}_=w(E(f,g))}return Buffer.byteLength(f,"utf-8")+Buffer.byteLength(_,"utf-8")+Buffer.byteLength(g,"utf-8")>r?{preview:o3r(_,r),truncated:!0,originalSize:c}:{preview:f+_+g,truncated:!0,originalSize:c}}var OO,MJ,jbt,OJ,Hbt,Lf=b({"src/lib/context/toolOutputLimits.ts"(){"use strict";OO=50*1024,MJ=2e3,jbt=.25,OJ="retrieve_context",Hbt=.75}});function iv(e,t){const r=typeof e;if(r!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const n=e.length;if(n!==t.length)return!1;for(let o=0;o<n;o++)if(!iv(e[o],t[o]))return!1;return!0}if(r==="object"){if(!e||!t)return e===t;const n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(const i of n)if(!iv(e[i],t[i]))return!1;return!0}return e===t}var Vbt=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js"(){}});function Dc(e){return encodeURI(Wbt(e))}function Wbt(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var DJ=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/pointer.js"(){}});function lp(e,t=Object.create(null),r=$J,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){const s=e.$id||e.id;if(s){const i=new URL(s,r.href);i.hash.length>1?t[i.href]=e:(i.hash="",n===""?r=i:lp(e,t,r))}}else if(e!==!0&&e!==!1)return t;const o=r.href+(n?"#"+n:"");if(t[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(t[o]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:o}),e.$ref&&e.__absolute_ref__===void 0){const s=new URL(e.$ref,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:s.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){const s=new URL(e.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(e.$anchor){const s=new URL("#"+e.$anchor,r.href);t[s.href]=e}for(let s in e){if(FJ[s])continue;const i=`${n}/${Dc(s)}`,a=e[s];if(Array.isArray(a)){if(NJ[s]){const c=a.length;for(let l=0;l<c;l++)lp(a[l],t,r,`${i}/${l}`)}}else if(LJ[s])for(let c in a)lp(a[c],t,r,`${i}/${Dc(c)}`);else lp(a,t,r,i)}return t}var Kbt,NJ,LJ,FJ,$J,UJ=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/dereference.js"(){DJ(),Kbt={additionalItems:!0,unevaluatedItems:!0,items:!0,contains:!0,additionalProperties:!0,unevaluatedProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},NJ={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},LJ={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},FJ={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},$J=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")}});function Au(e){return e.test.bind(e)}function s3r(e){return e%4===0&&(e%100!==0||e%400===0)}function Jbt(e){const t=e.match(Xbt);if(!t)return!1;const r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n==2&&s3r(r)?29:Zbt[n])}function Ybt(e,t){const r=t.match(Qbt);if(!r)return!1;const n=+r[1],o=+r[2],s=+r[3],i=!!r[5];return(n<=23&&o<=59&&s<=59||n==23&&o==59&&s==60)&&(!e||i)}function i3r(e){const t=e.split(m_t);return t.length==2&&Jbt(t[0])&&Ybt(!0,t[1])}function a3r(e){return p_t.test(e)&&h_t.test(e)}function c3r(e){if(f_t.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}var Xbt,Zbt,Qbt,e_t,t_t,r_t,n_t,o_t,s_t,i_t,a_t,c_t,l_t,u_t,d_t,DO,m_t,p_t,h_t,f_t,g_t=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/format.js"(){Xbt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Zbt=[0,31,28,31,30,31,30,31,31,30,31,30,31],Qbt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,e_t=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,t_t=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,r_t=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,n_t=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,o_t=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,s_t=/^(?:\/(?:[^~/]|~0|~1)*)*$/,i_t=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,a_t=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,c_t=e=>{if(e[0]==='"')return!1;const[t,r,...n]=e.split("@");return!t||!r||n.length!==0||t.length>64||r.length>253||t[0]==="."||t.endsWith(".")||t.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:r.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},l_t=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,u_t=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,d_t=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),DO={date:Jbt,time:Ybt.bind(void 0,!1),"date-time":i3r,duration:d_t,uri:a3r,"uri-reference":Au(t_t),"uri-template":Au(r_t),url:Au(n_t),email:c_t,hostname:Au(e_t),ipv4:Au(l_t),ipv6:Au(u_t),regex:c3r,uuid:Au(o_t),"json-pointer":Au(s_t),"json-pointer-uri-fragment":Au(i_t),"relative-json-pointer":Au(a_t)},m_t=/t|\s/i,p_t=/\/|:/,h_t=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,f_t=/[^\\]\\Z/}}),BJ,l3r=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/types.js"(){(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(BJ||(BJ={}))}});function y_t(e){let t=0,r=e.length,n=0,o;for(;n<r;)t++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<r&&(o=e.charCodeAt(n),(o&64512)==56320&&n++);return t}var v_t=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js"(){}});function Eo(e,t,r="2019-09",n=lp(t),o=!0,s=null,i="#",a="#",c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const l=typeof e;let u;switch(l){case"boolean":case"number":case"string":u=l;break;case"object":e===null?u="null":Array.isArray(e)?u="array":u="object";break;default:throw new Error(`Instances of "${l}" type are not supported.`)}const{$ref:d,$recursiveRef:m,$recursiveAnchor:h,type:f,const:g,enum:y,required:v,not:w,anyOf:E,allOf:_,oneOf:C,if:A,then:k,else:R,format:I,properties:P,patternProperties:O,additionalProperties:U,unevaluatedProperties:M,minProperties:F,maxProperties:N,propertyNames:L,dependentRequired:q,dependentSchemas:B,dependencies:H,prefixItems:G,items:X,additionalItems:ce,unevaluatedItems:Q,contains:Ae,minContains:Ee,maxContains:le,minItems:ae,maxItems:Pe,uniqueItems:ke,minimum:Te,maximum:he,exclusiveMinimum:Oe,exclusiveMaximum:De,multipleOf:Ye,minLength:gt,maxLength:$e,pattern:Ie,__absolute_ref__:ve,__absolute_recursive_ref__:J}=t,V=[];if(h===!0&&s===null&&(s=t),m==="#"){const oe=s===null?n[J]:s,Z=`${a}/$recursiveRef`,ie=Eo(e,s===null?t:s,r,n,o,oe,i,Z,c);ie.valid||V.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:Z,error:"A subschema had errors."},...ie.errors)}if(d!==void 0){const Z=n[ve||d];if(Z===void 0){let re=`Unresolved $ref "${d}".`;throw ve&&ve!==d&&(re+=` Absolute URI "${ve}".`),re+=`
|
|
1015
1015
|
Known schemas:
|
|
1016
1016
|
- ${Object.keys(n).join(`
|
|
1017
|
-
- `)}`,new Error(re)}const ie=`${a}/$ref`,W=Eo(e,Z,r,n,o,s,i,ie,c);if(W.valid||V.push({instanceLocation:i,keyword:"$ref",keywordLocation:ie,error:"A subschema had errors."},...W.errors),r==="4"||r==="7")return{valid:V.length===0,errors:V}}if(Array.isArray(f)){let oe=f.length,Z=!1;for(let ie=0;ie<oe;ie++)if(u===f[ie]||f[ie]==="integer"&&u==="number"&&e%1===0&&e===e){Z=!0;break}Z||V.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(u!=="number"||e%1||e!==e)&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f}".`}):f!==void 0&&u!==f&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f}".`});if(g!==void 0&&(u==="object"||u==="array"?iv(e,g)||V.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):e!==g&&V.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),y!==void 0&&(u==="object"||u==="array"?y.some(oe=>iv(e,oe))||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(oe=>e===oe)||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),w!==void 0){const oe=`${a}/not`;Eo(e,w,r,n,o,s,i,oe).valid&&V.push({instanceLocation:i,keyword:"not",keywordLocation:oe,error:'Instance matched "not" schema.'})}let se=[];if(E!==void 0){const oe=`${a}/anyOf`,Z=V.length;let ie=!1;for(let W=0;W<E.length;W++){const re=E[W],ye=Object.create(c),Re=Eo(e,re,r,n,o,h===!0?s:null,i,`${oe}/${W}`,ye);V.push(...Re.errors),ie=ie||Re.valid,Re.valid&&se.push(ye)}ie?V.length=Z:V.splice(Z,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:oe,error:"Instance does not match any subschemas."})}if(_!==void 0){const oe=`${a}/allOf`,Z=V.length;let ie=!0;for(let W=0;W<_.length;W++){const re=_[W],ye=Object.create(c),Re=Eo(e,re,r,n,o,h===!0?s:null,i,`${oe}/${W}`,ye);V.push(...Re.errors),ie=ie&&Re.valid,Re.valid&&se.push(ye)}ie?V.length=Z:V.splice(Z,0,{instanceLocation:i,keyword:"allOf",keywordLocation:oe,error:"Instance does not match every subschema."})}if(C!==void 0){const oe=`${a}/oneOf`,Z=V.length,ie=C.filter((W,re)=>{const ye=Object.create(c),Re=Eo(e,W,r,n,o,h===!0?s:null,i,`${oe}/${re}`,ye);return V.push(...Re.errors),Re.valid&&se.push(ye),Re.valid}).length;ie===1?V.length=Z:V.splice(Z,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:oe,error:`Instance does not match exactly one subschema (${ie} matches).`})}if((u==="object"||u==="array")&&Object.assign(c,...se),A!==void 0){const oe=`${a}/if`;if(Eo(e,A,r,n,o,s,i,oe,c).valid){if(k!==void 0){const ie=Eo(e,k,r,n,o,s,i,`${a}/then`,c);ie.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:oe,error:'Instance does not match "then" schema.'},...ie.errors)}}else if(R!==void 0){const ie=Eo(e,R,r,n,o,s,i,`${a}/else`,c);ie.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:oe,error:'Instance does not match "else" schema.'},...ie.errors)}}if(u==="object"){if(v!==void 0)for(const W of v)W in e||V.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${W}".`});const oe=Object.keys(e);if(F!==void 0&&oe.length<F&&V.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${F} properties.`}),N!==void 0&&oe.length>N&&V.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${N} properties.`}),L!==void 0){const W=`${a}/propertyNames`;for(const re in e){const ye=`${i}/${Dc(re)}`,Re=Eo(re,L,r,n,o,s,ye,W);Re.valid||V.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:W,error:`Property name "${re}" does not match schema.`},...Re.errors)}}if(q!==void 0){const W=`${a}/dependantRequired`;for(const re in q)if(re in e){const ye=q[re];for(const Re of ye)Re in e||V.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:W,error:`Instance has "${re}" but does not have "${Re}".`})}}if(B!==void 0)for(const W in B){const re=`${a}/dependentSchemas`;if(W in e){const ye=Eo(e,B[W],r,n,o,s,i,`${re}/${Dc(W)}`,c);ye.valid||V.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:re,error:`Instance has "${W}" but does not match dependant schema.`},...ye.errors)}}if(H!==void 0){const W=`${a}/dependencies`;for(const re in H)if(re in e){const ye=H[re];if(Array.isArray(ye))for(const Re of ye)Re in e||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:W,error:`Instance has "${re}" but does not have "${Re}".`});else{const Re=Eo(e,ye,r,n,o,s,i,`${W}/${Dc(re)}`);Re.valid||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:W,error:`Instance has "${re}" but does not match dependant schema.`},...Re.errors)}}}const Z=Object.create(null);let ie=!1;if(P!==void 0){const W=`${a}/properties`;for(const re in P){if(!(re in e))continue;const ye=`${i}/${Dc(re)}`,Re=Eo(e[re],P[re],r,n,o,s,ye,`${W}/${Dc(re)}`);if(Re.valid)c[re]=Z[re]=!0;else if(ie=o,V.push({instanceLocation:i,keyword:"properties",keywordLocation:W,error:`Property "${re}" does not match schema.`},...Re.errors),ie)break}}if(!ie&&O!==void 0){const W=`${a}/patternProperties`;for(const re in O){const ye=new RegExp(re,"u"),Re=O[re];for(const x in e){if(!ye.test(x))continue;const K=`${i}/${Dc(x)}`,Se=Eo(e[x],Re,r,n,o,s,K,`${W}/${Dc(re)}`);Se.valid?c[x]=Z[x]=!0:(ie=o,V.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:W,error:`Property "${x}" matches pattern "${re}" but does not match associated schema.`},...Se.errors))}}}if(!ie&&U!==void 0){const W=`${a}/additionalProperties`;for(const re in e){if(Z[re])continue;const ye=`${i}/${Dc(re)}`,Re=Eo(e[re],U,r,n,o,s,ye,W);Re.valid?c[re]=!0:(ie=o,V.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:W,error:`Property "${re}" does not match additional properties schema.`},...Re.errors))}}else if(!ie&&M!==void 0){const W=`${a}/unevaluatedProperties`;for(const re in e)if(!c[re]){const ye=`${i}/${Dc(re)}`,Re=Eo(e[re],M,r,n,o,s,ye,W);Re.valid?c[re]=!0:V.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:W,error:`Property "${re}" does not match unevaluated properties schema.`},...Re.errors)}}}else if(u==="array"){Pe!==void 0&&e.length>Pe&&V.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Pe}).`}),ae!==void 0&&e.length<ae&&V.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${ae}).`});const oe=e.length;let Z=0,ie=!1;if(G!==void 0){const W=`${a}/prefixItems`,re=Math.min(G.length,oe);for(;Z<re;Z++){const ye=Eo(e[Z],G[Z],r,n,o,s,`${i}/${Z}`,`${W}/${Z}`);if(c[Z]=!0,!ye.valid&&(ie=o,V.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:W,error:"Items did not match schema."},...ye.errors),ie))break}}if(X!==void 0){const W=`${a}/items`;if(Array.isArray(X)){const re=Math.min(X.length,oe);for(;Z<re;Z++){const ye=Eo(e[Z],X[Z],r,n,o,s,`${i}/${Z}`,`${W}/${Z}`);if(c[Z]=!0,!ye.valid&&(ie=o,V.push({instanceLocation:i,keyword:"items",keywordLocation:W,error:"Items did not match schema."},...ye.errors),ie))break}}else for(;Z<oe;Z++){const re=Eo(e[Z],X,r,n,o,s,`${i}/${Z}`,W);if(c[Z]=!0,!re.valid&&(ie=o,V.push({instanceLocation:i,keyword:"items",keywordLocation:W,error:"Items did not match schema."},...re.errors),ie))break}if(!ie&&ce!==void 0){const re=`${a}/additionalItems`;for(;Z<oe;Z++){const ye=Eo(e[Z],ce,r,n,o,s,`${i}/${Z}`,re);c[Z]=!0,ye.valid||(ie=o,V.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:re,error:"Items did not match additional items schema."},...ye.errors))}}}if(Ie!==void 0)if(oe===0&&Ee===void 0)V.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ee!==void 0&&oe<Ee)V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${oe}) than minContains (${Ee}).`});else{const W=`${a}/contains`,re=V.length;let ye=0;for(let Re=0;Re<oe;Re++){const x=Eo(e[Re],Ie,r,n,o,s,`${i}/${Re}`,W);x.valid?(c[Re]=!0,ye++):V.push(...x.errors)}ye>=(Ee||0)&&(V.length=re),Ee===void 0&&le===void 0&&ye===0?V.splice(re,0,{instanceLocation:i,keyword:"contains",keywordLocation:W,error:"Array does not contain item matching schema."}):Ee!==void 0&&ye<Ee?V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Ee} items matching schema. Only ${ye} items were found.`}):le!==void 0&&ye>le&&V.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${le} items matching schema. ${ye} items were found.`})}if(!ie&&Q!==void 0){const W=`${a}/unevaluatedItems`;for(Z;Z<oe;Z++){if(c[Z])continue;const re=Eo(e[Z],Q,r,n,o,s,`${i}/${Z}`,W);c[Z]=!0,re.valid||V.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:W,error:"Items did not match unevaluated items schema."},...re.errors)}}if(Ae)for(let W=0;W<oe;W++){const re=e[W],ye=typeof re=="object"&&re!==null;for(let Re=0;Re<oe;Re++){if(W===Re)continue;const x=e[Re];(re===x||ye&&(typeof x=="object"&&x!==null)&&iv(re,x))&&(V.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${W} and ${Re}.`}),W=Number.MAX_SAFE_INTEGER,Re=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(Te!==void 0&&(Oe===!0&&e<=Te||e<Te)&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Oe?"or equal to ":""} ${Te}.`}),he!==void 0&&(De===!0&&e>=he||e>he)&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${De?"or equal to ":""} ${he}.`})):(Te!==void 0&&e<Te&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Te}.`}),he!==void 0&&e>he&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${he}.`}),Oe!==void 0&&e<=Oe&&V.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Oe}.`}),De!==void 0&&e>=De&&V.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${De}.`})),Ye!==void 0){const oe=e%Ye;Math.abs(0-oe)>=11920929e-14&&Math.abs(Ye-oe)>=11920929e-14&&V.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ye}.`})}}else if(u==="string"){const oe=gt===void 0&&$e===void 0?0:y_t(e);gt!==void 0&&oe<gt&&V.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${oe} < ${gt}).`}),$e!==void 0&&oe>$e&&V.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${oe} > ${$e}).`}),xe!==void 0&&!new RegExp(xe,"u").test(e)&&V.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),I!==void 0&&DO[I]&&!DO[I](e)&&V.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${I}".`})}return{valid:V.length===0,errors:V}}var T_t=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validate.js"(){Vbt(),UJ(),g_t(),DJ(),v_t()}}),w_t,u3r=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validator.js"(){UJ(),T_t(),w_t=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=lp(e)}validate(e){return Eo(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),lp(e,this.lookup)}}}}),E_t={};ee(E_t,{OutputFormat:()=>BJ,Validator:()=>w_t,deepCompareStrict:()=>iv,dereference:()=>lp,encodePointer:()=>Dc,escapePointer:()=>Wbt,format:()=>DO,ignoredKeyword:()=>FJ,initialBaseURI:()=>$J,schemaArrayKeyword:()=>NJ,schemaKeyword:()=>Kbt,schemaMapKeyword:()=>LJ,ucs2length:()=>y_t,validate:()=>Eo});var d3r=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/index.js"(){Vbt(),UJ(),g_t(),DJ(),l3r(),v_t(),T_t(),u3r()}});function S_t(){const e=new Error("Tool execution aborted");return e.name="AbortError",e}async function m3r(e,t){try{const{Validator:r}=await Promise.resolve().then(()=>(d3r(),E_t)),n=new r(t,"7",!1),o=Array.isArray(t.required)?t.required:[],s=t.properties&&typeof t.properties=="object"?t.properties:{},i=Object.entries(s).map(([a,c])=>`${a}${o.includes(a)?"":"?"}: ${c?.type??"any"}`).join(", ");return a=>{try{const c=n.validate(a);if(c.valid)return{success:!0,value:a};const l=c.errors.filter(u=>u.instanceLocation!=="#"||/required property/i.test(u.error)).slice(0,3).map(u=>{const d=u.instanceLocation.replace(/^#\/?/,"");return d?`${d}: ${u.error}`:u.error}).join("; ");return{success:!1,error:new Error(`Invalid arguments for tool '${e}'${l?` \u2014 ${l}`:""}. Expected: { ${i} } (send every non-optional property with the exact name and JSON type).`)}}catch(c){return p.debug(`[ToolsManager] Schema validator failed for '${e}', passing through`,{error:c instanceof Error?c.message:String(c)}),{success:!0,value:a}}}}catch(r){p.debug(`[ToolsManager] Could not compile schema validator for '${e}' \u2014 arguments will not be pre-validated`,{error:r instanceof Error?r.message:String(r)});return}}function p3r(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(S_t())):new Promise((r,n)=>{const o=()=>{e.catch(()=>{}),n(S_t())};t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function zJ(e){try{return Buffer.byteLength(JSON.stringify(e),"utf-8")}catch{return}}function h3r(e){return e!==null&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"}function f3r(e,t){const r=new Array(e.length).fill(0),n=e.map((i,a)=>a).sort((i,a)=>e[i]-e[a]);let o=Math.max(0,t),s=n.length;for(const i of n){const a=Math.floor(o/s),c=Math.min(e[i],a);r[i]=c,o-=c,s--}return r}var NO,b_t,__t,g3r=b({"src/lib/core/modules/ToolsManager.ts"(){"use strict";en(),PJ(),Ka(),Xt(),z(),Ic(),ui(),Lf(),Ac(),NO=new WeakMap,b_t=6,__t=class{constructor(e,t,r,n){this.providerName=e,this.directTools=t,this.neurolink=r,this.utilities=n,this.mcpTools={}}providerName;directTools;neurolink;utilities;mcpTools;customTools;toolExecutor;sessionId;userId;wrapExecuteWithTruncation(e,t){return async(r,n)=>{const o=n?.abortSignal,s=t(r,n),i=o&&typeof o.addEventListener=="function"?await p3r(s,o):await s;return this.truncateToolResult(e,i)}}resolveTruncationMaxBytes(){const e=this.neurolink?.getToolsConfig?.()?.outputTruncationMaxBytes;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:OO}resolveTruncationNotice(){if(!(this.neurolink?.getCustomTools?.()?.has(OJ)??!1))return t=>`
|
|
1017
|
+
- `)}`,new Error(re)}const ie=`${a}/$ref`,W=Eo(e,Z,r,n,o,s,i,ie,c);if(W.valid||V.push({instanceLocation:i,keyword:"$ref",keywordLocation:ie,error:"A subschema had errors."},...W.errors),r==="4"||r==="7")return{valid:V.length===0,errors:V}}if(Array.isArray(f)){let oe=f.length,Z=!1;for(let ie=0;ie<oe;ie++)if(u===f[ie]||f[ie]==="integer"&&u==="number"&&e%1===0&&e===e){Z=!0;break}Z||V.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f.join('", "')}".`})}else f==="integer"?(u!=="number"||e%1||e!==e)&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f}".`}):f!==void 0&&u!==f&&V.push({instanceLocation:i,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${f}".`});if(g!==void 0&&(u==="object"||u==="array"?iv(e,g)||V.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(g)}.`}):e!==g&&V.push({instanceLocation:i,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(g)}.`})),y!==void 0&&(u==="object"||u==="array"?y.some(oe=>iv(e,oe))||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(oe=>e===oe)||V.push({instanceLocation:i,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),w!==void 0){const oe=`${a}/not`;Eo(e,w,r,n,o,s,i,oe).valid&&V.push({instanceLocation:i,keyword:"not",keywordLocation:oe,error:'Instance matched "not" schema.'})}let se=[];if(E!==void 0){const oe=`${a}/anyOf`,Z=V.length;let ie=!1;for(let W=0;W<E.length;W++){const re=E[W],ye=Object.create(c),Re=Eo(e,re,r,n,o,h===!0?s:null,i,`${oe}/${W}`,ye);V.push(...Re.errors),ie=ie||Re.valid,Re.valid&&se.push(ye)}ie?V.length=Z:V.splice(Z,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:oe,error:"Instance does not match any subschemas."})}if(_!==void 0){const oe=`${a}/allOf`,Z=V.length;let ie=!0;for(let W=0;W<_.length;W++){const re=_[W],ye=Object.create(c),Re=Eo(e,re,r,n,o,h===!0?s:null,i,`${oe}/${W}`,ye);V.push(...Re.errors),ie=ie&&Re.valid,Re.valid&&se.push(ye)}ie?V.length=Z:V.splice(Z,0,{instanceLocation:i,keyword:"allOf",keywordLocation:oe,error:"Instance does not match every subschema."})}if(C!==void 0){const oe=`${a}/oneOf`,Z=V.length,ie=C.filter((W,re)=>{const ye=Object.create(c),Re=Eo(e,W,r,n,o,h===!0?s:null,i,`${oe}/${re}`,ye);return V.push(...Re.errors),Re.valid&&se.push(ye),Re.valid}).length;ie===1?V.length=Z:V.splice(Z,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:oe,error:`Instance does not match exactly one subschema (${ie} matches).`})}if((u==="object"||u==="array")&&Object.assign(c,...se),A!==void 0){const oe=`${a}/if`;if(Eo(e,A,r,n,o,s,i,oe,c).valid){if(k!==void 0){const ie=Eo(e,k,r,n,o,s,i,`${a}/then`,c);ie.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:oe,error:'Instance does not match "then" schema.'},...ie.errors)}}else if(R!==void 0){const ie=Eo(e,R,r,n,o,s,i,`${a}/else`,c);ie.valid||V.push({instanceLocation:i,keyword:"if",keywordLocation:oe,error:'Instance does not match "else" schema.'},...ie.errors)}}if(u==="object"){if(v!==void 0)for(const W of v)W in e||V.push({instanceLocation:i,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${W}".`});const oe=Object.keys(e);if(F!==void 0&&oe.length<F&&V.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${F} properties.`}),N!==void 0&&oe.length>N&&V.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${N} properties.`}),L!==void 0){const W=`${a}/propertyNames`;for(const re in e){const ye=`${i}/${Dc(re)}`,Re=Eo(re,L,r,n,o,s,ye,W);Re.valid||V.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:W,error:`Property name "${re}" does not match schema.`},...Re.errors)}}if(q!==void 0){const W=`${a}/dependantRequired`;for(const re in q)if(re in e){const ye=q[re];for(const Re of ye)Re in e||V.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:W,error:`Instance has "${re}" but does not have "${Re}".`})}}if(B!==void 0)for(const W in B){const re=`${a}/dependentSchemas`;if(W in e){const ye=Eo(e,B[W],r,n,o,s,i,`${re}/${Dc(W)}`,c);ye.valid||V.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:re,error:`Instance has "${W}" but does not match dependant schema.`},...ye.errors)}}if(H!==void 0){const W=`${a}/dependencies`;for(const re in H)if(re in e){const ye=H[re];if(Array.isArray(ye))for(const Re of ye)Re in e||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:W,error:`Instance has "${re}" but does not have "${Re}".`});else{const Re=Eo(e,ye,r,n,o,s,i,`${W}/${Dc(re)}`);Re.valid||V.push({instanceLocation:i,keyword:"dependencies",keywordLocation:W,error:`Instance has "${re}" but does not match dependant schema.`},...Re.errors)}}}const Z=Object.create(null);let ie=!1;if(P!==void 0){const W=`${a}/properties`;for(const re in P){if(!(re in e))continue;const ye=`${i}/${Dc(re)}`,Re=Eo(e[re],P[re],r,n,o,s,ye,`${W}/${Dc(re)}`);if(Re.valid)c[re]=Z[re]=!0;else if(ie=o,V.push({instanceLocation:i,keyword:"properties",keywordLocation:W,error:`Property "${re}" does not match schema.`},...Re.errors),ie)break}}if(!ie&&O!==void 0){const W=`${a}/patternProperties`;for(const re in O){const ye=new RegExp(re,"u"),Re=O[re];for(const x in e){if(!ye.test(x))continue;const K=`${i}/${Dc(x)}`,Se=Eo(e[x],Re,r,n,o,s,K,`${W}/${Dc(re)}`);Se.valid?c[x]=Z[x]=!0:(ie=o,V.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:W,error:`Property "${x}" matches pattern "${re}" but does not match associated schema.`},...Se.errors))}}}if(!ie&&U!==void 0){const W=`${a}/additionalProperties`;for(const re in e){if(Z[re])continue;const ye=`${i}/${Dc(re)}`,Re=Eo(e[re],U,r,n,o,s,ye,W);Re.valid?c[re]=!0:(ie=o,V.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:W,error:`Property "${re}" does not match additional properties schema.`},...Re.errors))}}else if(!ie&&M!==void 0){const W=`${a}/unevaluatedProperties`;for(const re in e)if(!c[re]){const ye=`${i}/${Dc(re)}`,Re=Eo(e[re],M,r,n,o,s,ye,W);Re.valid?c[re]=!0:V.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:W,error:`Property "${re}" does not match unevaluated properties schema.`},...Re.errors)}}}else if(u==="array"){Pe!==void 0&&e.length>Pe&&V.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Pe}).`}),ae!==void 0&&e.length<ae&&V.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${ae}).`});const oe=e.length;let Z=0,ie=!1;if(G!==void 0){const W=`${a}/prefixItems`,re=Math.min(G.length,oe);for(;Z<re;Z++){const ye=Eo(e[Z],G[Z],r,n,o,s,`${i}/${Z}`,`${W}/${Z}`);if(c[Z]=!0,!ye.valid&&(ie=o,V.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:W,error:"Items did not match schema."},...ye.errors),ie))break}}if(X!==void 0){const W=`${a}/items`;if(Array.isArray(X)){const re=Math.min(X.length,oe);for(;Z<re;Z++){const ye=Eo(e[Z],X[Z],r,n,o,s,`${i}/${Z}`,`${W}/${Z}`);if(c[Z]=!0,!ye.valid&&(ie=o,V.push({instanceLocation:i,keyword:"items",keywordLocation:W,error:"Items did not match schema."},...ye.errors),ie))break}}else for(;Z<oe;Z++){const re=Eo(e[Z],X,r,n,o,s,`${i}/${Z}`,W);if(c[Z]=!0,!re.valid&&(ie=o,V.push({instanceLocation:i,keyword:"items",keywordLocation:W,error:"Items did not match schema."},...re.errors),ie))break}if(!ie&&ce!==void 0){const re=`${a}/additionalItems`;for(;Z<oe;Z++){const ye=Eo(e[Z],ce,r,n,o,s,`${i}/${Z}`,re);c[Z]=!0,ye.valid||(ie=o,V.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:re,error:"Items did not match additional items schema."},...ye.errors))}}}if(Ae!==void 0)if(oe===0&&Ee===void 0)V.push({instanceLocation:i,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ee!==void 0&&oe<Ee)V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${oe}) than minContains (${Ee}).`});else{const W=`${a}/contains`,re=V.length;let ye=0;for(let Re=0;Re<oe;Re++){const x=Eo(e[Re],Ae,r,n,o,s,`${i}/${Re}`,W);x.valid?(c[Re]=!0,ye++):V.push(...x.errors)}ye>=(Ee||0)&&(V.length=re),Ee===void 0&&le===void 0&&ye===0?V.splice(re,0,{instanceLocation:i,keyword:"contains",keywordLocation:W,error:"Array does not contain item matching schema."}):Ee!==void 0&&ye<Ee?V.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${Ee} items matching schema. Only ${ye} items were found.`}):le!==void 0&&ye>le&&V.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${le} items matching schema. ${ye} items were found.`})}if(!ie&&Q!==void 0){const W=`${a}/unevaluatedItems`;for(Z;Z<oe;Z++){if(c[Z])continue;const re=Eo(e[Z],Q,r,n,o,s,`${i}/${Z}`,W);c[Z]=!0,re.valid||V.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:W,error:"Items did not match unevaluated items schema."},...re.errors)}}if(ke)for(let W=0;W<oe;W++){const re=e[W],ye=typeof re=="object"&&re!==null;for(let Re=0;Re<oe;Re++){if(W===Re)continue;const x=e[Re];(re===x||ye&&(typeof x=="object"&&x!==null)&&iv(re,x))&&(V.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${W} and ${Re}.`}),W=Number.MAX_SAFE_INTEGER,Re=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(r==="4"?(Te!==void 0&&(Oe===!0&&e<=Te||e<Te)&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Oe?"or equal to ":""} ${Te}.`}),he!==void 0&&(De===!0&&e>=he||e>he)&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${De?"or equal to ":""} ${he}.`})):(Te!==void 0&&e<Te&&V.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${Te}.`}),he!==void 0&&e>he&&V.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${he}.`}),Oe!==void 0&&e<=Oe&&V.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${Oe}.`}),De!==void 0&&e>=De&&V.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${De}.`})),Ye!==void 0){const oe=e%Ye;Math.abs(0-oe)>=11920929e-14&&Math.abs(Ye-oe)>=11920929e-14&&V.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Ye}.`})}}else if(u==="string"){const oe=gt===void 0&&$e===void 0?0:y_t(e);gt!==void 0&&oe<gt&&V.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${oe} < ${gt}).`}),$e!==void 0&&oe>$e&&V.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${oe} > ${$e}).`}),Ie!==void 0&&!new RegExp(Ie,"u").test(e)&&V.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),I!==void 0&&DO[I]&&!DO[I](e)&&V.push({instanceLocation:i,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${I}".`})}return{valid:V.length===0,errors:V}}var T_t=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validate.js"(){Vbt(),UJ(),g_t(),DJ(),v_t()}}),w_t,u3r=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validator.js"(){UJ(),T_t(),w_t=class{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=lp(e)}validate(e){return Eo(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),lp(e,this.lookup)}}}}),E_t={};ee(E_t,{OutputFormat:()=>BJ,Validator:()=>w_t,deepCompareStrict:()=>iv,dereference:()=>lp,encodePointer:()=>Dc,escapePointer:()=>Wbt,format:()=>DO,ignoredKeyword:()=>FJ,initialBaseURI:()=>$J,schemaArrayKeyword:()=>NJ,schemaKeyword:()=>Kbt,schemaMapKeyword:()=>LJ,ucs2length:()=>y_t,validate:()=>Eo});var d3r=b({"node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/index.js"(){Vbt(),UJ(),g_t(),DJ(),l3r(),v_t(),T_t(),u3r()}});function S_t(){const e=new Error("Tool execution aborted");return e.name="AbortError",e}async function m3r(e,t){try{const{Validator:r}=await Promise.resolve().then(()=>(d3r(),E_t)),n=new r(t,"7",!1),o=Array.isArray(t.required)?t.required:[],s=t.properties&&typeof t.properties=="object"?t.properties:{},i=Object.entries(s).map(([a,c])=>`${a}${o.includes(a)?"":"?"}: ${c?.type??"any"}`).join(", ");return a=>{try{const c=n.validate(a);if(c.valid)return{success:!0,value:a};const l=c.errors.filter(u=>u.instanceLocation!=="#"||/required property/i.test(u.error)).slice(0,3).map(u=>{const d=u.instanceLocation.replace(/^#\/?/,"");return d?`${d}: ${u.error}`:u.error}).join("; ");return{success:!1,error:new Error(`Invalid arguments for tool '${e}'${l?` \u2014 ${l}`:""}. Expected: { ${i} } (send every non-optional property with the exact name and JSON type).`)}}catch(c){return p.debug(`[ToolsManager] Schema validator failed for '${e}', passing through`,{error:c instanceof Error?c.message:String(c)}),{success:!0,value:a}}}}catch(r){p.debug(`[ToolsManager] Could not compile schema validator for '${e}' \u2014 arguments will not be pre-validated`,{error:r instanceof Error?r.message:String(r)});return}}function p3r(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(S_t())):new Promise((r,n)=>{const o=()=>{e.catch(()=>{}),n(S_t())};t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function zJ(e){try{return Buffer.byteLength(JSON.stringify(e),"utf-8")}catch{return}}function h3r(e){return e!==null&&typeof e=="object"&&e.type==="text"&&typeof e.text=="string"}function f3r(e,t){const r=new Array(e.length).fill(0),n=e.map((i,a)=>a).sort((i,a)=>e[i]-e[a]);let o=Math.max(0,t),s=n.length;for(const i of n){const a=Math.floor(o/s),c=Math.min(e[i],a);r[i]=c,o-=c,s--}return r}var NO,b_t,__t,g3r=b({"src/lib/core/modules/ToolsManager.ts"(){"use strict";en(),PJ(),Ka(),Xt(),z(),Ic(),ui(),Lf(),Ac(),NO=new WeakMap,b_t=6,__t=class{constructor(e,t,r,n){this.providerName=e,this.directTools=t,this.neurolink=r,this.utilities=n,this.mcpTools={}}providerName;directTools;neurolink;utilities;mcpTools;customTools;toolExecutor;sessionId;userId;wrapExecuteWithTruncation(e,t){return async(r,n)=>{const o=n?.abortSignal,s=t(r,n),i=o&&typeof o.addEventListener=="function"?await p3r(s,o):await s;return this.truncateToolResult(e,i)}}resolveTruncationMaxBytes(){const e=this.neurolink?.getToolsConfig?.()?.outputTruncationMaxBytes;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:OO}resolveTruncationNotice(){if(!(this.neurolink?.getCustomTools?.()?.has(OJ)??!1))return t=>`
|
|
1018
1018
|
|
|
1019
1019
|
[... ${t} bytes omitted ...]
|
|
1020
1020
|
|
|
@@ -1031,7 +1031,7 @@ Based on this analysis, provide your response.`:`Here is a video/image analysis
|
|
|
1031
1031
|
${s}
|
|
1032
1032
|
|
|
1033
1033
|
Based on this analysis, provide your response.`;p.debug("[VideoAnalysis] Formatting via Claude",{userTextLength:i.length,analysisLength:s.length});const u=await TFe(n,{...t.systemPrompt?{system:t.systemPrompt}:{},prompt:l,maxOutputTokens:t.maxTokens||8192,temperature:.3,...t.abortSignal?{abortSignal:t.abortSignal}:{}});a=u.text,c=LM(u.usage),p.debug("[VideoAnalysis] Claude formatting complete",{formattedLength:a.length,usage:c})}catch(l){p.warn("[VideoAnalysis] Claude formatting failed, using raw Gemini output",{error:l instanceof Error?l.message:String(l)})}return this.enhanceResult({content:a,provider:t.provider??this.providerName,model:this.modelName,usage:c},t,o)}async finalizeNativeGenerate(t,r,n){await this.recordPerformanceMetrics(t.usage,Date.now()-n);const o=await this.synthesizeAIResponseIfNeeded(t,r);return this.enhanceResult(o,r,n)}fireGenerateOnFinish(t,r,n){const o=t.onFinish;if(typeof o=="function")try{const s=r?.usage,i=o({text:r?.content||"",usage:s?{promptTokens:s.input??0,completionTokens:s.output??0}:void 0,duration:Date.now()-n,finishReason:r?.finishReason??"stop"});Promise.resolve(i).catch(a=>p.warn(`[${this.providerName}] onFinish callback rejected: ${a instanceof Error?a.message:String(a)}`))}catch(s){p.warn(`[${this.providerName}] onFinish callback threw: ${s instanceof Error?s.message:String(s)}`)}}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 p.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 c=await N1(()=>wl.synthesize(o,s,n),a,`TTS synthesis timed out after ${a}ms for provider "${s}"`);return{...t,audio:c,ttsMetadata:{attempted:!0,success:!0,latency:Date.now()-i}}}catch(c){const l=Date.now()-i,u=this.getTTSErrorDetails(c);return this.telemetryHandler.recordTTSFailure(s,u,l),p.error("TTS synthesis failed in Mode 2 (AI response synthesis):",c),{...t,ttsMetadata:{attempted:!0,success:!1,error:u,latency:l}}}}getTTSErrorDetails(t){const r=Ah(t).message;return t instanceof ad?{code:At.SYNTHESIS_FAILED,message:r,retriable:!0}:t instanceof Me?{code:t.code,message:r,retriable:t.retriable}:{code:At.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){const n=typeof t=="string"?t.length:t.text?.length??0;throw p.warn(`embed() called on ${this.providerName} which does not have a native implementation`,{textLength:n}),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 p.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(){}async decide(t){throw p.warn(`decide() called on ${this.providerName}, which does not serve the decide inference type`),new Error(`The decide inference type is not supported by the ${this.providerName} provider. Supported providers: ${PS.map(r=>r.name).join(", ")}. A provider declares this capability with "decide" in its descriptor's inferenceKinds.`)}getDefaultDecisionModel(){}getToolCallRepairFn(t){if(!t?.disableToolCallRepair)return(async(...r)=>{const{createToolCallRepair:n}=await Promise.resolve().then(()=>(KJ(),P_t));return n()(...r)})}async executeStream(t,r){if(!this.doStream)throw new Me({code:je.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&&p.warn(`[${this.providerName}] doStream reported warnings`,{provider:this.providerName,count:a.length});const c={startTime:n,streamId:`${this.providerName}-${n}`},l=(async()=>{const[u,d]=await Promise.all([s,i]);return c.finishReason=u,c.rawFinishReason=u,I0(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:l,metadata:c}}async withTurnTimeout(t,r,n){const s=typeof t.turnTimeoutMs=="number"&&Number.isFinite(t.turnTimeoutMs)&&t.turnTimeoutMs>0?t.turnTimeoutMs:t.timeout??Math.max(r??0,18e4),i=da(s,this.providerName,"generate"),a=L1(t.abortSignal,i?.controller.signal),c=a?{...t,abortSignal:a}:t;try{return await n(c)}catch(l){const u=i?.controller.signal.aborted?i.controller.signal.reason:void 0;throw u instanceof ma&&cr(l)&&t.abortSignal?.aborted!==!0?u:l}finally{i?.cleanup()}}emitTurnEvent(t){try{this.neurolink?.getEventEmitter()?.emit("turn:lifecycle",{provider:this.providerName,timestamp:Date.now(),...t})}catch{}}getDescriptorGenerateMs(){return Ar.get(this.providerName)?.timeouts?.generateMs}getDescriptorDecideMs(){return Ar.get(this.providerName)?.timeouts?.decideMs}getModel(){return this.getAISDKModel()}async getAISDKModelWithMiddleware(t={}){return this.applyMiddlewareToModel(await this.getAISDKModel(),t)}async applyMiddlewareToModel(t,r={}){p.debug(`Retrieved base model for ${this.providerName}`,{provider:this.providerName,model:this.modelName,hasMiddlewareConfig:!!this.middlewareOptions,timestamp:Date.now()});const n=this.extractMiddlewareOptions(r);if(p.debug("Middleware extraction result",{provider:this.providerName,model:this.modelName,middlewareOptions:n}),!n)return t;try{p.debug(`Applying middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,middlewareOptions:n});const o=new EV(n),s=o.createContext(this.providerName,this.modelName,r,{sessionId:this.sessionId,userId:this.userId}),i=o.applyMiddleware(t,s,n);return p.debug(`Applied middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,hasMiddleware:!0}),i}catch(o){return p.warn(`Failed to apply middleware to ${this.providerName}, using base model`,{error:o instanceof Error?o.message:String(o)}),t}}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)}setFileToolRootPolicy(t){t===void 0||Object.keys(this.directTools).length===0||(this.fileToolRootsBound=!0,this.toolsManager.setDirectTools(t.roots===null?this.directTools:nH(t)))}applyFileToolRoots(t){if(Object.keys(this.directTools).length===0)return;const r=cH(t);if(r!==void 0){this.setFileToolRootPolicy(r);return}this.fileToolRootsBound&&t.toolRoots===void 0||this.setFileToolRootPolicy(HP({perCall:t.toolRoots,instance:this.neurolink?.getToolsConfig()?.fileRoots}))}async getAllTools(){return this.fileToolRootsBound||this.applyFileToolRoots({}),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 Z_t(r)||r instanceof ot||CS(r)===void 0?r:this.handleProviderError(r)}handleProviderError(t){if(cr(t))return t instanceof Error?t:new DOMException("The operation was aborted","AbortError");if(t instanceof Error&&Z_t(t))return t;const r=this.formatProviderError(t);if(t&&typeof t=="object"&&r!==t){const n=t,o=r,s=CS(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=Hve(t);i!==void 0&&(o.retryAfterMs=i)}}Gb(t)&&gM(r);try{const n=lt.getSpan(fr.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 H3r(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=da(n,this.providerName,r.operationType||"generate");try{return o?await Promise.race([t(),new Promise((s,i)=>{o.controller.signal.addEventListener("abort",()=>{i(new ma(`${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){p.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){p.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(()=>(up(),B_t)),{validateVideoGenerationInput:i,validateImageForVideo:a,validateDirectorModeInput:c}=await Promise.resolve().then(()=>(Md(),sTt)),{ErrorFactory:l}=await Promise.resolve().then(()=>(Ze(),SS)),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 I=u.input.segments,P=c(u);if(!P.isValid)throw l.invalidParameters("director-mode",new Error(P.errors.map(X=>X.message).join("; ")),{errors:P.errors});if(P.warnings.length>0)for(const X of P.warnings)p.warn(`Director Mode warning: ${X}`);const{executeDirectorPipeline:O,DIRECTOR_PIPELINE_TIMEOUT_MS:U}=await Promise.resolve().then(()=>(j3r(),q_t)),M=t.timeout??U,F=await this.executeWithTimeout(()=>O(I,u.output?.video??{},u.output?.director??{},t.region),{timeout:M,operationType:"generate"}),N=u.input.segments.map(X=>X.prompt).join(" \u2192 "),L=F.metadata?.segmentCount??u.input.segments.length,q=F.metadata?.transitionCount??Math.max(0,L-1),B=F.metadata?.duration??0,G={content:`${N} \u2014 duration: ${B}s, segments: ${L}, transitions: ${q}`,provider:"vertex",model:t.model||"veo-3.1-generate-001",usage:{input:0,output:0,total:0},video:F};return await this.enhanceResult(G,t,r)}const d=i(u);if(!d.isValid)throw l.invalidParameters("video-generation",new Error(d.errors.map(I=>I.message).join("; ")),{errors:d.errors});if(d.warnings.length>0)for(const I of d.warnings)p.warn(`Video generation warning: ${I}`);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 f;if(typeof m=="string")if(m.startsWith("http://")||m.startsWith("https://")){p.debug("Fetching image from URL for video generation",{url:m.substring(0,100)});let I;try{I=await this.executeWithTimeout(()=>fetch(m),{timeout:h,operationType:"generate"})}catch(P){throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${P instanceof Error?P.message:"Request timed out"}`,retriable:!0,context:{url:m,timeout:h},originalError:P instanceof Error?P:void 0})}if(!I.ok)throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${I.status} ${I.statusText}`,retriable:I.status>=500,context:{url:m,status:I.status}});f=Buffer.from(await I.arrayBuffer())}else{p.debug("Reading image from path for video generation",{path:m});const I=await Promise.resolve().then(()=>(Dr(),N0));try{f=await this.executeWithTimeout(()=>I.readFile(m),{timeout:h,operationType:"generate"})}catch(P){throw new o({code:s.INVALID_INPUT,message:`Failed to read image file: ${P instanceof Error?P.message:String(P)}`,retriable:!1,context:{path:m,timeout:h},originalError:P instanceof Error?P:void 0})}}else if(Buffer.isBuffer(m))f=m;else if(typeof m=="object"&&"data"in m){const I=m.data;if(typeof I=="string")f=Buffer.from(I,"base64");else if(Buffer.isBuffer(I))f=I;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 I}})}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 g=a(f);if(g)throw l.invalidParameters("video-generation",new Error(g.message),{field:"input.images[0]",validation:g});const y=t.prompt||t.input?.text||"",v=t.output?.video?.provider??IAr("video");if(!n.supports(v))throw new o({code:s.PROVIDER_NOT_SUPPORTED,message:`Video provider "${v}" is not registered. Available: ${n.listProviders().join(", ")}`,retriable:!1,context:{provider:v,available:n.listProviders()}});const E=t.output?.video?.model??t.model??(v==="vertex"?"veo-3.1-generate-001":void 0);p.info("Starting video generation",{provider:v,...E?{model:E}:{},promptLength:y.length,imageSize:f.length,resolution:t.output?.video?.resolution||"720p",duration:t.output?.video?.length||6});const _=t.timeout??6e5,C=t.output?.video?.abortSignal??t.abortSignal,A=await this.executeWithTimeout(()=>n.generate(v,{...t.output?.video??{},image:f,prompt:y,region:t.region,abortSignal:C}),{timeout:_,operationType:"generate"}),k=A.metadata?.model??E??(v==="vertex"?"veo-3.1-generate-001":"unknown");p.info("Video generation complete",{provider:v,model:k,videoSize:A.data.length,duration:A.metadata?.duration,processingTime:A.metadata?.processingTime});const R={content:y,provider:v,model:k,usage:{input:0,output:0,total:0},video:A};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 Ff(e,t){try{await e}catch(r){p.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var QJ=b({"src/lib/utils/drainDetachedPump.ts"(){"use strict";z()}}),$f=b({"src/lib/utils/async/index.ts"(){"use strict";Lr()}});function Uf(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 c=r.abortSignal?id(a(),r.abortSignal):a();return await(r.toolTimeoutMs===void 0||r.toolTimeoutMs===null?c:Ct(c,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var HO=b({"src/lib/core/toolExecutionGuards.ts"(){"use strict";$f()}});function V3r(e,t){const r=eCt[e];return Math.round(t.min+r*(t.max-t.min))}function eY(e,t){if(!e?.enabled&&!e?.thinkingLevel)return;const r=e.thinkingLevel??Q_t;if(t&&!y3r(t)){const n=v3r(t);if(n)return{includeThoughts:!0,thinkingBudget:V3r(r,n)};tY.has(t)||(tY.add(t),p.warn(`[thinkingConfig] "${t}" has no verified Gemini thinkingBudget range; omitting thinkingConfig \u2014 requested thinkingLevel is silently disabled.`));return}return{includeThoughts:!0,thinkingLevel:r}}var Q_t,eCt,tY,tCt=b({"src/lib/utils/thinkingConfig.ts"(){"use strict";FO(),z(),Q_t="high",eCt={minimal:0,low:.25,medium:.55,high:1},tY=new Set}});function W3r(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 K3r(e){if(lCt.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>JO&&(t=t.slice(0,JO)),t}function J3r(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,s=`${e.slice(0,JO-n.length)}${n}`;if(!t(s))return s;r++}}function dp(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],s=o.filter(l=>l.type!=="null"&&l.type!=="undefined");if(s.length===1){const l=dp({...s[0]});return l.nullable=!0,e.description&&(l.description=e.description),l}const i=s.map(l=>l.type||"unknown").join(" | "),a={type:"string"},c=e.description?`${e.description} (accepts: ${i})`:`Value as string (accepts: ${i})`;return a.description=c,o.some(l=>l.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]=dp(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"?dp(s):s):t[n]=dp(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>dp(n))),t.not&&typeof t.not=="object"&&(t.not=dp(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=dp(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 rCt(e,t){const r=[],n=new pv,o=[],s=[],i=new Set(t??[]),a=new Map;for(const[c,l]of Object.entries(e))try{const u=K3r(c),d=J3r(u,f=>i.has(f));a.set(d,c),d!==c&&s.push({from:c,to:d});const m={name:d,description:l.description||`Tool: ${d}`},h=l;if(h.parameters||l.inputSchema){let f;const g=h.parameters||l.inputSchema;f7(g)?f=Ao(g,"openApi3"):typeof g=="object"?f=g:f={type:"object",properties:{}},f.jsonSchema&&typeof f.jsonSchema=="object"&&!f.type&&(f=f.jsonSchema),m.parametersJsonSchema=dp(Xn(f))}r.push(m),i.add(d),l.execute&&n.set(m.name,l.execute)}catch(u){o.push(c),p.error(`[buildNativeToolDeclarations] Failed to convert tool "${c}":`,u)}return o.length>0&&p.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),s.length>0&&p.warn(`[buildNativeToolDeclarations] ${s.length} tool name(s) sanitized for Google's function-name regex: ${s.map(c=>`"${c.from}" -> "${c.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function VO(e,t,r){const n={},o=(s,i)=>r?Uf(s,i,r):async(a,c)=>i(a,c);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 Y3r(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=rCt(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 p.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([s])=>s).join(", ")}`),n.map(([s])=>s)}function nCt(e,t){const r=hl("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=eY(e.thinkingConfig,e.model);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function oCt(e){const t=e||Bs;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),sY):Math.min(Bs,sY)}function dC(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 X3r(e,t){return t?e?`${e}
|
|
1034
|
-
${t}`:t:e}async function Z3r(e,t){const r=[],n=[];let o=0,s=0,i=0,a=0,c;for await(const l of e){const u=l,m=u.candidates?.[0],h=m?.finishReason;typeof h=="string"&&(c=h);const f=m?.content;if(f&&Array.isArray(f.parts))for(const y of f.parts)r.push(y),typeof y.text=="string"&&y.text.length>0&&t.push({content:y.text});l.functionCalls&&n.push(...l.functionCalls);const g=u.usageMetadata;g&&(o=Math.max(o,g.promptTokenCount||0),s=Math.max(s,g.candidatesTokenCount||0),i=Math.max(i,g.cachedContentTokenCount||0),a=Math.max(a,g.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:c,inputTokens:o,outputTokens:s,cacheReadTokens:i,reasoningTokens:a}}function WO(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 Q3r(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function sCt(e,t,r,n,o){return t>=r&&!n?(p.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||pp(r,0)):n}function mp(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 pp(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 Nc(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 iCt(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 eUr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${iCt(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function tUr(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 ${iCt(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function rUr(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function rY(e){return e.timedOut?eUr(e.elapsedMs,e.toolCallCount):e.stalled?tUr(e.stallTimeoutMs??0,e.toolCallCount):e.wasAborted?rUr(e.toolCallCount):pp(e.maxSteps,e.toolCallCount)}function lv(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 uv(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 dv(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??E_e:void 0;let s=!1,i=!1,a=t,c,l;if(n!==void 0&&(c=setTimeout(()=>{s=!0,e.onDeadline("timeout")},n),c.unref?.()),r(e.stallTimeoutMs)){const u=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);l=setInterval(()=>{!i&&!s&&Date.now()-a>=u&&(i=!0,e.onDeadline("stall"))},d),l.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(){c&&clearTimeout(c),l&&clearInterval(l)}}}function mv(e,t=Y1){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 nUr(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function aCt(e){const t=Ao(e,"openApi3"),r=Xn(t);return r.$schema&&delete r.$schema,Hi(r)}function KO(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 c=s(a),l=r.get(c);if(l)return l;const u={type:"tool_step",callParts:[],resultParts:[]};return r.set(c,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 c=a.role==="assistant"?"model":a.role;if(c!=="user"&&c!=="model"||!a.content||a.content.trim().length===0)continue;o++;const l={text:a.content};a.metadata?.thoughtSignature&&(l.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:c,parts:[l]})}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&&p.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 nY(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 hvt(n.buffer,n.mimeType,i);if(sK(a.mimeType)){p.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")}}),p.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function oY(e,t,r,n,o="[GeminiNative]"){if(!t||t.length===0)return;let s=e.reduce((i,a)=>"inlineData"in a?i+Math.floor(a.inlineData.data.length*3/4):i,0);for(const i of t){const a=i.filename.split(/[\\/]/).pop()??i.filename,c=Svt(r,i,s,n);if(!c.deliver){p.warn(`${o} Sending keyframes instead of the clip for ${a}: ${c.reason}.`);continue}s+=i.buffer.length,e.push({inlineData:{mimeType:i.mimeType,data:i.buffer.toString("base64")}}),p.debug(`${o} Added native video part for ${a} (${i.mimeType})`)}}async function cCt(e,t,r="[GeminiNative]",n){const s=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){p.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const i of e.pdfFiles){let a;typeof i=="string"?Ai(i)?a=li(i):a=Buffer.from(i,"base64"):a=i,s.push({inlineData:{mimeType:"application/pdf",data:a.toString("base64")}})}}if(e?.images&&e.images.length>0){p.debug(`${r} Processing ${e.images.length} image(s)`);for(const i of e.images){const a=i&&typeof i=="object"&&!Buffer.isBuffer(i)?i.data:i;let c,l="image/jpeg";if(typeof a=="string")if(Ai(a)){c=li(a);const u=u0(a).toLowerCase();u===".png"?l="image/png":u===".gif"?l="image/gif":u===".webp"&&(l="image/webp")}else if(a.startsWith("data:")){const u=a.match(/^data:([^;]+);base64,(.+)$/);if(u)l=u[1],c=Buffer.from(u[2],"base64");else continue}else if(a.startsWith("http://")||a.startsWith("https://"))try{const u=await fetch(a);if(!u.ok){p.warn(`${r} Image fetch failed: ${u.status} ${u.statusText}, skipping`,{url:a});continue}const d=await u.arrayBuffer();c=Buffer.from(d);const m=u.headers.get("content-type");m&&m.startsWith("image/")&&(l=m.split(";")[0])}catch(u){p.warn(`${r} Image URL fetch threw, skipping: ${u instanceof Error?u.message:String(u)}`,{url:a});continue}else c=Buffer.from(a,"base64");else c=a;c&&s.push({inlineData:{mimeType:l,data:c.toString("base64")}})}}return await nY(s,e?.nativeAudioFiles,r),await oY(s,e?.nativeVideoFiles,"google-ai-studio",n,r),s}var pv,lCt,JO,sY,YO=b({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";Wr(),Pn(),zt(),Lo(),vvt(),aK(),z(),HO(),ud(),ui(),tCt(),pv=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}::${W3r(o)}`;if(r.has(i))return p.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}}},lCt=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,JO=128,sY=100}});function XO(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?Y3r(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=_Ke(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?Uf(n,a,e.toolGuards):(async(l,u)=>a(l,u))}},async executeStep(n,o,s){const i=await e.sendStep(n.raw,s),a=e.collectStep?await e.collectStep(i,o):await Z3r(i,{push:h=>o.push(h)});e.noteUsage?.(a.inputTokens,a.outputTokens);const c=Q3r(a.rawResponseParts),l=a.stepFunctionCalls.map((h,f)=>({id:`${e.providerLabel}_${f}_${h.name}`,name:t(h.name),args:h.args})),u=e.finalResultToolName?l.find(h=>h.name===e.finalResultToolName):void 0,d=u?[]:l,m=u?JSON.stringify(u.args):c;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 nUr(a,o.raw.rawResponseParts,o.raw.stepFunctionCalls),a.push({role:"user",parts:s.map(c=>({functionResponse:{name:r(c.name),response:c.error?c.output:{result:c.output}}}))}),a},mapFinishReason(n,o){const s=dC(n);return o&&s==="stop"?"tool-calls":s}}}var uCt=b({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";HO(),i_(),YO()}});function hv(){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 c(d){t=!0,r=d,n=!0,s()}let l=0;async function*u(){try{for(;;)if(l<e.length)yield e[l++],l>1024&&l*2>=e.length&&(e.splice(0,l),l=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:c,iterable:u()}}var fv=b({"src/lib/core/streamChannel.ts"(){"use strict"}});function oUr(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 sUr(e){const{name:t,execute:r,args:n,toolCallId:o,turnSignal:s,toolTimeoutMs:i}=e;if(i===null)return r(n,{toolCallId:o,abortSignal:s});const a=new AbortController,c=()=>a.abort(s.reason);s.aborted?a.abort(s.reason):s.addEventListener("abort",c,{once:!0});let l;const u=new Promise((d,m)=>{l=setTimeout(()=>{const h=new Error(`Tool "${t}" execution timed out after ${i}ms`);a.abort(h),m(h)},i)});try{return await Promise.race([Promise.resolve(r(n,{toolCallId:o,abortSignal:a.signal})),u])}finally{clearTimeout(l),s.removeEventListener("abort",c)}}async function iUr(e){const{calls:t,adapter:r,tools:n,failedTools:o,abortSignal:s,toolTimeoutMs:i}=e,a=[],c=[],l=[];let u=!1;for(const d of t){if(s.aborted){u=!0;break}l.push(d);const m=r.toolFailureBreaker,h=m?o.get(d.name):void 0;if(m&&h&&h.count>=m.maxRetries){const y={error:`TOOL_PERMANENTLY_FAILED: "${d.name}" has failed ${h.count} times. Last error: ${h.lastError}.`,status:"permanently_failed",do_not_retry:!0};a.push({...d,output:y,error:y.error,permanentlyFailed:!0}),c.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}const f=n?.[d.name];let g=f;if(!f?.execute){const y=r.resolveToolOnMiss?.(d.name);y&&(g=y,o.delete(d.name))}if(!g?.execute){const y=m?{error:`TOOL_NOT_FOUND: "${d.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${d.name}`};a.push({...d,output:y,error:y.error,permanentlyFailed:!!m}),c.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}try{const y=await sUr({name:d.name,execute:g.execute,args:d.args,toolCallId:d.id,turnSignal:s,toolTimeoutMs:i}),v=m?.classifyResultFailure?.(y);if(m)if(v){const w=o.get(d.name)??{count:0,lastError:""};w.count++,w.lastError=v,o.set(d.name,w)}else m.consecutive&&o.delete(d.name);a.push({...d,output:y}),c.push({id:d.id,name:d.name,input:d.args,output:y})}catch(y){const v=y instanceof Error?y.message:String(y);if(m){const E=o.get(d.name)??{count:0,lastError:""};E.count++,E.lastError=v,o.set(d.name,E)}const w={error:v,status:"failed"};a.push({...d,output:w,error:v}),c.push({id:d.id,name:d.name,input:d.args,output:w,error:v})}}return{toolResults:a,executions:c,dispatched:l,abortedMidBatch:u}}function Ld(e,t,r){const n=hv(),o=new AbortController,s=()=>o.abort();r.abortSignal?.addEventListener("abort",s),r.abortSignal?.aborted&&o.abort();const i=new Map;let a=!1;const c=(async()=>{let l=t,u={inputTokens:0,outputTokens:0},d="",m="",h;const f=[],g=[];let y=!1,v=e.maxSteps;const w=Date.now();try{for(let C=0;C<v&&!o.signal.aborted;C++){if(e.planReclaim){const M=e.planReclaim(l,C);if(M?.conversation!==void 0&&(l=M.conversation),M?.stop)break}const A=e.buildStepRequest(l,C);for(const M of A.hydratedToolNames??[])i.delete(M);let k=!1;const R={push:M=>{k=!0,n.push(M)}};let I;try{I=await r0(async()=>{k=!1;try{return await e.executeStep(A,R,o.signal)}catch(M){throw k?new iY(M):M}},r.span,`${e.providerLabel}.step`)}catch(M){throw M instanceof iY?M.cause:M}if(u=oUr(u,I.usage),h=I.rawStopReason,m=I.text||m,e.isMalformedStep?.(I)&&!a&&!o.signal.aborted){a=!0,p.warn(`[${e.providerLabel}] Malformed function call at step ${C+1}/${v}; retrying once.`),l=e.buildMalformedRetryNote?.(l,C)??l;continue}if(I.toolCalls.length===0){d=I.text||d;break}C===v-1&&(y=!0);const P=await iUr({calls:I.toolCalls,adapter:e,tools:r.tools,failedTools:i,abortSignal:o.signal,toolTimeoutMs:Ih(r.toolTimeoutMs)}),O=P.toolResults;if(f.push(...P.dispatched),g.push(...P.executions),P.abortedMidBatch)break;if(l=e.buildToolResultMessages(l,I,O,C),r.beforeStep&&!o.signal.aborted){const M=await r.beforeStep({stepIndex:C,stepsCompleted:C+1,maxSteps:v,elapsedMs:Date.now()-w,toolNames:P.dispatched.map(N=>N.name),signal:o.signal}),F=typeof M?.maxSteps=="number"&&Number.isFinite(M.maxSteps)?Math.floor(M.maxSteps):void 0;F!==void 0&&F>v&&(v=F,y=!1),M?.nudge&&e.appendPlanningNudge&&(l=e.appendPlanningNudge(l,M.nudge))}}const E=o.signal.aborted,_=e.mapFinishReason(h,y);return{text:d||(y?m:""),toolCalls:f,toolExecutions:g,usage:u,finishReason:E&&h===void 0?"other":_,rawStopReason:h,conversation:l,aborted:E}}catch(E){throw n.error(E),E}finally{n.close(),r.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:c}}var iY,ZO=b({"src/lib/core/loopEngine.ts"(){"use strict";fv(),z(),cd(),Lo(),iY=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function aUr(e,t){return e==="google-ai"?!0:e==="vertex"?!(t?.startsWith("claude-")??!1):!1}function cUr(e){return e==="anthropic"||e==="bedrock"}function aY(e,t,r,n){return(aUr(e,t)||cUr(e))&&r&&n>0}function lUr(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/cannot be combined with (a )?(tool|function)/i.test(t)||/json[\s_-]?(mode|schema|object|output)[^.]{0,60}(tool|function)/i.test(t)||/(tool|function)[\s-]?call[^.]{0,60}json[\s_-]?(mode|schema)/i.test(t)||/response_format[^.]{0,60}(tool|function)/i.test(t)}function dCt(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/too many states/i.test(t)}function uUr(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/does not support[^.]{0,80}response[\s_-]?format/i.test(t)||/response[\s_-]?format[^.]{0,60}(?:is )?not support/i.test(t)||/unsupported response[\s_-]?format/i.test(t)}var cY=b({"src/lib/core/modules/structuredOutputPolicy.ts"(){"use strict"}});function dUr(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function mUr(e,t,r){const n=[];let o=t;for(;o<r;){if(!dUr(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 QO(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=Y1,lowWaterRatio:s=mCt,protectedTailCount:i=pCt,calibration:a=1}=t,c=a>0?a:1,l=Math.floor(r*o/c),u=Math.floor(r*s/c);let d=n;for(const v of e)d+=v.tokens;if(d<=l)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const m=1,h=Math.max(m,e.length-i),f=[],g=new Set;for(let v=m;v<h&&d>u;v++){const w=e[v];if(w.kind!=="toolResult"||w.previewTokens===void 0)continue;const E=w.tokens-w.previewTokens;E<=0||(f.push(v),d-=E)}if(d>u){const v=mUr(e,m,h);for(const w of v){if(d<=u)break;for(let E=w.start;E<w.end;E++){const _=e[E],C=f.includes(E)?_.previewTokens??_.tokens:_.tokens;d-=C,g.add(E)}}}const y=f.filter(v=>!g.has(v));return{fire:y.length>0||g.size>0,truncate:y,drop:[...g].sort((v,w)=>v-w),projectedTokens:d}}var mCt,pCt,eD=b({"src/lib/context/loopGuardCore.ts"(){"use strict";Lo(),mCt=.6,pCt=4}});function hCt(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function fCt(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function pUr(e){return fCt(e,"functionResponse")}function lY(e){const{preview:t}=Qa(e,{maxBytes:uY,maxLines:yCt});return t}function hUr(e,t){return Gt(hCt(e.parts),t)+Oc}function fUr(e,t){return e.map(r=>{const n=hUr(r,t);if(pUr(r)){const o=hCt(r.parts),s=o.length>uY?Gt(lY(o),t)+Oc:n;return{kind:"toolResult",tokens:n,...s<n?{previewTokens:s}:{}}}return fCt(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function gCt(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:s}=e,i=fUr(t,o);let a=1;if(s&&s>0){const l=n+i.reduce((u,d)=>u+d.tokens,0);l>0&&(a=Math.min(3,Math.max(1,s/l)))}const c=QO(i,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(c.fire)return p.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:c.truncate.length,contentsDropped:c.drop.length,projectedTokens:c.projectedTokens,calibration:a}),c}var uY,yCt,dY,vCt=b({"src/lib/context/geminiLoopGuard.ts"(){"use strict";Ko(),Lf(),eD(),z(),uY=2048,yCt=60,dY="[Earlier tool exchanges were removed to fit the context window.]"}}),TCt=b({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";YO()}}),mY,Fd,wCt=b({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";mY=e=>{if(!e||e.length===0)return e;if(e.some(r=>r.cache_control!==void 0))return[...e];const t=e[e.length-1];return[...e.slice(0,-1),{...t,cache_control:{type:"ephemeral"}}]},Fd=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function gv(e,t){if(t==="functionDeclarations")return rCt(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?Ao(i):{type:"object",properties:{}},c=Fd(o);return{name:n,...s.description?{description:s.description}:{},input_schema:a,...c?{cache_control:c}:{}}})}var pY=b({"src/lib/core/nativeToolFormat.ts"(){"use strict";YO(),wCt(),ui()}});function gUr(e,t){try{const[r,n]=t.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;const s=l=>{const u=l.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},i=s(e),a=s(r),c=-1<<32-o>>>0;return(i&c)===(a&c)}catch{return!1}}function yUr(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 c=a.toLowerCase();if(c==="*")return!0;if(c.startsWith(".")){const l=c.slice(1);if(o.endsWith(l)||o===l)return!0}else if(c.includes(":")){const[l,u]=c.split(":");if(o===l&&s===u)return!0}else if(c.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&gUr(o,c))return!0}else if(o===c)return!0}return!1}catch(n){return p.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:e,error:n}),!1}}var vUr=b({"src/lib/proxy/utils/noProxyUtils.ts"(){"use strict";z()}});async function TUr(){try{return(await Promise.resolve().then(()=>(cp(),_J))).getLangfuseContext?.()}catch{return}}function wUr(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 ECt(e,t){const r={};wy.inject(fr.active(),r);const n=await TUr();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=wUr(e,t);for(const[s,i]of Object.entries(r))o.has(s)||o.set(s,i);return{...t,headers:o}}function EUr(e){try{const t=typeof e=="string"?e:e instanceof URL?e.href:e.url;return new URL(t).hostname}catch{return"[unknown]"}}function SCt(e){let t=e;for(let r=0;r<5&&t;r++){const n=t;if(n.code&&aq.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 bCt(e,t,r=3,n=500){const o=EUr(e);return xCt.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 c=await fetch(e,t);return s.setAttribute("http.request.total_attempts",i),s.setAttribute("http.response.status_code",c.status),s.setStatus({code:Ue.OK}),c}catch(c){const l=SCt(c),u=c;if(!l||a===r)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:Ue.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),s.recordException(c instanceof Error?c:new Error(String(c))),c;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(c)).slice(0,256)}),p.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 _Ct(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 hY(e){const t={};e.headers.forEach((r,n)=>{t[n]=ICt.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 SUr(e){try{const t=new URL(e),r={protocol:t.protocol,hostname:t.hostname,port:parseInt(t.port)||CCt(t.protocol),cleanUrl:`${t.protocol}//${t.hostname}:${t.port||CCt(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 p.error("[Proxy] Failed to parse proxy URL",{proxyUrl:r,error:t}),new Error(`Invalid proxy URL: ${r}`,{cause:t})}}function CCt(e){switch(e){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function bUr(e){if(yUr(e))return p.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 p.warn("[Proxy] Error selecting proxy URL",{targetUrl:e,error:t}),null}}async function _Ur(e){const t=SUr(e);switch(p.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(()=>(pf(),Y7));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 Ki(e){return yv(e)??"NOT_SET"}function ACt(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function CUr(){return async(e,t)=>{const r=await ECt(e,t),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=ACt(e);if(p.shouldLog("debug")){const{size:i,type:a}=_Ct(r?.body);p.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:s,method:r?.method||"POST",bodySize:i,bodyType:a})}try{const i=await bCt(e,r);if(p.shouldLog("debug")){const{parsed:a,size:c,type:l,headers:u}=await hY(i);p.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:s,status:i.status,statusText:i.statusText,durationMs:Date.now()-o,contentLength:c,hasContent:!!a,bodyType:l,responseHeaders:u})}return i}catch(i){throw p.debug("[Observability] HTTP request failed",{requestId:n,url:s,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-o}),i}}}async function AUr(e,t,r){const{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=r;t=await ECt(e,t);const c=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,l=Date.now(),u=ACt(e);if(p.shouldLog("debug")){const{size:h,type:f}=_Ct(t?.body);p.debug("[Observability] HTTP request to LLM provider",{requestId:c,url:u,method:t?.method||"POST",bodySize:h,bodyType:f})}p.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:c,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:Ki(o),httpsProxy:Ki(n),allProxy:Ki(s),socksProxy:Ki(i),noProxy:a||"NOT_SET",initMethod:t?.method||"GET"});const d=e instanceof Request?e.clone():null;try{const h=bUr(u);if(h){const f=new URL(u);p.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:c,targetUrl:u,urlHostname:f.hostname,urlProtocol:f.protocol,urlPort:f.port,selectedProxyUrl:Ki(h),timestamp:new Date().toISOString()}),p.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:c,proxyUrl:Ki(h),targetHostname:f.hostname,targetProtocol:f.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});const g=globalThis;g.__NL_PROXY_AGENT_CACHE__||(g.__NL_PROXY_AGENT_CACHE__=new Map);const y=g.__NL_PROXY_AGENT_CACHE__,v=Km("sha256").update(yv(h)??h).digest("hex"),w=y.get(v)||await _Ur(h);y.set(v,w),p.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:c,hasDispatcher:!!w,dispatcherType:typeof w,dispatcherConstructor:w?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let E,_={...t};e instanceof Request?(E=e.url,_={method:e.method,headers:e.headers,body:e.body,...t}):E=e;const A=await(await Promise.resolve().then(()=>(pf(),Y7))).fetch(E,{..._,dispatcher:w});if(p.shouldLog("debug")){const{parsed:k,size:R,type:I,headers:P}=await hY(A);p.debug("[Observability] HTTP response from LLM provider",{requestId:c,url:u,status:A?.status,statusText:A?.statusText,durationMs:Date.now()-l,contentLength:R,hasContent:!!k,bodyType:I,proxied:!0,responseHeaders:P})}return p.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:c,responseStatus:A?.status,responseOk:A?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),A}}catch(h){const f=h instanceof Error?h.message:String(h);p.debug("[Observability] HTTP request failed",{requestId:c,url:u,error:f,durationMs:Date.now()-l}),p.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:c,error:f,errorType:h instanceof Error?h.constructor.name:typeof h,willFallback:!0,timestamp:new Date().toISOString()}),p.warn(`[Proxy Fetch] Enhanced proxy failed (${f}), falling back to direct connection`)}p.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:c,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});const m=e instanceof Request?d??e:e;try{const h=await bCt(m,t);if(p.shouldLog("debug")){const{parsed:f,size:g,type:y,headers:v}=await hY(h);p.debug("[Observability] HTTP response from LLM provider",{requestId:c,url:u,status:h.status,statusText:h.statusText,durationMs:Date.now()-l,contentLength:g,hasContent:!!f,bodyType:y,proxied:!1,responseHeaders:v})}return h}catch(h){const f=h instanceof Error?h.message:String(h);throw p.debug("[Observability] HTTP request failed",{requestId:c,url:u,error:f,durationMs:Date.now()-l}),h}}function kUr(e){return async(t,r)=>AUr(t,r,e)}function Pt(){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(p.shouldLog("debug")){const i=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,c)=>{const l=process.env[c]||"NOT_SET";return a[c]=c.toLowerCase()==="no_proxy"?l:Ki(l),a},{});p.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:Ki(t),httpsProxy:Ki(e),allProxy:Ki(r),socksProxy:Ki(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:i,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!e&&!t&&!r&&!n?(p.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),CUr()):(p.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),p.debug(`[Proxy Fetch] HTTP_PROXY: ${Ki(t)}`),p.debug(`[Proxy Fetch] HTTPS_PROXY: ${Ki(e)}`),p.debug(`[Proxy Fetch] ALL_PROXY: ${Ki(r)}`),p.debug(`[Proxy Fetch] SOCKS_PROXY: ${Ki(n)}`),p.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),kUr(s))}function yv(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 xUr(){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:yv(t),httpsProxy:yv(e),allProxy:yv(r),socksProxy:yv(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 kCt(e){fY||!xUr().enabled||(fY=!0,p.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 xCt,ICt,fY,On=b({"src/lib/proxy/proxyFetch.ts"(){"use strict";z(),Xt(),pr(),vUr(),Wr(),Zve(),xCt=Be.http,ICt=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"]),fY=!1}});async function vv(e,t){const n=(await Promise.resolve().then(()=>(mb(),d0))).GoogleGenAI;if(!n)throw new Me({code:je.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 kCt("GoogleAIStudio"),new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{}}})}function RCt(e,t,r){const n=gCt({contents:e,availableInputTokens:Pc("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 c=e[a];if(s.has(a)&&Array.isArray(c.parts)){i.push({...c,parts:c.parts.map(l=>{const u=l;if(!u.functionResponse)return l;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?l:{functionResponse:{name:u.functionResponse.name,response:{result:lY(d)}}}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.parts)&&c.parts.some(l=>!!l.functionCall||!!l.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:dY}]})}return e.length=0,e.push(...i),!0}var PCt,IUr=b({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";ec(),Lo(),Z4(),Ka(),ut(),Ze(),z(),QJ(),uCt(),ZO(),Lo(),cY(),vCt(),bl(),pa(),$f(),Ko(),Ic(),Zm(),TCt(),fv(),pY(),On(),PCt=class extends ba{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,p.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 Me({code:je.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 ma)return new Go(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 Mr("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 $s("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 Oo(`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 Go(`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 ot(`Google AI server error: ${r}. Please try again later.`,this.providerName):new ot(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){await K_(e.input);const t=e.prompt||e.input?.text||"",r=e.model||this.modelName,n=Date.now(),o=this.getApiKey();p.info("\u{1F3A8} Starting Google AI Studio image generation",{model:r,prompt:t.substring(0,100),provider:this.providerName});let s;try{s=await vv(o,this.getBaseURL())}catch{throw new Mr("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 f=d.url;if(f.startsWith("http")){const v=await fetch(f);if(!v.ok)throw new Error(`Failed to fetch image from ${f}: ${v.status} ${v.statusText}`);const w=await v.arrayBuffer(),E=Buffer.from(w),_=this.detectImageType(E);return p.debug(`Downloaded and detected image MIME type: ${_}`),{inlineData:{mimeType:_,data:E.toString("base64")}}}const g=Buffer.from(f,"base64");return{inlineData:{mimeType:this.detectImageType(g),data:g.toString("base64")}}}if(typeof d=="string"&&d.startsWith("http")){const f=await fetch(d);if(!f.ok)throw new Error(`Failed to fetch image from ${d}: ${f.status} ${f.statusText}`);const g=await f.arrayBuffer(),y=Buffer.from(g),v=this.detectImageType(y);return p.debug(`Downloaded and detected image MIME type: ${v}`),{inlineData:{mimeType:v,data:y.toString("base64")}}}const m=Buffer.isBuffer(d)?d:typeof d=="string"?Buffer.from(d,"base64"):Buffer.from(""),h=this.detectImageType(m);return p.debug(`Detected image MIME type: ${h}`),{inlineData:{mimeType:h,data:m.toString("base64")}}})),a=[{role:"user",parts:[{text:t},...i]}],c={responseModalities:["IMAGE","TEXT"]};p.debug("Starting image generation request",{model:r,contentParts:a[0].parts.length,responseModalities:c.responseModalities});let l=null,u="";try{const d=await s.models.generateContentStream({model:r,contents:a,config:c});for await(const m of d){p.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 f of h.content.parts){if("inlineData"in f&&f.inlineData?.data){const g=f.inlineData.data;l=g;const y=f.inlineData.mimeType,v=y||"image/png";p.info("Image generation successful",{model:r,mimeType:v,dataLength:g.length,responseTime:Date.now()-n});const w={content:`Generated image using ${r} (${v})`,imageOutput:{base64:g,...y?{mimeType:y}:{}},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(w,e,n)}"text"in f&&f.text&&(u+=f.text,p.debug("Received text content",{text:f.text.substring(0,100)}))}}}catch(d){p.debug("Streaming failed, trying non-streaming approach",{error:d instanceof Error?d.message:String(d)})}if(!l){p.debug("Trying non-streaming approach");const m=(await s.models.generateContent({model:r,contents:a,config:c})).candidates?.[0];if(m?.content?.parts)for(const h of m.content.parts){if("inlineData"in h&&h.inlineData?.data){const f=h.inlineData.data;l=f;const g=h.inlineData.mimeType,y=g||"image/png";p.info("Image generation successful (non-streaming)",{model:r,mimeType:y,dataLength:f.length,responseTime:Date.now()-n});const v={content:`Generated image using ${r} (${y})`,imageOutput:{base64:f,...g?{mimeType: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 p.warn("No image data found in response",{model:r,prompt:t.substring(0,100),hasTextContent:!!u,textContent:u.substring(0,200)}),new ot(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 p.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 Gt(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&mK(e.input),e.input?.files&&e.input.files.length>0)try{await pK(e,100*1024*1024,this.providerName)}catch(t){p.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await K_(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,c=aY(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);return a&&c&&(p.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&&p.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 j6e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:"google-ai",[_e.GEN_AI_MODEL]:t,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=da(o,this.providerName,"stream");{const i=this.getApiKey(),a=await vv(i,this.getBaseURL());p.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const c=[];KO(c,e.conversationMessages);const l=await cCt(e.input,e.input.text,"[GoogleAIStudio:stream]",t);c.push({role:"user",parts:l});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const L=gv(e.tools,"functionDeclarations");d=L,u=L.toolsConfig,p.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(q=>q.name)})}const m=!u&&(e.output?.format==="json"||!!e.schema),h=m&&e.schema?aCt(e.schema):void 0,f=nCt({...e,model:t,wantsJsonOutput:m,responseSchema:h},u),g=oCt(e.maxSteps),y=L1(e.abortSignal,s?.controller.signal),v=new AbortController,w=()=>v.abort();y?.addEventListener("abort",w),y?.aborted&&v.abort();const E=Ih(e.toolTimeoutMs),_=dv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:L=>{p.warn(L==="timeout"?`[GoogleAIStudio] Native Gemini turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),v.abort()}}),C=v.signal,A=()=>_.timedOut||s?.controller.signal.aborted===!0,k=hv(),R=[],I=[];let P,O;const U=new Promise((L,q)=>{P=L,O=q}),M={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0};(async()=>{let L="",q=0,B=0,H=0,G=0,X=0,ce=0,Q=!1,Ie;const Ee=mv(kd("googleAiStudio",t));try{const le=XO({providerLabel:"GoogleAIStudio",maxSteps:g,toolFailureBreaker:{maxRetries:Rh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:E,abortSignal:C,onProgress:()=>_.noteProgress()},...d?{declarations:d}:{},buildRequest:J=>({model:t,contents:J,config:f}),sendStep:async(J,V)=>{_.noteProgress();const se=J;return a.models.generateContentStream({...se,config:{...se.config??{},abortSignal:V}})},noteUsage:(J,V)=>{Ee.noteUsage(J,V)},planReclaim:(J,V)=>{if(V!==0&&!Ee.shouldStop())return;const se=[...J];if(RCt(se,t,Ee.projectedNextPromptTokens))return Ee.resetAfterReclaim(),{conversation:se}}}),ae={...le,buildStepRequest:(J,V)=>(ce=V+1,_.noteProgress(),le.buildStepRequest(J,V)),buildToolResultMessages:(J,V,se,oe)=>{X=oe+1;for(const ie of V.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":ie.name,"tool.step":X});L=V.text||L;for(const ie of V.toolCalls)R.push({toolName:ie.name,args:ie.args});for(const ie of se)I.push({name:ie.name,input:ie.args,output:ie.output});if(se.length>0){const ie=WO(V.raw.rawResponseParts);Ct(this.handleToolExecutionStorage(V.toolCalls.map((W,re)=>({toolName:W.name,args:W.args,...re===0&&ie?{thoughtSignature:ie}:{},stepIndex:X})),se.map(W=>({toolName:W.name,output:W.output,stepIndex:X})),e,new Date),Ph,"tool storage write timed out").catch(W=>{p.warn("[GoogleAIStudio] Failed to store native tool executions",{error:W instanceof Error?W.message:String(W)})})}const Z=le.buildToolResultMessages(J,V,se,oe);if(_.shouldNudgeWrapup()){const ie=Z[Z.length-1];ie&&Array.isArray(ie.parts)&&ie.parts.push({text:lv(!1)})}try{const ie=Z[Z.length-1];Ee.noteAppendedChars(JSON.stringify(ie?.parts??[]).length)}catch{}return Z}},Pe=VO(d,e.tools,{toolTimeoutMs:E,abortSignal:C,onProgress:()=>_.noteProgress()}),{stream:Ae,resultPromise:Te}=Ld(ae,c,{tools:Pe,abortSignal:C,toolTimeoutMs:E}),he=(async()=>{for await(const J of Ae)_.noteProgress(),k.push(J)})();let Oe,De;try{Oe=await Te}catch(J){De=J}if(await Ff(he,"GoogleAIStudio"),De!==void 0)if(_.expired||e.abortSignal?.aborted)Q=!0;else throw p.error("[GoogleAIStudio] Native SDK error",De),this.handleProviderError(De);Oe&&(q+=Oe.usage.inputTokens,B+=Oe.usage.outputTokens,H+=Oe.usage.cacheReadTokens??0,G+=Oe.usage.reasoningTokens??0,Ie=Oe.rawStopReason??Ie,Oe.aborted&&(Q=!0)),C.aborted&&(Q=!0);const Ye=Oe!==void 0&&(Oe.toolCalls.length===0||Oe.finishReason!=="tool-calls"),gt=!Q&&X>=g&&!Ye;if(gt){const J=sCt("[GoogleAIStudio]",X,g,"",L);J&&k.push({content:J})}else Q&&!Ye&&(p.warn(`[GoogleAIStudio] Tool call loop ended mid-turn (${A()?"turn time limit":_.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),k.push({content:rY({timedOut:A(),stalled:_.stalled,elapsedMs:_.elapsedMs(),wasAborted:Q,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:g,toolCallCount:R.length})}));const $e=Date.now()-n,xe=uv({timedOut:A(),stalled:_.stalled,wasAborted:Q,cappedWithoutAnswer:gt,finishReason:dC(Ie)});xe!=="completed"&&this.emitTurnEvent({phase:xe,step:ce,maxSteps:g,toolCallCount:R.length,elapsedMs:_.elapsedMs()}),M.responseTime=$e,M.totalToolExecutions=R.length,M.stopReason=xe,M.stepsUsed=ce,Ie!==void 0&&(M.rawFinishReason=Ie),r.setAttribute(_e.GEN_AI_INPUT_TOKENS,q),r.setAttribute(_e.GEN_AI_OUTPUT_TOKENS,B),r.setAttribute(_e.GEN_AI_FINISH_REASON,gt?"max_steps":"stop");const ve=Math.max(0,q-H);P({provider:this.providerName,model:t,tokenUsage:{input:ve,output:B+G,total:ve+H+B+G,...H>0?{cacheReadTokens:H}:{},...G>0?{reasoning:G}:{}},requestDuration:$e,timestamp:new Date().toISOString(),stepsUsed:ce,toolCallCount:R.length,stopReason:xe,elapsedMs:_.elapsedMs(),...Ie!==void 0?{rawFinishReason:Ie}:{}}),k.close()}catch(le){k.error(le),O(le)}finally{_.dispose(),y?.removeEventListener("abort",w),s?.cleanup()}})().catch(()=>{});const N={stream:k.iterable,provider:this.providerName,model:t,toolCalls:R,analytics:U,metadata:M};return Object.defineProperty(N,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>R.map(L=>L.toolName)}),Object.defineProperty(N,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>bd(I)}),N}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return wb({name:"neurolink.provider.generate",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:"google-ai",[_e.GEN_AI_MODEL]:t,[_e.GEN_AI_OPERATION]:"generate",[_e.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=da(o,this.providerName,"generate");let i=()=>{};try{const a=this.getApiKey(),c=await vv(a,this.getBaseURL());p.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||"",u=[];KO(u,e.conversationMessages);const d=await cCt(e.input,l,"[GoogleAIStudio:generate]",t);u.push({role:"user",parts:d});let m,h;const f=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=aY(this.providerName,t,f,Object.keys(e.tools||{}).length);if(g&&y&&p.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),f&&!(g&&y)){const ve=e.tools||{};if(Object.keys(ve).length>0){const J=gv(ve,"functionDeclarations");h=J,m=J.toolsConfig,p.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:m[0].functionDeclarations.length,toolNames:m[0].functionDeclarations.map(V=>V.name)})}}const v=!m&&g,w=v&&e.schema?aCt(e.schema):void 0,E=nCt({...e,model:t,wantsJsonOutput:v,responseSchema:w},m),_=L1(e.abortSignal,s?.controller.signal),C=new AbortController,A=()=>C.abort();_?.addEventListener("abort",A),_?.aborted&&C.abort();const k=Ih(e.toolTimeoutMs),R=dv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:ve=>{p.warn(ve==="timeout"?`[GoogleAIStudio] Native Gemini generate turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini generate turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),C.abort()}}),I=C.signal;i=()=>{R.dispose(),_?.removeEventListener("abort",A)};const P=()=>R.timedOut||s?.controller.signal.aborted===!0,O=oCt(e.maxSteps);let U="",M="",F=0,N=0,L=0,q=0;const B=[],H=[];let G=0,X=0,ce=!1,Q;const Ie=mv(kd("googleAiStudio",t)),Ee=XO({providerLabel:"GoogleAIStudio",maxSteps:O,toolFailureBreaker:{maxRetries:Rh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:k,abortSignal:I,onProgress:()=>R.noteProgress()},...h?{declarations:h}:{},buildRequest:ve=>({model:t,contents:ve,config:E}),sendStep:async(ve,J)=>{R.noteProgress();const V=ve;return c.models.generateContentStream({...V,config:{...V.config??{},abortSignal:J}})},noteUsage:(ve,J)=>{Ie.noteUsage(ve,J)},planReclaim:(ve,J)=>{if(J!==0&&!Ie.shouldStop())return;const V=[...ve];if(RCt(V,t,Ie.projectedNextPromptTokens))return Ie.resetAfterReclaim(),{conversation:V}}}),le={...Ee,buildStepRequest:(ve,J)=>(X=J+1,R.noteProgress(),Ee.buildStepRequest(ve,J)),buildToolResultMessages:(ve,J,V,se)=>{G=se+1;for(const Z of J.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":Z.name,"tool.step":G}),B.push({toolName:Z.name,args:Z.args});M=J.text||M;for(const Z of V)H.push({name:Z.name,input:Z.args,output:Z.output});if(V.length>0){const Z=WO(J.raw.rawResponseParts);Ct(this.handleToolExecutionStorage(J.toolCalls.map((ie,W)=>({toolName:ie.name,args:ie.args,...W===0&&Z?{thoughtSignature:Z}:{},stepIndex:G})),V.map(ie=>({toolName:ie.name,output:ie.output,stepIndex:G})),e,new Date),Ph,"tool storage write timed out").catch(ie=>{p.warn("[GoogleAIStudio] Failed to store native tool executions",{error:ie instanceof Error?ie.message:String(ie)})})}const oe=Ee.buildToolResultMessages(ve,J,V,se);if(R.shouldNudgeWrapup()){const Z=oe[oe.length-1];Z&&Array.isArray(Z.parts)&&Z.parts.push({text:lv(!1)})}try{const Z=oe[oe.length-1];Ie.noteAppendedChars(JSON.stringify(Z?.parts??[]).length)}catch{}return oe}},ae=VO(h,e.tools,{toolTimeoutMs:k,abortSignal:I,onProgress:()=>R.noteProgress()}),{stream:Pe,resultPromise:Ae}=Ld(le,u,{tools:ae,abortSignal:I,toolTimeoutMs:k}),Te=(async()=>{for await(const ve of Pe)R.noteProgress()})();let he,Oe;try{he=await Ae}catch(ve){Oe=ve}if(await Ff(Te,"GoogleAIStudio"),Oe!==void 0)if(R.expired||e.abortSignal?.aborted)ce=!0;else throw p.error("[GoogleAIStudio] Native SDK generate error",Oe),this.handleProviderError(Oe);he&&(F+=he.usage.inputTokens,N+=he.usage.outputTokens,L+=he.usage.cacheReadTokens??0,q+=he.usage.reasoningTokens??0,Q=he.rawStopReason??Q,U=he.text,he.aborted&&(ce=!0)),I.aborted&&(ce=!0);const De=!ce&&G>=O&&!U;ce&&!U?(p.warn(`[GoogleAIStudio] Generate tool call loop ended mid-turn (${P()?"turn time limit":R.stalled?"stall watchdog":"caller abort"}); returning gathered text or an honest terminal message.`),U=M||rY({timedOut:P(),stalled:R.stalled,elapsedMs:R.elapsedMs(),wasAborted:ce,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:O,toolCallCount:B.length})):U=sCt("[GoogleAIStudio]",G,O,U,M);const Ye=Date.now()-n,gt=uv({timedOut:P(),stalled:R.stalled,wasAborted:ce,cappedWithoutAnswer:De,finishReason:dC(Q)});gt!=="completed"&&this.emitTurnEvent({phase:gt,step:X,maxSteps:O,toolCallCount:B.length,elapsedMs:R.elapsedMs()}),r.setAttribute(_e.GEN_AI_INPUT_TOKENS,F),r.setAttribute(_e.GEN_AI_OUTPUT_TOKENS,N),r.setAttribute(_e.GEN_AI_FINISH_REASON,G>=O?"max_steps":"stop");const $e=Math.max(0,F-L),xe={content:U,provider:this.providerName,model:t,stopReason:gt,stepsUsed:X,...Q!==void 0?{rawFinishReason:Q}:{},usage:{input:$e,output:N+q,total:$e+L+N+q,...L>0?{cacheReadTokens:L}:{},...q>0?{reasoning:q}:{}},...q>0&&{reasoningTokens:q},responseTime:Ye,toolsUsed:B.map(ve=>ve.toolName),toolExecutions:af(e,H),enhancedWithTools:B.length>0};return this.enhanceResult(xe,e,n)}finally{i(),s?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(MS.some(d=>r.toLowerCase().startsWith(d.toLowerCase())))return p.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return p.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};const i=t.output?.format==="json"||t.schema,a=aY(this.providerName,r,!s.disableTools,Object.keys(s.tools??{}).length);i&&a&&(p.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&&p.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length});const l=Date.now(),u=s.input?.text||s.prompt||"";try{let d=await dt({name:"neurolink.executeGeneration",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:this.providerName,[_e.GEN_AI_MODEL]:r,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(s));return d=await this.synthesizeAIResponseIfNeeded(d,t),this.emitPipelineBGenerationEvent(r,d,l,!0,void 0,u),d}catch(d){throw this.emitPipelineBGenerationEvent(r,null,l,!1,d,u),d}}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),!n&&o&&typeof o=="object"&&(o._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 vv(r,this.getBaseURL())}catch{throw new Mr("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 c=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)}},l=await n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async d=>{try{const m=d?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(m?.data){const f={data:Buffer.from(String(m.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};c({type:"audio",audio:f})}d?.serverContent?.interrupted}catch(m){c({type:"error",error:m})}},onerror:d=>{c({type:"error",error:d})},onclose:d=>{c({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}});return(async()=>{try{const d=e.input?.audio;if(!d){p.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{l.sendInput?await l.sendInput({event:"flush"}):l.sendRealtimeInput&&await l.sendRealtimeInput({event:"flush"})}catch(g){p.debug("[GeminiLive] flush control failed (non-fatal)",{error:g instanceof Error?g.message:String(g)})}continue}const h=m.toString("base64"),f=`audio/pcm;rate=${d.sampleRateHz||16e3}`;await l.sendRealtimeInput?.({media:{data:h,mimeType:f}})}try{l.sendInput?await l.sendInput({event:"flush"}):l.sendRealtimeInput&&await l.sendRealtimeInput({event:"flush"})}catch(m){p.debug("[GeminiLive] final flush failed (non-fatal)",{error:m instanceof Error?m.message:String(m)})}}catch(d){c({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){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const o=this.getApiKey(),a=(await(await vv(o,this.getBaseURL())).models.embedContent({model:n,contents:[r]})).embeddings?.[0]?.values;if(!a)throw new ot("No embedding returned from Google AI",this.providerName);return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.length}),a}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";p.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=this.getApiKey(),i=((await(await vv(n,this.getBaseURL())).models.embedContent({model:r,contents:e})).embeddings||[]).map(a=>a.values||[]);return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:i.length,embeddingDimension:i[0]?.length}),i}catch(n){throw p.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 Mr("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}}}}),MCt={};ee(MCt,{GoogleAIStudioProvider:()=>PCt});var RUr=b({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";IUr()}});async function ku(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=l=>new Error(`${r} download exceeded size cap after fetch: ${l} bytes (max ${t})`),s=e.body;if(!s||typeof s.getReader!="function"){const l=Buffer.from(await e.arrayBuffer());if(l.length>t)throw o(l.length);return l}const i=s.getReader(),a=[];let c=0;for(;;){const{done:l,value:u}=await i.read();if(l)break;if(c+=u.byteLength,c>t)throw await i.cancel().catch(()=>{}),o(c);a.push(u)}return Buffer.concat(a,c)}var Bf,zf,hp,_a=b({"src/lib/utils/sizeGuard.ts"(){"use strict";Bf=256*1024*1024,zf=50*1024*1024,hp=25*1024*1024}}),PUr,MUr,OUr,DUr,tD,OCt,gY,yY,NUr,LUr,FUr,$Ur,UUr=b({"node-stub:node:dns/promises"(){PUr=globalThis.crypto,MUr=globalThis.ReadableStream||class{},OUr=globalThis.URL,DUr=globalThis.URLSearchParams,tD=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},tD.custom=Symbol.for("nodejs.util.inspect.custom"),tD.colors={},tD.styles={},OCt=globalThis.TextDecoder,gY=globalThis.TextEncoder,yY=(e,t)=>t?.(null,"127.0.0.1",4),NUr=globalThis.performance||{now:()=>Date.now()},LUr=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 gY().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 gY().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 OCt().decode(this)}},FUr=globalThis.clearTimeout,$Ur=globalThis.clearInterval}}),BUr,zUr,qUr,GUr,rD,DCt,vY,jUr,HUr,NCt,VUr,WUr,KUr=b({"node-stub:node:net"(){BUr=globalThis.crypto,zUr=globalThis.ReadableStream||class{},qUr=globalThis.URL,GUr=globalThis.URLSearchParams,rD=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},rD.custom=Symbol.for("nodejs.util.inspect.custom"),rD.colors={},rD.styles={},DCt=globalThis.TextDecoder,vY=globalThis.TextEncoder,jUr=globalThis.performance||{now:()=>Date.now()},HUr=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 vY().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 vY().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 DCt().decode(this)}},NCt=()=>0,VUr=globalThis.clearTimeout,WUr=globalThis.clearInterval}});function JUr(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 nD(e){if(e.length===0)return null;const t=e.split(".");if(t.length===4){const r=t.map(JUr);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 LCt(e){if(NCt(e)!==6)return null;const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);let r;if(t){const n=nD(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 FCt(e){const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return nD(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 $Ct(e){const[t,r,n,o]=e.split(".").map(s=>parseInt(s,10));return(t<<24|r<<16|n<<8|o)>>>0}function mC(e){const t=$Ct(e);for(const[r,n]of GCt){const o=$Ct(r),s=n===0?0:4294967295<<32-n>>>0;if((t&s)===(o&s))return!0}return!1}function UCt(e){return jCt.some(t=>t.length===39?e===t:e.startsWith(t))}function BCt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function zCt(e){const t=nD(e);if(t)return mC(t)?`IPv4 ${e} \u2192 ${t} is in a blocked range`:null;if(e.includes(":")){const r=FCt(e);if(r)return mC(r)?`IPv4-mapped IPv6 ${e} \u2192 ${r} is in a blocked range`:null;const n=LCt(e);return n?UCt(n)?`IPv6 ${e} is in a blocked range`:null:`IPv6 ${e} could not be parsed`}return"not-an-ip"}async function fp(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=BCt(t.hostname).toLowerCase(),n=zCt(r);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);await qCt(e,r)}}async function qCt(e,t){const[r,n]=await Promise.allSettled([yY(t,{family:4,all:!0}),yY(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",c=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: ${c})`)}for(const a of o)if(mC(a))throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv4 in blocked range)`);for(const a of s){const c=zCt(a.toLowerCase());if(c&&c!=="not-an-ip")throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv6 ${c})`)}return{v4:o,v6:s}}async function YUr(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=BCt(t.hostname).toLowerCase(),n=nD(r);if(n){if(mC(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 c=FCt(r);if(c){if(mC(c))throw new Error(`URL "${e}" rejected: IPv4-mapped IPv6 ${r} \u2192 ${c} is in a blocked range`);return{url:e,ip:c,family:4,addresses:[{ip:c,family:4}]}}const l=LCt(r);if(!l)throw new Error(`URL "${e}" rejected: IPv6 ${r} could not be parsed`);if(UCt(l))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 qCt(e,r),i=[...o.map(c=>({ip:c,family:4})),...s.map(c=>({ip:c,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 GCt,jCt,gp=b({"src/lib/utils/ssrfGuard.ts"(){"use strict";UUr(),KUr(),GCt=[["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]],jCt=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]}});function TY(e){}function wY(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=TY,onError:r=TY,onRetry:n=TY,onComment:o}=e,s=[];let i=!0,a,c="",l=0,u;function d(v){if(i&&(i=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),s.length===0){const _=m(v);_!==""&&s.push(_);return}if(v.indexOf(`
|
|
1034
|
+
${t}`:t:e}async function Z3r(e,t){const r=[],n=[];let o=0,s=0,i=0,a=0,c;for await(const l of e){const u=l,m=u.candidates?.[0],h=m?.finishReason;typeof h=="string"&&(c=h);const f=m?.content;if(f&&Array.isArray(f.parts))for(const y of f.parts)r.push(y),typeof y.text=="string"&&y.text.length>0&&t.push({content:y.text});l.functionCalls&&n.push(...l.functionCalls);const g=u.usageMetadata;g&&(o=Math.max(o,g.promptTokenCount||0),s=Math.max(s,g.candidatesTokenCount||0),i=Math.max(i,g.cachedContentTokenCount||0),a=Math.max(a,g.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:c,inputTokens:o,outputTokens:s,cacheReadTokens:i,reasoningTokens:a}}function WO(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 Q3r(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function sCt(e,t,r,n,o){return t>=r&&!n?(p.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||pp(r,0)):n}function mp(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 pp(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 Nc(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 iCt(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 eUr(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${iCt(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function tUr(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 ${iCt(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function rUr(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function rY(e){return e.timedOut?eUr(e.elapsedMs,e.toolCallCount):e.stalled?tUr(e.stallTimeoutMs??0,e.toolCallCount):e.wasAborted?rUr(e.toolCallCount):pp(e.maxSteps,e.toolCallCount)}function lv(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 uv(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 dv(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??E_e:void 0;let s=!1,i=!1,a=t,c,l;if(n!==void 0&&(c=setTimeout(()=>{s=!0,e.onDeadline("timeout")},n),c.unref?.()),r(e.stallTimeoutMs)){const u=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);l=setInterval(()=>{!i&&!s&&Date.now()-a>=u&&(i=!0,e.onDeadline("stall"))},d),l.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(){c&&clearTimeout(c),l&&clearInterval(l)}}}function mv(e,t=Y1){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 nUr(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function aCt(e){const t=Ao(e,"openApi3"),r=Xn(t);return r.$schema&&delete r.$schema,Hi(r)}function KO(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 c=s(a),l=r.get(c);if(l)return l;const u={type:"tool_step",callParts:[],resultParts:[]};return r.set(c,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 c=a.role==="assistant"?"model":a.role;if(c!=="user"&&c!=="model"||!a.content||a.content.trim().length===0)continue;o++;const l={text:a.content};a.metadata?.thoughtSignature&&(l.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:c,parts:[l]})}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&&p.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 nY(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 hvt(n.buffer,n.mimeType,i);if(sK(a.mimeType)){p.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")}}),p.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function oY(e,t,r,n,o="[GeminiNative]"){if(!t||t.length===0)return;let s=e.reduce((i,a)=>"inlineData"in a?i+Math.floor(a.inlineData.data.length*3/4):i,0);for(const i of t){const a=i.filename.split(/[\\/]/).pop()??i.filename,c=Svt(r,i,s,n);if(!c.deliver){p.warn(`${o} Sending keyframes instead of the clip for ${a}: ${c.reason}.`);continue}s+=i.buffer.length,e.push({inlineData:{mimeType:i.mimeType,data:i.buffer.toString("base64")}}),p.debug(`${o} Added native video part for ${a} (${i.mimeType})`)}}async function cCt(e,t,r="[GeminiNative]",n){const s=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){p.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const i of e.pdfFiles){let a;typeof i=="string"?Ai(i)?a=li(i):a=Buffer.from(i,"base64"):a=i,s.push({inlineData:{mimeType:"application/pdf",data:a.toString("base64")}})}}if(e?.images&&e.images.length>0){p.debug(`${r} Processing ${e.images.length} image(s)`);for(const i of e.images){const a=i&&typeof i=="object"&&!Buffer.isBuffer(i)?i.data:i;let c,l="image/jpeg";if(typeof a=="string")if(Ai(a)){c=li(a);const u=u0(a).toLowerCase();u===".png"?l="image/png":u===".gif"?l="image/gif":u===".webp"&&(l="image/webp")}else if(a.startsWith("data:")){const u=a.match(/^data:([^;]+);base64,(.+)$/);if(u)l=u[1],c=Buffer.from(u[2],"base64");else continue}else if(a.startsWith("http://")||a.startsWith("https://"))try{const u=await fetch(a);if(!u.ok){p.warn(`${r} Image fetch failed: ${u.status} ${u.statusText}, skipping`,{url:a});continue}const d=await u.arrayBuffer();c=Buffer.from(d);const m=u.headers.get("content-type");m&&m.startsWith("image/")&&(l=m.split(";")[0])}catch(u){p.warn(`${r} Image URL fetch threw, skipping: ${u instanceof Error?u.message:String(u)}`,{url:a});continue}else c=Buffer.from(a,"base64");else c=a;c&&s.push({inlineData:{mimeType:l,data:c.toString("base64")}})}}return await nY(s,e?.nativeAudioFiles,r),await oY(s,e?.nativeVideoFiles,"google-ai-studio",n,r),s}var pv,lCt,JO,sY,YO=b({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";Wr(),Pn(),zt(),Lo(),vvt(),aK(),z(),HO(),ud(),ui(),tCt(),pv=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}::${W3r(o)}`;if(r.has(i))return p.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}}},lCt=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,JO=128,sY=100}});function XO(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?Y3r(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=_Ke(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?Uf(n,a,e.toolGuards):(async(l,u)=>a(l,u))}},async executeStep(n,o,s){const i=await e.sendStep(n.raw,s),a=e.collectStep?await e.collectStep(i,o):await Z3r(i,{push:h=>o.push(h)});e.noteUsage?.(a.inputTokens,a.outputTokens);const c=Q3r(a.rawResponseParts),l=a.stepFunctionCalls.map((h,f)=>({id:`${e.providerLabel}_${f}_${h.name}`,name:t(h.name),args:h.args})),u=e.finalResultToolName?l.find(h=>h.name===e.finalResultToolName):void 0,d=u?[]:l,m=u?JSON.stringify(u.args):c;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 nUr(a,o.raw.rawResponseParts,o.raw.stepFunctionCalls),a.push({role:"user",parts:s.map(c=>({functionResponse:{name:r(c.name),response:c.error?c.output:{result:c.output}}}))}),a},mapFinishReason(n,o){const s=dC(n);return o&&s==="stop"?"tool-calls":s}}}var uCt=b({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";HO(),i_(),YO()}});function hv(){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 c(d){t=!0,r=d,n=!0,s()}let l=0;async function*u(){try{for(;;)if(l<e.length)yield e[l++],l>1024&&l*2>=e.length&&(e.splice(0,l),l=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:c,iterable:u()}}var fv=b({"src/lib/core/streamChannel.ts"(){"use strict"}});function oUr(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 sUr(e){const{name:t,execute:r,args:n,toolCallId:o,turnSignal:s,toolTimeoutMs:i}=e;if(i===null)return r(n,{toolCallId:o,abortSignal:s});const a=new AbortController,c=()=>a.abort(s.reason);s.aborted?a.abort(s.reason):s.addEventListener("abort",c,{once:!0});let l;const u=new Promise((d,m)=>{l=setTimeout(()=>{const h=new Error(`Tool "${t}" execution timed out after ${i}ms`);a.abort(h),m(h)},i)});try{return await Promise.race([Promise.resolve(r(n,{toolCallId:o,abortSignal:a.signal})),u])}finally{clearTimeout(l),s.removeEventListener("abort",c)}}async function iUr(e){const{calls:t,adapter:r,tools:n,failedTools:o,abortSignal:s,toolTimeoutMs:i}=e,a=[],c=[],l=[];let u=!1;for(const d of t){if(s.aborted){u=!0;break}l.push(d);const m=r.toolFailureBreaker,h=m?o.get(d.name):void 0;if(m&&h&&h.count>=m.maxRetries){const y={error:`TOOL_PERMANENTLY_FAILED: "${d.name}" has failed ${h.count} times. Last error: ${h.lastError}.`,status:"permanently_failed",do_not_retry:!0};a.push({...d,output:y,error:y.error,permanentlyFailed:!0}),c.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}const f=n?.[d.name];let g=f;if(!f?.execute){const y=r.resolveToolOnMiss?.(d.name);y&&(g=y,o.delete(d.name))}if(!g?.execute){const y=m?{error:`TOOL_NOT_FOUND: "${d.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${d.name}`};a.push({...d,output:y,error:y.error,permanentlyFailed:!!m}),c.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}try{const y=await sUr({name:d.name,execute:g.execute,args:d.args,toolCallId:d.id,turnSignal:s,toolTimeoutMs:i}),v=m?.classifyResultFailure?.(y);if(m)if(v){const w=o.get(d.name)??{count:0,lastError:""};w.count++,w.lastError=v,o.set(d.name,w)}else m.consecutive&&o.delete(d.name);a.push({...d,output:y}),c.push({id:d.id,name:d.name,input:d.args,output:y})}catch(y){const v=y instanceof Error?y.message:String(y);if(m){const E=o.get(d.name)??{count:0,lastError:""};E.count++,E.lastError=v,o.set(d.name,E)}const w={error:v,status:"failed"};a.push({...d,output:w,error:v}),c.push({id:d.id,name:d.name,input:d.args,output:w,error:v})}}return{toolResults:a,executions:c,dispatched:l,abortedMidBatch:u}}function Ld(e,t,r){const n=hv(),o=new AbortController,s=()=>o.abort();r.abortSignal?.addEventListener("abort",s),r.abortSignal?.aborted&&o.abort();const i=new Map;let a=!1;const c=(async()=>{let l=t,u={inputTokens:0,outputTokens:0},d="",m="",h;const f=[],g=[];let y=!1,v=e.maxSteps;const w=Date.now();try{for(let C=0;C<v&&!o.signal.aborted;C++){if(e.planReclaim){const M=e.planReclaim(l,C);if(M?.conversation!==void 0&&(l=M.conversation),M?.stop)break}const A=e.buildStepRequest(l,C);for(const M of A.hydratedToolNames??[])i.delete(M);let k=!1;const R={push:M=>{k=!0,n.push(M)}};let I;try{I=await r0(async()=>{k=!1;try{return await e.executeStep(A,R,o.signal)}catch(M){throw k?new iY(M):M}},r.span,`${e.providerLabel}.step`)}catch(M){throw M instanceof iY?M.cause:M}if(u=oUr(u,I.usage),h=I.rawStopReason,m=I.text||m,e.isMalformedStep?.(I)&&!a&&!o.signal.aborted){a=!0,p.warn(`[${e.providerLabel}] Malformed function call at step ${C+1}/${v}; retrying once.`),l=e.buildMalformedRetryNote?.(l,C)??l;continue}if(I.toolCalls.length===0){d=I.text||d;break}C===v-1&&(y=!0);const P=await iUr({calls:I.toolCalls,adapter:e,tools:r.tools,failedTools:i,abortSignal:o.signal,toolTimeoutMs:Ih(r.toolTimeoutMs)}),O=P.toolResults;if(f.push(...P.dispatched),g.push(...P.executions),P.abortedMidBatch)break;if(l=e.buildToolResultMessages(l,I,O,C),r.beforeStep&&!o.signal.aborted){const M=await r.beforeStep({stepIndex:C,stepsCompleted:C+1,maxSteps:v,elapsedMs:Date.now()-w,toolNames:P.dispatched.map(N=>N.name),signal:o.signal}),F=typeof M?.maxSteps=="number"&&Number.isFinite(M.maxSteps)?Math.floor(M.maxSteps):void 0;F!==void 0&&F>v&&(v=F,y=!1),M?.nudge&&e.appendPlanningNudge&&(l=e.appendPlanningNudge(l,M.nudge))}}const E=o.signal.aborted,_=e.mapFinishReason(h,y);return{text:d||(y?m:""),toolCalls:f,toolExecutions:g,usage:u,finishReason:E&&h===void 0?"other":_,rawStopReason:h,conversation:l,aborted:E}}catch(E){throw n.error(E),E}finally{n.close(),r.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:c}}var iY,ZO=b({"src/lib/core/loopEngine.ts"(){"use strict";fv(),z(),cd(),Lo(),iY=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function aUr(e,t){return e==="google-ai"?!0:e==="vertex"?!(t?.startsWith("claude-")??!1):!1}function cUr(e){return e==="anthropic"||e==="bedrock"}function aY(e,t,r,n){return(aUr(e,t)||cUr(e))&&r&&n>0}function lUr(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/cannot be combined with (a )?(tool|function)/i.test(t)||/json[\s_-]?(mode|schema|object|output)[^.]{0,60}(tool|function)/i.test(t)||/(tool|function)[\s-]?call[^.]{0,60}json[\s_-]?(mode|schema)/i.test(t)||/response_format[^.]{0,60}(tool|function)/i.test(t)}function dCt(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/too many states/i.test(t)}function uUr(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/does not support[^.]{0,80}response[\s_-]?format/i.test(t)||/response[\s_-]?format[^.]{0,60}(?:is )?not support/i.test(t)||/unsupported response[\s_-]?format/i.test(t)}var cY=b({"src/lib/core/modules/structuredOutputPolicy.ts"(){"use strict"}});function dUr(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function mUr(e,t,r){const n=[];let o=t;for(;o<r;){if(!dUr(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 QO(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=Y1,lowWaterRatio:s=mCt,protectedTailCount:i=pCt,calibration:a=1}=t,c=a>0?a:1,l=Math.floor(r*o/c),u=Math.floor(r*s/c);let d=n;for(const v of e)d+=v.tokens;if(d<=l)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const m=1,h=Math.max(m,e.length-i),f=[],g=new Set;for(let v=m;v<h&&d>u;v++){const w=e[v];if(w.kind!=="toolResult"||w.previewTokens===void 0)continue;const E=w.tokens-w.previewTokens;E<=0||(f.push(v),d-=E)}if(d>u){const v=mUr(e,m,h);for(const w of v){if(d<=u)break;for(let E=w.start;E<w.end;E++){const _=e[E],C=f.includes(E)?_.previewTokens??_.tokens:_.tokens;d-=C,g.add(E)}}}const y=f.filter(v=>!g.has(v));return{fire:y.length>0||g.size>0,truncate:y,drop:[...g].sort((v,w)=>v-w),projectedTokens:d}}var mCt,pCt,eD=b({"src/lib/context/loopGuardCore.ts"(){"use strict";Lo(),mCt=.6,pCt=4}});function hCt(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function fCt(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function pUr(e){return fCt(e,"functionResponse")}function lY(e){const{preview:t}=Qa(e,{maxBytes:uY,maxLines:yCt});return t}function hUr(e,t){return Gt(hCt(e.parts),t)+Oc}function fUr(e,t){return e.map(r=>{const n=hUr(r,t);if(pUr(r)){const o=hCt(r.parts),s=o.length>uY?Gt(lY(o),t)+Oc:n;return{kind:"toolResult",tokens:n,...s<n?{previewTokens:s}:{}}}return fCt(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function gCt(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:s}=e,i=fUr(t,o);let a=1;if(s&&s>0){const l=n+i.reduce((u,d)=>u+d.tokens,0);l>0&&(a=Math.min(3,Math.max(1,s/l)))}const c=QO(i,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(c.fire)return p.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:c.truncate.length,contentsDropped:c.drop.length,projectedTokens:c.projectedTokens,calibration:a}),c}var uY,yCt,dY,vCt=b({"src/lib/context/geminiLoopGuard.ts"(){"use strict";Ko(),Lf(),eD(),z(),uY=2048,yCt=60,dY="[Earlier tool exchanges were removed to fit the context window.]"}}),TCt=b({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";YO()}}),mY,Fd,wCt=b({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";mY=e=>{if(!e||e.length===0)return e;if(e.some(r=>r.cache_control!==void 0))return[...e];const t=e[e.length-1];return[...e.slice(0,-1),{...t,cache_control:{type:"ephemeral"}}]},Fd=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function gv(e,t){if(t==="functionDeclarations")return rCt(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?Ao(i):{type:"object",properties:{}},c=Fd(o);return{name:n,...s.description?{description:s.description}:{},input_schema:a,...c?{cache_control:c}:{}}})}var pY=b({"src/lib/core/nativeToolFormat.ts"(){"use strict";YO(),wCt(),ui()}});function gUr(e,t){try{const[r,n]=t.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;const s=l=>{const u=l.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},i=s(e),a=s(r),c=-1<<32-o>>>0;return(i&c)===(a&c)}catch{return!1}}function yUr(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 c=a.toLowerCase();if(c==="*")return!0;if(c.startsWith(".")){const l=c.slice(1);if(o.endsWith(l)||o===l)return!0}else if(c.includes(":")){const[l,u]=c.split(":");if(o===l&&s===u)return!0}else if(c.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&gUr(o,c))return!0}else if(o===c)return!0}return!1}catch(n){return p.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:e,error:n}),!1}}var vUr=b({"src/lib/proxy/utils/noProxyUtils.ts"(){"use strict";z()}});async function TUr(){try{return(await Promise.resolve().then(()=>(cp(),_J))).getLangfuseContext?.()}catch{return}}function wUr(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 ECt(e,t){const r={};wy.inject(fr.active(),r);const n=await TUr();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=wUr(e,t);for(const[s,i]of Object.entries(r))o.has(s)||o.set(s,i);return{...t,headers:o}}function EUr(e){try{const t=typeof e=="string"?e:e instanceof URL?e.href:e.url;return new URL(t).hostname}catch{return"[unknown]"}}function SCt(e){let t=e;for(let r=0;r<5&&t;r++){const n=t;if(n.code&&aq.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 bCt(e,t,r=3,n=500){const o=EUr(e);return xCt.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 c=await fetch(e,t);return s.setAttribute("http.request.total_attempts",i),s.setAttribute("http.response.status_code",c.status),s.setStatus({code:Ue.OK}),c}catch(c){const l=SCt(c),u=c;if(!l||a===r)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:Ue.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),s.recordException(c instanceof Error?c:new Error(String(c))),c;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(c)).slice(0,256)}),p.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 _Ct(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 hY(e){const t={};e.headers.forEach((r,n)=>{t[n]=ICt.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 SUr(e){try{const t=new URL(e),r={protocol:t.protocol,hostname:t.hostname,port:parseInt(t.port)||CCt(t.protocol),cleanUrl:`${t.protocol}//${t.hostname}:${t.port||CCt(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 p.error("[Proxy] Failed to parse proxy URL",{proxyUrl:r,error:t}),new Error(`Invalid proxy URL: ${r}`,{cause:t})}}function CCt(e){switch(e){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function bUr(e){if(yUr(e))return p.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 p.warn("[Proxy] Error selecting proxy URL",{targetUrl:e,error:t}),null}}async function _Ur(e){const t=SUr(e);switch(p.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(()=>(pf(),Y7));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 Ki(e){return yv(e)??"NOT_SET"}function ACt(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function CUr(){return async(e,t)=>{const r=await ECt(e,t),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=ACt(e);if(p.shouldLog("debug")){const{size:i,type:a}=_Ct(r?.body);p.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:s,method:r?.method||"POST",bodySize:i,bodyType:a})}try{const i=await bCt(e,r);if(p.shouldLog("debug")){const{parsed:a,size:c,type:l,headers:u}=await hY(i);p.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:s,status:i.status,statusText:i.statusText,durationMs:Date.now()-o,contentLength:c,hasContent:!!a,bodyType:l,responseHeaders:u})}return i}catch(i){throw p.debug("[Observability] HTTP request failed",{requestId:n,url:s,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-o}),i}}}async function AUr(e,t,r){const{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=r;t=await ECt(e,t);const c=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,l=Date.now(),u=ACt(e);if(p.shouldLog("debug")){const{size:h,type:f}=_Ct(t?.body);p.debug("[Observability] HTTP request to LLM provider",{requestId:c,url:u,method:t?.method||"POST",bodySize:h,bodyType:f})}p.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:c,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:Ki(o),httpsProxy:Ki(n),allProxy:Ki(s),socksProxy:Ki(i),noProxy:a||"NOT_SET",initMethod:t?.method||"GET"});const d=e instanceof Request?e.clone():null;try{const h=bUr(u);if(h){const f=new URL(u);p.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:c,targetUrl:u,urlHostname:f.hostname,urlProtocol:f.protocol,urlPort:f.port,selectedProxyUrl:Ki(h),timestamp:new Date().toISOString()}),p.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:c,proxyUrl:Ki(h),targetHostname:f.hostname,targetProtocol:f.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});const g=globalThis;g.__NL_PROXY_AGENT_CACHE__||(g.__NL_PROXY_AGENT_CACHE__=new Map);const y=g.__NL_PROXY_AGENT_CACHE__,v=Km("sha256").update(yv(h)??h).digest("hex"),w=y.get(v)||await _Ur(h);y.set(v,w),p.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:c,hasDispatcher:!!w,dispatcherType:typeof w,dispatcherConstructor:w?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let E,_={...t};e instanceof Request?(E=e.url,_={method:e.method,headers:e.headers,body:e.body,...t}):E=e;const A=await(await Promise.resolve().then(()=>(pf(),Y7))).fetch(E,{..._,dispatcher:w});if(p.shouldLog("debug")){const{parsed:k,size:R,type:I,headers:P}=await hY(A);p.debug("[Observability] HTTP response from LLM provider",{requestId:c,url:u,status:A?.status,statusText:A?.statusText,durationMs:Date.now()-l,contentLength:R,hasContent:!!k,bodyType:I,proxied:!0,responseHeaders:P})}return p.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:c,responseStatus:A?.status,responseOk:A?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),A}}catch(h){const f=h instanceof Error?h.message:String(h);p.debug("[Observability] HTTP request failed",{requestId:c,url:u,error:f,durationMs:Date.now()-l}),p.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:c,error:f,errorType:h instanceof Error?h.constructor.name:typeof h,willFallback:!0,timestamp:new Date().toISOString()}),p.warn(`[Proxy Fetch] Enhanced proxy failed (${f}), falling back to direct connection`)}p.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:c,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});const m=e instanceof Request?d??e:e;try{const h=await bCt(m,t);if(p.shouldLog("debug")){const{parsed:f,size:g,type:y,headers:v}=await hY(h);p.debug("[Observability] HTTP response from LLM provider",{requestId:c,url:u,status:h.status,statusText:h.statusText,durationMs:Date.now()-l,contentLength:g,hasContent:!!f,bodyType:y,proxied:!1,responseHeaders:v})}return h}catch(h){const f=h instanceof Error?h.message:String(h);throw p.debug("[Observability] HTTP request failed",{requestId:c,url:u,error:f,durationMs:Date.now()-l}),h}}function kUr(e){return async(t,r)=>AUr(t,r,e)}function Pt(){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(p.shouldLog("debug")){const i=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,c)=>{const l=process.env[c]||"NOT_SET";return a[c]=c.toLowerCase()==="no_proxy"?l:Ki(l),a},{});p.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:Ki(t),httpsProxy:Ki(e),allProxy:Ki(r),socksProxy:Ki(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:i,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!e&&!t&&!r&&!n?(p.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),CUr()):(p.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),p.debug(`[Proxy Fetch] HTTP_PROXY: ${Ki(t)}`),p.debug(`[Proxy Fetch] HTTPS_PROXY: ${Ki(e)}`),p.debug(`[Proxy Fetch] ALL_PROXY: ${Ki(r)}`),p.debug(`[Proxy Fetch] SOCKS_PROXY: ${Ki(n)}`),p.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),kUr(s))}function yv(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 xUr(){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:yv(t),httpsProxy:yv(e),allProxy:yv(r),socksProxy:yv(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 kCt(e){fY||!xUr().enabled||(fY=!0,p.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 xCt,ICt,fY,On=b({"src/lib/proxy/proxyFetch.ts"(){"use strict";z(),Xt(),pr(),vUr(),Wr(),Zve(),xCt=Be.http,ICt=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"]),fY=!1}});async function vv(e,t){const n=(await Promise.resolve().then(()=>(mb(),d0))).GoogleGenAI;if(!n)throw new Me({code:je.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 kCt("GoogleAIStudio"),new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{}}})}function RCt(e,t,r){const n=gCt({contents:e,availableInputTokens:Pc("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 c=e[a];if(s.has(a)&&Array.isArray(c.parts)){i.push({...c,parts:c.parts.map(l=>{const u=l;if(!u.functionResponse)return l;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?l:{functionResponse:{name:u.functionResponse.name,response:{result:lY(d)}}}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.parts)&&c.parts.some(l=>!!l.functionCall||!!l.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:dY}]})}return e.length=0,e.push(...i),!0}var PCt,IUr=b({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";ec(),Lo(),Z4(),Ka(),ut(),Ze(),z(),QJ(),uCt(),ZO(),Lo(),cY(),vCt(),bl(),pa(),$f(),Ko(),Ic(),Zm(),TCt(),fv(),pY(),On(),PCt=class extends ba{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,p.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 Me({code:je.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 ma)return new Go(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 Mr("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 $s("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 Oo(`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 Go(`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 ot(`Google AI server error: ${r}. Please try again later.`,this.providerName):new ot(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){await K_(e.input);const t=e.prompt||e.input?.text||"",r=e.model||this.modelName,n=Date.now(),o=this.getApiKey();p.info("\u{1F3A8} Starting Google AI Studio image generation",{model:r,prompt:t.substring(0,100),provider:this.providerName});let s;try{s=await vv(o,this.getBaseURL())}catch{throw new Mr("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 f=d.url;if(f.startsWith("http")){const v=await fetch(f);if(!v.ok)throw new Error(`Failed to fetch image from ${f}: ${v.status} ${v.statusText}`);const w=await v.arrayBuffer(),E=Buffer.from(w),_=this.detectImageType(E);return p.debug(`Downloaded and detected image MIME type: ${_}`),{inlineData:{mimeType:_,data:E.toString("base64")}}}const g=Buffer.from(f,"base64");return{inlineData:{mimeType:this.detectImageType(g),data:g.toString("base64")}}}if(typeof d=="string"&&d.startsWith("http")){const f=await fetch(d);if(!f.ok)throw new Error(`Failed to fetch image from ${d}: ${f.status} ${f.statusText}`);const g=await f.arrayBuffer(),y=Buffer.from(g),v=this.detectImageType(y);return p.debug(`Downloaded and detected image MIME type: ${v}`),{inlineData:{mimeType:v,data:y.toString("base64")}}}const m=Buffer.isBuffer(d)?d:typeof d=="string"?Buffer.from(d,"base64"):Buffer.from(""),h=this.detectImageType(m);return p.debug(`Detected image MIME type: ${h}`),{inlineData:{mimeType:h,data:m.toString("base64")}}})),a=[{role:"user",parts:[{text:t},...i]}],c={responseModalities:["IMAGE","TEXT"]};p.debug("Starting image generation request",{model:r,contentParts:a[0].parts.length,responseModalities:c.responseModalities});let l=null,u="";try{const d=await s.models.generateContentStream({model:r,contents:a,config:c});for await(const m of d){p.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 f of h.content.parts){if("inlineData"in f&&f.inlineData?.data){const g=f.inlineData.data;l=g;const y=f.inlineData.mimeType,v=y||"image/png";p.info("Image generation successful",{model:r,mimeType:v,dataLength:g.length,responseTime:Date.now()-n});const w={content:`Generated image using ${r} (${v})`,imageOutput:{base64:g,...y?{mimeType:y}:{}},provider:this.providerName,model:r,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(w,e,n)}"text"in f&&f.text&&(u+=f.text,p.debug("Received text content",{text:f.text.substring(0,100)}))}}}catch(d){p.debug("Streaming failed, trying non-streaming approach",{error:d instanceof Error?d.message:String(d)})}if(!l){p.debug("Trying non-streaming approach");const m=(await s.models.generateContent({model:r,contents:a,config:c})).candidates?.[0];if(m?.content?.parts)for(const h of m.content.parts){if("inlineData"in h&&h.inlineData?.data){const f=h.inlineData.data;l=f;const g=h.inlineData.mimeType,y=g||"image/png";p.info("Image generation successful (non-streaming)",{model:r,mimeType:y,dataLength:f.length,responseTime:Date.now()-n});const v={content:`Generated image using ${r} (${y})`,imageOutput:{base64:f,...g?{mimeType: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 p.warn("No image data found in response",{model:r,prompt:t.substring(0,100),hasTextContent:!!u,textContent:u.substring(0,200)}),new ot(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 p.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 Gt(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&mK(e.input),e.input?.files&&e.input.files.length>0)try{await pK(e,100*1024*1024,this.providerName)}catch(t){p.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await K_(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,c=aY(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);return a&&c&&(p.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&&p.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 j6e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:"google-ai",[_e.GEN_AI_MODEL]:t,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=da(o,this.providerName,"stream");{const i=this.getApiKey(),a=await vv(i,this.getBaseURL());p.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const c=[];KO(c,e.conversationMessages);const l=await cCt(e.input,e.input.text,"[GoogleAIStudio:stream]",t);c.push({role:"user",parts:l});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const L=gv(e.tools,"functionDeclarations");d=L,u=L.toolsConfig,p.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(q=>q.name)})}const m=!u&&(e.output?.format==="json"||!!e.schema),h=m&&e.schema?aCt(e.schema):void 0,f=nCt({...e,model:t,wantsJsonOutput:m,responseSchema:h},u),g=oCt(e.maxSteps),y=L1(e.abortSignal,s?.controller.signal),v=new AbortController,w=()=>v.abort();y?.addEventListener("abort",w),y?.aborted&&v.abort();const E=Ih(e.toolTimeoutMs),_=dv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:L=>{p.warn(L==="timeout"?`[GoogleAIStudio] Native Gemini turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),v.abort()}}),C=v.signal,A=()=>_.timedOut||s?.controller.signal.aborted===!0,k=hv(),R=[],I=[];let P,O;const U=new Promise((L,q)=>{P=L,O=q}),M={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0};(async()=>{let L="",q=0,B=0,H=0,G=0,X=0,ce=0,Q=!1,Ae;const Ee=mv(kd("googleAiStudio",t));try{const le=XO({providerLabel:"GoogleAIStudio",maxSteps:g,toolFailureBreaker:{maxRetries:Rh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:E,abortSignal:C,onProgress:()=>_.noteProgress()},...d?{declarations:d}:{},buildRequest:J=>({model:t,contents:J,config:f}),sendStep:async(J,V)=>{_.noteProgress();const se=J;return a.models.generateContentStream({...se,config:{...se.config??{},abortSignal:V}})},noteUsage:(J,V)=>{Ee.noteUsage(J,V)},planReclaim:(J,V)=>{if(V!==0&&!Ee.shouldStop())return;const se=[...J];if(RCt(se,t,Ee.projectedNextPromptTokens))return Ee.resetAfterReclaim(),{conversation:se}}}),ae={...le,buildStepRequest:(J,V)=>(ce=V+1,_.noteProgress(),le.buildStepRequest(J,V)),buildToolResultMessages:(J,V,se,oe)=>{X=oe+1;for(const ie of V.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":ie.name,"tool.step":X});L=V.text||L;for(const ie of V.toolCalls)R.push({toolName:ie.name,args:ie.args});for(const ie of se)I.push({name:ie.name,input:ie.args,output:ie.output});if(se.length>0){const ie=WO(V.raw.rawResponseParts);Ct(this.handleToolExecutionStorage(V.toolCalls.map((W,re)=>({toolName:W.name,args:W.args,...re===0&&ie?{thoughtSignature:ie}:{},stepIndex:X})),se.map(W=>({toolName:W.name,output:W.output,stepIndex:X})),e,new Date),Ph,"tool storage write timed out").catch(W=>{p.warn("[GoogleAIStudio] Failed to store native tool executions",{error:W instanceof Error?W.message:String(W)})})}const Z=le.buildToolResultMessages(J,V,se,oe);if(_.shouldNudgeWrapup()){const ie=Z[Z.length-1];ie&&Array.isArray(ie.parts)&&ie.parts.push({text:lv(!1)})}try{const ie=Z[Z.length-1];Ee.noteAppendedChars(JSON.stringify(ie?.parts??[]).length)}catch{}return Z}},Pe=VO(d,e.tools,{toolTimeoutMs:E,abortSignal:C,onProgress:()=>_.noteProgress()}),{stream:ke,resultPromise:Te}=Ld(ae,c,{tools:Pe,abortSignal:C,toolTimeoutMs:E}),he=(async()=>{for await(const J of ke)_.noteProgress(),k.push(J)})();let Oe,De;try{Oe=await Te}catch(J){De=J}if(await Ff(he,"GoogleAIStudio"),De!==void 0)if(_.expired||e.abortSignal?.aborted)Q=!0;else throw p.error("[GoogleAIStudio] Native SDK error",De),this.handleProviderError(De);Oe&&(q+=Oe.usage.inputTokens,B+=Oe.usage.outputTokens,H+=Oe.usage.cacheReadTokens??0,G+=Oe.usage.reasoningTokens??0,Ae=Oe.rawStopReason??Ae,Oe.aborted&&(Q=!0)),C.aborted&&(Q=!0);const Ye=Oe!==void 0&&(Oe.toolCalls.length===0||Oe.finishReason!=="tool-calls"),gt=!Q&&X>=g&&!Ye;if(gt){const J=sCt("[GoogleAIStudio]",X,g,"",L);J&&k.push({content:J})}else Q&&!Ye&&(p.warn(`[GoogleAIStudio] Tool call loop ended mid-turn (${A()?"turn time limit":_.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),k.push({content:rY({timedOut:A(),stalled:_.stalled,elapsedMs:_.elapsedMs(),wasAborted:Q,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:g,toolCallCount:R.length})}));const $e=Date.now()-n,Ie=uv({timedOut:A(),stalled:_.stalled,wasAborted:Q,cappedWithoutAnswer:gt,finishReason:dC(Ae)});Ie!=="completed"&&this.emitTurnEvent({phase:Ie,step:ce,maxSteps:g,toolCallCount:R.length,elapsedMs:_.elapsedMs()}),M.responseTime=$e,M.totalToolExecutions=R.length,M.stopReason=Ie,M.stepsUsed=ce,Ae!==void 0&&(M.rawFinishReason=Ae),r.setAttribute(_e.GEN_AI_INPUT_TOKENS,q),r.setAttribute(_e.GEN_AI_OUTPUT_TOKENS,B),r.setAttribute(_e.GEN_AI_FINISH_REASON,gt?"max_steps":"stop");const ve=Math.max(0,q-H);P({provider:this.providerName,model:t,tokenUsage:{input:ve,output:B+G,total:ve+H+B+G,...H>0?{cacheReadTokens:H}:{},...G>0?{reasoning:G}:{}},requestDuration:$e,timestamp:new Date().toISOString(),stepsUsed:ce,toolCallCount:R.length,stopReason:Ie,elapsedMs:_.elapsedMs(),...Ae!==void 0?{rawFinishReason:Ae}:{}}),k.close()}catch(le){k.error(le),O(le)}finally{_.dispose(),y?.removeEventListener("abort",w),s?.cleanup()}})().catch(()=>{});const N={stream:k.iterable,provider:this.providerName,model:t,toolCalls:R,analytics:U,metadata:M};return Object.defineProperty(N,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>R.map(L=>L.toolName)}),Object.defineProperty(N,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>bd(I)}),N}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return wb({name:"neurolink.provider.generate",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:"google-ai",[_e.GEN_AI_MODEL]:t,[_e.GEN_AI_OPERATION]:"generate",[_e.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),s=da(o,this.providerName,"generate");let i=()=>{};try{const a=this.getApiKey(),c=await vv(a,this.getBaseURL());p.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||"",u=[];KO(u,e.conversationMessages);const d=await cCt(e.input,l,"[GoogleAIStudio:generate]",t);u.push({role:"user",parts:d});let m,h;const f=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=aY(this.providerName,t,f,Object.keys(e.tools||{}).length);if(g&&y&&p.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),f&&!(g&&y)){const ve=e.tools||{};if(Object.keys(ve).length>0){const J=gv(ve,"functionDeclarations");h=J,m=J.toolsConfig,p.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:m[0].functionDeclarations.length,toolNames:m[0].functionDeclarations.map(V=>V.name)})}}const v=!m&&g,w=v&&e.schema?aCt(e.schema):void 0,E=nCt({...e,model:t,wantsJsonOutput:v,responseSchema:w},m),_=L1(e.abortSignal,s?.controller.signal),C=new AbortController,A=()=>C.abort();_?.addEventListener("abort",A),_?.aborted&&C.abort();const k=Ih(e.toolTimeoutMs),R=dv({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:ve=>{p.warn(ve==="timeout"?`[GoogleAIStudio] Native Gemini generate turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini generate turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),C.abort()}}),I=C.signal;i=()=>{R.dispose(),_?.removeEventListener("abort",A)};const P=()=>R.timedOut||s?.controller.signal.aborted===!0,O=oCt(e.maxSteps);let U="",M="",F=0,N=0,L=0,q=0;const B=[],H=[];let G=0,X=0,ce=!1,Q;const Ae=mv(kd("googleAiStudio",t)),Ee=XO({providerLabel:"GoogleAIStudio",maxSteps:O,toolFailureBreaker:{maxRetries:Rh},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:k,abortSignal:I,onProgress:()=>R.noteProgress()},...h?{declarations:h}:{},buildRequest:ve=>({model:t,contents:ve,config:E}),sendStep:async(ve,J)=>{R.noteProgress();const V=ve;return c.models.generateContentStream({...V,config:{...V.config??{},abortSignal:J}})},noteUsage:(ve,J)=>{Ae.noteUsage(ve,J)},planReclaim:(ve,J)=>{if(J!==0&&!Ae.shouldStop())return;const V=[...ve];if(RCt(V,t,Ae.projectedNextPromptTokens))return Ae.resetAfterReclaim(),{conversation:V}}}),le={...Ee,buildStepRequest:(ve,J)=>(X=J+1,R.noteProgress(),Ee.buildStepRequest(ve,J)),buildToolResultMessages:(ve,J,V,se)=>{G=se+1;for(const Z of J.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":Z.name,"tool.step":G}),B.push({toolName:Z.name,args:Z.args});M=J.text||M;for(const Z of V)H.push({name:Z.name,input:Z.args,output:Z.output});if(V.length>0){const Z=WO(J.raw.rawResponseParts);Ct(this.handleToolExecutionStorage(J.toolCalls.map((ie,W)=>({toolName:ie.name,args:ie.args,...W===0&&Z?{thoughtSignature:Z}:{},stepIndex:G})),V.map(ie=>({toolName:ie.name,output:ie.output,stepIndex:G})),e,new Date),Ph,"tool storage write timed out").catch(ie=>{p.warn("[GoogleAIStudio] Failed to store native tool executions",{error:ie instanceof Error?ie.message:String(ie)})})}const oe=Ee.buildToolResultMessages(ve,J,V,se);if(R.shouldNudgeWrapup()){const Z=oe[oe.length-1];Z&&Array.isArray(Z.parts)&&Z.parts.push({text:lv(!1)})}try{const Z=oe[oe.length-1];Ae.noteAppendedChars(JSON.stringify(Z?.parts??[]).length)}catch{}return oe}},ae=VO(h,e.tools,{toolTimeoutMs:k,abortSignal:I,onProgress:()=>R.noteProgress()}),{stream:Pe,resultPromise:ke}=Ld(le,u,{tools:ae,abortSignal:I,toolTimeoutMs:k}),Te=(async()=>{for await(const ve of Pe)R.noteProgress()})();let he,Oe;try{he=await ke}catch(ve){Oe=ve}if(await Ff(Te,"GoogleAIStudio"),Oe!==void 0)if(R.expired||e.abortSignal?.aborted)ce=!0;else throw p.error("[GoogleAIStudio] Native SDK generate error",Oe),this.handleProviderError(Oe);he&&(F+=he.usage.inputTokens,N+=he.usage.outputTokens,L+=he.usage.cacheReadTokens??0,q+=he.usage.reasoningTokens??0,Q=he.rawStopReason??Q,U=he.text,he.aborted&&(ce=!0)),I.aborted&&(ce=!0);const De=!ce&&G>=O&&!U;ce&&!U?(p.warn(`[GoogleAIStudio] Generate tool call loop ended mid-turn (${P()?"turn time limit":R.stalled?"stall watchdog":"caller abort"}); returning gathered text or an honest terminal message.`),U=M||rY({timedOut:P(),stalled:R.stalled,elapsedMs:R.elapsedMs(),wasAborted:ce,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:O,toolCallCount:B.length})):U=sCt("[GoogleAIStudio]",G,O,U,M);const Ye=Date.now()-n,gt=uv({timedOut:P(),stalled:R.stalled,wasAborted:ce,cappedWithoutAnswer:De,finishReason:dC(Q)});gt!=="completed"&&this.emitTurnEvent({phase:gt,step:X,maxSteps:O,toolCallCount:B.length,elapsedMs:R.elapsedMs()}),r.setAttribute(_e.GEN_AI_INPUT_TOKENS,F),r.setAttribute(_e.GEN_AI_OUTPUT_TOKENS,N),r.setAttribute(_e.GEN_AI_FINISH_REASON,G>=O?"max_steps":"stop");const $e=Math.max(0,F-L),Ie={content:U,provider:this.providerName,model:t,stopReason:gt,stepsUsed:X,...Q!==void 0?{rawFinishReason:Q}:{},usage:{input:$e,output:N+q,total:$e+L+N+q,...L>0?{cacheReadTokens:L}:{},...q>0?{reasoning:q}:{}},...q>0&&{reasoningTokens:q},responseTime:Ye,toolsUsed:B.map(ve=>ve.toolName),toolExecutions:af(e,H),enhancedWithTools:B.length>0};return this.enhanceResult(Ie,e,n)}finally{i(),s?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(MS.some(d=>r.toLowerCase().startsWith(d.toLowerCase())))return p.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return p.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};const i=t.output?.format==="json"||t.schema,a=aY(this.providerName,r,!s.disableTools,Object.keys(s.tools??{}).length);i&&a&&(p.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&&p.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length});const l=Date.now(),u=s.input?.text||s.prompt||"";try{let d=await dt({name:"neurolink.executeGeneration",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:this.providerName,[_e.GEN_AI_MODEL]:r,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(s));return d=await this.synthesizeAIResponseIfNeeded(d,t),this.emitPipelineBGenerationEvent(r,d,l,!0,void 0,u),d}catch(d){throw this.emitPipelineBGenerationEvent(r,null,l,!1,d,u),d}}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),!n&&o&&typeof o=="object"&&(o._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 vv(r,this.getBaseURL())}catch{throw new Mr("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 c=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)}},l=await n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async d=>{try{const m=d?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(m?.data){const f={data:Buffer.from(String(m.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};c({type:"audio",audio:f})}d?.serverContent?.interrupted}catch(m){c({type:"error",error:m})}},onerror:d=>{c({type:"error",error:d})},onclose:d=>{c({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}});return(async()=>{try{const d=e.input?.audio;if(!d){p.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{l.sendInput?await l.sendInput({event:"flush"}):l.sendRealtimeInput&&await l.sendRealtimeInput({event:"flush"})}catch(g){p.debug("[GeminiLive] flush control failed (non-fatal)",{error:g instanceof Error?g.message:String(g)})}continue}const h=m.toString("base64"),f=`audio/pcm;rate=${d.sampleRateHz||16e3}`;await l.sendRealtimeInput?.({media:{data:h,mimeType:f}})}try{l.sendInput?await l.sendInput({event:"flush"}):l.sendRealtimeInput&&await l.sendRealtimeInput({event:"flush"})}catch(m){p.debug("[GeminiLive] final flush failed (non-fatal)",{error:m instanceof Error?m.message:String(m)})}}catch(d){c({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){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const o=this.getApiKey(),a=(await(await vv(o,this.getBaseURL())).models.embedContent({model:n,contents:[r]})).embeddings?.[0]?.values;if(!a)throw new ot("No embedding returned from Google AI",this.providerName);return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.length}),a}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";p.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=this.getApiKey(),i=((await(await vv(n,this.getBaseURL())).models.embedContent({model:r,contents:e})).embeddings||[]).map(a=>a.values||[]);return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:i.length,embeddingDimension:i[0]?.length}),i}catch(n){throw p.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 Mr("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}}}}),MCt={};ee(MCt,{GoogleAIStudioProvider:()=>PCt});var RUr=b({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";IUr()}});async function ku(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=l=>new Error(`${r} download exceeded size cap after fetch: ${l} bytes (max ${t})`),s=e.body;if(!s||typeof s.getReader!="function"){const l=Buffer.from(await e.arrayBuffer());if(l.length>t)throw o(l.length);return l}const i=s.getReader(),a=[];let c=0;for(;;){const{done:l,value:u}=await i.read();if(l)break;if(c+=u.byteLength,c>t)throw await i.cancel().catch(()=>{}),o(c);a.push(u)}return Buffer.concat(a,c)}var Bf,zf,hp,_a=b({"src/lib/utils/sizeGuard.ts"(){"use strict";Bf=256*1024*1024,zf=50*1024*1024,hp=25*1024*1024}}),PUr,MUr,OUr,DUr,tD,OCt,gY,yY,NUr,LUr,FUr,$Ur,UUr=b({"node-stub:node:dns/promises"(){PUr=globalThis.crypto,MUr=globalThis.ReadableStream||class{},OUr=globalThis.URL,DUr=globalThis.URLSearchParams,tD=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},tD.custom=Symbol.for("nodejs.util.inspect.custom"),tD.colors={},tD.styles={},OCt=globalThis.TextDecoder,gY=globalThis.TextEncoder,yY=(e,t)=>t?.(null,"127.0.0.1",4),NUr=globalThis.performance||{now:()=>Date.now()},LUr=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 gY().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 gY().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 OCt().decode(this)}},FUr=globalThis.clearTimeout,$Ur=globalThis.clearInterval}}),BUr,zUr,qUr,GUr,rD,DCt,vY,jUr,HUr,NCt,VUr,WUr,KUr=b({"node-stub:node:net"(){BUr=globalThis.crypto,zUr=globalThis.ReadableStream||class{},qUr=globalThis.URL,GUr=globalThis.URLSearchParams,rD=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},rD.custom=Symbol.for("nodejs.util.inspect.custom"),rD.colors={},rD.styles={},DCt=globalThis.TextDecoder,vY=globalThis.TextEncoder,jUr=globalThis.performance||{now:()=>Date.now()},HUr=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 vY().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 vY().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 DCt().decode(this)}},NCt=()=>0,VUr=globalThis.clearTimeout,WUr=globalThis.clearInterval}});function JUr(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 nD(e){if(e.length===0)return null;const t=e.split(".");if(t.length===4){const r=t.map(JUr);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 LCt(e){if(NCt(e)!==6)return null;const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);let r;if(t){const n=nD(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 FCt(e){const t=e.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(t)return nD(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 $Ct(e){const[t,r,n,o]=e.split(".").map(s=>parseInt(s,10));return(t<<24|r<<16|n<<8|o)>>>0}function mC(e){const t=$Ct(e);for(const[r,n]of GCt){const o=$Ct(r),s=n===0?0:4294967295<<32-n>>>0;if((t&s)===(o&s))return!0}return!1}function UCt(e){return jCt.some(t=>t.length===39?e===t:e.startsWith(t))}function BCt(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function zCt(e){const t=nD(e);if(t)return mC(t)?`IPv4 ${e} \u2192 ${t} is in a blocked range`:null;if(e.includes(":")){const r=FCt(e);if(r)return mC(r)?`IPv4-mapped IPv6 ${e} \u2192 ${r} is in a blocked range`:null;const n=LCt(e);return n?UCt(n)?`IPv6 ${e} is in a blocked range`:null:`IPv6 ${e} could not be parsed`}return"not-an-ip"}async function fp(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=BCt(t.hostname).toLowerCase(),n=zCt(r);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${e}" rejected: ${n}`);await qCt(e,r)}}async function qCt(e,t){const[r,n]=await Promise.allSettled([yY(t,{family:4,all:!0}),yY(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",c=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: ${c})`)}for(const a of o)if(mC(a))throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv4 in blocked range)`);for(const a of s){const c=zCt(a.toLowerCase());if(c&&c!=="not-an-ip")throw new Error(`URL "${e}" rejected: hostname ${t} resolves to ${a} (IPv6 ${c})`)}return{v4:o,v6:s}}async function YUr(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=BCt(t.hostname).toLowerCase(),n=nD(r);if(n){if(mC(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 c=FCt(r);if(c){if(mC(c))throw new Error(`URL "${e}" rejected: IPv4-mapped IPv6 ${r} \u2192 ${c} is in a blocked range`);return{url:e,ip:c,family:4,addresses:[{ip:c,family:4}]}}const l=LCt(r);if(!l)throw new Error(`URL "${e}" rejected: IPv6 ${r} could not be parsed`);if(UCt(l))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 qCt(e,r),i=[...o.map(c=>({ip:c,family:4})),...s.map(c=>({ip:c,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 GCt,jCt,gp=b({"src/lib/utils/ssrfGuard.ts"(){"use strict";UUr(),KUr(),GCt=[["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]],jCt=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]}});function TY(e){}function wY(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=TY,onError:r=TY,onRetry:n=TY,onComment:o}=e,s=[];let i=!0,a,c="",l=0,u;function d(v){if(i&&(i=!1,v.charCodeAt(0)===239&&v.charCodeAt(1)===187&&v.charCodeAt(2)===191&&(v=v.slice(3))),s.length===0){const _=m(v);_!==""&&s.push(_);return}if(v.indexOf(`
|
|
1035
1035
|
`)===-1&&v.indexOf("\r")===-1){s.push(v);return}s.push(v);const w=s.join("");s.length=0;const E=m(w);E!==""&&s.push(E)}function m(v){let w=0;if(v.indexOf("\r")===-1){let E=v.indexOf(`
|
|
1036
1036
|
`,w);for(;E!==-1;){if(w===E){l>0&&t({id:a,event:u,data:c}),a=void 0,c="",l=0,u=void 0,w=E+1,E=v.indexOf(`
|
|
1037
1037
|
`,w);continue}const _=v.charCodeAt(w);if(HCt(v,w,_)){const C=v.charCodeAt(w+5)===yp?w+6:w+5,A=v.slice(C,E);if(l===0&&v.charCodeAt(E+1)===SY){t({id:a,event:u,data:A}),a=void 0,c="",u=void 0,w=E+2,E=v.indexOf(`
|
|
@@ -1049,9 +1049,9 @@ ${r}`:r;return e.map((i,a)=>a===n?{...i,content:s}:i)}}}),Gf,o5r=b({"node_module
|
|
|
1049
1049
|
`||e==="\r"||e===" "||e==="\b"||e==="\f"}function Hf(e,t){const r=e.charCodeAt(t);return r===rX||r===LAt||r===nX||r===oX}function c5r(e,t){const r=e.charCodeAt(t);return r===rX||r===nX||r===oX}function l5r(e,t){const r=e.charCodeAt(t);return r===FAt||r===$At||r>=UAt&&r<=BAt||r===zAt||r===qAt||r===GAt||r===jAt}function lD(e){return OAt(e)||tX(e)}function OAt(e){return e==='"'||e==="\u201C"||e==="\u201D"}function DAt(e){return e==='"'}function tX(e){return e==="'"||e==="\u2018"||e==="\u2019"||e==="`"||e==="\xB4"}function NAt(e){return e==="'"}function vC(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=e.lastIndexOf(t);return n!==-1?e.substring(0,n)+(r?"":e.substring(n+1)):e}function Al(e,t){let r=e.length;if(!Hf(e,r-1))return e+t;for(;Hf(e,r-1);)r--;return e.substring(0,r)+t+e.substring(r)}function u5r(e,t,r){return e.substring(0,t)+e.substring(t+r)}function d5r(e){return/[,\n][ \t\r]*$/.test(e)}var rX,LAt,nX,oX,FAt,$At,UAt,BAt,zAt,qAt,GAt,jAt,sX,iX,HAt,m5r=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/utils/stringUtils.js"(){rX=32,LAt=10,nX=9,oX=13,FAt=160,$At=6158,UAt=8192,BAt=8203,zAt=8239,qAt=8287,GAt=12288,jAt=65279,sX=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,iX=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/,HAt=/^[[{\w-]$/}});function p5r(e){let t=0,r="";l(["```","[```","{```"]),s()||F(),l(["```","```]","```}"]);const o=d(",");for(o&&i(),MAt(e[t])&&d5r(r)?(o||(r=Al(r,",")),v()):o&&(r=vC(r,","));e[t]==="}"||e[t]==="]";)t++,i();if(t>=e.length)return r;M();function s(){i();const B=g()||y()||w()||_()||C()||k(!1)||R();return i(),B}function i(){let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;const H=t;let G=a(B);do G=c(),G&&(G=a(B));while(G);return t>H}function a(B){const H=B?Hf:c5r;let G="";for(;;)if(H(e,t))G+=e[t],t++;else if(l5r(e,t))G+=" ",t++;else break;return G.length>0?(r+=G,!0):!1}function c(){if(e[t]==="/"&&e[t+1]==="*"){for(;t<e.length&&!h5r(e,t);)t++;return t+=2,!0}if(e[t]==="/"&&e[t+1]==="/"){for(;t<e.length&&e[t]!==`
|
|
1050
1050
|
`;)t++;return!0}return!1}function l(B){if(u(B)){if(IAt(e[t]))for(;t<e.length&&RAt(e[t]);)t++;return i(),!0}return!1}function u(B){a(!0);for(const H of B){const G=t+H.length;if(e.slice(t,G)===H)return t=G,!0}return!1}function d(B){return e[t]===B?(r+=e[t],t++,!0):!1}function m(B){return e[t]===B?(t++,!0):!1}function h(){return m("\\")}function f(){return i(),e[t]==="."&&e[t+1]==="."&&e[t+2]==="."?(t+=3,i(),m(","),!0):!1}function g(){if(e[t]==="{"){r+="{",t++,i(),m(",")&&i();let B=!0;for(;t<e.length&&e[t]!=="}";){let H;if(B?(H=!0,B=!1):(H=d(","),H||(r=Al(r,",")),i()),f(),!(w()||k(!0))){e[t]==="}"||e[t]==="{"||e[t]==="]"||e[t]==="["||e[t]===void 0?r=vC(r,","):N();break}i();const X=d(":"),ce=t>=e.length;X||(MAt(e[t])||ce?r=Al(r,":"):L()),s()||(X||ce?r+="null":L())}return e[t]==="}"?(r+="}",t++):r=Al(r,"}"),!0}return!1}function y(){if(e[t]==="["){r+="[",t++,i(),m(",")&&i();let B=!0;for(;t<e.length&&e[t]!=="]";)if(B?B=!1:d(",")||(r=Al(r,",")),f(),!s()){r=vC(r,",");break}return e[t]==="]"?(r+="]",t++):r=Al(r,"]"),!0}return!1}function v(){let B=!0,H=!0;for(;H;)B?B=!1:d(",")||(r=Al(r,",")),H=s();H||(r=vC(r,",")),r=`[
|
|
1051
1051
|
${r}
|
|
1052
|
-
]`}function w(){let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,H=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,G=e[t]==="\\";if(G&&(t++,G=!0),lD(e[t])){const X=DAt(e[t])?DAt:NAt(e[t])?NAt:tX(e[t])?tX:OAt,ce=t,Q=r.length;let
|
|
1053
|
-
`?(
|
|
1054
|
-
`,r:"\r",t:" "}}}),g5r=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/index.js"(){f5r()}});function KAt(e,t=0){for(let r=t;r<e.length;r++){const n=e[r];if(n!=="{"&&n!=="[")continue;const o=n==="{"?"}":"]";let s=0,i=!1,a=!1;for(let c=r;c<e.length;c++){const l=e[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){i=!i;continue}if(!i){if(l===n)s++;else if(l===o&&(s--,s===0))return{span:e.substring(r,c+1),end:c+1}}}}return null}var y5r=b({"src/lib/utils/json/extract.ts"(){"use strict"}});function JAt(e){return typeof e.safeParse=="function"}function uD(e,t){return!e||!JAt(e)?!0:e.safeParse(t).success}function YAt(e,t){try{const r=JSON.parse(e);return r===""?{kind:"empty"}:r==null?{kind:"nullish"}:uD(t,r)?{kind:"accepted",value:r}:{kind:"rejected",value:r}}catch{return{kind:"not-json"}}}function XAt(e){try{return{value:JSON.parse(e),repaired:!1}}catch{}try{const t=p5r(e),r=JSON.parse(t);return t!==e&&p.shouldLog("debug")&&p.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:e.length,repairedLength:t.length}),{value:r,repaired:t!==e}}catch{return}}function v5r(e){let t=e;for(let r=0;r<QAt&&t.length>1;r++){const n=Math.max(t.lastIndexOf(","),t.lastIndexOf("}"),t.lastIndexOf("]"));if(n<=0)break;t=t.slice(0,n);const o=XAt(t);if(o!==void 0&&o.value!==null&&typeof o.value=="object")return o.value}}function aX(e,t=0){if(t>ZAt)return{value:e,changed:!1};if(typeof e=="string"){const r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const o=JSON.parse(r);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:e,changed:!1}}if(Array.isArray(e)){let r=!1;const n=e.map(o=>{const s=aX(o,t+1);return s.changed&&(r=!0),s.value});return{value:r?n:e,changed:r}}if(e!==null&&typeof e=="object"){let r=!1;const n={};for(const[o,s]of Object.entries(e)){const i=aX(s,t+1);i.changed&&(r=!0),n[o]=i.value}return{value:r?n:e,changed:r}}return{value:e,changed:!1}}function cX(e,t){if(typeof e!="string"||e.trim().length===0)return null;const r=[],n=[e.indexOf("{"),e.indexOf("[")].filter(v=>v>=0),o=n.length>0?Math.min(...n):-1;let s=!1,i=0;for(;;){const v=KAt(e,i);if(!v)break;const w=v.end-v.span.length;w===o&&(s=!0),r.push({text:v.span,truncated:!1,rootAligned:w===o}),i=v.end}const a=o>=0&&!s,c=Math.max(e.lastIndexOf("}"),e.lastIndexOf("]"));o>=0&&c>o&&r.push({text:e.slice(o,c+1),truncated:a,rootAligned:!0}),o>=0&&r.push({text:e.slice(o),truncated:!0,rootAligned:!0});const l=e.trim();if(l.length>1&&l.startsWith('"')&&l.endsWith('"'))try{const v=JSON.parse(l);if(typeof v=="string"){let w=0;for(;;){const E=KAt(v,w);if(!E)break;r.push({text:E.span,truncated:!1,rootAligned:!1}),w=E.end}}}catch{}const u=[...r.filter(v=>v.rootAligned),...r.filter(v=>!v.rootAligned)];let d;const m=[],h=!!(t&&JAt(t)),f=new Set;for(const v of u){if(f.has(v.text))continue;f.add(v.text);const w=XAt(v.text);if(w===void 0||w.value===null||typeof w.value!="object")continue;const E={value:w.value,repaired:w.repaired,truncated:v.truncated,rootAligned:v.rootAligned};if(d===void 0&&(d=E),!h)break;const _=t;if(_.safeParse(w.value).success)m.push(E);else{const C=aX(w.value);C.changed&&C.value!==null&&typeof C.value=="object"&&_.safeParse(C.value).success?m.push({value:C.value,repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned}):Array.isArray(w.value)&&w.value.length===1&&w.value[0]!==null&&typeof w.value[0]=="object"&&!Array.isArray(w.value[0])&&_.safeParse(w.value[0]).success&&m.push({value:w.value[0],repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned})}}const g=m.length>0?m.reduce((v,w)=>JSON.stringify(w.value).length>JSON.stringify(v.value).length?w:v):void 0;let y=g??d;if(a&&g===void 0&&(y===void 0||!y.rootAligned)){const v=v5r(e.slice(o));v!==void 0?(p.debug("[coerceJsonToSchema] salvaged a partial truncated object",{textLength:e.length}),y={value:v,repaired:!0,truncated:!0,rootAligned:!0}):y!==void 0&&(y={...y,truncated:!0})}return y===void 0?null:{content:JSON.stringify(y.value),structuredData:y.value,repaired:y.repaired,truncated:y.truncated}}var ZAt,QAt,ekt=b({"src/lib/utils/json/coerce.ts"(){"use strict";g5r(),z(),y5r(),ZAt=6,QAt=8}});function dD(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}function T5r(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(t.type==="tool")return t.toolName?{type:"tool",toolName:t.toolName}:void 0;if(t.type)return t.type}}var tkt=b({"src/lib/utils/toolChoice.ts"(){"use strict"}});async function*w5r(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const s=o.value;if(s.type==="text-delta")yield{content:s.delta};else if(s.type==="reasoning-delta")yield{content:"",reasoning:s.delta};else if(s.type==="finish")t(s);else if(s.type==="error")throw s.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}var mD,lX,TC,uX,rkt,Lc,kl=b({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";Xt(),bl(),r5r(),Ko(),TAt(),wAt(),EAt(),ec(),Lo(),bAt(),On(),z(),Ut(),$m(),DK(),pa(),CAt(),tf(),eX(),Zm(),ui(),ekt(),tkt(),Ic(),cd(),cY(),i_(),vp(),fv(),mD=512,lX=class extends Error{},TC=(e,t)=>{const r=cX(e,t);return r!==null&&uD(t,r.structuredData)},uX=(e,t)=>{const r=cX(e,t);if(r!==null&&uD(t,r.structuredData))return r.structuredData;const n=YAt(e,t);return n.kind==="accepted"?n.value:void 0},rkt=(e,t,r)=>{const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const s=await n.next();s.done?(o.enqueue(await t),o.close()):s.value.reasoning?o.enqueue({type:"reasoning-delta",delta:s.value.reasoning}):o.enqueue({type:"text-delta",delta:s.value.content})}catch(s){o.error(s)}},async cancel(){r(),await n.return?.()}})},Lc=class extends ba{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getModelFallbacks(){return this.getFallbackModels()}refreshHandlersForModel(e){this.resolvedModel=e,super.refreshHandlersForModel(e)}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}replayReasoningContent(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=J9(this.providerName,e);let s=t;o!==void 0&&(s===void 0||s>o)&&(s!==void 0&&p.debug(`${this.providerName}: clamping max_tokens ${s} to the advertised ${e} output ceiling ${o}`),s=o);const i=K9(this.providerName,e);if(i!==void 0){const a=MY(r,n,this.providerName),c=i-a-mD;if(c<=0)throw new Aa(`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-mD),stagesUsed:[],breakdown:{}});s!==void 0&&s>c&&(p.warn(`${this.providerName}: max_tokens ${s} cannot fit the ${e} window (${i}) with ~${a} input tokens \u2014 re-fitting to ${c}`),s=c)}return s}correctBodyAfterContextOverflow(e,t){if(!KY(t))return;const r=JY(t)??JY(t.responseBody);if(!r||r.budgetTokens<=0)return;W9(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-mD;if(!(o<=0||o>=n))return p.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`${Ca(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=`${Ca(this.config.baseURL)}/models`,n=await Pt()(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 p.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:No(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]),p.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){p.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=Pt(),n=this.getAuthHeaders.bind(this),o=this.providerName,s=this.adjustBuildBodyOptions.bind(this),i=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),c=this.adjustBodyAfter400.bind(this),l=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),m=this.useStreamingWireForGenerate.bind(this),h=this.replayReasoningContent.bind(this),f=g=>this.getTimeout(g??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async g=>{const y=sD((g.tools??[]).filter(G=>G.type==="function").map(G=>G.name)),v=NY(g.prompt,y?.toWire,h()),w=Array.isArray(g.tools)&&g.tools.length>0,E=g.responseFormat&&!(w&&d())?i(UY(g.responseFormat),e):void 0,_=cAt(g.tools,y?.toWire),C=u(e,g.maxOutputTokens,v,_),A=m(),k=BY(a(zY({modelId:e,messages:v,options:s(e,{maxTokens:C,temperature:g.temperature,topP:g.topP,presencePenalty:g.presencePenalty,frequencyPenalty:g.frequencyPenalty,seed:g.seed,stopSequences:g.stopSequences}),tools:_,...g.toolChoice?{toolChoice:lAt(g.toolChoice,y?.toWire)}:{},streaming:A,...E?{responseFormat:E}:{}}),e)),R=g.providerOptions?.neurolink?.timeoutMs,I=da(typeof R=="number"?R:f(g),o,"generate"),{signal:P,dispose:O}=F1(g.abortSignal,I?.controller.signal);let U,M=A;try{let G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(k),...P?{signal:P}:{}});if(!G.ok){const X=await fC(t,k,G),ce=X;let Q=G.status===400?(()=>{const Ie=l(k,ce);return c(Ie??k,ce)??Ie})():void 0;if(!Q&&A&&G.status===400&&/stream/i.test(ce.responseBody??"")){const{stream:Ie,stream_options:Ee,...le}=k;Q=le,M=!1}if(!Q)throw X;if(G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(Q),...P?{signal:P}:{}}),!G.ok)throw await fC(t,Q,G)}if(M){if(!G.body)throw new Error(`${o}: streaming generate response had no body`);const X=I?G.body.pipeThrough(new TransformStream({transform(Q,Ie){I.reset(),Ie.enqueue(Q)}})):G.body,ce=await qY(X,()=>{});U={...ce.id?{id:ce.id}:{},...ce.model?{model:ce.model}:{},choices:[{index:0,message:{role:"assistant",content:ce.text.length>0?ce.text:null,...ce.reasoning?{reasoning:ce.reasoning}:{},...ce.toolCalls.size>0?{tool_calls:[...ce.toolCalls.values()].map(Q=>({id:Q.id,type:"function",function:{name:Q.name,arguments:Q.argsBuffered}}))}:{}},finish_reason:ce.finishReason??"stop"}],...ce.usage?{usage:ce.usage}:{}}}else U=await G.json()}finally{I?.cleanup(),O()}const F=U.choices?.[0],N=(typeof F?.message?.content=="string"?F.message.content:"")??"",L=[],q=F?.message?.reasoning_content||F?.message?.reasoning;typeof q=="string"&&q.length>0&&L.push({type:"reasoning",text:q}),N.length>0&&L.push({type:"text",text:N});for(const G of F?.message?.tool_calls??[])L.push({type:"tool-call",toolCallId:G.id,toolName:y?.fromWire.get(G.function.name)??G.function.name,input:G.function.arguments??""});const B=F?.finish_reason;return{content:L,finishReason:{unified:B==="length"?"length":B==="tool_calls"||B==="function_call"?"tool-calls":B==="content_filter"?"content-filter":"stop",raw:B??"stop"},usage:{inputTokens:{total:U.usage?.prompt_tokens,noCache:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,U.usage.prompt_tokens-U.usage.prompt_tokens_details.cached_tokens):U.usage?.prompt_tokens,cacheRead:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(U.usage.prompt_tokens_details.cached_tokens,U.usage.prompt_tokens):U.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:U.usage?.completion_tokens,text:U.usage?.completion_tokens!==void 0&&U.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,U.usage.completion_tokens-U.usage.completion_tokens_details.reasoning_tokens):U.usage?.completion_tokens,reasoning:U.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:k},response:{...U.id?{id:U.id}:{},...U.model?{modelId:U.model}:{},headers:{},body:U}}},doStream:()=>{throw new Error(`${o}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(Ed(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),s=>this.executeNativeGenerate(s)),o)}async executeNativeGenerate(e){const t=Date.now(),r=await this.resolveModelName(),n=await this.getAISDKModelWithMiddleware(e);if(!yC(n))throw this.handleProviderError(new Error(`${this.providerName}: model handle exposes no doGenerate()`));const o=n.doGenerate.bind(n),s=!e.disableTools&&this.supportsTools(),i=s?e.tools||await this.getAllTools():{},a=s?Object.entries(i).map(([R,I])=>{const P=I;return{type:"function",name:R,description:P.description??"",inputSchema:P.inputSchema?Ao(P.inputSchema):{type:"object",properties:{}}}}):void 0,c=!!a&&a.length>0,l=e.schema?Ao(e.schema):void 0,u=l!==void 0&&c&&this.suppressResponseFormatWithTools(),d=l&&!u?{type:"json",schema:l}:void 0,m=await this.buildMessagesForStream(e),h=[],f=(R,I,P=!0)=>aD({doGenerate:o,...yAt({provider:this.providerName,availableInputTokens:Pc(this.providerName,r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Gt(H_({...P&&a?{tools:a}:{},responseFormat:I}),this.providerName)}),conversation:R,...P&&a?{tools:a}:{},toolsRecord:i,...P&&c&&e.toolChoice?{toolChoice:dD(e,i,!0)}:{},...typeof e.timeout=="number"?{providerOptions:{neurolink:{timeoutMs:e.timeout}}}:{},...I?{responseFormat:I}:{},maxSteps:e.maxSteps||Bs,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:O=>r0(O,lt.getActiveSpan()??void 0,`${this.providerName} generate`).catch(U=>{throw this.handleProviderError(U)})},h);let g;try{g=await f(m,d)}catch(R){if(!(d!==void 0&&(lUr(R)||dCt(R)||uUr(R))))throw R;p.warn(`[${this.providerName}] provider rejected response_format \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r}),g=await f(wv(m,d.schema),void 0)}if(d!==void 0&&e.schema!==void 0&&!TC(g.text,e.schema)){p.warn(`[${this.providerName}] response_format did not yield a schema-valid object \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r});const R=g,I=await f(wv(m,d.schema),void 0);g={...I,inputTokens:R.inputTokens+I.inputTokens,outputTokens:R.outputTokens+I.outputTokens,cacheReadTokens:(R.cacheReadTokens??0)+(I.cacheReadTokens??0),cacheWriteTokens:(R.cacheWriteTokens??0)+(I.cacheWriteTokens??0)}}u&&l&&e.schema&&(g=await this.reformatWithoutTools({toolPhase:g,conversation:m,schemaJson:l,schema:e.schema,runLoop:f,modelId:r,abortSignal:e.abortSignal}));const{text:y,finishReason:v,toolsUsed:w}=g,E=g.inputTokens,_=g.outputTokens,C=g.steps,A=C>=(e.maxSteps||Bs)&&v==="tool-calls"?"step-cap":v==="error"?"provider-error":"completed",k={content:y,provider:this.providerName,model:r,finishReason:v,...g.rawFinishReason?{rawFinishReason:g.rawFinishReason}:{},stopReason:A,stepsUsed:C,usage:{input:E,output:_,total:E+_+g.cacheReadTokens+g.cacheWriteTokens,...g.cacheReadTokens?{cacheReadTokens:g.cacheReadTokens}:{},...g.cacheWriteTokens?{cacheCreationTokens:g.cacheWriteTokens}:{}},responseTime:Date.now()-t,...g.reasoning?{reasoning:g.reasoning}:{},toolsUsed:w,toolCalls:E7(h),toolExecutions:af(e,bd(h)),enhancedWithTools:w.length>0};return this.finalizeNativeGenerate(k,e,t)}async reformatWithoutTools(e){const{toolPhase:t,conversation:r,schemaJson:n,schema:o,runLoop:s,modelId:i,abortSignal:a}=e;let c=t;const l=()=>a?.aborted===!0;if(c.text.trim().length>0&&!l()&&!TC(c.text,o)){p.warn(`[${this.providerName}] tools suppressed response_format and the answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:i});const u={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},d=m=>{u.inputTokens+=m.inputTokens,u.outputTokens+=m.outputTokens,u.cacheReadTokens+=m.cacheReadTokens??0,u.cacheWriteTokens+=m.cacheWriteTokens??0};try{const m=[...r,{role:"assistant",content:t.text},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let h,f=!1;try{h=await s(m,{type:"json",schema:n},!1),d(h)}catch(g){if(l())throw g;p.warn(`[${this.providerName}] the re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i,error:g instanceof Error?g.message:String(g)}),h=await s(wv(m,n),void 0,!1),d(h),f=!0}if(!f&&!l()&&!TC(h.text,o)&&(p.warn(`[${this.providerName}] the re-ask's response_format carried no schema \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i}),h=await s(wv(m,n),void 0,!1),d(h)),!TC(h.text,o))throw p.warn(`[${this.providerName}] the tool-free re-ask did not yield a schema-valid object either; keeping the original answer`,{provider:this.providerName,model:i}),new lX;c={...h,toolsUsed:[...new Set([...t.toolsUsed,...h.toolsUsed])],inputTokens:t.inputTokens+u.inputTokens,outputTokens:t.outputTokens+u.outputTokens,cacheReadTokens:(t.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(t.cacheWriteTokens??0)+u.cacheWriteTokens,steps:t.steps,...t.finishReason!=="stop"?{finishReason:t.finishReason,rawFinishReason:t.rawFinishReason}:{finishReason:h.finishReason}}}catch(m){if(l()&&!(a?.reason instanceof ma))throw m;m instanceof lX||p.warn(`[${this.providerName}] the tool-free structured-output re-ask failed; keeping the original answer`,{provider:this.providerName,model:i,error:m instanceof Error?m.message:String(m)}),c={...c,inputTokens:c.inputTokens+u.inputTokens,outputTokens:c.outputTokens+u.outputTokens,cacheReadTokens:(c.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(c.cacheWriteTokens??0)+u.cacheWriteTokens}}}return c}async resolveStreamStructuredData(e){const{schema:t,schemaJson:r,text:n,conversation:o,modelId:s,abortSignal:i,options:a}=e,c=()=>i?.aborted===!0;if(n.trim().length===0)return;const l=uX(n,t);if(l!==void 0)return{data:l,usage:{inputTokens:0,outputTokens:0}};if(!(!o||c()))try{const u=await this.getAISDKModelWithMiddleware(a);if(!yC(u))return;p.warn(`[${this.providerName}] streamed answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:s});const d=u.doGenerate.bind(u),m={inputTokens:0,outputTokens:0},h=(w,E)=>aD({doGenerate:d,conversation:w,toolsRecord:{},...E?{responseFormat:E}:{},maxSteps:1,...a.maxTokens?{maxOutputTokens:a.maxTokens}:{},...i?{abortSignal:i}:{},runStep:_=>_()},[]).then(_=>(m.inputTokens+=_.inputTokens,m.outputTokens+=_.outputTokens,_)),g=[...o.filter(w=>{if(w.role==="tool")return!1;const E=w.tool_calls;return!(w.role==="assistant"&&Array.isArray(E)&&E.length>0)}),{role:"assistant",content:n},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let y;try{y=await h(g,{type:"json",schema:r})}catch(w){if(c())throw w;p.warn(`[${this.providerName}] the stream re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:s,error:w instanceof Error?w.message:String(w)}),y=await h(wv(g,r),void 0)}const v=uX(y.text,t);return v===void 0?(p.warn(`[${this.providerName}] the tool-free stream re-ask did not yield a schema-valid value either; leaving structuredData unset`,{provider:this.providerName,model:s}),{data:void 0,usage:m}):{data:v,usage:m}}catch(u){if(c()&&!(i?.reason instanceof ma))throw u;p.warn(`[${this.providerName}] the tool-free structured-output re-ask failed for a stream; leaving structuredData unset`,{provider:this.providerName,model:s,error:u instanceof Error?u.message:String(u)});return}}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=da(n,this.providerName,"stream"),s=new AbortController,i=Bve([e.abortSignal,o?.controller.signal,s.signal]).signal;let a,c,l,u,d,m;try{a=await this.resolveModelName();const ae=!e.disableTools&&this.supportsTools();c=ae?e.tools||await this.getAllTools():{},l=ae?sD(Object.keys(c)):void 0,u=ae?LY(c,l?.toWire):void 0,d=mAt(dD(e,c,ae),l?.toWire),m=await this.buildMessagesForStream(e)}catch(ae){throw o?.cleanup(),ae}const h=e.schema?Ao(e.schema):void 0,f=!!u&&u.length>0,g=h!==void 0&&f&&this.suppressResponseFormatWithTools(),y=h&&!g?this.adjustResponseFormat(UY({type:"json",schema:h}),a):void 0,v=this.getChatCompletionsURL(a),w=Pt(),E=e.maxSteps||Bs,_=this.neurolink?.getEventEmitter(),C=[],A=[],{usagePromise:k,finishPromise:R,resolveUsage:I,resolveFinish:P}=GY(),O=hv(),U=this.onStreamStart(a),M=u?.map(ae=>({type:"function",name:ae.function.name,description:ae.function.description,inputSchema:ae.function.parameters})),F={prompt:m,...M?{tools:M}:{},...e.maxTokens!==void 0?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.topP!==void 0?{topP:e.topP}:{}};let N,L;const q=this.providerName,B={specificationVersion:"v3",provider:q,modelId:a,supportedUrls:{},doGenerate:async ae=>{const Pe=await this.getAISDKModel();if(typeof Pe=="string")throw new Error("Native model handle required");return Pe.doGenerate(ae)},doStream:async ae=>{ae?.tools!==void 0&&ae.tools!==M&&p.warn(`${q}: middleware rewrote 'tools' on the streaming path; tool rewrites are not applied to the wire request yet \u2014 the original tool list was sent.`);const Pe=Array.isArray(ae?.prompt)?ae.prompt:m,Ae=NY(Pe,l?.toWire,this.replayReasoningContent());L=Ae;const Te={...e,...typeof ae?.maxOutputTokens=="number"?{maxTokens:ae.maxOutputTokens}:{},...typeof ae?.temperature=="number"?{temperature:ae.temperature}:{},...typeof ae?.topP=="number"?{topP:ae.topP}:{}};N=this.runStreamLoop({maxSteps:E,modelId:a,url:v,fetchImpl:w,abortSignal:i,options:Te,conversation:Ae,openAITools:u,openAIToolChoice:d,toolsRecord:c,toolNameFromWire:l?.fromWire,emitter:_,toolsUsed:C,toolExecutionSummaries:A,pushChunk:O.push,closeChannel:O.close,resolveUsage:I,resolveFinish:P,responseFormat:y});const he=N.then(()=>Promise.all([k,R]).then(([Oe,De])=>({type:"finish",finishReason:{unified:De},usage:{inputTokens:{total:Oe.promptTokens,cacheRead:Oe.cacheReadTokens},outputTokens:{total:Oe.completionTokens}}})));return he.catch(()=>{}),{stream:rkt(O.iterable,he,()=>s.abort())}}};let H;try{const ae=await this.applyMiddlewareToModel(B,e);if(typeof ae=="string")throw new Error("Native stream model handle required");const{stream:Pe}=await ae.doStream(F);H=w5r(Pe,Ae=>{if(!N){const Te=Ae.usage.inputTokens.total??0,he=Ae.usage.outputTokens.total??0,Oe=Math.min(Ae.usage.inputTokens.cacheRead??0,Te);I({promptTokens:Te-Oe,completionTokens:he,totalTokens:Te+he,...Oe>0?{cacheReadTokens:Oe}:{}}),P(Ae.finishReason.unified)}})}catch(ae){throw s.abort(),O.close(),o?.cleanup(),ae}let G;const X=ae=>{G=ae};U?.onUsage&&k.then(U.onUsage).catch(()=>{}),U?.onFinish&&R.then(ae=>U.onFinish?.(ae,G)).catch(()=>{});const ce=this.providerName,Q=this,Ie={startTime:r,streamId:`${this.providerName}-${Date.now()}`},le={stream:async function*(){let ae=0,Pe="";try{for await(const Ae of H)"content"in Ae&&typeof Ae.content=="string"&&Ae.content.length>0&&(ae++,e.schema&&(Pe+=Ae.content)),yield Ae;if(await N,e.schema&&h){const Ae=await Q.resolveStreamStructuredData({schema:e.schema,schemaJson:h,text:Pe,conversation:L,modelId:a,abortSignal:i,options:e});Ae?.data!==void 0&&(Ie.structuredData=Ae.data),Ae&&(Ae.usage.inputTokens>0||Ae.usage.outputTokens>0)&&(Ie.structuredDataUsage=Ae.usage,p.info(`[${ce}] structured-output re-ask billed separately from the streamed turn`,{provider:ce,model:a,inputTokens:Ae.usage.inputTokens,outputTokens:Ae.usage.outputTokens}))}if(ae===0&&C.length===0){p.warn(`${ce}: Stream produced no output \u2014 emitting enriched sentinel`);const Ae=new cu({message:"Stream produced no output"}),Te=await Mf(Ae,void 0,G);Of(Te),yield Te}}catch(Ae){if(cu.isInstance(Ae)){const he=await Mf(Ae,void 0,G);Of(he),yield he;return}const Te=await Mf(Ae,void 0,G);throw Of(Te),yield Te,Ae}finally{N||(I({promptTokens:0,completionTokens:0,totalTokens:0}),P("stop")),o?.cleanup(),s.signal.aborted||s.abort()}}(),provider:this.providerName,model:a,analytics:ZY.createAnalytics(this.providerName,a,{textStream:(async function*(){})(),usage:k,finishReason:R},Date.now()-r,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:C,metadata:Ie};return Object.defineProperty(le,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>bd(A.map(ae=>({toolName:ae.toolName,input:ae.input,output:ae.output,duration:ae.endTime.getTime()-ae.startTime.getTime()})))}),N?.finally(()=>o?.cleanup()).catch(ae=>{X(ae)}),le}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,toolsRecord:u,toolNameFromWire:d,emitter:m,toolsUsed:h,toolExecutionSummaries:f,pushChunk:g,closeChannel:y,resolveUsage:v,resolveFinish:w,responseFormat:E}=e;let _=null,C;const A=()=>{const k=C?.prompt_tokens??0,R=C?.completion_tokens??0,I=Math.min(C?.prompt_tokens_details?.cached_tokens??0,k),P=Math.min(Math.max(0,C?.completion_tokens_details?.reasoning_tokens??0),R);return{promptTokens:k-I,completionTokens:R,totalTokens:C?.total_tokens||k+R,...I>0?{cacheReadTokens:I}:{},...P>0?{reasoningTokens:P}:{}}};try{let k=d,R,I;for(let P=0;P<t;P++){if(c){const M=new Set(c.map(N=>k?.get(N.function.name)??N.function.name)),F=Object.fromEntries(Object.entries(u).filter(([N])=>!M.has(N)));if(Object.keys(F).length>0){const N=sD(Object.keys(F),new Set(c.map(L=>L.function.name)));if(N){k??=new Map;for(const[L,q]of N.fromWire)k.set(L,q)}c.push(...LY(F,N?.toWire)??[]),p.info(`${this.providerName}: ${Object.keys(F).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(F).join(", ")}`)}}const O=t5r({conversation:a,availableInputTokens:Pc(this.providerName,r,i.maxTokens??void 0),fixedOverheadTokens:MY([],c,this.providerName),provider:this.providerName,observedPromptTokens:R,previousSentEstimate:I,onSentEstimate:M=>{I=M}});O&&(a.length=0,a.push(...O));const U=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,pushChunk:g,responseFormat:E});if(R=U.usage?.prompt_tokens,_=U.finishReason,U.usage&&(C=fAt(C,U.usage)),U.toolCalls.size===0)break;await this.executeToolBatch({stepResult:U,conversation:a,toolsRecord:u,toolNameFromWire:k,emitter:m,toolsUsed:h,toolExecutionSummaries:f,options:i})}return v(A()),w(_??"stop"),y(),{finishReason:_??"stop",usage:C}}catch(k){throw p.error(`${this.providerName}: Stream error`,{error:k instanceof Error?k.message:String(k)}),v(A()),w("error"),y(),k}}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=BY(this.adjustRequestBody(zY({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.responseFormat?{responseFormat:e.responseFormat}:{}}),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 fC(e.url,n,i);return i};let s;try{s=await r0(o,lt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(i){const a=i,c=a.statusCode===400?(()=>{const l=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(l??n,a)??l})():void 0;if(!c)throw a;if(s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(c),...e.abortSignal?{signal:e.abortSignal}:{}}),!s.ok)throw await fC(e.url,c,s)}if(!s.body)throw new Error(`${this.providerName}: stream response had no body`);return qY(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:c}=e,l=[];for(const[,d]of t.toolCalls)l.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:l,...this.replayReasoningContent()&&t.reasoning?{reasoning_content:t.reasoning}:{}});for(const[,d]of t.toolCalls){const m=new Date;let h;try{h=JSON.parse(d.argsBuffered||"{}")}catch{h=d.argsBuffered}let f,g;const y=o?.get(d.name)??d.name,v=n[y]??F7(n,y);if(s?.emit("tool:start",{toolName:y,toolCallId:d.id,input:h}),!v||typeof v.execute!="function")g=`Tool '${y}' is not registered.`,f={error:g};else try{f=await v.execute(h,{})}catch(E){g=E instanceof Error?E.message:String(E),f={error:g}}const w=new Date;i.push(y),a.push({toolCallId:d.id,toolName:y,input:h,output:f,...g?{error:g}:{},startTime:m,endTime:w}),r.push({role:"tool",tool_call_id:d.id,content:OY(f)})}const u=a.slice(-t.toolCalls.size);_At(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})),c,new Date)}catch(d){p.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=`${Ca(this.config.baseURL)}/models`;p.debug(`Fetching available models from: ${e}`);const t=Pt(),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 p.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const s=await o.json();if(!s.data||!Array.isArray(s.data))return p.warn("Invalid models response format"),this.getFallbackModels();const i=s.data.map(a=>a.id).filter(Boolean);return p.shouldLog("debug")&&p.debug(`Discovered ${i.length} models:`,i),i.length>0?i:this.getFallbackModels()}catch(e){return p.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),dX,nkt,okt,skt,ikt,akt,E5r=b({"src/lib/providers/openAI/client.ts"(){"use strict";Xt(),On(),ut(),z(),Ut(),Ja(),qi(),ts(),_a(),gp(),pa(),vp(),kl(),cd(),dX="https://api.openai.com/v1",nkt=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??dX;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ca(n.toString())}catch{}return r},okt=()=>fa(PCr()),skt=()=>_i("OPENAI_MODEL","gpt-5.4"),ikt=lt.getTracer("neurolink.provider.openai"),akt=class extends Lc{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:okt(),i=nkt(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:i,apiKey:s}),p.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:No(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return skt()}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:Mr,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=>Vve(o.error),errorClass:ot,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:$s,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:Oo,message:o=>`Model not found: ${o.modelName}`},..._c];return ha(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=ikt.startSpan("neurolink.provider.streamText",{kind:zr.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=xi(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:Ue.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){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel();p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const[o]=await this.callEmbeddings(n,[r],"embed");return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();p.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw p.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=`${Ca(this.config.baseURL)}/embeddings`,o=Pt(),s=da(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 l=await i.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${i.status}`,d;if(l)try{const m=JSON.parse(l);m.error?.message&&(u=m.error.message),d=m.error?.type}catch{}throw Object.assign(new Error(u),{status:i.status,type:d})}const c=((await i.json()).data??[]).map(l=>l.embedding).filter(l=>Array.isArray(l));if(c.length===0)throw new ot(`OpenAI ${r} returned no embeddings`,this.providerName);return c}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=Ca(this.config.baseURL??dX),s=e,i=s.size??this.aspectRatioToOpenAISize(s.aspectRatio,n),a=s.numberOfImages??1;let c;n==="gpt-image-1"||n.startsWith("dall-e-3")?c=1:n.startsWith("dall-e-2")?c=Math.min(Math.max(a,1),10):c=1;const u={model:n,prompt:r,n:c,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 f;try{f=await Pt()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:m.signal})}catch(E){throw E instanceof Error&&E.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:E}):E}finally{clearTimeout(h)}if(!f.ok){const E=await f.text();throw new Error(`OpenAI image generation failed: ${f.status} \u2014 ${E}`)}const y=(await f.json()).data?.[0];if(!y)throw new Error("OpenAI image generation returned no images");let v=y.b64_json;if(!v&&y.url){await fp(y.url);const E=Pt(),_=new AbortController,C=setTimeout(()=>_.abort(),6e4);let A;try{A=await E(y.url,{signal:_.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(C)}if(!A.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${y.url} (${A.status})`);v=(await ku(A,hp,"OpenAI image fallback")).toString("base64")}if(!v)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const w=Date.now()-t;return p.info(`[OpenAIProvider] Generated image (${v.length} base64 chars) in ${w}ms \u2014 model ${n}`),{content:y.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:v}}}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"}}}}),ckt={};ee(ckt,{OpenAIProvider:()=>akt});var S5r=b({"src/lib/providers/openAI/index.ts"(){"use strict";E5r()}});function Fe(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 j(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 tc=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),wC,mX=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){wC=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return wC=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 Ev(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var EC,Sv=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){EC=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)}}}),it,Mi,Fc,bv,pX,lkt,hX,fX,gX,yX,vX,TX,wX,EX,So=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){Sv(),it=class extends Error{},Mi=class Vde extends it{constructor(t,r,n,o,s){super(`${Vde.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 bv({message:n,cause:EC(r)});const s=r,i=s?.error?.type;return t===400?new hX(t,s,n,o,i):t===401?new fX(t,s,n,o,i):t===403?new gX(t,s,n,o,i):t===404?new yX(t,s,n,o,i):t===409?new vX(t,s,n,o,i):t===422?new TX(t,s,n,o,i):t===429?new wX(t,s,n,o,i):t>=500?new EX(t,s,n,o,i):new Vde(t,s,n,o,i)}},Fc=class extends Mi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},bv=class extends Mi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},pX=class extends bv{constructor({message:e}={}){super({message:e??"Request timed out."})}},lkt=class extends it{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},hX=class extends Mi{},fX=class extends Mi{},gX=class extends Mi{},yX=class extends Mi{},vX=class extends Mi{},TX=class extends Mi{},wX=class extends Mi{},EX=class extends Mi{}}});function SX(e){return typeof e!="object"?{}:e??{}}function ukt(e){if(!e)return!0;for(const t in e)return!1;return!0}function b5r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var dkt,mkt,Ji,bX,pkt,_X,Ud=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){So(),dkt=/^[a-z][a-z0-9+.-]*:/i,mkt=e=>dkt.test(e),Ji=e=>(Ji=Array.isArray,Ji(e)),bX=Ji,pkt=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new it(`${e} must be an integer`);if(t<0)throw new it(`${e} must be a positive integer`);return t},_X=e=>{try{return JSON.parse(e)}catch{return}}}}),Tp,SC=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){Tp=(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})})}}),Bd,pD=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){Bd="0.102.0"}});function _5r(){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 C5r(){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 hkt,fkt,CX,AX,gkt,hD,kX=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){pD(),hkt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",fkt=()=>{const e=_5r();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bd,"X-Stainless-OS":AX(Deno.build.os),"X-Stainless-Arch":CX(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":Bd,"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":Bd,"X-Stainless-OS":AX(globalThis.process.platform??"unknown"),"X-Stainless-Arch":CX(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=C5r();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bd,"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":Bd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},CX=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",AX=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"),hD=()=>gkt??(gkt=fkt())}});function A5r(){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 ykt(...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 vkt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ykt({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function xX(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 k5r(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 bC=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),Tkt,x5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){Tkt=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),IX,RX,PX,wkt,Ekt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){IX="RFC3986",RX=e=>String(e),PX={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:RX},wkt="RFC1738"}});function I5r(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Skt(e,t){if(Ji(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var fD,xl,gD,bkt,R5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){Ekt(),Ud(),fD=(e,t)=>(fD=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),fD(e,t)),xl=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),gD=1024,bkt=(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+=gD){const c=s.length>=gD?s.slice(a,a+gD):s,l=[];for(let u=0;u<c.length;++u){let d=c.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===wkt&&(d===40||d===41)){l[l.length]=c.charAt(u);continue}if(d<128){l[l.length]=xl[d];continue}if(d<2048){l[l.length]=xl[192|d>>6]+xl[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=xl[224|d>>12]+xl[128|d>>6&63]+xl[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=xl[240|d>>18]+xl[128|d>>12&63]+xl[128|d>>6&63]+xl[128|d&63]}i+=l.join("")}return i}}});function P5r(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function _kt(e,t,r,n,o,s,i,a,c,l,u,d,m,h,f,g,y,v){let w=e,E=v,_=0,C=!1;for(;(E=E.get(yD))!==void 0&&!C;){const P=E.get(e);if(_+=1,typeof P<"u"){if(P===_)throw new RangeError("Cyclic object value");C=!0}typeof E.get(yD)>"u"&&(_=0)}if(typeof l=="function"?w=l(t,w):w instanceof Date?w=m?.(w):r==="comma"&&Ji(w)&&(w=Skt(w,function(P){return P instanceof Date?m?.(P):P})),w===null){if(s)return c&&!g?c(t,ls.encoder,y,"key",h):t;w=""}if(P5r(w)||I5r(w)){if(c){const P=g?t:c(t,ls.encoder,y,"key",h);return[f?.(P)+"="+f?.(c(w,ls.encoder,y,"value",h))]}return[f?.(t)+"="+f?.(String(w))]}const A=[];if(typeof w>"u")return A;let k;if(r==="comma"&&Ji(w))g&&c&&(w=Skt(w,c)),k=[{value:w.length>0?w.join(",")||null:void 0}];else if(Ji(l))k=l;else{const P=Object.keys(w);k=u?P.sort(u):P}const R=a?String(t).replace(/\./g,"%2E"):String(t),I=n&&Ji(w)&&w.length===1?R+"[]":R;if(o&&Ji(w)&&w.length===0)return I+"[]";for(let P=0;P<k.length;++P){const O=k[P],U=typeof O=="object"&&typeof O.value<"u"?O.value:w[O];if(i&&U===null)continue;const M=d&&a?O.replace(/\./g,"%2E"):O,F=Ji(w)?typeof r=="function"?r(I,M):I:I+(d?"."+M:"["+M+"]");v.set(e,_);const N=new WeakMap;N.set(yD,v),OX(A,_kt(U,F,r,n,o,s,i,a,r==="comma"&&g&&Ji(w)?null:c,l,u,d,m,h,f,g,y,N))}return A}function M5r(e=ls){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||ls.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=IX;if(typeof e.format<"u"){if(!fD(PX,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=PX[r];let o=ls.filter;(typeof e.filter=="function"||Ji(e.filter))&&(o=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in MX?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=ls.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:ls.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:ls.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:ls.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:ls.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?ls.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:ls.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:ls.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:ls.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:ls.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:ls.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:ls.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:ls.strictNullHandling}}function O5r(e,t={}){let r=e;const n=M5r(t);let o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Ji(n.filter)&&(s=n.filter,o=s);const i=[];if(typeof r!="object"||r===null)return"";const a=MX[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const l=new WeakMap;for(let m=0;m<o.length;++m){const h=o[m];n.skipNulls&&r[h]===null||OX(i,_kt(r[h],h,a,c,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,l))}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 MX,OX,Ckt,ls,yD,D5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){R5r(),Ekt(),Ud(),MX={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},OX=function(e,t){Array.prototype.push.apply(e,Ji(t)?t:[t])},ls={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:bkt,encodeValuesOnly:!1,format:IX,formatter:RX,indices:!1,serializeDate(e){return(Ckt??(Ckt=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},yD={}}});function N5r(e){return O5r(e,{arrayFormat:"brackets"})}var Akt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){D5r()}});function kkt(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Dn(`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 Dn(`Refusing to send credential over non-https token endpoint "${e}"`)}async function xkt(e,t){const r=await L5r(e);let n;try{n=JSON.parse(r)}catch{throw new Dn(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,$c(r),t)}if(!n.access_token)throw new Dn(`Token endpoint response missing access_token: ${JSON.stringify($c(n))}`,e.status,$c(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new Dn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,$c(n),t);return n}function $c(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=TD?e:e.slice(0,TD)+`... <${e.length-TD} more chars>`}return JSON.stringify($c(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))Lkt.has(r)&&(t[r]=n);return t}return null}async function Ikt(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(Pn(),hd));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 Dn(`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 Dn(`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 Rkt(e,t){const r=await Promise.resolve().then(()=>(Pn(),hd)),o=(await Promise.resolve().then(()=>(zt(),jm))).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 L5r(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>NX){const a=NX-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 Pkt,Mkt,DX,_C,Okt,Dkt,vD,Nkt,NX,TD,Lkt,Dn,CC=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){So(),Pkt="urn:ietf:params:oauth:grant-type:jwt-bearer",Mkt="refresh_token",DX="/v1/oauth/token",_C="oauth-2025-04-20",Okt="oidc-federation-2026-04-01",Dkt=120,vD=30,Nkt=5,NX=1<<20,TD=2e3,Lkt=new Set(["error","error_description","error_uri"]),Dn=class extends it{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function Vf(){return Math.floor(Date.now()/1e3)}var wD=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),Fkt,F5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){CC(),wD(),Fkt=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-Vf();return r>Dkt?t.token:r>vD?(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||Vf()-this.lastAdvisoryError<Nkt||this.doRefresh().catch(e=>{this.lastAdvisoryError=Vf(),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}}}}),Sr,ED=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Sr=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 $5r(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 LX(e){let t;return(Ukt??(t=new globalThis.TextEncoder,Ukt=t.encode.bind(t)))(e)}function $kt(e){let t;return(Bkt??(t=new globalThis.TextDecoder,Bkt=t.decode.bind(t)))(e)}var Ukt,Bkt,FX=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),U5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){So(),FX()}});function AC(){}function SD(e,t,r){return!t||kC[e]>kC[r]?AC:t[e].bind(t)}function bo(e){const t=e.logger,r=e.logLevel??"off";if(!t)return zkt;const n=UX.get(t);if(n&&n[0]===r)return n[1];const o={error:SD("error",t,r),warn:SD("warn",t,r),info:SD("info",t,r),debug:SD("debug",t,r)};return UX.set(t,[r,o]),o}var kC,$X,zkt,UX,zd,wp=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){Ud(),kC={off:0,error:200,warn:300,info:400,debug:500},$X=(e,t,r)=>{if(e){if(b5r(kC,e))return e;bo(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(kC))}`)}},zkt={error:AC,warn:AC,info:AC,debug:AC},UX=new WeakMap,zd=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)}}),qkt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){Ud(),U5r(),ED(),wp(),mX(),SC(),Akt()}});function Gkt(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(!jkt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var BX,jkt,Hkt,Vkt,bD,Wkt,zX,Kkt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){kX(),qkt(),BX="1.0",jkt=/^[A-Za-z0-9_.-]+$/,Hkt=async e=>{var t,r;const n=await bD();if(n===null)return null;const o=e??await zX();if(o===null)return null;Gkt(o);const s=await Promise.resolve().then(()=>(Pn(),hd)),a=(await Promise.resolve().then(()=>(zt(),jm))).join(n,"configs",`${o}.json`);let c;try{c=await s.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);c=null}if(c===null){const d=Sr("ANTHROPIC_ORGANIZATION_ID"),m=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE"),h=Sr("ANTHROPIC_FEDERATION_RULE_ID");return h&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Sr("ANTHROPIC_WORKSPACE_ID"),base_url:Sr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:h,service_account_id:Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Sr("ANTHROPIC_SCOPE")}}}:null}let l;try{l=JSON.parse(c)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!l.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=l.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(l.organization_id??(l.organization_id=Sr("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Sr("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Sr("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Sr("ANTHROPIC_SCOPE")),l.authentication.type==="oidc_federation"){if(!l.authentication.identity_token){const d=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(l.authentication.identity_token={source:"file",path:d})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Sr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=l.authentication).service_account_id??(r.service_account_id=Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}},Vkt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await bD();if(!r)return null;const n=t??await zX();return n?(Gkt(n),(await Promise.resolve().then(()=>(zt(),jm))).join(r,"credentials",`${n}.json`)):null},bD=async()=>{if(!Wkt())return null;const e=await Promise.resolve().then(()=>(zt(),jm)),t=Sr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(hD()["X-Stainless-OS"]==="Windows"){const s=Sr("APPDATA");if(s)return e.join(s,"Anthropic");const i=Sr("USERPROFILE");return i?e.join(i,"AppData","Roaming","Anthropic"):null}const n=Sr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Sr("HOME");return o?e.join(o,".config","anthropic"):null},Wkt=()=>{const e=hD()["X-Stainless-Runtime"];return e==="node"||e==="deno"},zX=async()=>{const e=await bD();if(!e)return null;const t=Sr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(Pn(),hd)),o=(await Promise.resolve().then(()=>(zt(),jm))).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 Jkt(e){if(!e)throw new it("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(Pn(),hd));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new it(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new it(`Identity token file at ${e} is empty`);return n}}function B5r(e){if(!e)throw new it("Identity token value is empty");return()=>e}var z5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){So()}});function q5r(e){return async()=>{kkt(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new Dn(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:Pkt,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}${DX}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${_C},${Okt}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Bd} oidcFederationProvider`},body:JSON.stringify(r)})}catch(c){throw new Dn(`Failed to reach token endpoint ${n}: ${c}`)}const s=o.headers.get("Request-Id");if(!o.ok){const c=await o.text().catch(()=>""),l=$c(c);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 Dn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${l}${u}`,o.status,l,s)}const i=await xkt(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new Dn(`Token endpoint response missing required fields: ${JSON.stringify($c(i))}`,o.status,$c(i),s);return{token:i.access_token,expiresAt:Vf()+a}}}var G5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){CC(),wD(),pD()}});function j5r(e){return async t=>{const r=await Promise.resolve().then(()=>(Pn(),hd));await Ikt(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(y){throw new Dn(`Credentials file not found at ${e.credentialsPath}: ${y}`)}let o;try{o=JSON.parse(n)}catch(y){throw new Dn(`Credentials file at ${e.credentialsPath} is not valid JSON: ${y}`)}const s=o.access_token;if(!s)throw new Dn(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const i=o.expires_at;if(!t?.forceRefresh&&(i==null||Vf()<i-vD))return{token:s,expiresAt:i??null};const a=o.refresh_token;if(!e.clientId||!a)throw new Dn(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);kkt(e.baseURL);const c={grant_type:Mkt,refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${DX}`;let u;try{u=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":_C,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Bd} userOAuthProvider`},body:JSON.stringify(c)})}catch(y){throw new Dn(`User OAuth refresh failed to reach token endpoint: ${y}`)}const d=u.headers.get("Request-Id");if(!u.ok){const y=await u.text().catch(()=>"");throw new Dn(`User OAuth refresh failed (HTTP ${u.status}): ${$c(y)}`,u.status,$c(y),d)}const m=await xkt(u,d),h=Number(m.expires_in);if(!Number.isFinite(h))throw new Dn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify($c(m))}`,u.status,$c(m),d);const f=Vf()+h,g=m.refresh_token||a;return await Rkt(e.credentialsPath,{...o,version:BX,type:"oauth_token",access_token:m.access_token,expires_at:f,refresh_token:g}),{token:m.access_token,expiresAt:f}}}var H5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){Kkt(),CC(),wD(),pD()}});function Ykt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=W5r(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 V5r(e,t){const r=await Hkt(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 Vkt(n,t)??void 0}};return Ykt(s,e)}function W5r(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,s=K5r(o);if(!s)throw new Dn("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 Dn("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 Dn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const i=q5r({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?J5r(i,t,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!t)throw new Dn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return j5r({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 Dn(`authentication.type "${o}" is not a known authentication type`)}}}function K5r(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new Dn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Dn('identity_token.source "file" requires a non-empty path');return Jkt(e.identity_token.path)}const t=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return Jkt(t);const r=Sr("ANTHROPIC_IDENTITY_TOKEN");return r?B5r(r):null}function J5r(e,t,r,n){return async o=>{const s=await Promise.resolve().then(()=>(Pn(),hd));await Ikt(t,n);let i;try{const c=await s.promises.readFile(t,"utf-8");i=JSON.parse(c);const l=i?.access_token;if(l&&!o?.forceRefresh){const u=i?.expires_at;if(u==null||Vf()<u-vD)return{token:l,expiresAt:u??null}}}catch(c){c?.code!=="ENOENT"&&!(c instanceof SyntaxError)&&r?.(c)}const a=await e(o);try{await Rkt(t,{...i??{},version:BX,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(c){r?.(c)}return a}}var Y5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){ED(),Kkt(),CC(),wD(),z5r(),G5r(),H5r()}});function X5r(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 Z5r(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 rc,nc,_v,Xkt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){tc(),FX(),_v=class{constructor(){rc.set(this,void 0),nc.set(this,void 0),Fe(this,rc,new Uint8Array,"f"),Fe(this,nc,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?LX(e):e;Fe(this,rc,$5r([j(this,rc,"f"),t]),"f");const r=[];let n;for(;(n=X5r(j(this,rc,"f"),j(this,nc,"f")))!=null;){if(n.carriage&&j(this,nc,"f")==null){Fe(this,nc,n.index,"f");continue}if(j(this,nc,"f")!=null&&(n.index!==j(this,nc,"f")+1||n.carriage)){r.push($kt(j(this,rc,"f").subarray(0,j(this,nc,"f")-1))),Fe(this,rc,j(this,rc,"f").subarray(j(this,nc,"f")),"f"),Fe(this,nc,null,"f");continue}const o=j(this,nc,"f")!==null?n.preceding-1:n.preceding,s=$kt(j(this,rc,"f").subarray(0,o));r.push(s),Fe(this,rc,j(this,rc,"f").subarray(n.index),"f"),Fe(this,nc,null,"f")}return r}flush(){return j(this,rc,"f").length?this.decode(`
|
|
1052
|
+
]`}function w(){let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,H=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,G=e[t]==="\\";if(G&&(t++,G=!0),lD(e[t])){const X=DAt(e[t])?DAt:NAt(e[t])?NAt:tX(e[t])?tX:OAt,ce=t,Q=r.length;let Ae='"';for(t++;;){if(t>=e.length){const Ee=I(t-1);return!B&&cD(e.charAt(Ee))?(t=ce,r=r.substring(0,Q),w(!0)):(Ae=Al(Ae,'"'),r+=Ae,!0)}if(t===H)return Ae=Al(Ae,'"'),r+=Ae,!0;if(X(e[t])){const Ee=t,le=Ae.length;if(Ae+='"',t++,r+=Ae,i(!1),B||t>=e.length||cD(e[t])||lD(e[t])||jf(e[t]))return E(),!0;const ae=I(Ee-1),Pe=e.charAt(ae);if(Pe===",")return t=ce,r=r.substring(0,Q),w(!1,ae);if(cD(Pe))return t=ce,r=r.substring(0,Q),w(!0);r=r.substring(0,Q),t=Ee+1,Ae=`${Ae.substring(0,le)}\\${Ae.substring(le)}`}else if(B&&PAt(e[t])){if(e[t-1]===":"&&sX.test(e.substring(ce+1,t+2)))for(;t<e.length&&iX.test(e[t]);)Ae+=e[t],t++;return Ae=Al(Ae,'"'),r+=Ae,E(),!0}else if(e[t]==="\\"){const Ee=e.charAt(t+1);if(WAt[Ee]!==void 0)Ae+=e.slice(t,t+2),t+=2;else if(Ee==="u"){let ae=2;for(;ae<6&&s5r(e[t+ae]);)ae++;ae===6?(Ae+=e.slice(t,t+6),t+=6):t+ae>=e.length?t=e.length:q()}else Ee===`
|
|
1053
|
+
`?(Ae+="\\n",t+=2):(Ae+=Ee,t+=2)}else{const Ee=e.charAt(t);Ee==='"'&&e[t-1]!=="\\"?(Ae+=`\\${Ee}`,t++):a5r(Ee)?(Ae+=VAt[Ee],t++):(i5r(Ee)||U(Ee),Ae+=Ee,t++)}G&&h()}}return!1}function E(){let B=!1;for(i();e[t]==="+";){B=!0,t++,i(),r=vC(r,'"',!0);const H=r.length;w()?r=u5r(r,H,1):r=Al(r,'"')}return B}function _(){const B=t;if(e[t]==="-"){if(t++,P())return O(B),!0;if(!jf(e[t]))return t=B,!1}for(;jf(e[t]);)t++;if(e[t]==="."){if(t++,P())return O(B),!0;if(!jf(e[t]))return t=B,!1;for(;jf(e[t]);)t++}if(e[t]==="e"||e[t]==="E"){if(t++,(e[t]==="-"||e[t]==="+")&&t++,P())return O(B),!0;if(!jf(e[t]))return t=B,!1;for(;jf(e[t]);)t++}if(!P())return t=B,!1;if(t>B){const H=e.slice(B,t),G=/^0\d/.test(H);return r+=G?`"${H}"`:H,!0}return!1}function C(){return A("true","true")||A("false","false")||A("null","null")||A("True","true")||A("False","false")||A("None","null")}function A(B,H){return e.slice(t,t+B.length)===B?(r+=H,t+=B.length,!0):!1}function k(B){const H=t;if(IAt(e[t])){for(;t<e.length&&RAt(e[t]);)t++;let G=t;for(;Hf(e,G);)G++;if(e[G]==="(")return t=G+1,s(),e[t]===")"&&(t++,e[t]===";"&&t++),!0}for(;t<e.length&&!PAt(e[t])&&!lD(e[t])&&(!B||e[t]!==":");)t++;if(e[t-1]===":"&&sX.test(e.substring(H,t+2)))for(;t<e.length&&iX.test(e[t]);)t++;if(t>H){for(;Hf(e,t-1)&&t>0;)t--;const G=e.slice(H,t);return r+=G==="undefined"?"null":JSON.stringify(G),e[t]==='"'&&t++,!0}}function R(){if(e[t]==="/"){const B=t;for(t++;t<e.length&&(e[t]!=="/"||e[t-1]==="\\");)t++;return t++,r+=JSON.stringify(e.substring(B,t)),!0}}function I(B){let H=B;for(;H>0&&Hf(e,H);)H--;return H}function P(){return t>=e.length||cD(e[t])||Hf(e,t)}function O(B){r+=`${e.slice(B,t)}0`}function U(B){throw new Gf(`Invalid character ${JSON.stringify(B)}`,t)}function M(){throw new Gf(`Unexpected character ${JSON.stringify(e[t])}`,t)}function F(){throw new Gf("Unexpected end of json string",e.length)}function N(){throw new Gf("Object key expected",t)}function L(){throw new Gf("Colon expected",t)}function q(){const B=e.slice(t,t+6);throw new Gf(`Invalid unicode character "${B}"`,t)}}function h5r(e,t){return e[t]==="*"&&e[t+1]==="/"}var VAt,WAt,f5r=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/regular/jsonrepair.js"(){o5r(),m5r(),VAt={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},WAt={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
1054
|
+
`,r:"\r",t:" "}}}),g5r=b({"node_modules/.pnpm/jsonrepair@3.14.0/node_modules/jsonrepair/lib/esm/index.js"(){f5r()}});function KAt(e,t=0){for(let r=t;r<e.length;r++){const n=e[r];if(n!=="{"&&n!=="[")continue;const o=n==="{"?"}":"]";let s=0,i=!1,a=!1;for(let c=r;c<e.length;c++){const l=e[c];if(a){a=!1;continue}if(l==="\\"){a=!0;continue}if(l==='"'){i=!i;continue}if(!i){if(l===n)s++;else if(l===o&&(s--,s===0))return{span:e.substring(r,c+1),end:c+1}}}}return null}var y5r=b({"src/lib/utils/json/extract.ts"(){"use strict"}});function JAt(e){return typeof e.safeParse=="function"}function uD(e,t){return!e||!JAt(e)?!0:e.safeParse(t).success}function YAt(e,t){try{const r=JSON.parse(e);return r===""?{kind:"empty"}:r==null?{kind:"nullish"}:uD(t,r)?{kind:"accepted",value:r}:{kind:"rejected",value:r}}catch{return{kind:"not-json"}}}function XAt(e){try{return{value:JSON.parse(e),repaired:!1}}catch{}try{const t=p5r(e),r=JSON.parse(t);return t!==e&&p.shouldLog("debug")&&p.debug("[coerceJsonToSchema] jsonrepair altered model output",{originalLength:e.length,repairedLength:t.length}),{value:r,repaired:t!==e}}catch{return}}function v5r(e){let t=e;for(let r=0;r<QAt&&t.length>1;r++){const n=Math.max(t.lastIndexOf(","),t.lastIndexOf("}"),t.lastIndexOf("]"));if(n<=0)break;t=t.slice(0,n);const o=XAt(t);if(o!==void 0&&o.value!==null&&typeof o.value=="object")return o.value}}function aX(e,t=0){if(t>ZAt)return{value:e,changed:!1};if(typeof e=="string"){const r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const o=JSON.parse(r);if(o!==null&&typeof o=="object")return{value:o,changed:!0}}catch{}return{value:e,changed:!1}}if(Array.isArray(e)){let r=!1;const n=e.map(o=>{const s=aX(o,t+1);return s.changed&&(r=!0),s.value});return{value:r?n:e,changed:r}}if(e!==null&&typeof e=="object"){let r=!1;const n={};for(const[o,s]of Object.entries(e)){const i=aX(s,t+1);i.changed&&(r=!0),n[o]=i.value}return{value:r?n:e,changed:r}}return{value:e,changed:!1}}function cX(e,t){if(typeof e!="string"||e.trim().length===0)return null;const r=[],n=[e.indexOf("{"),e.indexOf("[")].filter(v=>v>=0),o=n.length>0?Math.min(...n):-1;let s=!1,i=0;for(;;){const v=KAt(e,i);if(!v)break;const w=v.end-v.span.length;w===o&&(s=!0),r.push({text:v.span,truncated:!1,rootAligned:w===o}),i=v.end}const a=o>=0&&!s,c=Math.max(e.lastIndexOf("}"),e.lastIndexOf("]"));o>=0&&c>o&&r.push({text:e.slice(o,c+1),truncated:a,rootAligned:!0}),o>=0&&r.push({text:e.slice(o),truncated:!0,rootAligned:!0});const l=e.trim();if(l.length>1&&l.startsWith('"')&&l.endsWith('"'))try{const v=JSON.parse(l);if(typeof v=="string"){let w=0;for(;;){const E=KAt(v,w);if(!E)break;r.push({text:E.span,truncated:!1,rootAligned:!1}),w=E.end}}}catch{}const u=[...r.filter(v=>v.rootAligned),...r.filter(v=>!v.rootAligned)];let d;const m=[],h=!!(t&&JAt(t)),f=new Set;for(const v of u){if(f.has(v.text))continue;f.add(v.text);const w=XAt(v.text);if(w===void 0||w.value===null||typeof w.value!="object")continue;const E={value:w.value,repaired:w.repaired,truncated:v.truncated,rootAligned:v.rootAligned};if(d===void 0&&(d=E),!h)break;const _=t;if(_.safeParse(w.value).success)m.push(E);else{const C=aX(w.value);C.changed&&C.value!==null&&typeof C.value=="object"&&_.safeParse(C.value).success?m.push({value:C.value,repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned}):Array.isArray(w.value)&&w.value.length===1&&w.value[0]!==null&&typeof w.value[0]=="object"&&!Array.isArray(w.value[0])&&_.safeParse(w.value[0]).success&&m.push({value:w.value[0],repaired:!0,truncated:v.truncated,rootAligned:v.rootAligned})}}const g=m.length>0?m.reduce((v,w)=>JSON.stringify(w.value).length>JSON.stringify(v.value).length?w:v):void 0;let y=g??d;if(a&&g===void 0&&(y===void 0||!y.rootAligned)){const v=v5r(e.slice(o));v!==void 0?(p.debug("[coerceJsonToSchema] salvaged a partial truncated object",{textLength:e.length}),y={value:v,repaired:!0,truncated:!0,rootAligned:!0}):y!==void 0&&(y={...y,truncated:!0})}return y===void 0?null:{content:JSON.stringify(y.value),structuredData:y.value,repaired:y.repaired,truncated:y.truncated}}var ZAt,QAt,ekt=b({"src/lib/utils/json/coerce.ts"(){"use strict";g5r(),z(),y5r(),ZAt=6,QAt=8}});function dD(e,t,r){return!r||!t||Object.keys(t).length===0?"none":e.toolChoice??"auto"}function T5r(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;if(t.type==="tool")return t.toolName?{type:"tool",toolName:t.toolName}:void 0;if(t.type)return t.type}}var tkt=b({"src/lib/utils/toolChoice.ts"(){"use strict"}});async function*w5r(e,t){const r=e.getReader();let n=!1;try{for(;;){const o=await r.read();if(o.done){n=!0;return}const s=o.value;if(s.type==="text-delta")yield{content:s.delta};else if(s.type==="reasoning-delta")yield{content:"",reasoning:s.delta};else if(s.type==="finish")t(s);else if(s.type==="error")throw s.error}}finally{try{n||await r.cancel()}finally{r.releaseLock()}}}var mD,lX,TC,uX,rkt,Lc,kl=b({"src/lib/providers/openaiChatCompletionsBase.ts"(){"use strict";Xt(),bl(),r5r(),Ko(),TAt(),wAt(),EAt(),ec(),Lo(),bAt(),On(),z(),Ut(),$m(),DK(),pa(),CAt(),tf(),eX(),Zm(),ui(),ekt(),tkt(),Ic(),cd(),cY(),i_(),vp(),fv(),mD=512,lX=class extends Error{},TC=(e,t)=>{const r=cX(e,t);return r!==null&&uD(t,r.structuredData)},uX=(e,t)=>{const r=cX(e,t);if(r!==null&&uD(t,r.structuredData))return r.structuredData;const n=YAt(e,t);return n.kind==="accepted"?n.value:void 0},rkt=(e,t,r)=>{const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const s=await n.next();s.done?(o.enqueue(await t),o.close()):s.value.reasoning?o.enqueue({type:"reasoning-delta",delta:s.value.reasoning}):o.enqueue({type:"text-delta",delta:s.value.content})}catch(s){o.error(s)}},async cancel(){r(),await n.return?.()}})},Lc=class extends ba{config;resolvedModel;constructor(e,t,r,n){super(t,e,r),this.config=n}getFallbackModelName(){return"gpt-3.5-turbo"}getModelFallbacks(){return this.getFallbackModels()}refreshHandlersForModel(e){this.resolvedModel=e,super.refreshHandlersForModel(e)}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}suppressResponseFormatWithTools(){return!0}useStreamingWireForGenerate(){return!1}replayReasoningContent(){return!1}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,r,n){const o=J9(this.providerName,e);let s=t;o!==void 0&&(s===void 0||s>o)&&(s!==void 0&&p.debug(`${this.providerName}: clamping max_tokens ${s} to the advertised ${e} output ceiling ${o}`),s=o);const i=K9(this.providerName,e);if(i!==void 0){const a=MY(r,n,this.providerName),c=i-a-mD;if(c<=0)throw new Aa(`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-mD),stagesUsed:[],breakdown:{}});s!==void 0&&s>c&&(p.warn(`${this.providerName}: max_tokens ${s} cannot fit the ${e} window (${i}) with ~${a} input tokens \u2014 re-fitting to ${c}`),s=c)}return s}correctBodyAfterContextOverflow(e,t){if(!KY(t))return;const r=JY(t)??JY(t.responseBody);if(!r||r.budgetTokens<=0)return;W9(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-mD;if(!(o<=0||o>=n))return p.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`${Ca(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=`${Ca(this.config.baseURL)}/models`,n=await Pt()(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 p.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:No(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]),p.info(`\u{1F50D} Auto-discovered model: ${r[0]} from ${r.length} available models`),r[0]}catch(r){p.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=Pt(),n=this.getAuthHeaders.bind(this),o=this.providerName,s=this.adjustBuildBodyOptions.bind(this),i=this.adjustResponseFormat.bind(this),a=this.adjustRequestBody.bind(this),c=this.adjustBodyAfter400.bind(this),l=this.correctBodyAfterContextOverflow.bind(this),u=this.resolveWireMaxTokens.bind(this),d=this.suppressResponseFormatWithTools.bind(this),m=this.useStreamingWireForGenerate.bind(this),h=this.replayReasoningContent.bind(this),f=g=>this.getTimeout(g??{});return{specificationVersion:"v3",provider:o,modelId:e,supportedUrls:{},doGenerate:async g=>{const y=sD((g.tools??[]).filter(G=>G.type==="function").map(G=>G.name)),v=NY(g.prompt,y?.toWire,h()),w=Array.isArray(g.tools)&&g.tools.length>0,E=g.responseFormat&&!(w&&d())?i(UY(g.responseFormat),e):void 0,_=cAt(g.tools,y?.toWire),C=u(e,g.maxOutputTokens,v,_),A=m(),k=BY(a(zY({modelId:e,messages:v,options:s(e,{maxTokens:C,temperature:g.temperature,topP:g.topP,presencePenalty:g.presencePenalty,frequencyPenalty:g.frequencyPenalty,seed:g.seed,stopSequences:g.stopSequences}),tools:_,...g.toolChoice?{toolChoice:lAt(g.toolChoice,y?.toWire)}:{},streaming:A,...E?{responseFormat:E}:{}}),e)),R=g.providerOptions?.neurolink?.timeoutMs,I=da(typeof R=="number"?R:f(g),o,"generate"),{signal:P,dispose:O}=F1(g.abortSignal,I?.controller.signal);let U,M=A;try{let G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(k),...P?{signal:P}:{}});if(!G.ok){const X=await fC(t,k,G),ce=X;let Q=G.status===400?(()=>{const Ae=l(k,ce);return c(Ae??k,ce)??Ae})():void 0;if(!Q&&A&&G.status===400&&/stream/i.test(ce.responseBody??"")){const{stream:Ae,stream_options:Ee,...le}=k;Q=le,M=!1}if(!Q)throw X;if(G=await r(t,{method:"POST",headers:{"Content-Type":"application/json",...n()},body:JSON.stringify(Q),...P?{signal:P}:{}}),!G.ok)throw await fC(t,Q,G)}if(M){if(!G.body)throw new Error(`${o}: streaming generate response had no body`);const X=I?G.body.pipeThrough(new TransformStream({transform(Q,Ae){I.reset(),Ae.enqueue(Q)}})):G.body,ce=await qY(X,()=>{});U={...ce.id?{id:ce.id}:{},...ce.model?{model:ce.model}:{},choices:[{index:0,message:{role:"assistant",content:ce.text.length>0?ce.text:null,...ce.reasoning?{reasoning:ce.reasoning}:{},...ce.toolCalls.size>0?{tool_calls:[...ce.toolCalls.values()].map(Q=>({id:Q.id,type:"function",function:{name:Q.name,arguments:Q.argsBuffered}}))}:{}},finish_reason:ce.finishReason??"stop"}],...ce.usage?{usage:ce.usage}:{}}}else U=await G.json()}finally{I?.cleanup(),O()}const F=U.choices?.[0],N=(typeof F?.message?.content=="string"?F.message.content:"")??"",L=[],q=F?.message?.reasoning_content||F?.message?.reasoning;typeof q=="string"&&q.length>0&&L.push({type:"reasoning",text:q}),N.length>0&&L.push({type:"text",text:N});for(const G of F?.message?.tool_calls??[])L.push({type:"tool-call",toolCallId:G.id,toolName:y?.fromWire.get(G.function.name)??G.function.name,input:G.function.arguments??""});const B=F?.finish_reason;return{content:L,finishReason:{unified:B==="length"?"length":B==="tool_calls"||B==="function_call"?"tool-calls":B==="content_filter"?"content-filter":"stop",raw:B??"stop"},usage:{inputTokens:{total:U.usage?.prompt_tokens,noCache:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,U.usage.prompt_tokens-U.usage.prompt_tokens_details.cached_tokens):U.usage?.prompt_tokens,cacheRead:U.usage?.prompt_tokens!==void 0&&U.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(U.usage.prompt_tokens_details.cached_tokens,U.usage.prompt_tokens):U.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:U.usage?.completion_tokens,text:U.usage?.completion_tokens!==void 0&&U.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,U.usage.completion_tokens-U.usage.completion_tokens_details.reasoning_tokens):U.usage?.completion_tokens,reasoning:U.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:k},response:{...U.id?{id:U.id}:{},...U.model?{modelId:U.model}:{},headers:{},body:U}}},doStream:()=>{throw new Error(`${o}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(Ed(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),s=>this.executeNativeGenerate(s)),o)}async executeNativeGenerate(e){const t=Date.now(),r=await this.resolveModelName(),n=await this.getAISDKModelWithMiddleware(e);if(!yC(n))throw this.handleProviderError(new Error(`${this.providerName}: model handle exposes no doGenerate()`));const o=n.doGenerate.bind(n),s=!e.disableTools&&this.supportsTools(),i=s?e.tools||await this.getAllTools():{},a=s?Object.entries(i).map(([R,I])=>{const P=I;return{type:"function",name:R,description:P.description??"",inputSchema:P.inputSchema?Ao(P.inputSchema):{type:"object",properties:{}}}}):void 0,c=!!a&&a.length>0,l=e.schema?Ao(e.schema):void 0,u=l!==void 0&&c&&this.suppressResponseFormatWithTools(),d=l&&!u?{type:"json",schema:l}:void 0,m=await this.buildMessagesForStream(e),h=[],f=(R,I,P=!0)=>aD({doGenerate:o,...yAt({provider:this.providerName,availableInputTokens:Pc(this.providerName,r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Gt(H_({...P&&a?{tools:a}:{},responseFormat:I}),this.providerName)}),conversation:R,...P&&a?{tools:a}:{},toolsRecord:i,...P&&c&&e.toolChoice?{toolChoice:dD(e,i,!0)}:{},...typeof e.timeout=="number"?{providerOptions:{neurolink:{timeoutMs:e.timeout}}}:{},...I?{responseFormat:I}:{},maxSteps:e.maxSteps||Bs,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:O=>r0(O,lt.getActiveSpan()??void 0,`${this.providerName} generate`).catch(U=>{throw this.handleProviderError(U)})},h);let g;try{g=await f(m,d)}catch(R){if(!(d!==void 0&&(lUr(R)||dCt(R)||uUr(R))))throw R;p.warn(`[${this.providerName}] provider rejected response_format \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r}),g=await f(wv(m,d.schema),void 0)}if(d!==void 0&&e.schema!==void 0&&!TC(g.text,e.schema)){p.warn(`[${this.providerName}] response_format did not yield a schema-valid object \u2014 retrying with the schema in the system prompt`,{provider:this.providerName,model:r});const R=g,I=await f(wv(m,d.schema),void 0);g={...I,inputTokens:R.inputTokens+I.inputTokens,outputTokens:R.outputTokens+I.outputTokens,cacheReadTokens:(R.cacheReadTokens??0)+(I.cacheReadTokens??0),cacheWriteTokens:(R.cacheWriteTokens??0)+(I.cacheWriteTokens??0)}}u&&l&&e.schema&&(g=await this.reformatWithoutTools({toolPhase:g,conversation:m,schemaJson:l,schema:e.schema,runLoop:f,modelId:r,abortSignal:e.abortSignal}));const{text:y,finishReason:v,toolsUsed:w}=g,E=g.inputTokens,_=g.outputTokens,C=g.steps,A=C>=(e.maxSteps||Bs)&&v==="tool-calls"?"step-cap":v==="error"?"provider-error":"completed",k={content:y,provider:this.providerName,model:r,finishReason:v,...g.rawFinishReason?{rawFinishReason:g.rawFinishReason}:{},stopReason:A,stepsUsed:C,usage:{input:E,output:_,total:E+_+g.cacheReadTokens+g.cacheWriteTokens,...g.cacheReadTokens?{cacheReadTokens:g.cacheReadTokens}:{},...g.cacheWriteTokens?{cacheCreationTokens:g.cacheWriteTokens}:{}},responseTime:Date.now()-t,...g.reasoning?{reasoning:g.reasoning}:{},toolsUsed:w,toolCalls:E7(h),toolExecutions:af(e,bd(h)),enhancedWithTools:w.length>0};return this.finalizeNativeGenerate(k,e,t)}async reformatWithoutTools(e){const{toolPhase:t,conversation:r,schemaJson:n,schema:o,runLoop:s,modelId:i,abortSignal:a}=e;let c=t;const l=()=>a?.aborted===!0;if(c.text.trim().length>0&&!l()&&!TC(c.text,o)){p.warn(`[${this.providerName}] tools suppressed response_format and the answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:i});const u={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},d=m=>{u.inputTokens+=m.inputTokens,u.outputTokens+=m.outputTokens,u.cacheReadTokens+=m.cacheReadTokens??0,u.cacheWriteTokens+=m.cacheWriteTokens??0};try{const m=[...r,{role:"assistant",content:t.text},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let h,f=!1;try{h=await s(m,{type:"json",schema:n},!1),d(h)}catch(g){if(l())throw g;p.warn(`[${this.providerName}] the re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i,error:g instanceof Error?g.message:String(g)}),h=await s(wv(m,n),void 0,!1),d(h),f=!0}if(!f&&!l()&&!TC(h.text,o)&&(p.warn(`[${this.providerName}] the re-ask's response_format carried no schema \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:i}),h=await s(wv(m,n),void 0,!1),d(h)),!TC(h.text,o))throw p.warn(`[${this.providerName}] the tool-free re-ask did not yield a schema-valid object either; keeping the original answer`,{provider:this.providerName,model:i}),new lX;c={...h,toolsUsed:[...new Set([...t.toolsUsed,...h.toolsUsed])],inputTokens:t.inputTokens+u.inputTokens,outputTokens:t.outputTokens+u.outputTokens,cacheReadTokens:(t.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(t.cacheWriteTokens??0)+u.cacheWriteTokens,steps:t.steps,...t.finishReason!=="stop"?{finishReason:t.finishReason,rawFinishReason:t.rawFinishReason}:{finishReason:h.finishReason}}}catch(m){if(l()&&!(a?.reason instanceof ma))throw m;m instanceof lX||p.warn(`[${this.providerName}] the tool-free structured-output re-ask failed; keeping the original answer`,{provider:this.providerName,model:i,error:m instanceof Error?m.message:String(m)}),c={...c,inputTokens:c.inputTokens+u.inputTokens,outputTokens:c.outputTokens+u.outputTokens,cacheReadTokens:(c.cacheReadTokens??0)+u.cacheReadTokens,cacheWriteTokens:(c.cacheWriteTokens??0)+u.cacheWriteTokens}}}return c}async resolveStreamStructuredData(e){const{schema:t,schemaJson:r,text:n,conversation:o,modelId:s,abortSignal:i,options:a}=e,c=()=>i?.aborted===!0;if(n.trim().length===0)return;const l=uX(n,t);if(l!==void 0)return{data:l,usage:{inputTokens:0,outputTokens:0}};if(!(!o||c()))try{const u=await this.getAISDKModelWithMiddleware(a);if(!yC(u))return;p.warn(`[${this.providerName}] streamed answer is not schema-valid \u2014 re-asking once without tools`,{provider:this.providerName,model:s});const d=u.doGenerate.bind(u),m={inputTokens:0,outputTokens:0},h=(w,E)=>aD({doGenerate:d,conversation:w,toolsRecord:{},...E?{responseFormat:E}:{},maxSteps:1,...a.maxTokens?{maxOutputTokens:a.maxTokens}:{},...i?{abortSignal:i}:{},runStep:_=>_()},[]).then(_=>(m.inputTokens+=_.inputTokens,m.outputTokens+=_.outputTokens,_)),g=[...o.filter(w=>{if(w.role==="tool")return!1;const E=w.tool_calls;return!(w.role==="assistant"&&Array.isArray(E)&&E.length>0)}),{role:"assistant",content:n},{role:"user",content:"Return that same answer as a single JSON value conforming to the required schema. No prose before or after it, and no markdown code fence."}];let y;try{y=await h(g,{type:"json",schema:r})}catch(w){if(c())throw w;p.warn(`[${this.providerName}] the stream re-ask's response_format was rejected \u2014 retrying with the schema in the prompt`,{provider:this.providerName,model:s,error:w instanceof Error?w.message:String(w)}),y=await h(wv(g,r),void 0)}const v=uX(y.text,t);return v===void 0?(p.warn(`[${this.providerName}] the tool-free stream re-ask did not yield a schema-valid value either; leaving structuredData unset`,{provider:this.providerName,model:s}),{data:void 0,usage:m}):{data:v,usage:m}}catch(u){if(c()&&!(i?.reason instanceof ma))throw u;p.warn(`[${this.providerName}] the tool-free structured-output re-ask failed for a stream; leaving structuredData unset`,{provider:this.providerName,model:s,error:u instanceof Error?u.message:String(u)});return}}async executeStream(e,t){this.validateStreamOptions(e);const r=Date.now(),n=this.getTimeout(e),o=da(n,this.providerName,"stream"),s=new AbortController,i=Bve([e.abortSignal,o?.controller.signal,s.signal]).signal;let a,c,l,u,d,m;try{a=await this.resolveModelName();const ae=!e.disableTools&&this.supportsTools();c=ae?e.tools||await this.getAllTools():{},l=ae?sD(Object.keys(c)):void 0,u=ae?LY(c,l?.toWire):void 0,d=mAt(dD(e,c,ae),l?.toWire),m=await this.buildMessagesForStream(e)}catch(ae){throw o?.cleanup(),ae}const h=e.schema?Ao(e.schema):void 0,f=!!u&&u.length>0,g=h!==void 0&&f&&this.suppressResponseFormatWithTools(),y=h&&!g?this.adjustResponseFormat(UY({type:"json",schema:h}),a):void 0,v=this.getChatCompletionsURL(a),w=Pt(),E=e.maxSteps||Bs,_=this.neurolink?.getEventEmitter(),C=[],A=[],{usagePromise:k,finishPromise:R,resolveUsage:I,resolveFinish:P}=GY(),O=hv(),U=this.onStreamStart(a),M=u?.map(ae=>({type:"function",name:ae.function.name,description:ae.function.description,inputSchema:ae.function.parameters})),F={prompt:m,...M?{tools:M}:{},...e.maxTokens!==void 0?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.topP!==void 0?{topP:e.topP}:{}};let N,L;const q=this.providerName,B={specificationVersion:"v3",provider:q,modelId:a,supportedUrls:{},doGenerate:async ae=>{const Pe=await this.getAISDKModel();if(typeof Pe=="string")throw new Error("Native model handle required");return Pe.doGenerate(ae)},doStream:async ae=>{ae?.tools!==void 0&&ae.tools!==M&&p.warn(`${q}: middleware rewrote 'tools' on the streaming path; tool rewrites are not applied to the wire request yet \u2014 the original tool list was sent.`);const Pe=Array.isArray(ae?.prompt)?ae.prompt:m,ke=NY(Pe,l?.toWire,this.replayReasoningContent());L=ke;const Te={...e,...typeof ae?.maxOutputTokens=="number"?{maxTokens:ae.maxOutputTokens}:{},...typeof ae?.temperature=="number"?{temperature:ae.temperature}:{},...typeof ae?.topP=="number"?{topP:ae.topP}:{}};N=this.runStreamLoop({maxSteps:E,modelId:a,url:v,fetchImpl:w,abortSignal:i,options:Te,conversation:ke,openAITools:u,openAIToolChoice:d,toolsRecord:c,toolNameFromWire:l?.fromWire,emitter:_,toolsUsed:C,toolExecutionSummaries:A,pushChunk:O.push,closeChannel:O.close,resolveUsage:I,resolveFinish:P,responseFormat:y});const he=N.then(()=>Promise.all([k,R]).then(([Oe,De])=>({type:"finish",finishReason:{unified:De},usage:{inputTokens:{total:Oe.promptTokens,cacheRead:Oe.cacheReadTokens},outputTokens:{total:Oe.completionTokens}}})));return he.catch(()=>{}),{stream:rkt(O.iterable,he,()=>s.abort())}}};let H;try{const ae=await this.applyMiddlewareToModel(B,e);if(typeof ae=="string")throw new Error("Native stream model handle required");const{stream:Pe}=await ae.doStream(F);H=w5r(Pe,ke=>{if(!N){const Te=ke.usage.inputTokens.total??0,he=ke.usage.outputTokens.total??0,Oe=Math.min(ke.usage.inputTokens.cacheRead??0,Te);I({promptTokens:Te-Oe,completionTokens:he,totalTokens:Te+he,...Oe>0?{cacheReadTokens:Oe}:{}}),P(ke.finishReason.unified)}})}catch(ae){throw s.abort(),O.close(),o?.cleanup(),ae}let G;const X=ae=>{G=ae};U?.onUsage&&k.then(U.onUsage).catch(()=>{}),U?.onFinish&&R.then(ae=>U.onFinish?.(ae,G)).catch(()=>{});const ce=this.providerName,Q=this,Ae={startTime:r,streamId:`${this.providerName}-${Date.now()}`},le={stream:async function*(){let ae=0,Pe="";try{for await(const ke of H)"content"in ke&&typeof ke.content=="string"&&ke.content.length>0&&(ae++,e.schema&&(Pe+=ke.content)),yield ke;if(await N,Ae.rawFinishReason=await R,e.schema&&h){const ke=await Q.resolveStreamStructuredData({schema:e.schema,schemaJson:h,text:Pe,conversation:L,modelId:a,abortSignal:i,options:e});ke?.data!==void 0&&(Ae.structuredData=ke.data),ke&&(ke.usage.inputTokens>0||ke.usage.outputTokens>0)&&(Ae.structuredDataUsage=ke.usage,p.info(`[${ce}] structured-output re-ask billed separately from the streamed turn`,{provider:ce,model:a,inputTokens:ke.usage.inputTokens,outputTokens:ke.usage.outputTokens}))}if(Ae.finishReason="stop",ae===0&&C.length===0){p.warn(`${ce}: Stream produced no output \u2014 emitting enriched sentinel`);const ke=new cu({message:"Stream produced no output"}),Te=await Mf(ke,void 0,G);Of(Te),yield Te}}catch(ke){if(cu.isInstance(ke)){const he=await Mf(ke,void 0,G);Of(he),yield he;return}const Te=await Mf(ke,void 0,G);throw Of(Te),yield Te,ke}finally{N||(I({promptTokens:0,completionTokens:0,totalTokens:0}),P("stop")),o?.cleanup(),s.signal.aborted||s.abort()}}(),provider:this.providerName,model:a,analytics:ZY.createAnalytics(this.providerName,a,{textStream:(async function*(){})(),usage:k,finishReason:R},Date.now()-r,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:C,metadata:Ae};return Object.defineProperty(le,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>bd(A.map(ae=>({toolName:ae.toolName,input:ae.input,output:ae.output,duration:ae.endTime.getTime()-ae.startTime.getTime()})))}),N?.finally(()=>o?.cleanup()).catch(ae=>{X(ae)}),le}async runStreamLoop(e){const{maxSteps:t,modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,toolsRecord:u,toolNameFromWire:d,emitter:m,toolsUsed:h,toolExecutionSummaries:f,pushChunk:g,closeChannel:y,resolveUsage:v,resolveFinish:w,responseFormat:E}=e;let _=null,C;const A=()=>{const k=C?.prompt_tokens??0,R=C?.completion_tokens??0,I=Math.min(C?.prompt_tokens_details?.cached_tokens??0,k),P=Math.min(Math.max(0,C?.completion_tokens_details?.reasoning_tokens??0),R);return{promptTokens:k-I,completionTokens:R,totalTokens:C?.total_tokens||k+R,...I>0?{cacheReadTokens:I}:{},...P>0?{reasoningTokens:P}:{}}};try{let k=d,R,I;for(let P=0;P<t;P++){if(c){const M=new Set(c.map(N=>k?.get(N.function.name)??N.function.name)),F=Object.fromEntries(Object.entries(u).filter(([N])=>!M.has(N)));if(Object.keys(F).length>0){const N=sD(Object.keys(F),new Set(c.map(L=>L.function.name)));if(N){k??=new Map;for(const[L,q]of N.fromWire)k.set(L,q)}c.push(...LY(F,N?.toWire)??[]),p.info(`${this.providerName}: ${Object.keys(F).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(F).join(", ")}`)}}const O=t5r({conversation:a,availableInputTokens:Pc(this.providerName,r,i.maxTokens??void 0),fixedOverheadTokens:MY([],c,this.providerName),provider:this.providerName,observedPromptTokens:R,previousSentEstimate:I,onSentEstimate:M=>{I=M}});O&&(a.length=0,a.push(...O));const U=await this.streamOneStep({modelId:r,url:n,fetchImpl:o,abortSignal:s,options:i,conversation:a,openAITools:c,openAIToolChoice:l,pushChunk:g,responseFormat:E});if(R=U.usage?.prompt_tokens,_=U.finishReason,U.usage&&(C=fAt(C,U.usage)),U.toolCalls.size===0)break;await this.executeToolBatch({stepResult:U,conversation:a,toolsRecord:u,toolNameFromWire:k,emitter:m,toolsUsed:h,toolExecutionSummaries:f,options:i})}return v(A()),w(_??"stop"),y(),{finishReason:_??"stop",usage:C}}catch(k){throw p.error(`${this.providerName}: Stream error`,{error:k instanceof Error?k.message:String(k)}),v(A()),w("error"),y(),k}}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=BY(this.adjustRequestBody(zY({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.responseFormat?{responseFormat:e.responseFormat}:{}}),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 fC(e.url,n,i);return i};let s;try{s=await r0(o,lt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(i){const a=i,c=a.statusCode===400?(()=>{const l=this.correctBodyAfterContextOverflow(n,a);return this.adjustBodyAfter400(l??n,a)??l})():void 0;if(!c)throw a;if(s=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(c),...e.abortSignal?{signal:e.abortSignal}:{}}),!s.ok)throw await fC(e.url,c,s)}if(!s.body)throw new Error(`${this.providerName}: stream response had no body`);return qY(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:c}=e,l=[];for(const[,d]of t.toolCalls)l.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:l,...this.replayReasoningContent()&&t.reasoning?{reasoning_content:t.reasoning}:{}});for(const[,d]of t.toolCalls){const m=new Date;let h;try{h=JSON.parse(d.argsBuffered||"{}")}catch{h=d.argsBuffered}let f,g;const y=o?.get(d.name)??d.name,v=n[y]??F7(n,y);if(s?.emit("tool:start",{toolName:y,toolCallId:d.id,input:h}),!v||typeof v.execute!="function")g=`Tool '${y}' is not registered.`,f={error:g};else try{f=await v.execute(h,{})}catch(E){g=E instanceof Error?E.message:String(E),f={error:g}}const w=new Date;i.push(y),a.push({toolCallId:d.id,toolName:y,input:h,output:f,...g?{error:g}:{},startTime:m,endTime:w}),r.push({role:"tool",tool_call_id:d.id,content:OY(f)})}const u=a.slice(-t.toolCalls.size);_At(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})),c,new Date)}catch(d){p.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=`${Ca(this.config.baseURL)}/models`;p.debug(`Fetching available models from: ${e}`);const t=Pt(),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 p.warn(`Models endpoint returned ${o.status}: ${o.statusText}`),this.getFallbackModels();const s=await o.json();if(!s.data||!Array.isArray(s.data))return p.warn("Invalid models response format"),this.getFallbackModels();const i=s.data.map(a=>a.id).filter(Boolean);return p.shouldLog("debug")&&p.debug(`Discovered ${i.length} models:`,i),i.length>0?i:this.getFallbackModels()}catch(e){return p.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}}}),dX,nkt,okt,skt,ikt,akt,E5r=b({"src/lib/providers/openAI/client.ts"(){"use strict";Xt(),On(),ut(),z(),Ut(),Ja(),qi(),ts(),_a(),gp(),pa(),vp(),kl(),cd(),dX="https://api.openai.com/v1",nkt=(e,t)=>{const r=[e,t].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??dX;try{const n=new URL(r),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ca(n.toString())}catch{}return r},okt=()=>fa(PCr()),skt=()=>_i("OPENAI_MODEL","gpt-5.4"),ikt=lt.getTracer("neurolink.provider.openai"),akt=class extends Lc{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:okt(),i=nkt(n?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:i,apiKey:s}),p.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:No(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return skt()}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:Mr,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=>Vve(o.error),errorClass:ot,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:$s,message:"OpenAI rate limit exceeded. Please try again later."},{match:o=>/model_not_found/i.test(o.message),errorClass:Oo,message:o=>`Model not found: ${o.modelName}`},..._c];return ha(e,n,this.providerName,this.modelName)}onStreamStart(e){const t=ikt.startSpan("neurolink.provider.streamText",{kind:zr.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=xi(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:Ue.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){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel();p.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const[o]=await this.callEmbeddings(n,[r],"embed");return p.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw p.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel();p.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});try{const n=await this.callEmbeddings(r,e,"embedMany");return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:n.length,embeddingDimension:n[0]?.length}),n}catch(n){throw p.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=`${Ca(this.config.baseURL)}/embeddings`,o=Pt(),s=da(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 l=await i.text().catch(()=>"");let u=`OpenAI ${r} failed with status ${i.status}`,d;if(l)try{const m=JSON.parse(l);m.error?.message&&(u=m.error.message),d=m.error?.type}catch{}throw Object.assign(new Error(u),{status:i.status,type:d})}const c=((await i.json()).data??[]).map(l=>l.embedding).filter(l=>Array.isArray(l));if(c.length===0)throw new ot(`OpenAI ${r} returned no embeddings`,this.providerName);return c}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=Ca(this.config.baseURL??dX),s=e,i=s.size??this.aspectRatioToOpenAISize(s.aspectRatio,n),a=s.numberOfImages??1;let c;n==="gpt-image-1"||n.startsWith("dall-e-3")?c=1:n.startsWith("dall-e-2")?c=Math.min(Math.max(a,1),10):c=1;const u={model:n,prompt:r,n:c,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 f;try{f=await Pt()(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(u),signal:m.signal})}catch(E){throw E instanceof Error&&E.name==="AbortError"?new Error(`OpenAI image generation timed out after ${d/1e3}s`,{cause:E}):E}finally{clearTimeout(h)}if(!f.ok){const E=await f.text();throw new Error(`OpenAI image generation failed: ${f.status} \u2014 ${E}`)}const y=(await f.json()).data?.[0];if(!y)throw new Error("OpenAI image generation returned no images");let v=y.b64_json;if(!v&&y.url){await fp(y.url);const E=Pt(),_=new AbortController,C=setTimeout(()=>_.abort(),6e4);let A;try{A=await E(y.url,{signal:_.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(C)}if(!A.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${y.url} (${A.status})`);v=(await ku(A,hp,"OpenAI image fallback")).toString("base64")}if(!v)throw new Error("OpenAI image generation returned neither b64_json nor a URL");const w=Date.now()-t;return p.info(`[OpenAIProvider] Generated image (${v.length} base64 chars) in ${w}ms \u2014 model ${n}`),{content:y.revised_prompt??r,provider:this.providerName,model:n,usage:{input:0,output:0,total:0},imageOutput:{base64:v}}}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"}}}}),ckt={};ee(ckt,{OpenAIProvider:()=>akt});var S5r=b({"src/lib/providers/openAI/index.ts"(){"use strict";E5r()}});function Fe(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 j(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 tc=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"(){}}),wC,mX=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"(){wC=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return wC=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 Ev(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var EC,Sv=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/errors.mjs"(){EC=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)}}}),it,Mi,Fc,bv,pX,lkt,hX,fX,gX,yX,vX,TX,wX,EX,So=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/error.mjs"(){Sv(),it=class extends Error{},Mi=class Vde extends it{constructor(t,r,n,o,s){super(`${Vde.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 bv({message:n,cause:EC(r)});const s=r,i=s?.error?.type;return t===400?new hX(t,s,n,o,i):t===401?new fX(t,s,n,o,i):t===403?new gX(t,s,n,o,i):t===404?new yX(t,s,n,o,i):t===409?new vX(t,s,n,o,i):t===422?new TX(t,s,n,o,i):t===429?new wX(t,s,n,o,i):t>=500?new EX(t,s,n,o,i):new Vde(t,s,n,o,i)}},Fc=class extends Mi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},bv=class extends Mi{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},pX=class extends bv{constructor({message:e}={}){super({message:e??"Request timed out."})}},lkt=class extends it{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},hX=class extends Mi{},fX=class extends Mi{},gX=class extends Mi{},yX=class extends Mi{},vX=class extends Mi{},TX=class extends Mi{},wX=class extends Mi{},EX=class extends Mi{}}});function SX(e){return typeof e!="object"?{}:e??{}}function ukt(e){if(!e)return!0;for(const t in e)return!1;return!0}function b5r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var dkt,mkt,Ji,bX,pkt,_X,Ud=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"(){So(),dkt=/^[a-z][a-z0-9+.-]*:/i,mkt=e=>dkt.test(e),Ji=e=>(Ji=Array.isArray,Ji(e)),bX=Ji,pkt=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new it(`${e} must be an integer`);if(t<0)throw new it(`${e} must be a positive integer`);return t},_X=e=>{try{return JSON.parse(e)}catch{return}}}}),Tp,SC=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"(){Tp=(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})})}}),Bd,pD=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/version.mjs"(){Bd="0.102.0"}});function _5r(){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 C5r(){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 hkt,fkt,CX,AX,gkt,hD,kX=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"(){pD(),hkt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",fkt=()=>{const e=_5r();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bd,"X-Stainless-OS":AX(Deno.build.os),"X-Stainless-Arch":CX(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":Bd,"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":Bd,"X-Stainless-OS":AX(globalThis.process.platform??"unknown"),"X-Stainless-Arch":CX(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=C5r();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bd,"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":Bd,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},CX=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",AX=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"),hD=()=>gkt??(gkt=fkt())}});function A5r(){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 ykt(...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 vkt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ykt({start(){},async pull(r){const{done:n,value:o}=await t.next();n?r.close():r.enqueue(o)},async cancel(){await t.return?.()}})}function xX(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 k5r(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 bC=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/shims.mjs"(){}}),Tkt,x5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"(){Tkt=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)})}}),IX,RX,PX,wkt,Ekt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"(){IX="RFC3986",RX=e=>String(e),PX={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:RX},wkt="RFC1738"}});function I5r(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Skt(e,t){if(Ji(e)){const r=[];for(let n=0;n<e.length;n+=1)r.push(t(e[n]));return r}return t(e)}var fD,xl,gD,bkt,R5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"(){Ekt(),Ud(),fD=(e,t)=>(fD=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),fD(e,t)),xl=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),gD=1024,bkt=(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+=gD){const c=s.length>=gD?s.slice(a,a+gD):s,l=[];for(let u=0;u<c.length;++u){let d=c.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===wkt&&(d===40||d===41)){l[l.length]=c.charAt(u);continue}if(d<128){l[l.length]=xl[d];continue}if(d<2048){l[l.length]=xl[192|d>>6]+xl[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=xl[224|d>>12]+xl[128|d>>6&63]+xl[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|c.charCodeAt(u)&1023),l[l.length]=xl[240|d>>18]+xl[128|d>>12&63]+xl[128|d>>6&63]+xl[128|d&63]}i+=l.join("")}return i}}});function P5r(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}function _kt(e,t,r,n,o,s,i,a,c,l,u,d,m,h,f,g,y,v){let w=e,E=v,_=0,C=!1;for(;(E=E.get(yD))!==void 0&&!C;){const P=E.get(e);if(_+=1,typeof P<"u"){if(P===_)throw new RangeError("Cyclic object value");C=!0}typeof E.get(yD)>"u"&&(_=0)}if(typeof l=="function"?w=l(t,w):w instanceof Date?w=m?.(w):r==="comma"&&Ji(w)&&(w=Skt(w,function(P){return P instanceof Date?m?.(P):P})),w===null){if(s)return c&&!g?c(t,ls.encoder,y,"key",h):t;w=""}if(P5r(w)||I5r(w)){if(c){const P=g?t:c(t,ls.encoder,y,"key",h);return[f?.(P)+"="+f?.(c(w,ls.encoder,y,"value",h))]}return[f?.(t)+"="+f?.(String(w))]}const A=[];if(typeof w>"u")return A;let k;if(r==="comma"&&Ji(w))g&&c&&(w=Skt(w,c)),k=[{value:w.length>0?w.join(",")||null:void 0}];else if(Ji(l))k=l;else{const P=Object.keys(w);k=u?P.sort(u):P}const R=a?String(t).replace(/\./g,"%2E"):String(t),I=n&&Ji(w)&&w.length===1?R+"[]":R;if(o&&Ji(w)&&w.length===0)return I+"[]";for(let P=0;P<k.length;++P){const O=k[P],U=typeof O=="object"&&typeof O.value<"u"?O.value:w[O];if(i&&U===null)continue;const M=d&&a?O.replace(/\./g,"%2E"):O,F=Ji(w)?typeof r=="function"?r(I,M):I:I+(d?"."+M:"["+M+"]");v.set(e,_);const N=new WeakMap;N.set(yD,v),OX(A,_kt(U,F,r,n,o,s,i,a,r==="comma"&&g&&Ji(w)?null:c,l,u,d,m,h,f,g,y,N))}return A}function M5r(e=ls){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||ls.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=IX;if(typeof e.format<"u"){if(!fD(PX,e.format))throw new TypeError("Unknown format option provided.");r=e.format}const n=PX[r];let o=ls.filter;(typeof e.filter=="function"||Ji(e.filter))&&(o=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in MX?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=ls.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:ls.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:ls.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:ls.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:ls.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?ls.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:ls.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:ls.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:ls.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:ls.encodeValuesOnly,filter:o,format:r,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:ls.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:ls.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:ls.strictNullHandling}}function O5r(e,t={}){let r=e;const n=M5r(t);let o,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Ji(n.filter)&&(s=n.filter,o=s);const i=[];if(typeof r!="object"||r===null)return"";const a=MX[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(r)),n.sort&&o.sort(n.sort);const l=new WeakMap;for(let m=0;m<o.length;++m){const h=o[m];n.skipNulls&&r[h]===null||OX(i,_kt(r[h],h,a,c,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,l))}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 MX,OX,Ckt,ls,yD,D5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"(){R5r(),Ekt(),Ud(),MX={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},OX=function(e,t){Array.prototype.push.apply(e,Ji(t)?t:[t])},ls={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:bkt,encodeValuesOnly:!1,format:IX,formatter:RX,indices:!1,serializeDate(e){return(Ckt??(Ckt=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},yD={}}});function N5r(e){return O5r(e,{arrayFormat:"brackets"})}var Akt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"(){D5r()}});function kkt(e){if(!e)return;let t;try{t=new URL(e)}catch(n){throw new Dn(`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 Dn(`Refusing to send credential over non-https token endpoint "${e}"`)}async function xkt(e,t){const r=await L5r(e);let n;try{n=JSON.parse(r)}catch{throw new Dn(`Token endpoint returned non-JSON response (status ${e.status})`,e.status,$c(r),t)}if(!n.access_token)throw new Dn(`Token endpoint response missing access_token: ${JSON.stringify($c(n))}`,e.status,$c(n),t);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new Dn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,e.status,$c(n),t);return n}function $c(e){if(e==null)return e;if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{return e.length<=TD?e:e.slice(0,TD)+`... <${e.length-TD} more chars>`}return JSON.stringify($c(t))}if(typeof e=="object"&&!Array.isArray(e)){const t={};for(const[r,n]of Object.entries(e))Lkt.has(r)&&(t[r]=n);return t}return null}async function Ikt(e,t=r=>console.warn(`anthropic-sdk: ${r}`)){if(typeof process>"u"||process.platform==="win32")return;const r=await Promise.resolve().then(()=>(Pn(),hd));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 Dn(`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 Dn(`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 Rkt(e,t){const r=await Promise.resolve().then(()=>(Pn(),hd)),o=(await Promise.resolve().then(()=>(zt(),jm))).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 L5r(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>NX){const a=NX-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 Pkt,Mkt,DX,_C,Okt,Dkt,vD,Nkt,NX,TD,Lkt,Dn,CC=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"(){So(),Pkt="urn:ietf:params:oauth:grant-type:jwt-bearer",Mkt="refresh_token",DX="/v1/oauth/token",_C="oauth-2025-04-20",Okt="oidc-federation-2026-04-01",Dkt=120,vD=30,Nkt=5,NX=1<<20,TD=2e3,Lkt=new Set(["error","error_description","error_uri"]),Dn=class extends it{constructor(e,t=null,r=null,n=null){super(e),this.statusCode=t,this.body=r,this.requestId=n}}}});function Vf(){return Math.floor(Date.now()/1e3)}var wD=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"(){}}),Fkt,F5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"(){CC(),wD(),Fkt=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-Vf();return r>Dkt?t.token:r>vD?(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||Vf()-this.lastAdvisoryError<Nkt||this.doRefresh().catch(e=>{this.lastAdvisoryError=Vf(),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}}}}),Sr,ED=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"(){Sr=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 $5r(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 LX(e){let t;return(Ukt??(t=new globalThis.TextEncoder,Ukt=t.encode.bind(t)))(e)}function $kt(e){let t;return(Bkt??(t=new globalThis.TextDecoder,Bkt=t.decode.bind(t)))(e)}var Ukt,Bkt,FX=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"(){}}),U5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"(){So(),FX()}});function AC(){}function SD(e,t,r){return!t||kC[e]>kC[r]?AC:t[e].bind(t)}function bo(e){const t=e.logger,r=e.logLevel??"off";if(!t)return zkt;const n=UX.get(t);if(n&&n[0]===r)return n[1];const o={error:SD("error",t,r),warn:SD("warn",t,r),info:SD("info",t,r),debug:SD("debug",t,r)};return UX.set(t,[r,o]),o}var kC,$X,zkt,UX,zd,wp=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"(){Ud(),kC={off:0,error:200,warn:300,info:400,debug:500},$X=(e,t,r)=>{if(e){if(b5r(kC,e))return e;bo(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(kC))}`)}},zkt={error:AC,warn:AC,info:AC,debug:AC},UX=new WeakMap,zd=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)}}),qkt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/utils.mjs"(){Ud(),U5r(),ED(),wp(),mX(),SC(),Akt()}});function Gkt(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(!jkt.test(e))throw new Error(`profile name "${e}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var BX,jkt,Hkt,Vkt,bD,Wkt,zX,Kkt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/credentials.mjs"(){kX(),qkt(),BX="1.0",jkt=/^[A-Za-z0-9_.-]+$/,Hkt=async e=>{var t,r;const n=await bD();if(n===null)return null;const o=e??await zX();if(o===null)return null;Gkt(o);const s=await Promise.resolve().then(()=>(Pn(),hd)),a=(await Promise.resolve().then(()=>(zt(),jm))).join(n,"configs",`${o}.json`);let c;try{c=await s.promises.readFile(a,"utf-8")}catch(d){if(d?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${d}`);c=null}if(c===null){const d=Sr("ANTHROPIC_ORGANIZATION_ID"),m=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE"),h=Sr("ANTHROPIC_FEDERATION_RULE_ID");return h&&d?{fromFile:!1,config:{organization_id:d,workspace_id:Sr("ANTHROPIC_WORKSPACE_ID"),base_url:Sr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:h,service_account_id:Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Sr("ANTHROPIC_SCOPE")}}}:null}let l;try{l=JSON.parse(c)}catch(d){throw new Error(`failed to parse config file ${a}: ${d}`)}if(!l.authentication)throw new Error(`config file ${a} is missing "authentication"`);const u=l.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(l.organization_id??(l.organization_id=Sr("ANTHROPIC_ORGANIZATION_ID")),l.workspace_id??(l.workspace_id=Sr("ANTHROPIC_WORKSPACE_ID")),l.base_url??(l.base_url=Sr("ANTHROPIC_BASE_URL")),(t=l.authentication).scope??(t.scope=Sr("ANTHROPIC_SCOPE")),l.authentication.type==="oidc_federation"){if(!l.authentication.identity_token){const d=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");d&&(l.authentication.identity_token={source:"file",path:d})}l.authentication.federation_rule_id||(l.authentication.federation_rule_id=Sr("ANTHROPIC_FEDERATION_RULE_ID")??""),(r=l.authentication).service_account_id??(r.service_account_id=Sr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:l,fromFile:!0}},Vkt=async(e,t)=>{if(e?.authentication.credentials_path)return e.authentication.credentials_path;const r=await bD();if(!r)return null;const n=t??await zX();return n?(Gkt(n),(await Promise.resolve().then(()=>(zt(),jm))).join(r,"credentials",`${n}.json`)):null},bD=async()=>{if(!Wkt())return null;const e=await Promise.resolve().then(()=>(zt(),jm)),t=Sr("ANTHROPIC_CONFIG_DIR");if(t)return t;if(hD()["X-Stainless-OS"]==="Windows"){const s=Sr("APPDATA");if(s)return e.join(s,"Anthropic");const i=Sr("USERPROFILE");return i?e.join(i,"AppData","Roaming","Anthropic"):null}const n=Sr("XDG_CONFIG_HOME");if(n)return e.join(n,"anthropic");const o=Sr("HOME");return o?e.join(o,".config","anthropic"):null},Wkt=()=>{const e=hD()["X-Stainless-Runtime"];return e==="node"||e==="deno"},zX=async()=>{const e=await bD();if(!e)return null;const t=Sr("ANTHROPIC_PROFILE");if(t)return t;const r=await Promise.resolve().then(()=>(Pn(),hd)),o=(await Promise.resolve().then(()=>(zt(),jm))).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 Jkt(e){if(!e)throw new it("Identity token file path is empty");return async()=>{const t=await Promise.resolve().then(()=>(Pn(),hd));let r;try{r=await t.promises.readFile(e,"utf-8")}catch(o){throw new it(`Failed to read identity token file at ${e}: ${o}`)}const n=r.trim();if(!n)throw new it(`Identity token file at ${e} is empty`);return n}}function B5r(e){if(!e)throw new it("Identity token value is empty");return()=>e}var z5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"(){So()}});function q5r(e){return async()=>{kkt(e.baseURL);const t=await e.identityTokenProvider();if(t.length>16*1024)throw new Dn(`Identity token is ${Math.ceil(t.length/1024)} KiB, exceeds the 16 KiB assertion limit`);const r={grant_type:Pkt,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}${DX}`;let o;try{o=await e.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${_C},${Okt}`,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Bd} oidcFederationProvider`},body:JSON.stringify(r)})}catch(c){throw new Dn(`Failed to reach token endpoint ${n}: ${c}`)}const s=o.headers.get("Request-Id");if(!o.ok){const c=await o.text().catch(()=>""),l=$c(c);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 Dn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${l}${u}`,o.status,l,s)}const i=await xkt(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new Dn(`Token endpoint response missing required fields: ${JSON.stringify($c(i))}`,o.status,$c(i),s);return{token:i.access_token,expiresAt:Vf()+a}}}var G5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"(){CC(),wD(),pD()}});function j5r(e){return async t=>{const r=await Promise.resolve().then(()=>(Pn(),hd));await Ikt(e.credentialsPath,e.onSafetyWarning);let n;try{n=await r.promises.readFile(e.credentialsPath,"utf-8")}catch(y){throw new Dn(`Credentials file not found at ${e.credentialsPath}: ${y}`)}let o;try{o=JSON.parse(n)}catch(y){throw new Dn(`Credentials file at ${e.credentialsPath} is not valid JSON: ${y}`)}const s=o.access_token;if(!s)throw new Dn(`Credentials file at ${e.credentialsPath} must include 'access_token'`);const i=o.expires_at;if(!t?.forceRefresh&&(i==null||Vf()<i-vD))return{token:s,expiresAt:i??null};const a=o.refresh_token;if(!e.clientId||!a)throw new Dn(`Access token at ${e.credentialsPath} has expired and no refresh is available (client_id ${e.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);kkt(e.baseURL);const c={grant_type:Mkt,refresh_token:a,client_id:e.clientId},l=`${e.baseURL}${DX}`;let u;try{u=await e.fetch(l,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":_C,"User-Agent":e.userAgent||`anthropic-sdk-typescript/${Bd} userOAuthProvider`},body:JSON.stringify(c)})}catch(y){throw new Dn(`User OAuth refresh failed to reach token endpoint: ${y}`)}const d=u.headers.get("Request-Id");if(!u.ok){const y=await u.text().catch(()=>"");throw new Dn(`User OAuth refresh failed (HTTP ${u.status}): ${$c(y)}`,u.status,$c(y),d)}const m=await xkt(u,d),h=Number(m.expires_in);if(!Number.isFinite(h))throw new Dn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify($c(m))}`,u.status,$c(m),d);const f=Vf()+h,g=m.refresh_token||a;return await Rkt(e.credentialsPath,{...o,version:BX,type:"oauth_token",access_token:m.access_token,expires_at:f,refresh_token:g}),{token:m.access_token,expiresAt:f}}}var H5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"(){Kkt(),CC(),wD(),pD()}});function Ykt(e,t){const r=e.authentication.credentials_path??null,n=(e.base_url||t.baseURL).replace(/\/+$/,""),o=W5r(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 V5r(e,t){const r=await Hkt(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 Vkt(n,t)??void 0}};return Ykt(s,e)}function W5r(e,t,r,n){switch(e.authentication.type){case"oidc_federation":{const o=e.authentication,s=K5r(o);if(!s)throw new Dn("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 Dn("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 Dn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");const i=q5r({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?J5r(i,t,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!t)throw new Dn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return j5r({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 Dn(`authentication.type "${o}" is not a known authentication type`)}}}function K5r(e){if(e.identity_token){const n=e.identity_token.source;if(n!=="file")throw new Dn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!e.identity_token.path)throw new Dn('identity_token.source "file" requires a non-empty path');return Jkt(e.identity_token.path)}const t=Sr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(t)return Jkt(t);const r=Sr("ANTHROPIC_IDENTITY_TOKEN");return r?B5r(r):null}function J5r(e,t,r,n){return async o=>{const s=await Promise.resolve().then(()=>(Pn(),hd));await Ikt(t,n);let i;try{const c=await s.promises.readFile(t,"utf-8");i=JSON.parse(c);const l=i?.access_token;if(l&&!o?.forceRefresh){const u=i?.expires_at;if(u==null||Vf()<u-vD)return{token:l,expiresAt:u??null}}}catch(c){c?.code!=="ENOENT"&&!(c instanceof SyntaxError)&&r?.(c)}const a=await e(o);try{await Rkt(t,{...i??{},version:BX,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(c){r?.(c)}return a}}var Y5r=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"(){ED(),Kkt(),CC(),wD(),z5r(),G5r(),H5r()}});function X5r(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 Z5r(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 rc,nc,_v,Xkt=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"(){tc(),FX(),_v=class{constructor(){rc.set(this,void 0),nc.set(this,void 0),Fe(this,rc,new Uint8Array,"f"),Fe(this,nc,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?LX(e):e;Fe(this,rc,$5r([j(this,rc,"f"),t]),"f");const r=[];let n;for(;(n=X5r(j(this,rc,"f"),j(this,nc,"f")))!=null;){if(n.carriage&&j(this,nc,"f")==null){Fe(this,nc,n.index,"f");continue}if(j(this,nc,"f")!=null&&(n.index!==j(this,nc,"f")+1||n.carriage)){r.push($kt(j(this,rc,"f").subarray(0,j(this,nc,"f")-1))),Fe(this,rc,j(this,rc,"f").subarray(j(this,nc,"f")),"f"),Fe(this,nc,null,"f");continue}const o=j(this,nc,"f")!==null?n.preceding-1:n.preceding,s=$kt(j(this,rc,"f").subarray(0,o));r.push(s),Fe(this,rc,j(this,rc,"f").subarray(n.index),"f"),Fe(this,nc,null,"f")}return r}flush(){return j(this,rc,"f").length?this.decode(`
|
|
1055
1055
|
`):[]}},rc=new WeakMap,nc=new WeakMap,_v.NEWLINE_CHARS=new Set([`
|
|
1056
1056
|
`,"\r"]),_v.NEWLINE_REGEXP=/\r\n|[\n\r]/g}});async function*Q5r(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new it("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 it("Attempted to iterate over a response with no body");const r=new Zkt,n=new _v,o=xX(e.body);for await(const s of e6r(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*e6r(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"?LX(r):r;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let s;for(;(s=Z5r(t))!==-1;)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}function t6r(e,t){const r=e.indexOf(t);return r!==-1?[e.substring(0,r),t,e.substring(r+t.length)]:[e,"",""]}var xC,Wf,Zkt,qX=b({"node_modules/.pnpm/@anthropic-ai+sdk@0.102.0_zod@4.3.6/node_modules/@anthropic-ai/sdk/core/streaming.mjs"(){tc(),So(),bC(),Xkt(),bC(),Sv(),Ud(),FX(),wp(),So(),Wf=class mI{constructor(t,r,n){this.iterator=t,xC.set(this,void 0),this.controller=r,Fe(this,xC,n,"f")}static fromSSEResponse(t,r,n){let o=!1;const s=n?bo(n):console;async function*i(){if(o)throw new it("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const c of Q5r(t,r)){if(c.event==="completion")try{yield JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}if(c.event==="message_start"||c.event==="message_delta"||c.event==="message_stop"||c.event==="content_block_start"||c.event==="content_block_delta"||c.event==="content_block_stop"||c.event==="message"||c.event==="user.message"||c.event==="user.interrupt"||c.event==="user.tool_confirmation"||c.event==="user.custom_tool_result"||c.event==="user.tool_result"||c.event==="agent.message"||c.event==="agent.thinking"||c.event==="agent.tool_use"||c.event==="agent.tool_result"||c.event==="agent.mcp_tool_use"||c.event==="agent.mcp_tool_result"||c.event==="agent.custom_tool_use"||c.event==="agent.thread_context_compacted"||c.event==="session.status_running"||c.event==="session.status_idle"||c.event==="session.status_rescheduled"||c.event==="session.status_terminated"||c.event==="session.error"||c.event==="session.deleted"||c.event==="session.updated"||c.event==="span.model_request_start"||c.event==="span.model_request_end"||c.event==="span.outcome_evaluation_start"||c.event==="span.outcome_evaluation_ongoing"||c.event==="span.outcome_evaluation_end"||c.event==="user.define_outcome"||c.event==="agent.thread_message_received"||c.event==="agent.thread_message_sent"||c.event==="agent.session_thread_message_received"||c.event==="agent.session_thread_message_sent"||c.event==="session.thread_created"||c.event==="session.thread_status_created"||c.event==="session.thread_status_running"||c.event==="session.thread_status_idle"||c.event==="session.thread_status_rescheduled"||c.event==="session.thread_status_terminated")try{yield JSON.parse(c.data)}catch(l){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),l}if(c.event!=="ping"&&c.event==="error"){const l=_X(c.data)??c.data,u=l?.error?.type;throw new Mi(void 0,l,void 0,t.headers,u)}}a=!0}catch(c){if(Ev(c))return;throw c}finally{a||r.abort()}}return new mI(i,r,n)}static fromReadableStream(t,r,n){let o=!1;async function*s(){const a=new _v,c=xX(t);for await(const l of c)for(const u of a.decode(l))yield u;for(const l of a.flush())yield l}async function*i(){if(o)throw new it("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(const c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(Ev(c))return;throw c}finally{a||r.abort()}}return new mI(i,r,n)}[(xC=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 mI(()=>o(t),this.controller,j(this,xC,"f")),new mI(()=>o(r),this.controller,j(this,xC,"f"))]}toReadableStream(){const t=this;let r;return ykt({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=LX(JSON.stringify(o)+`
|
|
1057
1057
|
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await r.return?.()}})}},Zkt=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(`
|
|
@@ -1109,21 +1109,21 @@ ${r[0].text}`;const n=r.length-1;r[n].text=`${r[n].text}
|
|
|
1109
1109
|
IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`}});function oqr(e,t){switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return t?"tool-calls":"stop"}}async function sqr({params:e,client:t,channel:r,stepSignal:n,requestTimeoutSignal:o,noteObservedPromptTokens:s,finalResultToolName:i,onTerminalResult:a,requireTerminalEvent:c}){const l=await t.messages.create({...e,stream:!0},{signal:n}),u=new Map,d=new Map,m=new Map,h=new Map;let f="",g="",y,v=0,w=0,E=0,_=0,C=0,A=0,k=0,R=0,I=0,P=!1;for await(const B of l){if(n.aborted)break;const H=B;if(H.type==="message_start"){const G=H.message?.usage;v+=G?.input_tokens??0;const X=G?.output_tokens??0;w+=X-k,k=X;const ce=G?.output_tokens_details?.thinking_tokens??0;R+=ce-I,I=ce,E+=G?.cache_read_input_tokens??0,_+=G?.cache_creation_input_tokens??0,C+=G?.cache_creation?.ephemeral_5m_input_tokens??0,A+=G?.cache_creation?.ephemeral_1h_input_tokens??0,s?.((G?.input_tokens??0)+(G?.cache_read_input_tokens??0)+(G?.cache_creation_input_tokens??0));continue}if(H.type==="content_block_start"){const G=H.index??0;if(H.content_block?.type==="redacted_thinking"){const X=H.content_block.data;typeof X=="string"&&h.set(G,X)}H.content_block?.type==="tool_use"&&d.set(G,{id:H.content_block.id??"",name:H.content_block.name??"",inputJson:""});continue}if(H.type==="content_block_delta"){const G=H.index??0,X=H.delta;if(X?.type==="text_delta"&&X.text)f+=X.text,u.set(G,(u.get(G)??"")+X.text),r.push({content:X.text});else if(X?.type==="thinking_delta"&&X.thinking){const ce=m.get(G)??{text:"",signature:""};ce.text+=X.thinking,m.set(G,ce),g+=X.thinking,r.push({content:"",reasoning:X.thinking})}else if(X?.type==="signature_delta"&&X.signature){const ce=m.get(G)??{text:"",signature:""};ce.signature+=X.signature,m.set(G,ce)}else if(X?.type==="input_json_delta"&&X.partial_json){const ce=d.get(G);ce&&(ce.inputJson+=X.partial_json)}continue}if(H.type==="message_delta"){y=H.delta?.stop_reason??y;const G=H.usage?.output_tokens??k;w+=G-k,k=G;const X=H.usage?.output_tokens_details?.thinking_tokens??I;R+=X-I,I=X;continue}H.type==="message_stop"&&(P=!0)}if(o?.aborted)throw o.reason;if(c&&!P&&!n.aborted)throw new Me({code:"ANTHROPIC_STREAM_TRUNCATED",message:"Anthropic stream ended before its terminal message_stop event; the turn is incomplete and its content blocks were not dispatched.",category:"network",severity:"high",retriable:!1,context:{provider:"anthropic",rawStopReason:y}});const O=B=>{if(!B)return{};try{const H=JSON.parse(B);return typeof H=="object"&&H!==null&&!Array.isArray(H)?H:{}}catch{return{}}},U=[],M=new Set([...u.keys(),...d.keys(),...m.keys(),...h.keys()]);for(const B of[...M].sort((H,G)=>H-G)){const H=h.get(B);H&&U.push({type:"redacted_thinking",data:H});const G=m.get(B);G?.text&&G.signature&&U.push({type:"thinking",thinking:G.text,signature:G.signature});const X=u.get(B);X&&U.push({type:"text",text:X});const ce=d.get(B);ce&&U.push({type:"tool_use",id:ce.id,name:ce.name,input:O(ce.inputJson)})}const F=[...d.values()].map(B=>({id:B.id,name:B.name,args:O(B.inputJson)})),N=i?[...d.values()].find(B=>B.name===i):void 0,L=N?[]:F,q=N?nqr(N.inputJson):f;return N&&a?.(q),{text:q,...g?{reasoning:g}:{},toolCalls:L,usage:{inputTokens:v,outputTokens:w,cacheReadTokens:E,cacheWriteTokens:_,...C?{cacheWrite5mTokens:C}:{},...A?{cacheWrite1hTokens:A}:{},...R?{reasoningTokens:R}:{}},rawStopReason:y,raw:U}}function EQ(e){return{providerLabel:"anthropic",maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},...e.planReclaim?{planReclaim:(t,r)=>e.planReclaim?.(t,r)}:{},resolveToolOnMiss:t=>{const n=F7(e.toolsRecord,t)?.execute;if(n)return{execute:async(o,s)=>n(o,s)}},buildStepRequest(t,r){return{raw:e.buildParams(t,r)}},async executeStep(t,r,n){const o=t.raw,s=e.requestTimeoutMs?da(e.requestTimeoutMs,"anthropic","stream"):null,i=F1(n,s?.controller.signal);try{return await sqr({params:o,client:e.client,channel:r,stepSignal:i.signal??n,requestTimeoutSignal:s?.controller.signal,...e.noteObservedPromptTokens?{noteObservedPromptTokens:e.noteObservedPromptTokens}:{},...e.finalResultToolName?{finalResultToolName:e.finalResultToolName}:{},...e.onTerminalResult?{onTerminalResult:e.onTerminalResult}:{},...e.requireTerminalEvent?{requireTerminalEvent:e.requireTerminalEvent}:{}})}finally{i.dispose(),s?.cleanup()}},appendPlanningNudge(t,r){const n={type:"text",text:r},o=t[t.length-1];if(o?.role==="user"&&Array.isArray(o.content)){const i={...o,content:[...o.content,n]};return[...t.slice(0,-1),i]}const s={role:"user",content:[n]};return[...t,s]},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw.filter(i=>i.type!=="server_tool_use")},s={role:"user",content:n.map(i=>({type:"tool_result",tool_use_id:i.id,content:i.error?`Error executing tool ${i.name}: ${i.error}`:wQ(i.output),...i.error?{is_error:!0}:{}}))};return[...t,o,s]},mapFinishReason:oqr}}var zMt=b({"src/lib/providers/anthropic/loopAdapter.ts"(){"use strict";i_(),LMt(),BMt(),pa(),Ze()}});function SQ(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70)return"image/gif";if(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)return"image/webp"}function AN(e,t){if(e instanceof ArrayBuffer)return AN(new Uint8Array(e),t);if(e instanceof Uint8Array)return{type:"image",source:{type:"base64",media_type:kN(t)??SQ(e)??"image/png",data:Buffer.from(e).toString("base64")}};if(typeof e!="string"&&!(e instanceof URL))return;const r=e instanceof URL?e.toString():e,n=r.match(/^data:(image\/[a-z0-9+.-]+);base64,(.+)$/i);if(n){const s=kN(n[1])??_Q(n[2]);return s?{type:"image",source:{type:"base64",media_type:s,data:n[2]}}:void 0}return/^https?:\/\//i.test(r)?{type:"image",source:{type:"url",url:r}}:{type:"image",source:{type:"base64",media_type:kN(t)??_Q(r)??"image/png",data:r}}}function iqr(e){const t=e?.data;if(t==null)return;const r=typeof e.mediaType=="string"?e.mediaType.toLowerCase().split(";")[0].trim():"";if(bQ.has(r)||r==="image/jpg")return AN(t,r);if(r==="application/pdf")return CQ(t);const n=t instanceof ArrayBuffer?new Uint8Array(t):t instanceof Uint8Array?t:void 0;if(n&&SQ(n))return AN(n)}var bQ,kN,qMt,_Q,CQ,aqr=b({"src/lib/providers/anthropicImageBlocks.ts"(){"use strict";bQ=new Set(["image/jpeg","image/png","image/gif","image/webp"]),kN=e=>{if(!e)return;const t=e.toLowerCase().split(";")[0].trim();return t==="image/jpg"?"image/jpeg":bQ.has(t)?t:void 0},qMt=32,_Q=e=>{try{return SQ(Buffer.from(e.slice(0,qMt),"base64"))}catch{return}},CQ=e=>{if(e instanceof ArrayBuffer)return CQ(new Uint8Array(e));if(e instanceof Uint8Array)return{type:"document",source:{type:"base64",media_type:"application/pdf",data:Buffer.from(e).toString("base64")}};if(e instanceof URL)return{type:"document",source:{type:"url",url:e.toString()}};if(typeof e=="string"){const t=e.match(/^data:application\/pdf;base64,(.+)$/i);return t?{type:"document",source:{type:"base64",media_type:"application/pdf",data:t[1]}}:/^https?:\/\//i.test(e)?{type:"document",source:{type:"url",url:e}}:{type:"document",source:{type:"base64",media_type:"application/pdf",data:e}}}}}}),xN,GMt=b({"src/lib/providers/anthropic/constants.ts"(){"use strict";xN={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")}}}),AQ,Vv,jMt,kQ,HMt,VMt,xQ,IQ,RQ,PQ,WMt,cqr=b({"src/lib/providers/anthropic/client.ts"(){"use strict";ERt(),Xt(),on(),Ri(),hr(),lA(),Y3(),ec(),Lo(),bAt(),wMt(),Uzr(),On(),Jzr(),ut(),qi(),z(),QJ(),OMt(),bl(),Ko(),Ut(),TQ(),Ja(),LMt(),zMt(),Md(),ZO(),eX(),cd(),tf(),Zm(),Ic(),ts(),pa(),$f(),tkt(),CAt(),$m(),DK(),ui(),GJ(),aqr(),ud(),vp(),fv(),pY(),GMt(),wCt(),TAt(),BMt(),wMt(),AQ=()=>fa(RCr()),Vv=()=>_i("ANTHROPIC_MODEL","claude-sonnet-4-6"),jMt=lt.getTracer("neurolink.provider.anthropic"),kQ=()=>{try{const t=kt(Ii(),".neurolink","anthropic-credentials.json");if(Gs(t)){const r=md(t,"utf-8"),n=JSON.parse(r);if(n.type==="oauth"&&n.oauth?.accessToken)return p.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(t){p.debug("[AnthropicProvider] Failed to read stored credentials:",t)}const e=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!e)return null;try{const t=JSON.parse(e);if(typeof t=="object"&&t.accessToken)return t;if(typeof t=="string")return{accessToken:t}}catch{}return{accessToken:e}},HMt=e=>{const t=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(t){const r=["free","pro","max","max_5","max_20","api"];if(r.includes(t))return p.debug("[detectSubscriptionTier] Using environment override",{tier:t}),t;p.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:t,validTiers:r})}if(e){const r=e.scopes??[];let n="pro";return r.includes("max_20")?n="max_20":r.includes("max_5")?n="max_5":r.includes("max")&&(n="max"),p.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:r}),n}return p.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},VMt=e=>{const t=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(t==="api_key"||t==="apikey")return p.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(t==="oauth"){if(e)return p.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";p.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else t&&p.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:t});const r=e?"oauth":"api_key";return p.debug("[detectAuthMethod] Auth method resolved",{method:r,hasOAuthToken:!!e}),r},xQ=e=>{const t=[],r=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{const c=Fd(a);if(c&&i.length>0){const l=i[i.length-1];l.cache_control=c}};for(const i of e)switch(i.role){case"system":{const a=typeof i.content=="string"?i.content:n(i.content).map(l=>typeof l=="string"?l:String(l?.text??"")).join(`
|
|
1110
1110
|
`),c=Fd(i);t.push({type:"text",text:a,...c?{cache_control:c}:{}});break}case"user":{const a=[];for(const c of n(i.content)){if(typeof c=="string"){c.length>0&&a.push({type:"text",text:c});continue}const l=c;if(l?.type==="text"&&typeof l.text=="string"){const u=Fd(l);a.push({type:"text",text:l.text,...u?{cache_control:u}:{}})}else if(l?.type==="image"||l?.type==="image_url"){const u=AN(l.image??l.data??l.url);if(u){const d=Fd(l);a.push(d?{...u,cache_control:d}:u)}}else if(l?.type==="file"){const d=typeof l=="object"&&l!==null&&("mediaType"in l?typeof l.mediaType=="string":!0)?iqr(l):void 0;if(d){const m=Fd(l);m&&(d.cache_control=m),a.push(d)}}}a.length>0&&(o(a,i),r.push({role:"user",content:a}));break}case"assistant":{const a=[];for(const c of n(i.content)){if(typeof c=="string"){c.length>0&&a.push({type:"text",text:c});continue}const l=c;if(l?.type==="reasoning"){const u=l.providerOptions?.anthropic,d=u?.redactedData;if(typeof d=="string"&&d.length>0){a.push({type:"redacted_thinking",data:d});continue}const m=u?.signature;typeof m=="string"&&m.length>0&&typeof l.text=="string"&&l.text.length>0&&a.push({type:"thinking",thinking:l.text,signature:m});continue}if(l?.type==="text"&&typeof l.text=="string"){if(l.text.length>0){const u=Fd(l);a.push({type:"text",text:l.text,...u?{cache_control:u}:{}})}}else if(l?.type==="tool-call"){let u=l.input;if(typeof u=="string")try{u=JSON.parse(u)}catch{u={}}a.push({type:"tool_use",id:l.toolCallId??"",name:l.toolName??"",input:u??{}})}}a.length>0&&(o(a,i),r.push({role:"assistant",content:a}));break}case"tool":{const a=[];if(Array.isArray(i.content))for(const c of i.content){const l=c;l?.type==="tool-result"&&a.push({type:"tool_result",tool_use_id:l.toolCallId??"",content:wQ(l.output)})}else typeof i.content=="string"&&a.push({type:"tool_result",tool_use_id:i.toolCallId??"",content:i.content});a.length>0&&r.push({role:"user",content:a});break}}const s=t.length===0?void 0:t.some(i=>i.cache_control)?t:t.map(i=>i.text).join(`
|
|
1111
1111
|
|
|
1112
|
-
`);return{...s!==void 0?{system:s}:{},messages:r}},IQ=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},RQ=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},PQ=6e5,WMt=class extends ba{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),s=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??kQ(),i=o?"api_key":r?.authMethod??VMt(s),a=r?.subscriptionTier??(i==="oauth"?HMt(s):"api"),c=e||Vv();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!mQ(c,a)&&(l=pQ(a),p.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:a,recommendedModel:l})),super(l,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=s,this.subscriptionTier=a,this.authMethod=i;const d=this.getAuthHeaders();let m;if(p.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){p.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const h=this.oauthToken,f=$zr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new tg({apiKey:"oauth-authenticated",fetch:CMt(f),timeout:PQ,maxRetries:0}),p.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),p.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const h=n?.apiKey??r?.apiKey??AQ(),f=(()=>{const g=process.env.ANTHROPIC_BASE_URL;if(!g)return;const y=g.replace(/\/+$/,""),v=y.replace(/\/v\d+$/,"");return v!==y&&p.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:No(g),rewrittenTo:No(v)}),v})();m=new tg({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:CMt(Pt()),timeout:PQ,maxRetries:0}),p.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},p.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?xN["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...cA,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=xN["anthropic-beta"];return t&&(e["User-Agent"]=rg),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return p.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=mQ(e,this.subscriptionTier);return t||p.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return hQ(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){p.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){p.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+zme;if(!t&&!r){p.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Mr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);p.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}p.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const i=new AbortController,a=setTimeout(()=>i.abort(),3e4),c=await fetch(aA,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":rg},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:uQ}),signal:i.signal});if(clearTimeout(a),!c.ok){const d=await c.text();throw new Mr(`Failed to refresh OAuth token: ${c.status} ${d}`,this.providerName)}const l=await c.json();n.accessToken=l.access_token,n.refreshToken=l.refresh_token||n.refreshToken,n.expiresAt=l.expires_in?Date.now()+l.expires_in*1e3:void 0,n.tokenType=l.token_type||"Bearer";const u=n;try{const d=kt(Ii(),".neurolink");Gs(d)||Wq(d,{recursive:!0});const m=kt(d,"anthropic-credentials.json"),h=`${m}.tmp`,g={...Gs(m)?JSON.parse(md(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};Q1(h,JSON.stringify(g,null,2),{mode:384}),Jq(h,m),p.debug("Refreshed OAuth credentials persisted to disk")}catch(d){p.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}p.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!l.refresh_token,expiresIn:l.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof Mr?s:new Mr(`Failed to refresh OAuth token: ${s instanceof Error?s.message:String(s)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&p.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&p.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return Vv()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||Vv(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=xQ(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(q=>q.type==="function").map(q=>{const B=Fd(q);return{name:q.name,...q.description?{description:q.description}:{},input_schema:q.inputSchema??{type:"object",properties:{}},...B?{cache_control:B}:{}}});u&&u.length===0&&(u=void 0);const d=T5r(i.toolChoice);let m=d?IQ(d):void 0,h;if(i.responseFormat?.type==="json"){h=i.responseFormat.name??"json";const q=i.responseFormat.schema??{type:"object"};u=[{name:h,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:q}],m={type:"tool",name:h}}const f=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!h&&f){const q=FMt(u,f);u=q.tools,g=q.applied,q.applied&&(l=$Mt(l))}const y=i.providerOptions?.anthropic?.thinking;u=mY(u);const v=vQ({system:l,tools:u,messages:c}),w=DMt(c,_N-v),E=hl("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate");y&&(E.temperature!==void 0||E.topP!==void 0)&&p.debug("[anthropic] extended thinking is enabled, so temperature/top_p are omitted \u2014 Anthropic rejects any temperature but 1 while thinking is set");const _={model:r,messages:w,max_tokens:UO(r,i.maxOutputTokens),...l?{system:l}:{},...!y&&E.temperature!==void 0?{temperature:E.temperature}:{},...!y&&E.topP!==void 0?{top_p:E.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...m?{tool_choice:m}:{},...y?{thinking:y}:{}},C=i.providerOptions?.neurolink,A=typeof C?.timeoutMs=="number"&&Number.isFinite(C.timeoutMs)&&C.timeoutMs>0?C.timeoutMs:void 0,k=A!==void 0?A:_.max_tokens>8192?Math.max(n(i),3e5):n(i),R=da(k,t,"generate"),I=L1(i.abortSignal,R?.controller.signal);let P;try{P=await e.messages.create(_,{signal:I})}catch(q){const B=I?.aborted?I.reason:void 0;throw B instanceof ma?B:q}finally{R?.cleanup()}const O=[];let U;const M=[];let F=!1;for(const q of P.content)q.type==="thinking"?O.push({type:"reasoning",text:q.thinking,providerOptions:{anthropic:{signature:q.signature}}}):q.type==="redacted_thinking"?O.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:q.data}}}):q.type==="text"?h?M.push(q.text):O.push({type:"text",text:q.text}):q.type==="tool_use"&&(h&&q.name===h?(F=!0,O.push({type:"text",text:hC(q.input)})):g&&q.name===mA?U=hC(q.input):O.push({type:"tool-call",toolCallId:q.id,toolName:q.name,input:hC(q.input)}));if(h&&!F&&M.length>0&&O.push({type:"text",text:M.join("")}),U!==void 0){const q=O.filter(B=>B.type==="reasoning");O.length=0,O.push(...q,{type:"text",text:U}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}const N=P.usage.cache_read_input_tokens??0,L=P.usage.cache_creation_input_tokens??0;return{content:O,finishReason:{unified:U!==void 0&&RQ(P.stop_reason)==="tool-calls"?"stop":RQ(P.stop_reason),raw:P.stop_reason??"stop"},usage:{inputTokens:{total:P.usage.input_tokens+N+L,noCache:P.usage.input_tokens,cacheRead:N,cacheWrite:L},outputTokens:{total:P.usage.output_tokens,text:P.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:_},response:{id:P.id,modelId:P.model,headers:Hzr()??{},body:P}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}formatProviderError(e){return ha(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:Mr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:$s,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:Go,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:ot,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:ot,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await Gzr(()=>this.dispatchGenerate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}async dispatchGenerate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(Ed(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),s=>this.executeNativeGenerate(s)),o)}async executeNativeGenerate(e){const t=Date.now(),r=this.modelName||Vv(),n=await this.getAISDKModelWithMiddleware(e);if(!yC(n))throw this.handleProviderError(new Error("anthropic: model handle exposes no doGenerate()"));const o=n.doGenerate.bind(n),i=!e.disableTools&&this.supportsTools()?e.tools||{}:{},a=Object.entries(i).map(([w,E])=>{const _=E;return{type:"function",name:w,description:_.description??"",inputSchema:_.inputSchema?Ao(_.inputSchema):{type:"object",properties:{}}}}),c=a.length>0,l=e.schema?Ao(e.schema):void 0,u=l&&!c?{type:"json",schema:l}:void 0,d={};l&&c&&(d.finalResultSchema=l),e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens&&(d.thinking={type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens});const m={};Object.keys(d).length>0&&(m.anthropic=d),typeof e.timeout=="number"&&(m.neurolink={timeoutMs:e.timeout});const h=Object.keys(m).length>0?m:void 0,f=await this.buildMessagesForStream(e),g=[],y=await aD({doGenerate:o,...yAt({provider:"anthropic",availableInputTokens:Pc("anthropic",r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Gt(H_({tools:a,responseFormat:u,providerOptions:h}),"anthropic")}),conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:dD(e,i,!0)}:{},...u?{responseFormat:u}:{},...h?{providerOptions:h}:{},maxSteps:e.maxSteps||Bs,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:w=>r0(w,lt.getActiveSpan()??void 0,"anthropic generate").catch(E=>{throw this.handleProviderError(E)})},g),v={content:y.text,provider:this.providerName,model:r,finishReason:y.finishReason,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},...y.reasoning?{reasoning:y.reasoning}:{},usage:{input:y.inputTokens,output:y.outputTokens,total:y.inputTokens+y.outputTokens+y.cacheReadTokens+y.cacheWriteTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,toolsUsed:y.toolsUsed,toolCalls:E7(g),toolExecutions:af(e,bd(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(v,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),Wzr(e),Kzr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return Vzr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=e.executionControl,n=typeof e.turnTimeoutMs=="number"&&Number.isFinite(e.turnTimeoutMs)&&e.turnTimeoutMs>0,o=r&&r.lifetimeTimeoutMs!==void 0?r.lifetimeTimeoutMs??void 0:n?e.turnTimeoutMs:this.getTimeout(e),s=da(o,this.providerName,"stream"),i=new AbortController,a=Bve([e.abortSignal,s?.controller.signal,i.signal]).signal;let c,l,u,d,m=!1;try{d=!e.disableTools&&this.supportsTools(),c=d?e.tools||await this.getAllTools():{},l=d?gv(c,"input_schema"):void 0;const ae=await this.buildMessagesForStream(e);if(u=xQ(ae),e.schema&&l&&l.length>0){const Pe=FMt(l,Ao(e.schema));l=Pe.tools,m=Pe.applied,Pe.applied&&(u.system=$Mt(u.system))}}catch(ae){throw s?.cleanup(),this.handleProviderError(ae)}const h=this.modelName||Vv(),f=d&&l&&l.length>0?IQ(dD(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=jMt.startSpan("neurolink.provider.streamText",{kind:zr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":h}}),v=e.maxSteps||Bs,w=this.neurolink?.getEventEmitter(),E=hv(),{push:_}=E,{usagePromise:C,finishPromise:A,resolveUsage:k,resolveFinish:R}=GY();C.then(ae=>{y.setAttribute("gen_ai.usage.input_tokens",ae.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",ae.completionTokens||0),ae.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",ae.cacheReadTokens);const Pe=xi(this.providerName,this.modelName,{input:ae.promptTokens||0,output:ae.completionTokens||0,total:ae.totalTokens||0,...ae.cacheReadTokens?{cacheReadTokens:ae.cacheReadTokens}:{},...ae.cacheCreationTokens?{cacheCreationTokens:ae.cacheCreationTokens}:{}});Pe&&Pe>0&&y.setAttribute("neurolink.cost",Pe)}).catch(()=>{}),A.then(ae=>{y.setAttribute("gen_ai.response.finish_reason",ae||"unknown"),y.end()}).catch(()=>{y.end()});let I;const P=this.client,O=[],U=Date.now(),M={};let F=0,N=0,L=0,q=0,B=null;const H=()=>({promptTokens:F,completionTokens:N,totalTokens:F+L+q+N,...L>0?{cacheReadTokens:L}:{},...q>0?{cacheCreationTokens:q}:{}});let G="",X;const ce=(ae,Pe)=>{const Ae=Te=>{if(typeof Te=="string")return Te;try{return JSON.stringify(Te)??""}catch{return""}};return Gt(Ae(ae),"anthropic")+Gt(Ae(Pe),"anthropic")},Ie=(async()=>{let ae,Pe;const he=EQ({client:P,maxSteps:v,toolsRecord:c,buildParams:se=>{if(l){const re=new Set(l.map(Re=>Re.name)),ye=Object.fromEntries(Object.entries(c).filter(([Re])=>!re.has(Re)));if(Object.keys(ye).length>0){const Re=gv(ye,"input_schema");Re&&Re.length>0&&(l=[...l,...Re])}}const oe=mY(l),Z=vQ({system:u.system,tools:oe,messages:se}),ie=DMt(se,_N-Z),W=hl("anthropic",h,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return g&&W.temperature!==void 0&&p.debug("[anthropic] extended thinking is enabled, so temperature is omitted on the stream path \u2014 Anthropic rejects any temperature but 1 while thinking is set"),{model:h,messages:ie,max_tokens:UO(h,e.maxTokens),...u.system?{system:u.system}:{},...!g&&W.temperature!==void 0?{temperature:W.temperature}:{},...oe&&oe.length>0?{tools:oe}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:se=>{const oe=MMt({conversation:se,availableInputTokens:Pc("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:ce(u.system,l),provider:"anthropic",observedPromptTokens:ae,previousSentEstimate:Pe,onSentEstimate:re=>{Pe=re}});if(!oe)return;const Z=new Set(oe.drop),ie=new Set(oe.truncate),W=[];for(let re=0;re<se.length;re++){if(Z.has(re))continue;const ye=se[re];if(ie.has(re)&&Array.isArray(ye.content)){W.push({...ye,content:ye.content.map(Re=>Re.type==="tool_result"?{...Re,content:PMt(typeof Re.content=="string"?Re.content:JSON.stringify(Re.content)??"")}:Re)});continue}W.push(ye)}if(Z.size>0){let re=W.findIndex(ye=>Array.isArray(ye.content)&&ye.content.some(Re=>Re.type==="tool_use"||Re.type==="tool_result"));re<0&&(re=Math.min(1,W.length)),W.splice(re,0,{role:"user",content:[{type:"text",text:yQ}]})}return{conversation:W}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:se=>{ae=se},...m?{finalResultToolName:mA,onTerminalResult:se=>{X=se,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:se.length})}}:{}}),Oe={...he,buildToolResultMessages:(se,oe,Z,ie)=>{for(const ye of Z)O.push(ye.name);const W=Z.map(ye=>({type:"tool-call",toolCallId:ye.id,toolName:ye.name,args:ye.args})),re=Z.map(ye=>ye.error?{type:"tool-result",toolCallId:ye.id,toolName:ye.name,error:ye.error}:{type:"tool-result",toolCallId:ye.id,toolName:ye.name,result:ye.output});return _At(w,re.map(ye=>({toolName:ye.toolName,result:"result"in ye?ye.result:void 0,error:"error"in ye?ye.error:void 0}))),this.handleToolExecutionStorage(W,re,e,new Date).catch(ye=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ye instanceof Error?ye.message:String(ye)})}),he.buildToolResultMessages(se,oe,Z,ie)}},De={};for(const[se,oe]of Object.entries(c)){const Z=oe.execute;Z&&(De[se]={execute:async(ie,W)=>{const re=W;return Z(ie,{toolCallId:re.toolCallId??"",...re.abortSignal?{abortSignal:re.abortSignal}:{},messages:[]})}})}const Ye=lt.getActiveSpan(),gt=r?.beforeStep,$e=gt?async se=>{const oe=r?.beforeStepTimeoutMs??OK,Z=da(oe,this.providerName,"stream"),ie=F1(se.signal,Z?.controller.signal);try{return await id(Promise.resolve(gt({...se,signal:ie.signal??se.signal})),ie.signal??se.signal)}catch(W){p.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:W instanceof Error?W.message:String(W),stepsCompleted:se.stepsCompleted});return}finally{ie.dispose(),Z?.cleanup()}}:void 0,{stream:xe,resultPromise:ve}=Ld(Oe,u.messages.slice(),{tools:De,...a?{abortSignal:a}:{},...Ye?{span:Ye}:{},...$e?{beforeStep:$e}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),J=(async()=>{for await(const se of xe)se.reasoning&&_({content:"",reasoning:se.reasoning}),se.content&&(m?G+=se.content:_({content:se.content}))})();let V;try{V=await ve}catch(se){throw await Ff(J,"Anthropic"),se}if(await J,F+=V.usage.inputTokens,N+=V.usage.outputTokens,L+=V.usage.cacheReadTokens??0,q+=V.usage.cacheWriteTokens??0,B=V.rawStopReason??B,V.aborted){const se=a?.aborted?a.reason:void 0;M.stopReason=se instanceof ma?"time-limit":"aborted",M.finishReason="other",V.rawStopReason&&(M.rawFinishReason=V.rawStopReason),k(H()),R("other");return}M.finishReason=V.finishReason,V.rawStopReason&&(M.rawFinishReason=V.rawStopReason),V.finishReason==="tool-calls"&&X===void 0&&(M.stopReason="step-cap"),k(H()),R(B??"stop")})().catch(ae=>{throw I=ae,p.error("Anthropic: Stream error",{error:ae instanceof Error?ae.message:String(ae)}),k(H()),R("error"),this.formatProviderError(ae)}).finally(()=>{if(m){const ae=X??G;ae.length>0&&_({content:ae})}s?.cleanup(),E.close()});Ie.catch(()=>{});const Ee=this.providerName;return{stream:async function*(){let ae=0;try{for await(const Pe of E.iterable)"content"in Pe&&typeof Pe.content=="string"&&Pe.content.length>0&&ae++,yield Pe;if(await Ie,ae===0&&O.length===0){p.warn(`${Ee}: Stream produced no output \u2014 emitting enriched sentinel`);const Pe=new cu({message:"Stream produced no output"}),Ae=await Mf(Pe,void 0,I);Of(Ae),yield Ae}}catch(Pe){const Ae=await Mf(Pe,void 0,I);if(Of(Ae),yield Ae,!cu.isInstance(Pe))throw Pe}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:M,analytics:A.then(async()=>{const ae=await ZY.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:C,finishReason:A},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Pe=jzr();return Pe&&ae&&(this.recordLimitSnapshot(Pe),ae.limits=Pe),ae})}}async isAvailable(){try{return kQ()||AQ(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),KMt={};ee(KMt,{ANTHROPIC_BETA_HEADERS:()=>xN,AnthropicProvider:()=>WMt,ModelAccessError:()=>AU,getModelCapabilities:()=>hQ,getRecommendedModelForTier:()=>pQ,isModelAvailableForTier:()=>mQ});var lqr=b({"src/lib/providers/anthropic/index.ts"(){"use strict";cqr(),GMt()}}),ng,Ks,uqr,dqr,JMt,YMt,XMt,pA,ZMt,mqr,pqr,hqr,fqr,gqr,yqr,vqr,Tqr,wqr,Eqr,Sqr,bqr,_qr,Cqr,Aqr,kqr,xqr,Iqr,Rqr,Pqr,Mqr,Oqr,Dqr,Nqr,Lqr,Fqr,$qr,Uqr,Bqr,zqr,qqr,Gqr,jqr,Hqr,Vqr,Wqr,Kqr,Jqr,Yqr,QMt=b({"npm-stub:@aws-sdk/client-bedrock-runtime"(){ng={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:ng.get}):new Proxy(function(...r){return new Proxy({},{get:ng.get})},{get:ng.get,apply(r,n,o){return new Proxy({},{get:ng.get})},construct(r,n){return new Proxy({},{get:ng.get})}})}},Ks=new Proxy({},ng),{BedrockClient:uqr,ListFoundationModelsCommand:dqr,BedrockRuntimeClient:JMt,ConverseCommand:YMt,ConverseStreamCommand:XMt,ImageFormat:pA,InvokeModelCommand:ZMt}=Ks,{SageMakerRuntimeClient:mqr,InvokeEndpointCommand:pqr,InvokeEndpointWithResponseStreamCommand:hqr}=Ks,{GoogleAuth:fqr,VertexAI:gqr,TextToSpeechClient:yqr}=Ks,{Webhook:vqr}=Ks,{Hippocampus:Tqr,HippocampusConfig:wqr}=Ks,{createClient:Eqr}=Ks,{Queue:Sqr,Worker:bqr,Job:_qr,QueueScheduler:Cqr,FlowProducer:Aqr}=Ks,{Cron:kqr}=Ks,{parseBuffer:xqr,selectCover:Iqr}=Ks,{extractRawText:Rqr,convertToHtml:Pqr}=Ks,{Hono:Mqr}=Ks,{cors:Oqr,HTTPException:Dqr,logger:Nqr,secureHeaders:Lqr,streamSSE:Fqr,timeout:$qr}=Ks,Uqr=globalThis.fetch,Bqr=globalThis.Request,zqr=globalThis.Response,qqr=globalThis.Headers,Gqr=globalThis.FormData,jqr=globalThis.File,Hqr=globalThis.Blob,Vqr=Ks.Agent,Wqr=Ks.Pool,Kqr=Ks.Client,Jqr=Ks.Dispatcher,Yqr=Ks.MockAgent}});function Xqr(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function Zqr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function e4t(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function Qqr(e,t){if(e.startsWith("arn:")||Zqr(e))return[];const r=[],n=Xqr(t);return n&&r.push(`${n}.${e}`),r.push(`${n4t}.${e}`),r}function t4t(e,t){return`${e}::${t}`}function eGr(e,t){return MQ.get(t4t(t,e))}function tGr(e,t,r){MQ.set(t4t(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function r4t(e,t,r){const n=eGr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!e4t(o))throw o;const s=Qqr(e,t);if(s.length===0)throw o;p.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:s.length});for(const i of s)try{const a=await r(i);return tGr(e,t,i),a}catch(a){if(!e4t(a))throw a}throw o}}var n4t,MQ,rGr=b({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";z(),n4t="global",MQ=new Map}});function IN(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function o4t(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function s4t(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??IN(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function nGr(e,t,r){const n=[],o=new Map,s=new Map,i=f=>{let g=o.get(f);return g||(g={},o.set(f,g),n.push(g)),g};let a="",c,l=0,u=0,d=0,m=0;if(e.stream)for await(const f of e.stream){if(r.aborted)break;const g=f;if(g.contentBlockStart&&i(g.contentBlockStart.contentBlockIndex??0),g.contentBlockDelta?.delta?.text){const y=g.contentBlockDelta.contentBlockIndex??0,v=g.contentBlockDelta.delta.text;i(y),a+=v,s.set(y,(s.get(y)??"")+v),t.push({content:v})}if(g.contentBlockStart?.start?.toolUse){const y=i(g.contentBlockStart.contentBlockIndex??0);y.toolUse={name:g.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:g.contentBlockStart.start.toolUse.toolUseId??IN()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:IN()};const v=g.contentBlockDelta.delta.toolUse.input;typeof v=="string"?y._inputBuffer=(y._inputBuffer??"")+v:typeof v=="object"&&v!==null&&!Array.isArray(v)&&(y.toolUse.input={...y.toolUse.input??{},...v})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;o4t(o.get(y),s.get(y)??"")}if(g.messageStop){c=g.messageStop.stopReason??"end_turn";continue}if(g.metadata?.usage){l+=g.metadata.usage.inputTokens??0,u+=g.metadata.usage.outputTokens??0,d+=g.metadata.usage.cacheReadInputTokens??0,m+=g.metadata.usage.cacheWriteInputTokens??0;break}}for(const[f,g]of o)o4t(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:s4t(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function oGr(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??IN(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:s4t(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function i4t(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const i=await r4t(o.modelId??"",e.region,a=>ze(e.client.send(new YMt({...o,modelId:a}),{abortSignal:n}),OQ,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return oGr(i)}const s=await r4t(o.modelId??"",e.region,i=>ze(e.client.send(new XMt({...o,modelId:i}),{abortSignal:n}),OQ,new Error("Bedrock streaming API call timed out")));return nGr(s,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...t,o,s]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var OQ,sGr=b({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";QMt(),Ze(),rGr(),OQ=12e4}});function a4t(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,videoOptions:e.videoOptions,officeOptions:e.officeOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var iGr=b({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),RN,c4t=b({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ka(),RN=Be.provider}}),l4t={};ee(l4t,{Agent:()=>Z4t,BedrockClient:()=>d4t,BedrockRuntimeClient:()=>p4t,Blob:()=>X4t,Client:()=>eOt,ConverseCommand:()=>h4t,ConverseStreamCommand:()=>f4t,Cron:()=>O4t,Dispatcher:()=>tOt,File:()=>Y4t,FlowProducer:()=>M4t,FormData:()=>J4t,GoogleAuth:()=>E4t,HTTPException:()=>B4t,Headers:()=>K4t,Hippocampus:()=>C4t,HippocampusConfig:()=>A4t,Hono:()=>$4t,ImageFormat:()=>g4t,InvokeEndpointCommand:()=>T4t,InvokeEndpointWithResponseStreamCommand:()=>w4t,InvokeModelCommand:()=>y4t,Job:()=>R4t,ListFoundationModelsCommand:()=>m4t,MockAgent:()=>oOt,Pool:()=>Q4t,Queue:()=>x4t,QueueScheduler:()=>P4t,Request:()=>V4t,Response:()=>W4t,SageMakerRuntimeClient:()=>v4t,TextToSpeechClient:()=>b4t,VertexAI:()=>S4t,Webhook:()=>_4t,Worker:()=>I4t,convertToHtml:()=>F4t,cors:()=>U4t,createClient:()=>k4t,default:()=>u4t,extractRawText:()=>L4t,fetch:()=>H4t,getGlobalDispatcher:()=>nOt,interceptors:()=>sOt,logger:()=>z4t,parseBuffer:()=>D4t,request:()=>iOt,secureHeaders:()=>q4t,selectCover:()=>N4t,setGlobalDispatcher:()=>rOt,streamSSE:()=>G4t,timeout:()=>j4t});var og,us,u4t,d4t,m4t,p4t,h4t,f4t,g4t,y4t,v4t,T4t,w4t,E4t,S4t,b4t,_4t,C4t,A4t,k4t,x4t,I4t,R4t,P4t,M4t,O4t,D4t,N4t,L4t,F4t,$4t,U4t,B4t,z4t,q4t,G4t,j4t,H4t,V4t,W4t,K4t,J4t,Y4t,X4t,Z4t,Q4t,eOt,tOt,rOt,nOt,oOt,sOt,iOt,aGr=b({"npm-stub:@aws-sdk/client-bedrock"(){og={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:og.get}):new Proxy(function(...r){return new Proxy({},{get:og.get})},{get:og.get,apply(r,n,o){return new Proxy({},{get:og.get})},construct(r,n){return new Proxy({},{get:og.get})}})}},us=new Proxy({},og),u4t=us,{BedrockClient:d4t,ListFoundationModelsCommand:m4t,BedrockRuntimeClient:p4t,ConverseCommand:h4t,ConverseStreamCommand:f4t,ImageFormat:g4t,InvokeModelCommand:y4t}=us,{SageMakerRuntimeClient:v4t,InvokeEndpointCommand:T4t,InvokeEndpointWithResponseStreamCommand:w4t}=us,{GoogleAuth:E4t,VertexAI:S4t,TextToSpeechClient:b4t}=us,{Webhook:_4t}=us,{Hippocampus:C4t,HippocampusConfig:A4t}=us,{createClient:k4t}=us,{Queue:x4t,Worker:I4t,Job:R4t,QueueScheduler:P4t,FlowProducer:M4t}=us,{Cron:O4t}=us,{parseBuffer:D4t,selectCover:N4t}=us,{extractRawText:L4t,convertToHtml:F4t}=us,{Hono:$4t}=us,{cors:U4t,HTTPException:B4t,logger:z4t,secureHeaders:q4t,streamSSE:G4t,timeout:j4t}=us,H4t=globalThis.fetch,V4t=globalThis.Request,W4t=globalThis.Response,K4t=globalThis.Headers,J4t=globalThis.FormData,Y4t=globalThis.File,X4t=globalThis.Blob,Z4t=us.Agent,Q4t=us.Pool,eOt=us.Client,tOt=us.Dispatcher,rOt=()=>{},nOt=()=>us,oOt=us.MockAgent,sOt={redirect:()=>e=>e,retry:()=>e=>e},iOt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}});async function DQ(){return await Promise.resolve().then(()=>(aGr(),l4t))}var aOt=b({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}});function cGr(e){const t=(e??"").split(";").at(0)?.trim().toLowerCase();return NQ[t??""]}var NQ,cOt,lGr=b({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";QMt(),hr(),Xb(),ec(),Lo(),ZO(),Zm(),Ic(),sGr(),ut(),qi(),Ze(),vf(),z(),ud(),Z4(),iGr(),ui(),Xt(),c4t(),aOt(),NQ={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},cOt=class k0r extends ba{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const s=t||process.env.BEDROCK_MODEL||this.modelName,i=k0r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",p.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),p.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{p.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new JMt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),p.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw p.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await DQ(),n=new t({region:this.region});try{p.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),s=Date.now();await n.send(o);const i=Date.now()-s;p.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);p.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){p.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const f=a4t(n,this.providerName,this.modelName),g=await J4(f,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(g)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const h={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(h)}p.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c,l,u;try{({text:i,usage:a,finishReason:c,rawFinishReason:l,toolExecutions:u}=await this.conversationLoop(n))}catch(h){const f=this.neurolink?.getEventEmitter();throw f&&(f.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:h instanceof Error?h.message:String(h)}),h&&typeof h=="object"&&(h._generationEndEmitted=!0)),h}const d=this.neurolink?.getEventEmitter();d&&d.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:c},success:!0});const m={content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...c!==void 0&&{finishReason:c},...l!==void 0&&{rawFinishReason:l},toolsUsed:u.filter(h=>h.error===void 0).map(h=>h.name),toolCalls:u.map(h=>({toolCallId:h.id,toolName:h.name,args:h.input})),toolExecutions:af(n,bd(u)),enhancedWithTools:u.some(h=>h.error===void 0)};return m._generationEndEmitted=!0,m}async conversationLoop(t){const r=t.maxSteps||Bs,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=hl(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=i4t({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{const{resultPromise:a}=Ld(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),c=await a;this.conversationHistory=c.conversation;const l=c.usage.inputTokens,u=c.usage.outputTokens,d=c.usage.cacheReadTokens??0,m=c.usage.cacheWriteTokens??0;return{text:c.text||"",usage:{input:l,output:u,total:l+d+m+u,...d>0&&{cacheReadTokens:d},...m>0&&{cacheCreationTokens:m}},finishReason:c.finishReason,rawFinishReason:c.rawStopReason,toolExecutions:c.toolExecutions}}catch(a){throw p.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return RN.startActiveSpan("bedrock.tool.execute",{kind:zr.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(p.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const i=t[r];if(!i||!i.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",p.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),p.debug("[AmazonBedrockProvider] Tool input parameters:",a);const c={};for(const[d,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(c[d]=m);const l=await i.execute(c);p.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:l});let u;if(l&&typeof l=="object"&&"success"in l)if(l.success&&l.data!==void 0)typeof l.data=="string"?u=l.data:typeof l.data=="object"?u=JSON.stringify(l.data,null,2):u=String(l.data);else if(l.error){const d=typeof l.error=="string"?l.error:l.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof l=="string"?u=l:typeof l=="object"?u=JSON.stringify(l,null,2):u=String(l);return s.setStatus({code:Ue.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Ue.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const i=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=Ao(o.parameters):s=o.parameters:s={type:"object",properties:{},required:[]},(!s.type||s.type!=="object")&&(s={type:"object",properties:s.properties||{},required:s.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:s}}}});return p.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?pA.JPEG:i==="png"?pA.PNG:i==="gif"?pA.GIF:pA.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?Bm.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return p.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),p.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),RN.startActiveSpan("bedrock.stream",{kind:zr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(p.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const s=a4t(t,this.providerName,this.modelName),i=await J4(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{p.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}p.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),p.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return p.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:Ue.OK}),r.end(),o}catch(n){p.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(p.debug("[TRACE] executeStream CATCH - checking if permission error"),p.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){p.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),p.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const i=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!i)throw r.setStatus({code:Ue.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:Ue.OK}),r.end();const a=new ReadableStream({start(l){const d=(i.content||"").split(/(\s+)/);let m="";for(let h=0;h<d.length;h++)m+=d[h],(h===d.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(l.enqueue({content:m}),m="");m.length>0&&l.enqueue({content:m}),l.close()}});return{stream:{async*[Symbol.asyncIterator](){const l=a.getReader();try{for(;;){const{done:u,value:d}=await l.read();if(u)break;yield d}}finally{l.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:Ue.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||Bs,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=hl(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),c=i4t({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:k=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(k),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let l=!1,u;const d=new Promise(k=>{u=()=>{l=!0,k()}}),m={...c,executeStep:async(k,R,I)=>{const P=await c.executeStep(k,R,I);return u(),P}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:f}=Ld(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),g=f.then(k=>({result:k,error:void 0}),k=>({result:void 0,error:k}));if(await Promise.race([d,g]),!l){const k=await g;if(k.error)throw k.error}const y=this.neurolink?.getEventEmitter(),v=this,w={startTime:n,streamId:`bedrock-${Date.now()}`};let E;const _=new Promise(k=>{E=k}),C=k=>{const R=k?.inputTokens??0,I=k?.outputTokens??0,P=k?.cacheReadTokens??0,O=k?.cacheWriteTokens??0;return{input:R,output:I,total:R+P+O+I,...P>0&&{cacheReadTokens:P},...O>0&&{cacheCreationTokens:O}}};return g.then(k=>{E(I0(this.providerName,this.modelName||this.getDefaultModel(),{usage:C(k.result?.usage),toolExecutions:k.result?.toolExecutions??[],toolsUsed:(k.result?.toolExecutions??[]).filter(R=>R.error===void 0).map(R=>R.name)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let k=!1;try{yield*h}catch(R){throw k=!0,R}finally{const R=await g;R.error&&(k=!0);const I=C(R.result?.usage);if(R.result&&(v.conversationHistory=R.result.conversation,w.finishReason=R.result.finishReason,w.rawFinishReason=R.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",R.result.rawStopReason??"unknown")),y){const P=t._streamDedupContext;P&&(P.providerEmitted=!0),y.emit("generation:end",{provider:v.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:I,model:v.modelName||v.getDefaultModel(),provider:v.providerName,finishReason:k?"error":R.result?.rawStopReason},success:!k})}}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:_,metadata:w}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await DQ(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{p.debug("[AmazonBedrockProvider] Starting health check...");const i=new o({}),c=(await s.send(i,{abortSignal:t.signal})).modelSummaries||[],l=c.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(p.debug(`[AmazonBedrockProvider] Health check passed - Found ${l.length} active models out of ${c.length} total models`),l.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(r);const a=i;if(cr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});const c=typeof a.message=="string"?a.message:"";throw c.includes("UnauthorizedOperation")||c.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:i}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:i}):(p.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${c||"Unknown error"}`,{cause:i}))}finally{clearTimeout(r);try{s.destroy()}catch{}}}formatProviderError(t){return ha(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Mr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:$s,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:ot,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:ot,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=typeof t=="string"?{text:t}:t,o=r||this.getDefaultEmbeddingModel(),s=o.includes("nova")&&o.includes("multimodal"),i=o.includes("image")||o.includes("multimodal")||o==="amazon.titan-embed-image-v1"||s;p.debug("Generating embedding",{provider:this.providerName,model:o,hasText:typeof n.text=="string",hasImage:n.image!==void 0,isMultiModalModel:i});try{let a;if(n.image&&!i)throw new ot(`${this.providerName} model ${o} does not support image embeddings`,this.providerName);if(s){if(n.image&&n.text)throw new ot(`${this.providerName} model ${o} does not support combined image+text embeddings; provide exactly one of image or text`,this.providerName);const m={embeddingPurpose:"GENERIC_RETRIEVAL"};if(n.image){const h=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64"),f=cGr(n.mimeType);if(f===void 0)throw new ot(`${this.providerName} model ${o} does not support image format '${n.mimeType??"unknown"}'; supported formats are ${Object.keys(NQ).join(", ")}`,this.providerName);m.image={detailLevel:"STANDARD_IMAGE",format:f,source:{bytes:no.safeBase64Convert(h,"bedrock nova embed image")}}}n.text&&(m.text={value:n.text,truncationMode:"NONE"}),a=JSON.stringify({taskType:"SINGLE_EMBEDDING",singleEmbeddingParams:m})}else if(n.image){const m=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64");a=JSON.stringify({inputText:n.text??"",inputImage:no.safeBase64Convert(m,"bedrock titan embed image")})}else a=JSON.stringify({inputText:n.text??""});const c=new ZMt({modelId:o,contentType:"application/json",accept:"application/json",body:a}),l=await ze(this.bedrockClient.send(c),6e4,new Error("Bedrock embedding API call timed out")),u=JSON.parse(new TextDecoder().decode(l.body)),d=s?u.embeddings?.at(0)?.embedding:u.embedding;if(!Array.isArray(d))throw new Error("Invalid embedding response from Bedrock");return p.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:d.length}),d}catch(a){throw p.error("Embedding generation failed",{error:a instanceof Error?a.message:String(a),model:o}),this.handleProviderError(a)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel();p.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(s=>this.embed(s,n)));return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw p.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),lOt={};ee(lOt,{AmazonBedrockProvider:()=>cOt,bedrockTracer:()=>RN,loadBedrockControl:()=>DQ});var uGr=b({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";lGr(),c4t(),aOt()}}),uOt={};ee(uOt,{AzureOpenAIProvider:()=>dOt});var dOt,dGr=b({"src/lib/providers/azureOpenai.ts"(){"use strict";ut(),z(),qi(),ts(),Ic(),kl(),vp(),dOt=class extends Lc{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",s=process.env.AZURE_OPENAI_ENDPOINT||"";let i;if(s)try{i=new URL(s.includes("://")?s:`https://${s}`)}catch{i=void 0}const a=i?.hostname??"",c=i?.pathname&&i.pathname!=="/"?i.pathname.replace(/\/+$/,""):"",l=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;l?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;const d=i?.origin??"",m=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",f=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,g=n?.useMaxCompletionTokens??(f===void 0?void 0:/^(1|true|yes)$/i.test(f));o||fa(MCr()),d||fa(OCr()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=h,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=g,p.shouldLog("debug")&&p.debug("Azure OpenAI Provider initialized",F7e({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>/401/.test(r.message),errorClass:Mr,message:"Invalid Azure OpenAI API key or endpoint."},..._c];return ha(e,t,this.providerName,this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??hAt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function LQ(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"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&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function hA(e){return LQ(e)??"image/png"}var PN=b({"src/lib/utils/imageDetection.ts"(){"use strict"}});function mOt(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var mGr=b({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),MN,pGr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){MN=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}}}),hGr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){So()}});function FQ(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var ON,$Q,pOt=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){hGr(),ON=e=>(ON=Array.isArray,ON(e)),$Q=ON}});function*fGr(e){if(!e)return;if(UQ in e){const{values:n,nulls:o}=e;yield*n.entries();for(const s of o)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():$Q(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const s=$Q(n[1])?n[1]:[n[1]];let i=!1;for(const a of s)a!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var UQ,hOt,gGr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){pOt(),UQ=Symbol.for("brand.privateNullableHeaders"),hOt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of fGr(n)){const a=s.toLowerCase();o.has(a)||(t.delete(s),o.add(a)),i===null?(t.delete(s),r.add(a)):(t.append(s,i),r.delete(a))}}return{[UQ]:!0,values:t,nulls:r}}}});function yGr(e){const t=new nA(e);return delete t.batches,t}function vGr(e){const t=new Xi(e);return delete t.messages.batches,t}var fOt,gOt,BQ,yOt=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){wN(),yRt(),L_(),pGr(),pOt(),gGr(),wN(),fOt="vertex-2023-10-16",gOt=new Set(["/v1/messages","/v1/messages?beta=true"]),BQ=class extends xo{constructor({baseURL:e=MN("ANTHROPIC_VERTEX_BASE_URL"),region:t=MN("CLOUD_ML_REGION")??null,projectId:r=MN("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=yGr(this),this.beta=vGr(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new IW({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=hOt([r,e.headers])}async buildRequest(e){if(FQ(e.body)&&(e.body={...e.body}),FQ(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=fOt)),gOt.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!FQ(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),zQ={};ee(zQ,{AnthropicVertex:()=>BQ,BaseAnthropic:()=>xo,default:()=>BQ});var vOt=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){yOt(),yOt()}});async function TGr(){return DN||(DN=await Promise.resolve().then(()=>(vOt(),zQ))),DN}function wGr(e){const t=[],r=new Map;let n=0;const o=s=>{const i=`${n}:${s??"x"}`;let a=r.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(i,a),t.push(a)),a};for(const s of e){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}const i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,t.push({type:"regular",role:i,parts:[s.content]}))}return t}function qQ(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function EGr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&p.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const s=[],i=[];for(let a=0;a<o;a++){const c=`hist_${t}_${a}`;s.push({type:"tool_use",id:c,name:r[a].name,input:r[a].input}),i.push({type:"tool_result",tool_use_id:c,content:n[a]})}return{uses:s,results:i}}function SGr(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function GQ(e){const t=[];let r=0;for(const n of wGr(e)){if(n.type==="regular"){qQ(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=EGr(n,r);o.length!==0&&(r++,qQ(t,"assistant",o),qQ(t,"user",s))}if(SGr(t),p.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);p.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function jQ(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function sg(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&sg(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&sg(n);else sg(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&sg(o)}function TOt(e,t,r){const n=gCt({contents:e,availableInputTokens:Pc("vertex",t),provider:"vertex",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 c=e[a];if(s.has(a)&&Array.isArray(c.parts)){i.push({...c,parts:c.parts.map(l=>{if(!("functionResponse"in l))return l;const u=l.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=COt?l:{functionResponse:{name:u.name,response:{result:lY(d)}}}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.parts)&&c.parts.some(l=>!!l.functionCall||!!l.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:dY}]})}return e.length=0,e.push(...i),!0}function wOt(e,t,r){const n=MMt({conversation:e,availableInputTokens:Pc("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});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 c=e[a];if(s.has(a)&&Array.isArray(c.content)){i.push({...c,content:c.content.map(l=>{if(l.type!=="tool_result")return l;const u=typeof l.content=="string"?l.content:JSON.stringify(l.content)??"";return{...l,content:PMt(u)}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.content)&&c.content.some(l=>l.type==="tool_use"||l.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:yQ}]})}return e.length=0,e.push(...i),!0}async function EOt(e,t,r={}){const n=[],o=[];let s,i=0,a=0,c=0,l=0;for await(const u of e){r.onProgress?.();const d=u,h=d.candidates?.[0],f=h?.finishReason;typeof f=="string"&&f&&(s=f);const g=h?.content;if(g&&Array.isArray(g.parts))for(const v of g.parts)n.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.text});u.functionCalls&&o.push(...u.functionCalls);const y=d.usageMetadata;if(y){if(y.promptTokenCount!==void 0&&y.promptTokenCount>0){r.onUsageDelta?.("input",y.promptTokenCount-i),i=y.promptTokenCount,r.onUsage?.(y.promptTokenCount,y.candidatesTokenCount??0);const v=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",v-c),c=v}y.candidatesTokenCount!==void 0&&y.candidatesTokenCount>0&&(r.onUsageDelta?.("output",y.candidatesTokenCount-a),a=y.candidatesTokenCount),y.thoughtsTokenCount!==void 0&&y.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",y.thoughtsTokenCount-l),l=y.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...s?{finishReason:s}:{},inputTokens:i,outputTokens:a,...c?{cacheReadTokens:c}:{},...l?{reasoningTokens:l}:{}}}var DN,SOt,HQ,fA,VQ,Wv,ig,bOt,_Ot,NN,COt,WQ,bGr=b({"src/lib/providers/googleVertex/client.ts"(){"use strict";on(),HO(),hr(),ec(),k9(),YO(),oW(),Lo(),tf(),of(),cY(),Ut(),On(),ut(),qi(),Ze(),TQ(),mvt(),Z4(),z(),QJ(),vCt(),OMt(),FO(),PN(),GJ(),ts(),ui(),tCt(),$f(),pa(),TCt(),uCt(),ZO(),zMt(),Z_(),fv(),pY(),bl(),i_(),Ka(),Xt(),Ja(),Ic(),Zm(),ud(),mGr(),Z_(),DN=null,SOt=()=>!0,HQ=()=>fa(zCr()),fA=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",VQ=(e,t)=>{const r=t||fA();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||Fq.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},Wv=VQ,ig=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",bOt=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),_Ot=async(e,t,r,n)=>{const o=e||fA();return{projectId:r?r.projectId?.trim()||"express":HQ(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},NN=e=>e.toLowerCase().includes("claude"),COt=2048,WQ=class Xr extends ba{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,s){super(t,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey),!s.projectId&&!s.location&&(this.expressApiKey=String(s.apiKey))),s.baseURL&&(this.baseURL=String(s.baseURL)));const i=!!this.resolveExpressApiKey();i||bOt()||fa(qCr()),this.projectId=s?.projectId||(i?"":HQ()),this.location=o||s?.location||fA(),p.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),p.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return ig()}async getAISDKModel(){throw new Me({code:je.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&mK(t.input),t.input?.files?.length)try{await pK(t,100*1024*1024,this.providerName)}catch(r){p.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await K_(t.input)}async executeStream(t,r){const n=t.model||this.modelName||ig();return j6e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:this.providerName,[_e.GEN_AI_MODEL]:n,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await dt({name:"neurolink.message.build",tracer:Be.provider,attributes:{[_e.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:i},l=c.input?.text||c.prompt||"";try{let u;NN(n)?(p.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),u=await this.executeNativeAnthropicStream(c)):(p.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),u=await this.executeNativeGemini3Stream(c)),this.attachUsageAndCostAttributes(o,n,u?.usage);const d=this.wrapStreamResultWithLifecycle(t,u,s);return this.emitStreamEnd(n,s,!0,void 0,u.finishReason),d}catch(u){throw this.fireGenerateOnError(t,u,s),this.emitStreamEnd(n,s,!1,u),this.emitGenerationEnd(n,null,s,!1,u,l),u}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(t,r,n,o,s){const i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){kCt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||fA(),i=(await Promise.resolve().then(()=>(mb(),d0))).GoogleGenAI;if(!i)throw new Me({code:je.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=i,c=this.resolveBaseURL(),l={...c?{baseUrl:c}:{}};return r?new a({vertexai:!0,apiKey:r,httpOptions:l}):new a({vertexai:!0,project:n,location:o,httpOptions:l})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},s=r.parameters||r.inputSchema;if(s){const i=Ao(s),a=Xn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),p.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,s){if(!n)return;const i=_Ke(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,i)),o.set(t,i.execute),s.delete(t),p.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildFinalResultTool(t){const r=Ao(t),n=Xn(r);n.$schema&&delete n.$schema;const o=Hi(n);return{name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",input_schema:{type:"object",properties:o.properties||o,required:o.required||[]}}}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||ig(),n=Wv(r,t.region),o=await this.createVertexGenAIClient(n);p.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const s=[],i=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const xe of a.pdfFiles){let ve;typeof xe=="string"?Fo.existsSync(xe)?ve=Fo.readFileSync(xe):ve=Buffer.from(xe,"base64"):ve=xe;const J=ve.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:J}})}}if(await nY(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const xe of a.images){const ve=E_(xe);let J,V="image/jpeg";if(typeof ve=="string")if(Fo.existsSync(ve)){J=Fo.readFileSync(ve);const oe=k_(ve);V=oe.startsWith("image/")?oe:this.detectImageType(J)}else if(ve.startsWith("data:")){const oe=ve.match(/^data:([^;]+);base64,(.+)$/);if(oe)V=oe[1],J=Buffer.from(oe[2],"base64");else continue}else if(ve.startsWith("http://")||ve.startsWith("https://"))try{const oe=await fetch(ve);if(!oe.ok){p.warn(`[GoogleVertex] Image fetch failed: ${oe.status} ${oe.statusText}, skipping`,{url:rr(ve)});continue}const Z=await oe.arrayBuffer();J=Buffer.from(Z);const ie=oe.headers.get("content-type");ie&&ie.startsWith("image/")&&(V=ie.split(";")[0])}catch(oe){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${oe instanceof Error?oe.message:String(oe)}`,{url:rr(ve)});continue}else J=Buffer.from(ve,"base64"),V=this.detectImageType(J);else J=ve,V=this.detectImageType(J);const se=J.toString("base64");i.push({inlineData:{mimeType:V,data:se}})}}await oY(i,a?.nativeVideoFiles,"vertex",r,"[GoogleVertex]"),KO(s,t.conversationMessages),s.push({role:"user",parts:i});let c;const l=new pv;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const xe=gv(t.tools,"functionDeclarations");u=xe,c=xe.toolsConfig;for(const[ve,J]of xe.executeMap)l.set(ve,J);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:xe.toolsConfig[0].functionDeclarations.length,toolNames:xe.toolsConfig[0].functionDeclarations.map(ve=>ve.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const xe=Ao(d.schema,"openApi3"),ve=Xn(xe);ve.$schema&&delete ve.$schema;const J=Hi(ve),V=c[0]?.functionDeclarations||[];V.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:J}),c=[{functionDeclarations:V}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(J),totalTools:V.length})}const h=hl(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),f={...h.temperature!==void 0&&{temperature:h.temperature},maxOutputTokens:t.maxTokens};qJ(r)&&(f.maxOutputTokens&&f.maxOutputTokens>Sa&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Sa} for ${r}`),f.maxOutputTokens=Sa),f.maxOutputTokens||(f.maxOutputTokens=Sa)),h.topP!==void 0&&(f.topP=h.topP),t.topK!==void 0&&(f.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(f.stopSequences=t.stopSequences),c&&(f.tools=c);let g=t.systemPrompt||"";m&&(g=g+`
|
|
1112
|
+
`);return{...s!==void 0?{system:s}:{},messages:r}},IQ=e=>{if(!(!e||e==="auto")){if(e==="none")return{type:"none"};if(e==="required")return{type:"any"};if(typeof e=="object"){const t=e;if(t.type==="tool"&&t.toolName)return{type:"tool",name:t.toolName}}}},RQ=e=>{switch(e){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},PQ=6e5,WMt=class extends ba{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,r,n){const o=!!(n?.apiKey&&!n?.oauthToken),s=o?null:(n?.oauthToken?{accessToken:n.oauthToken}:null)??r?.oauthToken??kQ(),i=o?"api_key":r?.authMethod??VMt(s),a=r?.subscriptionTier??(i==="oauth"?HMt(s):"api"),c=e||Vv();let l=c;!process.env.ANTHROPIC_BASE_URL&&a!=="api"&&!mQ(c,a)&&(l=pQ(a),p.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:a,recommendedModel:l})),super(l,"anthropic",t),this.enableBetaFeatures=r?.enableBetaFeatures??!0,this.oauthToken=s,this.subscriptionTier=a,this.authMethod=i;const d=this.getAuthHeaders();let m;if(p.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){p.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");const h=this.oauthToken,f=$zr(()=>h.accessToken,this.enableBetaFeatures,!1,!0);m=new tg({apiKey:"oauth-authenticated",fetch:CMt(f),timeout:PQ,maxRetries:0}),p.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),p.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{const h=n?.apiKey??r?.apiKey??AQ(),f=(()=>{const g=process.env.ANTHROPIC_BASE_URL;if(!g)return;const y=g.replace(/\/+$/,""),v=y.replace(/\/v\d+$/,"");return v!==y&&p.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:No(g),rewrittenTo:No(v)}),v})();m=new tg({apiKey:h,defaultHeaders:d,...f&&{baseURL:f},fetch:CMt(Pt()),timeout:PQ,maxRetries:0}),p.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=m,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},p.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?xN["anthropic-beta"]:"disabled"})}getAuthHeaders(){const e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){const r=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",n=[...cA,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];r&&n.push("context-1m-2025-08-07"),e["anthropic-beta"]=n.join(",")}else e["anthropic-beta"]=xN["anthropic-beta"];return t&&(e["User-Agent"]=rg),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return p.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;const t=mQ(e,this.subscriptionTier);return t||p.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return hQ(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){p.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){p.debug("Token has no expiry information, assuming valid");return}const e=Date.now(),t=this.oauthToken.expiresAt<=e,r=this.oauthToken.expiresAt<=e+zme;if(!t&&!r){p.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Mr("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);p.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}p.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});const n=this.oauthToken,o=n.refreshToken;this.refreshPromise=(async()=>{const i=new AbortController,a=setTimeout(()=>i.abort(),3e4),c=await fetch(aA,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":rg},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:o,client_id:uQ}),signal:i.signal});if(clearTimeout(a),!c.ok){const d=await c.text();throw new Mr(`Failed to refresh OAuth token: ${c.status} ${d}`,this.providerName)}const l=await c.json();n.accessToken=l.access_token,n.refreshToken=l.refresh_token||n.refreshToken,n.expiresAt=l.expires_in?Date.now()+l.expires_in*1e3:void 0,n.tokenType=l.token_type||"Bearer";const u=n;try{const d=kt(Ii(),".neurolink");Gs(d)||Wq(d,{recursive:!0});const m=kt(d,"anthropic-credentials.json"),h=`${m}.tmp`,g={...Gs(m)?JSON.parse(md(m,"utf-8")):{},type:"oauth",oauth:u,updatedAt:Date.now()};Q1(h,JSON.stringify(g,null,2),{mode:384}),Jq(h,m),p.debug("Refreshed OAuth credentials persisted to disk")}catch(d){p.warn("Failed to persist refreshed OAuth token to disk",{error:d instanceof Error?d.message:String(d)})}p.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!l.refresh_token,expiresIn:l.expires_in})})();try{await this.refreshPromise}catch(s){throw s instanceof Mr?s:new Mr(`Failed to refresh OAuth token: ${s instanceof Error?s.message:String(s)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,r){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),r&&(r.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=r.inputTokens,this.usageInfo.tokensUsed+=r.inputTokens),r.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=r.outputTokens,this.usageInfo.tokensUsed+=r.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&p.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&p.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return Vv()}getAISDKModel(){const e=this.client,t=this.providerName,r=this.modelName||Vv(),n=i=>this.getTimeout(i??{}),o=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:r,supportedUrls:{},doGenerate:async i=>{await o();const a=xQ(i.prompt),c=a.messages;let l=a.system,u=(i.tools??[]).filter(q=>q.type==="function").map(q=>{const B=Fd(q);return{name:q.name,...q.description?{description:q.description}:{},input_schema:q.inputSchema??{type:"object",properties:{}},...B?{cache_control:B}:{}}});u&&u.length===0&&(u=void 0);const d=T5r(i.toolChoice);let m=d?IQ(d):void 0,h;if(i.responseFormat?.type==="json"){h=i.responseFormat.name??"json";const q=i.responseFormat.schema??{type:"object"};u=[{name:h,description:i.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:q}],m={type:"tool",name:h}}const f=i.providerOptions?.anthropic?.finalResultSchema;let g=!1;if(!h&&f){const q=FMt(u,f);u=q.tools,g=q.applied,q.applied&&(l=$Mt(l))}const y=i.providerOptions?.anthropic?.thinking;u=mY(u);const v=vQ({system:l,tools:u,messages:c}),w=DMt(c,_N-v),E=hl("anthropic",r,{...i.temperature!==void 0&&i.temperature!==null?{temperature:i.temperature}:{},...i.topP!==void 0&&i.topP!==null?{topP:i.topP}:{}},"anthropic.doGenerate");y&&(E.temperature!==void 0||E.topP!==void 0)&&p.debug("[anthropic] extended thinking is enabled, so temperature/top_p are omitted \u2014 Anthropic rejects any temperature but 1 while thinking is set");const _={model:r,messages:w,max_tokens:UO(r,i.maxOutputTokens),...l?{system:l}:{},...!y&&E.temperature!==void 0?{temperature:E.temperature}:{},...!y&&E.topP!==void 0?{top_p:E.topP}:{},...i.stopSequences&&i.stopSequences.length>0?{stop_sequences:i.stopSequences}:{},...u?{tools:u}:{},...m?{tool_choice:m}:{},...y?{thinking:y}:{}},C=i.providerOptions?.neurolink,A=typeof C?.timeoutMs=="number"&&Number.isFinite(C.timeoutMs)&&C.timeoutMs>0?C.timeoutMs:void 0,k=A!==void 0?A:_.max_tokens>8192?Math.max(n(i),3e5):n(i),R=da(k,t,"generate"),I=L1(i.abortSignal,R?.controller.signal);let P;try{P=await e.messages.create(_,{signal:I})}catch(q){const B=I?.aborted?I.reason:void 0;throw B instanceof ma?B:q}finally{R?.cleanup()}const O=[];let U;const M=[];let F=!1;for(const q of P.content)q.type==="thinking"?O.push({type:"reasoning",text:q.thinking,providerOptions:{anthropic:{signature:q.signature}}}):q.type==="redacted_thinking"?O.push({type:"reasoning",text:"",providerOptions:{anthropic:{redactedData:q.data}}}):q.type==="text"?h?M.push(q.text):O.push({type:"text",text:q.text}):q.type==="tool_use"&&(h&&q.name===h?(F=!0,O.push({type:"text",text:hC(q.input)})):g&&q.name===mA?U=hC(q.input):O.push({type:"tool-call",toolCallId:q.id,toolName:q.name,input:hC(q.input)}));if(h&&!F&&M.length>0&&O.push({type:"text",text:M.join("")}),U!==void 0){const q=O.filter(B=>B.type==="reasoning");O.length=0,O.push(...q,{type:"text",text:U}),p.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}const N=P.usage.cache_read_input_tokens??0,L=P.usage.cache_creation_input_tokens??0;return{content:O,finishReason:{unified:U!==void 0&&RQ(P.stop_reason)==="tool-calls"?"stop":RQ(P.stop_reason),raw:P.stop_reason??"stop"},usage:{inputTokens:{total:P.usage.input_tokens+N+L,noCache:P.usage.input_tokens,cacheRead:N,cacheWrite:L},outputTokens:{total:P.usage.output_tokens,text:P.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:_},response:{id:P.id,modelId:P.model,headers:Hzr()??{},body:P}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model. NeuroLink streams through executeStream, reached via NeuroLink.stream() \u2014 use that (the browser bundle exports the NeuroLink class) rather than calling doStream on a model handle.`)}}}formatProviderError(e){return ha(e,[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(r.message),errorClass:Mr,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:r=>r.statusCode===429||/rate limit|too_many_requests|429/i.test(r.message),errorClass:$s,message:"Anthropic rate limit exceeded. Please try again later."},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(r.message),errorClass:Go,message:r=>`Connection error: ${r.message}`},{match:r=>/500|502|503|504|server error/i.test(r.message),errorClass:ot,message:r=>`Server error: ${r.message}`},{match:()=>!0,errorClass:ot,message:r=>`Anthropic error: ${r.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();const{result:r,snapshot:n}=await Gzr(()=>this.dispatchGenerate(e,t));return r&&n&&(this.recordLimitSnapshot(n),r.limits=n,r.analytics&&(r.analytics.limits=n)),r}async dispatchGenerate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(Ed(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),s=>this.executeNativeGenerate(s)),o)}async executeNativeGenerate(e){const t=Date.now(),r=this.modelName||Vv(),n=await this.getAISDKModelWithMiddleware(e);if(!yC(n))throw this.handleProviderError(new Error("anthropic: model handle exposes no doGenerate()"));const o=n.doGenerate.bind(n),i=!e.disableTools&&this.supportsTools()?e.tools||{}:{},a=Object.entries(i).map(([w,E])=>{const _=E;return{type:"function",name:w,description:_.description??"",inputSchema:_.inputSchema?Ao(_.inputSchema):{type:"object",properties:{}}}}),c=a.length>0,l=e.schema?Ao(e.schema):void 0,u=l&&!c?{type:"json",schema:l}:void 0,d={};l&&c&&(d.finalResultSchema=l),e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens&&(d.thinking={type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens});const m={};Object.keys(d).length>0&&(m.anthropic=d),typeof e.timeout=="number"&&(m.neurolink={timeoutMs:e.timeout});const h=Object.keys(m).length>0?m:void 0,f=await this.buildMessagesForStream(e),g=[],y=await aD({doGenerate:o,...yAt({provider:"anthropic",availableInputTokens:Pc("anthropic",r,e.maxTokens??void 0),getFixedOverheadTokens:()=>Gt(H_({tools:a,responseFormat:u,providerOptions:h}),"anthropic")}),conversation:f,...c?{tools:a}:{},toolsRecord:i,...c&&e.toolChoice?{toolChoice:dD(e,i,!0)}:{},...u?{responseFormat:u}:{},...h?{providerOptions:h}:{},maxSteps:e.maxSteps||Bs,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:w=>r0(w,lt.getActiveSpan()??void 0,"anthropic generate").catch(E=>{throw this.handleProviderError(E)})},g),v={content:y.text,provider:this.providerName,model:r,finishReason:y.finishReason,...y.rawFinishReason?{rawFinishReason:y.rawFinishReason}:{},...y.reasoning?{reasoning:y.reasoning}:{},usage:{input:y.inputTokens,output:y.outputTokens,total:y.inputTokens+y.outputTokens+y.cacheReadTokens+y.cacheWriteTokens,...y.cacheReadTokens?{cacheReadTokens:y.cacheReadTokens}:{},...y.cacheWriteTokens?{cacheCreationTokens:y.cacheWriteTokens}:{}},responseTime:Date.now()-t,toolsUsed:y.toolsUsed,toolCalls:E7(g),toolExecutions:af(e,bd(g)),enhancedWithTools:y.toolsUsed.length>0};return this.finalizeNativeGenerate(v,e,t)}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),Wzr(e),Kzr(e,this.modelName)}supportsExecutionControl(){return!0}async executeStream(e,t){return Vzr(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);const r=e.executionControl,n=typeof e.turnTimeoutMs=="number"&&Number.isFinite(e.turnTimeoutMs)&&e.turnTimeoutMs>0,o=r&&r.lifetimeTimeoutMs!==void 0?r.lifetimeTimeoutMs??void 0:n?e.turnTimeoutMs:this.getTimeout(e),s=da(o,this.providerName,"stream"),i=new AbortController,a=Bve([e.abortSignal,s?.controller.signal,i.signal]).signal;let c,l,u,d,m=!1;try{d=!e.disableTools&&this.supportsTools(),c=d?e.tools||await this.getAllTools():{},l=d?gv(c,"input_schema"):void 0;const ae=await this.buildMessagesForStream(e);if(u=xQ(ae),e.schema&&l&&l.length>0){const Pe=FMt(l,Ao(e.schema));l=Pe.tools,m=Pe.applied,Pe.applied&&(u.system=$Mt(u.system))}}catch(ae){throw s?.cleanup(),this.handleProviderError(ae)}const h=this.modelName||Vv(),f=d&&l&&l.length>0?IQ(dD(e,c,d)):void 0,g=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=jMt.startSpan("neurolink.provider.streamText",{kind:zr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":h}}),v=e.maxSteps||Bs,w=this.neurolink?.getEventEmitter(),E=hv(),{push:_}=E,{usagePromise:C,finishPromise:A,resolveUsage:k,resolveFinish:R}=GY();C.then(ae=>{y.setAttribute("gen_ai.usage.input_tokens",ae.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",ae.completionTokens||0),ae.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",ae.cacheReadTokens);const Pe=xi(this.providerName,this.modelName,{input:ae.promptTokens||0,output:ae.completionTokens||0,total:ae.totalTokens||0,...ae.cacheReadTokens?{cacheReadTokens:ae.cacheReadTokens}:{},...ae.cacheCreationTokens?{cacheCreationTokens:ae.cacheCreationTokens}:{}});Pe&&Pe>0&&y.setAttribute("neurolink.cost",Pe)}).catch(()=>{}),A.then(ae=>{y.setAttribute("gen_ai.response.finish_reason",ae||"unknown"),y.end()}).catch(()=>{y.end()});let I;const P=this.client,O=[],U=Date.now(),M={};let F=0,N=0,L=0,q=0,B=null;const H=()=>({promptTokens:F,completionTokens:N,totalTokens:F+L+q+N,...L>0?{cacheReadTokens:L}:{},...q>0?{cacheCreationTokens:q}:{}});let G="",X;const ce=(ae,Pe)=>{const ke=Te=>{if(typeof Te=="string")return Te;try{return JSON.stringify(Te)??""}catch{return""}};return Gt(ke(ae),"anthropic")+Gt(ke(Pe),"anthropic")},Ae=(async()=>{let ae,Pe;const he=EQ({client:P,maxSteps:v,toolsRecord:c,buildParams:se=>{if(l){const re=new Set(l.map(Re=>Re.name)),ye=Object.fromEntries(Object.entries(c).filter(([Re])=>!re.has(Re)));if(Object.keys(ye).length>0){const Re=gv(ye,"input_schema");Re&&Re.length>0&&(l=[...l,...Re])}}const oe=mY(l),Z=vQ({system:u.system,tools:oe,messages:se}),ie=DMt(se,_N-Z),W=hl("anthropic",h,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream");return g&&W.temperature!==void 0&&p.debug("[anthropic] extended thinking is enabled, so temperature is omitted on the stream path \u2014 Anthropic rejects any temperature but 1 while thinking is set"),{model:h,messages:ie,max_tokens:UO(h,e.maxTokens),...u.system?{system:u.system}:{},...!g&&W.temperature!==void 0?{temperature:W.temperature}:{},...oe&&oe.length>0?{tools:oe}:{},...f?{tool_choice:f}:{},...g?{thinking:g}:{}}},planReclaim:se=>{const oe=MMt({conversation:se,availableInputTokens:Pc("anthropic",h,e.maxTokens??void 0),fixedOverheadTokens:ce(u.system,l),provider:"anthropic",observedPromptTokens:ae,previousSentEstimate:Pe,onSentEstimate:re=>{Pe=re}});if(!oe)return;const Z=new Set(oe.drop),ie=new Set(oe.truncate),W=[];for(let re=0;re<se.length;re++){if(Z.has(re))continue;const ye=se[re];if(ie.has(re)&&Array.isArray(ye.content)){W.push({...ye,content:ye.content.map(Re=>Re.type==="tool_result"?{...Re,content:PMt(typeof Re.content=="string"?Re.content:JSON.stringify(Re.content)??"")}:Re)});continue}W.push(ye)}if(Z.size>0){let re=W.findIndex(ye=>Array.isArray(ye.content)&&ye.content.some(Re=>Re.type==="tool_use"||Re.type==="tool_result"));re<0&&(re=Math.min(1,W.length)),W.splice(re,0,{role:"user",content:[{type:"text",text:yQ}]})}return{conversation:W}},...r?{requestTimeoutMs:r.requestTimeoutMs,requireTerminalEvent:!0}:{},noteObservedPromptTokens:se=>{ae=se},...m?{finalResultToolName:mA,onTerminalResult:se=>{X=se,p.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:se.length})}}:{}}),Oe={...he,buildToolResultMessages:(se,oe,Z,ie)=>{for(const ye of Z)O.push(ye.name);const W=Z.map(ye=>({type:"tool-call",toolCallId:ye.id,toolName:ye.name,args:ye.args})),re=Z.map(ye=>ye.error?{type:"tool-result",toolCallId:ye.id,toolName:ye.name,error:ye.error}:{type:"tool-result",toolCallId:ye.id,toolName:ye.name,result:ye.output});return _At(w,re.map(ye=>({toolName:ye.toolName,result:"result"in ye?ye.result:void 0,error:"error"in ye?ye.error:void 0}))),this.handleToolExecutionStorage(W,re,e,new Date).catch(ye=>{p.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ye instanceof Error?ye.message:String(ye)})}),he.buildToolResultMessages(se,oe,Z,ie)}},De={};for(const[se,oe]of Object.entries(c)){const Z=oe.execute;Z&&(De[se]={execute:async(ie,W)=>{const re=W;return Z(ie,{toolCallId:re.toolCallId??"",...re.abortSignal?{abortSignal:re.abortSignal}:{},messages:[]})}})}const Ye=lt.getActiveSpan(),gt=r?.beforeStep,$e=gt?async se=>{const oe=r?.beforeStepTimeoutMs??OK,Z=da(oe,this.providerName,"stream"),ie=F1(se.signal,Z?.controller.signal);try{return await id(Promise.resolve(gt({...se,signal:ie.signal??se.signal})),ie.signal??se.signal)}catch(W){p.warn("[Anthropic] executionControl.beforeStep failed or timed out; the step cap stands",{error:W instanceof Error?W.message:String(W),stepsCompleted:se.stepsCompleted});return}finally{ie.dispose(),Z?.cleanup()}}:void 0,{stream:Ie,resultPromise:ve}=Ld(Oe,u.messages.slice(),{tools:De,...a?{abortSignal:a}:{},...Ye?{span:Ye}:{},...$e?{beforeStep:$e}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{}}),J=(async()=>{for await(const se of Ie)se.reasoning&&_({content:"",reasoning:se.reasoning}),se.content&&(m?G+=se.content:_({content:se.content}))})();let V;try{V=await ve}catch(se){throw await Ff(J,"Anthropic"),se}if(await J,F+=V.usage.inputTokens,N+=V.usage.outputTokens,L+=V.usage.cacheReadTokens??0,q+=V.usage.cacheWriteTokens??0,B=V.rawStopReason??B,V.aborted){const se=a?.aborted?a.reason:void 0;M.stopReason=se instanceof ma?"time-limit":"aborted",M.finishReason="other",V.rawStopReason&&(M.rawFinishReason=V.rawStopReason),k(H()),R("other");return}M.finishReason=V.finishReason,V.rawStopReason&&(M.rawFinishReason=V.rawStopReason),V.finishReason==="tool-calls"&&X===void 0&&(M.stopReason="step-cap"),k(H()),R(B??"stop")})().catch(ae=>{throw I=ae,p.error("Anthropic: Stream error",{error:ae instanceof Error?ae.message:String(ae)}),k(H()),R("error"),this.formatProviderError(ae)}).finally(()=>{if(m){const ae=X??G;ae.length>0&&_({content:ae})}s?.cleanup(),E.close()});Ae.catch(()=>{});const Ee=this.providerName;return{stream:async function*(){let ae=0;try{for await(const Pe of E.iterable)"content"in Pe&&typeof Pe.content=="string"&&Pe.content.length>0&&ae++,yield Pe;if(await Ae,ae===0&&O.length===0){p.warn(`${Ee}: Stream produced no output \u2014 emitting enriched sentinel`);const Pe=new cu({message:"Stream produced no output"}),ke=await Mf(Pe,void 0,I);Of(ke),yield ke}}catch(Pe){const ke=await Mf(Pe,void 0,I);if(Of(ke),yield ke,!cu.isInstance(Pe))throw Pe}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],metadata:M,analytics:A.then(async()=>{const ae=await ZY.createAnalytics(this.providerName,h,{textStream:(async function*(){})(),usage:C,finishReason:A},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Pe=jzr();return Pe&&ae&&(this.recordLimitSnapshot(Pe),ae.limits=Pe),ae})}}async isAvailable(){try{return kQ()||AQ(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}}}),KMt={};ee(KMt,{ANTHROPIC_BETA_HEADERS:()=>xN,AnthropicProvider:()=>WMt,ModelAccessError:()=>AU,getModelCapabilities:()=>hQ,getRecommendedModelForTier:()=>pQ,isModelAvailableForTier:()=>mQ});var lqr=b({"src/lib/providers/anthropic/index.ts"(){"use strict";cqr(),GMt()}}),ng,Ks,uqr,dqr,JMt,YMt,XMt,pA,ZMt,mqr,pqr,hqr,fqr,gqr,yqr,vqr,Tqr,wqr,Eqr,Sqr,bqr,_qr,Cqr,Aqr,kqr,xqr,Iqr,Rqr,Pqr,Mqr,Oqr,Dqr,Nqr,Lqr,Fqr,$qr,Uqr,Bqr,zqr,qqr,Gqr,jqr,Hqr,Vqr,Wqr,Kqr,Jqr,Yqr,QMt=b({"npm-stub:@aws-sdk/client-bedrock-runtime"(){ng={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:ng.get}):new Proxy(function(...r){return new Proxy({},{get:ng.get})},{get:ng.get,apply(r,n,o){return new Proxy({},{get:ng.get})},construct(r,n){return new Proxy({},{get:ng.get})}})}},Ks=new Proxy({},ng),{BedrockClient:uqr,ListFoundationModelsCommand:dqr,BedrockRuntimeClient:JMt,ConverseCommand:YMt,ConverseStreamCommand:XMt,ImageFormat:pA,InvokeModelCommand:ZMt}=Ks,{SageMakerRuntimeClient:mqr,InvokeEndpointCommand:pqr,InvokeEndpointWithResponseStreamCommand:hqr}=Ks,{GoogleAuth:fqr,VertexAI:gqr,TextToSpeechClient:yqr}=Ks,{Webhook:vqr}=Ks,{Hippocampus:Tqr,HippocampusConfig:wqr}=Ks,{createClient:Eqr}=Ks,{Queue:Sqr,Worker:bqr,Job:_qr,QueueScheduler:Cqr,FlowProducer:Aqr}=Ks,{Cron:kqr}=Ks,{parseBuffer:xqr,selectCover:Iqr}=Ks,{extractRawText:Rqr,convertToHtml:Pqr}=Ks,{Hono:Mqr}=Ks,{cors:Oqr,HTTPException:Dqr,logger:Nqr,secureHeaders:Lqr,streamSSE:Fqr,timeout:$qr}=Ks,Uqr=globalThis.fetch,Bqr=globalThis.Request,zqr=globalThis.Response,qqr=globalThis.Headers,Gqr=globalThis.FormData,jqr=globalThis.File,Hqr=globalThis.Blob,Vqr=Ks.Agent,Wqr=Ks.Pool,Kqr=Ks.Client,Jqr=Ks.Dispatcher,Yqr=Ks.MockAgent}});function Xqr(e){if(/^(us|ca)-/.test(e))return"us";if(/^(eu|il|me|af)-/.test(e))return"eu";if(/^ap-northeast-[13]$/.test(e))return"jp";if(/^ap-southeast-[246]$/.test(e))return"au";if(/^ap-/.test(e))return"apac"}function Zqr(e){return/^(us|eu|au|jp|apac|global)\./.test(e)}function e4t(e){if(typeof e!="object"||e===null)return!1;const t=e,r=typeof t.name=="string"?t.name:"",n=typeof t.message=="string"?t.message:"";return!/ValidationException/i.test(r)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function Qqr(e,t){if(e.startsWith("arn:")||Zqr(e))return[];const r=[],n=Xqr(t);return n&&r.push(`${n}.${e}`),r.push(`${n4t}.${e}`),r}function t4t(e,t){return`${e}::${t}`}function eGr(e,t){return MQ.get(t4t(t,e))}function tGr(e,t,r){MQ.set(t4t(t,e),r),p.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:t})}async function r4t(e,t,r){const n=eGr(e,t);if(n&&n!==e)return r(n);try{return await r(e)}catch(o){if(!e4t(o))throw o;const s=Qqr(e,t);if(s.length===0)throw o;p.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:t,candidates:s.length});for(const i of s)try{const a=await r(i);return tGr(e,t,i),a}catch(a){if(!e4t(a))throw a}throw o}}var n4t,MQ,rGr=b({"src/lib/providers/amazonBedrock/inferenceProfile.ts"(){"use strict";z(),n4t="global",MQ=new Map}});function IN(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function o4t(e,t){if(e){if(e.toolUse&&e._inputBuffer){try{e.toolUse.input=JSON.parse(e._inputBuffer)}catch{e.toolUse.input={}}delete e._inputBuffer}t&&!e.toolUse&&(e.text=t)}}function s4t(e){return e.filter(t=>t.toolUse).map(t=>({id:t.toolUse?.toolUseId??IN(),name:t.toolUse?.name??"",args:t.toolUse?.input??{}}))}async function nGr(e,t,r){const n=[],o=new Map,s=new Map,i=f=>{let g=o.get(f);return g||(g={},o.set(f,g),n.push(g)),g};let a="",c,l=0,u=0,d=0,m=0;if(e.stream)for await(const f of e.stream){if(r.aborted)break;const g=f;if(g.contentBlockStart&&i(g.contentBlockStart.contentBlockIndex??0),g.contentBlockDelta?.delta?.text){const y=g.contentBlockDelta.contentBlockIndex??0,v=g.contentBlockDelta.delta.text;i(y),a+=v,s.set(y,(s.get(y)??"")+v),t.push({content:v})}if(g.contentBlockStart?.start?.toolUse){const y=i(g.contentBlockStart.contentBlockIndex??0);y.toolUse={name:g.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:g.contentBlockStart.start.toolUse.toolUseId??IN()}}if(g.contentBlockDelta?.delta?.toolUse){const y=i(g.contentBlockDelta.contentBlockIndex??0);y.toolUse??={name:"",input:{},toolUseId:IN()};const v=g.contentBlockDelta.delta.toolUse.input;typeof v=="string"?y._inputBuffer=(y._inputBuffer??"")+v:typeof v=="object"&&v!==null&&!Array.isArray(v)&&(y.toolUse.input={...y.toolUse.input??{},...v})}if(g.contentBlockStop){const y=g.contentBlockStop.contentBlockIndex??0;o4t(o.get(y),s.get(y)??"")}if(g.messageStop){c=g.messageStop.stopReason??"end_turn";continue}if(g.metadata?.usage){l+=g.metadata.usage.inputTokens??0,u+=g.metadata.usage.outputTokens??0,d+=g.metadata.usage.cacheReadInputTokens??0,m+=g.metadata.usage.cacheWriteInputTokens??0;break}}for(const[f,g]of o)o4t(g,s.get(f)??"");const h=n.filter(f=>f.text||f.toolUse||f.image||f.document);return{text:a,toolCalls:s4t(h),usage:{inputTokens:l,outputTokens:u,cacheReadTokens:d,cacheWriteTokens:m},rawStopReason:c,raw:h}}function oGr(e){const t=[];let r="";for(const n of e.output?.message?.content??[]){const o={};"text"in n&&n.text&&(o.text=n.text,r+=r?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??IN(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),t.push(o)}return{text:r,toolCalls:s4t(t),usage:{inputTokens:e.usage?.inputTokens??0,outputTokens:e.usage?.outputTokens??0,cacheReadTokens:e.usage?.cacheReadInputTokens??0,cacheWriteTokens:e.usage?.cacheWriteInputTokens??0},rawStopReason:e.stopReason,raw:t}}function i4t(e){return{providerLabel:"bedrock",maxSteps:e.maxSteps,buildStepRequest(t,r){return{raw:e.buildCommandInput(t,r)}},async executeStep(t,r,n){const o=t.raw;if(!e.streaming){const i=await r4t(o.modelId??"",e.region,a=>ze(e.client.send(new YMt({...o,modelId:a}),{abortSignal:n}),OQ,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return oGr(i)}const s=await r4t(o.modelId??"",e.region,i=>ze(e.client.send(new XMt({...o,modelId:i}),{abortSignal:n}),OQ,new Error("Bedrock streaming API call timed out")));return nGr(s,r,n)},buildToolResultMessages(t,r,n){const o={role:"assistant",content:r.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...t,o,s]},mapFinishReason(t,r){switch(t){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return r?"tool-calls":"stop"}}}}var OQ,sGr=b({"src/lib/providers/amazonBedrock/loopAdapter.ts"(){"use strict";QMt(),Ze(),rGr(),OQ=12e4}});function a4t(e,t,r){return{input:{text:e.input?.text||"",images:e.input?.images,content:e.input?.content,files:e.input?.files,csvFiles:e.input?.csvFiles,pdfFiles:e.input?.pdfFiles,audioFiles:e.input?.audioFiles,videoFiles:e.input?.videoFiles},csvOptions:e.csvOptions,pdfOptions:e.pdfOptions,imageOptions:e.imageOptions,videoOptions:e.videoOptions,officeOptions:e.officeOptions,systemPrompt:e.systemPrompt,conversationHistory:e.conversationMessages,provider:t,model:r,temperature:e.temperature,maxTokens:e.maxTokens,enableAnalytics:e.enableAnalytics,enableEvaluation:e.enableEvaluation,context:e.context,fileRegistry:e.fileRegistry}}var iGr=b({"src/lib/utils/multimodalOptionsBuilder.ts"(){"use strict"}}),RN,c4t=b({"src/lib/providers/amazonBedrock/constants.ts"(){"use strict";Ka(),RN=Be.provider}}),l4t={};ee(l4t,{Agent:()=>Z4t,BedrockClient:()=>d4t,BedrockRuntimeClient:()=>p4t,Blob:()=>X4t,Client:()=>eOt,ConverseCommand:()=>h4t,ConverseStreamCommand:()=>f4t,Cron:()=>O4t,Dispatcher:()=>tOt,File:()=>Y4t,FlowProducer:()=>M4t,FormData:()=>J4t,GoogleAuth:()=>E4t,HTTPException:()=>B4t,Headers:()=>K4t,Hippocampus:()=>C4t,HippocampusConfig:()=>A4t,Hono:()=>$4t,ImageFormat:()=>g4t,InvokeEndpointCommand:()=>T4t,InvokeEndpointWithResponseStreamCommand:()=>w4t,InvokeModelCommand:()=>y4t,Job:()=>R4t,ListFoundationModelsCommand:()=>m4t,MockAgent:()=>oOt,Pool:()=>Q4t,Queue:()=>x4t,QueueScheduler:()=>P4t,Request:()=>V4t,Response:()=>W4t,SageMakerRuntimeClient:()=>v4t,TextToSpeechClient:()=>b4t,VertexAI:()=>S4t,Webhook:()=>_4t,Worker:()=>I4t,convertToHtml:()=>F4t,cors:()=>U4t,createClient:()=>k4t,default:()=>u4t,extractRawText:()=>L4t,fetch:()=>H4t,getGlobalDispatcher:()=>nOt,interceptors:()=>sOt,logger:()=>z4t,parseBuffer:()=>D4t,request:()=>iOt,secureHeaders:()=>q4t,selectCover:()=>N4t,setGlobalDispatcher:()=>rOt,streamSSE:()=>G4t,timeout:()=>j4t});var og,us,u4t,d4t,m4t,p4t,h4t,f4t,g4t,y4t,v4t,T4t,w4t,E4t,S4t,b4t,_4t,C4t,A4t,k4t,x4t,I4t,R4t,P4t,M4t,O4t,D4t,N4t,L4t,F4t,$4t,U4t,B4t,z4t,q4t,G4t,j4t,H4t,V4t,W4t,K4t,J4t,Y4t,X4t,Z4t,Q4t,eOt,tOt,rOt,nOt,oOt,sOt,iOt,aGr=b({"npm-stub:@aws-sdk/client-bedrock"(){og={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:og.get}):new Proxy(function(...r){return new Proxy({},{get:og.get})},{get:og.get,apply(r,n,o){return new Proxy({},{get:og.get})},construct(r,n){return new Proxy({},{get:og.get})}})}},us=new Proxy({},og),u4t=us,{BedrockClient:d4t,ListFoundationModelsCommand:m4t,BedrockRuntimeClient:p4t,ConverseCommand:h4t,ConverseStreamCommand:f4t,ImageFormat:g4t,InvokeModelCommand:y4t}=us,{SageMakerRuntimeClient:v4t,InvokeEndpointCommand:T4t,InvokeEndpointWithResponseStreamCommand:w4t}=us,{GoogleAuth:E4t,VertexAI:S4t,TextToSpeechClient:b4t}=us,{Webhook:_4t}=us,{Hippocampus:C4t,HippocampusConfig:A4t}=us,{createClient:k4t}=us,{Queue:x4t,Worker:I4t,Job:R4t,QueueScheduler:P4t,FlowProducer:M4t}=us,{Cron:O4t}=us,{parseBuffer:D4t,selectCover:N4t}=us,{extractRawText:L4t,convertToHtml:F4t}=us,{Hono:$4t}=us,{cors:U4t,HTTPException:B4t,logger:z4t,secureHeaders:q4t,streamSSE:G4t,timeout:j4t}=us,H4t=globalThis.fetch,V4t=globalThis.Request,W4t=globalThis.Response,K4t=globalThis.Headers,J4t=globalThis.FormData,Y4t=globalThis.File,X4t=globalThis.Blob,Z4t=us.Agent,Q4t=us.Pool,eOt=us.Client,tOt=us.Dispatcher,rOt=()=>{},nOt=()=>us,oOt=us.MockAgent,sOt={redirect:()=>e=>e,retry:()=>e=>e},iOt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}});async function DQ(){return await Promise.resolve().then(()=>(aGr(),l4t))}var aOt=b({"src/lib/providers/amazonBedrock/utils.ts"(){"use strict"}});function cGr(e){const t=(e??"").split(";").at(0)?.trim().toLowerCase();return NQ[t??""]}var NQ,cOt,lGr=b({"src/lib/providers/amazonBedrock/client.ts"(){"use strict";QMt(),hr(),Xb(),ec(),Lo(),ZO(),Zm(),Ic(),sGr(),ut(),qi(),Ze(),vf(),z(),ud(),Z4(),iGr(),ui(),Xt(),c4t(),aOt(),NQ={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},cOt=class k0r extends ba{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(t){return t?t.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(t,r,n,o){super(t,"bedrock",r);const s=t||process.env.BEDROCK_MODEL||this.modelName,i=k0r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",p.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),p.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{p.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new JMt({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),p.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw p.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){const{BedrockClient:t,ListFoundationModelsCommand:r}=await DQ(),n=new t({region:this.region});try{p.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");const o=new r({}),s=Date.now();await n.send(o);const i=Date.now()-s;p.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){const s=o instanceof Error?o.message:String(o);p.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(t){p.debug("[AmazonBedrockProvider] generate() called with conversation management");const r=Date.now(),n=typeof t=="string"?{prompt:t}:t;this.conversationHistory=[];const o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});const f=a4t(n,this.providerName,this.modelName),g=await J4(f,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(g)}else{p.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");const h={role:"user",content:[{text:n.prompt||o?.text||""}]};this.conversationHistory.push(h)}p.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c,l,u;try{({text:i,usage:a,finishReason:c,rawFinishReason:l,toolExecutions:u}=await this.conversationLoop(n))}catch(h){const f=this.neurolink?.getEventEmitter();throw f&&(f.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:h instanceof Error?h.message:String(h)}),h&&typeof h=="object"&&(h._generationEndEmitted=!0)),h}const d=this.neurolink?.getEventEmitter();d&&d.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:c},success:!0});const m={content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...c!==void 0&&{finishReason:c},...l!==void 0&&{rawFinishReason:l},toolsUsed:u.filter(h=>h.error===void 0).map(h=>h.name),toolCalls:u.map(h=>({toolCallId:h.id,toolName:h.name,args:h.input})),toolExecutions:af(n,bd(u)),enhancedWithTools:u.some(h=>h.error===void 0)};return m._generationEndEmitted=!0,m}async conversationLoop(t){const r=t.maxSteps||Bs,n=await this.resolveTurnTools(t.tools,t.disableTools),o=this.formatToolsForBedrock(n),s=hl(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converse"),i=i4t({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:r,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{const{resultPromise:a}=Ld(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),c=await a;this.conversationHistory=c.conversation;const l=c.usage.inputTokens,u=c.usage.outputTokens,d=c.usage.cacheReadTokens??0,m=c.usage.cacheWriteTokens??0;return{text:c.text||"",usage:{input:l,output:u,total:l+d+m+u,...d>0&&{cacheReadTokens:d},...m>0&&{cacheCreationTokens:m}},finishReason:c.finishReason,rawFinishReason:c.rawStopReason,toolExecutions:c.toolExecutions}}catch(a){throw p.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(t){return t.map(r=>({role:r.role,content:r.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(t,r,n,o){return RN.startActiveSpan("bedrock.tool.execute",{kind:zr.CLIENT,attributes:{"gen_ai.tool.name":r,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(p.debug(`[AmazonBedrockProvider] Executing single tool: ${r}`,{args:n}),!t[r])throw new Error(`Tool not found: ${r}`);const i=t[r];if(!i||!i.execute)throw new Error(`Tool ${r} does not have execute method`);const a=n||{};r==="list_directory"&&!a.path&&(a.path=".",p.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),p.debug("[AmazonBedrockProvider] Tool input parameters:",a);const c={};for(const[d,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(c[d]=m);const l=await i.execute(c);p.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:r,result:l});let u;if(l&&typeof l=="object"&&"success"in l)if(l.success&&l.data!==void 0)typeof l.data=="string"?u=l.data:typeof l.data=="object"?u=JSON.stringify(l.data,null,2):u=String(l.data);else if(l.error){const d=typeof l.error=="string"?l.error:l.error.message||"Tool execution failed";throw new Error(d)}else u="";else typeof l=="string"?u=l:typeof l=="object"?u=JSON.stringify(l,null,2):u=String(l);return s.setStatus({code:Ue.OK}),u}catch(i){throw p.error("[AmazonBedrockProvider] Tool execution error:",{toolName:r,error:i}),s.setStatus({code:Ue.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(t,r){if(r)return{};const n=t??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(t){const r={};for(const n of Object.keys(t))r[n]={execute:o=>this.executeSingleTool(t,n,o)};return r}convertAISDKToolsToToolDefinitions(t){const r={};for(const[n,o]of Object.entries(t))if("description"in o&&o.description){const i=o.parameters??o.inputSchema;r[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return r}formatToolsForBedrock(t){if(!t||Object.keys(t).length===0)return null;const r=Object.entries(t).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=Ao(o.parameters):s=o.parameters:s={type:"object",properties:{},required:[]},(!s.type||s.type!=="object")&&(s={type:"object",properties:s.properties||{},required:s.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:s}}}});return p.debug(`[AmazonBedrockProvider] Formatted ${r.length} tools for Bedrock`),{tools:r}}convertToBedrockMessages(t){return t.map(r=>{const n={role:r.role==="system"?"user":r.role,content:[]};return typeof r.content=="string"?n.content.push({text:r.content}):r.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){const s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image;let i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?pA.JPEG:i==="png"?pA.PNG:i==="gif"?pA.GIF:pA.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){const a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?Bm.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(t){return p.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),p.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),RN.startActiveSpan("bedrock.stream",{kind:zr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async r=>{try{if(p.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(t.input?.images?.length||t.input?.content?.length||t.input?.files?.length||t.input?.csvFiles?.length||t.input?.pdfFiles?.length)){p.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!t.input?.images?.length,imageCount:t.input?.images?.length||0,hasContent:!!t.input?.content?.length,contentCount:t.input?.content?.length||0,hasFiles:!!t.input?.files?.length,fileCount:t.input?.files?.length||0,hasCSVFiles:!!t.input?.csvFiles?.length,csvFileCount:t.input?.csvFiles?.length||0,hasPDFFiles:!!t.input?.pdfFiles?.length,pdfFileCount:t.input?.pdfFiles?.length||0});const s=a4t(t,this.providerName,this.modelName),i=await J4(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{p.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");const s={role:"user",content:[{text:t.input.text}]};this.conversationHistory.push(s)}p.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),p.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");const o=await this.streamingConversationLoop(t,r);return p.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),r.setStatus({code:Ue.OK}),r.end(),o}catch(n){p.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");const o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(p.debug("[TRACE] executeStream CATCH - checking if permission error"),p.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){p.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),p.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),r.addEvent("stream.fallback_to_generate",{reason:o.message});const i=await this.generate({prompt:t.input.text,input:t.input,maxTokens:t.maxTokens,temperature:t.temperature,systemPrompt:t.systemPrompt});if(!i)throw r.setStatus({code:Ue.ERROR,message:"Generate method returned null result"}),r.end(),new Error("Generate method returned null result");r.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),r.setStatus({code:Ue.OK}),r.end();const a=new ReadableStream({start(l){const d=(i.content||"").split(/(\s+)/);let m="";for(let h=0;h<d.length;h++)m+=d[h],(h===d.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(l.enqueue({content:m}),m="");m.length>0&&l.enqueue({content:m}),l.close()}});return{stream:{async*[Symbol.asyncIterator](){const l=a.getReader();try{for(;;){const{done:u,value:d}=await l.read();if(u)break;yield d}}finally{l.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw r.setStatus({code:Ue.ERROR,message:o instanceof Error?o.message:String(o)}),r.recordException(o instanceof Error?o:new Error(String(o))),r.end(),n}})}async streamingConversationLoop(t,r){const n=Date.now(),o=t.maxSteps||Bs,s=await this.resolveTurnTools(t.tools,t.disableTools),i=this.formatToolsForBedrock(s),a=hl(this.providerName,this.modelName||this.getDefaultModel(),{temperature:t.temperature??.7},"bedrock.converseStream"),c=i4t({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:k=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(k),system:[{text:t.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:t.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})});let l=!1,u;const d=new Promise(k=>{u=()=>{l=!0,k()}}),m={...c,executeStep:async(k,R,I)=>{const P=await c.executeStep(k,R,I);return u(),P}};r.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});const{stream:h,resultPromise:f}=Ld(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:t.abortSignal,...t.toolTimeoutMs!==void 0?{toolTimeoutMs:t.toolTimeoutMs}:{}}),g=f.then(k=>({result:k,error:void 0}),k=>({result:void 0,error:k}));if(await Promise.race([d,g]),!l){const k=await g;if(k.error)throw k.error}const y=this.neurolink?.getEventEmitter(),v=this,w={startTime:n,streamId:`bedrock-${Date.now()}`};let E;const _=new Promise(k=>{E=k}),C=k=>{const R=k?.inputTokens??0,I=k?.outputTokens??0,P=k?.cacheReadTokens??0,O=k?.cacheWriteTokens??0;return{input:R,output:I,total:R+P+O+I,...P>0&&{cacheReadTokens:P},...O>0&&{cacheCreationTokens:O}}};return g.then(k=>{E(I0(this.providerName,this.modelName||this.getDefaultModel(),{usage:C(k.result?.usage),toolExecutions:k.result?.toolExecutions??[],toolsUsed:(k.result?.toolExecutions??[]).filter(R=>R.error===void 0).map(R=>R.name)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let k=!1;try{yield*h}catch(R){throw k=!0,R}finally{const R=await g;R.error&&(k=!0);const I=C(R.result?.usage);if(R.result&&(v.conversationHistory=R.result.conversation,w.finishReason=R.result.finishReason,w.rawFinishReason=R.result.rawStopReason,r.setAttribute("gen_ai.response.stop_reason",R.result.rawStopReason??"unknown")),y){const P=t._streamDedupContext;P&&(P.providerEmitted=!0),y.emit("generation:end",{provider:v.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:I,model:v.modelName||v.getDefaultModel(),provider:v.providerName,finishReason:k?"error":R.result?.rawStopReason},success:!k})}}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:_,metadata:w}}async checkBedrockHealth(){const t=new AbortController,r=setTimeout(()=>t.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await DQ(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{p.debug("[AmazonBedrockProvider] Starting health check...");const i=new o({}),c=(await s.send(i,{abortSignal:t.signal})).modelSummaries||[],l=c.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(p.debug(`[AmazonBedrockProvider] Health check passed - Found ${l.length} active models out of ${c.length} total models`),l.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(r);const a=i;if(cr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});const c=typeof a.message=="string"?a.message:"";throw c.includes("UnauthorizedOperation")||c.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:i}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:i}):(p.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${c||"Unknown error"}`,{cause:i}))}finally{clearTimeout(r);try{s.destroy()}catch{}}}formatProviderError(t){return ha(t,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Mr,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:$s,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:ot,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:ot,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(t,r){const n=typeof t=="string"?{text:t}:t,o=r||this.getDefaultEmbeddingModel(),s=o.includes("nova")&&o.includes("multimodal"),i=o.includes("image")||o.includes("multimodal")||o==="amazon.titan-embed-image-v1"||s;p.debug("Generating embedding",{provider:this.providerName,model:o,hasText:typeof n.text=="string",hasImage:n.image!==void 0,isMultiModalModel:i});try{let a;if(n.image&&!i)throw new ot(`${this.providerName} model ${o} does not support image embeddings`,this.providerName);if(s){if(n.image&&n.text)throw new ot(`${this.providerName} model ${o} does not support combined image+text embeddings; provide exactly one of image or text`,this.providerName);const m={embeddingPurpose:"GENERIC_RETRIEVAL"};if(n.image){const h=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64"),f=cGr(n.mimeType);if(f===void 0)throw new ot(`${this.providerName} model ${o} does not support image format '${n.mimeType??"unknown"}'; supported formats are ${Object.keys(NQ).join(", ")}`,this.providerName);m.image={detailLevel:"STANDARD_IMAGE",format:f,source:{bytes:no.safeBase64Convert(h,"bedrock nova embed image")}}}n.text&&(m.text={value:n.text,truncationMode:"NONE"}),a=JSON.stringify({taskType:"SINGLE_EMBEDDING",singleEmbeddingParams:m})}else if(n.image){const m=Buffer.isBuffer(n.image)?n.image:Buffer.from(n.image,"base64");a=JSON.stringify({inputText:n.text??"",inputImage:no.safeBase64Convert(m,"bedrock titan embed image")})}else a=JSON.stringify({inputText:n.text??""});const c=new ZMt({modelId:o,contentType:"application/json",accept:"application/json",body:a}),l=await ze(this.bedrockClient.send(c),6e4,new Error("Bedrock embedding API call timed out")),u=JSON.parse(new TextDecoder().decode(l.body)),d=s?u.embeddings?.at(0)?.embedding:u.embedding;if(!Array.isArray(d))throw new Error("Invalid embedding response from Bedrock");return p.debug("Embedding generated successfully",{provider:this.providerName,model:o,embeddingDimension:d.length}),d}catch(a){throw p.error("Embedding generation failed",{error:a instanceof Error?a.message:String(a),model:o}),this.handleProviderError(a)}}async embedMany(t,r){const n=r||this.getDefaultEmbeddingModel();p.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:t.length});try{const o=await Promise.all(t.map(s=>this.embed(s,n)));return p.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw p.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:t.length}),this.handleProviderError(o)}}}}}),lOt={};ee(lOt,{AmazonBedrockProvider:()=>cOt,bedrockTracer:()=>RN,loadBedrockControl:()=>DQ});var uGr=b({"src/lib/providers/amazonBedrock/index.ts"(){"use strict";lGr(),c4t(),aOt()}}),uOt={};ee(uOt,{AzureOpenAIProvider:()=>dOt});var dOt,dGr=b({"src/lib/providers/azureOpenai.ts"(){"use strict";ut(),z(),qi(),ts(),Ic(),kl(),vp(),dOt=class extends Lc{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,r,n){const o=n?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",s=process.env.AZURE_OPENAI_ENDPOINT||"";let i;if(s)try{i=new URL(s.includes("://")?s:`https://${s}`)}catch{i=void 0}const a=i?.hostname??"",c=i?.pathname&&i.pathname!=="/"?i.pathname.replace(/\/+$/,""):"",l=/\.(openai|cognitiveservices)\.azure\.com$/.test(a);let u;l?u="/openai":u=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;const d=i?.origin??"",m=n?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=n?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",f=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,g=n?.useMaxCompletionTokens??(f===void 0?void 0:/^(1|true|yes)$/i.test(f));o||fa(MCr()),d||fa(OCr()),super("azure",e,t,{baseURL:d,apiKey:o}),this.azureDeployment=m,this.azureApiVersion=h,this.azureResourceOrigin=d,this.azureDeploymentPathPrefix=u,this.useMaxCompletionTokensOverride=g,p.shouldLog("debug")&&p.debug("Azure OpenAI Provider initialized",F7e({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){const t=[{match:r=>/401/.test(r.message),errorClass:Mr,message:"Invalid Azure OpenAI API key or endpoint."},..._c];return ha(e,t,this.providerName,this.modelName)}getChatCompletionsURL(e){const t=e||this.azureDeployment,r=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${r}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){const r=this.useMaxCompletionTokensOverride??hAt(t);return e.max_tokens!==void 0&&r?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}}});function LQ(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"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&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function hA(e){return LQ(e)??"image/png"}var PN=b({"src/lib/utils/imageDetection.ts"(){"use strict"}});function mOt(e){return e.map(t=>typeof t.content=="string"?{role:t.role,content:t.content}:{role:t.role,content:t.content.map(r=>r.type==="image"||r.type==="document"?{type:r.type,media_type:r.source.media_type,base64_chars:r.source.data.length}:r)})}var mGr=b({"src/lib/utils/anthropicTraceSanitizer.ts"(){"use strict"}}),MN,pGr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs"(){MN=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}}}),hGr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs"(){So()}});function FQ(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var ON,$Q,pOt=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs"(){hGr(),ON=e=>(ON=Array.isArray,ON(e)),$Q=ON}});function*fGr(e){if(!e)return;if(UQ in e){const{values:n,nulls:o}=e;yield*n.entries();for(const s of o)yield[s,null];return}let t=!1,r;e instanceof Headers?r=e.entries():$Q(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const s=$Q(n[1])?n[1]:[n[1]];let i=!1;for(const a of s)a!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var UQ,hOt,gGr=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs"(){pOt(),UQ=Symbol.for("brand.privateNullableHeaders"),hOt=e=>{const t=new Headers,r=new Set;for(const n of e){const o=new Set;for(const[s,i]of fGr(n)){const a=s.toLowerCase();o.has(a)||(t.delete(s),o.add(a)),i===null?(t.delete(s),r.add(a)):(t.append(s,i),r.delete(a))}}return{[UQ]:!0,values:t,nulls:r}}}});function yGr(e){const t=new nA(e);return delete t.batches,t}function vGr(e){const t=new Xi(e);return delete t.messages.batches,t}var fOt,gOt,BQ,yOt=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/client.mjs"(){wN(),yRt(),L_(),pGr(),pOt(),gGr(),wN(),fOt="vertex-2023-10-16",gOt=new Set(["/v1/messages","/v1/messages?beta=true"]),BQ=class extends xo{constructor({baseURL:e=MN("ANTHROPIC_VERTEX_BASE_URL"),region:t=MN("CLOUD_ML_REGION")??null,projectId:r=MN("ANTHROPIC_VERTEX_PROJECT_ID")??null,...n}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...n}),this.messages=yGr(this),this.beta=vGr(this),this.region=t,this.projectId=r,this.accessToken=n.accessToken??null,n.authClient&&n.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");n.authClient?this._authClientPromise=Promise.resolve(n.authClient):(this._auth=n.googleAuth??new IW({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){const t=await this._authClientPromise,r=await t.getRequestHeaders(),n=t.projectId??r["x-goog-user-project"];!this.projectId&&n&&(this.projectId=n),e.headers=hOt([r,e.headers])}async buildRequest(e){if(FQ(e.body)&&(e.body={...e.body}),FQ(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=fOt)),gOt.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!FQ(e.body))throw new Error("Expected request body to be an object for post /v1/messages");const t=e.body.model;e.body.model=void 0;const n=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${n}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}}}),zQ={};ee(zQ,{AnthropicVertex:()=>BQ,BaseAnthropic:()=>xo,default:()=>BQ});var vOt=b({"node_modules/.pnpm/@anthropic-ai+vertex-sdk@0.16.0_zod@4.3.6/node_modules/@anthropic-ai/vertex-sdk/index.mjs"(){yOt(),yOt()}});async function TGr(){return DN||(DN=await Promise.resolve().then(()=>(vOt(),zQ))),DN}function wGr(e){const t=[],r=new Map;let n=0;const o=s=>{const i=`${n}:${s??"x"}`;let a=r.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},r.set(i,a),t.push(a)),a};for(const s of e){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}const i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,t.push({type:"regular",role:i,parts:[s.content]}))}return t}function qQ(e,t,r){const n=e[e.length-1];n&&n.role===t&&Array.isArray(n.content)?n.content.push(...r):e.push({role:t,content:[...r]})}function EGr(e,t){const r=e.callParts,n=e.resultParts,o=Math.min(r.length,n.length);(o!==r.length||o!==n.length)&&p.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:r.length,results:n.length,paired:o});const s=[],i=[];for(let a=0;a<o;a++){const c=`hist_${t}_${a}`;s.push({type:"tool_use",id:c,name:r[a].name,input:r[a].input}),i.push({type:"tool_result",tool_use_id:c,content:n[a]})}return{uses:s,results:i}}function SGr(e){const t=r=>Array.isArray(r.content)&&r.content.length>0&&r.content.every(n=>n.type==="tool_result");for(;e.length>0&&(e[0].role!=="user"||t(e[0]));)e.shift()}function GQ(e){const t=[];let r=0;for(const n of wGr(e)){if(n.type==="regular"){qQ(t,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}const{uses:o,results:s}=EGr(n,r);o.length!==0&&(r++,qQ(t,"assistant",o),qQ(t,"user",s))}if(SGr(t),p.shouldLog("debug")){const n=t.flatMap(o=>Array.isArray(o.content)?o.content:[]);p.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:t.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return t}function jQ(e,t){const r=e[e.length-1];if(r&&r.role==="user"){const n=Array.isArray(r.content)?r.content:[{type:"text",text:r.content}],o=Array.isArray(t)?t:[{type:"text",text:t}];r.content=[...n,...o];return}e.push({role:"user",content:t})}function sg(e){if(!e||typeof e!="object")return;const t=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(const n of t)n in e&&delete e[n];typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);const r=2147483647;if(typeof e.maximum=="number"&&e.maximum>r&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-r&&delete e.minimum,e.properties&&typeof e.properties=="object")for(const n of Object.values(e.properties))n&&typeof n=="object"&&sg(n);if(e.items&&typeof e.items=="object")if(Array.isArray(e.items))for(const n of e.items)n&&typeof n=="object"&&sg(n);else sg(e.items);for(const n of["allOf","anyOf","oneOf"])if(Array.isArray(e[n]))for(const o of e[n])o&&typeof o=="object"&&sg(o)}function TOt(e,t,r){const n=gCt({contents:e,availableInputTokens:Pc("vertex",t),provider:"vertex",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 c=e[a];if(s.has(a)&&Array.isArray(c.parts)){i.push({...c,parts:c.parts.map(l=>{if(!("functionResponse"in l))return l;const u=l.functionResponse,d=JSON.stringify(u.response)??"";return d.length<=COt?l:{functionResponse:{name:u.name,response:{result:lY(d)}}}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.parts)&&c.parts.some(l=>!!l.functionCall||!!l.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:dY}]})}return e.length=0,e.push(...i),!0}function wOt(e,t,r){const n=MMt({conversation:e,availableInputTokens:Pc("vertex",t),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:r,observedDescribesCurrentPayload:!0});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 c=e[a];if(s.has(a)&&Array.isArray(c.content)){i.push({...c,content:c.content.map(l=>{if(l.type!=="tool_result")return l;const u=typeof l.content=="string"?l.content:JSON.stringify(l.content)??"";return{...l,content:PMt(u)}})});continue}i.push(c)}if(o.size>0){let a=i.findIndex(c=>Array.isArray(c.content)&&c.content.some(l=>l.type==="tool_use"||l.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:yQ}]})}return e.length=0,e.push(...i),!0}async function EOt(e,t,r={}){const n=[],o=[];let s,i=0,a=0,c=0,l=0;for await(const u of e){r.onProgress?.();const d=u,h=d.candidates?.[0],f=h?.finishReason;typeof f=="string"&&f&&(s=f);const g=h?.content;if(g&&Array.isArray(g.parts))for(const v of g.parts)n.push(v),typeof v.text=="string"&&v.text.length>0&&t.push({content:v.text});u.functionCalls&&o.push(...u.functionCalls);const y=d.usageMetadata;if(y){if(y.promptTokenCount!==void 0&&y.promptTokenCount>0){r.onUsageDelta?.("input",y.promptTokenCount-i),i=y.promptTokenCount,r.onUsage?.(y.promptTokenCount,y.candidatesTokenCount??0);const v=Math.min(y.cachedContentTokenCount??0,y.promptTokenCount);r.onUsageDelta?.("cacheRead",v-c),c=v}y.candidatesTokenCount!==void 0&&y.candidatesTokenCount>0&&(r.onUsageDelta?.("output",y.candidatesTokenCount-a),a=y.candidatesTokenCount),y.thoughtsTokenCount!==void 0&&y.thoughtsTokenCount>0&&(r.onUsageDelta?.("reasoning",y.thoughtsTokenCount-l),l=y.thoughtsTokenCount)}}return{rawResponseParts:n,stepFunctionCalls:o,...s?{finishReason:s}:{},inputTokens:i,outputTokens:a,...c?{cacheReadTokens:c}:{},...l?{reasoningTokens:l}:{}}}var DN,SOt,HQ,fA,VQ,Wv,ig,bOt,_Ot,NN,COt,WQ,bGr=b({"src/lib/providers/googleVertex/client.ts"(){"use strict";on(),HO(),hr(),ec(),k9(),YO(),oW(),Lo(),tf(),of(),cY(),Ut(),On(),ut(),qi(),Ze(),TQ(),mvt(),Z4(),z(),QJ(),vCt(),OMt(),FO(),PN(),GJ(),ts(),ui(),tCt(),$f(),pa(),TCt(),uCt(),ZO(),zMt(),Z_(),fv(),pY(),bl(),i_(),Ka(),Xt(),Ja(),Ic(),Zm(),ud(),mGr(),Z_(),DN=null,SOt=()=>!0,HQ=()=>fa(zCr()),fA=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",VQ=(e,t)=>{const r=t||fA();if(!e)return r;const n=e.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||Fq.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":r},Wv=VQ,ig=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",bOt=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),_Ot=async(e,t,r,n)=>{const o=e||fA();return{projectId:r?r.projectId?.trim()||"express":HQ(),region:o,...t!==void 0&&{timeout:t},maxRetries:0,...n?{baseURL:n}:{},...r?{authClient:{getRequestHeaders:async()=>({Authorization:`Bearer ${r.apiKey}`}),projectId:null}}:{}}},NN=e=>e.toLowerCase().includes("claude"),COt=2048,WQ=class Xr extends ba{projectId;location;expressApiKey;baseURL;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(t,r,n,o,s){super(t,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey),!s.projectId&&!s.location&&(this.expressApiKey=String(s.apiKey))),s.baseURL&&(this.baseURL=String(s.baseURL)));const i=!!this.resolveExpressApiKey();i||bOt()||fa(qCr()),this.projectId=s?.projectId||(i?"":HQ()),this.location=o||s?.location||fA(),p.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),p.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return ig()}async getAISDKModel(){throw new Me({code:je.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(t){this.validateStreamOptions(t)}async preprocessNativeFileInput(t){if(t.input&&mK(t.input),t.input?.files?.length)try{await pK(t,100*1024*1024,this.providerName)}catch(r){p.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${r instanceof Error?r.message:String(r)}`)}await K_(t.input)}async executeStream(t,r){const n=t.model||this.modelName||ig();return j6e({name:"neurolink.provider.stream",tracer:Be.provider,attributes:{[_e.GEN_AI_SYSTEM]:this.providerName,[_e.GEN_AI_MODEL]:n,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName}},async o=>{const s=Date.now(),i=t.tools||{};await this.preprocessNativeFileInput(t);const c={...await dt({name:"neurolink.message.build",tracer:Be.provider,attributes:{[_e.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(t)),tools:i},l=c.input?.text||c.prompt||"";try{let u;NN(n)?(p.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),u=await this.executeNativeAnthropicStream(c)):(p.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),u=await this.executeNativeGemini3Stream(c)),this.attachUsageAndCostAttributes(o,n,u?.usage);const d=this.wrapStreamResultWithLifecycle(t,u,s);return this.emitStreamEnd(n,s,!0,void 0,u.finishReason),d}catch(u){throw this.fireGenerateOnError(t,u,s),this.emitStreamEnd(n,s,!1,u),this.emitGenerationEnd(n,null,s,!1,u,l),u}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(t,r,n,o,s){const i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:t,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(t){kCt("GoogleVertex");const r=this.resolveExpressApiKey(),n=r?"":this.projectId,o=t||this.location||fA(),i=(await Promise.resolve().then(()=>(mb(),d0))).GoogleGenAI;if(!i)throw new Me({code:je.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const a=i,c=this.resolveBaseURL(),l={...c?{baseUrl:c}:{}};return r?new a({vertexai:!0,apiKey:r,httpOptions:l}):new a({vertexai:!0,project:n,location:o,httpOptions:l})}resolveBaseURL(){const t=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim();return t&&t.length>0?t:void 0}resolveExpressApiKey(){const t=this.expressApiKey?.trim();if(t)return t;const r=process.env.GOOGLE_VERTEX_API_KEY?.trim();return r?["GOOGLE_CLOUD_PROJECT_ID","VERTEX_PROJECT_ID","GOOGLE_VERTEX_PROJECT","GOOGLE_CLOUD_PROJECT"].some(o=>(process.env[o]??"").trim().length>0)?void 0:r:void 0}buildAnthropicToolDeclaration(t,r){const n={name:t,description:r.description||`Tool: ${t}`,input_schema:{type:"object"}},s=r.parameters||r.inputSchema;if(s){const i=Ao(s),a=Xn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(t,r,n,o){if(!t||!r)return;const s=new Set(r.map(i=>i.name));for(const[i,a]of Object.entries(t))s.has(i)||(r.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),p.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(t,r,n,o,s){if(!n)return;const i=_Ke(r,t);if(i?.execute)return n.some(a=>a.name===t)||n.push(this.buildAnthropicToolDeclaration(t,i)),o.set(t,i.execute),s.delete(t),p.info(`[GoogleVertex] Tool "${t}" resolved mid-turn via discovery \u2014 executing.`),o.get(t)}buildFinalResultTool(t){const r=Ao(t),n=Xn(r);n.$schema&&delete n.$schema;const o=Hi(n);return{name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",input_schema:{type:"object",properties:o.properties||o,required:o.required||[]}}}async executeNativeGemini3Stream(t){const r=t.model||this.modelName||ig(),n=Wv(r,t.region),o=await this.createVertexGenAIClient(n);p.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:r,hasTools:!!t.tools&&Object.keys(t.tools).length>0,project:this.projectId,location:n});const s=[],i=[{text:t.input.text??""}],a=t.input;if(a?.pdfFiles&&a.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(const Ie of a.pdfFiles){let ve;typeof Ie=="string"?Fo.existsSync(Ie)?ve=Fo.readFileSync(Ie):ve=Buffer.from(Ie,"base64"):ve=Ie;const J=ve.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:J}})}}if(await nY(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(const Ie of a.images){const ve=E_(Ie);let J,V="image/jpeg";if(typeof ve=="string")if(Fo.existsSync(ve)){J=Fo.readFileSync(ve);const oe=k_(ve);V=oe.startsWith("image/")?oe:this.detectImageType(J)}else if(ve.startsWith("data:")){const oe=ve.match(/^data:([^;]+);base64,(.+)$/);if(oe)V=oe[1],J=Buffer.from(oe[2],"base64");else continue}else if(ve.startsWith("http://")||ve.startsWith("https://"))try{const oe=await fetch(ve);if(!oe.ok){p.warn(`[GoogleVertex] Image fetch failed: ${oe.status} ${oe.statusText}, skipping`,{url:rr(ve)});continue}const Z=await oe.arrayBuffer();J=Buffer.from(Z);const ie=oe.headers.get("content-type");ie&&ie.startsWith("image/")&&(V=ie.split(";")[0])}catch(oe){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${oe instanceof Error?oe.message:String(oe)}`,{url:rr(ve)});continue}else J=Buffer.from(ve,"base64"),V=this.detectImageType(J);else J=ve,V=this.detectImageType(J);const se=J.toString("base64");i.push({inlineData:{mimeType:V,data:se}})}}await oY(i,a?.nativeVideoFiles,"vertex",r,"[GoogleVertex]"),KO(s,t.conversationMessages),s.push({role:"user",parts:i});let c;const l=new pv;let u;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){const Ie=gv(t.tools,"functionDeclarations");u=Ie,c=Ie.toolsConfig;for(const[ve,J]of Ie.executeMap)l.set(ve,J);p.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:Ie.toolsConfig[0].functionDeclarations.length,toolNames:Ie.toolsConfig[0].functionDeclarations.map(ve=>ve.name)})}const d=t;let m=!1;if(d.schema&&c){m=!0;const Ie=Ao(d.schema,"openApi3"),ve=Xn(Ie);ve.$schema&&delete ve.$schema;const J=Hi(ve),V=c[0]?.functionDeclarations||[];V.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:J}),c=[{functionDeclarations:V}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(J),totalTools:V.length})}const h=hl(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),f={...h.temperature!==void 0&&{temperature:h.temperature},maxOutputTokens:t.maxTokens};qJ(r)&&(f.maxOutputTokens&&f.maxOutputTokens>Sa&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Sa} for ${r}`),f.maxOutputTokens=Sa),f.maxOutputTokens||(f.maxOutputTokens=Sa)),h.topP!==void 0&&(f.topP=h.topP),t.topK!==void 0&&(f.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(f.stopSequences=t.stopSequences),c&&(f.tools=c);let g=t.systemPrompt||"";m&&(g=g+`
|
|
1113
1113
|
|
|
1114
|
-
IMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.`),g&&(f.systemInstruction=g);const y=eY(t.thinkingConfig,r);if(y&&(f.thinkingConfig=y),(d.output?.format==="json"||d.schema)&&!m&&!c&&(f.responseMimeType="application/json",d.schema)){const xe=Ao(d.schema,"openApi3"),ve=Xn(xe);ve.$schema&&delete ve.$schema;const J=Hi(ve);sg(J),f.responseSchema=J,p.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(J)})}const v=Date.now(),w=t.maxSteps||Bs,E=Number.isFinite(w)&&w>0?Math.min(Math.floor(w),100):Math.min(Bs,100),_=[...s];let C="",A;const k=[],R=[];let I;const P=mv(kd("vertex",r));let O=!1,U=0,M=0,F=0,N=0;const L=[],q=ml(t.timeout)??OS,B=Ih(t.toolTimeoutMs),H=t.turnTimeoutMs??q,G=new AbortController,X=()=>G.abort();t.abortSignal?.addEventListener("abort",X);const ce=dv({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:q,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:xe=>{p.warn(xe==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${H}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),G.abort()}}),Q=G.signal;t.abortSignal?.aborted&&G.abort();let Ie=!1,Ee=!1,le=!1,ae=0;try{const xe=XO({providerLabel:"GoogleVertex",maxSteps:E,toolFailureBreaker:{maxRetries:Rh,consecutive:!0,classifyResultFailure:ie=>lO(ie)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:B,abortSignal:Q,onProgress:()=>ce.noteProgress()},...u?{declarations:u}:{},...m?{finalResultToolName:"final_result",onTerminalResult:ie=>{try{I=JSON.parse(ie)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(ie,W)=>(this.emitTurnEvent({phase:"malformed-retry",step:W+1,maxSteps:E}),[...ie,{role:"user",parts:[{text:"Your previous function call was malformed and could not be parsed. Re-issue it as a single valid function call, or answer in plain text."}]}]),collectStep:(ie,W)=>EOt(ie,W,{onProgress:()=>ce.noteProgress(),onUsage:(re,ye)=>P.noteUsage(re,ye),onUsageDelta:(re,ye)=>{re==="input"?U+=ye:re==="output"?M+=ye:re==="cacheRead"?F+=ye:N+=ye}}),planReclaim:ie=>{if(!P.shouldStop())return;const W=[...ie];return TOt(W,r,P.projectedNextPromptTokens)?(P.resetAfterReclaim(),{conversation:W}):(O=!0,p.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${P.projectedNextPromptTokens} tokens >= threshold ${P.thresholdTokens} \u2014 synthesizing a final answer.`),{stop:!0})},buildRequest:ie=>({model:r,contents:ie,config:{...f,...c?{tools:c}:{}}}),sendStep:async(ie,W)=>{ce.noteProgress();const re=ie;return o.models.generateContentStream({model:re.model,contents:re.contents,config:{...re.config??{},abortSignal:W}})}}),ve={...xe,buildStepRequest:(ie,W)=>(ae=W+1,xe.buildStepRequest(ie,W)),buildToolResultMessages:(ie,W,re,ye)=>{const Re=xe.buildToolResultMessages(ie,W,re,ye);if(ce.shouldNudgeWrapup()){const K=Re[Re.length-1];K&&Array.isArray(K.parts)&&K.parts.push({text:lv(m)})}const x=WO(W.raw.rawResponseParts);Ct(this.handleToolExecutionStorage(re.map((K,Se)=>({toolName:K.name,args:K.args,...Se===0&&x?{thoughtSignature:x}:{},stepIndex:ye+1})),re.map(K=>({toolName:K.name,output:K.output,stepIndex:ye+1})),t,new Date),Ph,"tool storage write timed out").catch(K=>{p.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:K instanceof Error?K.message:String(K)})});try{const K=Re[Re.length-1];P.noteAppendedChars(JSON.stringify(K?.parts??[]).length)}catch{}return Re}},{stream:J,resultPromise:V}=Ld(ve,_,{tools:VO(u,t.tools,{toolTimeoutMs:B,abortSignal:Q,onProgress:()=>ce.noteProgress()}),abortSignal:Q,toolTimeoutMs:B}),se=(async()=>{for await(const ie of J)ie.content&&L.push(ie.content)})();let oe,Z;try{oe=await V}catch(ie){Z=ie}if(await Ff(se,"GoogleVertex"),Z!==void 0)if(Q.aborted||mp(Z))Ie=!0;else throw p.error("[GoogleVertex] Native SDK error",Z),this.handleProviderError(Z);if(oe){C=oe.text,A=oe.rawStopReason??A;for(const ie of oe.toolCalls)k.push({toolName:ie.name,args:ie.args});for(const ie of oe.toolExecutions)R.push({name:ie.name,input:ie.input,output:ie.output});_.length=0,_.push(...oe.conversation)}if(Q.aborted&&(Ie=!0),!C&&(ae>=E||Ie||O)){Ee=ae>=E&&!Ie;const ie=k.filter(W=>W.toolName!=="final_result").length;if(L.length>0)p.warn(O?"[GoogleVertex] Tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${E}); returning text already gathered from prior steps.`);else if(Ie)p.warn(`[GoogleVertex] Tool call loop ended mid-turn (${ce.timedOut?"turn time limit":ce.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),C=this.buildLoopExitMessage({turnClock:ce,wasAborted:Ie,stallTimeoutMs:t.stallTimeoutMs,maxSteps:E,toolCallCount:ie});else{p.warn(O?"[GoogleVertex] Tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${E}) with no text; synthesizing a final answer with tools disabled.`);const W=await this.synthesizeFinalAnswerWithoutTools(o,r,f,_,m,ml(t.timeout)??OS,Q);W.text?(le=!0,C=W.text,L.push(W.text),U+=W.inputTokens,M+=W.outputTokens,N+=W.reasoningTokens??0,W.finishReason&&(A=W.finishReason)):C=O?Nc(ie):pp(E,ie)}}}finally{ce.dispose(),t.abortSignal?.removeEventListener("abort",X)}const Pe=Ee&&!le?"tool-calls":dC(A),Ae=uv({timedOut:ce.timedOut,stalled:ce.stalled,wasAborted:Ie,cappedWithoutAnswer:Ee&&!le,contextCappedWithoutAnswer:O&&!le,finishReason:Pe});Ae!=="completed"&&this.emitTurnEvent({phase:Ae,step:ae,maxSteps:E,toolCallCount:k.filter(xe=>xe.toolName!=="final_result").length,elapsedMs:ce.elapsedMs()});const Te=Date.now()-v,he=I?[C]:L.length>0?L:[C];async function*Oe(){for(const xe of he)xe.length>0&&(yield{content:xe})}const De=k.filter(xe=>xe.toolName!=="final_result"),Ye=R.filter(xe=>xe.name!=="final_result"),gt=Math.max(0,U-F),$e={stream:Oe(),provider:this.providerName,model:r,finishReason:Pe,stopReason:Ae,rawFinishReason:A,usage:{input:gt,output:M+N,total:gt+F+M+N,...F>0&&{cacheReadTokens:F},...N>0&&{reasoning:N}},toolCalls:De.map(xe=>({toolName:xe.toolName,args:xe.args})),toolsUsed:De.map(xe=>xe.toolName),toolExecutions:bd(Ye),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:v,responseTime:Te,totalToolExecutions:De.length,stopReason:Ae,rawFinishReason:A,stepsUsed:ae}};return I&&($e.structuredOutput=I),$e}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||ig(),n=Wv(r,t.region),o=await this.createVertexGenAIClient(n);p.debug("[GoogleVertex] Using native @google/genai for Gemini 3 generate",{model:r,project:this.projectId,location:n});const s=t.input?.text||t.prompt||"Please respond.",i=[],a=[{text:s}],c=t.input;if(c?.pdfFiles&&c.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${c.pdfFiles.length} PDF file(s) for native generate`);for(const $e of c.pdfFiles){let xe;typeof $e=="string"?Fo.existsSync($e)?xe=Fo.readFileSync($e):xe=Buffer.from($e,"base64"):xe=$e;const ve=xe.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:ve}})}}if(await nY(a,c?.nativeAudioFiles,"[GoogleVertex]"),c?.images&&c.images.length>0){p.debug(`[GoogleVertex] Processing ${c.images.length} image(s) for native generate`);for(const $e of c.images){const xe=E_($e);let ve,J="image/jpeg";if(typeof xe=="string")if(Fo.existsSync(xe)){ve=Fo.readFileSync(xe);const se=k_(xe);J=se.startsWith("image/")?se:this.detectImageType(ve)}else if(xe.startsWith("data:")){const se=xe.match(/^data:([^;]+);base64,(.+)$/);if(se)J=se[1],ve=Buffer.from(se[2],"base64");else continue}else if(xe.startsWith("http://")||xe.startsWith("https://"))try{const se=await fetch(xe);if(!se.ok){p.warn(`[GoogleVertex] Image fetch failed: ${se.status} ${se.statusText}, skipping`,{url:rr(xe)});continue}const oe=await se.arrayBuffer();ve=Buffer.from(oe);const Z=se.headers.get("content-type");Z&&Z.startsWith("image/")&&(J=Z.split(";")[0])}catch(se){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${se instanceof Error?se.message:String(se)}`,{url:rr(xe)});continue}else ve=Buffer.from(xe,"base64"),J=this.detectImageType(ve);else ve=xe,J=this.detectImageType(ve);const V=ve.toString("base64");a.push({inlineData:{mimeType:J,data:V}})}}await oY(a,c?.nativeVideoFiles,"vertex",r,"[GoogleVertex]"),KO(i,t.conversationMessages),i.push({role:"user",parts:a});const l=t.disableTools?{}:t.tools||{};let u;const d=new pv;let m;if(Object.keys(l).length>0){const $e=gv(l,"functionDeclarations");m=$e,u=$e.toolsConfig;for(const[xe,ve]of $e.executeMap)d.set(xe,ve);p.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:$e.toolsConfig[0].functionDeclarations.length,toolNames:$e.toolsConfig[0].functionDeclarations.map(xe=>xe.name)})}let h=!1;if(t.schema&&u){h=!0;const $e=Ao(t.schema,"openApi3"),xe=Xn($e);xe.$schema&&delete xe.$schema;const ve=Hi(xe),J=u[0]?.functionDeclarations||[];J.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:ve}),u=[{functionDeclarations:J}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(ve),totalTools:J.length})}const f=hl(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:t.maxTokens};qJ(r)&&(g.maxOutputTokens&&g.maxOutputTokens>Sa&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${Sa} for ${r}`),g.maxOutputTokens=Sa),g.maxOutputTokens||(g.maxOutputTokens=Sa)),f.topP!==void 0&&(g.topP=f.topP),t.topK!==void 0&&(g.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(g.stopSequences=t.stopSequences),u&&(g.tools=u);let y=t.systemPrompt||"";h&&(y=y+`
|
|
1114
|
+
IMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.`),g&&(f.systemInstruction=g);const y=eY(t.thinkingConfig,r);if(y&&(f.thinkingConfig=y),(d.output?.format==="json"||d.schema)&&!m&&!c&&(f.responseMimeType="application/json",d.schema)){const Ie=Ao(d.schema,"openApi3"),ve=Xn(Ie);ve.$schema&&delete ve.$schema;const J=Hi(ve);sg(J),f.responseSchema=J,p.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(J)})}const v=Date.now(),w=t.maxSteps||Bs,E=Number.isFinite(w)&&w>0?Math.min(Math.floor(w),100):Math.min(Bs,100),_=[...s];let C="",A;const k=[],R=[];let I;const P=mv(kd("vertex",r));let O=!1,U=0,M=0,F=0,N=0;const L=[],q=ml(t.timeout)??OS,B=Ih(t.toolTimeoutMs),H=t.turnTimeoutMs??q,G=new AbortController,X=()=>G.abort();t.abortSignal?.addEventListener("abort",X);const ce=dv({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:q,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:Ie=>{p.warn(Ie==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${H}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),G.abort()}}),Q=G.signal;t.abortSignal?.aborted&&G.abort();let Ae=!1,Ee=!1,le=!1,ae=0;try{const Ie=XO({providerLabel:"GoogleVertex",maxSteps:E,toolFailureBreaker:{maxRetries:Rh,consecutive:!0,classifyResultFailure:ie=>lO(ie)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:B,abortSignal:Q,onProgress:()=>ce.noteProgress()},...u?{declarations:u}:{},...m?{finalResultToolName:"final_result",onTerminalResult:ie=>{try{I=JSON.parse(ie)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(ie,W)=>(this.emitTurnEvent({phase:"malformed-retry",step:W+1,maxSteps:E}),[...ie,{role:"user",parts:[{text:"Your previous function call was malformed and could not be parsed. Re-issue it as a single valid function call, or answer in plain text."}]}]),collectStep:(ie,W)=>EOt(ie,W,{onProgress:()=>ce.noteProgress(),onUsage:(re,ye)=>P.noteUsage(re,ye),onUsageDelta:(re,ye)=>{re==="input"?U+=ye:re==="output"?M+=ye:re==="cacheRead"?F+=ye:N+=ye}}),planReclaim:ie=>{if(!P.shouldStop())return;const W=[...ie];return TOt(W,r,P.projectedNextPromptTokens)?(P.resetAfterReclaim(),{conversation:W}):(O=!0,p.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${P.projectedNextPromptTokens} tokens >= threshold ${P.thresholdTokens} \u2014 synthesizing a final answer.`),{stop:!0})},buildRequest:ie=>({model:r,contents:ie,config:{...f,...c?{tools:c}:{}}}),sendStep:async(ie,W)=>{ce.noteProgress();const re=ie;return o.models.generateContentStream({model:re.model,contents:re.contents,config:{...re.config??{},abortSignal:W}})}}),ve={...Ie,buildStepRequest:(ie,W)=>(ae=W+1,Ie.buildStepRequest(ie,W)),buildToolResultMessages:(ie,W,re,ye)=>{const Re=Ie.buildToolResultMessages(ie,W,re,ye);if(ce.shouldNudgeWrapup()){const K=Re[Re.length-1];K&&Array.isArray(K.parts)&&K.parts.push({text:lv(m)})}const x=WO(W.raw.rawResponseParts);Ct(this.handleToolExecutionStorage(re.map((K,Se)=>({toolName:K.name,args:K.args,...Se===0&&x?{thoughtSignature:x}:{},stepIndex:ye+1})),re.map(K=>({toolName:K.name,output:K.output,stepIndex:ye+1})),t,new Date),Ph,"tool storage write timed out").catch(K=>{p.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:K instanceof Error?K.message:String(K)})});try{const K=Re[Re.length-1];P.noteAppendedChars(JSON.stringify(K?.parts??[]).length)}catch{}return Re}},{stream:J,resultPromise:V}=Ld(ve,_,{tools:VO(u,t.tools,{toolTimeoutMs:B,abortSignal:Q,onProgress:()=>ce.noteProgress()}),abortSignal:Q,toolTimeoutMs:B}),se=(async()=>{for await(const ie of J)ie.content&&L.push(ie.content)})();let oe,Z;try{oe=await V}catch(ie){Z=ie}if(await Ff(se,"GoogleVertex"),Z!==void 0)if(Q.aborted||mp(Z))Ae=!0;else throw p.error("[GoogleVertex] Native SDK error",Z),this.handleProviderError(Z);if(oe){C=oe.text,A=oe.rawStopReason??A;for(const ie of oe.toolCalls)k.push({toolName:ie.name,args:ie.args});for(const ie of oe.toolExecutions)R.push({name:ie.name,input:ie.input,output:ie.output});_.length=0,_.push(...oe.conversation)}if(Q.aborted&&(Ae=!0),!C&&(ae>=E||Ae||O)){Ee=ae>=E&&!Ae;const ie=k.filter(W=>W.toolName!=="final_result").length;if(L.length>0)p.warn(O?"[GoogleVertex] Tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${E}); returning text already gathered from prior steps.`);else if(Ae)p.warn(`[GoogleVertex] Tool call loop ended mid-turn (${ce.timedOut?"turn time limit":ce.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),C=this.buildLoopExitMessage({turnClock:ce,wasAborted:Ae,stallTimeoutMs:t.stallTimeoutMs,maxSteps:E,toolCallCount:ie});else{p.warn(O?"[GoogleVertex] Tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${E}) with no text; synthesizing a final answer with tools disabled.`);const W=await this.synthesizeFinalAnswerWithoutTools(o,r,f,_,m,ml(t.timeout)??OS,Q);W.text?(le=!0,C=W.text,L.push(W.text),U+=W.inputTokens,M+=W.outputTokens,N+=W.reasoningTokens??0,W.finishReason&&(A=W.finishReason)):C=O?Nc(ie):pp(E,ie)}}}finally{ce.dispose(),t.abortSignal?.removeEventListener("abort",X)}const Pe=Ee&&!le?"tool-calls":dC(A),ke=uv({timedOut:ce.timedOut,stalled:ce.stalled,wasAborted:Ae,cappedWithoutAnswer:Ee&&!le,contextCappedWithoutAnswer:O&&!le,finishReason:Pe});ke!=="completed"&&this.emitTurnEvent({phase:ke,step:ae,maxSteps:E,toolCallCount:k.filter(Ie=>Ie.toolName!=="final_result").length,elapsedMs:ce.elapsedMs()});const Te=Date.now()-v,he=I?[C]:L.length>0?L:[C];async function*Oe(){for(const Ie of he)Ie.length>0&&(yield{content:Ie})}const De=k.filter(Ie=>Ie.toolName!=="final_result"),Ye=R.filter(Ie=>Ie.name!=="final_result"),gt=Math.max(0,U-F),$e={stream:Oe(),provider:this.providerName,model:r,finishReason:Pe,stopReason:ke,rawFinishReason:A,usage:{input:gt,output:M+N,total:gt+F+M+N,...F>0&&{cacheReadTokens:F},...N>0&&{reasoning:N}},toolCalls:De.map(Ie=>({toolName:Ie.toolName,args:Ie.args})),toolsUsed:De.map(Ie=>Ie.toolName),toolExecutions:bd(Ye),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:v,responseTime:Te,totalToolExecutions:De.length,stopReason:ke,rawFinishReason:A,stepsUsed:ae}};return I&&($e.structuredOutput=I),$e}async executeNativeGemini3Generate(t){const r=t.model||this.modelName||ig(),n=Wv(r,t.region),o=await this.createVertexGenAIClient(n);p.debug("[GoogleVertex] Using native @google/genai for Gemini 3 generate",{model:r,project:this.projectId,location:n});const s=t.input?.text||t.prompt||"Please respond.",i=[],a=[{text:s}],c=t.input;if(c?.pdfFiles&&c.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${c.pdfFiles.length} PDF file(s) for native generate`);for(const $e of c.pdfFiles){let Ie;typeof $e=="string"?Fo.existsSync($e)?Ie=Fo.readFileSync($e):Ie=Buffer.from($e,"base64"):Ie=$e;const ve=Ie.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:ve}})}}if(await nY(a,c?.nativeAudioFiles,"[GoogleVertex]"),c?.images&&c.images.length>0){p.debug(`[GoogleVertex] Processing ${c.images.length} image(s) for native generate`);for(const $e of c.images){const Ie=E_($e);let ve,J="image/jpeg";if(typeof Ie=="string")if(Fo.existsSync(Ie)){ve=Fo.readFileSync(Ie);const se=k_(Ie);J=se.startsWith("image/")?se:this.detectImageType(ve)}else if(Ie.startsWith("data:")){const se=Ie.match(/^data:([^;]+);base64,(.+)$/);if(se)J=se[1],ve=Buffer.from(se[2],"base64");else continue}else if(Ie.startsWith("http://")||Ie.startsWith("https://"))try{const se=await fetch(Ie);if(!se.ok){p.warn(`[GoogleVertex] Image fetch failed: ${se.status} ${se.statusText}, skipping`,{url:rr(Ie)});continue}const oe=await se.arrayBuffer();ve=Buffer.from(oe);const Z=se.headers.get("content-type");Z&&Z.startsWith("image/")&&(J=Z.split(";")[0])}catch(se){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${se instanceof Error?se.message:String(se)}`,{url:rr(Ie)});continue}else ve=Buffer.from(Ie,"base64"),J=this.detectImageType(ve);else ve=Ie,J=this.detectImageType(ve);const V=ve.toString("base64");a.push({inlineData:{mimeType:J,data:V}})}}await oY(a,c?.nativeVideoFiles,"vertex",r,"[GoogleVertex]"),KO(i,t.conversationMessages),i.push({role:"user",parts:a});const l=t.disableTools?{}:t.tools||{};let u;const d=new pv;let m;if(Object.keys(l).length>0){const $e=gv(l,"functionDeclarations");m=$e,u=$e.toolsConfig;for(const[Ie,ve]of $e.executeMap)d.set(Ie,ve);p.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:$e.toolsConfig[0].functionDeclarations.length,toolNames:$e.toolsConfig[0].functionDeclarations.map(Ie=>Ie.name)})}let h=!1;if(t.schema&&u){h=!0;const $e=Ao(t.schema,"openApi3"),Ie=Xn($e);Ie.$schema&&delete Ie.$schema;const ve=Hi(Ie),J=u[0]?.functionDeclarations||[];J.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:ve}),u=[{functionDeclarations:J}],p.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(ve),totalTools:J.length})}const f=hl(this.providerName,r,{temperature:t.temperature??1,...t.topP!==void 0&&{topP:t.topP}},"vertex.gemini"),g={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:t.maxTokens};qJ(r)&&(g.maxOutputTokens&&g.maxOutputTokens>Sa&&(p.warn(`[GoogleVertex] Capping maxOutputTokens from ${g.maxOutputTokens} to ${Sa} for ${r}`),g.maxOutputTokens=Sa),g.maxOutputTokens||(g.maxOutputTokens=Sa)),f.topP!==void 0&&(g.topP=f.topP),t.topK!==void 0&&(g.topK=t.topK),t.stopSequences&&t.stopSequences.length>0&&(g.stopSequences=t.stopSequences),u&&(g.tools=u);let y=t.systemPrompt||"";h&&(y=y+`
|
|
1115
1115
|
|
|
1116
|
-
IMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.`),y&&(g.systemInstruction=y);const v=eY(t.thinkingConfig,r);if(v&&(g.thinkingConfig=v),(t.output?.format==="json"||t.schema)&&!h&&!u&&(g.responseMimeType="application/json",t.schema)){const $e=Ao(t.schema,"openApi3"),
|
|
1116
|
+
IMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.`),y&&(g.systemInstruction=y);const v=eY(t.thinkingConfig,r);if(v&&(g.thinkingConfig=v),(t.output?.format==="json"||t.schema)&&!h&&!u&&(g.responseMimeType="application/json",t.schema)){const $e=Ao(t.schema,"openApi3"),Ie=Xn($e);Ie.$schema&&delete Ie.$schema;const ve=Hi(Ie);sg(ve),g.responseSchema=ve,p.debug("[GoogleVertex] Added responseSchema for JSON output (generate)",{schemaKeys:Object.keys(ve)})}const w=Date.now(),E=t.maxSteps||Bs,_=Number.isFinite(E)&&E>0?Math.min(Math.floor(E),100):Math.min(Bs,100),C=[...i];let A="",k="",R;const I=[],P=[];let O;const U=mv(kd("vertex",r));let M=!1,F=0,N=0,L=0,q=0;const B=ml(t.timeout)??OS,H=Ih(t.toolTimeoutMs),G=t.turnTimeoutMs??B,X=new AbortController,ce=()=>X.abort();t.abortSignal?.addEventListener("abort",ce);const Q=dv({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:B,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:$e=>{p.warn($e==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${G}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),X.abort()}}),Ae=X.signal;t.abortSignal?.aborted&&X.abort();let Ee=!1,le=!1,ae=!1,Pe=0;try{const $e=XO({providerLabel:"GoogleVertex",maxSteps:_,toolFailureBreaker:{maxRetries:Rh,consecutive:!0,classifyResultFailure:oe=>lO(oe)??void 0},liveTools:t.tools??{},toolGuards:{toolTimeoutMs:H,abortSignal:Ae,onProgress:()=>Q.noteProgress()},...m?{declarations:m}:{},...h?{finalResultToolName:"final_result",onTerminalResult:oe=>{try{O=JSON.parse(oe)}catch{}}}:{},enableMalformedRetry:!0,buildMalformedRetryNote:(oe,Z)=>(this.emitTurnEvent({phase:"malformed-retry",step:Z+1,maxSteps:_}),[...oe,{role:"user",parts:[{text:"Your previous function call was malformed and could not be parsed. Re-issue it as a single valid function call, or answer in plain text."}]}]),collectStep:(oe,Z)=>EOt(oe,Z,{onProgress:()=>Q.noteProgress(),onUsage:(ie,W)=>U.noteUsage(ie,W),onUsageDelta:(ie,W)=>{ie==="input"?F+=W:ie==="output"?N+=W:ie==="cacheRead"?L+=W:q+=W}}),planReclaim:oe=>{if(!U.shouldStop())return;const Z=[...oe];return TOt(Z,r,U.projectedNextPromptTokens)?(U.resetAfterReclaim(),{conversation:Z}):(M=!0,p.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${U.projectedNextPromptTokens} tokens >= threshold ${U.thresholdTokens} \u2014 synthesizing a final answer.`),{stop:!0})},buildRequest:oe=>({model:r,contents:oe,config:{...g,...u?{tools:u}:{}}}),sendStep:async(oe,Z)=>{Q.noteProgress();const ie=oe;return o.models.generateContentStream({model:ie.model,contents:ie.contents,config:{...ie.config??{},abortSignal:Z}})}}),Ie={...$e,buildStepRequest:(oe,Z)=>(Pe=Z+1,$e.buildStepRequest(oe,Z)),buildToolResultMessages:(oe,Z,ie,W)=>{const re=$e.buildToolResultMessages(oe,Z,ie,W);if(Q.shouldNudgeWrapup()){const Re=re[re.length-1];Re&&Array.isArray(Re.parts)&&Re.parts.push({text:lv(h)})}const ye=WO(Z.raw.rawResponseParts);Ct(this.handleToolExecutionStorage(ie.map((Re,x)=>({toolName:Re.name,args:Re.args,...x===0&&ye?{thoughtSignature:ye}:{},stepIndex:W+1})),ie.map(Re=>({toolName:Re.name,output:Re.output,stepIndex:W+1})),t,new Date),Ph,"tool storage write timed out").catch(Re=>{p.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:Re instanceof Error?Re.message:String(Re)})});try{const Re=re[re.length-1];U.noteAppendedChars(JSON.stringify(Re?.parts??[]).length)}catch{}return re}},{stream:ve,resultPromise:J}=Ld(Ie,C,{tools:VO(m,t.tools,{toolTimeoutMs:H,abortSignal:Ae,onProgress:()=>Q.noteProgress()}),abortSignal:Ae,toolTimeoutMs:H}),V=(async()=>{for await(const oe of ve);})();let se;try{se=await J}catch(oe){if(await Ff(V,"GoogleVertex"),Ae.aborted||mp(oe))Ee=!0;else throw p.error("[GoogleVertex] Native SDK error",oe),this.handleProviderError(oe)}if(await V,se){A=se.text,R=se.rawStopReason??R;for(const oe of se.toolCalls)I.push({toolName:oe.name,args:oe.args});for(const oe of se.toolExecutions)P.push({name:oe.name,input:oe.input,output:oe.output});C.length=0,C.push(...se.conversation)}if(Ae.aborted&&(Ee=!0),!A&&(Pe>=_||Ee||M)){le=Pe>=_&&!Ee;const oe=I.filter(Z=>Z.toolName!=="final_result").length;if(k)p.warn(M?"[GoogleVertex] Generate tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Generate tool call loop terminated after reaching maxSteps (${_}); returning text already gathered from prior steps.`),A=k;else if(Ee)p.warn(`[GoogleVertex] Generate tool call loop ended mid-turn (${Q.timedOut?"turn time limit":Q.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),A=this.buildLoopExitMessage({turnClock:Q,wasAborted:Ee,stallTimeoutMs:t.stallTimeoutMs,maxSteps:_,toolCallCount:oe});else{p.warn(M?"[GoogleVertex] Generate tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Generate tool call loop terminated after reaching maxSteps (${_}) with no text; synthesizing a final answer with tools disabled.`);const Z=await this.synthesizeFinalAnswerWithoutTools(o,r,g,C,h,ml(t.timeout)??OS,Ae);Z.text?(ae=!0,A=Z.text,F+=Z.inputTokens,N+=Z.outputTokens,q+=Z.reasoningTokens??0,Z.finishReason&&(R=Z.finishReason)):A=M?Nc(oe):pp(_,oe)}}}finally{Q.dispose(),t.abortSignal?.removeEventListener("abort",ce)}const ke=le&&!ae?"tool-calls":dC(R),Te=uv({timedOut:Q.timedOut,stalled:Q.stalled,wasAborted:Ee,cappedWithoutAnswer:le&&!ae,contextCappedWithoutAnswer:M&&!ae,finishReason:ke});Te!=="completed"&&this.emitTurnEvent({phase:Te,step:Pe,maxSteps:_,toolCallCount:I.filter($e=>$e.toolName!=="final_result").length,elapsedMs:Q.elapsedMs()});const he=Date.now()-w,Oe=I.filter($e=>$e.toolName!=="final_result"),De=P.filter($e=>$e.name!=="final_result"),Ye=Math.max(0,F-L),gt={content:A,provider:this.providerName,model:r,finishReason:ke,stopReason:Te,rawFinishReason:R,stepsUsed:Pe,usage:{input:Ye,output:N+q,total:Ye+L+N+q,...L>0&&{cacheReadTokens:L},...q>0&&{reasoning:q}},...q>0&&{reasoningTokens:q},responseTime:he,toolsUsed:Oe.map($e=>$e.toolName),toolExecutions:af(t,De),enhancedWithTools:Oe.length>0};return O&&(gt.structuredOutput=O),this.enhanceResult(gt,t,w)}async synthesizeFinalAnswerWithoutTools(t,r,n,o,s,i,a){if(a?.aborted)return{text:"",inputTokens:0,outputTokens:0,reasoningTokens:0};try{const c={...n,...a?{abortSignal:a}:{}};if(delete c.tools,s){const l=typeof c.systemInstruction=="string"?c.systemInstruction:"";c.systemInstruction=l+`
|
|
1117
1117
|
|
|
1118
|
-
The final_result tool is no longer available. Provide your final answer directly as plain text now, using the information gathered so far.`}return await Ct((async()=>{const l=await t.models.generateContentStream({model:r,contents:o,config:c}),u=[];let d,m=0,h=0,f=0;for await(const y of l){const v=y,E=v.candidates?.[0],_=E?.finishReason;typeof _=="string"&&_&&(d=_);const C=E?.content;C&&Array.isArray(C.parts)&&u.push(...C.parts);const A=v.usageMetadata;A&&(A.promptTokenCount!==void 0&&A.promptTokenCount>0&&(m=A.promptTokenCount),A.candidatesTokenCount!==void 0&&A.candidatesTokenCount>0&&(h=A.candidatesTokenCount),A.thoughtsTokenCount!==void 0&&A.thoughtsTokenCount>0&&(f=A.thoughtsTokenCount))}return{text:u.filter(y=>typeof y.text=="string").map(y=>y.text).join(""),finishReason:d,inputTokens:m,outputTokens:h,reasoningTokens:f}})(),i,"Gemini synthesis call timed out")}catch(c){return p.warn("[GoogleVertex] Tools-disabled synthesis call failed; falling back to placeholder",{error:c instanceof Error?c.message:String(c)}),{text:"",inputTokens:0,outputTokens:0,reasoningTokens:0}}}async createAnthropicVertexClient(t){const r=await TGr(),n=this.resolveExpressApiKey(),o=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim(),s=await _Ot(this.location,t,n?{apiKey:n,...this.projectId?{projectId:this.projectId}:{}}:void 0,o),i=new r.AnthropicVertex(s),a=i;if("_authClientPromise"in a){const c=a._authClientPromise;c instanceof Promise&&c.catch(()=>{})}return i}buildClaudeThinkingParam(t,r,n){if(n){t.thinkingConfig?.enabled&&p.debug("[GoogleVertex] Omitting thinking: schema mode forces tool_choice:any, which Anthropic rejects alongside thinking");return}const o=t.thinkingConfig?.budgetTokens;if(!t.thinkingConfig?.enabled||!o||r<=1024)return;const s=Math.min(o,r-1024);if(!(s<1024))return{type:"enabled",budget_tokens:s}}async executeNativeAnthropicStream(t){const r=A_t(t.model||this.modelName||"claude-sonnet-4-5@20250929"),n=Date.now(),o=ml(t.timeout)??3e5,s=await this.createAnthropicVertexClient(o);p.debug("[GoogleVertex] Using native @anthropic-ai/vertex-sdk for Claude stream",{model:r,project:this.projectId,location:this.location});const i=[];if(t.conversationMessages&&t.conversationMessages.length>0)i.push(...GQ(t.conversationMessages));else if(t.conversationHistory&&t.conversationHistory.length>0)for(const he of t.conversationHistory)(he.role==="user"||he.role==="assistant")&&i.push({role:he.role,content:n0(he.content)});const a=t.input,c=[];if(a?.pdfFiles&&a.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native Anthropic stream`);for(const he of a.pdfFiles){let Oe;typeof he=="string"?Fo.existsSync(he)?Oe=Fo.readFileSync(he):Oe=Buffer.from(he,"base64"):Oe=he;const De=Oe.toString("base64");c.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:De}})}}if(a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native Anthropic stream`);for(const he of a.images){const Oe=E_(he);let De,Ye="image/jpeg";if(typeof Oe=="string")if(Fo.existsSync(Oe)){De=Fo.readFileSync(Oe);const $e=k_(Oe);Ye=$e.startsWith("image/")?$e:this.detectImageType(De)}else if(Oe.startsWith("data:")){const $e=Oe.match(/^data:([^;]+);base64,(.+)$/);if($e)Ye=$e[1],De=Buffer.from($e[2],"base64");else continue}else if(Oe.startsWith("http://")||Oe.startsWith("https://"))try{const $e=await fetch(Oe);if(!$e.ok){p.warn(`[GoogleVertex] Image fetch failed: ${$e.status} ${$e.statusText}, skipping`,{url:rr(Oe)});continue}const
|
|
1118
|
+
The final_result tool is no longer available. Provide your final answer directly as plain text now, using the information gathered so far.`}return await Ct((async()=>{const l=await t.models.generateContentStream({model:r,contents:o,config:c}),u=[];let d,m=0,h=0,f=0;for await(const y of l){const v=y,E=v.candidates?.[0],_=E?.finishReason;typeof _=="string"&&_&&(d=_);const C=E?.content;C&&Array.isArray(C.parts)&&u.push(...C.parts);const A=v.usageMetadata;A&&(A.promptTokenCount!==void 0&&A.promptTokenCount>0&&(m=A.promptTokenCount),A.candidatesTokenCount!==void 0&&A.candidatesTokenCount>0&&(h=A.candidatesTokenCount),A.thoughtsTokenCount!==void 0&&A.thoughtsTokenCount>0&&(f=A.thoughtsTokenCount))}return{text:u.filter(y=>typeof y.text=="string").map(y=>y.text).join(""),finishReason:d,inputTokens:m,outputTokens:h,reasoningTokens:f}})(),i,"Gemini synthesis call timed out")}catch(c){return p.warn("[GoogleVertex] Tools-disabled synthesis call failed; falling back to placeholder",{error:c instanceof Error?c.message:String(c)}),{text:"",inputTokens:0,outputTokens:0,reasoningTokens:0}}}async createAnthropicVertexClient(t){const r=await TGr(),n=this.resolveExpressApiKey(),o=this.baseURL?.trim()||process.env.GOOGLE_VERTEX_BASE_URL?.trim(),s=await _Ot(this.location,t,n?{apiKey:n,...this.projectId?{projectId:this.projectId}:{}}:void 0,o),i=new r.AnthropicVertex(s),a=i;if("_authClientPromise"in a){const c=a._authClientPromise;c instanceof Promise&&c.catch(()=>{})}return i}buildClaudeThinkingParam(t,r,n){if(n){t.thinkingConfig?.enabled&&p.debug("[GoogleVertex] Omitting thinking: schema mode forces tool_choice:any, which Anthropic rejects alongside thinking");return}const o=t.thinkingConfig?.budgetTokens;if(!t.thinkingConfig?.enabled||!o||r<=1024)return;const s=Math.min(o,r-1024);if(!(s<1024))return{type:"enabled",budget_tokens:s}}async executeNativeAnthropicStream(t){const r=A_t(t.model||this.modelName||"claude-sonnet-4-5@20250929"),n=Date.now(),o=ml(t.timeout)??3e5,s=await this.createAnthropicVertexClient(o);p.debug("[GoogleVertex] Using native @anthropic-ai/vertex-sdk for Claude stream",{model:r,project:this.projectId,location:this.location});const i=[];if(t.conversationMessages&&t.conversationMessages.length>0)i.push(...GQ(t.conversationMessages));else if(t.conversationHistory&&t.conversationHistory.length>0)for(const he of t.conversationHistory)(he.role==="user"||he.role==="assistant")&&i.push({role:he.role,content:n0(he.content)});const a=t.input,c=[];if(a?.pdfFiles&&a.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native Anthropic stream`);for(const he of a.pdfFiles){let Oe;typeof he=="string"?Fo.existsSync(he)?Oe=Fo.readFileSync(he):Oe=Buffer.from(he,"base64"):Oe=he;const De=Oe.toString("base64");c.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:De}})}}if(a?.images&&a.images.length>0){p.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native Anthropic stream`);for(const he of a.images){const Oe=E_(he);let De,Ye="image/jpeg";if(typeof Oe=="string")if(Fo.existsSync(Oe)){De=Fo.readFileSync(Oe);const $e=k_(Oe);Ye=$e.startsWith("image/")?$e:this.detectImageType(De)}else if(Oe.startsWith("data:")){const $e=Oe.match(/^data:([^;]+);base64,(.+)$/);if($e)Ye=$e[1],De=Buffer.from($e[2],"base64");else continue}else if(Oe.startsWith("http://")||Oe.startsWith("https://"))try{const $e=await fetch(Oe);if(!$e.ok){p.warn(`[GoogleVertex] Image fetch failed: ${$e.status} ${$e.statusText}, skipping`,{url:rr(Oe)});continue}const Ie=await $e.arrayBuffer();De=Buffer.from(Ie);const ve=$e.headers.get("content-type");ve&&ve.startsWith("image/")&&(Ye=ve.split(";")[0])}catch($e){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${$e instanceof Error?$e.message:String($e)}`,{url:rr(Oe)});continue}else De=Buffer.from(Oe,"base64"),Ye=this.detectImageType(De);else De=Oe,Ye=this.detectImageType(De);const gt=De.toString("base64");c.push({type:"image",source:{type:"base64",media_type:Ye,data:gt}})}}c.push({type:"text",text:a.text}),jQ(i,c.length===1&&c[0].type==="text"?a.text:c);let l;const u=new pv;if(t.tools&&Object.keys(t.tools).length>0&&!t.disableTools){l=[];for(const[he,Oe]of Object.entries(t.tools))l.push(this.buildAnthropicToolDeclaration(he,Oe)),Oe.execute&&u.set(he,Oe.execute);p.debug("[GoogleVertex] Converted tools for native Anthropic SDK",{toolCount:l.length,toolNames:l.map(he=>he.name)})}const d=t;let m=!1,h="";if(d.schema){m=!0;const he=this.buildFinalResultTool(d.schema);l||(l=[]),l.push(he),h=`
|
|
1119
1119
|
|
|
1120
|
-
IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`,p.debug("[GoogleVertex] Added final_result tool for Anthropic structured output (stream)",{schemaKeys:Object.keys(he.input_schema.properties??{}),totalTools:l.length})}const f=t.systemPrompt?t.systemPrompt+h:h?h.trim():void 0,g=hl(this.providerName,r,{...t.temperature!==void 0&&{temperature:t.temperature},...t.topP!==void 0&&{topP:t.topP}},"vertex.anthropic.stream"),y=UO(r,t.maxTokens),v=this.buildClaudeThinkingParam(t,y,m),w={model:r,max_tokens:y,...v&&{thinking:v},messages:i,...l&&l.length>0&&{tools:l},...m&&{tool_choice:{type:"any"}},...f&&{system:f},...g.temperature!==void 0&&{temperature:g.temperature},...g.topP!==void 0&&{top_p:g.topP},...t.stopSequences&&t.stopSequences.length>0&&{stop_sequences:t.stopSequences}},E=t.maxSteps||Bs,_=m?Math.max(E-1,0):E,C=[],A=[],k=hv(),R={input:0,output:0,total:0},I={streamId:`native-anthropic-vertex-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0},P=[],O={},U={},M={},F={},N=(l??[]).map(he=>he.name),L=ki({system:f,messages:mOt(i)}),q=Be.provider.startSpan("anthropic.vertex.stream",{kind:zr.CLIENT,attributes:{[wo.OBSERVATION_TYPE]:"span",[_e.GEN_AI_SYSTEM]:"anthropic",[_e.GEN_AI_MODEL]:r,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName,[_e.NL_TOOL_COUNT]:N.length,[wo.OBSERVATION_INPUT]:L,[wo.TRACE_INPUT]:L,[wo.OBSERVATION_METADATA]:ki({toolsOffered:N,toolCount:N.length,maxSteps:E,structuredOutput:m})}}),B=lt.setSpan(fr.active(),q);let H="",G=0;const X={read:0,creation:0,creation5m:0,creation1h:0};let ce;const Q=()=>{try{ce?.controller.abort()}catch{}},
|
|
1120
|
+
IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`,p.debug("[GoogleVertex] Added final_result tool for Anthropic structured output (stream)",{schemaKeys:Object.keys(he.input_schema.properties??{}),totalTools:l.length})}const f=t.systemPrompt?t.systemPrompt+h:h?h.trim():void 0,g=hl(this.providerName,r,{...t.temperature!==void 0&&{temperature:t.temperature},...t.topP!==void 0&&{topP:t.topP}},"vertex.anthropic.stream"),y=UO(r,t.maxTokens),v=this.buildClaudeThinkingParam(t,y,m),w={model:r,max_tokens:y,...v&&{thinking:v},messages:i,...l&&l.length>0&&{tools:l},...m&&{tool_choice:{type:"any"}},...f&&{system:f},...g.temperature!==void 0&&{temperature:g.temperature},...g.topP!==void 0&&{top_p:g.topP},...t.stopSequences&&t.stopSequences.length>0&&{stop_sequences:t.stopSequences}},E=t.maxSteps||Bs,_=m?Math.max(E-1,0):E,C=[],A=[],k=hv(),R={input:0,output:0,total:0},I={streamId:`native-anthropic-vertex-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0},P=[],O={},U={},M={},F={},N=(l??[]).map(he=>he.name),L=ki({system:f,messages:mOt(i)}),q=Be.provider.startSpan("anthropic.vertex.stream",{kind:zr.CLIENT,attributes:{[wo.OBSERVATION_TYPE]:"span",[_e.GEN_AI_SYSTEM]:"anthropic",[_e.GEN_AI_MODEL]:r,[_e.GEN_AI_OPERATION]:"stream",[_e.NL_PROVIDER]:this.providerName,[_e.NL_TOOL_COUNT]:N.length,[wo.OBSERVATION_INPUT]:L,[wo.TRACE_INPUT]:L,[wo.OBSERVATION_METADATA]:ki({toolsOffered:N,toolCount:N.length,maxSteps:E,structuredOutput:m})}}),B=lt.setSpan(fr.active(),q);let H="",G=0;const X={read:0,creation:0,creation5m:0,creation1h:0};let ce;const Q=()=>{try{ce?.controller.abort()}catch{}},Ae=new AbortController;Ae.signal.addEventListener("abort",Q);const Ee=()=>Ae.abort();t.abortSignal?.addEventListener("abort",Ee),t.abortSignal?.aborted&&Ae.abort();const le=Ih(t.toolTimeoutMs),ae=t.turnTimeoutMs??o,Pe=dv({turnTimeoutMs:t.turnTimeoutMs,defaultTurnTimeoutMs:o,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:he=>{p.warn(he==="timeout"?`[GoogleVertex] Anthropic stream turn exceeded its ${ae}ms time budget \u2014 aborting`:`[GoogleVertex] Anthropic stream turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),Ae.abort()}});(async()=>{let he=0;const Oe=[...i];let De=!1,Ye=!1,gt=!1,$e=!1,Ie=!1,ve;const J=mv(kd("vertex",r)),V=new Map;try{const se=(Y,de)=>{const ge=Be.mcp.startSpan("ai.toolCall",{kind:zr.INTERNAL,attributes:{[wo.OBSERVATION_TYPE]:"tool",[_e.GEN_AI_TOOL_NAME]:Y,"ai.toolCall.name":Y}},B),be=(we,ue)=>{ge.setAttribute("ai.toolCall.result",ki(we)),ge.setAttribute(wo.OBSERVATION_OUTPUT,ki(we)),ue?(ge.setAttribute(wo.OBSERVATION_LEVEL,"ERROR"),ge.setAttribute(wo.OBSERVATION_STATUS_MESSAGE,ue),ge.setStatus({code:Ue.ERROR,message:ue})):ge.setStatus({code:Ue.OK}),ge.end()};return fr.with(lt.setSpan(B,ge),async()=>{try{const we=await de();return be(we,wTt(we)),we}catch(we){throw be({error:!0},we instanceof Error?we.message:String(we)),we}})},oe={};for(const Y of u.keys()){const de=u.get(Y);de&&(oe[Y]={execute:Uf(Y,de,{toolTimeoutMs:le,abortSignal:Ae.signal,onProgress:()=>Pe.noteProgress(),withToolSpan:se})})}const Z=EQ({client:s,maxSteps:_,toolsRecord:t.tools??{},toolFailureBreaker:{maxRetries:Rh,classifyResultFailure:Y=>lO(Y)??void 0},buildParams:Y=>{this.refreshAnthropicToolDeclarations(t.tools,l,u,V);const de=jv({system:f,tools:l,messages:Y}),{stream:ge,output_config:be,...we}=w;return{...we,...de.system!==void 0&&{system:de.system},...de.tools&&de.tools.length>0&&{tools:de.tools},messages:de.messages}},planReclaim:Y=>{if(!J.shouldStop())return;const de=[...Y];if(wOt(de,r,J.projectedNextPromptTokens))return J.resetAfterReclaim(),{conversation:de};gt=!0,p.warn(`[GoogleVertex] Native Anthropic turn stopped by the context guard: projected prompt ~${J.projectedNextPromptTokens} tokens >= threshold ${J.thresholdTokens} \u2014 forcing finalization.`)},noteObservedPromptTokens:Y=>{J.noteUsage(Y,0)},...m?{finalResultToolName:"final_result",onTerminalResult:Y=>{try{O.value=JSON.parse(Y)}catch{}k.push({content:Y}),G+=Y.length,p.debug("[GoogleVertex] Extracted structured output from final_result tool (stream)",{chars:Y.length})}}:{}}),ie={...Z,buildStepRequest:(Y,de)=>(he=de+1,Pe.noteProgress(),Z.buildStepRequest(Y,de)),resolveToolOnMiss:Y=>{const de=this.resolveAnthropicToolOnMiss(Y,t.tools,l,u,V);if(de)return{execute:Uf(Y,de,{toolTimeoutMs:le,abortSignal:Ae.signal,onProgress:()=>Pe.noteProgress(),withToolSpan:se})}},executeStep:async(Y,de,ge)=>{const be=Be.generation.startSpan("anthropic.messages.stream",{kind:zr.CLIENT,attributes:{[wo.OBSERVATION_TYPE]:"generation",[wo.OBSERVATION_MODEL_NAME]:r,[wo.OBSERVATION_MODEL_PARAMETERS]:ki({max_tokens:w.max_tokens,temperature:w.temperature,top_p:w.top_p}),[wo.OBSERVATION_INPUT]:ki({system:f,messages:mOt(Oe)}),[wo.OBSERVATION_METADATA]:ki({step:he,toolsOffered:N.length}),[_e.GEN_AI_SYSTEM]:"anthropic",[_e.GEN_AI_MODEL]:r,[_e.GEN_AI_OPERATION]:"chat"}},B);let we=!1;try{const ue=await Z.executeStep(Y,{push:Le=>{Pe.noteProgress(),Le.content&&!we&&(we=!0,be.setAttribute(wo.OBSERVATION_COMPLETION_START_TIME,new Date().toISOString())),de.push(Le)}},ge);return X.read+=ue.usage.cacheReadTokens??0,X.creation+=ue.usage.cacheWriteTokens??0,X.creation5m+=ue.usage.cacheWrite5mTokens??0,X.creation1h+=ue.usage.cacheWrite1hTokens??0,be.setAttribute(wo.OBSERVATION_OUTPUT,ki({text:ue.text})),ue}catch(ue){throw be.setStatus({code:Ue.ERROR,message:ue instanceof Error?ue.message:String(ue)}),ue instanceof Error&&be.recordException(ue),ue}finally{be.end()}},buildToolResultMessages:(Y,de,ge,be)=>{for(const ue of ge)C.push({toolName:ue.name,args:ue.args}),P.push(ue.name),A.push({name:ue.name,input:ue.args,output:ue.output});I.totalToolExecutions+=ge.length;const we=Z.buildToolResultMessages(Y,de,ge,be);if(Pe.shouldNudgeWrapup()){const ue=we[we.length-1];ue&&Array.isArray(ue.content)&&ue.content.push({type:"text",text:lv(m)})}Ct(this.handleToolExecutionStorage(ge.map(ue=>({toolName:ue.name,args:ue.args,stepIndex:be+1})),ge.map(ue=>({toolName:ue.name,output:ue.output,stepIndex:be+1})),t,new Date),Ph,"tool storage write timed out").catch(ue=>{p.warn("[GoogleVertex] Failed to store native Anthropic stream tool executions",{error:ue instanceof Error?ue.message:String(ue)})});try{const ue=we[we.length-1];J.noteAppendedChars(JSON.stringify(ue?.content??[]).length)}catch{}return we}},W=lt.getSpan(B),{stream:re,resultPromise:ye}=Ld(ie,Oe.slice(),{tools:oe,abortSignal:Ae.signal,...W?{span:W}:{},toolTimeoutMs:le}),Re=(async()=>{for await(const Y of re)Y.reasoning&&k.push({content:"",reasoning:Y.reasoning}),Y.content&&(k.push({content:Y.content}),G+=Y.content.length,H+=Y.content)})();let x,K;try{x=await ye}catch(Y){K=Y}if(await Ff(Re,"GoogleVertex"),K!==void 0)if(Ae.signal.aborted||mp(K))De=!0;else throw K;if(x&&(R.input+=x.usage.inputTokens,R.output+=x.usage.outputTokens,x.usage.reasoningTokens&&(R.reasoning=(R.reasoning??0)+x.usage.reasoningTokens),U.value=x.rawStopReason??U.value,Ie=x.toolCalls.length===0||x.finishReason!=="tool-calls"||m&&O.value!==void 0,Oe.length=0,Oe.push(...x.conversation)),Ae.signal.aborted&&(De=!0),!Ie){Ae.signal.aborted&&(De=!0);const Y=C.filter(ge=>ge.toolName!=="final_result").length,de=Math.max(1024,Math.min(w.max_tokens,kd("vertex",r)-J.projectedNextPromptTokens-4e3));if(De){if(p.warn(`[GoogleVertex] Native Anthropic stream loop ended mid-turn (${Pe.timedOut?"turn time limit":Pe.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),H.length===0&&G===0&&!O.value){const ge=this.buildLoopExitMessage({turnClock:Pe,wasAborted:De,stallTimeoutMs:t.stallTimeoutMs,maxSteps:E,toolCallCount:Y});k.push({content:ge}),H=ge}}else if(m){gt||(Ye=!0),p.warn(gt?"[GoogleVertex] Native Anthropic stream loop stopped by the context guard without final_result; forcing a finalization call.":`[GoogleVertex] Native Anthropic stream loop reached maxSteps (${E}) without final_result; forcing a finalization call.`);try{const ge=jv({system:f,tools:l,messages:Oe}),be=await s.messages.stream({...w,max_tokens:de,tool_choice:{type:"tool",name:"final_result"},...ge.system!==void 0&&{system:ge.system},...ge.tools&&ge.tools.length>0&&{tools:ge.tools},messages:ge.messages});ce=be;const we=await be.finalMessage();ce=void 0,R.input+=we.usage?.input_tokens||0,R.output+=we.usage?.output_tokens||0,X.read+=we.usage?.cache_read_input_tokens??0,X.creation+=we.usage?.cache_creation_input_tokens??0,X.creation5m+=we.usage?.cache_creation?.ephemeral_5m_input_tokens??0,X.creation1h+=we.usage?.cache_creation?.ephemeral_1h_input_tokens??0,R.total=R.input+R.output+X.read+X.creation,ve=we.stop_reason;const ue=we.content.find(Le=>Le.type==="tool_use"&&Le.name==="final_result");if(ue)O.value=ue.input,k.push({content:JSON.stringify(ue.input)}),$e=!0,p.debug("[GoogleVertex] Forced finalization returned structured output (stream)",{keys:Object.keys(ue.input)});else{const Le=gt?Nc(Y):pp(E,Y);k.push({content:Le}),H+=Le}}catch(ge){ce=void 0,(Ae.signal.aborted||mp(ge))&&(Ye=!1,De=!0),p.warn("[GoogleVertex] Forced finalization call failed; falling back to a terminal message",{error:ge instanceof Error?ge.message:String(ge)});const be=gt&&!De?Nc(Y):this.buildLoopExitMessage({turnClock:Pe,wasAborted:De,stallTimeoutMs:t.stallTimeoutMs,maxSteps:E,toolCallCount:Y});k.push({content:be}),H+=be}}else if(gt||(Ye=!0),H.length===0){p.warn(gt?"[GoogleVertex] Native Anthropic stream loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Native Anthropic stream loop reached maxSteps (${E}) with no text; synthesizing a final answer with tools disabled.`);try{const ge=(f?f+`
|
|
1121
1121
|
|
|
1122
|
-
`:"")+"Tool calling is no longer available for this turn. Provide your final answer directly as plain text now, using the information gathered so far.",be=jv({system:ge,tools:l,messages:Oe}),we=this.buildClaudeThinkingParam(t,de,!1),ue=await s.messages.stream({...w,max_tokens:de,thinking:we,tool_choice:{type:"none"},system:be.system,...be.tools&&be.tools.length>0&&{tools:be.tools},messages:be.messages});ce=ue;const Le=await ue.finalMessage();ce=void 0,R.input+=Le.usage?.input_tokens||0,R.output+=Le.usage?.output_tokens||0,X.read+=Le.usage?.cache_read_input_tokens??0,X.creation+=Le.usage?.cache_creation_input_tokens??0,X.creation5m+=Le.usage?.cache_creation?.ephemeral_5m_input_tokens??0,X.creation1h+=Le.usage?.cache_creation?.ephemeral_1h_input_tokens??0,R.total=R.input+R.output+X.read+X.creation,Le.usage?.output_tokens_details?.thinking_tokens&&(R.reasoning=(R.reasoning??0)+Le.usage.output_tokens_details.thinking_tokens),ve=Le.stop_reason;const at=Le.content.filter(pt=>pt.type==="thinking").map(pt=>pt.thinking).join("");at&&k.push({content:"",reasoning:at});const vt=Le.content.filter(pt=>pt.type==="text").map(pt=>pt.text).join("");if(vt)$e=!0,k.push({content:vt}),H=vt;else{const pt=gt?Nc(Y):pp(E,Y);k.push({content:pt}),H=pt}}catch(ge){ce=void 0,(
|
|
1122
|
+
`:"")+"Tool calling is no longer available for this turn. Provide your final answer directly as plain text now, using the information gathered so far.",be=jv({system:ge,tools:l,messages:Oe}),we=this.buildClaudeThinkingParam(t,de,!1),ue=await s.messages.stream({...w,max_tokens:de,thinking:we,tool_choice:{type:"none"},system:be.system,...be.tools&&be.tools.length>0&&{tools:be.tools},messages:be.messages});ce=ue;const Le=await ue.finalMessage();ce=void 0,R.input+=Le.usage?.input_tokens||0,R.output+=Le.usage?.output_tokens||0,X.read+=Le.usage?.cache_read_input_tokens??0,X.creation+=Le.usage?.cache_creation_input_tokens??0,X.creation5m+=Le.usage?.cache_creation?.ephemeral_5m_input_tokens??0,X.creation1h+=Le.usage?.cache_creation?.ephemeral_1h_input_tokens??0,R.total=R.input+R.output+X.read+X.creation,Le.usage?.output_tokens_details?.thinking_tokens&&(R.reasoning=(R.reasoning??0)+Le.usage.output_tokens_details.thinking_tokens),ve=Le.stop_reason;const at=Le.content.filter(pt=>pt.type==="thinking").map(pt=>pt.thinking).join("");at&&k.push({content:"",reasoning:at});const vt=Le.content.filter(pt=>pt.type==="text").map(pt=>pt.text).join("");if(vt)$e=!0,k.push({content:vt}),H=vt;else{const pt=gt?Nc(Y):pp(E,Y);k.push({content:pt}),H=pt}}catch(ge){ce=void 0,(Ae.signal.aborted||mp(ge))&&(Ye=!1,De=!0),p.warn("[GoogleVertex] Tools-disabled backstop call failed; falling back to a terminal message",{error:ge instanceof Error?ge.message:String(ge)});const be=gt&&!De?Nc(Y):this.buildLoopExitMessage({turnClock:Pe,wasAborted:De,stallTimeoutMs:t.stallTimeoutMs,maxSteps:E,toolCallCount:Y});k.push({content:be}),H=be}}}const Se=H.length===0&&G===0&&!O.value,xe=C.filter(Y=>Y.toolName!=="final_result").length;if(Se&&xe>0){const Y=gt&&!De?Nc(xe):this.buildLoopExitMessage({turnClock:Pe,wasAborted:De,stallTimeoutMs:t.stallTimeoutMs,maxSteps:E,toolCallCount:xe});k.push({content:Y}),H=Y}U.value=ve==="max_tokens"?"length":Ye&&!$e?"tool-calls":"stop",I.finishReason=U.value,I.responseTime=Date.now()-n,I.totalToolExecutions=C.filter(Y=>Y.toolName!=="final_result").length;const fe=uv({timedOut:Pe.timedOut,stalled:Pe.stalled,wasAborted:De,cappedWithoutAnswer:Ye&&!$e,contextCappedWithoutAnswer:gt&&!$e,finishReason:U.value});M.value=fe,F.value=ve??void 0,I.stopReason=fe,I.rawFinishReason=F.value,I.stepsUsed=he,fe!=="completed"&&this.emitTurnEvent({phase:fe,step:he,maxSteps:E,toolCallCount:I.totalToolExecutions,elapsedMs:Pe.elapsedMs()}),X.read>0&&(R.cacheReadTokens=X.read),X.creation>0&&(R.cacheCreationTokens=X.creation);const $=ki({text:H,...O.value?{structuredOutput:O.value}:{}});q.setAttribute(wo.OBSERVATION_OUTPUT,$),q.setAttribute(wo.TRACE_OUTPUT,$),q.setAttribute(wo.OBSERVATION_METADATA,ki({toolsOffered:N,toolCount:N.length,maxSteps:E,steps:he,toolCallCount:I.totalToolExecutions,toolsCalled:P.filter(Y=>Y!=="final_result"),structuredOutput:m,usage:{input:R.input,output:R.output,input_cached_tokens:X.read,input_cache_creation:X.creation,input_cache_creation_5m:X.creation5m,input_cache_creation_1h:X.creation1h}})),q.setStatus({code:Ue.OK}),k.close()}catch(se){q.setStatus({code:Ue.ERROR,message:se instanceof Error?se.message:String(se)}),se instanceof Error&&q.recordException(se),p.error("[GoogleVertex] Native Anthropic SDK stream error",se),k.error(this.handleProviderError(se))}finally{q.end(),t.abortSignal?.removeEventListener("abort",Ee),Ae.signal.removeEventListener("abort",Q),Pe.dispose()}})().catch(()=>{});const Te={stream:k.iterable,provider:this.providerName,model:r,usage:R,metadata:I};return Object.defineProperty(Te,"toolCalls",{enumerable:!0,configurable:!0,get:()=>C.filter(he=>he.toolName!=="final_result")}),Object.defineProperty(Te,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>P.filter(he=>he!=="final_result")}),Object.defineProperty(Te,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>bd(A.filter(he=>he.name!=="final_result"))}),Object.defineProperty(Te,"structuredOutput",{enumerable:!0,configurable:!0,get:()=>O.value}),Object.defineProperty(Te,"finishReason",{enumerable:!0,configurable:!0,get:()=>U.value}),Object.defineProperty(Te,"stopReason",{enumerable:!0,configurable:!0,get:()=>M.value}),Object.defineProperty(Te,"rawFinishReason",{enumerable:!0,configurable:!0,get:()=>F.value}),Te}async executeNativeAnthropicGenerate(t){const r=A_t(t.model||this.modelName||"claude-sonnet-4-5@20250929"),n=Date.now(),o=ml(t.timeout)??3e5,s=await this.createAnthropicVertexClient(o);p.debug("[GoogleVertex] Using native @anthropic-ai/vertex-sdk for Claude generate",{model:r,project:this.projectId,location:this.location});const i=[],a=t.input?.text||t.prompt||"Please respond.";if(t.conversationMessages&&t.conversationMessages.length>0)i.push(...GQ(t.conversationMessages));else if(t.conversationHistory&&t.conversationHistory.length>0)for(const W of t.conversationHistory)(W.role==="user"||W.role==="assistant")&&i.push({role:W.role,content:n0(W.content)});const c=t.input,l=[];if(c?.pdfFiles&&c.pdfFiles.length>0){p.debug(`[GoogleVertex] Processing ${c.pdfFiles.length} PDF file(s) for native Anthropic generate`);for(const W of c.pdfFiles){let re;typeof W=="string"?Fo.existsSync(W)?re=Fo.readFileSync(W):re=Buffer.from(W,"base64"):re=W;const ye=re.toString("base64");l.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:ye}})}}if(c?.images&&c.images.length>0){p.debug(`[GoogleVertex] Processing ${c.images.length} image(s) for native Anthropic generate`);for(const W of c.images){const re=E_(W);let ye,Re="image/jpeg";if(typeof re=="string")if(Fo.existsSync(re)){ye=Fo.readFileSync(re);const K=k_(re);Re=K.startsWith("image/")?K:this.detectImageType(ye)}else if(re.startsWith("data:")){const K=re.match(/^data:([^;]+);base64,(.+)$/);if(K)Re=K[1],ye=Buffer.from(K[2],"base64");else continue}else if(re.startsWith("http://")||re.startsWith("https://"))try{const K=await fetch(re);if(!K.ok){p.warn(`[GoogleVertex] Image fetch failed: ${K.status} ${K.statusText}, skipping`,{url:rr(re)});continue}const Se=await K.arrayBuffer();ye=Buffer.from(Se);const xe=K.headers.get("content-type");xe&&xe.startsWith("image/")&&(Re=xe.split(";")[0])}catch(K){p.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${K instanceof Error?K.message:String(K)}`,{url:rr(re)});continue}else ye=Buffer.from(re,"base64"),Re=this.detectImageType(ye);else ye=re,Re=this.detectImageType(ye);const x=ye.toString("base64");l.push({type:"image",source:{type:"base64",media_type:Re,data:x}})}}l.push({type:"text",text:a}),jQ(i,l.length===1&&l[0].type==="text"?a:l);let u;const d=new pv,m=[];if(!t.disableTools&&t.tools&&Object.keys(t.tools).length>0){u=[];for(const[W,re]of Object.entries(t.tools))u.push(this.buildAnthropicToolDeclaration(W,re)),re.execute&&d.set(W,re.execute)}let h=!1,f="";if(t.schema){h=!0;const W=this.buildFinalResultTool(t.schema);u||(u=[]),u.push(W),f=`
|
|
1123
1123
|
|
|
1124
|
-
IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`,p.debug("[GoogleVertex] Added final_result tool for Anthropic structured output (generate)",{schemaKeys:Object.keys(W.input_schema.properties??{}),totalTools:u.length})}const g=t.systemPrompt?t.systemPrompt+f:f?f.trim():void 0,y=hl(this.providerName,r,{...t.temperature!==void 0&&{temperature:t.temperature},...t.topP!==void 0&&{topP:t.topP}},"vertex.anthropic.generate"),v=UO(r,t.maxTokens),w=this.buildClaudeThinkingParam(t,v,h),E={model:r,max_tokens:v,...w&&{thinking:w},messages:i,...u&&u.length>0&&{tools:u},...h&&{tool_choice:{type:"any"}},...g&&{system:g},...y.temperature!==void 0&&{temperature:y.temperature},...y.topP!==void 0&&{top_p:y.topP},...t.stopSequences&&t.stopSequences.length>0&&{stop_sequences:t.stopSequences}},_=t.maxSteps||Bs,C=h?Math.max(_-1,0):_;let A=0,k="",R="",I;const P=[];let O=0,U=0,M=0,F=0,N=0,L="",q,B=!1,H=!1,G=!1,X=!1,ce=!1;const Q=[...i],
|
|
1124
|
+
IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`,p.debug("[GoogleVertex] Added final_result tool for Anthropic structured output (generate)",{schemaKeys:Object.keys(W.input_schema.properties??{}),totalTools:u.length})}const g=t.systemPrompt?t.systemPrompt+f:f?f.trim():void 0,y=hl(this.providerName,r,{...t.temperature!==void 0&&{temperature:t.temperature},...t.topP!==void 0&&{topP:t.topP}},"vertex.anthropic.generate"),v=UO(r,t.maxTokens),w=this.buildClaudeThinkingParam(t,v,h),E={model:r,max_tokens:v,...w&&{thinking:w},messages:i,...u&&u.length>0&&{tools:u},...h&&{tool_choice:{type:"any"}},...g&&{system:g},...y.temperature!==void 0&&{temperature:y.temperature},...y.topP!==void 0&&{top_p:y.topP},...t.stopSequences&&t.stopSequences.length>0&&{stop_sequences:t.stopSequences}},_=t.maxSteps||Bs,C=h?Math.max(_-1,0):_;let A=0,k="",R="",I;const P=[];let O=0,U=0,M=0,F=0,N=0,L="",q,B=!1,H=!1,G=!1,X=!1,ce=!1;const Q=[...i],Ae=mv(kd("vertex",r)),Ee=new Map,le=new AbortController,ae=()=>le.abort();t.abortSignal?.addEventListener("abort",ae),t.abortSignal?.aborted&&le.abort();const Pe=Ih(t.toolTimeoutMs),ke=dv({turnTimeoutMs:t.turnTimeoutMs,stallTimeoutMs:t.stallTimeoutMs,wrapupTimeLeadMs:t.wrapupTimeLeadMs,onDeadline:W=>{p.warn(W==="timeout"?`[GoogleVertex] Anthropic generate turn exceeded its ${t.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleVertex] Anthropic generate turn made no progress for ${t.stallTimeoutMs}ms \u2014 aborting`),le.abort()}}),Te=()=>{ke.dispose(),t.abortSignal?.removeEventListener("abort",ae)},he={};for(const W of d.keys()){const re=d.get(W);re&&(he[W]={execute:Uf(W,re,{toolTimeoutMs:Pe,abortSignal:le.signal,onProgress:()=>ke.noteProgress()})})}const Oe=EQ({client:s,maxSteps:C,toolsRecord:t.tools??{},toolFailureBreaker:{maxRetries:Rh,classifyResultFailure:W=>lO(W)??void 0},buildParams:W=>{this.refreshAnthropicToolDeclarations(t.tools,u,d,Ee);const re=jv({system:g,tools:u,messages:W});return{...E,...re.system!==void 0&&{system:re.system},...re.tools&&re.tools.length>0&&{tools:re.tools},messages:re.messages}},planReclaim:W=>{if(!Ae.shouldStop())return;const re=[...W];return wOt(re,r,Ae.projectedNextPromptTokens)?(Ae.resetAfterReclaim(),{conversation:re}):(G=!0,p.warn(`[GoogleVertex] Anthropic generate turn stopped by the context guard: projected prompt ~${Ae.projectedNextPromptTokens} tokens >= threshold ${Ae.thresholdTokens} \u2014 forcing finalization.`),{stop:!0})},noteObservedPromptTokens:W=>{Ae.noteUsage(W,0)},...h?{finalResultToolName:"final_result",onTerminalResult:W=>{try{I=JSON.parse(W)}catch{}p.debug("[GoogleVertex] Extracted structured output from final_result tool (generate)",{chars:W.length})}}:{}}),De={...Oe,buildStepRequest:(W,re)=>(A=re+1,ke.noteProgress(),Oe.buildStepRequest(W,re)),resolveToolOnMiss:W=>{const re=this.resolveAnthropicToolOnMiss(W,t.tools,u,d,Ee);if(re)return{execute:Uf(W,re,{toolTimeoutMs:Pe,abortSignal:le.signal,onProgress:()=>ke.noteProgress()})}},buildToolResultMessages:(W,re,ye,Re)=>{for(const K of ye)P.push({toolName:K.name,args:K.args}),m.push({name:K.name,input:K.args,output:K.output});R=X3r(R,re.text);const x=Oe.buildToolResultMessages(W,re,ye,Re);if(ke.shouldNudgeWrapup()){const K=x[x.length-1];K&&Array.isArray(K.content)&&K.content.push({type:"text",text:lv(h)})}Ct(this.handleToolExecutionStorage(ye.map(K=>({toolName:K.name,args:K.args,stepIndex:Re+1})),ye.map(K=>({toolName:K.name,output:K.output,stepIndex:Re+1})),t,new Date),Ph,"tool storage write timed out").catch(K=>{p.warn("[GoogleVertex] Failed to store native Anthropic generate tool executions",{error:K instanceof Error?K.message:String(K)})});try{const K=x[x.length-1];Ae.noteAppendedChars(JSON.stringify(K?.content??[]).length)}catch{}return x}},{stream:Ye,resultPromise:gt}=Ld(De,Q.slice(),{tools:he,abortSignal:le.signal,toolTimeoutMs:Pe}),$e=(async()=>{for await(const W of Ye)W.reasoning&&(L+=W.reasoning)})();let Ie,ve;try{Ie=await gt}catch(W){ve=W}if(await Ff($e,"GoogleVertex"),ve!==void 0)if(le.signal.aborted||mp(ve))B=!0;else throw p.error("[GoogleVertex] Native Anthropic SDK generate error",{error:ve,model:r}),this.handleProviderError(ve);if(Ie&&(O+=Ie.usage.inputTokens,U+=Ie.usage.outputTokens,M+=Ie.usage.cacheReadTokens??0,F+=Ie.usage.cacheWriteTokens??0,N+=Ie.usage.reasoningTokens??0,q=Ie.rawStopReason??q,k=Ie.text||k,Q.length=0,Q.push(...Ie.conversation)),le.signal.aborted&&(B=!0),!ce&&!k){le.signal.aborted&&(B=!0);const W=P.filter(ye=>ye.toolName!=="final_result").length,re=Math.max(1024,Math.min(E.max_tokens,kd("vertex",r)-Ae.projectedNextPromptTokens-4e3));if(B)p.warn(`[GoogleVertex] Native Anthropic generate loop ended mid-turn (${ke.timedOut?"turn time limit":ke.stalled?"stall watchdog":"caller abort"}); returning gathered text or an honest terminal message.`),k=R||this.buildLoopExitMessage({turnClock:ke,wasAborted:B,stallTimeoutMs:t.stallTimeoutMs,maxSteps:_,toolCallCount:W});else if(h){G||(H=!0),p.warn(G?"[GoogleVertex] Native Anthropic generate loop stopped by the context guard without final_result; forcing a finalization call.":`[GoogleVertex] Native Anthropic generate loop reached maxSteps (${_}) without final_result; forcing a finalization call.`);try{const ye=jv({system:g,tools:u,messages:Q}),Re=await Ct(s.messages.create({...E,max_tokens:re,tool_choice:{type:"tool",name:"final_result"},...ye.system!==void 0&&{system:ye.system},...ye.tools&&ye.tools.length>0&&{tools:ye.tools},messages:ye.messages},{signal:le.signal}),o,"Anthropic finalization call timed out");O+=Re.usage?.input_tokens||0,U+=Re.usage?.output_tokens||0,M+=Re.usage?.cache_read_input_tokens||0,F+=Re.usage?.cache_creation_input_tokens||0,q=Re.stop_reason;const x=Re.content.find(K=>K.type==="tool_use"&&K.name==="final_result");x?(I=x.input,k=JSON.stringify(I),X=!0,p.debug("[GoogleVertex] Forced finalization returned structured output (generate)",{keys:Object.keys(I)})):k=G?Nc(W):pp(_,W)}catch(ye){(le.signal.aborted||mp(ye))&&(H=!1,B=!0),p.warn("[GoogleVertex] Forced finalization call failed; falling back to a terminal message",{error:ye instanceof Error?ye.message:String(ye)}),k=G&&!B?Nc(W):this.buildLoopExitMessage({turnClock:ke,wasAborted:B,stallTimeoutMs:t.stallTimeoutMs,maxSteps:_,toolCallCount:W})}}else if(G||(H=!0),R)p.warn(G?"[GoogleVertex] Native Anthropic generate loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Native Anthropic generate loop reached maxSteps (${_}); returning text already gathered from prior steps.`),k=R;else{p.warn(G?"[GoogleVertex] Native Anthropic generate loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Native Anthropic generate loop reached maxSteps (${_}) with no text; synthesizing a final answer with tools disabled.`);try{const ye=(g?g+`
|
|
1125
1125
|
|
|
1126
|
-
`:"")+"Tool calling is no longer available for this turn. Provide your final answer directly as plain text now, using the information gathered so far.",Re=jv({system:ye,tools:u,messages:Q}),x=this.buildClaudeThinkingParam(t,re,!1),K=await Ct(s.messages.create({...E,max_tokens:re,thinking:x,tool_choice:{type:"none"},system:Re.system,...Re.tools&&Re.tools.length>0&&{tools:Re.tools},messages:Re.messages},{signal:le.signal}),o,"Anthropic backstop call timed out");O+=K.usage?.input_tokens||0,U+=K.usage?.output_tokens||0,M+=K.usage?.cache_read_input_tokens||0,F+=K.usage?.cache_creation_input_tokens||0,N+=K.usage?.output_tokens_details?.thinking_tokens??0,q=K.stop_reason;const Se=K.content.filter(fe=>fe.type==="thinking").map(fe=>fe.thinking).join("");Se&&(L+=Se);const
|
|
1126
|
+
`:"")+"Tool calling is no longer available for this turn. Provide your final answer directly as plain text now, using the information gathered so far.",Re=jv({system:ye,tools:u,messages:Q}),x=this.buildClaudeThinkingParam(t,re,!1),K=await Ct(s.messages.create({...E,max_tokens:re,thinking:x,tool_choice:{type:"none"},system:Re.system,...Re.tools&&Re.tools.length>0&&{tools:Re.tools},messages:Re.messages},{signal:le.signal}),o,"Anthropic backstop call timed out");O+=K.usage?.input_tokens||0,U+=K.usage?.output_tokens||0,M+=K.usage?.cache_read_input_tokens||0,F+=K.usage?.cache_creation_input_tokens||0,N+=K.usage?.output_tokens_details?.thinking_tokens??0,q=K.stop_reason;const Se=K.content.filter(fe=>fe.type==="thinking").map(fe=>fe.thinking).join("");Se&&(L+=Se);const xe=K.content.filter(fe=>fe.type==="text").map(fe=>fe.text).join("");xe?(X=!0,k=xe):k=G?Nc(W):pp(_,W)}catch(ye){(le.signal.aborted||mp(ye))&&(H=!1,B=!0),p.warn("[GoogleVertex] Tools-disabled backstop call failed; falling back to a terminal message",{error:ye instanceof Error?ye.message:String(ye)}),k=G&&!B?Nc(W):this.buildLoopExitMessage({turnClock:ke,wasAborted:B,stallTimeoutMs:t.stallTimeoutMs,maxSteps:_,toolCallCount:W})}}}Te();const J=Date.now()-n,V=P.filter(W=>W.toolName!=="final_result"),se=m.filter(W=>W.name!=="final_result");!k&&V.length>0&&(k=G&&!B?Nc(V.length):this.buildLoopExitMessage({turnClock:ke,wasAborted:B,stallTimeoutMs:t.stallTimeoutMs,maxSteps:_,toolCallCount:V.length}));const oe=q==="max_tokens"?"length":H&&!X?"tool-calls":"stop",Z=uv({timedOut:ke.timedOut,stalled:ke.stalled,wasAborted:B,cappedWithoutAnswer:H&&!X,contextCappedWithoutAnswer:G&&!X,finishReason:oe});Z!=="completed"&&this.emitTurnEvent({phase:Z,step:A,maxSteps:_,toolCallCount:V.length,elapsedMs:ke.elapsedMs()});const ie={content:k,finishReason:oe,stopReason:Z,rawFinishReason:q??void 0,stepsUsed:A,provider:this.providerName,model:r,usage:{input:O,output:U,total:O+U+M+F,...M>0&&{cacheReadTokens:M},...F>0&&{cacheCreationTokens:F},...N>0&&{reasoning:N}},responseTime:J,toolsUsed:V.map(W=>W.toolName),toolExecutions:af(t,se),enhancedWithTools:V.length>0,...L&&{reasoning:L},...N>0&&{reasoningTokens:N}};return this.enhanceResult(ie,t,n)}async processCSVFilesForNativeSDK(t){const r=t.input;if(!r?.csvFiles||r.csvFiles.length===0)return t;p.info(`[GoogleVertex] Processing ${r.csvFiles.length} CSV file(s) for native Gemini 3 SDK`);let n=r.text||"";for(let o=0;o<r.csvFiles.length;o++){const s=r.csvFiles[o];try{const i=await Pd.detectAndProcess(s,{allowedTypes:["csv"],csvOptions:"csvOptions"in t?t.csvOptions:void 0}),a=typeof s=="string"?Bm.basename(s):`csv_file_${o+1}.csv`;let c=`
|
|
1127
1127
|
|
|
1128
1128
|
## CSV Data from "${a}":
|
|
1129
1129
|
`;if(i.metadata){const l=i.metadata;(l.rowCount||l.columnCount||l.columnNames)&&(c+=`**File Info:**
|
|
@@ -1317,7 +1317,7 @@ ${o.join(`
|
|
|
1317
1317
|
`);const r=e.prompt;return typeof r=="string"?r:Array.isArray(r)?r.filter(n=>n.role&&n.content).map(n=>typeof n.content=="string"?`${n.role}: ${n.content}`:`${n.role}: ${JSON.stringify(n.content)}`).join(`
|
|
1318
1318
|
`):String(r)}extractTextFromResponse(e){if(typeof e=="string")return e;if(e.generated_text)return e.generated_text;if(e.outputs)return e.outputs;if(e.text)return e.text;if(Array.isArray(e)&&e[0]?.generated_text)return e[0].generated_text;if(e.choices&&Array.isArray(e.choices)){const t=e.choices[0];if(typeof t?.message?.content=="string")return t.message.content;if(t?.message?.tool_calls?.length)return""}return JSON.stringify(e)}extractToolCallsFromResponse(e){if(e.choices&&Array.isArray(e.choices)){const t=e.choices[0];if(t?.message?.tool_calls)return t.message.tool_calls.map(r=>({type:"function",id:String(r.id||`call_${Xe()}`),function:{name:String(r.function.name),arguments:String(r.function.arguments)}}))}if(e.tool_calls&&Array.isArray(e.tool_calls))return e.tool_calls;if(e.content&&Array.isArray(e.content)){const t=e.content.filter(r=>r.type==="tool_use");if(t.length>0)return t.map(r=>({type:"function",id:String(r.id||`call_${Xe()}`),function:{name:String(r.name),arguments:JSON.stringify(r.input||{})}}))}}mapSageMakerFinishReason(e){switch(e?.toLowerCase()){case"stop":case"end_turn":case"stop_sequence":return"stop";case"length":case"max_tokens":case"max_length":return"length";case"content_filter":case"content_filtered":return"content-filter";case"tool_calls":case"function_call":return"tool-calls";case"error":return"error";default:return"unknown"}}getModelInfo(){return{modelId:this.modelId,provider:this.provider,specificationVersion:this.specificationVersion,endpointName:this.modelConfig.endpointName,modelType:this.modelConfig.modelType,region:this.config.region}}async testConnectivity(){try{return{success:!!(await this.doGenerate({inputFormat:"messages",mode:{type:"regular"},prompt:[{role:"user",content:[{type:"text",text:"Hello"}]}],maxTokens:10})).text}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async doBatchGenerate(e,t){try{p.debug("SageMaker batch generate called",{batchSize:e.length,endpointName:this.modelConfig.endpointName});const r=await this.processPromptsInParallel(e,t);return p.debug("SageMaker batch generate completed",{batchSize:e.length,successCount:r.length}),r}catch(r){throw p.error("SageMaker batch generate failed",{error:r instanceof Error?r.message:String(r),batchSize:e.length}),cr(r)?r:Kd(r,this.modelConfig.endpointName)}}async processPromptsInParallel(e,t){const r=Math.min(this.modelConfig.initialConcurrency??kDt,e.length),n=this.modelConfig.maxConcurrency??xDt,o=this.modelConfig.minConcurrency??IDt,s=new Array(e.length),i=[],a=m8r(r,n,o),c=async(d,m)=>{await a.acquire();const h=Date.now();try{const f=await this.doGenerate({inputFormat:"messages",mode:{type:"regular"},prompt:[{role:"user",content:[{type:"text",text:d}]}],maxTokens:t?.maxTokens,temperature:t?.temperature,topP:t?.topP}),g=Date.now()-h;s[m]={text:f.text||"",usage:{promptTokens:f.usage.inputTokens??0,completionTokens:f.usage.outputTokens??0,total:f.usage.totalTokens??(f.usage.inputTokens??0)+(f.usage.outputTokens??0)},finishReason:f.finishReason,index:m},a.recordSuccess(g)}catch(f){i.push({index:m,error:f instanceof Error?f:new Error(String(f))});const g=Date.now()-h;a.recordError(g),s[m]={text:"",usage:{promptTokens:0,completionTokens:0,total:0},finishReason:"error",index:m}}finally{a.release()}},l=e.map((d,m)=>c(d,m));await Promise.all(l);const u=a.getMetrics();return p.debug("Parallel batch processing completed",{totalPrompts:e.length,successCount:u.completedCount,errorCount:u.errorCount,finalConcurrency:u.currentConcurrency,errorRate:u.errorCount/e.length,averageResponseTime:u.averageResponseTime}),i.length>0&&p.warn("Batch processing encountered errors",{errorCount:i.length,sampleErrors:i.slice(0,3).map(d=>({index:d.index,message:d.error.message}))}),s.map(({text:d,usage:m,finishReason:h})=>({text:d,usage:m,finishReason:h}))}getModelCapabilities(){return{...this.getModelInfo(),capabilities:{streaming:!0,toolCalling:!0,structuredOutput:!0,batchInference:!0,supportedResponseFormats:["text","json_object","json_schema"],supportedToolTypes:["function"],maxBatchSize:100,adaptiveConcurrency:!0,errorRecovery:!0}}}}}}),PDt={};ee(PDt,{AmazonSageMakerProvider:()=>dee,default:()=>MDt});var dee,MDt,y8r=b({"src/lib/providers/amazonSagemaker.ts"(){"use strict";ec(),fv(),z(),tf(),Zm(),Ic(),ui(),cd(),Lo(),eX(),Or(),pr(),zGr(),wA(),g8r(),dee=class extends ba{sagemakerModel;sagemakerConfig;modelConfig;constructor(e,t,r,n,o){super(e,"sagemaker",n);try{const s=$Gr(o?.region??r,{...o?.region!==void 0&&{region:o.region},...o?.accessKeyId!==void 0&&{accessKeyId:o.accessKeyId},...o?.secretAccessKey!==void 0&&{secretAccessKey:o.secretAccessKey},...o?.sessionToken!==void 0&&{sessionToken:o.sessionToken},...o?.endpoint!==void 0&&{endpoint:o.endpoint}});this.sagemakerConfig={...s,...o?.region!==void 0&&{region:o.region},...o?.accessKeyId!==void 0&&{accessKeyId:o.accessKeyId},...o?.secretAccessKey!==void 0&&{secretAccessKey:o.secretAccessKey},...o?.sessionToken!==void 0&&{sessionToken:o.sessionToken},...o?.endpoint!==void 0&&{endpoint:o.endpoint}},this.modelConfig=UGr(t||sDt()),this.sagemakerModel=new RDt(this.modelName,this.sagemakerConfig,this.modelConfig),p.debug("Amazon SageMaker Provider initialized",{modelName:this.modelName,endpointName:this.modelConfig.endpointName,region:this.sagemakerConfig.region,provider:this.providerName})}catch(s){throw p.error("Failed to initialize SageMaker provider",{error:s instanceof Error?s.message:String(s),modelName:e,endpointName:t}),Kd(s)}}getProviderName(){return"sagemaker"}getDefaultModel(){return BGr()}getAISDKModel(){return this.sagemakerModel}async generate(e,t){await this.ensureModelLimits();const r=this.normalizeTextOptions(e);if(Ed(r,this.modelName)!=="text")return super.generate(r,t);this.validateOptions(r);const n=await this.getToolsForStream(r),o="disableInternalFallback"in r&&r.disableInternalFallback===!0;return this.runGenerateWithModelFallback(()=>this.withTurnTimeout({...r,tools:n},this.getDescriptorGenerateMs(),s=>this.executeNativeGenerate(s)),o)}async executeNativeGenerate(e){const t=Date.now(),r=await this.getAISDKModelWithMiddleware(e);if(!yC(r))throw this.handleProviderError(new Error("sagemaker: model handle exposes no doGenerate()"));const n=async m=>{const h=m.responseFormat,f=await r.doGenerate({...m,...m.maxOutputTokens!==void 0?{maxTokens:m.maxOutputTokens}:{},...h?.type==="json"?{responseFormat:h.schema?{type:"json_schema",json_schema:{name:"response",schema:h.schema}}:{type:"json_object"}}:{}});if(Array.isArray(f.content))return f;const g=[];typeof f.text=="string"&&f.text&&g.push({type:"text",text:f.text}),typeof f.reasoning=="string"&&f.reasoning&&g.push({type:"reasoning",text:f.reasoning});for(const v of Array.isArray(f.toolCalls)?f.toolCalls:[]){if(typeof v!="object"||v===null)continue;const w=v,E=w.function;typeof w.id=="string"&&typeof E?.name=="string"&&g.push({type:"tool-call",toolCallId:w.id,toolName:E.name,input:E.arguments??"{}"})}const y=f.usage;return{...f,content:g,usage:{inputTokens:{total:typeof y?.inputTokens=="number"?y.inputTokens:0},outputTokens:{total:typeof y?.outputTokens=="number"?y.outputTokens:0}}}},s=!e.disableTools&&this.supportsTools()?e.tools||{}:{},i=Object.entries(s).map(([m,h])=>{const f=h;return{type:"function",name:m,description:f.description??"",inputSchema:f.inputSchema?Ao(f.inputSchema):{type:"object",properties:{}}}}),a=e.schema?{type:"json",schema:Ao(e.schema)}:void 0,c=await this.buildMessagesForStream(e),l=[],u=await aD({doGenerate:n,conversation:c,...a?{responseFormat:a}:{},...i.length>0?{tools:i}:{},toolsRecord:s,maxSteps:e.maxSteps||Bs,...e.maxTokens?{maxOutputTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.toolTimeoutMs!==void 0?{toolTimeoutMs:e.toolTimeoutMs}:{},runStep:m=>r0(m,void 0,"sagemaker generate").catch(h=>{throw this.handleProviderError(h)})},l),d={content:u.text,provider:this.providerName,model:this.modelName,finishReason:u.finishReason,usage:{input:u.inputTokens,output:u.outputTokens,total:u.inputTokens+u.outputTokens},responseTime:Date.now()-t,...u.reasoning?{reasoning:u.reasoning}:{},toolsUsed:u.toolsUsed,toolCalls:E7(l),toolExecutions:af(e,bd(l)),enhancedWithTools:u.toolsUsed.length>0};return this.finalizeNativeGenerate(d,e,t)}async doStream(e){return dt({name:"neurolink.provider.sagemaker.stream",tracer:Be.stream,attributes:{"provider.name":"sagemaker","model.name":this.modelName,"sagemaker.endpoint":this.modelConfig.endpointName,"sagemaker.region":this.sagemakerConfig.region}},async()=>{try{const t=await this.buildMessagesForStream(e),r=await this.sagemakerModel.doStream({prompt:t,maxTokens:e.maxTokens,temperature:e.temperature});let n,o;const s=new Promise(c=>{n=c}),i=new Promise(c=>{o=c}),a=hv();return(async()=>{const c=r.stream.getReader();let l=!1;try{for(;;){const{done:u,value:d}=await c.read();if(u)break;const m=d;if(m.type==="text-delta"&&m.textDelta){a.push({content:m.textDelta});continue}m.type==="finish"&&(l=!0,n(m.finishReason??"stop"),o({inputTokens:m.usage?.inputTokens??m.usage?.promptTokens??0,outputTokens:m.usage?.outputTokens??m.usage?.completionTokens??0}))}a.close()}catch(u){a.error(u)}finally{c.releaseLock(),l||(n("unknown"),o({inputTokens:0,outputTokens:0}))}})(),{stream:a.iterable,finishReason:s,usage:i,warnings:(r.warnings??[]).map(c=>c.message??String(c))}}catch(t){throw this.handleProviderError(t)}})}formatProviderError(e){return e instanceof Co?e:e instanceof Error&&e.name==="TimeoutError"?new Co("SageMaker request timed out. Consider increasing timeout.",{code:"NETWORK_ERROR",statusCode:408,cause:e,endpoint:this.modelConfig.endpointName}):Kd(e,this.modelConfig.endpointName)}getSageMakerInfo(){return{endpointName:this.modelConfig.endpointName,modelType:this.modelConfig.modelType||"custom",region:this.sagemakerConfig.region,configured:!!(this.sagemakerConfig.accessKeyId&&this.sagemakerConfig.secretAccessKey)}}async testConnection(){try{return!this.sagemakerConfig.accessKeyId||!this.sagemakerConfig.secretAccessKey?{connected:!1,error:"AWS credentials not configured"}:!this.modelConfig.endpointName||this.modelConfig.endpointName==="default-endpoint"?{connected:!1,error:"SageMaker endpoint not configured"}:{connected:!0}}catch(e){return{connected:!1,error:e instanceof Error?e.message:String(e)}}}async getModel(){return this.getAISDKModel()}async testConnectivity(){const e=this.sagemakerModel;return e.testConnectivity?await e.testConnectivity():{success:!1,error:"Test method not available"}}getModelCapabilities(){const e=this.sagemakerModel;return e.getModelCapabilities?e.getModelCapabilities():{capabilities:{streaming:!0,toolCalling:!0,structuredOutput:!0,batchInference:!0,supportedResponseFormats:["text","json_object"],supportedToolTypes:["function"],maxBatchSize:10}}}},MDt=dee}}),ODt,mee,pee,DDt,hee,fee,NDt,LDt,gee,FDt,v8r=b({"src/lib/providers/nvidiaNim/client.ts"(){"use strict";ut(),qi(),z(),Ut(),ts(),kl(),Cc(),ODt=["unsupported","not supported","does not support","unrecognized","unknown field","unknown parameter","unknown argument","invalid field","invalid parameter","invalid argument"],mee=(e,t)=>{if(!e)return!1;const r=e.toLowerCase(),n=t.toLowerCase();let o=r.indexOf(n);for(;o!==-1;){const s=Math.max(0,o-80),i=Math.min(r.length,o+n.length+80),a=r.slice(s,i);if(ODt.some(c=>a.includes(c)))return!0;o=r.indexOf(n,o+n.length)}return!1},pee=(e,t)=>{try{const r=JSON.parse(e);let n=!1;if(t==="chat_template"&&"chat_template"in r&&(delete r.chat_template,n=!0),t==="reasoning_budget"){const o=r.chat_template_kwargs;o&&"reasoning_budget"in o&&(delete o.reasoning_budget,n=!0,Object.keys(o).length===0&&delete r.chat_template_kwargs)}return n?JSON.stringify(r):null}catch{return null}},DDt="https://integrate.api.nvidia.com/v1",hee=e=>{const t=process.env[e];if(!t)return;const r=Number.parseInt(t,10);return Number.isFinite(r)?r:void 0},fee=e=>{const t=process.env[e];if(!t)return;const r=Number.parseFloat(t);return Number.isFinite(r)?r:void 0},NDt=(e,t)=>{const r={},n=hee("NVIDIA_NIM_TOP_K");n!==void 0&&n!==-1&&(r.top_k=n);const o=fee("NVIDIA_NIM_MIN_P");o!==void 0&&o!==0&&(r.min_p=o);const s=fee("NVIDIA_NIM_REPETITION_PENALTY");s!==void 0&&s!==1&&(r.repetition_penalty=s);const i=hee("NVIDIA_NIM_MIN_TOKENS");i!==void 0&&i!==0&&(r.min_tokens=i);const a=process.env.NVIDIA_NIM_CHAT_TEMPLATE;return a&&(r.chat_template=a),e&&(r.chat_template_kwargs={thinking:!0,enable_thinking:!0,...t?{reasoning_budget:t}:{}}),r},LDt=()=>fa(DCr()),gee=()=>_i("NVIDIA_NIM_MODEL",Ar.get("nvidia-nim")?.defaultModel??"openai/gpt-oss-20b"),FDt=class extends Lc{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:LDt(),i=n?.baseURL??process.env.NVIDIA_NIM_BASE_URL??DDt;super("nvidia-nim",e,t,{baseURL:i,apiKey:s}),p.debug("NVIDIA NIM Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:No(this.config.baseURL)})}getProviderName(){return"nvidia-nim"}getDefaultModel(){return gee()}adjustBuildBodyOptions(e,t){const r=t,n=r.thinkingConfig,o=r.thinkingLevel??n?.thinkingLevel,s=o!==void 0&&o!=="minimal",i=typeof r.maxTokens=="number"?r.maxTokens:void 0,a=NDt(s,i);return Object.keys(a).length>0?{...t,extraBody:a}:t}adjustBodyAfter400(e,t){const r=t.responseBody??"";let n=JSON.stringify(e);const o=[];for(const s of["chat_template","reasoning_budget"])if(mee(r,s)){const i=pee(n,s);i!==null&&(n=i,o.push(s))}if(o.length!==0)return p.debug("NVIDIA NIM: 400 rejected request field(s) \u2014 retrying once without them",{strippedFields:o,model:e.model,rejection:r.slice(0,200)}),JSON.parse(n)}formatProviderError(e){const t=[{match:r=>/Invalid API key|401|Unauthorized/.test(r.message),errorClass:Mr,message:"Invalid NVIDIA NIM API key. Get one at https://build.nvidia.com/settings/api-keys"},{match:r=>/rate limit|429/.test(r.message),errorClass:$s,message:"NVIDIA NIM rate limit exceeded"},{match:r=>/404|model_not_found/.test(r.message),errorClass:Oo,message:()=>`NVIDIA NIM model '${this.modelName}' not available. Browse the catalog at https://build.nvidia.com/models`},{match:r=>/quota|403/.test(r.message),errorClass:ot,message:"NVIDIA NIM quota exceeded for your account"},..._c];return ha(e,t,this.providerName,this.modelName)}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:gee(),baseURL:this.config.baseURL}}}}}),$Dt,T8r=b({"src/lib/providers/nvidiaNim/constants.ts"(){"use strict";$Dt="https://integrate.api.nvidia.com/v1"}}),UDt={};ee(UDt,{NVIDIA_NIM_DEFAULT_BASE_URL:()=>$Dt,NvidiaNimProvider:()=>FDt,isNimFieldRejection:()=>mee,stripFieldFromJsonBody:()=>pee});var w8r=b({"src/lib/providers/nvidiaNim/index.ts"(){"use strict";v8r(),T8r()}}),BDt={};ee(BDt,{LMStudioProvider:()=>GDt});var zDt,yee,vee,qDt,GDt,E8r=b({"src/lib/providers/lmStudio.ts"(){"use strict";ut(),qi(),z(),Ut(),kl(),YQ(),zDt="http://localhost:1234/v1",yee="lm-studio",vee="local-model",qDt=()=>process.env.LM_STUDIO_BASE_URL||zDt,GDt=class extends Lc{constructor(e,t,r,n){const o=n?.apiKey??process.env.LM_STUDIO_API_KEY??yee,s=n?.baseURL??qDt();super("lm-studio",e,t,{baseURL:s,apiKey:o}),p.debug("LM Studio Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:No(this.config.baseURL)})}getProviderName(){return"lm-studio"}getDefaultModel(){return process.env.LM_STUDIO_MODEL||""}getFallbackModelName(){return vee}formatProviderError(e){const t=[JQ(e,()=>`LM Studio server not reachable at ${No(this.config.baseURL)}. Open the LM Studio app, load a model, and click "Start Server".`),{match:r=>/model_not_found|404/.test(r.message),errorClass:Oo,message:()=>`LM Studio model '${this.modelName}' is not loaded. Load it in the LM Studio app first.`},..._c];return ha(e,t,this.providerName,this.modelName)}async validateConfiguration(){return this.probeModelsEndpoint(this.config.apiKey&&this.config.apiKey!==yee?{Authorization:`Bearer ${this.config.apiKey}`}:{})}getConfiguration(){return{provider:this.providerName,model:this.modelName||this.resolvedModel||vee,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}}}}),jDt={};ee(jDt,{LlamaCppProvider:()=>KDt});var HDt,VDt,WDt,KDt,S8r=b({"src/lib/providers/llamaCpp.ts"(){"use strict";ut(),qi(),z(),Ut(),kl(),YQ(),HDt="http://localhost:8080/v1",VDt="llamacpp",WDt=()=>process.env.LLAMACPP_BASE_URL||HDt,KDt=class extends Lc{constructor(e,t,r,n){const o=n?.baseURL?.trim()||WDt(),s=n?.apiKey?.trim()||process.env.LLAMACPP_API_KEY||VDt;super("llamacpp",e,t,{baseURL:o,apiKey:s}),p.debug("llama.cpp Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:No(this.config.baseURL)})}async validateConfiguration(){return this.probeModelsEndpoint(this.getAuthHeaders())}getProviderName(){return"llamacpp"}getDefaultModel(){return process.env.LLAMACPP_MODEL||""}getFallbackModelName(){return"loaded-model"}getFallbackModels(){return["loaded-model"]}formatProviderError(e){const t=[JQ(e,()=>`llama.cpp server not reachable at ${No(this.config.baseURL)}. Start it with: ./llama-server -m model.gguf --port 8080`),{match:r=>/400/.test(r.message),errorClass:ot,message:"llama.cpp rejected the request. Common cause: model doesn't support tools (start llama-server with --jinja for tool support)."},..._c];return ha(e,t,this.providerName,this.modelName)}}}}),JDt={};ee(JDt,{CohereProvider:()=>ZDt});var YDt,XDt,Tee,ZDt,b8r=b({"src/lib/providers/cohere.ts"(){"use strict";ut(),qi(),z(),Ut(),On(),ts(),pa(),vp(),kl(),YDt="https://api.cohere.com/compatibility/v1",XDt=()=>fa(NCr()),Tee=()=>_i("COHERE_MODEL","command-r-plus-08-2024"),ZDt=class extends Lc{constructor(e,t,r,n){const o=n?.apiKey?.trim(),s=o&&o.length>0?o:XDt(),i=n?.baseURL?.trim()||process.env.COHERE_BASE_URL?.trim()||YDt;super("cohere",e,t,{baseURL:i,apiKey:s}),p.debug("Cohere Provider initialized",{modelName:this.modelName,providerName:this.providerName,baseURL:No(this.config.baseURL)})}getProviderName(){return"cohere"}getDefaultModel(){return Tee()}getFallbackModelName(){return"command-r-08-2024"}getFallbackModels(){return["command-a-03-2025","command-a-reasoning-08-2025","command-r-plus-08-2024","command-r-08-2024","command-r7b-12-2024"]}formatProviderError(e){const t=[{match:r=>/invalid api token|Authentication|401|invalid_api_token/.test(r.message),errorClass:Mr,message:"Invalid Cohere API key. Check COHERE_API_KEY. Get one at https://dashboard.cohere.com/api-keys"},{match:r=>/rate limit|429/.test(r.message),errorClass:$s,message:"Cohere rate limit exceeded. Back off and retry."},{match:r=>/model_not_found|404/.test(r.message),errorClass:Oo,message:()=>`Cohere model '${this.modelName}' not found. Use command-r, command-r-plus, or command-r7b-12-2024.`},{match:r=>/trial limit|trial_limit/.test(r.message),errorClass:ot,message:"Cohere trial usage limit exceeded. Upgrade at https://dashboard.cohere.com/billing."},..._c];return ha(e,t,this.providerName,this.modelName)}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Tee(),baseURL:this.config.baseURL}}getDefaultEmbeddingModel(){return"embed-english-v3.0"}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.embedMany([r],t);if(!n[0])throw new ot("Cohere /v2/embed returned no embeddings.","cohere");return n[0]}async embedMany(e,t){if(e.length===0)return[];const r=t??this.getDefaultEmbeddingModel(),o=`${Ca(this.config.baseURL.replace(/\/compatibility\/v\d+\/?$/,""))}/v2/embed`,s=96,i=[],a=Pt();for(let c=0;c<e.length;c+=s){const l=e.slice(c,c+s),u=da(3e4,this.providerName,"generate");try{const d=await a(o,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:r,texts:l,input_type:"search_document",embedding_types:["float"]}),...u?.controller.signal?{signal:u.controller.signal}:{}});if(!d.ok){const f=await d.text().catch(()=>"");throw this.formatProviderError(new Error(`Cohere /v2/embed failed: ${d.status} \u2014 ${f.slice(0,500)}`))}const m=await d.json(),h=m.embeddings?.float??(Array.isArray(m.embeddings)?m.embeddings:void 0);if(!h||h.length!==l.length)throw new ot(`Cohere /v2/embed returned ${h?.length??0} embeddings for ${l.length} inputs.`,"cohere");i.push(...h)}finally{u?.cleanup()}}return i}}}}),_8r=Ur({"node_modules/.pnpm/dotenv@17.3.1/node_modules/dotenv/package.json"(e,t){t.exports={name:"dotenv",version:"17.3.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}}}),C8r=Ur({"node_modules/.pnpm/dotenv@17.3.1/node_modules/dotenv/lib/main.js"(e,t){var r=(on(),Br(mu)),n=(hr(),Br(Um)),o=(Ri(),Br(cW)),s=(Dt(),Br(AS)),i=_8r(),a=i.version,c=["\u{1F510} encrypt with Dotenvx: https://dotenvx.com","\u{1F510} prevent committing .env to code: https://dotenvx.com/precommit","\u{1F510} prevent building .env in docker: https://dotenvx.com/prebuild","\u{1F916} agentic secret storage: https://dotenvx.com/as2","\u26A1\uFE0F secrets for agents: https://dotenvx.com/as2","\u{1F6E1}\uFE0F auth for agents: https://vestauth.com","\u{1F6E0}\uFE0F run anywhere with `dotenvx run -- yourcommand`","\u2699\uFE0F specify custom .env file path with { path: '/custom/path/.env' }","\u2699\uFE0F enable debug logging with { debug: true }","\u2699\uFE0F override existing env vars with { override: true }","\u2699\uFE0F suppress all logs with { quiet: true }","\u2699\uFE0F write to custom object with { processEnv: myObject }","\u2699\uFE0F load multiple .env files with { path: ['.env.local', '.env'] }"];function l(){return c[Math.floor(Math.random()*c.length)]}function u(M){return typeof M=="string"?!["false","0","no","off",""].includes(M.toLowerCase()):!!M}function d(){return process.stdout.isTTY}function m(M){return d()?`\x1B[2m${M}\x1B[0m`:M}var h=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function f(M){const F={};let N=M.toString();N=N.replace(/\r\n?/mg,`
|
|
1319
1319
|
`);let L;for(;(L=h.exec(N))!=null;){const q=L[1];let B=L[2]||"";B=B.trim();const H=B[0];B=B.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),H==='"'&&(B=B.replace(/\\n/g,`
|
|
1320
|
-
`),B=B.replace(/\\r/g,"\r")),F[q]=B}return F}function g(M){M=M||{};const F=C(M);M.path=F;const N=U.configDotenv(M);if(!N.parsed){const H=new Error(`MISSING_DATA: Cannot parse ${F} for an unknown reason`);throw H.code="MISSING_DATA",H}const L=E(M).split(","),q=L.length;let B;for(let H=0;H<q;H++)try{const G=L[H].trim(),X=_(N,G);B=U.decrypt(X.ciphertext,X.key);break}catch(G){if(H+1>=q)throw G}return U.parse(B)}function y(M){console.error(`[dotenv@${a}][WARN] ${M}`)}function v(M){console.log(`[dotenv@${a}][DEBUG] ${M}`)}function w(M){console.log(`[dotenv@${a}] ${M}`)}function E(M){return M&&M.DOTENV_KEY&&M.DOTENV_KEY.length>0?M.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function _(M,F){let N;try{N=new URL(F)}catch(G){if(G.code==="ERR_INVALID_URL"){const X=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw X.code="INVALID_DOTENV_KEY",X}throw G}const L=N.password;if(!L){const G=new Error("INVALID_DOTENV_KEY: Missing key part");throw G.code="INVALID_DOTENV_KEY",G}const q=N.searchParams.get("environment");if(!q){const G=new Error("INVALID_DOTENV_KEY: Missing environment part");throw G.code="INVALID_DOTENV_KEY",G}const B=`DOTENV_VAULT_${q.toUpperCase()}`,H=M.parsed[B];if(!H){const G=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${B} in your .env.vault file.`);throw G.code="NOT_FOUND_DOTENV_ENVIRONMENT",G}return{ciphertext:H,key:L}}function C(M){let F=null;if(M&&M.path&&M.path.length>0)if(Array.isArray(M.path))for(const N of M.path)r.existsSync(N)&&(F=N.endsWith(".vault")?N:`${N}.vault`);else F=M.path.endsWith(".vault")?M.path:`${M.path}.vault`;else F=n.resolve(process.cwd(),".env.vault");return r.existsSync(F)?F:null}function A(M){return M[0]==="~"?n.join(o.homedir(),M.slice(1)):M}function k(M){const F=u(process.env.DOTENV_CONFIG_DEBUG||M&&M.debug),N=u(process.env.DOTENV_CONFIG_QUIET||M&&M.quiet);(F||!N)&&w("Loading env from encrypted .env.vault");const L=U._parseVault(M);let q=process.env;return M&&M.processEnv!=null&&(q=M.processEnv),U.populate(q,L,M),{parsed:L}}function R(M){const F=n.resolve(process.cwd(),".env");let N="utf8",L=process.env;M&&M.processEnv!=null&&(L=M.processEnv);let q=u(L.DOTENV_CONFIG_DEBUG||M&&M.debug),B=u(L.DOTENV_CONFIG_QUIET||M&&M.quiet);M&&M.encoding?N=M.encoding:q&&v("No encoding is specified. UTF-8 is used by default");let H=[F];if(M&&M.path)if(!Array.isArray(M.path))H=[A(M.path)];else{H=[];for(const Q of M.path)H.push(A(Q))}let G;const X={};for(const Q of H)try{const Ie=U.parse(r.readFileSync(Q,{encoding:N}));U.populate(X,Ie,M)}catch(Ie){q&&v(`Failed to load ${Q} ${Ie.message}`),G=Ie}const ce=U.populate(L,X,M);if(q=u(L.DOTENV_CONFIG_DEBUG||q),B=u(L.DOTENV_CONFIG_QUIET||B),q||!B){const Q=Object.keys(ce).length,Ie=[];for(const Ee of H)try{const le=n.relative(process.cwd(),Ee);Ie.push(le)}catch(le){q&&v(`Failed to load ${Ee} ${le.message}`),G=le}w(`injecting env (${Q}) from ${Ie.join(",")} ${m(`-- tip: ${l()}`)}`)}return G?{parsed:X,error:G}:{parsed:X}}function I(M){if(E(M).length===0)return U.configDotenv(M);const F=C(M);return F?U._configVault(M):(y(`You set DOTENV_KEY but you are missing a .env.vault file at ${F}. Did you forget to build it?`),U.configDotenv(M))}function P(M,F){const N=Buffer.from(F.slice(-64),"hex");let L=Buffer.from(M,"base64");const q=L.subarray(0,12),B=L.subarray(-16);L=L.subarray(12,-16);try{const H=s.createDecipheriv("aes-256-gcm",N,q);return H.setAuthTag(B),`${H.update(L)}${H.final()}`}catch(H){const G=H instanceof RangeError,X=H.message==="Invalid key length",ce=H.message==="Unsupported state or unable to authenticate data";if(G||X){const Q=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw Q.code="INVALID_DOTENV_KEY",Q}else if(ce){const Q=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw Q.code="DECRYPTION_FAILED",Q}else throw H}}function O(M,F,N={}){const L=!!(N&&N.debug),q=!!(N&&N.override),B={};if(typeof F!="object"){const H=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw H.code="OBJECT_REQUIRED",H}for(const H of Object.keys(F))Object.prototype.hasOwnProperty.call(M,H)?(q===!0&&(M[H]=F[H],B[H]=F[H]),L&&v(q===!0?`"${H}" is already defined and WAS overwritten`:`"${H}" is already defined and was NOT overwritten`)):(M[H]=F[H],B[H]=F[H]);return B}var U={configDotenv:R,_configVault:k,_parseVault:g,config:I,decrypt:P,parse:f,populate:O};t.exports.configDotenv=U.configDotenv,t.exports._configVault=U._configVault,t.exports._parseVault=U._parseVault,t.exports.config=U.config,t.exports.decrypt=U.decrypt,t.exports.parse=U.parse,t.exports.populate=U.populate,t.exports=U}});async function A8r(){try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";const{config:e}=await Promise.resolve().then(()=>sl(C8r(),1)),t=process.env.DOTENV_CONFIG_PATH;e(t?{quiet:!0,path:t}:{quiet:!0})}catch{}}var k8r=b({"src/lib/utils/dotenvBootstrap.ts"(){"use strict"}});function VN(e,t){const{availableInputTokens:r,breakdown:n}=e,o=t===void 0?1:Math.max(0,Math.min(1,t/WN)),s=QDt*o;if(!n)return Math.max(0,Math.floor(r*s));const i=n.systemPrompt+n.currentPrompt+n.toolDefinitions+n.fileAttachments;return Math.max(0,Math.floor((r-i)*s))}function Zi(e){const{traceId:t,parentSpanId:r}=Hh(),n=Ce.createSpan("context.compaction","context.budgetCheck",{"context.operation":"budgetCheck"},r,t),o=Date.now();try{const{provider:s,model:i,maxTokens:a,systemPrompt:c,conversationMessages:l,currentPrompt:u,toolDefinitions:d,fileAttachments:m,compactionThreshold:h=WN}=e,f=Pc(s,i,a),g=c?Gt(c,s)+Oc:0,y=l?.length?$o(l,s):0,v=u?Gt(u,s)+Oc:0,w=d?.length?d.reduce((P,O)=>{try{const U=JSON.stringify(O);return P+Gt(U,s)}catch{return P+eNt}},0):0,E=m?.length?m.reduce((P,O)=>P+Gt(O.content,s),0):0,_=g+y+v+w+E,C=f>0?_/f:1,A=_<=f,k=C>=h,R={withinBudget:A,estimatedInputTokens:_,availableInputTokens:f,usageRatio:C,shouldCompact:k,breakdown:{systemPrompt:g,conversationHistory:y,currentPrompt:v,toolDefinitions:w,fileAttachments:E}};n.durationMs=Date.now()-o;const I=Ce.endSpan(Ce.updateAttributes(n,{"context.budgetUsage":C,"context.triggered":k,"context.estimatedTokens":_,"context.availableTokens":f,"context.compactionThreshold":h}),1);return rt().recordSpan(I),R}catch(s){n.durationMs=Date.now()-o;const i=Ce.endSpan(n,2);throw i.statusMessage=s instanceof Error?s.message:String(s),rt().recordSpan(i),s}}var WN,QDt,eNt,tNt=b({"src/lib/context/budgetChecker.ts"(){"use strict";bl(),Ko(),To(),Vh(),WN=.8,QDt=.95,eNt=200}});function x8r(e,t){const r=t?.protectTokens??rNt,n=t?.minimumSavings??nNt,o=new Set(t?.protectedTools??["skill"]),s=t?.provider,i=[...e];let a=0,c=0;for(let u=i.length-1;u>=0;u--){const d=i[u];if(d.role!=="tool_result"||d.tool&&o.has(d.tool))continue;const m=Gt(d.content,s);if(a<r){a+=m;continue}d.content!==KN&&(c+=m-Gt(KN,s),i[u]={...d,content:KN,metadata:{...d.metadata,truncated:!0}})}const l=c>=n;return{pruned:l,messages:l?i:e,tokensSaved:l?c:0}}var KN,rNt,nNt,I8r=b({"src/lib/context/stages/toolOutputPruner.ts"(){"use strict";Ko(),KN="[Tool result cleared]",rNt=4e4,nNt=2e4}});function R8r(e){const t=new Map;for(let c=0;c<e.length;c++){const l=e[c];if(l.role!=="tool_result"&&l.role!=="assistant")continue;const u=l.content.match(oNt);if(u){const d=u[1],m=t.get(d)||[];m.push(c),t.set(d,m)}}const r=new Map;for(const[c,l]of t)l.length>1&&r.set(c,l);if(r.size===0)return{deduplicated:!1,messages:e,filesDeduped:0};const n=[...e];let o=0,s=0;for(const[c,l]of r){const u=l[l.length-1];for(const d of l){if(d===u)continue;const m=n[d];o+=m.content.length;const h=sNt(c);s+=h.length,n[d]={...m,content:h,metadata:{...m.metadata,truncated:!0}}}}const a=(o>0?(o-s)/o:0)>=iNt;return{deduplicated:a,messages:a?n:e,filesDeduped:a?r.size:0}}var oNt,sNt,iNt,P8r=b({"src/lib/context/stages/fileReadDeduplicator.ts"(){"use strict";oNt=/(?:read|reading|read_file|readFile|Read file|cat)\s+['"`]?([^\s'"`\n]+)/i,sNt=e=>`[File ${e} - refer to latest read below]`,iNt=.3}});function aNt(e){for(let t=1;t<e.length;t++)e[t].role===e[t-1].role&&e[t].role!=="system"&&p.warn(`[SlidingWindowTruncator] Role alternation broken at index ${t}: consecutive "${e[t].role}" messages`)}function M8r(e,t){if(!t?.targetTokens)return{truncated:!1,messages:e,messagesRemoved:0};const r=t.provider,n=t.targetTokens;if($o(e,r)<=n)return{truncated:!1,messages:e,messagesRemoved:0};const s=200,i=24+e.length*4,a=n-i;if(a<=0)return{truncated:!1,messages:e,messagesRemoved:0};const c=e.map(m=>Gt(m.content,r)),l=c.reduce((m,h)=>m+h,0),u=[...e];let d=0;for(let m=0;m<u.length;m++){const h=u[m];if(h.role==="system"||h.metadata?.isSummary||h.metadata?.isSkill)continue;const f=Math.floor(c[m]/l*a),g=Math.max(s,f);if(c[m]>g){const y=Ovt(h.content,g,r);y.truncated&&(d+=c[m]-Gt(y.text,r),u[m]={...h,content:y.text,metadata:{...h.metadata,truncated:!0}})}}if(d>0){const m=$o(u,r);return p.info("[Truncation] Small conversation content truncated",{messageCount:e.length,tokensSaved:d,targetTokens:n,finalTokens:m}),{truncated:m<=n,messages:u,messagesRemoved:0}}return{truncated:!1,messages:e,messagesRemoved:0}}function O8r(e,t){const r=new Map,n=[],o=[];for(let f=0;f<e.length;f++){const g=e[f];if(!g.metadata?.isSkill){o.push(g);continue}const y=e.slice(f+1).find(v=>!v.metadata?.isSkill);if(y){const v=r.get(y.id);v?v.push(g):r.set(y.id,[g])}else n.push(g)}if(o.length<=4)return M8r(e,t);let s;if(t?.currentTokens&&t?.targetTokens&&t.currentTokens>t.targetTokens){const f=(t.currentTokens-t.targetTokens)/t.currentTokens,g=t?.adaptiveBuffer??.15;s=Math.min(.9,Math.max(.1,f+g)),p.info("[Truncation] Adaptive fraction calculated",{currentTokens:t.currentTokens,targetTokens:t.targetTokens,overageRatio:Math.round(f*100),fraction:Math.round(s*100)})}else s=t?.fraction??.5;const i=o.slice(0,2),a=o.slice(2),c=(f,g)=>{const y=new Set([...i,...f].map(E=>E.id)),v=[];for(const[E,_]of r)y.has(E)||v.push(..._);const w=E=>{const _=r.get(E.id);return _?[..._,E]:[E]};return[...i.flatMap(w),g,...v,...f.flatMap(w),...n]},l=()=>{const f=Xe();return{id:`truncation-marker-${f}`,role:"user",content:cNt,isTruncationMarker:!0,truncationId:f}},u=t?.maxIterations??3;let d=s;for(let f=0;f<u;f++){const g=Math.floor(a.length*d),y=g-g%2;if(y<=0)break;const v=c(a.slice(y),l());if(aNt(v),t?.targetTokens){if($o(v,t.provider)<=t.targetTokens)return{truncated:!0,messages:v,messagesRemoved:y};d=Math.min(.95,d+.1);continue}return{truncated:!0,messages:v,messagesRemoved:y}}const m=Math.floor(a.length*.95),h=m-m%2;if(h>0){const f=c(a.slice(h),l());return aNt(f),{truncated:!0,messages:f,messagesRemoved:h}}return{truncated:!1,messages:e,messagesRemoved:0}}var cNt,D8r=b({"src/lib/context/stages/slidingWindowTruncator.ts"(){"use strict";Ko(),z(),Dt(),cNt="[Earlier conversation history was truncated to fit within context limits]"}});function lNt(e,t){if(!(e&&e.length>0||t&&t.length>0))return"";let n=`
|
|
1320
|
+
`),B=B.replace(/\\r/g,"\r")),F[q]=B}return F}function g(M){M=M||{};const F=C(M);M.path=F;const N=U.configDotenv(M);if(!N.parsed){const H=new Error(`MISSING_DATA: Cannot parse ${F} for an unknown reason`);throw H.code="MISSING_DATA",H}const L=E(M).split(","),q=L.length;let B;for(let H=0;H<q;H++)try{const G=L[H].trim(),X=_(N,G);B=U.decrypt(X.ciphertext,X.key);break}catch(G){if(H+1>=q)throw G}return U.parse(B)}function y(M){console.error(`[dotenv@${a}][WARN] ${M}`)}function v(M){console.log(`[dotenv@${a}][DEBUG] ${M}`)}function w(M){console.log(`[dotenv@${a}] ${M}`)}function E(M){return M&&M.DOTENV_KEY&&M.DOTENV_KEY.length>0?M.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function _(M,F){let N;try{N=new URL(F)}catch(G){if(G.code==="ERR_INVALID_URL"){const X=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw X.code="INVALID_DOTENV_KEY",X}throw G}const L=N.password;if(!L){const G=new Error("INVALID_DOTENV_KEY: Missing key part");throw G.code="INVALID_DOTENV_KEY",G}const q=N.searchParams.get("environment");if(!q){const G=new Error("INVALID_DOTENV_KEY: Missing environment part");throw G.code="INVALID_DOTENV_KEY",G}const B=`DOTENV_VAULT_${q.toUpperCase()}`,H=M.parsed[B];if(!H){const G=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${B} in your .env.vault file.`);throw G.code="NOT_FOUND_DOTENV_ENVIRONMENT",G}return{ciphertext:H,key:L}}function C(M){let F=null;if(M&&M.path&&M.path.length>0)if(Array.isArray(M.path))for(const N of M.path)r.existsSync(N)&&(F=N.endsWith(".vault")?N:`${N}.vault`);else F=M.path.endsWith(".vault")?M.path:`${M.path}.vault`;else F=n.resolve(process.cwd(),".env.vault");return r.existsSync(F)?F:null}function A(M){return M[0]==="~"?n.join(o.homedir(),M.slice(1)):M}function k(M){const F=u(process.env.DOTENV_CONFIG_DEBUG||M&&M.debug),N=u(process.env.DOTENV_CONFIG_QUIET||M&&M.quiet);(F||!N)&&w("Loading env from encrypted .env.vault");const L=U._parseVault(M);let q=process.env;return M&&M.processEnv!=null&&(q=M.processEnv),U.populate(q,L,M),{parsed:L}}function R(M){const F=n.resolve(process.cwd(),".env");let N="utf8",L=process.env;M&&M.processEnv!=null&&(L=M.processEnv);let q=u(L.DOTENV_CONFIG_DEBUG||M&&M.debug),B=u(L.DOTENV_CONFIG_QUIET||M&&M.quiet);M&&M.encoding?N=M.encoding:q&&v("No encoding is specified. UTF-8 is used by default");let H=[F];if(M&&M.path)if(!Array.isArray(M.path))H=[A(M.path)];else{H=[];for(const Q of M.path)H.push(A(Q))}let G;const X={};for(const Q of H)try{const Ae=U.parse(r.readFileSync(Q,{encoding:N}));U.populate(X,Ae,M)}catch(Ae){q&&v(`Failed to load ${Q} ${Ae.message}`),G=Ae}const ce=U.populate(L,X,M);if(q=u(L.DOTENV_CONFIG_DEBUG||q),B=u(L.DOTENV_CONFIG_QUIET||B),q||!B){const Q=Object.keys(ce).length,Ae=[];for(const Ee of H)try{const le=n.relative(process.cwd(),Ee);Ae.push(le)}catch(le){q&&v(`Failed to load ${Ee} ${le.message}`),G=le}w(`injecting env (${Q}) from ${Ae.join(",")} ${m(`-- tip: ${l()}`)}`)}return G?{parsed:X,error:G}:{parsed:X}}function I(M){if(E(M).length===0)return U.configDotenv(M);const F=C(M);return F?U._configVault(M):(y(`You set DOTENV_KEY but you are missing a .env.vault file at ${F}. Did you forget to build it?`),U.configDotenv(M))}function P(M,F){const N=Buffer.from(F.slice(-64),"hex");let L=Buffer.from(M,"base64");const q=L.subarray(0,12),B=L.subarray(-16);L=L.subarray(12,-16);try{const H=s.createDecipheriv("aes-256-gcm",N,q);return H.setAuthTag(B),`${H.update(L)}${H.final()}`}catch(H){const G=H instanceof RangeError,X=H.message==="Invalid key length",ce=H.message==="Unsupported state or unable to authenticate data";if(G||X){const Q=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw Q.code="INVALID_DOTENV_KEY",Q}else if(ce){const Q=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw Q.code="DECRYPTION_FAILED",Q}else throw H}}function O(M,F,N={}){const L=!!(N&&N.debug),q=!!(N&&N.override),B={};if(typeof F!="object"){const H=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw H.code="OBJECT_REQUIRED",H}for(const H of Object.keys(F))Object.prototype.hasOwnProperty.call(M,H)?(q===!0&&(M[H]=F[H],B[H]=F[H]),L&&v(q===!0?`"${H}" is already defined and WAS overwritten`:`"${H}" is already defined and was NOT overwritten`)):(M[H]=F[H],B[H]=F[H]);return B}var U={configDotenv:R,_configVault:k,_parseVault:g,config:I,decrypt:P,parse:f,populate:O};t.exports.configDotenv=U.configDotenv,t.exports._configVault=U._configVault,t.exports._parseVault=U._parseVault,t.exports.config=U.config,t.exports.decrypt=U.decrypt,t.exports.parse=U.parse,t.exports.populate=U.populate,t.exports=U}});async function A8r(){try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";const{config:e}=await Promise.resolve().then(()=>sl(C8r(),1)),t=process.env.DOTENV_CONFIG_PATH;e(t?{quiet:!0,path:t}:{quiet:!0})}catch{}}var k8r=b({"src/lib/utils/dotenvBootstrap.ts"(){"use strict"}});function VN(e,t){const{availableInputTokens:r,breakdown:n}=e,o=t===void 0?1:Math.max(0,Math.min(1,t/WN)),s=QDt*o;if(!n)return Math.max(0,Math.floor(r*s));const i=n.systemPrompt+n.currentPrompt+n.toolDefinitions+n.fileAttachments;return Math.max(0,Math.floor((r-i)*s))}function Zi(e){const{traceId:t,parentSpanId:r}=Hh(),n=Ce.createSpan("context.compaction","context.budgetCheck",{"context.operation":"budgetCheck"},r,t),o=Date.now();try{const{provider:s,model:i,maxTokens:a,systemPrompt:c,conversationMessages:l,currentPrompt:u,toolDefinitions:d,fileAttachments:m,compactionThreshold:h=WN}=e,f=Pc(s,i,a),g=c?Gt(c,s)+Oc:0,y=l?.length?$o(l,s):0,v=u?Gt(u,s)+Oc:0,w=d?.length?d.reduce((P,O)=>{try{const U=JSON.stringify(O);return P+Gt(U,s)}catch{return P+eNt}},0):0,E=m?.length?m.reduce((P,O)=>P+Gt(O.content,s),0):0,_=g+y+v+w+E,C=f>0?_/f:1,A=_<=f,k=C>=h,R={withinBudget:A,estimatedInputTokens:_,availableInputTokens:f,usageRatio:C,shouldCompact:k,breakdown:{systemPrompt:g,conversationHistory:y,currentPrompt:v,toolDefinitions:w,fileAttachments:E}};n.durationMs=Date.now()-o;const I=Ce.endSpan(Ce.updateAttributes(n,{"context.budgetUsage":C,"context.triggered":k,"context.estimatedTokens":_,"context.availableTokens":f,"context.compactionThreshold":h}),1);return rt().recordSpan(I),R}catch(s){n.durationMs=Date.now()-o;const i=Ce.endSpan(n,2);throw i.statusMessage=s instanceof Error?s.message:String(s),rt().recordSpan(i),s}}var WN,QDt,eNt,tNt=b({"src/lib/context/budgetChecker.ts"(){"use strict";bl(),Ko(),To(),Vh(),WN=.8,QDt=.95,eNt=200}});function x8r(e,t){const r=t?.protectTokens??rNt,n=t?.minimumSavings??nNt,o=new Set(t?.protectedTools??["skill"]),s=t?.provider,i=[...e];let a=0,c=0;for(let u=i.length-1;u>=0;u--){const d=i[u];if(d.role!=="tool_result"||d.tool&&o.has(d.tool))continue;const m=Gt(d.content,s);if(a<r){a+=m;continue}d.content!==KN&&(c+=m-Gt(KN,s),i[u]={...d,content:KN,metadata:{...d.metadata,truncated:!0}})}const l=c>=n;return{pruned:l,messages:l?i:e,tokensSaved:l?c:0}}var KN,rNt,nNt,I8r=b({"src/lib/context/stages/toolOutputPruner.ts"(){"use strict";Ko(),KN="[Tool result cleared]",rNt=4e4,nNt=2e4}});function R8r(e){const t=new Map;for(let c=0;c<e.length;c++){const l=e[c];if(l.role!=="tool_result"&&l.role!=="assistant")continue;const u=l.content.match(oNt);if(u){const d=u[1],m=t.get(d)||[];m.push(c),t.set(d,m)}}const r=new Map;for(const[c,l]of t)l.length>1&&r.set(c,l);if(r.size===0)return{deduplicated:!1,messages:e,filesDeduped:0};const n=[...e];let o=0,s=0;for(const[c,l]of r){const u=l[l.length-1];for(const d of l){if(d===u)continue;const m=n[d];o+=m.content.length;const h=sNt(c);s+=h.length,n[d]={...m,content:h,metadata:{...m.metadata,truncated:!0}}}}const a=(o>0?(o-s)/o:0)>=iNt;return{deduplicated:a,messages:a?n:e,filesDeduped:a?r.size:0}}var oNt,sNt,iNt,P8r=b({"src/lib/context/stages/fileReadDeduplicator.ts"(){"use strict";oNt=/(?:read|reading|read_file|readFile|Read file|cat)\s+['"`]?([^\s'"`\n]+)/i,sNt=e=>`[File ${e} - refer to latest read below]`,iNt=.3}});function aNt(e){for(let t=1;t<e.length;t++)e[t].role===e[t-1].role&&e[t].role!=="system"&&p.warn(`[SlidingWindowTruncator] Role alternation broken at index ${t}: consecutive "${e[t].role}" messages`)}function M8r(e,t){if(!t?.targetTokens)return{truncated:!1,messages:e,messagesRemoved:0};const r=t.provider,n=t.targetTokens;if($o(e,r)<=n)return{truncated:!1,messages:e,messagesRemoved:0};const s=200,i=24+e.length*4,a=n-i;if(a<=0)return{truncated:!1,messages:e,messagesRemoved:0};const c=e.map(m=>Gt(m.content,r)),l=c.reduce((m,h)=>m+h,0),u=[...e];let d=0;for(let m=0;m<u.length;m++){const h=u[m];if(h.role==="system"||h.metadata?.isSummary||h.metadata?.isSkill)continue;const f=Math.floor(c[m]/l*a),g=Math.max(s,f);if(c[m]>g){const y=Ovt(h.content,g,r);y.truncated&&(d+=c[m]-Gt(y.text,r),u[m]={...h,content:y.text,metadata:{...h.metadata,truncated:!0}})}}if(d>0){const m=$o(u,r);return p.info("[Truncation] Small conversation content truncated",{messageCount:e.length,tokensSaved:d,targetTokens:n,finalTokens:m}),{truncated:m<=n,messages:u,messagesRemoved:0}}return{truncated:!1,messages:e,messagesRemoved:0}}function O8r(e,t){const r=new Map,n=[],o=[];for(let f=0;f<e.length;f++){const g=e[f];if(!g.metadata?.isSkill){o.push(g);continue}const y=e.slice(f+1).find(v=>!v.metadata?.isSkill);if(y){const v=r.get(y.id);v?v.push(g):r.set(y.id,[g])}else n.push(g)}if(o.length<=4)return M8r(e,t);let s;if(t?.currentTokens&&t?.targetTokens&&t.currentTokens>t.targetTokens){const f=(t.currentTokens-t.targetTokens)/t.currentTokens,g=t?.adaptiveBuffer??.15;s=Math.min(.9,Math.max(.1,f+g)),p.info("[Truncation] Adaptive fraction calculated",{currentTokens:t.currentTokens,targetTokens:t.targetTokens,overageRatio:Math.round(f*100),fraction:Math.round(s*100)})}else s=t?.fraction??.5;const i=o.slice(0,2),a=o.slice(2),c=(f,g)=>{const y=new Set([...i,...f].map(E=>E.id)),v=[];for(const[E,_]of r)y.has(E)||v.push(..._);const w=E=>{const _=r.get(E.id);return _?[..._,E]:[E]};return[...i.flatMap(w),g,...v,...f.flatMap(w),...n]},l=()=>{const f=Xe();return{id:`truncation-marker-${f}`,role:"user",content:cNt,isTruncationMarker:!0,truncationId:f}},u=t?.maxIterations??3;let d=s;for(let f=0;f<u;f++){const g=Math.floor(a.length*d),y=g-g%2;if(y<=0)break;const v=c(a.slice(y),l());if(aNt(v),t?.targetTokens){if($o(v,t.provider)<=t.targetTokens)return{truncated:!0,messages:v,messagesRemoved:y};d=Math.min(.95,d+.1);continue}return{truncated:!0,messages:v,messagesRemoved:y}}const m=Math.floor(a.length*.95),h=m-m%2;if(h>0){const f=c(a.slice(h),l());return aNt(f),{truncated:!0,messages:f,messagesRemoved:h}}return{truncated:!1,messages:e,messagesRemoved:0}}var cNt,D8r=b({"src/lib/context/stages/slidingWindowTruncator.ts"(){"use strict";Ko(),z(),Dt(),cNt="[Earlier conversation history was truncated to fit within context limits]"}});function lNt(e,t){if(!(e&&e.length>0||t&&t.length>0))return"";let n=`
|
|
1321
1321
|
|
|
1322
1322
|
File Context:
|
|
1323
1323
|
`;if(e&&e.length>0){n+=`Files Read:
|
|
@@ -1485,18 +1485,18 @@ ${e.instructions}`,timestamp:new Date().toISOString(),metadata:{isSkill:!0,skill
|
|
|
1485
1485
|
`;for(let g=1;g<=s.linesAfter&&!(u+g>=c.length);g++){const y=t(o.buffer,a[u+g],c[u+g],o.position-(a[u]-a[u+g]),h);d+=e.repeat(" ",s.indent)+r((o.line+g+1).toString(),m)+" | "+y.str+`
|
|
1486
1486
|
`}return d.replace(/\n$/,"")}return yne=n,yne}function ta(){if(w6t)return vne;w6t=1;const e=ek(),t=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],r=["scalar","sequence","mapping"];function n(s){const i={};return s!==null&&Object.keys(s).forEach(function(a){s[a].forEach(function(c){i[String(c)]=a})}),i}function o(s,i){if(i=i||{},Object.keys(i).forEach(function(a){if(t.indexOf(a)===-1)throw new e('Unknown option "'+a+'" is met in definition of "'+s+'" YAML type.')}),this.options=i,this.tag=s,this.kind=i.kind||null,this.resolve=i.resolve||function(){return!0},this.construct=i.construct||function(a){return a},this.instanceOf=i.instanceOf||null,this.predicate=i.predicate||null,this.represent=i.represent||null,this.representName=i.representName||null,this.defaultStyle=i.defaultStyle||null,this.multi=i.multi||!1,this.styleAliases=n(i.styleAliases||null),r.indexOf(this.kind)===-1)throw new e('Unknown kind "'+this.kind+'" is specified for "'+s+'" YAML type.')}return vne=o,vne}function e6t(){if(E6t)return Tne;E6t=1;const e=ek(),t=ta();function r(s,i){const a=[];return s[i].forEach(function(c){let l=a.length;a.forEach(function(u,d){u.tag===c.tag&&u.kind===c.kind&&u.multi===c.multi&&(l=d)}),a[l]=c}),a}function n(){const s={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function i(a){a.multi?(s.multi[a.kind].push(a),s.multi.fallback.push(a)):s[a.kind][a.tag]=s.fallback[a.tag]=a}for(let a=0,c=arguments.length;a<c;a+=1)arguments[a].forEach(i);return s}function o(s){return this.extend(s)}return o.prototype.extend=function(i){let a=[],c=[];if(i instanceof t)c.push(i);else if(Array.isArray(i))c=c.concat(i);else if(i&&(Array.isArray(i.implicit)||Array.isArray(i.explicit)))i.implicit&&(a=a.concat(i.implicit)),i.explicit&&(c=c.concat(i.explicit));else throw new e("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");a.forEach(function(u){if(!(u instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(u.loadKind&&u.loadKind!=="scalar")throw new e("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(u.multi)throw new e("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),c.forEach(function(u){if(!(u instanceof t))throw new e("Specified list of YAML types (or a single Type object) contains a non-Type object.")});const l=Object.create(o.prototype);return l.implicit=(this.implicit||[]).concat(a),l.explicit=(this.explicit||[]).concat(c),l.compiledImplicit=r(l,"implicit"),l.compiledExplicit=r(l,"explicit"),l.compiledTypeMap=n(l.compiledImplicit,l.compiledExplicit),l},Tne=o,Tne}function t6t(){if(S6t)return wne;S6t=1;const e=ta();return wne=new e("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),wne}function r6t(){if(b6t)return Ene;b6t=1;const e=ta();return Ene=new e("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Ene}function n6t(){if(_6t)return Sne;_6t=1;const e=ta();return Sne=new e("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Sne}function o6t(){if(C6t)return bne;C6t=1;const e=e6t();return bne=new e({explicit:[t6t(),r6t(),n6t()]}),bne}function s6t(){if(A6t)return _ne;A6t=1;const e=ta();function t(o){if(o===null)return!0;const s=o.length;return s===1&&o==="~"||s===4&&(o==="null"||o==="Null"||o==="NULL")}function r(){return null}function n(o){return o===null}return _ne=new e("tag:yaml.org,2002:null",{kind:"scalar",resolve:t,construct:r,predicate:n,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"}),_ne}function i6t(){if(k6t)return Cne;k6t=1;const e=ta();function t(o){if(o===null)return!1;const s=o.length;return s===4&&(o==="true"||o==="True"||o==="TRUE")||s===5&&(o==="false"||o==="False"||o==="FALSE")}function r(o){return o==="true"||o==="True"||o==="TRUE"}function n(o){return Object.prototype.toString.call(o)==="[object Boolean]"}return Cne=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:t,construct:r,predicate:n,represent:{lowercase:function(o){return o?"true":"false"},uppercase:function(o){return o?"TRUE":"FALSE"},camelcase:function(o){return o?"True":"False"}},defaultStyle:"lowercase"}),Cne}function a6t(){if(x6t)return Ane;x6t=1;const e=QA(),t=ta();function r(l){return l>=48&&l<=57||l>=65&&l<=70||l>=97&&l<=102}function n(l){return l>=48&&l<=55}function o(l){return l>=48&&l<=57}function s(l){if(l===null)return!1;const u=l.length;let d=0,m=!1;if(!u)return!1;let h=l[d];if((h==="-"||h==="+")&&(h=l[++d]),h==="0"){if(d+1===u)return!0;if(h=l[++d],h==="b"){for(d++;d<u;d++){if(h=l[d],h!=="0"&&h!=="1")return!1;m=!0}return m&&isFinite(i(l))}if(h==="x"){for(d++;d<u;d++){if(!r(l.charCodeAt(d)))return!1;m=!0}return m&&isFinite(i(l))}if(h==="o"){for(d++;d<u;d++){if(!n(l.charCodeAt(d)))return!1;m=!0}return m&&isFinite(i(l))}}for(;d<u;d++){if(!o(l.charCodeAt(d)))return!1;m=!0}return m?isFinite(i(l)):!1}function i(l){let u=l,d=1,m=u[0];if((m==="-"||m==="+")&&(m==="-"&&(d=-1),u=u.slice(1),m=u[0]),u==="0")return 0;if(m==="0"){if(u[1]==="b")return d*parseInt(u.slice(2),2);if(u[1]==="x")return d*parseInt(u.slice(2),16);if(u[1]==="o")return d*parseInt(u.slice(2),8)}return d*parseInt(u,10)}function a(l){return i(l)}function c(l){return Object.prototype.toString.call(l)==="[object Number]"&&l%1===0&&!e.isNegativeZero(l)}return Ane=new t("tag:yaml.org,2002:int",{kind:"scalar",resolve:s,construct:a,predicate:c,represent:{binary:function(l){return l>=0?"0b"+l.toString(2):"-0b"+l.toString(2).slice(1)},octal:function(l){return l>=0?"0o"+l.toString(8):"-0o"+l.toString(8).slice(1)},decimal:function(l){return l.toString(10)},hexadecimal:function(l){return l>=0?"0x"+l.toString(16).toUpperCase():"-0x"+l.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),Ane}function c6t(){if(I6t)return kne;I6t=1;const e=QA(),t=ta(),r=new RegExp("^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"),n=new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function o(l){return l===null||!r.test(l)?!1:isFinite(parseFloat(l,10))?!0:n.test(l)}function s(l){let u=l.toLowerCase();const d=u[0]==="-"?-1:1;return"+-".indexOf(u[0])>=0&&(u=u.slice(1)),u===".inf"?d===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:u===".nan"?NaN:d*parseFloat(u,10)}const i=/^[-+]?[0-9]+e/;function a(l,u){if(isNaN(l))switch(u){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===l)switch(u){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===l)switch(u){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(e.isNegativeZero(l))return"-0.0";const d=l.toString(10);return i.test(d)?d.replace("e",".e"):d}function c(l){return Object.prototype.toString.call(l)==="[object Number]"&&(l%1!==0||e.isNegativeZero(l))}return kne=new t("tag:yaml.org,2002:float",{kind:"scalar",resolve:o,construct:s,predicate:c,represent:a,defaultStyle:"lowercase"}),kne}function l6t(){return R6t||(R6t=1,xne=o6t().extend({implicit:[s6t(),i6t(),a6t(),c6t()]})),xne}function u6t(){return P6t||(P6t=1,Ine=l6t()),Ine}function d6t(){if(M6t)return Rne;M6t=1;const e=ta(),t=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),r=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function n(i){return i===null?!1:t.exec(i)!==null||r.exec(i)!==null}function o(i){let a=0,c=null,l=t.exec(i);if(l===null&&(l=r.exec(i)),l===null)throw new Error("Date resolve error");const u=+l[1],d=+l[2]-1,m=+l[3];if(!l[4])return new Date(Date.UTC(u,d,m));const h=+l[4],f=+l[5],g=+l[6];if(l[7]){for(a=l[7].slice(0,3);a.length<3;)a+="0";a=+a}if(l[9]){const v=+l[10],w=+(l[11]||0);c=(v*60+w)*6e4,l[9]==="-"&&(c=-c)}const y=new Date(Date.UTC(u,d,m,h,f,g,a));return c&&y.setTime(y.getTime()-c),y}function s(i){return i.toISOString()}return Rne=new e("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:n,construct:o,instanceOf:Date,represent:s}),Rne}function m6t(){if(O6t)return Pne;O6t=1;const e=ta();function t(r){return r==="<<"||r===null}return Pne=new e("tag:yaml.org,2002:merge",{kind:"scalar",resolve:t}),Pne}function p6t(){if(D6t)return Mne;D6t=1;const e=ta(),t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
1487
1487
|
\r`;function r(i){if(i===null)return!1;let a=0;const c=i.length,l=t;for(let u=0;u<c;u++){const d=l.indexOf(i.charAt(u));if(!(d>64)){if(d<0)return!1;a+=6}}return a%8===0}function n(i){const a=i.replace(/[\r\n=]/g,""),c=a.length,l=t;let u=0;const d=[];for(let h=0;h<c;h++)h%4===0&&h&&(d.push(u>>16&255),d.push(u>>8&255),d.push(u&255)),u=u<<6|l.indexOf(a.charAt(h));const m=c%4*6;return m===0?(d.push(u>>16&255),d.push(u>>8&255),d.push(u&255)):m===18?(d.push(u>>10&255),d.push(u>>2&255)):m===12&&d.push(u>>4&255),new Uint8Array(d)}function o(i){let a="",c=0;const l=i.length,u=t;for(let m=0;m<l;m++)m%3===0&&m&&(a+=u[c>>18&63],a+=u[c>>12&63],a+=u[c>>6&63],a+=u[c&63]),c=(c<<8)+i[m];const d=l%3;return d===0?(a+=u[c>>18&63],a+=u[c>>12&63],a+=u[c>>6&63],a+=u[c&63]):d===2?(a+=u[c>>10&63],a+=u[c>>4&63],a+=u[c<<2&63],a+=u[64]):d===1&&(a+=u[c>>2&63],a+=u[c<<4&63],a+=u[64],a+=u[64]),a}function s(i){return Object.prototype.toString.call(i)==="[object Uint8Array]"}return Mne=new e("tag:yaml.org,2002:binary",{kind:"scalar",resolve:r,construct:n,predicate:s,represent:o}),Mne}function h6t(){if(N6t)return One;N6t=1;const e=ta(),t=Object.prototype.hasOwnProperty,r=Object.prototype.toString;function n(s){if(s===null)return!0;const i={},a=s;for(let c=0,l=a.length;c<l;c+=1){const u=a[c];let d=!1;if(r.call(u)!=="[object Object]")return!1;let m;for(m in u)if(t.call(u,m))if(!d)d=!0;else return!1;if(!d||t.call(i,m))return!1;Object.defineProperty(i,m,{value:!0})}return!0}function o(s){return s!==null?s:[]}return One=new e("tag:yaml.org,2002:omap",{kind:"sequence",resolve:n,construct:o}),One}function f6t(){if(L6t)return Dne;L6t=1;const e=ta(),t=Object.prototype.toString;function r(o){if(o===null)return!0;const s=o,i=new Array(s.length);for(let a=0,c=s.length;a<c;a+=1){const l=s[a];if(t.call(l)!=="[object Object]")return!1;const u=Object.keys(l);if(u.length!==1)return!1;i[a]=[u[0],l[u[0]]]}return!0}function n(o){if(o===null)return[];const s=o,i=new Array(s.length);for(let a=0,c=s.length;a<c;a+=1){const l=s[a],u=Object.keys(l);i[a]=[u[0],l[u[0]]]}return i}return Dne=new e("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:r,construct:n}),Dne}function g6t(){if(F6t)return Nne;F6t=1;const e=ta(),t=Object.prototype.hasOwnProperty;function r(o){if(o===null)return!0;const s=o;for(const i in s)if(t.call(s,i)&&s[i]!==null)return!1;return!0}function n(o){return o!==null?o:{}}return Nne=new e("tag:yaml.org,2002:set",{kind:"mapping",resolve:r,construct:n}),Nne}function fne(){return $6t||($6t=1,Lne=u6t().extend({implicit:[d6t(),m6t()],explicit:[p6t(),h6t(),f6t(),g6t()]})),Lne}function yWr(){if(U6t)return tk;U6t=1;const e=QA(),t=ek(),r=gWr(),n=fne(),o=Object.prototype.hasOwnProperty,s=1,i=2,a=3,c=4,l=1,u=2,d=3,m=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,h=/[\x85\u2028\u2029]/,f=/[,\[\]{}]/,g=/^(?:!|!!|![0-9A-Za-z-]+!)$/,y=/^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;function v(x){return Object.prototype.toString.call(x)}function w(x){return x===10||x===13}function E(x){return x===9||x===32}function _(x){return x===9||x===32||x===10||x===13}function C(x){return x===44||x===91||x===93||x===123||x===125}function A(x){if(x>=48&&x<=57)return x-48;const K=x|32;return K>=97&&K<=102?K-97+10:-1}function k(x){return x===120?2:x===117?4:x===85?8:0}function R(x){return x>=48&&x<=57?x-48:-1}function I(x){switch(x){case 48:return"\0";case 97:return"\x07";case 98:return"\b";case 116:return" ";case 9:return" ";case 110:return`
|
|
1488
|
-
`;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"\x85";case 95:return"\xA0";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function P(x){return x<=65535?String.fromCharCode(x):String.fromCharCode((x-65536>>10)+55296,(x-65536&1023)+56320)}function O(x,K,Se){K==="__proto__"?Object.defineProperty(x,K,{configurable:!0,enumerable:!0,writable:!0,value:Se}):x[K]=Se}const U=new Array(256),M=new Array(256);for(let x=0;x<256;x++)U[x]=I(x)?1:0,M[x]=I(x);function F(x,K){this.input=x,this.filename=K.filename||null,this.schema=K.schema||n,this.onWarning=K.onWarning||null,this.legacy=K.legacy||!1,this.json=K.json||!1,this.listener=K.listener||null,this.maxDepth=typeof K.maxDepth=="number"?K.maxDepth:100,this.maxTotalMergeKeys=typeof K.maxTotalMergeKeys=="number"?K.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=x.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function N(x,K){const Se={name:x.filename,buffer:x.input.slice(0,-1),position:x.position,line:x.line,column:x.position-x.lineStart};return Se.snippet=r(Se),new t(K,Se)}function L(x,K){throw N(x,K)}function q(x,K){x.onWarning&&x.onWarning.call(null,N(x,K))}function B(x,K,Se){const
|
|
1489
|
-
`,K-1))}function De(x,K,Se){let
|
|
1490
|
-
`,fe?1+de:de):
|
|
1488
|
+
`;case 118:return"\v";case 102:return"\f";case 114:return"\r";case 101:return"\x1B";case 32:return" ";case 34:return'"';case 47:return"/";case 92:return"\\";case 78:return"\x85";case 95:return"\xA0";case 76:return"\u2028";case 80:return"\u2029";default:return""}}function P(x){return x<=65535?String.fromCharCode(x):String.fromCharCode((x-65536>>10)+55296,(x-65536&1023)+56320)}function O(x,K,Se){K==="__proto__"?Object.defineProperty(x,K,{configurable:!0,enumerable:!0,writable:!0,value:Se}):x[K]=Se}const U=new Array(256),M=new Array(256);for(let x=0;x<256;x++)U[x]=I(x)?1:0,M[x]=I(x);function F(x,K){this.input=x,this.filename=K.filename||null,this.schema=K.schema||n,this.onWarning=K.onWarning||null,this.legacy=K.legacy||!1,this.json=K.json||!1,this.listener=K.listener||null,this.maxDepth=typeof K.maxDepth=="number"?K.maxDepth:100,this.maxTotalMergeKeys=typeof K.maxTotalMergeKeys=="number"?K.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=x.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.depth=0,this.totalMergeKeys=0,this.firstTabInLine=-1,this.documents=[],this.anchorMapTransactions=[]}function N(x,K){const Se={name:x.filename,buffer:x.input.slice(0,-1),position:x.position,line:x.line,column:x.position-x.lineStart};return Se.snippet=r(Se),new t(K,Se)}function L(x,K){throw N(x,K)}function q(x,K){x.onWarning&&x.onWarning.call(null,N(x,K))}function B(x,K,Se){const xe=x.anchorMapTransactions;if(xe.length!==0){const fe=xe[xe.length-1];o.call(fe,K)||(fe[K]={existed:o.call(x.anchorMap,K),value:x.anchorMap[K]})}x.anchorMap[K]=Se}function H(x){x.anchorMapTransactions.push(Object.create(null))}function G(x){const K=x.anchorMapTransactions.pop(),Se=x.anchorMapTransactions;if(Se.length===0)return;const xe=Se[Se.length-1],fe=Object.keys(K);for(let $=0,Y=fe.length;$<Y;$+=1){const de=fe[$];o.call(xe,de)||(xe[de]=K[de])}}function X(x){const K=x.anchorMapTransactions.pop(),Se=Object.keys(K);for(let xe=Se.length-1;xe>=0;xe-=1){const fe=K[Se[xe]];fe.existed?x.anchorMap[Se[xe]]=fe.value:delete x.anchorMap[Se[xe]]}}function ce(x){return{position:x.position,line:x.line,lineStart:x.lineStart,lineIndent:x.lineIndent,firstTabInLine:x.firstTabInLine,tag:x.tag,anchor:x.anchor,kind:x.kind,result:x.result}}function Q(x,K){x.position=K.position,x.line=K.line,x.lineStart=K.lineStart,x.lineIndent=K.lineIndent,x.firstTabInLine=K.firstTabInLine,x.tag=K.tag,x.anchor=K.anchor,x.kind=K.kind,x.result=K.result}const Ae={YAML:function(K,Se,xe){K.version!==null&&L(K,"duplication of %YAML directive"),xe.length!==1&&L(K,"YAML directive accepts exactly one argument");const fe=/^([0-9]+)\.([0-9]+)$/.exec(xe[0]);fe===null&&L(K,"ill-formed argument of the YAML directive");const $=parseInt(fe[1],10),Y=parseInt(fe[2],10);$!==1&&L(K,"unacceptable YAML version of the document"),K.version=xe[0],K.checkLineBreaks=Y<2,Y!==1&&Y!==2&&q(K,"unsupported YAML version of the document")},TAG:function(K,Se,xe){let fe;xe.length!==2&&L(K,"TAG directive accepts exactly two arguments");const $=xe[0];fe=xe[1],g.test($)||L(K,"ill-formed tag handle (first argument) of the TAG directive"),o.call(K.tagMap,$)&&L(K,'there is a previously declared suffix for "'+$+'" tag handle'),y.test(fe)||L(K,"ill-formed tag prefix (second argument) of the TAG directive");try{fe=decodeURIComponent(fe)}catch{L(K,"tag prefix is malformed: "+fe)}K.tagMap[$]=fe}};function Ee(x,K,Se,xe){if(K<Se){const fe=x.input.slice(K,Se);if(xe)for(let $=0,Y=fe.length;$<Y;$+=1){const de=fe.charCodeAt($);de===9||de>=32&&de<=1114111||L(x,"expected valid JSON character")}else m.test(fe)&&L(x,"the stream contains non-printable characters");x.result+=fe}}function le(x){x.totalMergeKeys++,x.maxTotalMergeKeys!==-1&&x.totalMergeKeys>x.maxTotalMergeKeys&&L(x,"merge keys exceeded maxTotalMergeKeys ("+x.maxTotalMergeKeys+")")}function ae(x,K,Se,xe){e.isObject(Se)||L(x,"cannot merge mappings; the provided source object is unacceptable"),le(x);const fe=Object.keys(Se);for(let $=0,Y=fe.length;$<Y;$+=1){const de=fe[$];le(x),o.call(K,de)||(O(K,de,Se[de]),xe[de]=!0)}}function Pe(x,K,Se,xe,fe,$,Y,de,ge){if(Array.isArray(fe)){fe=Array.prototype.slice.call(fe);for(let be=0,we=fe.length;be<we;be+=1)Array.isArray(fe[be])&&L(x,"nested arrays are not supported inside keys"),typeof fe=="object"&&v(fe[be])==="[object Object]"&&(fe[be]="[object Object]")}if(typeof fe=="object"&&v(fe)==="[object Object]"&&(fe="[object Object]"),fe=String(fe),K===null&&(K={}),xe==="tag:yaml.org,2002:merge")if(Array.isArray($)){$.length>100&&L(x,"abnormal merge sequence size");for(let be=0,we=$.length;be<we;be+=1)ae(x,K,$[be],Se)}else ae(x,K,$,Se);else!x.json&&!o.call(Se,fe)&&o.call(K,fe)&&(x.line=Y||x.line,x.lineStart=de||x.lineStart,x.position=ge||x.position,L(x,"duplicated mapping key")),O(K,fe,$),delete Se[fe];return K}function ke(x){const K=x.input.charCodeAt(x.position);K===10?x.position++:K===13?(x.position++,x.input.charCodeAt(x.position)===10&&x.position++):L(x,"a line break is expected"),x.line+=1,x.lineStart=x.position,x.firstTabInLine=-1}function Te(x,K,Se){let xe=0,fe=x.input.charCodeAt(x.position);for(;fe!==0;){for(;E(fe);)fe===9&&x.firstTabInLine===-1&&(x.firstTabInLine=x.position),fe=x.input.charCodeAt(++x.position);if(K&&fe===35)do fe=x.input.charCodeAt(++x.position);while(fe!==10&&fe!==13&&fe!==0);if(w(fe))for(ke(x),fe=x.input.charCodeAt(x.position),xe++,x.lineIndent=0;fe===32;)x.lineIndent++,fe=x.input.charCodeAt(++x.position);else break}return Se!==-1&&xe!==0&&x.lineIndent<Se&&q(x,"deficient indentation"),xe}function he(x){let K=x.position,Se=x.input.charCodeAt(K);return!!((Se===45||Se===46)&&Se===x.input.charCodeAt(K+1)&&Se===x.input.charCodeAt(K+2)&&(K+=3,Se=x.input.charCodeAt(K),Se===0||_(Se)))}function Oe(x,K){K===1?x.result+=" ":K>1&&(x.result+=e.repeat(`
|
|
1489
|
+
`,K-1))}function De(x,K,Se){let xe,fe,$,Y,de,ge;const be=x.kind,we=x.result;let ue=x.input.charCodeAt(x.position);if(_(ue)||C(ue)||ue===35||ue===38||ue===42||ue===33||ue===124||ue===62||ue===39||ue===34||ue===37||ue===64||ue===96)return!1;if(ue===63||ue===45){const Le=x.input.charCodeAt(x.position+1);if(_(Le)||Se&&C(Le))return!1}for(x.kind="scalar",x.result="",xe=fe=x.position,$=!1;ue!==0;){if(ue===58){const Le=x.input.charCodeAt(x.position+1);if(_(Le)||Se&&C(Le))break}else if(ue===35){const Le=x.input.charCodeAt(x.position-1);if(_(Le))break}else{if(x.position===x.lineStart&&he(x)||Se&&C(ue))break;if(w(ue))if(Y=x.line,de=x.lineStart,ge=x.lineIndent,Te(x,!1,-1),x.lineIndent>=K){$=!0,ue=x.input.charCodeAt(x.position);continue}else{x.position=fe,x.line=Y,x.lineStart=de,x.lineIndent=ge;break}}$&&(Ee(x,xe,fe,!1),Oe(x,x.line-Y),xe=fe=x.position,$=!1),E(ue)||(fe=x.position+1),ue=x.input.charCodeAt(++x.position)}return Ee(x,xe,fe,!1),x.result?!0:(x.kind=be,x.result=we,!1)}function Ye(x,K){let Se,xe,fe=x.input.charCodeAt(x.position);if(fe!==39)return!1;for(x.kind="scalar",x.result="",x.position++,Se=xe=x.position;(fe=x.input.charCodeAt(x.position))!==0;)if(fe===39)if(Ee(x,Se,x.position,!0),fe=x.input.charCodeAt(++x.position),fe===39)Se=x.position,x.position++,xe=x.position;else return!0;else w(fe)?(Ee(x,Se,xe,!0),Oe(x,Te(x,!1,K)),Se=xe=x.position):x.position===x.lineStart&&he(x)?L(x,"unexpected end of the document within a single quoted scalar"):(x.position++,E(fe)||(xe=x.position));L(x,"unexpected end of the stream within a single quoted scalar")}function gt(x,K){let Se,xe,fe,$=x.input.charCodeAt(x.position);if($!==34)return!1;for(x.kind="scalar",x.result="",x.position++,Se=xe=x.position;($=x.input.charCodeAt(x.position))!==0;){if($===34)return Ee(x,Se,x.position,!0),x.position++,!0;if($===92){if(Ee(x,Se,x.position,!0),$=x.input.charCodeAt(++x.position),w($))Te(x,!1,K);else if($<256&&U[$])x.result+=M[$],x.position++;else if((fe=k($))>0){let Y=fe,de=0;for(;Y>0;Y--)$=x.input.charCodeAt(++x.position),(fe=A($))>=0?de=(de<<4)+fe:L(x,"expected hexadecimal character");x.result+=P(de),x.position++}else L(x,"unknown escape sequence");Se=xe=x.position}else w($)?(Ee(x,Se,xe,!0),Oe(x,Te(x,!1,K)),Se=xe=x.position):x.position===x.lineStart&&he(x)?L(x,"unexpected end of the document within a double quoted scalar"):(x.position++,E($)||(xe=x.position))}L(x,"unexpected end of the stream within a double quoted scalar")}function $e(x,K){let Se=!0,xe,fe,$;const Y=x.tag;let de;const ge=x.anchor;let be,we,ue,Le;const at=Object.create(null);let vt,pt,Lt,er=x.input.charCodeAt(x.position);if(er===91)be=93,Le=!1,de=[];else if(er===123)be=125,Le=!0,de={};else return!1;for(x.anchor!==null&&B(x,x.anchor,de),er=x.input.charCodeAt(++x.position);er!==0;){if(Te(x,!0,K),er=x.input.charCodeAt(x.position),er===be)return x.position++,x.tag=Y,x.anchor=ge,x.kind=Le?"mapping":"sequence",x.result=de,!0;if(Se?er===44&&L(x,"expected the node content, but found ','"):L(x,"missed comma between flow collection entries"),pt=vt=Lt=null,we=ue=!1,er===63){const _m=x.input.charCodeAt(x.position+1);_(_m)&&(we=ue=!0,x.position++,Te(x,!0,K))}xe=x.line,fe=x.lineStart,$=x.position,ie(x,K,s,!1,!0),pt=x.tag,vt=x.result,Te(x,!0,K),er=x.input.charCodeAt(x.position),(ue||x.line===xe)&&er===58&&(we=!0,er=x.input.charCodeAt(++x.position),Te(x,!0,K),ie(x,K,s,!1,!0),Lt=x.result),Le?Pe(x,de,at,pt,vt,Lt,xe,fe,$):we?de.push(Pe(x,null,at,pt,vt,Lt,xe,fe,$)):de.push(vt),Te(x,!0,K),er=x.input.charCodeAt(x.position),er===44?(Se=!0,er=x.input.charCodeAt(++x.position)):Se=!1}L(x,"unexpected end of the stream within a flow collection")}function Ie(x,K){let Se,xe=l,fe=!1,$=!1,Y=K,de=0,ge=!1,be,we=x.input.charCodeAt(x.position);if(we===124)Se=!1;else if(we===62)Se=!0;else return!1;for(x.kind="scalar",x.result="";we!==0;)if(we=x.input.charCodeAt(++x.position),we===43||we===45)l===xe?xe=we===43?d:u:L(x,"repeat of a chomping mode identifier");else if((be=R(we))>=0)be===0?L(x,"bad explicit indentation width of a block scalar; it cannot be less than one"):$?L(x,"repeat of an indentation width identifier"):(Y=K+be-1,$=!0);else break;if(E(we)){do we=x.input.charCodeAt(++x.position);while(E(we));if(we===35)do we=x.input.charCodeAt(++x.position);while(!w(we)&&we!==0)}for(;we!==0;){for(ke(x),x.lineIndent=0,we=x.input.charCodeAt(x.position);(!$||x.lineIndent<Y)&&we===32;)x.lineIndent++,we=x.input.charCodeAt(++x.position);if(!$&&x.lineIndent>Y&&(Y=x.lineIndent),w(we)){de++;continue}if(!$&&Y===0&&L(x,"missing indentation for block scalar"),x.lineIndent<Y){xe===d?x.result+=e.repeat(`
|
|
1490
|
+
`,fe?1+de:de):xe===l&&fe&&(x.result+=`
|
|
1491
1491
|
`);break}Se?E(we)?(ge=!0,x.result+=e.repeat(`
|
|
1492
1492
|
`,fe?1+de:de)):ge?(ge=!1,x.result+=e.repeat(`
|
|
1493
1493
|
`,de+1)):de===0?fe&&(x.result+=" "):x.result+=e.repeat(`
|
|
1494
1494
|
`,de):x.result+=e.repeat(`
|
|
1495
|
-
`,fe?1+de:de),fe=!0,$=!0,de=0;const ue=x.position;for(;!w(we)&&we!==0;)we=x.input.charCodeAt(++x.position);Ee(x,ue,x.position,!1)}return!0}function ve(x,K){const Se=x.tag,
|
|
1496
|
-
`),x.charCodeAt(0)===65279&&(x=x.slice(1)));const Se=new F(x,K),
|
|
1495
|
+
`,fe?1+de:de),fe=!0,$=!0,de=0;const ue=x.position;for(;!w(we)&&we!==0;)we=x.input.charCodeAt(++x.position);Ee(x,ue,x.position,!1)}return!0}function ve(x,K){const Se=x.tag,xe=x.anchor,fe=[];let $=!1;if(x.firstTabInLine!==-1)return!1;x.anchor!==null&&B(x,x.anchor,fe);let Y=x.input.charCodeAt(x.position);for(;Y!==0&&(x.firstTabInLine!==-1&&(x.position=x.firstTabInLine,L(x,"tab characters must not be used in indentation")),Y===45);){const de=x.input.charCodeAt(x.position+1);if(!_(de))break;if($=!0,x.position++,Te(x,!0,-1)&&x.lineIndent<=K){fe.push(null),Y=x.input.charCodeAt(x.position);continue}const ge=x.line;if(ie(x,K,a,!1,!0),fe.push(x.result),Te(x,!0,-1),Y=x.input.charCodeAt(x.position),(x.line===ge||x.lineIndent>K)&&Y!==0)L(x,"bad indentation of a sequence entry");else if(x.lineIndent<K)break}return $?(x.tag=Se,x.anchor=xe,x.kind="sequence",x.result=fe,!0):!1}function J(x,K,Se){let xe,fe,$,Y;const de=x.tag,ge=x.anchor,be={},we=Object.create(null);let ue=null,Le=null,at=null,vt=!1,pt=!1;if(x.firstTabInLine!==-1)return!1;x.anchor!==null&&B(x,x.anchor,be);let Lt=x.input.charCodeAt(x.position);for(;Lt!==0;){!vt&&x.firstTabInLine!==-1&&(x.position=x.firstTabInLine,L(x,"tab characters must not be used in indentation"));const er=x.input.charCodeAt(x.position+1),_m=x.line;if((Lt===63||Lt===58)&&_(er))Lt===63?(vt&&(Pe(x,be,we,ue,Le,null,fe,$,Y),ue=Le=at=null),pt=!0,vt=!0,xe=!0):vt?(vt=!1,xe=!0):L(x,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),x.position+=1,Lt=er;else{if(fe=x.line,$=x.lineStart,Y=x.position,!ie(x,Se,i,!1,!0))break;if(x.line===_m){for(Lt=x.input.charCodeAt(x.position);E(Lt);)Lt=x.input.charCodeAt(++x.position);if(Lt===58)Lt=x.input.charCodeAt(++x.position),_(Lt)||L(x,"a whitespace character is expected after the key-value separator within a block mapping"),vt&&(Pe(x,be,we,ue,Le,null,fe,$,Y),ue=Le=at=null),pt=!0,vt=!1,xe=!1,ue=x.tag,Le=x.result;else if(pt)L(x,"can not read an implicit mapping pair; a colon is missed");else return x.tag=de,x.anchor=ge,!0}else if(pt)L(x,"can not read a block mapping entry; a multiline key may not be an implicit key");else return x.tag=de,x.anchor=ge,!0}if((x.line===_m||x.lineIndent>K)&&(vt&&(fe=x.line,$=x.lineStart,Y=x.position),ie(x,K,c,!0,xe)&&(vt?Le=x.result:at=x.result),vt||(Pe(x,be,we,ue,Le,at,fe,$,Y),ue=Le=at=null),Te(x,!0,-1),Lt=x.input.charCodeAt(x.position)),(x.line===_m||x.lineIndent>K)&&Lt!==0)L(x,"bad indentation of a mapping entry");else if(x.lineIndent<K)break}return vt&&Pe(x,be,we,ue,Le,null,fe,$,Y),pt&&(x.tag=de,x.anchor=ge,x.kind="mapping",x.result=be),pt}function V(x){let K=!1,Se=!1,xe,fe,$=x.input.charCodeAt(x.position);if($!==33)return!1;x.tag!==null&&L(x,"duplication of a tag property"),$=x.input.charCodeAt(++x.position),$===60?(K=!0,$=x.input.charCodeAt(++x.position)):$===33?(Se=!0,xe="!!",$=x.input.charCodeAt(++x.position)):xe="!";let Y=x.position;if(K){do $=x.input.charCodeAt(++x.position);while($!==0&&$!==62);x.position<x.length?(fe=x.input.slice(Y,x.position),$=x.input.charCodeAt(++x.position)):L(x,"unexpected end of the stream within a verbatim tag")}else{for(;$!==0&&!_($);)$===33&&(Se?L(x,"tag suffix cannot contain exclamation marks"):(xe=x.input.slice(Y-1,x.position+1),g.test(xe)||L(x,"named tag handle cannot contain such characters"),Se=!0,Y=x.position+1)),$=x.input.charCodeAt(++x.position);fe=x.input.slice(Y,x.position),f.test(fe)&&L(x,"tag suffix cannot contain flow indicator characters")}fe&&!y.test(fe)&&L(x,"tag name cannot contain such characters: "+fe);try{fe=decodeURIComponent(fe)}catch{L(x,"tag name is malformed: "+fe)}return K?x.tag=fe:o.call(x.tagMap,xe)?x.tag=x.tagMap[xe]+fe:xe==="!"?x.tag="!"+fe:xe==="!!"?x.tag="tag:yaml.org,2002:"+fe:L(x,'undeclared tag handle "'+xe+'"'),!0}function se(x){let K=x.input.charCodeAt(x.position);if(K!==38)return!1;x.anchor!==null&&L(x,"duplication of an anchor property"),K=x.input.charCodeAt(++x.position);const Se=x.position;for(;K!==0&&!_(K)&&!C(K);)K=x.input.charCodeAt(++x.position);return x.position===Se&&L(x,"name of an anchor node must contain at least one character"),x.anchor=x.input.slice(Se,x.position),!0}function oe(x){let K=x.input.charCodeAt(x.position);if(K!==42)return!1;K=x.input.charCodeAt(++x.position);const Se=x.position;for(;K!==0&&!_(K)&&!C(K);)K=x.input.charCodeAt(++x.position);x.position===Se&&L(x,"name of an alias node must contain at least one character");const xe=x.input.slice(Se,x.position);return o.call(x.anchorMap,xe)||L(x,'unidentified alias "'+xe+'"'),x.result=x.anchorMap[xe],Te(x,!0,-1),!0}function Z(x,K,Se,xe){const fe=ce(x);return H(x),Q(x,K),x.tag=null,x.anchor=null,x.kind=null,x.result=null,J(x,Se,xe)&&x.kind==="mapping"?(G(x),!0):(X(x),Q(x,fe),!1)}function ie(x,K,Se,xe,fe){let $,Y,de=1,ge=!1,be=!1,we=null,ue,Le,at;x.depth>=x.maxDepth&&L(x,"nesting exceeded maxDepth ("+x.maxDepth+")"),x.depth+=1,x.listener!==null&&x.listener("open",x),x.tag=null,x.anchor=null,x.kind=null,x.result=null;const vt=$=Y=c===Se||a===Se;if(xe&&Te(x,!0,-1)&&(ge=!0,x.lineIndent>K?de=1:x.lineIndent===K?de=0:x.lineIndent<K&&(de=-1)),de===1)for(;;){const pt=x.input.charCodeAt(x.position),Lt=ce(x);if(ge&&(pt===33&&x.tag!==null||pt===38&&x.anchor!==null)||!V(x)&&!se(x))break;we===null&&(we=Lt),Te(x,!0,-1)?(ge=!0,Y=vt,x.lineIndent>K?de=1:x.lineIndent===K?de=0:x.lineIndent<K&&(de=-1)):Y=!1}if(Y&&(Y=ge||fe),de===1||c===Se)if(s===Se||i===Se?Le=K:Le=K+1,at=x.position-x.lineStart,de===1)if(Y&&(ve(x,at)||J(x,at,Le))||$e(x,Le))be=!0;else{const pt=x.input.charCodeAt(x.position);we!==null&&vt&&!Y&&pt!==124&&pt!==62&&Z(x,we,we.position-we.lineStart,Le)||$&&Ie(x,Le)||Ye(x,Le)||gt(x,Le)?be=!0:oe(x)?(be=!0,(x.tag!==null||x.anchor!==null)&&L(x,"alias node should not have any properties")):De(x,Le,s===Se)&&(be=!0,x.tag===null&&(x.tag="?")),x.anchor!==null&&B(x,x.anchor,x.result)}else de===0&&(be=Y&&ve(x,at));if(x.tag===null)x.anchor!==null&&B(x,x.anchor,x.result);else if(x.tag==="?"){x.result!==null&&x.kind!=="scalar"&&L(x,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+x.kind+'"');for(let pt=0,Lt=x.implicitTypes.length;pt<Lt;pt+=1)if(ue=x.implicitTypes[pt],ue.resolve(x.result)){x.result=ue.construct(x.result),x.tag=ue.tag,x.anchor!==null&&B(x,x.anchor,x.result);break}}else if(x.tag!=="!"){if(o.call(x.typeMap[x.kind||"fallback"],x.tag))ue=x.typeMap[x.kind||"fallback"][x.tag];else{ue=null;const pt=x.typeMap.multi[x.kind||"fallback"];for(let Lt=0,er=pt.length;Lt<er;Lt+=1)if(x.tag.slice(0,pt[Lt].tag.length)===pt[Lt].tag){ue=pt[Lt];break}}ue||L(x,"unknown tag !<"+x.tag+">"),x.result!==null&&ue.kind!==x.kind&&L(x,"unacceptable node kind for !<"+x.tag+'> tag; it should be "'+ue.kind+'", not "'+x.kind+'"'),ue.resolve(x.result,x.tag)?(x.result=ue.construct(x.result,x.tag),x.anchor!==null&&B(x,x.anchor,x.result)):L(x,"cannot resolve a node with !<"+x.tag+"> explicit tag")}return x.listener!==null&&x.listener("close",x),x.depth-=1,x.tag!==null||x.anchor!==null||be}function W(x){const K=x.position;let Se=!1,xe;for(x.version=null,x.checkLineBreaks=x.legacy,x.tagMap=Object.create(null),x.anchorMap=Object.create(null);(xe=x.input.charCodeAt(x.position))!==0&&(Te(x,!0,-1),xe=x.input.charCodeAt(x.position),!(x.lineIndent>0||xe!==37));){Se=!0,xe=x.input.charCodeAt(++x.position);let fe=x.position;for(;xe!==0&&!_(xe);)xe=x.input.charCodeAt(++x.position);const $=x.input.slice(fe,x.position),Y=[];for($.length<1&&L(x,"directive name must not be less than one character in length");xe!==0;){for(;E(xe);)xe=x.input.charCodeAt(++x.position);if(xe===35){do xe=x.input.charCodeAt(++x.position);while(xe!==0&&!w(xe));break}if(w(xe))break;for(fe=x.position;xe!==0&&!_(xe);)xe=x.input.charCodeAt(++x.position);Y.push(x.input.slice(fe,x.position))}xe!==0&&ke(x),o.call(Ae,$)?Ae[$](x,$,Y):q(x,'unknown document directive "'+$+'"')}if(Te(x,!0,-1),x.lineIndent===0&&x.input.charCodeAt(x.position)===45&&x.input.charCodeAt(x.position+1)===45&&x.input.charCodeAt(x.position+2)===45?(x.position+=3,Te(x,!0,-1)):Se&&L(x,"directives end mark is expected"),ie(x,x.lineIndent-1,c,!1,!0),Te(x,!0,-1),x.checkLineBreaks&&h.test(x.input.slice(K,x.position))&&q(x,"non-ASCII line breaks are interpreted as content"),x.documents.push(x.result),x.position===x.lineStart&&he(x)){x.input.charCodeAt(x.position)===46&&(x.position+=3,Te(x,!0,-1));return}x.position<x.length-1&&L(x,"end of the stream or a document separator is expected")}function re(x,K){x=String(x),K=K||{},x.length!==0&&(x.charCodeAt(x.length-1)!==10&&x.charCodeAt(x.length-1)!==13&&(x+=`
|
|
1496
|
+
`),x.charCodeAt(0)===65279&&(x=x.slice(1)));const Se=new F(x,K),xe=x.indexOf("\0");for(xe!==-1&&(Se.position=xe,L(Se,"null byte is not allowed in input")),Se.input+="\0";Se.input.charCodeAt(Se.position)===32;)Se.lineIndent+=1,Se.position+=1;for(;Se.position<Se.length-1;)W(Se);return Se.documents}function ye(x,K,Se){K!==null&&typeof K=="object"&&typeof Se>"u"&&(Se=K,K=null);const xe=re(x,Se);if(typeof K!="function")return xe;for(let fe=0,$=xe.length;fe<$;fe+=1)K(xe[fe])}function Re(x,K){const Se=re(x,K);if(Se.length!==0){if(Se.length===1)return Se[0];throw new t("expected a single document in the stream, but found more")}}return tk.loadAll=ye,tk.load=Re,tk}function vWr(){if(B6t)return v2;B6t=1;const e=QA(),t=ek(),r=fne(),n=Object.prototype.toString,o=Object.prototype.hasOwnProperty,s=65279,i=9,a=10,c=13,l=32,u=33,d=34,m=35,h=37,f=38,g=39,y=42,v=44,w=45,E=58,_=61,C=62,A=63,k=64,R=91,I=93,P=96,O=123,U=124,M=125,F={};F[0]="\\0",F[7]="\\a",F[8]="\\b",F[9]="\\t",F[10]="\\n",F[11]="\\v",F[12]="\\f",F[13]="\\r",F[27]="\\e",F[34]='\\"',F[92]="\\\\",F[133]="\\N",F[160]="\\_",F[8232]="\\L",F[8233]="\\P";const N=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],L=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;function q($,Y){if(Y===null)return{};const de={},ge=Object.keys(Y);for(let be=0,we=ge.length;be<we;be+=1){let ue=ge[be],Le=String(Y[ue]);ue.slice(0,2)==="!!"&&(ue="tag:yaml.org,2002:"+ue.slice(2));const at=$.compiledTypeMap.fallback[ue];at&&o.call(at.styleAliases,Le)&&(Le=at.styleAliases[Le]),de[ue]=Le}return de}function B($){let Y,de;const ge=$.toString(16).toUpperCase();if($<=255)Y="x",de=2;else if($<=65535)Y="u",de=4;else if($<=4294967295)Y="U",de=8;else throw new t("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+Y+e.repeat("0",de-ge.length)+ge}const H=1,G=2;function X($){this.schema=$.schema||r,this.indent=Math.max(1,$.indent||2),this.noArrayIndent=$.noArrayIndent||!1,this.skipInvalid=$.skipInvalid||!1,this.flowLevel=e.isNothing($.flowLevel)?-1:$.flowLevel,this.styleMap=q(this.schema,$.styles||null),this.sortKeys=$.sortKeys||!1,this.lineWidth=$.lineWidth||80,this.noRefs=$.noRefs||!1,this.noCompatMode=$.noCompatMode||!1,this.condenseFlow=$.condenseFlow||!1,this.quotingType=$.quotingType==='"'?G:H,this.forceQuotes=$.forceQuotes||!1,this.replacer=typeof $.replacer=="function"?$.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function ce($,Y){const de=e.repeat(" ",Y);let ge=0,be="";const we=$.length;for(;ge<we;){let ue;const Le=$.indexOf(`
|
|
1497
1497
|
`,ge);Le===-1?(ue=$.slice(ge),ge=we):(ue=$.slice(ge,Le+1),ge=Le+1),ue.length&&ue!==`
|
|
1498
1498
|
`&&(be+=de),be+=ue}return be}function Q($,Y){return`
|
|
1499
|
-
`+e.repeat(" ",$.indent*Y)}function
|
|
1499
|
+
`+e.repeat(" ",$.indent*Y)}function Ae($,Y){for(let de=0,ge=$.implicitTypes.length;de<ge;de+=1)if($.implicitTypes[de].resolve(Y))return!0;return!1}function Ee($){return $===l||$===i}function le($){return $>=32&&$<=126||$>=161&&$<=55295&&$!==8232&&$!==8233||$>=57344&&$<=65533&&$!==s||$>=65536&&$<=1114111}function ae($){return le($)&&$!==s&&$!==c&&$!==a}function Pe($,Y,de){const ge=ae($),be=ge&&!Ee($);return(de?ge:ge&&$!==v&&$!==R&&$!==I&&$!==O&&$!==M)&&$!==m&&!(Y===E&&!be)||ae(Y)&&!Ee(Y)&&$===m||Y===E&&be}function ke($){return le($)&&$!==s&&!Ee($)&&$!==w&&$!==A&&$!==E&&$!==v&&$!==R&&$!==I&&$!==O&&$!==M&&$!==m&&$!==f&&$!==y&&$!==u&&$!==U&&$!==_&&$!==C&&$!==g&&$!==d&&$!==h&&$!==k&&$!==P}function Te($){return!Ee($)&&$!==E}function he($,Y){const de=$.charCodeAt(Y);let ge;return de>=55296&&de<=56319&&Y+1<$.length&&(ge=$.charCodeAt(Y+1),ge>=56320&&ge<=57343)?(de-55296)*1024+ge-56320+65536:de}function Oe($){return/^\n* /.test($)}const De=1,Ye=2,gt=3,$e=4,Ie=5;function ve($,Y,de,ge,be,we,ue,Le){let at,vt=0,pt=null,Lt=!1,er=!1;const _m=ge!==-1;let lE=-1,uE=ke(he($,0))&&Te(he($,$.length-1));if(Y||ue)for(at=0;at<$.length;vt>=65536?at+=2:at++){if(vt=he($,at),!le(vt))return Ie;uE=uE&&Pe(vt,pt,Le),pt=vt}else{for(at=0;at<$.length;vt>=65536?at+=2:at++){if(vt=he($,at),vt===a)Lt=!0,_m&&(er=er||at-lE-1>ge&&$[lE+1]!==" ",lE=at);else if(!le(vt))return Ie;uE=uE&&Pe(vt,pt,Le),pt=vt}er=er||_m&&at-lE-1>ge&&$[lE+1]!==" "}return!Lt&&!er?uE&&!ue&&!be($)?De:we===G?Ie:Ye:de>9&&Oe($)?Ie:ue?we===G?Ie:Ye:er?$e:gt}function J($,Y,de,ge,be){$.dump=(function(){if(Y.length===0)return $.quotingType===G?'""':"''";if(!$.noCompatMode&&(N.indexOf(Y)!==-1||L.test(Y)))return $.quotingType===G?'"'+Y+'"':"'"+Y+"'";const we=$.indent*Math.max(1,de),ue=$.lineWidth===-1?-1:Math.max(Math.min($.lineWidth,40),$.lineWidth-we),Le=ge||$.flowLevel>-1&&de>=$.flowLevel;function at(vt){return Ae($,vt)}switch(ve(Y,Le,$.indent,ue,at,$.quotingType,$.forceQuotes&&!ge,be)){case De:return Y;case Ye:return"'"+Y.replace(/'/g,"''")+"'";case gt:return"|"+V(Y,$.indent)+se(ce(Y,we));case $e:return">"+V(Y,$.indent)+se(ce(oe(Y,ue),we));case Ie:return'"'+ie(Y)+'"';default:throw new t("impossible error: invalid scalar style")}})()}function V($,Y){const de=Oe($)?String(Y):"",ge=$[$.length-1]===`
|
|
1500
1500
|
`,we=ge&&($[$.length-2]===`
|
|
1501
1501
|
`||$===`
|
|
1502
1502
|
`)?"+":ge?"":"-";return de+we+`
|
|
@@ -1507,7 +1507,7 @@ ${e.instructions}`,timestamp:new Date().toISOString(),metadata:{isSkill:!0,skill
|
|
|
1507
1507
|
`:"")+Z(at,Y),be=we}return ge}function Z($,Y){if($===""||$[0]===" ")return $;const de=/ [^ ]/g;let ge,be=0,we,ue=0,Le=0,at="";for(;ge=de.exec($);)Le=ge.index,Le-be>Y&&(we=ue>be?ue:Le,at+=`
|
|
1508
1508
|
`+$.slice(be,we),be=we+1),ue=Le;return at+=`
|
|
1509
1509
|
`,$.length-be>Y&&ue>be?at+=$.slice(be,ue)+`
|
|
1510
|
-
`+$.slice(ue+1):at+=$.slice(be),at.slice(1)}function ie($){let Y="",de=0;for(let ge=0;ge<$.length;de>=65536?ge+=2:ge++){de=he($,ge);const be=F[de];!be&&le(de)?(Y+=$[ge],de>=65536&&(Y+=$[ge+1])):Y+=be||B(de)}return Y}function W($,Y,de){let ge="";const be=$.tag;for(let we=0,ue=de.length;we<ue;we+=1){let Le=de[we];$.replacer&&(Le=$.replacer.call(de,String(we),Le)),(K($,Y,Le,!1,!1)||typeof Le>"u"&&K($,Y,null,!1,!1))&&(ge!==""&&(ge+=","+($.condenseFlow?"":" ")),ge+=$.dump)}$.tag=be,$.dump="["+ge+"]"}function re($,Y,de,ge){let be="";const we=$.tag;for(let ue=0,Le=de.length;ue<Le;ue+=1){let at=de[ue];$.replacer&&(at=$.replacer.call(de,String(ue),at)),(K($,Y+1,at,!0,!0,!1,!0)||typeof at>"u"&&K($,Y+1,null,!0,!0,!1,!0))&&((!ge||be!=="")&&(be+=Q($,Y)),$.dump&&a===$.dump.charCodeAt(0)?be+="-":be+="- ",be+=$.dump)}$.tag=we,$.dump=be||"[]"}function ye($,Y,de){let ge="";const be=$.tag,we=Object.keys(de);for(let ue=0,Le=we.length;ue<Le;ue+=1){let at="";ge!==""&&(at+=", "),$.condenseFlow&&(at+='"');const vt=we[ue];let pt=de[vt];$.replacer&&(pt=$.replacer.call(de,vt,pt)),K($,Y,vt,!1,!1)&&($.dump.length>1024&&(at+="? "),at+=$.dump+($.condenseFlow?'"':"")+":"+($.condenseFlow?"":" "),K($,Y,pt,!1,!1)&&(at+=$.dump,ge+=at))}$.tag=be,$.dump="{"+ge+"}"}function Re($,Y,de,ge){let be="";const we=$.tag,ue=Object.keys(de);if($.sortKeys===!0)ue.sort();else if(typeof $.sortKeys=="function")ue.sort($.sortKeys);else if($.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Le=0,at=ue.length;Le<at;Le+=1){let vt="";(!ge||be!=="")&&(vt+=Q($,Y));const pt=ue[Le];let Lt=de[pt];if($.replacer&&(Lt=$.replacer.call(de,pt,Lt)),!K($,Y+1,pt,!0,!0,!0))continue;const er=$.tag!==null&&$.tag!=="?"||$.dump&&$.dump.length>1024;er&&($.dump&&a===$.dump.charCodeAt(0)?vt+="?":vt+="? "),vt+=$.dump,er&&(vt+=Q($,Y)),K($,Y+1,Lt,!0,er)&&($.dump&&a===$.dump.charCodeAt(0)?vt+=":":vt+=": ",vt+=$.dump,be+=vt)}$.tag=we,$.dump=be||"{}"}function x($,Y,de){const ge=de?$.explicitTypes:$.implicitTypes;for(let be=0,we=ge.length;be<we;be+=1){const ue=ge[be];if((ue.instanceOf||ue.predicate)&&(!ue.instanceOf||typeof Y=="object"&&Y instanceof ue.instanceOf)&&(!ue.predicate||ue.predicate(Y))){if(de?ue.multi&&ue.representName?$.tag=ue.representName(Y):$.tag=ue.tag:$.tag="?",ue.represent){const Le=$.styleMap[ue.tag]||ue.defaultStyle;let at;if(n.call(ue.represent)==="[object Function]")at=ue.represent(Y,Le);else if(o.call(ue.represent,Le))at=ue.represent[Le](Y,Le);else throw new t("!<"+ue.tag+'> tag resolver accepts not "'+Le+'" style');$.dump=at}return!0}}return!1}function K($,Y,de,ge,be,we,ue){$.tag=null,$.dump=de,x($,de,!1)||x($,de,!0);const Le=n.call($.dump),at=ge;ge&&(ge=$.flowLevel<0||$.flowLevel>Y);const vt=Le==="[object Object]"||Le==="[object Array]";let pt,Lt;if(vt&&(pt=$.duplicates.indexOf(de),Lt=pt!==-1),($.tag!==null&&$.tag!=="?"||Lt||$.indent!==2&&Y>0)&&(be=!1),Lt&&$.usedDuplicates[pt])$.dump="*ref_"+pt;else{if(vt&&Lt&&!$.usedDuplicates[pt]&&($.usedDuplicates[pt]=!0),Le==="[object Object]")ge&&Object.keys($.dump).length!==0?(Re($,Y,$.dump,be),Lt&&($.dump="&ref_"+pt+$.dump)):(ye($,Y,$.dump),Lt&&($.dump="&ref_"+pt+" "+$.dump));else if(Le==="[object Array]")ge&&$.dump.length!==0?($.noArrayIndent&&!ue&&Y>0?re($,Y-1,$.dump,be):re($,Y,$.dump,be),Lt&&($.dump="&ref_"+pt+$.dump)):(W($,Y,$.dump),Lt&&($.dump="&ref_"+pt+" "+$.dump));else if(Le==="[object String]")$.tag!=="?"&&J($,$.dump,Y,we,at);else{if(Le==="[object Undefined]")return!1;if($.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Le)}if($.tag!==null&&$.tag!=="?"){let er=encodeURI($.tag[0]==="!"?$.tag.slice(1):$.tag).replace(/!/g,"%21");$.tag[0]==="!"?er="!"+er:er.slice(0,18)==="tag:yaml.org,2002:"?er="!!"+er.slice(18):er="!<"+er+">",$.dump=er+" "+$.dump}}return!0}function Se($,Y){const de=[],ge=[];
|
|
1510
|
+
`+$.slice(ue+1):at+=$.slice(be),at.slice(1)}function ie($){let Y="",de=0;for(let ge=0;ge<$.length;de>=65536?ge+=2:ge++){de=he($,ge);const be=F[de];!be&&le(de)?(Y+=$[ge],de>=65536&&(Y+=$[ge+1])):Y+=be||B(de)}return Y}function W($,Y,de){let ge="";const be=$.tag;for(let we=0,ue=de.length;we<ue;we+=1){let Le=de[we];$.replacer&&(Le=$.replacer.call(de,String(we),Le)),(K($,Y,Le,!1,!1)||typeof Le>"u"&&K($,Y,null,!1,!1))&&(ge!==""&&(ge+=","+($.condenseFlow?"":" ")),ge+=$.dump)}$.tag=be,$.dump="["+ge+"]"}function re($,Y,de,ge){let be="";const we=$.tag;for(let ue=0,Le=de.length;ue<Le;ue+=1){let at=de[ue];$.replacer&&(at=$.replacer.call(de,String(ue),at)),(K($,Y+1,at,!0,!0,!1,!0)||typeof at>"u"&&K($,Y+1,null,!0,!0,!1,!0))&&((!ge||be!=="")&&(be+=Q($,Y)),$.dump&&a===$.dump.charCodeAt(0)?be+="-":be+="- ",be+=$.dump)}$.tag=we,$.dump=be||"[]"}function ye($,Y,de){let ge="";const be=$.tag,we=Object.keys(de);for(let ue=0,Le=we.length;ue<Le;ue+=1){let at="";ge!==""&&(at+=", "),$.condenseFlow&&(at+='"');const vt=we[ue];let pt=de[vt];$.replacer&&(pt=$.replacer.call(de,vt,pt)),K($,Y,vt,!1,!1)&&($.dump.length>1024&&(at+="? "),at+=$.dump+($.condenseFlow?'"':"")+":"+($.condenseFlow?"":" "),K($,Y,pt,!1,!1)&&(at+=$.dump,ge+=at))}$.tag=be,$.dump="{"+ge+"}"}function Re($,Y,de,ge){let be="";const we=$.tag,ue=Object.keys(de);if($.sortKeys===!0)ue.sort();else if(typeof $.sortKeys=="function")ue.sort($.sortKeys);else if($.sortKeys)throw new t("sortKeys must be a boolean or a function");for(let Le=0,at=ue.length;Le<at;Le+=1){let vt="";(!ge||be!=="")&&(vt+=Q($,Y));const pt=ue[Le];let Lt=de[pt];if($.replacer&&(Lt=$.replacer.call(de,pt,Lt)),!K($,Y+1,pt,!0,!0,!0))continue;const er=$.tag!==null&&$.tag!=="?"||$.dump&&$.dump.length>1024;er&&($.dump&&a===$.dump.charCodeAt(0)?vt+="?":vt+="? "),vt+=$.dump,er&&(vt+=Q($,Y)),K($,Y+1,Lt,!0,er)&&($.dump&&a===$.dump.charCodeAt(0)?vt+=":":vt+=": ",vt+=$.dump,be+=vt)}$.tag=we,$.dump=be||"{}"}function x($,Y,de){const ge=de?$.explicitTypes:$.implicitTypes;for(let be=0,we=ge.length;be<we;be+=1){const ue=ge[be];if((ue.instanceOf||ue.predicate)&&(!ue.instanceOf||typeof Y=="object"&&Y instanceof ue.instanceOf)&&(!ue.predicate||ue.predicate(Y))){if(de?ue.multi&&ue.representName?$.tag=ue.representName(Y):$.tag=ue.tag:$.tag="?",ue.represent){const Le=$.styleMap[ue.tag]||ue.defaultStyle;let at;if(n.call(ue.represent)==="[object Function]")at=ue.represent(Y,Le);else if(o.call(ue.represent,Le))at=ue.represent[Le](Y,Le);else throw new t("!<"+ue.tag+'> tag resolver accepts not "'+Le+'" style');$.dump=at}return!0}}return!1}function K($,Y,de,ge,be,we,ue){$.tag=null,$.dump=de,x($,de,!1)||x($,de,!0);const Le=n.call($.dump),at=ge;ge&&(ge=$.flowLevel<0||$.flowLevel>Y);const vt=Le==="[object Object]"||Le==="[object Array]";let pt,Lt;if(vt&&(pt=$.duplicates.indexOf(de),Lt=pt!==-1),($.tag!==null&&$.tag!=="?"||Lt||$.indent!==2&&Y>0)&&(be=!1),Lt&&$.usedDuplicates[pt])$.dump="*ref_"+pt;else{if(vt&&Lt&&!$.usedDuplicates[pt]&&($.usedDuplicates[pt]=!0),Le==="[object Object]")ge&&Object.keys($.dump).length!==0?(Re($,Y,$.dump,be),Lt&&($.dump="&ref_"+pt+$.dump)):(ye($,Y,$.dump),Lt&&($.dump="&ref_"+pt+" "+$.dump));else if(Le==="[object Array]")ge&&$.dump.length!==0?($.noArrayIndent&&!ue&&Y>0?re($,Y-1,$.dump,be):re($,Y,$.dump,be),Lt&&($.dump="&ref_"+pt+$.dump)):(W($,Y,$.dump),Lt&&($.dump="&ref_"+pt+" "+$.dump));else if(Le==="[object String]")$.tag!=="?"&&J($,$.dump,Y,we,at);else{if(Le==="[object Undefined]")return!1;if($.skipInvalid)return!1;throw new t("unacceptable kind of an object to dump "+Le)}if($.tag!==null&&$.tag!=="?"){let er=encodeURI($.tag[0]==="!"?$.tag.slice(1):$.tag).replace(/!/g,"%21");$.tag[0]==="!"?er="!"+er:er.slice(0,18)==="tag:yaml.org,2002:"?er="!!"+er.slice(18):er="!<"+er+">",$.dump=er+" "+$.dump}}return!0}function Se($,Y){const de=[],ge=[];xe($,de,ge);const be=ge.length;for(let we=0;we<be;we+=1)Y.duplicates.push(de[ge[we]]);Y.usedDuplicates=new Array(be)}function xe($,Y,de){if($!==null&&typeof $=="object"){const ge=Y.indexOf($);if(ge!==-1)de.indexOf(ge)===-1&&de.push(ge);else if(Y.push($),Array.isArray($))for(let be=0,we=$.length;be<we;be+=1)xe($[be],Y,de);else{const be=Object.keys($);for(let we=0,ue=be.length;we<ue;we+=1)xe($[be[we]],Y,de)}}}function fe($,Y){Y=Y||{};const de=new X(Y);de.noRefs||Se($,de);let ge=$;return de.replacer&&(ge=de.replacer.call({"":ge},"",ge)),K(de,0,ge,!0,!0)?de.dump+`
|
|
1511
1511
|
`:""}return v2.dump=fe,v2}function TWr(){if(z6t)return pi;z6t=1;const e=yWr(),t=vWr();function r(n,o){return function(){throw new Error("Function yaml."+n+" is removed in js-yaml 4. Use yaml."+o+" instead, which is now safe by default.")}}return pi.Type=ta(),pi.Schema=e6t(),pi.FAILSAFE_SCHEMA=o6t(),pi.JSON_SCHEMA=l6t(),pi.CORE_SCHEMA=u6t(),pi.DEFAULT_SCHEMA=fne(),pi.load=e.load,pi.loadAll=e.loadAll,pi.dump=t.dump,pi.YAMLException=ek(),pi.types={binary:p6t(),float:c6t(),map:n6t(),null:s6t(),pairs:f6t(),set:g6t(),timestamp:d6t(),bool:i6t(),int:a6t(),merge:m6t(),omap:h6t(),seq:r6t(),str:t6t()},pi.safeLoad=r("safeLoad","load"),pi.safeLoadAll=r("safeLoadAll","loadAll"),pi.safeDump=r("safeDump","dump"),pi}var pi,tk,Yd,y6t,gne,v6t,yne,T6t,vne,w6t,Tne,E6t,wne,S6t,Ene,b6t,Sne,_6t,bne,C6t,_ne,A6t,Cne,k6t,Ane,x6t,kne,I6t,xne,R6t,Ine,P6t,Rne,M6t,Pne,O6t,Mne,D6t,One,N6t,Dne,L6t,Nne,F6t,Lne,$6t,U6t,v2,B6t,z6t,q6t,Fne,wWr,EWr,SWr,bWr,_Wr,CWr,AWr,kWr,xWr,IWr,RWr,PWr,MWr,OWr,DWr=b({"node_modules/.pnpm/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs"(){pi={},tk={},Yd={},v2={},q6t=TWr(),Fne=fWr(q6t),{Type:wWr,Schema:EWr,FAILSAFE_SCHEMA:SWr,JSON_SCHEMA:bWr,CORE_SCHEMA:_Wr,DEFAULT_SCHEMA:CWr,load:AWr,loadAll:kWr,dump:xWr,YAMLException:IWr,types:RWr,safeLoad:PWr,safeLoadAll:MWr,safeDump:OWr}=Fne}});function NWr(){if(rk!==void 0)return rk;try{return rk=G6t("@aws-sdk/client-s3"),rk}catch(e){return rk=null,p.debug("[SkillStoreS3] @aws-sdk/client-s3 is not installed; S3 skill storage unavailable.",{error:e instanceof Error?e.message:String(e)}),null}}function LWr(e){const t=NWr();if(!t)throw new Error("Skills S3 storage requires @aws-sdk/client-s3. Run `pnpm add @aws-sdk/client-s3` (or your package manager equivalent), or supply a custom store instead.");const r=new t.S3Client({...e.region?{region:e.region}:{},...e.endpoint?{endpoint:e.endpoint}:{},...e.forcePathStyle!==void 0?{forcePathStyle:e.forcePathStyle}:{},...e.credentials?{credentials:e.credentials}:{}}),n=e.bucket;return{async getObject(o){try{return await(await r.send(new t.GetObjectCommand({Bucket:n,Key:o}))).Body?.transformToString()??null}catch(s){const i=s.name;if(i==="NoSuchKey"||i==="NotFound")return null;throw s}},async putObject(o,s){await r.send(new t.PutObjectCommand({Bucket:n,Key:o,Body:s,ContentType:"application/json"}))},async deleteObject(o){await r.send(new t.DeleteObjectCommand({Bucket:n,Key:o}))},async listKeys(o){const s=[];let i;do{const a=await r.send(new t.ListObjectsV2Command({Bucket:n,Prefix:o,...i?{ContinuationToken:i}:{}}));for(const c of a.Contents??[])c.Key&&s.push(c.Key);i=a.IsTruncated?a.NextContinuationToken:void 0}while(i);return s},async getObjectConditional(o,s){try{const i=await r.send(new t.GetObjectCommand({Bucket:n,Key:o,...s?{IfNoneMatch:s}:{}}));return{body:await i.Body?.transformToString()??null,...i.ETag?{etag:i.ETag}:{}}}catch(i){const a=i.name;if(i.$metadata?.httpStatusCode===304||a==="304"||a==="NotModified")return{body:null,notModified:!0};if(a==="NoSuchKey"||a==="NotFound")return{body:null};throw i}}}}var G6t,rk,$ne,j6t=b({"src/lib/skills/skillStoreS3.ts"(){"use strict";p4(),z(),vT(),G6t=q0(import.meta.url),$ne=class{constructor(e,t){this.config=e,this.injectedOps=t;const r=e.prefix??"neurolink-skills/";this.prefix=r===""||r.endsWith("/")?r:`${r}/`}config;injectedOps;prefix;ops=null;cachedIndexDoc=null;cachedIndexEtag;invalidate(){this.cachedIndexDoc=null,this.cachedIndexEtag=void 0}getOps(){return this.ops||(this.ops=this.injectedOps??LWr(this.config)),this.ops}skillKey(e){return`${this.prefix}skills/${e}.json`}indexKey(){return`${this.prefix}index.json`}resourceKey(e,t){return`${this.prefix}skills/${e}/${t}`}async getResource(e,t){return K5t(t)?this.getOps().getObject(this.resourceKey(e,t)):null}async get(e){const t=await this.getOps().getObject(this.skillKey(e));if(!t)return null;try{return JSON.parse(t)}catch(r){return p.warn("[SkillStoreS3] Failed to parse skill object",{id:e,error:r instanceof Error?r.message:String(r)}),null}}async put(e){await this.getOps().putObject(this.skillKey(e.id),JSON.stringify(e,null,2));const r=await this.readOrRebuildIndex(),n=ZA(e),o=r.skills.findIndex(s=>s.id===e.id);o>=0?r.skills[o]=n:r.skills.push(n),await this.writeIndex(r)}async delete(e){await this.getOps().deleteObject(this.skillKey(e));const r=await this.readOrRebuildIndex();r.skills=r.skills.filter(n=>n.id!==e),await this.writeIndex(r)}async index(){return(await this.readOrRebuildIndex()).skills}async writeIndex(e){e.lastUpdated=new Date().toISOString(),await this.getOps().putObject(this.indexKey(),JSON.stringify(e,null,2)),this.cachedIndexDoc=e,this.cachedIndexEtag=void 0}async readIndexObject(e){return e.getObjectConditional?e.getObjectConditional(this.indexKey(),this.cachedIndexDoc?this.cachedIndexEtag:void 0):{body:await e.getObject(this.indexKey())}}async readOrRebuildIndex(){const e=this.getOps(),t=await this.readIndexObject(e);if(t.notModified&&this.cachedIndexDoc)return this.cachedIndexDoc;if(t.body){try{const i=JSON.parse(t.body);if(Array.isArray(i.skills))return this.cachedIndexDoc=i,this.cachedIndexEtag=t.etag,i}catch(i){p.warn("[SkillStoreS3] index.json unparsable \u2014 rebuilding",{error:i instanceof Error?i.message:String(i)})}this.cachedIndexEtag=void 0}const r=`${this.prefix}skills/`,n=await e.listKeys(r),o=[];for(const i of n){if(!i.endsWith(".json"))continue;const a=await e.getObject(i);if(a)try{o.push(ZA(JSON.parse(a)))}catch{p.warn("[SkillStoreS3] Skipping unparsable skill during rebuild",{key:i})}}const s={lastUpdated:new Date().toISOString(),skills:o};this.cachedIndexDoc=s,this.cachedIndexEtag=void 0;try{await this.writeIndex(s),p.info("[SkillStoreS3] Rebuilt skills index",{count:o.length})}catch(i){p.warn("[SkillStoreS3] Failed to persist rebuilt index",{error:i instanceof Error?i.message:String(i)})}return s}}}}),H6t,Une,V6t=b({"src/lib/skills/skillStoreRedis.ts"(){"use strict";h2(),z(),vT(),H6t="neurolink:skills:",Une=class{keyPrefix;resourcePrefix;normalizedConfig;clientPromise=null;constructor(e){this.keyPrefix=e.keyPrefix??H6t,this.resourcePrefix=`${this.keyPrefix}__resources__:`,this.normalizedConfig=Zre({...e.url?{url:e.url}:{},...e.host?{host:e.host}:{},...e.port!==void 0?{port:e.port}:{},...e.username?{username:e.username}:{},...e.password?{password:e.password}:{},...e.db!==void 0?{db:e.db}:{},keyPrefix:this.keyPrefix})}getClient(){return this.clientPromise||(this.clientPromise=Kre(this.normalizedConfig).catch(e=>{throw this.clientPromise=null,e})),this.clientPromise}skillKey(e){return`${this.keyPrefix}${e}`}async getResource(e,t){if(!K5t(t))return null;const n=await(await this.getClient()).get(`${this.resourcePrefix}${e}:${t}`);return n?String(n):null}async get(e){const r=await(await this.getClient()).get(this.skillKey(e));return r?this.parseSkill(String(r),this.skillKey(e)):null}async put(e){await(await this.getClient()).set(this.skillKey(e.id),JSON.stringify(e))}async delete(e){await(await this.getClient()).del(this.skillKey(e))}async index(){const e=await this.getClient(),t=(await JA(e,`${this.keyPrefix}*`)).filter(o=>!o.startsWith(this.resourcePrefix));if(t.length===0)return[];const r=await e.mGet(t),n=[];return r.forEach((o,s)=>{if(!o)return;const i=this.parseSkill(String(o),t[s]);i&&n.push(ZA(i))}),n}parseSkill(e,t){try{const r=JSON.parse(e);return typeof r?.id=="string"&&typeof r?.name=="string"&&typeof r?.description=="string"&&typeof r?.instructions=="string"?r:(p.warn("[SkillStoreRedis] Value is not a valid skill \u2014 skipping",{key:t}),null)}catch(r){return p.warn("[SkillStoreRedis] Failed to parse skill value",{key:t,error:r instanceof Error?r.message:String(r)}),null}}}}});function nk(e){return{...e,scope:e.scope??"global",status:e.status??"active",version:e.version??1,tags:e.tags??[]}}function FWr(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.id=="string"&&t.id.length>0&&typeof t.name=="string"&&t.name.length>0&&typeof t.description=="string"&&typeof t.instructions=="string"}function W6t(e,t){const r=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);let n={},o=e;if(r){try{const l=Fne.load(r[1]);typeof l=="object"&&l!==null&&(n=l)}catch(l){return p.warn("[SkillStore] Invalid YAML frontmatter in skill markdown",{fallbackId:t,error:l instanceof Error?l.message:String(l)}),null}o=e.slice(r[0].length)}const s=typeof n.name=="string"?n.name:t,i=typeof n.description=="string"?n.description:"",a=o.trim();return!s||!i||!a?(p.warn("[SkillStore] Skipping skill markdown missing name/description/body",{fallbackId:t}),null):nk({id:typeof n.id=="string"?n.id:s,name:s,description:i,instructions:a,...typeof n.displayName=="string"?{displayName:n.displayName}:{},...Array.isArray(n.tags)?{tags:n.tags.map(l=>String(l))}:{},...n.scope==="scoped"||n.scope==="global"?{scope:n.scope}:{},...Array.isArray(n.scopeIds)?{scopeIds:n.scopeIds.map(l=>String(l))}:{},...typeof n.version=="number"?{version:n.version}:{}})}function $Wr(e){const t=[],r=(n,o)=>{let s;try{s=JS(n,{withFileTypes:!0})}catch{return}for(const i of s){const a=o?`${o}/${i.name}`:i.name;if(i.isDirectory())r(yt(n,i.name),a);else if(a!=="SKILL.md")try{t.push({path:a,size:zh(yt(n,i.name)).size})}catch{t.push({path:a})}}};return r(e,""),t.sort((n,o)=>n.path<o.path?-1:n.path>o.path?1:0)}function K6t(e){return!e||e.type==="memory"?new Bne(e?.type==="memory"?e.skills:void 0,e?.type==="memory"?e.resources:void 0):e.type==="filesystem"?new zne(e.path):e.type==="s3"?new $ne(e):e.type==="redis"?new Une(e):e.store}var Bne,zne,J6t=b({"src/lib/skills/skillStores.ts"(){"use strict";Pn(),zt(),DWr(),z(),vT(),j6t(),V6t(),Bne=class{skills=new Map;resources=new Map;constructor(e,t){for(const[r,n]of Object.entries(t??{}))this.resources.set(r,new Map(Object.entries(n)));for(const r of e??[]){const n=this.resources.get(r.id),o=n&&!r.resources?{...r,resources:Array.from(n.keys()).sort().map(s=>({path:s}))}:r;this.skills.set(r.id,nk(o))}}async get(e){return this.skills.get(e)??null}async put(e){this.skills.set(e.id,nk(e))}async delete(e){this.skills.delete(e)}async index(){return Array.from(this.skills.values()).map(ZA)}async getResource(e,t){return this.resources.get(e)?.get(t)??null}},zne=class{constructor(e){this.baseDir=e}baseDir;cache=null;skillDirs=new Map;invalidate(){this.cache=null}async get(e){return this.load().get(e)??null}async getResource(e,t){this.load();const r=this.skillDirs.get(e);if(!r)return null;try{const n=Bh(r),o=Bh(jo(r,t));return o!==n&&!o.startsWith(n+gd)?null:li(o,"utf-8")}catch(n){const o=n.code;if(o==="ENOENT"||o==="EISDIR"||o==="ELOOP")return null;throw n}}async put(e){hu(this.baseDir,{recursive:!0});const t=yt(this.baseDir,`${e.id}.json`);Uh(t,JSON.stringify(nk(e),null,2),"utf-8"),this.invalidate()}async delete(e){const t=yt(this.baseDir,`${e}.json`);try{aP(t)}catch(r){if(r.code!=="ENOENT")throw r}this.invalidate()}async index(){return Array.from(this.load().values()).map(ZA)}load(){if(this.cache)return this.cache;const e=new Map;this.skillDirs=new Map;let t;try{t=JS(this.baseDir,{withFileTypes:!0})}catch(n){return n.code!=="ENOENT"&&p.warn("[SkillStore] Failed to read skills directory",{baseDir:this.baseDir,error:n instanceof Error?n.message:String(n)}),this.cache=e,e}const r=[];for(const n of t){const o=yt(this.baseDir,n.name);try{if(n.isDirectory()){const s=yt(o,"SKILL.md");if(Ai(s)){const i=W6t(li(s,"utf-8"),n.name);if(i){const a=$Wr(o);e.set(i.id,a.length>0?{...i,resources:a}:i),this.skillDirs.set(i.id,jo(o))}}}else if(n.name.endsWith(".md")){const s=W6t(li(o,"utf-8"),n.name.replace(/\.md$/,""));s&&e.set(s.id,s)}else n.name.endsWith(".json")&&r.push(o)}catch(s){p.warn("[SkillStore] Failed to load skill file",{file:o,error:s instanceof Error?s.message:String(s)})}}for(const n of r)try{const o=JSON.parse(li(n,"utf-8"));FWr(o)?e.set(o.id,nk(o)):p.warn("[SkillStore] Skipping invalid skill JSON",{file:n})}catch(o){p.warn("[SkillStore] Failed to parse skill JSON",{file:n,error:o instanceof Error?o.message:String(o)})}return this.cache=e,e}}}});function Y6t(e){if(e.scope==="scoped"&&(e.scopeIds??[]).length===0)throw new Error('A skill with scope "scoped" must have at least one entry in scopeIds')}function UWr(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var X6t,Z6t,Q6t,eBt,qne,tBt=b({"src/lib/skills/skillsManager.ts"(){"use strict";Wr(),z(),vT(),Q5t(),J6t(),X6t=5,Z6t=50,Q6t=3e4,eBt=15e3,qne=class{constructor(e){this.config=e,this.store=K6t(e.storage)}config;store;cachedIndex=null;cachedIndexAt=0;mutationQueue=Promise.resolve();sessions=new Z5t;async getIndex(e=!1){const t=this.config.indexCacheTtlMs??Q6t;if(this.cachedIndex!==null&&t>0&&Date.now()-this.cachedIndexAt<t&&!e&&this.cachedIndex)return this.cachedIndex;const n=mWr(await this.store.index());return this.cachedIndex=n,this.cachedIndexAt=Date.now(),n}invalidateIndex(){this.cachedIndex=null,this.store.invalidate?.()}async search(e){const t=e.limit??this.config.maxMatches??X6t,r=e.scopeId??this.config.defaultScopeId,n=await this.getIndex(),o=W5t(n,{...e,...r!==void 0?{scopeId:r}:{},limit:t});return(await Promise.all(o.map(i=>this.store.get(i.id)))).filter(i=>i!==null)}async list(e){const t=e??this.config.defaultScopeId,r=await this.getIndex();return W5t(r,{...t!==void 0?{scopeId:t}:{}})}async get(e){const t=await this.store.get(e);if(t)return t;const r=await this.getIndex(),n=e.toLowerCase(),o=r.find(s=>s.name.toLowerCase()===n&&(s.status??"active")==="active")??r.find(s=>s.name.toLowerCase()===n);return o?this.store.get(o.id):null}async buildPromptIndex(e){const t=await this.visibleItems(e);return hWr(t,this.config.promptIndexMaxItems??Z6t)}async buildToolListing(e){const t=await this.visibleItems(e);return pWr(t,this.config.listingBudgetChars??eBt)}async visibleItems(e){let t=await this.list(e?.scopeId);if(e?.tags&&e.tags.length>0){const r=e.tags.map(n=>n.toLowerCase());t=t.filter(n=>(n.tags??[]).some(o=>r.includes(o.toLowerCase())))}return t}async getResource(e,t){const r=t.replace(/\\/g,"/");if(r.startsWith("/")||r.split("/").some(o=>o===".."))throw new Error(`Invalid resource path "${t}" \u2014 must be relative to the skill directory`);if(!this.store.getResource)return null;const n=await this.get(e);return n?this.store.getResource(n.id,r):null}get mutationsAllowed(){return this.config.allowMutations??!1}async requestMutation(e){let t={outcome:"approved"};if(this.config.onMutationRequest&&(t=await this.config.onMutationRequest(e)),t.outcome!=="approved")return{decision:t};const r=this.mutationQueue.then(()=>this.applyMutation(e));this.mutationQueue=r.catch(()=>{});const n=await r;return{decision:t,...n?{skill:n}:{}}}async applyMutation(e){const t=new Date().toISOString();if(e.type==="create"){await this.assertNameAvailable(e.skill.name);const o={id:dn(),version:1,status:"active",createdAt:t,updatedAt:t,...e.skill};return Y6t(o),await this.store.put(o),this.invalidateIndex(),p.info("[SkillsManager] Skill created",{skillId:o.id,name:o.name}),o}if(e.type==="update"){const o=await this.get(e.skillId);if(!o)throw new Error(`Skill "${e.skillId}" not found`);e.patch.name&&e.patch.name!==o.name&&await this.assertNameAvailable(e.patch.name,o.id);const s={...o,...UWr(e.patch),id:o.id,version:(o.version??1)+1,updatedAt:t};return Y6t(s),await this.store.put(s),this.invalidateIndex(),p.info("[SkillsManager] Skill updated",{skillId:s.id,version:s.version}),s}const r=await this.get(e.skillId);if(!r)throw new Error(`Skill "${e.skillId}" not found`);if(r.status==="deprecated")throw new Error(`Skill "${r.name}" is already deleted`);const n={...r,status:"deprecated",updatedAt:t};return await this.store.put(n),this.invalidateIndex(),p.info("[SkillsManager] Skill deprecated",{skillId:r.id,name:r.name}),n}async assertNameAvailable(e,t){const n=(await this.getIndex(!0)).find(o=>o.id!==t&&o.name.toLowerCase()===e.toLowerCase());if(n){const o=(n.status??"active")==="active"?"":` (that name belongs to a deprecated skill, id ${n.id}; remove it before reusing the name)`;throw new Error(`A skill named "${e}" already exists${o}`)}}}}});function BWr(e){return{name:e.name,...e.displayName?{displayName:e.displayName}:{},version:e.version??1,instructions:e.instructions,...e.resources&&e.resources.length>0?{resources:e.resources.map(t=>t.path),resourcesHint:"Auxiliary files \u2014 read one with read_skill_resource only when the task needs it."}:{},note:"Follow these instructions for the current task. The skill stays loaded for this conversation \u2014 do not invoke use_skill for it again."}}function zWr(e){const t="Load a team-defined skill (SOP, playbook, workflow) by name to get its full instructions. When the user's task matches a skill, invoke this tool, then follow the loaded instructions exactly. Do NOT invoke it for a skill that is already loaded in this conversation, and do not invoke it at all when no skill matches the task.";return e.discovery==="tool"&&e.listing?`${t}
|
|
1512
1512
|
|
|
1513
1513
|
Skills available in this conversation:
|
|
@@ -2150,7 +2150,7 @@ ${r}`:r}function DQr(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>ty
|
|
|
2150
2150
|
${this.escapeXml(t)}
|
|
2151
2151
|
</prosody>
|
|
2152
2152
|
</voice>
|
|
2153
|
-
</speak>`}extractLanguage(t){const r=t.match(/^([a-z]{2}-[A-Z]{2})/);return r?r[1]:"en-US"}escapeXml(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}mapGender(t){switch(t?.toLowerCase()){case"male":return"male";case"female":return"female";default:return"neutral"}}mapFormat(t){return{mp3:"audio-24khz-96kbitrate-mono-mp3",wav:"riff-24khz-16bit-mono-pcm",ogg:"ogg-24khz-16bit-mono-opus",opus:"ogg-24khz-16bit-mono-opus"}[t]??"audio-24khz-96kbitrate-mono-mp3"}getSampleRate(t){return t.includes("24khz")?24e3:t.includes("16khz")?16e3:t.includes("48khz")?48e3:24e3}effectiveFormat(t){return t.includes("mp3")?"mp3":t.includes("opus")?"opus":t.startsWith("raw")&&t.includes("pcm")?"pcm16":t.includes("riff")||t.includes("pcm")||t.includes("wav")?"wav":"mp3"}}}}),g7t,y7t,v7t,T7t,Kie,QT,w7t=b({"src/lib/voice/providers/CartesiaTTS.ts"(){"use strict";Lr(),z(),xc(),g7t="https://api.cartesia.ai",y7t="2025-04-16",v7t="sonic-2",T7t="694f9389-aac1-45b6-b726-9d9369183238",Kie=3e4,QT=class{maxTextLength=5e3;apiKey;baseUrl;apiVersion;constructor(e){const t=(e??process.env.CARTESIA_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.CARTESIA_BASE_URL??g7t).replace(/\/$/,""),this.apiVersion=process.env.CARTESIA_API_VERSION??y7t}isConfigured(){return this.apiKey!==null}async synthesize(e,t={}){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"CARTESIA_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=t.voice??process.env.CARTESIA_VOICE_ID??T7t,o=t.format??"mp3",{container:s,encoding:i,sampleRate:a}=this.mapOutputFormat(o),c=t,l=c.model??process.env.CARTESIA_MODEL??v7t,u={model_id:l,transcript:e,voice:{mode:"id",id:n},output_format:{container:s,encoding:i,sample_rate:a},language:c.language??"en"};let d;try{d=await Ct(fetch(`${this.baseUrl}/tts/bytes`,{method:"POST",headers:{"X-API-Key":this.apiKey,"Cartesia-Version":this.apiVersion,"Content-Type":"application/json"},body:JSON.stringify(u)}),Kie,`Cartesia request timed out after ${Kie/1e3}s`)}catch(v){throw v instanceof ad?new Et({code:At.SYNTHESIS_FAILED,message:v.message,category:"network",severity:"high",retriable:!0,originalError:v}):new Et({code:At.SYNTHESIS_FAILED,message:`Cartesia network error: ${v instanceof Error?v.message:String(v)}`,category:"network",severity:"high",retriable:!0,originalError:v instanceof Error?v:void 0})}if(!d.ok){const v=await d.text(),w=d.status===408||d.status===429||d.status>=500;throw new Et({code:At.SYNTHESIS_FAILED,message:`Cartesia synthesis failed: ${d.status} \u2014 ${v}`,category:w?"network":"execution",severity:"high",retriable:w,context:{status:d.status,voiceId:n,container:s,encoding:i}})}const m=await d.arrayBuffer(),h=Buffer.from(m),f=Date.now()-r,g=this.effectiveFormat(s,i),y={buffer:h,format:g,size:h.length,voice:n,sampleRate:a,metadata:{latency:f,provider:"cartesia",model:l,requestedFormat:t.format,container:s,encoding:i}};return p.info(`[CartesiaTTS] Synthesized ${h.length} bytes in ${f}ms`),y}mapOutputFormat(e){switch(e){case"mp3":return{container:"mp3",encoding:"mp3",sampleRate:44100};case"wav":return{container:"wav",encoding:"pcm_s16le",sampleRate:44100};case"pcm16":return{container:"raw",encoding:"pcm_s16le",sampleRate:24e3};default:throw new Et({code:At.SYNTHESIS_FAILED,message:`Cartesia does not support output format "${e}". Supported: mp3, wav, pcm16.`,category:"validation",severity:"medium",retriable:!1,context:{format:e,supported:["mp3","wav","pcm16"]}})}}effectiveFormat(e,t){if(e==="mp3")return"mp3";if(e==="wav")return"wav";if(t==="pcm_s16le")return"pcm16";throw new Et({code:At.SYNTHESIS_FAILED,message:`Unsupported Cartesia output combination: container=${e}, encoding=${t}`,category:"execution",severity:"high",retriable:!1,context:{container:e,encoding:t}})}}}}),ew,E7t=b({"src/lib/voice/providers/ElevenLabsTTS.ts"(){"use strict";z(),xc(),ew=class M0r{apiKey;baseUrl="https://api.elevenlabs.io/v1";voicesCache=null;static CACHE_TTL_MS=300*1e3;maxTextLength=5e3;constructor(t){const r=(t??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=r.length>0?r:null}isConfigured(){return this.apiKey!==null}async getVoices(t){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<M0r.CACHE_TTL_MS&&!t)return this.voicesCache.voices;try{const r=new AbortController,n=setTimeout(()=>r.abort(),3e4);let o;try{o=await fetch(`${this.baseUrl}/voices`,{method:"GET",headers:{"xi-api-key":this.apiKey},signal:r.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new Et({code:At.SYNTHESIS_FAILED,message:"ElevenLabs voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).voices.map(a=>({id:a.voice_id,name:a.name,languageCode:"en",languageCodes:["en","es","fr","de","it","pt","pl","hi","ar","zh","ja","ko"],gender:this.mapGender(a.labels?.gender),type:"neural",description:a.labels?.description}));if(t){const a=t.toLowerCase(),c=a.split("-")[0];i=i.filter(l=>l.languageCodes?.some(u=>{const d=u.toLowerCase();return d===a||d===c||d.startsWith(c)}))}return t||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(r){const n=r instanceof Error?r.message:String(r||"Unknown error");throw p.error(`[ElevenLabsTTSHandler] Failed to get voices: ${n}`),new Et({code:At.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:r instanceof Error?r:void 0})}}async synthesize(t,r={}){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});const n=Date.now(),o=r;try{const s=r.voice??"21m00Tcm4TlvDq8ikWAM",i=o.model??"eleven_multilingual_v2",a={text:t,model_id:i,voice_settings:{stability:o.stability??.5,similarity_boost:o.similarityBoost??.75,style:o.style??0,use_speaker_boost:o.useSpeakerBoost??!0}},c=this.mapFormat(r.format??"mp3"),l=new AbortController,u=setTimeout(()=>l.abort(),3e4);let d;try{d=await fetch(`${this.baseUrl}/text-to-speech/${s}?output_format=${c}`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Et({code:At.SYNTHESIS_FAILED,message:"ElevenLabs TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(u)}if(!d.ok){const v=(await d.json().catch(()=>Object.create(null))).detail?.message||`HTTP ${d.status}`;throw new Error(v)}const m=Date.now()-n,h=await d.arrayBuffer(),f=Buffer.from(h),g={buffer:f,format:this.effectiveFormat(c),size:f.length,voice:s,sampleRate:this.getSampleRate(c),metadata:{latency:m,provider:"elevenlabs-tts",model:i,requestedFormat:r.format,outputFormat:c}};return p.info(`[ElevenLabsTTSHandler] Synthesized ${f.length} bytes in ${m}ms`),g}catch(s){if(s instanceof Et)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw p.error(`[ElevenLabsTTSHandler] Synthesis failed: ${i}`),new Et({code:At.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:t.length},originalError:s instanceof Error?s:void 0})}}mapGender(t){if(!t)return"neutral";const r=t.toLowerCase();return r.includes("male")&&!r.includes("female")?"male":r.includes("female")?"female":"neutral"}mapFormat(t){return{mp3:"mp3_44100_128",wav:"pcm_44100",ogg:"ogg_22050",opus:"ogg_22050"}[t]??"mp3_44100_128"}getSampleRate(t){return t.includes("44100")?44100:t.includes("22050")?22050:t.includes("24000")?24e3:44100}effectiveFormat(t){return t.startsWith("mp3")?"mp3":t.startsWith("pcm")?"pcm16":t.startsWith("ogg")?"opus":"mp3"}}}}),S7t,Jie,b7t,tw,_7t=b({"src/lib/voice/providers/FishAudioTTS.ts"(){"use strict";z(),xc(),S7t="https://api.fish.audio",Jie=3e4,b7t="802e3bc2b27e49c2995d23ef70e6ac89",tw=class{maxTextLength=5e3;apiKey;baseUrl;constructor(e){const t=(e??process.env.FISH_AUDIO_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.FISH_AUDIO_BASE_URL??S7t).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async synthesize(e,t={}){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"FISH_AUDIO_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=t.voice??b7t,o=t.format??"mp3",s=this.mapFormat(o),i={text:e,reference_id:n,format:s,mp3_bitrate:128,chunk_length:200,normalize:!0,latency:"normal"},a=t;a.model&&(i.model=a.model),a.latency&&(i.latency=a.latency),a.mp3Bitrate!==void 0&&(i.mp3_bitrate=a.mp3Bitrate);const c=new AbortController,l=setTimeout(()=>c.abort(),Jie);let u;try{u=await fetch(`${this.baseUrl}/v1/tts`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:c.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Et({code:At.SYNTHESIS_FAILED,message:`Fish Audio request timed out after ${Jie/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:y}):new Et({code:At.SYNTHESIS_FAILED,message:`Fish Audio network error: ${y instanceof Error?y.message:String(y)}`,category:"network",severity:"high",retriable:!0,originalError:y instanceof Error?y:void 0})}finally{clearTimeout(l)}if(!u.ok){const y=await u.text(),v=u.status===408||u.status===429||u.status>=500;throw new Et({code:At.SYNTHESIS_FAILED,message:`Fish Audio synthesis failed: ${u.status} \u2014 ${y}`,category:v?"network":"execution",severity:"high",retriable:v,context:{status:u.status,referenceId:n,upstreamFormat:s}})}const d=await u.arrayBuffer(),m=Buffer.from(d),h=Date.now()-r,f=this.effectiveFormat(s),g={buffer:m,format:f,size:m.length,voice:n,sampleRate:this.getSampleRate(f),metadata:{latency:h,provider:"fish-audio",model:a.model??"s1",requestedFormat:t.format,upstreamFormat:s}};return p.info(`[FishAudioTTS] Synthesized ${m.length} bytes in ${h}ms`),g}mapFormat(e){const r={mp3:"mp3",wav:"wav",pcm16:"pcm"}[e];return r||(p.warn(`[FishAudioTTS] Unsupported format "${e}" \u2014 falling back to "mp3"`),"mp3")}effectiveFormat(e){return e==="mp3"?"mp3":e==="wav"?"wav":e==="pcm"?"pcm16":"mp3"}getSampleRate(e){return 44100}}}});function C7t(e){try{return e instanceof Error?String(e.message):String(e)}catch{return"[unprintable error]"}}function A7t(e,t){try{return e instanceof t}catch{return!1}}function k7t(e){try{return e instanceof Error&&e.name==="AbortError"}catch{return!1}}function x7t(e,t){if(A7t(e,Error))try{return String(e.name),String(e.message),String(e.stack),e}catch{return new Error(t)}}function I7t(e,t){try{return new Et({...e,originalError:t})}catch{return new Et(e)}}function cen(e){if(!A7t(e,Et))return!1;try{return String(e.name),String(e.message),String(e.code),e.retriable,String(e.stack),!0}catch{return!1}}var rw,R7t=b({"src/lib/voice/providers/OpenAITTS.ts"(){"use strict";z(),Qb(),xc(),rw=class Xde{apiKey;baseUrl="https://api.openai.com/v1";maxTextLength=4096;static VOICES=[{id:"alloy",name:"Alloy",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"echo",name:"Echo",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"fable",name:"Fable",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"onyx",name:"Onyx",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"nova",name:"Nova",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"},{id:"shimmer",name:"Shimmer",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"}];constructor(t){const r=(t??process.env.OPENAI_API_KEY??"").trim();this.apiKey=r.length>0?r:null}isConfigured(){return this.apiKey!==null}async getVoices(t){return t&&!t.startsWith("en"),Xde.VOICES}requireApiKey(){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"OpenAI TTS API key not configured",category:"configuration",severity:"high",retriable:!1});return this.apiKey}prepareRequest(t,r){const o=r.model??(r.quality==="hd"?"tts-1-hd":"tts-1"),s=r.voice??"alloy",i=this.mapFormat(r.format??"mp3");return{model:o,voice:s,responseFormat:i,effectiveFormat:this.effectiveFormat(i),body:{model:o,input:t,voice:s,response_format:i,speed:r.speed??1}}}async createSpeechResponse(t,r,n){let o;try{o=await fetch(`${this.baseUrl}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${this.requireApiKey()}`,"Content-Type":"application/json"},body:JSON.stringify(t.body),signal:r})}finally{n?.()}if(!o.ok){const i=(await o.json().catch(()=>Object.create(null))).error?.message||`HTTP ${o.status}`,a=o.status===408||o.status===429||o.status>=500;throw new Et({code:At.SYNTHESIS_FAILED,message:i,category:a?"network":"execution",severity:"high",retriable:a,context:{status:o.status,model:t.model,responseFormat:t.responseFormat}})}return o}synthesisError(t,r,n){if(cen(t))return t;if(k7t(t)&&n)return I7t({code:At.SYNTHESIS_FAILED,message:"OpenAI TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0},x7t(t,C7t(t)));const o=t?C7t(t):"Unknown error";return p.error(`[OpenAITTSHandler] Synthesis failed: ${o}`),I7t({code:At.SYNTHESIS_FAILED,message:`Synthesis failed: ${o}`,category:"execution",severity:"high",retriable:!0,context:{textLength:r}},x7t(t,o))}async synthesize(t,r={}){this.requireApiKey();const n=Date.now(),o=this.prepareRequest(t,r),s=new AbortController;let i=!1,a=setTimeout(()=>{i=!0,s.abort()},3e4);const c=()=>{a!==void 0&&(clearTimeout(a),a=void 0)};try{const l=await this.createSpeechResponse(o,s.signal,c),u=Date.now()-n,d=await l.arrayBuffer(),m=Buffer.from(d),h={buffer:m,format:o.effectiveFormat,size:m.length,voice:o.voice,sampleRate:this.getSampleRate(o.effectiveFormat),metadata:{latency:u,provider:"openai-tts",model:o.model,requestedFormat:r.format,responseFormat:o.responseFormat}};return p.info(`[OpenAITTSHandler] Synthesized ${m.length} bytes in ${u}ms`),h}catch(l){throw this.synthesisError(l,t.length,i)}finally{c()}}synthesizeStream(t,r={}){const n=r.format??"mp3";if(n!=="mp3"&&n!=="pcm16")return;const o=this.prepareRequest(t,r),s=this;let i,a,c=!1,l=!1,u=!1;const d=(async function*(){s.requireApiKey();const m=Date.now();i=new AbortController;const h=setTimeout(()=>{l=!0,i?.abort()},3e4);try{const f=await s.createSpeechResponse(o,i.signal);if(!f.body)throw new Et({code:At.SYNTHESIS_FAILED,message:"OpenAI TTS response did not include an audio body",category:"network",severity:"high",retriable:!0});a=f.body.getReader();let g=0,y=0;for(;;){const v=await a.read();if(v.done){u=!0;break}const w=Buffer.from(v.value);w.length!==0&&(y+=w.length,yield{data:w,format:o.effectiveFormat,index:g++,isFinal:!1,cumulativeSize:y,voice:o.voice,sampleRate:s.getSampleRate(o.effectiveFormat)})}p.info(`[OpenAITTSHandler] Streamed ${y} bytes in ${Date.now()-m}ms`)}catch(f){if(c&&k7t(f))return;throw s.synthesisError(f,t.length,l)}finally{clearTimeout(h),u||i?.abort();try{a?.releaseLock()}catch{}a=void 0,i=void 0}})();return Zb(d,()=>{c=!0,i?.abort()})}mapFormat(t){const n={mp3:"mp3",wav:"wav",ogg:"opus",opus:"opus",flac:"flac",pcm16:"pcm"}[t];return n===void 0?(p.warn(`[OpenAITTSHandler] Unsupported format "${t}" \u2014 falling back to "mp3". Supported formats: mp3, wav, ogg, opus, flac, pcm16.`),"mp3"):n}getSampleRate(t){switch(t){case"opus":case"ogg":return 48e3;default:return 24e3}}effectiveFormat(t){switch(t){case"mp3":return"mp3";case"wav":return"wav";case"opus":return"opus";case"flac":return"flac";case"pcm":return"pcm16";default:return"mp3"}}}}}),P7t={};ee(P7t,{Agent:()=>z7t,AsyncLocalStorage:()=>t9t,Buffer:()=>QWt,Channel:()=>qWt,DatabaseSync:()=>ZWt,Duplex:()=>n9t,EventEmitter:()=>e9t,Http2ServerRequest:()=>oKt,Http2ServerResponse:()=>sKt,Interface:()=>XWt,MIMEType:()=>dKt,PassThrough:()=>o9t,PerformanceObserver:()=>UWt,Readable:()=>Xie,ReadableStream:()=>s9t,Resolver:()=>FWt,STATUS_CODES:()=>iWt,TextDecoder:()=>eae,TextEncoder:()=>Fk,Transform:()=>r9t,URL:()=>_Wt,URLSearchParams:()=>CWt,Worker:()=>VWt,Writable:()=>Zie,access:()=>$9t,appendFile:()=>g9t,appendFileSync:()=>$7t,arch:()=>rWt,arrayBuffer:()=>iKt,availableParallelism:()=>p9t,basename:()=>W7t,builtinModules:()=>wWt,callbackify:()=>MWt,channel:()=>zWt,chmod:()=>m9t,chmodSync:()=>d9t,clearInterval:()=>uKt,clearTimeout:()=>cKt,closeSync:()=>w9t,connect:()=>aWt,constants:()=>eKt,copyFileSync:()=>v9t,cpSync:()=>U7t,cpus:()=>Z9t,createConnection:()=>cWt,createGunzip:()=>fWt,createGzip:()=>gWt,createHash:()=>Yie,createHmac:()=>D7t,createInterface:()=>YWt,createReadStream:()=>P9t,createRequire:()=>TWt,createServer:()=>B7t,createWriteStream:()=>R9t,debug:()=>RWt,debuglog:()=>Qie,default:()=>M7t,deflateSync:()=>uWt,deprecate:()=>PWt,deserialize:()=>HWt,dirname:()=>V7t,exec:()=>j9t,execFile:()=>V9t,execFileSync:()=>W9t,execSync:()=>H9t,existsSync:()=>c9t,extname:()=>K7t,fileURLToPath:()=>AWt,finished:()=>a9t,format:()=>bWt,freemem:()=>Q9t,fstatSync:()=>E9t,get:()=>sWt,gunzip:()=>hWt,gunzipSync:()=>dWt,gzip:()=>pWt,gzipSync:()=>mWt,hasSubscribers:()=>GWt,homedir:()=>J9t,hostname:()=>X9t,inflateSync:()=>lWt,inherits:()=>xWt,inspect:()=>Lk,isAbsolute:()=>Y7t,isBuiltin:()=>EWt,isDeepStrictEqual:()=>OWt,isIP:()=>nKt,isIPv4:()=>rKt,isIPv6:()=>tKt,isMainThread:()=>WWt,join:()=>j7t,loadavg:()=>h9t,lookup:()=>LWt,lstatSync:()=>_9t,mkdir:()=>D9t,mkdirSync:()=>S9t,monitorEventLoopDelay:()=>BWt,normalize:()=>Q7t,ok:()=>yWt,open:()=>z9t,openSync:()=>T9t,parentPort:()=>KWt,parse:()=>SWt,pathToFileURL:()=>kWt,performance:()=>$Wt,pipeline:()=>i9t,platform:()=>K9t,posix:()=>Z7t,promises:()=>O7t,promisify:()=>IWt,randomBytes:()=>N7t,randomUUID:()=>L7t,readFile:()=>M9t,readFileSync:()=>l9t,readdir:()=>L9t,readdirSync:()=>C9t,realpath:()=>q9t,realpathSync:()=>y9t,relative:()=>J7t,release:()=>nWt,rename:()=>U9t,renameSync:()=>k9t,request:()=>oWt,resolve:()=>H7t,rm:()=>B9t,rmSync:()=>I9t,rmdirSync:()=>x9t,sep:()=>X7t,serialize:()=>jWt,setImmediate:()=>f9t,setInterval:()=>lKt,setTimeout:()=>aKt,spawn:()=>G9t,stat:()=>N9t,statSync:()=>b9t,strict:()=>vWt,tmpdir:()=>Y9t,toUSVString:()=>DWt,totalmem:()=>eWt,type:()=>tWt,types:()=>NWt,unlink:()=>F9t,unlinkSync:()=>A9t,validateHeaderName:()=>q7t,validateHeaderValue:()=>G7t,webcrypto:()=>F7t,workerData:()=>JWt,writeFile:()=>O9t,writeFileSync:()=>u9t});var mo,bn,M7t,O7t,Yie,D7t,N7t,L7t,F7t,$7t,U7t,B7t,z7t,q7t,G7t,j7t,H7t,V7t,W7t,K7t,J7t,Y7t,X7t,Z7t,Q7t,e9t,t9t,Xie,Zie,r9t,n9t,o9t,s9t,i9t,a9t,c9t,l9t,u9t,d9t,m9t,p9t,h9t,f9t,g9t,y9t,v9t,T9t,w9t,E9t,S9t,b9t,_9t,C9t,A9t,k9t,x9t,I9t,R9t,P9t,M9t,O9t,D9t,N9t,L9t,F9t,$9t,U9t,B9t,z9t,q9t,G9t,j9t,H9t,V9t,W9t,K9t,J9t,Y9t,X9t,Z9t,Q9t,eWt,tWt,rWt,nWt,oWt,sWt,iWt,aWt,cWt,lWt,uWt,dWt,mWt,pWt,hWt,fWt,gWt,yWt,vWt,TWt,wWt,EWt,SWt,bWt,_Wt,CWt,AWt,kWt,xWt,IWt,Qie,RWt,Lk,PWt,MWt,OWt,DWt,NWt,eae,Fk,LWt,FWt,$Wt,UWt,BWt,zWt,qWt,GWt,jWt,HWt,VWt,WWt,KWt,JWt,YWt,XWt,ZWt,QWt,eKt,tKt,rKt,nKt,oKt,sKt,iKt,tae,aKt,cKt,lKt,uKt,dKt,len=b({"node-stub:https"(){mo=()=>{},bn=async()=>{},M7t={},O7t={readFile:bn,writeFile:bn,mkdir:bn,stat:bn,readdir:bn,unlink:bn,access:bn,rm:bn,rename:bn},Yie=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Fk().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}}},D7t=(e,t)=>Yie(e),N7t=e=>new Uint8Array(e||32),L7t=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),F7t=globalThis.crypto,$7t=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},U7t=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},B7t=()=>({listen:mo,close:mo,on:mo}),z7t=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},q7t=mo,G7t=mo,j7t=(...e)=>e.join("/"),H7t=(...e)=>e.join("/"),V7t=e=>e||"",W7t=e=>e?.split?.("/")?.pop?.()||"",K7t=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},J7t=(e,t)=>t||"",Y7t=()=>!1,X7t="/",Z7t={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},Q7t=e=>e,e9t=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},t9t=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},Xie=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Zie=class{write(){return!0}end(){}on(){return this}destroy(){}},r9t=class{push(){}on(){return this}},n9t=class{on(){return this}},o9t=class{pipe(){return this}on(){return this}},s9t=globalThis.ReadableStream||class{},i9t=mo,a9t=mo,c9t=()=>!1,l9t=()=>"",u9t=mo,d9t=mo,m9t=bn,p9t=()=>1,h9t=()=>[0,0,0],f9t=bn,g9t=bn,y9t=e=>e,v9t=mo,T9t=()=>0,w9t=mo,E9t=()=>({}),S9t=mo,b9t=()=>({}),_9t=()=>({isSymbolicLink:()=>!1}),C9t=()=>[],A9t=mo,k9t=mo,x9t=mo,I9t=mo,R9t=()=>new Zie,P9t=()=>new Xie,M9t=bn,O9t=bn,D9t=bn,N9t=bn,L9t=bn,F9t=bn,$9t=bn,U9t=bn,B9t=bn,z9t=async()=>({stat:bn,readFile:bn,close:bn,read:bn,write:bn}),q9t=async e=>e,G9t=()=>({on:mo,stdout:{on:mo},stderr:{on:mo},kill:mo}),j9t=(e,t)=>t?.(null,"",""),H9t=()=>"",V9t=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},W9t=()=>"",K9t="browser",J9t=()=>"/",Y9t=()=>"/tmp",X9t=()=>"browser",Z9t=()=>[{}],Q9t=()=>0,eWt=()=>0,tWt=()=>"Browser",rWt=()=>"wasm",nWt=()=>"0",oWt=()=>({}),sWt=()=>({}),iWt={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},aWt=()=>({}),cWt=()=>({}),lWt=()=>new Uint8Array,uWt=()=>new Uint8Array,dWt=()=>new Uint8Array,mWt=()=>new Uint8Array,pWt=(e,t)=>t?.(null,e),hWt=(e,t)=>t?.(null,e),fWt=()=>({}),gWt=()=>({}),yWt=mo,vWt={},TWt=()=>()=>({}),wWt=[],EWt=()=>!1,SWt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),bWt=()=>"",_Wt=globalThis.URL,CWt=globalThis.URLSearchParams,AWt=e=>typeof e=="string"?e.replace("file://",""):e,kWt=e=>new globalThis.URL("file://"+e),xWt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},IWt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),Qie=e=>{const t=(...r)=>{};return t.enabled=!1,t},RWt=Qie,Lk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},Lk.custom=Symbol.for("nodejs.util.inspect.custom"),Lk.colors={},Lk.styles={},PWt=e=>e,MWt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},OWt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),DWt=e=>String(e),NWt={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},eae=globalThis.TextDecoder,Fk=globalThis.TextEncoder,LWt=(e,t)=>t?.(null,"127.0.0.1",4),FWt=class{},$Wt=globalThis.performance||{now:()=>Date.now()},UWt=class{observe(){}disconnect(){}},BWt=()=>({enable:mo,disable:mo,percentile:()=>0}),zWt=()=>({}),qWt=class{},GWt=()=>!1,jWt=()=>new Uint8Array,HWt=mo,VWt=class{},WWt=!0,KWt=null,JWt=null,YWt=()=>({}),XWt=class{},ZWt=class{},QWt=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 Fk().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 Fk().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 eae().decode(this)}},eKt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},tKt=()=>!1,rKt=()=>!1,nKt=()=>0,oKt=class{},sKt=class{},iKt=async()=>new ArrayBuffer(0),tae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),aKt=(...e)=>tae(globalThis.setTimeout(...e)),cKt=globalThis.clearTimeout,lKt=(...e)=>tae(globalThis.setInterval(...e)),uKt=globalThis.clearInterval,dKt=class{constructor(e){this.type=e}toString(){return this.type}}}}),mKt={};ee(mKt,{Agent:()=>SKt,AsyncLocalStorage:()=>LKt,Buffer:()=>DYt,Channel:()=>bYt,DatabaseSync:()=>OYt,Duplex:()=>$Kt,EventEmitter:()=>NKt,Http2ServerRequest:()=>UYt,Http2ServerResponse:()=>BYt,Interface:()=>MYt,MIMEType:()=>VYt,PassThrough:()=>UKt,PerformanceObserver:()=>wYt,Readable:()=>nae,ReadableStream:()=>BKt,Resolver:()=>vYt,STATUS_CODES:()=>zJt,TextDecoder:()=>iae,TextEncoder:()=>Uk,Transform:()=>FKt,URL:()=>sYt,URLSearchParams:()=>iYt,Worker:()=>kYt,Writable:()=>oae,access:()=>TJt,appendFile:()=>XKt,appendFileSync:()=>TKt,arch:()=>FJt,arrayBuffer:()=>zYt,availableParallelism:()=>KKt,basename:()=>xKt,builtinModules:()=>tYt,callbackify:()=>pYt,channel:()=>SYt,chmod:()=>WKt,chmodSync:()=>VKt,clearInterval:()=>HYt,clearTimeout:()=>GYt,closeSync:()=>tJt,connect:()=>qJt,constants:()=>NYt,copyFileSync:()=>QKt,cpSync:()=>wKt,cpus:()=>OJt,createConnection:()=>GJt,createGunzip:()=>YJt,createGzip:()=>XJt,createHash:()=>rae,createHmac:()=>fKt,createInterface:()=>PYt,createReadStream:()=>mJt,createRequire:()=>eYt,createServer:()=>EKt,createWriteStream:()=>dJt,debug:()=>dYt,debuglog:()=>sae,default:()=>pKt,deflateSync:()=>HJt,deprecate:()=>mYt,deserialize:()=>AYt,dirname:()=>kKt,exec:()=>CJt,execFile:()=>kJt,execFileSync:()=>xJt,execSync:()=>AJt,existsSync:()=>GKt,extname:()=>IKt,fileURLToPath:()=>aYt,finished:()=>qKt,format:()=>oYt,freemem:()=>DJt,fstatSync:()=>rJt,get:()=>BJt,gunzip:()=>JJt,gunzipSync:()=>VJt,gzip:()=>KJt,gzipSync:()=>WJt,hasSubscribers:()=>_Yt,homedir:()=>RJt,hostname:()=>MJt,inflateSync:()=>jJt,inherits:()=>lYt,inspect:()=>$k,isAbsolute:()=>PKt,isBuiltin:()=>rYt,isDeepStrictEqual:()=>hYt,isIP:()=>$Yt,isIPv4:()=>FYt,isIPv6:()=>LYt,isMainThread:()=>xYt,join:()=>CKt,loadavg:()=>JKt,lookup:()=>yYt,lstatSync:()=>sJt,mkdir:()=>fJt,mkdirSync:()=>nJt,monitorEventLoopDelay:()=>EYt,normalize:()=>DKt,ok:()=>ZJt,open:()=>SJt,openSync:()=>eJt,parentPort:()=>IYt,parse:()=>nYt,pathToFileURL:()=>cYt,performance:()=>TYt,pipeline:()=>zKt,platform:()=>IJt,posix:()=>OKt,promises:()=>hKt,promisify:()=>uYt,randomBytes:()=>gKt,randomUUID:()=>yKt,readFile:()=>pJt,readFileSync:()=>jKt,readdir:()=>yJt,readdirSync:()=>iJt,realpath:()=>bJt,realpathSync:()=>ZKt,relative:()=>RKt,release:()=>$Jt,rename:()=>wJt,renameSync:()=>cJt,request:()=>UJt,resolve:()=>AKt,rm:()=>EJt,rmSync:()=>uJt,rmdirSync:()=>lJt,sep:()=>MKt,serialize:()=>CYt,setImmediate:()=>YKt,setInterval:()=>jYt,setTimeout:()=>qYt,spawn:()=>_Jt,stat:()=>gJt,statSync:()=>oJt,strict:()=>QJt,tmpdir:()=>PJt,toUSVString:()=>fYt,totalmem:()=>NJt,type:()=>LJt,types:()=>gYt,unlink:()=>vJt,unlinkSync:()=>aJt,validateHeaderName:()=>bKt,validateHeaderValue:()=>_Kt,webcrypto:()=>vKt,workerData:()=>RYt,writeFile:()=>hJt,writeFileSync:()=>HKt});var po,_n,pKt,hKt,rae,fKt,gKt,yKt,vKt,TKt,wKt,EKt,SKt,bKt,_Kt,CKt,AKt,kKt,xKt,IKt,RKt,PKt,MKt,OKt,DKt,NKt,LKt,nae,oae,FKt,$Kt,UKt,BKt,zKt,qKt,GKt,jKt,HKt,VKt,WKt,KKt,JKt,YKt,XKt,ZKt,QKt,eJt,tJt,rJt,nJt,oJt,sJt,iJt,aJt,cJt,lJt,uJt,dJt,mJt,pJt,hJt,fJt,gJt,yJt,vJt,TJt,wJt,EJt,SJt,bJt,_Jt,CJt,AJt,kJt,xJt,IJt,RJt,PJt,MJt,OJt,DJt,NJt,LJt,FJt,$Jt,UJt,BJt,zJt,qJt,GJt,jJt,HJt,VJt,WJt,KJt,JJt,YJt,XJt,ZJt,QJt,eYt,tYt,rYt,nYt,oYt,sYt,iYt,aYt,cYt,lYt,uYt,sae,dYt,$k,mYt,pYt,hYt,fYt,gYt,iae,Uk,yYt,vYt,TYt,wYt,EYt,SYt,bYt,_Yt,CYt,AYt,kYt,xYt,IYt,RYt,PYt,MYt,OYt,DYt,NYt,LYt,FYt,$Yt,UYt,BYt,zYt,aae,qYt,GYt,jYt,HYt,VYt,uen=b({"node-stub:net"(){po=()=>{},_n=async()=>{},pKt={},hKt={readFile:_n,writeFile:_n,mkdir:_n,stat:_n,readdir:_n,unlink:_n,access:_n,rm:_n,rename:_n},rae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Uk().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}}},fKt=(e,t)=>rae(e),gKt=e=>new Uint8Array(e||32),yKt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),vKt=globalThis.crypto,TKt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},wKt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},EKt=()=>({listen:po,close:po,on:po}),SKt=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},bKt=po,_Kt=po,CKt=(...e)=>e.join("/"),AKt=(...e)=>e.join("/"),kKt=e=>e||"",xKt=e=>e?.split?.("/")?.pop?.()||"",IKt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},RKt=(e,t)=>t||"",PKt=()=>!1,MKt="/",OKt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},DKt=e=>e,NKt=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},LKt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},nae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},oae=class{write(){return!0}end(){}on(){return this}destroy(){}},FKt=class{push(){}on(){return this}},$Kt=class{on(){return this}},UKt=class{pipe(){return this}on(){return this}},BKt=globalThis.ReadableStream||class{},zKt=po,qKt=po,GKt=()=>!1,jKt=()=>"",HKt=po,VKt=po,WKt=_n,KKt=()=>1,JKt=()=>[0,0,0],YKt=_n,XKt=_n,ZKt=e=>e,QKt=po,eJt=()=>0,tJt=po,rJt=()=>({}),nJt=po,oJt=()=>({}),sJt=()=>({isSymbolicLink:()=>!1}),iJt=()=>[],aJt=po,cJt=po,lJt=po,uJt=po,dJt=()=>new oae,mJt=()=>new nae,pJt=_n,hJt=_n,fJt=_n,gJt=_n,yJt=_n,vJt=_n,TJt=_n,wJt=_n,EJt=_n,SJt=async()=>({stat:_n,readFile:_n,close:_n,read:_n,write:_n}),bJt=async e=>e,_Jt=()=>({on:po,stdout:{on:po},stderr:{on:po},kill:po}),CJt=(e,t)=>t?.(null,"",""),AJt=()=>"",kJt=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},xJt=()=>"",IJt="browser",RJt=()=>"/",PJt=()=>"/tmp",MJt=()=>"browser",OJt=()=>[{}],DJt=()=>0,NJt=()=>0,LJt=()=>"Browser",FJt=()=>"wasm",$Jt=()=>"0",UJt=()=>({}),BJt=()=>({}),zJt={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},qJt=()=>({}),GJt=()=>({}),jJt=()=>new Uint8Array,HJt=()=>new Uint8Array,VJt=()=>new Uint8Array,WJt=()=>new Uint8Array,KJt=(e,t)=>t?.(null,e),JJt=(e,t)=>t?.(null,e),YJt=()=>({}),XJt=()=>({}),ZJt=po,QJt={},eYt=()=>()=>({}),tYt=[],rYt=()=>!1,nYt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),oYt=()=>"",sYt=globalThis.URL,iYt=globalThis.URLSearchParams,aYt=e=>typeof e=="string"?e.replace("file://",""):e,cYt=e=>new globalThis.URL("file://"+e),lYt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},uYt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),sae=e=>{const t=(...r)=>{};return t.enabled=!1,t},dYt=sae,$k=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},$k.custom=Symbol.for("nodejs.util.inspect.custom"),$k.colors={},$k.styles={},mYt=e=>e,pYt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},hYt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),fYt=e=>String(e),gYt={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},iae=globalThis.TextDecoder,Uk=globalThis.TextEncoder,yYt=(e,t)=>t?.(null,"127.0.0.1",4),vYt=class{},TYt=globalThis.performance||{now:()=>Date.now()},wYt=class{observe(){}disconnect(){}},EYt=()=>({enable:po,disable:po,percentile:()=>0}),SYt=()=>({}),bYt=class{},_Yt=()=>!1,CYt=()=>new Uint8Array,AYt=po,kYt=class{},xYt=!0,IYt=null,RYt=null,PYt=()=>({}),MYt=class{},OYt=class{},DYt=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 Uk().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 Uk().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 iae().decode(this)}},NYt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},LYt=()=>!1,FYt=()=>!1,$Yt=()=>0,UYt=class{},BYt=class{},zYt=async()=>new ArrayBuffer(0),aae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),qYt=(...e)=>aae(globalThis.setTimeout(...e)),GYt=globalThis.clearTimeout,jYt=(...e)=>aae(globalThis.setInterval(...e)),HYt=globalThis.clearInterval,VYt=class{constructor(e){this.type=e}toString(){return this.type}}}}),WYt={};ee(WYt,{Agent:()=>nXt,AsyncLocalStorage:()=>yXt,Buffer:()=>fQt,Channel:()=>oQt,DatabaseSync:()=>hQt,Duplex:()=>TXt,EventEmitter:()=>gXt,Http2ServerRequest:()=>wQt,Http2ServerResponse:()=>EQt,Interface:()=>pQt,MIMEType:()=>kQt,PassThrough:()=>wXt,PerformanceObserver:()=>tQt,Readable:()=>lae,ReadableStream:()=>EXt,Resolver:()=>QZt,STATUS_CODES:()=>SZt,TextDecoder:()=>mae,TextEncoder:()=>zk,Transform:()=>vXt,URL:()=>BZt,URLSearchParams:()=>zZt,Worker:()=>cQt,Writable:()=>uae,access:()=>eZt,appendFile:()=>MXt,appendFileSync:()=>eXt,arch:()=>vZt,arrayBuffer:()=>SQt,availableParallelism:()=>IXt,basename:()=>lXt,builtinModules:()=>LZt,callbackify:()=>KZt,channel:()=>nQt,chmod:()=>xXt,chmodSync:()=>kXt,clearInterval:()=>AQt,clearTimeout:()=>_Qt,closeSync:()=>LXt,connect:()=>bZt,constants:()=>gQt,copyFileSync:()=>DXt,cpSync:()=>tXt,cpus:()=>hZt,createConnection:()=>_Zt,createGunzip:()=>PZt,createGzip:()=>MZt,createHash:()=>cae,createHmac:()=>YYt,createInterface:()=>mQt,createReadStream:()=>WXt,createRequire:()=>NZt,createServer:()=>rXt,createWriteStream:()=>VXt,debug:()=>VZt,debuglog:()=>dae,default:()=>KYt,deflateSync:()=>AZt,deprecate:()=>WZt,deserialize:()=>aQt,dirname:()=>cXt,exec:()=>iZt,execFile:()=>cZt,execFileSync:()=>lZt,execSync:()=>aZt,existsSync:()=>_Xt,extname:()=>uXt,fileURLToPath:()=>qZt,finished:()=>bXt,format:()=>UZt,freemem:()=>fZt,fstatSync:()=>FXt,get:()=>EZt,gunzip:()=>RZt,gunzipSync:()=>kZt,gzip:()=>IZt,gzipSync:()=>xZt,hasSubscribers:()=>sQt,homedir:()=>dZt,hostname:()=>pZt,inflateSync:()=>CZt,inherits:()=>jZt,inspect:()=>Bk,isAbsolute:()=>mXt,isBuiltin:()=>FZt,isDeepStrictEqual:()=>JZt,isIP:()=>TQt,isIPv4:()=>vQt,isIPv6:()=>yQt,isMainThread:()=>lQt,join:()=>iXt,loadavg:()=>RXt,lookup:()=>ZZt,lstatSync:()=>BXt,mkdir:()=>YXt,mkdirSync:()=>$Xt,monitorEventLoopDelay:()=>rQt,normalize:()=>fXt,ok:()=>OZt,open:()=>nZt,openSync:()=>NXt,parentPort:()=>uQt,parse:()=>$Zt,pathToFileURL:()=>GZt,performance:()=>eQt,pipeline:()=>SXt,platform:()=>uZt,posix:()=>hXt,promises:()=>JYt,promisify:()=>HZt,randomBytes:()=>XYt,randomUUID:()=>ZYt,readFile:()=>KXt,readFileSync:()=>CXt,readdir:()=>ZXt,readdirSync:()=>zXt,realpath:()=>oZt,realpathSync:()=>OXt,relative:()=>dXt,release:()=>TZt,rename:()=>tZt,renameSync:()=>GXt,request:()=>wZt,resolve:()=>aXt,rm:()=>rZt,rmSync:()=>HXt,rmdirSync:()=>jXt,sep:()=>pXt,serialize:()=>iQt,setImmediate:()=>PXt,setInterval:()=>CQt,setTimeout:()=>bQt,spawn:()=>sZt,stat:()=>XXt,statSync:()=>UXt,strict:()=>DZt,tmpdir:()=>mZt,toUSVString:()=>YZt,totalmem:()=>gZt,type:()=>yZt,types:()=>XZt,unlink:()=>QXt,unlinkSync:()=>qXt,validateHeaderName:()=>oXt,validateHeaderValue:()=>sXt,webcrypto:()=>QYt,workerData:()=>dQt,writeFile:()=>JXt,writeFileSync:()=>AXt});var ho,Cn,KYt,JYt,cae,YYt,XYt,ZYt,QYt,eXt,tXt,rXt,nXt,oXt,sXt,iXt,aXt,cXt,lXt,uXt,dXt,mXt,pXt,hXt,fXt,gXt,yXt,lae,uae,vXt,TXt,wXt,EXt,SXt,bXt,_Xt,CXt,AXt,kXt,xXt,IXt,RXt,PXt,MXt,OXt,DXt,NXt,LXt,FXt,$Xt,UXt,BXt,zXt,qXt,GXt,jXt,HXt,VXt,WXt,KXt,JXt,YXt,XXt,ZXt,QXt,eZt,tZt,rZt,nZt,oZt,sZt,iZt,aZt,cZt,lZt,uZt,dZt,mZt,pZt,hZt,fZt,gZt,yZt,vZt,TZt,wZt,EZt,SZt,bZt,_Zt,CZt,AZt,kZt,xZt,IZt,RZt,PZt,MZt,OZt,DZt,NZt,LZt,FZt,$Zt,UZt,BZt,zZt,qZt,GZt,jZt,HZt,dae,VZt,Bk,WZt,KZt,JZt,YZt,XZt,mae,zk,ZZt,QZt,eQt,tQt,rQt,nQt,oQt,sQt,iQt,aQt,cQt,lQt,uQt,dQt,mQt,pQt,hQt,fQt,gQt,yQt,vQt,TQt,wQt,EQt,SQt,pae,bQt,_Qt,CQt,AQt,kQt,den=b({"node-stub:tls"(){ho=()=>{},Cn=async()=>{},KYt={},JYt={readFile:Cn,writeFile:Cn,mkdir:Cn,stat:Cn,readdir:Cn,unlink:Cn,access:Cn,rm:Cn,rename:Cn},cae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new zk().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}}},YYt=(e,t)=>cae(e),XYt=e=>new Uint8Array(e||32),ZYt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),QYt=globalThis.crypto,eXt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},tXt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},rXt=()=>({listen:ho,close:ho,on:ho}),nXt=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},oXt=ho,sXt=ho,iXt=(...e)=>e.join("/"),aXt=(...e)=>e.join("/"),cXt=e=>e||"",lXt=e=>e?.split?.("/")?.pop?.()||"",uXt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},dXt=(e,t)=>t||"",mXt=()=>!1,pXt="/",hXt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},fXt=e=>e,gXt=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},yXt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},lae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},uae=class{write(){return!0}end(){}on(){return this}destroy(){}},vXt=class{push(){}on(){return this}},TXt=class{on(){return this}},wXt=class{pipe(){return this}on(){return this}},EXt=globalThis.ReadableStream||class{},SXt=ho,bXt=ho,_Xt=()=>!1,CXt=()=>"",AXt=ho,kXt=ho,xXt=Cn,IXt=()=>1,RXt=()=>[0,0,0],PXt=Cn,MXt=Cn,OXt=e=>e,DXt=ho,NXt=()=>0,LXt=ho,FXt=()=>({}),$Xt=ho,UXt=()=>({}),BXt=()=>({isSymbolicLink:()=>!1}),zXt=()=>[],qXt=ho,GXt=ho,jXt=ho,HXt=ho,VXt=()=>new uae,WXt=()=>new lae,KXt=Cn,JXt=Cn,YXt=Cn,XXt=Cn,ZXt=Cn,QXt=Cn,eZt=Cn,tZt=Cn,rZt=Cn,nZt=async()=>({stat:Cn,readFile:Cn,close:Cn,read:Cn,write:Cn}),oZt=async e=>e,sZt=()=>({on:ho,stdout:{on:ho},stderr:{on:ho},kill:ho}),iZt=(e,t)=>t?.(null,"",""),aZt=()=>"",cZt=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},lZt=()=>"",uZt="browser",dZt=()=>"/",mZt=()=>"/tmp",pZt=()=>"browser",hZt=()=>[{}],fZt=()=>0,gZt=()=>0,yZt=()=>"Browser",vZt=()=>"wasm",TZt=()=>"0",wZt=()=>({}),EZt=()=>({}),SZt={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},bZt=()=>({}),_Zt=()=>({}),CZt=()=>new Uint8Array,AZt=()=>new Uint8Array,kZt=()=>new Uint8Array,xZt=()=>new Uint8Array,IZt=(e,t)=>t?.(null,e),RZt=(e,t)=>t?.(null,e),PZt=()=>({}),MZt=()=>({}),OZt=ho,DZt={},NZt=()=>()=>({}),LZt=[],FZt=()=>!1,$Zt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),UZt=()=>"",BZt=globalThis.URL,zZt=globalThis.URLSearchParams,qZt=e=>typeof e=="string"?e.replace("file://",""):e,GZt=e=>new globalThis.URL("file://"+e),jZt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},HZt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),dae=e=>{const t=(...r)=>{};return t.enabled=!1,t},VZt=dae,Bk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},Bk.custom=Symbol.for("nodejs.util.inspect.custom"),Bk.colors={},Bk.styles={},WZt=e=>e,KZt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},JZt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),YZt=e=>String(e),XZt={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},mae=globalThis.TextDecoder,zk=globalThis.TextEncoder,ZZt=(e,t)=>t?.(null,"127.0.0.1",4),QZt=class{},eQt=globalThis.performance||{now:()=>Date.now()},tQt=class{observe(){}disconnect(){}},rQt=()=>({enable:ho,disable:ho,percentile:()=>0}),nQt=()=>({}),oQt=class{},sQt=()=>!1,iQt=()=>new Uint8Array,aQt=ho,cQt=class{},lQt=!0,uQt=null,dQt=null,mQt=()=>({}),pQt=class{},hQt=class{},fQt=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 zk().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 zk().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 mae().decode(this)}},gQt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},yQt=()=>!1,vQt=()=>!1,TQt=()=>0,wQt=class{},EQt=class{},SQt=async()=>new ArrayBuffer(0),pae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),bQt=(...e)=>pae(globalThis.setTimeout(...e)),_Qt=globalThis.clearTimeout,CQt=(...e)=>pae(globalThis.setInterval(...e)),AQt=globalThis.clearInterval,kQt=class{constructor(e){this.type=e}toString(){return this.type}}}}),xQt={};ee(xQt,{Agent:()=>$Qt,AsyncLocalStorage:()=>ZQt,Buffer:()=>Ytr,Channel:()=>Utr,DatabaseSync:()=>Jtr,Duplex:()=>eer,EventEmitter:()=>XQt,Http2ServerRequest:()=>trr,Http2ServerResponse:()=>rrr,Interface:()=>Ktr,MIMEType:()=>crr,PassThrough:()=>ter,PerformanceObserver:()=>Ltr,Readable:()=>fae,ReadableStream:()=>rer,Resolver:()=>Dtr,STATUS_CODES:()=>ntr,TextDecoder:()=>vae,TextEncoder:()=>Gk,Transform:()=>QQt,URL:()=>Etr,URLSearchParams:()=>Str,Worker:()=>Gtr,Writable:()=>gae,access:()=>Ner,appendFile:()=>per,appendFileSync:()=>NQt,arch:()=>Qer,arrayBuffer:()=>nrr,availableParallelism:()=>uer,basename:()=>jQt,builtinModules:()=>ytr,callbackify:()=>Itr,channel:()=>$tr,chmod:()=>ler,chmodSync:()=>cer,clearInterval:()=>arr,clearTimeout:()=>srr,closeSync:()=>yer,connect:()=>otr,constants:()=>Xtr,copyFileSync:()=>fer,cpSync:()=>LQt,cpus:()=>Jer,createConnection:()=>str,createGunzip:()=>mtr,createGzip:()=>ptr,createHash:()=>hae,createHmac:()=>PQt,createInterface:()=>Wtr,createReadStream:()=>xer,createRequire:()=>gtr,createServer:()=>FQt,createWriteStream:()=>ker,debug:()=>ktr,debuglog:()=>yae,default:()=>IQt,deflateSync:()=>atr,deprecate:()=>xtr,deserialize:()=>qtr,dirname:()=>GQt,exec:()=>zer,execFile:()=>Ger,execFileSync:()=>jer,execSync:()=>qer,existsSync:()=>ser,extname:()=>HQt,fileURLToPath:()=>btr,finished:()=>oer,format:()=>wtr,freemem:()=>Yer,fstatSync:()=>ver,get:()=>rtr,gunzip:()=>dtr,gunzipSync:()=>ctr,gzip:()=>utr,gzipSync:()=>ltr,hasSubscribers:()=>Btr,homedir:()=>Ver,hostname:()=>Ker,inflateSync:()=>itr,inherits:()=>Ctr,inspect:()=>qk,isAbsolute:()=>WQt,isBuiltin:()=>vtr,isDeepStrictEqual:()=>Rtr,isIP:()=>err,isIPv4:()=>Qtr,isIPv6:()=>Ztr,isMainThread:()=>jtr,join:()=>zQt,loadavg:()=>der,lookup:()=>Otr,lstatSync:()=>Eer,mkdir:()=>Per,mkdirSync:()=>Ter,monitorEventLoopDelay:()=>Ftr,normalize:()=>YQt,ok:()=>htr,open:()=>$er,openSync:()=>ger,parentPort:()=>Htr,parse:()=>Ttr,pathToFileURL:()=>_tr,performance:()=>Ntr,pipeline:()=>ner,platform:()=>Her,posix:()=>JQt,promises:()=>RQt,promisify:()=>Atr,randomBytes:()=>MQt,randomUUID:()=>OQt,readFile:()=>Ier,readFileSync:()=>ier,readdir:()=>Oer,readdirSync:()=>Ser,realpath:()=>Uer,realpathSync:()=>her,relative:()=>VQt,release:()=>etr,rename:()=>Ler,renameSync:()=>_er,request:()=>ttr,resolve:()=>qQt,rm:()=>Fer,rmSync:()=>Aer,rmdirSync:()=>Cer,sep:()=>KQt,serialize:()=>ztr,setImmediate:()=>mer,setInterval:()=>irr,setTimeout:()=>orr,spawn:()=>Ber,stat:()=>Mer,statSync:()=>wer,strict:()=>ftr,tmpdir:()=>Wer,toUSVString:()=>Ptr,totalmem:()=>Xer,type:()=>Zer,types:()=>Mtr,unlink:()=>Der,unlinkSync:()=>ber,validateHeaderName:()=>UQt,validateHeaderValue:()=>BQt,webcrypto:()=>DQt,workerData:()=>Vtr,writeFile:()=>Rer,writeFileSync:()=>aer});var fo,An,IQt,RQt,hae,PQt,MQt,OQt,DQt,NQt,LQt,FQt,$Qt,UQt,BQt,zQt,qQt,GQt,jQt,HQt,VQt,WQt,KQt,JQt,YQt,XQt,ZQt,fae,gae,QQt,eer,ter,rer,ner,oer,ser,ier,aer,cer,ler,uer,der,mer,per,her,fer,ger,yer,ver,Ter,wer,Eer,Ser,ber,_er,Cer,Aer,ker,xer,Ier,Rer,Per,Mer,Oer,Der,Ner,Ler,Fer,$er,Uer,Ber,zer,qer,Ger,jer,Her,Ver,Wer,Ker,Jer,Yer,Xer,Zer,Qer,etr,ttr,rtr,ntr,otr,str,itr,atr,ctr,ltr,utr,dtr,mtr,ptr,htr,ftr,gtr,ytr,vtr,Ttr,wtr,Etr,Str,btr,_tr,Ctr,Atr,yae,ktr,qk,xtr,Itr,Rtr,Ptr,Mtr,vae,Gk,Otr,Dtr,Ntr,Ltr,Ftr,$tr,Utr,Btr,ztr,qtr,Gtr,jtr,Htr,Vtr,Wtr,Ktr,Jtr,Ytr,Xtr,Ztr,Qtr,err,trr,rrr,nrr,Tae,orr,srr,irr,arr,crr,men=b({"node-stub:url"(){fo=()=>{},An=async()=>{},IQt={},RQt={readFile:An,writeFile:An,mkdir:An,stat:An,readdir:An,unlink:An,access:An,rm:An,rename:An},hae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Gk().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}}},PQt=(e,t)=>hae(e),MQt=e=>new Uint8Array(e||32),OQt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),DQt=globalThis.crypto,NQt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},LQt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},FQt=()=>({listen:fo,close:fo,on:fo}),$Qt=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},UQt=fo,BQt=fo,zQt=(...e)=>e.join("/"),qQt=(...e)=>e.join("/"),GQt=e=>e||"",jQt=e=>e?.split?.("/")?.pop?.()||"",HQt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},VQt=(e,t)=>t||"",WQt=()=>!1,KQt="/",JQt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},YQt=e=>e,XQt=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},ZQt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},fae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},gae=class{write(){return!0}end(){}on(){return this}destroy(){}},QQt=class{push(){}on(){return this}},eer=class{on(){return this}},ter=class{pipe(){return this}on(){return this}},rer=globalThis.ReadableStream||class{},ner=fo,oer=fo,ser=()=>!1,ier=()=>"",aer=fo,cer=fo,ler=An,uer=()=>1,der=()=>[0,0,0],mer=An,per=An,her=e=>e,fer=fo,ger=()=>0,yer=fo,ver=()=>({}),Ter=fo,wer=()=>({}),Eer=()=>({isSymbolicLink:()=>!1}),Ser=()=>[],ber=fo,_er=fo,Cer=fo,Aer=fo,ker=()=>new gae,xer=()=>new fae,Ier=An,Rer=An,Per=An,Mer=An,Oer=An,Der=An,Ner=An,Ler=An,Fer=An,$er=async()=>({stat:An,readFile:An,close:An,read:An,write:An}),Uer=async e=>e,Ber=()=>({on:fo,stdout:{on:fo},stderr:{on:fo},kill:fo}),zer=(e,t)=>t?.(null,"",""),qer=()=>"",Ger=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},jer=()=>"",Her="browser",Ver=()=>"/",Wer=()=>"/tmp",Ker=()=>"browser",Jer=()=>[{}],Yer=()=>0,Xer=()=>0,Zer=()=>"Browser",Qer=()=>"wasm",etr=()=>"0",ttr=()=>({}),rtr=()=>({}),ntr={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},otr=()=>({}),str=()=>({}),itr=()=>new Uint8Array,atr=()=>new Uint8Array,ctr=()=>new Uint8Array,ltr=()=>new Uint8Array,utr=(e,t)=>t?.(null,e),dtr=(e,t)=>t?.(null,e),mtr=()=>({}),ptr=()=>({}),htr=fo,ftr={},gtr=()=>()=>({}),ytr=[],vtr=()=>!1,Ttr=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),wtr=()=>"",Etr=globalThis.URL,Str=globalThis.URLSearchParams,btr=e=>typeof e=="string"?e.replace("file://",""):e,_tr=e=>new globalThis.URL("file://"+e),Ctr=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},Atr=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),yae=e=>{const t=(...r)=>{};return t.enabled=!1,t},ktr=yae,qk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},qk.custom=Symbol.for("nodejs.util.inspect.custom"),qk.colors={},qk.styles={},xtr=e=>e,Itr=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},Rtr=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ptr=e=>String(e),Mtr={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},vae=globalThis.TextDecoder,Gk=globalThis.TextEncoder,Otr=(e,t)=>t?.(null,"127.0.0.1",4),Dtr=class{},Ntr=globalThis.performance||{now:()=>Date.now()},Ltr=class{observe(){}disconnect(){}},Ftr=()=>({enable:fo,disable:fo,percentile:()=>0}),$tr=()=>({}),Utr=class{},Btr=()=>!1,ztr=()=>new Uint8Array,qtr=fo,Gtr=class{},jtr=!0,Htr=null,Vtr=null,Wtr=()=>({}),Ktr=class{},Jtr=class{},Ytr=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 Gk().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 Gk().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 vae().decode(this)}},Xtr={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Ztr=()=>!1,Qtr=()=>!1,err=()=>0,trr=class{},rrr=class{},nrr=async()=>new ArrayBuffer(0),Tae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),orr=(...e)=>Tae(globalThis.setTimeout(...e)),srr=globalThis.clearTimeout,irr=(...e)=>Tae(globalThis.setInterval(...e)),arr=globalThis.clearInterval,crr=class{constructor(e){this.type=e}toString(){return this.type}}}}),Gp=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js"(e,t){"use strict";var r=["nodebuffer","arraybuffer","fragments"],n=typeof Blob<"u";n&&r.push("blob"),t.exports={BINARY_TYPES:r,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:n,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}}),PF=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js"(e,t){"use strict";var{EMPTY_BUFFER:r}=Gp(),n=Buffer[Symbol.species];function o(l,u){if(l.length===0)return r;if(l.length===1)return l[0];const d=Buffer.allocUnsafe(u);let m=0;for(let h=0;h<l.length;h++){const f=l[h];d.set(f,m),m+=f.length}return m<u?new n(d.buffer,d.byteOffset,m):d}function s(l,u,d,m,h){for(let f=0;f<h;f++)d[m+f]=l[f]^u[f&3]}function i(l,u){for(let d=0;d<l.length;d++)l[d]^=u[d&3]}function a(l){return l.length===l.buffer.byteLength?l.buffer:l.buffer.slice(l.byteOffset,l.byteOffset+l.length)}function c(l){if(c.readOnly=!0,Buffer.isBuffer(l))return l;let u;return l instanceof ArrayBuffer?u=new n(l):ArrayBuffer.isView(l)?u=new n(l.buffer,l.byteOffset,l.byteLength):(u=Buffer.from(l),c.readOnly=!1),u}if(t.exports={concat:o,mask:s,toArrayBuffer:a,toBuffer:c,unmask:i},!process.env.WS_NO_BUFFER_UTIL)try{const l=Qde("bufferutil");t.exports.mask=function(u,d,m,h,f){f<48?s(u,d,m,h,f):l.mask(u,d,m,h,f)},t.exports.unmask=function(u,d){u.length<32?i(u,d):l.unmask(u,d)}}catch{}}}),pen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js"(e,t){"use strict";var r=Symbol("kDone"),n=Symbol("kRun"),o=class{constructor(s){this[r]=()=>{this.pending--,this[n]()},this.concurrency=s||1/0,this.jobs=[],this.pending=0}add(s){this.jobs.push(s),this[n]()}[n](){if(this.pending!==this.concurrency&&this.jobs.length){const s=this.jobs.shift();this.pending++,s(this[r])}}};t.exports=o}}),jk=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js"(e,t){"use strict";var r=(Kh(),Br(Wh)),n=PF(),o=pen(),{kStatusCode:s}=Gp(),i=Buffer[Symbol.species],a=Buffer.from([0,0,255,255]),c=Symbol("permessage-deflate"),l=Symbol("total-length"),u=Symbol("callback"),d=Symbol("buffers"),m=Symbol("error"),h,f=class{constructor(w){if(this._options=w||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!h){const E=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;h=new o(E)}}static get extensionName(){return"permessage-deflate"}offer(){const w={};return this._options.serverNoContextTakeover&&(w.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(w.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(w.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?w.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(w.client_max_window_bits=!0),w}accept(w){return w=this.normalizeParams(w),this.params=this._isServer?this.acceptAsServer(w):this.acceptAsClient(w),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const w=this._deflate[u];this._deflate.close(),this._deflate=null,w&&w(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(w){const E=this._options,_=w.find(C=>!(E.serverNoContextTakeover===!1&&C.server_no_context_takeover||C.server_max_window_bits&&(E.serverMaxWindowBits===!1||typeof E.serverMaxWindowBits=="number"&&E.serverMaxWindowBits>C.server_max_window_bits)||typeof E.clientMaxWindowBits=="number"&&!C.client_max_window_bits));if(!_)throw new Error("None of the extension offers can be accepted");return E.serverNoContextTakeover&&(_.server_no_context_takeover=!0),E.clientNoContextTakeover&&(_.client_no_context_takeover=!0),typeof E.serverMaxWindowBits=="number"&&(_.server_max_window_bits=E.serverMaxWindowBits),typeof E.clientMaxWindowBits=="number"?_.client_max_window_bits=E.clientMaxWindowBits:(_.client_max_window_bits===!0||E.clientMaxWindowBits===!1)&&delete _.client_max_window_bits,_}acceptAsClient(w){const E=w[0];if(this._options.clientNoContextTakeover===!1&&E.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!E.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(E.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&E.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return E}normalizeParams(w){return w.forEach(E=>{Object.keys(E).forEach(_=>{let C=E[_];if(C.length>1)throw new Error(`Parameter "${_}" must have only a single value`);if(C=C[0],_==="client_max_window_bits"){if(C!==!0){const A=+C;if(!Number.isInteger(A)||A<8||A>15)throw new TypeError(`Invalid value for parameter "${_}": ${C}`);C=A}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${_}": ${C}`)}else if(_==="server_max_window_bits"){const A=+C;if(!Number.isInteger(A)||A<8||A>15)throw new TypeError(`Invalid value for parameter "${_}": ${C}`);C=A}else if(_==="client_no_context_takeover"||_==="server_no_context_takeover"){if(C!==!0)throw new TypeError(`Invalid value for parameter "${_}": ${C}`)}else throw new Error(`Unknown parameter "${_}"`);E[_]=C})}),w}decompress(w,E,_){h.add(C=>{this._decompress(w,E,(A,k)=>{C(),_(A,k)})})}compress(w,E,_){h.add(C=>{this._compress(w,E,(A,k)=>{C(),_(A,k)})})}_decompress(w,E,_){const C=this._isServer?"client":"server";if(!this._inflate){const A=`${C}_max_window_bits`,k=typeof this.params[A]!="number"?r.Z_DEFAULT_WINDOWBITS:this.params[A];this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:k}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on("error",v),this._inflate.on("data",y)}this._inflate[u]=_,this._inflate.write(w),E&&this._inflate.write(a),this._inflate.flush(()=>{const A=this._inflate[m];if(A){this._inflate.close(),this._inflate=null,_(A);return}const k=n.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],E&&this.params[`${C}_no_context_takeover`]&&this._inflate.reset()),_(null,k)})}_compress(w,E,_){const C=this._isServer?"server":"client";if(!this._deflate){const A=`${C}_max_window_bits`,k=typeof this.params[A]!="number"?r.Z_DEFAULT_WINDOWBITS:this.params[A];this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:k}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on("data",g)}this._deflate[u]=_,this._deflate.write(w),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let A=n.concat(this._deflate[d],this._deflate[l]);E&&(A=new i(A.buffer,A.byteOffset,A.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],E&&this.params[`${C}_no_context_takeover`]&&this._deflate.reset(),_(null,A)})}};t.exports=f;function g(w){this[d].push(w),this[l]+=w.length}function y(w){if(this[l]+=w.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(w);return}this[m]=new RangeError("Max payload size exceeded"),this[m].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[m][s]=1009,this.removeListener("data",y),this.reset()}function v(w){if(this[c]._inflate=null,this[m]){this[u](this[m]);return}w[s]=1007,this[u](w)}}}),lrr={};ee(lrr,{Agent:()=>Trr,AsyncLocalStorage:()=>Orr,Buffer:()=>Mor,Channel:()=>Eor,DatabaseSync:()=>Por,Duplex:()=>Nrr,EventEmitter:()=>Mrr,Http2ServerRequest:()=>For,Http2ServerResponse:()=>$or,Interface:()=>Ror,MIMEType:()=>jor,PassThrough:()=>Lrr,PerformanceObserver:()=>vor,Readable:()=>Eae,ReadableStream:()=>Frr,Resolver:()=>gor,STATUS_CODES:()=>$nr,TextDecoder:()=>_ae,TextEncoder:()=>Vk,Transform:()=>Drr,URL:()=>ror,URLSearchParams:()=>nor,Worker:()=>Cor,Writable:()=>Sae,access:()=>gnr,appendFile:()=>Krr,appendFileSync:()=>grr,arch:()=>Dnr,arrayBuffer:()=>Uor,availableParallelism:()=>Hrr,basename:()=>Crr,builtinModules:()=>Znr,callbackify:()=>uor,channel:()=>wor,chmod:()=>jrr,chmodSync:()=>Grr,clearInterval:()=>Gor,clearTimeout:()=>zor,closeSync:()=>Zrr,connect:()=>Unr,constants:()=>Oor,copyFileSync:()=>Yrr,cpSync:()=>yrr,cpus:()=>Rnr,createConnection:()=>Bnr,createGunzip:()=>Wnr,createGzip:()=>Knr,createHash:()=>wae,createHmac:()=>mrr,createInterface:()=>Ior,createReadStream:()=>lnr,createRequire:()=>Xnr,createServer:()=>vrr,createWriteStream:()=>cnr,debug:()=>cor,debuglog:()=>bae,default:()=>urr,deflateSync:()=>qnr,deprecate:()=>lor,deserialize:()=>_or,dirname:()=>_rr,exec:()=>Snr,execFile:()=>_nr,execFileSync:()=>Cnr,execSync:()=>bnr,existsSync:()=>Brr,extname:()=>Arr,fileURLToPath:()=>oor,finished:()=>Urr,format:()=>tor,freemem:()=>Pnr,fstatSync:()=>Qrr,get:()=>Fnr,gunzip:()=>Vnr,gunzipSync:()=>Gnr,gzip:()=>Hnr,gzipSync:()=>jnr,hasSubscribers:()=>Sor,homedir:()=>knr,hostname:()=>Inr,inflateSync:()=>znr,inherits:()=>ior,inspect:()=>Hk,isAbsolute:()=>xrr,isBuiltin:()=>Qnr,isDeepStrictEqual:()=>dor,isIP:()=>Lor,isIPv4:()=>Nor,isIPv6:()=>Dor,isMainThread:()=>Aor,join:()=>Srr,loadavg:()=>Vrr,lookup:()=>hor,lstatSync:()=>rnr,mkdir:()=>mnr,mkdirSync:()=>enr,monitorEventLoopDelay:()=>Tor,normalize:()=>Prr,ok:()=>Jnr,open:()=>Tnr,openSync:()=>Xrr,parentPort:()=>kor,parse:()=>eor,pathToFileURL:()=>sor,performance:()=>yor,pipeline:()=>$rr,platform:()=>Anr,posix:()=>Rrr,promises:()=>drr,promisify:()=>aor,randomBytes:()=>prr,randomUUID:()=>hrr,readFile:()=>unr,readFileSync:()=>zrr,readdir:()=>hnr,readdirSync:()=>nnr,realpath:()=>wnr,realpathSync:()=>Jrr,relative:()=>krr,release:()=>Nnr,rename:()=>ynr,renameSync:()=>snr,request:()=>Lnr,resolve:()=>brr,rm:()=>vnr,rmSync:()=>anr,rmdirSync:()=>inr,sep:()=>Irr,serialize:()=>bor,setImmediate:()=>Wrr,setInterval:()=>qor,setTimeout:()=>Bor,spawn:()=>Enr,stat:()=>pnr,statSync:()=>tnr,strict:()=>Ynr,tmpdir:()=>xnr,toUSVString:()=>mor,totalmem:()=>Mnr,type:()=>Onr,types:()=>por,unlink:()=>fnr,unlinkSync:()=>onr,validateHeaderName:()=>wrr,validateHeaderValue:()=>Err,webcrypto:()=>frr,workerData:()=>xor,writeFile:()=>dnr,writeFileSync:()=>qrr});var go,kn,urr,drr,wae,mrr,prr,hrr,frr,grr,yrr,vrr,Trr,wrr,Err,Srr,brr,_rr,Crr,Arr,krr,xrr,Irr,Rrr,Prr,Mrr,Orr,Eae,Sae,Drr,Nrr,Lrr,Frr,$rr,Urr,Brr,zrr,qrr,Grr,jrr,Hrr,Vrr,Wrr,Krr,Jrr,Yrr,Xrr,Zrr,Qrr,enr,tnr,rnr,nnr,onr,snr,inr,anr,cnr,lnr,unr,dnr,mnr,pnr,hnr,fnr,gnr,ynr,vnr,Tnr,wnr,Enr,Snr,bnr,_nr,Cnr,Anr,knr,xnr,Inr,Rnr,Pnr,Mnr,Onr,Dnr,Nnr,Lnr,Fnr,$nr,Unr,Bnr,znr,qnr,Gnr,jnr,Hnr,Vnr,Wnr,Knr,Jnr,Ynr,Xnr,Znr,Qnr,eor,tor,ror,nor,oor,sor,ior,aor,bae,cor,Hk,lor,uor,dor,mor,por,_ae,Vk,hor,gor,yor,vor,Tor,wor,Eor,Sor,bor,_or,Cor,Aor,kor,xor,Ior,Ror,Por,Mor,Oor,Dor,Nor,Lor,For,$or,Uor,Cae,Bor,zor,qor,Gor,jor,hen=b({"node-stub:buffer"(){go=()=>{},kn=async()=>{},urr={},drr={readFile:kn,writeFile:kn,mkdir:kn,stat:kn,readdir:kn,unlink:kn,access:kn,rm:kn,rename:kn},wae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Vk().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}}},mrr=(e,t)=>wae(e),prr=e=>new Uint8Array(e||32),hrr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),frr=globalThis.crypto,grr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},yrr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},vrr=()=>({listen:go,close:go,on:go}),Trr=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},wrr=go,Err=go,Srr=(...e)=>e.join("/"),brr=(...e)=>e.join("/"),_rr=e=>e||"",Crr=e=>e?.split?.("/")?.pop?.()||"",Arr=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},krr=(e,t)=>t||"",xrr=()=>!1,Irr="/",Rrr={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},Prr=e=>e,Mrr=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},Orr=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},Eae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Sae=class{write(){return!0}end(){}on(){return this}destroy(){}},Drr=class{push(){}on(){return this}},Nrr=class{on(){return this}},Lrr=class{pipe(){return this}on(){return this}},Frr=globalThis.ReadableStream||class{},$rr=go,Urr=go,Brr=()=>!1,zrr=()=>"",qrr=go,Grr=go,jrr=kn,Hrr=()=>1,Vrr=()=>[0,0,0],Wrr=kn,Krr=kn,Jrr=e=>e,Yrr=go,Xrr=()=>0,Zrr=go,Qrr=()=>({}),enr=go,tnr=()=>({}),rnr=()=>({isSymbolicLink:()=>!1}),nnr=()=>[],onr=go,snr=go,inr=go,anr=go,cnr=()=>new Sae,lnr=()=>new Eae,unr=kn,dnr=kn,mnr=kn,pnr=kn,hnr=kn,fnr=kn,gnr=kn,ynr=kn,vnr=kn,Tnr=async()=>({stat:kn,readFile:kn,close:kn,read:kn,write:kn}),wnr=async e=>e,Enr=()=>({on:go,stdout:{on:go},stderr:{on:go},kill:go}),Snr=(e,t)=>t?.(null,"",""),bnr=()=>"",_nr=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},Cnr=()=>"",Anr="browser",knr=()=>"/",xnr=()=>"/tmp",Inr=()=>"browser",Rnr=()=>[{}],Pnr=()=>0,Mnr=()=>0,Onr=()=>"Browser",Dnr=()=>"wasm",Nnr=()=>"0",Lnr=()=>({}),Fnr=()=>({}),$nr={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},Unr=()=>({}),Bnr=()=>({}),znr=()=>new Uint8Array,qnr=()=>new Uint8Array,Gnr=()=>new Uint8Array,jnr=()=>new Uint8Array,Hnr=(e,t)=>t?.(null,e),Vnr=(e,t)=>t?.(null,e),Wnr=()=>({}),Knr=()=>({}),Jnr=go,Ynr={},Xnr=()=>()=>({}),Znr=[],Qnr=()=>!1,eor=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),tor=()=>"",ror=globalThis.URL,nor=globalThis.URLSearchParams,oor=e=>typeof e=="string"?e.replace("file://",""):e,sor=e=>new globalThis.URL("file://"+e),ior=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},aor=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),bae=e=>{const t=(...r)=>{};return t.enabled=!1,t},cor=bae,Hk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},Hk.custom=Symbol.for("nodejs.util.inspect.custom"),Hk.colors={},Hk.styles={},lor=e=>e,uor=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},dor=(e,t)=>JSON.stringify(e)===JSON.stringify(t),mor=e=>String(e),por={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},_ae=globalThis.TextDecoder,Vk=globalThis.TextEncoder,hor=(e,t)=>t?.(null,"127.0.0.1",4),gor=class{},yor=globalThis.performance||{now:()=>Date.now()},vor=class{observe(){}disconnect(){}},Tor=()=>({enable:go,disable:go,percentile:()=>0}),wor=()=>({}),Eor=class{},Sor=()=>!1,bor=()=>new Uint8Array,_or=go,Cor=class{},Aor=!0,kor=null,xor=null,Ior=()=>({}),Ror=class{},Por=class{},Mor=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 Vk().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 Vk().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 _ae().decode(this)}},Oor={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Dor=()=>!1,Nor=()=>!1,Lor=()=>0,For=class{},$or=class{},Uor=async()=>new ArrayBuffer(0),Cae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Bor=(...e)=>Cae(globalThis.setTimeout(...e)),zor=globalThis.clearTimeout,qor=(...e)=>Cae(globalThis.setInterval(...e)),Gor=globalThis.clearInterval,jor=class{constructor(e){this.type=e}toString(){return this.type}}}}),Wk=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js"(e,t){"use strict";var{isUtf8:r}=(hen(),Br(lrr)),{hasBlob:n}=Gp(),o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function s(c){return c>=1e3&&c<=1014&&c!==1004&&c!==1005&&c!==1006||c>=3e3&&c<=4999}function i(c){const l=c.length;let u=0;for(;u<l;)if((c[u]&128)===0)u++;else if((c[u]&224)===192){if(u+1===l||(c[u+1]&192)!==128||(c[u]&254)===192)return!1;u+=2}else if((c[u]&240)===224){if(u+2>=l||(c[u+1]&192)!==128||(c[u+2]&192)!==128||c[u]===224&&(c[u+1]&224)===128||c[u]===237&&(c[u+1]&224)===160)return!1;u+=3}else if((c[u]&248)===240){if(u+3>=l||(c[u+1]&192)!==128||(c[u+2]&192)!==128||(c[u+3]&192)!==128||c[u]===240&&(c[u+1]&240)===128||c[u]===244&&c[u+1]>143||c[u]>244)return!1;u+=4}else return!1;return!0}function a(c){return n&&typeof c=="object"&&typeof c.arrayBuffer=="function"&&typeof c.type=="string"&&typeof c.stream=="function"&&(c[Symbol.toStringTag]==="Blob"||c[Symbol.toStringTag]==="File")}if(t.exports={isBlob:a,isValidStatusCode:s,isValidUTF8:i,tokenChars:o},r)t.exports.isValidUTF8=function(c){return c.length<24?i(c):r(c)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const c=Qde("utf-8-validate");t.exports.isValidUTF8=function(l){return l.length<32?i(l):c(l)}}catch{}}}),Hor=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js"(e,t){"use strict";var{Writable:r}=(Nh(),Br(c0)),n=jk(),{BINARY_TYPES:o,EMPTY_BUFFER:s,kStatusCode:i,kWebSocket:a}=Gp(),{concat:c,toArrayBuffer:l,unmask:u}=PF(),{isValidStatusCode:d,isValidUTF8:m}=Wk(),h=Buffer[Symbol.species],f=0,g=1,y=2,v=3,w=4,E=5,_=6,C=class extends r{constructor(A={}){super(),this._allowSynchronousEvents=A.allowSynchronousEvents!==void 0?A.allowSynchronousEvents:!0,this._binaryType=A.binaryType||o[0],this._extensions=A.extensions||{},this._isServer=!!A.isServer,this._maxBufferedChunks=A.maxBufferedChunks|0,this._maxFragments=A.maxFragments|0,this._maxPayload=A.maxPayload|0,this._skipUTF8Validation=!!A.skipUTF8Validation,this[a]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=f}_write(A,k,R){if(this._opcode===8&&this._state==f)return R();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){R(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=A.length,this._buffers.push(A),this.startLoop(R)}consume(A){if(this._bufferedBytes-=A,A===this._buffers[0].length)return this._buffers.shift();if(A<this._buffers[0].length){const R=this._buffers[0];return this._buffers[0]=new h(R.buffer,R.byteOffset+A,R.length-A),new h(R.buffer,R.byteOffset,A)}const k=Buffer.allocUnsafe(A);do{const R=this._buffers[0],I=k.length-A;A>=R.length?k.set(this._buffers.shift(),I):(k.set(new Uint8Array(R.buffer,R.byteOffset,A),I),this._buffers[0]=new h(R.buffer,R.byteOffset+A,R.length-A)),A-=R.length}while(A>0);return k}startLoop(A){this._loop=!0;do switch(this._state){case f:this.getInfo(A);break;case g:this.getPayloadLength16(A);break;case y:this.getPayloadLength64(A);break;case v:this.getMask();break;case w:this.getData(A);break;case E:case _:this._loop=!1;return}while(this._loop);this._errored||A()}getInfo(A){if(this._bufferedBytes<2){this._loop=!1;return}const k=this.consume(2);if((k[0]&48)!==0){const I=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");A(I);return}const R=(k[0]&64)===64;if(R&&!this._extensions[n.extensionName]){const I=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(I);return}if(this._fin=(k[0]&128)===128,this._opcode=k[0]&15,this._payloadLength=k[1]&127,this._opcode===0){if(R){const I=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(I);return}if(!this._fragmented){const I=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");A(I);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const I=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(I);return}this._compressed=R}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const I=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");A(I);return}if(R){const I=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(I);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const I=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");A(I);return}}else{const I=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(I);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(k[1]&128)===128,this._isServer){if(!this._masked){const I=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");A(I);return}}else if(this._masked){const I=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");A(I);return}this._payloadLength===126?this._state=g:this._payloadLength===127?this._state=y:this.haveLength(A)}getPayloadLength16(A){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(A)}getPayloadLength64(A){if(this._bufferedBytes<8){this._loop=!1;return}const k=this.consume(8),R=k.readUInt32BE(0);if(R>Math.pow(2,21)-1){const I=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");A(I);return}this._payloadLength=R*Math.pow(2,32)+k.readUInt32BE(4),this.haveLength(A)}haveLength(A){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){const k=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");A(k);return}this._masked?this._state=v:this._state=w}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=w}getData(A){let k=s;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}k=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(k,this._mask)}if(this._opcode>7){this.controlMessage(k,A);return}if(this._compressed){this._state=E,this.decompress(k,A);return}if(k.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const R=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");A(R);return}this._messageLength=this._totalPayloadLength,this._fragments.push(k)}this.dataMessage(A)}decompress(A,k){this._extensions[n.extensionName].decompress(A,this._fin,(I,P)=>{if(I)return k(I);if(P.length){if(this._messageLength+=P.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const O=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");k(O);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const O=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");k(O);return}this._fragments.push(P)}this.dataMessage(k),this._state===f&&this.startLoop(k)})}dataMessage(A){if(!this._fin){this._state=f;return}const k=this._messageLength,R=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let I;this._binaryType==="nodebuffer"?I=c(R,k):this._binaryType==="arraybuffer"?I=l(c(R,k)):this._binaryType==="blob"?I=new Blob(R):I=R,this._allowSynchronousEvents?(this.emit("message",I,!0),this._state=f):(this._state=_,setImmediate(()=>{this.emit("message",I,!0),this._state=f,this.startLoop(A)}))}else{const I=c(R,k);if(!this._skipUTF8Validation&&!m(I)){const P=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");A(P);return}this._state===E||this._allowSynchronousEvents?(this.emit("message",I,!1),this._state=f):(this._state=_,setImmediate(()=>{this.emit("message",I,!1),this._state=f,this.startLoop(A)}))}}controlMessage(A,k){if(this._opcode===8){if(A.length===0)this._loop=!1,this.emit("conclude",1005,s),this.end();else{const R=A.readUInt16BE(0);if(!d(R)){const P=this.createError(RangeError,`invalid status code ${R}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");k(P);return}const I=new h(A.buffer,A.byteOffset+2,A.length-2);if(!this._skipUTF8Validation&&!m(I)){const P=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");k(P);return}this._loop=!1,this.emit("conclude",R,I),this.end()}this._state=f;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",A),this._state=f):(this._state=_,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",A),this._state=f,this.startLoop(k)}))}createError(A,k,R,I,P){this._loop=!1,this._errored=!0;const O=new A(R?`Invalid WebSocket frame: ${k}`:k);return Error.captureStackTrace(O,this.createError),O.code=P,O[i]=I,O}};t.exports=C}}),Vor=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js"(e,t){"use strict";var{Duplex:r}=(Nh(),Br(c0)),{randomFillSync:n}=(Dt(),Br(AS)),{types:{isUint8Array:o}}=(y4(),Br(g4)),s=jk(),{EMPTY_BUFFER:i,kWebSocket:a,NOOP:c}=Gp(),{isBlob:l,isValidStatusCode:u}=Wk(),{mask:d,toBuffer:m}=PF(),h=Symbol("kByteLength"),f=Buffer.alloc(4),g=8*1024,y,v=g,w=0,E=1,_=2,C=class vy{constructor(I,P,O){this._extensions=P||{},O&&(this._generateMask=O,this._maskBuffer=Buffer.alloc(4)),this._socket=I,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=c,this[a]=void 0}static frame(I,P){let O,U=!1,M=2,F=!1;P.mask&&(O=P.maskBuffer||f,P.generateMask?P.generateMask(O):(v===g&&(y===void 0&&(y=Buffer.alloc(g)),n(y,0,g),v=0),O[0]=y[v++],O[1]=y[v++],O[2]=y[v++],O[3]=y[v++]),F=(O[0]|O[1]|O[2]|O[3])===0,M=6);let N;typeof I=="string"?(!P.mask||F)&&P[h]!==void 0?N=P[h]:(I=Buffer.from(I),N=I.length):(N=I.length,U=P.mask&&P.readOnly&&!F);let L=N;N>=65536?(M+=8,L=127):N>125&&(M+=2,L=126);const q=Buffer.allocUnsafe(U?N+M:M);return q[0]=P.fin?P.opcode|128:P.opcode,P.rsv1&&(q[0]|=64),q[1]=L,L===126?q.writeUInt16BE(N,2):L===127&&(q[2]=q[3]=0,q.writeUIntBE(N,4,6)),P.mask?(q[1]|=128,q[M-4]=O[0],q[M-3]=O[1],q[M-2]=O[2],q[M-1]=O[3],F?[q,I]:U?(d(I,O,q,M,N),[q]):(d(I,O,I,0,N),[q,I])):[q,I]}close(I,P,O,U){let M;if(I===void 0)M=i;else{if(typeof I!="number"||!u(I))throw new TypeError("First argument must be a valid error code number");if(P===void 0||!P.length)M=Buffer.allocUnsafe(2),M.writeUInt16BE(I,0);else{const N=Buffer.byteLength(P);if(N>123)throw new RangeError("The message must not be greater than 123 bytes");if(M=Buffer.allocUnsafe(2+N),M.writeUInt16BE(I,0),typeof P=="string")M.write(P,2);else if(o(P))M.set(P,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}const F={[h]:M.length,fin:!0,generateMask:this._generateMask,mask:O,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,M,!1,F,U]):this.sendFrame(vy.frame(M,F),U)}ping(I,P,O){let U,M;if(typeof I=="string"?(U=Buffer.byteLength(I),M=!1):l(I)?(U=I.size,M=!1):(I=m(I),U=I.length,M=m.readOnly),U>125)throw new RangeError("The data size must not be greater than 125 bytes");const F={[h]:U,fin:!0,generateMask:this._generateMask,mask:P,maskBuffer:this._maskBuffer,opcode:9,readOnly:M,rsv1:!1};l(I)?this._state!==w?this.enqueue([this.getBlobData,I,!1,F,O]):this.getBlobData(I,!1,F,O):this._state!==w?this.enqueue([this.dispatch,I,!1,F,O]):this.sendFrame(vy.frame(I,F),O)}pong(I,P,O){let U,M;if(typeof I=="string"?(U=Buffer.byteLength(I),M=!1):l(I)?(U=I.size,M=!1):(I=m(I),U=I.length,M=m.readOnly),U>125)throw new RangeError("The data size must not be greater than 125 bytes");const F={[h]:U,fin:!0,generateMask:this._generateMask,mask:P,maskBuffer:this._maskBuffer,opcode:10,readOnly:M,rsv1:!1};l(I)?this._state!==w?this.enqueue([this.getBlobData,I,!1,F,O]):this.getBlobData(I,!1,F,O):this._state!==w?this.enqueue([this.dispatch,I,!1,F,O]):this.sendFrame(vy.frame(I,F),O)}send(I,P,O){const U=this._extensions[s.extensionName];let M=P.binary?2:1,F=P.compress,N,L;typeof I=="string"?(N=Buffer.byteLength(I),L=!1):l(I)?(N=I.size,L=!1):(I=m(I),N=I.length,L=m.readOnly),this._firstFragment?(this._firstFragment=!1,F&&U&&U.params[U._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(F=N>=U._threshold),this._compress=F):(F=!1,M=0),P.fin&&(this._firstFragment=!0);const q={[h]:N,fin:P.fin,generateMask:this._generateMask,mask:P.mask,maskBuffer:this._maskBuffer,opcode:M,readOnly:L,rsv1:F};l(I)?this._state!==w?this.enqueue([this.getBlobData,I,this._compress,q,O]):this.getBlobData(I,this._compress,q,O):this._state!==w?this.enqueue([this.dispatch,I,this._compress,q,O]):this.dispatch(I,this._compress,q,O)}getBlobData(I,P,O,U){this._bufferedBytes+=O[h],this._state=_,I.arrayBuffer().then(M=>{if(this._socket.destroyed){const N=new Error("The socket was closed while the blob was being read");process.nextTick(A,this,N,U);return}this._bufferedBytes-=O[h];const F=m(M);P?this.dispatch(F,P,O,U):(this._state=w,this.sendFrame(vy.frame(F,O),U),this.dequeue())}).catch(M=>{process.nextTick(k,this,M,U)})}dispatch(I,P,O,U){if(!P){this.sendFrame(vy.frame(I,O),U);return}const M=this._extensions[s.extensionName];this._bufferedBytes+=O[h],this._state=E,M.compress(I,O.fin,(F,N)=>{if(this._socket.destroyed){const L=new Error("The socket was closed while data was being compressed");A(this,L,U);return}this._bufferedBytes-=O[h],this._state=w,O.readOnly=!1,this.sendFrame(vy.frame(N,O),U),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){const I=this._queue.shift();this._bufferedBytes-=I[3][h],Reflect.apply(I[0],this,I.slice(1))}}enqueue(I){this._bufferedBytes+=I[3][h],this._queue.push(I)}sendFrame(I,P){I.length===2?(this._socket.cork(),this._socket.write(I[0]),this._socket.write(I[1],P),this._socket.uncork()):this._socket.write(I[0],P)}};t.exports=C;function A(R,I,P){typeof P=="function"&&P(I);for(let O=0;O<R._queue.length;O++){const U=R._queue[O],M=U[U.length-1];typeof M=="function"&&M(I)}}function k(R,I,P){A(R,I,P),R.onerror(I)}}}),fen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js"(e,t){"use strict";var{kForOnEventAttribute:r,kListener:n}=Gp(),o=Symbol("kCode"),s=Symbol("kData"),i=Symbol("kError"),a=Symbol("kMessage"),c=Symbol("kReason"),l=Symbol("kTarget"),u=Symbol("kType"),d=Symbol("kWasClean"),m=class{constructor(w){this[l]=null,this[u]=w}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(m.prototype,"target",{enumerable:!0}),Object.defineProperty(m.prototype,"type",{enumerable:!0});var h=class extends m{constructor(w,E={}){super(w),this[o]=E.code===void 0?0:E.code,this[c]=E.reason===void 0?"":E.reason,this[d]=E.wasClean===void 0?!1:E.wasClean}get code(){return this[o]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(h.prototype,"code",{enumerable:!0}),Object.defineProperty(h.prototype,"reason",{enumerable:!0}),Object.defineProperty(h.prototype,"wasClean",{enumerable:!0});var f=class extends m{constructor(w,E={}){super(w),this[i]=E.error===void 0?null:E.error,this[a]=E.message===void 0?"":E.message}get error(){return this[i]}get message(){return this[a]}};Object.defineProperty(f.prototype,"error",{enumerable:!0}),Object.defineProperty(f.prototype,"message",{enumerable:!0});var g=class extends m{constructor(w,E={}){super(w),this[s]=E.data===void 0?null:E.data}get data(){return this[s]}};Object.defineProperty(g.prototype,"data",{enumerable:!0});var y={addEventListener(w,E,_={}){for(const A of this.listeners(w))if(!_[r]&&A[n]===E&&!A[r])return;let C;if(w==="message")C=function(k,R){const I=new g("message",{data:R?k:k.toString()});I[l]=this,v(E,this,I)};else if(w==="close")C=function(k,R){const I=new h("close",{code:k,reason:R.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});I[l]=this,v(E,this,I)};else if(w==="error")C=function(k){const R=new f("error",{error:k,message:k.message});R[l]=this,v(E,this,R)};else if(w==="open")C=function(){const k=new m("open");k[l]=this,v(E,this,k)};else return;C[r]=!!_[r],C[n]=E,_.once?this.once(w,C):this.on(w,C)},removeEventListener(w,E){for(const _ of this.listeners(w))if(_[n]===E&&!_[r]){this.removeListener(w,_);break}}};t.exports={CloseEvent:h,ErrorEvent:f,Event:m,EventTarget:y,MessageEvent:g};function v(w,E,_){typeof w=="object"&&w.handleEvent?w.handleEvent.call(w,_):w.call(E,_)}}}),Aae=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js"(e,t){"use strict";var{tokenChars:r}=Wk();function n(i,a,c){i[a]===void 0?i[a]=[c]:i[a].push(c)}function o(i){const a=Object.create(null);let c=Object.create(null),l=!1,u=!1,d=!1,m,h,f=-1,g=-1,y=-1,v=0;for(;v<i.length;v++)if(g=i.charCodeAt(v),m===void 0)if(y===-1&&r[g]===1)f===-1&&(f=v);else if(v!==0&&(g===32||g===9))y===-1&&f!==-1&&(y=v);else if(g===59||g===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${v}`);y===-1&&(y=v);const E=i.slice(f,y);g===44?(n(a,E,c),c=Object.create(null)):m=E,f=y=-1}else throw new SyntaxError(`Unexpected character at index ${v}`);else if(h===void 0)if(y===-1&&r[g]===1)f===-1&&(f=v);else if(g===32||g===9)y===-1&&f!==-1&&(y=v);else if(g===59||g===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${v}`);y===-1&&(y=v),n(c,i.slice(f,y),!0),g===44&&(n(a,m,c),c=Object.create(null),m=void 0),f=y=-1}else if(g===61&&f!==-1&&y===-1)h=i.slice(f,v),f=y=-1;else throw new SyntaxError(`Unexpected character at index ${v}`);else if(u){if(r[g]!==1)throw new SyntaxError(`Unexpected character at index ${v}`);f===-1?f=v:l||(l=!0),u=!1}else if(d)if(r[g]===1)f===-1&&(f=v);else if(g===34&&f!==-1)d=!1,y=v;else if(g===92)u=!0;else throw new SyntaxError(`Unexpected character at index ${v}`);else if(g===34&&i.charCodeAt(v-1)===61)d=!0;else if(y===-1&&r[g]===1)f===-1&&(f=v);else if(f!==-1&&(g===32||g===9))y===-1&&(y=v);else if(g===59||g===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${v}`);y===-1&&(y=v);let E=i.slice(f,y);l&&(E=E.replace(/\\/g,""),l=!1),n(c,h,E),g===44&&(n(a,m,c),c=Object.create(null),m=void 0),h=void 0,f=y=-1}else throw new SyntaxError(`Unexpected character at index ${v}`);if(f===-1||d||g===32||g===9)throw new SyntaxError("Unexpected end of input");y===-1&&(y=v);const w=i.slice(f,y);return m===void 0?n(a,w,c):(h===void 0?n(c,w,!0):l?n(c,h,w.replace(/\\/g,"")):n(c,h,w),n(a,m,c)),a}function s(i){return Object.keys(i).map(a=>{let c=i[a];return Array.isArray(c)||(c=[c]),c.map(l=>[a].concat(Object.keys(l).map(u=>{let d=l[u];return Array.isArray(d)||(d=[d]),d.map(m=>m===!0?u:`${u}=${m}`).join("; ")})).join("; ")).join(", ")}).join(", ")}t.exports={format:s,parse:o}}}),kae=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js"(e,t){"use strict";var r=(Mn(),Br(NH)),n=(len(),Br(P7t)),o=(lQ(),Br(rQ)),s=(uen(),Br(mKt)),i=(den(),Br(WYt)),{randomBytes:a,createHash:c}=(Dt(),Br(AS)),{Duplex:l,Readable:u}=(Nh(),Br(c0)),{URL:d}=(men(),Br(xQt)),m=jk(),h=Hor(),f=Vor(),{isBlob:g}=Wk(),{BINARY_TYPES:y,CLOSE_TIMEOUT:v,EMPTY_BUFFER:w,GUID:E,kForOnEventAttribute:_,kListener:C,kStatusCode:A,kWebSocket:k,NOOP:R}=Gp(),{EventTarget:{addEventListener:I,removeEventListener:P}}=fen(),{format:O,parse:U}=Aae(),{toBuffer:M}=PF(),F=Symbol("kAborted"),N=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],q=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,B=class qo extends r{constructor(V,se,oe){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=w,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=qo.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,V!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,se===void 0?se=[]:Array.isArray(se)||(typeof se=="object"&&se!==null?(oe=se,se=[]):se=[se]),H(this,V,se,oe)):(this._autoPong=oe.autoPong,this._closeTimeout=oe.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(V){y.includes(V)&&(this._binaryType=V,this._receiver&&(this._receiver._binaryType=V))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(V,se,oe){const Z=new h({allowSynchronousEvents:oe.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:oe.maxBufferedChunks,maxFragments:oe.maxFragments,maxPayload:oe.maxPayload,skipUTF8Validation:oe.skipUTF8Validation}),ie=new f(V,this._extensions,oe.generateMask);this._receiver=Z,this._sender=ie,this._socket=V,Z[k]=this,ie[k]=this,V[k]=this,Z.on("conclude",Ee),Z.on("drain",le),Z.on("error",ae),Z.on("message",Ae),Z.on("ping",Te),Z.on("pong",he),ie.onerror=De,V.setTimeout&&V.setTimeout(0),V.setNoDelay&&V.setNoDelay(),se.length>0&&V.unshift(se),V.on("close",gt),V.on("data",$e),V.on("end",xe),V.on("error",ve),this._readyState=qo.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=qo.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[m.extensionName]&&this._extensions[m.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=qo.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(V,se){if(this.readyState!==qo.CLOSED){if(this.readyState===qo.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===qo.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=qo.CLOSING,this._sender.close(V,se,!this._isServer,oe=>{oe||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ye(this)}}pause(){this.readyState===qo.CONNECTING||this.readyState===qo.CLOSED||(this._paused=!0,this._socket.pause())}ping(V,se,oe){if(this.readyState===qo.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof V=="function"?(oe=V,V=se=void 0):typeof se=="function"&&(oe=se,se=void 0),typeof V=="number"&&(V=V.toString()),this.readyState!==qo.OPEN){Ie(this,V,oe);return}se===void 0&&(se=!this._isServer),this._sender.ping(V||w,se,oe)}pong(V,se,oe){if(this.readyState===qo.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof V=="function"?(oe=V,V=se=void 0):typeof se=="function"&&(oe=se,se=void 0),typeof V=="number"&&(V=V.toString()),this.readyState!==qo.OPEN){Ie(this,V,oe);return}se===void 0&&(se=!this._isServer),this._sender.pong(V||w,se,oe)}resume(){this.readyState===qo.CONNECTING||this.readyState===qo.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(V,se,oe){if(this.readyState===qo.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof se=="function"&&(oe=se,se={}),typeof V=="number"&&(V=V.toString()),this.readyState!==qo.OPEN){Ie(this,V,oe);return}const Z={binary:typeof V!="string",mask:!this._isServer,compress:!0,fin:!0,...se};this._extensions[m.extensionName]||(Z.compress=!1),this._sender.send(V||w,Z,oe)}terminate(){if(this.readyState!==qo.CLOSED){if(this.readyState===qo.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=qo.CLOSING,this._socket.destroy())}}};Object.defineProperty(B,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")}),Object.defineProperty(B.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")}),Object.defineProperty(B,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")}),Object.defineProperty(B.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")}),Object.defineProperty(B,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")}),Object.defineProperty(B.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")}),Object.defineProperty(B,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")}),Object.defineProperty(B.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(J=>{Object.defineProperty(B.prototype,J,{enumerable:!0})}),["open","error","close","message"].forEach(J=>{Object.defineProperty(B.prototype,`on${J}`,{enumerable:!0,get(){for(const V of this.listeners(J))if(V[_])return V[C];return null},set(V){for(const se of this.listeners(J))if(se[_]){this.removeListener(J,se);break}typeof V=="function"&&this.addEventListener(J,V,{[_]:!0})}})}),B.prototype.addEventListener=I,B.prototype.removeEventListener=P,t.exports=B;function H(J,V,se,oe){const Z={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:N[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...oe,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(J._autoPong=Z.autoPong,J._closeTimeout=Z.closeTimeout,!N.includes(Z.protocolVersion))throw new RangeError(`Unsupported protocol version: ${Z.protocolVersion} (supported versions: ${N.join(", ")})`);let ie;if(V instanceof d)ie=V;else try{ie=new d(V)}catch{throw new SyntaxError(`Invalid URL: ${V}`)}ie.protocol==="http:"?ie.protocol="ws:":ie.protocol==="https:"&&(ie.protocol="wss:"),J._url=ie.href;const W=ie.protocol==="wss:",re=ie.protocol==="ws+unix:";let ye;if(ie.protocol!=="ws:"&&!W&&!re?ye=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:re&&!ie.pathname?ye="The URL's pathname is empty":ie.hash&&(ye="The URL contains a fragment identifier"),ye){const $=new SyntaxError(ye);if(J._redirects===0)throw $;G(J,$);return}const Re=W?443:80,x=a(16).toString("base64"),K=W?n.request:o.request,Se=new Set;let ke;if(Z.createConnection=Z.createConnection||(W?ce:X),Z.defaultPort=Z.defaultPort||Re,Z.port=ie.port||Re,Z.host=ie.hostname.startsWith("[")?ie.hostname.slice(1,-1):ie.hostname,Z.headers={...Z.headers,"Sec-WebSocket-Version":Z.protocolVersion,"Sec-WebSocket-Key":x,Connection:"Upgrade",Upgrade:"websocket"},Z.path=ie.pathname+ie.search,Z.timeout=Z.handshakeTimeout,Z.perMessageDeflate&&(ke=new m({...Z.perMessageDeflate,isServer:!1,maxPayload:Z.maxPayload}),Z.headers["Sec-WebSocket-Extensions"]=O({[m.extensionName]:ke.offer()})),se.length){for(const $ of se){if(typeof $!="string"||!q.test($)||Se.has($))throw new SyntaxError("An invalid or duplicated subprotocol was specified");Se.add($)}Z.headers["Sec-WebSocket-Protocol"]=se.join(",")}if(Z.origin&&(Z.protocolVersion<13?Z.headers["Sec-WebSocket-Origin"]=Z.origin:Z.headers.Origin=Z.origin),(ie.username||ie.password)&&(Z.auth=`${ie.username}:${ie.password}`),re){const $=Z.path.split(":");Z.socketPath=$[0],Z.path=$[1]}let fe;if(Z.followRedirects){if(J._redirects===0){J._originalIpc=re,J._originalSecure=W,J._originalHostOrSocketPath=re?Z.socketPath:ie.host;const $=oe&&oe.headers;if(oe={...oe,headers:{}},$)for(const[Y,de]of Object.entries($))oe.headers[Y.toLowerCase()]=de}else if(J.listenerCount("redirect")===0){const $=re?J._originalIpc?Z.socketPath===J._originalHostOrSocketPath:!1:J._originalIpc?!1:ie.host===J._originalHostOrSocketPath;(!$||J._originalSecure&&!W)&&(delete Z.headers.authorization,delete Z.headers.cookie,$||delete Z.headers.host,Z.auth=void 0)}Z.auth&&!oe.headers.authorization&&(oe.headers.authorization="Basic "+Buffer.from(Z.auth).toString("base64")),fe=J._req=K(Z),J._redirects&&J.emit("redirect",J.url,fe)}else fe=J._req=K(Z);Z.timeout&&fe.on("timeout",()=>{Q(J,fe,"Opening handshake has timed out")}),fe.on("error",$=>{fe===null||fe[F]||(fe=J._req=null,G(J,$))}),fe.on("response",$=>{const Y=$.headers.location,de=$.statusCode;if(Y&&Z.followRedirects&&de>=300&&de<400){if(++J._redirects>Z.maxRedirects){Q(J,fe,"Maximum redirects exceeded");return}fe.abort();let ge;try{ge=new d(Y,V)}catch{const we=new SyntaxError(`Invalid URL: ${Y}`);G(J,we);return}H(J,ge,se,oe)}else J.emit("unexpected-response",fe,$)||Q(J,fe,`Unexpected server response: ${$.statusCode}`)}),fe.on("upgrade",($,Y,de)=>{if(J.emit("upgrade",$),J.readyState!==B.CONNECTING)return;fe=J._req=null;const ge=$.headers.upgrade;if(ge===void 0||ge.toLowerCase()!=="websocket"){Q(J,Y,"Invalid Upgrade header");return}const be=c("sha1").update(x+E).digest("base64");if($.headers["sec-websocket-accept"]!==be){Q(J,Y,"Invalid Sec-WebSocket-Accept header");return}const we=$.headers["sec-websocket-protocol"];let ue;if(we!==void 0?Se.size?Se.has(we)||(ue="Server sent an invalid subprotocol"):ue="Server sent a subprotocol but none was requested":Se.size&&(ue="Server sent no subprotocol"),ue){Q(J,Y,ue);return}we&&(J._protocol=we);const Le=$.headers["sec-websocket-extensions"];if(Le!==void 0){if(!ke){Q(J,Y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let at;try{at=U(Le)}catch{Q(J,Y,"Invalid Sec-WebSocket-Extensions header");return}const vt=Object.keys(at);if(vt.length!==1||vt[0]!==m.extensionName){Q(J,Y,"Server indicated an extension that was not requested");return}try{ke.accept(at[m.extensionName])}catch{Q(J,Y,"Invalid Sec-WebSocket-Extensions header");return}J._extensions[m.extensionName]=ke}J.setSocket(Y,de,{allowSynchronousEvents:Z.allowSynchronousEvents,generateMask:Z.generateMask,maxBufferedChunks:Z.maxBufferedChunks,maxFragments:Z.maxFragments,maxPayload:Z.maxPayload,skipUTF8Validation:Z.skipUTF8Validation})}),Z.finishRequest?Z.finishRequest(fe,J):fe.end()}function G(J,V){J._readyState=B.CLOSING,J._errorEmitted=!0,J.emit("error",V),J.emitClose()}function X(J){return J.path=J.socketPath,s.connect(J)}function ce(J){return J.path=void 0,!J.servername&&J.servername!==""&&(J.servername=s.isIP(J.host)?"":J.host),i.connect(J)}function Q(J,V,se){J._readyState=B.CLOSING;const oe=new Error(se);Error.captureStackTrace(oe,Q),V.setHeader?(V[F]=!0,V.abort(),V.socket&&!V.socket.destroyed&&V.socket.destroy(),process.nextTick(G,J,oe)):(V.destroy(oe),V.once("error",J.emit.bind(J,"error")),V.once("close",J.emitClose.bind(J)))}function Ie(J,V,se){if(V){const oe=g(V)?V.size:M(V).length;J._socket?J._sender._bufferedBytes+=oe:J._bufferedAmount+=oe}if(se){const oe=new Error(`WebSocket is not open: readyState ${J.readyState} (${L[J.readyState]})`);process.nextTick(se,oe)}}function Ee(J,V){const se=this[k];se._closeFrameReceived=!0,se._closeMessage=V,se._closeCode=J,se._socket[k]!==void 0&&(se._socket.removeListener("data",$e),process.nextTick(Oe,se._socket),J===1005?se.close():se.close(J,V))}function le(){const J=this[k];J.isPaused||J._socket.resume()}function ae(J){const V=this[k];V._socket[k]!==void 0&&(V._socket.removeListener("data",$e),process.nextTick(Oe,V._socket),V.close(J[A])),V._errorEmitted||(V._errorEmitted=!0,V.emit("error",J))}function Pe(){this[k].emitClose()}function Ae(J,V){this[k].emit("message",J,V)}function Te(J){const V=this[k];V._autoPong&&V.pong(J,!this._isServer,R),V.emit("ping",J)}function he(J){this[k].emit("pong",J)}function Oe(J){J.resume()}function De(J){const V=this[k];V.readyState!==B.CLOSED&&(V.readyState===B.OPEN&&(V._readyState=B.CLOSING,Ye(V)),this._socket.end(),V._errorEmitted||(V._errorEmitted=!0,V.emit("error",J)))}function Ye(J){J._closeTimer=setTimeout(J._socket.destroy.bind(J._socket),J._closeTimeout)}function gt(){const J=this[k];if(this.removeListener("close",gt),this.removeListener("data",$e),this.removeListener("end",xe),J._readyState=B.CLOSING,!this._readableState.endEmitted&&!J._closeFrameReceived&&!J._receiver._writableState.errorEmitted&&this._readableState.length!==0){const V=this.read(this._readableState.length);J._receiver.write(V)}J._receiver.end(),this[k]=void 0,clearTimeout(J._closeTimer),J._receiver._writableState.finished||J._receiver._writableState.errorEmitted?J.emitClose():(J._receiver.on("error",Pe),J._receiver.on("finish",Pe))}function $e(J){this[k]._receiver.write(J)||this.pause()}function xe(){const J=this[k];J._readyState=B.CLOSING,J._receiver.end(),this.end()}function ve(){const J=this[k];this.removeListener("error",ve),this.on("error",R),J&&(J._readyState=B.CLOSING,this.destroy())}}}),gen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js"(e,t){"use strict";var r=kae(),{Duplex:n}=(Nh(),Br(c0));function o(c){c.emit("close")}function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}function i(c){this.removeListener("error",i),this.destroy(),this.listenerCount("error")===0&&this.emit("error",c)}function a(c,l){let u=!0;const d=new n({...l,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return c.on("message",function(h,f){const g=!f&&d._readableState.objectMode?h.toString():h;d.push(g)||c.pause()}),c.once("error",function(h){d.destroyed||(u=!1,d.destroy(h))}),c.once("close",function(){d.destroyed||d.push(null)}),d._destroy=function(m,h){if(c.readyState===c.CLOSED){h(m),process.nextTick(o,d);return}let f=!1;c.once("error",function(y){f=!0,h(y)}),c.once("close",function(){f||h(m),process.nextTick(o,d)}),u&&c.terminate()},d._final=function(m){if(c.readyState===c.CONNECTING){c.once("open",function(){d._final(m)});return}c._socket!==null&&(c._socket._writableState.finished?(m(),d._readableState.endEmitted&&d.destroy()):(c._socket.once("finish",function(){m()}),c.close()))},d._read=function(){c.isPaused&&c.resume()},d._write=function(m,h,f){if(c.readyState===c.CONNECTING){c.once("open",function(){d._write(m,h,f)});return}c.send(m,f)},d.on("end",s),d.on("error",i),d}t.exports=a}}),Wor=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js"(e,t){"use strict";var{tokenChars:r}=Wk();function n(o){const s=new Set;let i=-1,a=-1,c=0;for(c;c<o.length;c++){const u=o.charCodeAt(c);if(a===-1&&r[u]===1)i===-1&&(i=c);else if(c!==0&&(u===32||u===9))a===-1&&i!==-1&&(a=c);else if(u===44){if(i===-1)throw new SyntaxError(`Unexpected character at index ${c}`);a===-1&&(a=c);const d=o.slice(i,a);if(s.has(d))throw new SyntaxError(`The "${d}" subprotocol is duplicated`);s.add(d),i=a=-1}else throw new SyntaxError(`Unexpected character at index ${c}`)}if(i===-1||a!==-1)throw new SyntaxError("Unexpected end of input");const l=o.slice(i,c);if(s.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);return s.add(l),s}t.exports={parse:n}}}),yen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js"(e,t){"use strict";var r=(Mn(),Br(NH)),n=(lQ(),Br(rQ)),{Duplex:o}=(Nh(),Br(c0)),{createHash:s}=(Dt(),Br(AS)),i=Aae(),a=jk(),c=Wor(),l=kae(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:m}=Gp(),h=/^[+/0-9A-Za-z]{22}==$/,f=0,g=1,y=2,v=class extends r{constructor(k,R){if(super(),k={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...k},k.port==null&&!k.server&&!k.noServer||k.port!=null&&(k.server||k.noServer)||k.server&&k.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(k.port!=null?(this._server=n.createServer((I,P)=>{const O=n.STATUS_CODES[426];P.writeHead(426,{"Content-Length":O.length,"Content-Type":"text/plain"}),P.end(O)}),this._server.listen(k.port,k.host,k.backlog,R)):k.server&&(this._server=k.server),this._server){const I=this.emit.bind(this,"connection");this._removeListeners=w(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(P,O,U)=>{this.handleUpgrade(P,O,U,I)}})}k.perMessageDeflate===!0&&(k.perMessageDeflate={}),k.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=k,this._state=f}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(k){if(this._state===y){k&&this.once("close",()=>{k(new Error("The server is not running"))}),process.nextTick(E,this);return}if(k&&this.once("close",k),this._state!==g)if(this._state=g,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(E,this):process.nextTick(E,this);else{const R=this._server;this._removeListeners(),this._removeListeners=this._server=null,R.close(()=>{E(this)})}}shouldHandle(k){if(this.options.path){const R=k.url.indexOf("?");if((R!==-1?k.url.slice(0,R):k.url)!==this.options.path)return!1}return!0}handleUpgrade(k,R,I,P){R.on("error",_);const O=k.headers["sec-websocket-key"],U=k.headers.upgrade,M=+k.headers["sec-websocket-version"];if(k.method!=="GET"){A(this,k,R,405,"Invalid HTTP method");return}if(U===void 0||U.toLowerCase()!=="websocket"){A(this,k,R,400,"Invalid Upgrade header");return}if(O===void 0||!h.test(O)){A(this,k,R,400,"Missing or invalid Sec-WebSocket-Key header");return}if(M!==13&&M!==8){A(this,k,R,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(k)){C(R,400);return}const F=k.headers["sec-websocket-protocol"];let N=new Set;if(F!==void 0)try{N=c.parse(F)}catch{A(this,k,R,400,"Invalid Sec-WebSocket-Protocol header");return}const L=k.headers["sec-websocket-extensions"],q={};if(this.options.perMessageDeflate&&L!==void 0){const B=new a({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{const H=i.parse(L);H[a.extensionName]&&(B.accept(H[a.extensionName]),q[a.extensionName]=B)}catch{A(this,k,R,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){const B={origin:k.headers[`${M===8?"sec-websocket-origin":"origin"}`],secure:!!(k.socket.authorized||k.socket.encrypted),req:k};if(this.options.verifyClient.length===2){this.options.verifyClient(B,(H,G,X,ce)=>{if(!H)return C(R,G||401,X,ce);this.completeUpgrade(q,O,N,k,R,I,P)});return}if(!this.options.verifyClient(B))return C(R,401)}this.completeUpgrade(q,O,N,k,R,I,P)}completeUpgrade(k,R,I,P,O,U,M){if(!O.readable||!O.writable)return O.destroy();if(O[m])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>f)return C(O,503);const N=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(R+d).digest("base64")}`],L=new this.options.WebSocket(null,void 0,this.options);if(I.size){const q=this.options.handleProtocols?this.options.handleProtocols(I,P):I.values().next().value;q&&(N.push(`Sec-WebSocket-Protocol: ${q}`),L._protocol=q)}if(k[a.extensionName]){const q=k[a.extensionName].params,B=i.format({[a.extensionName]:[q]});N.push(`Sec-WebSocket-Extensions: ${B}`),L._extensions=k}this.emit("headers",N,P),O.write(N.concat(`\r
|
|
2153
|
+
</speak>`}extractLanguage(t){const r=t.match(/^([a-z]{2}-[A-Z]{2})/);return r?r[1]:"en-US"}escapeXml(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}mapGender(t){switch(t?.toLowerCase()){case"male":return"male";case"female":return"female";default:return"neutral"}}mapFormat(t){return{mp3:"audio-24khz-96kbitrate-mono-mp3",wav:"riff-24khz-16bit-mono-pcm",ogg:"ogg-24khz-16bit-mono-opus",opus:"ogg-24khz-16bit-mono-opus"}[t]??"audio-24khz-96kbitrate-mono-mp3"}getSampleRate(t){return t.includes("24khz")?24e3:t.includes("16khz")?16e3:t.includes("48khz")?48e3:24e3}effectiveFormat(t){return t.includes("mp3")?"mp3":t.includes("opus")?"opus":t.startsWith("raw")&&t.includes("pcm")?"pcm16":t.includes("riff")||t.includes("pcm")||t.includes("wav")?"wav":"mp3"}}}}),g7t,y7t,v7t,T7t,Kie,QT,w7t=b({"src/lib/voice/providers/CartesiaTTS.ts"(){"use strict";Lr(),z(),xc(),g7t="https://api.cartesia.ai",y7t="2025-04-16",v7t="sonic-2",T7t="694f9389-aac1-45b6-b726-9d9369183238",Kie=3e4,QT=class{maxTextLength=5e3;apiKey;baseUrl;apiVersion;constructor(e){const t=(e??process.env.CARTESIA_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.CARTESIA_BASE_URL??g7t).replace(/\/$/,""),this.apiVersion=process.env.CARTESIA_API_VERSION??y7t}isConfigured(){return this.apiKey!==null}async synthesize(e,t={}){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"CARTESIA_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=t.voice??process.env.CARTESIA_VOICE_ID??T7t,o=t.format??"mp3",{container:s,encoding:i,sampleRate:a}=this.mapOutputFormat(o),c=t,l=c.model??process.env.CARTESIA_MODEL??v7t,u={model_id:l,transcript:e,voice:{mode:"id",id:n},output_format:{container:s,encoding:i,sample_rate:a},language:c.language??"en"};let d;try{d=await Ct(fetch(`${this.baseUrl}/tts/bytes`,{method:"POST",headers:{"X-API-Key":this.apiKey,"Cartesia-Version":this.apiVersion,"Content-Type":"application/json"},body:JSON.stringify(u)}),Kie,`Cartesia request timed out after ${Kie/1e3}s`)}catch(v){throw v instanceof ad?new Et({code:At.SYNTHESIS_FAILED,message:v.message,category:"network",severity:"high",retriable:!0,originalError:v}):new Et({code:At.SYNTHESIS_FAILED,message:`Cartesia network error: ${v instanceof Error?v.message:String(v)}`,category:"network",severity:"high",retriable:!0,originalError:v instanceof Error?v:void 0})}if(!d.ok){const v=await d.text(),w=d.status===408||d.status===429||d.status>=500;throw new Et({code:At.SYNTHESIS_FAILED,message:`Cartesia synthesis failed: ${d.status} \u2014 ${v}`,category:w?"network":"execution",severity:"high",retriable:w,context:{status:d.status,voiceId:n,container:s,encoding:i}})}const m=await d.arrayBuffer(),h=Buffer.from(m),f=Date.now()-r,g=this.effectiveFormat(s,i),y={buffer:h,format:g,size:h.length,voice:n,sampleRate:a,metadata:{latency:f,provider:"cartesia",model:l,requestedFormat:t.format,container:s,encoding:i}};return p.info(`[CartesiaTTS] Synthesized ${h.length} bytes in ${f}ms`),y}mapOutputFormat(e){switch(e){case"mp3":return{container:"mp3",encoding:"mp3",sampleRate:44100};case"wav":return{container:"wav",encoding:"pcm_s16le",sampleRate:44100};case"pcm16":return{container:"raw",encoding:"pcm_s16le",sampleRate:24e3};default:throw new Et({code:At.SYNTHESIS_FAILED,message:`Cartesia does not support output format "${e}". Supported: mp3, wav, pcm16.`,category:"validation",severity:"medium",retriable:!1,context:{format:e,supported:["mp3","wav","pcm16"]}})}}effectiveFormat(e,t){if(e==="mp3")return"mp3";if(e==="wav")return"wav";if(t==="pcm_s16le")return"pcm16";throw new Et({code:At.SYNTHESIS_FAILED,message:`Unsupported Cartesia output combination: container=${e}, encoding=${t}`,category:"execution",severity:"high",retriable:!1,context:{container:e,encoding:t}})}}}}),ew,E7t=b({"src/lib/voice/providers/ElevenLabsTTS.ts"(){"use strict";z(),xc(),ew=class M0r{apiKey;baseUrl="https://api.elevenlabs.io/v1";voicesCache=null;static CACHE_TTL_MS=300*1e3;maxTextLength=5e3;constructor(t){const r=(t??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=r.length>0?r:null}isConfigured(){return this.apiKey!==null}async getVoices(t){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<M0r.CACHE_TTL_MS&&!t)return this.voicesCache.voices;try{const r=new AbortController,n=setTimeout(()=>r.abort(),3e4);let o;try{o=await fetch(`${this.baseUrl}/voices`,{method:"GET",headers:{"xi-api-key":this.apiKey},signal:r.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new Et({code:At.SYNTHESIS_FAILED,message:"ElevenLabs voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).voices.map(a=>({id:a.voice_id,name:a.name,languageCode:"en",languageCodes:["en","es","fr","de","it","pt","pl","hi","ar","zh","ja","ko"],gender:this.mapGender(a.labels?.gender),type:"neural",description:a.labels?.description}));if(t){const a=t.toLowerCase(),c=a.split("-")[0];i=i.filter(l=>l.languageCodes?.some(u=>{const d=u.toLowerCase();return d===a||d===c||d.startsWith(c)}))}return t||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(r){const n=r instanceof Error?r.message:String(r||"Unknown error");throw p.error(`[ElevenLabsTTSHandler] Failed to get voices: ${n}`),new Et({code:At.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:r instanceof Error?r:void 0})}}async synthesize(t,r={}){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});const n=Date.now(),o=r;try{const s=r.voice??"21m00Tcm4TlvDq8ikWAM",i=o.model??"eleven_multilingual_v2",a={text:t,model_id:i,voice_settings:{stability:o.stability??.5,similarity_boost:o.similarityBoost??.75,style:o.style??0,use_speaker_boost:o.useSpeakerBoost??!0}},c=this.mapFormat(r.format??"mp3"),l=new AbortController,u=setTimeout(()=>l.abort(),3e4);let d;try{d=await fetch(`${this.baseUrl}/text-to-speech/${s}?output_format=${c}`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Et({code:At.SYNTHESIS_FAILED,message:"ElevenLabs TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(u)}if(!d.ok){const v=(await d.json().catch(()=>Object.create(null))).detail?.message||`HTTP ${d.status}`;throw new Error(v)}const m=Date.now()-n,h=await d.arrayBuffer(),f=Buffer.from(h),g={buffer:f,format:this.effectiveFormat(c),size:f.length,voice:s,sampleRate:this.getSampleRate(c),metadata:{latency:m,provider:"elevenlabs-tts",model:i,requestedFormat:r.format,outputFormat:c}};return p.info(`[ElevenLabsTTSHandler] Synthesized ${f.length} bytes in ${m}ms`),g}catch(s){if(s instanceof Et)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw p.error(`[ElevenLabsTTSHandler] Synthesis failed: ${i}`),new Et({code:At.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:t.length},originalError:s instanceof Error?s:void 0})}}mapGender(t){if(!t)return"neutral";const r=t.toLowerCase();return r.includes("male")&&!r.includes("female")?"male":r.includes("female")?"female":"neutral"}mapFormat(t){return{mp3:"mp3_44100_128",wav:"pcm_44100",ogg:"ogg_22050",opus:"ogg_22050"}[t]??"mp3_44100_128"}getSampleRate(t){return t.includes("44100")?44100:t.includes("22050")?22050:t.includes("24000")?24e3:44100}effectiveFormat(t){return t.startsWith("mp3")?"mp3":t.startsWith("pcm")?"pcm16":t.startsWith("ogg")?"opus":"mp3"}}}}),S7t,Jie,b7t,tw,_7t=b({"src/lib/voice/providers/FishAudioTTS.ts"(){"use strict";z(),xc(),S7t="https://api.fish.audio",Jie=3e4,b7t="802e3bc2b27e49c2995d23ef70e6ac89",tw=class{maxTextLength=5e3;apiKey;baseUrl;constructor(e){const t=(e??process.env.FISH_AUDIO_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.FISH_AUDIO_BASE_URL??S7t).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async synthesize(e,t={}){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"FISH_AUDIO_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=t.voice??b7t,o=t.format??"mp3",s=this.mapFormat(o),i={text:e,reference_id:n,format:s,mp3_bitrate:128,chunk_length:200,normalize:!0,latency:"normal"},a=t;a.model&&(i.model=a.model),a.latency&&(i.latency=a.latency),a.mp3Bitrate!==void 0&&(i.mp3_bitrate=a.mp3Bitrate);const c=new AbortController,l=setTimeout(()=>c.abort(),Jie);let u;try{u=await fetch(`${this.baseUrl}/v1/tts`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(i),signal:c.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Et({code:At.SYNTHESIS_FAILED,message:`Fish Audio request timed out after ${Jie/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:y}):new Et({code:At.SYNTHESIS_FAILED,message:`Fish Audio network error: ${y instanceof Error?y.message:String(y)}`,category:"network",severity:"high",retriable:!0,originalError:y instanceof Error?y:void 0})}finally{clearTimeout(l)}if(!u.ok){const y=await u.text(),v=u.status===408||u.status===429||u.status>=500;throw new Et({code:At.SYNTHESIS_FAILED,message:`Fish Audio synthesis failed: ${u.status} \u2014 ${y}`,category:v?"network":"execution",severity:"high",retriable:v,context:{status:u.status,referenceId:n,upstreamFormat:s}})}const d=await u.arrayBuffer(),m=Buffer.from(d),h=Date.now()-r,f=this.effectiveFormat(s),g={buffer:m,format:f,size:m.length,voice:n,sampleRate:this.getSampleRate(f),metadata:{latency:h,provider:"fish-audio",model:a.model??"s1",requestedFormat:t.format,upstreamFormat:s}};return p.info(`[FishAudioTTS] Synthesized ${m.length} bytes in ${h}ms`),g}mapFormat(e){const r={mp3:"mp3",wav:"wav",pcm16:"pcm"}[e];return r||(p.warn(`[FishAudioTTS] Unsupported format "${e}" \u2014 falling back to "mp3"`),"mp3")}effectiveFormat(e){return e==="mp3"?"mp3":e==="wav"?"wav":e==="pcm"?"pcm16":"mp3"}getSampleRate(e){return 44100}}}});function C7t(e){try{return e instanceof Error?String(e.message):String(e)}catch{return"[unprintable error]"}}function A7t(e,t){try{return e instanceof t}catch{return!1}}function k7t(e){try{return e instanceof Error&&e.name==="AbortError"}catch{return!1}}function x7t(e,t){if(A7t(e,Error))try{return String(e.name),String(e.message),String(e.stack),e}catch{return new Error(t)}}function I7t(e,t){try{return new Et({...e,originalError:t})}catch{return new Et(e)}}function cen(e){if(!A7t(e,Et))return!1;try{return String(e.name),String(e.message),String(e.code),e.retriable,String(e.stack),!0}catch{return!1}}var rw,R7t=b({"src/lib/voice/providers/OpenAITTS.ts"(){"use strict";z(),Qb(),xc(),rw=class Xde{apiKey;baseUrl="https://api.openai.com/v1";maxTextLength=4096;static VOICES=[{id:"alloy",name:"Alloy",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"echo",name:"Echo",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"fable",name:"Fable",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"onyx",name:"Onyx",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"nova",name:"Nova",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"},{id:"shimmer",name:"Shimmer",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"}];constructor(t){const r=(t??process.env.OPENAI_API_KEY??"").trim();this.apiKey=r.length>0?r:null}isConfigured(){return this.apiKey!==null}async getVoices(t){return t&&!t.startsWith("en"),Xde.VOICES}requireApiKey(){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"OpenAI TTS API key not configured",category:"configuration",severity:"high",retriable:!1});return this.apiKey}prepareRequest(t,r){const o=r.model??(r.quality==="hd"?"tts-1-hd":"tts-1"),s=r.voice??"alloy",i=this.mapFormat(r.format??"mp3");return{model:o,voice:s,responseFormat:i,effectiveFormat:this.effectiveFormat(i),body:{model:o,input:t,voice:s,response_format:i,speed:r.speed??1}}}async createSpeechResponse(t,r,n){let o;try{o=await fetch(`${this.baseUrl}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${this.requireApiKey()}`,"Content-Type":"application/json"},body:JSON.stringify(t.body),signal:r})}finally{n?.()}if(!o.ok){const i=(await o.json().catch(()=>Object.create(null))).error?.message||`HTTP ${o.status}`,a=o.status===408||o.status===429||o.status>=500;throw new Et({code:At.SYNTHESIS_FAILED,message:i,category:a?"network":"execution",severity:"high",retriable:a,context:{status:o.status,model:t.model,responseFormat:t.responseFormat}})}return o}synthesisError(t,r,n){if(cen(t))return t;if(k7t(t)&&n)return I7t({code:At.SYNTHESIS_FAILED,message:"OpenAI TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0},x7t(t,C7t(t)));const o=t?C7t(t):"Unknown error";return p.error(`[OpenAITTSHandler] Synthesis failed: ${o}`),I7t({code:At.SYNTHESIS_FAILED,message:`Synthesis failed: ${o}`,category:"execution",severity:"high",retriable:!0,context:{textLength:r}},x7t(t,o))}async synthesize(t,r={}){this.requireApiKey();const n=Date.now(),o=this.prepareRequest(t,r),s=new AbortController;let i=!1,a=setTimeout(()=>{i=!0,s.abort()},3e4);const c=()=>{a!==void 0&&(clearTimeout(a),a=void 0)};try{const l=await this.createSpeechResponse(o,s.signal,c),u=Date.now()-n,d=await l.arrayBuffer(),m=Buffer.from(d),h={buffer:m,format:o.effectiveFormat,size:m.length,voice:o.voice,sampleRate:this.getSampleRate(o.effectiveFormat),metadata:{latency:u,provider:"openai-tts",model:o.model,requestedFormat:r.format,responseFormat:o.responseFormat}};return p.info(`[OpenAITTSHandler] Synthesized ${m.length} bytes in ${u}ms`),h}catch(l){throw this.synthesisError(l,t.length,i)}finally{c()}}synthesizeStream(t,r={}){const n=r.format??"mp3";if(n!=="mp3"&&n!=="pcm16")return;const o=this.prepareRequest(t,r),s=this;let i,a,c=!1,l=!1,u=!1;const d=(async function*(){s.requireApiKey();const m=Date.now();i=new AbortController;const h=setTimeout(()=>{l=!0,i?.abort()},3e4);try{const f=await s.createSpeechResponse(o,i.signal);if(!f.body)throw new Et({code:At.SYNTHESIS_FAILED,message:"OpenAI TTS response did not include an audio body",category:"network",severity:"high",retriable:!0});a=f.body.getReader();let g=0,y=0;for(;;){const v=await a.read();if(v.done){u=!0;break}const w=Buffer.from(v.value);w.length!==0&&(y+=w.length,yield{data:w,format:o.effectiveFormat,index:g++,isFinal:!1,cumulativeSize:y,voice:o.voice,sampleRate:s.getSampleRate(o.effectiveFormat)})}p.info(`[OpenAITTSHandler] Streamed ${y} bytes in ${Date.now()-m}ms`)}catch(f){if(c&&k7t(f))return;throw s.synthesisError(f,t.length,l)}finally{clearTimeout(h),u||i?.abort();try{a?.releaseLock()}catch{}a=void 0,i=void 0}})();return Zb(d,()=>{c=!0,i?.abort()})}mapFormat(t){const n={mp3:"mp3",wav:"wav",ogg:"opus",opus:"opus",flac:"flac",pcm16:"pcm"}[t];return n===void 0?(p.warn(`[OpenAITTSHandler] Unsupported format "${t}" \u2014 falling back to "mp3". Supported formats: mp3, wav, ogg, opus, flac, pcm16.`),"mp3"):n}getSampleRate(t){switch(t){case"opus":case"ogg":return 48e3;default:return 24e3}}effectiveFormat(t){switch(t){case"mp3":return"mp3";case"wav":return"wav";case"opus":return"opus";case"flac":return"flac";case"pcm":return"pcm16";default:return"mp3"}}}}}),P7t={};ee(P7t,{Agent:()=>z7t,AsyncLocalStorage:()=>t9t,Buffer:()=>QWt,Channel:()=>qWt,DatabaseSync:()=>ZWt,Duplex:()=>n9t,EventEmitter:()=>e9t,Http2ServerRequest:()=>oKt,Http2ServerResponse:()=>sKt,Interface:()=>XWt,MIMEType:()=>dKt,PassThrough:()=>o9t,PerformanceObserver:()=>UWt,Readable:()=>Xie,ReadableStream:()=>s9t,Resolver:()=>FWt,STATUS_CODES:()=>iWt,TextDecoder:()=>eae,TextEncoder:()=>Fk,Transform:()=>r9t,URL:()=>_Wt,URLSearchParams:()=>CWt,Worker:()=>VWt,Writable:()=>Zie,access:()=>$9t,appendFile:()=>g9t,appendFileSync:()=>$7t,arch:()=>rWt,arrayBuffer:()=>iKt,availableParallelism:()=>p9t,basename:()=>W7t,builtinModules:()=>wWt,callbackify:()=>MWt,channel:()=>zWt,chmod:()=>m9t,chmodSync:()=>d9t,clearInterval:()=>uKt,clearTimeout:()=>cKt,closeSync:()=>w9t,connect:()=>aWt,constants:()=>eKt,copyFileSync:()=>v9t,cpSync:()=>U7t,cpus:()=>Z9t,createConnection:()=>cWt,createGunzip:()=>fWt,createGzip:()=>gWt,createHash:()=>Yie,createHmac:()=>D7t,createInterface:()=>YWt,createReadStream:()=>P9t,createRequire:()=>TWt,createServer:()=>B7t,createWriteStream:()=>R9t,debug:()=>RWt,debuglog:()=>Qie,default:()=>M7t,deflateSync:()=>uWt,deprecate:()=>PWt,deserialize:()=>HWt,dirname:()=>V7t,exec:()=>j9t,execFile:()=>V9t,execFileSync:()=>W9t,execSync:()=>H9t,existsSync:()=>c9t,extname:()=>K7t,fileURLToPath:()=>AWt,finished:()=>a9t,format:()=>bWt,freemem:()=>Q9t,fstatSync:()=>E9t,get:()=>sWt,gunzip:()=>hWt,gunzipSync:()=>dWt,gzip:()=>pWt,gzipSync:()=>mWt,hasSubscribers:()=>GWt,homedir:()=>J9t,hostname:()=>X9t,inflateSync:()=>lWt,inherits:()=>xWt,inspect:()=>Lk,isAbsolute:()=>Y7t,isBuiltin:()=>EWt,isDeepStrictEqual:()=>OWt,isIP:()=>nKt,isIPv4:()=>rKt,isIPv6:()=>tKt,isMainThread:()=>WWt,join:()=>j7t,loadavg:()=>h9t,lookup:()=>LWt,lstatSync:()=>_9t,mkdir:()=>D9t,mkdirSync:()=>S9t,monitorEventLoopDelay:()=>BWt,normalize:()=>Q7t,ok:()=>yWt,open:()=>z9t,openSync:()=>T9t,parentPort:()=>KWt,parse:()=>SWt,pathToFileURL:()=>kWt,performance:()=>$Wt,pipeline:()=>i9t,platform:()=>K9t,posix:()=>Z7t,promises:()=>O7t,promisify:()=>IWt,randomBytes:()=>N7t,randomUUID:()=>L7t,readFile:()=>M9t,readFileSync:()=>l9t,readdir:()=>L9t,readdirSync:()=>C9t,realpath:()=>q9t,realpathSync:()=>y9t,relative:()=>J7t,release:()=>nWt,rename:()=>U9t,renameSync:()=>k9t,request:()=>oWt,resolve:()=>H7t,rm:()=>B9t,rmSync:()=>I9t,rmdirSync:()=>x9t,sep:()=>X7t,serialize:()=>jWt,setImmediate:()=>f9t,setInterval:()=>lKt,setTimeout:()=>aKt,spawn:()=>G9t,stat:()=>N9t,statSync:()=>b9t,strict:()=>vWt,tmpdir:()=>Y9t,toUSVString:()=>DWt,totalmem:()=>eWt,type:()=>tWt,types:()=>NWt,unlink:()=>F9t,unlinkSync:()=>A9t,validateHeaderName:()=>q7t,validateHeaderValue:()=>G7t,webcrypto:()=>F7t,workerData:()=>JWt,writeFile:()=>O9t,writeFileSync:()=>u9t});var mo,bn,M7t,O7t,Yie,D7t,N7t,L7t,F7t,$7t,U7t,B7t,z7t,q7t,G7t,j7t,H7t,V7t,W7t,K7t,J7t,Y7t,X7t,Z7t,Q7t,e9t,t9t,Xie,Zie,r9t,n9t,o9t,s9t,i9t,a9t,c9t,l9t,u9t,d9t,m9t,p9t,h9t,f9t,g9t,y9t,v9t,T9t,w9t,E9t,S9t,b9t,_9t,C9t,A9t,k9t,x9t,I9t,R9t,P9t,M9t,O9t,D9t,N9t,L9t,F9t,$9t,U9t,B9t,z9t,q9t,G9t,j9t,H9t,V9t,W9t,K9t,J9t,Y9t,X9t,Z9t,Q9t,eWt,tWt,rWt,nWt,oWt,sWt,iWt,aWt,cWt,lWt,uWt,dWt,mWt,pWt,hWt,fWt,gWt,yWt,vWt,TWt,wWt,EWt,SWt,bWt,_Wt,CWt,AWt,kWt,xWt,IWt,Qie,RWt,Lk,PWt,MWt,OWt,DWt,NWt,eae,Fk,LWt,FWt,$Wt,UWt,BWt,zWt,qWt,GWt,jWt,HWt,VWt,WWt,KWt,JWt,YWt,XWt,ZWt,QWt,eKt,tKt,rKt,nKt,oKt,sKt,iKt,tae,aKt,cKt,lKt,uKt,dKt,len=b({"node-stub:https"(){mo=()=>{},bn=async()=>{},M7t={},O7t={readFile:bn,writeFile:bn,mkdir:bn,stat:bn,readdir:bn,unlink:bn,access:bn,rm:bn,rename:bn},Yie=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Fk().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}}},D7t=(e,t)=>Yie(e),N7t=e=>new Uint8Array(e||32),L7t=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),F7t=globalThis.crypto,$7t=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},U7t=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},B7t=()=>({listen:mo,close:mo,on:mo}),z7t=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},q7t=mo,G7t=mo,j7t=(...e)=>e.join("/"),H7t=(...e)=>e.join("/"),V7t=e=>e||"",W7t=e=>e?.split?.("/")?.pop?.()||"",K7t=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},J7t=(e,t)=>t||"",Y7t=()=>!1,X7t="/",Z7t={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},Q7t=e=>e,e9t=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},t9t=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},Xie=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Zie=class{write(){return!0}end(){}on(){return this}destroy(){}},r9t=class{push(){}on(){return this}},n9t=class{on(){return this}},o9t=class{pipe(){return this}on(){return this}},s9t=globalThis.ReadableStream||class{},i9t=mo,a9t=mo,c9t=()=>!1,l9t=()=>"",u9t=mo,d9t=mo,m9t=bn,p9t=()=>1,h9t=()=>[0,0,0],f9t=bn,g9t=bn,y9t=e=>e,v9t=mo,T9t=()=>0,w9t=mo,E9t=()=>({}),S9t=mo,b9t=()=>({}),_9t=()=>({isSymbolicLink:()=>!1}),C9t=()=>[],A9t=mo,k9t=mo,x9t=mo,I9t=mo,R9t=()=>new Zie,P9t=()=>new Xie,M9t=bn,O9t=bn,D9t=bn,N9t=bn,L9t=bn,F9t=bn,$9t=bn,U9t=bn,B9t=bn,z9t=async()=>({stat:bn,readFile:bn,close:bn,read:bn,write:bn}),q9t=async e=>e,G9t=()=>({on:mo,stdout:{on:mo},stderr:{on:mo},kill:mo}),j9t=(e,t)=>t?.(null,"",""),H9t=()=>"",V9t=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},W9t=()=>"",K9t="browser",J9t=()=>"/",Y9t=()=>"/tmp",X9t=()=>"browser",Z9t=()=>[{}],Q9t=()=>0,eWt=()=>0,tWt=()=>"Browser",rWt=()=>"wasm",nWt=()=>"0",oWt=()=>({}),sWt=()=>({}),iWt={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},aWt=()=>({}),cWt=()=>({}),lWt=()=>new Uint8Array,uWt=()=>new Uint8Array,dWt=()=>new Uint8Array,mWt=()=>new Uint8Array,pWt=(e,t)=>t?.(null,e),hWt=(e,t)=>t?.(null,e),fWt=()=>({}),gWt=()=>({}),yWt=mo,vWt={},TWt=()=>()=>({}),wWt=[],EWt=()=>!1,SWt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),bWt=()=>"",_Wt=globalThis.URL,CWt=globalThis.URLSearchParams,AWt=e=>typeof e=="string"?e.replace("file://",""):e,kWt=e=>new globalThis.URL("file://"+e),xWt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},IWt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),Qie=e=>{const t=(...r)=>{};return t.enabled=!1,t},RWt=Qie,Lk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},Lk.custom=Symbol.for("nodejs.util.inspect.custom"),Lk.colors={},Lk.styles={},PWt=e=>e,MWt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},OWt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),DWt=e=>String(e),NWt={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},eae=globalThis.TextDecoder,Fk=globalThis.TextEncoder,LWt=(e,t)=>t?.(null,"127.0.0.1",4),FWt=class{},$Wt=globalThis.performance||{now:()=>Date.now()},UWt=class{observe(){}disconnect(){}},BWt=()=>({enable:mo,disable:mo,percentile:()=>0}),zWt=()=>({}),qWt=class{},GWt=()=>!1,jWt=()=>new Uint8Array,HWt=mo,VWt=class{},WWt=!0,KWt=null,JWt=null,YWt=()=>({}),XWt=class{},ZWt=class{},QWt=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 Fk().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 Fk().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 eae().decode(this)}},eKt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},tKt=()=>!1,rKt=()=>!1,nKt=()=>0,oKt=class{},sKt=class{},iKt=async()=>new ArrayBuffer(0),tae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),aKt=(...e)=>tae(globalThis.setTimeout(...e)),cKt=globalThis.clearTimeout,lKt=(...e)=>tae(globalThis.setInterval(...e)),uKt=globalThis.clearInterval,dKt=class{constructor(e){this.type=e}toString(){return this.type}}}}),mKt={};ee(mKt,{Agent:()=>SKt,AsyncLocalStorage:()=>LKt,Buffer:()=>DYt,Channel:()=>bYt,DatabaseSync:()=>OYt,Duplex:()=>$Kt,EventEmitter:()=>NKt,Http2ServerRequest:()=>UYt,Http2ServerResponse:()=>BYt,Interface:()=>MYt,MIMEType:()=>VYt,PassThrough:()=>UKt,PerformanceObserver:()=>wYt,Readable:()=>nae,ReadableStream:()=>BKt,Resolver:()=>vYt,STATUS_CODES:()=>zJt,TextDecoder:()=>iae,TextEncoder:()=>Uk,Transform:()=>FKt,URL:()=>sYt,URLSearchParams:()=>iYt,Worker:()=>kYt,Writable:()=>oae,access:()=>TJt,appendFile:()=>XKt,appendFileSync:()=>TKt,arch:()=>FJt,arrayBuffer:()=>zYt,availableParallelism:()=>KKt,basename:()=>xKt,builtinModules:()=>tYt,callbackify:()=>pYt,channel:()=>SYt,chmod:()=>WKt,chmodSync:()=>VKt,clearInterval:()=>HYt,clearTimeout:()=>GYt,closeSync:()=>tJt,connect:()=>qJt,constants:()=>NYt,copyFileSync:()=>QKt,cpSync:()=>wKt,cpus:()=>OJt,createConnection:()=>GJt,createGunzip:()=>YJt,createGzip:()=>XJt,createHash:()=>rae,createHmac:()=>fKt,createInterface:()=>PYt,createReadStream:()=>mJt,createRequire:()=>eYt,createServer:()=>EKt,createWriteStream:()=>dJt,debug:()=>dYt,debuglog:()=>sae,default:()=>pKt,deflateSync:()=>HJt,deprecate:()=>mYt,deserialize:()=>AYt,dirname:()=>kKt,exec:()=>CJt,execFile:()=>kJt,execFileSync:()=>xJt,execSync:()=>AJt,existsSync:()=>GKt,extname:()=>IKt,fileURLToPath:()=>aYt,finished:()=>qKt,format:()=>oYt,freemem:()=>DJt,fstatSync:()=>rJt,get:()=>BJt,gunzip:()=>JJt,gunzipSync:()=>VJt,gzip:()=>KJt,gzipSync:()=>WJt,hasSubscribers:()=>_Yt,homedir:()=>RJt,hostname:()=>MJt,inflateSync:()=>jJt,inherits:()=>lYt,inspect:()=>$k,isAbsolute:()=>PKt,isBuiltin:()=>rYt,isDeepStrictEqual:()=>hYt,isIP:()=>$Yt,isIPv4:()=>FYt,isIPv6:()=>LYt,isMainThread:()=>xYt,join:()=>CKt,loadavg:()=>JKt,lookup:()=>yYt,lstatSync:()=>sJt,mkdir:()=>fJt,mkdirSync:()=>nJt,monitorEventLoopDelay:()=>EYt,normalize:()=>DKt,ok:()=>ZJt,open:()=>SJt,openSync:()=>eJt,parentPort:()=>IYt,parse:()=>nYt,pathToFileURL:()=>cYt,performance:()=>TYt,pipeline:()=>zKt,platform:()=>IJt,posix:()=>OKt,promises:()=>hKt,promisify:()=>uYt,randomBytes:()=>gKt,randomUUID:()=>yKt,readFile:()=>pJt,readFileSync:()=>jKt,readdir:()=>yJt,readdirSync:()=>iJt,realpath:()=>bJt,realpathSync:()=>ZKt,relative:()=>RKt,release:()=>$Jt,rename:()=>wJt,renameSync:()=>cJt,request:()=>UJt,resolve:()=>AKt,rm:()=>EJt,rmSync:()=>uJt,rmdirSync:()=>lJt,sep:()=>MKt,serialize:()=>CYt,setImmediate:()=>YKt,setInterval:()=>jYt,setTimeout:()=>qYt,spawn:()=>_Jt,stat:()=>gJt,statSync:()=>oJt,strict:()=>QJt,tmpdir:()=>PJt,toUSVString:()=>fYt,totalmem:()=>NJt,type:()=>LJt,types:()=>gYt,unlink:()=>vJt,unlinkSync:()=>aJt,validateHeaderName:()=>bKt,validateHeaderValue:()=>_Kt,webcrypto:()=>vKt,workerData:()=>RYt,writeFile:()=>hJt,writeFileSync:()=>HKt});var po,_n,pKt,hKt,rae,fKt,gKt,yKt,vKt,TKt,wKt,EKt,SKt,bKt,_Kt,CKt,AKt,kKt,xKt,IKt,RKt,PKt,MKt,OKt,DKt,NKt,LKt,nae,oae,FKt,$Kt,UKt,BKt,zKt,qKt,GKt,jKt,HKt,VKt,WKt,KKt,JKt,YKt,XKt,ZKt,QKt,eJt,tJt,rJt,nJt,oJt,sJt,iJt,aJt,cJt,lJt,uJt,dJt,mJt,pJt,hJt,fJt,gJt,yJt,vJt,TJt,wJt,EJt,SJt,bJt,_Jt,CJt,AJt,kJt,xJt,IJt,RJt,PJt,MJt,OJt,DJt,NJt,LJt,FJt,$Jt,UJt,BJt,zJt,qJt,GJt,jJt,HJt,VJt,WJt,KJt,JJt,YJt,XJt,ZJt,QJt,eYt,tYt,rYt,nYt,oYt,sYt,iYt,aYt,cYt,lYt,uYt,sae,dYt,$k,mYt,pYt,hYt,fYt,gYt,iae,Uk,yYt,vYt,TYt,wYt,EYt,SYt,bYt,_Yt,CYt,AYt,kYt,xYt,IYt,RYt,PYt,MYt,OYt,DYt,NYt,LYt,FYt,$Yt,UYt,BYt,zYt,aae,qYt,GYt,jYt,HYt,VYt,uen=b({"node-stub:net"(){po=()=>{},_n=async()=>{},pKt={},hKt={readFile:_n,writeFile:_n,mkdir:_n,stat:_n,readdir:_n,unlink:_n,access:_n,rm:_n,rename:_n},rae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Uk().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}}},fKt=(e,t)=>rae(e),gKt=e=>new Uint8Array(e||32),yKt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),vKt=globalThis.crypto,TKt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},wKt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},EKt=()=>({listen:po,close:po,on:po}),SKt=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},bKt=po,_Kt=po,CKt=(...e)=>e.join("/"),AKt=(...e)=>e.join("/"),kKt=e=>e||"",xKt=e=>e?.split?.("/")?.pop?.()||"",IKt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},RKt=(e,t)=>t||"",PKt=()=>!1,MKt="/",OKt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},DKt=e=>e,NKt=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},LKt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},nae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},oae=class{write(){return!0}end(){}on(){return this}destroy(){}},FKt=class{push(){}on(){return this}},$Kt=class{on(){return this}},UKt=class{pipe(){return this}on(){return this}},BKt=globalThis.ReadableStream||class{},zKt=po,qKt=po,GKt=()=>!1,jKt=()=>"",HKt=po,VKt=po,WKt=_n,KKt=()=>1,JKt=()=>[0,0,0],YKt=_n,XKt=_n,ZKt=e=>e,QKt=po,eJt=()=>0,tJt=po,rJt=()=>({}),nJt=po,oJt=()=>({}),sJt=()=>({isSymbolicLink:()=>!1}),iJt=()=>[],aJt=po,cJt=po,lJt=po,uJt=po,dJt=()=>new oae,mJt=()=>new nae,pJt=_n,hJt=_n,fJt=_n,gJt=_n,yJt=_n,vJt=_n,TJt=_n,wJt=_n,EJt=_n,SJt=async()=>({stat:_n,readFile:_n,close:_n,read:_n,write:_n}),bJt=async e=>e,_Jt=()=>({on:po,stdout:{on:po},stderr:{on:po},kill:po}),CJt=(e,t)=>t?.(null,"",""),AJt=()=>"",kJt=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},xJt=()=>"",IJt="browser",RJt=()=>"/",PJt=()=>"/tmp",MJt=()=>"browser",OJt=()=>[{}],DJt=()=>0,NJt=()=>0,LJt=()=>"Browser",FJt=()=>"wasm",$Jt=()=>"0",UJt=()=>({}),BJt=()=>({}),zJt={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},qJt=()=>({}),GJt=()=>({}),jJt=()=>new Uint8Array,HJt=()=>new Uint8Array,VJt=()=>new Uint8Array,WJt=()=>new Uint8Array,KJt=(e,t)=>t?.(null,e),JJt=(e,t)=>t?.(null,e),YJt=()=>({}),XJt=()=>({}),ZJt=po,QJt={},eYt=()=>()=>({}),tYt=[],rYt=()=>!1,nYt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),oYt=()=>"",sYt=globalThis.URL,iYt=globalThis.URLSearchParams,aYt=e=>typeof e=="string"?e.replace("file://",""):e,cYt=e=>new globalThis.URL("file://"+e),lYt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},uYt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),sae=e=>{const t=(...r)=>{};return t.enabled=!1,t},dYt=sae,$k=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},$k.custom=Symbol.for("nodejs.util.inspect.custom"),$k.colors={},$k.styles={},mYt=e=>e,pYt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},hYt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),fYt=e=>String(e),gYt={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},iae=globalThis.TextDecoder,Uk=globalThis.TextEncoder,yYt=(e,t)=>t?.(null,"127.0.0.1",4),vYt=class{},TYt=globalThis.performance||{now:()=>Date.now()},wYt=class{observe(){}disconnect(){}},EYt=()=>({enable:po,disable:po,percentile:()=>0}),SYt=()=>({}),bYt=class{},_Yt=()=>!1,CYt=()=>new Uint8Array,AYt=po,kYt=class{},xYt=!0,IYt=null,RYt=null,PYt=()=>({}),MYt=class{},OYt=class{},DYt=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 Uk().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 Uk().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 iae().decode(this)}},NYt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},LYt=()=>!1,FYt=()=>!1,$Yt=()=>0,UYt=class{},BYt=class{},zYt=async()=>new ArrayBuffer(0),aae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),qYt=(...e)=>aae(globalThis.setTimeout(...e)),GYt=globalThis.clearTimeout,jYt=(...e)=>aae(globalThis.setInterval(...e)),HYt=globalThis.clearInterval,VYt=class{constructor(e){this.type=e}toString(){return this.type}}}}),WYt={};ee(WYt,{Agent:()=>nXt,AsyncLocalStorage:()=>yXt,Buffer:()=>fQt,Channel:()=>oQt,DatabaseSync:()=>hQt,Duplex:()=>TXt,EventEmitter:()=>gXt,Http2ServerRequest:()=>wQt,Http2ServerResponse:()=>EQt,Interface:()=>pQt,MIMEType:()=>kQt,PassThrough:()=>wXt,PerformanceObserver:()=>tQt,Readable:()=>lae,ReadableStream:()=>EXt,Resolver:()=>QZt,STATUS_CODES:()=>SZt,TextDecoder:()=>mae,TextEncoder:()=>zk,Transform:()=>vXt,URL:()=>BZt,URLSearchParams:()=>zZt,Worker:()=>cQt,Writable:()=>uae,access:()=>eZt,appendFile:()=>MXt,appendFileSync:()=>eXt,arch:()=>vZt,arrayBuffer:()=>SQt,availableParallelism:()=>IXt,basename:()=>lXt,builtinModules:()=>LZt,callbackify:()=>KZt,channel:()=>nQt,chmod:()=>xXt,chmodSync:()=>kXt,clearInterval:()=>AQt,clearTimeout:()=>_Qt,closeSync:()=>LXt,connect:()=>bZt,constants:()=>gQt,copyFileSync:()=>DXt,cpSync:()=>tXt,cpus:()=>hZt,createConnection:()=>_Zt,createGunzip:()=>PZt,createGzip:()=>MZt,createHash:()=>cae,createHmac:()=>YYt,createInterface:()=>mQt,createReadStream:()=>WXt,createRequire:()=>NZt,createServer:()=>rXt,createWriteStream:()=>VXt,debug:()=>VZt,debuglog:()=>dae,default:()=>KYt,deflateSync:()=>AZt,deprecate:()=>WZt,deserialize:()=>aQt,dirname:()=>cXt,exec:()=>iZt,execFile:()=>cZt,execFileSync:()=>lZt,execSync:()=>aZt,existsSync:()=>_Xt,extname:()=>uXt,fileURLToPath:()=>qZt,finished:()=>bXt,format:()=>UZt,freemem:()=>fZt,fstatSync:()=>FXt,get:()=>EZt,gunzip:()=>RZt,gunzipSync:()=>kZt,gzip:()=>IZt,gzipSync:()=>xZt,hasSubscribers:()=>sQt,homedir:()=>dZt,hostname:()=>pZt,inflateSync:()=>CZt,inherits:()=>jZt,inspect:()=>Bk,isAbsolute:()=>mXt,isBuiltin:()=>FZt,isDeepStrictEqual:()=>JZt,isIP:()=>TQt,isIPv4:()=>vQt,isIPv6:()=>yQt,isMainThread:()=>lQt,join:()=>iXt,loadavg:()=>RXt,lookup:()=>ZZt,lstatSync:()=>BXt,mkdir:()=>YXt,mkdirSync:()=>$Xt,monitorEventLoopDelay:()=>rQt,normalize:()=>fXt,ok:()=>OZt,open:()=>nZt,openSync:()=>NXt,parentPort:()=>uQt,parse:()=>$Zt,pathToFileURL:()=>GZt,performance:()=>eQt,pipeline:()=>SXt,platform:()=>uZt,posix:()=>hXt,promises:()=>JYt,promisify:()=>HZt,randomBytes:()=>XYt,randomUUID:()=>ZYt,readFile:()=>KXt,readFileSync:()=>CXt,readdir:()=>ZXt,readdirSync:()=>zXt,realpath:()=>oZt,realpathSync:()=>OXt,relative:()=>dXt,release:()=>TZt,rename:()=>tZt,renameSync:()=>GXt,request:()=>wZt,resolve:()=>aXt,rm:()=>rZt,rmSync:()=>HXt,rmdirSync:()=>jXt,sep:()=>pXt,serialize:()=>iQt,setImmediate:()=>PXt,setInterval:()=>CQt,setTimeout:()=>bQt,spawn:()=>sZt,stat:()=>XXt,statSync:()=>UXt,strict:()=>DZt,tmpdir:()=>mZt,toUSVString:()=>YZt,totalmem:()=>gZt,type:()=>yZt,types:()=>XZt,unlink:()=>QXt,unlinkSync:()=>qXt,validateHeaderName:()=>oXt,validateHeaderValue:()=>sXt,webcrypto:()=>QYt,workerData:()=>dQt,writeFile:()=>JXt,writeFileSync:()=>AXt});var ho,Cn,KYt,JYt,cae,YYt,XYt,ZYt,QYt,eXt,tXt,rXt,nXt,oXt,sXt,iXt,aXt,cXt,lXt,uXt,dXt,mXt,pXt,hXt,fXt,gXt,yXt,lae,uae,vXt,TXt,wXt,EXt,SXt,bXt,_Xt,CXt,AXt,kXt,xXt,IXt,RXt,PXt,MXt,OXt,DXt,NXt,LXt,FXt,$Xt,UXt,BXt,zXt,qXt,GXt,jXt,HXt,VXt,WXt,KXt,JXt,YXt,XXt,ZXt,QXt,eZt,tZt,rZt,nZt,oZt,sZt,iZt,aZt,cZt,lZt,uZt,dZt,mZt,pZt,hZt,fZt,gZt,yZt,vZt,TZt,wZt,EZt,SZt,bZt,_Zt,CZt,AZt,kZt,xZt,IZt,RZt,PZt,MZt,OZt,DZt,NZt,LZt,FZt,$Zt,UZt,BZt,zZt,qZt,GZt,jZt,HZt,dae,VZt,Bk,WZt,KZt,JZt,YZt,XZt,mae,zk,ZZt,QZt,eQt,tQt,rQt,nQt,oQt,sQt,iQt,aQt,cQt,lQt,uQt,dQt,mQt,pQt,hQt,fQt,gQt,yQt,vQt,TQt,wQt,EQt,SQt,pae,bQt,_Qt,CQt,AQt,kQt,den=b({"node-stub:tls"(){ho=()=>{},Cn=async()=>{},KYt={},JYt={readFile:Cn,writeFile:Cn,mkdir:Cn,stat:Cn,readdir:Cn,unlink:Cn,access:Cn,rm:Cn,rename:Cn},cae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new zk().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}}},YYt=(e,t)=>cae(e),XYt=e=>new Uint8Array(e||32),ZYt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),QYt=globalThis.crypto,eXt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},tXt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},rXt=()=>({listen:ho,close:ho,on:ho}),nXt=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},oXt=ho,sXt=ho,iXt=(...e)=>e.join("/"),aXt=(...e)=>e.join("/"),cXt=e=>e||"",lXt=e=>e?.split?.("/")?.pop?.()||"",uXt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},dXt=(e,t)=>t||"",mXt=()=>!1,pXt="/",hXt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},fXt=e=>e,gXt=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},yXt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},lae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},uae=class{write(){return!0}end(){}on(){return this}destroy(){}},vXt=class{push(){}on(){return this}},TXt=class{on(){return this}},wXt=class{pipe(){return this}on(){return this}},EXt=globalThis.ReadableStream||class{},SXt=ho,bXt=ho,_Xt=()=>!1,CXt=()=>"",AXt=ho,kXt=ho,xXt=Cn,IXt=()=>1,RXt=()=>[0,0,0],PXt=Cn,MXt=Cn,OXt=e=>e,DXt=ho,NXt=()=>0,LXt=ho,FXt=()=>({}),$Xt=ho,UXt=()=>({}),BXt=()=>({isSymbolicLink:()=>!1}),zXt=()=>[],qXt=ho,GXt=ho,jXt=ho,HXt=ho,VXt=()=>new uae,WXt=()=>new lae,KXt=Cn,JXt=Cn,YXt=Cn,XXt=Cn,ZXt=Cn,QXt=Cn,eZt=Cn,tZt=Cn,rZt=Cn,nZt=async()=>({stat:Cn,readFile:Cn,close:Cn,read:Cn,write:Cn}),oZt=async e=>e,sZt=()=>({on:ho,stdout:{on:ho},stderr:{on:ho},kill:ho}),iZt=(e,t)=>t?.(null,"",""),aZt=()=>"",cZt=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},lZt=()=>"",uZt="browser",dZt=()=>"/",mZt=()=>"/tmp",pZt=()=>"browser",hZt=()=>[{}],fZt=()=>0,gZt=()=>0,yZt=()=>"Browser",vZt=()=>"wasm",TZt=()=>"0",wZt=()=>({}),EZt=()=>({}),SZt={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},bZt=()=>({}),_Zt=()=>({}),CZt=()=>new Uint8Array,AZt=()=>new Uint8Array,kZt=()=>new Uint8Array,xZt=()=>new Uint8Array,IZt=(e,t)=>t?.(null,e),RZt=(e,t)=>t?.(null,e),PZt=()=>({}),MZt=()=>({}),OZt=ho,DZt={},NZt=()=>()=>({}),LZt=[],FZt=()=>!1,$Zt=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),UZt=()=>"",BZt=globalThis.URL,zZt=globalThis.URLSearchParams,qZt=e=>typeof e=="string"?e.replace("file://",""):e,GZt=e=>new globalThis.URL("file://"+e),jZt=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},HZt=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),dae=e=>{const t=(...r)=>{};return t.enabled=!1,t},VZt=dae,Bk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},Bk.custom=Symbol.for("nodejs.util.inspect.custom"),Bk.colors={},Bk.styles={},WZt=e=>e,KZt=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},JZt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),YZt=e=>String(e),XZt={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},mae=globalThis.TextDecoder,zk=globalThis.TextEncoder,ZZt=(e,t)=>t?.(null,"127.0.0.1",4),QZt=class{},eQt=globalThis.performance||{now:()=>Date.now()},tQt=class{observe(){}disconnect(){}},rQt=()=>({enable:ho,disable:ho,percentile:()=>0}),nQt=()=>({}),oQt=class{},sQt=()=>!1,iQt=()=>new Uint8Array,aQt=ho,cQt=class{},lQt=!0,uQt=null,dQt=null,mQt=()=>({}),pQt=class{},hQt=class{},fQt=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 zk().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 zk().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 mae().decode(this)}},gQt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},yQt=()=>!1,vQt=()=>!1,TQt=()=>0,wQt=class{},EQt=class{},SQt=async()=>new ArrayBuffer(0),pae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),bQt=(...e)=>pae(globalThis.setTimeout(...e)),_Qt=globalThis.clearTimeout,CQt=(...e)=>pae(globalThis.setInterval(...e)),AQt=globalThis.clearInterval,kQt=class{constructor(e){this.type=e}toString(){return this.type}}}}),xQt={};ee(xQt,{Agent:()=>$Qt,AsyncLocalStorage:()=>ZQt,Buffer:()=>Ytr,Channel:()=>Utr,DatabaseSync:()=>Jtr,Duplex:()=>eer,EventEmitter:()=>XQt,Http2ServerRequest:()=>trr,Http2ServerResponse:()=>rrr,Interface:()=>Ktr,MIMEType:()=>crr,PassThrough:()=>ter,PerformanceObserver:()=>Ltr,Readable:()=>fae,ReadableStream:()=>rer,Resolver:()=>Dtr,STATUS_CODES:()=>ntr,TextDecoder:()=>vae,TextEncoder:()=>Gk,Transform:()=>QQt,URL:()=>Etr,URLSearchParams:()=>Str,Worker:()=>Gtr,Writable:()=>gae,access:()=>Ner,appendFile:()=>per,appendFileSync:()=>NQt,arch:()=>Qer,arrayBuffer:()=>nrr,availableParallelism:()=>uer,basename:()=>jQt,builtinModules:()=>ytr,callbackify:()=>Itr,channel:()=>$tr,chmod:()=>ler,chmodSync:()=>cer,clearInterval:()=>arr,clearTimeout:()=>srr,closeSync:()=>yer,connect:()=>otr,constants:()=>Xtr,copyFileSync:()=>fer,cpSync:()=>LQt,cpus:()=>Jer,createConnection:()=>str,createGunzip:()=>mtr,createGzip:()=>ptr,createHash:()=>hae,createHmac:()=>PQt,createInterface:()=>Wtr,createReadStream:()=>xer,createRequire:()=>gtr,createServer:()=>FQt,createWriteStream:()=>ker,debug:()=>ktr,debuglog:()=>yae,default:()=>IQt,deflateSync:()=>atr,deprecate:()=>xtr,deserialize:()=>qtr,dirname:()=>GQt,exec:()=>zer,execFile:()=>Ger,execFileSync:()=>jer,execSync:()=>qer,existsSync:()=>ser,extname:()=>HQt,fileURLToPath:()=>btr,finished:()=>oer,format:()=>wtr,freemem:()=>Yer,fstatSync:()=>ver,get:()=>rtr,gunzip:()=>dtr,gunzipSync:()=>ctr,gzip:()=>utr,gzipSync:()=>ltr,hasSubscribers:()=>Btr,homedir:()=>Ver,hostname:()=>Ker,inflateSync:()=>itr,inherits:()=>Ctr,inspect:()=>qk,isAbsolute:()=>WQt,isBuiltin:()=>vtr,isDeepStrictEqual:()=>Rtr,isIP:()=>err,isIPv4:()=>Qtr,isIPv6:()=>Ztr,isMainThread:()=>jtr,join:()=>zQt,loadavg:()=>der,lookup:()=>Otr,lstatSync:()=>Eer,mkdir:()=>Per,mkdirSync:()=>Ter,monitorEventLoopDelay:()=>Ftr,normalize:()=>YQt,ok:()=>htr,open:()=>$er,openSync:()=>ger,parentPort:()=>Htr,parse:()=>Ttr,pathToFileURL:()=>_tr,performance:()=>Ntr,pipeline:()=>ner,platform:()=>Her,posix:()=>JQt,promises:()=>RQt,promisify:()=>Atr,randomBytes:()=>MQt,randomUUID:()=>OQt,readFile:()=>Ier,readFileSync:()=>ier,readdir:()=>Oer,readdirSync:()=>Ser,realpath:()=>Uer,realpathSync:()=>her,relative:()=>VQt,release:()=>etr,rename:()=>Ler,renameSync:()=>_er,request:()=>ttr,resolve:()=>qQt,rm:()=>Fer,rmSync:()=>Aer,rmdirSync:()=>Cer,sep:()=>KQt,serialize:()=>ztr,setImmediate:()=>mer,setInterval:()=>irr,setTimeout:()=>orr,spawn:()=>Ber,stat:()=>Mer,statSync:()=>wer,strict:()=>ftr,tmpdir:()=>Wer,toUSVString:()=>Ptr,totalmem:()=>Xer,type:()=>Zer,types:()=>Mtr,unlink:()=>Der,unlinkSync:()=>ber,validateHeaderName:()=>UQt,validateHeaderValue:()=>BQt,webcrypto:()=>DQt,workerData:()=>Vtr,writeFile:()=>Rer,writeFileSync:()=>aer});var fo,An,IQt,RQt,hae,PQt,MQt,OQt,DQt,NQt,LQt,FQt,$Qt,UQt,BQt,zQt,qQt,GQt,jQt,HQt,VQt,WQt,KQt,JQt,YQt,XQt,ZQt,fae,gae,QQt,eer,ter,rer,ner,oer,ser,ier,aer,cer,ler,uer,der,mer,per,her,fer,ger,yer,ver,Ter,wer,Eer,Ser,ber,_er,Cer,Aer,ker,xer,Ier,Rer,Per,Mer,Oer,Der,Ner,Ler,Fer,$er,Uer,Ber,zer,qer,Ger,jer,Her,Ver,Wer,Ker,Jer,Yer,Xer,Zer,Qer,etr,ttr,rtr,ntr,otr,str,itr,atr,ctr,ltr,utr,dtr,mtr,ptr,htr,ftr,gtr,ytr,vtr,Ttr,wtr,Etr,Str,btr,_tr,Ctr,Atr,yae,ktr,qk,xtr,Itr,Rtr,Ptr,Mtr,vae,Gk,Otr,Dtr,Ntr,Ltr,Ftr,$tr,Utr,Btr,ztr,qtr,Gtr,jtr,Htr,Vtr,Wtr,Ktr,Jtr,Ytr,Xtr,Ztr,Qtr,err,trr,rrr,nrr,Tae,orr,srr,irr,arr,crr,men=b({"node-stub:url"(){fo=()=>{},An=async()=>{},IQt={},RQt={readFile:An,writeFile:An,mkdir:An,stat:An,readdir:An,unlink:An,access:An,rm:An,rename:An},hae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Gk().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}}},PQt=(e,t)=>hae(e),MQt=e=>new Uint8Array(e||32),OQt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),DQt=globalThis.crypto,NQt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},LQt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},FQt=()=>({listen:fo,close:fo,on:fo}),$Qt=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},UQt=fo,BQt=fo,zQt=(...e)=>e.join("/"),qQt=(...e)=>e.join("/"),GQt=e=>e||"",jQt=e=>e?.split?.("/")?.pop?.()||"",HQt=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},VQt=(e,t)=>t||"",WQt=()=>!1,KQt="/",JQt={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},YQt=e=>e,XQt=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},ZQt=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},fae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},gae=class{write(){return!0}end(){}on(){return this}destroy(){}},QQt=class{push(){}on(){return this}},eer=class{on(){return this}},ter=class{pipe(){return this}on(){return this}},rer=globalThis.ReadableStream||class{},ner=fo,oer=fo,ser=()=>!1,ier=()=>"",aer=fo,cer=fo,ler=An,uer=()=>1,der=()=>[0,0,0],mer=An,per=An,her=e=>e,fer=fo,ger=()=>0,yer=fo,ver=()=>({}),Ter=fo,wer=()=>({}),Eer=()=>({isSymbolicLink:()=>!1}),Ser=()=>[],ber=fo,_er=fo,Cer=fo,Aer=fo,ker=()=>new gae,xer=()=>new fae,Ier=An,Rer=An,Per=An,Mer=An,Oer=An,Der=An,Ner=An,Ler=An,Fer=An,$er=async()=>({stat:An,readFile:An,close:An,read:An,write:An}),Uer=async e=>e,Ber=()=>({on:fo,stdout:{on:fo},stderr:{on:fo},kill:fo}),zer=(e,t)=>t?.(null,"",""),qer=()=>"",Ger=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},jer=()=>"",Her="browser",Ver=()=>"/",Wer=()=>"/tmp",Ker=()=>"browser",Jer=()=>[{}],Yer=()=>0,Xer=()=>0,Zer=()=>"Browser",Qer=()=>"wasm",etr=()=>"0",ttr=()=>({}),rtr=()=>({}),ntr={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},otr=()=>({}),str=()=>({}),itr=()=>new Uint8Array,atr=()=>new Uint8Array,ctr=()=>new Uint8Array,ltr=()=>new Uint8Array,utr=(e,t)=>t?.(null,e),dtr=(e,t)=>t?.(null,e),mtr=()=>({}),ptr=()=>({}),htr=fo,ftr={},gtr=()=>()=>({}),ytr=[],vtr=()=>!1,Ttr=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),wtr=()=>"",Etr=globalThis.URL,Str=globalThis.URLSearchParams,btr=e=>typeof e=="string"?e.replace("file://",""):e,_tr=e=>new globalThis.URL("file://"+e),Ctr=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},Atr=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),yae=e=>{const t=(...r)=>{};return t.enabled=!1,t},ktr=yae,qk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},qk.custom=Symbol.for("nodejs.util.inspect.custom"),qk.colors={},qk.styles={},xtr=e=>e,Itr=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},Rtr=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Ptr=e=>String(e),Mtr={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},vae=globalThis.TextDecoder,Gk=globalThis.TextEncoder,Otr=(e,t)=>t?.(null,"127.0.0.1",4),Dtr=class{},Ntr=globalThis.performance||{now:()=>Date.now()},Ltr=class{observe(){}disconnect(){}},Ftr=()=>({enable:fo,disable:fo,percentile:()=>0}),$tr=()=>({}),Utr=class{},Btr=()=>!1,ztr=()=>new Uint8Array,qtr=fo,Gtr=class{},jtr=!0,Htr=null,Vtr=null,Wtr=()=>({}),Ktr=class{},Jtr=class{},Ytr=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 Gk().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 Gk().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 vae().decode(this)}},Xtr={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Ztr=()=>!1,Qtr=()=>!1,err=()=>0,trr=class{},rrr=class{},nrr=async()=>new ArrayBuffer(0),Tae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),orr=(...e)=>Tae(globalThis.setTimeout(...e)),srr=globalThis.clearTimeout,irr=(...e)=>Tae(globalThis.setInterval(...e)),arr=globalThis.clearInterval,crr=class{constructor(e){this.type=e}toString(){return this.type}}}}),Gp=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/constants.js"(e,t){"use strict";var r=["nodebuffer","arraybuffer","fragments"],n=typeof Blob<"u";n&&r.push("blob"),t.exports={BINARY_TYPES:r,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:n,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}}),PF=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/buffer-util.js"(e,t){"use strict";var{EMPTY_BUFFER:r}=Gp(),n=Buffer[Symbol.species];function o(l,u){if(l.length===0)return r;if(l.length===1)return l[0];const d=Buffer.allocUnsafe(u);let m=0;for(let h=0;h<l.length;h++){const f=l[h];d.set(f,m),m+=f.length}return m<u?new n(d.buffer,d.byteOffset,m):d}function s(l,u,d,m,h){for(let f=0;f<h;f++)d[m+f]=l[f]^u[f&3]}function i(l,u){for(let d=0;d<l.length;d++)l[d]^=u[d&3]}function a(l){return l.length===l.buffer.byteLength?l.buffer:l.buffer.slice(l.byteOffset,l.byteOffset+l.length)}function c(l){if(c.readOnly=!0,Buffer.isBuffer(l))return l;let u;return l instanceof ArrayBuffer?u=new n(l):ArrayBuffer.isView(l)?u=new n(l.buffer,l.byteOffset,l.byteLength):(u=Buffer.from(l),c.readOnly=!1),u}if(t.exports={concat:o,mask:s,toArrayBuffer:a,toBuffer:c,unmask:i},!process.env.WS_NO_BUFFER_UTIL)try{const l=Qde("bufferutil");t.exports.mask=function(u,d,m,h,f){f<48?s(u,d,m,h,f):l.mask(u,d,m,h,f)},t.exports.unmask=function(u,d){u.length<32?i(u,d):l.unmask(u,d)}}catch{}}}),pen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/limiter.js"(e,t){"use strict";var r=Symbol("kDone"),n=Symbol("kRun"),o=class{constructor(s){this[r]=()=>{this.pending--,this[n]()},this.concurrency=s||1/0,this.jobs=[],this.pending=0}add(s){this.jobs.push(s),this[n]()}[n](){if(this.pending!==this.concurrency&&this.jobs.length){const s=this.jobs.shift();this.pending++,s(this[r])}}};t.exports=o}}),jk=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/permessage-deflate.js"(e,t){"use strict";var r=(Kh(),Br(Wh)),n=PF(),o=pen(),{kStatusCode:s}=Gp(),i=Buffer[Symbol.species],a=Buffer.from([0,0,255,255]),c=Symbol("permessage-deflate"),l=Symbol("total-length"),u=Symbol("callback"),d=Symbol("buffers"),m=Symbol("error"),h,f=class{constructor(w){if(this._options=w||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!h){const E=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;h=new o(E)}}static get extensionName(){return"permessage-deflate"}offer(){const w={};return this._options.serverNoContextTakeover&&(w.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(w.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(w.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?w.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(w.client_max_window_bits=!0),w}accept(w){return w=this.normalizeParams(w),this.params=this._isServer?this.acceptAsServer(w):this.acceptAsClient(w),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const w=this._deflate[u];this._deflate.close(),this._deflate=null,w&&w(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(w){const E=this._options,_=w.find(C=>!(E.serverNoContextTakeover===!1&&C.server_no_context_takeover||C.server_max_window_bits&&(E.serverMaxWindowBits===!1||typeof E.serverMaxWindowBits=="number"&&E.serverMaxWindowBits>C.server_max_window_bits)||typeof E.clientMaxWindowBits=="number"&&!C.client_max_window_bits));if(!_)throw new Error("None of the extension offers can be accepted");return E.serverNoContextTakeover&&(_.server_no_context_takeover=!0),E.clientNoContextTakeover&&(_.client_no_context_takeover=!0),typeof E.serverMaxWindowBits=="number"&&(_.server_max_window_bits=E.serverMaxWindowBits),typeof E.clientMaxWindowBits=="number"?_.client_max_window_bits=E.clientMaxWindowBits:(_.client_max_window_bits===!0||E.clientMaxWindowBits===!1)&&delete _.client_max_window_bits,_}acceptAsClient(w){const E=w[0];if(this._options.clientNoContextTakeover===!1&&E.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!E.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(E.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&E.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return E}normalizeParams(w){return w.forEach(E=>{Object.keys(E).forEach(_=>{let C=E[_];if(C.length>1)throw new Error(`Parameter "${_}" must have only a single value`);if(C=C[0],_==="client_max_window_bits"){if(C!==!0){const A=+C;if(!Number.isInteger(A)||A<8||A>15)throw new TypeError(`Invalid value for parameter "${_}": ${C}`);C=A}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${_}": ${C}`)}else if(_==="server_max_window_bits"){const A=+C;if(!Number.isInteger(A)||A<8||A>15)throw new TypeError(`Invalid value for parameter "${_}": ${C}`);C=A}else if(_==="client_no_context_takeover"||_==="server_no_context_takeover"){if(C!==!0)throw new TypeError(`Invalid value for parameter "${_}": ${C}`)}else throw new Error(`Unknown parameter "${_}"`);E[_]=C})}),w}decompress(w,E,_){h.add(C=>{this._decompress(w,E,(A,k)=>{C(),_(A,k)})})}compress(w,E,_){h.add(C=>{this._compress(w,E,(A,k)=>{C(),_(A,k)})})}_decompress(w,E,_){const C=this._isServer?"client":"server";if(!this._inflate){const A=`${C}_max_window_bits`,k=typeof this.params[A]!="number"?r.Z_DEFAULT_WINDOWBITS:this.params[A];this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:k}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on("error",v),this._inflate.on("data",y)}this._inflate[u]=_,this._inflate.write(w),E&&this._inflate.write(a),this._inflate.flush(()=>{const A=this._inflate[m];if(A){this._inflate.close(),this._inflate=null,_(A);return}const k=n.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],E&&this.params[`${C}_no_context_takeover`]&&this._inflate.reset()),_(null,k)})}_compress(w,E,_){const C=this._isServer?"server":"client";if(!this._deflate){const A=`${C}_max_window_bits`,k=typeof this.params[A]!="number"?r.Z_DEFAULT_WINDOWBITS:this.params[A];this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:k}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on("data",g)}this._deflate[u]=_,this._deflate.write(w),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let A=n.concat(this._deflate[d],this._deflate[l]);E&&(A=new i(A.buffer,A.byteOffset,A.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],E&&this.params[`${C}_no_context_takeover`]&&this._deflate.reset(),_(null,A)})}};t.exports=f;function g(w){this[d].push(w),this[l]+=w.length}function y(w){if(this[l]+=w.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(w);return}this[m]=new RangeError("Max payload size exceeded"),this[m].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[m][s]=1009,this.removeListener("data",y),this.reset()}function v(w){if(this[c]._inflate=null,this[m]){this[u](this[m]);return}w[s]=1007,this[u](w)}}}),lrr={};ee(lrr,{Agent:()=>Trr,AsyncLocalStorage:()=>Orr,Buffer:()=>Mor,Channel:()=>Eor,DatabaseSync:()=>Por,Duplex:()=>Nrr,EventEmitter:()=>Mrr,Http2ServerRequest:()=>For,Http2ServerResponse:()=>$or,Interface:()=>Ror,MIMEType:()=>jor,PassThrough:()=>Lrr,PerformanceObserver:()=>vor,Readable:()=>Eae,ReadableStream:()=>Frr,Resolver:()=>gor,STATUS_CODES:()=>$nr,TextDecoder:()=>_ae,TextEncoder:()=>Vk,Transform:()=>Drr,URL:()=>ror,URLSearchParams:()=>nor,Worker:()=>Cor,Writable:()=>Sae,access:()=>gnr,appendFile:()=>Krr,appendFileSync:()=>grr,arch:()=>Dnr,arrayBuffer:()=>Uor,availableParallelism:()=>Hrr,basename:()=>Crr,builtinModules:()=>Znr,callbackify:()=>uor,channel:()=>wor,chmod:()=>jrr,chmodSync:()=>Grr,clearInterval:()=>Gor,clearTimeout:()=>zor,closeSync:()=>Zrr,connect:()=>Unr,constants:()=>Oor,copyFileSync:()=>Yrr,cpSync:()=>yrr,cpus:()=>Rnr,createConnection:()=>Bnr,createGunzip:()=>Wnr,createGzip:()=>Knr,createHash:()=>wae,createHmac:()=>mrr,createInterface:()=>Ior,createReadStream:()=>lnr,createRequire:()=>Xnr,createServer:()=>vrr,createWriteStream:()=>cnr,debug:()=>cor,debuglog:()=>bae,default:()=>urr,deflateSync:()=>qnr,deprecate:()=>lor,deserialize:()=>_or,dirname:()=>_rr,exec:()=>Snr,execFile:()=>_nr,execFileSync:()=>Cnr,execSync:()=>bnr,existsSync:()=>Brr,extname:()=>Arr,fileURLToPath:()=>oor,finished:()=>Urr,format:()=>tor,freemem:()=>Pnr,fstatSync:()=>Qrr,get:()=>Fnr,gunzip:()=>Vnr,gunzipSync:()=>Gnr,gzip:()=>Hnr,gzipSync:()=>jnr,hasSubscribers:()=>Sor,homedir:()=>knr,hostname:()=>Inr,inflateSync:()=>znr,inherits:()=>ior,inspect:()=>Hk,isAbsolute:()=>xrr,isBuiltin:()=>Qnr,isDeepStrictEqual:()=>dor,isIP:()=>Lor,isIPv4:()=>Nor,isIPv6:()=>Dor,isMainThread:()=>Aor,join:()=>Srr,loadavg:()=>Vrr,lookup:()=>hor,lstatSync:()=>rnr,mkdir:()=>mnr,mkdirSync:()=>enr,monitorEventLoopDelay:()=>Tor,normalize:()=>Prr,ok:()=>Jnr,open:()=>Tnr,openSync:()=>Xrr,parentPort:()=>kor,parse:()=>eor,pathToFileURL:()=>sor,performance:()=>yor,pipeline:()=>$rr,platform:()=>Anr,posix:()=>Rrr,promises:()=>drr,promisify:()=>aor,randomBytes:()=>prr,randomUUID:()=>hrr,readFile:()=>unr,readFileSync:()=>zrr,readdir:()=>hnr,readdirSync:()=>nnr,realpath:()=>wnr,realpathSync:()=>Jrr,relative:()=>krr,release:()=>Nnr,rename:()=>ynr,renameSync:()=>snr,request:()=>Lnr,resolve:()=>brr,rm:()=>vnr,rmSync:()=>anr,rmdirSync:()=>inr,sep:()=>Irr,serialize:()=>bor,setImmediate:()=>Wrr,setInterval:()=>qor,setTimeout:()=>Bor,spawn:()=>Enr,stat:()=>pnr,statSync:()=>tnr,strict:()=>Ynr,tmpdir:()=>xnr,toUSVString:()=>mor,totalmem:()=>Mnr,type:()=>Onr,types:()=>por,unlink:()=>fnr,unlinkSync:()=>onr,validateHeaderName:()=>wrr,validateHeaderValue:()=>Err,webcrypto:()=>frr,workerData:()=>xor,writeFile:()=>dnr,writeFileSync:()=>qrr});var go,kn,urr,drr,wae,mrr,prr,hrr,frr,grr,yrr,vrr,Trr,wrr,Err,Srr,brr,_rr,Crr,Arr,krr,xrr,Irr,Rrr,Prr,Mrr,Orr,Eae,Sae,Drr,Nrr,Lrr,Frr,$rr,Urr,Brr,zrr,qrr,Grr,jrr,Hrr,Vrr,Wrr,Krr,Jrr,Yrr,Xrr,Zrr,Qrr,enr,tnr,rnr,nnr,onr,snr,inr,anr,cnr,lnr,unr,dnr,mnr,pnr,hnr,fnr,gnr,ynr,vnr,Tnr,wnr,Enr,Snr,bnr,_nr,Cnr,Anr,knr,xnr,Inr,Rnr,Pnr,Mnr,Onr,Dnr,Nnr,Lnr,Fnr,$nr,Unr,Bnr,znr,qnr,Gnr,jnr,Hnr,Vnr,Wnr,Knr,Jnr,Ynr,Xnr,Znr,Qnr,eor,tor,ror,nor,oor,sor,ior,aor,bae,cor,Hk,lor,uor,dor,mor,por,_ae,Vk,hor,gor,yor,vor,Tor,wor,Eor,Sor,bor,_or,Cor,Aor,kor,xor,Ior,Ror,Por,Mor,Oor,Dor,Nor,Lor,For,$or,Uor,Cae,Bor,zor,qor,Gor,jor,hen=b({"node-stub:buffer"(){go=()=>{},kn=async()=>{},urr={},drr={readFile:kn,writeFile:kn,mkdir:kn,stat:kn,readdir:kn,unlink:kn,access:kn,rm:kn,rename:kn},wae=e=>{const t=[];return{update(r){return t.push(typeof r=="string"?new Vk().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}}},mrr=(e,t)=>wae(e),prr=e=>new Uint8Array(e||32),hrr=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),frr=globalThis.crypto,grr=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},yrr=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},vrr=()=>({listen:go,close:go,on:go}),Trr=class{constructor(){throw new Error("[NeuroLink:browser] Node HTTP agents require a server runtime")}},wrr=go,Err=go,Srr=(...e)=>e.join("/"),brr=(...e)=>e.join("/"),_rr=e=>e||"",Crr=e=>e?.split?.("/")?.pop?.()||"",Arr=e=>{const t=e?.match?.(/\.[^.]+$/);return t?t[0]:""},krr=(e,t)=>t||"",xrr=()=>!1,Irr="/",Rrr={normalize:e=>e,join:(...e)=>e.join("/"),resolve:(...e)=>e.join("/"),sep:"/"},Prr=e=>e,Mrr=class{constructor(){this._ev=new Map}_list(t){let r=this._ev.get(t);return r||(r=[],this._ev.set(t,r)),r}on(t,r){return this._list(t).push(r),this}addListener(t,r){return this.on(t,r)}prependListener(t,r){return this._list(t).unshift(r),this}once(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.on(t,n)}prependOnceListener(t,r){const n=(...o)=>{this.off(t,n),r(...o)};return n.listener=r,this.prependListener(t,n)}off(t,r){const n=this._ev.get(t);if(n){const o=n.findIndex(s=>s===r||s.listener===r);o>=0&&n.splice(o,1)}return this}removeListener(t,r){return this.off(t,r)}removeAllListeners(t){return t===void 0?this._ev.clear():this._ev.delete(t),this}emit(t,...r){const n=this._ev.get(t);if(!n||n.length===0){if(t==="error")throw r[0]instanceof Error?r[0]:new Error("Unhandled error.");return!1}for(const o of[...n])o.apply(this,r);return!0}listenerCount(t){return(this._ev.get(t)||[]).length}listeners(t){return[...this._ev.get(t)||[]]}rawListeners(t){return this.listeners(t)}eventNames(){return[...this._ev.keys()]}setMaxListeners(){return this}getMaxListeners(){return 10}},Orr=class{getStore(){}run(e,t,...r){return t(...r)}enterWith(){}disable(){}},Eae=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},Sae=class{write(){return!0}end(){}on(){return this}destroy(){}},Drr=class{push(){}on(){return this}},Nrr=class{on(){return this}},Lrr=class{pipe(){return this}on(){return this}},Frr=globalThis.ReadableStream||class{},$rr=go,Urr=go,Brr=()=>!1,zrr=()=>"",qrr=go,Grr=go,jrr=kn,Hrr=()=>1,Vrr=()=>[0,0,0],Wrr=kn,Krr=kn,Jrr=e=>e,Yrr=go,Xrr=()=>0,Zrr=go,Qrr=()=>({}),enr=go,tnr=()=>({}),rnr=()=>({isSymbolicLink:()=>!1}),nnr=()=>[],onr=go,snr=go,inr=go,anr=go,cnr=()=>new Sae,lnr=()=>new Eae,unr=kn,dnr=kn,mnr=kn,pnr=kn,hnr=kn,fnr=kn,gnr=kn,ynr=kn,vnr=kn,Tnr=async()=>({stat:kn,readFile:kn,close:kn,read:kn,write:kn}),wnr=async e=>e,Enr=()=>({on:go,stdout:{on:go},stderr:{on:go},kill:go}),Snr=(e,t)=>t?.(null,"",""),bnr=()=>"",_nr=(e,t,r)=>{typeof t=="function"?t(null,"",""):r?.(null,"","")},Cnr=()=>"",Anr="browser",knr=()=>"/",xnr=()=>"/tmp",Inr=()=>"browser",Rnr=()=>[{}],Pnr=()=>0,Mnr=()=>0,Onr=()=>"Browser",Dnr=()=>"wasm",Nnr=()=>"0",Lnr=()=>({}),Fnr=()=>({}),$nr={100:"Continue",101:"Switching Protocols",200:"OK",201:"Created",202:"Accepted",204:"No Content",206:"Partial Content",301:"Moved Permanently",302:"Found",304:"Not Modified",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",422:"Unprocessable Entity",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported"},Unr=()=>({}),Bnr=()=>({}),znr=()=>new Uint8Array,qnr=()=>new Uint8Array,Gnr=()=>new Uint8Array,jnr=()=>new Uint8Array,Hnr=(e,t)=>t?.(null,e),Vnr=(e,t)=>t?.(null,e),Wnr=()=>({}),Knr=()=>({}),Jnr=go,Ynr={},Xnr=()=>()=>({}),Znr=[],Qnr=()=>!1,eor=e=>({pathname:e||"",hostname:"",protocol:"",search:"",hash:""}),tor=()=>"",ror=globalThis.URL,nor=globalThis.URLSearchParams,oor=e=>typeof e=="string"?e.replace("file://",""):e,sor=e=>new globalThis.URL("file://"+e),ior=(e,t)=>{t&&(e.super_=t,Object.setPrototypeOf(e.prototype,t.prototype))},aor=e=>(...t)=>new Promise((r,n)=>e(...t,(o,s)=>o?n(o):r(s))),bae=e=>{const t=(...r)=>{};return t.enabled=!1,t},cor=bae,Hk=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},Hk.custom=Symbol.for("nodejs.util.inspect.custom"),Hk.colors={},Hk.styles={},lor=e=>e,uor=e=>(...t)=>{const r=t.pop();e(...t).then(n=>r(null,n)).catch(r)},dor=(e,t)=>JSON.stringify(e)===JSON.stringify(t),mor=e=>String(e),por={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},_ae=globalThis.TextDecoder,Vk=globalThis.TextEncoder,hor=(e,t)=>t?.(null,"127.0.0.1",4),gor=class{},yor=globalThis.performance||{now:()=>Date.now()},vor=class{observe(){}disconnect(){}},Tor=()=>({enable:go,disable:go,percentile:()=>0}),wor=()=>({}),Eor=class{},Sor=()=>!1,bor=()=>new Uint8Array,_or=go,Cor=class{},Aor=!0,kor=null,xor=null,Ior=()=>({}),Ror=class{},Por=class{},Mor=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 Vk().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 Vk().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 _ae().decode(this)}},Oor={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Dor=()=>!1,Nor=()=>!1,Lor=()=>0,For=class{},$or=class{},Uor=async()=>new ArrayBuffer(0),Cae=e=>({[Symbol.toPrimitive](){return e},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),Bor=(...e)=>Cae(globalThis.setTimeout(...e)),zor=globalThis.clearTimeout,qor=(...e)=>Cae(globalThis.setInterval(...e)),Gor=globalThis.clearInterval,jor=class{constructor(e){this.type=e}toString(){return this.type}}}}),Wk=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/validation.js"(e,t){"use strict";var{isUtf8:r}=(hen(),Br(lrr)),{hasBlob:n}=Gp(),o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function s(c){return c>=1e3&&c<=1014&&c!==1004&&c!==1005&&c!==1006||c>=3e3&&c<=4999}function i(c){const l=c.length;let u=0;for(;u<l;)if((c[u]&128)===0)u++;else if((c[u]&224)===192){if(u+1===l||(c[u+1]&192)!==128||(c[u]&254)===192)return!1;u+=2}else if((c[u]&240)===224){if(u+2>=l||(c[u+1]&192)!==128||(c[u+2]&192)!==128||c[u]===224&&(c[u+1]&224)===128||c[u]===237&&(c[u+1]&224)===160)return!1;u+=3}else if((c[u]&248)===240){if(u+3>=l||(c[u+1]&192)!==128||(c[u+2]&192)!==128||(c[u+3]&192)!==128||c[u]===240&&(c[u+1]&240)===128||c[u]===244&&c[u+1]>143||c[u]>244)return!1;u+=4}else return!1;return!0}function a(c){return n&&typeof c=="object"&&typeof c.arrayBuffer=="function"&&typeof c.type=="string"&&typeof c.stream=="function"&&(c[Symbol.toStringTag]==="Blob"||c[Symbol.toStringTag]==="File")}if(t.exports={isBlob:a,isValidStatusCode:s,isValidUTF8:i,tokenChars:o},r)t.exports.isValidUTF8=function(c){return c.length<24?i(c):r(c)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const c=Qde("utf-8-validate");t.exports.isValidUTF8=function(l){return l.length<32?i(l):c(l)}}catch{}}}),Hor=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/receiver.js"(e,t){"use strict";var{Writable:r}=(Nh(),Br(c0)),n=jk(),{BINARY_TYPES:o,EMPTY_BUFFER:s,kStatusCode:i,kWebSocket:a}=Gp(),{concat:c,toArrayBuffer:l,unmask:u}=PF(),{isValidStatusCode:d,isValidUTF8:m}=Wk(),h=Buffer[Symbol.species],f=0,g=1,y=2,v=3,w=4,E=5,_=6,C=class extends r{constructor(A={}){super(),this._allowSynchronousEvents=A.allowSynchronousEvents!==void 0?A.allowSynchronousEvents:!0,this._binaryType=A.binaryType||o[0],this._extensions=A.extensions||{},this._isServer=!!A.isServer,this._maxBufferedChunks=A.maxBufferedChunks|0,this._maxFragments=A.maxFragments|0,this._maxPayload=A.maxPayload|0,this._skipUTF8Validation=!!A.skipUTF8Validation,this[a]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=f}_write(A,k,R){if(this._opcode===8&&this._state==f)return R();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){R(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=A.length,this._buffers.push(A),this.startLoop(R)}consume(A){if(this._bufferedBytes-=A,A===this._buffers[0].length)return this._buffers.shift();if(A<this._buffers[0].length){const R=this._buffers[0];return this._buffers[0]=new h(R.buffer,R.byteOffset+A,R.length-A),new h(R.buffer,R.byteOffset,A)}const k=Buffer.allocUnsafe(A);do{const R=this._buffers[0],I=k.length-A;A>=R.length?k.set(this._buffers.shift(),I):(k.set(new Uint8Array(R.buffer,R.byteOffset,A),I),this._buffers[0]=new h(R.buffer,R.byteOffset+A,R.length-A)),A-=R.length}while(A>0);return k}startLoop(A){this._loop=!0;do switch(this._state){case f:this.getInfo(A);break;case g:this.getPayloadLength16(A);break;case y:this.getPayloadLength64(A);break;case v:this.getMask();break;case w:this.getData(A);break;case E:case _:this._loop=!1;return}while(this._loop);this._errored||A()}getInfo(A){if(this._bufferedBytes<2){this._loop=!1;return}const k=this.consume(2);if((k[0]&48)!==0){const I=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");A(I);return}const R=(k[0]&64)===64;if(R&&!this._extensions[n.extensionName]){const I=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(I);return}if(this._fin=(k[0]&128)===128,this._opcode=k[0]&15,this._payloadLength=k[1]&127,this._opcode===0){if(R){const I=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(I);return}if(!this._fragmented){const I=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");A(I);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){const I=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(I);return}this._compressed=R}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const I=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");A(I);return}if(R){const I=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");A(I);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){const I=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");A(I);return}}else{const I=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");A(I);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(k[1]&128)===128,this._isServer){if(!this._masked){const I=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");A(I);return}}else if(this._masked){const I=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");A(I);return}this._payloadLength===126?this._state=g:this._payloadLength===127?this._state=y:this.haveLength(A)}getPayloadLength16(A){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(A)}getPayloadLength64(A){if(this._bufferedBytes<8){this._loop=!1;return}const k=this.consume(8),R=k.readUInt32BE(0);if(R>Math.pow(2,21)-1){const I=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");A(I);return}this._payloadLength=R*Math.pow(2,32)+k.readUInt32BE(4),this.haveLength(A)}haveLength(A){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){const k=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");A(k);return}this._masked?this._state=v:this._state=w}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=w}getData(A){let k=s;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}k=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(k,this._mask)}if(this._opcode>7){this.controlMessage(k,A);return}if(this._compressed){this._state=E,this.decompress(k,A);return}if(k.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const R=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");A(R);return}this._messageLength=this._totalPayloadLength,this._fragments.push(k)}this.dataMessage(A)}decompress(A,k){this._extensions[n.extensionName].decompress(A,this._fin,(I,P)=>{if(I)return k(I);if(P.length){if(this._messageLength+=P.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const O=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");k(O);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){const O=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");k(O);return}this._fragments.push(P)}this.dataMessage(k),this._state===f&&this.startLoop(k)})}dataMessage(A){if(!this._fin){this._state=f;return}const k=this._messageLength,R=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let I;this._binaryType==="nodebuffer"?I=c(R,k):this._binaryType==="arraybuffer"?I=l(c(R,k)):this._binaryType==="blob"?I=new Blob(R):I=R,this._allowSynchronousEvents?(this.emit("message",I,!0),this._state=f):(this._state=_,setImmediate(()=>{this.emit("message",I,!0),this._state=f,this.startLoop(A)}))}else{const I=c(R,k);if(!this._skipUTF8Validation&&!m(I)){const P=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");A(P);return}this._state===E||this._allowSynchronousEvents?(this.emit("message",I,!1),this._state=f):(this._state=_,setImmediate(()=>{this.emit("message",I,!1),this._state=f,this.startLoop(A)}))}}controlMessage(A,k){if(this._opcode===8){if(A.length===0)this._loop=!1,this.emit("conclude",1005,s),this.end();else{const R=A.readUInt16BE(0);if(!d(R)){const P=this.createError(RangeError,`invalid status code ${R}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");k(P);return}const I=new h(A.buffer,A.byteOffset+2,A.length-2);if(!this._skipUTF8Validation&&!m(I)){const P=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");k(P);return}this._loop=!1,this.emit("conclude",R,I),this.end()}this._state=f;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",A),this._state=f):(this._state=_,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",A),this._state=f,this.startLoop(k)}))}createError(A,k,R,I,P){this._loop=!1,this._errored=!0;const O=new A(R?`Invalid WebSocket frame: ${k}`:k);return Error.captureStackTrace(O,this.createError),O.code=P,O[i]=I,O}};t.exports=C}}),Vor=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/sender.js"(e,t){"use strict";var{Duplex:r}=(Nh(),Br(c0)),{randomFillSync:n}=(Dt(),Br(AS)),{types:{isUint8Array:o}}=(y4(),Br(g4)),s=jk(),{EMPTY_BUFFER:i,kWebSocket:a,NOOP:c}=Gp(),{isBlob:l,isValidStatusCode:u}=Wk(),{mask:d,toBuffer:m}=PF(),h=Symbol("kByteLength"),f=Buffer.alloc(4),g=8*1024,y,v=g,w=0,E=1,_=2,C=class vy{constructor(I,P,O){this._extensions=P||{},O&&(this._generateMask=O,this._maskBuffer=Buffer.alloc(4)),this._socket=I,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=c,this[a]=void 0}static frame(I,P){let O,U=!1,M=2,F=!1;P.mask&&(O=P.maskBuffer||f,P.generateMask?P.generateMask(O):(v===g&&(y===void 0&&(y=Buffer.alloc(g)),n(y,0,g),v=0),O[0]=y[v++],O[1]=y[v++],O[2]=y[v++],O[3]=y[v++]),F=(O[0]|O[1]|O[2]|O[3])===0,M=6);let N;typeof I=="string"?(!P.mask||F)&&P[h]!==void 0?N=P[h]:(I=Buffer.from(I),N=I.length):(N=I.length,U=P.mask&&P.readOnly&&!F);let L=N;N>=65536?(M+=8,L=127):N>125&&(M+=2,L=126);const q=Buffer.allocUnsafe(U?N+M:M);return q[0]=P.fin?P.opcode|128:P.opcode,P.rsv1&&(q[0]|=64),q[1]=L,L===126?q.writeUInt16BE(N,2):L===127&&(q[2]=q[3]=0,q.writeUIntBE(N,4,6)),P.mask?(q[1]|=128,q[M-4]=O[0],q[M-3]=O[1],q[M-2]=O[2],q[M-1]=O[3],F?[q,I]:U?(d(I,O,q,M,N),[q]):(d(I,O,I,0,N),[q,I])):[q,I]}close(I,P,O,U){let M;if(I===void 0)M=i;else{if(typeof I!="number"||!u(I))throw new TypeError("First argument must be a valid error code number");if(P===void 0||!P.length)M=Buffer.allocUnsafe(2),M.writeUInt16BE(I,0);else{const N=Buffer.byteLength(P);if(N>123)throw new RangeError("The message must not be greater than 123 bytes");if(M=Buffer.allocUnsafe(2+N),M.writeUInt16BE(I,0),typeof P=="string")M.write(P,2);else if(o(P))M.set(P,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}const F={[h]:M.length,fin:!0,generateMask:this._generateMask,mask:O,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,M,!1,F,U]):this.sendFrame(vy.frame(M,F),U)}ping(I,P,O){let U,M;if(typeof I=="string"?(U=Buffer.byteLength(I),M=!1):l(I)?(U=I.size,M=!1):(I=m(I),U=I.length,M=m.readOnly),U>125)throw new RangeError("The data size must not be greater than 125 bytes");const F={[h]:U,fin:!0,generateMask:this._generateMask,mask:P,maskBuffer:this._maskBuffer,opcode:9,readOnly:M,rsv1:!1};l(I)?this._state!==w?this.enqueue([this.getBlobData,I,!1,F,O]):this.getBlobData(I,!1,F,O):this._state!==w?this.enqueue([this.dispatch,I,!1,F,O]):this.sendFrame(vy.frame(I,F),O)}pong(I,P,O){let U,M;if(typeof I=="string"?(U=Buffer.byteLength(I),M=!1):l(I)?(U=I.size,M=!1):(I=m(I),U=I.length,M=m.readOnly),U>125)throw new RangeError("The data size must not be greater than 125 bytes");const F={[h]:U,fin:!0,generateMask:this._generateMask,mask:P,maskBuffer:this._maskBuffer,opcode:10,readOnly:M,rsv1:!1};l(I)?this._state!==w?this.enqueue([this.getBlobData,I,!1,F,O]):this.getBlobData(I,!1,F,O):this._state!==w?this.enqueue([this.dispatch,I,!1,F,O]):this.sendFrame(vy.frame(I,F),O)}send(I,P,O){const U=this._extensions[s.extensionName];let M=P.binary?2:1,F=P.compress,N,L;typeof I=="string"?(N=Buffer.byteLength(I),L=!1):l(I)?(N=I.size,L=!1):(I=m(I),N=I.length,L=m.readOnly),this._firstFragment?(this._firstFragment=!1,F&&U&&U.params[U._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(F=N>=U._threshold),this._compress=F):(F=!1,M=0),P.fin&&(this._firstFragment=!0);const q={[h]:N,fin:P.fin,generateMask:this._generateMask,mask:P.mask,maskBuffer:this._maskBuffer,opcode:M,readOnly:L,rsv1:F};l(I)?this._state!==w?this.enqueue([this.getBlobData,I,this._compress,q,O]):this.getBlobData(I,this._compress,q,O):this._state!==w?this.enqueue([this.dispatch,I,this._compress,q,O]):this.dispatch(I,this._compress,q,O)}getBlobData(I,P,O,U){this._bufferedBytes+=O[h],this._state=_,I.arrayBuffer().then(M=>{if(this._socket.destroyed){const N=new Error("The socket was closed while the blob was being read");process.nextTick(A,this,N,U);return}this._bufferedBytes-=O[h];const F=m(M);P?this.dispatch(F,P,O,U):(this._state=w,this.sendFrame(vy.frame(F,O),U),this.dequeue())}).catch(M=>{process.nextTick(k,this,M,U)})}dispatch(I,P,O,U){if(!P){this.sendFrame(vy.frame(I,O),U);return}const M=this._extensions[s.extensionName];this._bufferedBytes+=O[h],this._state=E,M.compress(I,O.fin,(F,N)=>{if(this._socket.destroyed){const L=new Error("The socket was closed while data was being compressed");A(this,L,U);return}this._bufferedBytes-=O[h],this._state=w,O.readOnly=!1,this.sendFrame(vy.frame(N,O),U),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){const I=this._queue.shift();this._bufferedBytes-=I[3][h],Reflect.apply(I[0],this,I.slice(1))}}enqueue(I){this._bufferedBytes+=I[3][h],this._queue.push(I)}sendFrame(I,P){I.length===2?(this._socket.cork(),this._socket.write(I[0]),this._socket.write(I[1],P),this._socket.uncork()):this._socket.write(I[0],P)}};t.exports=C;function A(R,I,P){typeof P=="function"&&P(I);for(let O=0;O<R._queue.length;O++){const U=R._queue[O],M=U[U.length-1];typeof M=="function"&&M(I)}}function k(R,I,P){A(R,I,P),R.onerror(I)}}}),fen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/event-target.js"(e,t){"use strict";var{kForOnEventAttribute:r,kListener:n}=Gp(),o=Symbol("kCode"),s=Symbol("kData"),i=Symbol("kError"),a=Symbol("kMessage"),c=Symbol("kReason"),l=Symbol("kTarget"),u=Symbol("kType"),d=Symbol("kWasClean"),m=class{constructor(w){this[l]=null,this[u]=w}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(m.prototype,"target",{enumerable:!0}),Object.defineProperty(m.prototype,"type",{enumerable:!0});var h=class extends m{constructor(w,E={}){super(w),this[o]=E.code===void 0?0:E.code,this[c]=E.reason===void 0?"":E.reason,this[d]=E.wasClean===void 0?!1:E.wasClean}get code(){return this[o]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(h.prototype,"code",{enumerable:!0}),Object.defineProperty(h.prototype,"reason",{enumerable:!0}),Object.defineProperty(h.prototype,"wasClean",{enumerable:!0});var f=class extends m{constructor(w,E={}){super(w),this[i]=E.error===void 0?null:E.error,this[a]=E.message===void 0?"":E.message}get error(){return this[i]}get message(){return this[a]}};Object.defineProperty(f.prototype,"error",{enumerable:!0}),Object.defineProperty(f.prototype,"message",{enumerable:!0});var g=class extends m{constructor(w,E={}){super(w),this[s]=E.data===void 0?null:E.data}get data(){return this[s]}};Object.defineProperty(g.prototype,"data",{enumerable:!0});var y={addEventListener(w,E,_={}){for(const A of this.listeners(w))if(!_[r]&&A[n]===E&&!A[r])return;let C;if(w==="message")C=function(k,R){const I=new g("message",{data:R?k:k.toString()});I[l]=this,v(E,this,I)};else if(w==="close")C=function(k,R){const I=new h("close",{code:k,reason:R.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});I[l]=this,v(E,this,I)};else if(w==="error")C=function(k){const R=new f("error",{error:k,message:k.message});R[l]=this,v(E,this,R)};else if(w==="open")C=function(){const k=new m("open");k[l]=this,v(E,this,k)};else return;C[r]=!!_[r],C[n]=E,_.once?this.once(w,C):this.on(w,C)},removeEventListener(w,E){for(const _ of this.listeners(w))if(_[n]===E&&!_[r]){this.removeListener(w,_);break}}};t.exports={CloseEvent:h,ErrorEvent:f,Event:m,EventTarget:y,MessageEvent:g};function v(w,E,_){typeof w=="object"&&w.handleEvent?w.handleEvent.call(w,_):w.call(E,_)}}}),Aae=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/extension.js"(e,t){"use strict";var{tokenChars:r}=Wk();function n(i,a,c){i[a]===void 0?i[a]=[c]:i[a].push(c)}function o(i){const a=Object.create(null);let c=Object.create(null),l=!1,u=!1,d=!1,m,h,f=-1,g=-1,y=-1,v=0;for(;v<i.length;v++)if(g=i.charCodeAt(v),m===void 0)if(y===-1&&r[g]===1)f===-1&&(f=v);else if(v!==0&&(g===32||g===9))y===-1&&f!==-1&&(y=v);else if(g===59||g===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${v}`);y===-1&&(y=v);const E=i.slice(f,y);g===44?(n(a,E,c),c=Object.create(null)):m=E,f=y=-1}else throw new SyntaxError(`Unexpected character at index ${v}`);else if(h===void 0)if(y===-1&&r[g]===1)f===-1&&(f=v);else if(g===32||g===9)y===-1&&f!==-1&&(y=v);else if(g===59||g===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${v}`);y===-1&&(y=v),n(c,i.slice(f,y),!0),g===44&&(n(a,m,c),c=Object.create(null),m=void 0),f=y=-1}else if(g===61&&f!==-1&&y===-1)h=i.slice(f,v),f=y=-1;else throw new SyntaxError(`Unexpected character at index ${v}`);else if(u){if(r[g]!==1)throw new SyntaxError(`Unexpected character at index ${v}`);f===-1?f=v:l||(l=!0),u=!1}else if(d)if(r[g]===1)f===-1&&(f=v);else if(g===34&&f!==-1)d=!1,y=v;else if(g===92)u=!0;else throw new SyntaxError(`Unexpected character at index ${v}`);else if(g===34&&i.charCodeAt(v-1)===61)d=!0;else if(y===-1&&r[g]===1)f===-1&&(f=v);else if(f!==-1&&(g===32||g===9))y===-1&&(y=v);else if(g===59||g===44){if(f===-1)throw new SyntaxError(`Unexpected character at index ${v}`);y===-1&&(y=v);let E=i.slice(f,y);l&&(E=E.replace(/\\/g,""),l=!1),n(c,h,E),g===44&&(n(a,m,c),c=Object.create(null),m=void 0),h=void 0,f=y=-1}else throw new SyntaxError(`Unexpected character at index ${v}`);if(f===-1||d||g===32||g===9)throw new SyntaxError("Unexpected end of input");y===-1&&(y=v);const w=i.slice(f,y);return m===void 0?n(a,w,c):(h===void 0?n(c,w,!0):l?n(c,h,w.replace(/\\/g,"")):n(c,h,w),n(a,m,c)),a}function s(i){return Object.keys(i).map(a=>{let c=i[a];return Array.isArray(c)||(c=[c]),c.map(l=>[a].concat(Object.keys(l).map(u=>{let d=l[u];return Array.isArray(d)||(d=[d]),d.map(m=>m===!0?u:`${u}=${m}`).join("; ")})).join("; ")).join(", ")}).join(", ")}t.exports={format:s,parse:o}}}),kae=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket.js"(e,t){"use strict";var r=(Mn(),Br(NH)),n=(len(),Br(P7t)),o=(lQ(),Br(rQ)),s=(uen(),Br(mKt)),i=(den(),Br(WYt)),{randomBytes:a,createHash:c}=(Dt(),Br(AS)),{Duplex:l,Readable:u}=(Nh(),Br(c0)),{URL:d}=(men(),Br(xQt)),m=jk(),h=Hor(),f=Vor(),{isBlob:g}=Wk(),{BINARY_TYPES:y,CLOSE_TIMEOUT:v,EMPTY_BUFFER:w,GUID:E,kForOnEventAttribute:_,kListener:C,kStatusCode:A,kWebSocket:k,NOOP:R}=Gp(),{EventTarget:{addEventListener:I,removeEventListener:P}}=fen(),{format:O,parse:U}=Aae(),{toBuffer:M}=PF(),F=Symbol("kAborted"),N=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],q=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,B=class qo extends r{constructor(V,se,oe){super(),this._binaryType=y[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=w,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=qo.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,V!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,se===void 0?se=[]:Array.isArray(se)||(typeof se=="object"&&se!==null?(oe=se,se=[]):se=[se]),H(this,V,se,oe)):(this._autoPong=oe.autoPong,this._closeTimeout=oe.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(V){y.includes(V)&&(this._binaryType=V,this._receiver&&(this._receiver._binaryType=V))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(V,se,oe){const Z=new h({allowSynchronousEvents:oe.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:oe.maxBufferedChunks,maxFragments:oe.maxFragments,maxPayload:oe.maxPayload,skipUTF8Validation:oe.skipUTF8Validation}),ie=new f(V,this._extensions,oe.generateMask);this._receiver=Z,this._sender=ie,this._socket=V,Z[k]=this,ie[k]=this,V[k]=this,Z.on("conclude",Ee),Z.on("drain",le),Z.on("error",ae),Z.on("message",ke),Z.on("ping",Te),Z.on("pong",he),ie.onerror=De,V.setTimeout&&V.setTimeout(0),V.setNoDelay&&V.setNoDelay(),se.length>0&&V.unshift(se),V.on("close",gt),V.on("data",$e),V.on("end",Ie),V.on("error",ve),this._readyState=qo.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=qo.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[m.extensionName]&&this._extensions[m.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=qo.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(V,se){if(this.readyState!==qo.CLOSED){if(this.readyState===qo.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===qo.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=qo.CLOSING,this._sender.close(V,se,!this._isServer,oe=>{oe||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ye(this)}}pause(){this.readyState===qo.CONNECTING||this.readyState===qo.CLOSED||(this._paused=!0,this._socket.pause())}ping(V,se,oe){if(this.readyState===qo.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof V=="function"?(oe=V,V=se=void 0):typeof se=="function"&&(oe=se,se=void 0),typeof V=="number"&&(V=V.toString()),this.readyState!==qo.OPEN){Ae(this,V,oe);return}se===void 0&&(se=!this._isServer),this._sender.ping(V||w,se,oe)}pong(V,se,oe){if(this.readyState===qo.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof V=="function"?(oe=V,V=se=void 0):typeof se=="function"&&(oe=se,se=void 0),typeof V=="number"&&(V=V.toString()),this.readyState!==qo.OPEN){Ae(this,V,oe);return}se===void 0&&(se=!this._isServer),this._sender.pong(V||w,se,oe)}resume(){this.readyState===qo.CONNECTING||this.readyState===qo.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(V,se,oe){if(this.readyState===qo.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof se=="function"&&(oe=se,se={}),typeof V=="number"&&(V=V.toString()),this.readyState!==qo.OPEN){Ae(this,V,oe);return}const Z={binary:typeof V!="string",mask:!this._isServer,compress:!0,fin:!0,...se};this._extensions[m.extensionName]||(Z.compress=!1),this._sender.send(V||w,Z,oe)}terminate(){if(this.readyState!==qo.CLOSED){if(this.readyState===qo.CONNECTING){Q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=qo.CLOSING,this._socket.destroy())}}};Object.defineProperty(B,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")}),Object.defineProperty(B.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")}),Object.defineProperty(B,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")}),Object.defineProperty(B.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")}),Object.defineProperty(B,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")}),Object.defineProperty(B.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")}),Object.defineProperty(B,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")}),Object.defineProperty(B.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(J=>{Object.defineProperty(B.prototype,J,{enumerable:!0})}),["open","error","close","message"].forEach(J=>{Object.defineProperty(B.prototype,`on${J}`,{enumerable:!0,get(){for(const V of this.listeners(J))if(V[_])return V[C];return null},set(V){for(const se of this.listeners(J))if(se[_]){this.removeListener(J,se);break}typeof V=="function"&&this.addEventListener(J,V,{[_]:!0})}})}),B.prototype.addEventListener=I,B.prototype.removeEventListener=P,t.exports=B;function H(J,V,se,oe){const Z={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v,protocolVersion:N[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...oe,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(J._autoPong=Z.autoPong,J._closeTimeout=Z.closeTimeout,!N.includes(Z.protocolVersion))throw new RangeError(`Unsupported protocol version: ${Z.protocolVersion} (supported versions: ${N.join(", ")})`);let ie;if(V instanceof d)ie=V;else try{ie=new d(V)}catch{throw new SyntaxError(`Invalid URL: ${V}`)}ie.protocol==="http:"?ie.protocol="ws:":ie.protocol==="https:"&&(ie.protocol="wss:"),J._url=ie.href;const W=ie.protocol==="wss:",re=ie.protocol==="ws+unix:";let ye;if(ie.protocol!=="ws:"&&!W&&!re?ye=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:re&&!ie.pathname?ye="The URL's pathname is empty":ie.hash&&(ye="The URL contains a fragment identifier"),ye){const $=new SyntaxError(ye);if(J._redirects===0)throw $;G(J,$);return}const Re=W?443:80,x=a(16).toString("base64"),K=W?n.request:o.request,Se=new Set;let xe;if(Z.createConnection=Z.createConnection||(W?ce:X),Z.defaultPort=Z.defaultPort||Re,Z.port=ie.port||Re,Z.host=ie.hostname.startsWith("[")?ie.hostname.slice(1,-1):ie.hostname,Z.headers={...Z.headers,"Sec-WebSocket-Version":Z.protocolVersion,"Sec-WebSocket-Key":x,Connection:"Upgrade",Upgrade:"websocket"},Z.path=ie.pathname+ie.search,Z.timeout=Z.handshakeTimeout,Z.perMessageDeflate&&(xe=new m({...Z.perMessageDeflate,isServer:!1,maxPayload:Z.maxPayload}),Z.headers["Sec-WebSocket-Extensions"]=O({[m.extensionName]:xe.offer()})),se.length){for(const $ of se){if(typeof $!="string"||!q.test($)||Se.has($))throw new SyntaxError("An invalid or duplicated subprotocol was specified");Se.add($)}Z.headers["Sec-WebSocket-Protocol"]=se.join(",")}if(Z.origin&&(Z.protocolVersion<13?Z.headers["Sec-WebSocket-Origin"]=Z.origin:Z.headers.Origin=Z.origin),(ie.username||ie.password)&&(Z.auth=`${ie.username}:${ie.password}`),re){const $=Z.path.split(":");Z.socketPath=$[0],Z.path=$[1]}let fe;if(Z.followRedirects){if(J._redirects===0){J._originalIpc=re,J._originalSecure=W,J._originalHostOrSocketPath=re?Z.socketPath:ie.host;const $=oe&&oe.headers;if(oe={...oe,headers:{}},$)for(const[Y,de]of Object.entries($))oe.headers[Y.toLowerCase()]=de}else if(J.listenerCount("redirect")===0){const $=re?J._originalIpc?Z.socketPath===J._originalHostOrSocketPath:!1:J._originalIpc?!1:ie.host===J._originalHostOrSocketPath;(!$||J._originalSecure&&!W)&&(delete Z.headers.authorization,delete Z.headers.cookie,$||delete Z.headers.host,Z.auth=void 0)}Z.auth&&!oe.headers.authorization&&(oe.headers.authorization="Basic "+Buffer.from(Z.auth).toString("base64")),fe=J._req=K(Z),J._redirects&&J.emit("redirect",J.url,fe)}else fe=J._req=K(Z);Z.timeout&&fe.on("timeout",()=>{Q(J,fe,"Opening handshake has timed out")}),fe.on("error",$=>{fe===null||fe[F]||(fe=J._req=null,G(J,$))}),fe.on("response",$=>{const Y=$.headers.location,de=$.statusCode;if(Y&&Z.followRedirects&&de>=300&&de<400){if(++J._redirects>Z.maxRedirects){Q(J,fe,"Maximum redirects exceeded");return}fe.abort();let ge;try{ge=new d(Y,V)}catch{const we=new SyntaxError(`Invalid URL: ${Y}`);G(J,we);return}H(J,ge,se,oe)}else J.emit("unexpected-response",fe,$)||Q(J,fe,`Unexpected server response: ${$.statusCode}`)}),fe.on("upgrade",($,Y,de)=>{if(J.emit("upgrade",$),J.readyState!==B.CONNECTING)return;fe=J._req=null;const ge=$.headers.upgrade;if(ge===void 0||ge.toLowerCase()!=="websocket"){Q(J,Y,"Invalid Upgrade header");return}const be=c("sha1").update(x+E).digest("base64");if($.headers["sec-websocket-accept"]!==be){Q(J,Y,"Invalid Sec-WebSocket-Accept header");return}const we=$.headers["sec-websocket-protocol"];let ue;if(we!==void 0?Se.size?Se.has(we)||(ue="Server sent an invalid subprotocol"):ue="Server sent a subprotocol but none was requested":Se.size&&(ue="Server sent no subprotocol"),ue){Q(J,Y,ue);return}we&&(J._protocol=we);const Le=$.headers["sec-websocket-extensions"];if(Le!==void 0){if(!xe){Q(J,Y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let at;try{at=U(Le)}catch{Q(J,Y,"Invalid Sec-WebSocket-Extensions header");return}const vt=Object.keys(at);if(vt.length!==1||vt[0]!==m.extensionName){Q(J,Y,"Server indicated an extension that was not requested");return}try{xe.accept(at[m.extensionName])}catch{Q(J,Y,"Invalid Sec-WebSocket-Extensions header");return}J._extensions[m.extensionName]=xe}J.setSocket(Y,de,{allowSynchronousEvents:Z.allowSynchronousEvents,generateMask:Z.generateMask,maxBufferedChunks:Z.maxBufferedChunks,maxFragments:Z.maxFragments,maxPayload:Z.maxPayload,skipUTF8Validation:Z.skipUTF8Validation})}),Z.finishRequest?Z.finishRequest(fe,J):fe.end()}function G(J,V){J._readyState=B.CLOSING,J._errorEmitted=!0,J.emit("error",V),J.emitClose()}function X(J){return J.path=J.socketPath,s.connect(J)}function ce(J){return J.path=void 0,!J.servername&&J.servername!==""&&(J.servername=s.isIP(J.host)?"":J.host),i.connect(J)}function Q(J,V,se){J._readyState=B.CLOSING;const oe=new Error(se);Error.captureStackTrace(oe,Q),V.setHeader?(V[F]=!0,V.abort(),V.socket&&!V.socket.destroyed&&V.socket.destroy(),process.nextTick(G,J,oe)):(V.destroy(oe),V.once("error",J.emit.bind(J,"error")),V.once("close",J.emitClose.bind(J)))}function Ae(J,V,se){if(V){const oe=g(V)?V.size:M(V).length;J._socket?J._sender._bufferedBytes+=oe:J._bufferedAmount+=oe}if(se){const oe=new Error(`WebSocket is not open: readyState ${J.readyState} (${L[J.readyState]})`);process.nextTick(se,oe)}}function Ee(J,V){const se=this[k];se._closeFrameReceived=!0,se._closeMessage=V,se._closeCode=J,se._socket[k]!==void 0&&(se._socket.removeListener("data",$e),process.nextTick(Oe,se._socket),J===1005?se.close():se.close(J,V))}function le(){const J=this[k];J.isPaused||J._socket.resume()}function ae(J){const V=this[k];V._socket[k]!==void 0&&(V._socket.removeListener("data",$e),process.nextTick(Oe,V._socket),V.close(J[A])),V._errorEmitted||(V._errorEmitted=!0,V.emit("error",J))}function Pe(){this[k].emitClose()}function ke(J,V){this[k].emit("message",J,V)}function Te(J){const V=this[k];V._autoPong&&V.pong(J,!this._isServer,R),V.emit("ping",J)}function he(J){this[k].emit("pong",J)}function Oe(J){J.resume()}function De(J){const V=this[k];V.readyState!==B.CLOSED&&(V.readyState===B.OPEN&&(V._readyState=B.CLOSING,Ye(V)),this._socket.end(),V._errorEmitted||(V._errorEmitted=!0,V.emit("error",J)))}function Ye(J){J._closeTimer=setTimeout(J._socket.destroy.bind(J._socket),J._closeTimeout)}function gt(){const J=this[k];if(this.removeListener("close",gt),this.removeListener("data",$e),this.removeListener("end",Ie),J._readyState=B.CLOSING,!this._readableState.endEmitted&&!J._closeFrameReceived&&!J._receiver._writableState.errorEmitted&&this._readableState.length!==0){const V=this.read(this._readableState.length);J._receiver.write(V)}J._receiver.end(),this[k]=void 0,clearTimeout(J._closeTimer),J._receiver._writableState.finished||J._receiver._writableState.errorEmitted?J.emitClose():(J._receiver.on("error",Pe),J._receiver.on("finish",Pe))}function $e(J){this[k]._receiver.write(J)||this.pause()}function Ie(){const J=this[k];J._readyState=B.CLOSING,J._receiver.end(),this.end()}function ve(){const J=this[k];this.removeListener("error",ve),this.on("error",R),J&&(J._readyState=B.CLOSING,this.destroy())}}}),gen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/stream.js"(e,t){"use strict";var r=kae(),{Duplex:n}=(Nh(),Br(c0));function o(c){c.emit("close")}function s(){!this.destroyed&&this._writableState.finished&&this.destroy()}function i(c){this.removeListener("error",i),this.destroy(),this.listenerCount("error")===0&&this.emit("error",c)}function a(c,l){let u=!0;const d=new n({...l,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return c.on("message",function(h,f){const g=!f&&d._readableState.objectMode?h.toString():h;d.push(g)||c.pause()}),c.once("error",function(h){d.destroyed||(u=!1,d.destroy(h))}),c.once("close",function(){d.destroyed||d.push(null)}),d._destroy=function(m,h){if(c.readyState===c.CLOSED){h(m),process.nextTick(o,d);return}let f=!1;c.once("error",function(y){f=!0,h(y)}),c.once("close",function(){f||h(m),process.nextTick(o,d)}),u&&c.terminate()},d._final=function(m){if(c.readyState===c.CONNECTING){c.once("open",function(){d._final(m)});return}c._socket!==null&&(c._socket._writableState.finished?(m(),d._readableState.endEmitted&&d.destroy()):(c._socket.once("finish",function(){m()}),c.close()))},d._read=function(){c.isPaused&&c.resume()},d._write=function(m,h,f){if(c.readyState===c.CONNECTING){c.once("open",function(){d._write(m,h,f)});return}c.send(m,f)},d.on("end",s),d.on("error",i),d}t.exports=a}}),Wor=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/subprotocol.js"(e,t){"use strict";var{tokenChars:r}=Wk();function n(o){const s=new Set;let i=-1,a=-1,c=0;for(c;c<o.length;c++){const u=o.charCodeAt(c);if(a===-1&&r[u]===1)i===-1&&(i=c);else if(c!==0&&(u===32||u===9))a===-1&&i!==-1&&(a=c);else if(u===44){if(i===-1)throw new SyntaxError(`Unexpected character at index ${c}`);a===-1&&(a=c);const d=o.slice(i,a);if(s.has(d))throw new SyntaxError(`The "${d}" subprotocol is duplicated`);s.add(d),i=a=-1}else throw new SyntaxError(`Unexpected character at index ${c}`)}if(i===-1||a!==-1)throw new SyntaxError("Unexpected end of input");const l=o.slice(i,c);if(s.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);return s.add(l),s}t.exports={parse:n}}}),yen=Ur({"node_modules/.pnpm/ws@8.21.0/node_modules/ws/lib/websocket-server.js"(e,t){"use strict";var r=(Mn(),Br(NH)),n=(lQ(),Br(rQ)),{Duplex:o}=(Nh(),Br(c0)),{createHash:s}=(Dt(),Br(AS)),i=Aae(),a=jk(),c=Wor(),l=kae(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:m}=Gp(),h=/^[+/0-9A-Za-z]{22}==$/,f=0,g=1,y=2,v=class extends r{constructor(k,R){if(super(),k={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...k},k.port==null&&!k.server&&!k.noServer||k.port!=null&&(k.server||k.noServer)||k.server&&k.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(k.port!=null?(this._server=n.createServer((I,P)=>{const O=n.STATUS_CODES[426];P.writeHead(426,{"Content-Length":O.length,"Content-Type":"text/plain"}),P.end(O)}),this._server.listen(k.port,k.host,k.backlog,R)):k.server&&(this._server=k.server),this._server){const I=this.emit.bind(this,"connection");this._removeListeners=w(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(P,O,U)=>{this.handleUpgrade(P,O,U,I)}})}k.perMessageDeflate===!0&&(k.perMessageDeflate={}),k.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=k,this._state=f}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(k){if(this._state===y){k&&this.once("close",()=>{k(new Error("The server is not running"))}),process.nextTick(E,this);return}if(k&&this.once("close",k),this._state!==g)if(this._state=g,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(E,this):process.nextTick(E,this);else{const R=this._server;this._removeListeners(),this._removeListeners=this._server=null,R.close(()=>{E(this)})}}shouldHandle(k){if(this.options.path){const R=k.url.indexOf("?");if((R!==-1?k.url.slice(0,R):k.url)!==this.options.path)return!1}return!0}handleUpgrade(k,R,I,P){R.on("error",_);const O=k.headers["sec-websocket-key"],U=k.headers.upgrade,M=+k.headers["sec-websocket-version"];if(k.method!=="GET"){A(this,k,R,405,"Invalid HTTP method");return}if(U===void 0||U.toLowerCase()!=="websocket"){A(this,k,R,400,"Invalid Upgrade header");return}if(O===void 0||!h.test(O)){A(this,k,R,400,"Missing or invalid Sec-WebSocket-Key header");return}if(M!==13&&M!==8){A(this,k,R,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(k)){C(R,400);return}const F=k.headers["sec-websocket-protocol"];let N=new Set;if(F!==void 0)try{N=c.parse(F)}catch{A(this,k,R,400,"Invalid Sec-WebSocket-Protocol header");return}const L=k.headers["sec-websocket-extensions"],q={};if(this.options.perMessageDeflate&&L!==void 0){const B=new a({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{const H=i.parse(L);H[a.extensionName]&&(B.accept(H[a.extensionName]),q[a.extensionName]=B)}catch{A(this,k,R,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){const B={origin:k.headers[`${M===8?"sec-websocket-origin":"origin"}`],secure:!!(k.socket.authorized||k.socket.encrypted),req:k};if(this.options.verifyClient.length===2){this.options.verifyClient(B,(H,G,X,ce)=>{if(!H)return C(R,G||401,X,ce);this.completeUpgrade(q,O,N,k,R,I,P)});return}if(!this.options.verifyClient(B))return C(R,401)}this.completeUpgrade(q,O,N,k,R,I,P)}completeUpgrade(k,R,I,P,O,U,M){if(!O.readable||!O.writable)return O.destroy();if(O[m])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>f)return C(O,503);const N=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(R+d).digest("base64")}`],L=new this.options.WebSocket(null,void 0,this.options);if(I.size){const q=this.options.handleProtocols?this.options.handleProtocols(I,P):I.values().next().value;q&&(N.push(`Sec-WebSocket-Protocol: ${q}`),L._protocol=q)}if(k[a.extensionName]){const q=k[a.extensionName].params,B=i.format({[a.extensionName]:[q]});N.push(`Sec-WebSocket-Extensions: ${B}`),L._extensions=k}this.emit("headers",N,P),O.write(N.concat(`\r
|
|
2154
2154
|
`).join(`\r
|
|
2155
2155
|
`)),O.removeListener("error",_),L.setSocket(O,U,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(L),L.on("close",()=>{this.clients.delete(L),this._shouldEmitClose&&!this.clients.size&&process.nextTick(E,this)})),M(L,P)}};t.exports=v;function w(k,R){for(const I of Object.keys(R))k.on(I,R[I]);return function(){for(const P of Object.keys(R))k.removeListener(P,R[P])}}function E(k){k._state=y,k.emit("close")}function _(){this.destroy()}function C(k,R,I,P){I=I||n.STATUS_CODES[R],P={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(I),...P},k.once("finish",k.destroy),k.end(`HTTP/1.1 ${R} ${n.STATUS_CODES[R]}\r
|
|
2156
2156
|
`+Object.keys(P).map(O=>`${O}: ${P[O]}`).join(`\r
|
|
@@ -2356,8 +2356,8 @@ data: ${r}
|
|
|
2356
2356
|
...[TRUNCATED]`;function Pue(){const e=new TextDecoder,t=[];let r=0,n=0,o=!1,s=!1,i;const a=new Promise(g=>{i=g});function c(){if(s)return;s=!0;const g=t.map(y=>e.decode(y,{stream:!0})).join("")+(o?"":e.decode());Rue-=n,t.length=0,i({totalBytes:r,text:g+(o?mgn:""),truncated:o})}const l=new TransformStream({transform(g,y){if(y.enqueue(g),r+=g.byteLength,!o&&n<Iue){const v=Math.min(Iue-n,Math.max(0,dgn-Rue)),w=Uint8Array.from(g.subarray(0,v));t.push(w),n+=w.byteLength,Rue+=w.byteLength,o=w.byteLength<g.byteLength}o||=r>Iue},flush(){c()}}),u=l.writable.getWriter();let d;const m=new WritableStream({start(g){d=g},write(g){return u.write(g)},close(){return u.close()},abort(g){return c(),u.abort(g)}});u.closed.catch(g=>{c();try{d.error(g)}catch{}});const h=l.readable.getReader();return{stream:{readable:new ReadableStream({async pull(g){try{const{done:y,value:v}=await h.read();y?g.close():g.enqueue(v)}catch(y){g.error(y)}},async cancel(g){c();try{d.error(g)}catch{}await Promise.allSettled([h.cancel(g),u.abort(g)])}}),writable:m},capture:a}}SMt(),Dr(),Hs(),zt(),Yc(),z(),cc();var pgn="proxy-peers.json",hgn=1e3,fgn={exhausted:9e5,withheld:6e5,paused:3e5,revoked:864e5,expired:864e5,unreachable:6e4,upstream_error:12e4},ggn=null,Tm={},Bx=0,zx=-1,qx=!1,xfr=new Da;function Mue(){return ggn??yt(wa(),".neurolink",pgn)}function ygn(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.name=="string"&&typeof t.url=="string"&&typeof t.token=="string"&&typeof t.priority=="number"&&typeof t.enabled=="boolean"}function vgn(e){return e?.code==="ENOENT"}async function Oue(e={}){const t=Date.now();if(!e.force&&qx&&t-Bx<hgn)return;const r=Mue();let n;try{n=(await xs(r)).mtimeMs}catch(o){if(!vgn(o))throw o;Tm={},zx=-1,Bx=t,qx=!0;return}if(!e.force&&qx&&n===zx){Bx=t;return}try{const o=JSON.parse(await Fr(r,"utf8"));Tm=Object.fromEntries(Object.entries(o?.peers??{}).filter(s=>ygn(s[1])))}catch(o){if(e.force)throw o;p.always(`[proxy] peer list unreadable, treating as empty: ${o instanceof Error?o.message:String(o)}`),Tm={}}zx=n,Bx=t,qx=!0}async function Ifr(){const e={schemaVersion:1,peers:Tm};await Na(Mue(),e);try{zx=(await xs(Mue())).mtimeMs}catch{zx=-1}Bx=Date.now(),qx=!0}function Rfr(e){return e.trim().toLowerCase()}async function Tgn(){return await Oue(),Object.values(Tm).sort((e,t)=>e.priority-t.priority||e.createdAt-t.createdAt)}async function wgn(e=Date.now()){return(await Tgn()).filter(r=>r.enabled&&!(r.cooldownUntil&&r.cooldownUntil>e))}function Egn(e){return fgn[e]}var Sgn=6048e5;async function Due(e,t,r){await xfr.runExclusive(async()=>{await Oue({force:!0});const n=Rfr(e),o=Tm[n];if(!o)return;const s=(r??0)*1e3,i=Date.now()+Math.min(Sgn,Math.max(Egn(t),Number.isFinite(s)?s:0));Tm[n]={...o,cooldownUntil:i,cooldownReason:t,updatedAt:Date.now()},await Ifr()})}async function bgn(e,t){await xfr.runExclusive(async()=>{await Oue({force:!0});const r=Rfr(e),n=Tm[r];n&&(Tm[r]={...n,cooldownUntil:0,lastUsedAt:Date.now(),updatedAt:Date.now(),...t?{lastObservation:t}:{}},await Ifr())})}Dr(),Hs(),zt(),Yc(),t$();var _gn=6048e5,Cgn=9e5,Agn=864e5;function kgn(e){return!e.usable}function Pfr(e){return{schemaVersion:e.schemaVersion,grantId:e.grantId,peerLabel:e.peerLabel,issuedAt:e.issuedAt,notAfter:e.notAfter,heartbeatEveryMs:e.heartbeatEveryMs,offlineGraceMs:e.offlineGraceMs,gates:e.gates,entitlementSnapshot:e.entitlementSnapshot}}function Mfr(e,t){return cce(e,t)}function Ofr(e,t=Date.now()){const r=e.leasePolicy,n=e.leaseSecret;if(!n)throw new Error(`Grant ${e.id} has no lease secret \u2014 provision it before issuing a lease.`);const o=r?.ttlMs??_gn,s=Math.min(t+o,e.gates.notAfter??Number.POSITIVE_INFINITY),i={schemaVersion:1,grantId:e.id,peerLabel:e.peerLabel,issuedAt:t,notAfter:s,heartbeatEveryMs:r?.heartbeatEveryMs??Cgn,offlineGraceMs:r?.offlineGraceMs??Agn,gates:e.gates,entitlementSnapshot:e.entitlement.ledger==="coins"?e.entitlement.coins??0:"unlimited"};return{...i,signature:Mfr(Pfr(i),n)}}function xgn(e,t){const{signature:r,...n}=e;return Ear(Mfr(Pfr(n),t),r)}function Ign(e){const t=e.now??Date.now();if(!xgn(e.lease,e.secret))return{usable:!1,reason:"unsigned",detail:"lease signature does not match the lender's secret"};if(e.lease.notAfter<=t)return{usable:!1,reason:"expired",detail:"the lease's hard expiry has passed"};const r=e.lastHeartbeatAt??e.lease.issuedAt;return r+e.lease.offlineGraceMs<=t?{usable:!1,reason:"grace_elapsed",detail:"the lender has been unreachable for longer than this lease allows"}:{usable:!0,nextHeartbeatDueAt:r+e.lease.heartbeatEveryMs}}function Rgn(e){const t=e.now??Date.now();if(!e.grant.leaseSecret)throw new Error(`Grant ${e.grant.id} has no lease secret \u2014 attach lease material first.`);return{code:e.code,state:e.state,accountLabel:`${e.grant.peerLabel}-via-${e.lenderName}`,leaseSecret:e.grant.leaseSecret,lease:Ofr(e.grant,t),lenderUrl:(e.lenderUrl??"").replace(/\/+$/,"")}}cc();var Pgn="proxy-resident-grants.json",Mgn=1e3,Ogn=null,dy={},Gx=0,jx=-1,Hx=!1,Dgn=new Da;function Nue(){return Ogn??yt(wa(),".neurolink",Pgn)}function Ngn(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.accountLabel=="string"&&typeof t.grantId=="string"&&typeof t.leaseSecret=="string"&&!!t.lease}function Lgn(e){return e?.code==="ENOENT"}async function Dfr(e={}){const t=Date.now();if(!e.force&&Hx&&t-Gx<Mgn)return;const r=Nue();let n;try{n=(await xs(r)).mtimeMs}catch(o){if(!Lgn(o))throw o;dy={},jx=-1,Gx=t,Hx=!0;return}if(!e.force&&Hx&&n===jx){Gx=t;return}try{const o=JSON.parse(await Fr(r,"utf8"));dy=Object.fromEntries(Object.entries(o?.grants??{}).filter(s=>Ngn(s[1])))}catch(o){if(e.force)throw o;dy={}}jx=n,Gx=t,Hx=!0}async function Fgn(){const e={schemaVersion:1,grants:dy};await Na(Nue(),e);try{jx=(await xs(Nue())).mtimeMs}catch{jx=-1}Gx=Date.now(),Hx=!0}function Nfr(e){return e.toLowerCase()}async function Lue(e){await Dfr();const t=e.toLowerCase(),r=t.includes(":")?t.slice(t.indexOf(":")+1):t;return dy[Nfr(r)]}async function $gn(e,t=Date.now()){const r=await Lue(e);if(r)return Ign({lease:r.lease,secret:r.leaseSecret,...r.lastHeartbeatAt!==void 0?{lastHeartbeatAt:r.lastHeartbeatAt}:{},now:t})}async function Ugn(e,t){await Dgn.runExclusive(async()=>{await Dfr({force:!0});const r=Nfr(e),n=dy[r];n&&(dy[r]={...n,unreportedCoins:(n.unreportedCoins??0)+t,unreportedRequests:(n.unreportedRequests??0)+1},await Fgn())})}z();var Bgn=15e3,zgn=12e4;function qgn(e){switch(e){case"exhausted":return"exhausted";case"paused":return"paused";case"revoked":return"revoked";case"expired":return"expired";case"reserve_floor":case"spillover_inactive":case"slice_exhausted":case"no_capacity":return"withheld";case"missing_token":case"unknown_token":case"malformed_token":return"revoked";default:return"upstream_error"}}function Lfr(e,t){const r=e.headers.get(t);if(r===null||r.trim()==="")return;const n=Number(r);return Number.isFinite(n)?n:void 0}function Ggn(e){const t=Lfr(e,"x-neurolink-grant-remaining-coins");return{observedAt:Date.now(),...e.headers.get("x-neurolink-grant-status")?{grantStatus:e.headers.get("x-neurolink-grant-status")??""}:{},...e.headers.get("x-neurolink-grant-reason")?{grantReason:e.headers.get("x-neurolink-grant-reason")??""}:{},...t!==void 0?{remainingCoins:t}:{}}}function jgn(e,t,r){const n=e.body;if(!n)return e;let o;const s=()=>{o!==void 0&&(clearTimeout(o),o=void 0)},i=()=>{s(),o=setTimeout(()=>{p.always(`[proxy] peer=${t.name} went quiet mid-response; abandoning it`),Due(t.name,"unreachable").catch(c=>{p.debug(`[proxy] could not cool peer=${t.name} after a stall: ${c instanceof Error?c.message:String(c)}`)}),r.abort()},zgn),o.unref?.()},a=n.pipeThrough(new TransformStream({start:i,transform(c,l){i(),l.enqueue(c)},flush:s}));return r.signal.addEventListener("abort",s,{once:!0}),new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}async function Hgn(e){const{peer:t,body:r,stream:n}=e,o=new AbortController,s=setTimeout(()=>o.abort(),Bgn);e.signal&&(e.signal.aborted?o.abort():e.signal.addEventListener("abort",()=>o.abort(),{once:!0}));try{const i=await fetch(`${t.url}/v1/messages`,{method:"POST",headers:{"content-type":"application/json","x-neurolink-share-token":t.token,accept:n?"text/event-stream":"application/json"},body:r,signal:o.signal});if(i.ok)return await bgn(t.name,Ggn(i)).catch(u=>{p.debug(`[proxy] could not record success for peer=${t.name}: ${u instanceof Error?u.message:String(u)}`)}),{ok:!0,response:jgn(i,t,o),peer:t};const a=i.headers.get("x-neurolink-grant-reason"),c=qgn(a),l=Lfr(i,"retry-after");return await Due(t.name,c,l),await i.text().catch(()=>""),p.always(`[proxy] peer=${t.name} declined (${c}); cooling before retry`),{ok:!1,peer:t,status:i.status,reason:c,message:`peer ${t.name} declined: ${c}`,...l!==void 0?{retryAfterSeconds:l}:{}}}catch(i){const a=i instanceof Error?i.message:String(i);return e.signal?.aborted?(p.debug(`[proxy] peer=${t.name} attempt cancelled by the caller: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} attempt cancelled`}):(await Due(t.name,"unreachable").catch(c=>{p.debug(`[proxy] could not cool peer=${t.name}: ${c instanceof Error?c.message:String(c)}`)}),p.always(`[proxy] peer=${t.name} unreachable: ${a}`),{ok:!1,peer:t,reason:"unreachable",message:`peer ${t.name} unreachable`})}finally{clearTimeout(s)}}lx();var Vgn=36e5,Wgn={missing_token:"No share token was presented.",unknown_token:"Share token is not recognized.",malformed_token:"Share token is malformed.",paused:"The lender has paused this share.",revoked:"This share has been revoked.",expired:"This share has expired.",out_of_window:"This share is outside its allowed hours.",model_not_allowed:"This share does not cover the requested model.",exhausted:"This share has no credit remaining.",rate_limited:"This share's request rate limit was exceeded.",concurrency_limited:"This share's concurrent request limit was reached.",reserve_floor:"The lender's reserved headroom is in force.",spillover_inactive:"This share serves only the lender's spare capacity, and none is spare yet.",slice_exhausted:"This share has used its allotted portion of the window.",no_capacity:"No lender account can currently serve this share."};function Kgn(e){return Wgn[e]}function Jgn(e){switch(e){case"missing_token":case"unknown_token":case"malformed_token":return 401;case"paused":case"revoked":case"expired":case"out_of_window":case"model_not_allowed":return 403;default:return 429}}function Ygn(e,t){const r=new Date(t).getHours(),{fromHour:n,toHour:o}=e;return n===o?!0:n<o?r>=n&&r<o:r>=n||r<o}function Xgn(e,t){if(!e||e.length===0)return!0;if(!t)return!1;const r=t.toLowerCase();return e.some(n=>r.includes(n.toLowerCase()))}function Ffr(e,t){const r=n=>n===void 0?t:t===void 0?n:Math.min(n,t);return{session:r(e?.session5hPct),weekly:r(e?.weekly7dPct)}}function $fr(e,t,r){const n=e.spillover;if(!n)return!1;const o=n.beforeResetHours*Vgn,s=n.whenUtilizationBelowPct/100,i=t.weeklyResetAt!==null&&t.weeklyResetAt-r<=o&&t.weeklyResetAt>r&&t.weeklyUsed!==null&&t.weeklyUsed<s,a=t.sessionResetAt!==null&&t.sessionResetAt-r<=o&&t.sessionResetAt>r&&t.sessionUsed!==null&&t.sessionUsed<s;return i||a}function Fue(e,t){if(!e.accounts||e.accounts.length===0)return{inScope:[...t],outOfScope:[]};const r=new Set(e.accounts.map(s=>s.trim().toLowerCase())),n=[],o=[];for(const s of t){const i=s.accountKey.toLowerCase(),a=i.includes(":")?i.slice(i.indexOf(":")+1):i;r.has(i)||r.has(a)?n.push(s):o.push(s)}return{inScope:n,outOfScope:o}}function $ue(e,t,r,n){const o=e.gates,{inScope:s,outOfScope:i}=Fue(o,t),a=s.some(m=>$fr(o,m,r)),c=Ffr(o.maxSlice,a?o.spillover?.maxSlicePct:void 0);if(c.session!==void 0&&n.sessionFraction*100>=c.session||c.weekly!==void 0&&n.weeklyFraction*100>=c.weekly)return{allowed:[],excluded:[...s.map(m=>({accountKey:m.accountKey,reason:"slice_exhausted"})),...i.map(m=>({accountKey:m.accountKey,reason:"no_capacity"}))]};const u=[],d=i.map(m=>({accountKey:m.accountKey,reason:"no_capacity"}));for(const m of s){const h=$fr(o,m,r);if(o.spillover&&!h){d.push({accountKey:m.accountKey,reason:"spillover_inactive"});continue}const f=o.reserveFloor;if(f){const w=f.session5hPct!==void 0&&m.sessionUsed!==null&&m.sessionUsed*100>100-f.session5hPct,E=f.weekly7dPct!==void 0&&m.weeklyUsed!==null&&m.weeklyUsed*100>100-f.weekly7dPct;if(w||E){d.push({accountKey:m.accountKey,reason:"reserve_floor"});continue}}const g=Ffr(o.maxSlicePerAccount,h?o.spillover?.maxSlicePct:void 0),y=g.session!==void 0&&m.borrowedSessionFraction*100>=g.session,v=g.weekly!==void 0&&m.borrowedWeeklyFraction*100>=g.weekly;if(y||v){d.push({accountKey:m.accountKey,reason:"slice_exhausted"});continue}u.push(m.accountKey)}return{allowed:u,excluded:d}}function Uue(e){return e.some(t=>t.reason==="reserve_floor")?"reserve_floor":e.some(t=>t.reason==="spillover_inactive")?"spillover_inactive":e.some(t=>t.reason==="slice_exhausted")?"slice_exhausted":"no_capacity"}var Zgn="x-neurolink-share-token",Qgn="x-neurolink-grant-status",eyn="x-neurolink-grant-reason",tyn="x-neurolink-grant-remaining-coins",ryn="x-neurolink-grant-peer";function nyn(e){const t=e[Zgn];if(t?.trim())return t.trim();const r=e.authorization??e.Authorization;if(!r)return;const n=r.trim(),o=n.toLowerCase().startsWith("bearer ")?n.slice(7).trim():n;return Qin(o)?o:void 0}function oyn(e){return e===401?"authentication_error":e===403?"permission_error":"rate_limit_error"}function syn(e,t){switch(e){case"paused":return"paused";case"revoked":return"revoked";case"expired":return"expired";case"exhausted":return"exhausted";case"out_of_window":return"out-of-window";case"missing_token":case"unknown_token":case"malformed_token":return"unauthorized";default:return t?.state??"active"}}function Xw(e,t){const{status:r,grant:n,retryAfterSeconds:o}=t,s={[Qgn]:syn(e,n),[eyn]:e};return n&&(s[ryn]=n.peerLabel,n.entitlement.ledger==="coins"&&(s[tyn]=String(Math.max(0,Math.floor(n.entitlement.coins??0))))),o!==void 0&&(s["retry-after"]=String(Math.max(1,Math.round(o)))),{status:r,headers:s,body:{type:"error",error:{type:oyn(r),message:t.message??Kgn(e)}}}}lx(),Dr(),Hs(),zt(),Yc(),cc();var iyn="proxy-share-audit.json",ayn=2,cyn=3,lyn=1e3,uyn=null,Zw={},Vx=0,Wx=-1,Kx=!1,dyn=new Da;function Bue(){return uyn??yt(wa(),".neurolink",iyn)}function myn(e){return e?.code==="ENOENT"}async function pyn(e={}){const t=Date.now();if(!e.force&&Kx&&t-Vx<lyn)return;const r=Bue();let n;try{n=(await xs(r)).mtimeMs}catch(o){if(!myn(o))throw o;Zw={},Wx=-1,Vx=t,Kx=!0;return}if(!e.force&&Kx&&n===Wx){Vx=t;return}try{Zw=JSON.parse(await Fr(r,"utf8"))?.records??{}}catch(o){if(e.force)throw o;Zw={}}Wx=n,Vx=t,Kx=!0}async function hyn(){const e={schemaVersion:1,records:Zw};await Na(Bue(),e);try{Wx=(await xs(Bue())).mtimeMs}catch{Wx=-1}Vx=Date.now(),Kx=!0}function Ufr(e,t){return e===null||t===null?0:Math.max(0,(t-e)*100)}function fyn(e,t,r=ayn){if(!e)return{drifted:!1,reason:"no_baseline"};if(t.lenderRequests>0)return{drifted:!1,reason:"attributable"};const n=Ufr(e.sessionUsed,t.sessionUsed),o=Ufr(e.weeklyUsed,t.weeklyUsed),s=Math.max(n,o);return s<=r?{drifted:!1,reason:"quiet"}:t.reportedCoins>0?{drifted:!1,reason:"attributable"}:{drifted:!0,unexplainedSessionPct:n,unexplainedWeeklyPct:o,detail:`the account moved ${s.toFixed(1)}% of a window since the last check-in while this node served none of it and the borrower reported no spend`}}async function gyn(e){const t=e.streakLimit??cyn;return dyn.runExclusive(async()=>{await pyn({force:!0});const r=Zw[e.grantId],n=e.lenderRequestsTotal===void 0?e.observation:{...e.observation,lenderRequests:Math.max(0,e.lenderRequestsTotal-(r?.lenderRequestsTotal??0))},o=fyn(r?.lastObservation,n,e.tolerancePct),s=o.drifted?(r?.driftStreak??0)+1:0,i={grantId:e.grantId,accountLabel:e.accountLabel,lastObservation:n,...e.lenderRequestsTotal!==void 0?{lenderRequestsTotal:e.lenderRequestsTotal}:r?.lenderRequestsTotal!==void 0?{lenderRequestsTotal:r.lenderRequestsTotal}:{},driftStreak:s,...o.drifted?{lastDriftAt:n.at,lastDriftDetail:o.detail}:{...r?.lastDriftAt!==void 0?{lastDriftAt:r.lastDriftAt}:{},...r?.lastDriftDetail!==void 0?{lastDriftDetail:r.lastDriftDetail}:{}},...r?.autoPausedAt!==void 0?{autoPausedAt:r.autoPausedAt}:{}},a=s>=t&&i.autoPausedAt===void 0;return a&&(i.autoPausedAt=n.at),Zw[e.grantId]=i,await hyn(),{verdict:o,shouldPause:a}})}Wr(),Dr(),Hs(),zt(),Yc(),cc();var yyn="proxy-share-provisioning.json",vyn=9e5,Tyn=/^[A-Za-z0-9_-]{43}$/,wyn=/^[A-Za-z0-9_-]{16,128}$/,Eyn=null,Qw={},Bfr=!1,zfr=new Da;function qfr(){return Eyn??yt(wa(),".neurolink",yyn)}function Syn(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.grantId=="string"&&typeof t.codeChallenge=="string"&&typeof t.state=="string"&&typeof t.expiresAt=="number"&&typeof t.status=="string"}async function Gfr(e={}){if(!(Bfr&&!e.force)){try{const t=JSON.parse(await Fr(qfr(),"utf8"));Qw=Object.fromEntries(Object.entries(t?.requests??{}).filter(r=>Syn(r[1])))}catch{Qw={}}Bfr=!0}}async function jfr(){const e={schemaVersion:1,requests:Qw};await Na(qfr(),e)}function byn(e,t=Date.now()){return e.status!=="consumed"&&e.expiresAt>t}async function _yn(e){if(!Tyn.test(e.codeChallenge))return{ok:!1,reason:"code_challenge must be a base64url S256 digest"};if(!wyn.test(e.state))return{ok:!1,reason:"state must be 16-128 base64url characters"};const t=e.now??Date.now();return zfr.runExclusive(async()=>{await Gfr({force:!0});const r={schemaVersion:1,grantId:e.grantId,codeChallenge:e.codeChallenge,challengeMethod:"S256",state:e.state,requestedAt:t,expiresAt:t+vyn,status:"pending"};return Qw[e.grantId]=r,await jfr(),{ok:!0,request:r}})}async function Cyn(e,t=Date.now()){return zfr.runExclusive(async()=>{await Gfr({force:!0});const r=Qw[e];if(!r||!byn(r,t))return{status:"none"};if(r.status!=="authorized"||!r.code)return{status:"pending"};const{code:n,...o}=r;return Qw[e]={...o,status:"consumed",claimedAt:t},await jfr(),{status:"ready",code:r.code,state:r.state}})}Nar(),Wr(),Dr(),Hs(),zt(),Yc(),lx(),t$();var Ayn="proxy-share-notes.json",Hfr="nln",kyn=null,eE={},Vfr=!1,xyn=new Da;function Wfr(){return kyn??yt(wa(),".neurolink",Ayn)}async function Kfr(e={}){if(!(Vfr&&!e.force)){try{eE=JSON.parse(await Fr(Wfr(),"utf8"))?.notes??{}}catch{eE={}}Vfr=!0}}async function Iyn(){const{writeJsonSnapshotAtomically:e}=await Promise.resolve().then(()=>(cc(),Yae)),t={schemaVersion:1,notes:eE};await e(Wfr(),t)}function Ryn(e){const t=e.trim();if(t.startsWith(`${Hfr}_`))try{const r=JSON.parse(Buffer.from(t.slice(Hfr.length+1),"base64url").toString("utf8"));return typeof r?.noteId!="string"||typeof r.coins!="number"||typeof r.signature!="string"||typeof r.notAfter!="number"?void 0:r}catch{return}}async function Pyn(e,t,r=Date.now()){const{signature:n,...o}=e;if(!t||!e$(o,n,t))return{status:"forged",coins:0};await Kfr({force:!0});const s=eE[e.noteId];return s?s.redeemedAt!==void 0?{status:"spent",coins:s.coins}:s.notAfter<=r?{status:"expired",coins:s.coins}:{status:"valid",coins:s.coins}:{status:"unknown",coins:0}}async function Myn(e){const t=e.now??Date.now(),{signature:r,...n}=e.note;if(!e.secret||!e$(n,r,e.secret))return{ok:!1,status:"forged"};const o=await xyn.runExclusive(async()=>{await Kfr({force:!0});const i=eE[e.note.noteId];return i?i.redeemedAt!==void 0?{status:"spent",coins:i.coins}:i.notAfter<=t?{status:"expired",coins:i.coins}:(eE[i.noteId]={...i,redeemedAt:t,redeemedByGrant:e.grantId},await Iyn(),{status:"valid",coins:i.coins}):{status:"unknown",coins:0}});if(o.status!=="valid")return{ok:!1,status:o.status};const s=await Car(e.grantId,o.coins);return{ok:!0,coins:o.coins,balance:s}}t$(),War();var Oyn=64*1024,Dyn=32;function Jfr(e){try{const t=JSON.parse(e);return{errorType:t.error?.type??t.type??"stream_error",message:t.error?.message??t.message??"Upstream SSE error"}}catch{return{errorType:"stream_error",message:e.trim()||"Upstream SSE error"}}}function Yfr(e){if(e.event==="error")return!0;try{const t=JSON.parse(e.data);return t.type==="error"||t.error!==void 0}catch{return!1}}async function Nyn(e){const t=new TextDecoder,r=[];let n="",o=0;for(;o<Oyn&&r.length<Dyn;){let s;try{s=await e.read()}catch(a){return{kind:"transport_error",chunks:r,error:a}}if(s.done){n+=t.decode();const{events:a}=$$(n),c=a.find(Yfr);return c?{kind:"sse_error",chunks:r,...Jfr(c.data)}:r.length>0?{kind:"ready",chunks:r}:{kind:"empty",chunks:r}}if(!s.value||s.value.length===0)continue;r.push(s.value),o+=s.value.byteLength,n+=t.decode(s.value,{stream:!0});const i=$$(n);n=i.remainder;for(const a of i.events){if(Yfr(a))return{kind:"sse_error",chunks:r,...Jfr(a.data)};if(a.event!=="ping"&&(a.event||a.data))return{kind:"ready",chunks:r}}}return r.length>0?{kind:"ready",chunks:r}:{kind:"empty",chunks:r}}function Xfr(){let e=!1,t;const r=new Promise(o=>{t=o}),n=o=>{e||(e=!0,t(o))};return{outcome:r,complete:()=>n({kind:"completed"}),fail:o=>n({kind:"upstream_error",message:o}),cancel:()=>n({kind:"client_cancelled"})}}function i3(e,t,r){return e.kind==="completed"&&t?{kind:"upstream_error",message:t}:e.kind==="completed"&&r===!1?{kind:"upstream_error",message:"Anthropic stream ended without a message_stop event"}:e}function Lyn(e){const t=e.toLowerCase();return t.includes("opus")?"opus":t.includes("sonnet")?"sonnet":t.includes("haiku")?"haiku":"other"}function tE(e,t,r,n,o=!1){const s=[{provider:e.provider,model:e.model,label:`${e.provider}/${e.model??"unknown"}`}];for(const i of t)i.provider===e.provider&&i.model===e.model||s.push({provider:i.provider,model:i.model,...i.reasoningEffort!==void 0?{reasoningEffort:i.reasoningEffort}:{},label:`${i.provider}/${i.model}`});return o&&(t.length===0||s.length===1)&&s.push({label:"auto-provider"}),{requestedModel:r,modelTier:Lyn(r),attempts:s,skipped:[]}}function a3(e){if(!e)return 0;const t=parseInt(e,10);if(!Number.isNaN(t))return Math.max(1,t)*1e3;const r=new Date(e);return Number.isNaN(r.getTime())?0:Math.max(1e3,r.getTime()-Date.now())}var Fyn=1,$yn=20;function zue(e){return typeof e=="number"&&Number.isInteger(e)&&e>=Fyn&&e<=$yn?e:void 0}cc(),ix(),Ut(),z(),Lr(),Ng(),Xg(),bl(),ix(),Ut(),z();var que=900*1e3,Gue=6e4,Zfr=900*1e3,Qfr=6e4,oa="codex-oauth",jue="neurolink.codexFallback";function Jx(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="string")return t;const r=e.cause;if(!r||typeof r!="object")return;const n=r.code;return typeof n=="string"?n:void 0}function Uyn(e){const t=Jx(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}function rE(e,t){return lr(e).slice(0,200)||t}var Hue=new Map;async function Byn(e,t,r,n){const o=Hue.get(e);if(o)return o;const s=(async()=>{const i=await r.peekTokens(e).catch(()=>null),a=i?.refreshToken??t,c=await n(a),l={accessToken:c.accessToken,refreshToken:c.refreshToken??a,expiresAt:c.expiresAt??i?.expiresAt??Date.now()+36e5};return i&&await r.saveTokens(e,{...l,tokenType:"Bearer",...i.scope?{scope:i.scope}:{}}),l})().finally(()=>{Hue.delete(e)});return Hue.set(e,s),s}async function Vue(e,t){return Byn(e,t,gi,qmn)}var zyn=new Set(["host","connection","content-length","transfer-encoding","cookie","proxy-authorization","authorization","x-api-key","chatgpt-account-id","accept-encoding"]);function nh(e,t,r){return new Response(JSON.stringify({error:{type:"proxy_error",message:t,...r?{code:r,retryable:!1}:{}}}),{status:e,headers:{"content-type":"application/json"}})}function qyn(e,t){const r={type:"response.failed",response:{error:{type:"insufficient_quota",code:"insufficient_quota",message:e}}},n={"content-type":"text/event-stream"};return t!==void 0&&(n["retry-after"]=String(t)),new Response(`event: response.failed
|
|
2357
2357
|
data: ${JSON.stringify(r)}
|
|
2358
2358
|
|
|
2359
|
-
`,{status:200,headers:n})}async function egr(){const[e,t,r]=await Promise.all([gi.getProviderSnapshot(),kx(),Ile()]),n=Date.now(),o=[];for(const[s,i]of Object.entries(e)){if(!s.startsWith(Qp)||i.disabled)continue;const a=i.tokens;if(!a||a.tokenType!=="Bearer")continue;let c=a.accessToken,l=a.expiresAt;if(jmn(l)&&a.refreshToken)try{const m=await Vue(s,a.refreshToken);c=m.accessToken,l=m.expiresAt??l}catch(m){p.debug(`Codex proactive refresh failed for ${s.slice(Qp.length)}: ${m instanceof Error?m.message:String(m)}`)}const u=t[s],d=u&&u.coolingUntil>n;o.push({key:s,label:s.slice(Qp.length)||s,token:c,refreshToken:a.refreshToken,expiresAt:l,accountId:Rx(c),quota:r[s],coolingUntil:d?u.coolingUntil:void 0,coolingReason:u?.reason,expiredCooldownUntil:u&&!d?u.coolingUntil:void 0})}return o}function tgr(e,t){return[...e].sort((r,n)=>{const o=r.coolingUntil!==void 0&&r.coolingUntil>t,s=n.coolingUntil!==void 0&&n.coolingUntil>t;if(o!==s)return o?1:-1;const i=r.quota?.unifiedStatus==="rejected",a=n.quota?.unifiedStatus==="rejected";if(i!==a)return i?1:-1;const c=r.quota&&r.quota.sessionStatus!=="unknown"?r.quota.sessionUsed:-1,l=n.quota&&n.quota.sessionStatus!=="unknown"?n.quota.sessionUsed:-1;return c-l})}function rgr(e,t){const r={};for(const[o,s]of Object.entries(e)){const i=o.toLowerCase();zyn.has(i)||(r[i]=s)}r.authorization=`Bearer ${t.token}`;const n=Rx(t.token,t.accountId);return n&&(r["chatgpt-account-id"]=n),r["content-type"]="application/json",r["user-agent"]||(r["user-agent"]=Dle),r.originator||(r.originator=$mn),r.accept||(r.accept="text/event-stream"),r}function ngr(e,t){try{const n=JSON.parse(e)?.error;if(!n||typeof n!="object"||n.type!=="usage_limit_reached"&&n.code!=="usage_limit_reached")return null;const o=n.resets_at??n.reset_at,s=n.resets_in_seconds??n.reset_after_seconds,i=typeof o=="number"&&Number.isFinite(o)&&o>0?o>4102444800?o:o*1e3:typeof s=="number"&&Number.isFinite(s)&&s>0?t+s*1e3:0,a=n.limit_type,l=n.model||n.scope!==void 0&&n.scope!=="account"?"unknown":a==="primary"||a==="session"?"session":a==="secondary"||a==="weekly"?"weekly":"unknown";return{errorCode:"usage_limit_reached",resetAt:Number.isFinite(i)?i:0,scope:l}}catch{return null}}function Gyn(e,t,r,n=""){const o=r+Gue;if(e){if(e.weeklyStatus==="rejected"&&e.weeklyResetAt>0)return{coolingUntil:Math.max(e.weeklyResetAt*1e3,o),reason:"weekly"};if(e.sessionStatus==="rejected"&&e.sessionResetAt>0)return{coolingUntil:Math.max(e.sessionResetAt*1e3,o),reason:"session"}}const s=ngr(n,r);if(s)return s.scope!=="unknown"&&s.resetAt>0?{coolingUntil:Math.max(s.resetAt,o),reason:s.scope}:{coolingUntil:r+Math.min(Zfr,Math.max(s.resetAt-r,t,Gue)),reason:"unified"};const i=Math.min(Zfr,Math.max(t,Gue));return{coolingUntil:r+i,reason:e?.unifiedStatus==="rejected"?"unified":"transient"}}function jyn(e,t,r,n){if(e.responseHeaders||(e.responseHeaders={}),e.responseHeaders["x-neurolink-account"]=t.label,e.responseHeaders["x-neurolink-account-type"]="codex-oauth",e.responseHeaders["x-neurolink-served-by"]="codex",e.responseHeaders["x-neurolink-attempt"]=String(r),e.responseHeaders["x-neurolink-quota-source"]=n?"live":"none",n&&n.sessionStatus!=="unknown"&&(e.responseHeaders["x-neurolink-quota-session-left-pct"]=String(Math.round((1-n.sessionUsed)*100))),n&&n.weeklyStatus!=="unknown"){const o=String(Math.round((1-n.weeklyUsed)*100));e.responseHeaders["x-neurolink-quota-weekly-left-pct"]=o,e.responseHeaders["x-neurolink-weekly-left-pct"]=o}}async function ogr(e){e.metadata?.[jue]!==!0&&Jw({timestamp:new Date().toISOString(),requestId:e.requestId,phase:"client_request",model:sgr(e),stream:!0,headers:e.headers,body:e.body,contentType:"application/json",...zw({requestId:e.requestId})});const t=await Hyn(e);return e.metadata?.[jue]===!0?t:igr(e,t,"client_response")}function sgr(e){const t=e.body;return typeof t?.model=="string"?t.model:"-"}function igr(e,t,r,n,o){if(!Sue())return t;const s={timestamp:new Date().toISOString(),requestId:e.requestId,phase:r,model:sgr(e),stream:!0,headers:Object.fromEntries(t.headers.entries()),contentType:t.headers.get("content-type")??void 0,responseStatus:t.status,account:n?.label,accountType:n?oa:void 0,attempt:o,...zw({requestId:e.requestId})};if(!t.body||mfr())return Jw(s),t;const i=Pue();return i.capture.then(a=>Jw({...s,timestamp:new Date().toISOString(),body:a.text,bodySize:a.totalBytes,sourceTruncated:a.truncated})).catch(()=>{}),new Response(t.body.pipeThrough(i.stream),{status:t.status,statusText:t.statusText,headers:t.headers})}async function Hyn(e){const t=Date.now();let r=e.body??{},n,o,s,i,a=!1;const c=async E=>{if(i)try{a?(await sue(i,E),i.snapshot.settlement==="unconfirmed"&&jw("token_budget",{requestId:e.requestId,event:"settlement_unconfirmed"})):await i.cancelBeforeDispatch()}catch(_){jw("token_budget",{requestId:e.requestId,event:"settlement_unconfirmed",errorCode:el(_)?.code??"PROXY_TOKEN_BUDGET_UNAVAILABLE"})}},l=typeof r.model=="string"?r.model:"-",u=e.metadata?.[jue]===!0,d=r.reasoning,m=d&&typeof d=="object"&&"effort"in d&&typeof d.effort=="string"?d.effort:void 0;let h;try{h=Ux.startRequest({requestId:e.requestId,method:e.method,path:e.path,model:l,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,provider:"openai",userAgent:e.headers["user-agent"],recordRequestMetrics:!u,recordUsageMetrics:!0},e.headers)}catch{}const f=(E,_,C={})=>Kw({timestamp:new Date().toISOString(),requestId:e.requestId,method:e.method,path:e.path,model:l,requestedModel:l,contextPreflight:s,tokenBudget:i?{...i.snapshot}:void 0,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:E?.label??"",...E?{accountKey:E.key}:{},accountType:E?oa:"",provider:"openai",inputIncludesCachedTokens:!0,...h?.getTraceContext(),...m?{reasoningEffort:m}:{},firstUsefulOutputStatus:C.firstUsefulOutputMs!==void 0?"observed":"not_observed",...Fx(e.headers),responseStatus:_,responseTimeMs:Date.now()-t,...C});let g=!1;const y=async(E,_,C={})=>{if(await c(C.inputTokens!==void 0&&C.outputTokens!==void 0?C.inputTokens+C.outputTokens:void 0),!g){if(g=!0,Fw(e.requestId)){const A=e.abortSignal?.aborted?e.abortSignal.reason?.name==="TimeoutError"?504:499:_;try{h?.end(A,Date.now()-t)}catch{}return}try{C.errorType&&h?.setError(C.errorType,C.errorMessage??C.errorType),h?.end(_,Date.now()-t)}catch{}u||(_>=400?Zg(_,E?.label,E?oa:void 0,{requestId:e.requestId,...E?{accountKey:E.key}:{},errorType:C.errorType,terminalOutcome:C.terminalOutcome??"handler_error",message:C.errorMessage,errorCode:C.errorCode}):nx(E?.label,E?oa:void 0),await f(E,_,C))}},v=(E,_,C,A,k={})=>{Eue({timestamp:new Date().toISOString(),requestId:e.requestId,attempt:_,...h?.getTraceContext(),...u?{parentRequestId:e.requestId.replace(/:codex-fallback$/,"")}:{},...m?{reasoningEffort:m}:{},method:e.method,path:e.path,model:l,requestedModel:l,contextPreflight:s,tokenBudget:i?{...i.snapshot}:void 0,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:E.label,accountKey:E.key,accountType:oa,provider:"openai",responseStatus:A,responseTimeMs:Date.now()-t,attemptDurationMs:Date.now()-C,...k}).catch(()=>{})},w=async()=>{try{o=Zle({provider:"codex",model:l,body:r}),s=o.evidence,r=o.body,n=JSON.stringify(r)}catch(M){if(!(M instanceof _r))throw M;return s=M.evidence,await y(void 0,M.status,{errorType:"context_preflight",errorCode:M.code,errorMessage:M.message,retryable:!1,terminalOutcome:"handler_error"}),nh(M.status,M.message,M.code)}const E=await egr(),_=async M=>(await y(M,499,{errorType:"client_cancelled",errorMessage:"Client cancelled Codex request",terminalOutcome:"client_cancelled"}),nh(499,"Client cancelled Codex request"));if(e.abortSignal?.aborted)return _();if(E.length===0)return await y(void 0,401,{errorType:"no_accounts",errorMessage:"No Codex accounts"}),nh(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const C=Date.now(),A=tgr(E,C),k=A.filter(M=>!(M.coolingUntil!==void 0&&M.coolingUntil>C));if(k.length===0){const M=A.reduce((L,q)=>q.coolingUntil===void 0?L:L===void 0?q.coolingUntil:Math.min(L,q.coolingUntil),void 0),F=M?Math.max(1,Math.ceil((M-C)/1e3)):60;await y(void 0,429,{errorType:"all_accounts_cooling",errorMessage:"All Codex accounts are rate-limited"});const N=M?new Date(M).toISOString():void 0;return qyn(N?`Codex quota exhausted: all accounts are rate-limited. Resets at ${N}.`:"Codex quota exhausted: all accounts are rate-limited.",F)}let R=0,I="All Codex accounts failed",P=502,O={errorType:"all_accounts_failed"},U;for(const M of k){try{h?.setAccountSelection({strategy:"codex-quota-order",accountsTotal:E.length,accountsHealthy:k.length,selectedAccount:M.label,accountType:oa})}catch{}let F=!1;for(;;){if(e.abortSignal?.aborted)return _(U);await c(),i=void 0,a=!1;try{i=await oue({provider:"codex",accountKey:M.key,sessionKey:eue(new Headers(e.headers)),requestId:e.requestId,reservationTokens:o.totalTokensReservation,estimateProvenance:"estimated_input_plus_serving_model_output_reserve"})}catch(G){const X=el(G);if(!X)throw G;return await y(M,X.status,{errorType:"token_budget",errorCode:X.code,errorMessage:X.message,retryable:!1,terminalOutcome:"handler_error"}),nh(X.status,X.message,X.code)}if(e.abortSignal?.aborted)return _(M);R+=1;const N=Date.now();U=M,YF(M.label,oa);let L;try{const G=rgr(e.headers,M);Jw({timestamp:new Date().toISOString(),requestId:e.requestId,phase:"upstream_request",model:l,stream:!0,body:n,headers:G,contentType:"application/json",account:M.label,accountType:oa,attempt:R,...h?.getTraceContext()}),a=!0,L=await fetch(Nmn,{method:"POST",headers:G,body:n,signal:e.abortSignal?AbortSignal.any([e.abortSignal,AbortSignal.timeout(que)]):AbortSignal.timeout(que)})}catch(G){if(e.abortSignal?.aborted)return v(M,R,N,499,{errorType:"client_cancelled",errorMessage:"Client cancelled Codex request",retryable:!1}),_(M);p.debug(`Codex upstream fetch failed (${M.label}): ${lr(G instanceof Error?G.message:String(G))}`);const X=rE(G instanceof Error?G.message:String(G),"Codex upstream request failed"),ce=Jx(G),Q=Uyn(G);if(Pr(M.label,oa,502),v(M,R,N,502,{errorType:"network_error",errorMessage:X,...ce?{errorCode:ce}:{},transportScope:Q,retryable:["UND_ERR_CONNECT_TIMEOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"].includes(ce??"")}),O={errorType:"network_error",errorMessage:X,errorCode:ce,transportScope:Q},!["UND_ERR_CONNECT_TIMEOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"].includes(ce??""))return await y(M,502,{...O,errorMessage:X}),nh(502,"Codex upstream request failed");I="Codex upstream request failed",P=502;break}if(L=igr(e,L,"upstream_response",M,R),L.ok){const G=Kpr(L.headers);G&&Zp(M.key,G).catch(()=>{}),M.expiredCooldownUntil!==void 0&&Yp(M.key,M.expiredCooldownUntil).catch(()=>{}),jyn(e,M,R,G),v(M,R,N,L.status);const X={"content-type":L.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive",...e.responseHeaders??{}};if(!L.body)return Pr(M.label,oa,502),v(M,R,N,502,{errorType:"incomplete_stream",errorMessage:"Codex returned no response stream",retryable:!1}),await y(M,502,{terminalOutcome:"stream_error",errorType:"incomplete_stream",errorMessage:"Codex returned no response stream"}),new Response(L.body,{status:L.status,headers:X});const{stream:ce,usage:Q,evidence:Ie}=Apn(),Ee=new Response(L.body.pipeThrough(ce),{status:L.status,headers:X});return $w(e.metadata,{onTerminal:({outcome:le,error:ae,observedBodyBytes:Pe})=>Q.then(Ae=>{const Te=Ie(),he=Te.completed&&Pe>=Te.terminalBytes,Oe=Te.errorType||(le==="completed"||le==="bodyless")&&!Te.completed,De=Ae?{inputTokens:Ae.inputTokensObserved?Ae.inputTokens:void 0,outputTokens:Ae.outputTokensObserved?Ae.outputTokens:void 0,cacheReadTokens:Ae.cacheReadTokensObserved?Ae.cacheReadTokens:void 0,cacheCreationTokens:Ae.cacheCreationTokensObserved?Ae.cacheCreationTokens:void 0,reasoningTokens:Ae.reasoningTokensObserved?Ae.reasoningTokens:void 0}:{};if(Ae?.inputTokensObserved&&Ae.outputTokensObserved)try{h?.setUsage({...Ae,reasoningTokens:Ae.reasoningTokensObserved?Ae.reasoningTokens:void 0,cacheReadTokensObserved:Ae.cacheReadTokensObserved===!0,cacheCreationTokensObserved:Ae.cacheCreationTokensObserved===!0,inputIncludesCachedTokens:!0})}catch{}const Ye=Te.firstUsefulOutputAt===void 0||Te.observationIncomplete?{firstUsefulOutputStatus:Te.completed&&!Te.observationIncomplete?"no_useful_output":"not_observed"}:{firstUsefulOutputStatus:"observed",firstUsefulOutputEvent:Te.firstUsefulOutputEvent,firstUsefulOutputMs:Math.max(0,Te.firstUsefulOutputAt-t)};return Oe?(Pr(M.label,oa,502),v(M,R,N,502,{...De,inputIncludesCachedTokens:!0,errorType:Te.errorType??"incomplete_stream",errorCode:Te.errorCode,errorMessage:Te.errorMessage??"Codex stream ended without a completion event",retryable:!1}),y(M,502,{...De,...Ye,terminalOutcome:"stream_error",errorType:Te.errorType??"incomplete_stream",errorCode:Te.errorCode,errorMessage:Te.errorMessage??"Codex stream ended without a completion event"})):le==="completed"||le==="bodyless"||le==="client_cancelled"&&he?y(M,L.status,{terminalOutcome:"completed",...De,...Ye}):(le==="stream_error"&&(Pr(M.label,oa,502),v(M,R,N,502,{errorType:"stream_error",errorCode:Jx(ae),errorMessage:rE(ae instanceof Error?ae.message:"","Codex upstream stream failed"),retryable:!1})),y(M,le==="client_cancelled"?499:502,{errorType:le==="client_cancelled"?"client_cancelled":"stream_error",errorMessage:le==="client_cancelled"?"Client cancelled Codex stream":rE(ae instanceof Error?ae.message:"","Codex upstream stream failed"),...le==="stream_error"?{errorCode:Jx(ae)}:{},terminalOutcome:le,...De,...Ye}))}).catch(()=>{})}),Ee}const q=await L.text().catch(()=>"");if((L.status===401||L.status===403)&&!F&&M.refreshToken){const G=rE(q,"Codex authentication rejected upstream");Pr(M.label,oa,L.status),v(M,R,N,L.status,{errorType:"authentication_error",errorMessage:G,retryable:!0}),F=!0;const X={accessToken:M.token,refreshToken:M.refreshToken,expiresAt:M.expiresAt??0};try{const ce=await Vue(M.key,M.refreshToken);M.token=ce.accessToken,M.refreshToken=ce.refreshToken??M.refreshToken,M.expiresAt=ce.expiresAt??M.expiresAt,M.accountId=Rx(ce.accessToken);continue}catch(ce){if(Gmn(ce)){await gi.markDisabledIfCurrent(M.key,X,"refresh_invalid")&&p.always(`[proxy] codex account=${M.label} disabled until re-authentication. Run: neurolink auth login codex --label ${M.label}`),O={errorType:"authentication_error",errorCode:"refresh_invalid"},P=401,I="Codex token refresh failed; re-login required";break}await Vu(M.key,Date.now()+Qfr,"auth").catch(()=>{}),p.debug(`[proxy] codex account=${M.label} refresh failed transiently; cooling and rotating`),O={errorType:"auth_refresh_unavailable",errorCode:Jx(ce)},P=503,I="Codex token refresh temporarily unavailable";break}}if(L.status===429){const G=Kpr(L.headers);G&&Zp(M.key,G).catch(()=>{});const X=a3(L.headers.get("retry-after")),ce=Date.now(),Q=ngr(q,ce),Ie=Gyn(G,X,ce,q);await Vu(M.key,Ie.coolingUntil,Ie.reason).catch(()=>{});const Ee=Ie.reason==="transient"?"transient":"quota",le=rE(q,"Codex account rate-limited");Pr(M.label,oa,L.status,Ee),v(M,R,N,L.status,{errorType:"rate_limit_error",errorMessage:le,retryable:Ee==="transient",rateLimitKind:Ee,cooldownReason:Ie.reason,...Q?{errorCode:Q.errorCode,quotaResetAt:Q.resetAt||void 0,quotaScope:Q.scope}:{}}),O={errorType:"rate_limit_error",errorCode:Q?.errorCode},P=429,I="Codex account rate-limited";break}(L.status===401||L.status===403)&&await Vu(M.key,Date.now()+Qfr,"auth").catch(()=>{});const B=rE(q,"Codex error"),H=L.status===401||L.status===403?"authentication_error":"api_error";Pr(M.label,oa,L.status),v(M,R,N,L.status,{errorType:H,errorMessage:B,retryable:L.status>=500}),O={errorType:H},P=L.status>=500?502:L.status,I=B;break}}return await y(U,P,{...O,errorMessage:O.errorMessage??I}),nh(P,I)};try{return await w()}catch(E){await c();try{h?.end(502,Date.now()-t)}catch{}throw E}}function Vyn(e){if(Buffer.byteLength(e,"utf8")>2*1024*1024)return;let t;try{t=JSON.parse(e)}catch{return}if(!(!t||typeof t!="object"||!("models"in t)||!Array.isArray(t.models)))for(const r of t.models.slice(0,1024)){if(!r||typeof r!="object")continue;const n=r.slug??r.id;if(typeof n!="string"||n.length===0||n.length>256)continue;const o=r.context_window,s=r.max_output_tokens;Number.isSafeInteger(o)&&o>0&&W9("codex",n,o);const i=K9("codex",n);Number.isSafeInteger(s)&&s>0&&(i===void 0||s<i)?Jot("codex",n,s):KLr("codex",n)}}async function Wyn(e){const t=await egr();if(t.length===0)return nh(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const r=Date.now(),n=tgr(t,r),o=d=>d.coolingUntil!==void 0&&d.coolingUntil>r,s=[...n.filter(d=>!o(d)),...n.filter(o)],a=new URLSearchParams(e.query??{}).toString(),c=a?`${qpr}?${a}`:qpr;let l=502,u="Codex model discovery upstream failed";for(const d of s){let m=!1;for(;;){let h;try{h=await fetch(c,{method:"GET",headers:rgr(e.headers??{},d),signal:AbortSignal.any([...e.abortSignal?[e.abortSignal]:[],AbortSignal.timeout(que)])})}catch(y){l=502,u=`Codex model discovery upstream failed: ${y instanceof Error?y.message:String(y)}`;break}if(h.status===401||h.status===403){if(!m&&d.refreshToken){m=!0;try{const y=await Vue(d.key,d.refreshToken);d.token=y.accessToken,d.refreshToken=y.refreshToken??d.refreshToken,d.expiresAt=y.expiresAt??d.expiresAt,d.accountId=Rx(y.accessToken);continue}catch{l=401,u="Codex token refresh failed; re-login required";break}}l=h.status,u="Codex model discovery rejected upstream";break}const f=await h.text();h.ok&&Vyn(f);const g=h.headers.get("content-type")??"application/json";return new Response(f,{status:h.status,headers:{"content-type":g}})}}return nh(l,u)}function Kyn(e=""){return{prefix:`${e}/backend-api/codex`,routes:[{method:"POST",path:`${e}/backend-api/codex/responses`,description:"Codex ChatGPT-backend Responses API (account pool)",handler:t=>ogr(t)},{method:"GET",path:`${e}/backend-api/codex/models`,description:"Codex model discovery, relayed upstream (account pool)",handler:t=>Wyn(t)}]}}function Jyn(e,t,r,n){if(t.snapshot.scope==="disabled")return e;let o,s=!1,i=!1,a=!1,c,l,u=0,d=0,m="",h=!1;const f=e.headers.get("content-type")?.includes("text/event-stream"),g=new TextDecoder,y=C=>{try{const A=JSON.parse(C);A?.type==="message_stop"&&(s=!0),A?.type==="error"&&(a=!0);const k=A?.usage??A?.message?.usage;if(!k||typeof k!="object")return;const R=I=>typeof I=="number"&&Number.isSafeInteger(I)&&I>=0;R(k.input_tokens)&&(c=Math.max(c??0,k.input_tokens)),R(k.output_tokens)&&(A?.type==="message_delta"&&(i=!0),l=Math.max(l??0,k.output_tokens)),R(k.cache_read_input_tokens)&&(u=Math.max(u,k.cache_read_input_tokens)),R(k.cache_creation_input_tokens)&&(d=Math.max(d,k.cache_creation_input_tokens))}catch{}},v=C=>{if(!f){!h&&m.length+C.length<=1024*1024?m+=C:(h=!0,m="");return}for(const A of C.split(/(?<=\n)/u))!h&&m.length+A.length<=64*1024?m+=A:(h=!0,m=""),A.endsWith(`
|
|
2360
|
-
`)&&(!h&&m.startsWith("data:")&&y(m.slice(5).trim()),m="",h=!1)},w=C=>o||(o=(async()=>{n?.removeEventListener("abort",E),C&&(v(g.decode()),!h&&m&&y(f&&m.startsWith("data:")?m.slice(5).trim():m));const A=C&&!a&&(!f||s&&i)&&c!==void 0&&l!==void 0?c+l+u+d:void 0;try{await sue(t,A)}finally{r()}})(),o),E=()=>{w(!1).catch(()=>{})};if(n?.aborted?E():n?.addEventListener("abort",E,{once:!0}),!e.body)return w(!1).catch(()=>{}),e;const _=e.body.getReader();return new Response(new ReadableStream({async pull(C){try{const A=await _.read();if(A.done){await w(!0),C.close();return}v(g.decode(A.value,{stream:!0})),C.enqueue(A.value)}catch(A){await w(!1).catch(()=>{}),C.error(A)}},async cancel(C){await Promise.allSettled([_.cancel(C),w(!1)])}},{highWaterMark:0}),{status:e.status,statusText:e.statusText,headers:e.headers})}var c3=new Set(["cookie","proxy-authorization","host","connection","content-length","transfer-encoding"]),Wue="proxy/internal",Kue="internal";function agr(e,t){return e?t==="codex-oauth"?{accountKey:e.startsWith("codex:")?e:`codex:${e}`,provider:"openai"}:t==="oauth"||t==="api_key"||t==="passthrough"?{accountKey:t==="passthrough"?e:jp(e),provider:"anthropic"}:t==="vertex"?{accountKey:e,provider:"vertex"}:{}:{}}var oh=0,cgr=0,Yx=5,l3=2,Jue=[250,1e3],lgr=4,ugr=[250,500,1e3,2e3],Yue=1,Yyn=120*1e3,u3=2,dgr=3e4,mgr=11520*60*1e3,pgr=5e3,Xyn=900*1e3,Xue=900*1e3,Zyn=3e4,Qyn=300*1e3,Xx=900*1e3;function hgr(e,t){const r=JSON.parse(t),n=Zle({provider:"anthropic",model:r.model,body:r});return e.metadata.contextPreflight=n.evidence,{bodyStr:n.body===r?t:JSON.stringify(n.body),preparedContext:n}}var fgr;async function Zue(e,t,r,n,o){w3(r);const s=o.preparedContext,i=await oue({provider:"anthropic",accountKey:n,requestId:r.requestId,sessionKey:eue({get:a=>r.headers[a]??null}),reservationTokens:s.totalTokensReservation,estimateProvenance:"estimated_input_plus_output_reserve"});if(r.metadata.tokenBudget=i.snapshot,t.signal?.aborted||r.abortSignal?.aborted)throw await i.cancelBeforeDispatch(),r.metadata.tokenBudget=i.snapshot,t.signal?.reason??r.abortSignal?.reason;fgr??=new d_({headersTimeout:Xx,bodyTimeout:Xx});try{const a=String(t.body);YF(o.accountLabel,o.accountType),o.tracer?.logUpstreamRequestHeaders(t.headers),o.tracer?.logUpstreamRequestBody(a),o.logProxyBody({phase:"upstream_request",headers:t.headers,body:a,bodySize:Buffer.byteLength(a,"utf8"),contentType:"application/json",account:o.accountLabel,accountType:o.accountType,attempt:o.attemptNumber,metadata:{upstreamMethod:"POST",upstreamUrl:e}});const c=await fetch(e,{...t,body:a,dispatcher:fgr});return Jyn(c,i,()=>{r.metadata.tokenBudget=i.snapshot},t.signal??void 0)}catch(a){throw await i.settle().catch(()=>{}),r.metadata.tokenBudget=i.snapshot,a}}var pc=new Map,Zx=new Xmn,nE=new Qmn,Que=900*1e3,ede=new Map,ggr=new Map,Qx=new Map;function ygr(e){let t=Qx.get(e);return t||(t={active:0,waiters:[]},Qx.set(e,t)),t}function tde(e,t){for(;t.waiters.length>0&&t.active<t.waiters[0].capacity;){const r=t.waiters.shift();if(!r)return;t.active+=1,r.resolve(d3(e,t))}}function e0n(e,t,r){if(r===void 0)return;const n=s=>s.generation!==void 0&&s.generation<r,o=t.waiters.filter(n);if(o.length!==0){t.waiters=t.waiters.filter(s=>!n(s));for(const s of o)t.active+=1,s.resolve(d3(e,t))}}function d3(e,t){let r=!1;return{release:()=>{r||(r=!0,t.active=Math.max(0,t.active-1),tde(e,t),vgr(e,t))}}}function vgr(e,t){t.active===0&&t.waiters.length===0&&Qx.delete(e)}function t0n(e,t,r){const n=zue(t),o=ygr(e);if(n===void 0)return e0n(e,o,r),o.active+=1,d3(e,o);if(!(o.waiters.length>0||o.active>=n))return o.active+=1,d3(e,o)}function r0n(e){return Qx.get(e)?.active??0}function n0n(e,t){const r=zue(t);if(r===void 0)return!0;const n=Qx.get(e);return!n||n.waiters.length===0&&n.active<r}function o0n(e,t,r){const n=zue(t);if(n===void 0)throw new Error("Account admission queue requires an explicit capacity");const o=ygr(e);let s=!0,i,a;const c=new Promise(u=>{a=u}),l={capacity:n,generation:r,resolve:u=>{s=!1,i=u,a(u)}};return o.waiters.push(l),tde(e,o),{accountKey:e,promise:c,cancel:()=>{if(i){const d=i;i=void 0,d.release();return}if(!s)return;s=!1;const u=o.waiters.indexOf(l);u>=0&&(o.waiters.splice(u,1),tde(e,o)),vgr(e,o)}}}async function s0n(e,t,r,n=ode,o){const s=[...new Set(e)].map(a=>o0n(a,t,o));let i;try{return await Ct(id(Promise.race(s.map(a=>a.promise.then(c=>i?(c.release(),new Promise(()=>{})):(i=a.accountKey,{accountKey:a.accountKey,lease:c})))),r),n,`Account admission timed out after ${n}ms`)}catch(a){if(r?.aborted)throw a;return}finally{for(const a of s)a.accountKey!==i&&a.cancel()}}var Tgr=!1,rde,nde=6e4,ode=9e4,i0n=12e4,a0n=250,c0n=15e3;function my(e,t,r){t<=1||e===r&&(oh=(oh+1)%t)}function wgr(e,t){if(!t)return 0;const r=e.findIndex(n=>Xae(n.key,t));return r>=0?r:0}function l0n(e,t){if(e.length<=1)return;const r=wgr(e,t);if(oh===r)return;const n=e[r],o=pc.get(n.key);if((!o||!o.coolingUntil||Date.now()>=o.coolingUntil)&&(oh=r,o?.coolingUntil)){const s=o.coolingUntil;o.coolingUntil=void 0,o.coolingReason=void 0,Yp(n.key,s).catch(()=>{}),p.always(`[proxy] home primary account=${n.label} cooling expired, resetting primaryAccountIndex to ${r}`)}}function Egr(e){const t=pc.get(e);return!!t?.coolingUntil&&Date.now()<t.coolingUntil}function u0n(e,t,r=Date.now()){let n=ede.get(e);if(!n||r>=n.coolingUntil?(n={coolingUntil:t,retriesClaimed:0},ede.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t),!(n.retriesClaimed>=u3))return n.retriesClaimed+=1,n.retriesClaimed}function Sgr(e,t,r,n){const o=u0n(e,t);if(r===void 0||n>=u3||o===void 0)return;const s=Math.min(r||1e3,dgr);return{slot:o,delayMs:Math.min(dgr,Jgr(s*o))}}function d0n(e,t){if(ede.delete(e.key),t.coolingReason!=="transient"||!t.coolingUntil)return;const r=t.coolingUntil;t.coolingUntil=void 0,t.coolingReason=void 0,Yp(e.key,r).catch(()=>{})}function m0n(e,t,r=Date.now()){if(t<=r)return 0;if(t-r>ode)return;let n=ggr.get(e);!n||r>=n.coolingUntil?(n={coolingUntil:t,nextAdmissionAt:t},ggr.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t,n.nextAdmissionAt=Math.max(n.nextAdmissionAt,t));const o=Math.max(r,n.coolingUntil,n.nextAdmissionAt);if(!(o-n.coolingUntil>c0n))return n.nextAdmissionAt=o+a0n,o-r}async function p0n(e){const t=Date.now()+i0n;for(;Date.now()<t;){const r=e.filter(i=>!Egr(i.key));if(r.length>0)return r;const n=Date.now(),o=e.map(i=>({account:i,state:$a(i.key)})).filter(({state:i})=>i.coolingReason==="transient"&&i.coolingUntil!==void 0&&i.coolingUntil>n).sort((i,a)=>(i.state.coolingUntil??Number.POSITIVE_INFINITY)-(a.state.coolingUntil??Number.POSITIVE_INFINITY))[0];if(!o?.state.coolingUntil)return[];const s=m0n(o.account.key,o.state.coolingUntil,n);if(s===void 0||n+s>t)return[];p.always(`[proxy] all usable accounts are transiently cooling; queueing request for account=${o.account.label} in ${s}ms`),await Zl(s)}return[]}function Fs(e,t){if(!e||e<=0)return;const r=e>4102444800?e:e*1e3;return r>t?r:void 0}function eI(e,t){try{const r=t.poolAccounts?hpn(t.poolAccounts.map(o=>{const s=pc.get(o.key);return{...s?.coolingUntil!==void 0?{coolingUntil:s.coolingUntil}:{},...s?.quota?{quota:s.quota}:{}}})):void 0,n=ppn({...t.upstreamHeaders?{upstreamHeaders:t.upstreamHeaders}:{},context:{quota:t.quota??null,source:t.source,...t.account?{accountLabel:t.account.label}:{},...t.accountType??t.account?.type?{accountType:t.accountType??t.account?.type}:{},...t.servedBy?{servedBy:t.servedBy}:{},...t.attempt!==void 0?{attempt:t.attempt}:{},...t.accountState?.coolingUntil!==void 0?{coolingUntil:t.accountState.coolingUntil}:{},...t.accountState?.coolingReason?{coolingReason:t.accountState.coolingReason}:{},...r?{pool:r}:{}}});e.responseHeaders={...e.responseHeaders??{},...vde(n)}}catch(r){p.debug(`[proxy] failed to publish limit headers: ${r instanceof Error?r.message:String(r)}`)}}function m3(e,t,r){const n=Math.min(mgr,(r&&xpr[r])??mgr);return Math.min(Math.max(e,t+pgr),t+n)}function p3(e){return e?.trim().toLowerCase()==="allowed"}function bgr(e,t){return!e||Fs(e.resetsAt,t)===void 0?!1:e.status?.trim().toLowerCase()==="rejected"||(e.used??0)>=1}function h0n(e,t,r,n=rl){if(!e||!t||!p3(e.sessionStatus)||!p3(e.weeklyStatus)||oE(e,n))return null;const o=pde(e,t,r);return bgr(o,r)?o:null}function f0n(e,t,r=rl){return!p3(e.sessionStatus)||!p3(e.weeklyStatus)||oE(e,r)?!1:(e.windows??[]).some(n=>n.kind==="weekly_scoped"&&typeof n.scopeModel=="string"&&t-mde(e,n)<=Que&&bgr(n,t))}function sde(e,t,r,n=e?.unifiedStatus,o=rl,s){if(e&&e.weeklyStatus==="rejected"){const l=Fs(e.weeklyResetAt,r)??(t>0?r+t:r+nde);return{reason:"weekly",scope:"account",coolingUntil:m3(l,r,"weekly"),rotateImmediately:!0}}const i=oE(e,o);if(e&&e.sessionStatus==="rejected"&&!i){const l=Fs(e.sessionResetAt,r)??(t>0?r+t:r+nde);return{reason:"session",scope:"account",coolingUntil:m3(l,r,"session"),rotateImmediately:!0}}const a=h0n(e,s,r,o);if(a)return{reason:"unified",scope:"model",coolingUntil:Fs(a.resetsAt,r)??(t>0?r+t:r+Xue),rotateImmediately:!0};if(n?.trim().toLowerCase()==="rejected"&&!i){const l=t>0?r+t:r+Xue;return{reason:"unified",scope:"account",coolingUntil:m3(l,r,"unified"),rotateImmediately:!0}}const c=t>0?t:nde;return{reason:"transient",scope:"account",coolingUntil:r+Math.max(pgr,Math.min(c,Xyn)),rotateImmediately:!1}}function ide(e,t){return Math.max(0,Math.round((e-t)/6e4))}function ade(e,t,r,n=rl){const o=oE(t,n),s=f0n(t,r,n);let i,a;if(t.weeklyStatus==="rejected"&&(i=Fs(t.weeklyResetAt,r),a="weekly"),i===void 0&&o&&e.coolingUntil&&(e.coolingReason==="session"||e.coolingReason==="unified")){const l=e.coolingUntil;return e.coolingUntil=void 0,e.coolingReason=void 0,p.always("[proxy] clearing subscription cooldown because Anthropic explicitly permits overage"),{kind:"cleared",coolingUntil:l}}if(i===void 0&&t.sessionStatus==="rejected"&&!o?(i=Fs(t.sessionResetAt,r),a="session"):i===void 0&&t.unifiedStatus==="rejected"&&!o&&!s&&(i=r+Xue,a="unified"),i===void 0){if(!!e.coolingUntil&&(e.coolingReason==="weekly"&&t.weeklyStatus==="allowed"||e.coolingReason==="session"&&t.sessionStatus==="allowed"||e.coolingReason==="unified"&&(t.unifiedStatus==="allowed"||s))&&e.coolingUntil){const u=e.coolingUntil,d=e.coolingReason;return e.coolingUntil=void 0,e.coolingReason=void 0,p.always(`[proxy] clearing ${d} cooldown from fresh provider quota`),{kind:"cleared",coolingUntil:u}}return null}const c=m3(i,r,a);return!e.coolingUntil||c>e.coolingUntil?(e.coolingUntil=c,e.coolingReason=a,p.always(`[proxy] proactively cooling account (${a}) ~${ide(c,r)}m from success-response quota (status rejected)`),{kind:"cooled",coolingUntil:c,coolingReason:a??"unified"}):null}async function g0n(e){try{const[t,r]=await Promise.all([Ile(),kx()]),n=Date.now();for(const o of e){const s=$a(o.key);s.quota||(s.quota=t[o.key]??t[o.label]);const i=r[o.key];i?.coolingUntil>n&&(!s.coolingUntil||i.coolingUntil>s.coolingUntil)&&(s.coolingUntil=i.coolingUntil,s.coolingReason=i.reason)}}catch{}}var y0n=15e3,_gr=new Map,h3=null,v0n=4;async function Cgr(e,t,r,n){if(t.ok===!1)return null;const o=$a(e.key),s=Bpr(t.usage,{now:r,prior:o.quota??n??null});if(!s)return null;if(s.lastUpdated<(o.quota?.lastUpdated??0))return o.quota??null;o.quota=fm(o.quota,s);const i=ade(o,s,Date.now());return i?.kind==="cooled"?await Vu(e.key,i.coolingUntil,i.coolingReason).catch(()=>{}):i?.kind==="cleared"&&await Yp(e.key,i.coolingUntil).catch(()=>{}),await Zp(e.key,s).catch(()=>{}),s}async function Agr(e){const t=await Imn(e);return t.ok===!1||Bpr(t.usage,{now:Date.now(),prior:pc.get(e.key)?.quota??null})?t:{ok:!1,reason:"parse",error:"usage payload had no recognizable limit windows"}}async function f3(e,t){const r=await Zx.run(e,t,Agr);r.kind!=="completed"||r.result.ok===!1||await Cgr(e,r.result,r.startedAt)}var tI=null;async function T0n(e){if(tI)return{anthropic:tI.anthropic,codex:tI.codex};const[t,r]=await Promise.all([$pr(e),Wmn()]);return{anthropic:t,codex:r}}async function w0n(){if(tI)return tI.knownKeys;const[e,t]=await Promise.all([gi.listByPrefix("anthropic:"),gi.listByPrefix("codex:")]);return new Set([...e.map(jp),...t])}async function cde(e={}){const t=Date.now(),r=await T0n(e.accountAllowlist),n=[...r.anthropic.map(u=>({account:u,provider:"anthropic"})),...r.codex.map(u=>({account:u,provider:"codex"}))],o=e.accountFilter?n.filter(({account:u})=>u.label===e.accountFilter||u.key===e.accountFilter):n,s=await Ile().catch(()=>({})),i=(u,d,m,h,f)=>{const g=pc.get(u.key),y=d==="anthropic"?s[u.key]??s[u.label]??null:s[u.key]??null,v={account:u.label,key:u.key,provider:d,type:u.type,status:m,quota:h??g?.quota??y};return f!==void 0&&(v.error=f),g?.coolingUntil&&g.coolingUntil>Date.now()&&(v.coolingUntil=g.coolingUntil,g.coolingReason&&(v.coolingReason=g.coolingReason)),v};if(e.snapshotOnly)return{fetchedAt:t,snapshot:!0,results:o.map(({account:u,provider:d})=>i(u,d,"snapshot",null)),refreshMetrics:Zx.getMetrics()};const a=new Array(o.length);let c=0;const l=async()=>{for(;;){const u=c++;if(u>=o.length)return;const{account:d,provider:m}=o[u];if(d.type!=="oauth"){a[u]=i(d,m,"skipped_api_key",null);continue}const h=_gr.get(d.key)??0;if(Date.now()-h<y0n){a[u]=i(d,m,"throttled",null);continue}if(_gr.set(d.key,Date.now()),m==="codex"){try{const f=await Kmn(d);if(f.ok===!1){a[u]=i(d,m,"error",null,`codex usage fetch failed: ${f.reason}`);continue}await Zp(d.key,f.quota),a[u]=i(d,m,"refreshed",f.quota)}catch(f){a[u]=i(d,m,"error",null,f instanceof Error?f.message:String(f))}continue}try{const f=await Zx.run(d,`manual:${d.key}`,Agr,{force:!0});if(f.kind!=="completed"){a[u]=i(d,m,"throttled",null);continue}const g=f.result;if(g.ok===!1){a[u]=i(d,m,"error",null,g.error);continue}const y=await Cgr(d,g,f.startedAt,s[d.key]??s[d.label]??null);if(!y){a[u]=i(d,m,"error",null,"usage payload had no recognizable limit windows");continue}a[u]=i(d,m,"refreshed",y)}catch(f){a[u]=i(d,m,"error",null,f instanceof Error?f.message:String(f))}}};return await Promise.all(Array.from({length:Math.min(v0n,o.length||1)},()=>l())),{fetchedAt:t,snapshot:!1,results:a,refreshMetrics:Zx.getMetrics()}}function lde(){const e=(process.env.NEUROLINK_PROXY_QUOTA_ROUTING??"").toLowerCase();return e!=="off"&&e!=="false"&&e!=="0"}function ude(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_SOFT_LIMIT??"");return Number.isFinite(e)&&e>0&&e<=1?e:.97}function rI(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS??"");return Number.isInteger(e)&&e>0?e:900*1e3}var rl="auto";function dde(e){e!==void 0&&(rl=e)}function E0n(){return rl}function oE(e,t=rl){return t==="never"?!1:Rpr(e)}var S0n=4;function g3(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function b0n(e){const t=g3(e);return t.startsWith("claude")?t.slice(6):t}function _0n(e,t,r){if(e.scopeModelId&&g3(R$(e.scopeModelId))===r)return Number.MAX_SAFE_INTEGER;if(!e.scopeModel)return null;const n=b0n(e.scopeModel);return n.length<S0n||!t.includes(n)?null:n.length}function mde(e,t){return t.updatedAt??e.windowsUpdatedAt??e.lastUpdated}function pde(e,t,r=Date.now()){if(!e?.windows?.length||!t)return null;const n=g3(t);if(!n)return null;const o=g3(R$(t));let s=null,i=-1,a=-1;for(const c of e.windows){if(r-mde(e,c)>Que)continue;const l=_0n(c,n,o);if(l===null)continue;const u=mde(e,c);(l>i||l===i&&u>a)&&(s=c,i=l,a=u)}return s}function C0n(e,t,r=Date.now(),n=rl){if(!t||e.length===0)return{eligible:e,exhaustion:null};const o=[],s=[];let i;for(const c of e){const l=pc.get(c.key)?.quota,u=pde(l,t,r),d=u?Fs(u.resetsAt,r):void 0;if(!(u!==null&&d!==void 0&&((u.status??"").trim().toLowerCase()==="rejected"||(u.used??0)>=1)&&!oE(l,n))||!u){o.push(c);continue}s.push({label:c.label,window:u}),i??=l?.overageDisabledReason}if(o.length>0||s.length===0)return{eligible:o,exhaustion:null};const a=Math.min(...s.map(c=>Fs(c.window.resetsAt,r)??Number.POSITIVE_INFINITY));return{eligible:o,exhaustion:{model:t,scopeModel:s[0]?.window.scopeModel??R$(t),earliestResetMs:a,accounts:s.map(c=>c.label),...i?{overageDisabledReason:i}:{}}}}function y3(e,t,r,n,o,s=rl){const i=pc.get(e),a=i?.quota,c=a&&Number.isFinite(a.lastUpdated)?a.lastUpdated:null,l=c===null?null:Math.max(0,t-c),u=Zx.getState(e),d=l!==null&&l>Que,m=X=>X.trim().toLowerCase(),h=Rpr(a),f=[a?.unifiedStatus,a?.sessionStatus,a?.weeklyStatus].filter(X=>!!X?.trim()),g=d&&!!a&&!h&&f.some(X=>m(X)!=="allowed"),y=a?d?g?"refresh_due":"stale_known":"fresh":"unknown",v=g?void 0:a,w=!!i?.coolingUntil&&t<i.coolingUntil,E=Fs(v?.weeklyResetAt,t),_=Fs(v?.sessionResetAt,t),C=_!==void 0,A=E!==void 0,k=v?C?v.sessionUsed??0:0:null,R=v?A?v.weeklyUsed??null:0:null,I=v?C?v.sessionStatus??"unknown":"allowed":null,P=v?A?v.weeklyStatus??"unknown":"allowed":null,O=oE(v,s),U=!O&&(I==="rejected"||I==="throttled"||P==="rejected"||P==="throttled"||v?.unifiedStatus?.trim().toLowerCase()==="rejected"||C&&(k??0)>=1||A&&(R??0)>=1),M=!U&&!O&&C&&(k??0)>=r,F=U||M,N=pde(v,o,t),L=N?Fs(N.resetsAt,t):void 0,q=L!==void 0,B=N?q?N.used:0:null,H=N?q?N.status??"unknown":"allowed":null,G=!d&&q&&(B??0)>=r;return{usable:!w&&!U&&(H!=="rejected"||O),saturated:F,scopedModel:N?.scopeModel??null,scopedStatus:H,scopedUsed:B,scopedReset:L??Number.POSITIVE_INFINITY,scopedUsedForSort:B??-1,scopedSaturated:G,hasQuota:!!a,quotaEvidenceRank:y==="fresh"||y==="stale_known"?0:y==="refresh_due"?1:2,quotaStale:d,quotaFreshness:y,refreshNeeded:y==="unknown"||y==="refresh_due",refreshReason:y==="unknown"?"startup_unknown":y==="refresh_due"?"ambiguous_snapshot":null,refreshInFlight:u.inFlight,lastRefreshAttemptAt:u.lastAttemptAt??null,lastRefreshSuccessAt:u.lastSuccessAt??null,nextRefreshEligibleAt:u.nextEligibleAt??null,saturationKind:U?"hard":M?"soft":"none",softLimitOverrideReason:O&&C&&(k??0)>=r?"overage":null,quotaLastUpdated:c,quotaAgeMs:l,coolingActive:w,coolingReason:i?.coolingReason??null,coolingUntil:i?.coolingUntil??0,unifiedStatus:v?.unifiedStatus??null,fallbackStatus:v?.fallbackStatus??null,upgradePaths:v?.upgradePaths??null,overageEligible:O,overageStatus:v?.overageStatus??null,sessionStatus:I,sessionUsed:k,sessionResetBucket:C?Math.floor(_/n):Number.POSITIVE_INFINITY,sessionReset:_??Number.POSITIVE_INFINITY,weeklyStatus:P,weeklyReset:E??Number.POSITIVE_INFINITY,weeklyUsed:R,weeklyUsedForSort:R??-1}}function kgr(e,t,r,n,o){return new Map(e.map(s=>[s.key,y3(s.key,t,r,n,o)]))}function A0n(e,t,r,n){for(const u of e){if(u.type!=="oauth")continue;const d=n?.get(u.key)??y3(u.key,Date.now(),r,rI());d.quotaFreshness==="unknown"?f3(u,`startup-unknown:${u.key}`).catch(m=>{p.debug(`[proxy] background quota discovery failed account=${u.label}: ${Ql(m)}`)}):d.quotaFreshness==="refresh_due"&&f3(u,`ambiguous:${d.quotaLastUpdated??0}`).catch(m=>{p.debug(`[proxy] ambiguous quota refresh failed account=${u.label}: ${Ql(m)}`)})}const o=t[0],s=t[1];if(!o||!s||s.type!=="oauth")return;const i=pc.get(o.key)?.quota;if(!i)return;const a=Math.max(0,r-.05);if(!((i.sessionUsed??0)>=a||(i.weeklyUsed??0)>=.9))return;const l=["handoff",o.key,i.sessionResetAt??0,i.weeklyResetAt??0,s.key].join(":");f3(s,l).catch(u=>{p.debug(`[proxy] quota handoff prewarm failed account=${s.label}: ${Ql(u)}`)})}function k0n(e,t,r,n){!t||t.type!=="oauth"||y3(t.key,Date.now(),n,rI()).quotaFreshness==="fresh"||f3(t,`hard-handoff:${e.key}:${r}:${t.key}`).catch(s=>{p.debug(`[proxy] hard-handoff quota refresh failed account=${t.label}: ${Ql(s)}`)})}function x0n(e){const{accounts:t,orderedAccounts:r,metricsByKey:n,evaluatedAt:o,strategy:s,primaryKey:i,quotaRoutingEnabled:a,quotaOrdered:c,sessionSoftLimit:l,sessionResetToleranceMs:u,rotationOffset:d}=e,m=new Map(t.map((w,E)=>[w.key,E])),h=!!i&&t.some(w=>w.key===i),f=[];for(const w of r){const E=n.get(w.key);if(!E){p.warn(`[proxy] routing evidence omitted because metrics are missing for account=${w.label}`);return}f.push({account:w.label,accountType:w.type,sourceIndex:m.get(w.key)??f.length,rank:f.length,configuredPrimary:!!i&&w.key===i,usable:E.usable,saturated:E.saturated,quotaObserved:E.hasQuota,quotaStale:E.quotaStale,quotaFreshness:E.quotaFreshness,refreshNeeded:E.refreshNeeded,refreshReason:E.refreshReason,refreshInFlight:E.refreshInFlight,lastRefreshAttemptAt:E.lastRefreshAttemptAt,lastRefreshSuccessAt:E.lastRefreshSuccessAt,nextRefreshEligibleAt:E.nextRefreshEligibleAt,saturationKind:E.saturationKind,softLimitOverrideReason:E.softLimitOverrideReason,quotaLastUpdated:E.quotaLastUpdated,quotaAgeMs:E.quotaAgeMs,coolingActive:E.coolingActive,coolingReason:E.coolingReason,coolingUntil:E.coolingUntil>0&&Number.isFinite(E.coolingUntil)?E.coolingUntil:null,unifiedStatus:E.unifiedStatus,fallbackStatus:E.fallbackStatus,upgradePaths:E.upgradePaths,overageEligible:E.overageEligible,overageStatus:E.overageStatus,sessionStatus:E.sessionStatus,sessionUsed:E.sessionUsed,sessionResetAt:Number.isFinite(E.sessionReset)?E.sessionReset:null,sessionResetBucket:Number.isFinite(E.sessionResetBucket)?E.sessionResetBucket:null,weeklyStatus:E.weeklyStatus,weeklyUsed:E.weeklyUsed,weeklyResetAt:Number.isFinite(E.weeklyReset)?E.weeklyReset:null,scopedModel:E.scopedModel,scopedStatus:E.scopedStatus,scopedUsed:E.scopedUsed,scopedResetAt:Number.isFinite(E.scopedReset)?E.scopedReset:null})}const g=r[0];let y,v;return r.length===1?(y="single_account",v="single_account"):c?(y="quota",v=e.policySelectionReason??Ypr(r[0],r[1],n,i)[1]):s==="round-robin"?(y="round_robin",v="round_robin"):(y="primary",v=e.policySelectionReason??(h&&g?.key===i?"configured_primary":"insertion_order")),{schemaVersion:1,evaluatedAt:new Date(o).toISOString(),strategy:s,mode:y,selectionReason:v,quotaRoutingEnabled:a,quotaInputsUsed:c,sessionSoftLimit:l,sessionResetToleranceMs:u,configuredPrimaryAccount:i??null,configuredPrimaryMatched:h,rotationOffset:d,initialAccount:g?.label??"",candidates:f,...e.policy?{policy:e.policy}:{},...e.affinity?{affinity:e.affinity}:{},...e.spill?{spill:e.spill}:{}}}var I0n=32,nI=new Set;function hde(e,t){const r=e instanceof Error?e.message:String(e),n=JSON.stringify([t,e instanceof Error?e.name:typeof e,r]);if(!nI.has(n)){if(nI.add(n),nI.size>I0n){const o=nI.values().next().value;o!==void 0&&nI.delete(o)}p.always(`[proxy] routing policy threw; falling back to ${t}: ${r}`)}}var R0n=!1,P0n=!1,M0n=!1;function O0n(e){const{enabledAccounts:t,accountStrategy:r,quotaRoutingEnabled:n,sessionSoftLimit:o,sessionResetToleranceMs:s,requestedModel:i,sessionId:a,ranking:c,preferPrimary:l,sessionAffinityEnabled:u,sessionAffinityIdleTtlMs:d,spillInflight:m,setRoutingDecision:h}=e,f=e.primaryAccountKey,g=f===void 0?void 0:t.find(N=>Xae(N.key,f))?.key??f;let y=[...t];const v=Date.now();let w,E=0;const _=r==="fill-first"&&y.length>1&&n,C=r==="fill-first"&&y.length>1,A=C?{ranking:c,preferPrimary:l,sessionAffinity:u,sessionAffinityIdleTtlMs:d,spillInflight:m}:void 0;let k,R,I;const P=()=>{if(!(!u||!a)){if(P0n)throw new Error("forced failure for affinity lookup throw test");return Ule.get(a,v,d)}},O=(N,L,q)=>({sessionBound:!!N,boundAccount:(N&&t.find(B=>B.key===N)?.label)??null,applied:L,skippedReason:u?a?N?L?null:q:"expired":"no_session":"disabled"}),U=N=>t.find(L=>L.key===N)?.label??N,M=(N,L,q)=>{if(R0n)throw new Error("forced failure for spill throw test");if(m<=0||L==="session_affinity")return;const B=new Map(N.map(X=>[X.key,r0n(X.key)])),H=tpn({orderedAccounts:N,inflightByKey:B,metricsByKey:q,spillInflight:m}),G=H.spill;if(G)return{orderedAccounts:H.orderedAccounts,spill:{from:U(G.from),to:U(G.to),inflight:G.inflight}}};if(!_&&r==="fill-first"&&l0n(t,g),_){w=kgr(t,v,o,s,i);try{const N=P(),L=Qpr({accounts:t,metricsByKey:w,primaryKey:g,ranking:c,affinityKey:N,preferPrimary:l}),q=M(L.orderedAccounts,L.reason,w),B=O(N,L.reason==="session_affinity",L.affinitySkippedReason);y=q?.orderedAccounts??L.orderedAccounts,k=q?"spill_inflight":L.reason,R=B,I=q?.spill}catch(N){hde(N,"expiry-first order"),y=Qpr({accounts:t,metricsByKey:w,primaryKey:g}).orderedAccounts,k="routing_policy_error"}p.shouldLog("debug")&&p.debug(`[proxy] quota-ordered fill sequence: ${y.map(N=>N.label).join(" \u2192 ")}`)}else{if(r==="round-robin"&&y.length!==cgr&&(oh=wgr(y,g),cgr=y.length),y.length>1&&(E=oh%y.length,r==="round-robin"&&(oh=(oh+1)%y.length),E>0)){const N=y.splice(0,E);y.push(...N)}if(w=kgr(t,v,o,s,i),C)try{const N=P(),L=Zpr({orderedAccounts:y,metricsByKey:w,affinityKey:N,primaryKey:g,preferPrimary:l}),q=M(L.orderedAccounts,L.reason,w),B=O(N,L.reason==="session_affinity",L.affinitySkippedReason);y=q?.orderedAccounts??L.orderedAccounts,k=q?"spill_inflight":L.reason??void 0,R=B,I=q?.spill}catch(N){hde(N,"pre-policy order"),k="routing_policy_error"}}const F=x0n({accounts:t,orderedAccounts:y,metricsByKey:w,evaluatedAt:v,strategy:r,primaryKey:g,quotaRoutingEnabled:n,quotaOrdered:_,sessionSoftLimit:o,sessionResetToleranceMs:s,rotationOffset:E,policySelectionReason:k,policy:A,affinity:R,spill:I});return F&&h(F),{orderedAccounts:y,metricsByKey:w}}function D0n(e){const t=Date.now();let r=e.servingAccountKey;try{if(M0n)throw new Error("forced failure for bind recheck throw test");const n=Ule.get(e.sessionId,t,e.idleTtlMs);n!==void 0&&!e.attemptedAccountKeys.has(n)&&e.enabledAccounts.some(o=>o.key===n)&&$le(y3(n,t,e.sessionSoftLimit,e.sessionResetToleranceMs,e.requestedModel))&&(r=n)}catch(n){hde(n,"serving-account binding")}Ule.bind(e.sessionId,r,t)}var v3=new Map,N0n=300*1e3,L0n=new Set(["accept","accept-encoding","accept-language","anthropic-beta","anthropic-dangerous-direct-browser-access","anthropic-version","sec-fetch-mode","user-agent","x-app","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout","x-subscription-tier"]),F0n=["oauth-2025-04-20","claude-code-20250219","fine-grained-tool-streaming-2025-05-14"];function T3(e){return e.replace(/[^a-zA-Z0-9._@-]/g,"_")}function xgr(e){return yt(wa(),".neurolink","header-snapshots",`anthropic_${T3(e)}.json`)}function $0n(e,t){if(t?.headers)for(const[r,n]of Object.entries(t.headers)){const o=r.toLowerCase();typeof n=="string"&&!e[o]&&!c3.has(o)&&o!=="authorization"&&o!=="x-api-key"&&o!=="x-claude-code-session-id"&&(e[o]=n)}}async function U0n(e){try{const t=T3(e),r=v3.get(t);if(r&&Date.now()-r.loadedAt<N0n)return r.snapshot;const n=xgr(e);try{await KM(n)}catch{return null}const o=JSON.parse(await Fr(n,"utf8"));if(!o||typeof o!="object")return null;const s={accountKey:"accountKey"in o&&typeof o.accountKey=="string"?o.accountKey:`anthropic:${e}`,capturedAt:"capturedAt"in o&&typeof o.capturedAt=="string"?o.capturedAt:new Date(0).toISOString(),source:"claude-code",headers:"headers"in o&&o.headers?o.headers:{},...o.body?{body:o.body}:{}};return Object.keys(s.headers).length===0&&Object.keys(s.body??{}).length===0?null:(v3.set(t,{snapshot:s,loadedAt:Date.now()}),s)}catch{return null}}function B0n(e,t){const r={...t??{}};for(const[n,o]of Object.entries(e)){const s=n.toLowerCase();typeof o=="string"&&L0n.has(s)&&!c3.has(s)&&s!=="authorization"&&s!=="x-api-key"&&s!=="x-claude-code-session-id"&&(r[s]=o)}return r}function Igr(e){if(!e||typeof e!="object")return;const t=e,r=nMt(t.metadata?.user_id),n=Array.isArray(t.system)?t.system:typeof t.system=="string"?[{type:"text",text:t.system}]:[],o=n.find(i=>typeof i?.text=="string"&&i.text.includes("x-anthropic-billing-header"))?.text,s=n.find(i=>typeof i?.text=="string"&&i.text.includes("Claude Agent SDK"))?.text;if(!(!r&&!o&&!s))return{...r?{metadataUserId:r.metadataUserId}:{},...r?{sessionId:r.sessionId}:{},...o?{billingHeader:o}:{},...s?{agentBlock:s}:{}}}function Rgr(e,t){return typeof e["x-claude-code-session-id"]=="string"||e["user-agent"]?.startsWith("claude-cli/")||!!t?.metadataUserId||!!t?.billingHeader||!!t?.agentBlock}function z0n(e,t){return e?JSON.stringify(e.headers??{})===JSON.stringify(t.headers??{})&&JSON.stringify(e.body??{})===JSON.stringify(t.body??{}):!1}async function q0n(e,t){const r=xgr(e);await Na(r,t,384),v3.set(T3(e),{snapshot:t,loadedAt:Date.now()})}async function G0n(e,t,r,n){const o=await U0n(e);let s;try{s=JSON.parse(n)}catch{return o}const i=Igr(s);if(!Rgr(r,i))return o;const a={accountKey:t,capturedAt:new Date().toISOString(),source:"claude-code",headers:B0n(r,o?.headers),body:{...o?.body??{},...i??{},...typeof r["x-claude-code-session-id"]=="string"?{sessionId:r["x-claude-code-session-id"]}:{}}};if(z0n(o,a))return o;try{await q0n(e,a)}catch(c){p.warn("[proxy] failed to persist Claude snapshot",{accountLabel:e,error:c instanceof Error?c.message:String(c)}),v3.set(T3(e),{snapshot:a,loadedAt:Date.now()})}return a}function fde(e){const t={};if(!e||typeof e!="object")return t;const r=e;if(typeof r.model=="string"&&(t.responseModel=r.model),typeof r.stop_reason=="string"&&(t.finishReason=r.stop_reason),typeof r.stop_sequence=="string"&&(t.stopSequence=r.stop_sequence),Array.isArray(r.content)){const n=r.content.filter(o=>!!o&&typeof o=="object"&&o.type==="tool_use").map(o=>String(o.name??"")).filter(o=>o.length>0);n.length>0&&(t.toolCalls=n)}return t}function Pgr(e){const t={};e.model&&(t.responseModel=e.model),e.stopReason&&(t.finishReason=e.stopReason),e.stopSequence&&(t.stopSequence=e.stopSequence);const r=(e.contentBlocks??[]).filter(n=>n.type==="tool_use").map(n=>String(n.toolName??"")).filter(n=>n.length>0);return r.length>0&&(t.toolCalls=r),t}function j0n(e,t,r,n,o){try{const s=JSON.parse(e),i={type:"text",text:r?.body?.agentBlock||"You are a Claude agent, built on Anthropic's Claude Agent SDK."};if(s.system){if(typeof s.system=="string"&&(s.system=[{type:"text",text:s.system}]),Array.isArray(s.system)){const l=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("x-anthropic-billing-header")),u=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("Claude Agent SDK")),d={type:"text",text:SN(s.system[l]?.text??r?.body?.billingHeader)};if(n&&u>=0)l<0&&s.system.unshift(d);else{const h=[l,u].filter(f=>f>=0).sort((f,g)=>g-f);for(const f of h)s.system.splice(f,1);s.system.length>0&&EMt(s,s.system),s.system=[d,i]}}}else{const l={type:"text",text:SN(r?.body?.billingHeader)};s.system=[l,i]}const a=t.substring(0,Math.min(20,t.length)),c=oMt(a,{existingUserId:s.metadata?.user_id??r?.body?.metadataUserId,preferredSessionId:o??r?.body?.sessionId});return s.metadata={...s.metadata,user_id:c.metadataUserId},{bodyStr:JSON.stringify(s),sessionId:c.sessionId}}catch{return{bodyStr:e}}}async function H0n(e,t){if(!e.oauth?.accessToken)return;let r=e.oauth.accessToken,n=e.oauth.refreshToken,o=e.oauth.expiresAt;const s=e.email?.trim()||"legacy-default",i=o?o<Date.now():!1,a=()=>({key:Qk,label:s,token:r,refreshToken:n,expiresAt:o,type:"oauth",persistTarget:{credPath:t}});if(!i)return a();const c=$a(Qk);if(c.permanentlyDisabled)return;const l=(await kx())[Qk];if(l?.coolingUntil>Date.now()&&(!c.coolingUntil||l.coolingUntil>c.coolingUntil)&&(c.coolingUntil=l.coolingUntil,c.coolingReason=l.reason),c.coolingReason==="auth"&&c.coolingUntil&&c.coolingUntil>Date.now())return a();if(!n){p.always("[proxy] skipping legacy account (expired, no refresh token)"),await wm(a(),c,"missing_refresh_token");return}const u={token:r,refreshToken:n,expiresAt:o,label:s},d=await Lpr(u);if(!d.success){if(sy(d)){await wm(a(),c,"refresh_invalid");return}const m=await b3(a(),c);return p.always(`[proxy] legacy refresh temporarily unavailable (${d.status??"network"}); cooling until ${new Date(m).toISOString()}`),a()}return r=u.token,n=u.refreshToken,o=u.expiresAt,await N$(t,u),await _3(a(),c),p.always("[proxy] refreshed legacy account at startup"),a()}async function V0n(e){const{ctx:t,body:r,route:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a}=e;s?.setMode("full");const c=L$(r),l=tE({provider:n.provider,model:n.model},o?.getFallbackChain()??[],r.model,c,o?.isAutoFallbackEnabled?.()??!1);Mgr(a,"translated_request",l);const u=l.attempts;if(r.stream)return r3({ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:u,tracer:s,requestStartTime:i});try{return await n3({ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:u,tracer:s,requestStartTime:i,terminalFailureStatus:502})}catch(d){const m=d instanceof Error?d.message:"unknown error";p.error(`[claude-proxy] Translated generation failed for ${r.model}: ${m}`);const h=$i(502,`Generation failed: ${m}`),f=JSON.stringify(h);return a({phase:"client_response",headers:{"content-type":"application/json"},body:f,bodySize:Buffer.byteLength(f,"utf8"),contentType:"application/json",account:"translation",accountType:"translation",responseStatus:502,durationMs:Date.now()-i}),h}}function Mgr(e,t,r){e({phase:"routing_decision",contentType:"application/json",body:{stage:t,attempts:r.attempts}})}async function W0n(e){const{ctx:t,body:r,clientRequestBody:n,tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:a}=e;o?.setMode("passthrough-cli");const{bodyStr:c,preparedContext:l}=hgr(t,n),u=Array.isArray(r.tools)?r.tools.length:0,d={};for(const[g,y]of Object.entries(t.headers))!c3.has(g.toLowerCase())&&y&&(d[g]=y);d["content-type"]||(d["content-type"]="application/json");const m=o?.startUpstreamAttempt({account:"passthrough",attempt:1,polyfillHeaders:!1,polyfillBody:!1,upstreamUrl:"https://api.anthropic.com/v1/messages?beta=true"});let h;try{h=await Zue("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:d,body:c,signal:AbortSignal.any([...t.abortSignal?[t.abortSignal]:[],AbortSignal.timeout(Xx)])},t,"anthropic:passthrough",{logProxyBody:i,tracer:o,attemptNumber:1,accountLabel:"passthrough",accountType:"passthrough",preparedContext:l})}catch(g){if(g instanceof _r||el(g)||t.abortSignal?.aborted)throw m?.end(),g;const y=g instanceof Error?g.message:String(g);Pr("passthrough","passthrough",502),o?.setError("network_error",y),m?.end(),o?.end(502,Date.now()-s),a(502,"passthrough","passthrough","network_error",y);const v=$i(502,`Passthrough fetch failed: ${y}`),w=JSON.stringify(v);return i({phase:"client_response",headers:{"content-type":"application/json"},body:w,bodySize:Buffer.byteLength(w,"utf8"),contentType:"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:502,durationMs:Date.now()-s}),v}const f={};h.headers.forEach((g,y)=>{f[y]=g}),o?.logUpstreamResponseHeaders(f);{const g=Mw(h.headers,{model:r.model});eI(t,{upstreamHeaders:h.headers,quota:g,source:g?"live":"none",accountType:"passthrough",servedBy:"anthropic",attempt:1})}if(!h.ok){const g=await h.text();Pr("passthrough","passthrough",h.status,h.status===429?"quota":void 0),o?.logUpstreamResponseBody(g),i({phase:"upstream_response",headers:f,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:f["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:h.status,durationMs:Date.now()-s}),i({phase:"client_response",headers:f,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:f["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:h.status,durationMs:Date.now()-s}),m?.end(),o?.setError("api_error",g.slice(0,500)),o?.end(h.status,Date.now()-s),a(h.status,"passthrough","passthrough",h.status===429?"rate_limit_error":"api_error",g);try{return JSON.parse(g)}catch{return $i(h.status,g)}}return r.stream&&h.body?J0n({ctx:t,body:r,bodyStr:c,response:h,tracer:o,requestStartTime:s,toolCount:u,upstreamSpan:m,upstreamResponseHeaders:f,logProxyBody:i,logFinalRequest:a}):Y0n({ctx:t,body:r,bodyStr:c,response:h,tracer:o,requestStartTime:s,toolCount:u,upstreamSpan:m,upstreamResponseHeaders:f,logProxyBody:i,logFinalRequest:a})}function K0n(e){const t=e.getReader(),r=Xfr();let n=!1;return{stream:new ReadableStream({async pull(s){if(!n)try{const{done:i,value:a}=await t.read();if(n)return;if(i){n=!0,r.complete(),s.close();return}s.enqueue(a)}catch(i){n=!0;const a=i instanceof Error?i.message:String(i);r.fail(a),s.error(i)}},cancel(s){return n=!0,r.cancel(),t.cancel(s)}}),outcome:r.outcome}}async function J0n(e){const{ctx:t,bodyStr:r,response:n,tracer:o,requestStartTime:s,upstreamSpan:i,upstreamResponseHeaders:a,logProxyBody:c,logFinalRequest:l}=e,u={...a},{stream:d,capture:m}=Pue(),h=n.body;if(!h)throw Pr("passthrough","passthrough",502),new Error("Expected passthrough stream response body");const f=K0n(h);let g=f.stream,y=!1,v;const w=(_,C,A,k)=>y?!1:(y=!0,C==="stream_error"&&Pr("passthrough","passthrough",_),l(_,"passthrough","passthrough",C,A,k),!0);if(o)try{const{stream:_,telemetry:C}=U$({captureRawText:!0});g=g.pipeThrough(_);const A=o,k=i,R=n,I=r.length;v=Promise.all([C,m,f.outcome]).then(([P,O,U])=>{const M=i3(U,P.streamErrorMessage,P.messageStopReceived);x$(t.metadata,P);const F=sh(M);A.setUsage({inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),A.logStreamEvents(P.events),A.setResponseInfo(Pgr(P));const N=parseFloat(R.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),L=parseFloat(R.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),q={inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens};isNaN(N)||(q.rateLimitAfter5h=N),isNaN(L)||(q.rateLimitAfter7d=L),(!isNaN(N)||!isNaN(L))&&A.setUsage(q),A.logUpstreamResponseBody(P.rawText??""),A.recordMetrics(),A.recordBodySizes(I,P.totalBytesReceived),k?.end(),F&&A.setError(F.errorType,F.message),A.end(F?.status??n.status,Date.now()-s),w(F?.status??n.status,F?.errorType,F?.message,{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),c({phase:"upstream_response",headers:u,body:P.rawText??"",sourceTruncated:P.rawTextTruncated,bodySize:P.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s}),c({phase:"client_response",headers:u,body:O.text,sourceTruncated:O.truncated,bodySize:O.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s})}).catch(P=>{if(y)return;const O=P instanceof Error?P.message:String(P);A.setError("stream_telemetry_error",O),k?.end(),A.end(500,Date.now()-s),w(500,"stream_telemetry_error",O)})}catch{v=f.outcome.then(_=>{const C=sh(_);i?.end(),C&&o.setError(C.errorType,C.message),o.end(C?.status??n.status,Date.now()-s),w(C?.status??n.status,C?.errorType,C?.message)})}else try{const{stream:_,telemetry:C}=U$({captureRawText:!0});g=g.pipeThrough(_),v=Promise.all([C,m,f.outcome]).then(([A,k,R])=>{const I=i3(R,A.streamErrorMessage,A.messageStopReceived);x$(t.metadata,A);const P=sh(I);w(P?.status??n.status,P?.errorType,P?.message,{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens}),c({phase:"upstream_response",headers:u,body:A.rawText??"",sourceTruncated:A.rawTextTruncated,bodySize:A.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s}),c({phase:"client_response",headers:u,body:k.text,sourceTruncated:k.truncated,bodySize:k.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s})}).catch(A=>{y||w(500,"stream_telemetry_error",A instanceof Error?A.message:String(A))})}catch{v=f.outcome.then(_=>{const C=sh(_);w(C?.status??n.status,C?.errorType,C?.message)})}const E=g.pipeThrough(d);return $w(t.metadata,{onTerminal:()=>v}),new Response(E,{status:n.status,headers:{...u,...t.responseHeaders??{}}})}async function Y0n(e){const{ctx:t,bodyStr:r,response:n,tracer:o,requestStartTime:s,upstreamSpan:i,upstreamResponseHeaders:a,logProxyBody:c,logFinalRequest:l}=e,u=await n.text();o?.logUpstreamResponseBody(u),c({phase:"upstream_response",headers:a,body:u,bodySize:Buffer.byteLength(u,"utf8"),contentType:a["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s}),c({phase:"client_response",headers:a,body:u,bodySize:Buffer.byteLength(u,"utf8"),contentType:a["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s});const d=JSON.parse(u);if(k$(t.metadata,d),o&&d&&typeof d=="object"){const m=d.usage;if(m){o.setUsage({inputTokens:m.input_tokens??0,outputTokens:m.output_tokens??0,cacheCreationTokens:m.cache_creation_input_tokens??0,cacheReadTokens:m.cache_read_input_tokens??0});const f=parseFloat(n.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),g=parseFloat(n.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(f)||!isNaN(g)){const y={inputTokens:m.input_tokens??0,outputTokens:m.output_tokens??0,cacheCreationTokens:m.cache_creation_input_tokens??0,cacheReadTokens:m.cache_read_input_tokens??0};isNaN(f)||(y.rateLimitAfter5h=f),isNaN(g)||(y.rateLimitAfter7d=g),o.setUsage(y)}}o.setResponseInfo(fde(d)),o.recordMetrics();const h=JSON.stringify(d);o.recordBodySizes(r.length,h.length),i?.end(),o.end(n.status,Date.now()-s),l(n.status,"passthrough","passthrough",void 0,void 0,{inputTokens:m?.input_tokens,outputTokens:m?.output_tokens,cacheCreationTokens:m?.cache_creation_input_tokens,cacheReadTokens:m?.cache_read_input_tokens})}else i?.end(),o?.end(n.status,Date.now()-s),l(n.status,"passthrough","passthrough");return d}async function X0n(e){const t=Hw();if(!t)return{accounts:e.accounts};if(e.accounts.length===0)return{accounts:e.accounts};const r=Date.now(),n=await Promise.all(e.accounts.map(async d=>{const m=$a(d.key).quota,h=Fs(m?.sessionResetAt,r)??null,f=Fs(m?.weeklyResetAt,r)??null,g=await vce(t.grantId,d.key,h,f);return{accountKey:d.key,sessionUsed:m?.sessionUsed??null,weeklyUsed:m?.weeklyUsed??null,sessionResetAt:h,weeklyResetAt:f,borrowedSessionFraction:g.sessionFraction,borrowedWeeklyFraction:g.weeklyFraction}})),o=await mce(t.grantId);if(!o)return{accounts:e.accounts};const s=await Tce(t.grantId,Fue(o.gates,n).inScope),i=$ue(o,n,r,s),a=new Set(i.allowed),c=e.accounts.filter(d=>a.has(d.key));if(c.length>0)return{accounts:c};const l=Uue(i.excluded),u=Xw(l,{status:Jgn(l),grant:o,retryAfterSeconds:Dgr(n,r)});return p.always(`[proxy] share ${t.peerLabel} withheld: ${l} (${i.excluded.length} accounts)`),{accounts:[],refusal:{status:u.status,message:u.body.error.message,errorType:u.body.error.type,responseHeaders:u.headers}}}async function Z0n(e){const t=[],r=[];for(const n of e){const o=await $gn(n.key);if(!o){t.push(n);continue}if(!kgn(o)){t.push(n);continue}p.always(`[proxy] withholding leased account=${n.label}: ${o.reason}`),r.push({label:n.label,reason:o.reason})}return{accounts:t,withheld:r}}async function Q0n(e,t){const r=[],n=[],o=Date.now();for(const s of e){const i=await Lue(s.key);if(!i){r.push(s);continue}const a=i.lease.gates;if(!Xgn(a.models,t)){p.always(`[proxy] leased account=${s.label} does not cover model ${lr(t??"unknown")}`),n.push({label:s.label,reason:"model_not_allowed"});continue}if(a.schedule&&!Ygn(a.schedule,o)){p.always(`[proxy] leased account=${s.label} is outside its allowed hours`),n.push({label:s.label,reason:"out_of_window"});continue}const c=$a(s.key).quota,l=Fs(c?.sessionResetAt,o)??null,u=Fs(c?.weeklyResetAt,o)??null,d=await vce(i.grantId,s.key,l,u),m={accountKey:s.key,sessionUsed:c?.sessionUsed??null,weeklyUsed:c?.weeklyUsed??null,sessionResetAt:l,weeklyResetAt:u,borrowedSessionFraction:d.sessionFraction,borrowedWeeklyFraction:d.weeklyFraction},h=await Tce(i.grantId,[m]),{accounts:f,...g}=a,y=$ue(evn(i,g),[m],o,h);if(y.allowed.length===0){const v=Uue(y.excluded);p.always(`[proxy] withholding leased account=${s.label}: ${v}`),n.push({label:s.label,reason:v});continue}r.push(s)}return{accounts:r,withheld:n}}function evn(e,t){const r=e.lease.entitlementSnapshot;return{schemaVersion:1,id:e.grantId,peerLabel:e.lease.peerLabel,tokenHash:"",tokenSalt:"",level:"complete",state:"active",entitlement:r==="unlimited"?{ledger:"unlimited"}:{ledger:"coins",coins:r},gates:t,createdAt:e.lease.issuedAt,updatedAt:e.lease.issuedAt}}function tvn(e,t,r){const n=Date.now(),o=i=>{fan({grantId:i,accountKey:e,sessionBefore:t?.sessionUsed??null,sessionAfter:r.sessionUsed,sessionResetAt:Fs(r.sessionResetAt,n)??null,weeklyBefore:t?.weeklyUsed??null,weeklyAfter:r.weeklyUsed,weeklyResetAt:Fs(r.weeklyResetAt,n)??null})},s=Hw();if(s){o(s.grantId);return}Lue(e).then(i=>{i&&o(i.grantId)}).catch(()=>{})}function gde(e,t,r){const n=yce({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},t);Ugn(e,n).catch(()=>{})}function Ogr(e,t){if(!t||typeof t!="object")return;const r=t.usage;if(!r)return;const n=cvn(t),o={inputTokens:r.input_tokens??0,outputTokens:r.output_tokens??0,cacheCreationTokens:r.cache_creation_input_tokens??0,cacheReadTokens:r.cache_read_input_tokens??0};yde(e.key,n,o),gde(e.label,n,o)}function yde(e,t,r){const n=Hw();n&&gan({grantId:n.grantId,accountKey:e,model:t??n.model,usage:{inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},...n.holdId?{holdId:n.holdId}:{}})}function vde(e){if(!Hw())return e;const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();o==="x-neurolink-account"||o==="x-neurolink-account-type"||o.startsWith("x-neurolink-pool-")||(t[r]=n)}return t}async function rvn(e,t){const r=e.provisionedAccount;if(!r)return{paused:!1,detail:"no provisioned account recorded"};const n=pc.get(`anthropic:${r}`),o=dar(r,"oauth"),{verdict:s,shouldPause:i}=await gyn({grantId:e.id,accountLabel:r,lenderRequestsTotal:o?.successCount??0,observation:{at:Date.now(),sessionUsed:n?.quota?.sessionUsed??null,weeklyUsed:n?.quota?.weeklyUsed??null,reportedCoins:t,lenderRequests:0}});return i?(await ean(e.id,"paused"),{paused:!0,detail:s.drifted?s.detail:"repeated unexplained usage"}):{paused:!1,detail:s.drifted?s.detail:"consistent"}}async function nvn(e,t){await _ar(e.id,t)}function ovn(e,t){if(e.length!==t.length||e.length===0)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var svn=1,ivn=["live","complete","handshake","limits"];async function avn(e,t){const r=Date.now(),n=await $pr(t),o=await Promise.all(n.map(async l=>{const u=$a(l.key).quota,d=Fs(u?.sessionResetAt,r)??null,m=Fs(u?.weeklyResetAt,r)??null,h=await vce(e.id,l.key,d,m);return{accountKey:l.key,sessionUsed:u?.sessionUsed??null,weeklyUsed:u?.weeklyUsed??null,sessionResetAt:d,weeklyResetAt:m,borrowedSessionFraction:h.sessionFraction,borrowedWeeklyFraction:h.weeklyFraction}})),s=Fue(e.gates,o).inScope,i=await Tce(e.id,s),a=$ue(e,o,r,i),c=(l,u)=>l===void 0?null:Math.max(0,l-u*100);return{grantState:e.state,level:e.level,ledger:e.entitlement.ledger,...e.entitlement.ledger==="coins"?{remainingCoins:Math.max(0,Math.floor(man(e)))}:{},servable:a.allowed.length>0,...a.allowed.length===0&&a.excluded.length>0?{withheldReason:Uue(a.excluded)}:{},sliceLeftPct:{session:c(e.gates.maxSlice?.session5hPct,i.sessionFraction),weekly:c(e.gates.maxSlice?.weekly7dPct,i.weeklyFraction)},...a.allowed.length===0?(()=>{const l=Dgr(o,r);return l===void 0?{}:{retryAfterSeconds:l}})():{}}}function py(e){return!e.ok}async function hy(e){const t=nyn(e);if(!t)return{ok:!1,body:Xw("missing_token",{status:401}).body};const r=await ran(t);return r?{ok:!0,grant:r}:{ok:!1,body:Xw("unknown_token",{status:401}).body}}function cvn(e){if(!e||typeof e!="object")return;const t=e.model;return typeof t=="string"?t:void 0}function Dgr(e,t){const r=e.flatMap(n=>[n.sessionResetAt,n.weeklyResetAt]).filter(n=>n!==null&&n>t);if(r.length!==0)return Math.max(1,Math.round((Math.min(...r)-t)/1e3))}async function lvn(e){const{ctx:t,body:r,accountStrategy:n,primaryAccountKey:o,accountAllowlist:s,quotaRoutingEnabled:i=lde(),sessionSoftLimit:a=ude(),sessionResetToleranceMs:c=rI(),ranking:l="expiry-first",preferPrimary:u=!1,sessionAffinityEnabled:d=!1,sessionAffinityIdleTtlMs:m=36e5,spillInflight:h=0,setRoutingDecision:f}=e,g=await Promise.resolve().then(()=>(on(),mu)),y=await Promise.resolve().then(()=>(Ri(),cW)),v=[],w=`${y.homedir()}/.neurolink/anthropic-credentials.json`,{tokenStore:E}=await Promise.resolve().then(()=>(Xg(),ece)),_=await kx();Tgr||(rde??=E.pruneExpired().then(()=>{Tgr=!0}).finally(()=>{rde=void 0}),await rde);const C=await E.getProviderSnapshot(),A=Object.keys(C).filter(le=>le.startsWith("anthropic:")),k=[];let R=0,I=0;for(const le of A){if(!Zae(le,s)){p.debug(`[proxy] skipping account=${le} (not in account allowlist)`);continue}if(C[le].disabled){const xe=$a(le),ve=C[le].disabledReason;if(ve==="refresh_failed")await E.markEnabled(le),p.always(`[proxy] account=${le.split(":")[1]??le} re-enabled for legacy refresh failure recheck`),xe.permanentlyDisabled=!1,xe.consecutiveRefreshFailures=0;else{const V=le.split(":")[1]??le;if(xe.permanentlyDisabled)p.debug(`[proxy] skipping disabled account=${V}`);else{const se=C[le].disabledAt;p.always(`[proxy] account=${V} is disabled in the token store (reason=${ve??"unknown"}${se?`, since ${new Date(se).toISOString()}`:""}); left out of the pool. Re-enable with: neurolink auth enable ${le}`)}xe.permanentlyDisabled=!0,ve==="entitlement_blocked"&&k.push(le.split(":")[1]??le),R+=1;continue}}const ae=C[le].tokens;if(!ae){I+=1;continue}let Pe=ae.accessToken,Ae=ae.refreshToken,Te=ae.expiresAt;const he=le.split(":")[1]??le,Oe=ae.tokenType==="Bearer"?"oauth":"api_key",De=$a(le),Ye=_[le];Ye?.coolingUntil>Date.now()&&(!De.coolingUntil||Ye.coolingUntil>De.coolingUntil)&&(De.coolingUntil=Ye.coolingUntil,De.coolingReason=Ye.reason);const gt=()=>{v.push({key:le,label:he,token:Pe,refreshToken:Ae,expiresAt:Te,type:Oe,persistTarget:{providerKey:le}})};if(Te?Te<Date.now():!1){if(De.permanentlyDisabled)continue;if(De.coolingReason==="auth"&&De.coolingUntil&&De.coolingUntil>Date.now()){gt();continue}if(!Ae){p.always(`[proxy] skipping account=${he} (expired, no refresh token)`),await wm({key:le,label:he,token:Pe,type:"oauth"},De,"missing_refresh_token");continue}const xe={token:Pe,refreshToken:Ae,expiresAt:Te,label:he},ve=await D$(xe,{providerKey:le});if(!ve.success){const J={key:le,label:he,token:Pe,type:"oauth"};if(sy(ve))p.always(`[proxy] skipping account=${he} (refresh token rejected: ${ve.error?.slice(0,200)??"unknown"})`),await wm(J,De,"refresh_invalid");else{const V=await b3(J,De);p.always(`[proxy] account=${he} refresh temporarily unavailable (${ve.status??"network"}); cooling until ${new Date(V).toISOString()} and rotating`),gt()}continue}Pe=xe.token,Ae=xe.refreshToken,Te=xe.expiresAt,await E.saveTokens(le,{accessToken:Pe,refreshToken:Ae,expiresAt:Te??Date.now()+36e5,tokenType:"Bearer"}),p.always(`[proxy] refreshed expired account=${le.split(":")[1]??le} at startup`),await _3({key:le},De)}gt()}if(v.length===0&&ear(A.length,Qk,s))try{const le=JSON.parse(g.readFileSync(w,"utf8")),ae=await H0n(le,w);ae&&v.push(ae)}catch{}if(process.env.ANTHROPIC_API_KEY&&v.length===0&&ear(A.length,Qae,s)&&v.push({key:Qae,label:"env",token:process.env.ANTHROPIC_API_KEY,type:"api_key"}),v.length===0)return k.length>0&&k.length===R&&I===0?{failure:{status:403,message:Ugr({status:403,accounts:k,message:"OAuth authentication is not allowed for this organization.",errorCode:"oauth_not_allowed_for_organization"}),errorType:"permission_error"}}:{failure:{status:401,message:s?"No allowed Anthropic credentials are currently available":A.length>0?"Configured Anthropic accounts are disabled or unavailable":"No Anthropic credentials found",errorType:"authentication_error"}};for(const le of v)Dvn(le);await g0n(v);const P=v.filter(le=>!$a(le.key).permanentlyDisabled),O=await Z0n(P),U=await Q0n(O.accounts,typeof r.model=="string"?r.model:void 0),M={accounts:U.accounts,withheld:[...O.withheld,...U.withheld]},F=M.accounts;if(F.length===0&&M.withheld.length>0){const le=M.withheld.map(Ae=>`${Ae.label} (${Ae.reason})`).join(", ");return{failure:{status:403,message:M.withheld.every(Ae=>Ae.reason==="model_not_allowed")?`Borrowed account(s) do not cover the requested model: ${le}. Ask the lender to widen the share, or use a model it allows.`:`Borrowed account(s) are no longer covered by a lease: ${le}. Run 'neurolink proxy peer sync' to check in with the lender, or ask them to resume the share.`,errorType:"permission_error"}}}const N=await X0n({accounts:F});if(N.refusal)return{failure:N.refusal};const L=N.accounts;if(L.length===0)return{failure:{status:401,message:C3(v.map(ae=>ae.label)),errorType:"authentication_error"}};const q=t.headers??{},B=Igr(r),{orderedAccounts:H,metricsByKey:G}=O0n({enabledAccounts:L,accountStrategy:n,primaryAccountKey:o,quotaRoutingEnabled:i,sessionSoftLimit:a,sessionResetToleranceMs:c,requestedModel:typeof r.model=="string"?r.model:void 0,sessionId:B?.sessionId,ranking:l,preferPrimary:u,sessionAffinityEnabled:d,sessionAffinityIdleTtlMs:m,spillInflight:h,setRoutingDecision:f});n==="fill-first"&&i&&L.length>1&&A0n(L,H,a,G);const X=Bvn(r),ce=JSON.stringify(X),Q=Date.now(),Ie=Array.isArray(r.tools)?r.tools.length:0;return{accounts:v,enabledAccounts:L,orderedAccounts:H,bodyStr:ce,requestStart:Q,toolCount:Ie,url:"https://api.anthropic.com/v1/messages?beta=true",clientHeaders:q,isClaudeClientRequest:Rgr(q,B),sessionId:B?.sessionId}}function uvn(e,t){const r=t==="vertex"?e.vertexFallbackModel:e.codexFallbackModel;return typeof r=="string"&&r.length>0?r:void 0}function w3(e){for(const t of["codexFallbackAccount","codexFallbackAccountType","codexFallbackModel","vertexFallbackModel","codexFallbackFailureUsage","codexFallbackDeferredFailure","sdkFallbackFailure"])delete e.metadata[t]}async function dvn(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,options:s,providerLabel:i,idleTimeoutMs:a=Yyn}=e;w3(t);const c=L$(r),l=typeof s.provider=="string"?s.provider:void 0,u=typeof s.model=="string"?s.model:void 0,d={ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:[{provider:l,model:u,label:i}],tracer:n,requestStartTime:o,options:s,attemptTimeoutMs:a};return r.stream?r3({...d,prefetchFirstOutput:!0}):n3({...d,deferFinalOnError:!0})}async function Ngr(e){let t;for(let r=0;r<=Yue;r+=1)try{return await dvn(e)}catch(n){if(t=n,iy(n)?.retryable===!1||!bde(n)||r===Yue)throw n;const o=Jue[r]??250;p.always(`[proxy] retrying fallback=${e.providerLabel} after transient network error (${r+1}/${Yue}) in ${o}ms: ${sE(Ql(n))}`),await Zl(o)}throw t}async function mvn(e){const{ctx:t,body:r,model:n,reasoningEffort:o,tracer:s,requestStartTime:i,logProxyBody:a,logFinalRequest:c}=e;w3(t);const l={...t,requestId:`${t.requestId}:codex-fallback`,method:"POST",path:"/backend-api/codex/responses",headers:{...t.headers,"content-type":"application/json",accept:"text/event-stream"},query:{},params:{},body:Dpn(r,n,o),metadata:{...t.metadata,"neurolink.codexFallback":!0},responseHeaders:{}},u=await ogr(l),d=bhn(l.metadata);let m=()=>{};const h=new Promise(k=>{m=k}),f=Chn(u,m,{onTerminal:k=>Promise.allSettled(d.map(async R=>R.onTerminal?.(k)))});$w(t.metadata,{onTerminal:()=>h});const g=(k,R=!0)=>{if(t.metadata.codexFallbackModel=n,!!R)try{s?.setModelSubstitution(r.model,n,"openai"),s?.setServedAccount(y["x-neurolink-account"]??"unknown","codex-oauth"),k?.usage?.inputTokensObserved&&k.usage.outputTokensObserved&&s?.setUsage({inputTokens:k.usage.input,outputTokens:k.usage.output,cacheReadTokens:k.usage.cacheReadTokens??0,cacheCreationTokens:k.usage.cacheCreationTokens??0,cacheReadTokensObserved:k.usage.cacheReadTokensObserved===!0,cacheCreationTokensObserved:k.usage.cacheCreationTokensObserved===!0,reasoningTokens:k.usage.reasoning},{recordMetrics:!1})}catch{}},y={...l.responseHeaders??{}};if(t.metadata.codexFallbackAccount=y["x-neurolink-account"],t.metadata.codexFallbackAccountType=y["x-neurolink-account-type"]??"codex-oauth",r.stream){const k=await Upn(f,r.model);t.responseHeaders??={},Object.assign(t.responseHeaders,vde(y));const R=y["x-neurolink-account"]??"",I=y["x-neurolink-account-type"]??"codex-oauth";let P=!1,O="",U=0,M=!1;const F=(B,H,G,X,ce)=>{P||(P=!0,t.abortSignal?.removeEventListener("abort",N),B>=400&&(t.metadata.terminalErrorType=G),g(H),s?.end(B,Date.now()-i),c(B,R,I,G,X,{inputTokens:H?.usage?.inputTokensObserved?H.usage.input:void 0,outputTokens:H?.usage?.outputTokensObserved?H.usage.output:void 0,cacheCreationTokens:H?.usage?.cacheCreationTokensObserved?H.usage.cacheCreationTokens:void 0,cacheReadTokens:H?.usage?.cacheReadTokensObserved?H.usage.cacheReadTokens:void 0,cacheReadTokensObserved:H?.usage?.cacheReadTokensObserved===!0,cacheCreationTokensObserved:H?.usage?.cacheCreationTokensObserved===!0,reasoningTokens:H?.usage?.reasoning,errorCode:ce?.code,retryable:ce?.retryable}),Yw({provider:"codex",model:n,status:B<400?"success":"failure",durationMs:Date.now()-i,...X?{errorMessage:X}:{}}),a({phase:"client_response",contentType:"text/event-stream",body:O,bodySize:U,sourceTruncated:M,responseStatus:B,durationMs:Date.now()-i}))},N=()=>{F(499,void 0,"client_cancelled","Client cancelled Codex fallback stream"),k.cancel()};t.abortSignal?.addEventListener("abort",N,{once:!0}),$w(t.metadata,{onTerminal:({outcome:B})=>{B==="client_cancelled"?N():B==="stream_error"&&(F(502,void 0,"stream_error","Codex fallback stream failed"),k.cancel())}});const L=B=>(U+=Buffer.byteLength(B),O.length+B.length>1024*1024&&(M=!0),O.length<1024*1024&&(O+=B.slice(0,1024*1024-O.length)),B);async function*q(){try{if(t.abortSignal?.aborted){N();return}let B=k.frames.next();for(;!P;){let H;const G=new Promise(Q=>{H=setTimeout(()=>Q(null),15e3),H.unref()});let X;try{X=await Promise.race([B,G])}finally{clearTimeout(H)}if(P)return;if(X===null){yield L(qle.pingEvent());continue}if(X.done===!0){F(200,X.value);return}const ce=L(X.value);if(ce.startsWith(`event: content_block_delta
|
|
2359
|
+
`,{status:200,headers:n})}async function egr(){const[e,t,r]=await Promise.all([gi.getProviderSnapshot(),kx(),Ile()]),n=Date.now(),o=[];for(const[s,i]of Object.entries(e)){if(!s.startsWith(Qp)||i.disabled)continue;const a=i.tokens;if(!a||a.tokenType!=="Bearer")continue;let c=a.accessToken,l=a.expiresAt;if(jmn(l)&&a.refreshToken)try{const m=await Vue(s,a.refreshToken);c=m.accessToken,l=m.expiresAt??l}catch(m){p.debug(`Codex proactive refresh failed for ${s.slice(Qp.length)}: ${m instanceof Error?m.message:String(m)}`)}const u=t[s],d=u&&u.coolingUntil>n;o.push({key:s,label:s.slice(Qp.length)||s,token:c,refreshToken:a.refreshToken,expiresAt:l,accountId:Rx(c),quota:r[s],coolingUntil:d?u.coolingUntil:void 0,coolingReason:u?.reason,expiredCooldownUntil:u&&!d?u.coolingUntil:void 0})}return o}function tgr(e,t){return[...e].sort((r,n)=>{const o=r.coolingUntil!==void 0&&r.coolingUntil>t,s=n.coolingUntil!==void 0&&n.coolingUntil>t;if(o!==s)return o?1:-1;const i=r.quota?.unifiedStatus==="rejected",a=n.quota?.unifiedStatus==="rejected";if(i!==a)return i?1:-1;const c=r.quota&&r.quota.sessionStatus!=="unknown"?r.quota.sessionUsed:-1,l=n.quota&&n.quota.sessionStatus!=="unknown"?n.quota.sessionUsed:-1;return c-l})}function rgr(e,t){const r={};for(const[o,s]of Object.entries(e)){const i=o.toLowerCase();zyn.has(i)||(r[i]=s)}r.authorization=`Bearer ${t.token}`;const n=Rx(t.token,t.accountId);return n&&(r["chatgpt-account-id"]=n),r["content-type"]="application/json",r["user-agent"]||(r["user-agent"]=Dle),r.originator||(r.originator=$mn),r.accept||(r.accept="text/event-stream"),r}function ngr(e,t){try{const n=JSON.parse(e)?.error;if(!n||typeof n!="object"||n.type!=="usage_limit_reached"&&n.code!=="usage_limit_reached")return null;const o=n.resets_at??n.reset_at,s=n.resets_in_seconds??n.reset_after_seconds,i=typeof o=="number"&&Number.isFinite(o)&&o>0?o>4102444800?o:o*1e3:typeof s=="number"&&Number.isFinite(s)&&s>0?t+s*1e3:0,a=n.limit_type,l=n.model||n.scope!==void 0&&n.scope!=="account"?"unknown":a==="primary"||a==="session"?"session":a==="secondary"||a==="weekly"?"weekly":"unknown";return{errorCode:"usage_limit_reached",resetAt:Number.isFinite(i)?i:0,scope:l}}catch{return null}}function Gyn(e,t,r,n=""){const o=r+Gue;if(e){if(e.weeklyStatus==="rejected"&&e.weeklyResetAt>0)return{coolingUntil:Math.max(e.weeklyResetAt*1e3,o),reason:"weekly"};if(e.sessionStatus==="rejected"&&e.sessionResetAt>0)return{coolingUntil:Math.max(e.sessionResetAt*1e3,o),reason:"session"}}const s=ngr(n,r);if(s)return s.scope!=="unknown"&&s.resetAt>0?{coolingUntil:Math.max(s.resetAt,o),reason:s.scope}:{coolingUntil:r+Math.min(Zfr,Math.max(s.resetAt-r,t,Gue)),reason:"unified"};const i=Math.min(Zfr,Math.max(t,Gue));return{coolingUntil:r+i,reason:e?.unifiedStatus==="rejected"?"unified":"transient"}}function jyn(e,t,r,n){if(e.responseHeaders||(e.responseHeaders={}),e.responseHeaders["x-neurolink-account"]=t.label,e.responseHeaders["x-neurolink-account-type"]="codex-oauth",e.responseHeaders["x-neurolink-served-by"]="codex",e.responseHeaders["x-neurolink-attempt"]=String(r),e.responseHeaders["x-neurolink-quota-source"]=n?"live":"none",n&&n.sessionStatus!=="unknown"&&(e.responseHeaders["x-neurolink-quota-session-left-pct"]=String(Math.round((1-n.sessionUsed)*100))),n&&n.weeklyStatus!=="unknown"){const o=String(Math.round((1-n.weeklyUsed)*100));e.responseHeaders["x-neurolink-quota-weekly-left-pct"]=o,e.responseHeaders["x-neurolink-weekly-left-pct"]=o}}async function ogr(e){e.metadata?.[jue]!==!0&&Jw({timestamp:new Date().toISOString(),requestId:e.requestId,phase:"client_request",model:sgr(e),stream:!0,headers:e.headers,body:e.body,contentType:"application/json",...zw({requestId:e.requestId})});const t=await Hyn(e);return e.metadata?.[jue]===!0?t:igr(e,t,"client_response")}function sgr(e){const t=e.body;return typeof t?.model=="string"?t.model:"-"}function igr(e,t,r,n,o){if(!Sue())return t;const s={timestamp:new Date().toISOString(),requestId:e.requestId,phase:r,model:sgr(e),stream:!0,headers:Object.fromEntries(t.headers.entries()),contentType:t.headers.get("content-type")??void 0,responseStatus:t.status,account:n?.label,accountType:n?oa:void 0,attempt:o,...zw({requestId:e.requestId})};if(!t.body||mfr())return Jw(s),t;const i=Pue();return i.capture.then(a=>Jw({...s,timestamp:new Date().toISOString(),body:a.text,bodySize:a.totalBytes,sourceTruncated:a.truncated})).catch(()=>{}),new Response(t.body.pipeThrough(i.stream),{status:t.status,statusText:t.statusText,headers:t.headers})}async function Hyn(e){const t=Date.now();let r=e.body??{},n,o,s,i,a=!1;const c=async E=>{if(i)try{a?(await sue(i,E),i.snapshot.settlement==="unconfirmed"&&jw("token_budget",{requestId:e.requestId,event:"settlement_unconfirmed"})):await i.cancelBeforeDispatch()}catch(_){jw("token_budget",{requestId:e.requestId,event:"settlement_unconfirmed",errorCode:el(_)?.code??"PROXY_TOKEN_BUDGET_UNAVAILABLE"})}},l=typeof r.model=="string"?r.model:"-",u=e.metadata?.[jue]===!0,d=r.reasoning,m=d&&typeof d=="object"&&"effort"in d&&typeof d.effort=="string"?d.effort:void 0;let h;try{h=Ux.startRequest({requestId:e.requestId,method:e.method,path:e.path,model:l,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,provider:"openai",userAgent:e.headers["user-agent"],recordRequestMetrics:!u,recordUsageMetrics:!0},e.headers)}catch{}const f=(E,_,C={})=>Kw({timestamp:new Date().toISOString(),requestId:e.requestId,method:e.method,path:e.path,model:l,requestedModel:l,contextPreflight:s,tokenBudget:i?{...i.snapshot}:void 0,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:E?.label??"",...E?{accountKey:E.key}:{},accountType:E?oa:"",provider:"openai",inputIncludesCachedTokens:!0,...h?.getTraceContext(),...m?{reasoningEffort:m}:{},firstUsefulOutputStatus:C.firstUsefulOutputMs!==void 0?"observed":"not_observed",...Fx(e.headers),responseStatus:_,responseTimeMs:Date.now()-t,...C});let g=!1;const y=async(E,_,C={})=>{if(await c(C.inputTokens!==void 0&&C.outputTokens!==void 0?C.inputTokens+C.outputTokens:void 0),!g){if(g=!0,Fw(e.requestId)){const A=e.abortSignal?.aborted?e.abortSignal.reason?.name==="TimeoutError"?504:499:_;try{h?.end(A,Date.now()-t)}catch{}return}try{C.errorType&&h?.setError(C.errorType,C.errorMessage??C.errorType),h?.end(_,Date.now()-t)}catch{}u||(_>=400?Zg(_,E?.label,E?oa:void 0,{requestId:e.requestId,...E?{accountKey:E.key}:{},errorType:C.errorType,terminalOutcome:C.terminalOutcome??"handler_error",message:C.errorMessage,errorCode:C.errorCode}):nx(E?.label,E?oa:void 0),await f(E,_,C))}},v=(E,_,C,A,k={})=>{Eue({timestamp:new Date().toISOString(),requestId:e.requestId,attempt:_,...h?.getTraceContext(),...u?{parentRequestId:e.requestId.replace(/:codex-fallback$/,"")}:{},...m?{reasoningEffort:m}:{},method:e.method,path:e.path,model:l,requestedModel:l,contextPreflight:s,tokenBudget:i?{...i.snapshot}:void 0,stream:!0,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:E.label,accountKey:E.key,accountType:oa,provider:"openai",responseStatus:A,responseTimeMs:Date.now()-t,attemptDurationMs:Date.now()-C,...k}).catch(()=>{})},w=async()=>{try{o=Zle({provider:"codex",model:l,body:r}),s=o.evidence,r=o.body,n=JSON.stringify(r)}catch(M){if(!(M instanceof _r))throw M;return s=M.evidence,await y(void 0,M.status,{errorType:"context_preflight",errorCode:M.code,errorMessage:M.message,retryable:!1,terminalOutcome:"handler_error"}),nh(M.status,M.message,M.code)}const E=await egr(),_=async M=>(await y(M,499,{errorType:"client_cancelled",errorMessage:"Client cancelled Codex request",terminalOutcome:"client_cancelled"}),nh(499,"Client cancelled Codex request"));if(e.abortSignal?.aborted)return _();if(E.length===0)return await y(void 0,401,{errorType:"no_accounts",errorMessage:"No Codex accounts"}),nh(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const C=Date.now(),A=tgr(E,C),k=A.filter(M=>!(M.coolingUntil!==void 0&&M.coolingUntil>C));if(k.length===0){const M=A.reduce((L,q)=>q.coolingUntil===void 0?L:L===void 0?q.coolingUntil:Math.min(L,q.coolingUntil),void 0),F=M?Math.max(1,Math.ceil((M-C)/1e3)):60;await y(void 0,429,{errorType:"all_accounts_cooling",errorMessage:"All Codex accounts are rate-limited"});const N=M?new Date(M).toISOString():void 0;return qyn(N?`Codex quota exhausted: all accounts are rate-limited. Resets at ${N}.`:"Codex quota exhausted: all accounts are rate-limited.",F)}let R=0,I="All Codex accounts failed",P=502,O={errorType:"all_accounts_failed"},U;for(const M of k){try{h?.setAccountSelection({strategy:"codex-quota-order",accountsTotal:E.length,accountsHealthy:k.length,selectedAccount:M.label,accountType:oa})}catch{}let F=!1;for(;;){if(e.abortSignal?.aborted)return _(U);await c(),i=void 0,a=!1;try{i=await oue({provider:"codex",accountKey:M.key,sessionKey:eue(new Headers(e.headers)),requestId:e.requestId,reservationTokens:o.totalTokensReservation,estimateProvenance:"estimated_input_plus_serving_model_output_reserve"})}catch(G){const X=el(G);if(!X)throw G;return await y(M,X.status,{errorType:"token_budget",errorCode:X.code,errorMessage:X.message,retryable:!1,terminalOutcome:"handler_error"}),nh(X.status,X.message,X.code)}if(e.abortSignal?.aborted)return _(M);R+=1;const N=Date.now();U=M,YF(M.label,oa);let L;try{const G=rgr(e.headers,M);Jw({timestamp:new Date().toISOString(),requestId:e.requestId,phase:"upstream_request",model:l,stream:!0,body:n,headers:G,contentType:"application/json",account:M.label,accountType:oa,attempt:R,...h?.getTraceContext()}),a=!0,L=await fetch(Nmn,{method:"POST",headers:G,body:n,signal:e.abortSignal?AbortSignal.any([e.abortSignal,AbortSignal.timeout(que)]):AbortSignal.timeout(que)})}catch(G){if(e.abortSignal?.aborted)return v(M,R,N,499,{errorType:"client_cancelled",errorMessage:"Client cancelled Codex request",retryable:!1}),_(M);p.debug(`Codex upstream fetch failed (${M.label}): ${lr(G instanceof Error?G.message:String(G))}`);const X=rE(G instanceof Error?G.message:String(G),"Codex upstream request failed"),ce=Jx(G),Q=Uyn(G);if(Pr(M.label,oa,502),v(M,R,N,502,{errorType:"network_error",errorMessage:X,...ce?{errorCode:ce}:{},transportScope:Q,retryable:["UND_ERR_CONNECT_TIMEOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"].includes(ce??"")}),O={errorType:"network_error",errorMessage:X,errorCode:ce,transportScope:Q},!["UND_ERR_CONNECT_TIMEOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN"].includes(ce??""))return await y(M,502,{...O,errorMessage:X}),nh(502,"Codex upstream request failed");I="Codex upstream request failed",P=502;break}if(L=igr(e,L,"upstream_response",M,R),L.ok){const G=Kpr(L.headers);G&&Zp(M.key,G).catch(()=>{}),M.expiredCooldownUntil!==void 0&&Yp(M.key,M.expiredCooldownUntil).catch(()=>{}),jyn(e,M,R,G),v(M,R,N,L.status);const X={"content-type":L.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive",...e.responseHeaders??{}};if(!L.body)return Pr(M.label,oa,502),v(M,R,N,502,{errorType:"incomplete_stream",errorMessage:"Codex returned no response stream",retryable:!1}),await y(M,502,{terminalOutcome:"stream_error",errorType:"incomplete_stream",errorMessage:"Codex returned no response stream"}),new Response(L.body,{status:L.status,headers:X});const{stream:ce,usage:Q,evidence:Ae}=Apn(),Ee=new Response(L.body.pipeThrough(ce),{status:L.status,headers:X});return $w(e.metadata,{onTerminal:({outcome:le,error:ae,observedBodyBytes:Pe})=>Q.then(ke=>{const Te=Ae(),he=Te.completed&&Pe>=Te.terminalBytes,Oe=Te.errorType||(le==="completed"||le==="bodyless")&&!Te.completed,De=ke?{inputTokens:ke.inputTokensObserved?ke.inputTokens:void 0,outputTokens:ke.outputTokensObserved?ke.outputTokens:void 0,cacheReadTokens:ke.cacheReadTokensObserved?ke.cacheReadTokens:void 0,cacheCreationTokens:ke.cacheCreationTokensObserved?ke.cacheCreationTokens:void 0,reasoningTokens:ke.reasoningTokensObserved?ke.reasoningTokens:void 0}:{};if(ke?.inputTokensObserved&&ke.outputTokensObserved)try{h?.setUsage({...ke,reasoningTokens:ke.reasoningTokensObserved?ke.reasoningTokens:void 0,cacheReadTokensObserved:ke.cacheReadTokensObserved===!0,cacheCreationTokensObserved:ke.cacheCreationTokensObserved===!0,inputIncludesCachedTokens:!0})}catch{}const Ye=Te.firstUsefulOutputAt===void 0||Te.observationIncomplete?{firstUsefulOutputStatus:Te.completed&&!Te.observationIncomplete?"no_useful_output":"not_observed"}:{firstUsefulOutputStatus:"observed",firstUsefulOutputEvent:Te.firstUsefulOutputEvent,firstUsefulOutputMs:Math.max(0,Te.firstUsefulOutputAt-t)};return Oe?(Pr(M.label,oa,502),v(M,R,N,502,{...De,inputIncludesCachedTokens:!0,errorType:Te.errorType??"incomplete_stream",errorCode:Te.errorCode,errorMessage:Te.errorMessage??"Codex stream ended without a completion event",retryable:!1}),y(M,502,{...De,...Ye,terminalOutcome:"stream_error",errorType:Te.errorType??"incomplete_stream",errorCode:Te.errorCode,errorMessage:Te.errorMessage??"Codex stream ended without a completion event"})):le==="completed"||le==="bodyless"||le==="client_cancelled"&&he?y(M,L.status,{terminalOutcome:"completed",...De,...Ye}):(le==="stream_error"&&(Pr(M.label,oa,502),v(M,R,N,502,{errorType:"stream_error",errorCode:Jx(ae),errorMessage:rE(ae instanceof Error?ae.message:"","Codex upstream stream failed"),retryable:!1})),y(M,le==="client_cancelled"?499:502,{errorType:le==="client_cancelled"?"client_cancelled":"stream_error",errorMessage:le==="client_cancelled"?"Client cancelled Codex stream":rE(ae instanceof Error?ae.message:"","Codex upstream stream failed"),...le==="stream_error"?{errorCode:Jx(ae)}:{},terminalOutcome:le,...De,...Ye}))}).catch(()=>{})}),Ee}const q=await L.text().catch(()=>"");if((L.status===401||L.status===403)&&!F&&M.refreshToken){const G=rE(q,"Codex authentication rejected upstream");Pr(M.label,oa,L.status),v(M,R,N,L.status,{errorType:"authentication_error",errorMessage:G,retryable:!0}),F=!0;const X={accessToken:M.token,refreshToken:M.refreshToken,expiresAt:M.expiresAt??0};try{const ce=await Vue(M.key,M.refreshToken);M.token=ce.accessToken,M.refreshToken=ce.refreshToken??M.refreshToken,M.expiresAt=ce.expiresAt??M.expiresAt,M.accountId=Rx(ce.accessToken);continue}catch(ce){if(Gmn(ce)){await gi.markDisabledIfCurrent(M.key,X,"refresh_invalid")&&p.always(`[proxy] codex account=${M.label} disabled until re-authentication. Run: neurolink auth login codex --label ${M.label}`),O={errorType:"authentication_error",errorCode:"refresh_invalid"},P=401,I="Codex token refresh failed; re-login required";break}await Vu(M.key,Date.now()+Qfr,"auth").catch(()=>{}),p.debug(`[proxy] codex account=${M.label} refresh failed transiently; cooling and rotating`),O={errorType:"auth_refresh_unavailable",errorCode:Jx(ce)},P=503,I="Codex token refresh temporarily unavailable";break}}if(L.status===429){const G=Kpr(L.headers);G&&Zp(M.key,G).catch(()=>{});const X=a3(L.headers.get("retry-after")),ce=Date.now(),Q=ngr(q,ce),Ae=Gyn(G,X,ce,q);await Vu(M.key,Ae.coolingUntil,Ae.reason).catch(()=>{});const Ee=Ae.reason==="transient"?"transient":"quota",le=rE(q,"Codex account rate-limited");Pr(M.label,oa,L.status,Ee),v(M,R,N,L.status,{errorType:"rate_limit_error",errorMessage:le,retryable:Ee==="transient",rateLimitKind:Ee,cooldownReason:Ae.reason,...Q?{errorCode:Q.errorCode,quotaResetAt:Q.resetAt||void 0,quotaScope:Q.scope}:{}}),O={errorType:"rate_limit_error",errorCode:Q?.errorCode},P=429,I="Codex account rate-limited";break}(L.status===401||L.status===403)&&await Vu(M.key,Date.now()+Qfr,"auth").catch(()=>{});const B=rE(q,"Codex error"),H=L.status===401||L.status===403?"authentication_error":"api_error";Pr(M.label,oa,L.status),v(M,R,N,L.status,{errorType:H,errorMessage:B,retryable:L.status>=500}),O={errorType:H},P=L.status>=500?502:L.status,I=B;break}}return await y(U,P,{...O,errorMessage:O.errorMessage??I}),nh(P,I)};try{return await w()}catch(E){await c();try{h?.end(502,Date.now()-t)}catch{}throw E}}function Vyn(e){if(Buffer.byteLength(e,"utf8")>2*1024*1024)return;let t;try{t=JSON.parse(e)}catch{return}if(!(!t||typeof t!="object"||!("models"in t)||!Array.isArray(t.models)))for(const r of t.models.slice(0,1024)){if(!r||typeof r!="object")continue;const n=r.slug??r.id;if(typeof n!="string"||n.length===0||n.length>256)continue;const o=r.context_window,s=r.max_output_tokens;Number.isSafeInteger(o)&&o>0&&W9("codex",n,o);const i=K9("codex",n);Number.isSafeInteger(s)&&s>0&&(i===void 0||s<i)?Jot("codex",n,s):KLr("codex",n)}}async function Wyn(e){const t=await egr();if(t.length===0)return nh(401,"No Codex accounts configured. Run `neurolink auth login codex`.");const r=Date.now(),n=tgr(t,r),o=d=>d.coolingUntil!==void 0&&d.coolingUntil>r,s=[...n.filter(d=>!o(d)),...n.filter(o)],a=new URLSearchParams(e.query??{}).toString(),c=a?`${qpr}?${a}`:qpr;let l=502,u="Codex model discovery upstream failed";for(const d of s){let m=!1;for(;;){let h;try{h=await fetch(c,{method:"GET",headers:rgr(e.headers??{},d),signal:AbortSignal.any([...e.abortSignal?[e.abortSignal]:[],AbortSignal.timeout(que)])})}catch(y){l=502,u=`Codex model discovery upstream failed: ${y instanceof Error?y.message:String(y)}`;break}if(h.status===401||h.status===403){if(!m&&d.refreshToken){m=!0;try{const y=await Vue(d.key,d.refreshToken);d.token=y.accessToken,d.refreshToken=y.refreshToken??d.refreshToken,d.expiresAt=y.expiresAt??d.expiresAt,d.accountId=Rx(y.accessToken);continue}catch{l=401,u="Codex token refresh failed; re-login required";break}}l=h.status,u="Codex model discovery rejected upstream";break}const f=await h.text();h.ok&&Vyn(f);const g=h.headers.get("content-type")??"application/json";return new Response(f,{status:h.status,headers:{"content-type":g}})}}return nh(l,u)}function Kyn(e=""){return{prefix:`${e}/backend-api/codex`,routes:[{method:"POST",path:`${e}/backend-api/codex/responses`,description:"Codex ChatGPT-backend Responses API (account pool)",handler:t=>ogr(t)},{method:"GET",path:`${e}/backend-api/codex/models`,description:"Codex model discovery, relayed upstream (account pool)",handler:t=>Wyn(t)}]}}function Jyn(e,t,r,n){if(t.snapshot.scope==="disabled")return e;let o,s=!1,i=!1,a=!1,c,l,u=0,d=0,m="",h=!1;const f=e.headers.get("content-type")?.includes("text/event-stream"),g=new TextDecoder,y=C=>{try{const A=JSON.parse(C);A?.type==="message_stop"&&(s=!0),A?.type==="error"&&(a=!0);const k=A?.usage??A?.message?.usage;if(!k||typeof k!="object")return;const R=I=>typeof I=="number"&&Number.isSafeInteger(I)&&I>=0;R(k.input_tokens)&&(c=Math.max(c??0,k.input_tokens)),R(k.output_tokens)&&(A?.type==="message_delta"&&(i=!0),l=Math.max(l??0,k.output_tokens)),R(k.cache_read_input_tokens)&&(u=Math.max(u,k.cache_read_input_tokens)),R(k.cache_creation_input_tokens)&&(d=Math.max(d,k.cache_creation_input_tokens))}catch{}},v=C=>{if(!f){!h&&m.length+C.length<=1024*1024?m+=C:(h=!0,m="");return}for(const A of C.split(/(?<=\n)/u))!h&&m.length+A.length<=64*1024?m+=A:(h=!0,m=""),A.endsWith(`
|
|
2360
|
+
`)&&(!h&&m.startsWith("data:")&&y(m.slice(5).trim()),m="",h=!1)},w=C=>o||(o=(async()=>{n?.removeEventListener("abort",E),C&&(v(g.decode()),!h&&m&&y(f&&m.startsWith("data:")?m.slice(5).trim():m));const A=C&&!a&&(!f||s&&i)&&c!==void 0&&l!==void 0?c+l+u+d:void 0;try{await sue(t,A)}finally{r()}})(),o),E=()=>{w(!1).catch(()=>{})};if(n?.aborted?E():n?.addEventListener("abort",E,{once:!0}),!e.body)return w(!1).catch(()=>{}),e;const _=e.body.getReader();return new Response(new ReadableStream({async pull(C){try{const A=await _.read();if(A.done){await w(!0),C.close();return}v(g.decode(A.value,{stream:!0})),C.enqueue(A.value)}catch(A){await w(!1).catch(()=>{}),C.error(A)}},async cancel(C){await Promise.allSettled([_.cancel(C),w(!1)])}},{highWaterMark:0}),{status:e.status,statusText:e.statusText,headers:e.headers})}var c3=new Set(["cookie","proxy-authorization","host","connection","content-length","transfer-encoding"]),Wue="proxy/internal",Kue="internal";function agr(e,t){return e?t==="codex-oauth"?{accountKey:e.startsWith("codex:")?e:`codex:${e}`,provider:"openai"}:t==="oauth"||t==="api_key"||t==="passthrough"?{accountKey:t==="passthrough"?e:jp(e),provider:"anthropic"}:t==="vertex"?{accountKey:e,provider:"vertex"}:{}:{}}var oh=0,cgr=0,Yx=5,l3=2,Jue=[250,1e3],lgr=4,ugr=[250,500,1e3,2e3],Yue=1,Yyn=120*1e3,u3=2,dgr=3e4,mgr=11520*60*1e3,pgr=5e3,Xyn=900*1e3,Xue=900*1e3,Zyn=3e4,Qyn=300*1e3,Xx=900*1e3;function hgr(e,t){const r=JSON.parse(t),n=Zle({provider:"anthropic",model:r.model,body:r});return e.metadata.contextPreflight=n.evidence,{bodyStr:n.body===r?t:JSON.stringify(n.body),preparedContext:n}}var fgr;async function Zue(e,t,r,n,o){w3(r);const s=o.preparedContext,i=await oue({provider:"anthropic",accountKey:n,requestId:r.requestId,sessionKey:eue({get:a=>r.headers[a]??null}),reservationTokens:s.totalTokensReservation,estimateProvenance:"estimated_input_plus_output_reserve"});if(r.metadata.tokenBudget=i.snapshot,t.signal?.aborted||r.abortSignal?.aborted)throw await i.cancelBeforeDispatch(),r.metadata.tokenBudget=i.snapshot,t.signal?.reason??r.abortSignal?.reason;fgr??=new d_({headersTimeout:Xx,bodyTimeout:Xx});try{const a=String(t.body);YF(o.accountLabel,o.accountType),o.tracer?.logUpstreamRequestHeaders(t.headers),o.tracer?.logUpstreamRequestBody(a),o.logProxyBody({phase:"upstream_request",headers:t.headers,body:a,bodySize:Buffer.byteLength(a,"utf8"),contentType:"application/json",account:o.accountLabel,accountType:o.accountType,attempt:o.attemptNumber,metadata:{upstreamMethod:"POST",upstreamUrl:e}});const c=await fetch(e,{...t,body:a,dispatcher:fgr});return Jyn(c,i,()=>{r.metadata.tokenBudget=i.snapshot},t.signal??void 0)}catch(a){throw await i.settle().catch(()=>{}),r.metadata.tokenBudget=i.snapshot,a}}var pc=new Map,Zx=new Xmn,nE=new Qmn,Que=900*1e3,ede=new Map,ggr=new Map,Qx=new Map;function ygr(e){let t=Qx.get(e);return t||(t={active:0,waiters:[]},Qx.set(e,t)),t}function tde(e,t){for(;t.waiters.length>0&&t.active<t.waiters[0].capacity;){const r=t.waiters.shift();if(!r)return;t.active+=1,r.resolve(d3(e,t))}}function e0n(e,t,r){if(r===void 0)return;const n=s=>s.generation!==void 0&&s.generation<r,o=t.waiters.filter(n);if(o.length!==0){t.waiters=t.waiters.filter(s=>!n(s));for(const s of o)t.active+=1,s.resolve(d3(e,t))}}function d3(e,t){let r=!1;return{release:()=>{r||(r=!0,t.active=Math.max(0,t.active-1),tde(e,t),vgr(e,t))}}}function vgr(e,t){t.active===0&&t.waiters.length===0&&Qx.delete(e)}function t0n(e,t,r){const n=zue(t),o=ygr(e);if(n===void 0)return e0n(e,o,r),o.active+=1,d3(e,o);if(!(o.waiters.length>0||o.active>=n))return o.active+=1,d3(e,o)}function r0n(e){return Qx.get(e)?.active??0}function n0n(e,t){const r=zue(t);if(r===void 0)return!0;const n=Qx.get(e);return!n||n.waiters.length===0&&n.active<r}function o0n(e,t,r){const n=zue(t);if(n===void 0)throw new Error("Account admission queue requires an explicit capacity");const o=ygr(e);let s=!0,i,a;const c=new Promise(u=>{a=u}),l={capacity:n,generation:r,resolve:u=>{s=!1,i=u,a(u)}};return o.waiters.push(l),tde(e,o),{accountKey:e,promise:c,cancel:()=>{if(i){const d=i;i=void 0,d.release();return}if(!s)return;s=!1;const u=o.waiters.indexOf(l);u>=0&&(o.waiters.splice(u,1),tde(e,o)),vgr(e,o)}}}async function s0n(e,t,r,n=ode,o){const s=[...new Set(e)].map(a=>o0n(a,t,o));let i;try{return await Ct(id(Promise.race(s.map(a=>a.promise.then(c=>i?(c.release(),new Promise(()=>{})):(i=a.accountKey,{accountKey:a.accountKey,lease:c})))),r),n,`Account admission timed out after ${n}ms`)}catch(a){if(r?.aborted)throw a;return}finally{for(const a of s)a.accountKey!==i&&a.cancel()}}var Tgr=!1,rde,nde=6e4,ode=9e4,i0n=12e4,a0n=250,c0n=15e3;function my(e,t,r){t<=1||e===r&&(oh=(oh+1)%t)}function wgr(e,t){if(!t)return 0;const r=e.findIndex(n=>Xae(n.key,t));return r>=0?r:0}function l0n(e,t){if(e.length<=1)return;const r=wgr(e,t);if(oh===r)return;const n=e[r],o=pc.get(n.key);if((!o||!o.coolingUntil||Date.now()>=o.coolingUntil)&&(oh=r,o?.coolingUntil)){const s=o.coolingUntil;o.coolingUntil=void 0,o.coolingReason=void 0,Yp(n.key,s).catch(()=>{}),p.always(`[proxy] home primary account=${n.label} cooling expired, resetting primaryAccountIndex to ${r}`)}}function Egr(e){const t=pc.get(e);return!!t?.coolingUntil&&Date.now()<t.coolingUntil}function u0n(e,t,r=Date.now()){let n=ede.get(e);if(!n||r>=n.coolingUntil?(n={coolingUntil:t,retriesClaimed:0},ede.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t),!(n.retriesClaimed>=u3))return n.retriesClaimed+=1,n.retriesClaimed}function Sgr(e,t,r,n){const o=u0n(e,t);if(r===void 0||n>=u3||o===void 0)return;const s=Math.min(r||1e3,dgr);return{slot:o,delayMs:Math.min(dgr,Jgr(s*o))}}function d0n(e,t){if(ede.delete(e.key),t.coolingReason!=="transient"||!t.coolingUntil)return;const r=t.coolingUntil;t.coolingUntil=void 0,t.coolingReason=void 0,Yp(e.key,r).catch(()=>{})}function m0n(e,t,r=Date.now()){if(t<=r)return 0;if(t-r>ode)return;let n=ggr.get(e);!n||r>=n.coolingUntil?(n={coolingUntil:t,nextAdmissionAt:t},ggr.set(e,n)):t>n.coolingUntil&&(n.coolingUntil=t,n.nextAdmissionAt=Math.max(n.nextAdmissionAt,t));const o=Math.max(r,n.coolingUntil,n.nextAdmissionAt);if(!(o-n.coolingUntil>c0n))return n.nextAdmissionAt=o+a0n,o-r}async function p0n(e){const t=Date.now()+i0n;for(;Date.now()<t;){const r=e.filter(i=>!Egr(i.key));if(r.length>0)return r;const n=Date.now(),o=e.map(i=>({account:i,state:$a(i.key)})).filter(({state:i})=>i.coolingReason==="transient"&&i.coolingUntil!==void 0&&i.coolingUntil>n).sort((i,a)=>(i.state.coolingUntil??Number.POSITIVE_INFINITY)-(a.state.coolingUntil??Number.POSITIVE_INFINITY))[0];if(!o?.state.coolingUntil)return[];const s=m0n(o.account.key,o.state.coolingUntil,n);if(s===void 0||n+s>t)return[];p.always(`[proxy] all usable accounts are transiently cooling; queueing request for account=${o.account.label} in ${s}ms`),await Zl(s)}return[]}function Fs(e,t){if(!e||e<=0)return;const r=e>4102444800?e:e*1e3;return r>t?r:void 0}function eI(e,t){try{const r=t.poolAccounts?hpn(t.poolAccounts.map(o=>{const s=pc.get(o.key);return{...s?.coolingUntil!==void 0?{coolingUntil:s.coolingUntil}:{},...s?.quota?{quota:s.quota}:{}}})):void 0,n=ppn({...t.upstreamHeaders?{upstreamHeaders:t.upstreamHeaders}:{},context:{quota:t.quota??null,source:t.source,...t.account?{accountLabel:t.account.label}:{},...t.accountType??t.account?.type?{accountType:t.accountType??t.account?.type}:{},...t.servedBy?{servedBy:t.servedBy}:{},...t.attempt!==void 0?{attempt:t.attempt}:{},...t.accountState?.coolingUntil!==void 0?{coolingUntil:t.accountState.coolingUntil}:{},...t.accountState?.coolingReason?{coolingReason:t.accountState.coolingReason}:{},...r?{pool:r}:{}}});e.responseHeaders={...e.responseHeaders??{},...vde(n)}}catch(r){p.debug(`[proxy] failed to publish limit headers: ${r instanceof Error?r.message:String(r)}`)}}function m3(e,t,r){const n=Math.min(mgr,(r&&xpr[r])??mgr);return Math.min(Math.max(e,t+pgr),t+n)}function p3(e){return e?.trim().toLowerCase()==="allowed"}function bgr(e,t){return!e||Fs(e.resetsAt,t)===void 0?!1:e.status?.trim().toLowerCase()==="rejected"||(e.used??0)>=1}function h0n(e,t,r,n=rl){if(!e||!t||!p3(e.sessionStatus)||!p3(e.weeklyStatus)||oE(e,n))return null;const o=pde(e,t,r);return bgr(o,r)?o:null}function f0n(e,t,r=rl){return!p3(e.sessionStatus)||!p3(e.weeklyStatus)||oE(e,r)?!1:(e.windows??[]).some(n=>n.kind==="weekly_scoped"&&typeof n.scopeModel=="string"&&t-mde(e,n)<=Que&&bgr(n,t))}function sde(e,t,r,n=e?.unifiedStatus,o=rl,s){if(e&&e.weeklyStatus==="rejected"){const l=Fs(e.weeklyResetAt,r)??(t>0?r+t:r+nde);return{reason:"weekly",scope:"account",coolingUntil:m3(l,r,"weekly"),rotateImmediately:!0}}const i=oE(e,o);if(e&&e.sessionStatus==="rejected"&&!i){const l=Fs(e.sessionResetAt,r)??(t>0?r+t:r+nde);return{reason:"session",scope:"account",coolingUntil:m3(l,r,"session"),rotateImmediately:!0}}const a=h0n(e,s,r,o);if(a)return{reason:"unified",scope:"model",coolingUntil:Fs(a.resetsAt,r)??(t>0?r+t:r+Xue),rotateImmediately:!0};if(n?.trim().toLowerCase()==="rejected"&&!i){const l=t>0?r+t:r+Xue;return{reason:"unified",scope:"account",coolingUntil:m3(l,r,"unified"),rotateImmediately:!0}}const c=t>0?t:nde;return{reason:"transient",scope:"account",coolingUntil:r+Math.max(pgr,Math.min(c,Xyn)),rotateImmediately:!1}}function ide(e,t){return Math.max(0,Math.round((e-t)/6e4))}function ade(e,t,r,n=rl){const o=oE(t,n),s=f0n(t,r,n);let i,a;if(t.weeklyStatus==="rejected"&&(i=Fs(t.weeklyResetAt,r),a="weekly"),i===void 0&&o&&e.coolingUntil&&(e.coolingReason==="session"||e.coolingReason==="unified")){const l=e.coolingUntil;return e.coolingUntil=void 0,e.coolingReason=void 0,p.always("[proxy] clearing subscription cooldown because Anthropic explicitly permits overage"),{kind:"cleared",coolingUntil:l}}if(i===void 0&&t.sessionStatus==="rejected"&&!o?(i=Fs(t.sessionResetAt,r),a="session"):i===void 0&&t.unifiedStatus==="rejected"&&!o&&!s&&(i=r+Xue,a="unified"),i===void 0){if(!!e.coolingUntil&&(e.coolingReason==="weekly"&&t.weeklyStatus==="allowed"||e.coolingReason==="session"&&t.sessionStatus==="allowed"||e.coolingReason==="unified"&&(t.unifiedStatus==="allowed"||s))&&e.coolingUntil){const u=e.coolingUntil,d=e.coolingReason;return e.coolingUntil=void 0,e.coolingReason=void 0,p.always(`[proxy] clearing ${d} cooldown from fresh provider quota`),{kind:"cleared",coolingUntil:u}}return null}const c=m3(i,r,a);return!e.coolingUntil||c>e.coolingUntil?(e.coolingUntil=c,e.coolingReason=a,p.always(`[proxy] proactively cooling account (${a}) ~${ide(c,r)}m from success-response quota (status rejected)`),{kind:"cooled",coolingUntil:c,coolingReason:a??"unified"}):null}async function g0n(e){try{const[t,r]=await Promise.all([Ile(),kx()]),n=Date.now();for(const o of e){const s=$a(o.key);s.quota||(s.quota=t[o.key]??t[o.label]);const i=r[o.key];i?.coolingUntil>n&&(!s.coolingUntil||i.coolingUntil>s.coolingUntil)&&(s.coolingUntil=i.coolingUntil,s.coolingReason=i.reason)}}catch{}}var y0n=15e3,_gr=new Map,h3=null,v0n=4;async function Cgr(e,t,r,n){if(t.ok===!1)return null;const o=$a(e.key),s=Bpr(t.usage,{now:r,prior:o.quota??n??null});if(!s)return null;if(s.lastUpdated<(o.quota?.lastUpdated??0))return o.quota??null;o.quota=fm(o.quota,s);const i=ade(o,s,Date.now());return i?.kind==="cooled"?await Vu(e.key,i.coolingUntil,i.coolingReason).catch(()=>{}):i?.kind==="cleared"&&await Yp(e.key,i.coolingUntil).catch(()=>{}),await Zp(e.key,s).catch(()=>{}),s}async function Agr(e){const t=await Imn(e);return t.ok===!1||Bpr(t.usage,{now:Date.now(),prior:pc.get(e.key)?.quota??null})?t:{ok:!1,reason:"parse",error:"usage payload had no recognizable limit windows"}}async function f3(e,t){const r=await Zx.run(e,t,Agr);r.kind!=="completed"||r.result.ok===!1||await Cgr(e,r.result,r.startedAt)}var tI=null;async function T0n(e){if(tI)return{anthropic:tI.anthropic,codex:tI.codex};const[t,r]=await Promise.all([$pr(e),Wmn()]);return{anthropic:t,codex:r}}async function w0n(){if(tI)return tI.knownKeys;const[e,t]=await Promise.all([gi.listByPrefix("anthropic:"),gi.listByPrefix("codex:")]);return new Set([...e.map(jp),...t])}async function cde(e={}){const t=Date.now(),r=await T0n(e.accountAllowlist),n=[...r.anthropic.map(u=>({account:u,provider:"anthropic"})),...r.codex.map(u=>({account:u,provider:"codex"}))],o=e.accountFilter?n.filter(({account:u})=>u.label===e.accountFilter||u.key===e.accountFilter):n,s=await Ile().catch(()=>({})),i=(u,d,m,h,f)=>{const g=pc.get(u.key),y=d==="anthropic"?s[u.key]??s[u.label]??null:s[u.key]??null,v={account:u.label,key:u.key,provider:d,type:u.type,status:m,quota:h??g?.quota??y};return f!==void 0&&(v.error=f),g?.coolingUntil&&g.coolingUntil>Date.now()&&(v.coolingUntil=g.coolingUntil,g.coolingReason&&(v.coolingReason=g.coolingReason)),v};if(e.snapshotOnly)return{fetchedAt:t,snapshot:!0,results:o.map(({account:u,provider:d})=>i(u,d,"snapshot",null)),refreshMetrics:Zx.getMetrics()};const a=new Array(o.length);let c=0;const l=async()=>{for(;;){const u=c++;if(u>=o.length)return;const{account:d,provider:m}=o[u];if(d.type!=="oauth"){a[u]=i(d,m,"skipped_api_key",null);continue}const h=_gr.get(d.key)??0;if(Date.now()-h<y0n){a[u]=i(d,m,"throttled",null);continue}if(_gr.set(d.key,Date.now()),m==="codex"){try{const f=await Kmn(d);if(f.ok===!1){a[u]=i(d,m,"error",null,`codex usage fetch failed: ${f.reason}`);continue}await Zp(d.key,f.quota),a[u]=i(d,m,"refreshed",f.quota)}catch(f){a[u]=i(d,m,"error",null,f instanceof Error?f.message:String(f))}continue}try{const f=await Zx.run(d,`manual:${d.key}`,Agr,{force:!0});if(f.kind!=="completed"){a[u]=i(d,m,"throttled",null);continue}const g=f.result;if(g.ok===!1){a[u]=i(d,m,"error",null,g.error);continue}const y=await Cgr(d,g,f.startedAt,s[d.key]??s[d.label]??null);if(!y){a[u]=i(d,m,"error",null,"usage payload had no recognizable limit windows");continue}a[u]=i(d,m,"refreshed",y)}catch(f){a[u]=i(d,m,"error",null,f instanceof Error?f.message:String(f))}}};return await Promise.all(Array.from({length:Math.min(v0n,o.length||1)},()=>l())),{fetchedAt:t,snapshot:!1,results:a,refreshMetrics:Zx.getMetrics()}}function lde(){const e=(process.env.NEUROLINK_PROXY_QUOTA_ROUTING??"").toLowerCase();return e!=="off"&&e!=="false"&&e!=="0"}function ude(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_SOFT_LIMIT??"");return Number.isFinite(e)&&e>0&&e<=1?e:.97}function rI(){const e=Number(process.env.NEUROLINK_PROXY_SESSION_RESET_TOLERANCE_MS??"");return Number.isInteger(e)&&e>0?e:900*1e3}var rl="auto";function dde(e){e!==void 0&&(rl=e)}function E0n(){return rl}function oE(e,t=rl){return t==="never"?!1:Rpr(e)}var S0n=4;function g3(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function b0n(e){const t=g3(e);return t.startsWith("claude")?t.slice(6):t}function _0n(e,t,r){if(e.scopeModelId&&g3(R$(e.scopeModelId))===r)return Number.MAX_SAFE_INTEGER;if(!e.scopeModel)return null;const n=b0n(e.scopeModel);return n.length<S0n||!t.includes(n)?null:n.length}function mde(e,t){return t.updatedAt??e.windowsUpdatedAt??e.lastUpdated}function pde(e,t,r=Date.now()){if(!e?.windows?.length||!t)return null;const n=g3(t);if(!n)return null;const o=g3(R$(t));let s=null,i=-1,a=-1;for(const c of e.windows){if(r-mde(e,c)>Que)continue;const l=_0n(c,n,o);if(l===null)continue;const u=mde(e,c);(l>i||l===i&&u>a)&&(s=c,i=l,a=u)}return s}function C0n(e,t,r=Date.now(),n=rl){if(!t||e.length===0)return{eligible:e,exhaustion:null};const o=[],s=[];let i;for(const c of e){const l=pc.get(c.key)?.quota,u=pde(l,t,r),d=u?Fs(u.resetsAt,r):void 0;if(!(u!==null&&d!==void 0&&((u.status??"").trim().toLowerCase()==="rejected"||(u.used??0)>=1)&&!oE(l,n))||!u){o.push(c);continue}s.push({label:c.label,window:u}),i??=l?.overageDisabledReason}if(o.length>0||s.length===0)return{eligible:o,exhaustion:null};const a=Math.min(...s.map(c=>Fs(c.window.resetsAt,r)??Number.POSITIVE_INFINITY));return{eligible:o,exhaustion:{model:t,scopeModel:s[0]?.window.scopeModel??R$(t),earliestResetMs:a,accounts:s.map(c=>c.label),...i?{overageDisabledReason:i}:{}}}}function y3(e,t,r,n,o,s=rl){const i=pc.get(e),a=i?.quota,c=a&&Number.isFinite(a.lastUpdated)?a.lastUpdated:null,l=c===null?null:Math.max(0,t-c),u=Zx.getState(e),d=l!==null&&l>Que,m=X=>X.trim().toLowerCase(),h=Rpr(a),f=[a?.unifiedStatus,a?.sessionStatus,a?.weeklyStatus].filter(X=>!!X?.trim()),g=d&&!!a&&!h&&f.some(X=>m(X)!=="allowed"),y=a?d?g?"refresh_due":"stale_known":"fresh":"unknown",v=g?void 0:a,w=!!i?.coolingUntil&&t<i.coolingUntil,E=Fs(v?.weeklyResetAt,t),_=Fs(v?.sessionResetAt,t),C=_!==void 0,A=E!==void 0,k=v?C?v.sessionUsed??0:0:null,R=v?A?v.weeklyUsed??null:0:null,I=v?C?v.sessionStatus??"unknown":"allowed":null,P=v?A?v.weeklyStatus??"unknown":"allowed":null,O=oE(v,s),U=!O&&(I==="rejected"||I==="throttled"||P==="rejected"||P==="throttled"||v?.unifiedStatus?.trim().toLowerCase()==="rejected"||C&&(k??0)>=1||A&&(R??0)>=1),M=!U&&!O&&C&&(k??0)>=r,F=U||M,N=pde(v,o,t),L=N?Fs(N.resetsAt,t):void 0,q=L!==void 0,B=N?q?N.used:0:null,H=N?q?N.status??"unknown":"allowed":null,G=!d&&q&&(B??0)>=r;return{usable:!w&&!U&&(H!=="rejected"||O),saturated:F,scopedModel:N?.scopeModel??null,scopedStatus:H,scopedUsed:B,scopedReset:L??Number.POSITIVE_INFINITY,scopedUsedForSort:B??-1,scopedSaturated:G,hasQuota:!!a,quotaEvidenceRank:y==="fresh"||y==="stale_known"?0:y==="refresh_due"?1:2,quotaStale:d,quotaFreshness:y,refreshNeeded:y==="unknown"||y==="refresh_due",refreshReason:y==="unknown"?"startup_unknown":y==="refresh_due"?"ambiguous_snapshot":null,refreshInFlight:u.inFlight,lastRefreshAttemptAt:u.lastAttemptAt??null,lastRefreshSuccessAt:u.lastSuccessAt??null,nextRefreshEligibleAt:u.nextEligibleAt??null,saturationKind:U?"hard":M?"soft":"none",softLimitOverrideReason:O&&C&&(k??0)>=r?"overage":null,quotaLastUpdated:c,quotaAgeMs:l,coolingActive:w,coolingReason:i?.coolingReason??null,coolingUntil:i?.coolingUntil??0,unifiedStatus:v?.unifiedStatus??null,fallbackStatus:v?.fallbackStatus??null,upgradePaths:v?.upgradePaths??null,overageEligible:O,overageStatus:v?.overageStatus??null,sessionStatus:I,sessionUsed:k,sessionResetBucket:C?Math.floor(_/n):Number.POSITIVE_INFINITY,sessionReset:_??Number.POSITIVE_INFINITY,weeklyStatus:P,weeklyReset:E??Number.POSITIVE_INFINITY,weeklyUsed:R,weeklyUsedForSort:R??-1}}function kgr(e,t,r,n,o){return new Map(e.map(s=>[s.key,y3(s.key,t,r,n,o)]))}function A0n(e,t,r,n){for(const u of e){if(u.type!=="oauth")continue;const d=n?.get(u.key)??y3(u.key,Date.now(),r,rI());d.quotaFreshness==="unknown"?f3(u,`startup-unknown:${u.key}`).catch(m=>{p.debug(`[proxy] background quota discovery failed account=${u.label}: ${Ql(m)}`)}):d.quotaFreshness==="refresh_due"&&f3(u,`ambiguous:${d.quotaLastUpdated??0}`).catch(m=>{p.debug(`[proxy] ambiguous quota refresh failed account=${u.label}: ${Ql(m)}`)})}const o=t[0],s=t[1];if(!o||!s||s.type!=="oauth")return;const i=pc.get(o.key)?.quota;if(!i)return;const a=Math.max(0,r-.05);if(!((i.sessionUsed??0)>=a||(i.weeklyUsed??0)>=.9))return;const l=["handoff",o.key,i.sessionResetAt??0,i.weeklyResetAt??0,s.key].join(":");f3(s,l).catch(u=>{p.debug(`[proxy] quota handoff prewarm failed account=${s.label}: ${Ql(u)}`)})}function k0n(e,t,r,n){!t||t.type!=="oauth"||y3(t.key,Date.now(),n,rI()).quotaFreshness==="fresh"||f3(t,`hard-handoff:${e.key}:${r}:${t.key}`).catch(s=>{p.debug(`[proxy] hard-handoff quota refresh failed account=${t.label}: ${Ql(s)}`)})}function x0n(e){const{accounts:t,orderedAccounts:r,metricsByKey:n,evaluatedAt:o,strategy:s,primaryKey:i,quotaRoutingEnabled:a,quotaOrdered:c,sessionSoftLimit:l,sessionResetToleranceMs:u,rotationOffset:d}=e,m=new Map(t.map((w,E)=>[w.key,E])),h=!!i&&t.some(w=>w.key===i),f=[];for(const w of r){const E=n.get(w.key);if(!E){p.warn(`[proxy] routing evidence omitted because metrics are missing for account=${w.label}`);return}f.push({account:w.label,accountType:w.type,sourceIndex:m.get(w.key)??f.length,rank:f.length,configuredPrimary:!!i&&w.key===i,usable:E.usable,saturated:E.saturated,quotaObserved:E.hasQuota,quotaStale:E.quotaStale,quotaFreshness:E.quotaFreshness,refreshNeeded:E.refreshNeeded,refreshReason:E.refreshReason,refreshInFlight:E.refreshInFlight,lastRefreshAttemptAt:E.lastRefreshAttemptAt,lastRefreshSuccessAt:E.lastRefreshSuccessAt,nextRefreshEligibleAt:E.nextRefreshEligibleAt,saturationKind:E.saturationKind,softLimitOverrideReason:E.softLimitOverrideReason,quotaLastUpdated:E.quotaLastUpdated,quotaAgeMs:E.quotaAgeMs,coolingActive:E.coolingActive,coolingReason:E.coolingReason,coolingUntil:E.coolingUntil>0&&Number.isFinite(E.coolingUntil)?E.coolingUntil:null,unifiedStatus:E.unifiedStatus,fallbackStatus:E.fallbackStatus,upgradePaths:E.upgradePaths,overageEligible:E.overageEligible,overageStatus:E.overageStatus,sessionStatus:E.sessionStatus,sessionUsed:E.sessionUsed,sessionResetAt:Number.isFinite(E.sessionReset)?E.sessionReset:null,sessionResetBucket:Number.isFinite(E.sessionResetBucket)?E.sessionResetBucket:null,weeklyStatus:E.weeklyStatus,weeklyUsed:E.weeklyUsed,weeklyResetAt:Number.isFinite(E.weeklyReset)?E.weeklyReset:null,scopedModel:E.scopedModel,scopedStatus:E.scopedStatus,scopedUsed:E.scopedUsed,scopedResetAt:Number.isFinite(E.scopedReset)?E.scopedReset:null})}const g=r[0];let y,v;return r.length===1?(y="single_account",v="single_account"):c?(y="quota",v=e.policySelectionReason??Ypr(r[0],r[1],n,i)[1]):s==="round-robin"?(y="round_robin",v="round_robin"):(y="primary",v=e.policySelectionReason??(h&&g?.key===i?"configured_primary":"insertion_order")),{schemaVersion:1,evaluatedAt:new Date(o).toISOString(),strategy:s,mode:y,selectionReason:v,quotaRoutingEnabled:a,quotaInputsUsed:c,sessionSoftLimit:l,sessionResetToleranceMs:u,configuredPrimaryAccount:i??null,configuredPrimaryMatched:h,rotationOffset:d,initialAccount:g?.label??"",candidates:f,...e.policy?{policy:e.policy}:{},...e.affinity?{affinity:e.affinity}:{},...e.spill?{spill:e.spill}:{}}}var I0n=32,nI=new Set;function hde(e,t){const r=e instanceof Error?e.message:String(e),n=JSON.stringify([t,e instanceof Error?e.name:typeof e,r]);if(!nI.has(n)){if(nI.add(n),nI.size>I0n){const o=nI.values().next().value;o!==void 0&&nI.delete(o)}p.always(`[proxy] routing policy threw; falling back to ${t}: ${r}`)}}var R0n=!1,P0n=!1,M0n=!1;function O0n(e){const{enabledAccounts:t,accountStrategy:r,quotaRoutingEnabled:n,sessionSoftLimit:o,sessionResetToleranceMs:s,requestedModel:i,sessionId:a,ranking:c,preferPrimary:l,sessionAffinityEnabled:u,sessionAffinityIdleTtlMs:d,spillInflight:m,setRoutingDecision:h}=e,f=e.primaryAccountKey,g=f===void 0?void 0:t.find(N=>Xae(N.key,f))?.key??f;let y=[...t];const v=Date.now();let w,E=0;const _=r==="fill-first"&&y.length>1&&n,C=r==="fill-first"&&y.length>1,A=C?{ranking:c,preferPrimary:l,sessionAffinity:u,sessionAffinityIdleTtlMs:d,spillInflight:m}:void 0;let k,R,I;const P=()=>{if(!(!u||!a)){if(P0n)throw new Error("forced failure for affinity lookup throw test");return Ule.get(a,v,d)}},O=(N,L,q)=>({sessionBound:!!N,boundAccount:(N&&t.find(B=>B.key===N)?.label)??null,applied:L,skippedReason:u?a?N?L?null:q:"expired":"no_session":"disabled"}),U=N=>t.find(L=>L.key===N)?.label??N,M=(N,L,q)=>{if(R0n)throw new Error("forced failure for spill throw test");if(m<=0||L==="session_affinity")return;const B=new Map(N.map(X=>[X.key,r0n(X.key)])),H=tpn({orderedAccounts:N,inflightByKey:B,metricsByKey:q,spillInflight:m}),G=H.spill;if(G)return{orderedAccounts:H.orderedAccounts,spill:{from:U(G.from),to:U(G.to),inflight:G.inflight}}};if(!_&&r==="fill-first"&&l0n(t,g),_){w=kgr(t,v,o,s,i);try{const N=P(),L=Qpr({accounts:t,metricsByKey:w,primaryKey:g,ranking:c,affinityKey:N,preferPrimary:l}),q=M(L.orderedAccounts,L.reason,w),B=O(N,L.reason==="session_affinity",L.affinitySkippedReason);y=q?.orderedAccounts??L.orderedAccounts,k=q?"spill_inflight":L.reason,R=B,I=q?.spill}catch(N){hde(N,"expiry-first order"),y=Qpr({accounts:t,metricsByKey:w,primaryKey:g}).orderedAccounts,k="routing_policy_error"}p.shouldLog("debug")&&p.debug(`[proxy] quota-ordered fill sequence: ${y.map(N=>N.label).join(" \u2192 ")}`)}else{if(r==="round-robin"&&y.length!==cgr&&(oh=wgr(y,g),cgr=y.length),y.length>1&&(E=oh%y.length,r==="round-robin"&&(oh=(oh+1)%y.length),E>0)){const N=y.splice(0,E);y.push(...N)}if(w=kgr(t,v,o,s,i),C)try{const N=P(),L=Zpr({orderedAccounts:y,metricsByKey:w,affinityKey:N,primaryKey:g,preferPrimary:l}),q=M(L.orderedAccounts,L.reason,w),B=O(N,L.reason==="session_affinity",L.affinitySkippedReason);y=q?.orderedAccounts??L.orderedAccounts,k=q?"spill_inflight":L.reason??void 0,R=B,I=q?.spill}catch(N){hde(N,"pre-policy order"),k="routing_policy_error"}}const F=x0n({accounts:t,orderedAccounts:y,metricsByKey:w,evaluatedAt:v,strategy:r,primaryKey:g,quotaRoutingEnabled:n,quotaOrdered:_,sessionSoftLimit:o,sessionResetToleranceMs:s,rotationOffset:E,policySelectionReason:k,policy:A,affinity:R,spill:I});return F&&h(F),{orderedAccounts:y,metricsByKey:w}}function D0n(e){const t=Date.now();let r=e.servingAccountKey;try{if(M0n)throw new Error("forced failure for bind recheck throw test");const n=Ule.get(e.sessionId,t,e.idleTtlMs);n!==void 0&&!e.attemptedAccountKeys.has(n)&&e.enabledAccounts.some(o=>o.key===n)&&$le(y3(n,t,e.sessionSoftLimit,e.sessionResetToleranceMs,e.requestedModel))&&(r=n)}catch(n){hde(n,"serving-account binding")}Ule.bind(e.sessionId,r,t)}var v3=new Map,N0n=300*1e3,L0n=new Set(["accept","accept-encoding","accept-language","anthropic-beta","anthropic-dangerous-direct-browser-access","anthropic-version","sec-fetch-mode","user-agent","x-app","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout","x-subscription-tier"]),F0n=["oauth-2025-04-20","claude-code-20250219","fine-grained-tool-streaming-2025-05-14"];function T3(e){return e.replace(/[^a-zA-Z0-9._@-]/g,"_")}function xgr(e){return yt(wa(),".neurolink","header-snapshots",`anthropic_${T3(e)}.json`)}function $0n(e,t){if(t?.headers)for(const[r,n]of Object.entries(t.headers)){const o=r.toLowerCase();typeof n=="string"&&!e[o]&&!c3.has(o)&&o!=="authorization"&&o!=="x-api-key"&&o!=="x-claude-code-session-id"&&(e[o]=n)}}async function U0n(e){try{const t=T3(e),r=v3.get(t);if(r&&Date.now()-r.loadedAt<N0n)return r.snapshot;const n=xgr(e);try{await KM(n)}catch{return null}const o=JSON.parse(await Fr(n,"utf8"));if(!o||typeof o!="object")return null;const s={accountKey:"accountKey"in o&&typeof o.accountKey=="string"?o.accountKey:`anthropic:${e}`,capturedAt:"capturedAt"in o&&typeof o.capturedAt=="string"?o.capturedAt:new Date(0).toISOString(),source:"claude-code",headers:"headers"in o&&o.headers?o.headers:{},...o.body?{body:o.body}:{}};return Object.keys(s.headers).length===0&&Object.keys(s.body??{}).length===0?null:(v3.set(t,{snapshot:s,loadedAt:Date.now()}),s)}catch{return null}}function B0n(e,t){const r={...t??{}};for(const[n,o]of Object.entries(e)){const s=n.toLowerCase();typeof o=="string"&&L0n.has(s)&&!c3.has(s)&&s!=="authorization"&&s!=="x-api-key"&&s!=="x-claude-code-session-id"&&(r[s]=o)}return r}function Igr(e){if(!e||typeof e!="object")return;const t=e,r=nMt(t.metadata?.user_id),n=Array.isArray(t.system)?t.system:typeof t.system=="string"?[{type:"text",text:t.system}]:[],o=n.find(i=>typeof i?.text=="string"&&i.text.includes("x-anthropic-billing-header"))?.text,s=n.find(i=>typeof i?.text=="string"&&i.text.includes("Claude Agent SDK"))?.text;if(!(!r&&!o&&!s))return{...r?{metadataUserId:r.metadataUserId}:{},...r?{sessionId:r.sessionId}:{},...o?{billingHeader:o}:{},...s?{agentBlock:s}:{}}}function Rgr(e,t){return typeof e["x-claude-code-session-id"]=="string"||e["user-agent"]?.startsWith("claude-cli/")||!!t?.metadataUserId||!!t?.billingHeader||!!t?.agentBlock}function z0n(e,t){return e?JSON.stringify(e.headers??{})===JSON.stringify(t.headers??{})&&JSON.stringify(e.body??{})===JSON.stringify(t.body??{}):!1}async function q0n(e,t){const r=xgr(e);await Na(r,t,384),v3.set(T3(e),{snapshot:t,loadedAt:Date.now()})}async function G0n(e,t,r,n){const o=await U0n(e);let s;try{s=JSON.parse(n)}catch{return o}const i=Igr(s);if(!Rgr(r,i))return o;const a={accountKey:t,capturedAt:new Date().toISOString(),source:"claude-code",headers:B0n(r,o?.headers),body:{...o?.body??{},...i??{},...typeof r["x-claude-code-session-id"]=="string"?{sessionId:r["x-claude-code-session-id"]}:{}}};if(z0n(o,a))return o;try{await q0n(e,a)}catch(c){p.warn("[proxy] failed to persist Claude snapshot",{accountLabel:e,error:c instanceof Error?c.message:String(c)}),v3.set(T3(e),{snapshot:a,loadedAt:Date.now()})}return a}function fde(e){const t={};if(!e||typeof e!="object")return t;const r=e;if(typeof r.model=="string"&&(t.responseModel=r.model),typeof r.stop_reason=="string"&&(t.finishReason=r.stop_reason),typeof r.stop_sequence=="string"&&(t.stopSequence=r.stop_sequence),Array.isArray(r.content)){const n=r.content.filter(o=>!!o&&typeof o=="object"&&o.type==="tool_use").map(o=>String(o.name??"")).filter(o=>o.length>0);n.length>0&&(t.toolCalls=n)}return t}function Pgr(e){const t={};e.model&&(t.responseModel=e.model),e.stopReason&&(t.finishReason=e.stopReason),e.stopSequence&&(t.stopSequence=e.stopSequence);const r=(e.contentBlocks??[]).filter(n=>n.type==="tool_use").map(n=>String(n.toolName??"")).filter(n=>n.length>0);return r.length>0&&(t.toolCalls=r),t}function j0n(e,t,r,n,o){try{const s=JSON.parse(e),i={type:"text",text:r?.body?.agentBlock||"You are a Claude agent, built on Anthropic's Claude Agent SDK."};if(s.system){if(typeof s.system=="string"&&(s.system=[{type:"text",text:s.system}]),Array.isArray(s.system)){const l=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("x-anthropic-billing-header")),u=s.system.findIndex(h=>typeof h.text=="string"&&h.text.includes("Claude Agent SDK")),d={type:"text",text:SN(s.system[l]?.text??r?.body?.billingHeader)};if(n&&u>=0)l<0&&s.system.unshift(d);else{const h=[l,u].filter(f=>f>=0).sort((f,g)=>g-f);for(const f of h)s.system.splice(f,1);s.system.length>0&&EMt(s,s.system),s.system=[d,i]}}}else{const l={type:"text",text:SN(r?.body?.billingHeader)};s.system=[l,i]}const a=t.substring(0,Math.min(20,t.length)),c=oMt(a,{existingUserId:s.metadata?.user_id??r?.body?.metadataUserId,preferredSessionId:o??r?.body?.sessionId});return s.metadata={...s.metadata,user_id:c.metadataUserId},{bodyStr:JSON.stringify(s),sessionId:c.sessionId}}catch{return{bodyStr:e}}}async function H0n(e,t){if(!e.oauth?.accessToken)return;let r=e.oauth.accessToken,n=e.oauth.refreshToken,o=e.oauth.expiresAt;const s=e.email?.trim()||"legacy-default",i=o?o<Date.now():!1,a=()=>({key:Qk,label:s,token:r,refreshToken:n,expiresAt:o,type:"oauth",persistTarget:{credPath:t}});if(!i)return a();const c=$a(Qk);if(c.permanentlyDisabled)return;const l=(await kx())[Qk];if(l?.coolingUntil>Date.now()&&(!c.coolingUntil||l.coolingUntil>c.coolingUntil)&&(c.coolingUntil=l.coolingUntil,c.coolingReason=l.reason),c.coolingReason==="auth"&&c.coolingUntil&&c.coolingUntil>Date.now())return a();if(!n){p.always("[proxy] skipping legacy account (expired, no refresh token)"),await wm(a(),c,"missing_refresh_token");return}const u={token:r,refreshToken:n,expiresAt:o,label:s},d=await Lpr(u);if(!d.success){if(sy(d)){await wm(a(),c,"refresh_invalid");return}const m=await b3(a(),c);return p.always(`[proxy] legacy refresh temporarily unavailable (${d.status??"network"}); cooling until ${new Date(m).toISOString()}`),a()}return r=u.token,n=u.refreshToken,o=u.expiresAt,await N$(t,u),await _3(a(),c),p.always("[proxy] refreshed legacy account at startup"),a()}async function V0n(e){const{ctx:t,body:r,route:n,modelRouter:o,tracer:s,requestStartTime:i,logProxyBody:a}=e;s?.setMode("full");const c=L$(r),l=tE({provider:n.provider,model:n.model},o?.getFallbackChain()??[],r.model,c,o?.isAutoFallbackEnabled?.()??!1);Mgr(a,"translated_request",l);const u=l.attempts;if(r.stream)return r3({ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:u,tracer:s,requestStartTime:i});try{return await n3({ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:u,tracer:s,requestStartTime:i,terminalFailureStatus:502})}catch(d){const m=d instanceof Error?d.message:"unknown error";p.error(`[claude-proxy] Translated generation failed for ${r.model}: ${m}`);const h=$i(502,`Generation failed: ${m}`),f=JSON.stringify(h);return a({phase:"client_response",headers:{"content-type":"application/json"},body:f,bodySize:Buffer.byteLength(f,"utf8"),contentType:"application/json",account:"translation",accountType:"translation",responseStatus:502,durationMs:Date.now()-i}),h}}function Mgr(e,t,r){e({phase:"routing_decision",contentType:"application/json",body:{stage:t,attempts:r.attempts}})}async function W0n(e){const{ctx:t,body:r,clientRequestBody:n,tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:a}=e;o?.setMode("passthrough-cli");const{bodyStr:c,preparedContext:l}=hgr(t,n),u=Array.isArray(r.tools)?r.tools.length:0,d={};for(const[g,y]of Object.entries(t.headers))!c3.has(g.toLowerCase())&&y&&(d[g]=y);d["content-type"]||(d["content-type"]="application/json");const m=o?.startUpstreamAttempt({account:"passthrough",attempt:1,polyfillHeaders:!1,polyfillBody:!1,upstreamUrl:"https://api.anthropic.com/v1/messages?beta=true"});let h;try{h=await Zue("https://api.anthropic.com/v1/messages?beta=true",{method:"POST",headers:d,body:c,signal:AbortSignal.any([...t.abortSignal?[t.abortSignal]:[],AbortSignal.timeout(Xx)])},t,"anthropic:passthrough",{logProxyBody:i,tracer:o,attemptNumber:1,accountLabel:"passthrough",accountType:"passthrough",preparedContext:l})}catch(g){if(g instanceof _r||el(g)||t.abortSignal?.aborted)throw m?.end(),g;const y=g instanceof Error?g.message:String(g);Pr("passthrough","passthrough",502),o?.setError("network_error",y),m?.end(),o?.end(502,Date.now()-s),a(502,"passthrough","passthrough","network_error",y);const v=$i(502,`Passthrough fetch failed: ${y}`),w=JSON.stringify(v);return i({phase:"client_response",headers:{"content-type":"application/json"},body:w,bodySize:Buffer.byteLength(w,"utf8"),contentType:"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:502,durationMs:Date.now()-s}),v}const f={};h.headers.forEach((g,y)=>{f[y]=g}),o?.logUpstreamResponseHeaders(f);{const g=Mw(h.headers,{model:r.model});eI(t,{upstreamHeaders:h.headers,quota:g,source:g?"live":"none",accountType:"passthrough",servedBy:"anthropic",attempt:1})}if(!h.ok){const g=await h.text();Pr("passthrough","passthrough",h.status,h.status===429?"quota":void 0),o?.logUpstreamResponseBody(g),i({phase:"upstream_response",headers:f,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:f["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:h.status,durationMs:Date.now()-s}),i({phase:"client_response",headers:f,body:g,bodySize:Buffer.byteLength(g,"utf8"),contentType:f["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:h.status,durationMs:Date.now()-s}),m?.end(),o?.setError("api_error",g.slice(0,500)),o?.end(h.status,Date.now()-s),a(h.status,"passthrough","passthrough",h.status===429?"rate_limit_error":"api_error",g);try{return JSON.parse(g)}catch{return $i(h.status,g)}}return r.stream&&h.body?J0n({ctx:t,body:r,bodyStr:c,response:h,tracer:o,requestStartTime:s,toolCount:u,upstreamSpan:m,upstreamResponseHeaders:f,logProxyBody:i,logFinalRequest:a}):Y0n({ctx:t,body:r,bodyStr:c,response:h,tracer:o,requestStartTime:s,toolCount:u,upstreamSpan:m,upstreamResponseHeaders:f,logProxyBody:i,logFinalRequest:a})}function K0n(e){const t=e.getReader(),r=Xfr();let n=!1;return{stream:new ReadableStream({async pull(s){if(!n)try{const{done:i,value:a}=await t.read();if(n)return;if(i){n=!0,r.complete(),s.close();return}s.enqueue(a)}catch(i){n=!0;const a=i instanceof Error?i.message:String(i);r.fail(a),s.error(i)}},cancel(s){return n=!0,r.cancel(),t.cancel(s)}}),outcome:r.outcome}}async function J0n(e){const{ctx:t,bodyStr:r,response:n,tracer:o,requestStartTime:s,upstreamSpan:i,upstreamResponseHeaders:a,logProxyBody:c,logFinalRequest:l}=e,u={...a},{stream:d,capture:m}=Pue(),h=n.body;if(!h)throw Pr("passthrough","passthrough",502),new Error("Expected passthrough stream response body");const f=K0n(h);let g=f.stream,y=!1,v;const w=(_,C,A,k)=>y?!1:(y=!0,C==="stream_error"&&Pr("passthrough","passthrough",_),l(_,"passthrough","passthrough",C,A,k),!0);if(o)try{const{stream:_,telemetry:C}=U$({captureRawText:!0});g=g.pipeThrough(_);const A=o,k=i,R=n,I=r.length;v=Promise.all([C,m,f.outcome]).then(([P,O,U])=>{const M=i3(U,P.streamErrorMessage,P.messageStopReceived);x$(t.metadata,P);const F=sh(M);A.setUsage({inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),A.logStreamEvents(P.events),A.setResponseInfo(Pgr(P));const N=parseFloat(R.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),L=parseFloat(R.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),q={inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens};isNaN(N)||(q.rateLimitAfter5h=N),isNaN(L)||(q.rateLimitAfter7d=L),(!isNaN(N)||!isNaN(L))&&A.setUsage(q),A.logUpstreamResponseBody(P.rawText??""),A.recordMetrics(),A.recordBodySizes(I,P.totalBytesReceived),k?.end(),F&&A.setError(F.errorType,F.message),A.end(F?.status??n.status,Date.now()-s),w(F?.status??n.status,F?.errorType,F?.message,{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,cacheCreationTokens:P.usage.cacheCreationInputTokens,cacheReadTokens:P.usage.cacheReadInputTokens}),c({phase:"upstream_response",headers:u,body:P.rawText??"",sourceTruncated:P.rawTextTruncated,bodySize:P.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s}),c({phase:"client_response",headers:u,body:O.text,sourceTruncated:O.truncated,bodySize:O.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:200,durationMs:Date.now()-s})}).catch(P=>{if(y)return;const O=P instanceof Error?P.message:String(P);A.setError("stream_telemetry_error",O),k?.end(),A.end(500,Date.now()-s),w(500,"stream_telemetry_error",O)})}catch{v=f.outcome.then(_=>{const C=sh(_);i?.end(),C&&o.setError(C.errorType,C.message),o.end(C?.status??n.status,Date.now()-s),w(C?.status??n.status,C?.errorType,C?.message)})}else try{const{stream:_,telemetry:C}=U$({captureRawText:!0});g=g.pipeThrough(_),v=Promise.all([C,m,f.outcome]).then(([A,k,R])=>{const I=i3(R,A.streamErrorMessage,A.messageStopReceived);x$(t.metadata,A);const P=sh(I);w(P?.status??n.status,P?.errorType,P?.message,{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens,cacheCreationTokens:A.usage.cacheCreationInputTokens,cacheReadTokens:A.usage.cacheReadInputTokens}),c({phase:"upstream_response",headers:u,body:A.rawText??"",sourceTruncated:A.rawTextTruncated,bodySize:A.totalBytesReceived,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s}),c({phase:"client_response",headers:u,body:k.text,sourceTruncated:k.truncated,bodySize:k.totalBytes,contentType:u["content-type"]??"text/event-stream",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s})}).catch(A=>{y||w(500,"stream_telemetry_error",A instanceof Error?A.message:String(A))})}catch{v=f.outcome.then(_=>{const C=sh(_);w(C?.status??n.status,C?.errorType,C?.message)})}const E=g.pipeThrough(d);return $w(t.metadata,{onTerminal:()=>v}),new Response(E,{status:n.status,headers:{...u,...t.responseHeaders??{}}})}async function Y0n(e){const{ctx:t,bodyStr:r,response:n,tracer:o,requestStartTime:s,upstreamSpan:i,upstreamResponseHeaders:a,logProxyBody:c,logFinalRequest:l}=e,u=await n.text();o?.logUpstreamResponseBody(u),c({phase:"upstream_response",headers:a,body:u,bodySize:Buffer.byteLength(u,"utf8"),contentType:a["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s}),c({phase:"client_response",headers:a,body:u,bodySize:Buffer.byteLength(u,"utf8"),contentType:a["content-type"]??"application/json",account:"passthrough",accountType:"passthrough",attempt:1,responseStatus:n.status,durationMs:Date.now()-s});const d=JSON.parse(u);if(k$(t.metadata,d),o&&d&&typeof d=="object"){const m=d.usage;if(m){o.setUsage({inputTokens:m.input_tokens??0,outputTokens:m.output_tokens??0,cacheCreationTokens:m.cache_creation_input_tokens??0,cacheReadTokens:m.cache_read_input_tokens??0});const f=parseFloat(n.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),g=parseFloat(n.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(f)||!isNaN(g)){const y={inputTokens:m.input_tokens??0,outputTokens:m.output_tokens??0,cacheCreationTokens:m.cache_creation_input_tokens??0,cacheReadTokens:m.cache_read_input_tokens??0};isNaN(f)||(y.rateLimitAfter5h=f),isNaN(g)||(y.rateLimitAfter7d=g),o.setUsage(y)}}o.setResponseInfo(fde(d)),o.recordMetrics();const h=JSON.stringify(d);o.recordBodySizes(r.length,h.length),i?.end(),o.end(n.status,Date.now()-s),l(n.status,"passthrough","passthrough",void 0,void 0,{inputTokens:m?.input_tokens,outputTokens:m?.output_tokens,cacheCreationTokens:m?.cache_creation_input_tokens,cacheReadTokens:m?.cache_read_input_tokens})}else i?.end(),o?.end(n.status,Date.now()-s),l(n.status,"passthrough","passthrough");return d}async function X0n(e){const t=Hw();if(!t)return{accounts:e.accounts};if(e.accounts.length===0)return{accounts:e.accounts};const r=Date.now(),n=await Promise.all(e.accounts.map(async d=>{const m=$a(d.key).quota,h=Fs(m?.sessionResetAt,r)??null,f=Fs(m?.weeklyResetAt,r)??null,g=await vce(t.grantId,d.key,h,f);return{accountKey:d.key,sessionUsed:m?.sessionUsed??null,weeklyUsed:m?.weeklyUsed??null,sessionResetAt:h,weeklyResetAt:f,borrowedSessionFraction:g.sessionFraction,borrowedWeeklyFraction:g.weeklyFraction}})),o=await mce(t.grantId);if(!o)return{accounts:e.accounts};const s=await Tce(t.grantId,Fue(o.gates,n).inScope),i=$ue(o,n,r,s),a=new Set(i.allowed),c=e.accounts.filter(d=>a.has(d.key));if(c.length>0)return{accounts:c};const l=Uue(i.excluded),u=Xw(l,{status:Jgn(l),grant:o,retryAfterSeconds:Dgr(n,r)});return p.always(`[proxy] share ${t.peerLabel} withheld: ${l} (${i.excluded.length} accounts)`),{accounts:[],refusal:{status:u.status,message:u.body.error.message,errorType:u.body.error.type,responseHeaders:u.headers}}}async function Z0n(e){const t=[],r=[];for(const n of e){const o=await $gn(n.key);if(!o){t.push(n);continue}if(!kgn(o)){t.push(n);continue}p.always(`[proxy] withholding leased account=${n.label}: ${o.reason}`),r.push({label:n.label,reason:o.reason})}return{accounts:t,withheld:r}}async function Q0n(e,t){const r=[],n=[],o=Date.now();for(const s of e){const i=await Lue(s.key);if(!i){r.push(s);continue}const a=i.lease.gates;if(!Xgn(a.models,t)){p.always(`[proxy] leased account=${s.label} does not cover model ${lr(t??"unknown")}`),n.push({label:s.label,reason:"model_not_allowed"});continue}if(a.schedule&&!Ygn(a.schedule,o)){p.always(`[proxy] leased account=${s.label} is outside its allowed hours`),n.push({label:s.label,reason:"out_of_window"});continue}const c=$a(s.key).quota,l=Fs(c?.sessionResetAt,o)??null,u=Fs(c?.weeklyResetAt,o)??null,d=await vce(i.grantId,s.key,l,u),m={accountKey:s.key,sessionUsed:c?.sessionUsed??null,weeklyUsed:c?.weeklyUsed??null,sessionResetAt:l,weeklyResetAt:u,borrowedSessionFraction:d.sessionFraction,borrowedWeeklyFraction:d.weeklyFraction},h=await Tce(i.grantId,[m]),{accounts:f,...g}=a,y=$ue(evn(i,g),[m],o,h);if(y.allowed.length===0){const v=Uue(y.excluded);p.always(`[proxy] withholding leased account=${s.label}: ${v}`),n.push({label:s.label,reason:v});continue}r.push(s)}return{accounts:r,withheld:n}}function evn(e,t){const r=e.lease.entitlementSnapshot;return{schemaVersion:1,id:e.grantId,peerLabel:e.lease.peerLabel,tokenHash:"",tokenSalt:"",level:"complete",state:"active",entitlement:r==="unlimited"?{ledger:"unlimited"}:{ledger:"coins",coins:r},gates:t,createdAt:e.lease.issuedAt,updatedAt:e.lease.issuedAt}}function tvn(e,t,r){const n=Date.now(),o=i=>{fan({grantId:i,accountKey:e,sessionBefore:t?.sessionUsed??null,sessionAfter:r.sessionUsed,sessionResetAt:Fs(r.sessionResetAt,n)??null,weeklyBefore:t?.weeklyUsed??null,weeklyAfter:r.weeklyUsed,weeklyResetAt:Fs(r.weeklyResetAt,n)??null})},s=Hw();if(s){o(s.grantId);return}Lue(e).then(i=>{i&&o(i.grantId)}).catch(()=>{})}function gde(e,t,r){const n=yce({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},t);Ugn(e,n).catch(()=>{})}function Ogr(e,t){if(!t||typeof t!="object")return;const r=t.usage;if(!r)return;const n=cvn(t),o={inputTokens:r.input_tokens??0,outputTokens:r.output_tokens??0,cacheCreationTokens:r.cache_creation_input_tokens??0,cacheReadTokens:r.cache_read_input_tokens??0};yde(e.key,n,o),gde(e.label,n,o)}function yde(e,t,r){const n=Hw();n&&gan({grantId:n.grantId,accountKey:e,model:t??n.model,usage:{inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,...r.cacheCreationTokens!==void 0?{cacheCreationTokens:r.cacheCreationTokens}:{},...r.cacheReadTokens!==void 0?{cacheReadTokens:r.cacheReadTokens}:{}},...n.holdId?{holdId:n.holdId}:{}})}function vde(e){if(!Hw())return e;const t={};for(const[r,n]of Object.entries(e)){const o=r.toLowerCase();o==="x-neurolink-account"||o==="x-neurolink-account-type"||o.startsWith("x-neurolink-pool-")||(t[r]=n)}return t}async function rvn(e,t){const r=e.provisionedAccount;if(!r)return{paused:!1,detail:"no provisioned account recorded"};const n=pc.get(`anthropic:${r}`),o=dar(r,"oauth"),{verdict:s,shouldPause:i}=await gyn({grantId:e.id,accountLabel:r,lenderRequestsTotal:o?.successCount??0,observation:{at:Date.now(),sessionUsed:n?.quota?.sessionUsed??null,weeklyUsed:n?.quota?.weeklyUsed??null,reportedCoins:t,lenderRequests:0}});return i?(await ean(e.id,"paused"),{paused:!0,detail:s.drifted?s.detail:"repeated unexplained usage"}):{paused:!1,detail:s.drifted?s.detail:"consistent"}}async function nvn(e,t){await _ar(e.id,t)}function ovn(e,t){if(e.length!==t.length||e.length===0)return!1;let r=0;for(let n=0;n<e.length;n+=1)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}var svn=1,ivn=["live","complete","handshake","limits"];async function avn(e,t){const r=Date.now(),n=await $pr(t),o=await Promise.all(n.map(async l=>{const u=$a(l.key).quota,d=Fs(u?.sessionResetAt,r)??null,m=Fs(u?.weeklyResetAt,r)??null,h=await vce(e.id,l.key,d,m);return{accountKey:l.key,sessionUsed:u?.sessionUsed??null,weeklyUsed:u?.weeklyUsed??null,sessionResetAt:d,weeklyResetAt:m,borrowedSessionFraction:h.sessionFraction,borrowedWeeklyFraction:h.weeklyFraction}})),s=Fue(e.gates,o).inScope,i=await Tce(e.id,s),a=$ue(e,o,r,i),c=(l,u)=>l===void 0?null:Math.max(0,l-u*100);return{grantState:e.state,level:e.level,ledger:e.entitlement.ledger,...e.entitlement.ledger==="coins"?{remainingCoins:Math.max(0,Math.floor(man(e)))}:{},servable:a.allowed.length>0,...a.allowed.length===0&&a.excluded.length>0?{withheldReason:Uue(a.excluded)}:{},sliceLeftPct:{session:c(e.gates.maxSlice?.session5hPct,i.sessionFraction),weekly:c(e.gates.maxSlice?.weekly7dPct,i.weeklyFraction)},...a.allowed.length===0?(()=>{const l=Dgr(o,r);return l===void 0?{}:{retryAfterSeconds:l}})():{}}}function py(e){return!e.ok}async function hy(e){const t=nyn(e);if(!t)return{ok:!1,body:Xw("missing_token",{status:401}).body};const r=await ran(t);return r?{ok:!0,grant:r}:{ok:!1,body:Xw("unknown_token",{status:401}).body}}function cvn(e){if(!e||typeof e!="object")return;const t=e.model;return typeof t=="string"?t:void 0}function Dgr(e,t){const r=e.flatMap(n=>[n.sessionResetAt,n.weeklyResetAt]).filter(n=>n!==null&&n>t);if(r.length!==0)return Math.max(1,Math.round((Math.min(...r)-t)/1e3))}async function lvn(e){const{ctx:t,body:r,accountStrategy:n,primaryAccountKey:o,accountAllowlist:s,quotaRoutingEnabled:i=lde(),sessionSoftLimit:a=ude(),sessionResetToleranceMs:c=rI(),ranking:l="expiry-first",preferPrimary:u=!1,sessionAffinityEnabled:d=!1,sessionAffinityIdleTtlMs:m=36e5,spillInflight:h=0,setRoutingDecision:f}=e,g=await Promise.resolve().then(()=>(on(),mu)),y=await Promise.resolve().then(()=>(Ri(),cW)),v=[],w=`${y.homedir()}/.neurolink/anthropic-credentials.json`,{tokenStore:E}=await Promise.resolve().then(()=>(Xg(),ece)),_=await kx();Tgr||(rde??=E.pruneExpired().then(()=>{Tgr=!0}).finally(()=>{rde=void 0}),await rde);const C=await E.getProviderSnapshot(),A=Object.keys(C).filter(le=>le.startsWith("anthropic:")),k=[];let R=0,I=0;for(const le of A){if(!Zae(le,s)){p.debug(`[proxy] skipping account=${le} (not in account allowlist)`);continue}if(C[le].disabled){const Ie=$a(le),ve=C[le].disabledReason;if(ve==="refresh_failed")await E.markEnabled(le),p.always(`[proxy] account=${le.split(":")[1]??le} re-enabled for legacy refresh failure recheck`),Ie.permanentlyDisabled=!1,Ie.consecutiveRefreshFailures=0;else{const V=le.split(":")[1]??le;if(Ie.permanentlyDisabled)p.debug(`[proxy] skipping disabled account=${V}`);else{const se=C[le].disabledAt;p.always(`[proxy] account=${V} is disabled in the token store (reason=${ve??"unknown"}${se?`, since ${new Date(se).toISOString()}`:""}); left out of the pool. Re-enable with: neurolink auth enable ${le}`)}Ie.permanentlyDisabled=!0,ve==="entitlement_blocked"&&k.push(le.split(":")[1]??le),R+=1;continue}}const ae=C[le].tokens;if(!ae){I+=1;continue}let Pe=ae.accessToken,ke=ae.refreshToken,Te=ae.expiresAt;const he=le.split(":")[1]??le,Oe=ae.tokenType==="Bearer"?"oauth":"api_key",De=$a(le),Ye=_[le];Ye?.coolingUntil>Date.now()&&(!De.coolingUntil||Ye.coolingUntil>De.coolingUntil)&&(De.coolingUntil=Ye.coolingUntil,De.coolingReason=Ye.reason);const gt=()=>{v.push({key:le,label:he,token:Pe,refreshToken:ke,expiresAt:Te,type:Oe,persistTarget:{providerKey:le}})};if(Te?Te<Date.now():!1){if(De.permanentlyDisabled)continue;if(De.coolingReason==="auth"&&De.coolingUntil&&De.coolingUntil>Date.now()){gt();continue}if(!ke){p.always(`[proxy] skipping account=${he} (expired, no refresh token)`),await wm({key:le,label:he,token:Pe,type:"oauth"},De,"missing_refresh_token");continue}const Ie={token:Pe,refreshToken:ke,expiresAt:Te,label:he},ve=await D$(Ie,{providerKey:le});if(!ve.success){const J={key:le,label:he,token:Pe,type:"oauth"};if(sy(ve))p.always(`[proxy] skipping account=${he} (refresh token rejected: ${ve.error?.slice(0,200)??"unknown"})`),await wm(J,De,"refresh_invalid");else{const V=await b3(J,De);p.always(`[proxy] account=${he} refresh temporarily unavailable (${ve.status??"network"}); cooling until ${new Date(V).toISOString()} and rotating`),gt()}continue}Pe=Ie.token,ke=Ie.refreshToken,Te=Ie.expiresAt,await E.saveTokens(le,{accessToken:Pe,refreshToken:ke,expiresAt:Te??Date.now()+36e5,tokenType:"Bearer"}),p.always(`[proxy] refreshed expired account=${le.split(":")[1]??le} at startup`),await _3({key:le},De)}gt()}if(v.length===0&&ear(A.length,Qk,s))try{const le=JSON.parse(g.readFileSync(w,"utf8")),ae=await H0n(le,w);ae&&v.push(ae)}catch{}if(process.env.ANTHROPIC_API_KEY&&v.length===0&&ear(A.length,Qae,s)&&v.push({key:Qae,label:"env",token:process.env.ANTHROPIC_API_KEY,type:"api_key"}),v.length===0)return k.length>0&&k.length===R&&I===0?{failure:{status:403,message:Ugr({status:403,accounts:k,message:"OAuth authentication is not allowed for this organization.",errorCode:"oauth_not_allowed_for_organization"}),errorType:"permission_error"}}:{failure:{status:401,message:s?"No allowed Anthropic credentials are currently available":A.length>0?"Configured Anthropic accounts are disabled or unavailable":"No Anthropic credentials found",errorType:"authentication_error"}};for(const le of v)Dvn(le);await g0n(v);const P=v.filter(le=>!$a(le.key).permanentlyDisabled),O=await Z0n(P),U=await Q0n(O.accounts,typeof r.model=="string"?r.model:void 0),M={accounts:U.accounts,withheld:[...O.withheld,...U.withheld]},F=M.accounts;if(F.length===0&&M.withheld.length>0){const le=M.withheld.map(ke=>`${ke.label} (${ke.reason})`).join(", ");return{failure:{status:403,message:M.withheld.every(ke=>ke.reason==="model_not_allowed")?`Borrowed account(s) do not cover the requested model: ${le}. Ask the lender to widen the share, or use a model it allows.`:`Borrowed account(s) are no longer covered by a lease: ${le}. Run 'neurolink proxy peer sync' to check in with the lender, or ask them to resume the share.`,errorType:"permission_error"}}}const N=await X0n({accounts:F});if(N.refusal)return{failure:N.refusal};const L=N.accounts;if(L.length===0)return{failure:{status:401,message:C3(v.map(ae=>ae.label)),errorType:"authentication_error"}};const q=t.headers??{},B=Igr(r),{orderedAccounts:H,metricsByKey:G}=O0n({enabledAccounts:L,accountStrategy:n,primaryAccountKey:o,quotaRoutingEnabled:i,sessionSoftLimit:a,sessionResetToleranceMs:c,requestedModel:typeof r.model=="string"?r.model:void 0,sessionId:B?.sessionId,ranking:l,preferPrimary:u,sessionAffinityEnabled:d,sessionAffinityIdleTtlMs:m,spillInflight:h,setRoutingDecision:f});n==="fill-first"&&i&&L.length>1&&A0n(L,H,a,G);const X=Bvn(r),ce=JSON.stringify(X),Q=Date.now(),Ae=Array.isArray(r.tools)?r.tools.length:0;return{accounts:v,enabledAccounts:L,orderedAccounts:H,bodyStr:ce,requestStart:Q,toolCount:Ae,url:"https://api.anthropic.com/v1/messages?beta=true",clientHeaders:q,isClaudeClientRequest:Rgr(q,B),sessionId:B?.sessionId}}function uvn(e,t){const r=t==="vertex"?e.vertexFallbackModel:e.codexFallbackModel;return typeof r=="string"&&r.length>0?r:void 0}function w3(e){for(const t of["codexFallbackAccount","codexFallbackAccountType","codexFallbackModel","vertexFallbackModel","codexFallbackFailureUsage","codexFallbackDeferredFailure","sdkFallbackFailure"])delete e.metadata[t]}async function dvn(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,options:s,providerLabel:i,idleTimeoutMs:a=Yyn}=e;w3(t);const c=L$(r),l=typeof s.provider=="string"?s.provider:void 0,u=typeof s.model=="string"?s.model:void 0,d={ctx:t,format:"claude",requestModel:r.model,parsed:c,attempts:[{provider:l,model:u,label:i}],tracer:n,requestStartTime:o,options:s,attemptTimeoutMs:a};return r.stream?r3({...d,prefetchFirstOutput:!0}):n3({...d,deferFinalOnError:!0})}async function Ngr(e){let t;for(let r=0;r<=Yue;r+=1)try{return await dvn(e)}catch(n){if(t=n,iy(n)?.retryable===!1||!bde(n)||r===Yue)throw n;const o=Jue[r]??250;p.always(`[proxy] retrying fallback=${e.providerLabel} after transient network error (${r+1}/${Yue}) in ${o}ms: ${sE(Ql(n))}`),await Zl(o)}throw t}async function mvn(e){const{ctx:t,body:r,model:n,reasoningEffort:o,tracer:s,requestStartTime:i,logProxyBody:a,logFinalRequest:c}=e;w3(t);const l={...t,requestId:`${t.requestId}:codex-fallback`,method:"POST",path:"/backend-api/codex/responses",headers:{...t.headers,"content-type":"application/json",accept:"text/event-stream"},query:{},params:{},body:Dpn(r,n,o),metadata:{...t.metadata,"neurolink.codexFallback":!0},responseHeaders:{}},u=await ogr(l),d=bhn(l.metadata);let m=()=>{};const h=new Promise(k=>{m=k}),f=Chn(u,m,{onTerminal:k=>Promise.allSettled(d.map(async R=>R.onTerminal?.(k)))});$w(t.metadata,{onTerminal:()=>h});const g=(k,R=!0)=>{if(t.metadata.codexFallbackModel=n,!!R)try{s?.setModelSubstitution(r.model,n,"openai"),s?.setServedAccount(y["x-neurolink-account"]??"unknown","codex-oauth"),k?.usage?.inputTokensObserved&&k.usage.outputTokensObserved&&s?.setUsage({inputTokens:k.usage.input,outputTokens:k.usage.output,cacheReadTokens:k.usage.cacheReadTokens??0,cacheCreationTokens:k.usage.cacheCreationTokens??0,cacheReadTokensObserved:k.usage.cacheReadTokensObserved===!0,cacheCreationTokensObserved:k.usage.cacheCreationTokensObserved===!0,reasoningTokens:k.usage.reasoning},{recordMetrics:!1})}catch{}},y={...l.responseHeaders??{}};if(t.metadata.codexFallbackAccount=y["x-neurolink-account"],t.metadata.codexFallbackAccountType=y["x-neurolink-account-type"]??"codex-oauth",r.stream){const k=await Upn(f,r.model);t.responseHeaders??={},Object.assign(t.responseHeaders,vde(y));const R=y["x-neurolink-account"]??"",I=y["x-neurolink-account-type"]??"codex-oauth";let P=!1,O="",U=0,M=!1;const F=(B,H,G,X,ce)=>{P||(P=!0,t.abortSignal?.removeEventListener("abort",N),B>=400&&(t.metadata.terminalErrorType=G),g(H),s?.end(B,Date.now()-i),c(B,R,I,G,X,{inputTokens:H?.usage?.inputTokensObserved?H.usage.input:void 0,outputTokens:H?.usage?.outputTokensObserved?H.usage.output:void 0,cacheCreationTokens:H?.usage?.cacheCreationTokensObserved?H.usage.cacheCreationTokens:void 0,cacheReadTokens:H?.usage?.cacheReadTokensObserved?H.usage.cacheReadTokens:void 0,cacheReadTokensObserved:H?.usage?.cacheReadTokensObserved===!0,cacheCreationTokensObserved:H?.usage?.cacheCreationTokensObserved===!0,reasoningTokens:H?.usage?.reasoning,errorCode:ce?.code,retryable:ce?.retryable}),Yw({provider:"codex",model:n,status:B<400?"success":"failure",durationMs:Date.now()-i,...X?{errorMessage:X}:{}}),a({phase:"client_response",contentType:"text/event-stream",body:O,bodySize:U,sourceTruncated:M,responseStatus:B,durationMs:Date.now()-i}))},N=()=>{F(499,void 0,"client_cancelled","Client cancelled Codex fallback stream"),k.cancel()};t.abortSignal?.addEventListener("abort",N,{once:!0}),$w(t.metadata,{onTerminal:({outcome:B})=>{B==="client_cancelled"?N():B==="stream_error"&&(F(502,void 0,"stream_error","Codex fallback stream failed"),k.cancel())}});const L=B=>(U+=Buffer.byteLength(B),O.length+B.length>1024*1024&&(M=!0),O.length<1024*1024&&(O+=B.slice(0,1024*1024-O.length)),B);async function*q(){try{if(t.abortSignal?.aborted){N();return}let B=k.frames.next();for(;!P;){let H;const G=new Promise(Q=>{H=setTimeout(()=>Q(null),15e3),H.unref()});let X;try{X=await Promise.race([B,G])}finally{clearTimeout(H)}if(P)return;if(X===null){yield L(qle.pingEvent());continue}if(X.done===!0){F(200,X.value);return}const ce=L(X.value);if(ce.startsWith(`event: content_block_delta
|
|
2361
2361
|
`)&&/"(?:text|partial_json)":"(?:[^"\\]|\\.)+"/.test(ce)&&(t.metadata.firstUsefulOutputAt??=Date.now()),ce.startsWith(`event: message_stop
|
|
2362
2362
|
`)){const Q=await k.frames.next();if(Q.done!==!0)throw new Error("Codex fallback emitted output after message_stop");if(P)return;F(200,Q.value),yield ce;return}yield ce,B=k.frames.next()}}catch(B){if(!P){const H=sE(Ql(B));p.always(`[proxy] Codex fallback stream failed: ${H}`);const G=B instanceof Nw?B:void 0,X=G?.status??502,ce=$i(X,H);Object.assign(ce.error,{code:G?.code,retryable:G?.retryable});const Q=[L(`event: error
|
|
2363
2363
|
data: ${JSON.stringify(ce)}
|
|
@@ -2365,7 +2365,7 @@ data: ${JSON.stringify(ce)}
|
|
|
2365
2365
|
`)];F(X,G?.usage?{text:"",toolCalls:[],finishReason:"end_turn",usage:G.usage}:void 0,"stream_error",H,G),yield*Q}}finally{t.abortSignal?.removeEventListener("abort",N),P||N(),await k.cancel(),await k.frames.return({text:"",toolCalls:[],finishReason:"end_turn"}).catch(()=>{})}}return q()}let v;try{v=await $pn(f)}catch(k){throw t.metadata.codexFallbackModel=n,t.metadata.codexFallbackDeferredFailure=!0,k instanceof q$&&p.always(`[proxy] Codex fallback returned ${k.status}: ${lr(k.responseBody,500)}`),k instanceof Nw&&(g(k.usage?{text:"",toolCalls:[],finishReason:"end_turn",usage:k.usage}:void 0,!1),t.metadata.codexFallbackFailureUsage=k.usage),k}Object.keys(y).length>0&&(t.responseHeaders??={},Object.assign(t.responseHeaders,vde(y)));const w=y["x-neurolink-account"]??"",E=y["x-neurolink-account-type"]??"codex-oauth",_={content:v.text,model:r.model,finishReason:v.finishReason,...v.usage?{usage:v.usage}:{},toolCalls:v.toolCalls};g(v),s?.end(200,Date.now()-i);const C=shr(_,r.model);k$(t.metadata,C),c(200,w,E,void 0,void 0,{inputTokens:v.usage?.inputTokensObserved?v.usage.input:void 0,outputTokens:v.usage?.outputTokensObserved?v.usage.output:void 0,cacheCreationTokens:v.usage?.cacheCreationTokens,cacheReadTokens:v.usage?.cacheReadTokens,reasoningTokens:v.usage?.reasoning});const A=JSON.stringify(C);return a({phase:"client_response",headers:{"content-type":"application/json"},body:A,bodySize:Buffer.byteLength(A,"utf8"),contentType:"application/json",responseStatus:200,durationMs:Date.now()-i}),C}async function Lgr(e){if(Hw())return null;const t=await wgn();if(t.length===0)return null;const r=e.body.stream===!0,n=JSON.stringify(e.body);for(const o of t){p.always(`[proxy] local pool spent \u2014 trying peer=${o.name}`);const s=await Hgn({peer:o,body:n,stream:r});if(s.ok)return p.always(`[proxy] served by peer=${o.name}`),e.logFinalRequest(s.response.status,`peer:${o.name}`,"peer"),r?new Response(s.response.body,{status:s.response.status,headers:{"content-type":s.response.headers.get("content-type")??"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}}):await s.response.json().catch(()=>null)??null}return null}function pvn(e){return!(e instanceof q$)||e.status!==400?null:{status:e.status,body:e.responseBody,contentType:"application/json"}}async function Fgr(e){const{ctx:t,body:r,parsedFallbackRequest:n,fallbackPlan:o,modelRouter:s,tracer:i,requestStartTime:a,logProxyBody:c,logFinalRequest:l}=e,u=o??tE({provider:"anthropic",model:r.model},s?.getFallbackChain()??[],r.model,n);t.metadata.fallbackPlan=u.attempts.slice(1).map(({provider:f,model:g,reasoningEffort:y})=>({provider:f,model:g,...y?{reasoningEffort:y}:{}})),c({phase:"routing_decision",contentType:"application/json",body:{stage:"anthropic_fallback",attempts:u.attempts.slice(1)}}),i?.setFallbackInfo({triggered:!0,attemptCount:u.attempts.slice(1).length,reason:"all_anthropic_accounts_exhausted"});let d,m,h;for(const f of u.attempts.slice(1)){if(!f.provider||!f.model)continue;const g=Date.now();try{p.always(`[proxy] fallback \u2192 ${f.provider}/${f.model}${f.reasoningEffort?` reasoning=${f.reasoningEffort}`:""}`);let y;if(f.provider==="codex")y=await mvn({ctx:t,body:r,model:f.model,reasoningEffort:f.reasoningEffort,tracer:i,requestStartTime:a,logProxyBody:c,logFinalRequest:l});else if(f.provider==="vertex"&&phn(f.model)){const v=f.model,w=`vertex/${v}`;w3(t),t.metadata.vertexFallbackModel=v,y=await fhn({body:r,model:v,...t.abortSignal?{signal:t.abortSignal}:{},onTerminal:({usage:E,status:_,errorMessage:C})=>{i?.setModelSubstitution(r.model,v,"vertex"),i?.setServedAccount(w,"vertex"),i?.setUsage(E),i?.end(_,Date.now()-a),l(_,w,"vertex",_===200?void 0:"vertex_fallback_stream",C,{inputTokens:E.inputTokens,outputTokens:E.outputTokens,cacheCreationTokens:E.cacheCreationTokens,cacheReadTokens:E.cacheReadTokens})}})}else{const v=await bT.checkFallbackProviderAvailability(f.provider,f.model);if(!v.available){const E=v.reason??"provider unavailable";p.always(`[proxy] fallback ${f.provider}/${f.model} health-check failed (${E}), skipping`),Yw({provider:f.provider,model:f.model,status:"failure",errorMessage:`[unavailable] ${E}`,durationMs:0}),d=`[${f.provider}/${f.model}] unavailable: ${E}`;continue}const w=Qgr(n,{provider:f.provider,model:f.model});y=await Ngr({ctx:t,body:r,tracer:i,requestStartTime:a,logProxyBody:c,logFinalRequest:l,options:w,providerLabel:f.provider})}return f.provider==="codex"&&r.stream?{response:y}:(Yw({provider:f.provider,model:f.model,status:"success",durationMs:Date.now()-g}),i?.setFallbackInfo({triggered:!0,provider:f.provider,model:f.model,attemptCount:u.attempts.slice(1).length,reason:"fallback_success"}),f.provider!=="codex"&&eI(t,{quota:null,source:"none",servedBy:f.provider}),{response:y})}catch(y){if(y instanceof _r||el(y))throw y;const v=iy(y),w=t.abortSignal?.aborted?499:v?.status??502;m={status:w,message:v?.message?lr(`Configured fallback ${f.provider}/${f.model} failed: ${v.message}`,500):`Configured fallback ${f.provider}/${f.model} failed (HTTP ${w})`,...v?{errorCode:v.code,retryable:v.retryable}:{},errorType:w===499?"client_cancelled":w===504?"upstream_timeout":w===429?"rate_limit_error":w===401?"authentication_error":w===403?"permission_error":w===400?"invalid_request_error":"api_error"},h=pvn(y)??void 0;const E=sE(y instanceof Error?y.message:String(y));let _="unknown";if(E.includes("Rate limit")||E.includes("rate_limit")||E.includes("max_parallel_requests")?_="rate_limit":E.includes("context length")||E.includes("ContextWindowExceeded")?_="context_overflow":E.includes("no content or tool calls")||E.includes("NoOutputGenerated")?_="empty_response":E.includes("thinking_level")||E.includes("Field required")?_="schema_mismatch":E.includes("Resource exhausted")&&(_="provider_quota"),p.always(`[proxy] fallback ${f.provider}/${f.model} failed [${_}]: ${sE(Ql(y))}`),Yw({provider:f.provider,model:f.model,status:"failure",errorMessage:`[${_}] ${E}`,durationMs:Date.now()-g}),d=`[${f.provider}/${f.model}] ${sE(Ql(y))}`,t.abortSignal?.aborted||m.retryable===!1)break}}return{response:null,lastErrorMessage:d,terminalFailure:m,...h?{invalidRequestFailure:h}:{}}}function $gr(e){const{failure:t,buildLoggedClaudeError:r,tracer:n,requestStartTime:o}=e;n?.setError(t.errorType,t.message);const s=r(t.status,t.message,t.errorType,{errorCode:t.errorCode,retryable:t.retryable});return n?.end(t.status,Date.now()-o),Object.assign(s.error,{code:t.errorCode,retryable:t.retryable}),new Response(JSON.stringify(s),{status:t.status,headers:{"content-type":"application/json"}})}async function hvn(e){const{ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i}=e,a=Date.now();try{const c=L$(r),l=tE({provider:"anthropic",model:r.model},[],r.model,c,!0);if(Mgr(s,"auto_fallback",l),!l.attempts.find(h=>h.label==="auto-provider"))return{response:null};p.always("[proxy] fallback \u2192 auto-provider");const d=Qgr(c),m=await Ngr({ctx:t,body:r,tracer:n,requestStartTime:o,logProxyBody:s,logFinalRequest:i,options:d,providerLabel:"auto-provider"});return Yw({provider:"auto-provider",model:r.model,status:"success",durationMs:Date.now()-a}),n?.setFallbackInfo({triggered:!0,provider:"auto-provider",model:r.model,attemptCount:1,reason:"fallback_success"}),eI(t,{quota:null,source:"none",servedBy:"auto-provider"}),{response:m}}catch(c){if(c instanceof _r||el(c)||t.abortSignal?.aborted)throw c;const l=sE(Ql(c));p.always(`[proxy] fallback auto-provider failed: ${l}`),Yw({provider:"auto-provider",model:r.model,status:"failure",errorMessage:l,durationMs:Date.now()-a}),n?.setFallbackInfo({triggered:!0,provider:"auto-provider",model:r.model,attemptCount:1,reason:"fallback_failure"});const u=iy(c),d=u?.status??502;return{response:null,lastErrorMessage:l,terminalFailure:{status:d,message:lr(`Automatic fallback failed: ${u?.message??l}`,500),errorCode:u?.code,retryable:u?.retryable,errorType:d===504?"upstream_timeout":d===429?"rate_limit_error":d===401?"authentication_error":d===403?"permission_error":d===400?"invalid_request_error":"api_error"}}}}function fvn(e,t=5){const r=[...new Set(e)];return r.length<=t?r.join(", "):`${r.slice(0,t).join(", ")} and ${r.length-t} more`}function Ugr(e){const t=new Set(e.accounts).size,r=e.errorCode?` (${e.errorCode})`:"";return`All ${t} Anthropic account${t===1?"":"s"} are blocked by an organization entitlement policy${r}. Accounts: ${fvn(e.accounts)}. Upstream: "${e.message}". Ask an organization admin to re-enable Claude Code OAuth access, then run: neurolink auth enable anthropic:<account>.`}function gvn(e){const t=new Set(e.map(r=>r.coolingReason));if(t.size===1)switch([...t][0]){case"session":return"5-hour subscription window";case"weekly":return"7-day subscription window";case"unified":return"subscription limit";case"transient":return"upstream burst limit";default:break}return"upstream rate limits"}function yvn(e){for(const t of e){const r=pc.get(t.key)?.quota;if(r?.overageDisabledReason&&r.overageStatus?.trim().toLowerCase()!=="allowed")return r.overageDisabledReason}}function Bgr(e){return e?` Paid extra usage is unavailable for this organization (${e}), so there is no additional capacity before the window resets.`:""}function vvn(e){const t=new Set(e.accounts).size;return`All ${t} Anthropic account${t===1?"":"s"} have exhausted the model-scoped limit for ${e.model} (window "${e.scopeModel}"). Other models remain available on this pool \u2014 switch model, or add an account with remaining ${e.scopeModel} capacity. Earliest reset at ${new Date(e.earliestResetMs).toISOString()}.`+Bgr(e.overageDisabledReason)}function Tde(e){const{tracer:t,requestStartTime:r,authFailureMessage:n,authCooldownMessage:o,invalidRequestFailure:s,entitlementFailure:i,scopedExhaustion:a,sawNetworkError:c,sawTransientFailure:l,sawRateLimit:u,lastError:d,lastTransportErrorCode:m,lastTransportScope:h,fallbackFailureMessage:f,orderedAccounts:g,buildLoggedClaudeError:y,logProxyBody:v,logFinalRequest:w}=e;if(i!==null&&g.length>0&&new Set(i.accounts).size>=g.length&&i&&!u){const M=Ugr(i);return t?.setError("permission_error",M),t?.end(403,Date.now()-r),y(403,M,"permission_error")}if(n&&!u)return t?.setError("authentication_error",n),t?.end(401,Date.now()-r),y(401,n);if(o&&!u)return t?.setError("token_refresh_unavailable",o),t?.end(503,Date.now()-r),y(503,o,"token_refresh_unavailable");if(s&&!u){const M=Ku(s.body),F=M.message!==void 0,N=Cr(M.message??s.body),L=F?s.body:JSON.stringify($i(s.status,N,"invalid_request_error")),q=F?s.contentType??"application/json":"application/json";return t?.setError("invalid_request_error",N),t?.end(s.status,Date.now()-r),w(s.status,"","final","invalid_request_error",N),v({phase:"client_response",headers:{"content-type":q},body:L,bodySize:Buffer.byteLength(L,"utf8"),contentType:q,responseStatus:s.status,durationMs:Date.now()-r}),new Response(L,{status:s.status,headers:{"content-type":q}})}if((c||l)&&!u){const M=f?` Fallback also failed: ${f}`:"",F=h==="shared_provider_transport"?"shared Anthropic network":h==="connection_transport"?"Anthropic connection":null,N=`${F?`${F} failure prevented safe cross-account rotation`:"All Anthropic accounts failed due to transient upstream/network errors"}. Last error${m?` (${m})`:""}: ${d instanceof Error?d.message:String(d??"unknown")}.${M}`;return t?.setError("transient_error",N.slice(0,500)),t?.end(502,Date.now()-r),y(502,N,f?"fallback_exhausted":"transient_error",{...m?{errorCode:m}:{},...h?{transportScope:h}:{}})}const _=(M,F)=>{const N=$i(429,M,"overloaded_error");t?.setError("rate_limit_error",M),t?.end(429,Date.now()-r),w(429,"","final","rate_limit_error",M);const L=JSON.stringify(N),q={"content-type":"application/json","retry-after":String(F)};return v({phase:"client_response",headers:q,body:L,bodySize:Buffer.byteLength(L,"utf8"),contentType:"application/json",responseStatus:429,durationMs:Date.now()-r}),new Response(L,{status:429,headers:q})};if(a){const M=vvn(a);return p.always(`[proxy] model-scoped limit exhausted for ${a.model} on all accounts`),_(M,Math.max(1,Math.ceil((a.earliestResetMs-Date.now())/1e3)))}if(!u){const M=f?` Fallback also failed: ${f}`:"",F=`All Anthropic accounts failed. Last error: ${d instanceof Error?d.message:String(d??"unknown")}.${M}`;return t?.setError("all_accounts_failed",F.slice(0,500)),t?.end(502,Date.now()-r),y(502,F,f?"fallback_exhausted":"all_accounts_failed")}const C=Date.now(),A=g.map(M=>$a(M.key)).filter(M=>M.coolingUntil&&M.coolingUntil>C&&M.coolingReason!=="auth"),k=Math.min(...A.map(M=>M.coolingUntil??Number.POSITIVE_INFINITY)),R=g.length>0&&A.length===g.length,I=R?Math.max(1,Math.ceil((k-C)/1e3)):1,P=gvn(A),O=Bgr(yvn(g)),U=R?`All ${g.length} Anthropic accounts are cooling after the ${P} was exhausted. Earliest retry at ${new Date(k).toISOString()}.${O}`:`All ${g.length} accounts rate-limited after per-account retries.${O}`;return p.always(`[proxy] all accounts rate-limited, retry in ${I}s`),_(U,I)}async function zgr(e){const{ctx:t,body:r,account:n,accountState:o,response:s,tracer:i,requestStartTime:a,fetchStartMs:c,attemptNumber:l,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,onStreamTerminal:f,poolAccounts:g,logFinalRequest:y}=e;o.consecutiveRefreshFailures=0,p.always(`[proxy] \u2190 ${s.status} account=${n.label}`);const v=Mw(s.headers,{model:r.model});if(v){tvn(n.key,o.quota,v),o.quota=fm(o.quota,v);const E=ade(o,v,Date.now());E?.kind==="cooled"?Vu(n.key,E.coolingUntil,E.coolingReason).catch(()=>{}):E?.kind==="cleared"&&Yp(n.key,E.coolingUntil).catch(()=>{}),Zp(n.key,v).catch(()=>{})}const w={};return s.headers.forEach((E,_)=>{w[_]=E}),i?.logUpstreamResponseHeaders(w),eI(t,{upstreamHeaders:s.headers,quota:v??o.quota??null,source:v?"live":o.quota?"snapshot":"none",account:n,accountState:o,servedBy:"anthropic",attempt:l,...g?{poolAccounts:g}:{}}),r.stream?Tvn({ctx:t,body:r,account:n,accountState:o,response:s,responseHeaders:w,tracer:i,requestStartTime:a,fetchStartMs:c,attemptNumber:l,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:y,onStreamTerminal:f}):Evn({ctx:t,account:n,response:s,responseHeaders:w,tracer:i,requestStartTime:a,fetchStartMs:c,attemptNumber:l,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:y})}async function Tvn(e){const{ctx:t,body:r,account:n,accountState:o,response:s,responseHeaders:i,tracer:a,requestStartTime:c,fetchStartMs:l,attemptNumber:u,finalBodyStr:d,upstreamSpan:m,logAttempt:h,logProxyBody:f,onStreamTerminal:g,logFinalRequest:y}=e;if(!s.body){Pr(n.label,n.type,502),h(502,"stream_error","No response body from upstream"),m?.end(),a?.setError("stream_error","No response body from upstream"),a?.end(502,Date.now()-c),y(502,n.label,n.type,"stream_error","No response body from upstream");const R=$i(502,"No response body from upstream"),I=JSON.stringify(R);return f({phase:"client_response",headers:{"content-type":"application/json"},body:I,bodySize:Buffer.byteLength(I,"utf8"),contentType:"application/json",account:n.label,accountType:n.type,attempt:u,responseStatus:502,durationMs:Date.now()-c}),{response:R,served:!1}}const v=s.body.getReader(),w=await Nyn(v);if(w.kind==="transport_error"){const R=Ql(w.error),I=Buffer.concat(w.chunks.map(P=>Buffer.from(P))).toString("utf8");return p.always(`[proxy] stream failed before first chunk account=${n.label}: ${R}; returning terminal error to avoid replaying an ambiguous request`),Pr(n.label,n.type,502),h(502,"stream_error",R,{retryable:!1}),m?.end(),f({phase:"upstream_response",headers:i,body:I,bodySize:Buffer.byteLength(I,"utf8"),contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-l,metadata:{logicalStatus:502,transportError:R}}),{response:Ggr({account:n,tracer:a,requestStartTime:c,attemptNumber:u,logProxyBody:f,logFinalRequest:y,errorType:"stream_error",message:R}),served:!1}}if(w.kind==="empty")return await v.cancel().catch(()=>{}),p.always(`[proxy] \u2190 empty stream from account=${n.label}, trying next`),Pr(n.label,n.type,502),h(502,"empty_stream","Empty upstream stream",{retryable:!0}),a?.recordRetry(n.label,"empty_stream"),m?.end(),f({phase:"upstream_response",headers:i,body:"",bodySize:0,contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-l,metadata:{logicalStatus:502,upstreamErrorType:"empty_stream"}}),{retryNextAccount:!0,failure:{message:"Empty upstream stream",rateLimit:!1}};if(w.kind==="sse_error"){await v.cancel().catch(()=>{});const R=Buffer.concat(w.chunks.map(F=>Buffer.from(F))).toString("utf8"),I=w.errorType==="rate_limit_error",P=I?429:502,O=Mw(i,{model:r.model}),U=Date.now();let M;if(I){const F=a3(i["retry-after"]??null),N=sde(O,F,U,P$(i),rl,typeof r.model=="string"?r.model:void 0);o.quota=O?fm(o.quota,O):o.quota;const L=N.reason==="transient"?"transient":"quota";N.scope==="account"&&(!o.coolingUntil||N.coolingUntil>o.coolingUntil)&&(o.coolingUntil=N.coolingUntil,o.coolingReason=N.reason,await Vu(n.key,N.coolingUntil,N.reason).catch(()=>{})),Pr(n.label,n.type,429,L),h(429,"rate_limit_error",w.message,{retryable:!0,rateLimitKind:L,cooldownReason:N.reason}),N.rotateImmediately||(M={coolingUntil:N.coolingUntil,retryAfterMs:F})}else Pr(n.label,n.type,P),h(P,w.errorType,w.message,{retryable:!0});return p.always(`[proxy] immediate SSE ${w.errorType} account=${n.label}: ${w.message}; ${M?"transient, same account may retry":"rotating"} before client commit`),a?.recordRetry(n.label,I?"stream_rate_limit_before_commit":"stream_error_before_commit"),m?.end(),f({phase:"upstream_response",headers:i,body:R,bodySize:Buffer.byteLength(R,"utf8"),contentType:i["content-type"]??"text/event-stream",account:n.label,accountType:n.type,attempt:u,responseStatus:s.status,durationMs:Date.now()-l,metadata:{logicalStatus:P,upstreamErrorType:w.errorType}}),{retryNextAccount:!0,failure:{message:w.message,rateLimit:I,...w.errorType==="overloaded_error"?{retryDelayMs:Kgr(u)}:{},...M?{sameAccountRetry:M}:{}}}}h(s.status,void 0,void 0,{attemptDurationMs:Date.now()-l});const E=Xfr();let _=!1;const C=new ReadableStream({start(R){for(const I of w.chunks)R.enqueue(I)},async pull(R){if(!_)try{const{done:I,value:P}=await v.read();if(_)return;if(I){_=!0,E.complete(),R.close();return}R.enqueue(P)}catch(I){const P=Ql(I);if(p.always(`[proxy] mid-stream error account=${n.label}: ${P}`),E.fail(P),!_){_=!0;const O=`event: error
|
|
2366
2366
|
data: ${JSON.stringify({type:"error",error:{type:"api_error",message:`Upstream stream interrupted: ${P}`}})}
|
|
2367
2367
|
|
|
2368
|
-
`;R.enqueue(new TextEncoder().encode(O)),R.close()}}},cancel(){return _=!0,E.cancel(),v.cancel()}}),{response:A,telemetryDone:k}=wvn({ctx:t,account:n,response:s,responseHeaders:i,remainingStream:C,streamOutcome:E.outcome,tracer:a,requestStartTime:c,attemptNumber:u,finalBodyStr:d,upstreamSpan:m,logAttempt:h,logProxyBody:f,logFinalRequest:y});return k.then(()=>g?.(),()=>g?.()),{response:A,holdsAccountAdmission:!0,served:!0}}function sh(e){if(e.kind==="upstream_error")return{status:502,errorType:"stream_error",message:e.message};if(e.kind==="client_cancelled")return{status:499,errorType:"client_cancelled",message:"Client cancelled the streaming response"}}function E3(e,t,r){e.kind==="upstream_error"&&(Pr(t.label,t.type,502),r(502,"stream_error",e.message,{retryable:!1}))}function wvn(e){const{ctx:t,account:r,response:n,responseHeaders:o,remainingStream:s,streamOutcome:i,tracer:a,requestStartTime:c,attemptNumber:l,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:f}=e,{stream:g,capture:y}=Pue();let v=s,w;if(a)try{const{stream:C,telemetry:A}=U$({captureRawText:!0});v=v.pipeThrough(C);const k=a,R=d,I=n,P=u.length,O=r.label,U=r.key;w=Promise.all([A,y,i]).then(([M,F,N])=>{const L=i3(N,M.streamErrorMessage,M.messageStopReceived);x$(t.metadata,M),E3(L,r,m),k.setUsage({inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens}),yde(U,M.model,{inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens}),gde(O,M.model,{inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens}),k.logStreamEvents(M.events),k.setResponseInfo(Pgr(M));const q=parseFloat(I.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),B=parseFloat(I.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),H={inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens};isNaN(q)||(H.rateLimitAfter5h=q),isNaN(B)||(H.rateLimitAfter7d=B),(!isNaN(q)||!isNaN(B))&&k.setUsage(H),k.logUpstreamResponseBody(M.rawText??""),k.recordMetrics(),k.recordBodySizes(P,M.totalBytesReceived),R?.end();const G=sh(L),X={inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens};G?(k.setError(G.errorType,G.message),k.end(G.status,Date.now()-c),f(G.status,O,r.type,G.errorType,G.message,X)):(k.end(200,Date.now()-c),f(200,O,r.type,void 0,void 0,X)),h({phase:"upstream_response",headers:o,body:M.rawText??"",sourceTruncated:M.rawTextTruncated,bodySize:M.totalBytesReceived,contentType:o["content-type"]??"text/event-stream",account:O,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c}),h({phase:"client_response",headers:o,body:F.text,sourceTruncated:F.truncated,bodySize:F.totalBytes,contentType:o["content-type"]??"text/event-stream",account:O,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c})}).catch(M=>{k.setError("stream_telemetry_error",M instanceof Error?M.message:String(M)),R?.end(),k.end(500,Date.now()-c),f(500,O,r.type,"stream_telemetry_error",M instanceof Error?M.message:String(M))})}catch{w=i.then(C=>{E3(C,r,m);const A=sh(C);d?.end(),A?(a.setError(A.errorType,A.message),a.end(A.status,Date.now()-c),f(A.status,r.label,r.type,A.errorType,A.message)):(a.end(n.status,Date.now()-c),f(n.status,r.label,r.type))}).catch(()=>{})}else{d?.end();try{const{stream:C,telemetry:A}=U$({captureRawText:!0});v=v.pipeThrough(C);const k=r.label,R=r.key;w=Promise.all([A,y,i]).then(([I,P,O])=>{const U=i3(O,I.streamErrorMessage,I.messageStopReceived);x$(t.metadata,I),E3(U,r,m);const M=sh(U),F={inputTokens:I.usage.inputTokens,outputTokens:I.usage.outputTokens,cacheCreationTokens:I.usage.cacheCreationInputTokens,cacheReadTokens:I.usage.cacheReadInputTokens};yde(R,I.model,F),gde(k,I.model,F),M?f(M.status,k,r.type,M.errorType,M.message,F):f(200,k,r.type,void 0,void 0,F),h({phase:"upstream_response",headers:o,body:I.rawText??"",sourceTruncated:I.rawTextTruncated,bodySize:I.totalBytesReceived,contentType:o["content-type"]??"text/event-stream",account:k,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c}),h({phase:"client_response",headers:o,body:P.text,sourceTruncated:P.truncated,bodySize:P.totalBytes,contentType:o["content-type"]??"text/event-stream",account:k,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c})}).catch(I=>{const P=I instanceof Error?I.message:String(I);f(500,r.label,r.type,"stream_telemetry_error",P)})}catch{y.then(C=>{h({phase:"client_response",headers:o,body:C.text,sourceTruncated:C.truncated,bodySize:C.totalBytes,contentType:o["content-type"]??"text/event-stream",account:r.label,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c})}).catch(()=>{}),w=i.then(C=>{E3(C,r,m);const A=sh(C);A?f(A.status,r.label,r.type,A.errorType,A.message):f(n.status,r.label,r.type)}).catch(()=>{})}}const E=v.pipeThrough(g);$w(t.metadata,{onTerminal:()=>w});const _={...t.responseHeaders??{},"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"};return{response:new Response(E,{status:n.status,headers:_}),telemetryDone:w}}async function Evn(e){const{ctx:t,account:r,response:n,responseHeaders:o,tracer:s,requestStartTime:i,fetchStartMs:a,attemptNumber:c,finalBodyStr:l,upstreamSpan:u,logAttempt:d,logProxyBody:m,logFinalRequest:h}=e,f=await n.text();d(n.status,void 0,void 0,{attemptDurationMs:Date.now()-a}),s?.logUpstreamResponseBody(f),m({phase:"upstream_response",headers:o,body:f,bodySize:Buffer.byteLength(f,"utf8"),contentType:o["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:c,responseStatus:n.status,durationMs:Date.now()-a}),m({phase:"client_response",headers:o,body:f,bodySize:Buffer.byteLength(f,"utf8"),contentType:o["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:c,responseStatus:n.status,durationMs:Date.now()-i});const g=JSON.parse(f);if(k$(t.metadata,g),Ogr(r,g),s&&g&&typeof g=="object"){const y=g.usage;if(y){s.setUsage({inputTokens:y.input_tokens??0,outputTokens:y.output_tokens??0,cacheCreationTokens:y.cache_creation_input_tokens??0,cacheReadTokens:y.cache_read_input_tokens??0});const w=parseFloat(n.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),E=parseFloat(n.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(w)||!isNaN(E)){const _={inputTokens:y.input_tokens??0,outputTokens:y.output_tokens??0,cacheCreationTokens:y.cache_creation_input_tokens??0,cacheReadTokens:y.cache_read_input_tokens??0};isNaN(w)||(_.rateLimitAfter5h=w),isNaN(E)||(_.rateLimitAfter7d=E),s.setUsage(_)}}s.setResponseInfo(fde(g)),s.recordMetrics();const v=JSON.stringify(g);s.recordBodySizes(l.length,v.length),u?.end(),s.end(n.status,Date.now()-i),h(n.status,r.label,r.type,void 0,void 0,{inputTokens:y?.input_tokens,outputTokens:y?.output_tokens,cacheCreationTokens:y?.cache_creation_input_tokens,cacheReadTokens:y?.cache_read_input_tokens})}else{u?.end();const y=g&&typeof g=="object"?g.usage:void 0;h(n.status,r.label,r.type,void 0,void 0,{inputTokens:y?.input_tokens,outputTokens:y?.output_tokens,cacheCreationTokens:y?.cache_creation_input_tokens,cacheReadTokens:y?.cache_read_input_tokens})}return{response:g,served:!0}}async function Svn(e){const{ctx:t,account:r,accountState:n,requestedModel:o,retryResp:s,tracer:i,requestStartTime:a,fetchStartMs:c,attemptNumber:l,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:f}=e,g=Mw(s.headers,{model:o});if(g){n.quota=fm(n.quota,g);const E=ade(n,g,Date.now());E?.kind==="cooled"?Vu(r.key,E.coolingUntil,E.coolingReason).catch(()=>{}):E?.kind==="cleared"&&Yp(r.key,E.coolingUntil).catch(()=>{}),Zp(r.key,g).catch(_=>{p.debug("[proxy] Failed to persist account quota after auth retry",{account:r.label,error:_ instanceof Error?_.message:String(_)})})}const y=Object.fromEntries([...s.headers.entries()]),v=await s.text();m(s.status,void 0,void 0,{attemptDurationMs:Date.now()-c}),i?.logUpstreamResponseHeaders(y),i?.logUpstreamResponseBody(v),h({phase:"upstream_response",headers:y,body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:y["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:l,responseStatus:s.status,durationMs:Date.now()-c}),h({phase:"client_response",headers:y,body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:y["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:l,responseStatus:s.status,durationMs:Date.now()-a});const w=JSON.parse(v);if(k$(t.metadata,w),Ogr(r,w),i&&w&&typeof w=="object"){const E=w.usage;E&&i.setUsage({inputTokens:E.input_tokens??0,outputTokens:E.output_tokens??0,cacheCreationTokens:E.cache_creation_input_tokens??0,cacheReadTokens:E.cache_read_input_tokens??0}),i.setResponseInfo(fde(w)),i.recordMetrics();const _=JSON.stringify(w);i.recordBodySizes(u.length,_.length),d?.end(),i.end(s.status,Date.now()-a),f(s.status,r.label,r.type,void 0,void 0,{inputTokens:E?.input_tokens,outputTokens:E?.output_tokens,cacheCreationTokens:E?.cache_creation_input_tokens,cacheReadTokens:E?.cache_read_input_tokens})}else d?.end(),f(s.status,r.label,r.type);return w}async function bvn(e){const{ctx:t,body:r,account:n,accountState:o,headers:s,buildUpstreamBody:i,url:a,enabledAccounts:c,orderedAccounts:l,tracer:u,requestStartTime:d,allocateAttemptNumber:m,upstreamSpan:h,logAttempt:f,logProxyBody:g,onStreamTerminal:y,logFinalRequest:v,lastError:w,authFailureMessage:E,entitlementFailure:_,sawRateLimit:C,sawTransientFailure:A,sawNetworkError:k,bindServedSession:R}=e;Pr(n.label,n.type,401),f(401,"authentication_error","received 401 from Anthropic",{retryable:!0});let I=w,P=E,O=_,U=C,M=A,F=k,N=h,L=!1,q="received 401 from Anthropic";for(let B=0;B<Yx;B++){p.always(`[proxy] \u2190 401 account=${n.label} refreshing (attempt ${B+1}/${Yx})`);const H=await D$(n,n.persistTarget);if(!H.success){if(q=`refresh failed for account=${n.label} attempt ${B+1}/${Yx}: ${H.error?.slice(0,200)??"unknown"}`,I=q,sy(H))await wm(n,o,"refresh_invalid"),P=C3(n.label),p.always(`[proxy] account=${n.label} refresh token rejected; disabled until re-authentication`);else{const Ee=await b3(n,o);M=!0,p.always(`[proxy] account=${n.label} refresh temporarily unavailable (${H.status??"network"}); cooling until ${new Date(Ee).toISOString()} and rotating`)}break}n.persistTarget&&await N$(n.persistTarget,n),await _3(n,o),s.authorization=`Bearer ${n.token}`;const G=m(),X=Date.now(),ce=(Ee,le,ae,Pe)=>f(Ee,le,ae,{...Pe,attempt:G,attemptDurationMs:Pe?.attemptDurationMs??Date.now()-X}),Q=i(n.token),Ie=Date.now();try{const Ee=await Zue(a,{method:"POST",headers:s,body:Q.bodyStr,signal:AbortSignal.any([...t.abortSignal?[t.abortSignal]:[],AbortSignal.timeout(Xx)])},t,n.key,{logProxyBody:g,tracer:u,attemptNumber:G,accountLabel:n.label,accountType:n.type,preparedContext:Q.preparedContext});if(Ee.ok){L=!0,o.consecutiveRefreshFailures=0,p.always(`[proxy] \u2190 200 account=${n.label} (after ${B+1} refresh(es))`);const he=r.stream?await zgr({ctx:t,body:r,account:n,accountState:o,response:Ee,tracer:u,requestStartTime:d,fetchStartMs:Ie,attemptNumber:G,finalBodyStr:Q.bodyStr,upstreamSpan:N,logAttempt:ce,logProxyBody:g,logFinalRequest:v,onStreamTerminal:y}):{response:await Svn({ctx:t,account:n,accountState:o,requestedModel:r.model,retryResp:Ee,tracer:u,requestStartTime:d,fetchStartMs:Ie,attemptNumber:G,finalBodyStr:Q.bodyStr,upstreamSpan:N,logAttempt:ce,logProxyBody:g,logFinalRequest:v}),served:!0};if("retryNextAccount"in he){const Oe=he.failure;return{continueLoop:!0,...Oe?.retryDelayMs?{retryDelayMs:Oe.retryDelayMs}:{},lastError:Oe?.message??I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U||!!Oe?.rateLimit,sawTransientFailure:M||!!(Oe&&!Oe.rateLimit),sawNetworkError:F,upstreamSpan:void 0}}return R&&he.served&&R(n.key),{response:he.response,holdsAccountAdmission:he.holdsAccountAdmission,continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:void 0}}const le=Ee.status,ae=await Ee.text(),Pe={};Ee.headers.forEach((he,Oe)=>{Pe[Oe]=he});const Ae={...Pe};delete Ae.authorization,delete Ae["x-api-key"];const Te=ae.length>4e3?ae.slice(0,4e3)+"...[truncated]":ae;if(u?.logUpstreamResponseHeaders(Ae),u?.logUpstreamResponseBody(Te),g({phase:"upstream_response",headers:Ae,body:Te,bodySize:Buffer.byteLength(ae,"utf8"),contentType:Pe["content-type"]??"application/json",account:n.label,accountType:n.type,attempt:G,responseStatus:le,durationMs:Date.now()-Ie}),q=`retry ${B+1}/${Yx} failed with status ${le}`,I=ae,p.debug(`[proxy] retry ${B+1} failed: ${le} ${ae.substring(0,120)}`),le===429&&jgr(Pe,ae))return p.always(`[proxy] \u2190 429 account=${n.label} anti-abuse/construction rejection after OAuth refresh \u2014 returning non-retryable request error`),ce(429,"construction_rejection",ae),u?.setError("construction_rejection",ae.slice(0,500)),N?.end(),{response:qgr({terminalError:Hgr(),account:n,tracer:u,requestStartTime:d,attemptNumber:G,logProxyBody:g,logFinalRequest:v}),continueLoop:!1,lastError:ae,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:void 0};if(le===429){U=!0;const he=Date.now(),Oe=Mw(Pe,{model:r.model});Oe&&(o.quota=fm(o.quota,Oe));const De=sde(Oe,a3(Pe["retry-after"]??null),he,P$(Pe),rl,typeof r.model=="string"?r.model:void 0),Ye=De.reason==="transient"?"transient":"quota";Pr(n.label,n.type,le,Ye),ce(429,"rate_limit_error",ae,{retryable:!0,rateLimitKind:Ye,cooldownReason:De.reason}),De.scope==="account"&&(!o.coolingUntil||De.coolingUntil>o.coolingUntil)&&(o.coolingUntil=De.coolingUntil,o.coolingReason=De.reason),Oe&&Zp(n.key,Oe).catch(()=>{}),De.scope==="account"&&await Vu(n.key,o.coolingUntil??De.coolingUntil,o.coolingReason??De.reason).catch(()=>{}),my(n.key,c.length,l[0]?.key);break}if(le===401||le===402||le===403){if(_de(le,ae)){const he=Ku(ae);Pr(n.label,n.type,le),ce(le,"permission_error",Cr(ae)),O={status:le,accounts:[...O?.accounts??[],n.label],message:O?.message??he.message??Cr(ae),...he.errorCode?{errorCode:he.errorCode}:{}},n.type==="oauth"&&Zgr(le,ae)&&await wm(n,o,"entitlement_blocked"),q=`entitlement blocked for account=${n.label}`,I=q,p.always(`[proxy] \u2190 ${le} account=${n.label} entitlement blocked after refresh; advancing to next account`);break}Pr(n.label,n.type,le),ce(le,"authentication_error",Cr(ae),{retryable:!0}),B<Yx-1&&await Zl(1e3);continue}if(eyr(le,ae)){Pr(n.label,n.type,le),ce(le,"api_error",Cr(ae),{retryable:!0}),M=!0;break}ce(le,"api_error",Cr(ae));try{return v(le,n.label,n.type,"api_error",Cr(ae)),{response:JSON.parse(ae),continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:N}}catch{return v(le,n.label,n.type,"api_error",Cr(ae)),{response:$i(le,ae),continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:N}}}catch(Ee){if(Ee instanceof _r||el(Ee))throw N?.end(),Ee;if(t.abortSignal?.aborted)throw ce(499,"client_cancelled","Client cancelled upstream request",{retryable:!1}),N?.end(),Ee;F=!0,Pr(n.label,n.type,502);const le=Ee instanceof Error?Ee.message:String(Ee);q=`network error on retry ${B+1}: ${le}`,I=q;const ae=bde(Ee);if(ce(502,"network_error",le,{retryable:ae,errorCode:oI(Ee)??"unknown"}),p.debug(`[proxy] ${q}`),!ae)return N?.end(),{response:Ggr({account:n,tracer:u,requestStartTime:d,attemptNumber:G,logProxyBody:g,logFinalRequest:v,errorType:"network_error",message:le}),continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:void 0};break}}return L||(I=q,p.always(`[proxy] \u26A0 account=${n.label} auth retries exhausted, rotating to next account`),u?.setError("authentication_error",q),u?.recordRetry(n.label,"auth_exhausted"),N?.end(),N=void 0,my(n.key,c.length,l[0]?.key)),{continueLoop:!0,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:N}}function wde(e){const{responseStatus:t,account:r,errBody:n,errRespHeaders:o,requestStartTime:s,attemptNumber:i,logProxyBody:a,logFinalRequest:c,errorType:l}=e;try{const u=JSON.parse(n);return c(t,r.label,r.type,l,Cr(n)),a({phase:"client_response",headers:{"content-type":o["content-type"]??"application/json"},body:n,bodySize:Buffer.byteLength(n,"utf8"),contentType:o["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:i,responseStatus:t,durationMs:Date.now()-s}),u}catch{c(t,r.label,r.type,l,Cr(n));const u=$i(t,n),d=JSON.stringify(u);return a({phase:"client_response",headers:{"content-type":"application/json"},body:d,bodySize:Buffer.byteLength(d,"utf8"),contentType:"application/json",account:r.label,accountType:r.type,attempt:i,responseStatus:t,durationMs:Date.now()-s}),u}}function qgr(e){const{terminalError:t,account:r,tracer:n,requestStartTime:o,attemptNumber:s,logProxyBody:i,logFinalRequest:a}=e;return n?.end(t.status,Date.now()-o),wde({responseStatus:t.status,account:r,errBody:t.body,errRespHeaders:t.headers,requestStartTime:o,attemptNumber:s,logProxyBody:i,logFinalRequest:a,errorType:t.errorType})}function Ggr(e){const{account:t,tracer:r,requestStartTime:n,attemptNumber:o,logProxyBody:s,logFinalRequest:i,errorType:a,message:c}=e;r?.setError(a,c),r?.end(502,Date.now()-n),i(502,t.label,t.type,a,c);const l=$i(502,c),u=JSON.stringify(l);return s({phase:"client_response",headers:{"content-type":"application/json"},body:u,bodySize:Buffer.byteLength(u,"utf8"),contentType:"application/json",account:t.label,accountType:t.type,attempt:o,responseStatus:502,durationMs:Date.now()-n}),l}async function _vn(e){const{response:t,account:r,accountState:n,enabledAccounts:o,orderedAccounts:s,tracer:i,requestStartTime:a,fetchStartMs:c,attemptNumber:l,logAttempt:u,logProxyBody:d,logFinalRequest:m,lastError:h,authFailureMessage:f,sawTransientFailure:g,invalidRequestFailure:y,entitlementFailure:v,allowConfiguredModelFallback:w=!1}=e;let E=h,_=f,C=g,A=y,k=v;const R=await t.text(),I={};if(t.headers.forEach((P,O)=>{I[O]=P}),i?.logUpstreamResponseHeaders(I),i?.logUpstreamResponseBody(R),d({phase:"upstream_response",headers:I,body:R,bodySize:Buffer.byteLength(R,"utf8"),contentType:I["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:l,responseStatus:t.status,durationMs:Date.now()-c}),Fvn(t.status,R))return Uvn(t.status,R)?(p.always(`[proxy] \u2190 ${t.status} account=${r.label} beta unavailable for subscription; advancing to next account`),u(t.status,"invalid_request_error",Cr(R)),i?.setError("invalid_request_error",Cr(R)),i?.recordRetry(r.label,"beta_unavailable"),my(r.key,o.length,s[0]?.key),E=Cr(R),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}):(p.always(`[proxy] \u2190 ${t.status} upstream invalid_request_error`),u(t.status,"invalid_request_error",Cr(R)),i?.setError("invalid_request_error",Cr(R)),A={status:t.status,body:R,contentType:I["content-type"]},E=Cr(R),{continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0});if(r.type==="oauth"&&_de(t.status,R)){const P=Ku(R);return Pr(r.label,r.type,t.status),k={status:t.status,accounts:[...k?.accounts??[],r.label],message:k?.message??P.message??Cr(R),...P.errorCode?{errorCode:P.errorCode}:{}},p.always(`[proxy] \u2190 ${t.status} account=${r.label} entitlement blocked${P.errorCode?` (${P.errorCode})`:""}; advancing to next account`),u(t.status,"permission_error",Cr(R)),i?.setError("permission_error",Cr(R)),i?.recordRetry(r.label,"entitlement_blocked"),r.type==="oauth"&&Zgr(t.status,R)&&await wm(r,n,"entitlement_blocked"),my(r.key,o.length,s[0]?.key),E=Cr(R),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}}if((t.status===401||t.status===402||t.status===403)&&r.type==="oauth"&&!r.refreshToken)return Pr(r.label,r.type,t.status),await wm(r,n,"missing_refresh_token"),_=C3(r.label),p.always(`[proxy] \u2190 ${t.status} account=${r.label} (auth failure, no refresh token)`),E=R,u(t.status,"authentication_error",Cr(R)),i?.setError("authentication_error",Cr(R)),i?.recordRetry(r.label,"auth_no_refresh"),my(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0};if((t.status===401||t.status===402||t.status===403)&&r.type==="api_key")return Pr(r.label,r.type,t.status),_="Authentication failed for Anthropic API key credentials. Update ANTHROPIC_API_KEY or re-login with OAuth.",p.always(`[proxy] \u2190 ${t.status} account=${r.label} (auth failure, api_key)`),E=R,u(t.status,"authentication_error",Cr(R)),i?.setError("authentication_error",Cr(R)),i?.recordRetry(r.label,"auth_api_key"),my(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0};if(t.status===404)return w&&$vn(t.status,R)?(p.always(`[proxy] \u2190 404 account=${r.label} model unavailable; trying configured fallback`),u(404,"not_found_error",Cr(R)),i?.setError("not_found_error",Cr(R)),i?.recordRetry(r.label,"model_not_found"),E=Cr(R),{continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}):(p.always(`[proxy] \u2190 404 account=${r.label}`),u(404,"not_found_error",Cr(R)),i?.setError("not_found_error",Cr(R)),i?.end(404,Date.now()-a),{response:wde({responseStatus:404,account:r,errBody:R,errRespHeaders:I,requestStartTime:a,attemptNumber:l,logProxyBody:d,logFinalRequest:m,errorType:"not_found_error"}),continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0});if(eyr(t.status,R)){const P=zvn(t.status,R);return Pr(r.label,r.type,t.status,t.status===429?"transient":void 0),C=!0,p.always(`[proxy] \u2190 ${t.status} account=${r.label} (${P?"overloaded":"transient"})`),E=R,u(t.status,"api_error",Cr(R),t.status===429?{retryable:!0,rateLimitKind:"transient",cooldownReason:"transient"}:void 0),i?.setError(P?"overloaded_error":"transient_error",Cr(R)),i?.recordRetry(r.label,P?"overloaded":"transient"),{continueLoop:!0,retrySameAccount:!P,...P?{retryDelayMs:Kgr(l)}:{},lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}}return p.always(`[proxy] \u2190 ${t.status} account=${r.label}`),p.debug(`[claude-proxy] error body: ${R.substring(0,200)}`),u(t.status,"api_error",Cr(R)),i?.setError("api_error",Cr(R)),i?.end(t.status,Date.now()-a),{response:wde({responseStatus:t.status,account:r,errBody:R,errRespHeaders:I,requestStartTime:a,attemptNumber:l,logProxyBody:d,logFinalRequest:m,errorType:"api_error"}),continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}}function Cvn(e){const{ctx:t,body:r,clientRequestBody:n}=e;let o;try{o=Ux.startRequest({recordRequestMetrics:Mx(t.requestId)?.accountingScope!=="internal",recordUsageMetrics:!0,requestId:t.requestId,method:t.method,path:t.path,model:r.model,stream:r.stream??!1,toolCount:Array.isArray(r.tools)?r.tools.length:0,toolNames:Array.isArray(r.tools)?r.tools.map(h=>h&&typeof h=="object"&&"name"in h?String(h.name??""):"").filter(h=>h.length>0):void 0,sessionId:t.headers["x-neurolink-session-id"]??t.headers["x-claude-code-session-id"]??void 0,userAgent:t.headers["user-agent"]??void 0},t.headers);const m=o.startReceive();o.logRequestHeaders(t.headers),o.logRequestBody(n),m.end()}catch{o=void 0}const s=Date.now(),i=m=>{const h=o?.getTraceContext();Jw({timestamp:new Date().toISOString(),requestId:t.requestId,model:r.model,stream:r.stream??!1,...m,...h?{traceId:h.traceId,spanId:h.spanId}:{}})};let a;const c=m=>{if(a){p.debug(`[claude-proxy] ignored duplicate routing decision for request ${t.requestId}`);return}a=m};let l=!1;const u=(m,h,f,g,y,v)=>{if(l||Fw(t.requestId)){p.debug(`[claude-proxy] ignored duplicate finalization for request ${t.requestId}`);return}l=!0,t.abortSignal?.aborted&&(m=499,g="client_cancelled",y="Client cancelled request");const w=t.metadata.sdkFallbackFailure;w&&(h="unknown",f="translation",o?.setServedAccount(h,f),w.model&&o?.setModelSubstitution(r.model,w.model,w.provider),w.inputTokens!==void 0&&w.outputTokens!==void 0&&o?.setUsage({inputTokens:w.inputTokens,outputTokens:w.outputTokens,cacheReadTokens:w.cacheReadTokens??0,cacheCreationTokens:w.cacheCreationTokens??0,inputIncludesCachedTokens:w.inputIncludesCachedTokens,reasoningTokens:w.reasoningTokens}));const E=t.metadata.codexFallbackFailureUsage;E&&(v={inputTokens:E.inputTokensObserved?E.input:void 0,outputTokens:E.outputTokensObserved?E.output:void 0,cacheReadTokens:E.cacheReadTokensObserved?E.cacheReadTokens:void 0,cacheCreationTokens:E.cacheCreationTokensObserved?E.cacheCreationTokens:void 0,cacheReadTokensObserved:E.cacheReadTokensObserved===!0,cacheCreationTokensObserved:E.cacheCreationTokensObserved===!0,reasoningTokens:E.reasoning,...v}),!h&&typeof t.metadata.codexFallbackAccount=="string"&&t.metadata.codexFallbackAccount&&(h=t.metadata.codexFallbackAccount,typeof t.metadata.codexFallbackAccountType=="string"&&(f=t.metadata.codexFallbackAccountType)),!w&&t.metadata.codexFallbackDeferredFailure===!0&&typeof t.metadata.codexFallbackModel=="string"&&(o?.setModelSubstitution(r.model,t.metadata.codexFallbackModel,"openai"),o?.setServedAccount(h||"unknown",f),E?.inputTokensObserved&&E.outputTokensObserved&&o?.setUsage({inputTokens:E.input,outputTokens:E.output,cacheReadTokens:E.cacheReadTokens??0,cacheCreationTokens:E.cacheCreationTokens??0,cacheReadTokensObserved:E.cacheReadTokensObserved===!0,cacheCreationTokensObserved:E.cacheCreationTokensObserved===!0,reasoningTokens:E.reasoning},{recordMetrics:!1}));const _=h||(m>=400?Wue:void 0),C=h?f||void 0:m>=400?Kue:void 0,A=w?{accountKey:w.accountKey,provider:w.provider}:agr(_,C),k=Mx(t.requestId)?.accountingScope!=="internal";k&&m>=400?Zg(m,_,C,{requestId:t.requestId,...A.accountKey?{accountKey:A.accountKey}:{},errorType:g,terminalOutcome:g==="client_cancelled"?"client_cancelled":g?.includes("stream")?"stream_error":"handler_error",message:y,errorCode:v?.errorCode}):k&&nx(_,C);const R=o?.getTraceContext(),I=uvn(t.metadata,C);Kw({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:I??r.model,...I?{requestedModel:r.model,...C==="vertex"?{}:{inputIncludesCachedTokens:!1}}:{},...t.metadata.contextPreflight?{contextPreflight:t.metadata.contextPreflight}:{},...t.metadata.tokenBudget?{tokenBudget:t.metadata.tokenBudget}:{},stream:!!r.stream,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:_??"",...A.accountKey?{accountKey:A.accountKey}:{},accountType:C??"",...A.provider?{provider:A.provider}:{},...w,...Fx(t.headers),responseStatus:m,responseTimeMs:Date.now()-s,...nmn(t.metadata,s),...g?{errorType:g}:{},...y?{errorMessage:y}:{},...v?.errorCode?{errorCode:v.errorCode}:{},...v?.retryable!==void 0?{retryable:v.retryable}:{},...v?.transportScope?{transportScope:v.transportScope}:{},...v?.inputTokens!==void 0?{inputTokens:v.inputTokens}:{},...v?.outputTokens!==void 0?{outputTokens:v.outputTokens}:{},...v?.cacheCreationTokens!==void 0?{cacheCreationTokens:v.cacheCreationTokens}:{},...v?.cacheReadTokens!==void 0?{cacheReadTokens:v.cacheReadTokens}:{},...v?.reasoningTokens!==void 0?{reasoningTokens:v.reasoningTokens}:{},...R?{traceId:R.traceId,spanId:R.spanId}:{},...a?{routingDecision:a}:{},...Array.isArray(t.metadata.fallbackPlan)?{fallbackPlan:t.metadata.fallbackPlan}:{}})},d=(m,h,f,g)=>{const y=$i(m,h,f),v=JSON.stringify(y);return u(m,g?.account??"",g?.accountType??"final",f,h,g),i({phase:"client_response",headers:{"content-type":"application/json"},body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:"application/json",responseStatus:m,durationMs:Date.now()-s,...g}),y};return i({phase:"client_request",headers:t.headers,body:n,bodySize:Buffer.byteLength(n,"utf8"),contentType:t.headers["content-type"]??"application/json"}),{tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:u,buildLoggedClaudeError:d,setRoutingDecision:c}}function Avn(e){const{ctx:t,body:r,toolCount:n,requestStart:o,tracer:s,account:i,attemptNumber:a}=e,c=Date.now(),l=agr(i.label,i.type);return(u,d,m,h)=>{const f=Date.now(),g=s?.getTraceContext();Eue({timestamp:new Date().toISOString(),requestId:t.requestId,attempt:h?.attempt??a,method:t.method,path:t.path,model:r.model,...t.metadata.contextPreflight?{contextPreflight:t.metadata.contextPreflight}:{},...t.metadata.tokenBudget?{tokenBudget:t.metadata.tokenBudget}:{},stream:!!r.stream,toolCount:n,account:i.label,accountKey:i.key,accountType:i.type,...l.provider?{provider:l.provider}:{},responseStatus:u,responseTimeMs:f-o,attemptDurationMs:h?.attemptDurationMs??f-c,...d?{errorType:d}:{},...m?{errorMessage:m}:{},...h?.errorCode?{errorCode:h.errorCode}:{},...h?.transportScope?{transportScope:h.transportScope}:{},...h?.inputTokens!==void 0?{inputTokens:h.inputTokens}:{},...h?.outputTokens!==void 0?{outputTokens:h.outputTokens}:{},...h?.cacheCreationTokens!==void 0?{cacheCreationTokens:h.cacheCreationTokens}:{},...h?.cacheReadTokens!==void 0?{cacheReadTokens:h.cacheReadTokens}:{},...h?.retryable!==void 0?{retryable:h.retryable}:{},...h?.connectPhase!==void 0?{connectPhase:h.connectPhase}:{},...h?.rateLimitKind?{rateLimitKind:h.rateLimitKind}:{},...h?.cooldownReason?{cooldownReason:h.cooldownReason}:{},...g?{traceId:g.traceId,spanId:g.spanId}:{}})}}async function kvn(e){const{ctx:t,account:r,accountState:n,bodyStr:o,clientHeaders:s,isClaudeClientRequest:i,url:a,tracer:c,attemptNumber:l,currentLastError:u,currentAuthFailureMessage:d,logAttempt:m,logProxyBody:h}=e;let f=u,g=d;if(Ple(r)){const I=await D$(r,r.persistTarget);if(I.success)r.persistTarget&&await N$(r.persistTarget,r),await _3(r,n);else return f=`token refresh failed for account=${r.label}: ${I.error?.slice(0,200)??"unknown"}`,sy(I)?(await wm(r,n,"refresh_invalid"),g=C3(r.label)):await b3(r,n),m(sy(I)?401:503,sy(I)?"authentication_error":"token_refresh_unavailable",String(f)),{continueLoop:!0,lastError:f,authFailureMessage:g}}const y=r.type==="oauth",v={};for(const[I,P]of Object.entries(s))typeof P=="string"&&(v[I]=P);const w=y?await G0n(r.label,r.key,v,o):null,E={};for(const[I,P]of Object.entries(s)){const O=I.toLowerCase();typeof P=="string"&&!c3.has(O)&&(E[O]=P)}if(E["content-type"]="application/json",y?(E.authorization=`Bearer ${r.token}`,delete E["x-api-key"],$0n(E,w)):(E["x-api-key"]=r.token,delete E.authorization),E["user-agent"]||(E["user-agent"]=rg),E["anthropic-version"]||(E["anthropic-version"]="2023-06-01"),E["anthropic-dangerous-direct-browser-access"]||(E["anthropic-dangerous-direct-browser-access"]="true"),E["x-app"]||(E["x-app"]="cli"),E.accept||(E.accept="application/json"),y){const I=i?E["anthropic-beta"]??"":s["anthropic-beta"]??"",P=new Set(I.split(",").map(O=>O.trim()).filter(Boolean));for(const O of i?cA:F0n)P.add(O);E["anthropic-beta"]=[...P].join(",")}else{const I=(E["anthropic-beta"]??"").split(",").map(P=>P.trim()).filter(P=>P&&!cA.includes(P)).join(",");I?E["anthropic-beta"]=I:delete E["anthropic-beta"]}const _=I=>{const P=y?j0n(o,I,w,i,E["x-claude-code-session-id"]):{bodyStr:o};return{...P,...hgr(t,P.bodyStr)}},C=_(r.token);y&&C.sessionId&&!E["x-claude-code-session-id"]&&(E["x-claude-code-session-id"]=C.sessionId);const A=C.bodyStr;p.always(`[proxy] \u2192 account=${r.label} (${r.type})`);const k=Date.now();let R;return c&&(R=c.startUpstreamAttempt({attempt:l,account:r.label,polyfillHeaders:y,polyfillBody:y,upstreamUrl:a}),Object.assign(E,c.getTraceHeaders())),{continueLoop:!1,lastError:f,authFailureMessage:g,headers:E,buildUpstreamBody:_,finalBodyStr:A,preparedContext:C.preparedContext,fetchStartMs:k,upstreamSpan:R}}function jgr(e,t){const r=!!e["retry-after"],n=Object.keys(e).some(o=>o.toLowerCase().startsWith("anthropic-ratelimit-"));return r||n?!1:t.includes("rate_limit_error")&&/"message"\s*:\s*"Error"/.test(t)}function Hgr(){return{status:400,body:JSON.stringify($i(400,"Anthropic rejected the OAuth request shape. This is not an account rate limit.","invalid_request_error")),headers:{"content-type":"application/json"},errorType:"construction_rejection"}}async function xvn(e){const{ctx:t,url:r,headers:n,finalBodyStr:o,preparedContext:s,requestedModel:i,account:a,accountState:c,enabledAccounts:l,orderedAccounts:u,tracer:d,logAttempt:m,logProxyBody:h,fetchStartMs:f,attemptNumber:g,currentLastError:y,currentSawRateLimit:v,currentSawNetworkError:w,upstreamSpan:E}=e;let _=y,C=v,A=w;const k=E;let R;try{R=await Zue(r,{method:"POST",headers:n,body:o,signal:AbortSignal.any([...t.abortSignal?[t.abortSignal]:[],AbortSignal.timeout(Xx)])},t,a.key,{logProxyBody:h,tracer:d,attemptNumber:g,accountLabel:a.label,accountType:a.type,preparedContext:s})}catch(I){if(I instanceof _r||el(I))throw k?.end(),I;if(t.abortSignal?.aborted)throw m(499,"client_cancelled","Client cancelled upstream request",{retryable:!1}),k?.end(),t.abortSignal.reason;const P=bde(I),O=Ygr(I),U=Nvn(I);A=!0,Pr(a.label,a.type,502);const M=oI(I)??"unknown",F=I instanceof Error?I.message:String(I);if(_=F,p.always(`[proxy] fetch error account=${a.label} code=${M} (${P?"retryable":"terminal"}): ${F}`),m(502,"network_error",F,{retryable:P,connectPhase:O,errorCode:M,transportScope:U}),d?.setError("network_error",F),P&&d?.recordRetry(a.label,"network_error"),k?.end(),!P)throw I;return{continueLoop:!0,retrySameAccount:!0,transportScope:U,errorCode:M,connectPhase:O,lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:void 0}}if(R.status===429){const I=a3(R.headers.get("retry-after")),P={};R.headers.forEach((B,H)=>{P[H]=B}),_=await R.text();const O={...P};delete O.authorization,delete O["x-api-key"];const U=String(_).length>4e3?String(_).slice(0,4e3)+"...[truncated]":String(_);if(d?.logUpstreamResponseHeaders(O),d?.logUpstreamResponseBody(U),h({phase:"upstream_response",headers:O,body:U,bodySize:Buffer.byteLength(String(_),"utf8"),contentType:P["content-type"]??"application/json",account:a.label,accountType:a.type,attempt:g,responseStatus:429,durationMs:Date.now()-f}),jgr(P,String(_)))return p.always(`[proxy] \u2190 429 account=${a.label} anti-abuse/construction rejection (no ratelimit headers, body="Error") \u2014 NOT a real rate limit; returning non-retryable request error`),m(429,"construction_rejection",String(_)),d?.setError("construction_rejection",String(_).slice(0,500)),k?.end(),{continueLoop:!1,terminalError:Hgr(),lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:void 0};C=!0;const M=Date.now(),F=Mw(P,{model:i}),N=P$(P),L=sde(F,I,M,N,rl,i),q=L.reason==="transient"?"transient":"quota";return Pr(a.label,a.type,429,q),p.always(`[proxy] \u2190 429 account=${a.label} reason=${L.reason} scope=${L.scope} retry-after=${I}ms 5h-status=${P["anthropic-ratelimit-unified-5h-status"]??"unknown"} 7d-status=${P["anthropic-ratelimit-unified-7d-status"]??"unknown"} unified-status=${N??"unknown"} \u2192 ${L.rotateImmediately?`rotate now, cool ${ide(L.coolingUntil,M)}m`:"retry same account (transient)"}`),m(429,"rate_limit_error",String(_),{retryable:!0,rateLimitKind:q,cooldownReason:L.reason}),d?.setError("rate_limit_error",String(_).slice(0,500)),d?.recordRetry(a.label,"rate_limit"),k?.end(),{continueLoop:!0,retrySameAccount:!L.rotateImmediately,retryAfterMs:I,cooldownPlan:L,...F?{quota:F}:{},lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:void 0}}return{continueLoop:!1,response:R,lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:k}}function Ivn(e){return e.invalidRequestFailure===null}function Rvn(e){const{ctx:t,tracer:r,requestStartTime:n,failure:o,buildLoggedClaudeError:s}=e;return o.responseHeaders&&(t.responseHeaders={...t.responseHeaders??{},...o.responseHeaders}),r?.setError(o.errorType,o.message),r?.end(o.status,Date.now()-n),s(o.status,o.message,o.errorType)}async function Pvn(e){const{ctx:t,body:r,modelRouter:n,configGeneration:o,tracer:s,requestStartTime:i,accountStrategy:a,primaryAccountKey:c,accountAllowlist:l,quotaRoutingEnabled:u=lde(),sessionSoftLimit:d=ude(),sessionResetToleranceMs:m=rI(),ranking:h="expiry-first",preferPrimary:f=!1,sessionAffinityEnabled:g=!1,sessionAffinityIdleTtlMs:y=36e5,spillInflight:v=0,buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_,setRoutingDecision:C}=e,A=L$(r),k=tE({provider:"anthropic",model:r.model},n?.getFallbackChain()??[],r.model,A),R=k.attempts.slice(1).some(Te=>!!(Te.provider&&Te.model)),I=await lvn({ctx:t,body:r,accountStrategy:a,primaryAccountKey:c,accountAllowlist:l,quotaRoutingEnabled:u,sessionSoftLimit:d,sessionResetToleranceMs:m,ranking:h,preferPrimary:f,sessionAffinityEnabled:g,sessionAffinityIdleTtlMs:y,spillInflight:v,setRoutingDecision:C});if("failure"in I){const Te=await Lgr({body:r,logFinalRequest:_});if(Te)return Te;const he=await Fgr({ctx:t,body:r,parsedFallbackRequest:A,fallbackPlan:k,modelRouter:n,tracer:s,requestStartTime:i,logProxyBody:E,logFinalRequest:_});if(he.response)return he.response;if(he.invalidRequestFailure)return Tde({tracer:s,requestStartTime:i,authFailureMessage:null,authCooldownMessage:null,invalidRequestFailure:he.invalidRequestFailure,entitlementFailure:null,scopedExhaustion:null,sawNetworkError:!1,sawTransientFailure:!1,sawRateLimit:!1,lastError:void 0,orderedAccounts:[],buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_});if(he.terminalFailure){const Oe=he.terminalFailure;return $gr({failure:Oe,buildLoggedClaudeError:w,tracer:s,requestStartTime:i})}return Rvn({ctx:t,tracer:s,requestStartTime:i,failure:I.failure,buildLoggedClaudeError:w})}const{accounts:P,enabledAccounts:O,orderedAccounts:U,bodyStr:M,requestStart:F,toolCount:N,url:L,clientHeaders:q,isClaudeClientRequest:B,sessionId:H}=I,G=new Set,X=g&&H&&a==="fill-first"&&O.length>1?Te=>D0n({sessionId:H,servingAccountKey:Te,attemptedAccountKeys:G,enabledAccounts:O,idleTtlMs:y,sessionSoftLimit:d,sessionResetToleranceMs:m,requestedModel:typeof r.model=="string"?r.model:void 0}):void 0,ce=E0n(),Q={lastError:void 0,sawRateLimit:!1,sawNetworkError:!1,sawTransientFailure:!1,invalidRequestFailure:null,authFailureMessage:null,authCooldownMessage:null,entitlementFailure:null,scopedExhaustion:null,attemptNumber:0},Ie=s?.startAccountSelection();let le=U.filter(Te=>!Egr(Te.key));if(le.length===0&&(le=await p0n(U)),le.length===0&&U.length>0){const Te=U.map(Oe=>$a(Oe.key)),he=Te.some(Oe=>Oe.coolingReason!=="auth");if(Q.sawRateLimit=he,Q.sawTransientFailure=!he,Q.lastError=he?"All Anthropic accounts have active rate-limit cooldowns":"All Anthropic accounts have active authentication cooldowns",!he){const Oe=Math.min(...Te.map(De=>De.coolingUntil??Number.POSITIVE_INFINITY));Q.authCooldownMessage=`All ${U.length} Anthropic accounts are temporarily unavailable while OAuth refresh is cooling. Earliest retry at ${new Date(Oe).toISOString()}.`}}const ae=C0n(le,typeof r.model=="string"?r.model:void 0,Date.now(),ce);ae.eligible.length>0?le=ae.eligible:ae.exhaustion&&(Q.scopedExhaustion=ae.exhaustion,Q.lastError=`Model-scoped limit exhausted for ${ae.exhaustion.model}`,le=[]);const Pe=n?.getMaxInflightPerAccount?.();let Ae;try{Pe!==void 0&&le.length>0&&le.every(Te=>!n0n(Te.key,Pe))&&(Ae=await s0n(le.map(Te=>Te.key),Pe,t.abortSignal,ode,o));e:for(const[Te,he]of le.entries()){const Oe=Te<le.length-1,De=$a(he.key);let Ye=0,gt=0;for(;;){const $e=await nE.acquire(t.abortSignal);if($e.allowed===!1){Q.sawNetworkError=!0,Q.lastTransportErrorCode=$e.errorCode??void 0,Q.lastTransportScope=$e.transportScope,Q.lastError=`Anthropic transport recovery probe failed (${$e.errorCode??"unknown"})`;const se=$e.connectPhase?lgr:l3;if(Ye<se){Ye+=1;const oe=Sde(Ye);p.always(`[proxy] retrying same account=${he.label} after failed transport recovery probe (${Ye}/${se}) in ${oe}ms`),await Zl(oe);continue}break e}Q.attemptNumber+=1,s&&Q.attemptNumber===1&&Ie&&(s.setAccountSelection({strategy:a,accountsTotal:P.length,accountsHealthy:O.length,selectedAccount:he.label,accountType:he.type}),Ie.end());const xe=Avn({ctx:t,body:r,toolCount:N,requestStart:F,tracer:s,account:he,attemptNumber:Q.attemptNumber}),ve=await kvn({ctx:t,account:he,accountState:De,bodyStr:M,clientHeaders:q,isClaudeClientRequest:B,url:L,tracer:s,attemptNumber:Q.attemptNumber,currentLastError:Q.lastError,currentAuthFailureMessage:Q.authFailureMessage,logAttempt:xe,logProxyBody:E});if(Q.lastError=ve.lastError,Q.authFailureMessage=ve.authFailureMessage,ve.continueLoop||!ve.headers||!ve.buildUpstreamBody||!ve.finalBodyStr||!ve.preparedContext||ve.fetchStartMs===void 0){G.add(he.key),$e.probe&&nE.reportProbeAbandoned($e);continue e}let J;if(Ae?.accountKey===he.key?(J=Ae.lease,Ae=void 0):(J=t0n(he.key,Pe,o),J&&Ae&&(Ae.lease.release(),Ae=void 0)),!J){$e.probe&&nE.reportProbeAbandoned($e);continue e}G.add(he.key);let V=!1;try{let se;try{se=await xvn({ctx:t,url:L,headers:ve.headers,finalBodyStr:ve.finalBodyStr,preparedContext:ve.preparedContext,requestedModel:r.model,account:he,accountState:De,enabledAccounts:O,orderedAccounts:U,tracer:s,logAttempt:xe,logProxyBody:E,fetchStartMs:ve.fetchStartMs,attemptNumber:Q.attemptNumber,currentLastError:Q.lastError,currentSawRateLimit:Q.sawRateLimit,currentSawNetworkError:Q.sawNetworkError,upstreamSpan:ve.upstreamSpan})}catch(W){throw $e.probe&&nE.reportProbeAbandoned($e),W}if(se.transportScope?nE.reportTransportFailure(se.errorCode,se.transportScope,$e,se.connectPhase===!0):nE.reportSuccess($e),Q.lastError=se.lastError,Q.sawRateLimit=se.sawRateLimit,Q.sawNetworkError=se.sawNetworkError,se.transportScope&&(Q.lastTransportScope=se.transportScope,Q.lastTransportErrorCode=se.errorCode),se.terminalError)return qgr({terminalError:se.terminalError,account:he,tracer:s,requestStartTime:i,attemptNumber:Q.attemptNumber,logProxyBody:E,logFinalRequest:_});if(se.continueLoop||!se.response){if(se.cooldownPlan){const re=se.cooldownPlan;se.quota&&(De.quota=fm(De.quota,se.quota),Zp(he.key,se.quota).catch(()=>{}));let ye=!1;re.scope==="account"&&(!De.coolingUntil||re.coolingUntil>De.coolingUntil)&&(De.coolingUntil=re.coolingUntil,De.coolingReason=re.reason,ye=!0),ye&&re.scope==="account"&&await Vu(he.key,De.coolingUntil??re.coolingUntil,De.coolingReason??re.reason).catch(()=>{});const Re=se.retrySameAccount?Sgr(he.key,re.coolingUntil,se.retryAfterMs,gt):void 0;if(Re){gt+=1,p.always(`[proxy] retrying same account=${he.label} after transient 429 (shared slot ${Re.slot}/${u3}) in ${Re.delayMs}ms`),await Zl(Re.delayMs);continue}my(he.key,O.length,U[0]?.key),p.always(`[proxy] account=${he.label} rate-limited (${re.reason}); cooling ~${ide(re.coolingUntil,Date.now())}m until ${new Date(re.coolingUntil).toISOString()}, rotating`),re.rotateImmediately&&k0n(he,le[Te+1],re.coolingUntil,d);continue e}const W=se.connectPhase?lgr:l3;if(se.retrySameAccount&&Ye<W){Ye+=1;const re=Sde(Ye);p.always(`[proxy] retrying same account=${he.label} after transient network error (${Ye}/${W}) in ${re}ms`),await Zl(re);continue}if(se.retrySameAccount&&!se.transportScope&&p.always(`[proxy] exhausted transient same-account retries for account=${he.label}; rotating`),se.transportScope){p.always(`[proxy] Anthropic ${se.transportScope} failure code=${se.errorCode??"unknown"}; suppressing cross-account rotation after ${Ye+1} attempts`);break e}continue e}let oe=se.upstreamSpan;const Z=se.response;if(Z.status===401&&he.type==="oauth"&&he.refreshToken){const W=await bvn({ctx:t,body:r,account:he,accountState:De,headers:ve.headers,buildUpstreamBody:ve.buildUpstreamBody,url:L,enabledAccounts:O,orderedAccounts:U,tracer:s,requestStartTime:i,allocateAttemptNumber:()=>(Q.attemptNumber+=1,Q.attemptNumber),upstreamSpan:oe,logAttempt:xe,logProxyBody:E,logFinalRequest:_,onStreamTerminal:J.release,lastError:Q.lastError,authFailureMessage:Q.authFailureMessage,entitlementFailure:Q.entitlementFailure,sawRateLimit:Q.sawRateLimit,sawTransientFailure:Q.sawTransientFailure,sawNetworkError:Q.sawNetworkError,bindServedSession:X});if(Q.lastError=W.lastError,Q.authFailureMessage=W.authFailureMessage,Q.entitlementFailure=W.entitlementFailure,Q.sawRateLimit=W.sawRateLimit,Q.sawTransientFailure=W.sawTransientFailure,Q.sawNetworkError=W.sawNetworkError,oe=W.upstreamSpan,W.response!==void 0)return V=W.holdsAccountAdmission===!0,W.response;if(W.continueLoop){Oe&&W.retryDelayMs&&(p.always(`[proxy] pacing cross-account SSE overload rotation for ${W.retryDelayMs}ms after auth refresh`),await Zl(W.retryDelayMs));continue e}}if(!Z.ok){const W=await _vn({response:Z,account:he,accountState:De,enabledAccounts:O,orderedAccounts:U,tracer:s,requestStartTime:i,fetchStartMs:ve.fetchStartMs,attemptNumber:Q.attemptNumber,logAttempt:xe,logProxyBody:E,logFinalRequest:_,lastError:Q.lastError,authFailureMessage:Q.authFailureMessage,sawTransientFailure:Q.sawTransientFailure,invalidRequestFailure:Q.invalidRequestFailure,entitlementFailure:Q.entitlementFailure,allowConfiguredModelFallback:R});if(Q.lastError=W.lastError,Q.authFailureMessage=W.authFailureMessage,Q.sawTransientFailure=W.sawTransientFailure,Q.invalidRequestFailure=W.invalidRequestFailure,Q.entitlementFailure=W.entitlementFailure,W.response!==void 0)return W.response;if(W.continueLoop){if(W.retrySameAccount&&Ye<l3){Ye+=1;const re=Sde(Ye);p.always(`[proxy] retrying same account=${he.label} after transient upstream ${Z.status} (${Ye}/${l3}) in ${re}ms`),await Zl(re);continue}W.retrySameAccount&&p.always(`[proxy] exhausted transient same-account retries for account=${he.label}; rotating`),Oe&&W.retryDelayMs&&(p.always(`[proxy] pacing cross-account overload rotation for ${W.retryDelayMs}ms`),await Zl(W.retryDelayMs));continue e}break e}if(De.coolingUntil&&Date.now()>=De.coolingUntil){const W=De.coolingUntil;De.coolingUntil=void 0,De.coolingReason=void 0,Yp(he.key,W).catch(()=>{})}const ie=await zgr({ctx:t,body:r,account:he,accountState:De,response:Z,tracer:s,requestStartTime:i,fetchStartMs:ve.fetchStartMs,attemptNumber:Q.attemptNumber,finalBodyStr:ve.finalBodyStr,upstreamSpan:oe,logAttempt:xe,logProxyBody:E,logFinalRequest:_,onStreamTerminal:J.release,poolAccounts:O});if("retryNextAccount"in ie){if(ie.failure){Q.lastError=ie.failure.message,Q.sawRateLimit||=ie.failure.rateLimit,Q.sawTransientFailure||=!ie.failure.rateLimit;const{sameAccountRetry:W}=ie.failure,re=W?Sgr(he.key,W.coolingUntil,W.retryAfterMs,gt):void 0;if(re){gt+=1,p.always(`[proxy] retrying same account=${he.label} after transient in-stream rate limit (shared slot ${re.slot}/${u3}) in ${re.delayMs}ms`),await Zl(re.delayMs);continue}Oe&&ie.failure.retryDelayMs&&(p.always(`[proxy] pacing cross-account SSE overload rotation for ${ie.failure.retryDelayMs}ms`),await Zl(ie.failure.retryDelayMs))}continue e}return V=ie.holdsAccountAdmission===!0,ie.served&>>0&&d0n(he,De),X&&ie.served&&X(he.key),ie.response}finally{V||J.release()}}}}finally{Ae?.lease.release(),Q.attemptNumber===0&&Ie?.end()}if(Ivn(Q)){let Te;const he=await Lgr({body:r,logFinalRequest:_});if(he)return he;const Oe=await Fgr({ctx:t,body:r,parsedFallbackRequest:A,fallbackPlan:k,modelRouter:n,tracer:s,requestStartTime:i,logProxyBody:E,logFinalRequest:_});if(Oe.response)return Oe.response;if(Oe.invalidRequestFailure)return Tde({tracer:s,requestStartTime:i,authFailureMessage:null,authCooldownMessage:null,invalidRequestFailure:Oe.invalidRequestFailure,entitlementFailure:null,scopedExhaustion:null,sawNetworkError:!1,sawTransientFailure:!1,sawRateLimit:!1,lastError:void 0,orderedAccounts:[],buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_});Te=Oe.lastErrorMessage;let De=Oe.terminalFailure;if(Q.invalidRequestFailure===null&&!Q.sawRateLimit&&!t.abortSignal?.aborted&&De?.retryable!==!1&&n?.isAutoFallbackEnabled?.()){const Ye=await hvn({ctx:t,body:r,tracer:s,requestStartTime:i,logProxyBody:E,logFinalRequest:_});if(Ye.response)return Ye.response;Te=Ye.lastErrorMessage??Te,De=Ye.terminalFailure??De}if(De)return $gr({failure:De,buildLoggedClaudeError:w,tracer:s,requestStartTime:i});Q.fallbackFailureMessage=Te}{const Te=U[0],he=Te?pc.get(Te.key):void 0;eI(t,{quota:he?.quota??null,source:he?.quota?"snapshot":"none",...Te?{account:Te}:{},...he?{accountState:he}:{},attempt:Q.attemptNumber,poolAccounts:O})}return Tde({tracer:s,requestStartTime:i,authFailureMessage:Q.authFailureMessage,authCooldownMessage:Q.authCooldownMessage,invalidRequestFailure:Q.invalidRequestFailure,entitlementFailure:Q.entitlementFailure,scopedExhaustion:Q.scopedExhaustion,sawNetworkError:Q.sawNetworkError,sawTransientFailure:Q.sawTransientFailure,sawRateLimit:Q.sawRateLimit,lastError:Q.lastError,lastTransportErrorCode:Q.lastTransportErrorCode,lastTransportScope:Q.lastTransportScope,fallbackFailureMessage:Q.fallbackFailureMessage,orderedAccounts:U,buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_})}function Vgr(e){return e!==void 0&&"runtimeConfigProvider"in e&&typeof e.runtimeConfigProvider=="function"}function Wgr(e){const{ctx:t,body:r,status:n,message:o,errorType:s}=e;return Fw(t.requestId)||(Zg(n,Wue,Kue,{requestId:t.requestId,errorType:s,terminalOutcome:"handler_error",message:o}),Kw({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:typeof r?.model=="string"?r.model:"",stream:r?.stream??!1,toolCount:Array.isArray(r?.tools)?r.tools.length:0,account:Wue,accountType:Kue,responseStatus:n,responseTimeMs:0,errorType:s,errorMessage:o})),$i(n,o)}function Ede(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e*1e3):null}function Mvn(e){if(!e||typeof e!="object")return null;const t={...e};return t.sessionResetAtMs=Ede(t.sessionResetAt),t.weeklyResetAtMs=Ede(t.weeklyResetAt),Array.isArray(t.windows)&&(t.windows=t.windows.map(r=>{const n={...r};return n.resetsAtMs=Ede(n.resetsAt),n.severity=n.severity??(n.status==="rejected"?"critical":"normal"),n.isActive=n.isActive??!1,n})),t}function S3(e){return e==="allowed"?"ok":e==="rejected"||e==="throttled"?"degraded":"unknown"}function Ovn(e,t="",r="fill-first",n=!1,o,s){const i=Vgr(s)?s.accountAllowlist:s,a=Vgr(s)?s.runtimeConfigProvider:void 0;return{prefix:`${t}/v1`,routes:[{method:"POST",path:`${t}/v1/messages`,handler:async c=>{const l=a?.()??{generation:0,strategy:r,modelRouter:e,passthrough:n,primaryAccountKey:o,accountAllowlist:i,quotaRoutingEnabled:lde(),sessionSoftLimit:ude(),sessionResetToleranceMs:rI(),useOverage:"auto",accountRanking:"expiry-first",preferPrimary:!1,sessionAffinity:!1,sessionAffinityIdleTtlMs:36e5,spillInflight:0};dde(l.useOverage);const u=l.modelRouter,d=c.body;if(typeof d?.model!="string"||!Array.isArray(d?.messages))return Wgr({ctx:c,body:d,status:400,message:"Missing required fields: model, messages",errorType:"invalid_request_error"});const m=d.model.toLowerCase();if(!u&&!m.startsWith("claude-"))return Wgr({ctx:c,body:d,status:404,message:`Model '${d.model}' is not an Anthropic model. The proxy only supports Claude models. Use a model router to route non-Claude models to other providers.`,errorType:"not_found_error"});const h=u?.resolve(d.model)??{provider:"anthropic",model:d.model},f=JSON.stringify(d),{tracer:g,requestStartTime:y,logProxyBody:v,logFinalRequest:w,buildLoggedClaudeError:E,setRoutingDecision:_}=Cvn({ctx:c,body:d,clientRequestBody:f});try{return h.provider===null?(g?.setError("not_found_error",`Model '${d.model}' is not a Claude model.`),g?.end(404,Date.now()-y),E(404,`Model '${d.model}' is not a Claude model. Use a model router to route it to another provider.`)):h.provider==="anthropic"?(g?.setMode("passthrough"),l.passthrough?await W0n({ctx:c,body:d,clientRequestBody:f,tracer:g,requestStartTime:y,logProxyBody:v,logFinalRequest:w}):await Pvn({ctx:c,body:d,modelRouter:u,configGeneration:l.generation,tracer:g,requestStartTime:y,accountStrategy:l.strategy,primaryAccountKey:l.primaryAccountKey,accountAllowlist:l.accountAllowlist,quotaRoutingEnabled:l.quotaRoutingEnabled,sessionSoftLimit:l.sessionSoftLimit,sessionResetToleranceMs:l.sessionResetToleranceMs,ranking:l.accountRanking,preferPrimary:l.preferPrimary,sessionAffinityEnabled:l.sessionAffinity,sessionAffinityIdleTtlMs:l.sessionAffinityIdleTtlMs,spillInflight:l.spillInflight,buildLoggedClaudeError:E,logProxyBody:v,logFinalRequest:w,setRoutingDecision:_})):await V0n({ctx:c,body:d,route:{provider:h.provider,model:h.model},modelRouter:u,tracer:g,requestStartTime:y,logProxyBody:v})}catch(C){if(c.abortSignal?.aborted)return new Response(JSON.stringify(E(499,"Client cancelled request","client_cancelled")),{status:499,headers:{"content-type":"application/json"}});const A=C instanceof _r?C:el(C);if(A){C instanceof _r&&C.evidence&&(c.metadata.contextPreflight=C.evidence);const R=E(A.status,A.message,A.code,{errorCode:A.code,retryable:!1});return new Response(JSON.stringify({...R,error:{...R.error,code:A.code,retryable:!1}}),{status:A.status,headers:{"content-type":"application/json"}})}const k=C instanceof Error?C.message:String(C);if(p.error(`[claude-proxy] Generation error for ${d.model}: ${k}`),g?.setError("generation_error",k.slice(0,500)),g?.end(502,Date.now()-y),h.provider==="anthropic")throw C;return E(502,`Generation failed: ${C instanceof Error?C.message:"unknown error"}`)}},description:"Claude-compatible messages endpoint routed through NeuroLink",tags:["claude-proxy","messages"],streaming:{enabled:!0,contentType:"text/event-stream"}},{method:"POST",path:`${t}/peer/heartbeat`,handler:async c=>{const l=c.headers["x-neurolink-share-token"],u=c.headers["x-neurolink-grant-id"];if(!l||!u)return{ok:!1,stop:!0,reason:"no grant identified"};const d=await mce(u);if(!d||!d.leaseSecret||!ovn(d.leaseSecret,l))return{ok:!1,stop:!0,reason:"grant not recognized"};if(d.level!=="complete")return{ok:!1,stop:!0,reason:"grant is not a complete share"};if(d.state!=="active")return{ok:!1,stop:!0,reason:d.state};const m=c.body,h=Number(m?.coinsSpent??0);Number.isFinite(h)&&h>0&&await nvn(d,h);const f=await rvn(d,Number.isFinite(h)?h:0);return f.paused?(p.always(`[proxy] auto-paused share ${d.peerLabel}: ${f.detail}`),{ok:!1,stop:!0,reason:"usage drift"}):{ok:!0,lease:Ofr(d)}},description:"Complete-share heartbeat: report spend, renew the lease",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/handshake`,handler:async c=>{const l=await hy(c.headers);return py(l)?l.body:{ok:!0,protocol:svn,capabilities:ivn,grant:{peerLabel:l.grant.peerLabel,level:l.grant.level,state:l.grant.state,ledger:l.grant.entitlement.ledger}}},description:"Peer handshake: protocol version, capabilities, grant state",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/provision`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;if(l.grant.state!=="active")return Xw(l.grant.state==="paused"?"paused":"revoked",{status:403,grant:l.grant}).body;if(l.grant.level!=="complete")return{type:"error",error:{type:"invalid_request_error",message:"This is a live share. Ask the lender to run `neurolink proxy share level --to complete` first."}};const u=c.body,d=await _yn({grantId:l.grant.id,codeChallenge:String(u?.codeChallenge??""),state:String(u?.state??"")});return d.ok!==!0?{type:"error",error:{type:"invalid_request_error",message:d.reason}}:(p.always(`[proxy] ${l.grant.peerLabel} asked to be provisioned \u2014 run \`neurolink proxy share provision --peer ${l.grant.peerLabel}\``),{ok:!0,status:"pending",expiresAt:d.request.expiresAt})},description:"Lodge a PKCE challenge for a resident credential (complete shares)",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/provision`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=await Cyn(l.grant.id);if(u.status!=="ready")return{ok:!0,status:u.status};const d=await Kin();return{ok:!0,status:"ready",claim:Rgn({grant:l.grant,lenderName:"lender",...d?{lenderUrl:d}:{},code:u.code,state:u.state})}},description:"Collect the authorization code the lender produced",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/receipts`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=Number(c.query?.since??0);return{ok:!0,receipts:await Mar(l.grant.id,Number.isFinite(u)?u:0)}},description:"Collect signed receipts for this grant's settled charges",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/net`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=l.grant.receiptSecret;if(!u)return{type:"error",error:{type:"invalid_request_error",message:"This grant predates receipts and cannot be netted. Ask the lender to re-issue it."}};const d=c.body,m=Number(d?.consumedByYou??NaN),h=Number(d?.alreadyNetted??NaN);return!Number.isFinite(m)||!Number.isFinite(h)?{type:"error",error:{type:"invalid_request_error",message:"A netting claim needs both cumulative totals."}}:e$({consumedByYou:m,alreadyNetted:h,grantId:l.grant.id},String(d?.signature??""),u)?{ok:!0,...await Oar({grantId:l.grant.id,consumedFromPeer:m,peerAlreadyNetted:h})}:Xw("unknown_token",{status:401}).body},description:"Settle one round of reciprocal netting against this grant",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/note`,handler:async c=>{const l=c.body,u=Ryn(String(l?.note??""));if(!u)return{type:"error",error:{type:"invalid_request_error",message:"That is not a NeuroLink coin note."}};const d=await tan();if(!l?.redeem)return{ok:!0,...await Pyn(u,d)};const m=await hy(c.headers);if(py(m))return m.body;if(m.grant.entitlement.ledger!=="coins")return{type:"error",error:{type:"invalid_request_error",message:"This grant is unlimited \u2014 there is no balance to redeem into."}};const h=await Myn({note:u,grantId:m.grant.id,secret:d});return h.ok!==!0?{ok:!1,status:h.status,error:{type:"invalid_request_error",message:`That note is ${h.status}.`}}:{ok:!0,status:"redeemed",coins:h.coins,balance:h.balance??null}},description:"Check or redeem a transferable coin note",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/limits`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=a?.();return{ok:!0,...await avn(l.grant,u?.accountAllowlist??i)}},description:"Peer limits: remaining coins, slice left, whether the grant can be served",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/v1/models`,handler:async c=>{const l=a?a().modelRouter:e;return dt({name:"neurolink.http.claudeProxy.listModels",tracer:Be.http,attributes:{"http.route":`${t}/v1/models`}},async()=>egn(l))},description:"List available models (Anthropic schema)",tags:["claude-proxy","models"]},{method:"POST",path:`${t}/v1/messages/count_tokens`,handler:async c=>dt({name:"neurolink.http.claudeProxy.countTokens",tracer:Be.http,attributes:{"http.route":`${t}/v1/messages/count_tokens`}},async l=>{const u=c.body;if(typeof u?.model!="string"||!Array.isArray(u?.messages))return $i(400,"Missing required fields: model, messages");const d=u.messages.map(h=>typeof h.content=="string"?h.content:JSON.stringify(h.content)).join(" "),m=Math.ceil(d.length/4);return l.setAttribute("ai.model",u.model),l.setAttribute("gen_ai.usage.input_tokens",m),{input_tokens:m}}),description:"Count tokens for a messages request",tags:["claude-proxy","tokens"]},{method:"GET",path:`${t}/limits`,handler:async c=>{if(Hw())return Xw("no_capacity",{status:403,message:"This proxy does not expose pool limits to peers. Use GET /peer/limits for what your grant may still do."}).body;const l=a?.(),u=l?.accountAllowlist??i;dde(l?.useOverage);const d=c.query?.snapshot==="true"||c.query?.snapshot==="1",m=c.query?.account;return dt({name:"neurolink.http.claudeProxy.limits",tracer:Be.http,attributes:{"http.route":`${t}/limits`}},async()=>!d&&!m?(h3||(h3=cde({accountAllowlist:u}).finally(()=>{h3=null})),h3):cde({accountAllowlist:u,accountFilter:m,snapshotOnly:d}))},description:"Fetch fresh per-account limits from Anthropic (usage API). ?account=<label> for one account, ?snapshot=true for stored state",tags:["claude-proxy","limits"]},{method:"GET",path:`${t}/accounts`,handler:async c=>{const l=a?.(),u=l?.accountAllowlist??i,d=l?.primaryAccountKey??o,m=M=>!!d&&!!M&&Xae(M,d),h=c.query?.refresh==="true";h&&dde(l?.useOverage);let f={fetchedAt:Date.now(),snapshot:!h,results:[]},g=null;try{f=await cde({accountAllowlist:u,snapshotOnly:!h})}catch(M){g=M instanceof Error?M.message:String(M)}const{getUsageSnapshot:y}=await Promise.resolve().then(()=>(ix(),iar)),v=y().stats.accounts,w=Date.now();let E={};try{E=await kx()}catch{}const _=M=>{if(!M)return!1;const F=E[M]?.coolingUntil;return typeof F=="number"&&F>w};let C=new Map,A=null,k="";try{const{readAccountUsage:M,currentUsageDate:F}=await Promise.resolve().then(()=>(Aan(),Kar));k=F(),C=await M(k)}catch(M){A=M instanceof Error?M.message:String(M)}const R=new Map;for(const[M,F]of Object.entries(v)){const L=Hpr(F.label,F.type,F.key??M).key??M,q=R.get(L);(!q||F.key&&!q.key)&&R.set(L,{...F,identityKey:L})}let I;try{I=await w0n()}catch{I=null}const P=[],O=new Set;for(const M of f.results){const F=M.account;O.add(M.key);const N=R.get(M.key),L=Mvn(M.quota),q=_(M.key??null);P.push({label:F,key:M.key??null,provider:M.provider,kind:"account",type:M.type??N?.type??"oauth",status:q?"cooling":S3(L?.weeklyStatus)==="degraded"||S3(L?.sessionStatus)==="degraded"?"exhausted":"active",cooling:q,allowed:null,expired:null,isPrimary:m(M.key??F),requests:N?N.successCount+N.errorCount:null,errors:N?.errorCount??null,rateLimits:N?.rateLimitCount??null,quotaRateLimits:N?.quotaRateLimitCount??null,quota:L?{...L,sessionHealth:S3(L.sessionStatus),weeklyHealth:S3(L.weeklyStatus)}:null,usage:C.get(M.key)??null})}for(const M of R.values()){const F=Hpr(M.label,M.type,M.identityKey);if(F.key!==null&&O.has(F.key))continue;const N=F.provider!=="other";N&&F.key!==null&&I!==null&&!I.has(F.key)||P.push({label:M.label,key:N?F.key:null,...N?{provider:F.provider}:{},kind:N?"account":M.type==="translation"?"translation":"internal",type:F.provider==="codex"?"oauth":M.type,status:N?"unrouted":null,cooling:!1,allowed:null,expired:null,isPrimary:N?m(F.key):!1,requests:M.successCount+M.errorCount,errors:M.errorCount,rateLimits:M.rateLimitCount,quotaRateLimits:M.quotaRateLimitCount,quota:null,usage:F.key!==null?C.get(F.key)??null:null})}return{generatedAt:Date.now(),usageDate:k,quotaFromSnapshot:!h,usageError:A,quotaError:g,costBasis:"api-equivalent",accounts:P}},description:"One row per account: status, quota, and today's tokens and API-equivalent cost. ?refresh=true forces a live quota fetch",tags:["claude-proxy","accounts"]}]}}function $a(e){const t=pc.get(e);if(t)return t;const r={consecutiveRefreshFailures:0,permanentlyDisabled:!1};return pc.set(e,r),r}function Dvn(e){const t=$a(e.key),r=t.lastToken!==e.token||t.lastRefreshToken!==e.refreshToken,n=t.permanentlyDisabled;n&&p.always(`[proxy] account=${e.label} is enabled in the token store; clearing stale runtime auth-disable state`),t.permanentlyDisabled=!1,(r||n)&&(t.consecutiveRefreshFailures=0),t.lastToken=e.token,t.lastRefreshToken=e.refreshToken}async function wm(e,t,r){try{const{tokenStore:n}=await Promise.resolve().then(()=>(Xg(),ece)),o=e.persistTarget&&typeof e.persistTarget!="string"&&"providerKey"in e.persistTarget?e.persistTarget.providerKey:void 0;if(o){if(!await n.markDisabledIfCurrent(o,{accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt??0},r))return t.permanentlyDisabled=!1,p.always(`[proxy] account=${e.label} credentials changed while authentication was in flight; ignored stale disable`),!1}else await n.markDisabled(e.key,r)}catch(n){p.debug(`[proxy] failed to persist disabled state for ${e.label}: ${n instanceof Error?n.message:String(n)}`)}return t.permanentlyDisabled=!0,p.always(r==="entitlement_blocked"?`[proxy] account=${e.label} disabled: the organization blocks Claude Code OAuth. Ask an admin to re-enable it, then run: neurolink auth enable ${e.key}`:`[proxy] account=${e.label} disabled until re-authentication. Run: neurolink auth login anthropic --method oauth`),!0}async function b3(e,t){t.consecutiveRefreshFailures+=1;const r=Math.min(t.consecutiveRefreshFailures-1,4),n=Math.min(Qyn,Zyn*2**r),o=Date.now()+n;(!t.coolingUntil||o>t.coolingUntil)&&(t.coolingUntil=o,t.coolingReason="auth");const s=t.coolingUntil??o,i=t.coolingReason??"auth";return t.coolingUntil=s,t.coolingReason=i,await Vu(e.key,s,i).catch(()=>{}),s}async function _3(e,t){if(t.consecutiveRefreshFailures=0,t.coolingReason!=="auth"||!t.coolingUntil)return;const r=t.coolingUntil;t.coolingUntil=void 0,t.coolingReason=void 0,await Yp(e.key,r).catch(()=>{})}function C3(e){return`Account(s) require re-authentication: ${Array.isArray(e)?e.join(", "):e}. Run: neurolink auth login anthropic --method oauth`}function Cr(e,t=180){const r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t)}...`}function Sde(e){const t=Math.min(Math.max(e-1,0),Jue.length-1);return Jue[t]??0}function Kgr(e){const t=Math.min(Math.max(e-1,0),ugr.length-1);return Jgr(ugr[t]??250)}async function Zl(e){await new Promise(t=>setTimeout(t,e))}function Jgr(e){return e+Math.floor(Math.random()*e*.25)}function oI(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="string")return t;const r=e.cause;if(!r||typeof r!="object")return;const n=r.code;return typeof n=="string"?n:void 0}function Ql(e){const t=e instanceof Error?e.message:String(e);if(!e||typeof e!="object")return t;const r=e.cause,n=r instanceof Error?r.message:r&&typeof r=="object"?String(r.message??""):"",s=[oI(e),n&&n!==t&&n].filter(Boolean).join(": ");return s?`${t} (${s})`:t}function Ygr(e){const t=new Set;let r=e;for(;r&&typeof r=="object"&&!t.has(r);){t.add(r);const n=r;if(n.syscall==="connect")return!0;if(Array.isArray(n.errors)&&n.errors.length>0)return n.errors.every(o=>o!==null&&typeof o=="object"&&o.syscall==="connect");r=n.cause}return!1}function bde(e){if(Ygr(e))return!0;const t=oI(e);return t!==void 0&&["ECONNREFUSED","EADDRNOTAVAIL","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CONNECT"].includes(t)}function Nvn(e){const t=oI(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}var Lvn=new Set([408,500,502,503,504,520,521,522,523,524,525,526,529]);function Ku(e){try{const t=JSON.parse(e);if(t&&t.type==="error"&&t.error&&typeof t.error=="object"){const r=t.error.details?.error_code;return{errorType:typeof t.error.type=="string"?t.error.type:void 0,message:typeof t.error.message=="string"?t.error.message:void 0,...typeof r=="string"?{errorCode:r}:{}}}}catch{}return{}}function Fvn(e,t){return e===422?!0:Ku(t).errorType==="invalid_request_error"||t.includes("invalid_request_error")}function $vn(e,t){if(e!==404)return!1;const r=Ku(t);return r.errorType==="not_found_error"&&(r.message??"").toLowerCase().includes("model")}function Uvn(e,t){if(e!==400)return!1;const r=Ku(t);if(r.errorType!=="invalid_request_error")return!1;const n=(r.message??"").toLowerCase();return n.includes("beta")&&n.includes("subscription")&&n.includes("available")}var Xgr=new Set(["oauth_not_allowed_for_organization","oauth_not_allowed","organization_disabled"]);function _de(e,t){if(e!==401&&e!==402&&e!==403)return!1;const r=Ku(t);return r.errorType==="permission_error"?!0:r.errorCode!==void 0&&Xgr.has(r.errorCode)}function Zgr(e,t){if(!_de(e,t))return!1;const r=Ku(t);return r.errorCode!==void 0&&Xgr.has(r.errorCode)}function Bvn(e){return{...e,messages:e.messages.map(t=>typeof t.content!="string"?t:{...t,content:[{type:"text",text:t.content}]})}}var Qgr=Efr;function eyr(e,t){if(Lvn.has(e))return!0;if(e!==400)return!1;const r=Ku(t);if(r.errorType==="overloaded_error")return!0;if(r.errorType!=="api_error")return!1;const n=(r.message??t).toLowerCase();return n.includes("<!doctype html")||n.includes("error code 520")||n.includes("web server is returning an unknown error")||n.includes("cloudflare")||n.includes("internal server error")}function zvn(e,t){return e===529||Ku(t).errorType==="overloaded_error"}var qvn=500;function sE(e){return lr(e,qvn)}Ut(),z();var Gvn=55669,jvn="generateContent",tyr="streamGenerateContent";function Hvn(e){const r=e.split("?")[0].replace(/\/+$/,"").split("/").pop()??"",n=r.lastIndexOf(":");return n===-1?{modelId:r,action:void 0}:{modelId:r.slice(0,n),action:r.slice(n+1)}}function Vvn(e){return{model:e.model,maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,systemPrompt:e.systemPrompt,stream:e.stream,prompt:e.prompt,images:e.images,conversationMessages:e.conversationMessages,tools:e.tools,stopSequences:e.stopSequences}}function Wvn(e,t="",r=Gvn,n){return{prefix:`${t}/v1beta`,routes:[{method:"POST",path:`${t}/v1beta/models/:model`,description:"Gemini-compatible generateContent / streamGenerateContent (translation mode)",handler:async o=>{const s=n?n().modelRouter:e,i=Date.now(),{modelId:a,action:c}=Hvn(o.path);if(!a||c!==jvn&&c!==tyr)return Yle(404,`Unsupported Gemini endpoint: ${o.path}`,"NOT_FOUND");const l=o.body;if(!l||!Array.isArray(l.contents)||l.contents.length===0)return Yle(400,"Request must include a non-empty 'contents' array");const u=c===tyr,d=s?s.resolve(a):{provider:null,model:a},m=d.provider??void 0,h=d.model??a;p.debug(`[proxy:gemini] ${a} \u2192 ${m??"auto"}/${h}`);const f=khn(h,l,u),g=Vvn(f),v=tE({provider:m??"auto",model:h},s?.getFallbackChain()??[],a,g,s?.isAutoFallbackEnabled?.()??!1).attempts;let w;try{w=Ux.startRequest({requestId:o.requestId,method:o.method,path:o.path,model:a,stream:u,toolCount:Object.keys(f.tools).length,clientApp:"gemini-compat",userAgent:o.headers["user-agent"]??"",provider:m??"google-ai"},o.headers),w.setMode("full")}catch{}try{return u?await r3({ctx:o,format:"gemini",requestModel:a,parsed:f,attempts:v,tracer:w,requestStartTime:i}):await n3({ctx:o,format:"gemini",requestModel:a,parsed:f,attempts:v,tracer:w,requestStartTime:i})}catch(E){const _=E instanceof Error?E.message:String(E),C=lr(_);return p.always(`[proxy:gemini] request failed: ${C}`),w?.setError("generation_error",C),w?.end(500,Date.now()-i),Yle(500,"Internal proxy error","INTERNAL")}}}]}}Or(),pr();function Cde(e,t,r){return n=>dt({name:e,tracer:Be.http,attributes:{"http.route":t,"http.request.id":n.requestId??""}},()=>r(n))}function ryr(e="/api"){return{prefix:`${e}/health`,routes:[{method:"GET",path:`${e}/health`,handler:Cde("neurolink.http.health.check",`${e}/health`,async()=>({status:"ok",timestamp:new Date().toISOString(),uptime:process.uptime()*1e3,version:process.env.npm_package_version||"unknown"})),description:"Basic health check",tags:["health"]},{method:"GET",path:`${e}/health/live`,handler:Cde("neurolink.http.health.live",`${e}/health/live`,async()=>({status:"alive",timestamp:new Date().toISOString()})),description:"Kubernetes liveness probe",tags:["health"]},{method:"GET",path:`${e}/health/ready`,handler:t=>dt({name:"neurolink.http.health.ready",tracer:Be.http,attributes:{"http.route":`${e}/health/ready`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools(),o=n.length>0,s=!!t.externalServerManager;let i=!0;if(t.externalServerManager){const c=t.externalServerManager.getServerStatuses();for(const l of c)if(l.status!=="connected"){i=!1;break}}const a=o||!s||i;return r.setAttribute("health.ready",a),r.setAttribute("health.tools_count",n.length),r.setAttribute("health.external_servers_ready",i),{ready:a,timestamp:new Date().toISOString(),services:{neurolink:!0,tools:o,externalServers:i}}}),description:"Kubernetes readiness probe",tags:["health"]},{method:"GET",path:`${e}/health/startup`,handler:t=>dt({name:"neurolink.http.health.startup",tracer:Be.http,attributes:{"http.route":`${e}/health/startup`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools();return r.setAttribute("health.tools_count",n.length),{started:!0,timestamp:new Date().toISOString(),services:{neurolink:!0,toolsLoaded:n.length,externalServerManager:!!t.externalServerManager}}}),description:"Kubernetes startup probe",tags:["health"]},{method:"GET",path:`${e}/health/detailed`,handler:t=>dt({name:"neurolink.http.health.detailed",tracer:Be.http,attributes:{"http.route":`${e}/health/detailed`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools(),o={};for(const l of n){const u=typeof l.source=="string"?l.source:l.serverId||"built-in";o[u]=(o[u]||0)+1}const s=[];if(t.externalServerManager){const l=t.externalServerManager.getServerStatuses();for(const u of l)s.push({name:u.serverId,status:u.status,toolCount:u.toolCount})}const i=t.neurolink.conversationMemory,a={available:!!i,type:i?.constructor.name||"none"},c={status:"ok",timestamp:new Date().toISOString(),uptime:process.uptime()*1e3,version:process.env.npm_package_version||"unknown",node:{version:process.version,platform:process.platform,arch:process.arch},memory:{...a,process:{heapUsed:Math.round(process.memoryUsage().heapUsed/1024/1024),heapTotal:Math.round(process.memoryUsage().heapTotal/1024/1024),rss:Math.round(process.memoryUsage().rss/1024/1024),external:Math.round(process.memoryUsage().external/1024/1024)}},tools:{total:n.length,bySource:o},externalServers:{count:s.length,servers:s}};if(t.metadata?.accountPool){const l=t.metadata.accountPool,u=l.getAllAccounts(),d={};for(const m of u)d[m.status]=(d[m.status]||0)+1;c.proxy={totalAccounts:u.length,statusDistribution:d,healthyCount:l.getHealthyCount(),strategy:l.getStrategy()},r.setAttribute("health.proxy.accounts",u.length),r.setAttribute("health.proxy.healthy",l.getHealthyCount())}return r.setAttribute("health.tools_count",n.length),r.setAttribute("health.external_servers_count",s.length),r.setAttribute("health.memory.heap_mb",Math.round(process.memoryUsage().heapUsed/1024/1024)),c}),description:"Detailed health information",tags:["health"]},{method:"GET",path:`${e}/version`,handler:Cde("neurolink.http.version",`${e}/version`,async()=>({name:"@juspay/neurolink",version:process.env.npm_package_version||"unknown",node:process.version,timestamp:new Date().toISOString()})),description:"Get version information",tags:["health","version"]}]}}ix(),Lr(),Ut(),z();var Kvn=300*1e3,Jvn=55669;function nyr(e){return e?{status:502,errorType:"loopback_stream_error",errorMessage:e}:{status:499,errorType:"client_cancelled",errorMessage:"Client cancelled the OpenAI-compatible stream"}}function A3(e,t){return new Response(JSON.stringify(Lhr(e,t)),{status:e,headers:{"content-type":"application/json"}})}function Yvn(e){return{model:e.model,maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,systemPrompt:typeof e.systemPrompt=="string"?e.systemPrompt:void 0,stream:e.stream,prompt:e.prompt,images:e.images,conversationMessages:e.conversationMessages,tools:e.tools,toolChoice:e.toolChoice,toolChoiceName:e.toolChoiceName,stopSequences:e.stopSequences}}function Xvn(e,t){try{const r=Ux.startRequest({requestId:e.requestId,method:e.method,path:e.path,model:t.model,stream:t.stream===!0,toolCount:t.tools?.length??0,provider:"openai-bridge",recordRequestMetrics:!0,recordUsageMetrics:!1,...Fx(e.headers)},e.headers);return r.setMode("full"),r}catch{return}}function Zvn(e,t,r){const n={"content-type":"application/json",accept:t?"text/event-stream":"application/json","x-neurolink-internal-request":r},o=iue(e.requestId);o&&(n.traceparent=`00-${o.traceId}-${o.spanId}-${o.traceFlags.toString(16).padStart(2,"0")}`);for(const[s,i]of Object.entries(e.headers)){if(typeof i!="string")continue;const a=s.toLowerCase();(a.startsWith("anthropic-")||a==="x-api-key"||["user-agent","x-neurolink-session-id","x-claude-code-session-id","session_id","session-id","tracestate","baggage"].includes(a)||a==="traceparent"&&!n.traceparent)&&(n[a]=i)}return n}function Qvn(e){const t=e?.servingModelStatus??"unavailable",r=e?.accountIdentityStatus??(e?.accountKey&&e.accountType!=="translation"&&e.account!=="unknown"?"observed":"unavailable");return{servingModelStatus:t,accountIdentityStatus:r}}async function eTn(e,t,r,n,o,s){try{const i=await id(e.json(),t),a=Dhn(i,r);return s.json(a,200),await n(200),a}catch(i){const a=t.aborted&&t.reason?.name!=="TimeoutError"?499:t.reason?.name==="TimeoutError"?504:502;return await n(a,{errorType:a===499?"client_cancelled":a===504?"loopback_timeout":"loopback_response_error",errorMessage:i instanceof Error?i.message:String(i)}),o(a,"Anthropic loopback failed")}}async function tTn(e){const{ctx:t,body:r,targetModel:n,requestStartTime:o,loopbackPort:s,internalDispatch:i}=e,a=r.stream===!0,c=r.tools?.length??0,l=vfr(t,r.model,a,o);l.request();const u=(E,_)=>(l.json(Lhr(E,_),E),A3(E,_)),d=Thn(t.requestId),m=Xvn(t,r),h=new AbortController,f=AbortSignal.any([h.signal,AbortSignal.timeout(Kvn),...t.abortSignal?[t.abortSignal]:[]]);let g=!1;const y=(E,_={})=>{if(g)return Promise.resolve();g=!0,d.dispose();const C=vhn(t.requestId),{servingModelStatus:A,accountIdentityStatus:k}=Qvn(C);return A==="observed"&&C?.model&&C.model!==r.model&&m?.setModelSubstitution(r.model,C.model,C.provider),_.errorType&&m?.setError(_.errorType,_.errorMessage??_.errorType),m?.end(E,Date.now()-o),Fw(t.requestId)||(E>=400?Zg(E,C?.account,C?.accountType,{requestId:t.requestId,errorType:_.errorType,message:_.errorMessage,terminalOutcome:E===499?"client_cancelled":_.errorType?.includes("stream")?"stream_error":"handler_error"}):nx(C?.account,C?.accountType)),Kw({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:C?.model??r.model,servingModelStatus:A,stream:a,toolCount:c,account:C?.account??"",accountKey:C?.accountKey,accountType:C?.accountType??"openai-bridge",accountIdentityStatus:k,requestedModel:r.model,provider:C?.provider,errorCode:C?.errorCode,transportScope:C?.transportScope,retryable:C?.retryable,accountingScope:"client",usageOwnerRequestId:d.requestId,...Fx(t.headers),responseStatus:E,responseTimeMs:Date.now()-o,..._}).finally(()=>bhr(t.requestId))},v=`http://127.0.0.1:${s}/v1/messages`;let w;try{f.throwIfAborted();const E=Ohn(r);E.model=n;const C={method:"POST",headers:Zvn(t,a,d.token),body:JSON.stringify({...E,stream:a}),signal:f};w=await id(Promise.resolve(i?i(new Request(v,C)):fetch(v,C)),f)}catch(E){d.dispose();const _=t.abortSignal?.aborted?499:f.aborted?504:502;return h.abort(E),await y(_,{errorType:t.abortSignal?.aborted?"client_cancelled":_===504?"loopback_timeout":"loopback_exception",errorMessage:E instanceof Error?E.message:String(E)}),u(_,"Anthropic loopback failed")}if(!w.ok){const E=await id(w.text(),f).catch(()=>""),_=lr(E);return p.always(`[proxy:openai] anthropic loopback error ${w.status}: ${_}`),await y(w.status,{errorType:"loopback_upstream_error",errorMessage:_}),u(w.status,_||`Anthropic loopback failed with status ${w.status}`)}if(a){if(!w.body)return await y(502,{errorType:"loopback_empty_stream",errorMessage:"Anthropic loopback returned empty stream body"}),u(502,"Anthropic loopback returned empty stream body");const E=l.accumulator("client_response","text/event-stream");let _;const A=w.body.pipeThrough(Nhn(r.model,{onError:P=>{_=lr(P)}})).getReader(),k=async(P,O,U)=>{f.removeEventListener("abort",R),E.finish(P),await y(P,{errorType:O,errorMessage:U})},R=()=>{const P=_?nyr(_):{status:f.reason?.name==="TimeoutError"?504:499,errorType:f.reason?.name==="TimeoutError"?"loopback_timeout":"client_cancelled",errorMessage:"Anthropic loopback cancelled"};k(P.status,P.errorType,P.errorMessage),Ct(A.cancel(f.reason),1e3,"Loopback cancellation timed out").catch(()=>{})};f.addEventListener("abort",R,{once:!0}),f.aborted&&R();const I=new ReadableStream({async pull(P){try{const{value:O,done:U}=await A.read();if(U){_?await k(502,"loopback_stream_error",_):await k(200),P.close();return}E.append(O),P.enqueue(O)}catch(O){const U=lr(O instanceof Error?O.message:String(O));await k(502,"loopback_stream_error",U),P.error(O)}},async cancel(P){const O=nyr(_),U=k(O.status,O.errorType,O.errorMessage);h.abort(P),await Promise.all([U,Ct(A.cancel(P),1e3,"Loopback cancellation timed out").catch(()=>{})])}});return new Response(I,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}})}return eTn(w,f,r.model,y,u,l)}function rTn(e,t="",r=Jvn,n,o){return{prefix:`${t}/v1`,routes:[{method:"POST",path:`${t}/v1/chat/completions`,description:"OpenAI-compatible chat completions (translation mode)",handler:async s=>{const i=n?n().modelRouter:e,a=Date.now(),c=s.body;if(!c||!c.model||!c.messages?.length)return A3(400,"Request must include 'model' and 'messages' fields");const l=i?i.resolve(c.model):{provider:null,model:c.model},u=l.provider??void 0,d=l.model??c.model;if(p.debug(`[proxy:openai] ${c.model} \u2192 ${u??"auto"}/${d}`),l.provider==="anthropic")try{return await tTn({ctx:s,body:c,targetModel:d,requestStartTime:a,loopbackPort:r,internalDispatch:o})}catch(v){const w=v instanceof Error?v.message:String(v),E=lr(w);p.always(`[proxy:openai] anthropic loopback failed: ${E}`);const _=s.abortSignal?.aborted?499:v instanceof Error&&"status"in v&&v.status===503?503:v instanceof Error&&v.name==="TimeoutError"?504:502;return Fw(s.requestId)||Zg(_,void 0,void 0,{requestId:s.requestId,errorType:_===499?"client_cancelled":"loopback_exception",message:E}),await Kw({timestamp:new Date().toISOString(),requestId:s.requestId,method:s.method,path:s.path,model:c.model,stream:c.stream===!0,toolCount:c.tools?.length??0,account:"",accountType:"openai-bridge",responseStatus:_,responseTimeMs:Date.now()-a,errorType:_===499?"client_cancelled":"loopback_exception",errorMessage:E}).finally(()=>bhr(s.requestId)),A3(_,"Anthropic loopback failed")}const m=Phn(c),h=Yvn(m),g=tE({provider:u??"auto",model:d},i?.getFallbackChain()??[],c.model,h,i?.isAutoFallbackEnabled?.()??!1).attempts;let y;try{y=Ux.startRequest({requestId:s.requestId,method:s.method,path:s.path,model:c.model,stream:c.stream===!0,toolCount:Object.keys(m.tools).length,clientApp:"openai-compat",userAgent:s.headers["user-agent"]??"",provider:u??"openai-compatible"},s.headers),y.setMode("full")}catch{}try{return c.stream?r3({ctx:s,format:"openai",requestModel:c.model,parsed:m,attempts:g,tracer:y,requestStartTime:a}):await n3({ctx:s,format:"openai",requestModel:c.model,parsed:m,attempts:g,tracer:y,requestStartTime:a})}catch(v){const w=v instanceof Error?v.message:String(v),E=lr(w);return p.always(`[proxy:openai] request failed: ${E}`),y?.setError("generation_error",E),y?.end(500,Date.now()-a),A3(500,"Internal proxy error")}}},{method:"GET",path:`${t}/v1/models`,description:"List available models in OpenAI format",handler:async()=>{const s=n?n().modelRouter:e;return Qfn(s)}}]}}Xt(),en(),Or(),pr(),Uu();function fy(e,t,r){return n=>dt({name:e,tracer:Be.http,attributes:{"http.route":t,"http.request.id":n.requestId}},async o=>{const s=await r(n);if(s&&typeof s=="object"){const i=s.error;if(i!=null){const a=typeof i=="string"?i:typeof i?.message=="string"?i.message:"MCP handler error";o.setStatus({code:Ue.ERROR,message:a})}}return s})}var nTn=D.object({name:D.string().min(1,"Server name is required"),toolName:D.string().min(1,"Tool name is required")});async function oTn(e){const t=e.externalServerManager;if(!t)return{servers:[],total:0,message:"External server manager not available",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}};const r=t.listServers(),n=t.getServerStatuses(),o=new Map(n.map(i=>[i.serverId,i])),s=r.map(i=>{const a=o.get(i.name);return{serverId:i.name,name:i.name,status:a?.status||"disconnected",toolCount:a?.toolCount||0,lastHealthCheck:a?.checkedAt?.toISOString(),error:a?.issues?.[0]}});return{servers:s,total:s.length,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function sTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Bt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);if(!n.listServers().find(u=>u.name===r))return Bt("SERVER_NOT_FOUND",`MCP server '${r}' not found`,void 0,e.requestId);const a=n.getServerStatuses().find(u=>u.serverId===r),l=(await e.toolRegistry.listTools()).filter(u=>u.source===r);return{serverId:r,name:r,status:a?.status||"disconnected",toolCount:a?.toolCount||0,tools:l.map(u=>({name:u.name,description:u.description})),lastHealthCheck:a?.checkedAt?.toISOString(),error:a?.issues?.[0],metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function iTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Bt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);try{if(!n.listServers().find(c=>c.name===r))return Bt("SERVER_NOT_FOUND",`Server '${r}' not found`,void 0,e.requestId);const a=n.getServerStatuses().find(c=>c.serverId===r);return{success:!0,server:{serverId:r,name:r,status:a?.status||"disconnected",toolCount:a?.toolCount||0},message:"Server status retrieved (full reconnect requires server restart)",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(o){return Bt("RECONNECT_FAILED",o instanceof Error?o.message:String(o),void 0,e.requestId)}}async function aTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Bt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);try{const o=await n.removeServer(r);return o.success?{success:!0,message:`Server '${r}' removed`,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}:Bt("REMOVE_FAILED",o.error||"Failed to remove server",void 0,e.requestId)}catch(o){return Bt("REMOVE_FAILED",o instanceof Error?o.message:String(o),void 0,e.requestId)}}async function cTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,o=(await e.toolRegistry.listTools()).filter(s=>s.source===r);if(o.length===0){const s=e.externalServerManager;if(s&&!s.listServers().find(c=>c.name===r))return Bt("SERVER_NOT_FOUND",`MCP server '${r}' not found`,void 0,e.requestId)}return{serverId:r,tools:o.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema})),total:o.length,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function lTn(e){const t=Gl(nTn,e.params,e.requestId);if(!t.success)return t.error;const{name:r,toolName:n}=t.data,o=$u(jF,e.body||{},e.requestId);if(!o.success)return o.error;const s=o.data,i=Date.now();try{return(await e.toolRegistry.listTools()).find(u=>u.name===n&&u.source===r)?{success:!0,data:await e.toolRegistry.executeTool(n,s),duration:Date.now()-i,metadata:{server:r,toolName:n,timestamp:new Date().toISOString(),requestId:e.requestId}}:Bt("TOOL_NOT_FOUND",`Tool '${n}' not found on server '${r}'`,void 0,e.requestId)}catch(a){return Bt("EXECUTION_FAILED",a instanceof Error?a.message:String(a),{duration:Date.now()-i},e.requestId)}}async function uTn(e){const t=e.externalServerManager;if(!t)return{healthy:!1,message:"External server manager not available",servers:[]};const n=t.getServerStatuses().map(i=>({name:i.serverId,healthy:i.isHealthy,error:i.issues?.[0]})),o=n.every(i=>i.healthy),s=n.some(i=>i.healthy);return{healthy:n.length===0||o,status:n.length===0?"no_servers":o?"all_healthy":s?"degraded":"unhealthy",servers:n,timestamp:new Date().toISOString()}}function oyr(e="/api"){return{prefix:`${e}/mcp`,routes:[{method:"GET",path:`${e}/mcp/servers`,handler:fy("neurolink.http.mcp.listServers",`${e}/mcp/servers`,oTn),description:"List all MCP servers",tags:["mcp"]},{method:"GET",path:`${e}/mcp/servers/:name`,handler:fy("neurolink.http.mcp.getServer",`${e}/mcp/servers/:name`,sTn),description:"Get MCP server status",tags:["mcp"]},{method:"POST",path:`${e}/mcp/servers/:name/reconnect`,handler:fy("neurolink.http.mcp.reconnectServer",`${e}/mcp/servers/:name/reconnect`,iTn),description:"Reconnect to an MCP server",tags:["mcp"]},{method:"DELETE",path:`${e}/mcp/servers/:name`,handler:fy("neurolink.http.mcp.removeServer",`${e}/mcp/servers/:name`,aTn),description:"Remove an MCP server",tags:["mcp"]},{method:"GET",path:`${e}/mcp/servers/:name/tools`,handler:fy("neurolink.http.mcp.listServerTools",`${e}/mcp/servers/:name/tools`,cTn),description:"List tools from a specific MCP server",tags:["mcp","tools"]},{method:"POST",path:`${e}/mcp/servers/:name/tools/:toolName/execute`,handler:fy("neurolink.http.mcp.executeTool",`${e}/mcp/servers/:name/tools/:toolName/execute`,lTn),description:"Execute a tool from a specific MCP server",tags:["mcp","tools"]},{method:"GET",path:`${e}/mcp/health`,handler:fy("neurolink.http.mcp.health",`${e}/mcp/health`,uTn),description:"Health check for all MCP servers",tags:["mcp","health"]}]}}Or(),pr(),Uu();function gy(e,t,r){return n=>dt({name:e,tracer:Be.http,attributes:{"http.route":t,"http.request.id":n.requestId}},()=>r(n))}async function dTn(e){const t=Gl(Gae,e.params,e.requestId);if(!t.success)return t.error;const{id:r}=t.data,n=e.query.limit?parseInt(e.query.limit,10):50,o=e.query.offset?parseInt(e.query.offset,10):0,s=isNaN(n)||n<1?50:Math.min(n,100),i=isNaN(o)||o<0?0:o,a=e.neurolink.conversationMemory;if(!a)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{let c=[];if("getUserSessionHistory"in a){const d=e.query.userId||"default",m=await a.getUserSessionHistory(d,r);if(m===null)return Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId);c=m}else if("getSession"in a){const d=a.getSession(r);if(!d)return Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId);c=d.messages}else if("buildContextMessages"in a&&(c=await a.buildContextMessages(r),c.length===0))return Bt("SESSION_NOT_FOUND",`Session '${r}' not found or has no messages`,void 0,e.requestId);const l=c.length,u=c.slice(i,i+s);return{sessionId:r,messages:u,total:l,limit:s,offset:i,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(c){return Bt("MEMORY_ERROR",c instanceof Error?c.message:"Failed to get session messages",void 0,e.requestId)}}async function mTn(e){const t=Gl(Gae,e.params,e.requestId);if(!t.success)return t.error;const{id:r}=t.data,n=e.neurolink.conversationMemory;if(!n)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{if("getUserSessionObject"in n){const o=e.query.userId||"default",s=await n.getUserSessionObject(o,r);return s===null?Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId):{session:s,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}else if("getSession"in n){const o=n.getSession(r);return o?{session:o,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}:Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId)}return Bt("MEMORY_ERROR","Session retrieval not supported for this memory type",void 0,e.requestId)}catch(o){return Bt("MEMORY_ERROR",o instanceof Error?o.message:"Failed to get session",void 0,e.requestId)}}async function pTn(e){const t=e.query.userId,r=e.query.limit?parseInt(e.query.limit,10):50,n=e.query.offset?parseInt(e.query.offset,10):0,o=isNaN(r)||r<1?50:Math.min(r,100),s=isNaN(n)||n<0?0:n,i=e.neurolink.conversationMemory;if(!i)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{let a=[];if("getUserAllSessionsHistory"in i&&t)a=await i.getUserAllSessionsHistory(t);else if("getUserSessions"in i&&t){const u=await i.getUserSessions(t);if("getUserSessionMetadata"in i){const d=u.map(h=>i.getUserSessionMetadata(t,h));a=(await Promise.all(d)).filter(h=>h!==null)}else a=u.map(d=>({id:d}))}else if("getStats"in i){const u=await i.getStats?.();return{sessions:[],total:u?.totalSessions||0,limit:o,offset:s,message:"Session listing not fully supported for in-memory storage. Use /stats endpoint for session counts.",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}const c=a.length;return{sessions:a.slice(s,s+o),total:c,limit:o,offset:s,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(a){return Bt("MEMORY_ERROR",a instanceof Error?a.message:"Failed to list sessions",void 0,e.requestId)}}async function hTn(e){const t=e.neurolink.conversationMemory;if(!t)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{const r=await t.getStats?.();return{available:!0,type:t.constructor.name,stats:r||{message:"Statistics not available for this memory type"},timestamp:new Date().toISOString()}}catch(r){return Bt("MEMORY_ERROR",r instanceof Error?r.message:"Failed to get statistics",void 0,e.requestId)}}async function fTn(e){const t=Gl(qae,e.params,e.requestId);if(!t.success)return t.error;const{sessionId:r}=t.data,n=e.neurolink.conversationMemory;if(!n)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{return await n.clearSession?.(r)===!1?Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId):{success:!0,sessionId:r,message:"Session cleared successfully",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(o){return Bt("MEMORY_ERROR",o instanceof Error?o.message:"Failed to clear session",void 0,e.requestId)}}async function gTn(e){const t=e.neurolink.conversationMemory;if(!t)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{return await t.clearAllSessions?.(),{success:!0,message:"All sessions cleared successfully",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(r){return Bt("MEMORY_ERROR",r instanceof Error?r.message:"Failed to clear sessions",void 0,e.requestId)}}async function yTn(e){const t=e.neurolink.conversationMemory;return{available:!!t,type:t?.constructor.name||"none",timestamp:new Date().toISOString()}}function syr(e="/api"){return{prefix:`${e}/memory`,routes:[{method:"GET",path:`${e}/memory/sessions/:id/messages`,handler:gy("neurolink.http.memory.getSessionMessages",`${e}/memory/sessions/:id/messages`,dTn),description:"Get messages for a session",tags:["memory"]},{method:"GET",path:`${e}/memory/sessions/:id`,handler:gy("neurolink.http.memory.getSession",`${e}/memory/sessions/:id`,mTn),description:"Get session by ID",tags:["memory"]},{method:"GET",path:`${e}/memory/sessions`,handler:gy("neurolink.http.memory.listSessions",`${e}/memory/sessions`,pTn),description:"List all conversation sessions",tags:["memory"]},{method:"GET",path:`${e}/memory/stats`,handler:gy("neurolink.http.memory.stats",`${e}/memory/stats`,hTn),description:"Get memory statistics",tags:["memory"]},{method:"DELETE",path:`${e}/memory/sessions/:sessionId`,handler:gy("neurolink.http.memory.clearSession",`${e}/memory/sessions/:sessionId`,fTn),description:"Clear a conversation session",tags:["memory"]},{method:"DELETE",path:`${e}/memory/sessions`,handler:gy("neurolink.http.memory.clearAllSessions",`${e}/memory/sessions`,gTn),description:"Clear all conversation sessions",tags:["memory"]},{method:"GET",path:`${e}/memory/health`,handler:gy("neurolink.http.memory.health",`${e}/memory/health`,yTn),description:"Check memory system health",tags:["memory","health"]}]}}z(),Or(),pr();function vTn(e="/api",t){return t||p.debug("[OpenAPI] createOpenApiRoutes called without getRoutes callback. Custom routes will not be documented in the OpenAPI spec."),{prefix:`${e}/openapi`,routes:[{method:"GET",path:`${e}/openapi.json`,handler:async()=>dt({name:"neurolink.http.openapi.json",tracer:Be.http,attributes:{"http.route":`${e}/openapi.json`,"openapi.format":"json"}},async r=>{const n=t?.()??[];return t?n.length===0&&p.debug("[OpenAPI] getRoutes returned empty array. No custom routes will be documented."):p.warn("[OpenAPI] No getRoutes callback provided. OpenAPI spec will use default endpoint definitions. Use registerAllRoutes(server, basePath, { enableSwagger: true }) to automatically include your routes."),r.setAttribute("openapi.route_count",n.length),new Ax({basePath:e,routes:n}).generate()}),description:"Get OpenAPI specification as JSON",tags:["openapi","documentation"]},{method:"GET",path:`${e}/openapi.yaml`,handler:async()=>dt({name:"neurolink.http.openapi.yaml",tracer:Be.http,attributes:{"http.route":`${e}/openapi.yaml`,"openapi.format":"yaml"}},async r=>{const n=t?.()??[];return t?n.length===0&&p.debug("[OpenAPI] getRoutes returned empty array. No custom routes will be documented."):p.warn("[OpenAPI] No getRoutes callback provided. OpenAPI spec will use default endpoint definitions. Use registerAllRoutes(server, basePath, { enableSwagger: true }) to automatically include your routes."),r.setAttribute("openapi.route_count",n.length),{_raw:!0,contentType:"text/yaml",body:new Ax({basePath:e,routes:n}).toYAML()}}),description:"Get OpenAPI specification as YAML",tags:["openapi","documentation"]},{method:"GET",path:`${e}/docs`,handler:async()=>dt({name:"neurolink.http.openapi.docs",tracer:Be.http,attributes:{"http.route":`${e}/docs`}},async()=>({_raw:!0,contentType:"text/html",body:`<!DOCTYPE html>
|
|
2368
|
+
`;R.enqueue(new TextEncoder().encode(O)),R.close()}}},cancel(){return _=!0,E.cancel(),v.cancel()}}),{response:A,telemetryDone:k}=wvn({ctx:t,account:n,response:s,responseHeaders:i,remainingStream:C,streamOutcome:E.outcome,tracer:a,requestStartTime:c,attemptNumber:u,finalBodyStr:d,upstreamSpan:m,logAttempt:h,logProxyBody:f,logFinalRequest:y});return k.then(()=>g?.(),()=>g?.()),{response:A,holdsAccountAdmission:!0,served:!0}}function sh(e){if(e.kind==="upstream_error")return{status:502,errorType:"stream_error",message:e.message};if(e.kind==="client_cancelled")return{status:499,errorType:"client_cancelled",message:"Client cancelled the streaming response"}}function E3(e,t,r){e.kind==="upstream_error"&&(Pr(t.label,t.type,502),r(502,"stream_error",e.message,{retryable:!1}))}function wvn(e){const{ctx:t,account:r,response:n,responseHeaders:o,remainingStream:s,streamOutcome:i,tracer:a,requestStartTime:c,attemptNumber:l,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:f}=e,{stream:g,capture:y}=Pue();let v=s,w;if(a)try{const{stream:C,telemetry:A}=U$({captureRawText:!0});v=v.pipeThrough(C);const k=a,R=d,I=n,P=u.length,O=r.label,U=r.key;w=Promise.all([A,y,i]).then(([M,F,N])=>{const L=i3(N,M.streamErrorMessage,M.messageStopReceived);x$(t.metadata,M),E3(L,r,m),k.setUsage({inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens}),yde(U,M.model,{inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens}),gde(O,M.model,{inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens}),k.logStreamEvents(M.events),k.setResponseInfo(Pgr(M));const q=parseFloat(I.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),B=parseFloat(I.headers.get("anthropic-ratelimit-unified-7d-utilization")??""),H={inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens};isNaN(q)||(H.rateLimitAfter5h=q),isNaN(B)||(H.rateLimitAfter7d=B),(!isNaN(q)||!isNaN(B))&&k.setUsage(H),k.logUpstreamResponseBody(M.rawText??""),k.recordMetrics(),k.recordBodySizes(P,M.totalBytesReceived),R?.end();const G=sh(L),X={inputTokens:M.usage.inputTokens,outputTokens:M.usage.outputTokens,cacheCreationTokens:M.usage.cacheCreationInputTokens,cacheReadTokens:M.usage.cacheReadInputTokens};G?(k.setError(G.errorType,G.message),k.end(G.status,Date.now()-c),f(G.status,O,r.type,G.errorType,G.message,X)):(k.end(200,Date.now()-c),f(200,O,r.type,void 0,void 0,X)),h({phase:"upstream_response",headers:o,body:M.rawText??"",sourceTruncated:M.rawTextTruncated,bodySize:M.totalBytesReceived,contentType:o["content-type"]??"text/event-stream",account:O,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c}),h({phase:"client_response",headers:o,body:F.text,sourceTruncated:F.truncated,bodySize:F.totalBytes,contentType:o["content-type"]??"text/event-stream",account:O,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c})}).catch(M=>{k.setError("stream_telemetry_error",M instanceof Error?M.message:String(M)),R?.end(),k.end(500,Date.now()-c),f(500,O,r.type,"stream_telemetry_error",M instanceof Error?M.message:String(M))})}catch{w=i.then(C=>{E3(C,r,m);const A=sh(C);d?.end(),A?(a.setError(A.errorType,A.message),a.end(A.status,Date.now()-c),f(A.status,r.label,r.type,A.errorType,A.message)):(a.end(n.status,Date.now()-c),f(n.status,r.label,r.type))}).catch(()=>{})}else{d?.end();try{const{stream:C,telemetry:A}=U$({captureRawText:!0});v=v.pipeThrough(C);const k=r.label,R=r.key;w=Promise.all([A,y,i]).then(([I,P,O])=>{const U=i3(O,I.streamErrorMessage,I.messageStopReceived);x$(t.metadata,I),E3(U,r,m);const M=sh(U),F={inputTokens:I.usage.inputTokens,outputTokens:I.usage.outputTokens,cacheCreationTokens:I.usage.cacheCreationInputTokens,cacheReadTokens:I.usage.cacheReadInputTokens};yde(R,I.model,F),gde(k,I.model,F),M?f(M.status,k,r.type,M.errorType,M.message,F):f(200,k,r.type,void 0,void 0,F),h({phase:"upstream_response",headers:o,body:I.rawText??"",sourceTruncated:I.rawTextTruncated,bodySize:I.totalBytesReceived,contentType:o["content-type"]??"text/event-stream",account:k,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c}),h({phase:"client_response",headers:o,body:P.text,sourceTruncated:P.truncated,bodySize:P.totalBytes,contentType:o["content-type"]??"text/event-stream",account:k,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c})}).catch(I=>{const P=I instanceof Error?I.message:String(I);f(500,r.label,r.type,"stream_telemetry_error",P)})}catch{y.then(C=>{h({phase:"client_response",headers:o,body:C.text,sourceTruncated:C.truncated,bodySize:C.totalBytes,contentType:o["content-type"]??"text/event-stream",account:r.label,accountType:r.type,attempt:l,responseStatus:200,durationMs:Date.now()-c})}).catch(()=>{}),w=i.then(C=>{E3(C,r,m);const A=sh(C);A?f(A.status,r.label,r.type,A.errorType,A.message):f(n.status,r.label,r.type)}).catch(()=>{})}}const E=v.pipeThrough(g);$w(t.metadata,{onTerminal:()=>w});const _={...t.responseHeaders??{},"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"};return{response:new Response(E,{status:n.status,headers:_}),telemetryDone:w}}async function Evn(e){const{ctx:t,account:r,response:n,responseHeaders:o,tracer:s,requestStartTime:i,fetchStartMs:a,attemptNumber:c,finalBodyStr:l,upstreamSpan:u,logAttempt:d,logProxyBody:m,logFinalRequest:h}=e,f=await n.text();d(n.status,void 0,void 0,{attemptDurationMs:Date.now()-a}),s?.logUpstreamResponseBody(f),m({phase:"upstream_response",headers:o,body:f,bodySize:Buffer.byteLength(f,"utf8"),contentType:o["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:c,responseStatus:n.status,durationMs:Date.now()-a}),m({phase:"client_response",headers:o,body:f,bodySize:Buffer.byteLength(f,"utf8"),contentType:o["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:c,responseStatus:n.status,durationMs:Date.now()-i});const g=JSON.parse(f);if(k$(t.metadata,g),Ogr(r,g),s&&g&&typeof g=="object"){const y=g.usage;if(y){s.setUsage({inputTokens:y.input_tokens??0,outputTokens:y.output_tokens??0,cacheCreationTokens:y.cache_creation_input_tokens??0,cacheReadTokens:y.cache_read_input_tokens??0});const w=parseFloat(n.headers.get("anthropic-ratelimit-unified-5h-utilization")??""),E=parseFloat(n.headers.get("anthropic-ratelimit-unified-7d-utilization")??"");if(!isNaN(w)||!isNaN(E)){const _={inputTokens:y.input_tokens??0,outputTokens:y.output_tokens??0,cacheCreationTokens:y.cache_creation_input_tokens??0,cacheReadTokens:y.cache_read_input_tokens??0};isNaN(w)||(_.rateLimitAfter5h=w),isNaN(E)||(_.rateLimitAfter7d=E),s.setUsage(_)}}s.setResponseInfo(fde(g)),s.recordMetrics();const v=JSON.stringify(g);s.recordBodySizes(l.length,v.length),u?.end(),s.end(n.status,Date.now()-i),h(n.status,r.label,r.type,void 0,void 0,{inputTokens:y?.input_tokens,outputTokens:y?.output_tokens,cacheCreationTokens:y?.cache_creation_input_tokens,cacheReadTokens:y?.cache_read_input_tokens})}else{u?.end();const y=g&&typeof g=="object"?g.usage:void 0;h(n.status,r.label,r.type,void 0,void 0,{inputTokens:y?.input_tokens,outputTokens:y?.output_tokens,cacheCreationTokens:y?.cache_creation_input_tokens,cacheReadTokens:y?.cache_read_input_tokens})}return{response:g,served:!0}}async function Svn(e){const{ctx:t,account:r,accountState:n,requestedModel:o,retryResp:s,tracer:i,requestStartTime:a,fetchStartMs:c,attemptNumber:l,finalBodyStr:u,upstreamSpan:d,logAttempt:m,logProxyBody:h,logFinalRequest:f}=e,g=Mw(s.headers,{model:o});if(g){n.quota=fm(n.quota,g);const E=ade(n,g,Date.now());E?.kind==="cooled"?Vu(r.key,E.coolingUntil,E.coolingReason).catch(()=>{}):E?.kind==="cleared"&&Yp(r.key,E.coolingUntil).catch(()=>{}),Zp(r.key,g).catch(_=>{p.debug("[proxy] Failed to persist account quota after auth retry",{account:r.label,error:_ instanceof Error?_.message:String(_)})})}const y=Object.fromEntries([...s.headers.entries()]),v=await s.text();m(s.status,void 0,void 0,{attemptDurationMs:Date.now()-c}),i?.logUpstreamResponseHeaders(y),i?.logUpstreamResponseBody(v),h({phase:"upstream_response",headers:y,body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:y["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:l,responseStatus:s.status,durationMs:Date.now()-c}),h({phase:"client_response",headers:y,body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:y["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:l,responseStatus:s.status,durationMs:Date.now()-a});const w=JSON.parse(v);if(k$(t.metadata,w),Ogr(r,w),i&&w&&typeof w=="object"){const E=w.usage;E&&i.setUsage({inputTokens:E.input_tokens??0,outputTokens:E.output_tokens??0,cacheCreationTokens:E.cache_creation_input_tokens??0,cacheReadTokens:E.cache_read_input_tokens??0}),i.setResponseInfo(fde(w)),i.recordMetrics();const _=JSON.stringify(w);i.recordBodySizes(u.length,_.length),d?.end(),i.end(s.status,Date.now()-a),f(s.status,r.label,r.type,void 0,void 0,{inputTokens:E?.input_tokens,outputTokens:E?.output_tokens,cacheCreationTokens:E?.cache_creation_input_tokens,cacheReadTokens:E?.cache_read_input_tokens})}else d?.end(),f(s.status,r.label,r.type);return w}async function bvn(e){const{ctx:t,body:r,account:n,accountState:o,headers:s,buildUpstreamBody:i,url:a,enabledAccounts:c,orderedAccounts:l,tracer:u,requestStartTime:d,allocateAttemptNumber:m,upstreamSpan:h,logAttempt:f,logProxyBody:g,onStreamTerminal:y,logFinalRequest:v,lastError:w,authFailureMessage:E,entitlementFailure:_,sawRateLimit:C,sawTransientFailure:A,sawNetworkError:k,bindServedSession:R}=e;Pr(n.label,n.type,401),f(401,"authentication_error","received 401 from Anthropic",{retryable:!0});let I=w,P=E,O=_,U=C,M=A,F=k,N=h,L=!1,q="received 401 from Anthropic";for(let B=0;B<Yx;B++){p.always(`[proxy] \u2190 401 account=${n.label} refreshing (attempt ${B+1}/${Yx})`);const H=await D$(n,n.persistTarget);if(!H.success){if(q=`refresh failed for account=${n.label} attempt ${B+1}/${Yx}: ${H.error?.slice(0,200)??"unknown"}`,I=q,sy(H))await wm(n,o,"refresh_invalid"),P=C3(n.label),p.always(`[proxy] account=${n.label} refresh token rejected; disabled until re-authentication`);else{const Ee=await b3(n,o);M=!0,p.always(`[proxy] account=${n.label} refresh temporarily unavailable (${H.status??"network"}); cooling until ${new Date(Ee).toISOString()} and rotating`)}break}n.persistTarget&&await N$(n.persistTarget,n),await _3(n,o),s.authorization=`Bearer ${n.token}`;const G=m(),X=Date.now(),ce=(Ee,le,ae,Pe)=>f(Ee,le,ae,{...Pe,attempt:G,attemptDurationMs:Pe?.attemptDurationMs??Date.now()-X}),Q=i(n.token),Ae=Date.now();try{const Ee=await Zue(a,{method:"POST",headers:s,body:Q.bodyStr,signal:AbortSignal.any([...t.abortSignal?[t.abortSignal]:[],AbortSignal.timeout(Xx)])},t,n.key,{logProxyBody:g,tracer:u,attemptNumber:G,accountLabel:n.label,accountType:n.type,preparedContext:Q.preparedContext});if(Ee.ok){L=!0,o.consecutiveRefreshFailures=0,p.always(`[proxy] \u2190 200 account=${n.label} (after ${B+1} refresh(es))`);const he=r.stream?await zgr({ctx:t,body:r,account:n,accountState:o,response:Ee,tracer:u,requestStartTime:d,fetchStartMs:Ae,attemptNumber:G,finalBodyStr:Q.bodyStr,upstreamSpan:N,logAttempt:ce,logProxyBody:g,logFinalRequest:v,onStreamTerminal:y}):{response:await Svn({ctx:t,account:n,accountState:o,requestedModel:r.model,retryResp:Ee,tracer:u,requestStartTime:d,fetchStartMs:Ae,attemptNumber:G,finalBodyStr:Q.bodyStr,upstreamSpan:N,logAttempt:ce,logProxyBody:g,logFinalRequest:v}),served:!0};if("retryNextAccount"in he){const Oe=he.failure;return{continueLoop:!0,...Oe?.retryDelayMs?{retryDelayMs:Oe.retryDelayMs}:{},lastError:Oe?.message??I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U||!!Oe?.rateLimit,sawTransientFailure:M||!!(Oe&&!Oe.rateLimit),sawNetworkError:F,upstreamSpan:void 0}}return R&&he.served&&R(n.key),{response:he.response,holdsAccountAdmission:he.holdsAccountAdmission,continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:void 0}}const le=Ee.status,ae=await Ee.text(),Pe={};Ee.headers.forEach((he,Oe)=>{Pe[Oe]=he});const ke={...Pe};delete ke.authorization,delete ke["x-api-key"];const Te=ae.length>4e3?ae.slice(0,4e3)+"...[truncated]":ae;if(u?.logUpstreamResponseHeaders(ke),u?.logUpstreamResponseBody(Te),g({phase:"upstream_response",headers:ke,body:Te,bodySize:Buffer.byteLength(ae,"utf8"),contentType:Pe["content-type"]??"application/json",account:n.label,accountType:n.type,attempt:G,responseStatus:le,durationMs:Date.now()-Ae}),q=`retry ${B+1}/${Yx} failed with status ${le}`,I=ae,p.debug(`[proxy] retry ${B+1} failed: ${le} ${ae.substring(0,120)}`),le===429&&jgr(Pe,ae))return p.always(`[proxy] \u2190 429 account=${n.label} anti-abuse/construction rejection after OAuth refresh \u2014 returning non-retryable request error`),ce(429,"construction_rejection",ae),u?.setError("construction_rejection",ae.slice(0,500)),N?.end(),{response:qgr({terminalError:Hgr(),account:n,tracer:u,requestStartTime:d,attemptNumber:G,logProxyBody:g,logFinalRequest:v}),continueLoop:!1,lastError:ae,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:void 0};if(le===429){U=!0;const he=Date.now(),Oe=Mw(Pe,{model:r.model});Oe&&(o.quota=fm(o.quota,Oe));const De=sde(Oe,a3(Pe["retry-after"]??null),he,P$(Pe),rl,typeof r.model=="string"?r.model:void 0),Ye=De.reason==="transient"?"transient":"quota";Pr(n.label,n.type,le,Ye),ce(429,"rate_limit_error",ae,{retryable:!0,rateLimitKind:Ye,cooldownReason:De.reason}),De.scope==="account"&&(!o.coolingUntil||De.coolingUntil>o.coolingUntil)&&(o.coolingUntil=De.coolingUntil,o.coolingReason=De.reason),Oe&&Zp(n.key,Oe).catch(()=>{}),De.scope==="account"&&await Vu(n.key,o.coolingUntil??De.coolingUntil,o.coolingReason??De.reason).catch(()=>{}),my(n.key,c.length,l[0]?.key);break}if(le===401||le===402||le===403){if(_de(le,ae)){const he=Ku(ae);Pr(n.label,n.type,le),ce(le,"permission_error",Cr(ae)),O={status:le,accounts:[...O?.accounts??[],n.label],message:O?.message??he.message??Cr(ae),...he.errorCode?{errorCode:he.errorCode}:{}},n.type==="oauth"&&Zgr(le,ae)&&await wm(n,o,"entitlement_blocked"),q=`entitlement blocked for account=${n.label}`,I=q,p.always(`[proxy] \u2190 ${le} account=${n.label} entitlement blocked after refresh; advancing to next account`);break}Pr(n.label,n.type,le),ce(le,"authentication_error",Cr(ae),{retryable:!0}),B<Yx-1&&await Zl(1e3);continue}if(eyr(le,ae)){Pr(n.label,n.type,le),ce(le,"api_error",Cr(ae),{retryable:!0}),M=!0;break}ce(le,"api_error",Cr(ae));try{return v(le,n.label,n.type,"api_error",Cr(ae)),{response:JSON.parse(ae),continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:N}}catch{return v(le,n.label,n.type,"api_error",Cr(ae)),{response:$i(le,ae),continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:N}}}catch(Ee){if(Ee instanceof _r||el(Ee))throw N?.end(),Ee;if(t.abortSignal?.aborted)throw ce(499,"client_cancelled","Client cancelled upstream request",{retryable:!1}),N?.end(),Ee;F=!0,Pr(n.label,n.type,502);const le=Ee instanceof Error?Ee.message:String(Ee);q=`network error on retry ${B+1}: ${le}`,I=q;const ae=bde(Ee);if(ce(502,"network_error",le,{retryable:ae,errorCode:oI(Ee)??"unknown"}),p.debug(`[proxy] ${q}`),!ae)return N?.end(),{response:Ggr({account:n,tracer:u,requestStartTime:d,attemptNumber:G,logProxyBody:g,logFinalRequest:v,errorType:"network_error",message:le}),continueLoop:!1,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:void 0};break}}return L||(I=q,p.always(`[proxy] \u26A0 account=${n.label} auth retries exhausted, rotating to next account`),u?.setError("authentication_error",q),u?.recordRetry(n.label,"auth_exhausted"),N?.end(),N=void 0,my(n.key,c.length,l[0]?.key)),{continueLoop:!0,lastError:I,authFailureMessage:P,entitlementFailure:O,sawRateLimit:U,sawTransientFailure:M,sawNetworkError:F,upstreamSpan:N}}function wde(e){const{responseStatus:t,account:r,errBody:n,errRespHeaders:o,requestStartTime:s,attemptNumber:i,logProxyBody:a,logFinalRequest:c,errorType:l}=e;try{const u=JSON.parse(n);return c(t,r.label,r.type,l,Cr(n)),a({phase:"client_response",headers:{"content-type":o["content-type"]??"application/json"},body:n,bodySize:Buffer.byteLength(n,"utf8"),contentType:o["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:i,responseStatus:t,durationMs:Date.now()-s}),u}catch{c(t,r.label,r.type,l,Cr(n));const u=$i(t,n),d=JSON.stringify(u);return a({phase:"client_response",headers:{"content-type":"application/json"},body:d,bodySize:Buffer.byteLength(d,"utf8"),contentType:"application/json",account:r.label,accountType:r.type,attempt:i,responseStatus:t,durationMs:Date.now()-s}),u}}function qgr(e){const{terminalError:t,account:r,tracer:n,requestStartTime:o,attemptNumber:s,logProxyBody:i,logFinalRequest:a}=e;return n?.end(t.status,Date.now()-o),wde({responseStatus:t.status,account:r,errBody:t.body,errRespHeaders:t.headers,requestStartTime:o,attemptNumber:s,logProxyBody:i,logFinalRequest:a,errorType:t.errorType})}function Ggr(e){const{account:t,tracer:r,requestStartTime:n,attemptNumber:o,logProxyBody:s,logFinalRequest:i,errorType:a,message:c}=e;r?.setError(a,c),r?.end(502,Date.now()-n),i(502,t.label,t.type,a,c);const l=$i(502,c),u=JSON.stringify(l);return s({phase:"client_response",headers:{"content-type":"application/json"},body:u,bodySize:Buffer.byteLength(u,"utf8"),contentType:"application/json",account:t.label,accountType:t.type,attempt:o,responseStatus:502,durationMs:Date.now()-n}),l}async function _vn(e){const{response:t,account:r,accountState:n,enabledAccounts:o,orderedAccounts:s,tracer:i,requestStartTime:a,fetchStartMs:c,attemptNumber:l,logAttempt:u,logProxyBody:d,logFinalRequest:m,lastError:h,authFailureMessage:f,sawTransientFailure:g,invalidRequestFailure:y,entitlementFailure:v,allowConfiguredModelFallback:w=!1}=e;let E=h,_=f,C=g,A=y,k=v;const R=await t.text(),I={};if(t.headers.forEach((P,O)=>{I[O]=P}),i?.logUpstreamResponseHeaders(I),i?.logUpstreamResponseBody(R),d({phase:"upstream_response",headers:I,body:R,bodySize:Buffer.byteLength(R,"utf8"),contentType:I["content-type"]??"application/json",account:r.label,accountType:r.type,attempt:l,responseStatus:t.status,durationMs:Date.now()-c}),Fvn(t.status,R))return Uvn(t.status,R)?(p.always(`[proxy] \u2190 ${t.status} account=${r.label} beta unavailable for subscription; advancing to next account`),u(t.status,"invalid_request_error",Cr(R)),i?.setError("invalid_request_error",Cr(R)),i?.recordRetry(r.label,"beta_unavailable"),my(r.key,o.length,s[0]?.key),E=Cr(R),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}):(p.always(`[proxy] \u2190 ${t.status} upstream invalid_request_error`),u(t.status,"invalid_request_error",Cr(R)),i?.setError("invalid_request_error",Cr(R)),A={status:t.status,body:R,contentType:I["content-type"]},E=Cr(R),{continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0});if(r.type==="oauth"&&_de(t.status,R)){const P=Ku(R);return Pr(r.label,r.type,t.status),k={status:t.status,accounts:[...k?.accounts??[],r.label],message:k?.message??P.message??Cr(R),...P.errorCode?{errorCode:P.errorCode}:{}},p.always(`[proxy] \u2190 ${t.status} account=${r.label} entitlement blocked${P.errorCode?` (${P.errorCode})`:""}; advancing to next account`),u(t.status,"permission_error",Cr(R)),i?.setError("permission_error",Cr(R)),i?.recordRetry(r.label,"entitlement_blocked"),r.type==="oauth"&&Zgr(t.status,R)&&await wm(r,n,"entitlement_blocked"),my(r.key,o.length,s[0]?.key),E=Cr(R),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}}if((t.status===401||t.status===402||t.status===403)&&r.type==="oauth"&&!r.refreshToken)return Pr(r.label,r.type,t.status),await wm(r,n,"missing_refresh_token"),_=C3(r.label),p.always(`[proxy] \u2190 ${t.status} account=${r.label} (auth failure, no refresh token)`),E=R,u(t.status,"authentication_error",Cr(R)),i?.setError("authentication_error",Cr(R)),i?.recordRetry(r.label,"auth_no_refresh"),my(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0};if((t.status===401||t.status===402||t.status===403)&&r.type==="api_key")return Pr(r.label,r.type,t.status),_="Authentication failed for Anthropic API key credentials. Update ANTHROPIC_API_KEY or re-login with OAuth.",p.always(`[proxy] \u2190 ${t.status} account=${r.label} (auth failure, api_key)`),E=R,u(t.status,"authentication_error",Cr(R)),i?.setError("authentication_error",Cr(R)),i?.recordRetry(r.label,"auth_api_key"),my(r.key,o.length,s[0]?.key),{continueLoop:!0,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0};if(t.status===404)return w&&$vn(t.status,R)?(p.always(`[proxy] \u2190 404 account=${r.label} model unavailable; trying configured fallback`),u(404,"not_found_error",Cr(R)),i?.setError("not_found_error",Cr(R)),i?.recordRetry(r.label,"model_not_found"),E=Cr(R),{continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}):(p.always(`[proxy] \u2190 404 account=${r.label}`),u(404,"not_found_error",Cr(R)),i?.setError("not_found_error",Cr(R)),i?.end(404,Date.now()-a),{response:wde({responseStatus:404,account:r,errBody:R,errRespHeaders:I,requestStartTime:a,attemptNumber:l,logProxyBody:d,logFinalRequest:m,errorType:"not_found_error"}),continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0});if(eyr(t.status,R)){const P=zvn(t.status,R);return Pr(r.label,r.type,t.status,t.status===429?"transient":void 0),C=!0,p.always(`[proxy] \u2190 ${t.status} account=${r.label} (${P?"overloaded":"transient"})`),E=R,u(t.status,"api_error",Cr(R),t.status===429?{retryable:!0,rateLimitKind:"transient",cooldownReason:"transient"}:void 0),i?.setError(P?"overloaded_error":"transient_error",Cr(R)),i?.recordRetry(r.label,P?"overloaded":"transient"),{continueLoop:!0,retrySameAccount:!P,...P?{retryDelayMs:Kgr(l)}:{},lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}}return p.always(`[proxy] \u2190 ${t.status} account=${r.label}`),p.debug(`[claude-proxy] error body: ${R.substring(0,200)}`),u(t.status,"api_error",Cr(R)),i?.setError("api_error",Cr(R)),i?.end(t.status,Date.now()-a),{response:wde({responseStatus:t.status,account:r,errBody:R,errRespHeaders:I,requestStartTime:a,attemptNumber:l,logProxyBody:d,logFinalRequest:m,errorType:"api_error"}),continueLoop:!1,lastError:E,authFailureMessage:_,sawTransientFailure:C,invalidRequestFailure:A,entitlementFailure:k,upstreamSpan:void 0}}function Cvn(e){const{ctx:t,body:r,clientRequestBody:n}=e;let o;try{o=Ux.startRequest({recordRequestMetrics:Mx(t.requestId)?.accountingScope!=="internal",recordUsageMetrics:!0,requestId:t.requestId,method:t.method,path:t.path,model:r.model,stream:r.stream??!1,toolCount:Array.isArray(r.tools)?r.tools.length:0,toolNames:Array.isArray(r.tools)?r.tools.map(h=>h&&typeof h=="object"&&"name"in h?String(h.name??""):"").filter(h=>h.length>0):void 0,sessionId:t.headers["x-neurolink-session-id"]??t.headers["x-claude-code-session-id"]??void 0,userAgent:t.headers["user-agent"]??void 0},t.headers);const m=o.startReceive();o.logRequestHeaders(t.headers),o.logRequestBody(n),m.end()}catch{o=void 0}const s=Date.now(),i=m=>{const h=o?.getTraceContext();Jw({timestamp:new Date().toISOString(),requestId:t.requestId,model:r.model,stream:r.stream??!1,...m,...h?{traceId:h.traceId,spanId:h.spanId}:{}})};let a;const c=m=>{if(a){p.debug(`[claude-proxy] ignored duplicate routing decision for request ${t.requestId}`);return}a=m};let l=!1;const u=(m,h,f,g,y,v)=>{if(l||Fw(t.requestId)){p.debug(`[claude-proxy] ignored duplicate finalization for request ${t.requestId}`);return}l=!0,t.abortSignal?.aborted&&(m=499,g="client_cancelled",y="Client cancelled request");const w=t.metadata.sdkFallbackFailure;w&&(h="unknown",f="translation",o?.setServedAccount(h,f),w.model&&o?.setModelSubstitution(r.model,w.model,w.provider),w.inputTokens!==void 0&&w.outputTokens!==void 0&&o?.setUsage({inputTokens:w.inputTokens,outputTokens:w.outputTokens,cacheReadTokens:w.cacheReadTokens??0,cacheCreationTokens:w.cacheCreationTokens??0,inputIncludesCachedTokens:w.inputIncludesCachedTokens,reasoningTokens:w.reasoningTokens}));const E=t.metadata.codexFallbackFailureUsage;E&&(v={inputTokens:E.inputTokensObserved?E.input:void 0,outputTokens:E.outputTokensObserved?E.output:void 0,cacheReadTokens:E.cacheReadTokensObserved?E.cacheReadTokens:void 0,cacheCreationTokens:E.cacheCreationTokensObserved?E.cacheCreationTokens:void 0,cacheReadTokensObserved:E.cacheReadTokensObserved===!0,cacheCreationTokensObserved:E.cacheCreationTokensObserved===!0,reasoningTokens:E.reasoning,...v}),!h&&typeof t.metadata.codexFallbackAccount=="string"&&t.metadata.codexFallbackAccount&&(h=t.metadata.codexFallbackAccount,typeof t.metadata.codexFallbackAccountType=="string"&&(f=t.metadata.codexFallbackAccountType)),!w&&t.metadata.codexFallbackDeferredFailure===!0&&typeof t.metadata.codexFallbackModel=="string"&&(o?.setModelSubstitution(r.model,t.metadata.codexFallbackModel,"openai"),o?.setServedAccount(h||"unknown",f),E?.inputTokensObserved&&E.outputTokensObserved&&o?.setUsage({inputTokens:E.input,outputTokens:E.output,cacheReadTokens:E.cacheReadTokens??0,cacheCreationTokens:E.cacheCreationTokens??0,cacheReadTokensObserved:E.cacheReadTokensObserved===!0,cacheCreationTokensObserved:E.cacheCreationTokensObserved===!0,reasoningTokens:E.reasoning},{recordMetrics:!1}));const _=h||(m>=400?Wue:void 0),C=h?f||void 0:m>=400?Kue:void 0,A=w?{accountKey:w.accountKey,provider:w.provider}:agr(_,C),k=Mx(t.requestId)?.accountingScope!=="internal";k&&m>=400?Zg(m,_,C,{requestId:t.requestId,...A.accountKey?{accountKey:A.accountKey}:{},errorType:g,terminalOutcome:g==="client_cancelled"?"client_cancelled":g?.includes("stream")?"stream_error":"handler_error",message:y,errorCode:v?.errorCode}):k&&nx(_,C);const R=o?.getTraceContext(),I=uvn(t.metadata,C);Kw({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:I??r.model,...I?{requestedModel:r.model,...C==="vertex"?{}:{inputIncludesCachedTokens:!1}}:{},...t.metadata.contextPreflight?{contextPreflight:t.metadata.contextPreflight}:{},...t.metadata.tokenBudget?{tokenBudget:t.metadata.tokenBudget}:{},stream:!!r.stream,toolCount:Array.isArray(r.tools)?r.tools.length:0,account:_??"",...A.accountKey?{accountKey:A.accountKey}:{},accountType:C??"",...A.provider?{provider:A.provider}:{},...w,...Fx(t.headers),responseStatus:m,responseTimeMs:Date.now()-s,...nmn(t.metadata,s),...g?{errorType:g}:{},...y?{errorMessage:y}:{},...v?.errorCode?{errorCode:v.errorCode}:{},...v?.retryable!==void 0?{retryable:v.retryable}:{},...v?.transportScope?{transportScope:v.transportScope}:{},...v?.inputTokens!==void 0?{inputTokens:v.inputTokens}:{},...v?.outputTokens!==void 0?{outputTokens:v.outputTokens}:{},...v?.cacheCreationTokens!==void 0?{cacheCreationTokens:v.cacheCreationTokens}:{},...v?.cacheReadTokens!==void 0?{cacheReadTokens:v.cacheReadTokens}:{},...v?.reasoningTokens!==void 0?{reasoningTokens:v.reasoningTokens}:{},...R?{traceId:R.traceId,spanId:R.spanId}:{},...a?{routingDecision:a}:{},...Array.isArray(t.metadata.fallbackPlan)?{fallbackPlan:t.metadata.fallbackPlan}:{}})},d=(m,h,f,g)=>{const y=$i(m,h,f),v=JSON.stringify(y);return u(m,g?.account??"",g?.accountType??"final",f,h,g),i({phase:"client_response",headers:{"content-type":"application/json"},body:v,bodySize:Buffer.byteLength(v,"utf8"),contentType:"application/json",responseStatus:m,durationMs:Date.now()-s,...g}),y};return i({phase:"client_request",headers:t.headers,body:n,bodySize:Buffer.byteLength(n,"utf8"),contentType:t.headers["content-type"]??"application/json"}),{tracer:o,requestStartTime:s,logProxyBody:i,logFinalRequest:u,buildLoggedClaudeError:d,setRoutingDecision:c}}function Avn(e){const{ctx:t,body:r,toolCount:n,requestStart:o,tracer:s,account:i,attemptNumber:a}=e,c=Date.now(),l=agr(i.label,i.type);return(u,d,m,h)=>{const f=Date.now(),g=s?.getTraceContext();Eue({timestamp:new Date().toISOString(),requestId:t.requestId,attempt:h?.attempt??a,method:t.method,path:t.path,model:r.model,...t.metadata.contextPreflight?{contextPreflight:t.metadata.contextPreflight}:{},...t.metadata.tokenBudget?{tokenBudget:t.metadata.tokenBudget}:{},stream:!!r.stream,toolCount:n,account:i.label,accountKey:i.key,accountType:i.type,...l.provider?{provider:l.provider}:{},responseStatus:u,responseTimeMs:f-o,attemptDurationMs:h?.attemptDurationMs??f-c,...d?{errorType:d}:{},...m?{errorMessage:m}:{},...h?.errorCode?{errorCode:h.errorCode}:{},...h?.transportScope?{transportScope:h.transportScope}:{},...h?.inputTokens!==void 0?{inputTokens:h.inputTokens}:{},...h?.outputTokens!==void 0?{outputTokens:h.outputTokens}:{},...h?.cacheCreationTokens!==void 0?{cacheCreationTokens:h.cacheCreationTokens}:{},...h?.cacheReadTokens!==void 0?{cacheReadTokens:h.cacheReadTokens}:{},...h?.retryable!==void 0?{retryable:h.retryable}:{},...h?.connectPhase!==void 0?{connectPhase:h.connectPhase}:{},...h?.rateLimitKind?{rateLimitKind:h.rateLimitKind}:{},...h?.cooldownReason?{cooldownReason:h.cooldownReason}:{},...g?{traceId:g.traceId,spanId:g.spanId}:{}})}}async function kvn(e){const{ctx:t,account:r,accountState:n,bodyStr:o,clientHeaders:s,isClaudeClientRequest:i,url:a,tracer:c,attemptNumber:l,currentLastError:u,currentAuthFailureMessage:d,logAttempt:m,logProxyBody:h}=e;let f=u,g=d;if(Ple(r)){const I=await D$(r,r.persistTarget);if(I.success)r.persistTarget&&await N$(r.persistTarget,r),await _3(r,n);else return f=`token refresh failed for account=${r.label}: ${I.error?.slice(0,200)??"unknown"}`,sy(I)?(await wm(r,n,"refresh_invalid"),g=C3(r.label)):await b3(r,n),m(sy(I)?401:503,sy(I)?"authentication_error":"token_refresh_unavailable",String(f)),{continueLoop:!0,lastError:f,authFailureMessage:g}}const y=r.type==="oauth",v={};for(const[I,P]of Object.entries(s))typeof P=="string"&&(v[I]=P);const w=y?await G0n(r.label,r.key,v,o):null,E={};for(const[I,P]of Object.entries(s)){const O=I.toLowerCase();typeof P=="string"&&!c3.has(O)&&(E[O]=P)}if(E["content-type"]="application/json",y?(E.authorization=`Bearer ${r.token}`,delete E["x-api-key"],$0n(E,w)):(E["x-api-key"]=r.token,delete E.authorization),E["user-agent"]||(E["user-agent"]=rg),E["anthropic-version"]||(E["anthropic-version"]="2023-06-01"),E["anthropic-dangerous-direct-browser-access"]||(E["anthropic-dangerous-direct-browser-access"]="true"),E["x-app"]||(E["x-app"]="cli"),E.accept||(E.accept="application/json"),y){const I=i?E["anthropic-beta"]??"":s["anthropic-beta"]??"",P=new Set(I.split(",").map(O=>O.trim()).filter(Boolean));for(const O of i?cA:F0n)P.add(O);E["anthropic-beta"]=[...P].join(",")}else{const I=(E["anthropic-beta"]??"").split(",").map(P=>P.trim()).filter(P=>P&&!cA.includes(P)).join(",");I?E["anthropic-beta"]=I:delete E["anthropic-beta"]}const _=I=>{const P=y?j0n(o,I,w,i,E["x-claude-code-session-id"]):{bodyStr:o};return{...P,...hgr(t,P.bodyStr)}},C=_(r.token);y&&C.sessionId&&!E["x-claude-code-session-id"]&&(E["x-claude-code-session-id"]=C.sessionId);const A=C.bodyStr;p.always(`[proxy] \u2192 account=${r.label} (${r.type})`);const k=Date.now();let R;return c&&(R=c.startUpstreamAttempt({attempt:l,account:r.label,polyfillHeaders:y,polyfillBody:y,upstreamUrl:a}),Object.assign(E,c.getTraceHeaders())),{continueLoop:!1,lastError:f,authFailureMessage:g,headers:E,buildUpstreamBody:_,finalBodyStr:A,preparedContext:C.preparedContext,fetchStartMs:k,upstreamSpan:R}}function jgr(e,t){const r=!!e["retry-after"],n=Object.keys(e).some(o=>o.toLowerCase().startsWith("anthropic-ratelimit-"));return r||n?!1:t.includes("rate_limit_error")&&/"message"\s*:\s*"Error"/.test(t)}function Hgr(){return{status:400,body:JSON.stringify($i(400,"Anthropic rejected the OAuth request shape. This is not an account rate limit.","invalid_request_error")),headers:{"content-type":"application/json"},errorType:"construction_rejection"}}async function xvn(e){const{ctx:t,url:r,headers:n,finalBodyStr:o,preparedContext:s,requestedModel:i,account:a,accountState:c,enabledAccounts:l,orderedAccounts:u,tracer:d,logAttempt:m,logProxyBody:h,fetchStartMs:f,attemptNumber:g,currentLastError:y,currentSawRateLimit:v,currentSawNetworkError:w,upstreamSpan:E}=e;let _=y,C=v,A=w;const k=E;let R;try{R=await Zue(r,{method:"POST",headers:n,body:o,signal:AbortSignal.any([...t.abortSignal?[t.abortSignal]:[],AbortSignal.timeout(Xx)])},t,a.key,{logProxyBody:h,tracer:d,attemptNumber:g,accountLabel:a.label,accountType:a.type,preparedContext:s})}catch(I){if(I instanceof _r||el(I))throw k?.end(),I;if(t.abortSignal?.aborted)throw m(499,"client_cancelled","Client cancelled upstream request",{retryable:!1}),k?.end(),t.abortSignal.reason;const P=bde(I),O=Ygr(I),U=Nvn(I);A=!0,Pr(a.label,a.type,502);const M=oI(I)??"unknown",F=I instanceof Error?I.message:String(I);if(_=F,p.always(`[proxy] fetch error account=${a.label} code=${M} (${P?"retryable":"terminal"}): ${F}`),m(502,"network_error",F,{retryable:P,connectPhase:O,errorCode:M,transportScope:U}),d?.setError("network_error",F),P&&d?.recordRetry(a.label,"network_error"),k?.end(),!P)throw I;return{continueLoop:!0,retrySameAccount:!0,transportScope:U,errorCode:M,connectPhase:O,lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:void 0}}if(R.status===429){const I=a3(R.headers.get("retry-after")),P={};R.headers.forEach((B,H)=>{P[H]=B}),_=await R.text();const O={...P};delete O.authorization,delete O["x-api-key"];const U=String(_).length>4e3?String(_).slice(0,4e3)+"...[truncated]":String(_);if(d?.logUpstreamResponseHeaders(O),d?.logUpstreamResponseBody(U),h({phase:"upstream_response",headers:O,body:U,bodySize:Buffer.byteLength(String(_),"utf8"),contentType:P["content-type"]??"application/json",account:a.label,accountType:a.type,attempt:g,responseStatus:429,durationMs:Date.now()-f}),jgr(P,String(_)))return p.always(`[proxy] \u2190 429 account=${a.label} anti-abuse/construction rejection (no ratelimit headers, body="Error") \u2014 NOT a real rate limit; returning non-retryable request error`),m(429,"construction_rejection",String(_)),d?.setError("construction_rejection",String(_).slice(0,500)),k?.end(),{continueLoop:!1,terminalError:Hgr(),lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:void 0};C=!0;const M=Date.now(),F=Mw(P,{model:i}),N=P$(P),L=sde(F,I,M,N,rl,i),q=L.reason==="transient"?"transient":"quota";return Pr(a.label,a.type,429,q),p.always(`[proxy] \u2190 429 account=${a.label} reason=${L.reason} scope=${L.scope} retry-after=${I}ms 5h-status=${P["anthropic-ratelimit-unified-5h-status"]??"unknown"} 7d-status=${P["anthropic-ratelimit-unified-7d-status"]??"unknown"} unified-status=${N??"unknown"} \u2192 ${L.rotateImmediately?`rotate now, cool ${ide(L.coolingUntil,M)}m`:"retry same account (transient)"}`),m(429,"rate_limit_error",String(_),{retryable:!0,rateLimitKind:q,cooldownReason:L.reason}),d?.setError("rate_limit_error",String(_).slice(0,500)),d?.recordRetry(a.label,"rate_limit"),k?.end(),{continueLoop:!0,retrySameAccount:!L.rotateImmediately,retryAfterMs:I,cooldownPlan:L,...F?{quota:F}:{},lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:void 0}}return{continueLoop:!1,response:R,lastError:_,sawRateLimit:C,sawNetworkError:A,upstreamSpan:k}}function Ivn(e){return e.invalidRequestFailure===null}function Rvn(e){const{ctx:t,tracer:r,requestStartTime:n,failure:o,buildLoggedClaudeError:s}=e;return o.responseHeaders&&(t.responseHeaders={...t.responseHeaders??{},...o.responseHeaders}),r?.setError(o.errorType,o.message),r?.end(o.status,Date.now()-n),s(o.status,o.message,o.errorType)}async function Pvn(e){const{ctx:t,body:r,modelRouter:n,configGeneration:o,tracer:s,requestStartTime:i,accountStrategy:a,primaryAccountKey:c,accountAllowlist:l,quotaRoutingEnabled:u=lde(),sessionSoftLimit:d=ude(),sessionResetToleranceMs:m=rI(),ranking:h="expiry-first",preferPrimary:f=!1,sessionAffinityEnabled:g=!1,sessionAffinityIdleTtlMs:y=36e5,spillInflight:v=0,buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_,setRoutingDecision:C}=e,A=L$(r),k=tE({provider:"anthropic",model:r.model},n?.getFallbackChain()??[],r.model,A),R=k.attempts.slice(1).some(Te=>!!(Te.provider&&Te.model)),I=await lvn({ctx:t,body:r,accountStrategy:a,primaryAccountKey:c,accountAllowlist:l,quotaRoutingEnabled:u,sessionSoftLimit:d,sessionResetToleranceMs:m,ranking:h,preferPrimary:f,sessionAffinityEnabled:g,sessionAffinityIdleTtlMs:y,spillInflight:v,setRoutingDecision:C});if("failure"in I){const Te=await Lgr({body:r,logFinalRequest:_});if(Te)return Te;const he=await Fgr({ctx:t,body:r,parsedFallbackRequest:A,fallbackPlan:k,modelRouter:n,tracer:s,requestStartTime:i,logProxyBody:E,logFinalRequest:_});if(he.response)return he.response;if(he.invalidRequestFailure)return Tde({tracer:s,requestStartTime:i,authFailureMessage:null,authCooldownMessage:null,invalidRequestFailure:he.invalidRequestFailure,entitlementFailure:null,scopedExhaustion:null,sawNetworkError:!1,sawTransientFailure:!1,sawRateLimit:!1,lastError:void 0,orderedAccounts:[],buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_});if(he.terminalFailure){const Oe=he.terminalFailure;return $gr({failure:Oe,buildLoggedClaudeError:w,tracer:s,requestStartTime:i})}return Rvn({ctx:t,tracer:s,requestStartTime:i,failure:I.failure,buildLoggedClaudeError:w})}const{accounts:P,enabledAccounts:O,orderedAccounts:U,bodyStr:M,requestStart:F,toolCount:N,url:L,clientHeaders:q,isClaudeClientRequest:B,sessionId:H}=I,G=new Set,X=g&&H&&a==="fill-first"&&O.length>1?Te=>D0n({sessionId:H,servingAccountKey:Te,attemptedAccountKeys:G,enabledAccounts:O,idleTtlMs:y,sessionSoftLimit:d,sessionResetToleranceMs:m,requestedModel:typeof r.model=="string"?r.model:void 0}):void 0,ce=E0n(),Q={lastError:void 0,sawRateLimit:!1,sawNetworkError:!1,sawTransientFailure:!1,invalidRequestFailure:null,authFailureMessage:null,authCooldownMessage:null,entitlementFailure:null,scopedExhaustion:null,attemptNumber:0},Ae=s?.startAccountSelection();let le=U.filter(Te=>!Egr(Te.key));if(le.length===0&&(le=await p0n(U)),le.length===0&&U.length>0){const Te=U.map(Oe=>$a(Oe.key)),he=Te.some(Oe=>Oe.coolingReason!=="auth");if(Q.sawRateLimit=he,Q.sawTransientFailure=!he,Q.lastError=he?"All Anthropic accounts have active rate-limit cooldowns":"All Anthropic accounts have active authentication cooldowns",!he){const Oe=Math.min(...Te.map(De=>De.coolingUntil??Number.POSITIVE_INFINITY));Q.authCooldownMessage=`All ${U.length} Anthropic accounts are temporarily unavailable while OAuth refresh is cooling. Earliest retry at ${new Date(Oe).toISOString()}.`}}const ae=C0n(le,typeof r.model=="string"?r.model:void 0,Date.now(),ce);ae.eligible.length>0?le=ae.eligible:ae.exhaustion&&(Q.scopedExhaustion=ae.exhaustion,Q.lastError=`Model-scoped limit exhausted for ${ae.exhaustion.model}`,le=[]);const Pe=n?.getMaxInflightPerAccount?.();let ke;try{Pe!==void 0&&le.length>0&&le.every(Te=>!n0n(Te.key,Pe))&&(ke=await s0n(le.map(Te=>Te.key),Pe,t.abortSignal,ode,o));e:for(const[Te,he]of le.entries()){const Oe=Te<le.length-1,De=$a(he.key);let Ye=0,gt=0;for(;;){const $e=await nE.acquire(t.abortSignal);if($e.allowed===!1){Q.sawNetworkError=!0,Q.lastTransportErrorCode=$e.errorCode??void 0,Q.lastTransportScope=$e.transportScope,Q.lastError=`Anthropic transport recovery probe failed (${$e.errorCode??"unknown"})`;const se=$e.connectPhase?lgr:l3;if(Ye<se){Ye+=1;const oe=Sde(Ye);p.always(`[proxy] retrying same account=${he.label} after failed transport recovery probe (${Ye}/${se}) in ${oe}ms`),await Zl(oe);continue}break e}Q.attemptNumber+=1,s&&Q.attemptNumber===1&&Ae&&(s.setAccountSelection({strategy:a,accountsTotal:P.length,accountsHealthy:O.length,selectedAccount:he.label,accountType:he.type}),Ae.end());const Ie=Avn({ctx:t,body:r,toolCount:N,requestStart:F,tracer:s,account:he,attemptNumber:Q.attemptNumber}),ve=await kvn({ctx:t,account:he,accountState:De,bodyStr:M,clientHeaders:q,isClaudeClientRequest:B,url:L,tracer:s,attemptNumber:Q.attemptNumber,currentLastError:Q.lastError,currentAuthFailureMessage:Q.authFailureMessage,logAttempt:Ie,logProxyBody:E});if(Q.lastError=ve.lastError,Q.authFailureMessage=ve.authFailureMessage,ve.continueLoop||!ve.headers||!ve.buildUpstreamBody||!ve.finalBodyStr||!ve.preparedContext||ve.fetchStartMs===void 0){G.add(he.key),$e.probe&&nE.reportProbeAbandoned($e);continue e}let J;if(ke?.accountKey===he.key?(J=ke.lease,ke=void 0):(J=t0n(he.key,Pe,o),J&&ke&&(ke.lease.release(),ke=void 0)),!J){$e.probe&&nE.reportProbeAbandoned($e);continue e}G.add(he.key);let V=!1;try{let se;try{se=await xvn({ctx:t,url:L,headers:ve.headers,finalBodyStr:ve.finalBodyStr,preparedContext:ve.preparedContext,requestedModel:r.model,account:he,accountState:De,enabledAccounts:O,orderedAccounts:U,tracer:s,logAttempt:Ie,logProxyBody:E,fetchStartMs:ve.fetchStartMs,attemptNumber:Q.attemptNumber,currentLastError:Q.lastError,currentSawRateLimit:Q.sawRateLimit,currentSawNetworkError:Q.sawNetworkError,upstreamSpan:ve.upstreamSpan})}catch(W){throw $e.probe&&nE.reportProbeAbandoned($e),W}if(se.transportScope?nE.reportTransportFailure(se.errorCode,se.transportScope,$e,se.connectPhase===!0):nE.reportSuccess($e),Q.lastError=se.lastError,Q.sawRateLimit=se.sawRateLimit,Q.sawNetworkError=se.sawNetworkError,se.transportScope&&(Q.lastTransportScope=se.transportScope,Q.lastTransportErrorCode=se.errorCode),se.terminalError)return qgr({terminalError:se.terminalError,account:he,tracer:s,requestStartTime:i,attemptNumber:Q.attemptNumber,logProxyBody:E,logFinalRequest:_});if(se.continueLoop||!se.response){if(se.cooldownPlan){const re=se.cooldownPlan;se.quota&&(De.quota=fm(De.quota,se.quota),Zp(he.key,se.quota).catch(()=>{}));let ye=!1;re.scope==="account"&&(!De.coolingUntil||re.coolingUntil>De.coolingUntil)&&(De.coolingUntil=re.coolingUntil,De.coolingReason=re.reason,ye=!0),ye&&re.scope==="account"&&await Vu(he.key,De.coolingUntil??re.coolingUntil,De.coolingReason??re.reason).catch(()=>{});const Re=se.retrySameAccount?Sgr(he.key,re.coolingUntil,se.retryAfterMs,gt):void 0;if(Re){gt+=1,p.always(`[proxy] retrying same account=${he.label} after transient 429 (shared slot ${Re.slot}/${u3}) in ${Re.delayMs}ms`),await Zl(Re.delayMs);continue}my(he.key,O.length,U[0]?.key),p.always(`[proxy] account=${he.label} rate-limited (${re.reason}); cooling ~${ide(re.coolingUntil,Date.now())}m until ${new Date(re.coolingUntil).toISOString()}, rotating`),re.rotateImmediately&&k0n(he,le[Te+1],re.coolingUntil,d);continue e}const W=se.connectPhase?lgr:l3;if(se.retrySameAccount&&Ye<W){Ye+=1;const re=Sde(Ye);p.always(`[proxy] retrying same account=${he.label} after transient network error (${Ye}/${W}) in ${re}ms`),await Zl(re);continue}if(se.retrySameAccount&&!se.transportScope&&p.always(`[proxy] exhausted transient same-account retries for account=${he.label}; rotating`),se.transportScope){p.always(`[proxy] Anthropic ${se.transportScope} failure code=${se.errorCode??"unknown"}; suppressing cross-account rotation after ${Ye+1} attempts`);break e}continue e}let oe=se.upstreamSpan;const Z=se.response;if(Z.status===401&&he.type==="oauth"&&he.refreshToken){const W=await bvn({ctx:t,body:r,account:he,accountState:De,headers:ve.headers,buildUpstreamBody:ve.buildUpstreamBody,url:L,enabledAccounts:O,orderedAccounts:U,tracer:s,requestStartTime:i,allocateAttemptNumber:()=>(Q.attemptNumber+=1,Q.attemptNumber),upstreamSpan:oe,logAttempt:Ie,logProxyBody:E,logFinalRequest:_,onStreamTerminal:J.release,lastError:Q.lastError,authFailureMessage:Q.authFailureMessage,entitlementFailure:Q.entitlementFailure,sawRateLimit:Q.sawRateLimit,sawTransientFailure:Q.sawTransientFailure,sawNetworkError:Q.sawNetworkError,bindServedSession:X});if(Q.lastError=W.lastError,Q.authFailureMessage=W.authFailureMessage,Q.entitlementFailure=W.entitlementFailure,Q.sawRateLimit=W.sawRateLimit,Q.sawTransientFailure=W.sawTransientFailure,Q.sawNetworkError=W.sawNetworkError,oe=W.upstreamSpan,W.response!==void 0)return V=W.holdsAccountAdmission===!0,W.response;if(W.continueLoop){Oe&&W.retryDelayMs&&(p.always(`[proxy] pacing cross-account SSE overload rotation for ${W.retryDelayMs}ms after auth refresh`),await Zl(W.retryDelayMs));continue e}}if(!Z.ok){const W=await _vn({response:Z,account:he,accountState:De,enabledAccounts:O,orderedAccounts:U,tracer:s,requestStartTime:i,fetchStartMs:ve.fetchStartMs,attemptNumber:Q.attemptNumber,logAttempt:Ie,logProxyBody:E,logFinalRequest:_,lastError:Q.lastError,authFailureMessage:Q.authFailureMessage,sawTransientFailure:Q.sawTransientFailure,invalidRequestFailure:Q.invalidRequestFailure,entitlementFailure:Q.entitlementFailure,allowConfiguredModelFallback:R});if(Q.lastError=W.lastError,Q.authFailureMessage=W.authFailureMessage,Q.sawTransientFailure=W.sawTransientFailure,Q.invalidRequestFailure=W.invalidRequestFailure,Q.entitlementFailure=W.entitlementFailure,W.response!==void 0)return W.response;if(W.continueLoop){if(W.retrySameAccount&&Ye<l3){Ye+=1;const re=Sde(Ye);p.always(`[proxy] retrying same account=${he.label} after transient upstream ${Z.status} (${Ye}/${l3}) in ${re}ms`),await Zl(re);continue}W.retrySameAccount&&p.always(`[proxy] exhausted transient same-account retries for account=${he.label}; rotating`),Oe&&W.retryDelayMs&&(p.always(`[proxy] pacing cross-account overload rotation for ${W.retryDelayMs}ms`),await Zl(W.retryDelayMs));continue e}break e}if(De.coolingUntil&&Date.now()>=De.coolingUntil){const W=De.coolingUntil;De.coolingUntil=void 0,De.coolingReason=void 0,Yp(he.key,W).catch(()=>{})}const ie=await zgr({ctx:t,body:r,account:he,accountState:De,response:Z,tracer:s,requestStartTime:i,fetchStartMs:ve.fetchStartMs,attemptNumber:Q.attemptNumber,finalBodyStr:ve.finalBodyStr,upstreamSpan:oe,logAttempt:Ie,logProxyBody:E,logFinalRequest:_,onStreamTerminal:J.release,poolAccounts:O});if("retryNextAccount"in ie){if(ie.failure){Q.lastError=ie.failure.message,Q.sawRateLimit||=ie.failure.rateLimit,Q.sawTransientFailure||=!ie.failure.rateLimit;const{sameAccountRetry:W}=ie.failure,re=W?Sgr(he.key,W.coolingUntil,W.retryAfterMs,gt):void 0;if(re){gt+=1,p.always(`[proxy] retrying same account=${he.label} after transient in-stream rate limit (shared slot ${re.slot}/${u3}) in ${re.delayMs}ms`),await Zl(re.delayMs);continue}Oe&&ie.failure.retryDelayMs&&(p.always(`[proxy] pacing cross-account SSE overload rotation for ${ie.failure.retryDelayMs}ms`),await Zl(ie.failure.retryDelayMs))}continue e}return V=ie.holdsAccountAdmission===!0,ie.served&>>0&&d0n(he,De),X&&ie.served&&X(he.key),ie.response}finally{V||J.release()}}}}finally{ke?.lease.release(),Q.attemptNumber===0&&Ae?.end()}if(Ivn(Q)){let Te;const he=await Lgr({body:r,logFinalRequest:_});if(he)return he;const Oe=await Fgr({ctx:t,body:r,parsedFallbackRequest:A,fallbackPlan:k,modelRouter:n,tracer:s,requestStartTime:i,logProxyBody:E,logFinalRequest:_});if(Oe.response)return Oe.response;if(Oe.invalidRequestFailure)return Tde({tracer:s,requestStartTime:i,authFailureMessage:null,authCooldownMessage:null,invalidRequestFailure:Oe.invalidRequestFailure,entitlementFailure:null,scopedExhaustion:null,sawNetworkError:!1,sawTransientFailure:!1,sawRateLimit:!1,lastError:void 0,orderedAccounts:[],buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_});Te=Oe.lastErrorMessage;let De=Oe.terminalFailure;if(Q.invalidRequestFailure===null&&!Q.sawRateLimit&&!t.abortSignal?.aborted&&De?.retryable!==!1&&n?.isAutoFallbackEnabled?.()){const Ye=await hvn({ctx:t,body:r,tracer:s,requestStartTime:i,logProxyBody:E,logFinalRequest:_});if(Ye.response)return Ye.response;Te=Ye.lastErrorMessage??Te,De=Ye.terminalFailure??De}if(De)return $gr({failure:De,buildLoggedClaudeError:w,tracer:s,requestStartTime:i});Q.fallbackFailureMessage=Te}{const Te=U[0],he=Te?pc.get(Te.key):void 0;eI(t,{quota:he?.quota??null,source:he?.quota?"snapshot":"none",...Te?{account:Te}:{},...he?{accountState:he}:{},attempt:Q.attemptNumber,poolAccounts:O})}return Tde({tracer:s,requestStartTime:i,authFailureMessage:Q.authFailureMessage,authCooldownMessage:Q.authCooldownMessage,invalidRequestFailure:Q.invalidRequestFailure,entitlementFailure:Q.entitlementFailure,scopedExhaustion:Q.scopedExhaustion,sawNetworkError:Q.sawNetworkError,sawTransientFailure:Q.sawTransientFailure,sawRateLimit:Q.sawRateLimit,lastError:Q.lastError,lastTransportErrorCode:Q.lastTransportErrorCode,lastTransportScope:Q.lastTransportScope,fallbackFailureMessage:Q.fallbackFailureMessage,orderedAccounts:U,buildLoggedClaudeError:w,logProxyBody:E,logFinalRequest:_})}function Vgr(e){return e!==void 0&&"runtimeConfigProvider"in e&&typeof e.runtimeConfigProvider=="function"}function Wgr(e){const{ctx:t,body:r,status:n,message:o,errorType:s}=e;return Fw(t.requestId)||(Zg(n,Wue,Kue,{requestId:t.requestId,errorType:s,terminalOutcome:"handler_error",message:o}),Kw({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:typeof r?.model=="string"?r.model:"",stream:r?.stream??!1,toolCount:Array.isArray(r?.tools)?r.tools.length:0,account:Wue,accountType:Kue,responseStatus:n,responseTimeMs:0,errorType:s,errorMessage:o})),$i(n,o)}function Ede(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.round(e*1e3):null}function Mvn(e){if(!e||typeof e!="object")return null;const t={...e};return t.sessionResetAtMs=Ede(t.sessionResetAt),t.weeklyResetAtMs=Ede(t.weeklyResetAt),Array.isArray(t.windows)&&(t.windows=t.windows.map(r=>{const n={...r};return n.resetsAtMs=Ede(n.resetsAt),n.severity=n.severity??(n.status==="rejected"?"critical":"normal"),n.isActive=n.isActive??!1,n})),t}function S3(e){return e==="allowed"?"ok":e==="rejected"||e==="throttled"?"degraded":"unknown"}function Ovn(e,t="",r="fill-first",n=!1,o,s){const i=Vgr(s)?s.accountAllowlist:s,a=Vgr(s)?s.runtimeConfigProvider:void 0;return{prefix:`${t}/v1`,routes:[{method:"POST",path:`${t}/v1/messages`,handler:async c=>{const l=a?.()??{generation:0,strategy:r,modelRouter:e,passthrough:n,primaryAccountKey:o,accountAllowlist:i,quotaRoutingEnabled:lde(),sessionSoftLimit:ude(),sessionResetToleranceMs:rI(),useOverage:"auto",accountRanking:"expiry-first",preferPrimary:!1,sessionAffinity:!1,sessionAffinityIdleTtlMs:36e5,spillInflight:0};dde(l.useOverage);const u=l.modelRouter,d=c.body;if(typeof d?.model!="string"||!Array.isArray(d?.messages))return Wgr({ctx:c,body:d,status:400,message:"Missing required fields: model, messages",errorType:"invalid_request_error"});const m=d.model.toLowerCase();if(!u&&!m.startsWith("claude-"))return Wgr({ctx:c,body:d,status:404,message:`Model '${d.model}' is not an Anthropic model. The proxy only supports Claude models. Use a model router to route non-Claude models to other providers.`,errorType:"not_found_error"});const h=u?.resolve(d.model)??{provider:"anthropic",model:d.model},f=JSON.stringify(d),{tracer:g,requestStartTime:y,logProxyBody:v,logFinalRequest:w,buildLoggedClaudeError:E,setRoutingDecision:_}=Cvn({ctx:c,body:d,clientRequestBody:f});try{return h.provider===null?(g?.setError("not_found_error",`Model '${d.model}' is not a Claude model.`),g?.end(404,Date.now()-y),E(404,`Model '${d.model}' is not a Claude model. Use a model router to route it to another provider.`)):h.provider==="anthropic"?(g?.setMode("passthrough"),l.passthrough?await W0n({ctx:c,body:d,clientRequestBody:f,tracer:g,requestStartTime:y,logProxyBody:v,logFinalRequest:w}):await Pvn({ctx:c,body:d,modelRouter:u,configGeneration:l.generation,tracer:g,requestStartTime:y,accountStrategy:l.strategy,primaryAccountKey:l.primaryAccountKey,accountAllowlist:l.accountAllowlist,quotaRoutingEnabled:l.quotaRoutingEnabled,sessionSoftLimit:l.sessionSoftLimit,sessionResetToleranceMs:l.sessionResetToleranceMs,ranking:l.accountRanking,preferPrimary:l.preferPrimary,sessionAffinityEnabled:l.sessionAffinity,sessionAffinityIdleTtlMs:l.sessionAffinityIdleTtlMs,spillInflight:l.spillInflight,buildLoggedClaudeError:E,logProxyBody:v,logFinalRequest:w,setRoutingDecision:_})):await V0n({ctx:c,body:d,route:{provider:h.provider,model:h.model},modelRouter:u,tracer:g,requestStartTime:y,logProxyBody:v})}catch(C){if(c.abortSignal?.aborted)return new Response(JSON.stringify(E(499,"Client cancelled request","client_cancelled")),{status:499,headers:{"content-type":"application/json"}});const A=C instanceof _r?C:el(C);if(A){C instanceof _r&&C.evidence&&(c.metadata.contextPreflight=C.evidence);const R=E(A.status,A.message,A.code,{errorCode:A.code,retryable:!1});return new Response(JSON.stringify({...R,error:{...R.error,code:A.code,retryable:!1}}),{status:A.status,headers:{"content-type":"application/json"}})}const k=C instanceof Error?C.message:String(C);if(p.error(`[claude-proxy] Generation error for ${d.model}: ${k}`),g?.setError("generation_error",k.slice(0,500)),g?.end(502,Date.now()-y),h.provider==="anthropic")throw C;return E(502,`Generation failed: ${C instanceof Error?C.message:"unknown error"}`)}},description:"Claude-compatible messages endpoint routed through NeuroLink",tags:["claude-proxy","messages"],streaming:{enabled:!0,contentType:"text/event-stream"}},{method:"POST",path:`${t}/peer/heartbeat`,handler:async c=>{const l=c.headers["x-neurolink-share-token"],u=c.headers["x-neurolink-grant-id"];if(!l||!u)return{ok:!1,stop:!0,reason:"no grant identified"};const d=await mce(u);if(!d||!d.leaseSecret||!ovn(d.leaseSecret,l))return{ok:!1,stop:!0,reason:"grant not recognized"};if(d.level!=="complete")return{ok:!1,stop:!0,reason:"grant is not a complete share"};if(d.state!=="active")return{ok:!1,stop:!0,reason:d.state};const m=c.body,h=Number(m?.coinsSpent??0);Number.isFinite(h)&&h>0&&await nvn(d,h);const f=await rvn(d,Number.isFinite(h)?h:0);return f.paused?(p.always(`[proxy] auto-paused share ${d.peerLabel}: ${f.detail}`),{ok:!1,stop:!0,reason:"usage drift"}):{ok:!0,lease:Ofr(d)}},description:"Complete-share heartbeat: report spend, renew the lease",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/handshake`,handler:async c=>{const l=await hy(c.headers);return py(l)?l.body:{ok:!0,protocol:svn,capabilities:ivn,grant:{peerLabel:l.grant.peerLabel,level:l.grant.level,state:l.grant.state,ledger:l.grant.entitlement.ledger}}},description:"Peer handshake: protocol version, capabilities, grant state",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/provision`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;if(l.grant.state!=="active")return Xw(l.grant.state==="paused"?"paused":"revoked",{status:403,grant:l.grant}).body;if(l.grant.level!=="complete")return{type:"error",error:{type:"invalid_request_error",message:"This is a live share. Ask the lender to run `neurolink proxy share level --to complete` first."}};const u=c.body,d=await _yn({grantId:l.grant.id,codeChallenge:String(u?.codeChallenge??""),state:String(u?.state??"")});return d.ok!==!0?{type:"error",error:{type:"invalid_request_error",message:d.reason}}:(p.always(`[proxy] ${l.grant.peerLabel} asked to be provisioned \u2014 run \`neurolink proxy share provision --peer ${l.grant.peerLabel}\``),{ok:!0,status:"pending",expiresAt:d.request.expiresAt})},description:"Lodge a PKCE challenge for a resident credential (complete shares)",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/provision`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=await Cyn(l.grant.id);if(u.status!=="ready")return{ok:!0,status:u.status};const d=await Kin();return{ok:!0,status:"ready",claim:Rgn({grant:l.grant,lenderName:"lender",...d?{lenderUrl:d}:{},code:u.code,state:u.state})}},description:"Collect the authorization code the lender produced",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/receipts`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=Number(c.query?.since??0);return{ok:!0,receipts:await Mar(l.grant.id,Number.isFinite(u)?u:0)}},description:"Collect signed receipts for this grant's settled charges",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/net`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=l.grant.receiptSecret;if(!u)return{type:"error",error:{type:"invalid_request_error",message:"This grant predates receipts and cannot be netted. Ask the lender to re-issue it."}};const d=c.body,m=Number(d?.consumedByYou??NaN),h=Number(d?.alreadyNetted??NaN);return!Number.isFinite(m)||!Number.isFinite(h)?{type:"error",error:{type:"invalid_request_error",message:"A netting claim needs both cumulative totals."}}:e$({consumedByYou:m,alreadyNetted:h,grantId:l.grant.id},String(d?.signature??""),u)?{ok:!0,...await Oar({grantId:l.grant.id,consumedFromPeer:m,peerAlreadyNetted:h})}:Xw("unknown_token",{status:401}).body},description:"Settle one round of reciprocal netting against this grant",tags:["claude-proxy","sharing"]},{method:"POST",path:`${t}/peer/note`,handler:async c=>{const l=c.body,u=Ryn(String(l?.note??""));if(!u)return{type:"error",error:{type:"invalid_request_error",message:"That is not a NeuroLink coin note."}};const d=await tan();if(!l?.redeem)return{ok:!0,...await Pyn(u,d)};const m=await hy(c.headers);if(py(m))return m.body;if(m.grant.entitlement.ledger!=="coins")return{type:"error",error:{type:"invalid_request_error",message:"This grant is unlimited \u2014 there is no balance to redeem into."}};const h=await Myn({note:u,grantId:m.grant.id,secret:d});return h.ok!==!0?{ok:!1,status:h.status,error:{type:"invalid_request_error",message:`That note is ${h.status}.`}}:{ok:!0,status:"redeemed",coins:h.coins,balance:h.balance??null}},description:"Check or redeem a transferable coin note",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/peer/limits`,handler:async c=>{const l=await hy(c.headers);if(py(l))return l.body;const u=a?.();return{ok:!0,...await avn(l.grant,u?.accountAllowlist??i)}},description:"Peer limits: remaining coins, slice left, whether the grant can be served",tags:["claude-proxy","sharing"]},{method:"GET",path:`${t}/v1/models`,handler:async c=>{const l=a?a().modelRouter:e;return dt({name:"neurolink.http.claudeProxy.listModels",tracer:Be.http,attributes:{"http.route":`${t}/v1/models`}},async()=>egn(l))},description:"List available models (Anthropic schema)",tags:["claude-proxy","models"]},{method:"POST",path:`${t}/v1/messages/count_tokens`,handler:async c=>dt({name:"neurolink.http.claudeProxy.countTokens",tracer:Be.http,attributes:{"http.route":`${t}/v1/messages/count_tokens`}},async l=>{const u=c.body;if(typeof u?.model!="string"||!Array.isArray(u?.messages))return $i(400,"Missing required fields: model, messages");const d=u.messages.map(h=>typeof h.content=="string"?h.content:JSON.stringify(h.content)).join(" "),m=Math.ceil(d.length/4);return l.setAttribute("ai.model",u.model),l.setAttribute("gen_ai.usage.input_tokens",m),{input_tokens:m}}),description:"Count tokens for a messages request",tags:["claude-proxy","tokens"]},{method:"GET",path:`${t}/limits`,handler:async c=>{if(Hw())return Xw("no_capacity",{status:403,message:"This proxy does not expose pool limits to peers. Use GET /peer/limits for what your grant may still do."}).body;const l=a?.(),u=l?.accountAllowlist??i;dde(l?.useOverage);const d=c.query?.snapshot==="true"||c.query?.snapshot==="1",m=c.query?.account;return dt({name:"neurolink.http.claudeProxy.limits",tracer:Be.http,attributes:{"http.route":`${t}/limits`}},async()=>!d&&!m?(h3||(h3=cde({accountAllowlist:u}).finally(()=>{h3=null})),h3):cde({accountAllowlist:u,accountFilter:m,snapshotOnly:d}))},description:"Fetch fresh per-account limits from Anthropic (usage API). ?account=<label> for one account, ?snapshot=true for stored state",tags:["claude-proxy","limits"]},{method:"GET",path:`${t}/accounts`,handler:async c=>{const l=a?.(),u=l?.accountAllowlist??i,d=l?.primaryAccountKey??o,m=M=>!!d&&!!M&&Xae(M,d),h=c.query?.refresh==="true";h&&dde(l?.useOverage);let f={fetchedAt:Date.now(),snapshot:!h,results:[]},g=null;try{f=await cde({accountAllowlist:u,snapshotOnly:!h})}catch(M){g=M instanceof Error?M.message:String(M)}const{getUsageSnapshot:y}=await Promise.resolve().then(()=>(ix(),iar)),v=y().stats.accounts,w=Date.now();let E={};try{E=await kx()}catch{}const _=M=>{if(!M)return!1;const F=E[M]?.coolingUntil;return typeof F=="number"&&F>w};let C=new Map,A=null,k="";try{const{readAccountUsage:M,currentUsageDate:F}=await Promise.resolve().then(()=>(Aan(),Kar));k=F(),C=await M(k)}catch(M){A=M instanceof Error?M.message:String(M)}const R=new Map;for(const[M,F]of Object.entries(v)){const L=Hpr(F.label,F.type,F.key??M).key??M,q=R.get(L);(!q||F.key&&!q.key)&&R.set(L,{...F,identityKey:L})}let I;try{I=await w0n()}catch{I=null}const P=[],O=new Set;for(const M of f.results){const F=M.account;O.add(M.key);const N=R.get(M.key),L=Mvn(M.quota),q=_(M.key??null);P.push({label:F,key:M.key??null,provider:M.provider,kind:"account",type:M.type??N?.type??"oauth",status:q?"cooling":S3(L?.weeklyStatus)==="degraded"||S3(L?.sessionStatus)==="degraded"?"exhausted":"active",cooling:q,allowed:null,expired:null,isPrimary:m(M.key??F),requests:N?N.successCount+N.errorCount:null,errors:N?.errorCount??null,rateLimits:N?.rateLimitCount??null,quotaRateLimits:N?.quotaRateLimitCount??null,quota:L?{...L,sessionHealth:S3(L.sessionStatus),weeklyHealth:S3(L.weeklyStatus)}:null,usage:C.get(M.key)??null})}for(const M of R.values()){const F=Hpr(M.label,M.type,M.identityKey);if(F.key!==null&&O.has(F.key))continue;const N=F.provider!=="other";N&&F.key!==null&&I!==null&&!I.has(F.key)||P.push({label:M.label,key:N?F.key:null,...N?{provider:F.provider}:{},kind:N?"account":M.type==="translation"?"translation":"internal",type:F.provider==="codex"?"oauth":M.type,status:N?"unrouted":null,cooling:!1,allowed:null,expired:null,isPrimary:N?m(F.key):!1,requests:M.successCount+M.errorCount,errors:M.errorCount,rateLimits:M.rateLimitCount,quotaRateLimits:M.quotaRateLimitCount,quota:null,usage:F.key!==null?C.get(F.key)??null:null})}return{generatedAt:Date.now(),usageDate:k,quotaFromSnapshot:!h,usageError:A,quotaError:g,costBasis:"api-equivalent",accounts:P}},description:"One row per account: status, quota, and today's tokens and API-equivalent cost. ?refresh=true forces a live quota fetch",tags:["claude-proxy","accounts"]}]}}function $a(e){const t=pc.get(e);if(t)return t;const r={consecutiveRefreshFailures:0,permanentlyDisabled:!1};return pc.set(e,r),r}function Dvn(e){const t=$a(e.key),r=t.lastToken!==e.token||t.lastRefreshToken!==e.refreshToken,n=t.permanentlyDisabled;n&&p.always(`[proxy] account=${e.label} is enabled in the token store; clearing stale runtime auth-disable state`),t.permanentlyDisabled=!1,(r||n)&&(t.consecutiveRefreshFailures=0),t.lastToken=e.token,t.lastRefreshToken=e.refreshToken}async function wm(e,t,r){try{const{tokenStore:n}=await Promise.resolve().then(()=>(Xg(),ece)),o=e.persistTarget&&typeof e.persistTarget!="string"&&"providerKey"in e.persistTarget?e.persistTarget.providerKey:void 0;if(o){if(!await n.markDisabledIfCurrent(o,{accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt??0},r))return t.permanentlyDisabled=!1,p.always(`[proxy] account=${e.label} credentials changed while authentication was in flight; ignored stale disable`),!1}else await n.markDisabled(e.key,r)}catch(n){p.debug(`[proxy] failed to persist disabled state for ${e.label}: ${n instanceof Error?n.message:String(n)}`)}return t.permanentlyDisabled=!0,p.always(r==="entitlement_blocked"?`[proxy] account=${e.label} disabled: the organization blocks Claude Code OAuth. Ask an admin to re-enable it, then run: neurolink auth enable ${e.key}`:`[proxy] account=${e.label} disabled until re-authentication. Run: neurolink auth login anthropic --method oauth`),!0}async function b3(e,t){t.consecutiveRefreshFailures+=1;const r=Math.min(t.consecutiveRefreshFailures-1,4),n=Math.min(Qyn,Zyn*2**r),o=Date.now()+n;(!t.coolingUntil||o>t.coolingUntil)&&(t.coolingUntil=o,t.coolingReason="auth");const s=t.coolingUntil??o,i=t.coolingReason??"auth";return t.coolingUntil=s,t.coolingReason=i,await Vu(e.key,s,i).catch(()=>{}),s}async function _3(e,t){if(t.consecutiveRefreshFailures=0,t.coolingReason!=="auth"||!t.coolingUntil)return;const r=t.coolingUntil;t.coolingUntil=void 0,t.coolingReason=void 0,await Yp(e.key,r).catch(()=>{})}function C3(e){return`Account(s) require re-authentication: ${Array.isArray(e)?e.join(", "):e}. Run: neurolink auth login anthropic --method oauth`}function Cr(e,t=180){const r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t)}...`}function Sde(e){const t=Math.min(Math.max(e-1,0),Jue.length-1);return Jue[t]??0}function Kgr(e){const t=Math.min(Math.max(e-1,0),ugr.length-1);return Jgr(ugr[t]??250)}async function Zl(e){await new Promise(t=>setTimeout(t,e))}function Jgr(e){return e+Math.floor(Math.random()*e*.25)}function oI(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="string")return t;const r=e.cause;if(!r||typeof r!="object")return;const n=r.code;return typeof n=="string"?n:void 0}function Ql(e){const t=e instanceof Error?e.message:String(e);if(!e||typeof e!="object")return t;const r=e.cause,n=r instanceof Error?r.message:r&&typeof r=="object"?String(r.message??""):"",s=[oI(e),n&&n!==t&&n].filter(Boolean).join(": ");return s?`${t} (${s})`:t}function Ygr(e){const t=new Set;let r=e;for(;r&&typeof r=="object"&&!t.has(r);){t.add(r);const n=r;if(n.syscall==="connect")return!0;if(Array.isArray(n.errors)&&n.errors.length>0)return n.errors.every(o=>o!==null&&typeof o=="object"&&o.syscall==="connect");r=n.cause}return!1}function bde(e){if(Ygr(e))return!0;const t=oI(e);return t!==void 0&&["ECONNREFUSED","EADDRNOTAVAIL","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","UND_ERR_CONNECT_TIMEOUT","UND_ERR_CONNECT"].includes(t)}function Nvn(e){const t=oI(e);return t==="ENOTFOUND"||t==="EAI_AGAIN"?"shared_provider_transport":"connection_transport"}var Lvn=new Set([408,500,502,503,504,520,521,522,523,524,525,526,529]);function Ku(e){try{const t=JSON.parse(e);if(t&&t.type==="error"&&t.error&&typeof t.error=="object"){const r=t.error.details?.error_code;return{errorType:typeof t.error.type=="string"?t.error.type:void 0,message:typeof t.error.message=="string"?t.error.message:void 0,...typeof r=="string"?{errorCode:r}:{}}}}catch{}return{}}function Fvn(e,t){return e===422?!0:Ku(t).errorType==="invalid_request_error"||t.includes("invalid_request_error")}function $vn(e,t){if(e!==404)return!1;const r=Ku(t);return r.errorType==="not_found_error"&&(r.message??"").toLowerCase().includes("model")}function Uvn(e,t){if(e!==400)return!1;const r=Ku(t);if(r.errorType!=="invalid_request_error")return!1;const n=(r.message??"").toLowerCase();return n.includes("beta")&&n.includes("subscription")&&n.includes("available")}var Xgr=new Set(["oauth_not_allowed_for_organization","oauth_not_allowed","organization_disabled"]);function _de(e,t){if(e!==401&&e!==402&&e!==403)return!1;const r=Ku(t);return r.errorType==="permission_error"?!0:r.errorCode!==void 0&&Xgr.has(r.errorCode)}function Zgr(e,t){if(!_de(e,t))return!1;const r=Ku(t);return r.errorCode!==void 0&&Xgr.has(r.errorCode)}function Bvn(e){return{...e,messages:e.messages.map(t=>typeof t.content!="string"?t:{...t,content:[{type:"text",text:t.content}]})}}var Qgr=Efr;function eyr(e,t){if(Lvn.has(e))return!0;if(e!==400)return!1;const r=Ku(t);if(r.errorType==="overloaded_error")return!0;if(r.errorType!=="api_error")return!1;const n=(r.message??t).toLowerCase();return n.includes("<!doctype html")||n.includes("error code 520")||n.includes("web server is returning an unknown error")||n.includes("cloudflare")||n.includes("internal server error")}function zvn(e,t){return e===529||Ku(t).errorType==="overloaded_error"}var qvn=500;function sE(e){return lr(e,qvn)}Ut(),z();var Gvn=55669,jvn="generateContent",tyr="streamGenerateContent";function Hvn(e){const r=e.split("?")[0].replace(/\/+$/,"").split("/").pop()??"",n=r.lastIndexOf(":");return n===-1?{modelId:r,action:void 0}:{modelId:r.slice(0,n),action:r.slice(n+1)}}function Vvn(e){return{model:e.model,maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,systemPrompt:e.systemPrompt,stream:e.stream,prompt:e.prompt,images:e.images,conversationMessages:e.conversationMessages,tools:e.tools,stopSequences:e.stopSequences}}function Wvn(e,t="",r=Gvn,n){return{prefix:`${t}/v1beta`,routes:[{method:"POST",path:`${t}/v1beta/models/:model`,description:"Gemini-compatible generateContent / streamGenerateContent (translation mode)",handler:async o=>{const s=n?n().modelRouter:e,i=Date.now(),{modelId:a,action:c}=Hvn(o.path);if(!a||c!==jvn&&c!==tyr)return Yle(404,`Unsupported Gemini endpoint: ${o.path}`,"NOT_FOUND");const l=o.body;if(!l||!Array.isArray(l.contents)||l.contents.length===0)return Yle(400,"Request must include a non-empty 'contents' array");const u=c===tyr,d=s?s.resolve(a):{provider:null,model:a},m=d.provider??void 0,h=d.model??a;p.debug(`[proxy:gemini] ${a} \u2192 ${m??"auto"}/${h}`);const f=khn(h,l,u),g=Vvn(f),v=tE({provider:m??"auto",model:h},s?.getFallbackChain()??[],a,g,s?.isAutoFallbackEnabled?.()??!1).attempts;let w;try{w=Ux.startRequest({requestId:o.requestId,method:o.method,path:o.path,model:a,stream:u,toolCount:Object.keys(f.tools).length,clientApp:"gemini-compat",userAgent:o.headers["user-agent"]??"",provider:m??"google-ai"},o.headers),w.setMode("full")}catch{}try{return u?await r3({ctx:o,format:"gemini",requestModel:a,parsed:f,attempts:v,tracer:w,requestStartTime:i}):await n3({ctx:o,format:"gemini",requestModel:a,parsed:f,attempts:v,tracer:w,requestStartTime:i})}catch(E){const _=E instanceof Error?E.message:String(E),C=lr(_);return p.always(`[proxy:gemini] request failed: ${C}`),w?.setError("generation_error",C),w?.end(500,Date.now()-i),Yle(500,"Internal proxy error","INTERNAL")}}}]}}Or(),pr();function Cde(e,t,r){return n=>dt({name:e,tracer:Be.http,attributes:{"http.route":t,"http.request.id":n.requestId??""}},()=>r(n))}function ryr(e="/api"){return{prefix:`${e}/health`,routes:[{method:"GET",path:`${e}/health`,handler:Cde("neurolink.http.health.check",`${e}/health`,async()=>({status:"ok",timestamp:new Date().toISOString(),uptime:process.uptime()*1e3,version:process.env.npm_package_version||"unknown"})),description:"Basic health check",tags:["health"]},{method:"GET",path:`${e}/health/live`,handler:Cde("neurolink.http.health.live",`${e}/health/live`,async()=>({status:"alive",timestamp:new Date().toISOString()})),description:"Kubernetes liveness probe",tags:["health"]},{method:"GET",path:`${e}/health/ready`,handler:t=>dt({name:"neurolink.http.health.ready",tracer:Be.http,attributes:{"http.route":`${e}/health/ready`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools(),o=n.length>0,s=!!t.externalServerManager;let i=!0;if(t.externalServerManager){const c=t.externalServerManager.getServerStatuses();for(const l of c)if(l.status!=="connected"){i=!1;break}}const a=o||!s||i;return r.setAttribute("health.ready",a),r.setAttribute("health.tools_count",n.length),r.setAttribute("health.external_servers_ready",i),{ready:a,timestamp:new Date().toISOString(),services:{neurolink:!0,tools:o,externalServers:i}}}),description:"Kubernetes readiness probe",tags:["health"]},{method:"GET",path:`${e}/health/startup`,handler:t=>dt({name:"neurolink.http.health.startup",tracer:Be.http,attributes:{"http.route":`${e}/health/startup`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools();return r.setAttribute("health.tools_count",n.length),{started:!0,timestamp:new Date().toISOString(),services:{neurolink:!0,toolsLoaded:n.length,externalServerManager:!!t.externalServerManager}}}),description:"Kubernetes startup probe",tags:["health"]},{method:"GET",path:`${e}/health/detailed`,handler:t=>dt({name:"neurolink.http.health.detailed",tracer:Be.http,attributes:{"http.route":`${e}/health/detailed`,"http.request.id":t.requestId??""}},async r=>{const n=await t.toolRegistry.listTools(),o={};for(const l of n){const u=typeof l.source=="string"?l.source:l.serverId||"built-in";o[u]=(o[u]||0)+1}const s=[];if(t.externalServerManager){const l=t.externalServerManager.getServerStatuses();for(const u of l)s.push({name:u.serverId,status:u.status,toolCount:u.toolCount})}const i=t.neurolink.conversationMemory,a={available:!!i,type:i?.constructor.name||"none"},c={status:"ok",timestamp:new Date().toISOString(),uptime:process.uptime()*1e3,version:process.env.npm_package_version||"unknown",node:{version:process.version,platform:process.platform,arch:process.arch},memory:{...a,process:{heapUsed:Math.round(process.memoryUsage().heapUsed/1024/1024),heapTotal:Math.round(process.memoryUsage().heapTotal/1024/1024),rss:Math.round(process.memoryUsage().rss/1024/1024),external:Math.round(process.memoryUsage().external/1024/1024)}},tools:{total:n.length,bySource:o},externalServers:{count:s.length,servers:s}};if(t.metadata?.accountPool){const l=t.metadata.accountPool,u=l.getAllAccounts(),d={};for(const m of u)d[m.status]=(d[m.status]||0)+1;c.proxy={totalAccounts:u.length,statusDistribution:d,healthyCount:l.getHealthyCount(),strategy:l.getStrategy()},r.setAttribute("health.proxy.accounts",u.length),r.setAttribute("health.proxy.healthy",l.getHealthyCount())}return r.setAttribute("health.tools_count",n.length),r.setAttribute("health.external_servers_count",s.length),r.setAttribute("health.memory.heap_mb",Math.round(process.memoryUsage().heapUsed/1024/1024)),c}),description:"Detailed health information",tags:["health"]},{method:"GET",path:`${e}/version`,handler:Cde("neurolink.http.version",`${e}/version`,async()=>({name:"@juspay/neurolink",version:process.env.npm_package_version||"unknown",node:process.version,timestamp:new Date().toISOString()})),description:"Get version information",tags:["health","version"]}]}}ix(),Lr(),Ut(),z();var Kvn=300*1e3,Jvn=55669;function nyr(e){return e?{status:502,errorType:"loopback_stream_error",errorMessage:e}:{status:499,errorType:"client_cancelled",errorMessage:"Client cancelled the OpenAI-compatible stream"}}function A3(e,t){return new Response(JSON.stringify(Lhr(e,t)),{status:e,headers:{"content-type":"application/json"}})}function Yvn(e){return{model:e.model,maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,systemPrompt:typeof e.systemPrompt=="string"?e.systemPrompt:void 0,stream:e.stream,prompt:e.prompt,images:e.images,conversationMessages:e.conversationMessages,tools:e.tools,toolChoice:e.toolChoice,toolChoiceName:e.toolChoiceName,stopSequences:e.stopSequences}}function Xvn(e,t){try{const r=Ux.startRequest({requestId:e.requestId,method:e.method,path:e.path,model:t.model,stream:t.stream===!0,toolCount:t.tools?.length??0,provider:"openai-bridge",recordRequestMetrics:!0,recordUsageMetrics:!1,...Fx(e.headers)},e.headers);return r.setMode("full"),r}catch{return}}function Zvn(e,t,r){const n={"content-type":"application/json",accept:t?"text/event-stream":"application/json","x-neurolink-internal-request":r},o=iue(e.requestId);o&&(n.traceparent=`00-${o.traceId}-${o.spanId}-${o.traceFlags.toString(16).padStart(2,"0")}`);for(const[s,i]of Object.entries(e.headers)){if(typeof i!="string")continue;const a=s.toLowerCase();(a.startsWith("anthropic-")||a==="x-api-key"||["user-agent","x-neurolink-session-id","x-claude-code-session-id","session_id","session-id","tracestate","baggage"].includes(a)||a==="traceparent"&&!n.traceparent)&&(n[a]=i)}return n}function Qvn(e){const t=e?.servingModelStatus??"unavailable",r=e?.accountIdentityStatus??(e?.accountKey&&e.accountType!=="translation"&&e.account!=="unknown"?"observed":"unavailable");return{servingModelStatus:t,accountIdentityStatus:r}}async function eTn(e,t,r,n,o,s){try{const i=await id(e.json(),t),a=Dhn(i,r);return s.json(a,200),await n(200),a}catch(i){const a=t.aborted&&t.reason?.name!=="TimeoutError"?499:t.reason?.name==="TimeoutError"?504:502;return await n(a,{errorType:a===499?"client_cancelled":a===504?"loopback_timeout":"loopback_response_error",errorMessage:i instanceof Error?i.message:String(i)}),o(a,"Anthropic loopback failed")}}async function tTn(e){const{ctx:t,body:r,targetModel:n,requestStartTime:o,loopbackPort:s,internalDispatch:i}=e,a=r.stream===!0,c=r.tools?.length??0,l=vfr(t,r.model,a,o);l.request();const u=(E,_)=>(l.json(Lhr(E,_),E),A3(E,_)),d=Thn(t.requestId),m=Xvn(t,r),h=new AbortController,f=AbortSignal.any([h.signal,AbortSignal.timeout(Kvn),...t.abortSignal?[t.abortSignal]:[]]);let g=!1;const y=(E,_={})=>{if(g)return Promise.resolve();g=!0,d.dispose();const C=vhn(t.requestId),{servingModelStatus:A,accountIdentityStatus:k}=Qvn(C);return A==="observed"&&C?.model&&C.model!==r.model&&m?.setModelSubstitution(r.model,C.model,C.provider),_.errorType&&m?.setError(_.errorType,_.errorMessage??_.errorType),m?.end(E,Date.now()-o),Fw(t.requestId)||(E>=400?Zg(E,C?.account,C?.accountType,{requestId:t.requestId,errorType:_.errorType,message:_.errorMessage,terminalOutcome:E===499?"client_cancelled":_.errorType?.includes("stream")?"stream_error":"handler_error"}):nx(C?.account,C?.accountType)),Kw({timestamp:new Date().toISOString(),requestId:t.requestId,method:t.method,path:t.path,model:C?.model??r.model,servingModelStatus:A,stream:a,toolCount:c,account:C?.account??"",accountKey:C?.accountKey,accountType:C?.accountType??"openai-bridge",accountIdentityStatus:k,requestedModel:r.model,provider:C?.provider,errorCode:C?.errorCode,transportScope:C?.transportScope,retryable:C?.retryable,accountingScope:"client",usageOwnerRequestId:d.requestId,...Fx(t.headers),responseStatus:E,responseTimeMs:Date.now()-o,..._}).finally(()=>bhr(t.requestId))},v=`http://127.0.0.1:${s}/v1/messages`;let w;try{f.throwIfAborted();const E=Ohn(r);E.model=n;const C={method:"POST",headers:Zvn(t,a,d.token),body:JSON.stringify({...E,stream:a}),signal:f};w=await id(Promise.resolve(i?i(new Request(v,C)):fetch(v,C)),f)}catch(E){d.dispose();const _=t.abortSignal?.aborted?499:f.aborted?504:502;return h.abort(E),await y(_,{errorType:t.abortSignal?.aborted?"client_cancelled":_===504?"loopback_timeout":"loopback_exception",errorMessage:E instanceof Error?E.message:String(E)}),u(_,"Anthropic loopback failed")}if(!w.ok){const E=await id(w.text(),f).catch(()=>""),_=lr(E);return p.always(`[proxy:openai] anthropic loopback error ${w.status}: ${_}`),await y(w.status,{errorType:"loopback_upstream_error",errorMessage:_}),u(w.status,_||`Anthropic loopback failed with status ${w.status}`)}if(a){if(!w.body)return await y(502,{errorType:"loopback_empty_stream",errorMessage:"Anthropic loopback returned empty stream body"}),u(502,"Anthropic loopback returned empty stream body");const E=l.accumulator("client_response","text/event-stream");let _;const A=w.body.pipeThrough(Nhn(r.model,{onError:P=>{_=lr(P)}})).getReader(),k=async(P,O,U)=>{f.removeEventListener("abort",R),E.finish(P),await y(P,{errorType:O,errorMessage:U})},R=()=>{const P=_?nyr(_):{status:f.reason?.name==="TimeoutError"?504:499,errorType:f.reason?.name==="TimeoutError"?"loopback_timeout":"client_cancelled",errorMessage:"Anthropic loopback cancelled"};k(P.status,P.errorType,P.errorMessage),Ct(A.cancel(f.reason),1e3,"Loopback cancellation timed out").catch(()=>{})};f.addEventListener("abort",R,{once:!0}),f.aborted&&R();const I=new ReadableStream({async pull(P){try{const{value:O,done:U}=await A.read();if(U){_?await k(502,"loopback_stream_error",_):await k(200),P.close();return}E.append(O),P.enqueue(O)}catch(O){const U=lr(O instanceof Error?O.message:String(O));await k(502,"loopback_stream_error",U),P.error(O)}},async cancel(P){const O=nyr(_),U=k(O.status,O.errorType,O.errorMessage);h.abort(P),await Promise.all([U,Ct(A.cancel(P),1e3,"Loopback cancellation timed out").catch(()=>{})])}});return new Response(I,{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}})}return eTn(w,f,r.model,y,u,l)}function rTn(e,t="",r=Jvn,n,o){return{prefix:`${t}/v1`,routes:[{method:"POST",path:`${t}/v1/chat/completions`,description:"OpenAI-compatible chat completions (translation mode)",handler:async s=>{const i=n?n().modelRouter:e,a=Date.now(),c=s.body;if(!c||!c.model||!c.messages?.length)return A3(400,"Request must include 'model' and 'messages' fields");const l=i?i.resolve(c.model):{provider:null,model:c.model},u=l.provider??void 0,d=l.model??c.model;if(p.debug(`[proxy:openai] ${c.model} \u2192 ${u??"auto"}/${d}`),l.provider==="anthropic")try{return await tTn({ctx:s,body:c,targetModel:d,requestStartTime:a,loopbackPort:r,internalDispatch:o})}catch(v){const w=v instanceof Error?v.message:String(v),E=lr(w);p.always(`[proxy:openai] anthropic loopback failed: ${E}`);const _=s.abortSignal?.aborted?499:v instanceof Error&&"status"in v&&v.status===503?503:v instanceof Error&&v.name==="TimeoutError"?504:502;return Fw(s.requestId)||Zg(_,void 0,void 0,{requestId:s.requestId,errorType:_===499?"client_cancelled":"loopback_exception",message:E}),await Kw({timestamp:new Date().toISOString(),requestId:s.requestId,method:s.method,path:s.path,model:c.model,stream:c.stream===!0,toolCount:c.tools?.length??0,account:"",accountType:"openai-bridge",responseStatus:_,responseTimeMs:Date.now()-a,errorType:_===499?"client_cancelled":"loopback_exception",errorMessage:E}).finally(()=>bhr(s.requestId)),A3(_,"Anthropic loopback failed")}const m=Phn(c),h=Yvn(m),g=tE({provider:u??"auto",model:d},i?.getFallbackChain()??[],c.model,h,i?.isAutoFallbackEnabled?.()??!1).attempts;let y;try{y=Ux.startRequest({requestId:s.requestId,method:s.method,path:s.path,model:c.model,stream:c.stream===!0,toolCount:Object.keys(m.tools).length,clientApp:"openai-compat",userAgent:s.headers["user-agent"]??"",provider:u??"openai-compatible"},s.headers),y.setMode("full")}catch{}try{return c.stream?r3({ctx:s,format:"openai",requestModel:c.model,parsed:m,attempts:g,tracer:y,requestStartTime:a}):await n3({ctx:s,format:"openai",requestModel:c.model,parsed:m,attempts:g,tracer:y,requestStartTime:a})}catch(v){const w=v instanceof Error?v.message:String(v),E=lr(w);return p.always(`[proxy:openai] request failed: ${E}`),y?.setError("generation_error",E),y?.end(500,Date.now()-a),A3(500,"Internal proxy error")}}},{method:"GET",path:`${t}/v1/models`,description:"List available models in OpenAI format",handler:async()=>{const s=n?n().modelRouter:e;return Qfn(s)}}]}}Xt(),en(),Or(),pr(),Uu();function fy(e,t,r){return n=>dt({name:e,tracer:Be.http,attributes:{"http.route":t,"http.request.id":n.requestId}},async o=>{const s=await r(n);if(s&&typeof s=="object"){const i=s.error;if(i!=null){const a=typeof i=="string"?i:typeof i?.message=="string"?i.message:"MCP handler error";o.setStatus({code:Ue.ERROR,message:a})}}return s})}var nTn=D.object({name:D.string().min(1,"Server name is required"),toolName:D.string().min(1,"Tool name is required")});async function oTn(e){const t=e.externalServerManager;if(!t)return{servers:[],total:0,message:"External server manager not available",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}};const r=t.listServers(),n=t.getServerStatuses(),o=new Map(n.map(i=>[i.serverId,i])),s=r.map(i=>{const a=o.get(i.name);return{serverId:i.name,name:i.name,status:a?.status||"disconnected",toolCount:a?.toolCount||0,lastHealthCheck:a?.checkedAt?.toISOString(),error:a?.issues?.[0]}});return{servers:s,total:s.length,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function sTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Bt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);if(!n.listServers().find(u=>u.name===r))return Bt("SERVER_NOT_FOUND",`MCP server '${r}' not found`,void 0,e.requestId);const a=n.getServerStatuses().find(u=>u.serverId===r),l=(await e.toolRegistry.listTools()).filter(u=>u.source===r);return{serverId:r,name:r,status:a?.status||"disconnected",toolCount:a?.toolCount||0,tools:l.map(u=>({name:u.name,description:u.description})),lastHealthCheck:a?.checkedAt?.toISOString(),error:a?.issues?.[0],metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function iTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Bt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);try{if(!n.listServers().find(c=>c.name===r))return Bt("SERVER_NOT_FOUND",`Server '${r}' not found`,void 0,e.requestId);const a=n.getServerStatuses().find(c=>c.serverId===r);return{success:!0,server:{serverId:r,name:r,status:a?.status||"disconnected",toolCount:a?.toolCount||0},message:"Server status retrieved (full reconnect requires server restart)",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(o){return Bt("RECONNECT_FAILED",o instanceof Error?o.message:String(o),void 0,e.requestId)}}async function aTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,n=e.externalServerManager;if(!n)return Bt("MCP_UNAVAILABLE","External server manager not available",void 0,e.requestId);try{const o=await n.removeServer(r);return o.success?{success:!0,message:`Server '${r}' removed`,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}:Bt("REMOVE_FAILED",o.error||"Failed to remove server",void 0,e.requestId)}catch(o){return Bt("REMOVE_FAILED",o instanceof Error?o.message:String(o),void 0,e.requestId)}}async function cTn(e){const t=Gl(dw,e.params,e.requestId);if(!t.success)return t.error;const{name:r}=t.data,o=(await e.toolRegistry.listTools()).filter(s=>s.source===r);if(o.length===0){const s=e.externalServerManager;if(s&&!s.listServers().find(c=>c.name===r))return Bt("SERVER_NOT_FOUND",`MCP server '${r}' not found`,void 0,e.requestId)}return{serverId:r,tools:o.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema})),total:o.length,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}async function lTn(e){const t=Gl(nTn,e.params,e.requestId);if(!t.success)return t.error;const{name:r,toolName:n}=t.data,o=$u(jF,e.body||{},e.requestId);if(!o.success)return o.error;const s=o.data,i=Date.now();try{return(await e.toolRegistry.listTools()).find(u=>u.name===n&&u.source===r)?{success:!0,data:await e.toolRegistry.executeTool(n,s),duration:Date.now()-i,metadata:{server:r,toolName:n,timestamp:new Date().toISOString(),requestId:e.requestId}}:Bt("TOOL_NOT_FOUND",`Tool '${n}' not found on server '${r}'`,void 0,e.requestId)}catch(a){return Bt("EXECUTION_FAILED",a instanceof Error?a.message:String(a),{duration:Date.now()-i},e.requestId)}}async function uTn(e){const t=e.externalServerManager;if(!t)return{healthy:!1,message:"External server manager not available",servers:[]};const n=t.getServerStatuses().map(i=>({name:i.serverId,healthy:i.isHealthy,error:i.issues?.[0]})),o=n.every(i=>i.healthy),s=n.some(i=>i.healthy);return{healthy:n.length===0||o,status:n.length===0?"no_servers":o?"all_healthy":s?"degraded":"unhealthy",servers:n,timestamp:new Date().toISOString()}}function oyr(e="/api"){return{prefix:`${e}/mcp`,routes:[{method:"GET",path:`${e}/mcp/servers`,handler:fy("neurolink.http.mcp.listServers",`${e}/mcp/servers`,oTn),description:"List all MCP servers",tags:["mcp"]},{method:"GET",path:`${e}/mcp/servers/:name`,handler:fy("neurolink.http.mcp.getServer",`${e}/mcp/servers/:name`,sTn),description:"Get MCP server status",tags:["mcp"]},{method:"POST",path:`${e}/mcp/servers/:name/reconnect`,handler:fy("neurolink.http.mcp.reconnectServer",`${e}/mcp/servers/:name/reconnect`,iTn),description:"Reconnect to an MCP server",tags:["mcp"]},{method:"DELETE",path:`${e}/mcp/servers/:name`,handler:fy("neurolink.http.mcp.removeServer",`${e}/mcp/servers/:name`,aTn),description:"Remove an MCP server",tags:["mcp"]},{method:"GET",path:`${e}/mcp/servers/:name/tools`,handler:fy("neurolink.http.mcp.listServerTools",`${e}/mcp/servers/:name/tools`,cTn),description:"List tools from a specific MCP server",tags:["mcp","tools"]},{method:"POST",path:`${e}/mcp/servers/:name/tools/:toolName/execute`,handler:fy("neurolink.http.mcp.executeTool",`${e}/mcp/servers/:name/tools/:toolName/execute`,lTn),description:"Execute a tool from a specific MCP server",tags:["mcp","tools"]},{method:"GET",path:`${e}/mcp/health`,handler:fy("neurolink.http.mcp.health",`${e}/mcp/health`,uTn),description:"Health check for all MCP servers",tags:["mcp","health"]}]}}Or(),pr(),Uu();function gy(e,t,r){return n=>dt({name:e,tracer:Be.http,attributes:{"http.route":t,"http.request.id":n.requestId}},()=>r(n))}async function dTn(e){const t=Gl(Gae,e.params,e.requestId);if(!t.success)return t.error;const{id:r}=t.data,n=e.query.limit?parseInt(e.query.limit,10):50,o=e.query.offset?parseInt(e.query.offset,10):0,s=isNaN(n)||n<1?50:Math.min(n,100),i=isNaN(o)||o<0?0:o,a=e.neurolink.conversationMemory;if(!a)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{let c=[];if("getUserSessionHistory"in a){const d=e.query.userId||"default",m=await a.getUserSessionHistory(d,r);if(m===null)return Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId);c=m}else if("getSession"in a){const d=a.getSession(r);if(!d)return Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId);c=d.messages}else if("buildContextMessages"in a&&(c=await a.buildContextMessages(r),c.length===0))return Bt("SESSION_NOT_FOUND",`Session '${r}' not found or has no messages`,void 0,e.requestId);const l=c.length,u=c.slice(i,i+s);return{sessionId:r,messages:u,total:l,limit:s,offset:i,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(c){return Bt("MEMORY_ERROR",c instanceof Error?c.message:"Failed to get session messages",void 0,e.requestId)}}async function mTn(e){const t=Gl(Gae,e.params,e.requestId);if(!t.success)return t.error;const{id:r}=t.data,n=e.neurolink.conversationMemory;if(!n)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{if("getUserSessionObject"in n){const o=e.query.userId||"default",s=await n.getUserSessionObject(o,r);return s===null?Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId):{session:s,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}else if("getSession"in n){const o=n.getSession(r);return o?{session:o,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}:Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId)}return Bt("MEMORY_ERROR","Session retrieval not supported for this memory type",void 0,e.requestId)}catch(o){return Bt("MEMORY_ERROR",o instanceof Error?o.message:"Failed to get session",void 0,e.requestId)}}async function pTn(e){const t=e.query.userId,r=e.query.limit?parseInt(e.query.limit,10):50,n=e.query.offset?parseInt(e.query.offset,10):0,o=isNaN(r)||r<1?50:Math.min(r,100),s=isNaN(n)||n<0?0:n,i=e.neurolink.conversationMemory;if(!i)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{let a=[];if("getUserAllSessionsHistory"in i&&t)a=await i.getUserAllSessionsHistory(t);else if("getUserSessions"in i&&t){const u=await i.getUserSessions(t);if("getUserSessionMetadata"in i){const d=u.map(h=>i.getUserSessionMetadata(t,h));a=(await Promise.all(d)).filter(h=>h!==null)}else a=u.map(d=>({id:d}))}else if("getStats"in i){const u=await i.getStats?.();return{sessions:[],total:u?.totalSessions||0,limit:o,offset:s,message:"Session listing not fully supported for in-memory storage. Use /stats endpoint for session counts.",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}const c=a.length;return{sessions:a.slice(s,s+o),total:c,limit:o,offset:s,metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(a){return Bt("MEMORY_ERROR",a instanceof Error?a.message:"Failed to list sessions",void 0,e.requestId)}}async function hTn(e){const t=e.neurolink.conversationMemory;if(!t)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{const r=await t.getStats?.();return{available:!0,type:t.constructor.name,stats:r||{message:"Statistics not available for this memory type"},timestamp:new Date().toISOString()}}catch(r){return Bt("MEMORY_ERROR",r instanceof Error?r.message:"Failed to get statistics",void 0,e.requestId)}}async function fTn(e){const t=Gl(qae,e.params,e.requestId);if(!t.success)return t.error;const{sessionId:r}=t.data,n=e.neurolink.conversationMemory;if(!n)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{return await n.clearSession?.(r)===!1?Bt("SESSION_NOT_FOUND",`Session '${r}' not found`,void 0,e.requestId):{success:!0,sessionId:r,message:"Session cleared successfully",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(o){return Bt("MEMORY_ERROR",o instanceof Error?o.message:"Failed to clear session",void 0,e.requestId)}}async function gTn(e){const t=e.neurolink.conversationMemory;if(!t)return Bt("MEMORY_UNAVAILABLE","Conversation memory not available",void 0,e.requestId);try{return await t.clearAllSessions?.(),{success:!0,message:"All sessions cleared successfully",metadata:{timestamp:new Date().toISOString(),requestId:e.requestId}}}catch(r){return Bt("MEMORY_ERROR",r instanceof Error?r.message:"Failed to clear sessions",void 0,e.requestId)}}async function yTn(e){const t=e.neurolink.conversationMemory;return{available:!!t,type:t?.constructor.name||"none",timestamp:new Date().toISOString()}}function syr(e="/api"){return{prefix:`${e}/memory`,routes:[{method:"GET",path:`${e}/memory/sessions/:id/messages`,handler:gy("neurolink.http.memory.getSessionMessages",`${e}/memory/sessions/:id/messages`,dTn),description:"Get messages for a session",tags:["memory"]},{method:"GET",path:`${e}/memory/sessions/:id`,handler:gy("neurolink.http.memory.getSession",`${e}/memory/sessions/:id`,mTn),description:"Get session by ID",tags:["memory"]},{method:"GET",path:`${e}/memory/sessions`,handler:gy("neurolink.http.memory.listSessions",`${e}/memory/sessions`,pTn),description:"List all conversation sessions",tags:["memory"]},{method:"GET",path:`${e}/memory/stats`,handler:gy("neurolink.http.memory.stats",`${e}/memory/stats`,hTn),description:"Get memory statistics",tags:["memory"]},{method:"DELETE",path:`${e}/memory/sessions/:sessionId`,handler:gy("neurolink.http.memory.clearSession",`${e}/memory/sessions/:sessionId`,fTn),description:"Clear a conversation session",tags:["memory"]},{method:"DELETE",path:`${e}/memory/sessions`,handler:gy("neurolink.http.memory.clearAllSessions",`${e}/memory/sessions`,gTn),description:"Clear all conversation sessions",tags:["memory"]},{method:"GET",path:`${e}/memory/health`,handler:gy("neurolink.http.memory.health",`${e}/memory/health`,yTn),description:"Check memory system health",tags:["memory","health"]}]}}z(),Or(),pr();function vTn(e="/api",t){return t||p.debug("[OpenAPI] createOpenApiRoutes called without getRoutes callback. Custom routes will not be documented in the OpenAPI spec."),{prefix:`${e}/openapi`,routes:[{method:"GET",path:`${e}/openapi.json`,handler:async()=>dt({name:"neurolink.http.openapi.json",tracer:Be.http,attributes:{"http.route":`${e}/openapi.json`,"openapi.format":"json"}},async r=>{const n=t?.()??[];return t?n.length===0&&p.debug("[OpenAPI] getRoutes returned empty array. No custom routes will be documented."):p.warn("[OpenAPI] No getRoutes callback provided. OpenAPI spec will use default endpoint definitions. Use registerAllRoutes(server, basePath, { enableSwagger: true }) to automatically include your routes."),r.setAttribute("openapi.route_count",n.length),new Ax({basePath:e,routes:n}).generate()}),description:"Get OpenAPI specification as JSON",tags:["openapi","documentation"]},{method:"GET",path:`${e}/openapi.yaml`,handler:async()=>dt({name:"neurolink.http.openapi.yaml",tracer:Be.http,attributes:{"http.route":`${e}/openapi.yaml`,"openapi.format":"yaml"}},async r=>{const n=t?.()??[];return t?n.length===0&&p.debug("[OpenAPI] getRoutes returned empty array. No custom routes will be documented."):p.warn("[OpenAPI] No getRoutes callback provided. OpenAPI spec will use default endpoint definitions. Use registerAllRoutes(server, basePath, { enableSwagger: true }) to automatically include your routes."),r.setAttribute("openapi.route_count",n.length),{_raw:!0,contentType:"text/yaml",body:new Ax({basePath:e,routes:n}).toYAML()}}),description:"Get OpenAPI specification as YAML",tags:["openapi","documentation"]},{method:"GET",path:`${e}/docs`,handler:async()=>dt({name:"neurolink.http.openapi.docs",tracer:Be.http,attributes:{"http.route":`${e}/docs`}},async()=>({_raw:!0,contentType:"text/html",body:`<!DOCTYPE html>
|
|
2369
2369
|
<html>
|
|
2370
2370
|
<head>
|
|
2371
2371
|
<title>NeuroLink API Documentation</title>
|