@juspay/neurolink 9.68.4 → 9.68.6
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 +12 -0
- package/dist/browser/neurolink.min.js +1 -1
- package/dist/lib/providers/openaiChatCompletionsBase.d.ts +18 -0
- package/dist/lib/providers/openaiChatCompletionsBase.js +37 -2
- package/dist/providers/openaiChatCompletionsBase.d.ts +18 -0
- package/dist/providers/openaiChatCompletionsBase.js +37 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
+
## [9.68.6](https://github.com/juspay/neurolink/compare/v9.68.5...v9.68.6) (2026-06-06)
|
|
2
|
+
|
|
3
|
+
### Bug Fixes
|
|
4
|
+
|
|
5
|
+
- **(providers):** add default config methods to OpenAI-compat base ([cf99a1e](https://github.com/juspay/neurolink/commit/cf99a1e545b19211a9bfdc007a0577a876d14ebb))
|
|
6
|
+
|
|
7
|
+
## [9.68.5](https://github.com/juspay/neurolink/compare/v9.68.4...v9.68.5) (2026-06-06)
|
|
8
|
+
|
|
9
|
+
### Bug Fixes
|
|
10
|
+
|
|
11
|
+
- **(providers):** retry model auto-discovery after a failed probe ([f7242d3](https://github.com/juspay/neurolink/commit/f7242d31368d16c3e13aa4898ab1a86023e1ea30))
|
|
12
|
+
|
|
1
13
|
## [9.68.4](https://github.com/juspay/neurolink/compare/v9.68.3...v9.68.4) (2026-06-05)
|
|
2
14
|
|
|
3
15
|
## [9.68.3](https://github.com/juspay/neurolink/compare/v9.68.2...v9.68.3) (2026-06-04)
|
|
@@ -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 or(r,e){return process.env[r]||e}function ZNe(){let r=o7t(),e=s7t(),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 XNe(){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 YNe(){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 QNe(){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 eDe(){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 tDe(){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 rDe(){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 nDe(){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 oDe(){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 sDe(){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 iDe(){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 aDe(){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 cDe(){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 lDe(){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 uDe(){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 dDe(){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 pDe(){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 mDe(){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 fDe(){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 gDe(){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 hDe(){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 yDe(){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 o7t(){return process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase()==="oauth"?"oauth":"api_key"}function s7t(){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 Sb,yu,FG,Jn=_(()=>{"use strict";Sb={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}$/},yu={OPENAI_MIN:48,ANTHROPIC_MIN:95,HUGGINGFACE_EXACT:37,AZURE_MIN:32,MISTRAL_EXACT:32,AWS_ACCESS_KEY:20,GOOGLE_AI_EXACT:39},FG={MIN_LENGTH:6,MAX_LENGTH:30,PATTERN:/^[a-z][a-z0-9-]{4,28}[a-z0-9]$/}});function Dn(r,e,t){return!t||!e||Object.keys(e).length===0?"none":r.toolChoice??"auto"}var Lc=_(()=>{"use strict"});async function _a(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 Xf=_(()=>{"use strict"});var mIn,fIn,gIn,hIn,Ore,i7t,vDe,$G,yIn,vIn,bIn,TIn,xDe=_(()=>{mIn=globalThis.crypto,fIn=globalThis.ReadableStream||class{},gIn=globalThis.URL,hIn=globalThis.URLSearchParams,Ore=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Ore.custom=Symbol.for("nodejs.util.inspect.custom");Ore.colors={};Ore.styles={};i7t=globalThis.TextDecoder,vDe=globalThis.TextEncoder,$G=(r,e)=>e?.(null,"127.0.0.1",4),yIn=globalThis.performance||{now:()=>Date.now()},vIn=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 vDe().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 vDe().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 i7t().decode(this)}},bIn=globalThis.clearTimeout,TIn=globalThis.clearInterval});var _In,EIn,CIn,kIn,Mre,a7t,bDe,RIn,AIn,TDe,PIn,OIn,SDe=_(()=>{_In=globalThis.crypto,EIn=globalThis.ReadableStream||class{},CIn=globalThis.URL,kIn=globalThis.URLSearchParams,Mre=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Mre.custom=Symbol.for("nodejs.util.inspect.custom");Mre.colors={};Mre.styles={};a7t=globalThis.TextDecoder,bDe=globalThis.TextEncoder,RIn=globalThis.performance||{now:()=>Date.now()},AIn=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 bDe().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 bDe().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 a7t().decode(this)}},TDe=()=>0,PIn=globalThis.clearTimeout,OIn=globalThis.clearInterval});function u7t(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 BG(r){if(r.length===0)return null;let e=r.split(".");if(e.length===4){let t=e.map(u7t);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 EDe(r){if(TDe(r)!==6)return null;let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i),t;if(e){let n=BG(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 CDe(r){let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(e)return BG(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 wDe(r){let[e,t,n,o]=r.split(".").map(s=>parseInt(s,10));return(e<<24|t<<16|n<<8|o)>>>0}function rO(r){let e=wDe(r);for(let[t,n]of c7t){let o=wDe(t),s=n===0?0:4294967295<<32-n>>>0;if((e&s)===(o&s))return!0}return!1}function kDe(r){return l7t.some(e=>e.length===39?r===e:r.startsWith(e))}function RDe(r){return r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r}function _De(r){let e=BG(r);if(e)return rO(e)?`IPv4 ${r} \u2192 ${e} is in a blocked range`:null;if(r.includes(":")){let t=CDe(r);if(t)return rO(t)?`IPv4-mapped IPv6 ${r} \u2192 ${t} is in a blocked range`:null;let n=EDe(r);return n?kDe(n)?`IPv6 ${r} is in a blocked range`:null:`IPv6 ${r} could not be parsed`}return"not-an-ip"}async function El(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=RDe(e.hostname).toLowerCase(),n=_De(t);if(n===null)return;if(n!=="not-an-ip")throw new Error(`URL "${r}" rejected: ${n}`);let[o,s]=await Promise.allSettled([$G(t,{family:4,all:!0}),$G(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(rO(l))throw new Error(`URL "${r}" rejected: hostname ${t} resolves to ${l} (IPv4 in blocked range)`);for(let l of a){let u=_De(l.toLowerCase());if(u&&u!=="not-an-ip")throw new Error(`URL "${r}" rejected: hostname ${t} resolves to ${l} (IPv6 ${u})`)}}async function ADe(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=RDe(e.hostname).toLowerCase(),n=BG(t);if(n){if(rO(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=CDe(t);if(s){if(rO(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=EDe(t);if(!i)throw new Error(`URL "${r}" rejected: IPv6 ${t} could not be parsed`);if(kDe(i))throw new Error(`URL "${r}" rejected: IPv6 ${t} is in a blocked range`);return{url:r,ip:t,family:6}}await El(r);let o=await $G(t);return{url:r,ip:o.address,family:o.family}}var c7t,l7t,Ly=_(()=>{"use strict";xDe();SDe();c7t=[["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]],l7t=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]});var PDe={};Z(PDe,{OpenAIProvider:()=>GG,default:()=>p7t});function zG(r){let e=r;return e.inputSchema??e.parameters}var jG,IDe,d7t,GG,p7t,ODe=_(()=>{"use strict";gp();br();Kn();on();hu();wn();gt();H();aE();Yd();Jn();qd();Vn();Lc();_i();Xf();Ly();SB();Yu();bi();Es();jG=()=>nr(XNe()),IDe=()=>or("OPENAI_MODEL","gpt-4o"),d7t=ct.getTracer("neurolink.provider.openai"),GG=class extends Ct{model;credentials;constructor(e,t,n,o){super(e||IDe(),"openai",t),this.credentials=o;let s=oo({apiKey:o?.apiKey??jG(),...o?.baseURL?{baseURL:o.baseURL}:{},fetch:Ve()});this.model=s(this.modelName),g.debug("OpenAIProvider constructor called",{model:this.modelName,provider:this.providerName,supportsTools:this.supportsTools(),className:this.constructor.name})}supportsTools(){return!0}getProviderName(){return"openai"}getDefaultModel(){return IDe()}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}getAISDKModel(){return this.model}validateAndFilterToolsForOpenAI(e){let t={};for(let[n,o]of Object.entries(e))try{if(o&&typeof o=="object")if(o.description&&typeof o.description=="string"){let s={...o},i=zG(o);i&&wf(i)&&(g.debug(`OpenAI: Tool ${n} has Zod schema - AI SDK will handle conversion`),this.validateZodSchema(n,i)),this.isValidToolStructure(s)?t[n]=s:g.warn(`OpenAI: Filtering out tool with invalid structure: ${n}`,{parametersType:typeof zG(s),hasDescription:!!s.description,hasExecute:!!s.execute})}else g.warn(`OpenAI: Filtering out tool without description: ${n}`);else g.warn(`OpenAI: Filtering out invalid tool: ${n}`)}catch(s){g.warn(`OpenAI: Error validating tool ${n}:`,s)}return t}validateZodSchema(e,t){try{let n=t;n._def&&n._def.typeName?g.debug(`OpenAI: Zod schema for ${e} appears valid`,{typeName:n._def.typeName}):g.warn(`OpenAI: Zod schema for ${e} missing typeName - may cause issues`)}catch(n){g.warn(`OpenAI: Zod schema validation failed for ${e}:`,n)}}endStreamSpanWithError(e,t){e.setStatus({code:me.ERROR,message:t instanceof Error?t.message:String(t)}),t instanceof Error&&e.recordException(t),e.end()}isValidToolStructure(e){if(!e||typeof e!="object")return!1;let t=e;if(!t.description||typeof t.description!="string"||!t.execute||typeof t.execute!="function")return!1;let n="inputSchema"in t?t.inputSchema:"parameters"in t?t.parameters:void 0;return this.isValidToolParameters(n)}isValidToolParameters(e){if(!e||wf(e))return!0;if(typeof e!="object"||e===null)return!1;let t=e;return t.type&&t.type!=="object"?!1:t.type==="object"&&!t.properties?(g.warn("Tool parameter schema missing properties field:",t),!1):!(t.properties&&typeof t.properties!="object"||t.required&&!Array.isArray(t.required))}formatProviderError(e){if(e instanceof At)return new xt(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 pt(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"?new Pt("OpenAI rate limit exceeded. Please try again later.",this.providerName):n.includes("model_not_found")?new Ot(`Model not found: ${this.modelName}`,this.providerName):new Ee(`OpenAI error: ${n}`,this.providerName)}async executeStream(e,t){this.validateStreamOptions(e);let n=Date.now(),o=this.getTimeout(e),s=Er(o,this.providerName,"stream");try{let i=!e.disableTools&&this.supportsTools(),a=i?e.tools||await this.getAllTools():{},c=this.validateAndFilterToolsForOpenAI(a),l=parseInt(process.env.OPENAI_MAX_TOOLS||"150",10);if(Object.keys(c).length>l){g.warn(`OpenAI: Too many tools (${Object.keys(c).length}), limiting to ${l} tools`);let w=Object.entries(c);c=Object.fromEntries(w.slice(0,l))}let u=Object.values(a).filter(w=>{if(!w||typeof w!="object")return!1;let E=zG(w);return E!=null&&wf(E)}).length;g.info("OpenAI streaming tools",{shouldUseTools:i,allToolsCount:Object.keys(a).length,filteredToolsCount:Object.keys(c).length,zodToolsCount:u,toolNames:Object.keys(c),filteredOutTools:Object.keys(a).filter(w=>!c[w])});let d=await this.buildMessagesForStream(e),m=Dn(e,c,i);m!==null&&typeof m=="object"&&"toolName"in m&&typeof m.toolName=="string"&&!c[m.toolName]&&(g.warn(`OpenAI: toolChoice references tool "${m.toolName}" which was removed during filtering; falling back to "auto"`),m="auto"),g.debug("OpenAI: streamText request parameters:",{modelName:this.modelName,messagesCount:d.length,temperature:e.temperature,maxTokens:e.maxTokens,toolsCount:Object.keys(c).length,toolChoice:m,maxSteps:e.maxSteps||Lt,firstToolExample:Object.keys(c).length>0?{name:Object.keys(c)[0],description:c[Object.keys(c)[0]]?.description,parametersType:typeof zG(c[Object.keys(c)[0]])}:"no-tools"});let f=await this.getAISDKModelWithMiddleware(e),h=d7t.startSpan("neurolink.provider.streamText",{kind:xr.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":Kh(f)||this.modelName||"unknown"}}),y,v;try{v=Sn({model:f,messages:d,temperature:e.temperature,maxOutputTokens:e.maxTokens,maxRetries:0,tools:c,stopWhen:nn(e.maxSteps||Lt),toolChoice:m,abortSignal:qr(e.abortSignal,s?.controller.signal),experimental_repairToolCall:this.getToolCallRepairFn(e),experimental_telemetry:this.telemetryHandler.getTelemetryConfig(e),onError:w=>{y=w.error,g.error("OpenAI: Stream error",{error:w.error instanceof Error?w.error.message:String(w.error)})},onStepFinish:({toolCalls:w,toolResults:E})=>{g.info("Tool execution completed",{toolResults:E,toolCalls:w}),jr(this.neurolink?.getEventEmitter(),E),this.handleToolExecutionStorage(w,E,e,new Date).catch(C=>{g.warn("[OpenAIProvider] Failed to store tool executions",{provider:this.providerName,error:C instanceof Error?C.message:String(C)})})}})}catch(w){throw this.endStreamSpanWithError(h,w),w}Promise.resolve(v.usage).then(w=>{h.setAttribute("gen_ai.usage.input_tokens",w.inputTokens||0),h.setAttribute("gen_ai.usage.output_tokens",w.outputTokens||0);let E=Vo(this.providerName,this.modelName,{input:w.inputTokens||0,output:w.outputTokens||0,total:(w.inputTokens||0)+(w.outputTokens||0)});E&&E>0&&h.setAttribute("neurolink.cost",E)}).catch(()=>{}),Promise.resolve(v.finishReason).then(w=>{h.setAttribute("gen_ai.response.finish_reason",w||"unknown")}).catch(()=>{}),Promise.resolve(v.text).then(()=>{h.end()}).catch(w=>{this.endStreamSpanWithError(h,w)}),s?.cleanup(),g.debug("OpenAI: streamText result structure:",{resultKeys:Object.keys(v),hasTextStream:!!v.textStream,hasToolCalls:!!v.toolCalls,hasToolResults:!!v.toolResults,resultType:typeof v});let b=this.createOpenAITransformedStream(v,i,c,()=>y),T=ho.createAnalytics(this.providerName,this.modelName,v,Date.now()-n,{requestId:`openai-stream-${Date.now()}`,streamingMode:!0});return{stream:b,provider:this.providerName,model:this.modelName,analytics:T,metadata:{startTime:n,streamId:`openai-${Date.now()}`}}}catch(i){throw s?.cleanup(),this.handleProviderError(i)}}async*createOpenAITransformedStream(e,t,n,o){try{g.debug("OpenAI: Starting stream transformation",{hasTextStream:!!e.textStream,hasFullStream:!!e.fullStream,resultKeys:Object.keys(e),toolsEnabled:t,toolsCount:Object.keys(n).length});let s=0,i=0,a=e.fullStream||e.textStream;if(!a){g.error("OpenAI: No stream available in result",{resultKeys:Object.keys(e)});return}g.debug("OpenAI: Stream source selected:",{usingFullStream:!!e.fullStream,usingTextStream:!!e.textStream&&!e.fullStream,streamSourceType:e.fullStream?"fullStream":"textStream"});for await(let c of a){s++,g.debug(`OpenAI: Processing chunk ${s}:`,{chunkType:typeof c,chunkValue:typeof c=="string"?c.substring(0,50):"not-string",chunkKeys:c&&typeof c=="object"?Object.keys(c):"not-object",hasText:c&&typeof c=="object"&&"text"in c,hasTextDelta:c&&typeof c=="object"&&"textDelta"in c,hasType:c&&typeof c=="object"&&"type"in c,chunkTypeValue:c&&typeof c=="object"&&"type"in c?c.type:"no-type"});let l=this.extractOpenAIChunkContent(c);l&&(i++,g.debug(`OpenAI: Yielding content ${i}:`,{content:l.substring(0,50),length:l.length}),yield{content:l})}if(g.debug("OpenAI: Stream transformation completed",{totalChunks:s,contentYielded:i,success:i>0}),i===0){g.warn(`OpenAI: No content was yielded from stream despite processing ${s} chunks`);let c=await Cy(e,o?.());c&&(g.warn("OpenAI: Stream produced no output (NoOutputGeneratedError) \u2014 caught from finishReason rejection"),Ya(c.sentinel),yield c.sentinel)}}catch(s){if(_s.isInstance(s)){g.warn("OpenAI: Stream produced no output (NoOutputGeneratedError) \u2014 caught from textStream");let i=await gu(s,e,o?.());Ya(i),yield i;return}throw g.error("OpenAI: Stream transformation error:",s),s}}extractOpenAIChunkContent(e){if(e&&typeof e=="object"){if(process.env.NEUROLINK_DEBUG==="true"&&g.debug("OpenAI: Full chunk structure:",{chunkKeys:Object.keys(e),fullChunk:JSON.stringify(e).substring(0,500)}),"type"in e&&e.type==="error"){let t=e;g.error("OpenAI: Error chunk received:",{errorType:t.type,errorDetails:t.error,fullChunk:JSON.stringify(e)});let n=t.error&&typeof t.error=="object"&&"message"in t.error?String(t.error.message):"OpenAI API error when tools are enabled";throw new Error(`OpenAI streaming error with tools: ${n}. Try disabling tools with --disableTools`)}if("type"in e&&e.type==="text-delta"&&"textDelta"in e){let t=e.textDelta;return g.debug("OpenAI: Found text-delta:",{textDelta:t}),t}if("text"in e){let t=e.text;return g.debug("OpenAI: Found direct text:",{text:t}),t}return process.env.NEUROLINK_DEBUG==="true"&&g.debug("OpenAI: Unhandled object chunk:",{chunkKeys:Object.keys(e),chunkType:"type"in e?String(e.type):"no-type",fullChunk:JSON.stringify(e).substring(0,500)}),null}return typeof e=="string"?(g.debug("OpenAI: Found string chunk:",{content:e}),e):(g.warn("OpenAI: Unhandled chunk type:",{type:typeof e,value:String(e).substring(0,100)}),null)}async embed(e,t){let n=t||"text-embedding-3-small";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let s=oo({apiKey:this.credentials?.apiKey??jG(),...this.credentials?.baseURL?{baseURL:this.credentials.baseURL}:{},fetch:Ve()}).textEmbeddingModel(n),i=await LF({model:s,value:e});return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:i.embedding.length}),i.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||"text-embedding-3-small";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let s=oo({apiKey:this.credentials?.apiKey??jG(),...this.credentials?.baseURL?{baseURL:this.credentials.baseURL}:{},fetch:Ve()}).textEmbeddingModel(n),i=await UF({model:s,values:e});return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:i.embeddings.length,embeddingDimension:i.embeddings[0]?.length}),i.embeddings}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 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=this.credentials?.apiKey??jG(),i=(this.credentials?.baseURL??process.env.OPENAI_BASE_URL??"https://api.openai.com/v1").replace(/\/$/,""),a=e,c=a.size??this.aspectRatioToOpenAISize(a.aspectRatio,o),l=a.numberOfImages??1,u;o==="gpt-image-1"||o.startsWith("dall-e-3")?u=1:o.startsWith("dall-e-2")?u=Math.min(Math.max(l,1),10):u=1;let m={model:o,prompt:n,n:u,size:c};o==="gpt-image-1"?a.quality&&(m.quality=a.quality):o.startsWith("dall-e-3")?(m.response_format="b64_json",a.quality&&(m.quality=a.quality),a.style&&(m.style=a.style)):m.response_format="b64_json";let f=12e4,h=new AbortController,y=setTimeout(()=>h.abort(),f),v;try{v=await Ve()(`${i}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify(m),signal:h.signal})}catch(C){throw C instanceof Error&&C.name==="AbortError"?new Error(`OpenAI image generation timed out after ${f/1e3}s`,{cause:C}):C}finally{clearTimeout(y)}if(!v.ok){let C=await v.text();throw new Error(`OpenAI image generation failed: ${v.status} \u2014 ${C}`)}let T=(await v.json()).data?.[0];if(!T)throw new Error("OpenAI image generation returned no images");let w=T.b64_json;if(!w&&T.url){await El(T.url);let C=Ve(),k=new AbortController,I=setTimeout(()=>k.abort(),6e4),R;try{R=await C(T.url,{signal:k.signal})}catch(P){throw P instanceof Error&&P.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:P}):P}finally{clearTimeout(I)}if(!R.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${T.url} (${R.status})`);w=(await _a(R,26214400,"OpenAI image fallback")).toString("base64")}if(!w)throw new Error("OpenAI image generation returned neither b64_json nor a URL");let E=Date.now()-t;return g.info(`[OpenAIProvider] Generated image (${w.length} base64 chars) in ${E}ms \u2014 model ${o}`),{content:T.revised_prompt??n,provider:this.providerName,model:o,usage:{input:0,output:0,total:0},imageOutput:{base64:w}}}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"}},p7t=GG});function v7t(r){var e;let t=r?.anthropic;return(e=t?.cacheControl)!=null?e:t?.cache_control}async function z7t({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 Ure;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,v=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}:{},...v!=null?{defer_loading:v}:{},...b!=null?{allowed_callers:b}:{},...m.inputExamples!=null?{input_examples:m.inputExamples.map(T=>T.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 fr({value:m.args,schema:x7t});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 fr({value:m.args,schema:U7t});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 fr({value:m.args,schema:O7t});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 fr({value:m.args,schema:R7t});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 fr({value:m.args,schema:w7t});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 cr({functionality:`tool choice type: ${m}`})}}}function UDe({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 eQt(r){if(typeof r=="string")return new TextDecoder().decode(el(r));if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw r instanceof URL?new cr({functionality:"URL-based text documents are not supported for citations"}):new cr({functionality:`unsupported data type for text documents: ${typeof r}`})}function Nre(r){return r instanceof URL||tQt(r)}function tQt(r){return typeof r=="string"&&/^https?:\/\//i.test(r)}function Dre(r){return r instanceof URL?r.toString():r}async function rQt({prompt:r,sendReasoning:e,warnings:t,cacheControlValidator:n,toolNameMapping:o}){var s,i,a,c,l,u,d,m,f,h,y,v,b,T,w,E,C,k,I;let R=new Set,A=nQt(r),P=n||new Ure,D,$=[];async function O(N){var U,L;let z=await Qn({provider:"anthropic",providerOptions:N,schema:NDe});return(L=(U=z?.citations)==null?void 0:U.enabled)!=null?L:!1}async function F(N){let U=await Qn({provider:"anthropic",providerOptions:N,schema:NDe});return{title:U?.title,context:U?.context}}for(let N=0;N<A.length;N++){let U=A[N],L=N===A.length-1,z=U.type;switch(z){case"system":{if(D!=null)throw new cr({functionality:"Multiple system messages that are separated by user/assistant messages"});D=U.messages.map(({content:B,providerOptions:j})=>({type:"text",text:B,cache_control:P.getCacheControl(j,{type:"system message",canCache:!0})}));break}case"user":{let B=[];for(let j of U.messages){let{role:q,content:K}=j;switch(q){case"user":{for(let ge=0;ge<K.length;ge++){let Y=K[ge],he=ge===K.length-1,V=(s=P.getCacheControl(Y.providerOptions,{type:"user message part",canCache:!0}))!=null?s:he?P.getCacheControl(j.providerOptions,{type:"user message",canCache:!0}):void 0;switch(Y.type){case"text":{B.push({type:"text",text:Y.text,cache_control:V});break}case"file":{if(Y.mediaType.startsWith("image/"))B.push({type:"image",source:Nre(Y.data)?{type:"url",url:Dre(Y.data)}:{type:"base64",media_type:Y.mediaType==="image/*"?"image/jpeg":Y.mediaType,data:Xl(Y.data)},cache_control:V});else if(Y.mediaType==="application/pdf"){R.add("pdfs-2024-09-25");let ve=await O(Y.providerOptions),Ie=await F(Y.providerOptions);B.push({type:"document",source:Nre(Y.data)?{type:"url",url:Dre(Y.data)}:{type:"base64",media_type:"application/pdf",data:Xl(Y.data)},title:(i=Ie.title)!=null?i:Y.filename,...Ie.context&&{context:Ie.context},...ve&&{citations:{enabled:!0}},cache_control:V})}else if(Y.mediaType==="text/plain"){let ve=await O(Y.providerOptions),Ie=await F(Y.providerOptions);B.push({type:"document",source:Nre(Y.data)?{type:"url",url:Dre(Y.data)}:{type:"text",media_type:"text/plain",data:eQt(Y.data)},title:(a=Ie.title)!=null?a:Y.filename,...Ie.context&&{context:Ie.context},...ve&&{citations:{enabled:!0}},cache_control:V})}else throw new cr({functionality:`media type: ${Y.mediaType}`});break}}}break}case"tool":{for(let ge=0;ge<K.length;ge++){let Y=K[ge];if(Y.type==="tool-approval-response")continue;let he=ge===K.length-1,V=(c=P.getCacheControl(Y.providerOptions,{type:"tool result part",canCache:!0}))!=null?c:he?P.getCacheControl(j.providerOptions,{type:"tool result message",canCache:!0}):void 0,ve=Y.output,Ie;switch(ve.type){case"content":Ie=ve.value.map(xe=>{var te;switch(xe.type){case"text":return{type:"text",text:xe.text};case"image-data":return{type:"image",source:{type:"base64",media_type:xe.mediaType,data:xe.data}};case"image-url":return{type:"image",source:{type:"url",url:xe.url}};case"file-url":return{type:"document",source:{type:"url",url:xe.url}};case"file-data":{if(xe.mediaType==="application/pdf")return R.add("pdfs-2024-09-25"),{type:"document",source:{type:"base64",media_type:xe.mediaType,data:xe.data}};t.push({type:"other",message:`unsupported tool content part type: ${xe.type} with media type: ${xe.mediaType}`});return}case"custom":{let oe=(te=xe.providerOptions)==null?void 0:te.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: ${xe.type}`});return}}}).filter(uA);break;case"text":case"error-text":Ie=ve.value;break;case"execution-denied":Ie=(l=ve.reason)!=null?l:"Tool execution denied.";break;default:Ie=JSON.stringify(ve.value);break}B.push({type:"tool_result",tool_use_id:Y.toolCallId,content:Ie,is_error:ve.type==="error-text"||ve.type==="error-json"?!0:void 0,cache_control:V})}break}default:{let ge=q;throw new Error(`Unsupported role: ${ge}`)}}}$.push({role:"user",content:B});break}case"assistant":{let B=[],j=new Set;for(let q=0;q<U.messages.length;q++){let K=U.messages[q],ge=q===U.messages.length-1,{content:Y}=K;for(let he=0;he<Y.length;he++){let V=Y[he],ve=he===Y.length-1,Ie=(u=P.getCacheControl(V.providerOptions,{type:"assistant message part",canCache:!0}))!=null?u:ve?P.getCacheControl(K.providerOptions,{type:"assistant message",canCache:!0}):void 0;switch(V.type){case"text":{let xe=(d=V.providerOptions)==null?void 0:d.anthropic;xe?.type==="compaction"?B.push({type:"compaction",content:V.text,cache_control:Ie}):B.push({type:"text",text:L&&ge&&ve?V.text.trim():V.text,cache_control:Ie});break}case"reasoning":{if(e){let xe=await Qn({provider:"anthropic",providerOptions:V.providerOptions,schema:y7t});xe!=null?xe.signature!=null?(P.getCacheControl(V.providerOptions,{type:"thinking block",canCache:!1}),B.push({type:"thinking",thinking:V.text,signature:xe.signature})):xe.redactedData!=null?(P.getCacheControl(V.providerOptions,{type:"redacted thinking block",canCache:!1}),B.push({type:"redacted_thinking",data:xe.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(V.providerExecuted){let oe=o.toProviderToolName(V.toolName);if(((f=(m=V.providerOptions)==null?void 0:m.anthropic)==null?void 0:f.type)==="mcp-tool-use"){j.add(V.toolCallId);let re=(y=(h=V.providerOptions)==null?void 0:h.anthropic)==null?void 0:y.serverName;if(re==null||typeof re!="string"){t.push({type:"other",message:"mcp tool use server name is required and must be a string"});break}B.push({type:"mcp_tool_use",id:V.toolCallId,name:V.toolName,input:V.input,server_name:re,cache_control:Ie})}else if(oe==="code_execution"&&V.input!=null&&typeof V.input=="object"&&"type"in V.input&&typeof V.input.type=="string"&&(V.input.type==="bash_code_execution"||V.input.type==="text_editor_code_execution"))B.push({type:"server_tool_use",id:V.toolCallId,name:V.input.type,input:V.input,cache_control:Ie});else if(oe==="code_execution"&&V.input!=null&&typeof V.input=="object"&&"type"in V.input&&V.input.type==="programmatic-tool-call"){let{type:re,...Xe}=V.input;B.push({type:"server_tool_use",id:V.toolCallId,name:"code_execution",input:Xe,cache_control:Ie})}else oe==="code_execution"||oe==="web_fetch"||oe==="web_search"?B.push({type:"server_tool_use",id:V.toolCallId,name:oe,input:V.input,cache_control:Ie}):oe==="tool_search_tool_regex"||oe==="tool_search_tool_bm25"?B.push({type:"server_tool_use",id:V.toolCallId,name:oe,input:V.input,cache_control:Ie}):t.push({type:"other",message:`provider executed tool call for tool ${V.toolName} is not supported`});break}let xe=(v=V.providerOptions)==null?void 0:v.anthropic,te=xe?.caller?(xe.caller.type==="code_execution_20250825"||xe.caller.type==="code_execution_20260120")&&xe.caller.toolId?{type:xe.caller.type,tool_id:xe.caller.toolId}:xe.caller.type==="direct"?{type:"direct"}:void 0:void 0;B.push({type:"tool_use",id:V.toolCallId,name:V.toolName,input:V.input,...te&&{caller:te},cache_control:Ie});break}case"tool-result":{let xe=o.toProviderToolName(V.toolName);if(j.has(V.toolCallId)){let te=V.output;if(te.type!=="json"&&te.type!=="error-json"){t.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${V.toolName} is not supported`});break}B.push({type:"mcp_tool_result",tool_use_id:V.toolCallId,is_error:te.type==="error-json",content:te.value,cache_control:Ie})}else if(xe==="code_execution"){let te=V.output;if(te.type==="error-text"||te.type==="error-json"){let oe={};try{typeof te.value=="string"?oe=JSON.parse(te.value):typeof te.value=="object"&&te.value!==null&&(oe=te.value)}catch{}oe.type==="code_execution_tool_result_error"?B.push({type:"code_execution_tool_result",tool_use_id:V.toolCallId,content:{type:"code_execution_tool_result_error",error_code:(b=oe.errorCode)!=null?b:"unknown"},cache_control:Ie}):B.push({type:"bash_code_execution_tool_result",tool_use_id:V.toolCallId,cache_control:Ie,content:{type:"bash_code_execution_tool_result_error",error_code:(T=oe.errorCode)!=null?T:"unknown"}});break}if(te.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${V.toolName} is not supported`});break}if(te.value==null||typeof te.value!="object"||!("type"in te.value)||typeof te.value.type!="string"){t.push({type:"other",message:`provider executed tool result output value is not a valid code execution result for tool ${V.toolName}`});break}if(te.value.type==="code_execution_result"){let oe=await fr({value:te.value,schema:GDe});B.push({type:"code_execution_tool_result",tool_use_id:V.toolCallId,content:{type:oe.type,stdout:oe.stdout,stderr:oe.stderr,return_code:oe.return_code,content:(w=oe.content)!=null?w:[]},cache_control:Ie})}else if(te.value.type==="encrypted_code_execution_result"){let oe=await fr({value:te.value,schema:HDe});oe.type==="encrypted_code_execution_result"&&B.push({type:"code_execution_tool_result",tool_use_id:V.toolCallId,content:{type:oe.type,encrypted_stdout:oe.encrypted_stdout,stderr:oe.stderr,return_code:oe.return_code,content:(E=oe.content)!=null?E:[]},cache_control:Ie})}else{let oe=await fr({value:te.value,schema:VDe});oe.type==="code_execution_result"?B.push({type:"code_execution_tool_result",tool_use_id:V.toolCallId,content:{type:oe.type,stdout:oe.stdout,stderr:oe.stderr,return_code:oe.return_code,content:(C=oe.content)!=null?C:[]},cache_control:Ie}):oe.type==="bash_code_execution_result"||oe.type==="bash_code_execution_tool_result_error"?B.push({type:"bash_code_execution_tool_result",tool_use_id:V.toolCallId,cache_control:Ie,content:oe}):B.push({type:"text_editor_code_execution_tool_result",tool_use_id:V.toolCallId,cache_control:Ie,content:oe})}break}if(xe==="web_fetch"){let te=V.output;if(te.type==="error-json"){let pe={};try{typeof te.value=="string"?pe=JSON.parse(te.value):typeof te.value=="object"&&te.value!==null&&(pe=te.value)}catch{let Xe=(k=te.value)==null?void 0:k.errorCode;pe={errorCode:typeof Xe=="string"?Xe:"unavailable"}}B.push({type:"web_fetch_tool_result",tool_use_id:V.toolCallId,content:{type:"web_fetch_tool_result_error",error_code:(I=pe.errorCode)!=null?I:"unavailable"},cache_control:Ie});break}if(te.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${V.toolName} is not supported`});break}let oe=await fr({value:te.value,schema:jDe});B.push({type:"web_fetch_tool_result",tool_use_id:V.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:Ie});break}if(xe==="web_search"){let te=V.output;if(te.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${V.toolName} is not supported`});break}let oe=await fr({value:te.value,schema:zDe});B.push({type:"web_search_tool_result",tool_use_id:V.toolCallId,content:oe.map(pe=>({url:pe.url,title:pe.title,page_age:pe.pageAge,encrypted_content:pe.encryptedContent,type:pe.type})),cache_control:Ie});break}if(xe==="tool_search_tool_regex"||xe==="tool_search_tool_bm25"){let te=V.output;if(te.type!=="json"){t.push({type:"other",message:`provider executed tool result output type ${te.type} for tool ${V.toolName} is not supported`});break}let pe=(await fr({value:te.value,schema:qDe})).map(re=>({type:"tool_reference",tool_name:re.toolName}));B.push({type:"tool_search_tool_result",tool_use_id:V.toolCallId,content:{type:"tool_search_tool_search_result",tool_references:pe},cache_control:Ie});break}t.push({type:"other",message:`provider executed tool result for tool ${V.toolName} is not supported`});break}}}}$.push({role:"assistant",content:B});break}default:{let B=z;throw new Error(`content type: ${B}`)}}}return{prompt:{system:D,messages:$},betas:R}}function nQt(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 Lre({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 FDe(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 sQt(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 $De(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 BDe(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 nO(r={}){var e,t;let n=(e=Ch(Wp({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 Gp({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":nw({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"})};return No({"anthropic-version":"2023-06-01",...c,...r.headers},`ai-sdk/anthropic/${m7t}`)},i=c=>{var l;return new oQt(c,{provider:o,baseURL:n,headers:s,fetch:r.fetch,generateId:(l=r.generateId)!=null?l:ao,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 WR({modelId:c,modelType:"embeddingModel"})},a.textEmbeddingModel=a.embeddingModel,a.imageModel=c=>{throw new WR({modelId:c,modelType:"imageModel"})},a.tools=RQt,a}var m7t,f7t,MDe,g7t,h7t,y7t,NDe,DDe,LDe,Ure,x7t,b7t,T7t,S7t,w7t,_7t,E7t,C7t,k7t,R7t,zDe,A7t,I7t,P7t,O7t,M7t,N7t,D7t,L7t,U7t,jDe,F7t,$7t,B7t,GDe,j7t,G7t,V7t,VDe,H7t,q7t,W7t,HDe,K7t,J7t,Z7t,qDe,X7t,Y7t,Q7t,oQt,iQt,aQt,cQt,lQt,uQt,dQt,pQt,mQt,fQt,gQt,hQt,yQt,vQt,xQt,bQt,TQt,SQt,wQt,_Qt,EQt,CQt,kQt,RQt,AQt,Fre=_(()=>{st();Se();st();Se();Se();Le();Se();Le();Le();st();Se();Le();Se();Se();Le();Se();Le();Se();Le();Se();Le();Se();st();Se();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();Se();Le();m7t="3.0.64",f7t=ue(()=>ce(p.object({type:p.literal("error"),error:p.object({type:p.string(),message:p.string()})}))),MDe=Lo({errorSchema:f7t,errorToMessage:r=>r.error.message}),g7t=ue(()=>ce(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()}))),h7t=ue(()=>ce(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")})]))),y7t=ue(()=>ce(p.object({signature:p.string().optional(),redactedData:p.string().optional()}))),NDe=p.object({citations:p.object({enabled:p.boolean()}).optional(),title:p.string().optional(),context:p.string().optional()}),DDe=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()}),LDe=4;Ure=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(r,e){let t=v7t(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>LDe){this.warnings.push({type:"unsupported",feature:"cacheControl breakpoint limit",details:`Maximum ${LDe} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return t}}getWarnings(){return this.warnings}},x7t=ue(()=>ce(p.object({maxCharacters:p.number().optional()}))),b7t=ue(()=>ce(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()}))),T7t=Do({id:"anthropic.text_editor_20250728",inputSchema:b7t}),S7t=(r={})=>T7t(r),w7t=ue(()=>ce(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()}))),_7t=ue(()=>ce(p.array(p.object({url:p.string(),title:p.string().nullable(),pageAge:p.string().nullable(),encryptedContent:p.string(),type:p.literal("web_search_result")})))),E7t=ue(()=>ce(p.object({query:p.string()}))),C7t=tr({id:"anthropic.web_search_20260209",inputSchema:E7t,outputSchema:_7t,supportsDeferredResults:!0}),k7t=(r={})=>C7t(r),R7t=ue(()=>ce(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()}))),zDe=ue(()=>ce(p.array(p.object({url:p.string(),title:p.string().nullable(),pageAge:p.string().nullable(),encryptedContent:p.string(),type:p.literal("web_search_result")})))),A7t=ue(()=>ce(p.object({query:p.string()}))),I7t=tr({id:"anthropic.web_search_20250305",inputSchema:A7t,outputSchema:zDe,supportsDeferredResults:!0}),P7t=(r={})=>I7t(r),O7t=ue(()=>ce(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()}))),M7t=ue(()=>ce(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()}))),N7t=ue(()=>ce(p.object({url:p.string()}))),D7t=tr({id:"anthropic.web_fetch_20260209",inputSchema:N7t,outputSchema:M7t,supportsDeferredResults:!0}),L7t=(r={})=>D7t(r),U7t=ue(()=>ce(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()}))),jDe=ue(()=>ce(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()}))),F7t=ue(()=>ce(p.object({url:p.string()}))),$7t=tr({id:"anthropic.web_fetch_20250910",inputSchema:F7t,outputSchema:jDe,supportsDeferredResults:!0}),B7t=(r={})=>$7t(r);GDe=ue(()=>ce(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([])}))),j7t=ue(()=>ce(p.object({code:p.string()}))),G7t=tr({id:"anthropic.code_execution_20250522",inputSchema:j7t,outputSchema:GDe}),V7t=(r={})=>G7t(r),VDe=ue(()=>ce(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()})]))),H7t=ue(()=>ce(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()})])]))),q7t=tr({id:"anthropic.code_execution_20250825",inputSchema:H7t,outputSchema:VDe,supportsDeferredResults:!0}),W7t=(r={})=>q7t(r),HDe=ue(()=>ce(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()})]))),K7t=ue(()=>ce(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()})])]))),J7t=tr({id:"anthropic.code_execution_20260120",inputSchema:K7t,outputSchema:HDe,supportsDeferredResults:!0}),Z7t=(r={})=>J7t(r),qDe=ue(()=>ce(p.array(p.object({type:p.literal("tool_reference"),toolName:p.string()})))),X7t=ue(()=>ce(p.object({pattern:p.string(),limit:p.number().optional()}))),Y7t=tr({id:"anthropic.tool_search_regex_20251119",inputSchema:X7t,outputSchema:qDe,supportsDeferredResults:!0}),Q7t=(r={})=>Y7t(r);oQt=class{constructor(r,e){this.specificationVersion="v3";var t;this.modelId=r,this.config=e,this.generateId=(t=e.generateId)!=null?t:ao}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,v,b,T,w,E,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,P=await Qn({provider:"anthropic",providerOptions:f,schema:DDe}),D=A!=="anthropic"?await Qn({provider:A,providerOptions:f,schema:DDe}):null,$=D!=null,O=Object.assign({},P??{},D??{}),{maxOutputTokens:F,supportsStructuredOutput:N,isKnownModel:U}=sQt(this.modelId),L=((y=this.config.supportsNativeStructuredOutput)!=null?y:!0)&&N,z=((v=this.config.supportsStrictTools)!=null?v:!0)&&N,B=(b=O?.structuredOutputMode)!=null?b:"auto",j=B==="outputFormat"||B==="auto"&&L,q=l?.type==="json"&&l.schema!=null&&!j?{type:"function",name:"json",description:"Respond with a JSON object.",inputSchema:l.schema}:void 0,K=O?.contextManagement,ge=new Ure,Y=pF({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:he,betas:V}=await rQt({prompt:e,sendReasoning:(T=O?.sendReasoning)!=null?T:!0,warnings:R,cacheControlValidator:ge,toolNameMapping:Y}),ve=(w=O?.thinking)==null?void 0:w.type,Ie=ve==="enabled"||ve==="adaptive",xe=ve==="enabled"?(E=O?.thinking)==null?void 0:E.budgetTokens:void 0,te=t??F,oe={model:this.modelId,max_tokens:te,temperature:n,top_k:s,top_p:o,stop_sequences:c,...Ie&&{thinking:{type:ve,...xe!=null&&{budget_tokens:xe}}},...(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(fe=>({type:fe.type,name:fe.name,url:fe.url,authorization_token:fe.authorizationToken,tool_configuration:fe.toolConfiguration?{allowed_tools:fe.toolConfiguration.allowedTools,enabled:fe.toolConfiguration.enabled}:void 0}))},...O?.container&&{container:O.container.skills&&O.container.skills.length>0?{id:O.container.id,skills:O.container.skills.map(fe=>({type:fe.type,skill_id:fe.skillId,version:fe.version}))}:O.container.id},system:he.system,messages:he.messages,...K&&{context_management:{edits:K.edits.map(fe=>{let ir=fe.type;switch(ir){case"clear_tool_uses_20250919":return{type:fe.type,...fe.trigger!==void 0&&{trigger:fe.trigger},...fe.keep!==void 0&&{keep:fe.keep},...fe.clearAtLeast!==void 0&&{clear_at_least:fe.clearAtLeast},...fe.clearToolInputs!==void 0&&{clear_tool_inputs:fe.clearToolInputs},...fe.excludeTools!==void 0&&{exclude_tools:fe.excludeTools}};case"clear_thinking_20251015":return{type:fe.type,...fe.keep!==void 0&&{keep:fe.keep}};case"compact_20260112":return{type:fe.type,...fe.trigger!==void 0&&{trigger:fe.trigger},...fe.pauseAfterCompaction!==void 0&&{pause_after_compaction:fe.pauseAfterCompaction},...fe.instructions!==void 0&&{instructions:fe.instructions}};default:R.push({type:"other",message:`Unknown context management strategy: ${ir}`});return}}).filter(fe=>fe!==void 0)}}};Ie?(ve==="enabled"&&xe==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},xe=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=te+(xe??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),U&&oe.max_tokens>F&&(t!=null&&R.push({type:"unsupported",feature:"maxOutputTokens",details:`${oe.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${F} max output tokens. The max output tokens have been limited to ${F}.`}),oe.max_tokens=F),O?.mcpServers&&O.mcpServers.length>0&&V.add("mcp-client-2025-04-04"),K&&(V.add("context-management-2025-06-27"),K.edits.some(fe=>fe.type==="compact_20260112")&&V.add("compact-2026-01-12")),O?.container&&O.container.skills&&O.container.skills.length>0&&(V.add("code-execution-2025-08-25"),V.add("skills-2025-10-02"),V.add("files-api-2025-04-14"),d?.some(fe=>fe.type==="provider"&&(fe.id==="anthropic.code_execution_20250825"||fe.id==="anthropic.code_execution_20260120"))||R.push({type:"other",message:"code execution tool is required when using skills"})),O?.effort&&V.add("effort-2025-11-24"),O?.speed==="fast"&&V.add("fast-mode-2026-02-01"),h&&((k=O?.toolStreaming)==null||k)&&V.add("fine-grained-tool-streaming-2025-05-14");let{tools:pe,toolChoice:re,toolWarnings:Xe,betas:_e}=await z7t(q!=null?{tools:[...d??[],q],toolChoice:{type:"required"},disableParallelToolUse:!0,cacheControlValidator:ge,supportsStructuredOutput:!1,supportsStrictTools:z}:{tools:d??[],toolChoice:m,disableParallelToolUse:O?.disableParallelToolUse,cacheControlValidator:ge,supportsStructuredOutput:L,supportsStrictTools:z}),Te=ge.getWarnings();return{args:{...oe,tools:pe,tool_choice:re,stream:h===!0?!0:void 0},warnings:[...R,...Xe,...Te],betas:new Set([...V,..._e,...r,...(I=O?.anthropicBeta)!=null?I:[]]),usesJsonResponseTool:q!=null,toolNameMapping:Y,providerOptionsName:A,usedCustomProviderKey:$}}async getHeaders({betas:r,headers:e}){return zr(await Bn(this.config.headers),e,r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{})}async getBetasFromHeaders(r){var e,t;let o=(e=(await Bn(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)],v=$De(c.tools),{responseHeaders:b,value:T,rawValue:w}=await Zr({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:u,headers:r.headers}),body:this.transformRequestBody(c,u),failedResponseHandler:MDe,successfulResponseHandler:Xr(g7t),abortSignal:r.abortSignal,fetch:this.config.fetch}),E=[],C={},k={},I=!1;for(let R of T.content)switch(R.type){case"text":{if(!d&&(E.push({type:"text",text:R.text}),R.citations))for(let A of R.citations){let P=FDe(A,y,this.generateId);P&&E.push(P)}break}case"thinking":{E.push({type:"reasoning",text:R.thinking,providerMetadata:{anthropic:{signature:R.signature}}});break}case"redacted_thinking":{E.push({type:"reasoning",text:"",providerMetadata:{anthropic:{redactedData:R.data}}});break}case"compaction":{E.push({type:"text",text:R.content,providerMetadata:{anthropic:{type:"compaction"}}});break}case"tool_use":{if(d&&R.name==="json")I=!0,E.push({type:"text",text:JSON.stringify(R.input)});else{let P=R.caller,D=P?{type:P.type,toolId:"tool_id"in P?P.tool_id:void 0}:void 0;E.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")E.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;E.push({type:"tool-call",toolCallId:R.id,toolName:m.toCustomToolName(R.name),input:JSON.stringify(A),providerExecuted:!0,...v&&R.name==="code_execution"?{dynamic:!0}:{}})}else(R.name==="tool_search_tool_regex"||R.name==="tool_search_tool_bm25")&&(k[R.id]=R.name,E.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}}},E.push(C[R.id]);break}case"mcp_tool_result":{E.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}),E.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"&&E.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)){E.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName("web_search"),result:R.content.map(A=>{var P;return{url:A.url,title:A.title,pageAge:(P=A.page_age)!=null?P:null,encryptedContent:A.encrypted_content,type:A.type}})});for(let A of R.content)E.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 E.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"?E.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"?E.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"&&E.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":{E.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 P=m.toCustomToolName("tool_search_tool_bm25"),D=m.toCustomToolName("tool_search_tool_regex");P!=="tool_search_tool_bm25"?A="tool_search_tool_bm25":A="tool_search_tool_regex"}R.content.type==="tool_search_tool_search_result"?E.push({type:"tool-result",toolCallId:R.tool_use_id,toolName:m.toCustomToolName(A),result:R.content.tool_references.map(P=>({type:P.type,toolName:P.tool_name}))}):E.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:E,finishReason:{unified:Lre({finishReason:T.stop_reason,isJsonResponseFromTool:I}),raw:(s=T.stop_reason)!=null?s:void 0},usage:UDe({usage:T.usage}),request:{body:c},response:{id:(i=T.id)!=null?i:void 0,modelId:(a=T.model)!=null?a:void 0,headers:b,body:w},warnings:l,providerMetadata:(()=>{var R,A,P,D,$;let O={usage:T.usage,cacheCreationInputTokens:(R=T.usage.cache_creation_input_tokens)!=null?R:null,stopSequence:(A=T.stop_sequence)!=null?A:null,iterations:T.usage.iterations?T.usage.iterations.map(N=>({type:N.type,inputTokens:N.input_tokens,outputTokens:N.output_tokens})):null,container:T.container?{expiresAt:T.container.expires_at,id:T.container.id,skills:(D=(P=T.container.skills)==null?void 0:P.map(N=>({type:N.type,skillId:N.skill_id,version:N.version})))!=null?D:null}:null,contextManagement:($=BDe(T.context_management))!=null?$:null},F={anthropic:O};return h&&f!=="anthropic"&&(F[f]=O),F})()}}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=$De(n.tools),m=this.buildRequestUrl(!0),{responseHeaders:f,value:h}=await Zr({url:m,headers:await this.getHeaders({betas:s,headers:r.headers}),body:this.transformRequestBody(n,s),failedResponseHandler:MDe,successfulResponseHandler:ju(h7t),abortSignal:r.abortSignal,fetch:this.config.fetch}),y={unified:"other",raw:void 0},v={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0,iterations:null},b={},T={},w={},E=null,C,k=null,I=null,R=null,A=!1,P,D=this.generateId,$=h.pipeThrough(new TransformStream({start(U){U.enqueue({type:"stream-start",warnings:o})},transform(U,L){var z,B,j,q,K,ge,Y,he,V,ve,Ie,xe,te,oe;if(r.includeRawChunks&&L.enqueue({type:"raw",rawValue:U.rawValue}),!U.success){L.enqueue({type:"error",error:U.error});return}let pe=U.value;switch(pe.type){case"ping":return;case"content_block_start":{let re=pe.content_block,Xe=re.type;switch(P=Xe,Xe){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:re.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&&re.name==="json")A=!0,b[pe.index]={type:"text"},L.enqueue({type:"text-start",id:String(pe.index)});else{let Te=re.caller,fe=Te?{type:Te.type,toolId:"tool_id"in Te?Te.tool_id:void 0}:void 0,fc=re.input&&Object.keys(re.input).length>0?JSON.stringify(re.input):"";b[pe.index]={type:"tool-call",toolCallId:re.id,toolName:re.name,input:fc,firstDelta:fc.length===0,...fe&&{caller:fe}},L.enqueue({type:"tool-input-start",id:re.id,toolName:re.name})}return}case"server_tool_use":{if(["web_fetch","web_search","code_execution","text_editor_code_execution","bash_code_execution"].includes(re.name)){let _e=re.name==="text_editor_code_execution"||re.name==="bash_code_execution"?"code_execution":re.name,Te=a.toCustomToolName(_e),fe=re.input!=null&&typeof re.input=="object"&&Object.keys(re.input).length>0?JSON.stringify(re.input):"";b[pe.index]={type:"tool-call",toolCallId:re.id,toolName:Te,input:fe,providerExecuted:!0,...d&&_e==="code_execution"?{dynamic:!0}:{},firstDelta:!0,providerToolName:re.name},L.enqueue({type:"tool-input-start",id:re.id,toolName:Te,providerExecuted:!0,...d&&_e==="code_execution"?{dynamic:!0}:{}})}else if(re.name==="tool_search_tool_regex"||re.name==="tool_search_tool_bm25"){w[re.id]=re.name;let _e=a.toCustomToolName(re.name);b[pe.index]={type:"tool-call",toolCallId:re.id,toolName:_e,input:"",providerExecuted:!0,firstDelta:!0,providerToolName:re.name},L.enqueue({type:"tool-input-start",id:re.id,toolName:_e,providerExecuted:!0})}return}case"web_fetch_tool_result":{re.content.type==="web_fetch_result"?(u.push({title:(z=re.content.content.title)!=null?z:re.content.url,mediaType:re.content.content.source.media_type}),L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("web_fetch"),result:{type:"web_fetch_result",url:re.content.url,retrievedAt:re.content.retrieved_at,content:{type:re.content.content.type,title:re.content.content.title,citations:re.content.content.citations,source:{type:re.content.content.source.type,mediaType:re.content.content.source.media_type,data:re.content.content.source.data}}}})):re.content.type==="web_fetch_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("web_fetch"),isError:!0,result:{type:"web_fetch_tool_result_error",errorCode:re.content.error_code}});return}case"web_search_tool_result":{if(Array.isArray(re.content)){L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("web_search"),result:re.content.map(_e=>{var Te;return{url:_e.url,title:_e.title,pageAge:(Te=_e.page_age)!=null?Te:null,encryptedContent:_e.encrypted_content,type:_e.type}})});for(let _e of re.content)L.enqueue({type:"source",sourceType:"url",id:D(),url:_e.url,title:_e.title,providerMetadata:{anthropic:{pageAge:(B=_e.page_age)!=null?B:null}}})}else L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("web_search"),isError:!0,result:{type:"web_search_tool_result_error",errorCode:re.content.error_code}});return}case"code_execution_tool_result":{re.content.type==="code_execution_result"?L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:{type:re.content.type,stdout:re.content.stdout,stderr:re.content.stderr,return_code:re.content.return_code,content:(j=re.content.content)!=null?j:[]}}):re.content.type==="encrypted_code_execution_result"?L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:{type:re.content.type,encrypted_stdout:re.content.encrypted_stdout,stderr:re.content.stderr,return_code:re.content.return_code,content:(q=re.content.content)!=null?q:[]}}):re.content.type==="code_execution_tool_result_error"&&L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("code_execution"),isError:!0,result:{type:"code_execution_tool_result_error",errorCode:re.content.error_code}});return}case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":{L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName("code_execution"),result:re.content});return}case"tool_search_tool_result":{let _e=w[re.tool_use_id];if(_e==null){let Te=a.toCustomToolName("tool_search_tool_bm25"),fe=a.toCustomToolName("tool_search_tool_regex");Te!=="tool_search_tool_bm25"?_e="tool_search_tool_bm25":_e="tool_search_tool_regex"}re.content.type==="tool_search_tool_search_result"?L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName(_e),result:re.content.tool_references.map(Te=>({type:Te.type,toolName:Te.tool_name}))}):L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:a.toCustomToolName(_e),isError:!0,result:{type:"tool_search_tool_result_error",errorCode:re.content.error_code}});return}case"mcp_tool_use":{T[re.id]={type:"tool-call",toolCallId:re.id,toolName:re.name,input:JSON.stringify(re.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:"mcp-tool-use",serverName:re.server_name}}},L.enqueue(T[re.id]);return}case"mcp_tool_result":{L.enqueue({type:"tool-result",toolCallId:re.tool_use_id,toolName:T[re.tool_use_id].toolName,isError:re.is_error,result:re.content,dynamic:!0,providerMetadata:T[re.tool_use_id].providerMetadata});return}default:{let _e=Xe;throw new Error(`Unsupported content block type: ${_e}`)}}}case"content_block_stop":{if(b[pe.index]!=null){let re=b[pe.index];switch(re.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&&re.toolName==="json")){L.enqueue({type:"tool-input-end",id:re.toolCallId});let _e=re.input===""?"{}":re.input;if(re.providerToolName==="code_execution")try{let Te=JSON.parse(_e);Te!=null&&typeof Te=="object"&&"code"in Te&&!("type"in Te)&&(_e=JSON.stringify({type:"programmatic-tool-call",...Te}))}catch{}L.enqueue({type:"tool-call",toolCallId:re.toolCallId,toolName:re.toolName,input:_e,providerExecuted:re.providerExecuted,...d&&re.providerToolName==="code_execution"?{dynamic:!0}:{},...re.caller&&{providerMetadata:{anthropic:{caller:re.caller}}}})}break}delete b[pe.index]}P=void 0;return}case"content_block_delta":{let re=pe.delta.type;switch(re){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":{P==="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 Xe=b[pe.index],_e=pe.delta.partial_json;if(_e.length===0)return;if(A){if(Xe?.type!=="text")return;L.enqueue({type:"text-delta",id:String(pe.index),delta:_e})}else{if(Xe?.type!=="tool-call")return;Xe.firstDelta&&(Xe.providerToolName==="bash_code_execution"||Xe.providerToolName==="text_editor_code_execution")&&(_e=`{"type": "${Xe.providerToolName}",${_e.substring(1)}`),L.enqueue({type:"tool-input-delta",id:Xe.toolCallId,delta:_e}),Xe.input+=_e,Xe.firstDelta=!1}return}case"citations_delta":{let Xe=pe.delta.citation,_e=FDe(Xe,u,D);_e&&L.enqueue(_e);return}default:{let Xe=re;throw new Error(`Unsupported delta type: ${Xe}`)}}}case"message_start":{if(v.input_tokens=pe.message.usage.input_tokens,v.cache_read_input_tokens=(K=pe.message.usage.cache_read_input_tokens)!=null?K:0,v.cache_creation_input_tokens=(ge=pe.message.usage.cache_creation_input_tokens)!=null?ge: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:Lre({finishReason:pe.message.stop_reason,isJsonResponseFromTool:A}),raw:pe.message.stop_reason}),L.enqueue({type:"response-metadata",id:(he=pe.message.id)!=null?he:void 0,modelId:(V=pe.message.model)!=null?V:void 0}),pe.message.content!=null)for(let re=0;re<pe.message.content.length;re++){let Xe=pe.message.content[re];if(Xe.type==="tool_use"){let _e=Xe.caller,Te=_e?{type:_e.type,toolId:"tool_id"in _e?_e.tool_id:void 0}:void 0;L.enqueue({type:"tool-input-start",id:Xe.id,toolName:Xe.name});let fe=JSON.stringify((ve=Xe.input)!=null?ve:{});L.enqueue({type:"tool-input-delta",id:Xe.id,delta:fe}),L.enqueue({type:"tool-input-end",id:Xe.id}),L.enqueue({type:"tool-call",toolCallId:Xe.id,toolName:Xe.name,input:fe,...Te&&{providerMetadata:{anthropic:{caller:Te}}}})}}return}case"message_delta":{pe.usage.input_tokens!=null&&v.input_tokens!==pe.usage.input_tokens&&(v.input_tokens=pe.usage.input_tokens),v.output_tokens=pe.usage.output_tokens,pe.usage.cache_read_input_tokens!=null&&(v.cache_read_input_tokens=pe.usage.cache_read_input_tokens),pe.usage.cache_creation_input_tokens!=null&&(v.cache_creation_input_tokens=pe.usage.cache_creation_input_tokens,k=pe.usage.cache_creation_input_tokens),pe.usage.iterations!=null&&(v.iterations=pe.usage.iterations),y={unified:Lre({finishReason:pe.delta.stop_reason,isJsonResponseFromTool:A}),raw:(Ie=pe.delta.stop_reason)!=null?Ie:void 0},I=(xe=pe.delta.stop_sequence)!=null?xe:null,R=pe.delta.container!=null?{expiresAt:pe.delta.container.expires_at,id:pe.delta.container.id,skills:(oe=(te=pe.delta.container.skills)==null?void 0:te.map(re=>({type:re.type,skillId:re.skill_id,version:re.version})))!=null?oe:null}:null,pe.context_management&&(E=BDe(pe.context_management)),C={...C,...pe.usage};return}case"message_stop":{let re={usage:C??null,cacheCreationInputTokens:k,stopSequence:I,iterations:v.iterations?v.iterations.map(_e=>({type:_e.type,inputTokens:_e.input_tokens,outputTokens:_e.output_tokens})):null,container:R,contextManagement:E},Xe={anthropic:re};l&&c!=="anthropic"&&(Xe[c]=re),L.enqueue({type:"finish",finishReason:y,usage:UDe({usage:v,rawUsage:C}),providerMetadata:Xe});return}case"error":{L.enqueue({type:"error",error:pe.error});return}default:{let re=pe;throw new Error(`Unsupported chunk type: ${re}`)}}}})),[O,F]=$.tee(),N=O.getReader();try{await N.read();let U=await N.read();if(((e=U.value)==null?void 0:e.type)==="raw"&&(U=await N.read()),((t=U.value)==null?void 0:t.type)==="error"){let L=U.value.error;throw new Rt({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:F,request:{body:n},response:{headers:f}}}};iQt=ue(()=>ce(p.object({command:p.string(),restart:p.boolean().optional()}))),aQt=Do({id:"anthropic.bash_20241022",inputSchema:iQt}),cQt=ue(()=>ce(p.object({command:p.string(),restart:p.boolean().optional()}))),lQt=Do({id:"anthropic.bash_20250124",inputSchema:cQt}),uQt=ue(()=>ce(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()}))),dQt=Do({id:"anthropic.computer_20241022",inputSchema:uQt}),pQt=ue(()=>ce(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()}))),mQt=Do({id:"anthropic.computer_20250124",inputSchema:pQt}),fQt=ue(()=>ce(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()}))),gQt=Do({id:"anthropic.computer_20251124",inputSchema:fQt}),hQt=ue(()=>ce(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()})]))),yQt=Do({id:"anthropic.memory_20250818",inputSchema:hQt}),vQt=ue(()=>ce(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()}))),xQt=Do({id:"anthropic.text_editor_20241022",inputSchema:vQt}),bQt=ue(()=>ce(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()}))),TQt=Do({id:"anthropic.text_editor_20250124",inputSchema:bQt}),SQt=ue(()=>ce(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()}))),wQt=Do({id:"anthropic.text_editor_20250429",inputSchema:SQt}),_Qt=ue(()=>ce(p.array(p.object({type:p.literal("tool_reference"),toolName:p.string()})))),EQt=ue(()=>ce(p.object({query:p.string(),limit:p.number().optional()}))),CQt=tr({id:"anthropic.tool_search_bm25_20251119",inputSchema:EQt,outputSchema:_Qt,supportsDeferredResults:!0}),kQt=(r={})=>CQt(r),RQt={bash_20241022:aQt,bash_20250124:lQt,codeExecution_20250522:V7t,codeExecution_20250825:W7t,codeExecution_20260120:Z7t,computer_20241022:dQt,computer_20250124:mQt,computer_20251124:gQt,memory_20250818:yQt,textEditor_20241022:xQt,textEditor_20250124:TQt,textEditor_20250429:wQt,textEditor_20250728:S7t,webFetch_20250910:B7t,webFetch_20260209:L7t,webSearch_20250305:P7t,webSearch_20260209:k7t,toolSearchRegex_20251119:Q7t,toolSearchBm25_20251119:kQt};AQt=nO()});var Bre={};Z(Bre,{AsyncLocalStorage:()=>KQt,Buffer:()=>Ftr,Channel:()=>ktr,DatabaseSync:()=>Utr,Duplex:()=>ZQt,EventEmitter:()=>WQt,Http2ServerRequest:()=>Gtr,Http2ServerResponse:()=>Vtr,Interface:()=>Ltr,MIMEType:()=>Ztr,PassThrough:()=>XQt,PerformanceObserver:()=>_tr,Readable:()=>JDe,ReadableStream:()=>YQt,Resolver:()=>Str,TextDecoder:()=>YDe,TextEncoder:()=>VG,Transform:()=>JQt,URL:()=>ltr,URLSearchParams:()=>utr,Worker:()=>Ptr,Writable:()=>ZDe,access:()=>Cer,appendFile:()=>ser,appendFileSync:()=>DQt,arch:()=>jer,arrayBuffer:()=>Htr,basename:()=>BQt,builtinModules:()=>str,callbackify:()=>ytr,channel:()=>Ctr,chmodSync:()=>oer,clearInterval:()=>Jtr,clearTimeout:()=>Wtr,closeSync:()=>ler,connect:()=>qer,constants:()=>$tr,copyFileSync:()=>aer,cpSync:()=>LQt,cpus:()=>Fer,createConnection:()=>Wer,createGunzip:()=>etr,createGzip:()=>ttr,createHash:()=>WDe,createHmac:()=>PQt,createInterface:()=>Dtr,createReadStream:()=>xer,createRequire:()=>otr,createServer:()=>KDe,createWriteStream:()=>ver,debug:()=>gtr,debuglog:()=>XDe,default:()=>$re,deflateSync:()=>Jer,deprecate:()=>htr,deserialize:()=>Itr,dirname:()=>$Qt,exec:()=>Ier,execFile:()=>Oer,execFileSync:()=>Mer,execSync:()=>Per,existsSync:()=>ter,extname:()=>zQt,fileURLToPath:()=>dtr,finished:()=>eer,format:()=>ctr,freemem:()=>$er,fstatSync:()=>uer,get:()=>Her,gunzip:()=>Qer,gunzipSync:()=>Zer,gzip:()=>Yer,gzipSync:()=>Xer,hasSubscribers:()=>Rtr,homedir:()=>Der,hostname:()=>Uer,inflateSync:()=>Ker,inherits:()=>mtr,inspect:()=>HG,isAbsolute:()=>GQt,isBuiltin:()=>itr,isDeepStrictEqual:()=>vtr,isIP:()=>jtr,isIPv4:()=>ztr,isIPv6:()=>Btr,isMainThread:()=>Otr,join:()=>UQt,lookup:()=>Ttr,mkdir:()=>Ser,mkdirSync:()=>der,monitorEventLoopDelay:()=>Etr,normalize:()=>qQt,ok:()=>rtr,openSync:()=>cer,parentPort:()=>Mtr,parse:()=>atr,pathToFileURL:()=>ptr,performance:()=>wtr,pipeline:()=>QQt,platform:()=>Ner,posix:()=>HQt,promises:()=>IQt,promisify:()=>ftr,randomBytes:()=>OQt,randomUUID:()=>MQt,readFile:()=>ber,readFileSync:()=>rer,readdir:()=>_er,readdirSync:()=>mer,realpathSync:()=>ier,relative:()=>jQt,release:()=>Ger,rename:()=>ker,renameSync:()=>ger,request:()=>Ver,resolve:()=>FQt,rm:()=>Rer,rmSync:()=>yer,rmdirSync:()=>her,sep:()=>VQt,serialize:()=>Atr,setInterval:()=>Ktr,setTimeout:()=>qtr,spawn:()=>Aer,stat:()=>wer,statSync:()=>per,strict:()=>ntr,tmpdir:()=>Ler,toUSVString:()=>xtr,totalmem:()=>Ber,type:()=>zer,types:()=>btr,unlink:()=>Eer,unlinkSync:()=>fer,webcrypto:()=>NQt,workerData:()=>Ntr,writeFile:()=>Ter,writeFileSync:()=>ner});var Yo,si,$re,IQt,WDe,PQt,OQt,MQt,NQt,DQt,LQt,KDe,UQt,FQt,$Qt,BQt,zQt,jQt,GQt,VQt,HQt,qQt,WQt,KQt,JDe,ZDe,JQt,ZQt,XQt,YQt,QQt,eer,ter,rer,ner,oer,ser,ier,aer,cer,ler,uer,der,per,mer,fer,ger,her,yer,ver,xer,ber,Ter,Ser,wer,_er,Eer,Cer,ker,Rer,Aer,Ier,Per,Oer,Mer,Ner,Der,Ler,Uer,Fer,$er,Ber,zer,jer,Ger,Ver,Her,qer,Wer,Ker,Jer,Zer,Xer,Yer,Qer,etr,ttr,rtr,ntr,otr,str,itr,atr,ctr,ltr,utr,dtr,ptr,mtr,ftr,XDe,gtr,HG,htr,ytr,vtr,xtr,btr,YDe,VG,Ttr,Str,wtr,_tr,Etr,Ctr,ktr,Rtr,Atr,Itr,Ptr,Otr,Mtr,Ntr,Dtr,Ltr,Utr,Ftr,$tr,Btr,ztr,jtr,Gtr,Vtr,Htr,QDe,qtr,Wtr,Ktr,Jtr,Ztr,oO=_(()=>{Yo=()=>{},si=async()=>{},$re={},IQt={readFile:si,writeFile:si,mkdir:si,stat:si,readdir:si,unlink:si,access:si,rm:si,rename:si},WDe=r=>{let e=[];return{update(t){return e.push(typeof t=="string"?new VG().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}}},PQt=(r,e)=>WDe(r),OQt=r=>new Uint8Array(r||32),MQt=()=>globalThis.crypto?.randomUUID?.()||Math.random().toString(36),NQt=globalThis.crypto,DQt=()=>{throw new Error("[NeuroLink:browser] fs.appendFileSync is not supported in browser runtime \u2014 use server-side execution")},LQt=()=>{throw new Error("[NeuroLink:browser] fs.cpSync is not supported in browser runtime \u2014 use server-side execution")},KDe=()=>({listen:Yo,close:Yo,on:Yo}),UQt=(...r)=>r.join("/"),FQt=(...r)=>r.join("/"),$Qt=r=>r||"",BQt=r=>r?.split?.("/")?.pop?.()||"",zQt=r=>{let e=r?.match?.(/\.[^.]+$/);return e?e[0]:""},jQt=(r,e)=>e||"",GQt=()=>!1,VQt="/",HQt={normalize:r=>r,join:(...r)=>r.join("/"),resolve:(...r)=>r.join("/"),sep:"/"},qQt=r=>r,WQt=class{on(){return this}off(){return this}emit(){return this}once(){return this}removeListener(){return this}addListener(){return this}},KQt=class{getStore(){}run(r,e,...t){return e(...t)}enterWith(){}disable(){}},JDe=class{pipe(){return this}on(){return this}read(){return null}push(){}destroy(){}},ZDe=class{write(){return!0}end(){}on(){return this}destroy(){}},JQt=class{push(){}on(){return this}},ZQt=class{on(){return this}},XQt=class{pipe(){return this}on(){return this}},YQt=globalThis.ReadableStream||class{},QQt=Yo,eer=Yo,ter=()=>!1,rer=()=>"",ner=Yo,oer=Yo,ser=si,ier=r=>r,aer=Yo,cer=()=>0,ler=Yo,uer=()=>({}),der=Yo,per=()=>({}),mer=()=>[],fer=Yo,ger=Yo,her=Yo,yer=Yo,ver=()=>new ZDe,xer=()=>new JDe,ber=si,Ter=si,Ser=si,wer=si,_er=si,Eer=si,Cer=si,ker=si,Rer=si,Aer=()=>({on:Yo,stdout:{on:Yo},stderr:{on:Yo},kill:Yo}),Ier=(r,e)=>e?.(null,"",""),Per=()=>"",Oer=(r,e,t)=>{typeof e=="function"?e(null,"",""):t?.(null,"","")},Mer=()=>"",Ner="browser",Der=()=>"/",Ler=()=>"/tmp",Uer=()=>"browser",Fer=()=>[{}],$er=()=>0,Ber=()=>0,zer=()=>"Browser",jer=()=>"wasm",Ger=()=>"0",Ver=()=>({}),Her=()=>({}),qer=()=>({}),Wer=()=>({}),Ker=()=>new Uint8Array,Jer=()=>new Uint8Array,Zer=()=>new Uint8Array,Xer=()=>new Uint8Array,Yer=(r,e)=>e?.(null,r),Qer=(r,e)=>e?.(null,r),etr=()=>({}),ttr=()=>({}),rtr=Yo,ntr={},otr=()=>()=>({}),str=[],itr=()=>!1,atr=r=>({pathname:r||"",hostname:"",protocol:"",search:"",hash:""}),ctr=()=>"",ltr=globalThis.URL,utr=globalThis.URLSearchParams,dtr=r=>typeof r=="string"?r.replace("file://",""):r,ptr=r=>new globalThis.URL("file://"+r),mtr=(r,e)=>{e&&(r.super_=e,Object.setPrototypeOf(r.prototype,e.prototype))},ftr=r=>(...e)=>new Promise((t,n)=>r(...e,(o,s)=>o?n(o):t(s))),XDe=r=>{let e=(...t)=>{};return e.enabled=!1,e},gtr=XDe,HG=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};HG.custom=Symbol.for("nodejs.util.inspect.custom");HG.colors={};HG.styles={};htr=r=>r,ytr=r=>(...e)=>{let t=e.pop();r(...e).then(n=>t(null,n)).catch(t)},vtr=(r,e)=>JSON.stringify(r)===JSON.stringify(e),xtr=r=>String(r),btr={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},YDe=globalThis.TextDecoder,VG=globalThis.TextEncoder,Ttr=(r,e)=>e?.(null,"127.0.0.1",4),Str=class{},wtr=globalThis.performance||{now:()=>Date.now()},_tr=class{observe(){}disconnect(){}},Etr=()=>({enable:Yo,disable:Yo,percentile:()=>0}),Ctr=()=>({}),ktr=class{},Rtr=()=>!1,Atr=()=>new Uint8Array,Itr=Yo,Ptr=class{},Otr=!0,Mtr=null,Ntr=null,Dtr=()=>({}),Ltr=class{},Utr=class{},Ftr=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 VG().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 VG().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 YDe().decode(this)}},$tr={F_OK:0,R_OK:4,W_OK:2,X_OK:1},Btr=()=>!1,ztr=()=>!1,jtr=()=>0,Gtr=class{},Vtr=class{},Htr=async()=>new ArrayBuffer(0),QDe=r=>({[Symbol.toPrimitive](){return r},ref(){return this},unref(){return this},hasRef(){return!1},refresh(){return this},close(){}}),qtr=(...r)=>QDe(globalThis.setTimeout(...r)),Wtr=globalThis.clearTimeout,Ktr=(...r)=>QDe(globalThis.setInterval(...r)),Jtr=globalThis.clearInterval,Ztr=class{constructor(r){this.type=r}toString(){return this.type}}});function eLe(r){return Q7("sha256",trr).update(r).digest("hex")}function rrr(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 sO(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 qG(r){return JSON.stringify({device_id:r.deviceId,account_uuid:r.accountUuid,session_id:r.sessionId})}function zre(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"||!sO(e.account_uuid)||typeof e.session_id!="string"||!sO(e.session_id)?null:{deviceId:e.device_id,accountUuid:e.account_uuid,sessionId:e.session_id,metadataUserId:qG({deviceId:e.device_id,accountUuid:e.account_uuid,sessionId:e.session_id})}}catch{return null}}function WG(r,e){let t=zre(e?.existingUserId);if(t)return e?.preferredSessionId&&sO(e.preferredSessionId)?{deviceId:t.deviceId,accountUuid:t.accountUuid,sessionId:e.preferredSessionId,metadataUserId:qG({deviceId:t.deviceId,accountUuid:t.accountUuid,sessionId:e.preferredSessionId})}:t;let n=Date.now(),o=r||"default",s=wb.get(o);if(s&&s.expiresAt>n)return e?.preferredSessionId&&sO(e.preferredSessionId)?{deviceId:s.deviceId,accountUuid:s.accountUuid,sessionId:e.preferredSessionId,metadataUserId:qG({deviceId:s.deviceId,accountUuid:s.accountUuid,sessionId:e.preferredSessionId})}:s;let i=eLe(`${o}:device`),a=rrr(eLe(`${o}:account`)),c=e?.preferredSessionId&&sO(e.preferredSessionId)?e.preferredSessionId:ze(),l={deviceId:i,accountUuid:a,sessionId:c,metadataUserId:qG({deviceId:i,accountUuid:a,sessionId:c}),expiresAt:n+Qtr};return orr(n),wb.set(o,l),l}function nrr(r=Date.now()){let e=0;for(let[t,n]of wb.entries())n.expiresAt<=r&&(wb.delete(t),e+=1);return e}function orr(r=Date.now()){for(nrr(r);wb.size>=err;){let e=wb.keys().next().value;if(!e)break;wb.delete(e)}}function wE(r){let e=r?.match(/cc_version=([^;]+)/)?.[1]?.trim()||Xtr,t=r?.match(/cc_entrypoint=([^;]+)/)?.[1]?.trim()||Ytr;return`x-anthropic-billing-header: cc_version=${e}; cc_entrypoint=${t}; cch=00000;`}var tLe,rLe,Xtr,Ytr,SE,Qtr,err,trr,wb,_b,jre,KG=_(()=>{"use strict";dr();oO();tLe="9d1c250a-e61b-44d9-88ed-5944d1962f5e",rLe="https://api.anthropic.com/v1/oauth/token",Xtr="2.1.87.6d6",Ytr="sdk-cli",SE="claude-cli/2.1.87 (external, sdk-cli)",Qtr=36e5,err=1024,trr="neurolink-claude-code-identity-v1",wb=new Map;_b=["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"],jre="mcp_"});function crr(){return Object.values(nLe)}function iO(r,e){let t=srr[e];return t.includes("*")?crr().includes(r):t.includes(r)}function lrr(r){return arr[r]}function urr(r){return irr[r]}var nLe,srr,irr,arr,JG,ZG,Gre=_(()=>{"use strict";gt();nLe=(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))(nLe||{}),srr={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:["*"]},irr={"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"}},arr={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"};JG=lrr,ZG=urr});function drr(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 prr(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 mrr(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?_b.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",SE),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 frr(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 grr(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?`${jre}${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:`${jre}${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:wE(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:wE()};o.system=[l,s]}let i=t(),a=o.metadata?.user_id??i.substring(0,Math.min(20,i.length)),c=WG(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 hrr(r){try{let{propagation:e,context:t}=await Promise.resolve().then(()=>(br(),U6)),n={};e.inject(t.active(),n);for(let[o,s]of Object.entries(n))r.has(o)||r.set(o,s)}catch{}}function yrr(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('"'),v=y>=0?y+1:d.length;f=d.slice(0,v),s=d.slice(v)}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 vrr(r,e,t,n,o,s){let i=drr(r);i&&i.pathname==="/v1/messages"&&!i.searchParams.has("beta")&&i.searchParams.set("beta","true");let a=prr(r,e);mrr(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 frr(r,e),d=u;if(d&&typeof d=="string"&&!s)try{d=grr(d,a,t,o)}catch{}a.delete("content-length"),await hrr(a);let f=await Ve()(i?.toString()||(r instanceof Request?r.url:r.toString()),{...e,method:l,body:d,signal:e?.signal??c?.signal,headers:a});return o?yrr(f):f}function oLe(r,e=!0,t=!1,n=!1){return async(o,s)=>vrr(o,s,r,e,t,n)}var sLe=_(()=>{"use strict";KG();H();wn()});var cLe={};Z(cLe,{ANTHROPIC_BETA_HEADERS:()=>Hre,AnthropicProvider:()=>XG,ModelAccessError:()=>EA,default:()=>wrr,getModelCapabilities:()=>ZG,getRecommendedModelForTier:()=>JG,isModelAvailableForTier:()=>iO});var Hre,iLe,Vre,xrr,aLe,brr,Trr,Srr,XG,wrr,lLe=_(()=>{"use strict";Fre();br();$n();Fd();bn();KG();Kn();on();Gre();sLe();wn();gt();H();Yd();Jn();Vn();Lc();_i();SB();bi();Es();Gre();Hre={"anthropic-beta":["claude-code-20250219","fine-grained-tool-streaming-2025-05-14"].join(",")},iLe=()=>nr(ZNe()),Vre=()=>or("ANTHROPIC_MODEL","claude-sonnet-4-6"),xrr=ct.getTracer("neurolink.provider.anthropic"),aLe=()=>{try{let e=_r(Kp(),".neurolink","anthropic-credentials.json");if(Fn(e)){let t=Xc(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}},brr=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"},Trr=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},Srr=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"))}},XG=class extends Ct{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??aLe(),a=s?"api_key":n?.authMethod??Trr(i),c=n?.subscriptionTier??(a==="oauth"?brr(i):"api"),l=e||Vre(),u=l;!process.env.ANTHROPIC_BASE_URL&&c!=="api"&&!iO(l,c)&&(u=JG(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=oLe(()=>h.accessToken,this.enableBetaFeatures,!1,!0);f=nO({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??iLe(),y=(()=>{let v=process.env.ANTHROPIC_BASE_URL;if(!v)return;let b=v.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:v,rewrittenTo:`${b}/v1`}),`${b}/v1`)})();f=nO({apiKey:h,headers:m,...y&&{baseURL:y},fetch:Ve()}),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||Vre()),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?Hre["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=[..._b,"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"]=Hre["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=iO(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 ZG(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 pt("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(rLe,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":SE},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:s,client_id:tLe}),signal:a.signal});if(clearTimeout(c),!l.ok){let m=await l.text();throw new pt(`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=_r(Kp(),".neurolink");Fn(m)||GR(m,{recursive:!0});let f=_r(m,"anthropic-credentials.json"),h=`${f}.tmp`,v={...Fn(f)?JSON.parse(Xc(f,"utf-8")):{},type:"oauth",oauth:d,updatedAt:Date.now()};jR(h,JSON.stringify(v,null,2),{mode:384}),W8(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 pt?i:new pt(`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:Srr(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 Vre()}getAISDKModel(){return this.model}formatProviderError(e){if(e instanceof At)return new xt(`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 pt("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 Pt("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 xt(`Connection error: ${n}`,this.providerName):n.includes("500")||n.includes("502")||n.includes("503")||n.includes("504")||n.includes("server error")?new Ee(`Server error: ${n}`,this.providerName):new Ee(`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=Er(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=xrr.startSpan("neurolink.provider.streamText",{kind:xr.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":Kh(c,this.modelName||"unknown")}}),u,d;try{d=Sn({model:c,messages:a,temperature:e.temperature,maxOutputTokens:e.maxTokens,maxRetries:0,tools:i,stopWhen:nn(e.maxSteps||Lt),toolChoice:Dn(e,i,s),abortSignal:qr(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:v})=>{jr(this.neurolink?.getEventEmitter(),v),this.handleToolExecutionStorage(y,v,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 v=Vo(this.providerName,this.modelName,{input:y.inputTokens||0,output:y.outputTokens||0,total:(y.inputTokens||0)+(y.outputTokens||0)});v&&v>0&&l.setAttribute("neurolink.cost",v)}).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 aLe()||iLe(),!0}catch{return!1}}getModel(){return this.model}},wrr=XG});var uLe={};Z(uLe,{Agent:()=>inr,BedrockClient:()=>Err,BedrockRuntimeClient:()=>qre,Blob:()=>snr,Client:()=>cnr,ConverseCommand:()=>Wre,ConverseStreamCommand:()=>YG,Cron:()=>zrr,Dispatcher:()=>lnr,File:()=>onr,FlowProducer:()=>Brr,FormData:()=>nnr,GoogleAuth:()=>Irr,HTTPException:()=>Krr,Headers:()=>rnr,Hippocampus:()=>Mrr,HippocampusConfig:()=>Nrr,Hono:()=>qrr,ImageFormat:()=>EE,InvokeEndpointCommand:()=>Rrr,InvokeEndpointWithResponseStreamCommand:()=>Arr,Job:()=>Frr,ListFoundationModelsCommand:()=>Crr,MockAgent:()=>pnr,Pool:()=>anr,Queue:()=>Lrr,QueueScheduler:()=>$rr,Request:()=>enr,Response:()=>tnr,SageMakerRuntimeClient:()=>krr,TextToSpeechClient:()=>Orr,VertexAI:()=>Prr,Worker:()=>Urr,convertToHtml:()=>Hrr,cors:()=>Wrr,createClient:()=>Drr,default:()=>_rr,extractRawText:()=>Vrr,fetch:()=>Qrr,getGlobalDispatcher:()=>dnr,interceptors:()=>mnr,logger:()=>Jrr,parseBuffer:()=>jrr,request:()=>fnr,secureHeaders:()=>Zrr,selectCover:()=>Grr,setGlobalDispatcher:()=>unr,streamSSE:()=>Xrr,timeout:()=>Yrr});var _E,Gi,_rr,Err,Crr,qre,Wre,YG,EE,krr,Rrr,Arr,Irr,Prr,Orr,Mrr,Nrr,Drr,Lrr,Urr,Frr,$rr,Brr,zrr,jrr,Grr,Vrr,Hrr,qrr,Wrr,Krr,Jrr,Zrr,Xrr,Yrr,Qrr,enr,tnr,rnr,nnr,onr,snr,inr,anr,cnr,lnr,unr,dnr,pnr,mnr,fnr,Kre=_(()=>{_E={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:_E.get}):new Proxy(function(...t){return new Proxy({},{get:_E.get})},{get:_E.get,apply(t,n,o){return new Proxy({},{get:_E.get})},construct(t,n){return new Proxy({},{get:_E.get})}})}},Gi=new Proxy({},_E),_rr=Gi,{BedrockClient:Err,ListFoundationModelsCommand:Crr,BedrockRuntimeClient:qre,ConverseCommand:Wre,ConverseStreamCommand:YG,ImageFormat:EE}=Gi,{SageMakerRuntimeClient:krr,InvokeEndpointCommand:Rrr,InvokeEndpointWithResponseStreamCommand:Arr}=Gi,{GoogleAuth:Irr,VertexAI:Prr,TextToSpeechClient:Orr}=Gi,{Hippocampus:Mrr,HippocampusConfig:Nrr}=Gi,{createClient:Drr}=Gi,{Queue:Lrr,Worker:Urr,Job:Frr,QueueScheduler:$rr,FlowProducer:Brr}=Gi,{Cron:zrr}=Gi,{parseBuffer:jrr,selectCover:Grr}=Gi,{extractRawText:Vrr,convertToHtml:Hrr}=Gi,{Hono:qrr}=Gi,{cors:Wrr,HTTPException:Krr,logger:Jrr,secureHeaders:Zrr,streamSSE:Xrr,timeout:Yrr}=Gi,Qrr=globalThis.fetch,enr=globalThis.Request,tnr=globalThis.Response,rnr=globalThis.Headers,nnr=globalThis.FormData,onr=globalThis.File,snr=globalThis.Blob,inr=Gi.Agent,anr=Gi.Pool,cnr=Gi.Client,lnr=Gi.Dispatcher,unr=()=>{},dnr=()=>Gi,pnr=Gi.MockAgent,mnr={redirect:()=>r=>r,retry:()=>r=>r},fnr=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 Eb(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 Jre=_(()=>{"use strict"});var dLe={};Z(dLe,{Agent:()=>tor,BedrockClient:()=>hnr,BedrockRuntimeClient:()=>vnr,Blob:()=>eor,Client:()=>nor,ConverseCommand:()=>xnr,ConverseStreamCommand:()=>bnr,Cron:()=>Lnr,Dispatcher:()=>oor,File:()=>Qnr,FlowProducer:()=>Dnr,FormData:()=>Ynr,GoogleAuth:()=>Enr,HTTPException:()=>Gnr,Headers:()=>Xnr,Hippocampus:()=>Rnr,HippocampusConfig:()=>Anr,Hono:()=>znr,ImageFormat:()=>Tnr,InvokeEndpointCommand:()=>wnr,InvokeEndpointWithResponseStreamCommand:()=>_nr,Job:()=>Mnr,ListFoundationModelsCommand:()=>ynr,MockAgent:()=>aor,Pool:()=>ror,Queue:()=>Pnr,QueueScheduler:()=>Nnr,Request:()=>Jnr,Response:()=>Znr,SageMakerRuntimeClient:()=>Snr,TextToSpeechClient:()=>knr,VertexAI:()=>Cnr,Worker:()=>Onr,convertToHtml:()=>Bnr,cors:()=>jnr,createClient:()=>Inr,default:()=>gnr,extractRawText:()=>$nr,fetch:()=>Knr,getGlobalDispatcher:()=>ior,interceptors:()=>cor,logger:()=>Vnr,parseBuffer:()=>Unr,request:()=>lor,secureHeaders:()=>Hnr,selectCover:()=>Fnr,setGlobalDispatcher:()=>sor,streamSSE:()=>qnr,timeout:()=>Wnr});var CE,Vi,gnr,hnr,ynr,vnr,xnr,bnr,Tnr,Snr,wnr,_nr,Enr,Cnr,knr,Rnr,Anr,Inr,Pnr,Onr,Mnr,Nnr,Dnr,Lnr,Unr,Fnr,$nr,Bnr,znr,jnr,Gnr,Vnr,Hnr,qnr,Wnr,Knr,Jnr,Znr,Xnr,Ynr,Qnr,eor,tor,ror,nor,oor,sor,ior,aor,cor,lor,pLe=_(()=>{CE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:CE.get}):new Proxy(function(...t){return new Proxy({},{get:CE.get})},{get:CE.get,apply(t,n,o){return new Proxy({},{get:CE.get})},construct(t,n){return new Proxy({},{get:CE.get})}})}},Vi=new Proxy({},CE),gnr=Vi,{BedrockClient:hnr,ListFoundationModelsCommand:ynr,BedrockRuntimeClient:vnr,ConverseCommand:xnr,ConverseStreamCommand:bnr,ImageFormat:Tnr}=Vi,{SageMakerRuntimeClient:Snr,InvokeEndpointCommand:wnr,InvokeEndpointWithResponseStreamCommand:_nr}=Vi,{GoogleAuth:Enr,VertexAI:Cnr,TextToSpeechClient:knr}=Vi,{Hippocampus:Rnr,HippocampusConfig:Anr}=Vi,{createClient:Inr}=Vi,{Queue:Pnr,Worker:Onr,Job:Mnr,QueueScheduler:Nnr,FlowProducer:Dnr}=Vi,{Cron:Lnr}=Vi,{parseBuffer:Unr,selectCover:Fnr}=Vi,{extractRawText:$nr,convertToHtml:Bnr}=Vi,{Hono:znr}=Vi,{cors:jnr,HTTPException:Gnr,logger:Vnr,secureHeaders:Hnr,streamSSE:qnr,timeout:Wnr}=Vi,Knr=globalThis.fetch,Jnr=globalThis.Request,Znr=globalThis.Response,Xnr=globalThis.Headers,Ynr=globalThis.FormData,Qnr=globalThis.File,eor=globalThis.Blob,tor=Vi.Agent,ror=Vi.Pool,nor=Vi.Client,oor=Vi.Dispatcher,sor=()=>{},ior=()=>Vi,aor=Vi.MockAgent,cor={redirect:()=>r=>r,retry:()=>r=>r},lor=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 fLe={};Z(fLe,{AmazonBedrockProvider:()=>Xre});async function mLe(){return await Promise.resolve().then(()=>(pLe(),dLe))}var Zre,Xre,gLe=_(()=>{"use strict";Kre();bn();lE();Kn();on();gt();lt();_i();H();Yd();oE();Jre();qd();br();Co();Zre=ie.provider,Xre=class r extends Ct{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 qre({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 mLe(),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=Eb(n,this.providerName,this.modelName),m=await Sm(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 Zre.startActiveSpan("bedrock.generate",{kind:xr.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 Wre(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 ke(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=Vo(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 Zre.startActiveSpan("bedrock.tool.execute",{kind:xr.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=Ti(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"?EE.JPEG:i==="png"?EE.PNG:i==="gif"?EE.GIF:EE.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?za.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"),Zre.startActiveSpan("bedrock.stream",{kind:xr.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=Eb(e,this.providerName,this.modelName),i=await Sm(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||Lt,s=0,i=0,a=0,c;try{g.debug("[TRACE] streamingConversationLoop - testing first streaming call");let l=await this.prepareStreamCommand(e),u=new YG(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 ke(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 E=>{g.debug("[TRACE] streamingConversationLoop - ReadableStream start() called");try{let C="";if(m.stream){let k=[],I="";for await(let P of m.stream){if(P.contentBlockStart&&k.push({}),P.contentBlockDelta?.delta?.text){let D=P.contentBlockDelta.delta.text;I+=D,E.enqueue({content:D})}if(P.contentBlockStart?.start?.toolUse){let D=k[k.length-1];D.toolUse={name:P.contentBlockStart.start.toolUse.name||"",input:{},toolUseId:P.contentBlockStart.start.toolUse.toolUseId||`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}}if(P.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 $=P.contentBlockDelta.delta.toolUse.input;if($){if(typeof $=="string")D._inputBuffer=(D._inputBuffer||"")+$;else if(typeof $=="object"&&!Array.isArray($)){let O=D.toolUse.input||{};D.toolUse.input={...O,...$}}}}if(P.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(P.messageStop){C=P.messageStop.stopReason||"end_turn";continue}if(P.metadata?.usage){i+=P.metadata.usage.inputTokens??0,a+=P.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 P=k.flatMap(D=>D.toolUse?.name?[D.toolUse.name]:[]).join(", ");t.addEvent("stream.tool_use",{iteration:0,tool_names:P})}if(!await this.handleStreamStopReason(C,R,E,e)){t.setAttribute("gen_ai.response.stop_reason",C),E.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,E);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($=>$.toolUse?.name?[$.toolUse.name]:[]).join(", ");t.addEvent("stream.tool_use",{iteration:s,tool_names:D})}if(!await this.handleStreamStopReason(I,R,E,e)){t.setAttribute("gen_ai.response.stop_reason",I);break}}if(s>=o){t.setAttribute("gen_ai.response.stop_reason","max_iterations"),E.error(new Error("Streaming conversation exceeded maximum iterations"));return}E.close()}catch(C){g.debug("[TRACE] streamingConversationLoop - CATCH block hit in ReadableStream"),E.error(C)}}}),h=this.neurolink?.getEventEmitter(),y=this.convertToAsyncIterable(f),v=this,b,T=new Promise(E=>{b=E});return{stream:{async*[Symbol.asyncIterator](){let E=!1;try{yield*y}catch(C){throw E=!0,C}finally{let C={input:i,output:a,total:i+a};b(wm(v.providerName,v.modelName||v.getDefaultModel(),{usage:C},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0})),h&&h.emit("generation:end",{provider:v.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:C,model:v.modelName||v.getDefaultModel(),provider:v.providerName,finishReason:E?"error":c},success:!E})}}},usage:{total:0,input:0,output:0},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:T,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 YG(e);g.debug("[Observability] Bedrock streaming API request (continuation)",{model:e.modelId,messageCount:e.messages?.length||0});let o=Date.now(),s=await ke(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)`),jr(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 mLe(),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(Ur(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 pt("AWS Bedrock access denied. Check your credentials and permissions.",this.providerName);if(t.includes("ValidationException"))return new Ee(`Validation error: ${t}`,this.providerName);let n=e?.name??"",o=e?.code??"";return n==="ThrottlingException"||o==="ThrottlingException"?new Pt(`Bedrock rate limit (throttled): ${e instanceof Error?e.message:String(e)}`,"bedrock"):new Ee(`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(()=>(Kre(),uLe)),s=JSON.stringify({inputText:e}),i=new o({modelId:n,contentType:"application/json",accept:"application/json",body:s}),a=await ke(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 kE,Cb,uor,Yre,dor,por,Qre,hLe,yLe,vLe,xLe,bLe,mor,ene,TLe,tne,SLe,rne,wLe,_Le,ELe,QG=_(()=>{"use strict";uF();qd();kE=r=>r.replace(/\/+$/,""),Cb=r=>{try{return JSON.stringify(r??"")}catch{return String(r??"")}},uor=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r??{})}catch{return"{}"}},Yre=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:Cb(e.value);case"json":return Cb(e.value);case"execution-denied":return`Tool execution denied${e.reason?`: ${e.reason}`:""}`;case"error-text":return typeof e.value=="string"?e.value:Cb(e.value);case"error-json":return Cb(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 Cb(r)}},dor=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")}`},por=r=>{if(typeof r=="string")return r;if(!Array.isArray(r))return Cb(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=dor(o);s&&e.push({type:"image_url",image_url:{url:s}})}}return e.length===1&&e[0].type==="text"?e[0].text:e},Qre=r=>{let e=[];for(let t of r)switch(t.role){case"system":e.push({role:"system",content:typeof t.content=="string"?t.content:Cb(t.content)});break;case"user":e.push({role:"user",content:por(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:uor(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:Yre(o.output)})}else typeof t.content=="string"&&e.push({role:"tool",tool_call_id:t.toolCallId??"",content:t.content});break}}return e},hLe=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?Ti(i):{type:"object",properties:{}};t.push({type:"function",function:{name:n,...s.description?{description:s.description}:{},parameters:a}})}return t},yLe=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},vLe=r=>{switch(r.type){case"auto":case"none":case"required":return r.type;case"tool":return{type:"function",function:{name:r.toolName}}}},xLe=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"},bLe=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}}}}},mor=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}),ene=r=>r.response_format?.type==="json_object"&&!mor(r.messages)?{...r,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...r.messages]}:r,TLe=r=>/^(o\d|gpt-5)/i.test(r.replace(/^.*\//,"")),tne=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},SLe=async(r,e)=>{let t={text:"",toolCalls:new Map,finishReason:null,usage:void 0},n=new TextDecoder,o,i=ew({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},rne=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},wLe=()=>{let r=()=>{},e=new Promise(o=>{r=o}),t=()=>{},n=new Promise(o=>{t=o});return{usagePromise:e,finishPromise:n,resolveUsage:r,resolveFinish:t}},_Le=()=>{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})}},ELe=(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 Cl,kb=_(()=>{"use strict";Kn();on();hu();wn();H();Yu();aE();Vn();_i();Lc();Gh();QG();Cl=class extends Ct{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`${kE(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}supportsTools(){return!0}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)}let t=this.getFallbackModelName();return this.resolvedModel=t,this.refreshHandlersForModel(t),t}buildDelegatingModel(e){let t=this.getChatCompletionsURL(e),n=Ve(),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=Qre(u.prompt),m=u.responseFormat?a(xLe(u.responseFormat),e):void 0,f=ene(c(tne({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:yLe(u.tools),...u.toolChoice?{toolChoice:vLe(u.toolChoice)}:{},streaming:!1,...m?{responseFormat:m}:{}}),e)),h=Er(l(u),s,"generate"),y=qr(u.abortSignal,h?.controller.signal),v;try{v=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(f),...y?{signal:y}:{}})}finally{h?.cleanup()}if(!v.ok)throw await rne(t,f,v);let b=await v.json(),T=b.choices?.[0],w=(typeof T?.message?.content=="string"?T.message.content:"")??"",E=[];w.length>0&&E.push({type:"text",text:w});for(let I of T?.message?.tool_calls??[])E.push({type:"tool-call",toolCallId:I.id,toolName:I.function.name,input:I.function.arguments??""});let C=T?.finish_reason;return{content:E,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=Er(o,this.providerName,"stream"),i=new AbortController,a=cCe([e.abortSignal,s?.controller.signal,i.signal]).signal,c,l,u,d,m;try{c=await this.resolveModelName();let U=!e.disableTools&&this.supportsTools();l=U?e.tools||await this.getAllTools():{},u=U?hLe(l):void 0,d=bLe(Dn(e,l,U));let L=await this.buildMessagesForStream(e);m=Qre(L)}catch(U){throw s?.cleanup(),U}let f=this.getChatCompletionsURL(c),h=Ve(),y=e.maxSteps||Lt,v=this.neurolink?.getEventEmitter(),b=[],T=[],{usagePromise:w,finishPromise:E,resolveUsage:C,resolveFinish:k}=wLe(),{pushChunk:I,nextChunk:R}=_Le(),A=this.onStreamStart(c),P=this.runStreamLoop({maxSteps:y,modelId:c,url:f,fetchImpl:h,abortSignal:a,options:e,conversation:m,openAITools:u,openAIToolChoice:d,toolsRecord:l,emitter:v,toolsUsed:b,toolExecutionSummaries:T,pushChunk:I,resolveUsage:C,resolveFinish:k}),D,$=U=>{D=U};A?.onUsage&&w.then(A.onUsage).catch(()=>{}),A?.onFinish&&E.then(U=>A.onFinish?.(U,D)).catch(()=>{});let O=this.providerName,N={stream:async function*(){let U=0;try{for(;;){let L=await R();if("done"in L)break;"content"in L&&typeof L.content=="string"&&L.content.length>0&&U++,yield L}if(await P,U===0&&b.length===0){g.warn(`${O}: Stream produced no output \u2014 emitting enriched sentinel`);let L=new _s({message:"Stream produced no output"}),z=await gu(L,void 0,D);Ya(z),yield z}}catch(L){if(_s.isInstance(L)){let B=await gu(L,void 0,D);Ya(B),yield B;return}let z=await gu(L,void 0,D);throw Ya(z),yield z,L}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:this.modelName,analytics:ho.createAnalytics(this.providerName,this.modelName,{textStream:(async function*(){})(),usage:w,finishReason:E},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:()=>Zu(T.map(U=>({toolName:U.toolName,input:U.input,output:U.output,duration:U.endTime.getTime()-U.startTime.getTime()})))}),P.finally(()=>s?.cleanup()).catch(U=>{$(U)}),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:v,resolveFinish:b}=e;try{let T=null,w;for(let E=0;E<t;E++){let C=await this.streamOneStep({modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:c,openAITools:l,openAIToolChoice:u,pushChunk:y});if(T=C.finishReason,C.usage&&(w=ELe(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 v({promptTokens:w?.prompt_tokens??0,completionTokens:w?.completion_tokens??0,totalTokens:w?.total_tokens??0}),b(T??"stop"),y({done:!0}),{finishReason:T??"stop",usage:w}}catch(T){throw g.error(`${this.providerName}: Stream error`,{error:T instanceof Error?T.message:String(T)}),v({promptTokens:0,completionTokens:0,totalTokens:0}),b("error"),y({done:!0}),T}}async streamOneStep(e){let t=ene(this.adjustRequestBody(tne({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 rne(e.url,t,n);if(!n.body)throw new Error(`${this.providerName}: stream response had no body`);return SLe(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,v=o[d.name];if(s?.emit("tool:start",{toolName:d.name,toolCallId:d.id,input:f}),!v||typeof v.execute!="function")y=`Tool '${d.name}' is not registered.`,h={error:y};else try{h=await v.execute(f,{})}catch(T){y=T instanceof Error?T.message:String(T),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:Yre(h)})}let u=a.slice(-t.toolCalls.size);jr(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=`${kE(this.config.baseURL)}/models`;g.debug(`Fetching available models from: ${e}`);let t=Ve(),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 CLe={};Z(CLe,{AzureOpenAIProvider:()=>nne});var nne,kLe=_(()=>{"use strict";gt();H();Jn();Vn();Gh();kb();QG();nne=class extends Cl{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,v=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||nr(eDe()),m||nr(tDe()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=d,this.useMaxCompletionTokensOverride=v,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",y2({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 xt(`Request timed out: ${e.message}`,"azure");let t=e;if(t?.message&&typeof t.message=="string"&&t.message.includes("401"))return new pt("Invalid Azure OpenAI API key or endpoint.","azure");let n=t?.message&&typeof t.message=="string"?t.message:"Unknown error";return new Ee(`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??TLe(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function Ze(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 se(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 Qf=_(()=>{});var one,RLe=_(()=>{one=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return one=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 eg(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var aO,RE=_(()=>{aO=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 ut,Ea,ec,Rb,cO,lO,uO,dO,pO,mO,fO,gO,hO,kl=_(()=>{RE();ut=class extends Error{},Ea=class r extends ut{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 Rb({message:n,cause:aO(t)});let s=t,i=s?.error?.type;return e===400?new lO(e,s,n,o,i):e===401?new uO(e,s,n,o,i):e===403?new dO(e,s,n,o,i):e===404?new pO(e,s,n,o,i):e===409?new mO(e,s,n,o,i):e===422?new fO(e,s,n,o,i):e===429?new gO(e,s,n,o,i):e>=500?new hO(e,s,n,o,i):new r(e,s,n,o,i)}},ec=class extends Ea{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Rb=class extends Ea{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},cO=class extends Rb{constructor({message:e}={}){super({message:e??"Request timed out."})}},lO=class extends Ea{},uO=class extends Ea{},dO=class extends Ea{},pO=class extends Ea{},mO=class extends Ea{},fO=class extends Ea{},gO=class extends Ea{},hO=class extends Ea{}});function e4(r){return typeof r!="object"?{}:r??{}}function ane(r){if(!r)return!0;for(let e in r)return!1;return!0}function ILe(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var hor,ALe,sne,ine,PLe,t4,Ab=_(()=>{kl();hor=/^[a-z][a-z0-9+.-]*:/i,ALe=r=>hor.test(r),sne=r=>(sne=Array.isArray,sne(r)),ine=sne;PLe=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ut(`${r} must be an integer`);if(e<0)throw new ut(`${r} must be a positive integer`);return e},t4=r=>{try{return JSON.parse(r)}catch{return}}});var OLe,MLe=_(()=>{OLe=r=>new Promise(e=>setTimeout(e,r))});var Uy,cne=_(()=>{Uy="0.91.1"});function yor(){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 xor(){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 ULe,vor,NLe,DLe,LLe,FLe,lne=_(()=>{cne();ULe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";vor=()=>{let r=yor();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uy,"X-Stainless-OS":DLe(Deno.build.os),"X-Stainless-Arch":NLe(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":Uy,"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":Uy,"X-Stainless-OS":DLe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":NLe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=xor();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uy,"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":Uy,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};NLe=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",DLe=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"),FLe=()=>LLe??(LLe=vor())});function $Le(){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 une(...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 r4(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return une({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function yO(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 BLe(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 AE=_(()=>{});var zLe,jLe=_(()=>{zLe=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function GLe(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 ut(`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 VLe=_(()=>{kl()});function WLe(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 vO(r){let e;return(HLe??(e=new globalThis.TextEncoder,HLe=e.encode.bind(e)))(r)}function dne(r){let e;return(qLe??(e=new globalThis.TextDecoder,qLe=e.decode.bind(e)))(r)}var HLe,qLe,pne=_(()=>{});function Sor(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 KLe(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 vu,xu,tg,mne=_(()=>{Qf();pne();tg=class{constructor(){vu.set(this,void 0),xu.set(this,void 0),Ze(this,vu,new Uint8Array,"f"),Ze(this,xu,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vO(e):e;Ze(this,vu,WLe([se(this,vu,"f"),t]),"f");let n=[],o;for(;(o=Sor(se(this,vu,"f"),se(this,xu,"f")))!=null;){if(o.carriage&&se(this,xu,"f")==null){Ze(this,xu,o.index,"f");continue}if(se(this,xu,"f")!=null&&(o.index!==se(this,xu,"f")+1||o.carriage)){n.push(dne(se(this,vu,"f").subarray(0,se(this,xu,"f")-1))),Ze(this,vu,se(this,vu,"f").subarray(se(this,xu,"f")),"f"),Ze(this,xu,null,"f");continue}let s=se(this,xu,"f")!==null?o.preceding-1:o.preceding,i=dne(se(this,vu,"f").subarray(0,s));n.push(i),Ze(this,vu,se(this,vu,"f").subarray(o.index),"f"),Ze(this,xu,null,"f")}return n}flush(){return se(this,vu,"f").length?this.decode(`
|
|
1159
|
+
`):"";default:return Cb(r)}},dor=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")}`},por=r=>{if(typeof r=="string")return r;if(!Array.isArray(r))return Cb(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=dor(o);s&&e.push({type:"image_url",image_url:{url:s}})}}return e.length===1&&e[0].type==="text"?e[0].text:e},Qre=r=>{let e=[];for(let t of r)switch(t.role){case"system":e.push({role:"system",content:typeof t.content=="string"?t.content:Cb(t.content)});break;case"user":e.push({role:"user",content:por(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:uor(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:Yre(o.output)})}else typeof t.content=="string"&&e.push({role:"tool",tool_call_id:t.toolCallId??"",content:t.content});break}}return e},hLe=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?Ti(i):{type:"object",properties:{}};t.push({type:"function",function:{name:n,...s.description?{description:s.description}:{},parameters:a}})}return t},yLe=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},vLe=r=>{switch(r.type){case"auto":case"none":case"required":return r.type;case"tool":return{type:"function",function:{name:r.toolName}}}},xLe=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"},bLe=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}}}}},mor=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}),ene=r=>r.response_format?.type==="json_object"&&!mor(r.messages)?{...r,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...r.messages]}:r,TLe=r=>/^(o\d|gpt-5)/i.test(r.replace(/^.*\//,"")),tne=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},SLe=async(r,e)=>{let t={text:"",toolCalls:new Map,finishReason:null,usage:void 0},n=new TextDecoder,o,i=ew({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},rne=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},wLe=()=>{let r=()=>{},e=new Promise(o=>{r=o}),t=()=>{},n=new Promise(o=>{t=o});return{usagePromise:e,finishPromise:n,resolveUsage:r,resolveFinish:t}},_Le=()=>{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})}},ELe=(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 Cl,kb=_(()=>{"use strict";Kn();on();hu();wn();H();Yu();aE();Vn();_i();Lc();Gh();QG();Cl=class extends Ct{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`${kE(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=Ve(),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=Qre(u.prompt),m=u.responseFormat?a(xLe(u.responseFormat),e):void 0,f=ene(c(tne({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:yLe(u.tools),...u.toolChoice?{toolChoice:vLe(u.toolChoice)}:{},streaming:!1,...m?{responseFormat:m}:{}}),e)),h=Er(l(u),s,"generate"),y=qr(u.abortSignal,h?.controller.signal),v;try{v=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(f),...y?{signal:y}:{}})}finally{h?.cleanup()}if(!v.ok)throw await rne(t,f,v);let b=await v.json(),T=b.choices?.[0],w=(typeof T?.message?.content=="string"?T.message.content:"")??"",E=[];w.length>0&&E.push({type:"text",text:w});for(let I of T?.message?.tool_calls??[])E.push({type:"tool-call",toolCallId:I.id,toolName:I.function.name,input:I.function.arguments??""});let C=T?.finish_reason;return{content:E,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=Er(o,this.providerName,"stream"),i=new AbortController,a=cCe([e.abortSignal,s?.controller.signal,i.signal]).signal,c,l,u,d,m;try{c=await this.resolveModelName();let U=!e.disableTools&&this.supportsTools();l=U?e.tools||await this.getAllTools():{},u=U?hLe(l):void 0,d=bLe(Dn(e,l,U));let L=await this.buildMessagesForStream(e);m=Qre(L)}catch(U){throw s?.cleanup(),U}let f=this.getChatCompletionsURL(c),h=Ve(),y=e.maxSteps||Lt,v=this.neurolink?.getEventEmitter(),b=[],T=[],{usagePromise:w,finishPromise:E,resolveUsage:C,resolveFinish:k}=wLe(),{pushChunk:I,nextChunk:R}=_Le(),A=this.onStreamStart(c),P=this.runStreamLoop({maxSteps:y,modelId:c,url:f,fetchImpl:h,abortSignal:a,options:e,conversation:m,openAITools:u,openAIToolChoice:d,toolsRecord:l,emitter:v,toolsUsed:b,toolExecutionSummaries:T,pushChunk:I,resolveUsage:C,resolveFinish:k}),D,$=U=>{D=U};A?.onUsage&&w.then(A.onUsage).catch(()=>{}),A?.onFinish&&E.then(U=>A.onFinish?.(U,D)).catch(()=>{});let O=this.providerName,N={stream:async function*(){let U=0;try{for(;;){let L=await R();if("done"in L)break;"content"in L&&typeof L.content=="string"&&L.content.length>0&&U++,yield L}if(await P,U===0&&b.length===0){g.warn(`${O}: Stream produced no output \u2014 emitting enriched sentinel`);let L=new _s({message:"Stream produced no output"}),z=await gu(L,void 0,D);Ya(z),yield z}}catch(L){if(_s.isInstance(L)){let B=await gu(L,void 0,D);Ya(B),yield B;return}let z=await gu(L,void 0,D);throw Ya(z),yield z,L}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:c,analytics:ho.createAnalytics(this.providerName,c,{textStream:(async function*(){})(),usage:w,finishReason:E},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:()=>Zu(T.map(U=>({toolName:U.toolName,input:U.input,output:U.output,duration:U.endTime.getTime()-U.startTime.getTime()})))}),P.finally(()=>s?.cleanup()).catch(U=>{$(U)}),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:v,resolveFinish:b}=e;try{let T=null,w;for(let E=0;E<t;E++){let C=await this.streamOneStep({modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:c,openAITools:l,openAIToolChoice:u,pushChunk:y});if(T=C.finishReason,C.usage&&(w=ELe(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 v({promptTokens:w?.prompt_tokens??0,completionTokens:w?.completion_tokens??0,totalTokens:w?.total_tokens??0}),b(T??"stop"),y({done:!0}),{finishReason:T??"stop",usage:w}}catch(T){throw g.error(`${this.providerName}: Stream error`,{error:T instanceof Error?T.message:String(T)}),v({promptTokens:0,completionTokens:0,totalTokens:0}),b("error"),y({done:!0}),T}}async streamOneStep(e){let t=ene(this.adjustRequestBody(tne({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 rne(e.url,t,n);if(!n.body)throw new Error(`${this.providerName}: stream response had no body`);return SLe(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,v=o[d.name];if(s?.emit("tool:start",{toolName:d.name,toolCallId:d.id,input:f}),!v||typeof v.execute!="function")y=`Tool '${d.name}' is not registered.`,h={error:y};else try{h=await v.execute(f,{})}catch(T){y=T instanceof Error?T.message:String(T),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:Yre(h)})}let u=a.slice(-t.toolCalls.size);jr(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=`${kE(this.config.baseURL)}/models`;g.debug(`Fetching available models from: ${e}`);let t=Ve(),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 CLe={};Z(CLe,{AzureOpenAIProvider:()=>nne});var nne,kLe=_(()=>{"use strict";gt();H();Jn();Vn();Gh();kb();QG();nne=class extends Cl{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,v=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||nr(eDe()),m||nr(tDe()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=d,this.useMaxCompletionTokensOverride=v,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",y2({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 xt(`Request timed out: ${e.message}`,"azure");let t=e;if(t?.message&&typeof t.message=="string"&&t.message.includes("401"))return new pt("Invalid Azure OpenAI API key or endpoint.","azure");let n=t?.message&&typeof t.message=="string"?t.message:"Unknown error";return new Ee(`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??TLe(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function Ze(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 se(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 Qf=_(()=>{});var one,RLe=_(()=>{one=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return one=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 eg(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var aO,RE=_(()=>{aO=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 ut,Ea,ec,Rb,cO,lO,uO,dO,pO,mO,fO,gO,hO,kl=_(()=>{RE();ut=class extends Error{},Ea=class r extends ut{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 Rb({message:n,cause:aO(t)});let s=t,i=s?.error?.type;return e===400?new lO(e,s,n,o,i):e===401?new uO(e,s,n,o,i):e===403?new dO(e,s,n,o,i):e===404?new pO(e,s,n,o,i):e===409?new mO(e,s,n,o,i):e===422?new fO(e,s,n,o,i):e===429?new gO(e,s,n,o,i):e>=500?new hO(e,s,n,o,i):new r(e,s,n,o,i)}},ec=class extends Ea{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Rb=class extends Ea{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},cO=class extends Rb{constructor({message:e}={}){super({message:e??"Request timed out."})}},lO=class extends Ea{},uO=class extends Ea{},dO=class extends Ea{},pO=class extends Ea{},mO=class extends Ea{},fO=class extends Ea{},gO=class extends Ea{},hO=class extends Ea{}});function e4(r){return typeof r!="object"?{}:r??{}}function ane(r){if(!r)return!0;for(let e in r)return!1;return!0}function ILe(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var hor,ALe,sne,ine,PLe,t4,Ab=_(()=>{kl();hor=/^[a-z][a-z0-9+.-]*:/i,ALe=r=>hor.test(r),sne=r=>(sne=Array.isArray,sne(r)),ine=sne;PLe=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ut(`${r} must be an integer`);if(e<0)throw new ut(`${r} must be a positive integer`);return e},t4=r=>{try{return JSON.parse(r)}catch{return}}});var OLe,MLe=_(()=>{OLe=r=>new Promise(e=>setTimeout(e,r))});var Uy,cne=_(()=>{Uy="0.91.1"});function yor(){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 xor(){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 ULe,vor,NLe,DLe,LLe,FLe,lne=_(()=>{cne();ULe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";vor=()=>{let r=yor();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uy,"X-Stainless-OS":DLe(Deno.build.os),"X-Stainless-Arch":NLe(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":Uy,"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":Uy,"X-Stainless-OS":DLe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":NLe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=xor();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uy,"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":Uy,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};NLe=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",DLe=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"),FLe=()=>LLe??(LLe=vor())});function $Le(){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 une(...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 r4(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return une({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function yO(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 BLe(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 AE=_(()=>{});var zLe,jLe=_(()=>{zLe=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function GLe(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 ut(`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 VLe=_(()=>{kl()});function WLe(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 vO(r){let e;return(HLe??(e=new globalThis.TextEncoder,HLe=e.encode.bind(e)))(r)}function dne(r){let e;return(qLe??(e=new globalThis.TextDecoder,qLe=e.decode.bind(e)))(r)}var HLe,qLe,pne=_(()=>{});function Sor(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 KLe(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 vu,xu,tg,mne=_(()=>{Qf();pne();tg=class{constructor(){vu.set(this,void 0),xu.set(this,void 0),Ze(this,vu,new Uint8Array,"f"),Ze(this,xu,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vO(e):e;Ze(this,vu,WLe([se(this,vu,"f"),t]),"f");let n=[],o;for(;(o=Sor(se(this,vu,"f"),se(this,xu,"f")))!=null;){if(o.carriage&&se(this,xu,"f")==null){Ze(this,xu,o.index,"f");continue}if(se(this,xu,"f")!=null&&(o.index!==se(this,xu,"f")+1||o.carriage)){n.push(dne(se(this,vu,"f").subarray(0,se(this,xu,"f")-1))),Ze(this,vu,se(this,vu,"f").subarray(se(this,xu,"f")),"f"),Ze(this,xu,null,"f");continue}let s=se(this,xu,"f")!==null?o.preceding-1:o.preceding,i=dne(se(this,vu,"f").subarray(0,s));n.push(i),Ze(this,vu,se(this,vu,"f").subarray(o.index),"f"),Ze(this,xu,null,"f")}return n}flush(){return se(this,vu,"f").length?this.decode(`
|
|
1160
1160
|
`):[]}};vu=new WeakMap,xu=new WeakMap;tg.NEWLINE_CHARS=new Set([`
|
|
1161
1161
|
`,"\r"]);tg.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function xO(){}function n4(r,e,t){return!e||o4[r]>o4[t]?xO:e[r].bind(e)}function Hi(r){let e=r.logger,t=r.logLevel??"off";if(!e)return wor;let n=JLe.get(e);if(n&&n[0]===t)return n[1];let o={error:n4("error",e,t),warn:n4("warn",e,t),info:n4("info",e,t),debug:n4("debug",e,t)};return JLe.set(e,[t,o]),o}var o4,fne,wor,JLe,rg,s4=_(()=>{Ab();o4={off:0,error:200,warn:300,info:400,debug:500},fne=(r,e,t)=>{if(r){if(ILe(o4,r))return r;Hi(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(o4))}`)}};wor={error:xO,warn:xO,info:xO,debug:xO},JLe=new WeakMap;rg=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*_or(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ut("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 ut("Attempted to iterate over a response with no body");let t=new gne,n=new tg,o=yO(r.body);for await(let s of Eor(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*Eor(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"?vO(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=KLe(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}function Cor(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var bO,km,gne,hne=_(()=>{Qf();kl();AE();mne();AE();RE();Ab();pne();s4();kl();km=class r{constructor(e,t,n){this.iterator=e,bO.set(this,void 0),this.controller=t,Ze(this,bO,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?Hi(n):console;async function*i(){if(o)throw new ut("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let c of _or(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=t4(c.data)??c.data,u=l?.error?.type;throw new Ea(void 0,l,void 0,e.headers,u)}}a=!0}catch(c){if(eg(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 tg,c=yO(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 ut("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(eg(c))return;throw c}finally{a||t.abort()}}return new r(i,t,n)}[(bO=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,se(this,bO,"f")),new r(()=>o(t),this.controller,se(this,bO,"f"))]}toReadableStream(){let e=this,t;return une({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=vO(JSON.stringify(o)+`
|
|
1162
1162
|
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};gne=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(`
|
|
@@ -97,6 +97,24 @@ export declare abstract class OpenAIChatCompletionsProvider extends BaseProvider
|
|
|
97
97
|
*/
|
|
98
98
|
protected getAuthHeaders(): Record<string, string>;
|
|
99
99
|
supportsTools(): boolean;
|
|
100
|
+
/**
|
|
101
|
+
* Health-check hook — part of the documented public provider contract
|
|
102
|
+
* (`docs/provider-integration/00-architecture.md`). Default returns true
|
|
103
|
+
* when an apiKey is configured; local providers (LM Studio, llama.cpp)
|
|
104
|
+
* override this to probe the server's `/models` endpoint.
|
|
105
|
+
*/
|
|
106
|
+
validateConfiguration(): Promise<boolean>;
|
|
107
|
+
/**
|
|
108
|
+
* Snapshot of the provider's resolved configuration — part of the documented
|
|
109
|
+
* public provider contract (`docs/provider-integration/00-architecture.md`).
|
|
110
|
+
* Subclasses inherit this; override only to expose extra fields.
|
|
111
|
+
*/
|
|
112
|
+
getConfiguration(): {
|
|
113
|
+
provider: AIProviderName;
|
|
114
|
+
model: string;
|
|
115
|
+
defaultModel: string;
|
|
116
|
+
baseURL: string;
|
|
117
|
+
};
|
|
100
118
|
/**
|
|
101
119
|
* Returns a minimal V3-shaped model used by BaseProvider's `generate()`
|
|
102
120
|
* non-streaming path. Driven by the parent's `generateText`. The
|
|
@@ -126,6 +126,29 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
126
126
|
supportsTools() {
|
|
127
127
|
return true;
|
|
128
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* Health-check hook — part of the documented public provider contract
|
|
131
|
+
* (`docs/provider-integration/00-architecture.md`). Default returns true
|
|
132
|
+
* when an apiKey is configured; local providers (LM Studio, llama.cpp)
|
|
133
|
+
* override this to probe the server's `/models` endpoint.
|
|
134
|
+
*/
|
|
135
|
+
async validateConfiguration() {
|
|
136
|
+
return (typeof this.config.apiKey === "string" &&
|
|
137
|
+
this.config.apiKey.trim().length > 0);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Snapshot of the provider's resolved configuration — part of the documented
|
|
141
|
+
* public provider contract (`docs/provider-integration/00-architecture.md`).
|
|
142
|
+
* Subclasses inherit this; override only to expose extra fields.
|
|
143
|
+
*/
|
|
144
|
+
getConfiguration() {
|
|
145
|
+
return {
|
|
146
|
+
provider: this.providerName,
|
|
147
|
+
model: this.modelName,
|
|
148
|
+
defaultModel: this.getDefaultModel(),
|
|
149
|
+
baseURL: this.config.baseURL,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
129
152
|
/**
|
|
130
153
|
* Returns a minimal V3-shaped model used by BaseProvider's `generate()`
|
|
131
154
|
* non-streaming path. Driven by the parent's `generateText`. The
|
|
@@ -160,7 +183,19 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
160
183
|
catch (err) {
|
|
161
184
|
logger.warn("Model auto-discovery failed, using fallback:", err);
|
|
162
185
|
}
|
|
186
|
+
// Auto-discovery was attempted but yielded no model (local server/model
|
|
187
|
+
// not up yet, transient probe failure, …). Use the fallback for THIS
|
|
188
|
+
// call but persist NOTHING — not `resolvedModel`, and not `this.modelName`
|
|
189
|
+
// either. `refreshHandlersForModel()` sets `this.modelName = model`, which
|
|
190
|
+
// the explicit branch above would then memoize on the next call, pinning
|
|
191
|
+
// the instance to the fallback and defeating the retry. Returning the
|
|
192
|
+
// bare fallback (it is still used as the wire `modelId`) lets a later
|
|
193
|
+
// call re-probe once the server/model becomes available — matching the
|
|
194
|
+
// pre-migration local providers.
|
|
195
|
+
return this.getFallbackModelName();
|
|
163
196
|
}
|
|
197
|
+
// No auto-discovery for this provider — the fallback is stable, so memoize
|
|
198
|
+
// it (and refresh handlers so telemetry/pricing reflect the resolved name).
|
|
164
199
|
const fallback = this.getFallbackModelName();
|
|
165
200
|
this.resolvedModel = fallback;
|
|
166
201
|
this.refreshHandlersForModel(fallback);
|
|
@@ -428,8 +463,8 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
428
463
|
const result = {
|
|
429
464
|
stream: transformedStream(),
|
|
430
465
|
provider: this.providerName,
|
|
431
|
-
model:
|
|
432
|
-
analytics: streamAnalyticsCollector.createAnalytics(this.providerName,
|
|
466
|
+
model: modelId,
|
|
467
|
+
analytics: streamAnalyticsCollector.createAnalytics(this.providerName, modelId, {
|
|
433
468
|
textStream: (async function* () { })(),
|
|
434
469
|
usage: usagePromise,
|
|
435
470
|
finishReason: finishPromise,
|
|
@@ -97,6 +97,24 @@ export declare abstract class OpenAIChatCompletionsProvider extends BaseProvider
|
|
|
97
97
|
*/
|
|
98
98
|
protected getAuthHeaders(): Record<string, string>;
|
|
99
99
|
supportsTools(): boolean;
|
|
100
|
+
/**
|
|
101
|
+
* Health-check hook — part of the documented public provider contract
|
|
102
|
+
* (`docs/provider-integration/00-architecture.md`). Default returns true
|
|
103
|
+
* when an apiKey is configured; local providers (LM Studio, llama.cpp)
|
|
104
|
+
* override this to probe the server's `/models` endpoint.
|
|
105
|
+
*/
|
|
106
|
+
validateConfiguration(): Promise<boolean>;
|
|
107
|
+
/**
|
|
108
|
+
* Snapshot of the provider's resolved configuration — part of the documented
|
|
109
|
+
* public provider contract (`docs/provider-integration/00-architecture.md`).
|
|
110
|
+
* Subclasses inherit this; override only to expose extra fields.
|
|
111
|
+
*/
|
|
112
|
+
getConfiguration(): {
|
|
113
|
+
provider: AIProviderName;
|
|
114
|
+
model: string;
|
|
115
|
+
defaultModel: string;
|
|
116
|
+
baseURL: string;
|
|
117
|
+
};
|
|
100
118
|
/**
|
|
101
119
|
* Returns a minimal V3-shaped model used by BaseProvider's `generate()`
|
|
102
120
|
* non-streaming path. Driven by the parent's `generateText`. The
|
|
@@ -126,6 +126,29 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
126
126
|
supportsTools() {
|
|
127
127
|
return true;
|
|
128
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* Health-check hook — part of the documented public provider contract
|
|
131
|
+
* (`docs/provider-integration/00-architecture.md`). Default returns true
|
|
132
|
+
* when an apiKey is configured; local providers (LM Studio, llama.cpp)
|
|
133
|
+
* override this to probe the server's `/models` endpoint.
|
|
134
|
+
*/
|
|
135
|
+
async validateConfiguration() {
|
|
136
|
+
return (typeof this.config.apiKey === "string" &&
|
|
137
|
+
this.config.apiKey.trim().length > 0);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Snapshot of the provider's resolved configuration — part of the documented
|
|
141
|
+
* public provider contract (`docs/provider-integration/00-architecture.md`).
|
|
142
|
+
* Subclasses inherit this; override only to expose extra fields.
|
|
143
|
+
*/
|
|
144
|
+
getConfiguration() {
|
|
145
|
+
return {
|
|
146
|
+
provider: this.providerName,
|
|
147
|
+
model: this.modelName,
|
|
148
|
+
defaultModel: this.getDefaultModel(),
|
|
149
|
+
baseURL: this.config.baseURL,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
129
152
|
/**
|
|
130
153
|
* Returns a minimal V3-shaped model used by BaseProvider's `generate()`
|
|
131
154
|
* non-streaming path. Driven by the parent's `generateText`. The
|
|
@@ -160,7 +183,19 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
160
183
|
catch (err) {
|
|
161
184
|
logger.warn("Model auto-discovery failed, using fallback:", err);
|
|
162
185
|
}
|
|
186
|
+
// Auto-discovery was attempted but yielded no model (local server/model
|
|
187
|
+
// not up yet, transient probe failure, …). Use the fallback for THIS
|
|
188
|
+
// call but persist NOTHING — not `resolvedModel`, and not `this.modelName`
|
|
189
|
+
// either. `refreshHandlersForModel()` sets `this.modelName = model`, which
|
|
190
|
+
// the explicit branch above would then memoize on the next call, pinning
|
|
191
|
+
// the instance to the fallback and defeating the retry. Returning the
|
|
192
|
+
// bare fallback (it is still used as the wire `modelId`) lets a later
|
|
193
|
+
// call re-probe once the server/model becomes available — matching the
|
|
194
|
+
// pre-migration local providers.
|
|
195
|
+
return this.getFallbackModelName();
|
|
163
196
|
}
|
|
197
|
+
// No auto-discovery for this provider — the fallback is stable, so memoize
|
|
198
|
+
// it (and refresh handlers so telemetry/pricing reflect the resolved name).
|
|
164
199
|
const fallback = this.getFallbackModelName();
|
|
165
200
|
this.resolvedModel = fallback;
|
|
166
201
|
this.refreshHandlersForModel(fallback);
|
|
@@ -428,8 +463,8 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
|
|
|
428
463
|
const result = {
|
|
429
464
|
stream: transformedStream(),
|
|
430
465
|
provider: this.providerName,
|
|
431
|
-
model:
|
|
432
|
-
analytics: streamAnalyticsCollector.createAnalytics(this.providerName,
|
|
466
|
+
model: modelId,
|
|
467
|
+
analytics: streamAnalyticsCollector.createAnalytics(this.providerName, modelId, {
|
|
433
468
|
textStream: (async function* () { })(),
|
|
434
469
|
usage: usagePromise,
|
|
435
470
|
finishReason: finishPromise,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "9.68.
|
|
3
|
+
"version": "9.68.6",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "Universal AI Development Platform with working MCP integration, multi-provider support, voice (TTS/STT/realtime), and professional CLI. 58+ external MCP servers discoverable, multimodal file processing, RAG pipelines. Build, test, and deploy AI applications with 21+ providers: OpenAI, Anthropic, Google AI Studio, Google Vertex, AWS Bedrock, Azure OpenAI, Mistral, LiteLLM, SageMaker, Hugging Face, Ollama, OpenAI-compatible, OpenRouter, DeepSeek, NVIDIA NIM, LM Studio, llama.cpp, plus voice (OpenAI TTS, ElevenLabs, Deepgram, Azure Speech).",
|
|
6
6
|
"author": {
|