@juspay/neurolink 9.68.20 → 9.69.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/browser/neurolink.min.js +1 -1
- package/dist/lib/providers/deepseek.d.ts +6 -6
- package/dist/lib/providers/deepseek.js +6 -6
- package/dist/lib/providers/nvidiaNim.d.ts +3 -1
- package/dist/lib/providers/nvidiaNim.js +3 -1
- package/dist/lib/providers/openaiChatCompletionsBase.js +18 -2
- package/dist/lib/providers/openaiChatCompletionsClient.d.ts +1 -1
- package/dist/lib/providers/openaiChatCompletionsClient.js +10 -1
- package/dist/lib/types/openaiCompatible.d.ts +7 -0
- package/dist/lib/types/stream.d.ts +1 -0
- package/dist/providers/deepseek.d.ts +6 -6
- package/dist/providers/deepseek.js +6 -6
- package/dist/providers/nvidiaNim.d.ts +3 -1
- package/dist/providers/nvidiaNim.js +3 -1
- package/dist/providers/openaiChatCompletionsBase.js +18 -2
- package/dist/providers/openaiChatCompletionsClient.d.ts +1 -1
- package/dist/providers/openaiChatCompletionsClient.js +10 -1
- package/dist/types/openaiCompatible.d.ts +7 -0
- package/dist/types/stream.d.ts +1 -0
- package/package.json +2 -4
|
@@ -1156,7 +1156,7 @@ ${r.envVarName}=your_key_here
|
|
|
1156
1156
|
|
|
1157
1157
|
\u{1F527} Step 3: Restart Application
|
|
1158
1158
|
Restart your application to load the new environment variables.`}function tr(r,e){return process.env[r]||e}function QMe(){let r=XJt(),e=ZJt(),t=["\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=r==="oauth"?[...n.slice(1),"",...t]:[...t,...n];return{providerName:"Anthropic",envVarName:r==="oauth"?"ANTHROPIC_OAUTH_TOKEN":"ANTHROPIC_API_KEY",setupUrl:r==="oauth"?"https://claude.ai/settings":"https://console.anthropic.com/",description:r==="oauth"?`Anthropic OAuth Token (${e} tier)`:"Anthropic API Key",instructions:o,fallbackEnvVars:r==="oauth"?["ANTHROPIC_API_KEY"]:["ANTHROPIC_OAUTH_TOKEN","CLAUDE_OAUTH_TOKEN","ANTHROPIC_OAUTH_ACCESS_TOKEN"]}}function eOe(){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 tOe(){return{providerName:"HuggingFace",envVarName:"HUGGINGFACE_API_KEY",setupUrl:"https://huggingface.co/settings/tokens",description:"Credentials",instructions:["1. Visit: https://huggingface.co/settings/tokens","2. Create new API token","3. Copy the token"],fallbackEnvVars:["HF_TOKEN"]}}function rOe(){return{providerName:"Mistral",envVarName:"MISTRAL_API_KEY",setupUrl:"https://console.mistral.ai/",description:"API key",instructions:["1. Visit: https://console.mistral.ai/","2. Create or sign in to your account","3. Generate a new API key"]}}function nOe(){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 oOe(){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 sOe(){return{providerName:"DeepSeek",envVarName:"DEEPSEEK_API_KEY",setupUrl:"https://platform.deepseek.com/api_keys",description:"API key",instructions:["1. Visit: https://platform.deepseek.com/api_keys","2. Create or sign in to your DeepSeek account","3. Generate a new API key","4. Set DEEPSEEK_API_KEY in your .env file"]}}function iOe(){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 aOe(){return{providerName:"xAI",envVarName:"XAI_API_KEY",setupUrl:"https://console.x.ai/",description:"API key",instructions:["1. Visit: https://console.x.ai/","2. Sign in with your xAI account","3. Create an API key","4. Set XAI_API_KEY in your .env file"]}}function cOe(){return{providerName:"Groq",envVarName:"GROQ_API_KEY",setupUrl:"https://console.groq.com/keys",description:"API key",instructions:["1. Visit: https://console.groq.com/keys","2. Sign in to your Groq account","3. Create a new API key","4. Set GROQ_API_KEY in your .env file"]}}function lOe(){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 uOe(){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 dOe(){return{providerName:"Together AI",envVarName:"TOGETHER_API_KEY",setupUrl:"https://api.together.xyz/settings/api-keys",description:"API key",instructions:["1. Visit: https://api.together.xyz/settings/api-keys","2. Sign in to your Together AI account","3. Create a new API key","4. Set TOGETHER_API_KEY in your .env file"]}}function pOe(){return{providerName:"Fireworks AI",envVarName:"FIREWORKS_API_KEY",setupUrl:"https://fireworks.ai/account/api-keys",description:"API key",instructions:["1. Visit: https://fireworks.ai/account/api-keys","2. Sign in to your Fireworks AI account","3. Create a new API key","4. Set FIREWORKS_API_KEY in your .env file"]}}function mOe(){return{providerName:"Perplexity",envVarName:"PERPLEXITY_API_KEY",setupUrl:"https://www.perplexity.ai/settings/api",description:"API key",instructions:["1. Visit: https://www.perplexity.ai/settings/api","2. Sign in to your Perplexity account","3. Create a new API key (Sonar tier)","4. Set PERPLEXITY_API_KEY in your .env file"]}}function fOe(){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 gOe(){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 hOe(){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 yOe(){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 xOe(){return{providerName:"Cloudflare Workers AI",envVarName:"CLOUDFLARE_API_KEY",setupUrl:"https://dash.cloudflare.com/profile/api-tokens",description:"API token (Workers AI Read+Write scope)",instructions:["1. Visit: https://dash.cloudflare.com/profile/api-tokens","2. Create a token with 'Workers AI: Read + Write' scope","3. Set CLOUDFLARE_API_KEY in your .env file","4. Also set CLOUDFLARE_ACCOUNT_ID (find it in the dashboard URL or under 'Account ID')"]}}function vOe(){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 bOe(){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 XJt(){return process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase()==="oauth"?"oauth":"api_key"}function ZJt(){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"}}var Nv,Wl,OG,Nn=E(()=>{"use strict";Nv={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}$/},Wl={OPENAI_MIN:48,ANTHROPIC_MIN:95,HUGGINGFACE_EXACT:37,AZURE_MIN:32,MISTRAL_EXACT:32,AWS_ACCESS_KEY:20,GOOGLE_AI_EXACT:39},OG={MIN_LENGTH:6,MAX_LENGTH:30,PATTERN:/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/}});async function ca(r,e,t){let n=parseInt(r.headers.get("content-length")??"0",10);if(n>0&&n>e)throw new Error(`${t} download too large: ${n} bytes (max ${e})`);let o=Buffer.from(await r.arrayBuffer());if(o.length>e)throw new Error(`${t} download exceeded size cap after fetch: ${o.length} bytes (max ${e})`);return o}var ff=E(()=>{"use strict"});var ewn,twn,rwn,nwn,Yee,YJt,TOe,NG,own,swn,awn,cwn,SOe=E(()=>{ewn=globalThis.crypto,twn=globalThis.ReadableStream||class{},rwn=globalThis.URL,nwn=globalThis.URLSearchParams,Yee=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Yee.custom=Symbol.for("nodejs.util.inspect.custom");Yee.colors={};Yee.styles={};YJt=globalThis.TextDecoder,TOe=globalThis.TextEncoder,NG=(r,e)=>e?.(null,"127.0.0.1",4),own=globalThis.performance||{now:()=>Date.now()},swn=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new TOe().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new TOe().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new YJt().decode(this)}},awn=globalThis.clearTimeout,cwn=globalThis.clearInterval});var dwn,pwn,mwn,fwn,Qee,QJt,wOe,gwn,hwn,EOe,xwn,vwn,_Oe=E(()=>{dwn=globalThis.crypto,pwn=globalThis.ReadableStream||class{},mwn=globalThis.URL,fwn=globalThis.URLSearchParams,Qee=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Qee.custom=Symbol.for("nodejs.util.inspect.custom");Qee.colors={};Qee.styles={};QJt=globalThis.TextDecoder,wOe=globalThis.TextEncoder,gwn=globalThis.performance||{now:()=>Date.now()},hwn=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new wOe().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new wOe().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new QJt().decode(this)}},EOe=()=>0,xwn=globalThis.clearTimeout,vwn=globalThis.clearInterval});function r9t(r){return r.length===0?null:/^0x[0-9a-f]+$/i.test(r)?parseInt(r.slice(2),16):r.length>1&&r.startsWith("0")&&/^0[0-7]+$/.test(r)?parseInt(r.slice(1),8):/^\d+$/.test(r)?parseInt(r,10):null}function DG(r){if(r.length===0)return null;let e=r.split(".");if(e.length===4){let t=e.map(r9t);return t.some(n=>n===null||n<0||n>255)?null:t.join(".")}if(e.length===1){let t;if(/^0x[0-9a-f]+$/i.test(r))t=parseInt(r.slice(2),16);else if(/^\d+$/.test(r))t=parseInt(r,10);else return null;return Number.isNaN(t)||t<0||t>4294967295?null:[t>>>24&255,t>>>16&255,t>>>8&255,t&255].join(".")}return null}function ROe(r){if(EOe(r)!==6)return null;let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i),t;if(e){let n=DG(e[1]);if(!n)return null;let o=n.split(".").map(a=>parseInt(a,10)),s=(o[0]<<8|o[1]).toString(16),i=(o[2]<<8|o[3]).toString(16);t=["0","0","0","0","0","ffff",s,i]}else{let[n,o=""]=r.split("::"),s=n?n.split(":"):[],i=o?o.split(":"):[],a=8-s.length-i.length;if(a<0)return null;t=[...s,...Array(a).fill("0"),...i]}return t.length!==8?null:t.map(n=>n.toLowerCase().padStart(4,"0")).join(":")}function AOe(r){let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(e)return DG(e[1]);let t=r.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(t){let n=parseInt(t[1],16),o=parseInt(t[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 COe(r){let[e,t,n,o]=r.split(".").map(s=>parseInt(s,10));return(e<<24|t<<16|n<<8|o)>>>0}function aP(r){let e=COe(r);for(let[t,n]of e9t){let o=COe(t),s=n===0?0:4294967295<<32-n>>>0;if((e&s)===(o&s))return!0}return!1}function IOe(r){return t9t.some(e=>e.length===39?r===e:r.startsWith(e))}function POe(r){return r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r}function kOe(r){let e=DG(r);if(e)return aP(e)?`IPv4 ${r} \u2192 ${e} is in a blocked range`:null;if(r.includes(":")){let t=AOe(r);if(t)return aP(t)?`IPv4-mapped IPv6 ${r} \u2192 ${t} is in a blocked range`:null;let n=ROe(r);return n?IOe(n)?`IPv6 ${r} is in a blocked range`:null:`IPv6 ${r} could not be parsed`}return"not-an-ip"}async function ol(r){let e;try{e=new URL(r)}catch{throw new Error(`Invalid URL: "${r}"`)}if(e.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${e.protocol}//" in "${r}"`);let t=POe(e.hostname).toLowerCase(),n=kOe(t);if(n===null)return;if(n!=="not-an-ip")throw new Error(`URL "${r}" rejected: ${n}`);let[o,s]=await Promise.allSettled([NG(t,{family:4,all:!0}),NG(t,{family:6,all:!0})]),i=[],a=[],c=!1;if(o.status==="fulfilled"){c=!0;for(let l of o.value)i.push(l.address)}if(s.status==="fulfilled"){c=!0;for(let l of s.value)a.push(l.address)}if(!c){let l=o.status==="rejected"?o.reason instanceof Error?o.reason.message:String(o.reason):"ok",u=s.status==="rejected"?s.reason instanceof Error?s.reason.message:String(s.reason):"ok";throw new Error(`URL "${r}" rejected: hostname ${t} could not be resolved (A: ${l}; AAAA: ${u})`)}for(let l of i)if(aP(l))throw new Error(`URL "${r}" rejected: hostname ${t} resolves to ${l} (IPv4 in blocked range)`);for(let l of a){let u=kOe(l.toLowerCase());if(u&&u!=="not-an-ip")throw new Error(`URL "${r}" rejected: hostname ${t} resolves to ${l} (IPv6 ${u})`)}}async function MOe(r){let e;try{e=new URL(r)}catch{throw new Error(`Invalid URL: "${r}"`)}if(e.protocol!=="https:")throw new Error(`Only HTTPS URLs are permitted; got "${e.protocol}//" in "${r}"`);let t=POe(e.hostname).toLowerCase(),n=DG(t);if(n){if(aP(n))throw new Error(`URL "${r}" rejected: IPv4 ${t} \u2192 ${n} is in a blocked range`);return{url:r,ip:n,family:4}}if(t.includes(":")){let s=AOe(t);if(s){if(aP(s))throw new Error(`URL "${r}" rejected: IPv4-mapped IPv6 ${t} \u2192 ${s} is in a blocked range`);return{url:r,ip:s,family:4}}let i=ROe(t);if(!i)throw new Error(`URL "${r}" rejected: IPv6 ${t} could not be parsed`);if(IOe(i))throw new Error(`URL "${r}" rejected: IPv6 ${t} is in a blocked range`);return{url:r,ip:t,family:6}}await ol(r);let o=await NG(t);return{url:r,ip:o.address,family:o.family}}var e9t,t9t,qh=E(()=>{"use strict";SOe();_Oe();e9t=[["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]],t9t=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]});var Ci,Dv,n9t,ete,o9t,s9t,tte,OOe,NOe,DOe,LOe,UOe,i9t,rte,FOe,nte,$Oe,ote,BOe,zOe,GOe,Wh=E(()=>{"use strict";cU();wp();Ci=r=>r.replace(/\/+$/,""),Dv=r=>{try{return JSON.stringify(r??"")}catch{return String(r??"")}},n9t=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r??{})}catch{return"{}"}},ete=r=>{if(r==null)return"";if(typeof r=="string")return r;if(typeof r!="object")return String(r);let e=r;switch(e.type){case"text":return typeof e.value=="string"?e.value:Dv(e.value);case"json":return Dv(e.value);case"execution-denied":return`Tool execution denied${e.reason?`: ${e.reason}`:""}`;case"error-text":return typeof e.value=="string"?e.value:Dv(e.value);case"error-json":return Dv(e.value);case"content":return Array.isArray(e.value)?e.value.map(t=>t&&typeof t=="object"&&t.type==="text"?String(t.text??""):"").filter(t=>t.length>0).join(`
|
|
1159
|
-
`):"";default:return Dv(r)}},o9t=r=>{if(typeof r=="string")return r.startsWith("data:")||/^https?:\/\//i.test(r)?r:`data:image/png;base64,${r}`;if(r instanceof URL)return r.toString();if(r instanceof Uint8Array)return`data:image/png;base64,${Buffer.from(r).toString("base64")}`},s9t=r=>{if(typeof r=="string")return r;if(!Array.isArray(r))return Dv(r);let e=[];for(let t of r){if(typeof t=="string"){e.push({type:"text",text:t});continue}if(!t||typeof t!="object")continue;let n=t;if(n.type==="text")e.push({type:"text",text:t.text??""});else if(n.type==="image"||n.type==="image_url"){let o=t.image??t.data??t.url,s=o9t(o);s&&e.push({type:"image_url",image_url:{url:s}})}}return e.length===1&&e[0].type==="text"?e[0].text:e},tte=r=>{let e=[];for(let t of r)switch(t.role){case"system":e.push({role:"system",content:typeof t.content=="string"?t.content:Dv(t.content)});break;case"user":e.push({role:"user",content:s9t(t.content)});break;case"assistant":{let n=Array.isArray(t.content)?t.content:[t.content],o=[],s=[];for(let a of n)if(a&&typeof a=="object"){let c=a;if(c.type==="text")o.push({type:"text",text:a.text??""});else if(c.type==="tool-call"){let l=a;s.push({id:l.toolCallId??"",type:"function",function:{name:l.toolName??"",arguments:n9t(l.input)}})}}else typeof a=="string"&&o.push({type:"text",text:a});let i=o.length===0?null:o.length===1&&o[0].type==="text"?o[0].text:o;e.push({role:"assistant",content:i,...s.length>0?{tool_calls:s}:{}});break}case"tool":{if(Array.isArray(t.content))for(let n of t.content){if(!n||typeof n!="object")continue;let o=n;o.type==="tool-result"&&e.push({role:"tool",tool_call_id:o.toolCallId??"",content:ete(o.output)})}else typeof t.content=="string"&&e.push({role:"tool",tool_call_id:t.toolCallId??"",content:t.content});break}}return e},OOe=r=>{let e=Object.entries(r);if(e.length===0)return;let t=[];for(let[n,o]of e){let s=o,i=s.inputSchema??s.parameters,a=i?si(i):{type:"object",properties:{}};t.push({type:"function",function:{name:n,...s.description?{description:s.description}:{},parameters:a}})}return t},NOe=r=>{if(!r||r.length===0)return;let e=[];for(let t of r)t.type==="function"&&e.push({type:"function",function:{name:t.name,...t.description?{description:t.description}:{},parameters:t.inputSchema,...t.strict!==void 0?{strict:t.strict}:{}}});return e.length>0?e:void 0},DOe=r=>{switch(r.type){case"auto":case"none":case"required":return r.type;case"tool":return{type:"function",function:{name:r.toolName}}}},LOe=r=>r.type==="text"?{type:"text"}:r.schema?{type:"json_schema",json_schema:{name:r.name??"response",schema:r.schema,...r.description?{description:r.description}:{},strict:!0}}:{type:"json_object"},UOe=r=>{if(r){if(r==="auto"||r==="none"||r==="required")return r;if(typeof r=="object"&&r!==null){let e=r;if(e.type==="tool"&&e.toolName)return{type:"function",function:{name:e.toolName}}}}},i9t=r=>r.some(e=>{let t=e.content;return typeof t=="string"?/\bjson\b/i.test(t):Array.isArray(t)?t.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),rte=r=>r.response_format?.type==="json_object"&&!i9t(r.messages)?{...r,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...r.messages]}:r,FOe=r=>/^(o\d|gpt-5)/i.test(r.replace(/^.*\//,"")),nte=r=>{let{modelId:e,messages:t,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=r,c={model:e,messages:t,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};return n.maxTokens!==void 0&&n.maxTokens!==null&&(c.max_tokens=n.maxTokens),n.temperature!==void 0&&n.temperature!==null&&(c.temperature=n.temperature),n.topP!==void 0&&n.topP!==null&&(c.top_p=n.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(c.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(c.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(c.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(c.stop=n.stopSequences),o&&(c.tools=o),s!==void 0&&(c.tool_choice=s),a&&(c.response_format=a),c},$Oe=async(r,e)=>{let t={text:"",toolCalls:new Map,finishReason:null,usage:void 0},n=new TextDecoder,o,i=sS({onEvent:c=>{let l=c.data;if(!l||l==="[DONE]")return;let u;try{u=JSON.parse(l)}catch(f){o=f instanceof Error?f:new Error(String(f));return}u.usage&&(t.usage=u.usage);let d=u.choices?.[0];if(!d)return;let m=d.delta;if(m?.content&&(t.text+=m.content,e(m.content)),m?.tool_calls)for(let f of m.tool_calls){let h=t.toolCalls.get(f.index);h?f.id&&(h.id=f.id):(h={id:f.id??`call_${f.index}_${Date.now()}`,name:f.function?.name??"",argsBuffered:""},t.toolCalls.set(f.index,h)),f.function?.name&&(h.name=f.function.name),f.function?.arguments&&(h.argsBuffered+=f.function.arguments)}d.finish_reason&&(t.finishReason=d.finish_reason)}}),a=r.getReader();try{for(;;){let{done:c,value:l}=await a.read();if(c)break;i.feed(n.decode(l,{stream:!0}))}i.feed(n.decode())}finally{a.releaseLock()}if(o)throw o;return t},ote=async(r,e,t)=>{let n,o;try{n=await t.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}let s=o?.error?.message??`OpenAI-compatible request failed with status ${t.status}`,i=new Error(s);return i.statusCode=t.status,i.url=r,i.requestBody={model:e.model,stream:e.stream===!0,tool_count:e.tools?.length??0},n!==void 0&&(i.responseBody=n),i},BOe=()=>{let r=()=>{},e=new Promise(o=>{r=o}),t=()=>{},n=new Promise(o=>{t=o});return{usagePromise:e,finishPromise:n,resolveUsage:r,resolveFinish:t}},zOe=()=>{let r=[],e;return{pushChunk:o=>{if(e){let s=e;e=void 0,s(o)}else r.push(o)},nextChunk:()=>new Promise(o=>{r.length>0?o(r.shift()):e=o})}},GOe=(r,e)=>r?e?{prompt_tokens:(r.prompt_tokens??0)+(e.prompt_tokens??0),completion_tokens:(r.completion_tokens??0)+(e.completion_tokens??0),total_tokens:(r.total_tokens??0)+(e.total_tokens??0)}:r:e});var ste,jOe,VOe=E(()=>{"use strict";zI();V();b2();jm();ste=class{async collectUsage(e){try{let t=await e.usage;return t?QS(t):(g.debug("No usage data available from stream result"),aY())}catch(t){return Nc.isInstance(t)?g.debug("No output generated from stream \u2014 returning empty usage"):g.warn("Failed to collect usage from stream result",{error:t}),aY()}}async collectMetadata(e){try{let[t,n]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:n}}catch(t){return Nc.isInstance(t)?g.debug("No output generated from stream \u2014 returning default metadata"):g.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,n,o,s){try{let[i,a]=await Promise.all([this.collectUsage(n),this.collectMetadata(n)]),[c,l,u,d]=await Promise.all([Promise.resolve(n.text).catch(()=>""),Promise.resolve(n.finishReason).catch(()=>"error"),Promise.resolve(n.toolResults||[]).catch(()=>[]),Promise.resolve(n.toolCalls||[]).catch(()=>[])]);return Fh(e,t,{usage:i,content:c,response:a,finishReason:l,toolResults:u,toolCalls:d},o,{...s,streamingMode:!0,responseId:a.id,finishReason:l})}catch(i){return g.error("Failed to create analytics from stream result",{provider:e,model:t,error:i instanceof Error?i.message:String(i)}),Fh(e,t,{usage:{input:0,output:0,total:0}},o,{...s,streamingMode:!0,analyticsError:!0})}}cleanup(){let e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},jOe=new ste});function LG(r,e,t){return!t||!e||Object.keys(e).length===0?"none":r.toolChoice??"auto"}var ite=E(()=>{"use strict"});var ar,ys=E(()=>{"use strict";ql();oi();VOe();Vn();V();jm();gee();Rn();yA();ite();eh();Wh();ar=class extends Mn{config;resolvedModel;constructor(e,t,n,o){super(t,e,n),this.config=o}getFallbackModelName(){return"gpt-3.5-turbo"}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}adjustRequestBody(e,t){return e}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ci(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}supportsTools(){return!0}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){let e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;let e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{let n=await this.getAvailableModels();if(n.length>0)return this.resolvedModel=n[0],this.refreshHandlersForModel(n[0]),g.info(`\u{1F50D} Auto-discovered model: ${n[0]} from ${n.length} available models`),n[0]}catch(n){g.warn("Model auto-discovery failed, using fallback:",n)}return this.getFallbackModelName()}let t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){let t=this.getChatCompletionsURL(e),n=Ze(),o=this.getAuthHeaders.bind(this),s=this.providerName,i=this.adjustBuildBodyOptions.bind(this),a=this.adjustResponseFormat.bind(this),c=this.adjustRequestBody.bind(this),l=u=>this.getTimeout(u??{});return{specificationVersion:"v3",provider:s,modelId:e,supportedUrls:{},doGenerate:async u=>{let d=tte(u.prompt),m=u.responseFormat?a(LOe(u.responseFormat),e):void 0,f=rte(c(nte({modelId:e,messages:d,options:i(e,{maxTokens:u.maxOutputTokens,temperature:u.temperature,topP:u.topP,presencePenalty:u.presencePenalty,frequencyPenalty:u.frequencyPenalty,seed:u.seed,stopSequences:u.stopSequences}),tools:NOe(u.tools),...u.toolChoice?{toolChoice:DOe(u.toolChoice)}:{},streaming:!1,...m?{responseFormat:m}:{}}),e)),h=Is(l(u),s,"generate"),y=Fm(u.abortSignal,h?.controller.signal),x;try{x=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(f),...y?{signal:y}:{}})}finally{h?.cleanup()}if(!x.ok)throw await ote(t,f,x);let b=await x.json(),S=b.choices?.[0],w=(typeof S?.message?.content=="string"?S.message.content:"")??"",_=[];w.length>0&&_.push({type:"text",text:w});for(let I of S?.message?.tool_calls??[])_.push({type:"tool-call",toolCallId:I.id,toolName:I.function.name,input:I.function.arguments??""});let C=S?.finish_reason;return{content:_,finishReason:{unified:C==="length"?"length":C==="tool_calls"||C==="function_call"?"tool-calls":C==="content_filter"?"content-filter":"stop",raw:C??"stop"},usage:{inputTokens:{total:b.usage?.prompt_tokens,noCache:b.usage?.prompt_tokens,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:b.usage?.completion_tokens,text:b.usage?.completion_tokens,reasoning:void 0}},warnings:[],request:{body:f},response:{...b.id?{id:b.id}:{},...b.model?{modelId:b.model}:{},headers:{},body:b}}},doStream:()=>{throw new Error(`${s}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}async executeStream(e,t){this.validateStreamOptions(e);let n=Date.now(),o=this.getTimeout(e),s=Is(o,this.providerName,"stream"),i=new AbortController,a=l_e([e.abortSignal,s?.controller.signal,i.signal]).signal,c,l,u,d,m;try{c=await this.resolveModelName();let $=!e.disableTools&&this.supportsTools();l=$?e.tools||await this.getAllTools():{},u=$?OOe(l):void 0,d=UOe(LG(e,l,$));let L=await this.buildMessagesForStream(e);m=tte(L)}catch($){throw s?.cleanup(),$}let f=this.getChatCompletionsURL(c),h=Ze(),y=e.maxSteps||Vo,x=this.neurolink?.getEventEmitter(),b=[],S=[],{usagePromise:w,finishPromise:_,resolveUsage:C,resolveFinish:k}=BOe(),{pushChunk:I,nextChunk:R}=zOe(),A=this.onStreamStart(c),M=this.runStreamLoop({maxSteps:y,modelId:c,url:f,fetchImpl:h,abortSignal:a,options:e,conversation:m,openAITools:u,openAIToolChoice:d,toolsRecord:l,emitter:x,toolsUsed:b,toolExecutionSummaries:S,pushChunk:I,resolveUsage:C,resolveFinish:k}),D,B=$=>{D=$};A?.onUsage&&w.then(A.onUsage).catch(()=>{}),A?.onFinish&&_.then($=>A.onFinish?.($,D)).catch(()=>{});let O=this.providerName,N={stream:async function*(){let $=0;try{for(;;){let L=await R();if("done"in L)break;"content"in L&&typeof L.content=="string"&&L.content.length>0&&$++,yield L}if(await M,$===0&&b.length===0){g.warn(`${O}: Stream produced no output \u2014 emitting enriched sentinel`);let L=new Nc({message:"Stream produced no output"}),z=await kv(L,void 0,D);Rv(z),yield z}}catch(L){if(Nc.isInstance(L)){let F=await kv(L,void 0,D);Rv(F),yield F;return}let z=await kv(L,void 0,D);throw Rv(z),yield z,L}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:c,analytics:jOe.createAnalytics(this.providerName,c,{textStream:(async function*(){})(),usage:w,finishReason:_},Date.now()-n,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:b,metadata:{startTime:n,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(N,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Eu(S.map($=>({toolName:$.toolName,input:$.input,output:$.output,duration:$.endTime.getTime()-$.startTime.getTime()})))}),M.finally(()=>s?.cleanup()).catch($=>{B($)}),N}async runStreamLoop(e){let{maxSteps:t,modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:c,openAITools:l,openAIToolChoice:u,toolsRecord:d,emitter:m,toolsUsed:f,toolExecutionSummaries:h,pushChunk:y,resolveUsage:x,resolveFinish:b}=e;try{let S=null,w;for(let _=0;_<t;_++){let C=await this.streamOneStep({modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:c,openAITools:l,openAIToolChoice:u,pushChunk:y});if(S=C.finishReason,C.usage&&(w=GOe(w,C.usage)),C.toolCalls.size===0)break;await this.executeToolBatch({stepResult:C,conversation:c,toolsRecord:d,emitter:m,toolsUsed:f,toolExecutionSummaries:h,options:a})}return x({promptTokens:w?.prompt_tokens??0,completionTokens:w?.completion_tokens??0,totalTokens:w?.total_tokens??0}),b(S??"stop"),y({done:!0}),{finishReason:S??"stop",usage:w}}catch(S){throw g.error(`${this.providerName}: Stream error`,{error:S instanceof Error?S.message:String(S)}),x({promptTokens:0,completionTokens:0,totalTokens:0}),b("error"),y({done:!0}),S}}async streamOneStep(e){let t=rte(this.adjustRequestBody(nte({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,e.options),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),n=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(t),...e.abortSignal?{signal:e.abortSignal}:{}});if(!n.ok)throw await ote(e.url,t,n);if(!n.body)throw new Error(`${this.providerName}: stream response had no body`);return $Oe(n.body,o=>{e.pushChunk({content:o})})}async executeToolBatch(e){let{stepResult:t,conversation:n,toolsRecord:o,emitter:s,toolsUsed:i,toolExecutionSummaries:a,options:c}=e,l=[];for(let[,d]of t.toolCalls)l.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});n.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:l});for(let[,d]of t.toolCalls){let m=new Date,f;try{f=JSON.parse(d.argsBuffered||"{}")}catch{f=d.argsBuffered}let h,y,x=o[d.name];if(s?.emit("tool:start",{toolName:d.name,toolCallId:d.id,input:f}),!x||typeof x.execute!="function")y=`Tool '${d.name}' is not registered.`,h={error:y};else try{h=await x.execute(f,{})}catch(S){y=S instanceof Error?S.message:String(S),h={error:y}}let b=new Date;i.push(d.name),a.push({toolCallId:d.id,toolName:d.name,input:f,output:h,...y?{error:y}:{},startTime:m,endTime:b}),n.push({role:"tool",tool_call_id:d.id,content:ete(h)})}let u=a.slice(-t.toolCalls.size);sh(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){g.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{let e=`${Ci(this.config.baseURL)}/models`;g.debug(`Fetching available models from: ${e}`);let t=Ze(),n=new AbortController,o=setTimeout(()=>n.abort(),5e3),s=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:n.signal});if(clearTimeout(o),!s.ok)return g.warn(`Models endpoint returned ${s.status}: ${s.statusText}`),this.getFallbackModels();let i=await s.json();if(!i.data||!Array.isArray(i.data))return g.warn("Invalid models response format"),this.getFallbackModels();let a=i.data.map(c=>c.id).filter(Boolean);return g.shouldLog("debug")&&g.debug(`Discovered ${a.length} models:`,a),a.length>0?a:this.getFallbackModels()}catch(e){return g.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}});var qOe={};K(qOe,{OpenAIProvider:()=>ate});var HOe,a9t,c9t,l9t,u9t,ate,WOe=E(()=>{"use strict";hr();Vn();mt();V();On();Ed();Nn();ff();qh();Rn();Wh();ys();HOe="https://api.openai.com/v1",a9t=(r,e)=>{let t=[r,e].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??HOe;try{let n=new URL(t),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ci(n.toString())}catch{}return t},c9t=()=>er(eOe()),l9t=()=>tr("OPENAI_MODEL","gpt-4o"),u9t=it.getTracer("neurolink.provider.openai"),ate=class extends ar{constructor(e,t,n,o){let s=o?.apiKey?.trim(),i=s&&s.length>0?s:c9t(),a=a9t(o?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:a,apiKey:i}),g.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Qt(this.config.baseURL)})}getProviderName(){return"openai"}getDefaultModel(){return l9t()}formatProviderError(e){if(e instanceof At)return new ht(e.message,this.providerName);let t=e,n=t?.message&&typeof t.message=="string"?t.message:"Unknown error",o=t?.type&&typeof t.type=="string"?t.type:void 0,s=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return n.includes("API_KEY_INVALID")||n.includes("Invalid API key")||n.includes("Incorrect API key")||n.includes("invalid_api_key")||o==="invalid_api_key"||s===401?new ut(n.includes("Incorrect API key")||n.includes("Invalid API key")?n:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable.",this.providerName):n.includes("rate limit")||o==="rate_limit_error"||s===429?new Rt("OpenAI rate limit exceeded. Please try again later.",this.providerName):n.includes("model_not_found")?new Ct(`Model not found: ${this.modelName}`,this.providerName):new Te(`OpenAI error: ${n}`,this.providerName)}onStreamStart(e){let t=u9t.startSpan("neurolink.provider.streamText",{kind:gr.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}}),n=!1,o=()=>{n||(n=!0,t.end())};return{onUsage:s=>{t.setAttribute("gen_ai.usage.input_tokens",s.promptTokens),t.setAttribute("gen_ai.usage.output_tokens",s.completionTokens);let i=ko(this.providerName,this.modelName,{input:s.promptTokens,output:s.completionTokens,total:s.totalTokens});i&&i>0&&t.setAttribute("neurolink.cost",i)},onFinish:(s,i)=>{t.setAttribute("gen_ai.response.finish_reason",s||"unknown"),s==="error"&&t.setStatus({code:me.ERROR,message:i instanceof Error?i.message:String(i??"stream error")}),o()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let[o]=await this.callEmbeddings(n,[e],"embed");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await this.callEmbeddings(n,e,"embedMany");return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}async callEmbeddings(e,t,n){let o=`${Ci(this.config.baseURL)}/embeddings`,s=Ze(),i=Is(3e4,this.providerName,"generate");try{let a=await s(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!a.ok){let u=await a.text().catch(()=>""),d=`OpenAI ${n} failed with status ${a.status}`,m;if(u)try{let f=JSON.parse(u);f.error?.message&&(d=f.error.message),m=f.error?.type}catch{}throw Object.assign(new Error(d),{status:a.status,type:m})}let l=((await a.json()).data??[]).map(u=>u.embedding).filter(u=>Array.isArray(u));if(l.length===0)throw new Te(`OpenAI ${n} returned no embeddings`,this.providerName);return l}finally{i?.cleanup()}}async executeImageGeneration(e){let t=Date.now(),n=e.prompt??e.input?.text??"";if(!n.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");let o=e.model??this.modelName,s=Ci(this.config.baseURL??HOe),i=e,a=i.size??this.aspectRatioToOpenAISize(i.aspectRatio,o),c=i.numberOfImages??1,l;o==="gpt-image-1"||o.startsWith("dall-e-3")?l=1:o.startsWith("dall-e-2")?l=Math.min(Math.max(c,1),10):l=1;let d={model:o,prompt:n,n:l,size:a};o==="gpt-image-1"?i.quality&&(d.quality=i.quality):o.startsWith("dall-e-3")?(d.response_format="b64_json",i.quality&&(d.quality=i.quality),i.style&&(d.style=i.style)):d.response_format="b64_json";let m=12e4,f=new AbortController,h=setTimeout(()=>f.abort(),m),y;try{y=await Ze()(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:f.signal})}catch(_){throw _ instanceof Error&&_.name==="AbortError"?new Error(`OpenAI image generation timed out after ${m/1e3}s`,{cause:_}):_}finally{clearTimeout(h)}if(!y.ok){let _=await y.text();throw new Error(`OpenAI image generation failed: ${y.status} \u2014 ${_}`)}let b=(await y.json()).data?.[0];if(!b)throw new Error("OpenAI image generation returned no images");let S=b.b64_json;if(!S&&b.url){await ol(b.url);let _=Ze(),C=new AbortController,k=setTimeout(()=>C.abort(),6e4),I;try{I=await _(b.url,{signal:C.signal})}catch(A){throw A instanceof Error&&A.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:A}):A}finally{clearTimeout(k)}if(!I.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${b.url} (${I.status})`);S=(await ca(I,26214400,"OpenAI image fallback")).toString("base64")}if(!S)throw new Error("OpenAI image generation returned neither b64_json nor a URL");let w=Date.now()-t;return g.info(`[OpenAIProvider] Generated image (${S.length} base64 chars) in ${w}ms \u2014 model ${o}`),{content:b.revised_prompt??n,provider:this.providerName,model:o,usage:{input:0,output:0,total:0},imageOutput:{base64:S}}}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"}}});function h9t(r){var e;let t=r?.anthropic;return(e=t?.cacheControl)!=null?e:t?.cache_control}async function $9t({tools:r,toolChoice:e,disableParallelToolUse:t,cacheControlValidator:n,supportsStructuredOutput:o,supportsStrictTools:s}){var i;r=r?.length?r:void 0;let a=[],c=new Set,l=n||new dte;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a,betas:c};let u=[];for(let m of r)switch(m.type){case"function":{let f=l.getCacheControl(m.providerOptions,{type:"tool definition",canCache:!0}),h=(i=m.providerOptions)==null?void 0:i.anthropic,y=h?.eagerInputStreaming,x=h?.deferLoading,b=h?.allowedCallers;!s&&m.strict!=null&&a.push({type:"unsupported",feature:"strict",details:`Tool '${m.name}' has strict: ${m.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),u.push({name:m.name,description:m.description,input_schema:m.inputSchema,cache_control:f,...y?{eager_input_streaming:!0}:{},...s===!0&&m.strict!=null?{strict:m.strict}:{},...x!=null?{defer_loading:x}:{},...b!=null?{allowed_callers:b}:{},...m.inputExamples!=null?{input_examples:m.inputExamples.map(S=>S.input)}:{}}),o===!0&&c.add("structured-outputs-2025-11-13"),(m.inputExamples!=null||b!=null)&&c.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(m.id){case"anthropic.code_execution_20250522":{c.add("code-execution-2025-05-22"),u.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{c.add("code-execution-2025-08-25"),u.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{u.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{c.add("computer-use-2025-01-24"),u.push({name:"computer",type:"computer_20250124",display_width_px:m.args.displayWidthPx,display_height_px:m.args.displayHeightPx,display_number:m.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{c.add("computer-use-2025-11-24"),u.push({name:"computer",type:"computer_20251124",display_width_px:m.args.displayWidthPx,display_height_px:m.args.displayHeightPx,display_number:m.args.displayNumber,enable_zoom:m.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{c.add("computer-use-2024-10-22"),u.push({name:"computer",type:"computer_20241022",display_width_px:m.args.displayWidthPx,display_height_px:m.args.displayHeightPx,display_number:m.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{c.add("computer-use-2025-01-24"),u.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{c.add("computer-use-2024-10-22"),u.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{c.add("computer-use-2025-01-24"),u.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let f=await ur({value:m.args,schema:y9t});u.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:f.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{c.add("computer-use-2025-01-24"),u.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{c.add("computer-use-2024-10-22"),u.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{c.add("context-management-2025-06-27"),u.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{c.add("web-fetch-2025-09-10");let f=await ur({value:m.args,schema:D9t});u.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,citations:f.citations,max_content_tokens:f.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{c.add("code-execution-web-tools-2026-02-09");let f=await ur({value:m.args,schema:I9t});u.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,citations:f.citations,max_content_tokens:f.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let f=await ur({value:m.args,schema:C9t});u.push({type:"web_search_20250305",name:"web_search",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,user_location:f.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{c.add("code-execution-web-tools-2026-02-09");let f=await ur({value:m.args,schema:T9t});u.push({type:"web_search_20260209",name:"web_search",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,user_location:f.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{u.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{u.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{a.push({type:"unsupported",feature:`provider-defined tool ${m.id}`});break}}break}default:{a.push({type:"unsupported",feature:`tool ${m}`});break}}if(e==null)return{tools:u,toolChoice:t?{type:"auto",disable_parallel_tool_use:t}:void 0,toolWarnings:a,betas:c};let d=e.type;switch(d){case"auto":return{tools:u,toolChoice:{type:"auto",disable_parallel_tool_use:t},toolWarnings:a,betas:c};case"required":return{tools:u,toolChoice:{type:"any",disable_parallel_tool_use:t},toolWarnings:a,betas:c};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:a,betas:c};case"tool":return{tools:u,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:t},toolWarnings:a,betas:c};default:{let m=d;throw new Jr({functionality:`tool choice type: ${m}`})}}}function YOe({usage:r,rawUsage:e}){var t,n;let o=(t=r.cache_creation_input_tokens)!=null?t:0,s=(n=r.cache_read_input_tokens)!=null?n:0,i,a;if(r.iterations&&r.iterations.length>0){let c=r.iterations.reduce((l,u)=>({input:l.input+u.input_tokens,output:l.output+u.output_tokens}),{input:0,output:0});i=c.input,a=c.output}else i=r.input_tokens,a=r.output_tokens;return{inputTokens:{total:i+o+s,noCache:i,cacheRead:s,cacheWrite:o},outputTokens:{total:a,text:void 0,reasoning:void 0},raw:e??r}}function Y9t(r){if(typeof r=="string")return new TextDecoder().decode(Pc(r));if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw r instanceof URL?new Jr({functionality:"URL-based text documents are not supported for citations"}):new Jr({functionality:`unsupported data type for text documents: ${typeof r}`})}function cte(r){return r instanceof URL||Q9t(r)}function Q9t(r){return typeof r=="string"&&/^https?:\/\//i.test(r)}function lte(r){return r instanceof URL?r.toString():r}async function eXt({prompt:r,sendReasoning:e,warnings:t,cacheControlValidator:n,toolNameMapping:o}){var s,i,a,c,l,u,d,m,f,h,y,x,b,S,w,_,C,k,I;let R=new Set,A=tXt(r),M=n||new dte,D,B=[];async function O(N){var $,L;let z=await Fn({provider:"anthropic",providerOptions:N,schema:JOe});return(L=($=z?.citations)==null?void 0:$.enabled)!=null?L:!1}async function U(N){let $=await Fn({provider:"anthropic",providerOptions:N,schema:JOe});return{title:$?.title,context:$?.context}}for(let N=0;N<A.length;N++){let $=A[N],L=N===A.length-1,z=$.type;switch(z){case"system":{if(D!=null)throw new Jr({functionality:"Multiple system messages that are separated by user/assistant messages"});D=$.messages.map(({content:F,providerOptions:j})=>({type:"text",text:F,cache_control:M.getCacheControl(j,{type:"system message",canCache:!0})}));break}case"user":{let F=[];for(let j of $.messages){let{role:H,content:J}=j;switch(H){case"user":{for(let he=0;he<J.length;he++){let Y=J[he],ve=he===J.length-1,W=(s=M.getCacheControl(Y.providerOptions,{type:"user message part",canCache:!0}))!=null?s:ve?M.getCacheControl(j.providerOptions,{type:"user message",canCache:!0}):void 0;switch(Y.type){case"text":{F.push({type:"text",text:Y.text,cache_control:W});break}case"file":{if(Y.mediaType.startsWith("image/"))F.push({type:"image",source:cte(Y.data)?{type:"url",url:lte(Y.data)}:{type:"base64",media_type:Y.mediaType==="image/*"?"image/jpeg":Y.mediaType,data:Al(Y.data)},cache_control:W});else if(Y.mediaType==="application/pdf"){R.add("pdfs-2024-09-25");let Ie=await O(Y.providerOptions),Me=await U(Y.providerOptions);F.push({type:"document",source:cte(Y.data)?{type:"url",url:lte(Y.data)}:{type:"base64",media_type:"application/pdf",data:Al(Y.data)},title:(i=Me.title)!=null?i:Y.filename,...Me.context&&{context:Me.context},...Ie&&{citations:{enabled:!0}},cache_control:W})}else if(Y.mediaType==="text/plain"){let Ie=await O(Y.providerOptions),Me=await U(Y.providerOptions);F.push({type:"document",source:cte(Y.data)?{type:"url",url:lte(Y.data)}:{type:"text",media_type:"text/plain",data:Y9t(Y.data)},title:(a=Me.title)!=null?a:Y.filename,...Me.context&&{context:Me.context},...Ie&&{citations:{enabled:!0}},cache_control:W})}else throw new Jr({functionality:`media type: ${Y.mediaType}`});break}}}break}case"tool":{for(let he=0;he<J.length;he++){let Y=J[he];if(Y.type==="tool-approval-response")continue;let ve=he===J.length-1,W=(c=M.getCacheControl(Y.providerOptions,{type:"tool result part",canCache:!0}))!=null?c:ve?M.getCacheControl(j.providerOptions,{type:"tool result message",canCache:!0}):void 0,Ie=Y.output,Me;switch(Ie.type){case"content":Me=Ie.value.map(ye=>{var Q;switch(ye.type){case"text":return{type:"text",text:ye.text};case"image-data":return{type:"image",source:{type:"base64",media_type:ye.mediaType,data:ye.data}};case"image-url":return{type:"image",source:{type:"url",url:ye.url}};case"file-url":return{type:"document",source:{type:"url",url:ye.url}};case"file-data":{if(ye.mediaType==="application/pdf")return R.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:ye.mediaType,data:ye.data}};t.push({type:"other",message:`unsupported tool content part type: ${ye.type} with media type: ${ye.mediaType}`});return}case"custom":{let oe=(Q=ye.providerOptions)==null?void 0:Q.anthropic;if(oe?.type==="tool-reference")return{type:"tool_reference",tool_name:oe.toolName};t.push({type:"other",message:"unsupported custom tool content part"});return}default:{t.push({type:"other",message:`unsupported tool content part type: ${ye.type}`});return}}}).filter(lR);break;case"text":case"error-text":Me=Ie.value;break;case"execution-denied":Me=(l=Ie.reason)!=null?l:"Tool execution denied.";break;default:Me=JSON.stringify(Ie.value);break}F.push({type:"tool_result",tool_use_id:Y.toolCallId,content:Me,is_error:Ie.type==="error-text"||Ie.type==="error-json"?!0:void 0,cache_control:W})}break}default:{let he=H;throw new Error(`Unsupported role: ${he}`)}}}B.push({role:"user",content:F});break}case"assistant":{let F=[],j=new Set;for(let H=0;H<$.messages.length;H++){let J=$.messages[H],he=H===$.messages.length-1,{content:Y}=J;for(let ve=0;ve<Y.length;ve++){let W=Y[ve],Ie=ve===Y.length-1,Me=(u=M.getCacheControl(W.providerOptions,{type:"assistant message part",canCache:!0}))!=null?u:Ie?M.getCacheControl(J.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(W.type){case"text":{let ye=(d=W.providerOptions)==null?void 0:d.anthropic;ye?.type==="compaction"?F.push({type:"compaction",content:W.text,cache_control:Me}):F.push({type:"text",text:L&&he&&Ie?W.text.trim():W.text,cache_control:Me});break}case"reasoning":{if(e){let ye=await Fn({provider:"anthropic",providerOptions:W.providerOptions,schema:g9t});ye!=null?ye.signature!=null?(M.getCacheControl(W.providerOptions,{type:"thinking block",canCache:!1}),F.push({type:"thinking",thinking:W.text,signature:ye.signature})):ye.redactedData!=null?(M.getCacheControl(W.providerOptions,{type:"redacted thinking block",canCache:!1}),F.push({type:"redacted_thinking",data:ye.redactedData})):t.push({type:"other",message:"unsupported reasoning metadata"}):t.push({type:"other",message:"unsupported reasoning metadata"})}else t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(W.providerExecuted){let oe=o.toProviderToolName(W.toolName);if(((f=(m=W.providerOptions)==null?void 0:m.anthropic)==null?void 0:f.type)==="mcp-tool-use"){j.add(W.toolCallId);let te=(y=(h=W.providerOptions)==null?void 0:h.anthropic)==null?void 0:y.serverName;if(te==null||typeof te!="string"){t.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}F.push({type:"mcp_tool_use",id:W.toolCallId,name:W.toolName,input:W.input,server_name:te,cache_control:Me})}else if(oe==="code_execution"&&W.input!=null&&typeof W.input=="object"&&"type"in W.input&&typeof W.input.type=="string"&&(W.input.type==="bash_code_execution"||W.input.type==="text_editor_code_execution"))F.push({type:"server_tool_use",id:W.toolCallId,name:W.input.type,input:W.input,cache_control:Me});else if(oe==="code_execution"&&W.input!=null&&typeof W.input=="object"&&"type"in W.input&&W.input.type==="programmatic-tool-call"){let{type:te,...Qe}=W.input;F.push({type:"server_tool_use",id:W.toolCallId,name:"code_execution",input:Qe,cache_control:Me})}else oe==="code_execution"||oe==="web_fetch"||oe==="web_search"?F.push({type:"server_tool_use",id:W.toolCallId,name:oe,input:W.input,cache_control:Me}):oe==="tool_search_tool_regex"||oe==="tool_search_tool_bm25"?F.push({type:"server_tool_use",id:W.toolCallId,name:oe,input:W.input,cache_control:Me}):t.push({type:"other",message:`provider executed tool call for tool ${W.toolName} is not supported`});break}let ye=(x=W.providerOptions)==null?void 0:x.anthropic,Q=ye?.caller?(ye.caller.type==="code_execution_20250825"||ye.caller.type==="code_execution_20260120")&&ye.caller.toolId?{type:ye.caller.type,tool_id:ye.caller.toolId}:ye.caller.type==="direct"?{type:"direct"}:void 0:void 0;F.push({type:"tool_use",id:W.toolCallId,name:W.toolName,input:W.input,...Q&&{caller:Q},cache_control:Me});break}case"tool-result":{let ye=o.toProviderToolName(W.toolName);if(j.has(W.toolCallId)){let Q=W.output;if(Q.type!=="json"&&Q.type!=="error-json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}F.push({type:"mcp_tool_result",tool_use_id:W.toolCallId,is_error:Q.type==="error-json",content:Q.value,cache_control:Me})}else if(ye==="code_execution"){let Q=W.output;if(Q.type==="error-text"||Q.type==="error-json"){let oe={};try{typeof Q.value=="string"?oe=JSON.parse(Q.value):typeof Q.value=="object"&&Q.value!==null&&(oe=Q.value)}catch{}oe.type==="code_execution_tool_result_error"?F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(b=oe.errorCode)!=null?b:"unknown"},cache_control:Me}):F.push({type:"bash_code_execution_tool_result",tool_use_id:W.toolCallId,cache_control:Me,content:{type:"bash_code_execution_tool_result_error",error_code:(S=oe.errorCode)!=null?S:"unknown"}});break}if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}if(Q.value==null||typeof Q.value!="object"||!("type"in Q.value)||typeof Q.value.type!="string"){t.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${W.toolName}`});break}if(Q.value.type==="code_execution_result"){let oe=await ur({value:Q.value,schema:oNe});F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:oe.type,stdout:oe.stdout,stderr:oe.stderr,return_code:oe.return_code,content:(w=oe.content)!=null?w:[]},cache_control:Me})}else if(Q.value.type==="encrypted_code_execution_result"){let oe=await ur({value:Q.value,schema:iNe});oe.type==="encrypted_code_execution_result"&&F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:oe.type,encrypted_stdout:oe.encrypted_stdout,stderr:oe.stderr,return_code:oe.return_code,content:(_=oe.content)!=null?_:[]},cache_control:Me})}else{let oe=await ur({value:Q.value,schema:sNe});oe.type==="code_execution_result"?F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:oe.type,stdout:oe.stdout,stderr:oe.stderr,return_code:oe.return_code,content:(C=oe.content)!=null?C:[]},cache_control:Me}):oe.type==="bash_code_execution_result"||oe.type==="bash_code_execution_tool_result_error"?F.push({type:"bash_code_execution_tool_result",tool_use_id:W.toolCallId,cache_control:Me,content:oe}):F.push({type:"text_editor_code_execution_tool_result",tool_use_id:W.toolCallId,cache_control:Me,content:oe})}break}if(ye==="web_fetch"){let Q=W.output;if(Q.type==="error-json"){let pe={};try{typeof Q.value=="string"?pe=JSON.parse(Q.value):typeof Q.value=="object"&&Q.value!==null&&(pe=Q.value)}catch{let Qe=(k=Q.value)==null?void 0:k.errorCode;pe={errorCode:typeof Qe=="string"?Qe:"unavailable"}}F.push({type:"web_fetch_tool_result",tool_use_id:W.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(I=pe.errorCode)!=null?I:"unavailable"},cache_control:Me});break}if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}let oe=await ur({value:Q.value,schema:nNe});F.push({type:"web_fetch_tool_result",tool_use_id:W.toolCallId,content:{type:"web_fetch_result",url:oe.url,retrieved_at:oe.retrievedAt,content:{type:"document",title:oe.content.title,citations:oe.content.citations,source:{type:oe.content.source.type,media_type:oe.content.source.mediaType,data:oe.content.source.data}}},cache_control:Me});break}if(ye==="web_search"){let Q=W.output;if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}let oe=await ur({value:Q.value,schema:rNe});F.push({type:"web_search_tool_result",tool_use_id:W.toolCallId,content:oe.map(pe=>({url:pe.url,title:pe.title,page_age:pe.pageAge,encrypted_content:pe.encryptedContent,type:pe.type})),cache_control:Me});break}if(ye==="tool_search_tool_regex"||ye==="tool_search_tool_bm25"){let Q=W.output;if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}let pe=(await ur({value:Q.value,schema:aNe})).map(te=>({type:"tool_reference",tool_name:te.toolName}));F.push({type:"tool_search_tool_result",tool_use_id:W.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:pe},cache_control:Me});break}t.push({type:"other",message:`provider executed tool result for tool ${W.toolName} is not supported`});break}}}}B.push({role:"assistant",content:F});break}default:{let F=z;throw new Error(`content type: ${F}`)}}}return{prompt:{system:D,messages:B},betas:R}}function tXt(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case"system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case"assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case"user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case"tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let s=o;throw new Error(`Unsupported role: ${s}`)}}}return e}function ute({finishReason:r,isJsonResponseFromTool:e}){switch(r){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}function QOe(r,e,t){var n;if(r.type==="web_search_result_location")return{type:"source",sourceType:"url",id:t(),url:r.url,title:r.title,providerMetadata:{anthropic:{citedText:r.cited_text,encryptedIndex:r.encrypted_index}}};if(r.type!=="page_location"&&r.type!=="char_location")return;let o=e[r.document_index];if(o)return{type:"source",sourceType:"document",id:t(),mediaType:o.mediaType,title:(n=r.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:r.type==="page_location"?{citedText:r.cited_text,startPageNumber:r.start_page_number,endPageNumber:r.end_page_number}:{citedText:r.cited_text,startCharIndex:r.start_char_index,endCharIndex:r.end_char_index}}}}function nXt(r){return r.includes("claude-sonnet-4-6")||r.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,isKnownModel:!0}:r.includes("claude-sonnet-4-5")||r.includes("claude-opus-4-5")||r.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:r.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:r.includes("claude-sonnet-4-")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:r.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:r.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function eNe(r){if(!r)return!1;let e=!1,t=!1;for(let n of r){if("type"in n&&(n.type==="web_fetch_20260209"||n.type==="web_search_20260209")){e=!0;continue}if(n.name==="code_execution"){t=!0;break}}return e&&!t}function tNe(r){return r?{appliedEdits:r.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens};case"compact_20260112":return{type:e.type}}}).filter(e=>e!==void 0)}:null}function cP(r={}){var e,t;let n=(e=Ug(up({settingValue:r.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?e:"https://api.anthropic.com/v1",o=(t=r.name)!=null?t:"anthropic.messages";if(r.apiKey&&r.authToken)throw new VT({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let s=()=>{let c=r.authToken?{Authorization:`Bearer ${r.authToken}`}:{"x-api-key":lS({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return yo({"anthropic-version":"2023-06-01",...c,...r.headers},`ai-sdk/anthropic/${d9t}`)},i=c=>{var l;return new rXt(c,{provider:o,baseURL:n,headers:s,fetch:r.fetch,generateId:(l=r.generateId)!=null?l:qn,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},a=function(c){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(c)};return a.specificationVersion="v3",a.languageModel=i,a.chat=i,a.messages=i,a.embeddingModel=c=>{throw new Wk({modelId:c,modelType:"embeddingModel"})},a.textEmbeddingModel=a.embeddingModel,a.imageModel=c=>{throw new Wk({modelId:c,modelType:"imageModel"})},a.tools=CXt,a}var d9t,p9t,KOe,m9t,f9t,g9t,JOe,XOe,ZOe,dte,y9t,x9t,v9t,b9t,T9t,S9t,w9t,E9t,_9t,C9t,rNe,k9t,R9t,A9t,I9t,P9t,M9t,O9t,N9t,D9t,nNe,L9t,U9t,F9t,oNe,B9t,z9t,G9t,sNe,j9t,V9t,H9t,iNe,q9t,W9t,K9t,aNe,J9t,X9t,Z9t,rXt,oXt,sXt,iXt,aXt,cXt,lXt,uXt,dXt,pXt,mXt,fXt,gXt,hXt,yXt,xXt,vXt,bXt,TXt,SXt,wXt,EXt,_Xt,CXt,kXt,pte=E(()=>{xt();xe();xt();xe();xe();Ye();xe();Ye();Ye();xt();xe();Ye();xe();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();xt();xe();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();d9t="3.0.64",p9t=ae(()=>se(p.object({type:p.literal("error"),error:p.object({type:p.string(),message:p.string()})}))),KOe=vo({errorSchema:p9t,errorToMessage:r=>r.error.message}),m9t=ae(()=>se(p.object({type:p.literal("message"),id:p.string().nullish(),model:p.string().nullish(),content:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("text"),text:p.string(),citations:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("web_search_result_location"),cited_text:p.string(),url:p.string(),title:p.string(),encrypted_index:p.string()}),p.object({type:p.literal("page_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_page_number:p.number(),end_page_number:p.number()}),p.object({type:p.literal("char_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_char_index:p.number(),end_char_index:p.number()})])).optional()}),p.object({type:p.literal("thinking"),thinking:p.string(),signature:p.string()}),p.object({type:p.literal("redacted_thinking"),data:p.string()}),p.object({type:p.literal("compaction"),content:p.string()}),p.object({type:p.literal("tool_use"),id:p.string(),name:p.string(),input:p.unknown(),caller:p.union([p.object({type:p.literal("code_execution_20250825"),tool_id:p.string()}),p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("server_tool_use"),id:p.string(),name:p.string(),input:p.record(p.string(),p.unknown()).nullish(),caller:p.union([p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("mcp_tool_use"),id:p.string(),name:p.string(),input:p.unknown(),server_name:p.string()}),p.object({type:p.literal("mcp_tool_result"),tool_use_id:p.string(),is_error:p.boolean(),content:p.array(p.union([p.string(),p.object({type:p.literal("text"),text:p.string()})]))}),p.object({type:p.literal("web_fetch_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("web_fetch_result"),url:p.string(),retrieved_at:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),media_type:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),media_type:p.literal("text/plain"),data:p.string()})])})}),p.object({type:p.literal("web_fetch_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("web_search_tool_result"),tool_use_id:p.string(),content:p.union([p.array(p.object({type:p.literal("web_search_result"),url:p.string(),title:p.string(),encrypted_content:p.string(),page_age:p.string().nullish()})),p.object({type:p.literal("web_search_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("code_execution_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("encrypted_code_execution_result"),encrypted_stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("bash_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("text_editor_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})])}),p.object({type:p.literal("tool_search_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("tool_search_tool_search_result"),tool_references:p.array(p.object({type:p.literal("tool_reference"),tool_name:p.string()}))}),p.object({type:p.literal("tool_search_tool_result_error"),error_code:p.string()})])})])),stop_reason:p.string().nullish(),stop_sequence:p.string().nullish(),usage:p.looseObject({input_tokens:p.number(),output_tokens:p.number(),cache_creation_input_tokens:p.number().nullish(),cache_read_input_tokens:p.number().nullish(),iterations:p.array(p.object({type:p.union([p.literal("compaction"),p.literal("message")]),input_tokens:p.number(),output_tokens:p.number()})).nullish()}),container:p.object({expires_at:p.string(),id:p.string(),skills:p.array(p.object({type:p.union([p.literal("anthropic"),p.literal("custom")]),skill_id:p.string(),version:p.string()})).nullish()}).nullish(),context_management:p.object({applied_edits:p.array(p.union([p.object({type:p.literal("clear_tool_uses_20250919"),cleared_tool_uses:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("clear_thinking_20251015"),cleared_thinking_turns:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("compact_20260112")})]))}).nullish()}))),f9t=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("message_start"),message:p.object({id:p.string().nullish(),model:p.string().nullish(),role:p.string().nullish(),usage:p.looseObject({input_tokens:p.number(),cache_creation_input_tokens:p.number().nullish(),cache_read_input_tokens:p.number().nullish()}),content:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("tool_use"),id:p.string(),name:p.string(),input:p.unknown(),caller:p.union([p.object({type:p.literal("code_execution_20250825"),tool_id:p.string()}),p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()})])).nullish(),stop_reason:p.string().nullish(),container:p.object({expires_at:p.string(),id:p.string()}).nullish()})}),p.object({type:p.literal("content_block_start"),index:p.number(),content_block:p.discriminatedUnion("type",[p.object({type:p.literal("text"),text:p.string()}),p.object({type:p.literal("thinking"),thinking:p.string()}),p.object({type:p.literal("tool_use"),id:p.string(),name:p.string(),input:p.record(p.string(),p.unknown()).optional(),caller:p.union([p.object({type:p.literal("code_execution_20250825"),tool_id:p.string()}),p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("redacted_thinking"),data:p.string()}),p.object({type:p.literal("compaction"),content:p.string().nullish()}),p.object({type:p.literal("server_tool_use"),id:p.string(),name:p.string(),input:p.record(p.string(),p.unknown()).nullish(),caller:p.union([p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("mcp_tool_use"),id:p.string(),name:p.string(),input:p.unknown(),server_name:p.string()}),p.object({type:p.literal("mcp_tool_result"),tool_use_id:p.string(),is_error:p.boolean(),content:p.array(p.union([p.string(),p.object({type:p.literal("text"),text:p.string()})]))}),p.object({type:p.literal("web_fetch_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("web_fetch_result"),url:p.string(),retrieved_at:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),media_type:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),media_type:p.literal("text/plain"),data:p.string()})])})}),p.object({type:p.literal("web_fetch_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("web_search_tool_result"),tool_use_id:p.string(),content:p.union([p.array(p.object({type:p.literal("web_search_result"),url:p.string(),title:p.string(),encrypted_content:p.string(),page_age:p.string().nullish()})),p.object({type:p.literal("web_search_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("code_execution_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("encrypted_code_execution_result"),encrypted_stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("bash_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("text_editor_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})])}),p.object({type:p.literal("tool_search_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("tool_search_tool_search_result"),tool_references:p.array(p.object({type:p.literal("tool_reference"),tool_name:p.string()}))}),p.object({type:p.literal("tool_search_tool_result_error"),error_code:p.string()})])})])}),p.object({type:p.literal("content_block_delta"),index:p.number(),delta:p.discriminatedUnion("type",[p.object({type:p.literal("input_json_delta"),partial_json:p.string()}),p.object({type:p.literal("text_delta"),text:p.string()}),p.object({type:p.literal("thinking_delta"),thinking:p.string()}),p.object({type:p.literal("signature_delta"),signature:p.string()}),p.object({type:p.literal("compaction_delta"),content:p.string().nullish()}),p.object({type:p.literal("citations_delta"),citation:p.discriminatedUnion("type",[p.object({type:p.literal("web_search_result_location"),cited_text:p.string(),url:p.string(),title:p.string(),encrypted_index:p.string()}),p.object({type:p.literal("page_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_page_number:p.number(),end_page_number:p.number()}),p.object({type:p.literal("char_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_char_index:p.number(),end_char_index:p.number()})])})])}),p.object({type:p.literal("content_block_stop"),index:p.number()}),p.object({type:p.literal("error"),error:p.object({type:p.string(),message:p.string()})}),p.object({type:p.literal("message_delta"),delta:p.object({stop_reason:p.string().nullish(),stop_sequence:p.string().nullish(),container:p.object({expires_at:p.string(),id:p.string(),skills:p.array(p.object({type:p.union([p.literal("anthropic"),p.literal("custom")]),skill_id:p.string(),version:p.string()})).nullish()}).nullish()}),usage:p.looseObject({input_tokens:p.number().nullish(),output_tokens:p.number(),cache_creation_input_tokens:p.number().nullish(),cache_read_input_tokens:p.number().nullish(),iterations:p.array(p.object({type:p.union([p.literal("compaction"),p.literal("message")]),input_tokens:p.number(),output_tokens:p.number()})).nullish()}),context_management:p.object({applied_edits:p.array(p.union([p.object({type:p.literal("clear_tool_uses_20250919"),cleared_tool_uses:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("clear_thinking_20251015"),cleared_thinking_turns:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("compact_20260112")})]))}).nullish()}),p.object({type:p.literal("message_stop")}),p.object({type:p.literal("ping")})]))),g9t=ae(()=>se(p.object({signature:p.string().optional(),redactedData:p.string().optional()}))),JOe=p.object({citations:p.object({enabled:p.boolean()}).optional(),title:p.string().optional(),context:p.string().optional()}),XOe=p.object({sendReasoning:p.boolean().optional(),structuredOutputMode:p.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:p.discriminatedUnion("type",[p.object({type:p.literal("adaptive")}),p.object({type:p.literal("enabled"),budgetTokens:p.number().optional()}),p.object({type:p.literal("disabled")})]).optional(),disableParallelToolUse:p.boolean().optional(),cacheControl:p.object({type:p.literal("ephemeral"),ttl:p.union([p.literal("5m"),p.literal("1h")]).optional()}).optional(),metadata:p.object({userId:p.string().optional()}).optional(),mcpServers:p.array(p.object({type:p.literal("url"),name:p.string(),url:p.string(),authorizationToken:p.string().nullish(),toolConfiguration:p.object({enabled:p.boolean().nullish(),allowedTools:p.array(p.string()).nullish()}).nullish()})).optional(),container:p.object({id:p.string().optional(),skills:p.array(p.object({type:p.union([p.literal("anthropic"),p.literal("custom")]),skillId:p.string(),version:p.string().optional()})).optional()}).optional(),toolStreaming:p.boolean().optional(),effort:p.enum(["low","medium","high","max"]).optional(),speed:p.enum(["fast","standard"]).optional(),anthropicBeta:p.array(p.string()).optional(),contextManagement:p.object({edits:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("clear_tool_uses_20250919"),trigger:p.discriminatedUnion("type",[p.object({type:p.literal("input_tokens"),value:p.number()}),p.object({type:p.literal("tool_uses"),value:p.number()})]).optional(),keep:p.object({type:p.literal("tool_uses"),value:p.number()}).optional(),clearAtLeast:p.object({type:p.literal("input_tokens"),value:p.number()}).optional(),clearToolInputs:p.boolean().optional(),excludeTools:p.array(p.string()).optional()}),p.object({type:p.literal("clear_thinking_20251015"),keep:p.union([p.literal("all"),p.object({type:p.literal("thinking_turns"),value:p.number()})]).optional()}),p.object({type:p.literal("compact_20260112"),trigger:p.object({type:p.literal("input_tokens"),value:p.number()}).optional(),pauseAfterCompaction:p.boolean().optional(),instructions:p.string().optional()})]))}).optional()}),ZOe=4;dte=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(r,e){let t=h9t(r);if(t){if(!e.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${e.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>ZOe){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${ZOe} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return t}}getWarnings(){return this.warnings}},y9t=ae(()=>se(p.object({maxCharacters:p.number().optional()}))),x9t=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),v9t=xo({id:"anthropic.text_editor_20250728",inputSchema:x9t}),b9t=(r={})=>v9t(r),T9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),userLocation:p.object({type:p.literal("approximate"),city:p.string().optional(),region:p.string().optional(),country:p.string().optional(),timezone:p.string().optional()}).optional()}))),S9t=ae(()=>se(p.array(p.object({url:p.string(),title:p.string().nullable(),pageAge:p.string().nullable(),encryptedContent:p.string(),type:p.literal("web_search_result")})))),w9t=ae(()=>se(p.object({query:p.string()}))),E9t=Zt({id:"anthropic.web_search_20260209",inputSchema:w9t,outputSchema:S9t,supportsDeferredResults:!0}),_9t=(r={})=>E9t(r),C9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),userLocation:p.object({type:p.literal("approximate"),city:p.string().optional(),region:p.string().optional(),country:p.string().optional(),timezone:p.string().optional()}).optional()}))),rNe=ae(()=>se(p.array(p.object({url:p.string(),title:p.string().nullable(),pageAge:p.string().nullable(),encryptedContent:p.string(),type:p.literal("web_search_result")})))),k9t=ae(()=>se(p.object({query:p.string()}))),R9t=Zt({id:"anthropic.web_search_20250305",inputSchema:k9t,outputSchema:rNe,supportsDeferredResults:!0}),A9t=(r={})=>R9t(r),I9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),citations:p.object({enabled:p.boolean()}).optional(),maxContentTokens:p.number().optional()}))),P9t=ae(()=>se(p.object({type:p.literal("web_fetch_result"),url:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),mediaType:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),mediaType:p.literal("text/plain"),data:p.string()})])}),retrievedAt:p.string().nullable()}))),M9t=ae(()=>se(p.object({url:p.string()}))),O9t=Zt({id:"anthropic.web_fetch_20260209",inputSchema:M9t,outputSchema:P9t,supportsDeferredResults:!0}),N9t=(r={})=>O9t(r),D9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),citations:p.object({enabled:p.boolean()}).optional(),maxContentTokens:p.number().optional()}))),nNe=ae(()=>se(p.object({type:p.literal("web_fetch_result"),url:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),mediaType:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),mediaType:p.literal("text/plain"),data:p.string()})])}),retrievedAt:p.string().nullable()}))),L9t=ae(()=>se(p.object({url:p.string()}))),U9t=Zt({id:"anthropic.web_fetch_20250910",inputSchema:L9t,outputSchema:nNe,supportsDeferredResults:!0}),F9t=(r={})=>U9t(r);oNe=ae(()=>se(p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}))),B9t=ae(()=>se(p.object({code:p.string()}))),z9t=Zt({id:"anthropic.code_execution_20250522",inputSchema:B9t,outputSchema:oNe}),G9t=(r={})=>z9t(r),sNe=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})]))),j9t=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("programmatic-tool-call"),code:p.string()}),p.object({type:p.literal("bash_code_execution"),command:p.string()}),p.discriminatedUnion("command",[p.object({type:p.literal("text_editor_code_execution"),command:p.literal("view"),path:p.string()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("create"),path:p.string(),file_text:p.string().nullish()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("str_replace"),path:p.string(),old_str:p.string(),new_str:p.string()})])]))),V9t=Zt({id:"anthropic.code_execution_20250825",inputSchema:j9t,outputSchema:sNe,supportsDeferredResults:!0}),H9t=(r={})=>V9t(r),iNe=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("encrypted_code_execution_result"),encrypted_stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})]))),q9t=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("programmatic-tool-call"),code:p.string()}),p.object({type:p.literal("bash_code_execution"),command:p.string()}),p.discriminatedUnion("command",[p.object({type:p.literal("text_editor_code_execution"),command:p.literal("view"),path:p.string()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("create"),path:p.string(),file_text:p.string().nullish()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("str_replace"),path:p.string(),old_str:p.string(),new_str:p.string()})])]))),W9t=Zt({id:"anthropic.code_execution_20260120",inputSchema:q9t,outputSchema:iNe,supportsDeferredResults:!0}),K9t=(r={})=>W9t(r),aNe=ae(()=>se(p.array(p.object({type:p.literal("tool_reference"),toolName:p.string()})))),J9t=ae(()=>se(p.object({pattern:p.string(),limit:p.number().optional()}))),X9t=Zt({id:"anthropic.tool_search_regex_20251119",inputSchema:J9t,outputSchema:aNe,supportsDeferredResults:!0}),Z9t=(r={})=>X9t(r);rXt=class{constructor(r,e){this.specificationVersion="v3";var t;this.modelId=r,this.config=e,this.generateId=(t=e.generateId)!=null?t:qn}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let r=this.config.provider,e=r.indexOf(".");return e===-1?r:r.substring(0,e)}get supportedUrls(){var r,e,t;return(t=(e=(r=this.config).supportedUrls)==null?void 0:e.call(r))!=null?t:{}}async getArgs({userSuppliedBetas:r,prompt:e,maxOutputTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:m,providerOptions:f,stream:h}){var y,x,b,S,w,_,C,k,I;let R=[];i!=null&&R.push({type:"unsupported",feature:"frequencyPenalty"}),a!=null&&R.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&R.push({type:"unsupported",feature:"seed"}),n!=null&&n>1?(R.push({type:"unsupported",feature:"temperature",details:`${n} exceeds anthropic maximum of 1.0. clamped to 1.0`}),n=1):n!=null&&n<0&&(R.push({type:"unsupported",feature:"temperature",details:`${n} is below anthropic minimum of 0. clamped to 0`}),n=0),l?.type==="json"&&l.schema==null&&R.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let A=this.providerOptionsName,M=await Fn({provider:"anthropic",providerOptions:f,schema:XOe}),D=A!=="anthropic"?await Fn({provider:A,providerOptions:f,schema:XOe}):null,B=D!=null,O=Object.assign({},M??{},D??{}),{maxOutputTokens:U,supportsStructuredOutput:N,isKnownModel:$}=nXt(this.modelId),L=((y=this.config.supportsNativeStructuredOutput)!=null?y:!0)&&N,z=((x=this.config.supportsStrictTools)!=null?x:!0)&&N,F=(b=O?.structuredOutputMode)!=null?b:"auto",j=F==="outputFormat"||F==="auto"&&L,H=l?.type==="json"&&l.schema!=null&&!j?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:l.schema}:void 0,J=O?.contextManagement,he=new dte,Y=lU({tools:d,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:ve,betas:W}=await eXt({prompt:e,sendReasoning:(S=O?.sendReasoning)!=null?S:!0,warnings:R,cacheControlValidator:he,toolNameMapping:Y}),Ie=(w=O?.thinking)==null?void 0:w.type,Me=Ie==="enabled"||Ie==="adaptive",ye=Ie==="enabled"?(_=O?.thinking)==null?void 0:_.budgetTokens:void 0,Q=t??U,oe={model:this.modelId,max_tokens:Q,temperature:n,top_k:s,top_p:o,stop_sequences:c,...Me&&{thinking:{type:Ie,...ye!=null&&{budget_tokens:ye}}},...(O?.effort||j&&l?.type==="json"&&l.schema!=null)&&{output_config:{...O?.effort&&{effort:O.effort},...j&&l?.type==="json"&&l.schema!=null&&{format:{type:"json_schema",schema:l.schema}}}},...O?.speed&&{speed:O.speed},...O?.cacheControl&&{cache_control:O.cacheControl},...((C=O?.metadata)==null?void 0:C.userId)!=null&&{metadata:{user_id:O.metadata.userId}},...O?.mcpServers&&O.mcpServers.length>0&&{mcp_servers:O.mcpServers.map(Ee=>({type:Ee.type,name:Ee.name,url:Ee.url,authorization_token:Ee.authorizationToken,tool_configuration:Ee.toolConfiguration?{allowed_tools:Ee.toolConfiguration.allowedTools,enabled:Ee.toolConfiguration.enabled}:void 0}))},...O?.container&&{container:O.container.skills&&O.container.skills.length>0?{id:O.container.id,skills:O.container.skills.map(Ee=>({type:Ee.type,skill_id:Ee.skillId,version:Ee.version}))}:O.container.id},system:ve.system,messages:ve.messages,...J&&{context_management:{edits:J.edits.map(Ee=>{let ro=Ee.type;switch(ro){case"clear_tool_uses_20250919":return{type:Ee.type,...Ee.trigger!==void 0&&{trigger:Ee.trigger},...Ee.keep!==void 0&&{keep:Ee.keep},...Ee.clearAtLeast!==void 0&&{clear_at_least:Ee.clearAtLeast},...Ee.clearToolInputs!==void 0&&{clear_tool_inputs:Ee.clearToolInputs},...Ee.excludeTools!==void 0&&{exclude_tools:Ee.excludeTools}};case"clear_thinking_20251015":return{type:Ee.type,...Ee.keep!==void 0&&{keep:Ee.keep}};case"compact_20260112":return{type:Ee.type,...Ee.trigger!==void 0&&{trigger:Ee.trigger},...Ee.pauseAfterCompaction!==void 0&&{pause_after_compaction:Ee.pauseAfterCompaction},...Ee.instructions!==void 0&&{instructions:Ee.instructions}};default:R.push({type:"other",message:`Unknown context management strategy: ${ro}`});return}}).filter(Ee=>Ee!==void 0)}}};Me?(Ie==="enabled"&&ye==null&&(R.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),oe.thinking={type:"enabled",budget_tokens:1024},ye=1024),oe.temperature!=null&&(oe.temperature=void 0,R.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),s!=null&&(oe.top_k=void 0,R.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(oe.top_p=void 0,R.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),oe.max_tokens=Q+(ye??0)):o!=null&&n!=null&&(R.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),oe.top_p=void 0),$&&oe.max_tokens>U&&(t!=null&&R.push({type:"unsupported",feature:"maxOutputTokens",details:`${oe.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${U} max output tokens. The max output tokens have been limited to ${U}.`}),oe.max_tokens=U),O?.mcpServers&&O.mcpServers.length>0&&W.add("mcp-client-2025-04-04"),J&&(W.add("context-management-2025-06-27"),J.edits.some(Ee=>Ee.type==="compact_20260112")&&W.add("compact-2026-01-12")),O?.container&&O.container.skills&&O.container.skills.length>0&&(W.add("code-execution-2025-08-25"),W.add("skills-2025-10-02"),W.add("files-api-2025-04-14"),d?.some(Ee=>Ee.type==="provider"&&(Ee.id==="anthropic.code_execution_20250825"||Ee.id==="anthropic.code_execution_20260120"))||R.push({type:"other",message:"code execution tool is required when using skills"})),O?.effort&&W.add("effort-2025-11-24"),O?.speed==="fast"&&W.add("fast-mode-2026-02-01"),h&&((k=O?.toolStreaming)==null||k)&&W.add("fine-grained-tool-streaming-2025-05-14");let{tools:pe,toolChoice:te,toolWarnings:Qe,betas:nt}=await $9t(H!=null?{tools:[...d??[],H],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:he,supportsStructuredOutput:!1,supportsStrictTools:z}:{tools:d??[],toolChoice:m,disableParallelToolUse:O?.disableParallelToolUse,cacheControlValidator:he,supportsStructuredOutput:L,supportsStrictTools:z}),je=he.getWarnings();return{args:{...oe,tools:pe,tool_choice:te,stream:h===!0?!0:void 0},warnings:[...R,...Qe,...je],betas:new Set([...W,...nt,...r,...(I=O?.anthropicBeta)!=null?I:[]]),usesJsonResponseTool:H!=null,toolNameMapping:Y,providerOptionsName:A,usedCustomProviderKey:B}}async getHeaders({betas:r,headers:e}){return Ur(await En(this.config.headers),e,r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{})}async getBetasFromHeaders(r){var e,t;let o=(e=(await En(this.config.headers))["anthropic-beta"])!=null?e:"",s=(t=r?.["anthropic-beta"])!=null?t:"";return new Set([...o.toLowerCase().split(","),...s.toLowerCase().split(",")].map(i=>i.trim()).filter(i=>i!==""))}buildRequestUrl(r){var e,t,n;return(n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r,e){var t,n,o;return(o=(n=(t=this.config).transformRequestBody)==null?void 0:n.call(t,r,e))!=null?o:r}extractCitationDocuments(r){let e=t=>{var n,o;if(t.type!=="file"||t.mediaType!=="application/pdf"&&t.mediaType!=="text/plain")return!1;let s=(n=t.providerOptions)==null?void 0:n.anthropic,i=s?.citations;return(o=i?.enabled)!=null?o:!1};return r.filter(t=>t.role==="user").flatMap(t=>t.content).filter(e).map(t=>{var n;let o=t;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(r){var e,t,n,o,s,i,a;let{args:c,warnings:l,betas:u,usesJsonResponseTool:d,toolNameMapping:m,providerOptionsName:f,usedCustomProviderKey:h}=await this.getArgs({...r,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(r.headers)}),y=[...this.extractCitationDocuments(r.prompt)],x=eNe(c.tools),{responseHeaders:b,value:S,rawValue:w}=await jr({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:u,headers:r.headers}),body:this.transformRequestBody(c,u),failedResponseHandler:KOe,successfulResponseHandler:Vr(m9t),abortSignal:r.abortSignal,fetch:this.config.fetch}),_=[],C={},k={},I=!1;for(let R of S.content)switch(R.type){case"text":{if(!d&&(_.push({type:"text",text:R.text}),R.citations))for(let A of R.citations){let M=QOe(A,y,this.generateId);M&&_.push(M)}break}case"thinking":{_.push({type:"reasoning",text:R.thinking,providerMetadata:{anthropic:{signature:R.signature}}});break}case"redacted_thinking":{_.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:R.data}}});break}case"compaction":{_.push({type:"text",text:R.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(d&&R.name==="json")I=!0,_.push({type:"text",text:JSON.stringify(R.input)});else{let M=R.caller,D=M?{type:M.type,toolId:"tool_id"in M?M.tool_id:void 0}:void 0;_.push({type:"tool-call",toolCallId:R.id,toolName:R.name,input:JSON.stringify(R.input),...D&&{providerMetadata:{anthropic:{caller:D}}}})}break}case"server_tool_use":{if(R.name==="text_editor_code_execution"||R.name==="bash_code_execution")_.push({type:"tool-call",toolCallId:R.id,toolName:m.toCustomToolName("code_execution"),input:JSON.stringify({type:R.name,...R.input}),providerExecuted:!0});else if(R.name==="web_search"||R.name==="code_execution"||R.name==="web_fetch"){let A=R.name==="code_execution"&&R.input!=null&&typeof R.input=="object"&&"code"in R.input&&!("type"in R.input)?{type:"programmatic-tool-call",...R.input}:R.input;_.push({type:"tool-call",toolCallId:R.id,toolName:m.toCustomToolName(R.name),input:JSON.stringify(A),providerExecuted:!0,...x&&R.name==="code_execution"?{dynamic:!0}:{}})}else(R.name==="tool_search_tool_regex"||R.name==="tool_search_tool_bm25")&&(k[R.id]=R.name,_.push({type:"tool-call",toolCallId:R.id,toolName:m.toCustomToolName(R.name),input:JSON.stringify(R.input),providerExecuted:!0}));break}case"mcp_tool_use":{C[R.id]={type:"tool-call",toolCallId:R.id,toolName:R.name,input:JSON.stringify(R.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:R.server_name}}},_.push(C[R.id]);break}case"mcp_tool_result":{_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:C[R.tool_use_id].toolName,isError:R.is_error,result:R.content,dynamic:!0,providerMetadata:C[R.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{R.content.type==="web_fetch_result"?(y.push({title:(e=R.content.content.title)!=null?e:R.content.url,mediaType:R.content.content.source.media_type}),_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:R.content.url,retrievedAt:R.content.retrieved_at,content:{type:R.content.content.type,title:R.content.content.title,citations:R.content.content.citations,source:{type:R.content.content.source.type,mediaType:R.content.content.source.media_type,data:R.content.content.source.data}}}})):R.content.type==="web_fetch_tool_result_error"&&_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:R.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(R.content)){_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_search"),result:R.content.map(A=>{var M;return{url:A.url,title:A.title,pageAge:(M=A.page_age)!=null?M:null,encryptedContent:A.encrypted_content,type:A.type}})});for(let A of R.content)_.push({type:"source",sourceType:"url",id:this.generateId(),url:A.url,title:A.title,providerMetadata:{anthropic:{pageAge:(t=A.page_age)!=null?t:null}}})}else _.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:R.content.error_code}});break}case"code_execution_tool_result":{R.content.type==="code_execution_result"?_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),result:{type:R.content.type,stdout:R.content.stdout,stderr:R.content.stderr,return_code:R.content.return_code,content:(n=R.content.content)!=null?n:[]}}):R.content.type==="encrypted_code_execution_result"?_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),result:{type:R.content.type,encrypted_stdout:R.content.encrypted_stdout,stderr:R.content.stderr,return_code:R.content.return_code,content:(o=R.content.content)!=null?o:[]}}):R.content.type==="code_execution_tool_result_error"&&_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:R.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),result:R.content});break}case"tool_search_tool_result":{let A=k[R.tool_use_id];if(A==null){let M=m.toCustomToolName("tool_search_tool_bm25"),D=m.toCustomToolName("tool_search_tool_regex");M!=="tool_search_tool_bm25"?A="tool_search_tool_bm25":A="tool_search_tool_regex"}R.content.type==="tool_search_tool_search_result"?_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName(A),result:R.content.tool_references.map(M=>({type:M.type,toolName:M.tool_name}))}):_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName(A),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:R.content.error_code}});break}}return{content:_,finishReason:{unified:ute({finishReason:S.stop_reason,isJsonResponseFromTool:I}),raw:(s=S.stop_reason)!=null?s:void 0},usage:YOe({usage:S.usage}),request:{body:c},response:{id:(i=S.id)!=null?i:void 0,modelId:(a=S.model)!=null?a:void 0,headers:b,body:w},warnings:l,providerMetadata:(()=>{var R,A,M,D,B;let O={usage:S.usage,cacheCreationInputTokens:(R=S.usage.cache_creation_input_tokens)!=null?R:null,stopSequence:(A=S.stop_sequence)!=null?A:null,iterations:S.usage.iterations?S.usage.iterations.map(N=>({type:N.type,inputTokens:N.input_tokens,outputTokens:N.output_tokens})):null,container:S.container?{expiresAt:S.container.expires_at,id:S.container.id,skills:(D=(M=S.container.skills)==null?void 0:M.map(N=>({type:N.type,skillId:N.skill_id,version:N.version})))!=null?D:null}:null,contextManagement:(B=tNe(S.context_management))!=null?B:null},U={anthropic:O};return h&&f!=="anthropic"&&(U[f]=O),U})()}}async doStream(r){var e,t;let{args:n,warnings:o,betas:s,usesJsonResponseTool:i,toolNameMapping:a,providerOptionsName:c,usedCustomProviderKey:l}=await this.getArgs({...r,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(r.headers)}),u=[...this.extractCitationDocuments(r.prompt)],d=eNe(n.tools),m=this.buildRequestUrl(!0),{responseHeaders:f,value:h}=await jr({url:m,headers:await this.getHeaders({betas:s,headers:r.headers}),body:this.transformRequestBody(n,s),failedResponseHandler:KOe,successfulResponseHandler:hu(f9t),abortSignal:r.abortSignal,fetch:this.config.fetch}),y={unified:"other",raw:void 0},x={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},b={},S={},w={},_=null,C,k=null,I=null,R=null,A=!1,M,D=this.generateId,B=h.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:o})},transform($,L){var z,F,j,H,J,he,Y,ve,W,Ie,Me,ye,Q,oe;if(r.includeRawChunks&&L.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){L.enqueue({type:"error",error:$.error});return}let pe=$.value;switch(pe.type){case"ping":return;case"content_block_start":{let te=pe.content_block,Qe=te.type;switch(M=Qe,Qe){case"text":{if(i)return;b[pe.index]={type:"text"},L.enqueue({type:"text-start",id:String(pe.index)});return}case"thinking":{b[pe.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(pe.index)});return}case"redacted_thinking":{b[pe.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(pe.index),providerMetadata:{anthropic:{redactedData:te.data}}});return}case"compaction":{b[pe.index]={type:"text"},L.enqueue({type:"text-start",id:String(pe.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(i&&te.name==="json")A=!0,b[pe.index]={type:"text"},L.enqueue({type:"text-start",id:String(pe.index)});else{let je=te.caller,Ee=je?{type:je.type,toolId:"tool_id"in je?je.tool_id:void 0}:void 0,Xa=te.input&&Object.keys(te.input).length>0?JSON.stringify(te.input):"";b[pe.index]={type:"tool-call",toolCallId:te.id,toolName:te.name,input:Xa,firstDelta:Xa.length===0,...Ee&&{caller:Ee}},L.enqueue({type:"tool-input-start",id:te.id,toolName:te.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(te.name)){let nt=te.name==="text_editor_code_execution"||te.name==="bash_code_execution"?"code_execution":te.name,je=a.toCustomToolName(nt),Ee=te.input!=null&&typeof te.input=="object"&&Object.keys(te.input).length>0?JSON.stringify(te.input):"";b[pe.index]={type:"tool-call",toolCallId:te.id,toolName:je,input:Ee,providerExecuted:!0,...d&&nt==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:te.name},L.enqueue({type:"tool-input-start",id:te.id,toolName:je,providerExecuted:!0,...d&&nt==="code_execution"?{dynamic:!0}:{}})}else if(te.name==="tool_search_tool_regex"||te.name==="tool_search_tool_bm25"){w[te.id]=te.name;let nt=a.toCustomToolName(te.name);b[pe.index]={type:"tool-call",toolCallId:te.id,toolName:nt,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:te.name},L.enqueue({type:"tool-input-start",id:te.id,toolName:nt,providerExecuted:!0})}return}case"web_fetch_tool_result":{te.content.type==="web_fetch_result"?(u.push({title:(z=te.content.content.title)!=null?z:te.content.url,mediaType:te.content.content.source.media_type}),L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:te.content.url,retrievedAt:te.content.retrieved_at,content:{type:te.content.content.type,title:te.content.content.title,citations:te.content.content.citations,source:{type:te.content.content.source.type,mediaType:te.content.content.source.media_type,data:te.content.content.source.data}}}})):te.content.type==="web_fetch_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:te.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(te.content)){L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_search"),result:te.content.map(nt=>{var je;return{url:nt.url,title:nt.title,pageAge:(je=nt.page_age)!=null?je:null,encryptedContent:nt.encrypted_content,type:nt.type}})});for(let nt of te.content)L.enqueue({type:"source",sourceType:"url",id:D(),url:nt.url,title:nt.title,providerMetadata:{anthropic:{pageAge:(F=nt.page_age)!=null?F:null}}})}else L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:te.content.error_code}});return}case"code_execution_tool_result":{te.content.type==="code_execution_result"?L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:{type:te.content.type,stdout:te.content.stdout,stderr:te.content.stderr,return_code:te.content.return_code,content:(j=te.content.content)!=null?j:[]}}):te.content.type==="encrypted_code_execution_result"?L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:{type:te.content.type,encrypted_stdout:te.content.encrypted_stdout,stderr:te.content.stderr,return_code:te.content.return_code,content:(H=te.content.content)!=null?H:[]}}):te.content.type==="code_execution_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:te.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:te.content});return}case"tool_search_tool_result":{let nt=w[te.tool_use_id];if(nt==null){let je=a.toCustomToolName("tool_search_tool_bm25"),Ee=a.toCustomToolName("tool_search_tool_regex");je!=="tool_search_tool_bm25"?nt="tool_search_tool_bm25":nt="tool_search_tool_regex"}te.content.type==="tool_search_tool_search_result"?L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName(nt),result:te.content.tool_references.map(je=>({type:je.type,toolName:je.tool_name}))}):L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName(nt),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:te.content.error_code}});return}case"mcp_tool_use":{S[te.id]={type:"tool-call",toolCallId:te.id,toolName:te.name,input:JSON.stringify(te.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:te.server_name}}},L.enqueue(S[te.id]);return}case"mcp_tool_result":{L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:S[te.tool_use_id].toolName,isError:te.is_error,result:te.content,dynamic:!0,providerMetadata:S[te.tool_use_id].providerMetadata});return}default:{let nt=Qe;throw new Error(`Unsupported content block type: ${nt}`)}}}case"content_block_stop":{if(b[pe.index]!=null){let te=b[pe.index];switch(te.type){case"text":{L.enqueue({type:"text-end",id:String(pe.index)});break}case"reasoning":{L.enqueue({type:"reasoning-end",id:String(pe.index)});break}case"tool-call":if(!(i&&te.toolName==="json")){L.enqueue({type:"tool-input-end",id:te.toolCallId});let nt=te.input===""?"{}":te.input;if(te.providerToolName==="code_execution")try{let je=JSON.parse(nt);je!=null&&typeof je=="object"&&"code"in je&&!("type"in je)&&(nt=JSON.stringify({type:"programmatic-tool-call",...je}))}catch{}L.enqueue({type:"tool-call",toolCallId:te.toolCallId,toolName:te.toolName,input:nt,providerExecuted:te.providerExecuted,...d&&te.providerToolName==="code_execution"?{dynamic:!0}:{},...te.caller&&{providerMetadata:{anthropic:{caller:te.caller}}}})}break}delete b[pe.index]}M=void 0;return}case"content_block_delta":{let te=pe.delta.type;switch(te){case"text_delta":{if(i)return;L.enqueue({type:"text-delta",id:String(pe.index),delta:pe.delta.text});return}case"thinking_delta":{L.enqueue({type:"reasoning-delta",id:String(pe.index),delta:pe.delta.thinking});return}case"signature_delta":{M==="thinking"&&L.enqueue({type:"reasoning-delta",id:String(pe.index),delta:"",providerMetadata:{anthropic:{signature:pe.delta.signature}}});return}case"compaction_delta":{pe.delta.content!=null&&L.enqueue({type:"text-delta",id:String(pe.index),delta:pe.delta.content});return}case"input_json_delta":{let Qe=b[pe.index],nt=pe.delta.partial_json;if(nt.length===0)return;if(A){if(Qe?.type!=="text")return;L.enqueue({type:"text-delta",id:String(pe.index),delta:nt})}else{if(Qe?.type!=="tool-call")return;Qe.firstDelta&&(Qe.providerToolName==="bash_code_execution"||Qe.providerToolName==="text_editor_code_execution")&&(nt=`{"type": "${Qe.providerToolName}",${nt.substring(1)}`),L.enqueue({type:"tool-input-delta",id:Qe.toolCallId,delta:nt}),Qe.input+=nt,Qe.firstDelta=!1}return}case"citations_delta":{let Qe=pe.delta.citation,nt=QOe(Qe,u,D);nt&&L.enqueue(nt);return}default:{let Qe=te;throw new Error(`Unsupported delta type: ${Qe}`)}}}case"message_start":{if(x.input_tokens=pe.message.usage.input_tokens,x.cache_read_input_tokens=(J=pe.message.usage.cache_read_input_tokens)!=null?J:0,x.cache_creation_input_tokens=(he=pe.message.usage.cache_creation_input_tokens)!=null?he:0,C={...pe.message.usage},k=(Y=pe.message.usage.cache_creation_input_tokens)!=null?Y:null,pe.message.container!=null&&(R={expiresAt:pe.message.container.expires_at,id:pe.message.container.id,skills:null}),pe.message.stop_reason!=null&&(y={unified:ute({finishReason:pe.message.stop_reason,isJsonResponseFromTool:A}),raw:pe.message.stop_reason}),L.enqueue({type:"response-metadata",id:(ve=pe.message.id)!=null?ve:void 0,modelId:(W=pe.message.model)!=null?W:void 0}),pe.message.content!=null)for(let te=0;te<pe.message.content.length;te++){let Qe=pe.message.content[te];if(Qe.type==="tool_use"){let nt=Qe.caller,je=nt?{type:nt.type,toolId:"tool_id"in nt?nt.tool_id:void 0}:void 0;L.enqueue({type:"tool-input-start",id:Qe.id,toolName:Qe.name});let Ee=JSON.stringify((Ie=Qe.input)!=null?Ie:{});L.enqueue({type:"tool-input-delta",id:Qe.id,delta:Ee}),L.enqueue({type:"tool-input-end",id:Qe.id}),L.enqueue({type:"tool-call",toolCallId:Qe.id,toolName:Qe.name,input:Ee,...je&&{providerMetadata:{anthropic:{caller:je}}}})}}return}case"message_delta":{pe.usage.input_tokens!=null&&x.input_tokens!==pe.usage.input_tokens&&(x.input_tokens=pe.usage.input_tokens),x.output_tokens=pe.usage.output_tokens,pe.usage.cache_read_input_tokens!=null&&(x.cache_read_input_tokens=pe.usage.cache_read_input_tokens),pe.usage.cache_creation_input_tokens!=null&&(x.cache_creation_input_tokens=pe.usage.cache_creation_input_tokens,k=pe.usage.cache_creation_input_tokens),pe.usage.iterations!=null&&(x.iterations=pe.usage.iterations),y={unified:ute({finishReason:pe.delta.stop_reason,isJsonResponseFromTool:A}),raw:(Me=pe.delta.stop_reason)!=null?Me:void 0},I=(ye=pe.delta.stop_sequence)!=null?ye:null,R=pe.delta.container!=null?{expiresAt:pe.delta.container.expires_at,id:pe.delta.container.id,skills:(oe=(Q=pe.delta.container.skills)==null?void 0:Q.map(te=>({type:te.type,skillId:te.skill_id,version:te.version})))!=null?oe:null}:null,pe.context_management&&(_=tNe(pe.context_management)),C={...C,...pe.usage};return}case"message_stop":{let te={usage:C??null,cacheCreationInputTokens:k,stopSequence:I,iterations:x.iterations?x.iterations.map(nt=>({type:nt.type,inputTokens:nt.input_tokens,outputTokens:nt.output_tokens})):null,container:R,contextManagement:_},Qe={anthropic:te};l&&c!=="anthropic"&&(Qe[c]=te),L.enqueue({type:"finish",finishReason:y,usage:YOe({usage:x,rawUsage:C}),providerMetadata:Qe});return}case"error":{L.enqueue({type:"error",error:pe.error});return}default:{let te=pe;throw new Error(`Unsupported chunk type: ${te}`)}}}})),[O,U]=B.tee(),N=O.getReader();try{await N.read();let $=await N.read();if(((e=$.value)==null?void 0:e.type)==="raw"&&($=await N.read()),((t=$.value)==null?void 0:t.type)==="error"){let L=$.value.error;throw new xr({message:L.message,url:m,requestBodyValues:n,statusCode:L.type==="overloaded_error"?529:500,responseHeaders:f,responseBody:JSON.stringify(L),isRetryable:L.type==="overloaded_error"})}}finally{N.cancel().catch(()=>{}),N.releaseLock()}return{stream:U,request:{body:n},response:{headers:f}}}};oXt=ae(()=>se(p.object({command:p.string(),restart:p.boolean().optional()}))),sXt=xo({id:"anthropic.bash_20241022",inputSchema:oXt}),iXt=ae(()=>se(p.object({command:p.string(),restart:p.boolean().optional()}))),aXt=xo({id:"anthropic.bash_20250124",inputSchema:iXt}),cXt=ae(()=>se(p.object({action:p.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:p.array(p.number().int()).optional(),text:p.string().optional()}))),lXt=xo({id:"anthropic.computer_20241022",inputSchema:cXt}),uXt=ae(()=>se(p.object({action:p.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),duration:p.number().optional(),scroll_amount:p.number().optional(),scroll_direction:p.enum(["up","down","left","right"]).optional(),start_coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),text:p.string().optional()}))),dXt=xo({id:"anthropic.computer_20250124",inputSchema:uXt}),pXt=ae(()=>se(p.object({action:p.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),duration:p.number().optional(),region:p.tuple([p.number().int(),p.number().int(),p.number().int(),p.number().int()]).optional(),scroll_amount:p.number().optional(),scroll_direction:p.enum(["up","down","left","right"]).optional(),start_coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),text:p.string().optional()}))),mXt=xo({id:"anthropic.computer_20251124",inputSchema:pXt}),fXt=ae(()=>se(p.discriminatedUnion("command",[p.object({command:p.literal("view"),path:p.string(),view_range:p.tuple([p.number(),p.number()]).optional()}),p.object({command:p.literal("create"),path:p.string(),file_text:p.string()}),p.object({command:p.literal("str_replace"),path:p.string(),old_str:p.string(),new_str:p.string()}),p.object({command:p.literal("insert"),path:p.string(),insert_line:p.number(),insert_text:p.string()}),p.object({command:p.literal("delete"),path:p.string()}),p.object({command:p.literal("rename"),old_path:p.string(),new_path:p.string()})]))),gXt=xo({id:"anthropic.memory_20250818",inputSchema:fXt}),hXt=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert","undo_edit"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),yXt=xo({id:"anthropic.text_editor_20241022",inputSchema:hXt}),xXt=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert","undo_edit"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),vXt=xo({id:"anthropic.text_editor_20250124",inputSchema:xXt}),bXt=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),TXt=xo({id:"anthropic.text_editor_20250429",inputSchema:bXt}),SXt=ae(()=>se(p.array(p.object({type:p.literal("tool_reference"),toolName:p.string()})))),wXt=ae(()=>se(p.object({query:p.string(),limit:p.number().optional()}))),EXt=Zt({id:"anthropic.tool_search_bm25_20251119",inputSchema:wXt,outputSchema:SXt,supportsDeferredResults:!0}),_Xt=(r={})=>EXt(r),CXt={bash_20241022:sXt,bash_20250124:aXt,codeExecution_20250522:G9t,codeExecution_20250825:H9t,codeExecution_20260120:K9t,computer_20241022:lXt,computer_20250124:dXt,computer_20251124:mXt,memory_20250818:gXt,textEditor_20241022:yXt,textEditor_20250124:vXt,textEditor_20250429:TXt,textEditor_20250728:b9t,webFetch_20250910:F9t,webFetch_20260209:N9t,webSearch_20250305:A9t,webSearch_20260209:_9t,toolSearchRegex_20251119:Z9t,toolSearchBm25_20251119:_Xt};kXt=cP()});var fte={};K(fte,{AsyncLocalStorage:()=>qXt,Buffer:()=>LYt,Channel:()=>_Yt,DatabaseSync:()=>DYt,Duplex:()=>KXt,EventEmitter:()=>HXt,Http2ServerRequest:()=>zYt,Http2ServerResponse:()=>GYt,Interface:()=>NYt,MIMEType:()=>KYt,PassThrough:()=>JXt,PerformanceObserver:()=>SYt,Readable:()=>uNe,ReadableStream:()=>XXt,Resolver:()=>bYt,TextDecoder:()=>mNe,TextEncoder:()=>UG,Transform:()=>WXt,URL:()=>aYt,URLSearchParams:()=>cYt,Worker:()=>AYt,Writable:()=>dNe,access:()=>EZt,appendFile:()=>nZt,appendFileSync:()=>OXt,arch:()=>BZt,arrayBuffer:()=>jYt,basename:()=>FXt,builtinModules:()=>nYt,callbackify:()=>gYt,channel:()=>EYt,chmodSync:()=>rZt,clearInterval:()=>WYt,clearTimeout:()=>HYt,closeSync:()=>aZt,connect:()=>VZt,constants:()=>UYt,copyFileSync:()=>sZt,cpSync:()=>NXt,cpus:()=>LZt,createConnection:()=>HZt,createGunzip:()=>YZt,createGzip:()=>QZt,createHash:()=>cNe,createHmac:()=>AXt,createInterface:()=>OYt,createReadStream:()=>yZt,createRequire:()=>rYt,createServer:()=>lNe,createWriteStream:()=>hZt,debug:()=>mYt,debuglog:()=>pNe,default:()=>mte,deflateSync:()=>WZt,deprecate:()=>fYt,deserialize:()=>RYt,dirname:()=>UXt,exec:()=>RZt,execFile:()=>IZt,execFileSync:()=>PZt,execSync:()=>AZt,existsSync:()=>QXt,extname:()=>$Xt,fileURLToPath:()=>lYt,finished:()=>YXt,format:()=>iYt,freemem:()=>UZt,fstatSync:()=>cZt,get:()=>jZt,gunzip:()=>ZZt,gunzipSync:()=>KZt,gzip:()=>XZt,gzipSync:()=>JZt,hasSubscribers:()=>CYt,homedir:()=>OZt,hostname:()=>DZt,inflateSync:()=>qZt,inherits:()=>dYt,inspect:()=>FG,isAbsolute:()=>zXt,isBuiltin:()=>oYt,isDeepStrictEqual:()=>hYt,isIP:()=>BYt,isIPv4:()=>$Yt,isIPv6:()=>FYt,isMainThread:()=>IYt,join:()=>DXt,lookup:()=>vYt,mkdir:()=>bZt,mkdirSync:()=>lZt,monitorEventLoopDelay:()=>wYt,normalize:()=>VXt,ok:()=>eYt,openSync:()=>iZt,parentPort:()=>PYt,parse:()=>sYt,pathToFileURL:()=>uYt,performance:()=>TYt,pipeline:()=>ZXt,platform:()=>MZt,posix:()=>jXt,promises:()=>RXt,promisify:()=>pYt,randomBytes:()=>IXt,randomUUID:()=>PXt,readFile:()=>xZt,readFileSync:()=>eZt,readdir:()=>SZt,readdirSync:()=>dZt,realpathSync:()=>oZt,relative:()=>BXt,release:()=>zZt,rename:()=>_Zt,renameSync:()=>mZt,request:()=>GZt,resolve:()=>LXt,rm:()=>CZt,rmSync:()=>gZt,rmdirSync:()=>fZt,sep:()=>GXt,serialize:()=>kYt,setInterval:()=>qYt,setTimeout:()=>VYt,spawn:()=>kZt,stat:()=>TZt,statSync:()=>uZt,strict:()=>tYt,tmpdir:()=>NZt,toUSVString:()=>yYt,totalmem:()=>FZt,type:()=>$Zt,types:()=>xYt,unlink:()=>wZt,unlinkSync:()=>pZt,webcrypto:()=>MXt,workerData:()=>MYt,writeFile:()=>vZt,writeFileSync:()=>tZt});var Do,js,mte,RXt,cNe,AXt,IXt,PXt,MXt,OXt,NXt,lNe,DXt,LXt,UXt,FXt,$Xt,BXt,zXt,GXt,jXt,VXt,HXt,qXt,uNe,dNe,WXt,KXt,JXt,XXt,ZXt,YXt,QXt,eZt,tZt,rZt,nZt,oZt,sZt,iZt,aZt,cZt,lZt,uZt,dZt,pZt,mZt,fZt,gZt,hZt,yZt,xZt,vZt,bZt,TZt,SZt,wZt,EZt,_Zt,CZt,kZt,RZt,AZt,IZt,PZt,MZt,OZt,NZt,DZt,LZt,UZt,FZt,$Zt,BZt,zZt,GZt,jZt,VZt,HZt,qZt,WZt,KZt,JZt,XZt,ZZt,YZt,QZt,eYt,tYt,rYt,nYt,oYt,sYt,iYt,aYt,cYt,lYt,uYt,dYt,pYt,pNe,mYt,FG,fYt,gYt,hYt,yYt,xYt,mNe,UG,vYt,bYt,TYt,SYt,wYt,EYt,_Yt,CYt,kYt,RYt,AYt,IYt,PYt,MYt,OYt,NYt,DYt,LYt,UYt,FYt,$Yt,BYt,zYt,GYt,jYt,fNe,VYt,HYt,qYt,WYt,KYt,lP=E(()=>{Do=()=>{},js=async()=>{},mte={},RXt={readFile:js,writeFile:js,mkdir:js,stat:js,readdir:js,unlink:js,access:js,rm:js,rename:js},cNe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new UG().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},AXt=(r,e)=>cNe(r),IXt=r=>new Uint8Array(r||32),PXt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),MXt=globalThis.crypto,OXt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},NXt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},lNe=()=>({listen:Do,close:Do,on:Do}),DXt=(...r)=>r.join("/"),LXt=(...r)=>r.join("/"),UXt=r=>r||"",FXt=r=>r?.split?.("/")?.pop?.()||"",$Xt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},BXt=(r,e)=>e||"",zXt=()=>!1,GXt="/",jXt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},VXt=r=>r,HXt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},qXt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},uNe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},dNe=class{write(){return!0}end(){}on(){return this}destroy(){}},WXt=class{push(){}on(){return this}},KXt=class{on(){return this}},JXt=class{pipe(){return this}on(){return this}},XXt=globalThis.ReadableStream||class{},ZXt=Do,YXt=Do,QXt=()=>!1,eZt=()=>"",tZt=Do,rZt=Do,nZt=js,oZt=r=>r,sZt=Do,iZt=()=>0,aZt=Do,cZt=()=>({}),lZt=Do,uZt=()=>({}),dZt=()=>[],pZt=Do,mZt=Do,fZt=Do,gZt=Do,hZt=()=>new dNe,yZt=()=>new uNe,xZt=js,vZt=js,bZt=js,TZt=js,SZt=js,wZt=js,EZt=js,_Zt=js,CZt=js,kZt=()=>({on:Do,stdout:{on:Do},stderr:{on:Do},kill:Do}),RZt=(r,e)=>e?.(null,"",""),AZt=()=>"",IZt=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},PZt=()=>"",MZt="browser",OZt=()=>"/",NZt=()=>"/tmp",DZt=()=>"browser",LZt=()=>[{}],UZt=()=>0,FZt=()=>0,$Zt=()=>"Browser",BZt=()=>"wasm",zZt=()=>"0",GZt=()=>({}),jZt=()=>({}),VZt=()=>({}),HZt=()=>({}),qZt=()=>new Uint8Array,WZt=()=>new Uint8Array,KZt=()=>new Uint8Array,JZt=()=>new Uint8Array,XZt=(r,e)=>e?.(null,r),ZZt=(r,e)=>e?.(null,r),YZt=()=>({}),QZt=()=>({}),eYt=Do,tYt={},rYt=()=>()=>({}),nYt=[],oYt=()=>!1,sYt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),iYt=()=>"",aYt=globalThis.URL,cYt=globalThis.URLSearchParams,lYt=r=>typeof r=="string"?r.replace("file://",""):r,uYt=r=>new globalThis.URL("file://"+r),dYt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},pYt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),pNe=r=>{let e=(...t)=>{};return e.enabled=!1,e},mYt=pNe,FG=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};FG.custom=Symbol.for("nodejs.util.inspect.custom");FG.colors={};FG.styles={};fYt=r=>r,gYt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},hYt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),yYt=r=>String(r),xYt={isPromise:r=>r instanceof Promise,isDate:r=>r instanceof Date,isRegExp:r=>r instanceof RegExp,isNativeError:r=>r instanceof Error,isArrayBuffer:r=>r instanceof ArrayBuffer,isTypedArray:r=>ArrayBuffer.isView(r),isUint8Array:r=>r instanceof Uint8Array,isProxy:()=>!1},mNe=globalThis.TextDecoder,UG=globalThis.TextEncoder,vYt=(r,e)=>e?.(null,"127.0.0.1",4),bYt=class{},TYt=globalThis.performance||{now:()=>Date.now()},SYt=class{observe(){}disconnect(){}},wYt=()=>({enable:Do,disable:Do,percentile:()=>0}),EYt=()=>({}),_Yt=class{},CYt=()=>!1,kYt=()=>new Uint8Array,RYt=Do,AYt=class{},IYt=!0,PYt=null,MYt=null,OYt=()=>({}),NYt=class{},DYt=class{},LYt=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new UG().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new UG().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new mNe().decode(this)}},UYt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},FYt=()=>!1,$Yt=()=>!1,BYt=()=>0,zYt=class{},GYt=class{},jYt=async()=>new ArrayBuffer(0),fNe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),VYt=(...r)=>fNe(globalThis.setTimeout(...r)),HYt=globalThis.clearTimeout,qYt=(...r)=>fNe(globalThis.setInterval(...r)),WYt=globalThis.clearInterval,KYt=class{constructor(r){this.type=r}toString(){return this.type}}});function gNe(r){return yY("sha256",QYt).update(r).digest("hex")}function e7t(r){let e=r.replace(/-/g,"").slice(0,32).padEnd(32,"0");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}function uP(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r)}function $G(r){return JSON.stringify({device_id:r.deviceId,account_uuid:r.accountUuid,session_id:r.sessionId})}function gte(r){if(typeof r!="string")return null;try{let e=JSON.parse(r);return typeof e.device_id!="string"||!/^[0-9a-f]{64}$/i.test(e.device_id)||typeof e.account_uuid!="string"||!uP(e.account_uuid)||typeof e.session_id!="string"||!uP(e.session_id)?null:{deviceId:e.device_id,accountUuid:e.account_uuid,sessionId:e.session_id,metadataUserId:$G({deviceId:e.device_id,accountUuid:e.account_uuid,sessionId:e.session_id})}}catch{return null}}function BG(r,e){let t=gte(e?.existingUserId);if(t)return e?.preferredSessionId&&uP(e.preferredSessionId)?{deviceId:t.deviceId,accountUuid:t.accountUuid,sessionId:e.preferredSessionId,metadataUserId:$G({deviceId:t.deviceId,accountUuid:t.accountUuid,sessionId:e.preferredSessionId})}:t;let n=Date.now(),o=r||"default",s=Lv.get(o);if(s&&s.expiresAt>n)return e?.preferredSessionId&&uP(e.preferredSessionId)?{deviceId:s.deviceId,accountUuid:s.accountUuid,sessionId:e.preferredSessionId,metadataUserId:$G({deviceId:s.deviceId,accountUuid:s.accountUuid,sessionId:e.preferredSessionId})}:s;let i=gNe(`${o}:device`),a=e7t(gNe(`${o}:account`)),c=e?.preferredSessionId&&uP(e.preferredSessionId)?e.preferredSessionId:Fe(),l={deviceId:i,accountUuid:a,sessionId:c,metadataUserId:$G({deviceId:i,accountUuid:a,sessionId:c}),expiresAt:n+ZYt};return r7t(n),Lv.set(o,l),l}function t7t(r=Date.now()){let e=0;for(let[t,n]of Lv.entries())n.expiresAt<=r&&(Lv.delete(t),e+=1);return e}function r7t(r=Date.now()){for(t7t(r);Lv.size>=YYt;){let e=Lv.keys().next().value;if(!e)break;Lv.delete(e)}}function RE(r){let e=r?.match(/cc_version=([^;]+)/)?.[1]?.trim()||JYt,t=r?.match(/cc_entrypoint=([^;]+)/)?.[1]?.trim()||XYt;return`x-anthropic-billing-header: cc_version=${e}; cc_entrypoint=${t}; cch=00000;`}var hNe,yNe,JYt,XYt,kE,ZYt,YYt,QYt,Lv,Uv,hte,zG=E(()=>{"use strict";ir();lP();hNe="9d1c250a-e61b-44d9-88ed-5944d1962f5e",yNe="https://api.anthropic.com/v1/oauth/token",JYt="2.1.87.6d6",XYt="sdk-cli",kE="claude-cli/2.1.87 (external, sdk-cli)",ZYt=36e5,YYt=1024,QYt="neurolink-claude-code-identity-v1",Lv=new Map;Uv=["oauth-2025-04-20","claude-code-20250219","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advanced-tool-use-2025-11-20","effort-2025-11-24"],hte="mcp_"});function i7t(){return Object.values(xNe)}function dP(r,e){let t=n7t[e];return t.includes("*")?i7t().includes(r):t.includes(r)}function a7t(r){return s7t[r]}function c7t(r){return o7t[r]}var xNe,n7t,o7t,s7t,GG,jG,yte=E(()=>{"use strict";mt();xNe=(l=>(l.CLAUDE_3_HAIKU="claude-3-haiku-20240307",l.CLAUDE_3_5_HAIKU="claude-3-5-haiku-20241022",l.CLAUDE_3_5_SONNET="claude-3-5-sonnet-20241022",l.CLAUDE_3_5_SONNET_V2="claude-3-5-sonnet-v2-20241022",l.CLAUDE_SONNET_4="claude-sonnet-4-20250514",l.CLAUDE_SONNET_4_6="claude-sonnet-4-6",l.CLAUDE_3_OPUS="claude-3-opus-20240229",l.CLAUDE_OPUS_4="claude-opus-4-20250514",l.CLAUDE_OPUS_4_6="claude-opus-4-6",l))(xNe||{}),n7t={free:["claude-3-haiku-20240307","claude-3-5-haiku-20241022"],pro:["claude-3-haiku-20240307","claude-3-5-haiku-20241022","claude-3-5-sonnet-20241022","claude-3-5-sonnet-v2-20241022","claude-sonnet-4-20250514","claude-sonnet-4-6"],max:["*"],max_5:["*"],max_20:["*"],api:["*"]},o7t={"claude-3-haiku-20240307":{displayName:"Claude 3 Haiku",contextWindow:2e5,maxOutputTokens:4096,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!0,family:"haiku",description:"Fast and efficient model for simple tasks"},"claude-3-5-haiku-20241022":{displayName:"Claude 3.5 Haiku",contextWindow:2e5,maxOutputTokens:8192,supportsVision:!1,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"haiku",description:"Improved fast model with better performance"},"claude-3-5-sonnet-20241022":{displayName:"Claude 3.5 Sonnet",contextWindow:2e5,maxOutputTokens:8192,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Balanced model for most tasks"},"claude-3-5-sonnet-v2-20241022":{displayName:"Claude 3.5 Sonnet V2",contextWindow:2e5,maxOutputTokens:8192,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Updated Sonnet with improved capabilities"},"claude-sonnet-4-20250514":{displayName:"Claude Sonnet 4",contextWindow:2e5,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Latest Sonnet with extended thinking support"},"claude-3-opus-20240229":{displayName:"Claude 3 Opus",contextWindow:2e5,maxOutputTokens:4096,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!0,family:"opus",description:"Legacy flagship model for complex tasks"},"claude-opus-4-20250514":{displayName:"Claude Opus 4",contextWindow:2e5,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"opus",description:"Latest flagship model with advanced reasoning"},"claude-sonnet-4-6":{displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Claude 4.6 Sonnet with 1M context window"},"claude-opus-4-6":{displayName:"Claude Opus 4.6",contextWindow:1e6,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"opus",description:"Claude 4.6 Opus flagship with 1M context window"}},s7t={free:"claude-3-5-haiku-20241022",pro:"claude-sonnet-4-20250514",max:"claude-opus-4-20250514",max_5:"claude-opus-4-20250514",max_20:"claude-opus-4-20250514",api:"claude-sonnet-4-20250514"};GG=a7t,jG=c7t});function l7t(r){try{if(typeof r=="string"||r instanceof URL)return new URL(r.toString());if(r instanceof Request)return new URL(r.url)}catch{return null}return null}function u7t(r,e){let t=new Headers;if(r instanceof Request&&r.headers.forEach((n,o)=>{t.set(o,n)}),!e?.headers)return t;if(e.headers instanceof Headers)return e.headers.forEach((n,o)=>{t.set(o,n)}),t;if(Array.isArray(e.headers)){for(let[n,o]of e.headers)typeof o<"u"&&t.set(n,String(o));return t}for(let[n,o]of Object.entries(e.headers))typeof o<"u"&&t.set(n,String(o));return t}function d7t(r,e,t,n){let o=(r.get("anthropic-beta")??"").split(",").map(i=>i.trim()).filter(Boolean),s=["oauth-2025-04-20"];n||s.push(...t?Uv.filter(i=>i!=="oauth-2025-04-20"):[]),r.set("authorization",`Bearer ${e()}`),r.set("anthropic-beta",[...new Set([...o,...s])].join(",")),r.delete("x-api-key"),!n&&(r.set("user-agent",kE),r.set("anthropic-version","2023-06-01"),r.set("accept","application/json"),r.set("anthropic-dangerous-direct-browser-access","true"),r.set("x-app","cli"),r.set("connection","keep-alive"),r.set("x-stainless-retry-count","0"),r.set("x-stainless-runtime-version","v24.3.0"),r.set("x-stainless-package-version","0.74.0"),r.set("x-stainless-runtime","node"),r.set("x-stainless-lang","js"),r.set("x-stainless-arch",process.arch==="x64"?"x64":process.arch),r.set("x-stainless-os",process.platform==="darwin"?"MacOS":process.platform==="win32"?"Windows":"Linux"),r.set("x-stainless-timeout","600"))}async function p7t(r,e){let t=r instanceof Request?r:void 0,n=e?.method??t?.method,o=e?.body;return o===void 0&&t&&n!=="GET"&&n!=="HEAD"&&((t.headers.get("content-type")??"").includes("application/json")?o=await t.clone().text()||void 0:o=t.clone().body??void 0),{sourceRequest:t,method:n,body:o??void 0}}function m7t(r,e,t,n){let o=JSON.parse(r);n&&(o.tools&&Array.isArray(o.tools)&&(o.tools=o.tools.map(l=>({...l,name:l.name?`${hte}${l.name}`:l.name}))),o.messages&&Array.isArray(o.messages)&&(o.messages=o.messages.map(l=>(l.content&&Array.isArray(l.content)&&(l.content=l.content.map(u=>{let d=u;return d.type==="tool_use"&&d.name?{...d,name:`${hte}${d.name}`}:u})),l)))),(o.tool_choice?.type==="any"||o.tool_choice?.type==="tool")&&delete o.thinking;let s={type:"text",text:"You are a Claude agent, built on Anthropic's Claude Agent SDK."};if(o.system){if(typeof o.system=="string"&&(o.system=[{type:"text",text:o.system}]),Array.isArray(o.system)){let l=o.system.findIndex(f=>typeof f.text=="string"&&f.text.includes("x-anthropic-billing-header")),u=o.system.findIndex(f=>typeof f.text=="string"&&f.text.includes("Claude Agent SDK")),d={type:"text",text:RE(o.system[l]?.text)},m=[l,u].filter(f=>f>=0).sort((f,h)=>h-f);for(let f of m)o.system.splice(f,1);o.system=[...o.system,d,s]}}else{let l={type:"text",text:RE()};o.system=[l,s]}let i=t(),a=o.metadata?.user_id??i.substring(0,Math.min(20,i.length)),c=BG(a,{existingUserId:o.metadata?.user_id,preferredSessionId:e.get("x-claude-code-session-id")??void 0});return o.metadata={...o.metadata,user_id:c.metadataUserId},e.set("x-claude-code-session-id",c.sessionId),JSON.stringify(o)}async function f7t(r){try{let{propagation:e,context:t}=await Promise.resolve().then(()=>(hr(),Y3)),n={};e.inject(t.active(),n);for(let[o,s]of Object.entries(n))r.has(o)||r.set(o,s)}catch{}}function g7t(r){if(!r.body)return r;let e=r.body.getReader(),t=new TextDecoder,n=new TextEncoder,o=new Headers(r.headers);o.delete("content-length");let s="",i=new ReadableStream({async pull(a){let{done:c,value:l}=await e.read();if(c){s&&(a.enqueue(n.encode(s.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,'"name": "$1"'))),s=""),a.close();return}let u=t.decode(l,{stream:!0}),d=s+u,m=d.match(/"name"\s*:\s*"mcp_[^"]*$/),f;if(m&&m.index!==void 0)f=d.slice(0,m.index),s=d.slice(m.index);else{let y=d.lastIndexOf('"'),x=y>=0?y+1:d.length;f=d.slice(0,x),s=d.slice(x)}let h=f.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,'"name": "$1"');h&&a.enqueue(n.encode(h))},async cancel(a){await e.cancel(a)}});return new Response(i,{status:r.status,statusText:r.statusText,headers:o})}async function h7t(r,e,t,n,o,s){let i=l7t(r);i&&i.pathname==="/v1/messages"&&!i.searchParams.has("beta")&&i.searchParams.set("beta","true");let a=u7t(r,e);d7t(a,t,n,s),g.debug("[createOAuthFetch] Making OAuth request:",{url:i?.toString()||r.toString(),hasAuthorization:a.has("authorization"),authType:"Bearer",anthropicBeta:a.get("anthropic-beta"),userAgent:a.get("user-agent")});let{sourceRequest:c,method:l,body:u}=await p7t(r,e),d=u;if(d&&typeof d=="string"&&!s)try{d=m7t(d,a,t,o)}catch{}a.delete("content-length"),await f7t(a);let f=await Ze()(i?.toString()||(r instanceof Request?r.url:r.toString()),{...e,method:l,body:d,signal:e?.signal??c?.signal,headers:a});return o?g7t(f):f}function vNe(r,e=!0,t=!1,n=!1){return async(o,s)=>h7t(o,s,r,e,t,n)}var bNe=E(()=>{"use strict";zG();V();Vn()});var wNe={};K(wNe,{ANTHROPIC_BETA_HEADERS:()=>vte,AnthropicProvider:()=>VG,ModelAccessError:()=>_R,default:()=>T7t,getModelCapabilities:()=>jG,getRecommendedModelForTier:()=>GG,isModelAvailableForTier:()=>dP});var vte,TNe,xte,y7t,SNe,x7t,v7t,b7t,VG,T7t,ENe=E(()=>{"use strict";pte();hr();wn();dd();dn();zG();ql();oi();yte();bNe();Vn();mt();V();Ed();Nn();Rn();ite();yA();tY();vS();Bg();yte();vte={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")},TNe=()=>er(QMe()),xte=()=>tr("ANTHROPIC_MODEL","claude-sonnet-4-6"),y7t=it.getTracer("neurolink.provider.anthropic"),SNe=()=>{try{let e=Tr(dp(),".neurolink","anthropic-credentials.json");if(Sn(e)){let t=Ac(e,"utf-8"),n=JSON.parse(t);if(n.type==="oauth"&&n.oauth?.accessToken)return g.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(e){g.debug("[AnthropicProvider] Failed to read stored credentials:",e)}let r=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!r)return null;try{let e=JSON.parse(r);if(typeof e=="object"&&e.accessToken)return e;if(typeof e=="string")return{accessToken:e}}catch{}return{accessToken:r}},x7t=r=>{let e=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(e){let t=["free","pro","max","max_5","max_20","api"];if(t.includes(e))return g.debug("[detectSubscriptionTier] Using environment override",{tier:e}),e;g.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:e,validTiers:t})}if(r){let t=r.scopes??[],n="pro";return t.includes("max_20")?n="max_20":t.includes("max_5")?n="max_5":t.includes("max")&&(n="max"),g.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:t}),n}return g.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},v7t=r=>{let e=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(e==="api_key"||e==="apikey")return g.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(e==="oauth"){if(r)return g.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";g.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else e&&g.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:e});let t=r?"oauth":"api_key";return g.debug("[detectAuthMethod] Auth method resolved",{method:t,hasOAuthToken:!!r}),t},b7t=r=>{let e=n=>r instanceof Headers?r.get(n):r[n]||r[n.toLowerCase()]||null,t=n=>{if(!n)return;let o=parseInt(n,10);return isNaN(o)?void 0:o};return{requestsLimit:t(e("anthropic-ratelimit-requests-limit")),requestsRemaining:t(e("anthropic-ratelimit-requests-remaining")),requestsReset:e("anthropic-ratelimit-requests-reset")||void 0,tokensLimit:t(e("anthropic-ratelimit-tokens-limit")),tokensRemaining:t(e("anthropic-ratelimit-tokens-remaining")),tokensReset:e("anthropic-ratelimit-tokens-reset")||void 0,retryAfter:t(e("retry-after"))}},VG=class extends Mn{model;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,n,o){let s=!!(o?.apiKey&&!o?.oauthToken),i=s?null:(o?.oauthToken?{accessToken:o.oauthToken}:null)??n?.oauthToken??SNe(),a=s?"api_key":n?.authMethod??v7t(i),c=n?.subscriptionTier??(a==="oauth"?x7t(i):"api"),l=e||xte(),u=l;!process.env.ANTHROPIC_BASE_URL&&c!=="api"&&!dP(l,c)&&(u=GG(c),g.warn("Model not available for subscription tier, using recommended model",{requestedModel:l,subscriptionTier:c,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=n?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=c,this.authMethod=a;let m=this.getAuthHeaders(),f;if(g.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){g.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");let h=this.oauthToken,y=vNe(()=>h.accessToken,this.enableBetaFeatures,!1,!0);f=cP({apiKey:"oauth-authenticated",fetch:y}),g.debug("[AnthropicProvider] Anthropic SDK created with OAuth fetch wrapper"),g.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{let h=o?.apiKey??n?.apiKey??TNe(),y=(()=>{let x=process.env.ANTHROPIC_BASE_URL;if(!x)return;let b=x.replace(/\/+$/,"");return/\/v\d+$/.test(b)?b:(g.warn("[AnthropicProvider] ANTHROPIC_BASE_URL does not end with /vN; appending /v1 so the Vercel AI SDK can build /messages correctly. To silence this warning, set ANTHROPIC_BASE_URL with an explicit version segment (e.g. https://api.anthropic.com/v1). If your proxy exposes Anthropic at a custom path that doesn't expose /v1/messages, the auto-append will produce a 404 \u2014 pass the full path including the version explicitly.",{baseURL:x,rewrittenTo:`${b}/v1`}),`${b}/v1`)})();f=cP({apiKey:h,headers:m,...y&&{baseURL:y},fetch:Ze()}),g.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.model=f(this.modelName||xte()),this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},g.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?vte["anthropic-beta"]:"disabled"})}getAuthHeaders(){let e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){let n=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",o=[...Uv,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];n&&o.push("context-1m-2025-08-07"),e["anthropic-beta"]=o.join(",")}else e["anthropic-beta"]=vte["anthropic-beta"];return this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return g.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;let t=dP(e,this.subscriptionTier);return t||g.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return jG(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){g.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){g.debug("Token has no expiry information, assuming valid");return}let e=Date.now(),t=this.oauthToken.expiresAt<=e,n=this.oauthToken.expiresAt<=e+3e5;if(!t&&!n){g.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new ut("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);g.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}g.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});let o=this.oauthToken,s=o.refreshToken;this.refreshPromise=(async()=>{let a=new AbortController,c=setTimeout(()=>a.abort(),3e4),l=await fetch(yNe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":kE},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:s,client_id:hNe}),signal:a.signal});if(clearTimeout(c),!l.ok){let m=await l.text();throw new ut(`Failed to refresh OAuth token: ${l.status} ${m}`,this.providerName)}let u=await l.json();o.accessToken=u.access_token,o.refreshToken=u.refresh_token||o.refreshToken,o.expiresAt=u.expires_in?Date.now()+u.expires_in*1e3:void 0,o.tokenType=u.token_type||"Bearer";let d=o;try{let m=Tr(dp(),".neurolink");Sn(m)||jk(m,{recursive:!0});let f=Tr(m,"anthropic-credentials.json"),h=`${f}.tmp`,x={...Sn(f)?JSON.parse(Ac(f,"utf-8")):{},type:"oauth",oauth:d,updatedAt:Date.now()};Gk(h,JSON.stringify(x,null,2),{mode:384}),cK(h,f),g.debug("Refreshed OAuth credentials persisted to disk")}catch(m){g.warn("Failed to persist refreshed OAuth token to disk",{error:m instanceof Error?m.message:String(m)})}g.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!u.refresh_token,expiresIn:u.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof ut?i:new ut(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,n){this.lastResponseMetadata={rateLimit:b7t(e),requestId:t||(e instanceof Headers?e.get("x-request-id")||void 0:e["x-request-id"]),serverTiming:e instanceof Headers?e.get("server-timing")||void 0:e["server-timing"]};let o=this.lastResponseMetadata.rateLimit;this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),n&&(n.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=n.inputTokens,this.usageInfo.tokensUsed+=n.inputTokens),n.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=n.outputTokens,this.usageInfo.tokensUsed+=n.outputTokens)),o?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=o.requestsRemaining),o?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=o.tokensRemaining),o?.requestsLimit&&o.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((o.requestsLimit-(o.requestsRemaining??0))/o.requestsLimit*100)),o?.tokensLimit&&o.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((o.tokensLimit-(o.tokensRemaining??0))/o.tokensLimit*100)),o?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+o.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),o?.requestsRemaining!==void 0&&o.requestsRemaining<=5&&g.warn("Approaching Anthropic request rate limit",{remaining:o.requestsRemaining,limit:o.requestsLimit,reset:o.requestsReset}),o?.tokensRemaining!==void 0&&o.tokensLimit&&o.tokensRemaining<o.tokensLimit*.1&&g.warn("Approaching Anthropic token rate limit",{remaining:o.tokensRemaining,limit:o.tokensLimit,reset:o.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return xte()}getAISDKModel(){return this.model}formatProviderError(e){if(e instanceof At)return new ht(`Request timed out after ${e.timeout}ms`,this.providerName);let t=e,n=typeof t?.message=="string"?t.message:"Unknown error";return n.includes("API_KEY_INVALID")||n.includes("Invalid API key")?new ut("Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable.",this.providerName):n.includes("rate limit")||n.includes("too_many_requests")||n.includes("429")?new Rt("Anthropic rate limit exceeded. Please try again later.",this.providerName):n.includes("ECONNRESET")||n.includes("ENOTFOUND")||n.includes("ECONNREFUSED")||n.includes("network")||n.includes("connection")?new ht(`Connection error: ${n}`,this.providerName):n.includes("500")||n.includes("502")||n.includes("503")||n.includes("504")||n.includes("server error")?new Te(`Server error: ${n}`,this.providerName):new Te(`Anthropic error: ${n}`,this.providerName)}async generate(e,t){return await this.refreshAuthIfNeeded(),super.generate(e,t)}async executeStream(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);let n=this.getTimeout(e),o=Is(n,this.providerName,"stream");try{let s=!e.disableTools&&this.supportsTools(),i=s?e.tools||await this.getAllTools():{},a=await this.buildMessagesForStream(e),c=await this.getAISDKModelWithMiddleware(e),l=y7t.startSpan("neurolink.provider.streamText",{kind:gr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":YS(c,this.modelName||"unknown")}}),u,d;try{d=vR({model:c,messages:a,temperature:e.temperature,maxOutputTokens:e.maxTokens,maxRetries:0,tools:i,stopWhen:yx(e.maxSteps||Vo),toolChoice:LG(e,i,s),abortSignal:Fm(e.abortSignal,o?.controller.signal),onError:y=>{u=y.error,g.error("Anthropic: Stream error",{error:y.error instanceof Error?y.error.message:String(y.error)})},experimental_repairToolCall:this.getToolCallRepairFn(e),experimental_telemetry:this.telemetryHandler.getTelemetryConfig(e),onStepFinish:({toolCalls:y,toolResults:x})=>{sh(this.neurolink?.getEventEmitter(),x),this.handleToolExecutionStorage(y,x,e,new Date).catch(b=>{g.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:b instanceof Error?b.message:String(b)})})}})}catch(y){throw l.setStatus({code:me.ERROR,message:y instanceof Error?y.message:String(y)}),y instanceof Error&&l.recordException(y),l.end(),y}Promise.resolve(d.usage).then(y=>{l.setAttribute("gen_ai.usage.input_tokens",y.inputTokens||0),l.setAttribute("gen_ai.usage.output_tokens",y.outputTokens||0);let x=ko(this.providerName,this.modelName,{input:y.inputTokens||0,output:y.outputTokens||0,total:(y.inputTokens||0)+(y.outputTokens||0)});x&&x>0&&l.setAttribute("neurolink.cost",x)}).catch(()=>{}),Promise.resolve(d.finishReason).then(y=>{l.setAttribute("gen_ai.response.finish_reason",y||"unknown")}).catch(()=>{}),Promise.resolve(d.text).then(()=>{l.end()}).catch(y=>{l.setStatus({code:me.ERROR,message:y instanceof Error?y.message:String(y)}),l.end()}),o?.cleanup();let m=this.createTextStream(d,()=>u),f=[],h=[];return{stream:m,provider:this.providerName,model:this.modelName,toolCalls:f,toolResults:h}}catch(s){throw o?.cleanup(),this.handleProviderError(s)}}async isAvailable(){try{return SNe()||TNe(),!0}catch{return!1}}getModel(){return this.model}},T7t=VG});var _Ne={};K(_Ne,{Agent:()=>oQt,BedrockClient:()=>w7t,BedrockRuntimeClient:()=>bte,Blob:()=>nQt,Client:()=>iQt,ConverseCommand:()=>Tte,ConverseStreamCommand:()=>HG,Cron:()=>$7t,Dispatcher:()=>aQt,File:()=>rQt,FlowProducer:()=>F7t,FormData:()=>tQt,GoogleAuth:()=>R7t,HTTPException:()=>q7t,Headers:()=>eQt,Hippocampus:()=>P7t,HippocampusConfig:()=>M7t,Hono:()=>V7t,ImageFormat:()=>IE,InvokeEndpointCommand:()=>C7t,InvokeEndpointWithResponseStreamCommand:()=>k7t,Job:()=>L7t,ListFoundationModelsCommand:()=>E7t,MockAgent:()=>uQt,Pool:()=>sQt,Queue:()=>N7t,QueueScheduler:()=>U7t,Request:()=>Y7t,Response:()=>Q7t,SageMakerRuntimeClient:()=>_7t,TextToSpeechClient:()=>I7t,VertexAI:()=>A7t,Worker:()=>D7t,convertToHtml:()=>j7t,cors:()=>H7t,createClient:()=>O7t,default:()=>S7t,extractRawText:()=>G7t,fetch:()=>Z7t,getGlobalDispatcher:()=>lQt,interceptors:()=>dQt,logger:()=>W7t,parseBuffer:()=>B7t,request:()=>pQt,secureHeaders:()=>K7t,selectCover:()=>z7t,setGlobalDispatcher:()=>cQt,streamSSE:()=>J7t,timeout:()=>X7t});var AE,ki,S7t,w7t,E7t,bte,Tte,HG,IE,_7t,C7t,k7t,R7t,A7t,I7t,P7t,M7t,O7t,N7t,D7t,L7t,U7t,F7t,$7t,B7t,z7t,G7t,j7t,V7t,H7t,q7t,W7t,K7t,J7t,X7t,Z7t,Y7t,Q7t,eQt,tQt,rQt,nQt,oQt,sQt,iQt,aQt,cQt,lQt,uQt,dQt,pQt,Ste=E(()=>{AE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:AE.get}):new Proxy(function(...t){return new Proxy({},{get:AE.get})},{get:AE.get,apply(t,n,o){return new Proxy({},{get:AE.get})},construct(t,n){return new Proxy({},{get:AE.get})}})}},ki=new Proxy({},AE),S7t=ki,{BedrockClient:w7t,ListFoundationModelsCommand:E7t,BedrockRuntimeClient:bte,ConverseCommand:Tte,ConverseStreamCommand:HG,ImageFormat:IE}=ki,{SageMakerRuntimeClient:_7t,InvokeEndpointCommand:C7t,InvokeEndpointWithResponseStreamCommand:k7t}=ki,{GoogleAuth:R7t,VertexAI:A7t,TextToSpeechClient:I7t}=ki,{Hippocampus:P7t,HippocampusConfig:M7t}=ki,{createClient:O7t}=ki,{Queue:N7t,Worker:D7t,Job:L7t,QueueScheduler:U7t,FlowProducer:F7t}=ki,{Cron:$7t}=ki,{parseBuffer:B7t,selectCover:z7t}=ki,{extractRawText:G7t,convertToHtml:j7t}=ki,{Hono:V7t}=ki,{cors:H7t,HTTPException:q7t,logger:W7t,secureHeaders:K7t,streamSSE:J7t,timeout:X7t}=ki,Z7t=globalThis.fetch,Y7t=globalThis.Request,Q7t=globalThis.Response,eQt=globalThis.Headers,tQt=globalThis.FormData,rQt=globalThis.File,nQt=globalThis.Blob,oQt=ki.Agent,sQt=ki.Pool,iQt=ki.Client,aQt=ki.Dispatcher,cQt=()=>{},lQt=()=>ki,uQt=ki.MockAgent,dQt={redirect:()=>r=>r,retry:()=>r=>r},pQt=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});function wte(r,e,t){return{input:{text:r.input?.text||"",images:r.input?.images,content:r.input?.content,files:r.input?.files,csvFiles:r.input?.csvFiles,pdfFiles:r.input?.pdfFiles},csvOptions:r.csvOptions,systemPrompt:r.systemPrompt,conversationHistory:r.conversationMessages,provider:e,model:t,temperature:r.temperature,maxTokens:r.maxTokens,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,context:r.context,fileRegistry:r.fileRegistry}}var CNe=E(()=>{"use strict"});var kNe={};K(kNe,{Agent:()=>QQt,BedrockClient:()=>fQt,BedrockRuntimeClient:()=>hQt,Blob:()=>YQt,Client:()=>ter,ConverseCommand:()=>yQt,ConverseStreamCommand:()=>xQt,Cron:()=>NQt,Dispatcher:()=>rer,File:()=>ZQt,FlowProducer:()=>OQt,FormData:()=>XQt,GoogleAuth:()=>wQt,HTTPException:()=>zQt,Headers:()=>JQt,Hippocampus:()=>CQt,HippocampusConfig:()=>kQt,Hono:()=>$Qt,ImageFormat:()=>vQt,InvokeEndpointCommand:()=>TQt,InvokeEndpointWithResponseStreamCommand:()=>SQt,Job:()=>PQt,ListFoundationModelsCommand:()=>gQt,MockAgent:()=>ser,Pool:()=>eer,Queue:()=>AQt,QueueScheduler:()=>MQt,Request:()=>WQt,Response:()=>KQt,SageMakerRuntimeClient:()=>bQt,TextToSpeechClient:()=>_Qt,VertexAI:()=>EQt,Worker:()=>IQt,convertToHtml:()=>FQt,cors:()=>BQt,createClient:()=>RQt,default:()=>mQt,extractRawText:()=>UQt,fetch:()=>qQt,getGlobalDispatcher:()=>oer,interceptors:()=>ier,logger:()=>GQt,parseBuffer:()=>DQt,request:()=>aer,secureHeaders:()=>jQt,selectCover:()=>LQt,setGlobalDispatcher:()=>ner,streamSSE:()=>VQt,timeout:()=>HQt});var PE,Ri,mQt,fQt,gQt,hQt,yQt,xQt,vQt,bQt,TQt,SQt,wQt,EQt,_Qt,CQt,kQt,RQt,AQt,IQt,PQt,MQt,OQt,NQt,DQt,LQt,UQt,FQt,$Qt,BQt,zQt,GQt,jQt,VQt,HQt,qQt,WQt,KQt,JQt,XQt,ZQt,YQt,QQt,eer,ter,rer,ner,oer,ser,ier,aer,RNe=E(()=>{PE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:PE.get}):new Proxy(function(...t){return new Proxy({},{get:PE.get})},{get:PE.get,apply(t,n,o){return new Proxy({},{get:PE.get})},construct(t,n){return new Proxy({},{get:PE.get})}})}},Ri=new Proxy({},PE),mQt=Ri,{BedrockClient:fQt,ListFoundationModelsCommand:gQt,BedrockRuntimeClient:hQt,ConverseCommand:yQt,ConverseStreamCommand:xQt,ImageFormat:vQt}=Ri,{SageMakerRuntimeClient:bQt,InvokeEndpointCommand:TQt,InvokeEndpointWithResponseStreamCommand:SQt}=Ri,{GoogleAuth:wQt,VertexAI:EQt,TextToSpeechClient:_Qt}=Ri,{Hippocampus:CQt,HippocampusConfig:kQt}=Ri,{createClient:RQt}=Ri,{Queue:AQt,Worker:IQt,Job:PQt,QueueScheduler:MQt,FlowProducer:OQt}=Ri,{Cron:NQt}=Ri,{parseBuffer:DQt,selectCover:LQt}=Ri,{extractRawText:UQt,convertToHtml:FQt}=Ri,{Hono:$Qt}=Ri,{cors:BQt,HTTPException:zQt,logger:GQt,secureHeaders:jQt,streamSSE:VQt,timeout:HQt}=Ri,qQt=globalThis.fetch,WQt=globalThis.Request,KQt=globalThis.Response,JQt=globalThis.Headers,XQt=globalThis.FormData,ZQt=globalThis.File,YQt=globalThis.Blob,QQt=Ri.Agent,eer=Ri.Pool,ter=Ri.Client,rer=Ri.Dispatcher,ner=()=>{},oer=()=>Ri,ser=Ri.MockAgent,ier={redirect:()=>r=>r,retry:()=>r=>r},aer=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});var INe={};K(INe,{AmazonBedrockProvider:()=>_te});async function ANe(){return await Promise.resolve().then(()=>(RNe(),kNe))}var Ete,_te,PNe=E(()=>{"use strict";Ste();dn();zI();ql();oi();mt();at();yA();V();Ed();LI();CNe();wp();hr();zc();Ete=ce.provider,_te=class r extends Mn{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(e){return e?e.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(e,t,n,o){super(e,"bedrock",t);let s=e||process.env.BEDROCK_MODEL||this.modelName,i=r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",g.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),g.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{g.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new bte({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),g.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw g.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){let{BedrockClient:e,ListFoundationModelsCommand:t}=await ANe(),n=new e({region:this.region});try{g.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");let o=new t({}),s=Date.now();await n.send(o);let i=Date.now()-s;g.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){let s=o instanceof Error?o.message:String(o);g.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(e){g.debug("[AmazonBedrockProvider] generate() called with conversation management");let t=Date.now(),n=typeof e=="string"?{prompt:e}:e;this.conversationHistory=[];let o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){g.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});let d=wte(n,this.providerName,this.modelName),m=await dE(d,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(m)}else{g.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");let u={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(u)}g.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c;try{({text:i,usage:a,finishReason:c}=await this.conversationLoop(n))}catch(u){let d=this.neurolink?.getEventEmitter();throw d&&d.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,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:u instanceof Error?u.message:String(u)}),u}let l=this.neurolink?.getEventEmitter();return l&&l.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:c},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName()}}async conversationLoop(e){let n=0,o=0,s=0,i;for(;n<10;){n++,g.debug(`[AmazonBedrockProvider] Conversation iteration ${n}`);try{g.debug("[AmazonBedrockProvider] About to call Bedrock API");let a=await this.callBedrock(e);g.debug("[AmazonBedrockProvider] Received Bedrock response",JSON.stringify(a,null,2)),o+=a.usage?.inputTokens??0,s+=a.usage?.outputTokens??0,a.stopReason&&(i=a.stopReason);let c=await this.handleBedrockResponse(a);if(g.debug("[AmazonBedrockProvider] Handle response result:",c),c.shouldContinue)g.debug("[AmazonBedrockProvider] Continuing conversation loop...");else return g.debug("[AmazonBedrockProvider] Conversation completed with final text"),g.debug(`[AmazonBedrockProvider] Returning final text: "${c.text}"`),{text:c.text||"",usage:{input:o,output:s,total:o+s},finishReason:i}}catch(a){throw g.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}throw new Error("Conversation loop exceeded maximum iterations")}async callBedrock(e){let t=Date.now();return Ete.startActiveSpan("bedrock.generate",{kind:gr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"chat"}},async n=>{g.info(`[AmazonBedrockProvider] Starting Bedrock API call at ${new Date().toISOString()}`);try{let o="unknown";try{o=typeof this.bedrockClient.config.region=="function"?await this.bedrockClient.config.region():this.bedrockClient.config.region??"unknown"}catch{}g.info(`[AmazonBedrockProvider] Client region: ${o}`),g.info(`[AmazonBedrockProvider] Model: ${this.modelName||this.getDefaultModel()}`),g.info(`[AmazonBedrockProvider] Conversation history length: ${this.conversationHistory.length}`);let s=await this.getAllTools(),i=this.convertAISDKToolsToToolDefinitions(s),a=this.formatToolsForBedrock(i),c={modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(this.conversationHistory),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,temperature:e.temperature||.7}};a&&(c.toolConfig=a,g.info(`[AmazonBedrockProvider] Tools configured: ${a.tools?.length||0}`)),g.info("[AmazonBedrockProvider] Command input summary:"),g.info(` - Model ID: ${c.modelId}`),g.info(` - Messages count: ${c.messages?.length||0}`),g.info(` - System prompts: ${c.system?.length||0}`),g.info(` - Max tokens: ${c.inferenceConfig?.maxTokens}`),g.info(` - Temperature: ${c.inferenceConfig?.temperature}`),g.debug(`[AmazonBedrockProvider] Calling Bedrock with ${this.conversationHistory.length} messages and ${a?.tools?.length||0} tools`);let l=new Tte(c);g.debug("[Observability] Bedrock API request",{model:c.modelId,region:o,messageCount:c.messages?.length||0,toolCount:c.toolConfig?.tools?.length||0,maxTokens:c.inferenceConfig?.maxTokens});let u=Date.now(),d=await we(this.bedrockClient.send(l),12e4,new Error("Bedrock API call timed out")),m=Date.now()-u;g.debug("[Observability] Bedrock API response",{model:c.modelId,durationMs:m,hasContent:!!d.output?.message?.content?.length,stopReason:d.stopReason,usage:d.usage?{inputTokens:d.usage.inputTokens,outputTokens:d.usage.outputTokens,totalTokens:(d.usage.inputTokens||0)+(d.usage.outputTokens||0)}:void 0}),g.info("[AmazonBedrockProvider] Bedrock API call successful"),g.info(`[AmazonBedrockProvider] API call duration: ${m}ms`);let f=Date.now()-t;g.info(`[AmazonBedrockProvider] Total callBedrock duration: ${f}ms`),n.setAttribute("gen_ai.response.stop_reason",d.stopReason??""),n.setAttribute("gen_ai.usage.input_tokens",d.usage?.inputTokens??0),n.setAttribute("gen_ai.usage.output_tokens",d.usage?.outputTokens??0);let h=ko(this.providerName,this.modelName,{input:d.usage?.inputTokens??0,output:d.usage?.outputTokens??0,total:(d.usage?.inputTokens??0)+(d.usage?.outputTokens??0)});return h&&h>0&&n.setAttribute("neurolink.cost",h),n.setStatus({code:me.OK}),n.end(),d}catch(o){let s=Date.now()-t,i=o&&typeof o=="object"?o:null,a=i?.$metadata&&typeof i.$metadata=="object"?i.$metadata:null;throw g.debug("[Observability] Bedrock API request failed",{model:this.modelName||this.getDefaultModel(),durationMs:s,error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:void 0,httpStatus:a?.httpStatusCode,awsRequestId:a?.requestId,awsErrorCode:i?.Code}),g.error(`[AmazonBedrockProvider] Bedrock API call failed after ${s}ms`),o instanceof Error&&g.error(`[AmazonBedrockProvider] Error: ${o.name} - ${o.message}`),a&&g.error("[AmazonBedrockProvider] AWS SDK metadata",{httpStatus:a.httpStatusCode,requestId:a.requestId,attempts:a.attempts,totalRetryDelay:a.totalRetryDelay}),n.setStatus({code:me.ERROR,message:o instanceof Error?o.message:String(o)}),n.recordException(o instanceof Error?o:new Error(String(o))),n.end(),o}})}async handleBedrockResponse(e){if(g.debug(`[AmazonBedrockProvider] Received response with stopReason: ${e.stopReason}`),!e.output||!e.output.message)throw new Error("Invalid response structure from Bedrock API");let t=e.output.message,n=e.stopReason,o={role:"assistant",content:(t.content||[]).map(s=>{let i={};return"text"in s&&s.text&&(i.text=s.text),"toolUse"in s&&s.toolUse&&(i.toolUse={toolUseId:s.toolUse.toolUseId||"",name:s.toolUse.name||"",input:s.toolUse.input||{}}),"toolResult"in s&&s.toolResult&&(i.toolResult={toolUseId:s.toolResult.toolUseId||"",content:(s.toolResult.content||[]).map(a=>({text:typeof a=="object"&&"text"in a&&a.text||""})),status:s.toolResult.status||"unknown"}),i})};if(this.conversationHistory.push(o),n==="end_turn"||n==="stop_sequence")return{shouldContinue:!1,text:o.content.filter(i=>i.text).map(i=>i.text).join(" ")};if(n==="tool_use"){g.debug("[AmazonBedrockProvider] Tool use detected - executing tools immediately");let s=[];for(let i of o.content)if(i.toolUse){g.debug(`[AmazonBedrockProvider] Executing tool: ${i.toolUse.name}`);try{g.debug("[AmazonBedrockProvider] Debug toolUse.input:",JSON.stringify(i.toolUse.input,null,2));let a=await this.executeSingleTool(i.toolUse.name,i.toolUse.input||{},i.toolUse.toolUseId);g.debug(`[AmazonBedrockProvider] Tool execution successful: ${i.toolUse.name}`),s.push({toolResult:{toolUseId:i.toolUse.toolUseId,content:[{text:String(a)}],status:"success"}})}catch(a){g.error(`[AmazonBedrockProvider] Tool execution failed: ${i.toolUse.name}`,a);let c=a instanceof Error?a.message:String(a);s.push({toolResult:{toolUseId:i.toolUse.toolUseId,content:[{text:`Error executing tool ${i.toolUse.name}: ${c}`}],status:"error"}})}}if(s.length>0){let i={role:"user",content:s};this.conversationHistory.push(i),g.debug(`[AmazonBedrockProvider] Added ${s.length} tool results to conversation`)}return{shouldContinue:!0}}else return n==="max_tokens"?{shouldContinue:!1,text:o.content.filter(i=>i.text).map(i=>i.text).join(" ")}:(g.warn(`[AmazonBedrockProvider] Unrecognized stop reason "${n}", ending conversation.`),{shouldContinue:!1,text:""})}convertToAWSMessages(e){return e.map(t=>({role:t.role,content:t.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(e,t,n){return Ete.startActiveSpan("bedrock.tool.execute",{kind:gr.CLIENT,attributes:{"gen_ai.tool.name":e,"gen_ai.system":"aws.bedrock"}},async o=>{try{g.debug(`[AmazonBedrockProvider] Executing single tool: ${e}`,{args:t});let s=await this.getAllTools(),i=this.convertAISDKToolsToToolDefinitions(s);if(!i[e])throw new Error(`Tool not found: ${e}`);let a=i[e];if(!a||!a.execute)throw new Error(`Tool ${e} does not have execute method`);let c=t||{};e==="list_directory"&&!c.path&&(c.path=".",g.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),g.debug("[AmazonBedrockProvider] Tool input parameters:",c);let l={};for(let[m,f]of Object.entries(c))(f===null||typeof f=="string"||typeof f=="number"||typeof f=="boolean"||typeof f=="object"&&f!==null)&&(l[m]=f);let u=await a.execute(l);g.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:e,result:u});let d;if(u&&typeof u=="object"&&"success"in u)if(u.success&&u.data!==void 0)typeof u.data=="string"?d=u.data:typeof u.data=="object"?d=JSON.stringify(u.data,null,2):d=String(u.data);else if(u.error){let m=typeof u.error=="string"?u.error:u.error.message||"Tool execution failed";throw new Error(m)}else d="";else typeof u=="string"?d=u:typeof u=="object"?d=JSON.stringify(u,null,2):d=String(u);return o.setStatus({code:me.OK}),d}catch(s){throw g.error("[AmazonBedrockProvider] Tool execution error:",{toolName:e,error:s}),o.setStatus({code:me.ERROR,message:s.message}),o.recordException(s),s}finally{o.end()}})}convertAISDKToolsToToolDefinitions(e){let t={};for(let[n,o]of Object.entries(e))if("description"in o&&o.description){let i=o.parameters??o.inputSchema;t[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 t}formatToolsForBedrock(e){if(!e||Object.keys(e).length===0)return null;let t=Object.entries(e).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=si(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 g.debug(`[AmazonBedrockProvider] Formatted ${t.length} tools for Bedrock`),{tools:t}}convertToBedrockMessages(e){return e.map(t=>{let n={role:t.role==="system"?"user":t.role,content:[]};return typeof t.content=="string"?n.content.push({text:t.content}):t.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){let s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image,i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?IE.JPEG:i==="png"?IE.PNG:i==="gif"?IE.GIF:IE.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"){let 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?_a.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(e){return g.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),g.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Ete.startActiveSpan("bedrock.stream",{kind:gr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async t=>{try{if(g.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(e.input?.images?.length||e.input?.content?.length||e.input?.files?.length||e.input?.csvFiles?.length||e.input?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!e.input?.images?.length,imageCount:e.input?.images?.length||0,hasContent:!!e.input?.content?.length,contentCount:e.input?.content?.length||0,hasFiles:!!e.input?.files?.length,fileCount:e.input?.files?.length||0,hasCSVFiles:!!e.input?.csvFiles?.length,csvFileCount:e.input?.csvFiles?.length||0,hasPDFFiles:!!e.input?.pdfFiles?.length,pdfFileCount:e.input?.pdfFiles?.length||0});let s=wte(e,this.providerName,this.modelName),i=await dE(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{g.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");let s={role:"user",content:[{text:e.input.text}]};this.conversationHistory.push(s)}g.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),g.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");let o=await this.streamingConversationLoop(e,t);return g.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),t.setStatus({code:me.OK}),t.end(),o}catch(n){g.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");let o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(g.debug("[TRACE] executeStream CATCH - checking if permission error"),g.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){g.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),g.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),t.addEvent("stream.fallback_to_generate",{reason:o.message});let i=await this.generate({prompt:e.input.text,input:e.input,maxTokens:e.maxTokens,temperature:e.temperature,systemPrompt:e.systemPrompt});if(!i)throw t.setStatus({code:me.ERROR,message:"Generate method returned null result"}),t.end(),new Error("Generate method returned null result");t.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),t.setStatus({code:me.OK}),t.end();let a=new ReadableStream({start(l){let d=(i.content||"").split(/(\s+)/),m="";for(let f=0;f<d.length;f++)m+=d[f],(f===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](){let l=a.getReader();try{for(;;){let{done:u,value:d}=await l.read();if(u)break;yield d}}finally{l.releaseLock()}}},usage:{total:0,input:0,output:0},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw t.setStatus({code:me.ERROR,message:o instanceof Error?o.message:String(o)}),t.recordException(o instanceof Error?o:new Error(String(o))),t.end(),n}})}async streamingConversationLoop(e,t){g.debug("[TRACE] streamingConversationLoop ENTRY");let n=Date.now(),o=e.maxSteps||Vo,s=0,i=0,a=0,c;try{g.debug("[TRACE] streamingConversationLoop - testing first streaming call");let l=await this.prepareStreamCommand(e),u=new HG(l);g.debug("[Observability] Bedrock streaming API request",{model:l.modelId,messageCount:l.messages?.length||0,toolCount:l.toolConfig?.tools?.length||0}),t.addEvent("stream.api_call",{"bedrock.message_count":l.messages?.length||0,"bedrock.tool_count":l.toolConfig?.tools?.length||0});let d=Date.now(),m=await we(this.bedrockClient.send(u),12e4,new Error("Bedrock streaming API call timed out"));g.debug("[Observability] Bedrock streaming API connection established",{model:l.modelId,durationMs:Date.now()-d,hasStream:!!m.stream});let f=new ReadableStream({start:async _=>{g.debug("[TRACE] streamingConversationLoop - ReadableStream start() called");try{let C="";if(m.stream){let k=[],I="";for await(let M of m.stream){if(M.contentBlockStart&&k.push({}),M.contentBlockDelta?.delta?.text){let D=M.contentBlockDelta.delta.text;I+=D,_.enqueue({content:D})}if(M.contentBlockStart?.start?.toolUse){let D=k[k.length-1];D.toolUse={name:M.contentBlockStart.start.toolUse.name||"",input:{},toolUseId:M.contentBlockStart.start.toolUse.toolUseId||`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}}if(M.contentBlockDelta?.delta?.toolUse){let D=k[k.length-1];D.toolUse||(D.toolUse={name:"",input:{},toolUseId:`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`});let B=M.contentBlockDelta.delta.toolUse.input;if(B){if(typeof B=="string")D._inputBuffer=(D._inputBuffer||"")+B;else if(typeof B=="object"&&!Array.isArray(B)){let O=D.toolUse.input||{};D.toolUse.input={...O,...B}}}}if(M.contentBlockStop){let D=k[k.length-1];if(D?.toolUse&&D._inputBuffer){try{D.toolUse.input=JSON.parse(D._inputBuffer)}catch{D.toolUse.input={}}delete D._inputBuffer}I&&D&&!D.toolUse&&(D.text=I),I=""}if(M.messageStop){C=M.messageStop.stopReason||"end_turn";continue}if(M.metadata?.usage){i+=M.metadata.usage.inputTokens??0,a+=M.metadata.usage.outputTokens??0;break}}C&&(c=C);let R={role:"assistant",content:k};if(this.conversationHistory.push(R),t.addEvent("stream.turn_complete",{iteration:0,stop_reason:C}),C==="tool_use"){let M=k.flatMap(D=>D.toolUse?.name?[D.toolUse.name]:[]).join(", ");t.addEvent("stream.tool_use",{iteration:0,tool_names:M})}if(!await this.handleStreamStopReason(C,R,_,e)){t.setAttribute("gen_ai.response.stop_reason",C),_.close();return}}for(;s<o;){s++,g.debug(`[AmazonBedrockProvider] Streaming iteration ${s}`);let k=await this.prepareStreamCommand(e),{stopReason:I,assistantMessage:R,usage:A}=await this.processStreamResponse(k,_);if(A&&(i+=A.input,a+=A.output),I&&(c=I),t.addEvent("stream.turn_complete",{iteration:s,stop_reason:I}),I==="tool_use"){let D=R.content.flatMap(B=>B.toolUse?.name?[B.toolUse.name]:[]).join(", ");t.addEvent("stream.tool_use",{iteration:s,tool_names:D})}if(!await this.handleStreamStopReason(I,R,_,e)){t.setAttribute("gen_ai.response.stop_reason",I);break}}if(s>=o){t.setAttribute("gen_ai.response.stop_reason","max_iterations"),_.error(new Error("Streaming conversation exceeded maximum iterations"));return}_.close()}catch(C){g.debug("[TRACE] streamingConversationLoop - CATCH block hit in ReadableStream"),_.error(C)}}}),h=this.neurolink?.getEventEmitter(),y=this.convertToAsyncIterable(f),x=this,b,S=new Promise(_=>{b=_});return{stream:{async*[Symbol.asyncIterator](){let _=!1;try{yield*y}catch(C){throw _=!0,C}finally{let C={input:i,output:a,total:i+a};b(Fh(x.providerName,x.modelName||x.getDefaultModel(),{usage:C},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0})),h&&h.emit("generation:end",{provider:x.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:C,model:x.modelName||x.getDefaultModel(),provider:x.providerName,finishReason:_?"error":c},success:!_})}}},usage:{total:0,input:0,output:0},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:S,metadata:{startTime:n,streamId:`bedrock-${Date.now()}`}}}catch(l){throw g.debug("[TRACE] streamingConversationLoop - first streaming call FAILED, throwing"),l}}convertToAsyncIterable(e){return{async*[Symbol.asyncIterator](){let t=e.getReader();try{for(;;){let{done:n,value:o}=await t.read();if(n)break;yield o}}finally{t.releaseLock()}}}}async prepareStreamCommand(e){g.shouldLog("debug")&&(g.debug(`[AmazonBedrockProvider] BEFORE conversion - conversationHistory length: ${this.conversationHistory.length}`),this.conversationHistory.forEach((a,c)=>{g.debug(`[AmazonBedrockProvider] Message ${c}: role=${a.role}, content=${JSON.stringify(a.content)}`)}));let t=e.tools||await this.getAllTools(),n=this.convertAISDKToolsToToolDefinitions(t),o=this.formatToolsForBedrock(n),s=this.convertToAWSMessages(this.conversationHistory);g.shouldLog("debug")&&(g.debug(`[AmazonBedrockProvider] AFTER conversion - messages length: ${s.length}`),s.forEach((a,c)=>{g.debug(`[AmazonBedrockProvider] Converted Message ${c}: role=${a.role}, content=${JSON.stringify(a.content)}`)}));let i={modelId:this.modelName||this.getDefaultModel(),messages:s,system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,temperature:e.temperature||.7}};return o&&(i.toolConfig=o),g.debug(`[AmazonBedrockProvider] Calling Bedrock streaming with ${this.conversationHistory.length} messages`),g.debug("[AmazonBedrockProvider] DEBUG - Conversation structure:"),this.conversationHistory.forEach((a,c)=>{g.debug(` Message ${c} (${a.role}): ${a.content.length} content items`),a.content.forEach((l,u)=>{let d=Object.keys(l);g.debug(` Content ${u}: ${d.join(", ")}`)})}),i}async processStreamResponse(e,t){let n=new HG(e);g.debug("[Observability] Bedrock streaming API request (continuation)",{model:e.modelId,messageCount:e.messages?.length||0});let o=Date.now(),s=await we(this.bedrockClient.send(n),12e4,new Error("Bedrock streaming API call timed out"));if(g.debug("[Observability] Bedrock streaming API connection established (continuation)",{model:e.modelId,durationMs:Date.now()-o}),!s.stream)throw new Error("No stream returned from Bedrock");let i=[],a="",c="",l;for await(let d of s.stream){if(d.contentBlockStart&&i.push({}),d.contentBlockDelta?.delta?.text){let m=d.contentBlockDelta.delta.text;c+=m,t.enqueue({content:m})}if(d.contentBlockStart?.start?.toolUse){let m=i[i.length-1];m.toolUse={name:d.contentBlockStart.start.toolUse.name||"",input:{},toolUseId:d.contentBlockStart.start.toolUse.toolUseId||`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}}if(d.contentBlockDelta?.delta?.toolUse){let m=i[i.length-1];if(m.toolUse||(m.toolUse={name:"",input:{},toolUseId:`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}),d.contentBlockDelta.delta.toolUse.input){let f=d.contentBlockDelta.delta.toolUse.input;if(typeof f=="string")m._inputBuffer=(m._inputBuffer||"")+f;else if(f&&typeof f=="object"&&!Array.isArray(f)){let h=m.toolUse.input||{};m.toolUse.input={...h,...f}}}}if(d.contentBlockStop){let m=i[i.length-1];if(m?.toolUse&&m._inputBuffer){try{m.toolUse.input=JSON.parse(m._inputBuffer)}catch{m.toolUse.input={}}delete m._inputBuffer}c&&m&&!m.toolUse&&(m.text=c),c=""}if(d.messageStop){a=d.messageStop.stopReason||"end_turn";continue}if(d.metadata?.usage){let m=d.metadata.usage.inputTokens??0,f=d.metadata.usage.outputTokens??0;l={input:m,output:f,total:d.metadata.usage.totalTokens??m+f};break}}let u={role:"assistant",content:i};return this.conversationHistory.push(u),{stopReason:a,assistantMessage:u,usage:l}}async handleStreamStopReason(e,t,n,o){return e==="end_turn"||e==="stop_sequence"?(n.close(),!1):e==="tool_use"?(g.debug("[AmazonBedrockProvider] Tool use detected in streaming - executing tools"),await this.executeStreamTools(t.content,o),!0):(n.close(),!1)}async executeStreamTools(e,t){let n=[],o=0,s=[],i=[];for(let a of e)a.toolUse&&o++;g.debug(`[AmazonBedrockProvider] Found ${o} toolUse blocks in assistant message`);for(let a of e)if(a.toolUse){g.debug(`[AmazonBedrockProvider] Executing tool: ${a.toolUse.name}`),s.push({type:"tool-call",toolCallId:a.toolUse.toolUseId,toolName:a.toolUse.name,args:a.toolUse.input||{}});try{let c=await this.executeSingleTool(a.toolUse.name,a.toolUse.input||{},a.toolUse.toolUseId);g.debug(`[AmazonBedrockProvider] Tool execution successful: ${a.toolUse.name}`),i.push({type:"tool-result",toolCallId:a.toolUse.toolUseId,toolName:a.toolUse.name,result:c}),n.push({toolResult:{toolUseId:a.toolUse.toolUseId,content:[{text:String(c)}],status:"success"}})}catch(c){g.error(`[AmazonBedrockProvider] Tool execution failed: ${a.toolUse.name}`,c);let l=c instanceof Error?c.message:String(c);i.push({type:"tool-result",toolCallId:a.toolUse.toolUseId,toolName:a.toolUse.name,result:{error:l}}),n.push({toolResult:{toolUseId:a.toolUse.toolUseId,content:[{text:`Error executing tool ${a.toolUse.name}: ${l}`}],status:"error"}})}}if(g.debug(`[AmazonBedrockProvider] Created ${n.length} toolResult blocks for ${o} toolUse blocks`),n.length!==o)throw g.error(`[AmazonBedrockProvider] Mismatch: ${n.length} toolResults vs ${o} toolUse blocks`),new Error(`Tool mapping mismatch: ${n.length} toolResults for ${o} toolUse blocks`);if(n.length>0){let a={role:"user",content:n};this.conversationHistory.push(a),g.debug(`[AmazonBedrockProvider] Added ${n.length} tool results to conversation (1:1 mapping validated)`),sh(this.neurolink?.getEventEmitter(),i.map(c=>{let l=c.result&&typeof c.result=="object"&&"error"in c.result;return{toolName:c.toolName,result:c.result,error:l?String(c.result.error):void 0}})),this.handleToolExecutionStorage(s,i,t,new Date).catch(c=>{g.warn("[AmazonBedrockProvider] Failed to store tool executions",{provider:this.providerName,error:c instanceof Error?c.message:String(c)})})}}async checkBedrockHealth(){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await ANe(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{g.debug("[AmazonBedrockProvider] Starting health check...");let i=new o({}),c=(await s.send(i,{abortSignal:e.signal})).modelSummaries||[],l=c.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(g.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(t);let a=i;if(Or(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});let 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}):(g.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${c||"Unknown error"}`,{cause:i}))}finally{clearTimeout(t);try{s.destroy()}catch{}}}formatProviderError(e){let t=e instanceof Error?e.message:String(e);if(t.includes("AccessDeniedException"))return new ut("AWS Bedrock access denied. Check your credentials and permissions.",this.providerName);if(t.includes("ValidationException"))return new Te(`Validation error: ${t}`,this.providerName);let n=e?.name??"",o=e?.code??"";return n==="ThrottlingException"||o==="ThrottlingException"?new Rt(`Bedrock rate limit (throttled): ${e instanceof Error?e.message:String(e)}`,"bedrock"):new Te(`AWS Bedrock error: ${t}`,this.providerName)}async embed(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let{InvokeModelCommand:o}=await Promise.resolve().then(()=>(Ste(),_Ne)),s=JSON.stringify({inputText:e}),i=new o({modelId:n,contentType:"application/json",accept:"application/json",body:s}),a=await we(this.bedrockClient.send(i),6e4,new Error("Bedrock embedding API call timed out")),c=JSON.parse(new TextDecoder().decode(a.body));if(!c.embedding||!Array.isArray(c.embedding))throw new Error("Invalid embedding response from Bedrock");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:c.embedding.length}),c.embedding}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await Promise.all(e.map(s=>this.embed(s,n)));return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}}});var MNe={};K(MNe,{AzureOpenAIProvider:()=>Cte});var Cte,ONe=E(()=>{"use strict";mt();V();Nn();Rn();eh();ys();Wh();Cte=class extends ar{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,n,o){let s=o?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"",a;if(i)try{a=new URL(i.includes("://")?i:`https://${i}`)}catch{a=void 0}let c=a?.hostname??"",l=a?.pathname&&a.pathname!=="/"?a.pathname.replace(/\/+$/,""):"",u=/\.(openai|cognitiveservices)\.azure\.com$/.test(c),d;u?d="/openai":d=/\/openai(?:\/v\d+)?$/.test(l)?l:`${l}/openai`;let m=a?.origin??"",f=o?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=o?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",y=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,x=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||er(nOe()),m||er(oOe()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=d,this.useMaxCompletionTokensOverride=x,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",m$({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){if(e instanceof At)return new ht(`Request timed out: ${e.message}`,"azure");let t=e;if(t?.message&&typeof t.message=="string"&&t.message.includes("401"))return new ut("Invalid Azure OpenAI API key or endpoint.","azure");let n=t?.message&&typeof t.message=="string"?t.message:"Unknown error";return new Te(`Azure OpenAI error: ${n}`,"azure")}getChatCompletionsURL(e){let t=e||this.azureDeployment,n=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${n}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){let n=this.useMaxCompletionTokensOverride??FOe(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function He(r,e,t,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 e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function re(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var hf=E(()=>{});var kte,NNe=E(()=>{kte=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return kte=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))}});function yf(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var pP,ME=E(()=>{pP=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)}});var ct,la,Ua,Fv,mP,fP,gP,hP,yP,xP,vP,bP,TP,sl=E(()=>{ME();ct=class extends Error{},la=class r extends ct{constructor(e,t,n,o,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=t,this.type=s??null}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new Fv({message:n,cause:pP(t)});let s=t,i=s?.error?.type;return e===400?new fP(e,s,n,o,i):e===401?new gP(e,s,n,o,i):e===403?new hP(e,s,n,o,i):e===404?new yP(e,s,n,o,i):e===409?new xP(e,s,n,o,i):e===422?new vP(e,s,n,o,i):e===429?new bP(e,s,n,o,i):e>=500?new TP(e,s,n,o,i):new r(e,s,n,o,i)}},Ua=class extends la{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Fv=class extends la{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},mP=class extends Fv{constructor({message:e}={}){super({message:e??"Request timed out."})}},fP=class extends la{},gP=class extends la{},hP=class extends la{},yP=class extends la{},xP=class extends la{},vP=class extends la{},bP=class extends la{},TP=class extends la{}});function qG(r){return typeof r!="object"?{}:r??{}}function Ite(r){if(!r)return!0;for(let e in r)return!1;return!0}function LNe(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var ler,DNe,Rte,Ate,UNe,WG,$v=E(()=>{sl();ler=/^[a-z][a-z0-9+.-]*:/i,DNe=r=>ler.test(r),Rte=r=>(Rte=Array.isArray,Rte(r)),Ate=Rte;UNe=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ct(`${r} must be an integer`);if(e<0)throw new ct(`${r} must be a positive integer`);return e},WG=r=>{try{return JSON.parse(r)}catch{return}}});var FNe,$Ne=E(()=>{FNe=r=>new Promise(e=>setTimeout(e,r))});var Kh,Pte=E(()=>{Kh="0.91.1"});function uer(){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 per(){if(typeof navigator>"u"||!navigator)return null;let r=[{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(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var jNe,der,BNe,zNe,GNe,VNe,Mte=E(()=>{Pte();jNe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";der=()=>{let r=uer();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":zNe(Deno.build.os),"X-Stainless-Arch":BNe(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":Kh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":zNe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":BNe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=per();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};BNe=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",zNe=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),VNe=()=>GNe??(GNe=der())});function HNe(){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 Ote(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function KG(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Ote({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function SP(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qNe(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var OE=E(()=>{});var WNe,KNe=E(()=>{WNe=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function JNe(r){return Object.entries(r).filter(([e,t])=>typeof t<"u").map(([e,t])=>{if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new ct(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var XNe=E(()=>{sl()});function QNe(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function wP(r){let e;return(ZNe??(e=new globalThis.TextEncoder,ZNe=e.encode.bind(e)))(r)}function Nte(r){let e;return(YNe??(e=new globalThis.TextDecoder,YNe=e.decode.bind(e)))(r)}var ZNe,YNe,Dte=E(()=>{});function ger(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function eDe(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Kl,Jl,xf,Lte=E(()=>{hf();Dte();xf=class{constructor(){Kl.set(this,void 0),Jl.set(this,void 0),He(this,Kl,new Uint8Array,"f"),He(this,Jl,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?wP(e):e;He(this,Kl,QNe([re(this,Kl,"f"),t]),"f");let n=[],o;for(;(o=ger(re(this,Kl,"f"),re(this,Jl,"f")))!=null;){if(o.carriage&&re(this,Jl,"f")==null){He(this,Jl,o.index,"f");continue}if(re(this,Jl,"f")!=null&&(o.index!==re(this,Jl,"f")+1||o.carriage)){n.push(Nte(re(this,Kl,"f").subarray(0,re(this,Jl,"f")-1))),He(this,Kl,re(this,Kl,"f").subarray(re(this,Jl,"f")),"f"),He(this,Jl,null,"f");continue}let s=re(this,Jl,"f")!==null?o.preceding-1:o.preceding,i=Nte(re(this,Kl,"f").subarray(0,s));n.push(i),He(this,Kl,re(this,Kl,"f").subarray(o.index),"f"),He(this,Jl,null,"f")}return n}flush(){return re(this,Kl,"f").length?this.decode(`
|
|
1159
|
+
`):"";default:return Dv(r)}},o9t=r=>{if(typeof r=="string")return r.startsWith("data:")||/^https?:\/\//i.test(r)?r:`data:image/png;base64,${r}`;if(r instanceof URL)return r.toString();if(r instanceof Uint8Array)return`data:image/png;base64,${Buffer.from(r).toString("base64")}`},s9t=r=>{if(typeof r=="string")return r;if(!Array.isArray(r))return Dv(r);let e=[];for(let t of r){if(typeof t=="string"){e.push({type:"text",text:t});continue}if(!t||typeof t!="object")continue;let n=t;if(n.type==="text")e.push({type:"text",text:t.text??""});else if(n.type==="image"||n.type==="image_url"){let o=t.image??t.data??t.url,s=o9t(o);s&&e.push({type:"image_url",image_url:{url:s}})}}return e.length===1&&e[0].type==="text"?e[0].text:e},tte=r=>{let e=[];for(let t of r)switch(t.role){case"system":e.push({role:"system",content:typeof t.content=="string"?t.content:Dv(t.content)});break;case"user":e.push({role:"user",content:s9t(t.content)});break;case"assistant":{let n=Array.isArray(t.content)?t.content:[t.content],o=[],s=[];for(let a of n)if(a&&typeof a=="object"){let c=a;if(c.type==="text")o.push({type:"text",text:a.text??""});else if(c.type==="tool-call"){let l=a;s.push({id:l.toolCallId??"",type:"function",function:{name:l.toolName??"",arguments:n9t(l.input)}})}}else typeof a=="string"&&o.push({type:"text",text:a});let i=o.length===0?null:o.length===1&&o[0].type==="text"?o[0].text:o;e.push({role:"assistant",content:i,...s.length>0?{tool_calls:s}:{}});break}case"tool":{if(Array.isArray(t.content))for(let n of t.content){if(!n||typeof n!="object")continue;let o=n;o.type==="tool-result"&&e.push({role:"tool",tool_call_id:o.toolCallId??"",content:ete(o.output)})}else typeof t.content=="string"&&e.push({role:"tool",tool_call_id:t.toolCallId??"",content:t.content});break}}return e},OOe=r=>{let e=Object.entries(r);if(e.length===0)return;let t=[];for(let[n,o]of e){let s=o,i=s.inputSchema??s.parameters,a=i?si(i):{type:"object",properties:{}};t.push({type:"function",function:{name:n,...s.description?{description:s.description}:{},parameters:a}})}return t},NOe=r=>{if(!r||r.length===0)return;let e=[];for(let t of r)t.type==="function"&&e.push({type:"function",function:{name:t.name,...t.description?{description:t.description}:{},parameters:t.inputSchema,...t.strict!==void 0?{strict:t.strict}:{}}});return e.length>0?e:void 0},DOe=r=>{switch(r.type){case"auto":case"none":case"required":return r.type;case"tool":return{type:"function",function:{name:r.toolName}}}},LOe=r=>r.type==="text"?{type:"text"}:r.schema?{type:"json_schema",json_schema:{name:r.name??"response",schema:r.schema,...r.description?{description:r.description}:{},strict:!0}}:{type:"json_object"},UOe=r=>{if(r){if(r==="auto"||r==="none"||r==="required")return r;if(typeof r=="object"&&r!==null){let e=r;if(e.type==="tool"&&e.toolName)return{type:"function",function:{name:e.toolName}}}}},i9t=r=>r.some(e=>{let t=e.content;return typeof t=="string"?/\bjson\b/i.test(t):Array.isArray(t)?t.some(n=>typeof n?.text=="string"&&/\bjson\b/i.test(n.text)):!1}),rte=r=>r.response_format?.type==="json_object"&&!i9t(r.messages)?{...r,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...r.messages]}:r,FOe=r=>/^(o\d|gpt-5)/i.test(r.replace(/^.*\//,"")),nte=r=>{let{modelId:e,messages:t,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=r,c={model:e,messages:t,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};return n.maxTokens!==void 0&&n.maxTokens!==null&&(c.max_tokens=n.maxTokens),n.temperature!==void 0&&n.temperature!==null&&(c.temperature=n.temperature),n.topP!==void 0&&n.topP!==null&&(c.top_p=n.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(c.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(c.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(c.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(c.stop=n.stopSequences),o&&(c.tools=o),s!==void 0&&(c.tool_choice=s),a&&(c.response_format=a),c},$Oe=async(r,e,t)=>{let n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder,s,a=sS({onEvent:l=>{let u=l.data;if(!u||u==="[DONE]")return;let d;try{d=JSON.parse(u)}catch(y){s=y instanceof Error?y:new Error(String(y));return}d.usage&&(n.usage=d.usage);let m=d.choices?.[0];if(!m)return;let f=m.delta;f?.content&&(n.text+=f.content,e(f.content));let h=f?.reasoning_content??f?.reasoning;if(h&&(n.reasoning+=h,t?.(h)),f?.tool_calls)for(let y of f.tool_calls){let x=n.toolCalls.get(y.index);x?y.id&&(x.id=y.id):(x={id:y.id??`call_${y.index}_${Date.now()}`,name:y.function?.name??"",argsBuffered:""},n.toolCalls.set(y.index,x)),y.function?.name&&(x.name=y.function.name),y.function?.arguments&&(x.argsBuffered+=y.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),c=r.getReader();try{for(;;){let{done:l,value:u}=await c.read();if(l)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{c.releaseLock()}if(s)throw s;return n},ote=async(r,e,t)=>{let n,o;try{n=await t.text(),o=n?JSON.parse(n):void 0}catch{o=void 0}let s=o?.error?.message??`OpenAI-compatible request failed with status ${t.status}`,i=new Error(s);return i.statusCode=t.status,i.url=r,i.requestBody={model:e.model,stream:e.stream===!0,tool_count:e.tools?.length??0},n!==void 0&&(i.responseBody=n),i},BOe=()=>{let r=()=>{},e=new Promise(o=>{r=o}),t=()=>{},n=new Promise(o=>{t=o});return{usagePromise:e,finishPromise:n,resolveUsage:r,resolveFinish:t}},zOe=()=>{let r=[],e;return{pushChunk:o=>{if(e){let s=e;e=void 0,s(o)}else r.push(o)},nextChunk:()=>new Promise(o=>{r.length>0?o(r.shift()):e=o})}},GOe=(r,e)=>r?e?{prompt_tokens:(r.prompt_tokens??0)+(e.prompt_tokens??0),completion_tokens:(r.completion_tokens??0)+(e.completion_tokens??0),total_tokens:(r.total_tokens??0)+(e.total_tokens??0)}:r:e});var ste,jOe,VOe=E(()=>{"use strict";zI();V();b2();jm();ste=class{async collectUsage(e){try{let t=await e.usage;return t?QS(t):(g.debug("No usage data available from stream result"),aY())}catch(t){return Nc.isInstance(t)?g.debug("No output generated from stream \u2014 returning empty usage"):g.warn("Failed to collect usage from stream result",{error:t}),aY()}}async collectMetadata(e){try{let[t,n]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:n}}catch(t){return Nc.isInstance(t)?g.debug("No output generated from stream \u2014 returning default metadata"):g.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,n,o,s){try{let[i,a]=await Promise.all([this.collectUsage(n),this.collectMetadata(n)]),[c,l,u,d]=await Promise.all([Promise.resolve(n.text).catch(()=>""),Promise.resolve(n.finishReason).catch(()=>"error"),Promise.resolve(n.toolResults||[]).catch(()=>[]),Promise.resolve(n.toolCalls||[]).catch(()=>[])]);return Fh(e,t,{usage:i,content:c,response:a,finishReason:l,toolResults:u,toolCalls:d},o,{...s,streamingMode:!0,responseId:a.id,finishReason:l})}catch(i){return g.error("Failed to create analytics from stream result",{provider:e,model:t,error:i instanceof Error?i.message:String(i)}),Fh(e,t,{usage:{input:0,output:0,total:0}},o,{...s,streamingMode:!0,analyticsError:!0})}}cleanup(){let e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},jOe=new ste});function LG(r,e,t){return!t||!e||Object.keys(e).length===0?"none":r.toolChoice??"auto"}var ite=E(()=>{"use strict"});var ar,ys=E(()=>{"use strict";ql();oi();VOe();Vn();V();jm();gee();Rn();yA();ite();eh();Wh();ar=class extends Mn{config;resolvedModel;constructor(e,t,n,o){super(t,e,n),this.config=o}getFallbackModelName(){return"gpt-3.5-turbo"}getFallbackModels(){return[]}adjustBuildBodyOptions(e,t){return t}adjustResponseFormat(e,t){return e}adjustRequestBody(e,t){return e}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ci(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}supportsTools(){return!0}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){let e=await this.resolveModelName();return this.buildDelegatingModel(e)}async resolveModelName(){if(this.resolvedModel)return this.resolvedModel;let e=this.modelName||this.getDefaultModel();if(e&&e.trim()!=="")return this.resolvedModel=e,this.modelName!==e&&this.refreshHandlersForModel(e),e;if(this.shouldAutoDiscoverModel()){try{let n=await this.getAvailableModels();if(n.length>0)return this.resolvedModel=n[0],this.refreshHandlersForModel(n[0]),g.info(`\u{1F50D} Auto-discovered model: ${n[0]} from ${n.length} available models`),n[0]}catch(n){g.warn("Model auto-discovery failed, using fallback:",n)}return this.getFallbackModelName()}let t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){let t=this.getChatCompletionsURL(e),n=Ze(),o=this.getAuthHeaders.bind(this),s=this.providerName,i=this.adjustBuildBodyOptions.bind(this),a=this.adjustResponseFormat.bind(this),c=this.adjustRequestBody.bind(this),l=u=>this.getTimeout(u??{});return{specificationVersion:"v3",provider:s,modelId:e,supportedUrls:{},doGenerate:async u=>{let d=tte(u.prompt),m=u.responseFormat?a(LOe(u.responseFormat),e):void 0,f=rte(c(nte({modelId:e,messages:d,options:i(e,{maxTokens:u.maxOutputTokens,temperature:u.temperature,topP:u.topP,presencePenalty:u.presencePenalty,frequencyPenalty:u.frequencyPenalty,seed:u.seed,stopSequences:u.stopSequences}),tools:NOe(u.tools),...u.toolChoice?{toolChoice:DOe(u.toolChoice)}:{},streaming:!1,...m?{responseFormat:m}:{}}),e)),h=Is(l(u),s,"generate"),y=Fm(u.abortSignal,h?.controller.signal),x;try{x=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(f),...y?{signal:y}:{}})}finally{h?.cleanup()}if(!x.ok)throw await ote(t,f,x);let b=await x.json(),S=b.choices?.[0],w=(typeof S?.message?.content=="string"?S.message.content:"")??"",_=[],C=S?.message?.reasoning_content??S?.message?.reasoning;typeof C=="string"&&C.length>0&&_.push({type:"reasoning",text:C}),w.length>0&&_.push({type:"text",text:w});for(let R of S?.message?.tool_calls??[])_.push({type:"tool-call",toolCallId:R.id,toolName:R.function.name,input:R.function.arguments??""});let k=S?.finish_reason;return{content:_,finishReason:{unified:k==="length"?"length":k==="tool_calls"||k==="function_call"?"tool-calls":k==="content_filter"?"content-filter":"stop",raw:k??"stop"},usage:{inputTokens:{total:b.usage?.prompt_tokens,noCache:b.usage?.prompt_tokens,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:b.usage?.completion_tokens,text:b.usage?.completion_tokens!==void 0&&b.usage?.completion_tokens_details?.reasoning_tokens!==void 0?b.usage.completion_tokens-b.usage.completion_tokens_details.reasoning_tokens:b.usage?.completion_tokens,reasoning:b.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:f},response:{...b.id?{id:b.id}:{},...b.model?{modelId:b.model}:{},headers:{},body:b}}},doStream:()=>{throw new Error(`${s}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}async executeStream(e,t){this.validateStreamOptions(e);let n=Date.now(),o=this.getTimeout(e),s=Is(o,this.providerName,"stream"),i=new AbortController,a=l_e([e.abortSignal,s?.controller.signal,i.signal]).signal,c,l,u,d,m;try{c=await this.resolveModelName();let $=!e.disableTools&&this.supportsTools();l=$?e.tools||await this.getAllTools():{},u=$?OOe(l):void 0,d=UOe(LG(e,l,$));let L=await this.buildMessagesForStream(e);m=tte(L)}catch($){throw s?.cleanup(),$}let f=this.getChatCompletionsURL(c),h=Ze(),y=e.maxSteps||Vo,x=this.neurolink?.getEventEmitter(),b=[],S=[],{usagePromise:w,finishPromise:_,resolveUsage:C,resolveFinish:k}=BOe(),{pushChunk:I,nextChunk:R}=zOe(),A=this.onStreamStart(c),M=this.runStreamLoop({maxSteps:y,modelId:c,url:f,fetchImpl:h,abortSignal:a,options:e,conversation:m,openAITools:u,openAIToolChoice:d,toolsRecord:l,emitter:x,toolsUsed:b,toolExecutionSummaries:S,pushChunk:I,resolveUsage:C,resolveFinish:k}),D,B=$=>{D=$};A?.onUsage&&w.then(A.onUsage).catch(()=>{}),A?.onFinish&&_.then($=>A.onFinish?.($,D)).catch(()=>{});let O=this.providerName,N={stream:async function*(){let $=0;try{for(;;){let L=await R();if("done"in L)break;"content"in L&&typeof L.content=="string"&&L.content.length>0&&$++,yield L}if(await M,$===0&&b.length===0){g.warn(`${O}: Stream produced no output \u2014 emitting enriched sentinel`);let L=new Nc({message:"Stream produced no output"}),z=await kv(L,void 0,D);Rv(z),yield z}}catch(L){if(Nc.isInstance(L)){let F=await kv(L,void 0,D);Rv(F),yield F;return}let z=await kv(L,void 0,D);throw Rv(z),yield z,L}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:c,analytics:jOe.createAnalytics(this.providerName,c,{textStream:(async function*(){})(),usage:w,finishReason:_},Date.now()-n,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:b,metadata:{startTime:n,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(N,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Eu(S.map($=>({toolName:$.toolName,input:$.input,output:$.output,duration:$.endTime.getTime()-$.startTime.getTime()})))}),M.finally(()=>s?.cleanup()).catch($=>{B($)}),N}async runStreamLoop(e){let{maxSteps:t,modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:c,openAITools:l,openAIToolChoice:u,toolsRecord:d,emitter:m,toolsUsed:f,toolExecutionSummaries:h,pushChunk:y,resolveUsage:x,resolveFinish:b}=e;try{let S=null,w;for(let _=0;_<t;_++){let C=await this.streamOneStep({modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:c,openAITools:l,openAIToolChoice:u,pushChunk:y});if(S=C.finishReason,C.usage&&(w=GOe(w,C.usage)),C.toolCalls.size===0)break;await this.executeToolBatch({stepResult:C,conversation:c,toolsRecord:d,emitter:m,toolsUsed:f,toolExecutionSummaries:h,options:a})}return x({promptTokens:w?.prompt_tokens??0,completionTokens:w?.completion_tokens??0,totalTokens:w?.total_tokens??0}),b(S??"stop"),y({done:!0}),{finishReason:S??"stop",usage:w}}catch(S){throw g.error(`${this.providerName}: Stream error`,{error:S instanceof Error?S.message:String(S)}),x({promptTokens:0,completionTokens:0,totalTokens:0}),b("error"),y({done:!0}),S}}async streamOneStep(e){let t=rte(this.adjustRequestBody(nte({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,e.options),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),n=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(t),...e.abortSignal?{signal:e.abortSignal}:{}});if(!n.ok)throw await ote(e.url,t,n);if(!n.body)throw new Error(`${this.providerName}: stream response had no body`);return $Oe(n.body,o=>{e.pushChunk({content:o})},o=>{e.pushChunk({content:"",reasoning:o})})}async executeToolBatch(e){let{stepResult:t,conversation:n,toolsRecord:o,emitter:s,toolsUsed:i,toolExecutionSummaries:a,options:c}=e,l=[];for(let[,d]of t.toolCalls)l.push({id:d.id,type:"function",function:{name:d.name,arguments:d.argsBuffered}});n.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:l});for(let[,d]of t.toolCalls){let m=new Date,f;try{f=JSON.parse(d.argsBuffered||"{}")}catch{f=d.argsBuffered}let h,y,x=o[d.name];if(s?.emit("tool:start",{toolName:d.name,toolCallId:d.id,input:f}),!x||typeof x.execute!="function")y=`Tool '${d.name}' is not registered.`,h={error:y};else try{h=await x.execute(f,{})}catch(S){y=S instanceof Error?S.message:String(S),h={error:y}}let b=new Date;i.push(d.name),a.push({toolCallId:d.id,toolName:d.name,input:f,output:h,...y?{error:y}:{},startTime:m,endTime:b}),n.push({role:"tool",tool_call_id:d.id,content:ete(h)})}let u=a.slice(-t.toolCalls.size);sh(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){g.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:d instanceof Error?d.message:String(d)})}}async getAvailableModels(){try{let e=`${Ci(this.config.baseURL)}/models`;g.debug(`Fetching available models from: ${e}`);let t=Ze(),n=new AbortController,o=setTimeout(()=>n.abort(),5e3),s=await t(e,{headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},signal:n.signal});if(clearTimeout(o),!s.ok)return g.warn(`Models endpoint returned ${s.status}: ${s.statusText}`),this.getFallbackModels();let i=await s.json();if(!i.data||!Array.isArray(i.data))return g.warn("Invalid models response format"),this.getFallbackModels();let a=i.data.map(c=>c.id).filter(Boolean);return g.shouldLog("debug")&&g.debug(`Discovered ${a.length} models:`,a),a.length>0?a:this.getFallbackModels()}catch(e){return g.warn(`[${this.constructor.name}] Failed to fetch models from endpoint:`,e),this.getFallbackModels()}}async getFirstAvailableModel(){return(await this.getAvailableModels())[0]||this.getFallbackModelName()}}});var qOe={};K(qOe,{OpenAIProvider:()=>ate});var HOe,a9t,c9t,l9t,u9t,ate,WOe=E(()=>{"use strict";hr();Vn();mt();V();On();Ed();Nn();ff();qh();Rn();Wh();ys();HOe="https://api.openai.com/v1",a9t=(r,e)=>{let t=[r,e].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??HOe;try{let n=new URL(t),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ci(n.toString())}catch{}return t},c9t=()=>er(eOe()),l9t=()=>tr("OPENAI_MODEL","gpt-4o"),u9t=it.getTracer("neurolink.provider.openai"),ate=class extends ar{constructor(e,t,n,o){let s=o?.apiKey?.trim(),i=s&&s.length>0?s:c9t(),a=a9t(o?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:a,apiKey:i}),g.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Qt(this.config.baseURL)})}getProviderName(){return"openai"}getDefaultModel(){return l9t()}formatProviderError(e){if(e instanceof At)return new ht(e.message,this.providerName);let t=e,n=t?.message&&typeof t.message=="string"?t.message:"Unknown error",o=t?.type&&typeof t.type=="string"?t.type:void 0,s=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return n.includes("API_KEY_INVALID")||n.includes("Invalid API key")||n.includes("Incorrect API key")||n.includes("invalid_api_key")||o==="invalid_api_key"||s===401?new ut(n.includes("Incorrect API key")||n.includes("Invalid API key")?n:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable.",this.providerName):n.includes("rate limit")||o==="rate_limit_error"||s===429?new Rt("OpenAI rate limit exceeded. Please try again later.",this.providerName):n.includes("model_not_found")?new Ct(`Model not found: ${this.modelName}`,this.providerName):new Te(`OpenAI error: ${n}`,this.providerName)}onStreamStart(e){let t=u9t.startSpan("neurolink.provider.streamText",{kind:gr.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}}),n=!1,o=()=>{n||(n=!0,t.end())};return{onUsage:s=>{t.setAttribute("gen_ai.usage.input_tokens",s.promptTokens),t.setAttribute("gen_ai.usage.output_tokens",s.completionTokens);let i=ko(this.providerName,this.modelName,{input:s.promptTokens,output:s.completionTokens,total:s.totalTokens});i&&i>0&&t.setAttribute("neurolink.cost",i)},onFinish:(s,i)=>{t.setAttribute("gen_ai.response.finish_reason",s||"unknown"),s==="error"&&t.setStatus({code:me.ERROR,message:i instanceof Error?i.message:String(i??"stream error")}),o()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let[o]=await this.callEmbeddings(n,[e],"embed");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await this.callEmbeddings(n,e,"embedMany");return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}async callEmbeddings(e,t,n){let o=`${Ci(this.config.baseURL)}/embeddings`,s=Ze(),i=Is(3e4,this.providerName,"generate");try{let a=await s(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!a.ok){let u=await a.text().catch(()=>""),d=`OpenAI ${n} failed with status ${a.status}`,m;if(u)try{let f=JSON.parse(u);f.error?.message&&(d=f.error.message),m=f.error?.type}catch{}throw Object.assign(new Error(d),{status:a.status,type:m})}let l=((await a.json()).data??[]).map(u=>u.embedding).filter(u=>Array.isArray(u));if(l.length===0)throw new Te(`OpenAI ${n} returned no embeddings`,this.providerName);return l}finally{i?.cleanup()}}async executeImageGeneration(e){let t=Date.now(),n=e.prompt??e.input?.text??"";if(!n.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");let o=e.model??this.modelName,s=Ci(this.config.baseURL??HOe),i=e,a=i.size??this.aspectRatioToOpenAISize(i.aspectRatio,o),c=i.numberOfImages??1,l;o==="gpt-image-1"||o.startsWith("dall-e-3")?l=1:o.startsWith("dall-e-2")?l=Math.min(Math.max(c,1),10):l=1;let d={model:o,prompt:n,n:l,size:a};o==="gpt-image-1"?i.quality&&(d.quality=i.quality):o.startsWith("dall-e-3")?(d.response_format="b64_json",i.quality&&(d.quality=i.quality),i.style&&(d.style=i.style)):d.response_format="b64_json";let m=12e4,f=new AbortController,h=setTimeout(()=>f.abort(),m),y;try{y=await Ze()(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:f.signal})}catch(_){throw _ instanceof Error&&_.name==="AbortError"?new Error(`OpenAI image generation timed out after ${m/1e3}s`,{cause:_}):_}finally{clearTimeout(h)}if(!y.ok){let _=await y.text();throw new Error(`OpenAI image generation failed: ${y.status} \u2014 ${_}`)}let b=(await y.json()).data?.[0];if(!b)throw new Error("OpenAI image generation returned no images");let S=b.b64_json;if(!S&&b.url){await ol(b.url);let _=Ze(),C=new AbortController,k=setTimeout(()=>C.abort(),6e4),I;try{I=await _(b.url,{signal:C.signal})}catch(A){throw A instanceof Error&&A.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:A}):A}finally{clearTimeout(k)}if(!I.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${b.url} (${I.status})`);S=(await ca(I,26214400,"OpenAI image fallback")).toString("base64")}if(!S)throw new Error("OpenAI image generation returned neither b64_json nor a URL");let w=Date.now()-t;return g.info(`[OpenAIProvider] Generated image (${S.length} base64 chars) in ${w}ms \u2014 model ${o}`),{content:b.revised_prompt??n,provider:this.providerName,model:o,usage:{input:0,output:0,total:0},imageOutput:{base64:S}}}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"}}});function h9t(r){var e;let t=r?.anthropic;return(e=t?.cacheControl)!=null?e:t?.cache_control}async function $9t({tools:r,toolChoice:e,disableParallelToolUse:t,cacheControlValidator:n,supportsStructuredOutput:o,supportsStrictTools:s}){var i;r=r?.length?r:void 0;let a=[],c=new Set,l=n||new dte;if(r==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a,betas:c};let u=[];for(let m of r)switch(m.type){case"function":{let f=l.getCacheControl(m.providerOptions,{type:"tool definition",canCache:!0}),h=(i=m.providerOptions)==null?void 0:i.anthropic,y=h?.eagerInputStreaming,x=h?.deferLoading,b=h?.allowedCallers;!s&&m.strict!=null&&a.push({type:"unsupported",feature:"strict",details:`Tool '${m.name}' has strict: ${m.strict}, but strict mode is not supported by this provider. The strict property will be ignored.`}),u.push({name:m.name,description:m.description,input_schema:m.inputSchema,cache_control:f,...y?{eager_input_streaming:!0}:{},...s===!0&&m.strict!=null?{strict:m.strict}:{},...x!=null?{defer_loading:x}:{},...b!=null?{allowed_callers:b}:{},...m.inputExamples!=null?{input_examples:m.inputExamples.map(S=>S.input)}:{}}),o===!0&&c.add("structured-outputs-2025-11-13"),(m.inputExamples!=null||b!=null)&&c.add("advanced-tool-use-2025-11-20");break}case"provider":{switch(m.id){case"anthropic.code_execution_20250522":{c.add("code-execution-2025-05-22"),u.push({type:"code_execution_20250522",name:"code_execution",cache_control:void 0});break}case"anthropic.code_execution_20250825":{c.add("code-execution-2025-08-25"),u.push({type:"code_execution_20250825",name:"code_execution"});break}case"anthropic.code_execution_20260120":{u.push({type:"code_execution_20260120",name:"code_execution"});break}case"anthropic.computer_20250124":{c.add("computer-use-2025-01-24"),u.push({name:"computer",type:"computer_20250124",display_width_px:m.args.displayWidthPx,display_height_px:m.args.displayHeightPx,display_number:m.args.displayNumber,cache_control:void 0});break}case"anthropic.computer_20251124":{c.add("computer-use-2025-11-24"),u.push({name:"computer",type:"computer_20251124",display_width_px:m.args.displayWidthPx,display_height_px:m.args.displayHeightPx,display_number:m.args.displayNumber,enable_zoom:m.args.enableZoom,cache_control:void 0});break}case"anthropic.computer_20241022":{c.add("computer-use-2024-10-22"),u.push({name:"computer",type:"computer_20241022",display_width_px:m.args.displayWidthPx,display_height_px:m.args.displayHeightPx,display_number:m.args.displayNumber,cache_control:void 0});break}case"anthropic.text_editor_20250124":{c.add("computer-use-2025-01-24"),u.push({name:"str_replace_editor",type:"text_editor_20250124",cache_control:void 0});break}case"anthropic.text_editor_20241022":{c.add("computer-use-2024-10-22"),u.push({name:"str_replace_editor",type:"text_editor_20241022",cache_control:void 0});break}case"anthropic.text_editor_20250429":{c.add("computer-use-2025-01-24"),u.push({name:"str_replace_based_edit_tool",type:"text_editor_20250429",cache_control:void 0});break}case"anthropic.text_editor_20250728":{let f=await ur({value:m.args,schema:y9t});u.push({name:"str_replace_based_edit_tool",type:"text_editor_20250728",max_characters:f.maxCharacters,cache_control:void 0});break}case"anthropic.bash_20250124":{c.add("computer-use-2025-01-24"),u.push({name:"bash",type:"bash_20250124",cache_control:void 0});break}case"anthropic.bash_20241022":{c.add("computer-use-2024-10-22"),u.push({name:"bash",type:"bash_20241022",cache_control:void 0});break}case"anthropic.memory_20250818":{c.add("context-management-2025-06-27"),u.push({name:"memory",type:"memory_20250818"});break}case"anthropic.web_fetch_20250910":{c.add("web-fetch-2025-09-10");let f=await ur({value:m.args,schema:D9t});u.push({type:"web_fetch_20250910",name:"web_fetch",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,citations:f.citations,max_content_tokens:f.maxContentTokens,cache_control:void 0});break}case"anthropic.web_fetch_20260209":{c.add("code-execution-web-tools-2026-02-09");let f=await ur({value:m.args,schema:I9t});u.push({type:"web_fetch_20260209",name:"web_fetch",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,citations:f.citations,max_content_tokens:f.maxContentTokens,cache_control:void 0});break}case"anthropic.web_search_20250305":{let f=await ur({value:m.args,schema:C9t});u.push({type:"web_search_20250305",name:"web_search",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,user_location:f.userLocation,cache_control:void 0});break}case"anthropic.web_search_20260209":{c.add("code-execution-web-tools-2026-02-09");let f=await ur({value:m.args,schema:T9t});u.push({type:"web_search_20260209",name:"web_search",max_uses:f.maxUses,allowed_domains:f.allowedDomains,blocked_domains:f.blockedDomains,user_location:f.userLocation,cache_control:void 0});break}case"anthropic.tool_search_regex_20251119":{u.push({type:"tool_search_tool_regex_20251119",name:"tool_search_tool_regex"});break}case"anthropic.tool_search_bm25_20251119":{u.push({type:"tool_search_tool_bm25_20251119",name:"tool_search_tool_bm25"});break}default:{a.push({type:"unsupported",feature:`provider-defined tool ${m.id}`});break}}break}default:{a.push({type:"unsupported",feature:`tool ${m}`});break}}if(e==null)return{tools:u,toolChoice:t?{type:"auto",disable_parallel_tool_use:t}:void 0,toolWarnings:a,betas:c};let d=e.type;switch(d){case"auto":return{tools:u,toolChoice:{type:"auto",disable_parallel_tool_use:t},toolWarnings:a,betas:c};case"required":return{tools:u,toolChoice:{type:"any",disable_parallel_tool_use:t},toolWarnings:a,betas:c};case"none":return{tools:void 0,toolChoice:void 0,toolWarnings:a,betas:c};case"tool":return{tools:u,toolChoice:{type:"tool",name:e.toolName,disable_parallel_tool_use:t},toolWarnings:a,betas:c};default:{let m=d;throw new Jr({functionality:`tool choice type: ${m}`})}}}function YOe({usage:r,rawUsage:e}){var t,n;let o=(t=r.cache_creation_input_tokens)!=null?t:0,s=(n=r.cache_read_input_tokens)!=null?n:0,i,a;if(r.iterations&&r.iterations.length>0){let c=r.iterations.reduce((l,u)=>({input:l.input+u.input_tokens,output:l.output+u.output_tokens}),{input:0,output:0});i=c.input,a=c.output}else i=r.input_tokens,a=r.output_tokens;return{inputTokens:{total:i+o+s,noCache:i,cacheRead:s,cacheWrite:o},outputTokens:{total:a,text:void 0,reasoning:void 0},raw:e??r}}function Y9t(r){if(typeof r=="string")return new TextDecoder().decode(Pc(r));if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw r instanceof URL?new Jr({functionality:"URL-based text documents are not supported for citations"}):new Jr({functionality:`unsupported data type for text documents: ${typeof r}`})}function cte(r){return r instanceof URL||Q9t(r)}function Q9t(r){return typeof r=="string"&&/^https?:\/\//i.test(r)}function lte(r){return r instanceof URL?r.toString():r}async function eXt({prompt:r,sendReasoning:e,warnings:t,cacheControlValidator:n,toolNameMapping:o}){var s,i,a,c,l,u,d,m,f,h,y,x,b,S,w,_,C,k,I;let R=new Set,A=tXt(r),M=n||new dte,D,B=[];async function O(N){var $,L;let z=await Fn({provider:"anthropic",providerOptions:N,schema:JOe});return(L=($=z?.citations)==null?void 0:$.enabled)!=null?L:!1}async function U(N){let $=await Fn({provider:"anthropic",providerOptions:N,schema:JOe});return{title:$?.title,context:$?.context}}for(let N=0;N<A.length;N++){let $=A[N],L=N===A.length-1,z=$.type;switch(z){case"system":{if(D!=null)throw new Jr({functionality:"Multiple system messages that are separated by user/assistant messages"});D=$.messages.map(({content:F,providerOptions:j})=>({type:"text",text:F,cache_control:M.getCacheControl(j,{type:"system message",canCache:!0})}));break}case"user":{let F=[];for(let j of $.messages){let{role:H,content:J}=j;switch(H){case"user":{for(let he=0;he<J.length;he++){let Y=J[he],ve=he===J.length-1,W=(s=M.getCacheControl(Y.providerOptions,{type:"user message part",canCache:!0}))!=null?s:ve?M.getCacheControl(j.providerOptions,{type:"user message",canCache:!0}):void 0;switch(Y.type){case"text":{F.push({type:"text",text:Y.text,cache_control:W});break}case"file":{if(Y.mediaType.startsWith("image/"))F.push({type:"image",source:cte(Y.data)?{type:"url",url:lte(Y.data)}:{type:"base64",media_type:Y.mediaType==="image/*"?"image/jpeg":Y.mediaType,data:Al(Y.data)},cache_control:W});else if(Y.mediaType==="application/pdf"){R.add("pdfs-2024-09-25");let Ie=await O(Y.providerOptions),Me=await U(Y.providerOptions);F.push({type:"document",source:cte(Y.data)?{type:"url",url:lte(Y.data)}:{type:"base64",media_type:"application/pdf",data:Al(Y.data)},title:(i=Me.title)!=null?i:Y.filename,...Me.context&&{context:Me.context},...Ie&&{citations:{enabled:!0}},cache_control:W})}else if(Y.mediaType==="text/plain"){let Ie=await O(Y.providerOptions),Me=await U(Y.providerOptions);F.push({type:"document",source:cte(Y.data)?{type:"url",url:lte(Y.data)}:{type:"text",media_type:"text/plain",data:Y9t(Y.data)},title:(a=Me.title)!=null?a:Y.filename,...Me.context&&{context:Me.context},...Ie&&{citations:{enabled:!0}},cache_control:W})}else throw new Jr({functionality:`media type: ${Y.mediaType}`});break}}}break}case"tool":{for(let he=0;he<J.length;he++){let Y=J[he];if(Y.type==="tool-approval-response")continue;let ve=he===J.length-1,W=(c=M.getCacheControl(Y.providerOptions,{type:"tool result part",canCache:!0}))!=null?c:ve?M.getCacheControl(j.providerOptions,{type:"tool result message",canCache:!0}):void 0,Ie=Y.output,Me;switch(Ie.type){case"content":Me=Ie.value.map(ye=>{var Q;switch(ye.type){case"text":return{type:"text",text:ye.text};case"image-data":return{type:"image",source:{type:"base64",media_type:ye.mediaType,data:ye.data}};case"image-url":return{type:"image",source:{type:"url",url:ye.url}};case"file-url":return{type:"document",source:{type:"url",url:ye.url}};case"file-data":{if(ye.mediaType==="application/pdf")return R.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:ye.mediaType,data:ye.data}};t.push({type:"other",message:`unsupported tool content part type: ${ye.type} with media type: ${ye.mediaType}`});return}case"custom":{let oe=(Q=ye.providerOptions)==null?void 0:Q.anthropic;if(oe?.type==="tool-reference")return{type:"tool_reference",tool_name:oe.toolName};t.push({type:"other",message:"unsupported custom tool content part"});return}default:{t.push({type:"other",message:`unsupported tool content part type: ${ye.type}`});return}}}).filter(lR);break;case"text":case"error-text":Me=Ie.value;break;case"execution-denied":Me=(l=Ie.reason)!=null?l:"Tool execution denied.";break;default:Me=JSON.stringify(Ie.value);break}F.push({type:"tool_result",tool_use_id:Y.toolCallId,content:Me,is_error:Ie.type==="error-text"||Ie.type==="error-json"?!0:void 0,cache_control:W})}break}default:{let he=H;throw new Error(`Unsupported role: ${he}`)}}}B.push({role:"user",content:F});break}case"assistant":{let F=[],j=new Set;for(let H=0;H<$.messages.length;H++){let J=$.messages[H],he=H===$.messages.length-1,{content:Y}=J;for(let ve=0;ve<Y.length;ve++){let W=Y[ve],Ie=ve===Y.length-1,Me=(u=M.getCacheControl(W.providerOptions,{type:"assistant message part",canCache:!0}))!=null?u:Ie?M.getCacheControl(J.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(W.type){case"text":{let ye=(d=W.providerOptions)==null?void 0:d.anthropic;ye?.type==="compaction"?F.push({type:"compaction",content:W.text,cache_control:Me}):F.push({type:"text",text:L&&he&&Ie?W.text.trim():W.text,cache_control:Me});break}case"reasoning":{if(e){let ye=await Fn({provider:"anthropic",providerOptions:W.providerOptions,schema:g9t});ye!=null?ye.signature!=null?(M.getCacheControl(W.providerOptions,{type:"thinking block",canCache:!1}),F.push({type:"thinking",thinking:W.text,signature:ye.signature})):ye.redactedData!=null?(M.getCacheControl(W.providerOptions,{type:"redacted thinking block",canCache:!1}),F.push({type:"redacted_thinking",data:ye.redactedData})):t.push({type:"other",message:"unsupported reasoning metadata"}):t.push({type:"other",message:"unsupported reasoning metadata"})}else t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case"tool-call":{if(W.providerExecuted){let oe=o.toProviderToolName(W.toolName);if(((f=(m=W.providerOptions)==null?void 0:m.anthropic)==null?void 0:f.type)==="mcp-tool-use"){j.add(W.toolCallId);let te=(y=(h=W.providerOptions)==null?void 0:h.anthropic)==null?void 0:y.serverName;if(te==null||typeof te!="string"){t.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}F.push({type:"mcp_tool_use",id:W.toolCallId,name:W.toolName,input:W.input,server_name:te,cache_control:Me})}else if(oe==="code_execution"&&W.input!=null&&typeof W.input=="object"&&"type"in W.input&&typeof W.input.type=="string"&&(W.input.type==="bash_code_execution"||W.input.type==="text_editor_code_execution"))F.push({type:"server_tool_use",id:W.toolCallId,name:W.input.type,input:W.input,cache_control:Me});else if(oe==="code_execution"&&W.input!=null&&typeof W.input=="object"&&"type"in W.input&&W.input.type==="programmatic-tool-call"){let{type:te,...Qe}=W.input;F.push({type:"server_tool_use",id:W.toolCallId,name:"code_execution",input:Qe,cache_control:Me})}else oe==="code_execution"||oe==="web_fetch"||oe==="web_search"?F.push({type:"server_tool_use",id:W.toolCallId,name:oe,input:W.input,cache_control:Me}):oe==="tool_search_tool_regex"||oe==="tool_search_tool_bm25"?F.push({type:"server_tool_use",id:W.toolCallId,name:oe,input:W.input,cache_control:Me}):t.push({type:"other",message:`provider executed tool call for tool ${W.toolName} is not supported`});break}let ye=(x=W.providerOptions)==null?void 0:x.anthropic,Q=ye?.caller?(ye.caller.type==="code_execution_20250825"||ye.caller.type==="code_execution_20260120")&&ye.caller.toolId?{type:ye.caller.type,tool_id:ye.caller.toolId}:ye.caller.type==="direct"?{type:"direct"}:void 0:void 0;F.push({type:"tool_use",id:W.toolCallId,name:W.toolName,input:W.input,...Q&&{caller:Q},cache_control:Me});break}case"tool-result":{let ye=o.toProviderToolName(W.toolName);if(j.has(W.toolCallId)){let Q=W.output;if(Q.type!=="json"&&Q.type!=="error-json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}F.push({type:"mcp_tool_result",tool_use_id:W.toolCallId,is_error:Q.type==="error-json",content:Q.value,cache_control:Me})}else if(ye==="code_execution"){let Q=W.output;if(Q.type==="error-text"||Q.type==="error-json"){let oe={};try{typeof Q.value=="string"?oe=JSON.parse(Q.value):typeof Q.value=="object"&&Q.value!==null&&(oe=Q.value)}catch{}oe.type==="code_execution_tool_result_error"?F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(b=oe.errorCode)!=null?b:"unknown"},cache_control:Me}):F.push({type:"bash_code_execution_tool_result",tool_use_id:W.toolCallId,cache_control:Me,content:{type:"bash_code_execution_tool_result_error",error_code:(S=oe.errorCode)!=null?S:"unknown"}});break}if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}if(Q.value==null||typeof Q.value!="object"||!("type"in Q.value)||typeof Q.value.type!="string"){t.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${W.toolName}`});break}if(Q.value.type==="code_execution_result"){let oe=await ur({value:Q.value,schema:oNe});F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:oe.type,stdout:oe.stdout,stderr:oe.stderr,return_code:oe.return_code,content:(w=oe.content)!=null?w:[]},cache_control:Me})}else if(Q.value.type==="encrypted_code_execution_result"){let oe=await ur({value:Q.value,schema:iNe});oe.type==="encrypted_code_execution_result"&&F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:oe.type,encrypted_stdout:oe.encrypted_stdout,stderr:oe.stderr,return_code:oe.return_code,content:(_=oe.content)!=null?_:[]},cache_control:Me})}else{let oe=await ur({value:Q.value,schema:sNe});oe.type==="code_execution_result"?F.push({type:"code_execution_tool_result",tool_use_id:W.toolCallId,content:{type:oe.type,stdout:oe.stdout,stderr:oe.stderr,return_code:oe.return_code,content:(C=oe.content)!=null?C:[]},cache_control:Me}):oe.type==="bash_code_execution_result"||oe.type==="bash_code_execution_tool_result_error"?F.push({type:"bash_code_execution_tool_result",tool_use_id:W.toolCallId,cache_control:Me,content:oe}):F.push({type:"text_editor_code_execution_tool_result",tool_use_id:W.toolCallId,cache_control:Me,content:oe})}break}if(ye==="web_fetch"){let Q=W.output;if(Q.type==="error-json"){let pe={};try{typeof Q.value=="string"?pe=JSON.parse(Q.value):typeof Q.value=="object"&&Q.value!==null&&(pe=Q.value)}catch{let Qe=(k=Q.value)==null?void 0:k.errorCode;pe={errorCode:typeof Qe=="string"?Qe:"unavailable"}}F.push({type:"web_fetch_tool_result",tool_use_id:W.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(I=pe.errorCode)!=null?I:"unavailable"},cache_control:Me});break}if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}let oe=await ur({value:Q.value,schema:nNe});F.push({type:"web_fetch_tool_result",tool_use_id:W.toolCallId,content:{type:"web_fetch_result",url:oe.url,retrieved_at:oe.retrievedAt,content:{type:"document",title:oe.content.title,citations:oe.content.citations,source:{type:oe.content.source.type,media_type:oe.content.source.mediaType,data:oe.content.source.data}}},cache_control:Me});break}if(ye==="web_search"){let Q=W.output;if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}let oe=await ur({value:Q.value,schema:rNe});F.push({type:"web_search_tool_result",tool_use_id:W.toolCallId,content:oe.map(pe=>({url:pe.url,title:pe.title,page_age:pe.pageAge,encrypted_content:pe.encryptedContent,type:pe.type})),cache_control:Me});break}if(ye==="tool_search_tool_regex"||ye==="tool_search_tool_bm25"){let Q=W.output;if(Q.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${Q.type} for tool ${W.toolName} is not supported`});break}let pe=(await ur({value:Q.value,schema:aNe})).map(te=>({type:"tool_reference",tool_name:te.toolName}));F.push({type:"tool_search_tool_result",tool_use_id:W.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:pe},cache_control:Me});break}t.push({type:"other",message:`provider executed tool result for tool ${W.toolName} is not supported`});break}}}}B.push({role:"assistant",content:F});break}default:{let F=z;throw new Error(`content type: ${F}`)}}}return{prompt:{system:D,messages:B},betas:R}}function tXt(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case"system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case"assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case"user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case"tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let s=o;throw new Error(`Unsupported role: ${s}`)}}}return e}function ute({finishReason:r,isJsonResponseFromTool:e}){switch(r){case"pause_turn":case"end_turn":case"stop_sequence":return"stop";case"refusal":return"content-filter";case"tool_use":return e?"stop":"tool-calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"compaction":return"other";default:return"other"}}function QOe(r,e,t){var n;if(r.type==="web_search_result_location")return{type:"source",sourceType:"url",id:t(),url:r.url,title:r.title,providerMetadata:{anthropic:{citedText:r.cited_text,encryptedIndex:r.encrypted_index}}};if(r.type!=="page_location"&&r.type!=="char_location")return;let o=e[r.document_index];if(o)return{type:"source",sourceType:"document",id:t(),mediaType:o.mediaType,title:(n=r.document_title)!=null?n:o.title,filename:o.filename,providerMetadata:{anthropic:r.type==="page_location"?{citedText:r.cited_text,startPageNumber:r.start_page_number,endPageNumber:r.end_page_number}:{citedText:r.cited_text,startCharIndex:r.start_char_index,endCharIndex:r.end_char_index}}}}function nXt(r){return r.includes("claude-sonnet-4-6")||r.includes("claude-opus-4-6")?{maxOutputTokens:128e3,supportsStructuredOutput:!0,isKnownModel:!0}:r.includes("claude-sonnet-4-5")||r.includes("claude-opus-4-5")||r.includes("claude-haiku-4-5")?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:r.includes("claude-opus-4-1")?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:r.includes("claude-sonnet-4-")?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:r.includes("claude-opus-4-")?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:r.includes("claude-3-haiku")?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function eNe(r){if(!r)return!1;let e=!1,t=!1;for(let n of r){if("type"in n&&(n.type==="web_fetch_20260209"||n.type==="web_search_20260209")){e=!0;continue}if(n.name==="code_execution"){t=!0;break}}return e&&!t}function tNe(r){return r?{appliedEdits:r.applied_edits.map(e=>{switch(e.type){case"clear_tool_uses_20250919":return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case"clear_thinking_20251015":return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens};case"compact_20260112":return{type:e.type}}}).filter(e=>e!==void 0)}:null}function cP(r={}){var e,t;let n=(e=Ug(up({settingValue:r.baseURL,environmentVariableName:"ANTHROPIC_BASE_URL"})))!=null?e:"https://api.anthropic.com/v1",o=(t=r.name)!=null?t:"anthropic.messages";if(r.apiKey&&r.authToken)throw new VT({argument:"apiKey/authToken",message:"Both apiKey and authToken were provided. Please use only one authentication method."});let s=()=>{let c=r.authToken?{Authorization:`Bearer ${r.authToken}`}:{"x-api-key":lS({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return yo({"anthropic-version":"2023-06-01",...c,...r.headers},`ai-sdk/anthropic/${d9t}`)},i=c=>{var l;return new rXt(c,{provider:o,baseURL:n,headers:s,fetch:r.fetch,generateId:(l=r.generateId)!=null?l:qn,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]})})},a=function(c){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return i(c)};return a.specificationVersion="v3",a.languageModel=i,a.chat=i,a.messages=i,a.embeddingModel=c=>{throw new Wk({modelId:c,modelType:"embeddingModel"})},a.textEmbeddingModel=a.embeddingModel,a.imageModel=c=>{throw new Wk({modelId:c,modelType:"imageModel"})},a.tools=CXt,a}var d9t,p9t,KOe,m9t,f9t,g9t,JOe,XOe,ZOe,dte,y9t,x9t,v9t,b9t,T9t,S9t,w9t,E9t,_9t,C9t,rNe,k9t,R9t,A9t,I9t,P9t,M9t,O9t,N9t,D9t,nNe,L9t,U9t,F9t,oNe,B9t,z9t,G9t,sNe,j9t,V9t,H9t,iNe,q9t,W9t,K9t,aNe,J9t,X9t,Z9t,rXt,oXt,sXt,iXt,aXt,cXt,lXt,uXt,dXt,pXt,mXt,fXt,gXt,hXt,yXt,xXt,vXt,bXt,TXt,SXt,wXt,EXt,_Xt,CXt,kXt,pte=E(()=>{xt();xe();xt();xe();xe();Ye();xe();Ye();Ye();xt();xe();Ye();xe();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();xt();xe();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();xe();Ye();d9t="3.0.64",p9t=ae(()=>se(p.object({type:p.literal("error"),error:p.object({type:p.string(),message:p.string()})}))),KOe=vo({errorSchema:p9t,errorToMessage:r=>r.error.message}),m9t=ae(()=>se(p.object({type:p.literal("message"),id:p.string().nullish(),model:p.string().nullish(),content:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("text"),text:p.string(),citations:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("web_search_result_location"),cited_text:p.string(),url:p.string(),title:p.string(),encrypted_index:p.string()}),p.object({type:p.literal("page_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_page_number:p.number(),end_page_number:p.number()}),p.object({type:p.literal("char_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_char_index:p.number(),end_char_index:p.number()})])).optional()}),p.object({type:p.literal("thinking"),thinking:p.string(),signature:p.string()}),p.object({type:p.literal("redacted_thinking"),data:p.string()}),p.object({type:p.literal("compaction"),content:p.string()}),p.object({type:p.literal("tool_use"),id:p.string(),name:p.string(),input:p.unknown(),caller:p.union([p.object({type:p.literal("code_execution_20250825"),tool_id:p.string()}),p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("server_tool_use"),id:p.string(),name:p.string(),input:p.record(p.string(),p.unknown()).nullish(),caller:p.union([p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("mcp_tool_use"),id:p.string(),name:p.string(),input:p.unknown(),server_name:p.string()}),p.object({type:p.literal("mcp_tool_result"),tool_use_id:p.string(),is_error:p.boolean(),content:p.array(p.union([p.string(),p.object({type:p.literal("text"),text:p.string()})]))}),p.object({type:p.literal("web_fetch_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("web_fetch_result"),url:p.string(),retrieved_at:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),media_type:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),media_type:p.literal("text/plain"),data:p.string()})])})}),p.object({type:p.literal("web_fetch_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("web_search_tool_result"),tool_use_id:p.string(),content:p.union([p.array(p.object({type:p.literal("web_search_result"),url:p.string(),title:p.string(),encrypted_content:p.string(),page_age:p.string().nullish()})),p.object({type:p.literal("web_search_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("code_execution_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("encrypted_code_execution_result"),encrypted_stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("bash_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("text_editor_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})])}),p.object({type:p.literal("tool_search_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("tool_search_tool_search_result"),tool_references:p.array(p.object({type:p.literal("tool_reference"),tool_name:p.string()}))}),p.object({type:p.literal("tool_search_tool_result_error"),error_code:p.string()})])})])),stop_reason:p.string().nullish(),stop_sequence:p.string().nullish(),usage:p.looseObject({input_tokens:p.number(),output_tokens:p.number(),cache_creation_input_tokens:p.number().nullish(),cache_read_input_tokens:p.number().nullish(),iterations:p.array(p.object({type:p.union([p.literal("compaction"),p.literal("message")]),input_tokens:p.number(),output_tokens:p.number()})).nullish()}),container:p.object({expires_at:p.string(),id:p.string(),skills:p.array(p.object({type:p.union([p.literal("anthropic"),p.literal("custom")]),skill_id:p.string(),version:p.string()})).nullish()}).nullish(),context_management:p.object({applied_edits:p.array(p.union([p.object({type:p.literal("clear_tool_uses_20250919"),cleared_tool_uses:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("clear_thinking_20251015"),cleared_thinking_turns:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("compact_20260112")})]))}).nullish()}))),f9t=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("message_start"),message:p.object({id:p.string().nullish(),model:p.string().nullish(),role:p.string().nullish(),usage:p.looseObject({input_tokens:p.number(),cache_creation_input_tokens:p.number().nullish(),cache_read_input_tokens:p.number().nullish()}),content:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("tool_use"),id:p.string(),name:p.string(),input:p.unknown(),caller:p.union([p.object({type:p.literal("code_execution_20250825"),tool_id:p.string()}),p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()})])).nullish(),stop_reason:p.string().nullish(),container:p.object({expires_at:p.string(),id:p.string()}).nullish()})}),p.object({type:p.literal("content_block_start"),index:p.number(),content_block:p.discriminatedUnion("type",[p.object({type:p.literal("text"),text:p.string()}),p.object({type:p.literal("thinking"),thinking:p.string()}),p.object({type:p.literal("tool_use"),id:p.string(),name:p.string(),input:p.record(p.string(),p.unknown()).optional(),caller:p.union([p.object({type:p.literal("code_execution_20250825"),tool_id:p.string()}),p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("redacted_thinking"),data:p.string()}),p.object({type:p.literal("compaction"),content:p.string().nullish()}),p.object({type:p.literal("server_tool_use"),id:p.string(),name:p.string(),input:p.record(p.string(),p.unknown()).nullish(),caller:p.union([p.object({type:p.literal("code_execution_20260120"),tool_id:p.string()}),p.object({type:p.literal("direct")})]).optional()}),p.object({type:p.literal("mcp_tool_use"),id:p.string(),name:p.string(),input:p.unknown(),server_name:p.string()}),p.object({type:p.literal("mcp_tool_result"),tool_use_id:p.string(),is_error:p.boolean(),content:p.array(p.union([p.string(),p.object({type:p.literal("text"),text:p.string()})]))}),p.object({type:p.literal("web_fetch_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("web_fetch_result"),url:p.string(),retrieved_at:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),media_type:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),media_type:p.literal("text/plain"),data:p.string()})])})}),p.object({type:p.literal("web_fetch_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("web_search_tool_result"),tool_use_id:p.string(),content:p.union([p.array(p.object({type:p.literal("web_search_result"),url:p.string(),title:p.string(),encrypted_content:p.string(),page_age:p.string().nullish()})),p.object({type:p.literal("web_search_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("code_execution_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("encrypted_code_execution_result"),encrypted_stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("bash_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()})])}),p.object({type:p.literal("text_editor_code_execution_tool_result"),tool_use_id:p.string(),content:p.discriminatedUnion("type",[p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})])}),p.object({type:p.literal("tool_search_tool_result"),tool_use_id:p.string(),content:p.union([p.object({type:p.literal("tool_search_tool_search_result"),tool_references:p.array(p.object({type:p.literal("tool_reference"),tool_name:p.string()}))}),p.object({type:p.literal("tool_search_tool_result_error"),error_code:p.string()})])})])}),p.object({type:p.literal("content_block_delta"),index:p.number(),delta:p.discriminatedUnion("type",[p.object({type:p.literal("input_json_delta"),partial_json:p.string()}),p.object({type:p.literal("text_delta"),text:p.string()}),p.object({type:p.literal("thinking_delta"),thinking:p.string()}),p.object({type:p.literal("signature_delta"),signature:p.string()}),p.object({type:p.literal("compaction_delta"),content:p.string().nullish()}),p.object({type:p.literal("citations_delta"),citation:p.discriminatedUnion("type",[p.object({type:p.literal("web_search_result_location"),cited_text:p.string(),url:p.string(),title:p.string(),encrypted_index:p.string()}),p.object({type:p.literal("page_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_page_number:p.number(),end_page_number:p.number()}),p.object({type:p.literal("char_location"),cited_text:p.string(),document_index:p.number(),document_title:p.string().nullable(),start_char_index:p.number(),end_char_index:p.number()})])})])}),p.object({type:p.literal("content_block_stop"),index:p.number()}),p.object({type:p.literal("error"),error:p.object({type:p.string(),message:p.string()})}),p.object({type:p.literal("message_delta"),delta:p.object({stop_reason:p.string().nullish(),stop_sequence:p.string().nullish(),container:p.object({expires_at:p.string(),id:p.string(),skills:p.array(p.object({type:p.union([p.literal("anthropic"),p.literal("custom")]),skill_id:p.string(),version:p.string()})).nullish()}).nullish()}),usage:p.looseObject({input_tokens:p.number().nullish(),output_tokens:p.number(),cache_creation_input_tokens:p.number().nullish(),cache_read_input_tokens:p.number().nullish(),iterations:p.array(p.object({type:p.union([p.literal("compaction"),p.literal("message")]),input_tokens:p.number(),output_tokens:p.number()})).nullish()}),context_management:p.object({applied_edits:p.array(p.union([p.object({type:p.literal("clear_tool_uses_20250919"),cleared_tool_uses:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("clear_thinking_20251015"),cleared_thinking_turns:p.number(),cleared_input_tokens:p.number()}),p.object({type:p.literal("compact_20260112")})]))}).nullish()}),p.object({type:p.literal("message_stop")}),p.object({type:p.literal("ping")})]))),g9t=ae(()=>se(p.object({signature:p.string().optional(),redactedData:p.string().optional()}))),JOe=p.object({citations:p.object({enabled:p.boolean()}).optional(),title:p.string().optional(),context:p.string().optional()}),XOe=p.object({sendReasoning:p.boolean().optional(),structuredOutputMode:p.enum(["outputFormat","jsonTool","auto"]).optional(),thinking:p.discriminatedUnion("type",[p.object({type:p.literal("adaptive")}),p.object({type:p.literal("enabled"),budgetTokens:p.number().optional()}),p.object({type:p.literal("disabled")})]).optional(),disableParallelToolUse:p.boolean().optional(),cacheControl:p.object({type:p.literal("ephemeral"),ttl:p.union([p.literal("5m"),p.literal("1h")]).optional()}).optional(),metadata:p.object({userId:p.string().optional()}).optional(),mcpServers:p.array(p.object({type:p.literal("url"),name:p.string(),url:p.string(),authorizationToken:p.string().nullish(),toolConfiguration:p.object({enabled:p.boolean().nullish(),allowedTools:p.array(p.string()).nullish()}).nullish()})).optional(),container:p.object({id:p.string().optional(),skills:p.array(p.object({type:p.union([p.literal("anthropic"),p.literal("custom")]),skillId:p.string(),version:p.string().optional()})).optional()}).optional(),toolStreaming:p.boolean().optional(),effort:p.enum(["low","medium","high","max"]).optional(),speed:p.enum(["fast","standard"]).optional(),anthropicBeta:p.array(p.string()).optional(),contextManagement:p.object({edits:p.array(p.discriminatedUnion("type",[p.object({type:p.literal("clear_tool_uses_20250919"),trigger:p.discriminatedUnion("type",[p.object({type:p.literal("input_tokens"),value:p.number()}),p.object({type:p.literal("tool_uses"),value:p.number()})]).optional(),keep:p.object({type:p.literal("tool_uses"),value:p.number()}).optional(),clearAtLeast:p.object({type:p.literal("input_tokens"),value:p.number()}).optional(),clearToolInputs:p.boolean().optional(),excludeTools:p.array(p.string()).optional()}),p.object({type:p.literal("clear_thinking_20251015"),keep:p.union([p.literal("all"),p.object({type:p.literal("thinking_turns"),value:p.number()})]).optional()}),p.object({type:p.literal("compact_20260112"),trigger:p.object({type:p.literal("input_tokens"),value:p.number()}).optional(),pauseAfterCompaction:p.boolean().optional(),instructions:p.string().optional()})]))}).optional()}),ZOe=4;dte=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(r,e){let t=h9t(r);if(t){if(!e.canCache){this.warnings.push({type:"unsupported",feature:"cache_control on non-cacheable context",details:`cache_control cannot be set on ${e.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>ZOe){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${ZOe} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return t}}getWarnings(){return this.warnings}},y9t=ae(()=>se(p.object({maxCharacters:p.number().optional()}))),x9t=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),v9t=xo({id:"anthropic.text_editor_20250728",inputSchema:x9t}),b9t=(r={})=>v9t(r),T9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),userLocation:p.object({type:p.literal("approximate"),city:p.string().optional(),region:p.string().optional(),country:p.string().optional(),timezone:p.string().optional()}).optional()}))),S9t=ae(()=>se(p.array(p.object({url:p.string(),title:p.string().nullable(),pageAge:p.string().nullable(),encryptedContent:p.string(),type:p.literal("web_search_result")})))),w9t=ae(()=>se(p.object({query:p.string()}))),E9t=Zt({id:"anthropic.web_search_20260209",inputSchema:w9t,outputSchema:S9t,supportsDeferredResults:!0}),_9t=(r={})=>E9t(r),C9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),userLocation:p.object({type:p.literal("approximate"),city:p.string().optional(),region:p.string().optional(),country:p.string().optional(),timezone:p.string().optional()}).optional()}))),rNe=ae(()=>se(p.array(p.object({url:p.string(),title:p.string().nullable(),pageAge:p.string().nullable(),encryptedContent:p.string(),type:p.literal("web_search_result")})))),k9t=ae(()=>se(p.object({query:p.string()}))),R9t=Zt({id:"anthropic.web_search_20250305",inputSchema:k9t,outputSchema:rNe,supportsDeferredResults:!0}),A9t=(r={})=>R9t(r),I9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),citations:p.object({enabled:p.boolean()}).optional(),maxContentTokens:p.number().optional()}))),P9t=ae(()=>se(p.object({type:p.literal("web_fetch_result"),url:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),mediaType:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),mediaType:p.literal("text/plain"),data:p.string()})])}),retrievedAt:p.string().nullable()}))),M9t=ae(()=>se(p.object({url:p.string()}))),O9t=Zt({id:"anthropic.web_fetch_20260209",inputSchema:M9t,outputSchema:P9t,supportsDeferredResults:!0}),N9t=(r={})=>O9t(r),D9t=ae(()=>se(p.object({maxUses:p.number().optional(),allowedDomains:p.array(p.string()).optional(),blockedDomains:p.array(p.string()).optional(),citations:p.object({enabled:p.boolean()}).optional(),maxContentTokens:p.number().optional()}))),nNe=ae(()=>se(p.object({type:p.literal("web_fetch_result"),url:p.string(),content:p.object({type:p.literal("document"),title:p.string().nullable(),citations:p.object({enabled:p.boolean()}).optional(),source:p.union([p.object({type:p.literal("base64"),mediaType:p.literal("application/pdf"),data:p.string()}),p.object({type:p.literal("text"),mediaType:p.literal("text/plain"),data:p.string()})])}),retrievedAt:p.string().nullable()}))),L9t=ae(()=>se(p.object({url:p.string()}))),U9t=Zt({id:"anthropic.web_fetch_20250910",inputSchema:L9t,outputSchema:nNe,supportsDeferredResults:!0}),F9t=(r={})=>U9t(r);oNe=ae(()=>se(p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}))),B9t=ae(()=>se(p.object({code:p.string()}))),z9t=Zt({id:"anthropic.code_execution_20250522",inputSchema:B9t,outputSchema:oNe}),G9t=(r={})=>z9t(r),sNe=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})]))),j9t=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("programmatic-tool-call"),code:p.string()}),p.object({type:p.literal("bash_code_execution"),command:p.string()}),p.discriminatedUnion("command",[p.object({type:p.literal("text_editor_code_execution"),command:p.literal("view"),path:p.string()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("create"),path:p.string(),file_text:p.string().nullish()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("str_replace"),path:p.string(),old_str:p.string(),new_str:p.string()})])]))),V9t=Zt({id:"anthropic.code_execution_20250825",inputSchema:j9t,outputSchema:sNe,supportsDeferredResults:!0}),H9t=(r={})=>V9t(r),iNe=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("code_execution_result"),stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("encrypted_code_execution_result"),encrypted_stdout:p.string(),stderr:p.string(),return_code:p.number(),content:p.array(p.object({type:p.literal("code_execution_output"),file_id:p.string()})).optional().default([])}),p.object({type:p.literal("bash_code_execution_result"),content:p.array(p.object({type:p.literal("bash_code_execution_output"),file_id:p.string()})),stdout:p.string(),stderr:p.string(),return_code:p.number()}),p.object({type:p.literal("bash_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_tool_result_error"),error_code:p.string()}),p.object({type:p.literal("text_editor_code_execution_view_result"),content:p.string(),file_type:p.string(),num_lines:p.number().nullable(),start_line:p.number().nullable(),total_lines:p.number().nullable()}),p.object({type:p.literal("text_editor_code_execution_create_result"),is_file_update:p.boolean()}),p.object({type:p.literal("text_editor_code_execution_str_replace_result"),lines:p.array(p.string()).nullable(),new_lines:p.number().nullable(),new_start:p.number().nullable(),old_lines:p.number().nullable(),old_start:p.number().nullable()})]))),q9t=ae(()=>se(p.discriminatedUnion("type",[p.object({type:p.literal("programmatic-tool-call"),code:p.string()}),p.object({type:p.literal("bash_code_execution"),command:p.string()}),p.discriminatedUnion("command",[p.object({type:p.literal("text_editor_code_execution"),command:p.literal("view"),path:p.string()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("create"),path:p.string(),file_text:p.string().nullish()}),p.object({type:p.literal("text_editor_code_execution"),command:p.literal("str_replace"),path:p.string(),old_str:p.string(),new_str:p.string()})])]))),W9t=Zt({id:"anthropic.code_execution_20260120",inputSchema:q9t,outputSchema:iNe,supportsDeferredResults:!0}),K9t=(r={})=>W9t(r),aNe=ae(()=>se(p.array(p.object({type:p.literal("tool_reference"),toolName:p.string()})))),J9t=ae(()=>se(p.object({pattern:p.string(),limit:p.number().optional()}))),X9t=Zt({id:"anthropic.tool_search_regex_20251119",inputSchema:J9t,outputSchema:aNe,supportsDeferredResults:!0}),Z9t=(r={})=>X9t(r);rXt=class{constructor(r,e){this.specificationVersion="v3";var t;this.modelId=r,this.config=e,this.generateId=(t=e.generateId)!=null?t:qn}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get providerOptionsName(){let r=this.config.provider,e=r.indexOf(".");return e===-1?r:r.substring(0,e)}get supportedUrls(){var r,e,t;return(t=(e=(r=this.config).supportedUrls)==null?void 0:e.call(r))!=null?t:{}}async getArgs({userSuppliedBetas:r,prompt:e,maxOutputTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:m,providerOptions:f,stream:h}){var y,x,b,S,w,_,C,k,I;let R=[];i!=null&&R.push({type:"unsupported",feature:"frequencyPenalty"}),a!=null&&R.push({type:"unsupported",feature:"presencePenalty"}),u!=null&&R.push({type:"unsupported",feature:"seed"}),n!=null&&n>1?(R.push({type:"unsupported",feature:"temperature",details:`${n} exceeds anthropic maximum of 1.0. clamped to 1.0`}),n=1):n!=null&&n<0&&(R.push({type:"unsupported",feature:"temperature",details:`${n} is below anthropic minimum of 0. clamped to 0`}),n=0),l?.type==="json"&&l.schema==null&&R.push({type:"unsupported",feature:"responseFormat",details:"JSON response format requires a schema. The response format is ignored."});let A=this.providerOptionsName,M=await Fn({provider:"anthropic",providerOptions:f,schema:XOe}),D=A!=="anthropic"?await Fn({provider:A,providerOptions:f,schema:XOe}):null,B=D!=null,O=Object.assign({},M??{},D??{}),{maxOutputTokens:U,supportsStructuredOutput:N,isKnownModel:$}=nXt(this.modelId),L=((y=this.config.supportsNativeStructuredOutput)!=null?y:!0)&&N,z=((x=this.config.supportsStrictTools)!=null?x:!0)&&N,F=(b=O?.structuredOutputMode)!=null?b:"auto",j=F==="outputFormat"||F==="auto"&&L,H=l?.type==="json"&&l.schema!=null&&!j?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:l.schema}:void 0,J=O?.contextManagement,he=new dte,Y=lU({tools:d,providerToolNames:{"anthropic.code_execution_20250522":"code_execution","anthropic.code_execution_20250825":"code_execution","anthropic.code_execution_20260120":"code_execution","anthropic.computer_20241022":"computer","anthropic.computer_20250124":"computer","anthropic.text_editor_20241022":"str_replace_editor","anthropic.text_editor_20250124":"str_replace_editor","anthropic.text_editor_20250429":"str_replace_based_edit_tool","anthropic.text_editor_20250728":"str_replace_based_edit_tool","anthropic.bash_20241022":"bash","anthropic.bash_20250124":"bash","anthropic.memory_20250818":"memory","anthropic.web_search_20250305":"web_search","anthropic.web_search_20260209":"web_search","anthropic.web_fetch_20250910":"web_fetch","anthropic.web_fetch_20260209":"web_fetch","anthropic.tool_search_regex_20251119":"tool_search_tool_regex","anthropic.tool_search_bm25_20251119":"tool_search_tool_bm25"}}),{prompt:ve,betas:W}=await eXt({prompt:e,sendReasoning:(S=O?.sendReasoning)!=null?S:!0,warnings:R,cacheControlValidator:he,toolNameMapping:Y}),Ie=(w=O?.thinking)==null?void 0:w.type,Me=Ie==="enabled"||Ie==="adaptive",ye=Ie==="enabled"?(_=O?.thinking)==null?void 0:_.budgetTokens:void 0,Q=t??U,oe={model:this.modelId,max_tokens:Q,temperature:n,top_k:s,top_p:o,stop_sequences:c,...Me&&{thinking:{type:Ie,...ye!=null&&{budget_tokens:ye}}},...(O?.effort||j&&l?.type==="json"&&l.schema!=null)&&{output_config:{...O?.effort&&{effort:O.effort},...j&&l?.type==="json"&&l.schema!=null&&{format:{type:"json_schema",schema:l.schema}}}},...O?.speed&&{speed:O.speed},...O?.cacheControl&&{cache_control:O.cacheControl},...((C=O?.metadata)==null?void 0:C.userId)!=null&&{metadata:{user_id:O.metadata.userId}},...O?.mcpServers&&O.mcpServers.length>0&&{mcp_servers:O.mcpServers.map(Ee=>({type:Ee.type,name:Ee.name,url:Ee.url,authorization_token:Ee.authorizationToken,tool_configuration:Ee.toolConfiguration?{allowed_tools:Ee.toolConfiguration.allowedTools,enabled:Ee.toolConfiguration.enabled}:void 0}))},...O?.container&&{container:O.container.skills&&O.container.skills.length>0?{id:O.container.id,skills:O.container.skills.map(Ee=>({type:Ee.type,skill_id:Ee.skillId,version:Ee.version}))}:O.container.id},system:ve.system,messages:ve.messages,...J&&{context_management:{edits:J.edits.map(Ee=>{let ro=Ee.type;switch(ro){case"clear_tool_uses_20250919":return{type:Ee.type,...Ee.trigger!==void 0&&{trigger:Ee.trigger},...Ee.keep!==void 0&&{keep:Ee.keep},...Ee.clearAtLeast!==void 0&&{clear_at_least:Ee.clearAtLeast},...Ee.clearToolInputs!==void 0&&{clear_tool_inputs:Ee.clearToolInputs},...Ee.excludeTools!==void 0&&{exclude_tools:Ee.excludeTools}};case"clear_thinking_20251015":return{type:Ee.type,...Ee.keep!==void 0&&{keep:Ee.keep}};case"compact_20260112":return{type:Ee.type,...Ee.trigger!==void 0&&{trigger:Ee.trigger},...Ee.pauseAfterCompaction!==void 0&&{pause_after_compaction:Ee.pauseAfterCompaction},...Ee.instructions!==void 0&&{instructions:Ee.instructions}};default:R.push({type:"other",message:`Unknown context management strategy: ${ro}`});return}}).filter(Ee=>Ee!==void 0)}}};Me?(Ie==="enabled"&&ye==null&&(R.push({type:"compatibility",feature:"extended thinking",details:"thinking budget is required when thinking is enabled. using default budget of 1024 tokens."}),oe.thinking={type:"enabled",budget_tokens:1024},ye=1024),oe.temperature!=null&&(oe.temperature=void 0,R.push({type:"unsupported",feature:"temperature",details:"temperature is not supported when thinking is enabled"})),s!=null&&(oe.top_k=void 0,R.push({type:"unsupported",feature:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(oe.top_p=void 0,R.push({type:"unsupported",feature:"topP",details:"topP is not supported when thinking is enabled"})),oe.max_tokens=Q+(ye??0)):o!=null&&n!=null&&(R.push({type:"unsupported",feature:"topP",details:"topP is not supported when temperature is set. topP is ignored."}),oe.top_p=void 0),$&&oe.max_tokens>U&&(t!=null&&R.push({type:"unsupported",feature:"maxOutputTokens",details:`${oe.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${U} max output tokens. The max output tokens have been limited to ${U}.`}),oe.max_tokens=U),O?.mcpServers&&O.mcpServers.length>0&&W.add("mcp-client-2025-04-04"),J&&(W.add("context-management-2025-06-27"),J.edits.some(Ee=>Ee.type==="compact_20260112")&&W.add("compact-2026-01-12")),O?.container&&O.container.skills&&O.container.skills.length>0&&(W.add("code-execution-2025-08-25"),W.add("skills-2025-10-02"),W.add("files-api-2025-04-14"),d?.some(Ee=>Ee.type==="provider"&&(Ee.id==="anthropic.code_execution_20250825"||Ee.id==="anthropic.code_execution_20260120"))||R.push({type:"other",message:"code execution tool is required when using skills"})),O?.effort&&W.add("effort-2025-11-24"),O?.speed==="fast"&&W.add("fast-mode-2026-02-01"),h&&((k=O?.toolStreaming)==null||k)&&W.add("fine-grained-tool-streaming-2025-05-14");let{tools:pe,toolChoice:te,toolWarnings:Qe,betas:nt}=await $9t(H!=null?{tools:[...d??[],H],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:he,supportsStructuredOutput:!1,supportsStrictTools:z}:{tools:d??[],toolChoice:m,disableParallelToolUse:O?.disableParallelToolUse,cacheControlValidator:he,supportsStructuredOutput:L,supportsStrictTools:z}),je=he.getWarnings();return{args:{...oe,tools:pe,tool_choice:te,stream:h===!0?!0:void 0},warnings:[...R,...Qe,...je],betas:new Set([...W,...nt,...r,...(I=O?.anthropicBeta)!=null?I:[]]),usesJsonResponseTool:H!=null,toolNameMapping:Y,providerOptionsName:A,usedCustomProviderKey:B}}async getHeaders({betas:r,headers:e}){return Ur(await En(this.config.headers),e,r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{})}async getBetasFromHeaders(r){var e,t;let o=(e=(await En(this.config.headers))["anthropic-beta"])!=null?e:"",s=(t=r?.["anthropic-beta"])!=null?t:"";return new Set([...o.toLowerCase().split(","),...s.toLowerCase().split(",")].map(i=>i.trim()).filter(i=>i!==""))}buildRequestUrl(r){var e,t,n;return(n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r,e){var t,n,o;return(o=(n=(t=this.config).transformRequestBody)==null?void 0:n.call(t,r,e))!=null?o:r}extractCitationDocuments(r){let e=t=>{var n,o;if(t.type!=="file"||t.mediaType!=="application/pdf"&&t.mediaType!=="text/plain")return!1;let s=(n=t.providerOptions)==null?void 0:n.anthropic,i=s?.citations;return(o=i?.enabled)!=null?o:!1};return r.filter(t=>t.role==="user").flatMap(t=>t.content).filter(e).map(t=>{var n;let o=t;return{title:(n=o.filename)!=null?n:"Untitled Document",filename:o.filename,mediaType:o.mediaType}})}async doGenerate(r){var e,t,n,o,s,i,a;let{args:c,warnings:l,betas:u,usesJsonResponseTool:d,toolNameMapping:m,providerOptionsName:f,usedCustomProviderKey:h}=await this.getArgs({...r,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(r.headers)}),y=[...this.extractCitationDocuments(r.prompt)],x=eNe(c.tools),{responseHeaders:b,value:S,rawValue:w}=await jr({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:u,headers:r.headers}),body:this.transformRequestBody(c,u),failedResponseHandler:KOe,successfulResponseHandler:Vr(m9t),abortSignal:r.abortSignal,fetch:this.config.fetch}),_=[],C={},k={},I=!1;for(let R of S.content)switch(R.type){case"text":{if(!d&&(_.push({type:"text",text:R.text}),R.citations))for(let A of R.citations){let M=QOe(A,y,this.generateId);M&&_.push(M)}break}case"thinking":{_.push({type:"reasoning",text:R.thinking,providerMetadata:{anthropic:{signature:R.signature}}});break}case"redacted_thinking":{_.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:R.data}}});break}case"compaction":{_.push({type:"text",text:R.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(d&&R.name==="json")I=!0,_.push({type:"text",text:JSON.stringify(R.input)});else{let M=R.caller,D=M?{type:M.type,toolId:"tool_id"in M?M.tool_id:void 0}:void 0;_.push({type:"tool-call",toolCallId:R.id,toolName:R.name,input:JSON.stringify(R.input),...D&&{providerMetadata:{anthropic:{caller:D}}}})}break}case"server_tool_use":{if(R.name==="text_editor_code_execution"||R.name==="bash_code_execution")_.push({type:"tool-call",toolCallId:R.id,toolName:m.toCustomToolName("code_execution"),input:JSON.stringify({type:R.name,...R.input}),providerExecuted:!0});else if(R.name==="web_search"||R.name==="code_execution"||R.name==="web_fetch"){let A=R.name==="code_execution"&&R.input!=null&&typeof R.input=="object"&&"code"in R.input&&!("type"in R.input)?{type:"programmatic-tool-call",...R.input}:R.input;_.push({type:"tool-call",toolCallId:R.id,toolName:m.toCustomToolName(R.name),input:JSON.stringify(A),providerExecuted:!0,...x&&R.name==="code_execution"?{dynamic:!0}:{}})}else(R.name==="tool_search_tool_regex"||R.name==="tool_search_tool_bm25")&&(k[R.id]=R.name,_.push({type:"tool-call",toolCallId:R.id,toolName:m.toCustomToolName(R.name),input:JSON.stringify(R.input),providerExecuted:!0}));break}case"mcp_tool_use":{C[R.id]={type:"tool-call",toolCallId:R.id,toolName:R.name,input:JSON.stringify(R.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:R.server_name}}},_.push(C[R.id]);break}case"mcp_tool_result":{_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:C[R.tool_use_id].toolName,isError:R.is_error,result:R.content,dynamic:!0,providerMetadata:C[R.tool_use_id].providerMetadata});break}case"web_fetch_tool_result":{R.content.type==="web_fetch_result"?(y.push({title:(e=R.content.content.title)!=null?e:R.content.url,mediaType:R.content.content.source.media_type}),_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:R.content.url,retrievedAt:R.content.retrieved_at,content:{type:R.content.content.type,title:R.content.content.title,citations:R.content.content.citations,source:{type:R.content.content.source.type,mediaType:R.content.content.source.media_type,data:R.content.content.source.data}}}})):R.content.type==="web_fetch_tool_result_error"&&_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:R.content.error_code}});break}case"web_search_tool_result":{if(Array.isArray(R.content)){_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_search"),result:R.content.map(A=>{var M;return{url:A.url,title:A.title,pageAge:(M=A.page_age)!=null?M:null,encryptedContent:A.encrypted_content,type:A.type}})});for(let A of R.content)_.push({type:"source",sourceType:"url",id:this.generateId(),url:A.url,title:A.title,providerMetadata:{anthropic:{pageAge:(t=A.page_age)!=null?t:null}}})}else _.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:R.content.error_code}});break}case"code_execution_tool_result":{R.content.type==="code_execution_result"?_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),result:{type:R.content.type,stdout:R.content.stdout,stderr:R.content.stderr,return_code:R.content.return_code,content:(n=R.content.content)!=null?n:[]}}):R.content.type==="encrypted_code_execution_result"?_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),result:{type:R.content.type,encrypted_stdout:R.content.encrypted_stdout,stderr:R.content.stderr,return_code:R.content.return_code,content:(o=R.content.content)!=null?o:[]}}):R.content.type==="code_execution_tool_result_error"&&_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:R.content.error_code}});break}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("code_execution"),result:R.content});break}case"tool_search_tool_result":{let A=k[R.tool_use_id];if(A==null){let M=m.toCustomToolName("tool_search_tool_bm25"),D=m.toCustomToolName("tool_search_tool_regex");M!=="tool_search_tool_bm25"?A="tool_search_tool_bm25":A="tool_search_tool_regex"}R.content.type==="tool_search_tool_search_result"?_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName(A),result:R.content.tool_references.map(M=>({type:M.type,toolName:M.tool_name}))}):_.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName(A),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:R.content.error_code}});break}}return{content:_,finishReason:{unified:ute({finishReason:S.stop_reason,isJsonResponseFromTool:I}),raw:(s=S.stop_reason)!=null?s:void 0},usage:YOe({usage:S.usage}),request:{body:c},response:{id:(i=S.id)!=null?i:void 0,modelId:(a=S.model)!=null?a:void 0,headers:b,body:w},warnings:l,providerMetadata:(()=>{var R,A,M,D,B;let O={usage:S.usage,cacheCreationInputTokens:(R=S.usage.cache_creation_input_tokens)!=null?R:null,stopSequence:(A=S.stop_sequence)!=null?A:null,iterations:S.usage.iterations?S.usage.iterations.map(N=>({type:N.type,inputTokens:N.input_tokens,outputTokens:N.output_tokens})):null,container:S.container?{expiresAt:S.container.expires_at,id:S.container.id,skills:(D=(M=S.container.skills)==null?void 0:M.map(N=>({type:N.type,skillId:N.skill_id,version:N.version})))!=null?D:null}:null,contextManagement:(B=tNe(S.context_management))!=null?B:null},U={anthropic:O};return h&&f!=="anthropic"&&(U[f]=O),U})()}}async doStream(r){var e,t;let{args:n,warnings:o,betas:s,usesJsonResponseTool:i,toolNameMapping:a,providerOptionsName:c,usedCustomProviderKey:l}=await this.getArgs({...r,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(r.headers)}),u=[...this.extractCitationDocuments(r.prompt)],d=eNe(n.tools),m=this.buildRequestUrl(!0),{responseHeaders:f,value:h}=await jr({url:m,headers:await this.getHeaders({betas:s,headers:r.headers}),body:this.transformRequestBody(n,s),failedResponseHandler:KOe,successfulResponseHandler:hu(f9t),abortSignal:r.abortSignal,fetch:this.config.fetch}),y={unified:"other",raw:void 0},x={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},b={},S={},w={},_=null,C,k=null,I=null,R=null,A=!1,M,D=this.generateId,B=h.pipeThrough(new TransformStream({start($){$.enqueue({type:"stream-start",warnings:o})},transform($,L){var z,F,j,H,J,he,Y,ve,W,Ie,Me,ye,Q,oe;if(r.includeRawChunks&&L.enqueue({type:"raw",rawValue:$.rawValue}),!$.success){L.enqueue({type:"error",error:$.error});return}let pe=$.value;switch(pe.type){case"ping":return;case"content_block_start":{let te=pe.content_block,Qe=te.type;switch(M=Qe,Qe){case"text":{if(i)return;b[pe.index]={type:"text"},L.enqueue({type:"text-start",id:String(pe.index)});return}case"thinking":{b[pe.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(pe.index)});return}case"redacted_thinking":{b[pe.index]={type:"reasoning"},L.enqueue({type:"reasoning-start",id:String(pe.index),providerMetadata:{anthropic:{redactedData:te.data}}});return}case"compaction":{b[pe.index]={type:"text"},L.enqueue({type:"text-start",id:String(pe.index),providerMetadata:{anthropic:{type:"compaction"}}});return}case"tool_use":{if(i&&te.name==="json")A=!0,b[pe.index]={type:"text"},L.enqueue({type:"text-start",id:String(pe.index)});else{let je=te.caller,Ee=je?{type:je.type,toolId:"tool_id"in je?je.tool_id:void 0}:void 0,Xa=te.input&&Object.keys(te.input).length>0?JSON.stringify(te.input):"";b[pe.index]={type:"tool-call",toolCallId:te.id,toolName:te.name,input:Xa,firstDelta:Xa.length===0,...Ee&&{caller:Ee}},L.enqueue({type:"tool-input-start",id:te.id,toolName:te.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(te.name)){let nt=te.name==="text_editor_code_execution"||te.name==="bash_code_execution"?"code_execution":te.name,je=a.toCustomToolName(nt),Ee=te.input!=null&&typeof te.input=="object"&&Object.keys(te.input).length>0?JSON.stringify(te.input):"";b[pe.index]={type:"tool-call",toolCallId:te.id,toolName:je,input:Ee,providerExecuted:!0,...d&&nt==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:te.name},L.enqueue({type:"tool-input-start",id:te.id,toolName:je,providerExecuted:!0,...d&&nt==="code_execution"?{dynamic:!0}:{}})}else if(te.name==="tool_search_tool_regex"||te.name==="tool_search_tool_bm25"){w[te.id]=te.name;let nt=a.toCustomToolName(te.name);b[pe.index]={type:"tool-call",toolCallId:te.id,toolName:nt,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:te.name},L.enqueue({type:"tool-input-start",id:te.id,toolName:nt,providerExecuted:!0})}return}case"web_fetch_tool_result":{te.content.type==="web_fetch_result"?(u.push({title:(z=te.content.content.title)!=null?z:te.content.url,mediaType:te.content.content.source.media_type}),L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:te.content.url,retrievedAt:te.content.retrieved_at,content:{type:te.content.content.type,title:te.content.content.title,citations:te.content.content.citations,source:{type:te.content.content.source.type,mediaType:te.content.content.source.media_type,data:te.content.content.source.data}}}})):te.content.type==="web_fetch_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:te.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(te.content)){L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_search"),result:te.content.map(nt=>{var je;return{url:nt.url,title:nt.title,pageAge:(je=nt.page_age)!=null?je:null,encryptedContent:nt.encrypted_content,type:nt.type}})});for(let nt of te.content)L.enqueue({type:"source",sourceType:"url",id:D(),url:nt.url,title:nt.title,providerMetadata:{anthropic:{pageAge:(F=nt.page_age)!=null?F:null}}})}else L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:te.content.error_code}});return}case"code_execution_tool_result":{te.content.type==="code_execution_result"?L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:{type:te.content.type,stdout:te.content.stdout,stderr:te.content.stderr,return_code:te.content.return_code,content:(j=te.content.content)!=null?j:[]}}):te.content.type==="encrypted_code_execution_result"?L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:{type:te.content.type,encrypted_stdout:te.content.encrypted_stdout,stderr:te.content.stderr,return_code:te.content.return_code,content:(H=te.content.content)!=null?H:[]}}):te.content.type==="code_execution_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:te.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:te.content});return}case"tool_search_tool_result":{let nt=w[te.tool_use_id];if(nt==null){let je=a.toCustomToolName("tool_search_tool_bm25"),Ee=a.toCustomToolName("tool_search_tool_regex");je!=="tool_search_tool_bm25"?nt="tool_search_tool_bm25":nt="tool_search_tool_regex"}te.content.type==="tool_search_tool_search_result"?L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName(nt),result:te.content.tool_references.map(je=>({type:je.type,toolName:je.tool_name}))}):L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:a.toCustomToolName(nt),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:te.content.error_code}});return}case"mcp_tool_use":{S[te.id]={type:"tool-call",toolCallId:te.id,toolName:te.name,input:JSON.stringify(te.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:te.server_name}}},L.enqueue(S[te.id]);return}case"mcp_tool_result":{L.enqueue({type:"tool-result",toolCallId:te.tool_use_id,toolName:S[te.tool_use_id].toolName,isError:te.is_error,result:te.content,dynamic:!0,providerMetadata:S[te.tool_use_id].providerMetadata});return}default:{let nt=Qe;throw new Error(`Unsupported content block type: ${nt}`)}}}case"content_block_stop":{if(b[pe.index]!=null){let te=b[pe.index];switch(te.type){case"text":{L.enqueue({type:"text-end",id:String(pe.index)});break}case"reasoning":{L.enqueue({type:"reasoning-end",id:String(pe.index)});break}case"tool-call":if(!(i&&te.toolName==="json")){L.enqueue({type:"tool-input-end",id:te.toolCallId});let nt=te.input===""?"{}":te.input;if(te.providerToolName==="code_execution")try{let je=JSON.parse(nt);je!=null&&typeof je=="object"&&"code"in je&&!("type"in je)&&(nt=JSON.stringify({type:"programmatic-tool-call",...je}))}catch{}L.enqueue({type:"tool-call",toolCallId:te.toolCallId,toolName:te.toolName,input:nt,providerExecuted:te.providerExecuted,...d&&te.providerToolName==="code_execution"?{dynamic:!0}:{},...te.caller&&{providerMetadata:{anthropic:{caller:te.caller}}}})}break}delete b[pe.index]}M=void 0;return}case"content_block_delta":{let te=pe.delta.type;switch(te){case"text_delta":{if(i)return;L.enqueue({type:"text-delta",id:String(pe.index),delta:pe.delta.text});return}case"thinking_delta":{L.enqueue({type:"reasoning-delta",id:String(pe.index),delta:pe.delta.thinking});return}case"signature_delta":{M==="thinking"&&L.enqueue({type:"reasoning-delta",id:String(pe.index),delta:"",providerMetadata:{anthropic:{signature:pe.delta.signature}}});return}case"compaction_delta":{pe.delta.content!=null&&L.enqueue({type:"text-delta",id:String(pe.index),delta:pe.delta.content});return}case"input_json_delta":{let Qe=b[pe.index],nt=pe.delta.partial_json;if(nt.length===0)return;if(A){if(Qe?.type!=="text")return;L.enqueue({type:"text-delta",id:String(pe.index),delta:nt})}else{if(Qe?.type!=="tool-call")return;Qe.firstDelta&&(Qe.providerToolName==="bash_code_execution"||Qe.providerToolName==="text_editor_code_execution")&&(nt=`{"type": "${Qe.providerToolName}",${nt.substring(1)}`),L.enqueue({type:"tool-input-delta",id:Qe.toolCallId,delta:nt}),Qe.input+=nt,Qe.firstDelta=!1}return}case"citations_delta":{let Qe=pe.delta.citation,nt=QOe(Qe,u,D);nt&&L.enqueue(nt);return}default:{let Qe=te;throw new Error(`Unsupported delta type: ${Qe}`)}}}case"message_start":{if(x.input_tokens=pe.message.usage.input_tokens,x.cache_read_input_tokens=(J=pe.message.usage.cache_read_input_tokens)!=null?J:0,x.cache_creation_input_tokens=(he=pe.message.usage.cache_creation_input_tokens)!=null?he:0,C={...pe.message.usage},k=(Y=pe.message.usage.cache_creation_input_tokens)!=null?Y:null,pe.message.container!=null&&(R={expiresAt:pe.message.container.expires_at,id:pe.message.container.id,skills:null}),pe.message.stop_reason!=null&&(y={unified:ute({finishReason:pe.message.stop_reason,isJsonResponseFromTool:A}),raw:pe.message.stop_reason}),L.enqueue({type:"response-metadata",id:(ve=pe.message.id)!=null?ve:void 0,modelId:(W=pe.message.model)!=null?W:void 0}),pe.message.content!=null)for(let te=0;te<pe.message.content.length;te++){let Qe=pe.message.content[te];if(Qe.type==="tool_use"){let nt=Qe.caller,je=nt?{type:nt.type,toolId:"tool_id"in nt?nt.tool_id:void 0}:void 0;L.enqueue({type:"tool-input-start",id:Qe.id,toolName:Qe.name});let Ee=JSON.stringify((Ie=Qe.input)!=null?Ie:{});L.enqueue({type:"tool-input-delta",id:Qe.id,delta:Ee}),L.enqueue({type:"tool-input-end",id:Qe.id}),L.enqueue({type:"tool-call",toolCallId:Qe.id,toolName:Qe.name,input:Ee,...je&&{providerMetadata:{anthropic:{caller:je}}}})}}return}case"message_delta":{pe.usage.input_tokens!=null&&x.input_tokens!==pe.usage.input_tokens&&(x.input_tokens=pe.usage.input_tokens),x.output_tokens=pe.usage.output_tokens,pe.usage.cache_read_input_tokens!=null&&(x.cache_read_input_tokens=pe.usage.cache_read_input_tokens),pe.usage.cache_creation_input_tokens!=null&&(x.cache_creation_input_tokens=pe.usage.cache_creation_input_tokens,k=pe.usage.cache_creation_input_tokens),pe.usage.iterations!=null&&(x.iterations=pe.usage.iterations),y={unified:ute({finishReason:pe.delta.stop_reason,isJsonResponseFromTool:A}),raw:(Me=pe.delta.stop_reason)!=null?Me:void 0},I=(ye=pe.delta.stop_sequence)!=null?ye:null,R=pe.delta.container!=null?{expiresAt:pe.delta.container.expires_at,id:pe.delta.container.id,skills:(oe=(Q=pe.delta.container.skills)==null?void 0:Q.map(te=>({type:te.type,skillId:te.skill_id,version:te.version})))!=null?oe:null}:null,pe.context_management&&(_=tNe(pe.context_management)),C={...C,...pe.usage};return}case"message_stop":{let te={usage:C??null,cacheCreationInputTokens:k,stopSequence:I,iterations:x.iterations?x.iterations.map(nt=>({type:nt.type,inputTokens:nt.input_tokens,outputTokens:nt.output_tokens})):null,container:R,contextManagement:_},Qe={anthropic:te};l&&c!=="anthropic"&&(Qe[c]=te),L.enqueue({type:"finish",finishReason:y,usage:YOe({usage:x,rawUsage:C}),providerMetadata:Qe});return}case"error":{L.enqueue({type:"error",error:pe.error});return}default:{let te=pe;throw new Error(`Unsupported chunk type: ${te}`)}}}})),[O,U]=B.tee(),N=O.getReader();try{await N.read();let $=await N.read();if(((e=$.value)==null?void 0:e.type)==="raw"&&($=await N.read()),((t=$.value)==null?void 0:t.type)==="error"){let L=$.value.error;throw new xr({message:L.message,url:m,requestBodyValues:n,statusCode:L.type==="overloaded_error"?529:500,responseHeaders:f,responseBody:JSON.stringify(L),isRetryable:L.type==="overloaded_error"})}}finally{N.cancel().catch(()=>{}),N.releaseLock()}return{stream:U,request:{body:n},response:{headers:f}}}};oXt=ae(()=>se(p.object({command:p.string(),restart:p.boolean().optional()}))),sXt=xo({id:"anthropic.bash_20241022",inputSchema:oXt}),iXt=ae(()=>se(p.object({command:p.string(),restart:p.boolean().optional()}))),aXt=xo({id:"anthropic.bash_20250124",inputSchema:iXt}),cXt=ae(()=>se(p.object({action:p.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:p.array(p.number().int()).optional(),text:p.string().optional()}))),lXt=xo({id:"anthropic.computer_20241022",inputSchema:cXt}),uXt=ae(()=>se(p.object({action:p.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),duration:p.number().optional(),scroll_amount:p.number().optional(),scroll_direction:p.enum(["up","down","left","right"]).optional(),start_coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),text:p.string().optional()}))),dXt=xo({id:"anthropic.computer_20250124",inputSchema:uXt}),pXt=ae(()=>se(p.object({action:p.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot","zoom"]),coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),duration:p.number().optional(),region:p.tuple([p.number().int(),p.number().int(),p.number().int(),p.number().int()]).optional(),scroll_amount:p.number().optional(),scroll_direction:p.enum(["up","down","left","right"]).optional(),start_coordinate:p.tuple([p.number().int(),p.number().int()]).optional(),text:p.string().optional()}))),mXt=xo({id:"anthropic.computer_20251124",inputSchema:pXt}),fXt=ae(()=>se(p.discriminatedUnion("command",[p.object({command:p.literal("view"),path:p.string(),view_range:p.tuple([p.number(),p.number()]).optional()}),p.object({command:p.literal("create"),path:p.string(),file_text:p.string()}),p.object({command:p.literal("str_replace"),path:p.string(),old_str:p.string(),new_str:p.string()}),p.object({command:p.literal("insert"),path:p.string(),insert_line:p.number(),insert_text:p.string()}),p.object({command:p.literal("delete"),path:p.string()}),p.object({command:p.literal("rename"),old_path:p.string(),new_path:p.string()})]))),gXt=xo({id:"anthropic.memory_20250818",inputSchema:fXt}),hXt=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert","undo_edit"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),yXt=xo({id:"anthropic.text_editor_20241022",inputSchema:hXt}),xXt=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert","undo_edit"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),vXt=xo({id:"anthropic.text_editor_20250124",inputSchema:xXt}),bXt=ae(()=>se(p.object({command:p.enum(["view","create","str_replace","insert"]),path:p.string(),file_text:p.string().optional(),insert_line:p.number().int().optional(),new_str:p.string().optional(),insert_text:p.string().optional(),old_str:p.string().optional(),view_range:p.array(p.number().int()).optional()}))),TXt=xo({id:"anthropic.text_editor_20250429",inputSchema:bXt}),SXt=ae(()=>se(p.array(p.object({type:p.literal("tool_reference"),toolName:p.string()})))),wXt=ae(()=>se(p.object({query:p.string(),limit:p.number().optional()}))),EXt=Zt({id:"anthropic.tool_search_bm25_20251119",inputSchema:wXt,outputSchema:SXt,supportsDeferredResults:!0}),_Xt=(r={})=>EXt(r),CXt={bash_20241022:sXt,bash_20250124:aXt,codeExecution_20250522:G9t,codeExecution_20250825:H9t,codeExecution_20260120:K9t,computer_20241022:lXt,computer_20250124:dXt,computer_20251124:mXt,memory_20250818:gXt,textEditor_20241022:yXt,textEditor_20250124:vXt,textEditor_20250429:TXt,textEditor_20250728:b9t,webFetch_20250910:F9t,webFetch_20260209:N9t,webSearch_20250305:A9t,webSearch_20260209:_9t,toolSearchRegex_20251119:Z9t,toolSearchBm25_20251119:_Xt};kXt=cP()});var fte={};K(fte,{AsyncLocalStorage:()=>qXt,Buffer:()=>LYt,Channel:()=>_Yt,DatabaseSync:()=>DYt,Duplex:()=>KXt,EventEmitter:()=>HXt,Http2ServerRequest:()=>zYt,Http2ServerResponse:()=>GYt,Interface:()=>NYt,MIMEType:()=>KYt,PassThrough:()=>JXt,PerformanceObserver:()=>SYt,Readable:()=>uNe,ReadableStream:()=>XXt,Resolver:()=>bYt,TextDecoder:()=>mNe,TextEncoder:()=>UG,Transform:()=>WXt,URL:()=>aYt,URLSearchParams:()=>cYt,Worker:()=>AYt,Writable:()=>dNe,access:()=>EZt,appendFile:()=>nZt,appendFileSync:()=>OXt,arch:()=>BZt,arrayBuffer:()=>jYt,basename:()=>FXt,builtinModules:()=>nYt,callbackify:()=>gYt,channel:()=>EYt,chmodSync:()=>rZt,clearInterval:()=>WYt,clearTimeout:()=>HYt,closeSync:()=>aZt,connect:()=>VZt,constants:()=>UYt,copyFileSync:()=>sZt,cpSync:()=>NXt,cpus:()=>LZt,createConnection:()=>HZt,createGunzip:()=>YZt,createGzip:()=>QZt,createHash:()=>cNe,createHmac:()=>AXt,createInterface:()=>OYt,createReadStream:()=>yZt,createRequire:()=>rYt,createServer:()=>lNe,createWriteStream:()=>hZt,debug:()=>mYt,debuglog:()=>pNe,default:()=>mte,deflateSync:()=>WZt,deprecate:()=>fYt,deserialize:()=>RYt,dirname:()=>UXt,exec:()=>RZt,execFile:()=>IZt,execFileSync:()=>PZt,execSync:()=>AZt,existsSync:()=>QXt,extname:()=>$Xt,fileURLToPath:()=>lYt,finished:()=>YXt,format:()=>iYt,freemem:()=>UZt,fstatSync:()=>cZt,get:()=>jZt,gunzip:()=>ZZt,gunzipSync:()=>KZt,gzip:()=>XZt,gzipSync:()=>JZt,hasSubscribers:()=>CYt,homedir:()=>OZt,hostname:()=>DZt,inflateSync:()=>qZt,inherits:()=>dYt,inspect:()=>FG,isAbsolute:()=>zXt,isBuiltin:()=>oYt,isDeepStrictEqual:()=>hYt,isIP:()=>BYt,isIPv4:()=>$Yt,isIPv6:()=>FYt,isMainThread:()=>IYt,join:()=>DXt,lookup:()=>vYt,mkdir:()=>bZt,mkdirSync:()=>lZt,monitorEventLoopDelay:()=>wYt,normalize:()=>VXt,ok:()=>eYt,openSync:()=>iZt,parentPort:()=>PYt,parse:()=>sYt,pathToFileURL:()=>uYt,performance:()=>TYt,pipeline:()=>ZXt,platform:()=>MZt,posix:()=>jXt,promises:()=>RXt,promisify:()=>pYt,randomBytes:()=>IXt,randomUUID:()=>PXt,readFile:()=>xZt,readFileSync:()=>eZt,readdir:()=>SZt,readdirSync:()=>dZt,realpathSync:()=>oZt,relative:()=>BXt,release:()=>zZt,rename:()=>_Zt,renameSync:()=>mZt,request:()=>GZt,resolve:()=>LXt,rm:()=>CZt,rmSync:()=>gZt,rmdirSync:()=>fZt,sep:()=>GXt,serialize:()=>kYt,setInterval:()=>qYt,setTimeout:()=>VYt,spawn:()=>kZt,stat:()=>TZt,statSync:()=>uZt,strict:()=>tYt,tmpdir:()=>NZt,toUSVString:()=>yYt,totalmem:()=>FZt,type:()=>$Zt,types:()=>xYt,unlink:()=>wZt,unlinkSync:()=>pZt,webcrypto:()=>MXt,workerData:()=>MYt,writeFile:()=>vZt,writeFileSync:()=>tZt});var Do,js,mte,RXt,cNe,AXt,IXt,PXt,MXt,OXt,NXt,lNe,DXt,LXt,UXt,FXt,$Xt,BXt,zXt,GXt,jXt,VXt,HXt,qXt,uNe,dNe,WXt,KXt,JXt,XXt,ZXt,YXt,QXt,eZt,tZt,rZt,nZt,oZt,sZt,iZt,aZt,cZt,lZt,uZt,dZt,pZt,mZt,fZt,gZt,hZt,yZt,xZt,vZt,bZt,TZt,SZt,wZt,EZt,_Zt,CZt,kZt,RZt,AZt,IZt,PZt,MZt,OZt,NZt,DZt,LZt,UZt,FZt,$Zt,BZt,zZt,GZt,jZt,VZt,HZt,qZt,WZt,KZt,JZt,XZt,ZZt,YZt,QZt,eYt,tYt,rYt,nYt,oYt,sYt,iYt,aYt,cYt,lYt,uYt,dYt,pYt,pNe,mYt,FG,fYt,gYt,hYt,yYt,xYt,mNe,UG,vYt,bYt,TYt,SYt,wYt,EYt,_Yt,CYt,kYt,RYt,AYt,IYt,PYt,MYt,OYt,NYt,DYt,LYt,UYt,FYt,$Yt,BYt,zYt,GYt,jYt,fNe,VYt,HYt,qYt,WYt,KYt,lP=E(()=>{Do=()=>{},js=async()=>{},mte={},RXt={readFile:js,writeFile:js,mkdir:js,stat:js,readdir:js,unlink:js,access:js,rm:js,rename:js},cNe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new UG().encode(t):t),this},digest(t){let n=0;for(let s of e)for(let i=0;i<s.length;i++)n=(n<<5)-n+s[i]|0;let o=(n>>>0).toString(16).padStart(8,"0");return t==="hex"?o:t==="base64"?btoa(o):o}}},AXt=(r,e)=>cNe(r),IXt=r=>new Uint8Array(r||32),PXt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),MXt=globalThis.crypto,OXt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},NXt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},lNe=()=>({listen:Do,close:Do,on:Do}),DXt=(...r)=>r.join("/"),LXt=(...r)=>r.join("/"),UXt=r=>r||"",FXt=r=>r?.split?.("/")?.pop?.()||"",$Xt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},BXt=(r,e)=>e||"",zXt=()=>!1,GXt="/",jXt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},VXt=r=>r,HXt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},qXt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},uNe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},dNe=class{write(){return!0}end(){}on(){return this}destroy(){}},WXt=class{push(){}on(){return this}},KXt=class{on(){return this}},JXt=class{pipe(){return this}on(){return this}},XXt=globalThis.ReadableStream||class{},ZXt=Do,YXt=Do,QXt=()=>!1,eZt=()=>"",tZt=Do,rZt=Do,nZt=js,oZt=r=>r,sZt=Do,iZt=()=>0,aZt=Do,cZt=()=>({}),lZt=Do,uZt=()=>({}),dZt=()=>[],pZt=Do,mZt=Do,fZt=Do,gZt=Do,hZt=()=>new dNe,yZt=()=>new uNe,xZt=js,vZt=js,bZt=js,TZt=js,SZt=js,wZt=js,EZt=js,_Zt=js,CZt=js,kZt=()=>({on:Do,stdout:{on:Do},stderr:{on:Do},kill:Do}),RZt=(r,e)=>e?.(null,"",""),AZt=()=>"",IZt=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},PZt=()=>"",MZt="browser",OZt=()=>"/",NZt=()=>"/tmp",DZt=()=>"browser",LZt=()=>[{}],UZt=()=>0,FZt=()=>0,$Zt=()=>"Browser",BZt=()=>"wasm",zZt=()=>"0",GZt=()=>({}),jZt=()=>({}),VZt=()=>({}),HZt=()=>({}),qZt=()=>new Uint8Array,WZt=()=>new Uint8Array,KZt=()=>new Uint8Array,JZt=()=>new Uint8Array,XZt=(r,e)=>e?.(null,r),ZZt=(r,e)=>e?.(null,r),YZt=()=>({}),QZt=()=>({}),eYt=Do,tYt={},rYt=()=>()=>({}),nYt=[],oYt=()=>!1,sYt=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),iYt=()=>"",aYt=globalThis.URL,cYt=globalThis.URLSearchParams,lYt=r=>typeof r=="string"?r.replace("file://",""):r,uYt=r=>new globalThis.URL("file://"+r),dYt=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},pYt=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),pNe=r=>{let e=(...t)=>{};return e.enabled=!1,e},mYt=pNe,FG=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};FG.custom=Symbol.for("nodejs.util.inspect.custom");FG.colors={};FG.styles={};fYt=r=>r,gYt=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},hYt=(r,e)=>JSON.stringify(r)===JSON.stringify(e),yYt=r=>String(r),xYt={isPromise:r=>r instanceof Promise,isDate:r=>r instanceof Date,isRegExp:r=>r instanceof RegExp,isNativeError:r=>r instanceof Error,isArrayBuffer:r=>r instanceof ArrayBuffer,isTypedArray:r=>ArrayBuffer.isView(r),isUint8Array:r=>r instanceof Uint8Array,isProxy:()=>!1},mNe=globalThis.TextDecoder,UG=globalThis.TextEncoder,vYt=(r,e)=>e?.(null,"127.0.0.1",4),bYt=class{},TYt=globalThis.performance||{now:()=>Date.now()},SYt=class{observe(){}disconnect(){}},wYt=()=>({enable:Do,disable:Do,percentile:()=>0}),EYt=()=>({}),_Yt=class{},CYt=()=>!1,kYt=()=>new Uint8Array,RYt=Do,AYt=class{},IYt=!0,PYt=null,MYt=null,OYt=()=>({}),NYt=class{},DYt=class{},LYt=globalThis.Buffer||class extends Uint8Array{static from(e,t){if(typeof e=="string"){let n=(t||"utf8").toLowerCase();if(n==="base64"){let o=atob(e),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){let o=new Uint8Array(e.length/2);for(let s=0;s<e.length;s+=2)o[s/2]=parseInt(e.substr(s,2),16);return o}return new UG().encode(e)}return new Uint8Array(e)}static alloc(e){return new Uint8Array(e)}static isBuffer(e){return e instanceof Uint8Array}static concat(e){let t=e.reduce((s,i)=>s+i.length,0),n=new Uint8Array(t),o=0;for(let s of e)n.set(s,o),o+=s.length;return n}static byteLength(e,t){return t==="base64"?Math.ceil(e.length*3/4):new UG().encode(e).length}toString(e){let t=(e||"utf8").toLowerCase();if(t==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(t==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new mNe().decode(this)}},UYt={F_OK:0,R_OK:4,W_OK:2,X_OK:1},FYt=()=>!1,$Yt=()=>!1,BYt=()=>0,zYt=class{},GYt=class{},jYt=async()=>new ArrayBuffer(0),fNe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),VYt=(...r)=>fNe(globalThis.setTimeout(...r)),HYt=globalThis.clearTimeout,qYt=(...r)=>fNe(globalThis.setInterval(...r)),WYt=globalThis.clearInterval,KYt=class{constructor(r){this.type=r}toString(){return this.type}}});function gNe(r){return yY("sha256",QYt).update(r).digest("hex")}function e7t(r){let e=r.replace(/-/g,"").slice(0,32).padEnd(32,"0");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}function uP(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r)}function $G(r){return JSON.stringify({device_id:r.deviceId,account_uuid:r.accountUuid,session_id:r.sessionId})}function gte(r){if(typeof r!="string")return null;try{let e=JSON.parse(r);return typeof e.device_id!="string"||!/^[0-9a-f]{64}$/i.test(e.device_id)||typeof e.account_uuid!="string"||!uP(e.account_uuid)||typeof e.session_id!="string"||!uP(e.session_id)?null:{deviceId:e.device_id,accountUuid:e.account_uuid,sessionId:e.session_id,metadataUserId:$G({deviceId:e.device_id,accountUuid:e.account_uuid,sessionId:e.session_id})}}catch{return null}}function BG(r,e){let t=gte(e?.existingUserId);if(t)return e?.preferredSessionId&&uP(e.preferredSessionId)?{deviceId:t.deviceId,accountUuid:t.accountUuid,sessionId:e.preferredSessionId,metadataUserId:$G({deviceId:t.deviceId,accountUuid:t.accountUuid,sessionId:e.preferredSessionId})}:t;let n=Date.now(),o=r||"default",s=Lv.get(o);if(s&&s.expiresAt>n)return e?.preferredSessionId&&uP(e.preferredSessionId)?{deviceId:s.deviceId,accountUuid:s.accountUuid,sessionId:e.preferredSessionId,metadataUserId:$G({deviceId:s.deviceId,accountUuid:s.accountUuid,sessionId:e.preferredSessionId})}:s;let i=gNe(`${o}:device`),a=e7t(gNe(`${o}:account`)),c=e?.preferredSessionId&&uP(e.preferredSessionId)?e.preferredSessionId:Fe(),l={deviceId:i,accountUuid:a,sessionId:c,metadataUserId:$G({deviceId:i,accountUuid:a,sessionId:c}),expiresAt:n+ZYt};return r7t(n),Lv.set(o,l),l}function t7t(r=Date.now()){let e=0;for(let[t,n]of Lv.entries())n.expiresAt<=r&&(Lv.delete(t),e+=1);return e}function r7t(r=Date.now()){for(t7t(r);Lv.size>=YYt;){let e=Lv.keys().next().value;if(!e)break;Lv.delete(e)}}function RE(r){let e=r?.match(/cc_version=([^;]+)/)?.[1]?.trim()||JYt,t=r?.match(/cc_entrypoint=([^;]+)/)?.[1]?.trim()||XYt;return`x-anthropic-billing-header: cc_version=${e}; cc_entrypoint=${t}; cch=00000;`}var hNe,yNe,JYt,XYt,kE,ZYt,YYt,QYt,Lv,Uv,hte,zG=E(()=>{"use strict";ir();lP();hNe="9d1c250a-e61b-44d9-88ed-5944d1962f5e",yNe="https://api.anthropic.com/v1/oauth/token",JYt="2.1.87.6d6",XYt="sdk-cli",kE="claude-cli/2.1.87 (external, sdk-cli)",ZYt=36e5,YYt=1024,QYt="neurolink-claude-code-identity-v1",Lv=new Map;Uv=["oauth-2025-04-20","claude-code-20250219","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advanced-tool-use-2025-11-20","effort-2025-11-24"],hte="mcp_"});function i7t(){return Object.values(xNe)}function dP(r,e){let t=n7t[e];return t.includes("*")?i7t().includes(r):t.includes(r)}function a7t(r){return s7t[r]}function c7t(r){return o7t[r]}var xNe,n7t,o7t,s7t,GG,jG,yte=E(()=>{"use strict";mt();xNe=(l=>(l.CLAUDE_3_HAIKU="claude-3-haiku-20240307",l.CLAUDE_3_5_HAIKU="claude-3-5-haiku-20241022",l.CLAUDE_3_5_SONNET="claude-3-5-sonnet-20241022",l.CLAUDE_3_5_SONNET_V2="claude-3-5-sonnet-v2-20241022",l.CLAUDE_SONNET_4="claude-sonnet-4-20250514",l.CLAUDE_SONNET_4_6="claude-sonnet-4-6",l.CLAUDE_3_OPUS="claude-3-opus-20240229",l.CLAUDE_OPUS_4="claude-opus-4-20250514",l.CLAUDE_OPUS_4_6="claude-opus-4-6",l))(xNe||{}),n7t={free:["claude-3-haiku-20240307","claude-3-5-haiku-20241022"],pro:["claude-3-haiku-20240307","claude-3-5-haiku-20241022","claude-3-5-sonnet-20241022","claude-3-5-sonnet-v2-20241022","claude-sonnet-4-20250514","claude-sonnet-4-6"],max:["*"],max_5:["*"],max_20:["*"],api:["*"]},o7t={"claude-3-haiku-20240307":{displayName:"Claude 3 Haiku",contextWindow:2e5,maxOutputTokens:4096,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!0,family:"haiku",description:"Fast and efficient model for simple tasks"},"claude-3-5-haiku-20241022":{displayName:"Claude 3.5 Haiku",contextWindow:2e5,maxOutputTokens:8192,supportsVision:!1,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"haiku",description:"Improved fast model with better performance"},"claude-3-5-sonnet-20241022":{displayName:"Claude 3.5 Sonnet",contextWindow:2e5,maxOutputTokens:8192,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Balanced model for most tasks"},"claude-3-5-sonnet-v2-20241022":{displayName:"Claude 3.5 Sonnet V2",contextWindow:2e5,maxOutputTokens:8192,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Updated Sonnet with improved capabilities"},"claude-sonnet-4-20250514":{displayName:"Claude Sonnet 4",contextWindow:2e5,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Latest Sonnet with extended thinking support"},"claude-3-opus-20240229":{displayName:"Claude 3 Opus",contextWindow:2e5,maxOutputTokens:4096,supportsVision:!0,supportsExtendedThinking:!1,supportsToolUse:!0,supportsStreaming:!0,deprecated:!0,family:"opus",description:"Legacy flagship model for complex tasks"},"claude-opus-4-20250514":{displayName:"Claude Opus 4",contextWindow:2e5,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"opus",description:"Latest flagship model with advanced reasoning"},"claude-sonnet-4-6":{displayName:"Claude Sonnet 4.6",contextWindow:1e6,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"sonnet",description:"Claude 4.6 Sonnet with 1M context window"},"claude-opus-4-6":{displayName:"Claude Opus 4.6",contextWindow:1e6,maxOutputTokens:64e3,supportsVision:!0,supportsExtendedThinking:!0,supportsToolUse:!0,supportsStreaming:!0,deprecated:!1,family:"opus",description:"Claude 4.6 Opus flagship with 1M context window"}},s7t={free:"claude-3-5-haiku-20241022",pro:"claude-sonnet-4-20250514",max:"claude-opus-4-20250514",max_5:"claude-opus-4-20250514",max_20:"claude-opus-4-20250514",api:"claude-sonnet-4-20250514"};GG=a7t,jG=c7t});function l7t(r){try{if(typeof r=="string"||r instanceof URL)return new URL(r.toString());if(r instanceof Request)return new URL(r.url)}catch{return null}return null}function u7t(r,e){let t=new Headers;if(r instanceof Request&&r.headers.forEach((n,o)=>{t.set(o,n)}),!e?.headers)return t;if(e.headers instanceof Headers)return e.headers.forEach((n,o)=>{t.set(o,n)}),t;if(Array.isArray(e.headers)){for(let[n,o]of e.headers)typeof o<"u"&&t.set(n,String(o));return t}for(let[n,o]of Object.entries(e.headers))typeof o<"u"&&t.set(n,String(o));return t}function d7t(r,e,t,n){let o=(r.get("anthropic-beta")??"").split(",").map(i=>i.trim()).filter(Boolean),s=["oauth-2025-04-20"];n||s.push(...t?Uv.filter(i=>i!=="oauth-2025-04-20"):[]),r.set("authorization",`Bearer ${e()}`),r.set("anthropic-beta",[...new Set([...o,...s])].join(",")),r.delete("x-api-key"),!n&&(r.set("user-agent",kE),r.set("anthropic-version","2023-06-01"),r.set("accept","application/json"),r.set("anthropic-dangerous-direct-browser-access","true"),r.set("x-app","cli"),r.set("connection","keep-alive"),r.set("x-stainless-retry-count","0"),r.set("x-stainless-runtime-version","v24.3.0"),r.set("x-stainless-package-version","0.74.0"),r.set("x-stainless-runtime","node"),r.set("x-stainless-lang","js"),r.set("x-stainless-arch",process.arch==="x64"?"x64":process.arch),r.set("x-stainless-os",process.platform==="darwin"?"MacOS":process.platform==="win32"?"Windows":"Linux"),r.set("x-stainless-timeout","600"))}async function p7t(r,e){let t=r instanceof Request?r:void 0,n=e?.method??t?.method,o=e?.body;return o===void 0&&t&&n!=="GET"&&n!=="HEAD"&&((t.headers.get("content-type")??"").includes("application/json")?o=await t.clone().text()||void 0:o=t.clone().body??void 0),{sourceRequest:t,method:n,body:o??void 0}}function m7t(r,e,t,n){let o=JSON.parse(r);n&&(o.tools&&Array.isArray(o.tools)&&(o.tools=o.tools.map(l=>({...l,name:l.name?`${hte}${l.name}`:l.name}))),o.messages&&Array.isArray(o.messages)&&(o.messages=o.messages.map(l=>(l.content&&Array.isArray(l.content)&&(l.content=l.content.map(u=>{let d=u;return d.type==="tool_use"&&d.name?{...d,name:`${hte}${d.name}`}:u})),l)))),(o.tool_choice?.type==="any"||o.tool_choice?.type==="tool")&&delete o.thinking;let s={type:"text",text:"You are a Claude agent, built on Anthropic's Claude Agent SDK."};if(o.system){if(typeof o.system=="string"&&(o.system=[{type:"text",text:o.system}]),Array.isArray(o.system)){let l=o.system.findIndex(f=>typeof f.text=="string"&&f.text.includes("x-anthropic-billing-header")),u=o.system.findIndex(f=>typeof f.text=="string"&&f.text.includes("Claude Agent SDK")),d={type:"text",text:RE(o.system[l]?.text)},m=[l,u].filter(f=>f>=0).sort((f,h)=>h-f);for(let f of m)o.system.splice(f,1);o.system=[...o.system,d,s]}}else{let l={type:"text",text:RE()};o.system=[l,s]}let i=t(),a=o.metadata?.user_id??i.substring(0,Math.min(20,i.length)),c=BG(a,{existingUserId:o.metadata?.user_id,preferredSessionId:e.get("x-claude-code-session-id")??void 0});return o.metadata={...o.metadata,user_id:c.metadataUserId},e.set("x-claude-code-session-id",c.sessionId),JSON.stringify(o)}async function f7t(r){try{let{propagation:e,context:t}=await Promise.resolve().then(()=>(hr(),Y3)),n={};e.inject(t.active(),n);for(let[o,s]of Object.entries(n))r.has(o)||r.set(o,s)}catch{}}function g7t(r){if(!r.body)return r;let e=r.body.getReader(),t=new TextDecoder,n=new TextEncoder,o=new Headers(r.headers);o.delete("content-length");let s="",i=new ReadableStream({async pull(a){let{done:c,value:l}=await e.read();if(c){s&&(a.enqueue(n.encode(s.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,'"name": "$1"'))),s=""),a.close();return}let u=t.decode(l,{stream:!0}),d=s+u,m=d.match(/"name"\s*:\s*"mcp_[^"]*$/),f;if(m&&m.index!==void 0)f=d.slice(0,m.index),s=d.slice(m.index);else{let y=d.lastIndexOf('"'),x=y>=0?y+1:d.length;f=d.slice(0,x),s=d.slice(x)}let h=f.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,'"name": "$1"');h&&a.enqueue(n.encode(h))},async cancel(a){await e.cancel(a)}});return new Response(i,{status:r.status,statusText:r.statusText,headers:o})}async function h7t(r,e,t,n,o,s){let i=l7t(r);i&&i.pathname==="/v1/messages"&&!i.searchParams.has("beta")&&i.searchParams.set("beta","true");let a=u7t(r,e);d7t(a,t,n,s),g.debug("[createOAuthFetch] Making OAuth request:",{url:i?.toString()||r.toString(),hasAuthorization:a.has("authorization"),authType:"Bearer",anthropicBeta:a.get("anthropic-beta"),userAgent:a.get("user-agent")});let{sourceRequest:c,method:l,body:u}=await p7t(r,e),d=u;if(d&&typeof d=="string"&&!s)try{d=m7t(d,a,t,o)}catch{}a.delete("content-length"),await f7t(a);let f=await Ze()(i?.toString()||(r instanceof Request?r.url:r.toString()),{...e,method:l,body:d,signal:e?.signal??c?.signal,headers:a});return o?g7t(f):f}function vNe(r,e=!0,t=!1,n=!1){return async(o,s)=>h7t(o,s,r,e,t,n)}var bNe=E(()=>{"use strict";zG();V();Vn()});var wNe={};K(wNe,{ANTHROPIC_BETA_HEADERS:()=>vte,AnthropicProvider:()=>VG,ModelAccessError:()=>_R,default:()=>T7t,getModelCapabilities:()=>jG,getRecommendedModelForTier:()=>GG,isModelAvailableForTier:()=>dP});var vte,TNe,xte,y7t,SNe,x7t,v7t,b7t,VG,T7t,ENe=E(()=>{"use strict";pte();hr();wn();dd();dn();zG();ql();oi();yte();bNe();Vn();mt();V();Ed();Nn();Rn();ite();yA();tY();vS();Bg();yte();vte={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")},TNe=()=>er(QMe()),xte=()=>tr("ANTHROPIC_MODEL","claude-sonnet-4-6"),y7t=it.getTracer("neurolink.provider.anthropic"),SNe=()=>{try{let e=Tr(dp(),".neurolink","anthropic-credentials.json");if(Sn(e)){let t=Ac(e,"utf-8"),n=JSON.parse(t);if(n.type==="oauth"&&n.oauth?.accessToken)return g.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(e){g.debug("[AnthropicProvider] Failed to read stored credentials:",e)}let r=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!r)return null;try{let e=JSON.parse(r);if(typeof e=="object"&&e.accessToken)return e;if(typeof e=="string")return{accessToken:e}}catch{}return{accessToken:r}},x7t=r=>{let e=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(e){let t=["free","pro","max","max_5","max_20","api"];if(t.includes(e))return g.debug("[detectSubscriptionTier] Using environment override",{tier:e}),e;g.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:e,validTiers:t})}if(r){let t=r.scopes??[],n="pro";return t.includes("max_20")?n="max_20":t.includes("max_5")?n="max_5":t.includes("max")&&(n="max"),g.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:t}),n}return g.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},v7t=r=>{let e=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(e==="api_key"||e==="apikey")return g.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(e==="oauth"){if(r)return g.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";g.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else e&&g.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:e});let t=r?"oauth":"api_key";return g.debug("[detectAuthMethod] Auth method resolved",{method:t,hasOAuthToken:!!r}),t},b7t=r=>{let e=n=>r instanceof Headers?r.get(n):r[n]||r[n.toLowerCase()]||null,t=n=>{if(!n)return;let o=parseInt(n,10);return isNaN(o)?void 0:o};return{requestsLimit:t(e("anthropic-ratelimit-requests-limit")),requestsRemaining:t(e("anthropic-ratelimit-requests-remaining")),requestsReset:e("anthropic-ratelimit-requests-reset")||void 0,tokensLimit:t(e("anthropic-ratelimit-tokens-limit")),tokensRemaining:t(e("anthropic-ratelimit-tokens-remaining")),tokensReset:e("anthropic-ratelimit-tokens-reset")||void 0,retryAfter:t(e("retry-after"))}},VG=class extends Mn{model;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,n,o){let s=!!(o?.apiKey&&!o?.oauthToken),i=s?null:(o?.oauthToken?{accessToken:o.oauthToken}:null)??n?.oauthToken??SNe(),a=s?"api_key":n?.authMethod??v7t(i),c=n?.subscriptionTier??(a==="oauth"?x7t(i):"api"),l=e||xte(),u=l;!process.env.ANTHROPIC_BASE_URL&&c!=="api"&&!dP(l,c)&&(u=GG(c),g.warn("Model not available for subscription tier, using recommended model",{requestedModel:l,subscriptionTier:c,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=n?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=c,this.authMethod=a;let m=this.getAuthHeaders(),f;if(g.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){g.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");let h=this.oauthToken,y=vNe(()=>h.accessToken,this.enableBetaFeatures,!1,!0);f=cP({apiKey:"oauth-authenticated",fetch:y}),g.debug("[AnthropicProvider] Anthropic SDK created with OAuth fetch wrapper"),g.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{let h=o?.apiKey??n?.apiKey??TNe(),y=(()=>{let x=process.env.ANTHROPIC_BASE_URL;if(!x)return;let b=x.replace(/\/+$/,"");return/\/v\d+$/.test(b)?b:(g.warn("[AnthropicProvider] ANTHROPIC_BASE_URL does not end with /vN; appending /v1 so the Vercel AI SDK can build /messages correctly. To silence this warning, set ANTHROPIC_BASE_URL with an explicit version segment (e.g. https://api.anthropic.com/v1). If your proxy exposes Anthropic at a custom path that doesn't expose /v1/messages, the auto-append will produce a 404 \u2014 pass the full path including the version explicitly.",{baseURL:x,rewrittenTo:`${b}/v1`}),`${b}/v1`)})();f=cP({apiKey:h,headers:m,...y&&{baseURL:y},fetch:Ze()}),g.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.model=f(this.modelName||xte()),this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},g.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?vte["anthropic-beta"]:"disabled"})}getAuthHeaders(){let e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){let n=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",o=[...Uv,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];n&&o.push("context-1m-2025-08-07"),e["anthropic-beta"]=o.join(",")}else e["anthropic-beta"]=vte["anthropic-beta"];return this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return g.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;let t=dP(e,this.subscriptionTier);return t||g.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return jG(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){g.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){g.debug("Token has no expiry information, assuming valid");return}let e=Date.now(),t=this.oauthToken.expiresAt<=e,n=this.oauthToken.expiresAt<=e+3e5;if(!t&&!n){g.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new ut("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);g.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}g.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});let o=this.oauthToken,s=o.refreshToken;this.refreshPromise=(async()=>{let a=new AbortController,c=setTimeout(()=>a.abort(),3e4),l=await fetch(yNe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":kE},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:s,client_id:hNe}),signal:a.signal});if(clearTimeout(c),!l.ok){let m=await l.text();throw new ut(`Failed to refresh OAuth token: ${l.status} ${m}`,this.providerName)}let u=await l.json();o.accessToken=u.access_token,o.refreshToken=u.refresh_token||o.refreshToken,o.expiresAt=u.expires_in?Date.now()+u.expires_in*1e3:void 0,o.tokenType=u.token_type||"Bearer";let d=o;try{let m=Tr(dp(),".neurolink");Sn(m)||jk(m,{recursive:!0});let f=Tr(m,"anthropic-credentials.json"),h=`${f}.tmp`,x={...Sn(f)?JSON.parse(Ac(f,"utf-8")):{},type:"oauth",oauth:d,updatedAt:Date.now()};Gk(h,JSON.stringify(x,null,2),{mode:384}),cK(h,f),g.debug("Refreshed OAuth credentials persisted to disk")}catch(m){g.warn("Failed to persist refreshed OAuth token to disk",{error:m instanceof Error?m.message:String(m)})}g.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!u.refresh_token,expiresIn:u.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof ut?i:new ut(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,n){this.lastResponseMetadata={rateLimit:b7t(e),requestId:t||(e instanceof Headers?e.get("x-request-id")||void 0:e["x-request-id"]),serverTiming:e instanceof Headers?e.get("server-timing")||void 0:e["server-timing"]};let o=this.lastResponseMetadata.rateLimit;this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),n&&(n.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=n.inputTokens,this.usageInfo.tokensUsed+=n.inputTokens),n.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=n.outputTokens,this.usageInfo.tokensUsed+=n.outputTokens)),o?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=o.requestsRemaining),o?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=o.tokensRemaining),o?.requestsLimit&&o.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((o.requestsLimit-(o.requestsRemaining??0))/o.requestsLimit*100)),o?.tokensLimit&&o.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((o.tokensLimit-(o.tokensRemaining??0))/o.tokensLimit*100)),o?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+o.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),o?.requestsRemaining!==void 0&&o.requestsRemaining<=5&&g.warn("Approaching Anthropic request rate limit",{remaining:o.requestsRemaining,limit:o.requestsLimit,reset:o.requestsReset}),o?.tokensRemaining!==void 0&&o.tokensLimit&&o.tokensRemaining<o.tokensLimit*.1&&g.warn("Approaching Anthropic token rate limit",{remaining:o.tokensRemaining,limit:o.tokensLimit,reset:o.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return xte()}getAISDKModel(){return this.model}formatProviderError(e){if(e instanceof At)return new ht(`Request timed out after ${e.timeout}ms`,this.providerName);let t=e,n=typeof t?.message=="string"?t.message:"Unknown error";return n.includes("API_KEY_INVALID")||n.includes("Invalid API key")?new ut("Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable.",this.providerName):n.includes("rate limit")||n.includes("too_many_requests")||n.includes("429")?new Rt("Anthropic rate limit exceeded. Please try again later.",this.providerName):n.includes("ECONNRESET")||n.includes("ENOTFOUND")||n.includes("ECONNREFUSED")||n.includes("network")||n.includes("connection")?new ht(`Connection error: ${n}`,this.providerName):n.includes("500")||n.includes("502")||n.includes("503")||n.includes("504")||n.includes("server error")?new Te(`Server error: ${n}`,this.providerName):new Te(`Anthropic error: ${n}`,this.providerName)}async generate(e,t){return await this.refreshAuthIfNeeded(),super.generate(e,t)}async executeStream(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);let n=this.getTimeout(e),o=Is(n,this.providerName,"stream");try{let s=!e.disableTools&&this.supportsTools(),i=s?e.tools||await this.getAllTools():{},a=await this.buildMessagesForStream(e),c=await this.getAISDKModelWithMiddleware(e),l=y7t.startSpan("neurolink.provider.streamText",{kind:gr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":YS(c,this.modelName||"unknown")}}),u,d;try{d=vR({model:c,messages:a,temperature:e.temperature,maxOutputTokens:e.maxTokens,maxRetries:0,tools:i,stopWhen:yx(e.maxSteps||Vo),toolChoice:LG(e,i,s),abortSignal:Fm(e.abortSignal,o?.controller.signal),onError:y=>{u=y.error,g.error("Anthropic: Stream error",{error:y.error instanceof Error?y.error.message:String(y.error)})},experimental_repairToolCall:this.getToolCallRepairFn(e),experimental_telemetry:this.telemetryHandler.getTelemetryConfig(e),onStepFinish:({toolCalls:y,toolResults:x})=>{sh(this.neurolink?.getEventEmitter(),x),this.handleToolExecutionStorage(y,x,e,new Date).catch(b=>{g.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:b instanceof Error?b.message:String(b)})})}})}catch(y){throw l.setStatus({code:me.ERROR,message:y instanceof Error?y.message:String(y)}),y instanceof Error&&l.recordException(y),l.end(),y}Promise.resolve(d.usage).then(y=>{l.setAttribute("gen_ai.usage.input_tokens",y.inputTokens||0),l.setAttribute("gen_ai.usage.output_tokens",y.outputTokens||0);let x=ko(this.providerName,this.modelName,{input:y.inputTokens||0,output:y.outputTokens||0,total:(y.inputTokens||0)+(y.outputTokens||0)});x&&x>0&&l.setAttribute("neurolink.cost",x)}).catch(()=>{}),Promise.resolve(d.finishReason).then(y=>{l.setAttribute("gen_ai.response.finish_reason",y||"unknown")}).catch(()=>{}),Promise.resolve(d.text).then(()=>{l.end()}).catch(y=>{l.setStatus({code:me.ERROR,message:y instanceof Error?y.message:String(y)}),l.end()}),o?.cleanup();let m=this.createTextStream(d,()=>u),f=[],h=[];return{stream:m,provider:this.providerName,model:this.modelName,toolCalls:f,toolResults:h}}catch(s){throw o?.cleanup(),this.handleProviderError(s)}}async isAvailable(){try{return SNe()||TNe(),!0}catch{return!1}}getModel(){return this.model}},T7t=VG});var _Ne={};K(_Ne,{Agent:()=>oQt,BedrockClient:()=>w7t,BedrockRuntimeClient:()=>bte,Blob:()=>nQt,Client:()=>iQt,ConverseCommand:()=>Tte,ConverseStreamCommand:()=>HG,Cron:()=>$7t,Dispatcher:()=>aQt,File:()=>rQt,FlowProducer:()=>F7t,FormData:()=>tQt,GoogleAuth:()=>R7t,HTTPException:()=>q7t,Headers:()=>eQt,Hippocampus:()=>P7t,HippocampusConfig:()=>M7t,Hono:()=>V7t,ImageFormat:()=>IE,InvokeEndpointCommand:()=>C7t,InvokeEndpointWithResponseStreamCommand:()=>k7t,Job:()=>L7t,ListFoundationModelsCommand:()=>E7t,MockAgent:()=>uQt,Pool:()=>sQt,Queue:()=>N7t,QueueScheduler:()=>U7t,Request:()=>Y7t,Response:()=>Q7t,SageMakerRuntimeClient:()=>_7t,TextToSpeechClient:()=>I7t,VertexAI:()=>A7t,Worker:()=>D7t,convertToHtml:()=>j7t,cors:()=>H7t,createClient:()=>O7t,default:()=>S7t,extractRawText:()=>G7t,fetch:()=>Z7t,getGlobalDispatcher:()=>lQt,interceptors:()=>dQt,logger:()=>W7t,parseBuffer:()=>B7t,request:()=>pQt,secureHeaders:()=>K7t,selectCover:()=>z7t,setGlobalDispatcher:()=>cQt,streamSSE:()=>J7t,timeout:()=>X7t});var AE,ki,S7t,w7t,E7t,bte,Tte,HG,IE,_7t,C7t,k7t,R7t,A7t,I7t,P7t,M7t,O7t,N7t,D7t,L7t,U7t,F7t,$7t,B7t,z7t,G7t,j7t,V7t,H7t,q7t,W7t,K7t,J7t,X7t,Z7t,Y7t,Q7t,eQt,tQt,rQt,nQt,oQt,sQt,iQt,aQt,cQt,lQt,uQt,dQt,pQt,Ste=E(()=>{AE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:AE.get}):new Proxy(function(...t){return new Proxy({},{get:AE.get})},{get:AE.get,apply(t,n,o){return new Proxy({},{get:AE.get})},construct(t,n){return new Proxy({},{get:AE.get})}})}},ki=new Proxy({},AE),S7t=ki,{BedrockClient:w7t,ListFoundationModelsCommand:E7t,BedrockRuntimeClient:bte,ConverseCommand:Tte,ConverseStreamCommand:HG,ImageFormat:IE}=ki,{SageMakerRuntimeClient:_7t,InvokeEndpointCommand:C7t,InvokeEndpointWithResponseStreamCommand:k7t}=ki,{GoogleAuth:R7t,VertexAI:A7t,TextToSpeechClient:I7t}=ki,{Hippocampus:P7t,HippocampusConfig:M7t}=ki,{createClient:O7t}=ki,{Queue:N7t,Worker:D7t,Job:L7t,QueueScheduler:U7t,FlowProducer:F7t}=ki,{Cron:$7t}=ki,{parseBuffer:B7t,selectCover:z7t}=ki,{extractRawText:G7t,convertToHtml:j7t}=ki,{Hono:V7t}=ki,{cors:H7t,HTTPException:q7t,logger:W7t,secureHeaders:K7t,streamSSE:J7t,timeout:X7t}=ki,Z7t=globalThis.fetch,Y7t=globalThis.Request,Q7t=globalThis.Response,eQt=globalThis.Headers,tQt=globalThis.FormData,rQt=globalThis.File,nQt=globalThis.Blob,oQt=ki.Agent,sQt=ki.Pool,iQt=ki.Client,aQt=ki.Dispatcher,cQt=()=>{},lQt=()=>ki,uQt=ki.MockAgent,dQt={redirect:()=>r=>r,retry:()=>r=>r},pQt=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});function wte(r,e,t){return{input:{text:r.input?.text||"",images:r.input?.images,content:r.input?.content,files:r.input?.files,csvFiles:r.input?.csvFiles,pdfFiles:r.input?.pdfFiles},csvOptions:r.csvOptions,systemPrompt:r.systemPrompt,conversationHistory:r.conversationMessages,provider:e,model:t,temperature:r.temperature,maxTokens:r.maxTokens,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,context:r.context,fileRegistry:r.fileRegistry}}var CNe=E(()=>{"use strict"});var kNe={};K(kNe,{Agent:()=>QQt,BedrockClient:()=>fQt,BedrockRuntimeClient:()=>hQt,Blob:()=>YQt,Client:()=>ter,ConverseCommand:()=>yQt,ConverseStreamCommand:()=>xQt,Cron:()=>NQt,Dispatcher:()=>rer,File:()=>ZQt,FlowProducer:()=>OQt,FormData:()=>XQt,GoogleAuth:()=>wQt,HTTPException:()=>zQt,Headers:()=>JQt,Hippocampus:()=>CQt,HippocampusConfig:()=>kQt,Hono:()=>$Qt,ImageFormat:()=>vQt,InvokeEndpointCommand:()=>TQt,InvokeEndpointWithResponseStreamCommand:()=>SQt,Job:()=>PQt,ListFoundationModelsCommand:()=>gQt,MockAgent:()=>ser,Pool:()=>eer,Queue:()=>AQt,QueueScheduler:()=>MQt,Request:()=>WQt,Response:()=>KQt,SageMakerRuntimeClient:()=>bQt,TextToSpeechClient:()=>_Qt,VertexAI:()=>EQt,Worker:()=>IQt,convertToHtml:()=>FQt,cors:()=>BQt,createClient:()=>RQt,default:()=>mQt,extractRawText:()=>UQt,fetch:()=>qQt,getGlobalDispatcher:()=>oer,interceptors:()=>ier,logger:()=>GQt,parseBuffer:()=>DQt,request:()=>aer,secureHeaders:()=>jQt,selectCover:()=>LQt,setGlobalDispatcher:()=>ner,streamSSE:()=>VQt,timeout:()=>HQt});var PE,Ri,mQt,fQt,gQt,hQt,yQt,xQt,vQt,bQt,TQt,SQt,wQt,EQt,_Qt,CQt,kQt,RQt,AQt,IQt,PQt,MQt,OQt,NQt,DQt,LQt,UQt,FQt,$Qt,BQt,zQt,GQt,jQt,VQt,HQt,qQt,WQt,KQt,JQt,XQt,ZQt,YQt,QQt,eer,ter,rer,ner,oer,ser,ier,aer,RNe=E(()=>{PE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:PE.get}):new Proxy(function(...t){return new Proxy({},{get:PE.get})},{get:PE.get,apply(t,n,o){return new Proxy({},{get:PE.get})},construct(t,n){return new Proxy({},{get:PE.get})}})}},Ri=new Proxy({},PE),mQt=Ri,{BedrockClient:fQt,ListFoundationModelsCommand:gQt,BedrockRuntimeClient:hQt,ConverseCommand:yQt,ConverseStreamCommand:xQt,ImageFormat:vQt}=Ri,{SageMakerRuntimeClient:bQt,InvokeEndpointCommand:TQt,InvokeEndpointWithResponseStreamCommand:SQt}=Ri,{GoogleAuth:wQt,VertexAI:EQt,TextToSpeechClient:_Qt}=Ri,{Hippocampus:CQt,HippocampusConfig:kQt}=Ri,{createClient:RQt}=Ri,{Queue:AQt,Worker:IQt,Job:PQt,QueueScheduler:MQt,FlowProducer:OQt}=Ri,{Cron:NQt}=Ri,{parseBuffer:DQt,selectCover:LQt}=Ri,{extractRawText:UQt,convertToHtml:FQt}=Ri,{Hono:$Qt}=Ri,{cors:BQt,HTTPException:zQt,logger:GQt,secureHeaders:jQt,streamSSE:VQt,timeout:HQt}=Ri,qQt=globalThis.fetch,WQt=globalThis.Request,KQt=globalThis.Response,JQt=globalThis.Headers,XQt=globalThis.FormData,ZQt=globalThis.File,YQt=globalThis.Blob,QQt=Ri.Agent,eer=Ri.Pool,ter=Ri.Client,rer=Ri.Dispatcher,ner=()=>{},oer=()=>Ri,ser=Ri.MockAgent,ier={redirect:()=>r=>r,retry:()=>r=>r},aer=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});var INe={};K(INe,{AmazonBedrockProvider:()=>_te});async function ANe(){return await Promise.resolve().then(()=>(RNe(),kNe))}var Ete,_te,PNe=E(()=>{"use strict";Ste();dn();zI();ql();oi();mt();at();yA();V();Ed();LI();CNe();wp();hr();zc();Ete=ce.provider,_te=class r extends Mn{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(e){return e?e.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(e,t,n,o){super(e,"bedrock",t);let s=e||process.env.BEDROCK_MODEL||this.modelName,i=r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",g.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),g.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{g.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new bte({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),g.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw g.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){let{BedrockClient:e,ListFoundationModelsCommand:t}=await ANe(),n=new e({region:this.region});try{g.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");let o=new t({}),s=Date.now();await n.send(o);let i=Date.now()-s;g.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){let s=o instanceof Error?o.message:String(o);g.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(e){g.debug("[AmazonBedrockProvider] generate() called with conversation management");let t=Date.now(),n=typeof e=="string"?{prompt:e}:e;this.conversationHistory=[];let o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){g.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});let d=wte(n,this.providerName,this.modelName),m=await dE(d,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(m)}else{g.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");let u={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(u)}g.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,c;try{({text:i,usage:a,finishReason:c}=await this.conversationLoop(n))}catch(u){let d=this.neurolink?.getEventEmitter();throw d&&d.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,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:u instanceof Error?u.message:String(u)}),u}let l=this.neurolink?.getEventEmitter();return l&&l.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:c},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName()}}async conversationLoop(e){let n=0,o=0,s=0,i;for(;n<10;){n++,g.debug(`[AmazonBedrockProvider] Conversation iteration ${n}`);try{g.debug("[AmazonBedrockProvider] About to call Bedrock API");let a=await this.callBedrock(e);g.debug("[AmazonBedrockProvider] Received Bedrock response",JSON.stringify(a,null,2)),o+=a.usage?.inputTokens??0,s+=a.usage?.outputTokens??0,a.stopReason&&(i=a.stopReason);let c=await this.handleBedrockResponse(a);if(g.debug("[AmazonBedrockProvider] Handle response result:",c),c.shouldContinue)g.debug("[AmazonBedrockProvider] Continuing conversation loop...");else return g.debug("[AmazonBedrockProvider] Conversation completed with final text"),g.debug(`[AmazonBedrockProvider] Returning final text: "${c.text}"`),{text:c.text||"",usage:{input:o,output:s,total:o+s},finishReason:i}}catch(a){throw g.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}throw new Error("Conversation loop exceeded maximum iterations")}async callBedrock(e){let t=Date.now();return Ete.startActiveSpan("bedrock.generate",{kind:gr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"chat"}},async n=>{g.info(`[AmazonBedrockProvider] Starting Bedrock API call at ${new Date().toISOString()}`);try{let o="unknown";try{o=typeof this.bedrockClient.config.region=="function"?await this.bedrockClient.config.region():this.bedrockClient.config.region??"unknown"}catch{}g.info(`[AmazonBedrockProvider] Client region: ${o}`),g.info(`[AmazonBedrockProvider] Model: ${this.modelName||this.getDefaultModel()}`),g.info(`[AmazonBedrockProvider] Conversation history length: ${this.conversationHistory.length}`);let s=await this.getAllTools(),i=this.convertAISDKToolsToToolDefinitions(s),a=this.formatToolsForBedrock(i),c={modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(this.conversationHistory),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,temperature:e.temperature||.7}};a&&(c.toolConfig=a,g.info(`[AmazonBedrockProvider] Tools configured: ${a.tools?.length||0}`)),g.info("[AmazonBedrockProvider] Command input summary:"),g.info(` - Model ID: ${c.modelId}`),g.info(` - Messages count: ${c.messages?.length||0}`),g.info(` - System prompts: ${c.system?.length||0}`),g.info(` - Max tokens: ${c.inferenceConfig?.maxTokens}`),g.info(` - Temperature: ${c.inferenceConfig?.temperature}`),g.debug(`[AmazonBedrockProvider] Calling Bedrock with ${this.conversationHistory.length} messages and ${a?.tools?.length||0} tools`);let l=new Tte(c);g.debug("[Observability] Bedrock API request",{model:c.modelId,region:o,messageCount:c.messages?.length||0,toolCount:c.toolConfig?.tools?.length||0,maxTokens:c.inferenceConfig?.maxTokens});let u=Date.now(),d=await we(this.bedrockClient.send(l),12e4,new Error("Bedrock API call timed out")),m=Date.now()-u;g.debug("[Observability] Bedrock API response",{model:c.modelId,durationMs:m,hasContent:!!d.output?.message?.content?.length,stopReason:d.stopReason,usage:d.usage?{inputTokens:d.usage.inputTokens,outputTokens:d.usage.outputTokens,totalTokens:(d.usage.inputTokens||0)+(d.usage.outputTokens||0)}:void 0}),g.info("[AmazonBedrockProvider] Bedrock API call successful"),g.info(`[AmazonBedrockProvider] API call duration: ${m}ms`);let f=Date.now()-t;g.info(`[AmazonBedrockProvider] Total callBedrock duration: ${f}ms`),n.setAttribute("gen_ai.response.stop_reason",d.stopReason??""),n.setAttribute("gen_ai.usage.input_tokens",d.usage?.inputTokens??0),n.setAttribute("gen_ai.usage.output_tokens",d.usage?.outputTokens??0);let h=ko(this.providerName,this.modelName,{input:d.usage?.inputTokens??0,output:d.usage?.outputTokens??0,total:(d.usage?.inputTokens??0)+(d.usage?.outputTokens??0)});return h&&h>0&&n.setAttribute("neurolink.cost",h),n.setStatus({code:me.OK}),n.end(),d}catch(o){let s=Date.now()-t,i=o&&typeof o=="object"?o:null,a=i?.$metadata&&typeof i.$metadata=="object"?i.$metadata:null;throw g.debug("[Observability] Bedrock API request failed",{model:this.modelName||this.getDefaultModel(),durationMs:s,error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:void 0,httpStatus:a?.httpStatusCode,awsRequestId:a?.requestId,awsErrorCode:i?.Code}),g.error(`[AmazonBedrockProvider] Bedrock API call failed after ${s}ms`),o instanceof Error&&g.error(`[AmazonBedrockProvider] Error: ${o.name} - ${o.message}`),a&&g.error("[AmazonBedrockProvider] AWS SDK metadata",{httpStatus:a.httpStatusCode,requestId:a.requestId,attempts:a.attempts,totalRetryDelay:a.totalRetryDelay}),n.setStatus({code:me.ERROR,message:o instanceof Error?o.message:String(o)}),n.recordException(o instanceof Error?o:new Error(String(o))),n.end(),o}})}async handleBedrockResponse(e){if(g.debug(`[AmazonBedrockProvider] Received response with stopReason: ${e.stopReason}`),!e.output||!e.output.message)throw new Error("Invalid response structure from Bedrock API");let t=e.output.message,n=e.stopReason,o={role:"assistant",content:(t.content||[]).map(s=>{let i={};return"text"in s&&s.text&&(i.text=s.text),"toolUse"in s&&s.toolUse&&(i.toolUse={toolUseId:s.toolUse.toolUseId||"",name:s.toolUse.name||"",input:s.toolUse.input||{}}),"toolResult"in s&&s.toolResult&&(i.toolResult={toolUseId:s.toolResult.toolUseId||"",content:(s.toolResult.content||[]).map(a=>({text:typeof a=="object"&&"text"in a&&a.text||""})),status:s.toolResult.status||"unknown"}),i})};if(this.conversationHistory.push(o),n==="end_turn"||n==="stop_sequence")return{shouldContinue:!1,text:o.content.filter(i=>i.text).map(i=>i.text).join(" ")};if(n==="tool_use"){g.debug("[AmazonBedrockProvider] Tool use detected - executing tools immediately");let s=[];for(let i of o.content)if(i.toolUse){g.debug(`[AmazonBedrockProvider] Executing tool: ${i.toolUse.name}`);try{g.debug("[AmazonBedrockProvider] Debug toolUse.input:",JSON.stringify(i.toolUse.input,null,2));let a=await this.executeSingleTool(i.toolUse.name,i.toolUse.input||{},i.toolUse.toolUseId);g.debug(`[AmazonBedrockProvider] Tool execution successful: ${i.toolUse.name}`),s.push({toolResult:{toolUseId:i.toolUse.toolUseId,content:[{text:String(a)}],status:"success"}})}catch(a){g.error(`[AmazonBedrockProvider] Tool execution failed: ${i.toolUse.name}`,a);let c=a instanceof Error?a.message:String(a);s.push({toolResult:{toolUseId:i.toolUse.toolUseId,content:[{text:`Error executing tool ${i.toolUse.name}: ${c}`}],status:"error"}})}}if(s.length>0){let i={role:"user",content:s};this.conversationHistory.push(i),g.debug(`[AmazonBedrockProvider] Added ${s.length} tool results to conversation`)}return{shouldContinue:!0}}else return n==="max_tokens"?{shouldContinue:!1,text:o.content.filter(i=>i.text).map(i=>i.text).join(" ")}:(g.warn(`[AmazonBedrockProvider] Unrecognized stop reason "${n}", ending conversation.`),{shouldContinue:!1,text:""})}convertToAWSMessages(e){return e.map(t=>({role:t.role,content:t.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(e,t,n){return Ete.startActiveSpan("bedrock.tool.execute",{kind:gr.CLIENT,attributes:{"gen_ai.tool.name":e,"gen_ai.system":"aws.bedrock"}},async o=>{try{g.debug(`[AmazonBedrockProvider] Executing single tool: ${e}`,{args:t});let s=await this.getAllTools(),i=this.convertAISDKToolsToToolDefinitions(s);if(!i[e])throw new Error(`Tool not found: ${e}`);let a=i[e];if(!a||!a.execute)throw new Error(`Tool ${e} does not have execute method`);let c=t||{};e==="list_directory"&&!c.path&&(c.path=".",g.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),g.debug("[AmazonBedrockProvider] Tool input parameters:",c);let l={};for(let[m,f]of Object.entries(c))(f===null||typeof f=="string"||typeof f=="number"||typeof f=="boolean"||typeof f=="object"&&f!==null)&&(l[m]=f);let u=await a.execute(l);g.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:e,result:u});let d;if(u&&typeof u=="object"&&"success"in u)if(u.success&&u.data!==void 0)typeof u.data=="string"?d=u.data:typeof u.data=="object"?d=JSON.stringify(u.data,null,2):d=String(u.data);else if(u.error){let m=typeof u.error=="string"?u.error:u.error.message||"Tool execution failed";throw new Error(m)}else d="";else typeof u=="string"?d=u:typeof u=="object"?d=JSON.stringify(u,null,2):d=String(u);return o.setStatus({code:me.OK}),d}catch(s){throw g.error("[AmazonBedrockProvider] Tool execution error:",{toolName:e,error:s}),o.setStatus({code:me.ERROR,message:s.message}),o.recordException(s),s}finally{o.end()}})}convertAISDKToolsToToolDefinitions(e){let t={};for(let[n,o]of Object.entries(e))if("description"in o&&o.description){let i=o.parameters??o.inputSchema;t[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 t}formatToolsForBedrock(e){if(!e||Object.keys(e).length===0)return null;let t=Object.entries(e).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=si(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 g.debug(`[AmazonBedrockProvider] Formatted ${t.length} tools for Bedrock`),{tools:t}}convertToBedrockMessages(e){return e.map(t=>{let n={role:t.role==="system"?"user":t.role,content:[]};return typeof t.content=="string"?n.content.push({text:t.content}):t.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){let s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image,i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?IE.JPEG:i==="png"?IE.PNG:i==="gif"?IE.GIF:IE.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"){let 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?_a.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(e){return g.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),g.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Ete.startActiveSpan("bedrock.stream",{kind:gr.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async t=>{try{if(g.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(e.input?.images?.length||e.input?.content?.length||e.input?.files?.length||e.input?.csvFiles?.length||e.input?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!e.input?.images?.length,imageCount:e.input?.images?.length||0,hasContent:!!e.input?.content?.length,contentCount:e.input?.content?.length||0,hasFiles:!!e.input?.files?.length,fileCount:e.input?.files?.length||0,hasCSVFiles:!!e.input?.csvFiles?.length,csvFileCount:e.input?.csvFiles?.length||0,hasPDFFiles:!!e.input?.pdfFiles?.length,pdfFileCount:e.input?.pdfFiles?.length||0});let s=wte(e,this.providerName,this.modelName),i=await dE(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{g.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");let s={role:"user",content:[{text:e.input.text}]};this.conversationHistory.push(s)}g.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),g.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");let o=await this.streamingConversationLoop(e,t);return g.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),t.setStatus({code:me.OK}),t.end(),o}catch(n){g.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");let o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(g.debug("[TRACE] executeStream CATCH - checking if permission error"),g.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){g.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),g.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),t.addEvent("stream.fallback_to_generate",{reason:o.message});let i=await this.generate({prompt:e.input.text,input:e.input,maxTokens:e.maxTokens,temperature:e.temperature,systemPrompt:e.systemPrompt});if(!i)throw t.setStatus({code:me.ERROR,message:"Generate method returned null result"}),t.end(),new Error("Generate method returned null result");t.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),t.setStatus({code:me.OK}),t.end();let a=new ReadableStream({start(l){let d=(i.content||"").split(/(\s+)/),m="";for(let f=0;f<d.length;f++)m+=d[f],(f===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](){let l=a.getReader();try{for(;;){let{done:u,value:d}=await l.read();if(u)break;yield d}}finally{l.releaseLock()}}},usage:{total:0,input:0,output:0},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw t.setStatus({code:me.ERROR,message:o instanceof Error?o.message:String(o)}),t.recordException(o instanceof Error?o:new Error(String(o))),t.end(),n}})}async streamingConversationLoop(e,t){g.debug("[TRACE] streamingConversationLoop ENTRY");let n=Date.now(),o=e.maxSteps||Vo,s=0,i=0,a=0,c;try{g.debug("[TRACE] streamingConversationLoop - testing first streaming call");let l=await this.prepareStreamCommand(e),u=new HG(l);g.debug("[Observability] Bedrock streaming API request",{model:l.modelId,messageCount:l.messages?.length||0,toolCount:l.toolConfig?.tools?.length||0}),t.addEvent("stream.api_call",{"bedrock.message_count":l.messages?.length||0,"bedrock.tool_count":l.toolConfig?.tools?.length||0});let d=Date.now(),m=await we(this.bedrockClient.send(u),12e4,new Error("Bedrock streaming API call timed out"));g.debug("[Observability] Bedrock streaming API connection established",{model:l.modelId,durationMs:Date.now()-d,hasStream:!!m.stream});let f=new ReadableStream({start:async _=>{g.debug("[TRACE] streamingConversationLoop - ReadableStream start() called");try{let C="";if(m.stream){let k=[],I="";for await(let M of m.stream){if(M.contentBlockStart&&k.push({}),M.contentBlockDelta?.delta?.text){let D=M.contentBlockDelta.delta.text;I+=D,_.enqueue({content:D})}if(M.contentBlockStart?.start?.toolUse){let D=k[k.length-1];D.toolUse={name:M.contentBlockStart.start.toolUse.name||"",input:{},toolUseId:M.contentBlockStart.start.toolUse.toolUseId||`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}}if(M.contentBlockDelta?.delta?.toolUse){let D=k[k.length-1];D.toolUse||(D.toolUse={name:"",input:{},toolUseId:`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`});let B=M.contentBlockDelta.delta.toolUse.input;if(B){if(typeof B=="string")D._inputBuffer=(D._inputBuffer||"")+B;else if(typeof B=="object"&&!Array.isArray(B)){let O=D.toolUse.input||{};D.toolUse.input={...O,...B}}}}if(M.contentBlockStop){let D=k[k.length-1];if(D?.toolUse&&D._inputBuffer){try{D.toolUse.input=JSON.parse(D._inputBuffer)}catch{D.toolUse.input={}}delete D._inputBuffer}I&&D&&!D.toolUse&&(D.text=I),I=""}if(M.messageStop){C=M.messageStop.stopReason||"end_turn";continue}if(M.metadata?.usage){i+=M.metadata.usage.inputTokens??0,a+=M.metadata.usage.outputTokens??0;break}}C&&(c=C);let R={role:"assistant",content:k};if(this.conversationHistory.push(R),t.addEvent("stream.turn_complete",{iteration:0,stop_reason:C}),C==="tool_use"){let M=k.flatMap(D=>D.toolUse?.name?[D.toolUse.name]:[]).join(", ");t.addEvent("stream.tool_use",{iteration:0,tool_names:M})}if(!await this.handleStreamStopReason(C,R,_,e)){t.setAttribute("gen_ai.response.stop_reason",C),_.close();return}}for(;s<o;){s++,g.debug(`[AmazonBedrockProvider] Streaming iteration ${s}`);let k=await this.prepareStreamCommand(e),{stopReason:I,assistantMessage:R,usage:A}=await this.processStreamResponse(k,_);if(A&&(i+=A.input,a+=A.output),I&&(c=I),t.addEvent("stream.turn_complete",{iteration:s,stop_reason:I}),I==="tool_use"){let D=R.content.flatMap(B=>B.toolUse?.name?[B.toolUse.name]:[]).join(", ");t.addEvent("stream.tool_use",{iteration:s,tool_names:D})}if(!await this.handleStreamStopReason(I,R,_,e)){t.setAttribute("gen_ai.response.stop_reason",I);break}}if(s>=o){t.setAttribute("gen_ai.response.stop_reason","max_iterations"),_.error(new Error("Streaming conversation exceeded maximum iterations"));return}_.close()}catch(C){g.debug("[TRACE] streamingConversationLoop - CATCH block hit in ReadableStream"),_.error(C)}}}),h=this.neurolink?.getEventEmitter(),y=this.convertToAsyncIterable(f),x=this,b,S=new Promise(_=>{b=_});return{stream:{async*[Symbol.asyncIterator](){let _=!1;try{yield*y}catch(C){throw _=!0,C}finally{let C={input:i,output:a,total:i+a};b(Fh(x.providerName,x.modelName||x.getDefaultModel(),{usage:C},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0})),h&&h.emit("generation:end",{provider:x.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:C,model:x.modelName||x.getDefaultModel(),provider:x.providerName,finishReason:_?"error":c},success:!_})}}},usage:{total:0,input:0,output:0},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:S,metadata:{startTime:n,streamId:`bedrock-${Date.now()}`}}}catch(l){throw g.debug("[TRACE] streamingConversationLoop - first streaming call FAILED, throwing"),l}}convertToAsyncIterable(e){return{async*[Symbol.asyncIterator](){let t=e.getReader();try{for(;;){let{done:n,value:o}=await t.read();if(n)break;yield o}}finally{t.releaseLock()}}}}async prepareStreamCommand(e){g.shouldLog("debug")&&(g.debug(`[AmazonBedrockProvider] BEFORE conversion - conversationHistory length: ${this.conversationHistory.length}`),this.conversationHistory.forEach((a,c)=>{g.debug(`[AmazonBedrockProvider] Message ${c}: role=${a.role}, content=${JSON.stringify(a.content)}`)}));let t=e.tools||await this.getAllTools(),n=this.convertAISDKToolsToToolDefinitions(t),o=this.formatToolsForBedrock(n),s=this.convertToAWSMessages(this.conversationHistory);g.shouldLog("debug")&&(g.debug(`[AmazonBedrockProvider] AFTER conversion - messages length: ${s.length}`),s.forEach((a,c)=>{g.debug(`[AmazonBedrockProvider] Converted Message ${c}: role=${a.role}, content=${JSON.stringify(a.content)}`)}));let i={modelId:this.modelName||this.getDefaultModel(),messages:s,system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,temperature:e.temperature||.7}};return o&&(i.toolConfig=o),g.debug(`[AmazonBedrockProvider] Calling Bedrock streaming with ${this.conversationHistory.length} messages`),g.debug("[AmazonBedrockProvider] DEBUG - Conversation structure:"),this.conversationHistory.forEach((a,c)=>{g.debug(` Message ${c} (${a.role}): ${a.content.length} content items`),a.content.forEach((l,u)=>{let d=Object.keys(l);g.debug(` Content ${u}: ${d.join(", ")}`)})}),i}async processStreamResponse(e,t){let n=new HG(e);g.debug("[Observability] Bedrock streaming API request (continuation)",{model:e.modelId,messageCount:e.messages?.length||0});let o=Date.now(),s=await we(this.bedrockClient.send(n),12e4,new Error("Bedrock streaming API call timed out"));if(g.debug("[Observability] Bedrock streaming API connection established (continuation)",{model:e.modelId,durationMs:Date.now()-o}),!s.stream)throw new Error("No stream returned from Bedrock");let i=[],a="",c="",l;for await(let d of s.stream){if(d.contentBlockStart&&i.push({}),d.contentBlockDelta?.delta?.text){let m=d.contentBlockDelta.delta.text;c+=m,t.enqueue({content:m})}if(d.contentBlockStart?.start?.toolUse){let m=i[i.length-1];m.toolUse={name:d.contentBlockStart.start.toolUse.name||"",input:{},toolUseId:d.contentBlockStart.start.toolUse.toolUseId||`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}}if(d.contentBlockDelta?.delta?.toolUse){let m=i[i.length-1];if(m.toolUse||(m.toolUse={name:"",input:{},toolUseId:`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}),d.contentBlockDelta.delta.toolUse.input){let f=d.contentBlockDelta.delta.toolUse.input;if(typeof f=="string")m._inputBuffer=(m._inputBuffer||"")+f;else if(f&&typeof f=="object"&&!Array.isArray(f)){let h=m.toolUse.input||{};m.toolUse.input={...h,...f}}}}if(d.contentBlockStop){let m=i[i.length-1];if(m?.toolUse&&m._inputBuffer){try{m.toolUse.input=JSON.parse(m._inputBuffer)}catch{m.toolUse.input={}}delete m._inputBuffer}c&&m&&!m.toolUse&&(m.text=c),c=""}if(d.messageStop){a=d.messageStop.stopReason||"end_turn";continue}if(d.metadata?.usage){let m=d.metadata.usage.inputTokens??0,f=d.metadata.usage.outputTokens??0;l={input:m,output:f,total:d.metadata.usage.totalTokens??m+f};break}}let u={role:"assistant",content:i};return this.conversationHistory.push(u),{stopReason:a,assistantMessage:u,usage:l}}async handleStreamStopReason(e,t,n,o){return e==="end_turn"||e==="stop_sequence"?(n.close(),!1):e==="tool_use"?(g.debug("[AmazonBedrockProvider] Tool use detected in streaming - executing tools"),await this.executeStreamTools(t.content,o),!0):(n.close(),!1)}async executeStreamTools(e,t){let n=[],o=0,s=[],i=[];for(let a of e)a.toolUse&&o++;g.debug(`[AmazonBedrockProvider] Found ${o} toolUse blocks in assistant message`);for(let a of e)if(a.toolUse){g.debug(`[AmazonBedrockProvider] Executing tool: ${a.toolUse.name}`),s.push({type:"tool-call",toolCallId:a.toolUse.toolUseId,toolName:a.toolUse.name,args:a.toolUse.input||{}});try{let c=await this.executeSingleTool(a.toolUse.name,a.toolUse.input||{},a.toolUse.toolUseId);g.debug(`[AmazonBedrockProvider] Tool execution successful: ${a.toolUse.name}`),i.push({type:"tool-result",toolCallId:a.toolUse.toolUseId,toolName:a.toolUse.name,result:c}),n.push({toolResult:{toolUseId:a.toolUse.toolUseId,content:[{text:String(c)}],status:"success"}})}catch(c){g.error(`[AmazonBedrockProvider] Tool execution failed: ${a.toolUse.name}`,c);let l=c instanceof Error?c.message:String(c);i.push({type:"tool-result",toolCallId:a.toolUse.toolUseId,toolName:a.toolUse.name,result:{error:l}}),n.push({toolResult:{toolUseId:a.toolUse.toolUseId,content:[{text:`Error executing tool ${a.toolUse.name}: ${l}`}],status:"error"}})}}if(g.debug(`[AmazonBedrockProvider] Created ${n.length} toolResult blocks for ${o} toolUse blocks`),n.length!==o)throw g.error(`[AmazonBedrockProvider] Mismatch: ${n.length} toolResults vs ${o} toolUse blocks`),new Error(`Tool mapping mismatch: ${n.length} toolResults for ${o} toolUse blocks`);if(n.length>0){let a={role:"user",content:n};this.conversationHistory.push(a),g.debug(`[AmazonBedrockProvider] Added ${n.length} tool results to conversation (1:1 mapping validated)`),sh(this.neurolink?.getEventEmitter(),i.map(c=>{let l=c.result&&typeof c.result=="object"&&"error"in c.result;return{toolName:c.toolName,result:c.result,error:l?String(c.result.error):void 0}})),this.handleToolExecutionStorage(s,i,t,new Date).catch(c=>{g.warn("[AmazonBedrockProvider] Failed to store tool executions",{provider:this.providerName,error:c instanceof Error?c.message:String(c)})})}}async checkBedrockHealth(){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await ANe(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{g.debug("[AmazonBedrockProvider] Starting health check...");let i=new o({}),c=(await s.send(i,{abortSignal:e.signal})).modelSummaries||[],l=c.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(g.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(t);let a=i;if(Or(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});let 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}):(g.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${c||"Unknown error"}`,{cause:i}))}finally{clearTimeout(t);try{s.destroy()}catch{}}}formatProviderError(e){let t=e instanceof Error?e.message:String(e);if(t.includes("AccessDeniedException"))return new ut("AWS Bedrock access denied. Check your credentials and permissions.",this.providerName);if(t.includes("ValidationException"))return new Te(`Validation error: ${t}`,this.providerName);let n=e?.name??"",o=e?.code??"";return n==="ThrottlingException"||o==="ThrottlingException"?new Rt(`Bedrock rate limit (throttled): ${e instanceof Error?e.message:String(e)}`,"bedrock"):new Te(`AWS Bedrock error: ${t}`,this.providerName)}async embed(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let{InvokeModelCommand:o}=await Promise.resolve().then(()=>(Ste(),_Ne)),s=JSON.stringify({inputText:e}),i=new o({modelId:n,contentType:"application/json",accept:"application/json",body:s}),a=await we(this.bedrockClient.send(i),6e4,new Error("Bedrock embedding API call timed out")),c=JSON.parse(new TextDecoder().decode(a.body));if(!c.embedding||!Array.isArray(c.embedding))throw new Error("Invalid embedding response from Bedrock");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:c.embedding.length}),c.embedding}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await Promise.all(e.map(s=>this.embed(s,n)));return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}}});var MNe={};K(MNe,{AzureOpenAIProvider:()=>Cte});var Cte,ONe=E(()=>{"use strict";mt();V();Nn();Rn();eh();ys();Wh();Cte=class extends ar{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,n,o){let s=o?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"",a;if(i)try{a=new URL(i.includes("://")?i:`https://${i}`)}catch{a=void 0}let c=a?.hostname??"",l=a?.pathname&&a.pathname!=="/"?a.pathname.replace(/\/+$/,""):"",u=/\.(openai|cognitiveservices)\.azure\.com$/.test(c),d;u?d="/openai":d=/\/openai(?:\/v\d+)?$/.test(l)?l:`${l}/openai`;let m=a?.origin??"",f=o?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=o?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",y=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,x=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||er(nOe()),m||er(oOe()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=d,this.useMaxCompletionTokensOverride=x,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",m$({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){if(e instanceof At)return new ht(`Request timed out: ${e.message}`,"azure");let t=e;if(t?.message&&typeof t.message=="string"&&t.message.includes("401"))return new ut("Invalid Azure OpenAI API key or endpoint.","azure");let n=t?.message&&typeof t.message=="string"?t.message:"Unknown error";return new Te(`Azure OpenAI error: ${n}`,"azure")}getChatCompletionsURL(e){let t=e||this.azureDeployment,n=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${n}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){let n=this.useMaxCompletionTokensOverride??FOe(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function He(r,e,t,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 e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function re(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var hf=E(()=>{});var kte,NNe=E(()=>{kte=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return kte=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))}});function yf(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var pP,ME=E(()=>{pP=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)}});var ct,la,Ua,Fv,mP,fP,gP,hP,yP,xP,vP,bP,TP,sl=E(()=>{ME();ct=class extends Error{},la=class r extends ct{constructor(e,t,n,o,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=t,this.type=s??null}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new Fv({message:n,cause:pP(t)});let s=t,i=s?.error?.type;return e===400?new fP(e,s,n,o,i):e===401?new gP(e,s,n,o,i):e===403?new hP(e,s,n,o,i):e===404?new yP(e,s,n,o,i):e===409?new xP(e,s,n,o,i):e===422?new vP(e,s,n,o,i):e===429?new bP(e,s,n,o,i):e>=500?new TP(e,s,n,o,i):new r(e,s,n,o,i)}},Ua=class extends la{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Fv=class extends la{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},mP=class extends Fv{constructor({message:e}={}){super({message:e??"Request timed out."})}},fP=class extends la{},gP=class extends la{},hP=class extends la{},yP=class extends la{},xP=class extends la{},vP=class extends la{},bP=class extends la{},TP=class extends la{}});function qG(r){return typeof r!="object"?{}:r??{}}function Ite(r){if(!r)return!0;for(let e in r)return!1;return!0}function LNe(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var ler,DNe,Rte,Ate,UNe,WG,$v=E(()=>{sl();ler=/^[a-z][a-z0-9+.-]*:/i,DNe=r=>ler.test(r),Rte=r=>(Rte=Array.isArray,Rte(r)),Ate=Rte;UNe=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ct(`${r} must be an integer`);if(e<0)throw new ct(`${r} must be a positive integer`);return e},WG=r=>{try{return JSON.parse(r)}catch{return}}});var FNe,$Ne=E(()=>{FNe=r=>new Promise(e=>setTimeout(e,r))});var Kh,Pte=E(()=>{Kh="0.91.1"});function uer(){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 per(){if(typeof navigator>"u"||!navigator)return null;let r=[{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(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,i=n[3]||0;return{browser:e,version:`${o}.${s}.${i}`}}}return null}var jNe,der,BNe,zNe,GNe,VNe,Mte=E(()=>{Pte();jNe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";der=()=>{let r=uer();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":zNe(Deno.build.os),"X-Stainless-Arch":BNe(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":Kh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":zNe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":BNe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=per();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Kh,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};BNe=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",zNe=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),VNe=()=>GNe??(GNe=der())});function HNe(){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 Ote(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function KG(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Ote({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function SP(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qNe(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var OE=E(()=>{});var WNe,KNe=E(()=>{WNe=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function JNe(r){return Object.entries(r).filter(([e,t])=>typeof t<"u").map(([e,t])=>{if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new ct(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var XNe=E(()=>{sl()});function QNe(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function wP(r){let e;return(ZNe??(e=new globalThis.TextEncoder,ZNe=e.encode.bind(e)))(r)}function Nte(r){let e;return(YNe??(e=new globalThis.TextDecoder,YNe=e.decode.bind(e)))(r)}var ZNe,YNe,Dte=E(()=>{});function ger(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function eDe(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Kl,Jl,xf,Lte=E(()=>{hf();Dte();xf=class{constructor(){Kl.set(this,void 0),Jl.set(this,void 0),He(this,Kl,new Uint8Array,"f"),He(this,Jl,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?wP(e):e;He(this,Kl,QNe([re(this,Kl,"f"),t]),"f");let n=[],o;for(;(o=ger(re(this,Kl,"f"),re(this,Jl,"f")))!=null;){if(o.carriage&&re(this,Jl,"f")==null){He(this,Jl,o.index,"f");continue}if(re(this,Jl,"f")!=null&&(o.index!==re(this,Jl,"f")+1||o.carriage)){n.push(Nte(re(this,Kl,"f").subarray(0,re(this,Jl,"f")-1))),He(this,Kl,re(this,Kl,"f").subarray(re(this,Jl,"f")),"f"),He(this,Jl,null,"f");continue}let s=re(this,Jl,"f")!==null?o.preceding-1:o.preceding,i=Nte(re(this,Kl,"f").subarray(0,s));n.push(i),He(this,Kl,re(this,Kl,"f").subarray(o.index),"f"),He(this,Jl,null,"f")}return n}flush(){return re(this,Kl,"f").length?this.decode(`
|
|
1160
1160
|
`):[]}};Kl=new WeakMap,Jl=new WeakMap;xf.NEWLINE_CHARS=new Set([`
|
|
1161
1161
|
`,"\r"]);xf.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function EP(){}function JG(r,e,t){return!e||XG[r]>XG[t]?EP:e[r].bind(e)}function Ai(r){let e=r.logger,t=r.logLevel??"off";if(!e)return her;let n=tDe.get(e);if(n&&n[0]===t)return n[1];let o={error:JG("error",e,t),warn:JG("warn",e,t),info:JG("info",e,t),debug:JG("debug",e,t)};return tDe.set(e,[t,o]),o}var XG,Ute,her,tDe,vf,ZG=E(()=>{$v();XG={off:0,error:200,warn:300,info:400,debug:500},Ute=(r,e,t)=>{if(r){if(LNe(XG,r))return r;Ai(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(XG))}`)}};her={error:EP,warn:EP,info:EP,debug:EP},tDe=new WeakMap;vf=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r)});async function*yer(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ct("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 ct("Attempted to iterate over a response with no body");let t=new Fte,n=new xf,o=SP(r.body);for await(let s of xer(o))for(let i of n.decode(s)){let a=t.decode(i);a&&(yield a)}for(let s of n.flush()){let i=t.decode(s);i&&(yield i)}}async function*xer(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?wP(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=eDe(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}function ver(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var _P,Vp,Fte,$te=E(()=>{hf();sl();OE();Lte();OE();ME();$v();Dte();ZG();sl();Vp=class r{constructor(e,t,n){this.iterator=e,_P.set(this,void 0),this.controller=t,He(this,_P,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?Ai(n):console;async function*i(){if(o)throw new ct("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let c of yer(e,t)){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==="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==="span.model_request_start"||c.event==="span.model_request_end")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"){let l=WG(c.data)??c.data,u=l?.error?.type;throw new la(void 0,l,void 0,e.headers,u)}}a=!0}catch(c){if(yf(c))return;throw c}finally{a||t.abort()}}return new r(i,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let a=new xf,c=SP(e);for await(let l of c)for(let u of a.decode(l))yield u;for(let l of a.flush())yield l}async function*i(){if(o)throw new ct("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let c of s())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(yf(c))return;throw c}finally{a||t.abort()}}return new r(i,t,n)}[(_P=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let i=n.next();e.push(i),t.push(i)}return s.shift()}});return[new r(()=>o(e),this.controller,re(this,_P,"f")),new r(()=>o(t),this.controller,re(this,_P,"f"))]}toReadableStream(){let e=this,t;return Ote({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let i=wP(JSON.stringify(o)+`
|
|
1162
1162
|
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};Fte=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;let s={event:this.event,data:this.data.join(`
|