@juspay/neurolink 11.2.1 → 11.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,9 @@
1
+ ## [11.2.2](https://github.com/juspay/neurolink/compare/v11.2.1...v11.2.2) (2026-08-18)
2
+
3
+ ### Bug Fixes
4
+
5
+ - **(providers):** compose overflow and subclass 400-retry body corrections ([d001db0](https://github.com/juspay/neurolink/commit/d001db014f8d034d7bd3db3fd51bc607608acbfc))
6
+
1
7
  ## [11.2.1](https://github.com/juspay/neurolink/compare/v11.2.0...v11.2.1) (2026-08-18)
2
8
 
3
9
  ### Bug Fixes
@@ -1068,7 +1068,7 @@ ${s}
1068
1068
 
1069
1069
  Based on this analysis, provide your response.`;g.debug("[VideoAnalysis] Formatting via Claude",{userTextLength:i.length,analysisLength:s.length});let u=await Ym({model:n,system:e.systemPrompt,messages:[{role:"user",content:c}],maxOutputTokens:e.maxTokens||8192,temperature:.3,abortSignal:e.abortSignal,experimental_telemetry:this.telemetryHandler?.getTelemetryConfig(e,"generate")});a=u.text,l=Od(u.totalUsage??u.usage),g.debug("[VideoAnalysis] Claude formatting complete",{formattedLength:a.length,usage:l})}catch(c){g.warn("[VideoAnalysis] Claude formatting failed, using raw Gemini output",{error:c instanceof Error?c.message:String(c)})}return this.enhanceResult({content:a,provider:e.provider??this.providerName,model:this.modelName,usage:l},e,o)}async executeStandardGenerateFlow(e,t,n,o,s){let i=e.timeout??18e4,a=ei(i,this.providerName,"generate"),l=yv(e.abortSignal,a?.controller.signal),c=l?{...e,abortSignal:l}:e,u;try{u=await this.executeGeneration(n,o,s,c)}finally{a?.cleanup()}this.analyzeAIResponse(u),this.logGenerationComplete(u);let p=Date.now()-t,{toolsUsed:m,toolExecutions:f}=this.extractToolInformation(u),h=vv(e,f),y=this.formatEnhancedResult(u,s,m,h,e);return await this.recordPerformanceMetrics(y.usage,p),y=await this.synthesizeAIResponseIfNeeded(y,e),await this.enhanceResult(y,e,t)}async synthesizeAIResponseIfNeeded(e,t){if(!t.tts?.enabled||!t.tts?.useAiResponse)return e;let n=t.tts,o=e.content,s=n.provider??t.provider??this.providerName;if(!o||!s)return g.warn("TTS synthesis skipped despite being enabled",{provider:this.providerName,hasAiResponse:!!o,aiResponseLength:o?.length??0,hasProvider:!!s,ttsConfig:{enabled:t.tts?.enabled,useAiResponse:t.tts?.useAiResponse},reason:o?"Provider is missing":"AI response is empty or undefined"}),{...e,ttsMetadata:{attempted:!1,success:!1}};let i=Date.now(),a=this.getTimeout(t);try{let l=await zS(()=>Md.synthesize(o,s,n),a,`TTS synthesis timed out after ${a}ms for provider "${s}"`);return{...e,audio:l,ttsMetadata:{attempted:!0,success:!0,latency:Date.now()-i}}}catch(l){let c=Date.now()-i,u=this.getTTSErrorDetails(l);return this.telemetryHandler.recordTTSFailure(s,u,c),g.error("TTS synthesis failed in Mode 2 (AI response synthesis):",l),{...e,ttsMetadata:{attempted:!0,success:!1,error:u,latency:c}}}}getTTSErrorDetails(e){return e instanceof na?{code:Ht.SYNTHESIS_FAILED,message:e.message,retriable:!0}:e instanceof De?{code:e.code,message:e.message,retriable:e.retriable}:{code:Ht.SYNTHESIS_FAILED,message:e instanceof Error?e.message:String(e)}}async generateText(e){let t=e.prompt||e.input?.text;if(!t||typeof t!="string"||t.trim()==="")throw new Error("GenerateText options must include prompt or input.text as a non-empty string");let n=await this.generate(e);if(!n)throw new Error("Generation failed: No result returned");return{content:n.content||"",provider:n.provider||this.providerName,model:n.model||this.modelName,usage:n.usage||{input:0,output:0,total:0},responseTime:0,toolsUsed:n.toolsUsed||[],toolExecutions:n.toolExecutions?.map(o=>({toolName:o.toolName,executionTime:o.durationMs,success:!o.isError})),enhancedWithTools:!!(n.toolsUsed&&n.toolsUsed.length>0),analytics:n.analytics,evaluation:n.evaluation,audio:n.audio,reasoning:n.reasoning,reasoningTokens:n.reasoningTokens}}async embed(e,t){throw g.warn(`embed() called on ${this.providerName} which does not have a native implementation`,{textLength:e.length}),new Error(`Embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}async embedMany(e,t){throw g.warn(`embedMany() called on ${this.providerName} which does not have a native implementation`,{count:e.length}),new Error(`Batch embedding generation is not supported by the ${this.providerName} provider. Supported providers: openai, googleAiStudio, vertex/google, bedrock, cohere, voyage, jina. Use an embedding model like text-embedding-3-small (OpenAI), gemini-embedding-001 (Google AI), text-embedding-004 (Vertex), embed-english-v3.0 (Cohere), voyage-3 (Voyage), jina-embeddings-v3 (Jina), or amazon.titan-embed-text-v2:0 (Bedrock).`)}getDefaultEmbeddingModel(){}getToolCallRepairFn(e){if(!e?.disableToolCallRepair)return(async(...t)=>{let{createToolCallRepair:n}=await Promise.resolve().then(()=>(ez(),iee));return n()(...t)})}async getAISDKModelWithMiddleware(e={}){let t=await this.getAISDKModel();g.debug(`Retrieved base model for ${this.providerName}`,{provider:this.providerName,model:this.modelName,hasMiddlewareConfig:!!this.middlewareOptions,timestamp:Date.now()});let n=this.extractMiddlewareOptions(e);if(g.debug("Middleware extraction result",{provider:this.providerName,model:this.modelName,middlewareOptions:n}),!n)return t;try{g.debug(`Applying middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,middlewareOptions:n});let o=new HA(n),s=o.createContext(this.providerName,this.modelName,e,{sessionId:this.sessionId,userId:this.userId}),i=o.applyMiddleware(t,s,n);return g.debug(`Applied middleware to ${this.providerName} model`,{provider:this.providerName,model:this.modelName,hasMiddleware:!0}),i}catch(o){return g.warn(`Failed to apply middleware to ${this.providerName}, using base model`,{error:o instanceof Error?o.message:String(o)}),t}}extractMiddlewareOptions(e){return this.utilities.extractMiddlewareOptions(e)}isZodSchema(e){return this.utilities.isZodSchema(e)}async convertToolResult(e){return this.utilities.convertToolResult(e)}fixSchemaForOpenAIStrictMode(e){return this.utilities.fixSchemaForOpenAIStrictMode(e)}async getAllTools(){return this.toolsManager.getAllTools()}async calculateActualCost(e){return this.telemetryHandler.calculateActualCost(e)}createPermissiveZodSchema(){return this.utilities.createPermissiveZodSchema()}setSessionContext(e,t){this.sessionId=e,this.userId=t,this.toolsManager.setSessionContext(e,t)}handleProviderError(e){if(Rr(e))return e instanceof Error?e:new DOMException("The operation was aborted","AbortError");let t=this.formatProviderError(e);if(e&&typeof e=="object"&&t!==e){let n=e,o=t,s=Lw(e);if(s!==void 0&&o.statusCode===void 0&&(o.statusCode=s),typeof n.isRetryable=="boolean"&&o.isRetryable===void 0&&(o.isRetryable=n.isRetryable),o.retryAfterMs===void 0){let i=aQ(e);i!==void 0&&(o.retryAfterMs=i)}}hv(e)&&Mw(t);try{let n=mt.getSpan(dr.active());if(n){let o="provider_error",s=t?.constructor?.name??"";s==="RateLimitError"?o="rate_limit":s==="AuthenticationError"?o="auth_failure":s==="NetworkError"?o="network":s==="InvalidModelError"?o="invalid_model":s==="TimeoutError"&&(o="timeout"),n.setAttribute("error.type",o),t instanceof Error&&n.setAttribute("error.message",t.message.substring(0,500))}}catch{}return t}async executeImageGeneration(e){throw new Error(`Image generation is not supported by the ${this.providerName} provider or the selected model.`)}async executeWithTimeout(e,t){let n=this.getTimeout(t),o=ei(n,this.providerName,t.operationType||"generate");try{return o?await Promise.race([e(),new Promise((s,i)=>{o.controller.signal.addEventListener("abort",()=>{i(new al(`${this.providerName} operation timed out`,o.timeoutMs,this.providerName,t.operationType||"generate"))})})]):await e()}finally{o?.cleanup()}}validateStreamOptions(e){this.streamHandler.validateStreamOptions(e)}createTextStream(e,t){return this.streamHandler.createTextStream(e,t)}createStreamResult(e,t={}){return this.streamHandler.createStreamResult(e,t)}async createStreamAnalytics(e,t,n){return this.streamHandler.createStreamAnalytics(e,t,n)}handleCommonErrors(e){return this.utilities.handleCommonErrors(e)}setupToolExecutor(e,t){this.toolsManager.setupToolExecutor(e,t)}normalizeTextOptions(e){return this.utilities.normalizeTextOptions(e)}normalizeStreamOptions(e){return this.utilities.normalizeStreamOptions(e)}async enhanceResult(e,t,n){let o=Date.now()-n,s=e.imageOutput,i={...e};if(t.enableAnalytics)try{let a=await this.createAnalytics(e,o,t);i={...i,analytics:a,imageOutput:s}}catch(a){g.warn(`Analytics creation failed for ${this.providerName}:`,a)}if(t.enableEvaluation)try{let a=await this.createEvaluation(e,t);i={...i,evaluation:a,imageOutput:s}}catch(a){g.warn(`Evaluation creation failed for ${this.providerName}:`,a)}return s&&(i.imageOutput=s),i}async handleVideoGeneration(e,t){let{VideoProcessor:n,VideoError:o,VIDEO_ERROR_CODES:s}=await Promise.resolve().then(()=>(Jh(),fre)),{validateVideoGenerationInput:i,validateImageForVideo:a,validateDirectorModeInput:l}=await Promise.resolve().then(()=>(jh(),YDe)),{ErrorFactory:c}=await Promise.resolve().then(()=>(Tt(),Zk)),u={input:e.input||{text:e.prompt||""},output:e.output,provider:e.provider,model:e.model};if(u.input?.segments&&Array.isArray(u.input.segments)&&u.input.segments.length>0){let I=u.input.segments,A=l(u);if(!A.isValid)throw c.invalidParameters("director-mode",new Error(A.errors.map(re=>re.message).join("; ")),{errors:A.errors});if(A.warnings.length>0)for(let re of A.warnings)g.warn(`Director Mode warning: ${re}`);let{executeDirectorPipeline:M,DIRECTOR_PIPELINE_TIMEOUT_MS:F}=await Promise.resolve().then(()=>(_Fe(),wFe)),D=e.timeout??F,N=await this.executeWithTimeout(()=>M(I,u.output?.video??{},u.output?.director??{},e.region),{timeout:D,operationType:"generate"}),z=u.input.segments.map(re=>re.prompt).join(" \u2192 "),G=N.metadata?.segmentCount??u.input.segments.length,B=N.metadata?.transitionCount??Math.max(0,G-1),$=N.metadata?.duration??0,W={content:`${z} \u2014 duration: ${$}s, segments: ${G}, transitions: ${B}`,provider:"vertex",model:e.model||"veo-3.1-generate-001",usage:{input:0,output:0,total:0},video:N};return await this.enhanceResult(W,e,t)}let p=i(u);if(!p.isValid)throw c.invalidParameters("video-generation",new Error(p.errors.map(I=>I.message).join("; ")),{errors:p.errors});if(p.warnings.length>0)for(let I of p.warnings)g.warn(`Video generation warning: ${I}`);let m=e.input?.images?.[0];if(!m)throw new o({code:s.INVALID_INPUT,message:"Video generation requires an input image. Provide via input.images array.",retriable:!1,context:{field:"input.images"}});let f=15e3,h;if(typeof m=="string")if(m.startsWith("http://")||m.startsWith("https://")){g.debug("Fetching image from URL for video generation",{url:m.substring(0,100)});let I;try{I=await this.executeWithTimeout(()=>fetch(m),{timeout:f,operationType:"generate"})}catch(A){throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${A instanceof Error?A.message:"Request timed out"}`,retriable:!0,context:{url:m,timeout:f},originalError:A instanceof Error?A:void 0})}if(!I.ok)throw new o({code:s.INVALID_INPUT,message:`Failed to fetch image from URL: ${I.status} ${I.statusText}`,retriable:I.status>=500,context:{url:m,status:I.status}});h=Buffer.from(await I.arrayBuffer())}else{g.debug("Reading image from path for video generation",{path:m});let I=await Promise.resolve().then(()=>(ti(),Pl));try{h=await this.executeWithTimeout(()=>I.readFile(m),{timeout:f,operationType:"generate"})}catch(A){throw new o({code:s.INVALID_INPUT,message:`Failed to read image file: ${A instanceof Error?A.message:String(A)}`,retriable:!1,context:{path:m,timeout:f},originalError:A instanceof Error?A:void 0})}}else if(Buffer.isBuffer(m))h=m;else if(typeof m=="object"&&"data"in m){let I=m.data;if(typeof I=="string")h=Buffer.from(I,"base64");else if(Buffer.isBuffer(I))h=I;else throw new o({code:s.INVALID_INPUT,message:"ImageWithAltText.data must be a base64 string or Buffer.",retriable:!1,context:{field:"input.images[0].data",type:typeof I}})}else throw new o({code:s.INVALID_INPUT,message:"Invalid image input type. Provide Buffer, path string, URL, or ImageWithAltText.",retriable:!1,context:{field:"input.images[0]",type:typeof m}});let y=a(h);if(y)throw c.invalidParameters("video-generation",new Error(y.message),{field:"input.images[0]",validation:y});let x=e.prompt||e.input?.text||"",b=e.output?.video?.provider??"vertex";if(!n.supports(b))throw new o({code:s.PROVIDER_NOT_SUPPORTED,message:`Video provider "${b}" is not registered. Available: ${n.listProviders().join(", ")}`,retriable:!1,context:{provider:b,available:n.listProviders()}});let w=e.output?.video?.model??e.model??(b==="vertex"?"veo-3.1-generate-001":void 0);g.info("Starting video generation",{provider:b,...w?{model:w}:{},promptLength:x.length,imageSize:h.length,resolution:e.output?.video?.resolution||"720p",duration:e.output?.video?.length||6});let C=e.timeout??6e5,R=await this.executeWithTimeout(()=>n.generate(b,h,x,e.output?.video??{},e.region),{timeout:C,operationType:"generate"}),k=R.metadata?.model??w??(b==="vertex"?"veo-3.1-generate-001":"unknown");g.info("Video generation complete",{provider:b,model:k,videoSize:R.data.length,duration:R.metadata?.duration,processingTime:R.metadata?.processingTime});let P={content:x,provider:b,model:k,usage:{input:0,output:0,total:0},video:R};return await this.enhanceResult(P,e,t)}async createAnalytics(e,t,n){return this.telemetryHandler.createAnalytics(e,t,n.context)}async createEvaluation(e,t){return this.telemetryHandler.createEvaluation(e,t)}validateOptions(e){this.utilities.validateOptions(e)}getProviderInfo(){return this.utilities.getProviderInfo()}getTimeout(e){return this.utilities.getTimeout(e)}async handleToolExecutionStorage(e,t,n,o){return this.telemetryHandler.handleToolExecutionStorage(e,t,n,o)}static chunkPrompt(e,t=9e5,n=100){if(e.length<=t)return[e];let o=[],s=0;for(;s<e.length;){let i=Math.min(s+t,e.length);if(o.push(e.slice(s,i)),i>=e.length)break;let a=i-n;a<=s?s=i:s=Math.max(a,0)}return o}}});function Bhr(r){return r?.kind==="toolCall"||r?.kind==="toolResult"}function zhr(r,e,t){let n=[],o=e;for(;o<t;){if(!Bhr(r[o])){o++;continue}let s=o;for(;o<r.length&&r[o].kind==="toolCall";)o++;for(;o<r.length&&r[o].kind==="toolResult";)o++;if(o>t)break;n.push({start:s,end:o})}return n}function C_(r,e){let{availableInputTokens:t,fixedOverheadTokens:n,thresholdRatio:o=Yx,lowWaterRatio:s=Fhr,protectedTailCount:i=$hr,calibration:a=1}=e,l=a>0?a:1,c=Math.floor(t*o/l),u=Math.floor(t*s/l),p=n;for(let b of r)p+=b.tokens;if(p<=c)return{fire:!1,truncate:[],drop:[],projectedTokens:p};let m=1,f=Math.max(m,r.length-i),h=[],y=new Set;for(let b=m;b<f&&p>u;b++){let T=r[b];if(T.kind!=="toolResult"||T.previewTokens===void 0)continue;let w=T.tokens-T.previewTokens;w<=0||(h.push(b),p-=w)}if(p>u){let b=zhr(r,m,f);for(let T of b){if(p<=u)break;for(let w=T.start;w<T.end;w++){let C=r[w],R=h.includes(w)?C.previewTokens??C.tokens:C.tokens;p-=R,y.add(w)}}}let x=h.filter(b=>!y.has(b));return{fire:x.length>0||y.size>0,truncate:x,drop:[...y].sort((b,T)=>b-T),projectedTokens:p}}var Fhr,$hr,Vj=E(()=>{"use strict";us();Fhr=.6,$hr=4});function RFe(r){if(typeof r=="string")return r;if(r==null)return"";try{return JSON.stringify(r)??""}catch{return"x".repeat(2e5)}}function kFe(r,e){return Array.isArray(r.parts)&&r.parts.some(t=>t&&typeof t=="object"&&e in t)}function Ghr(r){return kFe(r,"functionResponse")}function sP(r){let{preview:e}=hi(r,{maxBytes:CFe,maxLines:jhr});return e}function qhr(r,e){return zt(RFe(r.parts),e)+4}function Vhr(r,e){return r.map(t=>{let n=qhr(t,e);if(Ghr(t)){let o=RFe(t.parts),s=o.length>CFe?zt(sP(o),e)+4:n;return{kind:"toolResult",tokens:n,...s<n?{previewTokens:s}:{}}}return kFe(t,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function Kj(r){let{contents:e,availableInputTokens:t,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:s}=r,i=Vhr(e,o),a=1;if(s&&s>0){let c=n+i.reduce((u,p)=>u+p.tokens,0);c>0&&(a=Math.min(3,Math.max(1,s/c)))}let l=C_(i,{availableInputTokens:t,fixedOverheadTokens:n,calibration:a});if(l.fire)return g.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:e.length,toolResponsesTruncated:l.truncate.length,contentsDropped:l.drop.length,projectedTokens:l.projectedTokens,calibration:a}),l}var CFe,jhr,Hj,xre=E(()=>{"use strict";fi();Rh();Vj();X();CFe=2048,jhr=60,Hj="[Earlier tool exchanges were removed to fit the context window.]"});var R_=E(()=>{"use strict";co()});function iP(r){if(!(!r?.enabled&&!r?.thinkingLevel))return{includeThoughts:!0,thinkingLevel:r.thinkingLevel??Hhr}}var Hhr,vre=E(()=>{"use strict";Hhr="high"});function Khr(r){return JSON.stringify(r,(e,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((n,o)=>(n[o]=t[o],n),{}):t)}function Jhr(r){if(Whr.test(r))return r;let e=r.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(e)||(e=`_${e}`),e.length>bre&&(e=e.slice(0,bre)),e}function Xhr(r,e){if(!e(r))return r;let t=2;for(;;){let n=`_${t}`,s=`${r.slice(0,bre-n.length)}${n}`;if(!e(s))return s;t++}}function Xh(r){if(Array.isArray(r.anyOf)||Array.isArray(r.oneOf)){let n=r.anyOf?"anyOf":"oneOf",o=r[n],s=o.filter(c=>c.type!=="null"&&c.type!=="undefined");if(s.length===1){let c=Xh({...s[0]});return c.nullable=!0,r.description&&(c.description=r.description),c}let i=s.map(c=>c.type||"unknown").join(" | "),a={type:"string"},l=r.description?`${r.description} (accepts: ${i})`:`Value as string (accepts: ${i})`;return a.description=l,o.some(c=>c.type==="null")&&(a.nullable=!0),a}let e={};for(let[n,o]of Object.entries(r))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){let s={};for(let[i,a]of Object.entries(o))a&&typeof a=="object"?s[i]=Xh(a):s[i]=a;e[n]=s}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?e[n]=o.map(s=>s&&typeof s=="object"?Xh(s):s):e[n]=Xh(o):e[n]=o;Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Xh(n))),e.not&&typeof e.not=="object"&&(e.not=Xh(e.not));for(let n of["if","then","else"])e[n]&&typeof e[n]=="object"&&(e[n]=Xh(e[n]));typeof e.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum===!0&&typeof e.minimum=="number"?(e.exclusiveMinimum=e.minimum,delete e.minimum):delete e.exclusiveMinimum),typeof e.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum===!0&&typeof e.maximum=="number"?(e.exclusiveMaximum=e.maximum,delete e.maximum):delete e.exclusiveMaximum);let t=2147483647;return typeof e.maximum=="number"&&e.maximum>t&&delete e.maximum,typeof e.minimum=="number"&&e.minimum<-t&&delete e.minimum,e}function Wj(r,e){let t=[],n=new Gd,o=[],s=[],i=new Set(e??[]),a=new Map;for(let[l,c]of Object.entries(r))try{let u=Jhr(l),p=Xhr(u,h=>i.has(h));a.set(p,l),p!==l&&s.push({from:l,to:p});let m={name:p,description:c.description||`Tool: ${p}`},f=c;if(f.parameters||c.inputSchema){let h,y=f.parameters||c.inputSchema;QA(y)?h=Rn(y,"openApi3"):typeof y=="object"?h=y:h={type:"object",properties:{}},h.jsonSchema&&typeof h.jsonSchema=="object"&&!h.type&&(h=h.jsonSchema),m.parametersJsonSchema=Xh(gn(h))}t.push(m),i.add(p),c.execute&&n.set(m.name,c.execute)}catch(u){o.push(l),g.error(`[buildNativeToolDeclarations] Failed to convert tool "${l}":`,u)}return o.length>0&&g.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),s.length>0&&g.warn(`[buildNativeToolDeclarations] ${s.length} tool name(s) sanitized for Google's function-name regex: ${s.map(l=>`"${l.from}" -> "${l.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:t}],executeMap:n,originalNameMap:a}}function Jj(r,e){if(!r)return!1;let t=new Set(e.originalNameMap.values()),n=Object.entries(r).filter(([s])=>!t.has(s));if(n.length===0)return!1;let o=Wj(Object.fromEntries(n),new Set(e.originalNameMap.keys()));e.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(let[s,i]of o.originalNameMap)e.originalNameMap.set(s,i);for(let[s,i]of o.executeMap)e.executeMap.set(s,i);return g.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([s])=>s).join(", ")}`),!0}function Tre(r,e){let t=Ea("google-ai",r.model,{temperature:r.temperature??1},"googleAiStudio.buildNativeConfig"),n={...t.temperature!==void 0&&{temperature:t.temperature},maxOutputTokens:r.maxTokens};e&&(n.tools=e),r.systemPrompt&&(n.systemInstruction=r.systemPrompt);let o=iP(r.thinkingConfig);return o&&(n.thinkingConfig=o),e||((r.responseSchema||r.wantsJsonOutput)&&(n.responseMimeType="application/json"),r.responseSchema&&(n.responseSchema=r.responseSchema)),n}function Sre(r){let e=r||cs;return Number.isFinite(e)&&e>0?Math.min(Math.floor(e),AFe):Math.min(cs,AFe)}function wre(r){switch(r){case"MAX_TOKENS":return"length";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"IMAGE_SAFETY":return"content-filter";default:return"stop"}}function _re(r,e){return e?r?`${r}
1070
1070
  ${e}`:e:r}async function IFe(r){let e=[],t=[],n=0,o=0,s=0,i=0;for await(let a of r){let l=a,p=l.candidates?.[0]?.content;p&&Array.isArray(p.parts)&&e.push(...p.parts),a.functionCalls&&t.push(...a.functionCalls);let m=l.usageMetadata;m&&(n=Math.max(n,m.promptTokenCount||0),o=Math.max(o,m.candidatesTokenCount||0),s=Math.max(s,m.cachedContentTokenCount||0),i=Math.max(i,m.thoughtsTokenCount||0))}return{rawResponseParts:e,stepFunctionCalls:t,inputTokens:n,outputTokens:o,cacheReadTokens:s,reasoningTokens:i}}function Xj(){let r=[],e=!1,t,n=null;function o(){if(n){let u=n;n=null,u()}}function s(u){e||(r.push({content:u}),o())}function i(){e=!0,o()}function a(u){e=!0,t=u,o()}let l=0;async function*c(){try{for(;;)if(l<r.length)yield r[l++],l>1024&&l*2>=r.length&&(r.splice(0,l),l=0);else if(e){if(t!==void 0)throw t instanceof Error?t:new Error(String(t));return}else await new Promise(u=>{n=u})}finally{e=!0,r.length=0,n?.()}}return{push:s,close:i,error:a,iterable:c()}}async function PFe(r,e){let t=[],n=[],o=0,s=0,i=0,a=0;for await(let l of r){let c=l,m=c.candidates?.[0]?.content;if(m&&Array.isArray(m.parts))for(let h of m.parts)t.push(h),typeof h.text=="string"&&h.text.length>0&&e.push(h.text);l.functionCalls&&n.push(...l.functionCalls);let f=c.usageMetadata;f&&(o=Math.max(o,f.promptTokenCount||0),s=Math.max(s,f.candidatesTokenCount||0),i=Math.max(i,f.cachedContentTokenCount||0),a=Math.max(a,f.thoughtsTokenCount||0))}return{rawResponseParts:t,stepFunctionCalls:n,inputTokens:o,outputTokens:s,cacheReadTokens:i,reasoningTokens:a}}function k_(r){for(let e=r.length-1;e>=0;e--){let t=r[e];if(t!=null&&typeof t=="object"&&"thoughtSignature"in t&&typeof t.thoughtSignature=="string")return t.thoughtSignature}}function Ere(r){return r.filter(e=>typeof e.text=="string").map(e=>e.text).join("")}async function Cre(r,e,t,n,o,s){let i=[],a=l=>s?.originalNameMap?.get(l)??l;for(let l of e){let c=a(l.name);o.push({toolName:c,args:l.args});let u=n.get(l.name);if(u&&u.count>=Kn){g.warn(`${r} Tool "${c}" has exceeded retry limit (${Kn}), skipping execution`);let m={error:`TOOL_PERMANENTLY_FAILED: The tool "${c}" has failed ${u.count} times and will not be retried. Last error: ${u.lastError}. Please proceed without using this tool or inform the user that this functionality is unavailable.`,status:"permanently_failed",do_not_retry:!0};i.push({functionResponse:{name:l.name,response:m}}),s?.toolExecutions?.push({name:c,input:l.args,output:m});continue}let p=t.get(l.name);if(!p&&s?.declarations&&sI(s.liveTools,c)?.execute){Jj(s.liveTools,s.declarations),n.delete(l.name);for(let[f,h]of s.declarations.originalNameMap)if(h===c){p=t.get(f);break}p&&g.info(`${r} Tool "${c}" resolved mid-turn via discovery \u2014 executing.`)}if(p)try{let m={toolCallId:`${l.name}-${$n()}`,messages:[],abortSignal:s?.abortSignal},f=await p(l.args,m);i.push({functionResponse:{name:l.name,response:{result:f}}}),s?.toolExecutions?.push({name:c,input:l.args,output:f})}catch(m){let f=m instanceof Error?m.message:"Unknown error",h=n.get(l.name)||{count:0,lastError:""};h.count++,h.lastError=f,n.set(l.name,h),g.warn(`${r} Tool "${c}" failed (attempt ${h.count}/${Kn}): ${f}`);let y=h.count>=Kn,x={error:y?`TOOL_PERMANENTLY_FAILED: The tool "${c}" has failed ${h.count} times with error: ${f}. This tool will not be retried. Please proceed without using this tool or inform the user that this functionality is unavailable.`:`TOOL_EXECUTION_ERROR: ${f}. Retry attempt ${h.count}/${Kn}.`,status:y?"permanently_failed":"failed",do_not_retry:y,retry_count:h.count,max_retries:Kn};i.push({functionResponse:{name:l.name,response:x}}),s?.toolExecutions?.push({name:c,input:l.args,output:x})}else{let m={error:`TOOL_NOT_FOUND: The tool "${c}" does not exist. Do not attempt to call this tool again.`,status:"permanently_failed",do_not_retry:!0};i.push({functionResponse:{name:l.name,response:m}}),s?.toolExecutions?.push({name:c,input:l.args,output:m})}}return i}function Rre(r,e,t,n,o){return e>=t&&!n?(g.warn(`${r} Tool call loop terminated after reaching maxSteps (${t}). Model was still calling tools. Using accumulated text from last step.`),o||Tg(t,0)):n}function eu(r){if(!r)return!1;let e=r;return e.name==="AbortError"||typeof e.message=="string"&&/abort/i.test(e.message)||typeof DOMException<"u"&&r instanceof DOMException&&e.code===20}function Tg(r,e){return`${e>0?`I gathered information across ${e} tool call${e===1?"":"s"} but `:"I "}reached the ${r}-step limit for a single turn before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function tu(r){return`${r>0?`I gathered information across ${r} tool call${r===1?"":"s"} but `:"I "}had to stop because the gathered material filled this turn's context window before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function MFe(r){let e=Math.max(0,Math.round(r/1e3)),t=Math.floor(e/60),n=e%60;return t>0?`${t}m ${n}s`:`${n}s`}function OFe(r,e){let t=e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping;`:"";return`I had to stop after ${MFe(r)} \u2014 this turn hit its processing time limit.${t} ask me to continue and I'll pick up from there.`}function NFe(r,e){let t=e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping;`:"";return`I had to stop because this turn made no progress for ${MFe(r)} \u2014 a tool or model call appears to be stuck.${t} ask me to continue and I'll pick up from there.`}function LFe(r){return`This turn was stopped before I could finish.${r>0?` I completed ${r} tool call${r===1?"":"s"} before stopping.`:""}`}function aP(r){return"NOTE: processing time for this turn is nearly up. Consolidate what you have and "+(r?"call final_result with your best answer now.":"provide your final answer now.")}function lP(r){return r.timedOut?"time-limit":r.stalled?"stalled":r.wasAborted?"aborted":r.contextCappedWithoutAnswer?"context-cap":r.cappedWithoutAnswer?"step-cap":r.finishReason==="error"?"provider-error":"completed"}function cP(r){let e=Date.now(),t=u=>u!==void 0&&Number.isFinite(u)&&u>0,n=t(r.turnTimeoutMs)?r.turnTimeoutMs:t(r.defaultTurnTimeoutMs)?r.defaultTurnTimeoutMs:void 0,o=t(r.turnTimeoutMs)?r.wrapupTimeLeadMs??UA:void 0,s=!1,i=!1,a=e,l,c;if(n!==void 0&&(l=setTimeout(()=>{s=!0,r.onDeadline("timeout")},n),l.unref?.()),t(r.stallTimeoutMs)){let u=r.stallTimeoutMs,p=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);c=setInterval(()=>{!i&&!s&&Date.now()-a>=u&&(i=!0,r.onDeadline("stall"))},p),c.unref?.()}return{get timedOut(){return s},get stalled(){return i},get expired(){return s||i},get turnTimeoutMs(){return n},elapsedMs(){return Date.now()-e},noteProgress(){a=Date.now()},shouldNudgeWrapup(){if(n===void 0||o===void 0)return!1;let u=n-(Date.now()-e);return u>0&&u<=o},dispose(){l&&clearTimeout(l),c&&clearInterval(c)}}}function Yh(r,e=Yx){let t=Math.floor(r*e),n=0,o=0;return{get thresholdTokens(){return t},get projectedNextPromptTokens(){return n+o},noteUsage(s,i){s>0&&(n=s,o=Math.max(0,i))},noteAppendedChars(s){s>0&&(o+=Math.ceil(s/4))},resetAfterReclaim(){n=0,o=0},shouldStop(){return n>0&&n+o>=t}}}function kre(r,e,t){r.push({role:"model",parts:e.length>0?e:t.map(n=>({functionCall:n}))})}function Are(r){let e=Rn(r,"openApi3"),t=gn(e);return t.$schema&&delete t.$schema,mi(t)}function A_(r,e){if(!e||e.length===0)return;let t=new Map,n=[],o=0,s=a=>`${o}:${a??"undefined"}`,i=a=>{let l=s(a),c=t.get(l);if(c)return c;let u={type:"tool_step",callParts:[],resultParts:[]};return t.set(l,u),n.push(u),u};for(let a of e){if(a.role==="tool_call"){let u=i(a.metadata?.stepIndex),p={functionCall:{name:a.tool||"unknown",args:a.args||{}}};a.metadata?.thoughtSignature&&(p.thoughtSignature=a.metadata.thoughtSignature),u.callParts.push(p);continue}if(a.role==="tool_result"){let u=i(a.metadata?.stepIndex),p;try{p=a.content!==void 0&&a.content!==null?{result:JSON.parse(a.content)}:{result:"success"}}catch{p={result:a.content??"success"}}u.resultParts.push({functionResponse:{name:a.tool||"unknown",response:p}});continue}let l=a.role==="assistant"?"model":a.role;if(l!=="user"&&l!=="model"||!a.content||a.content.trim().length===0)continue;o++;let c={text:a.content};a.metadata?.thoughtSignature&&(c.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:l,parts:[c]})}for(let a of n){if(a.type==="regular"){r.push({role:a.role,parts:a.parts});continue}if(a.callParts.length===0){a.resultParts.length>0&&g.debug("[GoogleNativeGemini3] Dropping orphan tool_result segment with no matching tool_call rows",{resultCount:a.resultParts.length});continue}r.push({role:"model",parts:a.callParts}),a.resultParts.length>0&&r.push({role:"user",parts:a.resultParts})}}async function Yj(r,e,t="[GeminiNative]"){if(!(!e||e.length===0))for(let n of e){let o=n.filename.split(/[\\/]/).pop()??n.filename,s=o.lastIndexOf("."),i=s>0?o.slice(s):".bin",a=await Tj(n.buffer,n.mimeType,i);if(DI(a.mimeType)){g.warn(`${t} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}r.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),g.debug(`${t} Added native audio part for ${o} (${a.mimeType})`)}}async function Ire(r,e,t="[GeminiNative]"){let o=[{text:typeof e=="string"?e:r?.text??""}];if(r?.pdfFiles&&r.pdfFiles.length>0){g.debug(`${t} Processing ${r.pdfFiles.length} PDF(s)`);for(let s of r.pdfFiles){let i;typeof s=="string"?vs(s)?i=bs(s):i=Buffer.from(s,"base64"):i=s,o.push({inlineData:{mimeType:"application/pdf",data:i.toString("base64")}})}}if(r?.images&&r.images.length>0){g.debug(`${t} Processing ${r.images.length} image(s)`);for(let s of r.images){let i=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s,a,l="image/jpeg";if(typeof i=="string")if(vs(i)){a=bs(i);let c=kv(i).toLowerCase();c===".png"?l="image/png":c===".gif"?l="image/gif":c===".webp"&&(l="image/webp")}else if(i.startsWith("data:")){let c=i.match(/^data:([^;]+);base64,(.+)$/);if(c)l=c[1],a=Buffer.from(c[2],"base64");else continue}else if(i.startsWith("http://")||i.startsWith("https://"))try{let c=await fetch(i);if(!c.ok){g.warn(`${t} Image fetch failed: ${c.status} ${c.statusText}, skipping`,{url:i});continue}let u=await c.arrayBuffer();a=Buffer.from(u);let p=c.headers.get("content-type");p&&p.startsWith("image/")&&(l=p.split(";")[0])}catch(c){g.warn(`${t} Image URL fetch threw, skipping: ${c instanceof Error?c.message:String(c)}`,{url:i});continue}else a=Buffer.from(i,"base64");else a=i;a&&o.push({inlineData:{mimeType:l,data:a.toString("base64")}})}}return await Yj(o,r?.nativeAudioFiles,t),o}var Gd,Whr,bre,AFe,Pre=E(()=>{"use strict";wa();Bs();An();us();$te();X();ig();cl();vre();zw();Gd=class extends Map{resultCache=new Map;get(e){let t=super.get(e);if(!t)return t;let n=this.resultCache;return async(s,i)=>{let a=`${e}::${Khr(s)}`;if(n.has(a))return g.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),n.get(a);let l=await t(s,i);return n.set(a,l),l}}},Whr=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,bre=128;AFe=100});var Mre=E(()=>{"use strict";Pre()});function Yhr(r,e){try{let[t,n]=e.split("/"),o=parseInt(n,10);if(isNaN(o)||o<0||o>32)return!1;let s=c=>{let u=c.split(".").map(Number);return(u[0]<<24)+(u[1]<<16)+(u[2]<<8)+u[3]},i=s(r),a=s(t),l=-1<<32-o>>>0;return(i&l)===(a&l)}catch{return!1}}function DFe(r,e){let t=e||process.env.NO_PROXY||process.env.no_proxy;if(!t)return!1;try{let n=new URL(r),o=n.hostname.toLowerCase(),s=n.port||(n.protocol==="https:"?"443":"80"),i=t.split(",").map(a=>a.trim()).filter(Boolean);for(let a of i){let l=a.toLowerCase();if(l==="*")return!0;if(l.startsWith(".")){let c=l.slice(1);if(o.endsWith(c)||o===c)return!0}else if(l.includes(":")){let[c,u]=l.split(":");if(o===c&&s===u)return!0}else if(l.includes("/")){if(/^\d{1,3}(\.\d{1,3}){3}$/.test(o)&&Yhr(o,l))return!0}else if(o===l)return!0}return!1}catch(n){return g.warn("[Proxy] Error in NO_PROXY bypass logic",{targetUrl:r,error:n}),!1}}var UFe=E(()=>{"use strict";X()});var Zj,Ore=E(()=>{"use strict";Zj=new Set(["ECONNRESET","ETIMEDOUT","ECONNREFUSED","EPIPE","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"])});async function Zhr(){try{return(await Promise.resolve().then(()=>(bg(),tre))).getLangfuseContext?.()}catch{return}}function Qhr(r,e){let t=new Headers(r instanceof Request?r.headers:void 0);if(e?.headers){let n=new Headers(e.headers);for(let[o,s]of n.entries())t.set(o,s)}return t}async function $Fe(r,e){let t={};px.inject(dr.active(),t);let n=await Zhr();if(n?.sessionId&&(t["x-neurolink-session-id"]=n.sessionId),n?.userId&&(t["x-neurolink-user-id"]=n.userId),n?.conversationId&&(t["x-neurolink-conversation-id"]=n.conversationId),Object.keys(t).length===0)return e??{};let o=Qhr(r,e);for(let[s,i]of Object.entries(t))o.has(s)||o.set(s,i);return{...e,headers:o}}function tyr(r){try{let e=typeof r=="string"?r:r instanceof URL?r.href:r.url;return new URL(e).hostname}catch{return"[unknown]"}}function ryr(r){let e=r;for(let t=0;t<5&&e;t++){let n=e;if(n.code&&Zj.has(n.code)||n.message?.includes("socket hang up")||n.message?.includes("network socket disconnected")||n.message?.includes("other side closed"))return!0;e=n.cause}return!1}async function BFe(r,e,t=3,n=500){let o=tyr(r);return eyr.startActiveSpan("neurolink.http.fetchWithRetry",async s=>{s.setAttribute("http.request.max_retries",t),s.setAttribute("http.request.hostname",o),s.setAttribute("http.request.method",e?.method||"GET");let i=0;try{for(let a=0;a<=t;a++){i=a+1;try{let l=await fetch(r,e);return s.setAttribute("http.request.total_attempts",i),s.setAttribute("http.response.status_code",l.status),s.setStatus({code:$e.OK}),l}catch(l){let c=ryr(l),u=l;if(!c||a===t)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:$e.ERROR,message:u?.message||u?.code||"fetchWithRetry final failure"}),s.recordException(l instanceof Error?l:new Error(String(l))),l;let p=n*Math.pow(2,a);s.addEvent("http.request.retry",{"retry.attempt":a+1,"retry.delay_ms":p,"retry.error":(u?.code||u?.message||String(l)).slice(0,256)}),g.debug(`[fetchWithRetry] Transient error (${u?.code||u?.message}), retrying in ${p}ms (attempt ${a+1}/${t})`),await new Promise(m=>setTimeout(m,p))}}throw new Error("fetchWithRetry exhausted")}finally{s.end()}})}function zFe(r){if(!r)return{parsed:null,size:0,type:"empty"};if(typeof r=="string")try{return{parsed:JSON.parse(r),size:r.length,type:"json"}}catch{return{parsed:r,size:r.length,type:"text"}}return r instanceof ArrayBuffer?{parsed:"[ArrayBuffer]",size:r.byteLength,type:"arraybuffer"}:r instanceof Uint8Array?{parsed:"[Uint8Array]",size:r.length,type:"uint8array"}:{parsed:"[Stream]",size:-1,type:"stream"}}async function Nre(r){let e={};r.headers.forEach((t,n)=>{e[n]=nyr.has(n.toLowerCase())?`${t.substring(0,4)}***`:t});try{let n=await r.clone().text();try{return{parsed:JSON.parse(n),size:n.length,type:"json",headers:e}}catch{return{parsed:n,size:n.length,type:"text",headers:e}}}catch{return{parsed:"[unable to read body]",size:-1,type:"error",headers:e}}}function oyr(r){try{let e=new URL(r),t={protocol:e.protocol,hostname:e.hostname,port:parseInt(e.port)||FFe(e.protocol),cleanUrl:`${e.protocol}//${e.hostname}:${e.port||FFe(e.protocol)}`};return e.username&&e.password&&(t.auth={username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}),t}catch(e){let t;try{let n=new URL(r);n.username="",n.password="",t=n.toString()}catch{t="[invalid-url]"}throw g.error("[Proxy] Failed to parse proxy URL",{proxyUrl:t,error:e}),new Error(`Invalid proxy URL: ${t}`,{cause:e})}}function FFe(r){switch(r){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function syr(r){if(DFe(r))return g.debug("[Proxy] Bypassing proxy due to NO_PROXY",{targetUrl:r}),null;try{let e=new URL(r),t=process.env.HTTPS_PROXY||process.env.https_proxy,n=process.env.HTTP_PROXY||process.env.http_proxy,o=process.env.ALL_PROXY||process.env.all_proxy,s=process.env.SOCKS_PROXY||process.env.socks_proxy;return e.protocol==="https:"&&t?t:e.protocol==="http:"&&n?n:o||s||null}catch(e){return g.warn("[Proxy] Error selecting proxy URL",{targetUrl:r,error:e}),null}}async function iyr(r){let e=oyr(r);switch(g.debug("[Proxy] Creating proxy agent",{protocol:e.protocol,hostname:e.hostname,port:e.port,hasAuth:!!e.auth}),e.protocol){case"http:":case"https:":{let{ProxyAgent:t}=await Promise.resolve().then(()=>(Ev(),cee));return new t(r)}case"socks4:":case"socks5:":throw new Error("SOCKS proxy support requires 'proxy-agent' package. Install it with: npm install proxy-agent");default:throw new Error(`Unsupported proxy protocol: ${e.protocol}`)}}function Dl(r){return GFe(r)??"NOT_SET"}function jFe(r){return typeof r=="string"?r:r instanceof URL?r.href:r.url}function ayr(){return async(r,e)=>{let t=await $Fe(r,e),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=jFe(r);if(g.shouldLog("debug")){let{size:i,type:a}=zFe(t?.body);g.debug("[Observability] HTTP request to LLM provider",{requestId:n,url:s,method:t?.method||"POST",bodySize:i,bodyType:a})}try{let i=await BFe(r,t);if(g.shouldLog("debug")){let{parsed:a,size:l,type:c,headers:u}=await Nre(i);g.debug("[Observability] HTTP response from LLM provider",{requestId:n,url:s,status:i.status,statusText:i.statusText,durationMs:Date.now()-o,contentLength:l,hasContent:!!a,bodyType:c,responseHeaders:u})}return i}catch(i){throw g.debug("[Observability] HTTP request failed",{requestId:n,url:s,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-o}),i}}}async function lyr(r,e,t){let{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=t;e=await $Fe(r,e);let l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=jFe(r);if(g.shouldLog("debug")){let{size:f,type:h}=zFe(e?.body);g.debug("[Observability] HTTP request to LLM provider",{requestId:l,url:u,method:e?.method||"POST",bodySize:f,bodyType:h})}g.debug("[Proxy Fetch] ENHANCED REQUEST START",{requestId:l,targetUrl:u,timestamp:new Date().toISOString(),httpProxy:Dl(o),httpsProxy:Dl(n),allProxy:Dl(s),socksProxy:Dl(i),noProxy:a||"NOT_SET",initMethod:e?.method||"GET"});let p=r instanceof Request?r.clone():null;try{let f=syr(u);if(f){let h=new URL(u);g.debug("[Proxy Fetch] \u{1F517} ENHANCED URL ANALYSIS",{requestId:l,targetUrl:u,urlHostname:h.hostname,urlProtocol:h.protocol,urlPort:h.port,selectedProxyUrl:Dl(f),timestamp:new Date().toISOString()}),g.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:Dl(f),targetHostname:h.hostname,targetProtocol:h.protocol,aboutToCreateProxyAgent:!0,timestamp:new Date().toISOString()});let y=globalThis;y.__NL_PROXY_AGENT_CACHE__||(y.__NL_PROXY_AGENT_CACHE__=new Map);let x=y.__NL_PROXY_AGENT_CACHE__,b=b2("sha256").update(GFe(f)??f).digest("hex"),T=x.get(b)||await iyr(f);x.set(b,T),g.debug("[Proxy Fetch] \u2705 ENHANCED PROXY AGENT CREATED",{requestId:l,hasDispatcher:!!T,dispatcherType:typeof T,dispatcherConstructor:T?.constructor?.name||"unknown",timestamp:new Date().toISOString()});let w,C={...e};r instanceof Request?(w=r.url,C={method:r.method,headers:r.headers,body:r.body,...e}):w=r;let k=await(await Promise.resolve().then(()=>(Ev(),cee))).fetch(w,{...C,dispatcher:T});if(g.shouldLog("debug")){let{parsed:P,size:I,type:A,headers:M}=await Nre(k);g.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:k?.status,statusText:k?.statusText,durationMs:Date.now()-c,contentLength:I,hasContent:!!P,bodyType:A,proxied:!0,responseHeaders:M})}return g.debug("[Proxy Fetch] ENHANCED PROXY SUCCESS",{requestId:l,responseStatus:k?.status,responseOk:k?.ok,proxyUsed:!0,timestamp:new Date().toISOString()}),k}}catch(f){let h=f instanceof Error?f.message:String(f);g.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:h,durationMs:Date.now()-c}),g.debug("[Proxy Fetch] ENHANCED ERROR ANALYSIS",{requestId:l,error:h,errorType:f instanceof Error?f.constructor.name:typeof f,willFallback:!0,timestamp:new Date().toISOString()}),g.warn(`[Proxy Fetch] Enhanced proxy failed (${h}), falling back to direct connection`)}g.debug("[Proxy Fetch] ENHANCED FALLBACK TO STANDARD FETCH",{requestId:l,fallbackReason:"No proxy configured or proxy failed",timestamp:new Date().toISOString()});let m=r instanceof Request?p??r:r;try{let f=await BFe(m,e);if(g.shouldLog("debug")){let{parsed:h,size:y,type:x,headers:b}=await Nre(f);g.debug("[Observability] HTTP response from LLM provider",{requestId:l,url:u,status:f.status,statusText:f.statusText,durationMs:Date.now()-c,contentLength:y,hasContent:!!h,bodyType:x,proxied:!1,responseHeaders:b})}return f}catch(f){let h=f instanceof Error?f.message:String(f);throw g.debug("[Observability] HTTP request failed",{requestId:l,url:u,error:h,durationMs:Date.now()-c}),f}}function cyr(r){return async(e,t)=>lyr(e,t,r)}function yt(){let r=process.env.HTTPS_PROXY||process.env.https_proxy,e=process.env.HTTP_PROXY||process.env.http_proxy,t=process.env.ALL_PROXY||process.env.all_proxy,n=process.env.SOCKS_PROXY||process.env.socks_proxy,o=process.env.NO_PROXY||process.env.no_proxy,s={httpsProxy:r,httpProxy:e,allProxy:t,socksProxy:n,noProxy:o};if(g.shouldLog("debug")){let i=Object.keys(process.env).filter(a=>a.toLowerCase().includes("proxy")).reduce((a,l)=>{let c=process.env[l]||"NOT_SET";return a[l]=l.toLowerCase()==="no_proxy"?c:Dl(c),a},{});g.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:Dl(e),httpsProxy:Dl(r),allProxy:Dl(t),socksProxy:Dl(n),noProxy:o||"NOT_SET",allProxyRelatedEnvVars:i,message:"Enhanced proxy environment detection \u2014 credentials redacted"})}return!r&&!e&&!t&&!n?(g.debug("[Proxy Fetch] No proxy environment variables found - using standard fetch"),ayr()):(g.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),g.debug(`[Proxy Fetch] HTTP_PROXY: ${Dl(e)}`),g.debug(`[Proxy Fetch] HTTPS_PROXY: ${Dl(r)}`),g.debug(`[Proxy Fetch] ALL_PROXY: ${Dl(t)}`),g.debug(`[Proxy Fetch] SOCKS_PROXY: ${Dl(n)}`),g.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),cyr(s))}function GFe(r){if(!r)return null;try{let e=new URL(r);return(e.username||e.password)&&(e.username="***",e.password="***"),e.toString()}catch{return"[invalid-url]"}}var eyr,nyr,io=E(()=>{"use strict";X();yr();Lr();UFe();wa();Ore();eyr=Oe.http;nyr=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"])});async function I_(r,e){let n=(await Promise.resolve().then(()=>(hw(),fw))).GoogleGenAI;if(!n)throw new De({code:it.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});let o=n;return new o({apiKey:r,httpOptions:{fetch:yt(),...e?{baseUrl:e}:{}}})}function qFe(r,e,t){let n=Kj({contents:r,availableInputTokens:gi("googleAiStudio",e),provider:"googleAiStudio",...t?{observedPromptTokens:t}:{}});if(!n)return!1;let o=new Set(n.drop),s=new Set(n.truncate),i=[];for(let a=0;a<r.length;a++){if(o.has(a))continue;let l=r[a];if(s.has(a)&&Array.isArray(l.parts)){i.push({...l,parts:l.parts.map(c=>{let u=c;if(!u.functionResponse)return c;let p=JSON.stringify(u.functionResponse.response)??"";return p.length<=2048?c:{functionResponse:{name:u.functionResponse.name,response:{result:sP(p)}}}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",parts:[{text:Hj}]})}return r.length=0,r.push(...i),!0}var Lre,VFe=E(()=>{"use strict";Qc();us();$I();lc();It();Tt();X();JB();xre();Ld();Il();R_();fi();jp();tI();Mre();io();Lre=class extends so{credentials;constructor(e,t,n){super(e,"google-ai",t),this.credentials=n,g.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new De({code:it.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof al)return new dn(e.message,this.providerName);let t=e,n=typeof t?.message=="string"?t.message:"Unknown error",o=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")||o===401?new At("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):n.includes("RATE_LIMIT_EXCEEDED")||n.includes("rate limit")||n.includes("429")||o===429?new Yr("Google AI rate limit exceeded. Please try again later.",this.providerName):o===404||o===void 0&&(n.includes("model not found")||n.includes("Model not found"))?new wr(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):n.includes("ECONNRESET")||n.includes("ENOTFOUND")||n.includes("ETIMEDOUT")||n.includes("ECONNREFUSED")||n.includes("network")||n.includes("connection")?new dn(`Connection error: ${n}`,this.providerName):n.includes("500")||n.includes("502")||n.includes("503")||n.includes("504")||n.includes("server error")||n.includes("Internal Server Error")||o&&o>=500&&o<600?new pt(`Google AI server error: ${n}. Please try again later.`,this.providerName):new pt(`Google AI error: ${n}`,this.providerName)}async executeImageGeneration(e){await Nv(e.input);let t=e.prompt||e.input?.text||"",n=e.model||this.modelName,o=Date.now(),s=this.getApiKey();g.info("\u{1F3A8} Starting Google AI Studio image generation",{model:n,prompt:t.substring(0,100),provider:this.providerName});let i;try{i=await I_(s,this.getBaseURL())}catch{throw new At("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{let a=await Promise.all((e.input?.images||[]).map(async m=>{if(typeof m=="object"&&"url"in m){let y=m.url;if(y.startsWith("http")){let T=await fetch(y);if(!T.ok)throw new Error(`Failed to fetch image from ${y}: ${T.status} ${T.statusText}`);let w=await T.arrayBuffer(),C=Buffer.from(w),R=this.detectImageType(C);return g.debug(`Downloaded and detected image MIME type: ${R}`),{inlineData:{mimeType:R,data:C.toString("base64")}}}let x=Buffer.from(y,"base64");return{inlineData:{mimeType:this.detectImageType(x),data:x.toString("base64")}}}if(typeof m=="string"&&m.startsWith("http")){let y=await fetch(m);if(!y.ok)throw new Error(`Failed to fetch image from ${m}: ${y.status} ${y.statusText}`);let x=await y.arrayBuffer(),b=Buffer.from(x),T=this.detectImageType(b);return g.debug(`Downloaded and detected image MIME type: ${T}`),{inlineData:{mimeType:T,data:b.toString("base64")}}}let f=Buffer.isBuffer(m)?m:typeof m=="string"?Buffer.from(m,"base64"):Buffer.from(""),h=this.detectImageType(f);return g.debug(`Detected image MIME type: ${h}`),{inlineData:{mimeType:h,data:f.toString("base64")}}})),l=[{role:"user",parts:[{text:t},...a]}],c={responseModalities:["IMAGE","TEXT"]};g.debug("Starting image generation request",{model:n,contentParts:l[0].parts.length,responseModalities:c.responseModalities});let u=null,p="";try{let m=await i.models.generateContentStream({model:n,contents:l,config:c});for await(let f of m){g.debug("Received chunk",{hasCandidate:!!f.candidates?.[0],hasContent:!!f.candidates?.[0]?.content,hasParts:!!f.candidates?.[0]?.content?.parts});let h=f.candidates?.[0];if(h?.content?.parts)for(let y of h.content.parts){if("inlineData"in y&&y.inlineData?.data){let x=y.inlineData.data;u=x;let b=y.inlineData.mimeType||"image/png";g.info("Image generation successful",{model:n,mimeType:b,dataLength:x.length,responseTime:Date.now()-o});let T={content:`Generated image using ${n} (${b})`,imageOutput:{base64:x},provider:this.providerName,model:n,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(T,e,o)}"text"in y&&y.text&&(p+=y.text,g.debug("Received text content",{text:y.text.substring(0,100)}))}}}catch(m){g.debug("Streaming failed, trying non-streaming approach",{error:m instanceof Error?m.message:String(m)})}if(!u){g.debug("Trying non-streaming approach");let f=(await i.models.generateContent({model:n,contents:l,config:c})).candidates?.[0];if(f?.content?.parts)for(let h of f.content.parts){if("inlineData"in h&&h.inlineData?.data){let y=h.inlineData.data;u=y;let x=h.inlineData.mimeType||"image/png";g.info("Image generation successful (non-streaming)",{model:n,mimeType:x,dataLength:y.length,responseTime:Date.now()-o});let b={content:`Generated image using ${n} (${x})`,imageOutput:{base64:y},provider:this.providerName,model:n,usage:{input:this.estimateTokenCount(t),output:0,total:this.estimateTokenCount(t)}};return await this.enhanceResult(b,e,o)}"text"in h&&h.text&&(p+=h.text)}}throw g.warn("No image data found in response",{model:n,prompt:t.substring(0,100),hasTextContent:!!p,textContent:p.substring(0,200)}),new pt(p||`Image generation completed but no image data was returned. This may indicate an issue with the model "${n}" or the prompt: "${t}". Please try again or use a different model.`,this.providerName)}catch(a){throw g.error("Image generation failed",{error:a instanceof Error?a.message:String(a),model:n,prompt:t.substring(0,100)}),this.handleProviderError(a)}}detectImageType(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70?"image/gif":"image/png"}estimateTokenCount(e){return zt(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&UI(e.input),e.input?.files&&e.input.files.length>0)try{await FI(e,100*1024*1024,this.providerName)}catch(t){g.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Nv(e.input)}async executeStream(e,t){let n=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);let o=!!(t||e.output?.format==="json"||e.schema),s=!e.disableTools&&this.supportsTools()&&!o,i=e.tools||{},a={...e,tools:i},l=e.output?.format==="json"||e.schema,c=pI(this.providerName,n,!a.disableTools,Object.keys(a.tools??{}).length);return l&&c&&(g.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),a={...a,disableTools:!0,tools:{}}),s&&!a.disableTools&&a.tools&&Object.keys(a.tools).length>0&&g.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:n,totalToolCount:Object.keys(a.tools??{}).length}),this.executeNativeGemini3Stream(a)}async executeNativeGemini3Stream(e){let t=e.model||this.modelName;return BA({name:"neurolink.provider.stream",tracer:Oe.provider,attributes:{[Pe.GEN_AI_SYSTEM]:"google-ai",[Pe.GEN_AI_MODEL]:t,[Pe.GEN_AI_OPERATION]:"stream",[Pe.NL_PROVIDER]:this.providerName}},async n=>{let o=Date.now(),s=this.getTimeout(e),i=ei(s,this.providerName,"stream");{let a=this.getApiKey(),l=await I_(a,this.getBaseURL());g.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});let c=[];A_(c,e.conversationMessages);let u=await Ire(e.input,e.input.text,"[GoogleAIStudio:stream]");c.push({role:"user",parts:u});let p,m=new Gd,f=new Map,h;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){let N=Wj(e.tools);h=N,p=N.toolsConfig,m=N.executeMap,f=N.originalNameMap,g.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:p[0].functionDeclarations.length,toolNames:p[0].functionDeclarations.map(z=>z.name)})}let y=!p&&(e.output?.format==="json"||!!e.schema),x=y&&e.schema?Are(e.schema):void 0,b=Tre({...e,model:t,wantsJsonOutput:y,responseSchema:x},p),T=Sre(e.maxSteps),w=yv(e.abortSignal,i?.controller.signal),C=Xj(),R=[],k=[],P,I,A=new Promise((N,z)=>{P=N,I=z}),M={streamId:`native-${Date.now()}`,startTime:o,responseTime:0,totalToolExecutions:0};(async()=>{let N="",z=0,G=0,B=0,$=0,O=0,W=!1,re=new Map,te=Yh(Nd("googleAiStudio",t));try{for(;O<T;){if((O===0||te.shouldStop())&&qFe(c,t,te.projectedNextPromptTokens)&&te.resetAfterReclaim(),w?.aborted)throw w.reason instanceof Error?w.reason:new Error("Request aborted");O++,h&&Jj(e.tools,h),g.debug(`[GoogleAIStudio] Native SDK step ${O}/${T}`);try{let oe=await l.models.generateContentStream({model:t,contents:c,config:b,...w?{httpOptions:{signal:w}}:{}}),Z=await PFe(oe,C);z+=Z.inputTokens,G+=Z.outputTokens,B+=Z.cacheReadTokens??0,$+=Z.reasoningTokens??0,te.noteUsage(Z.inputTokens,Z.outputTokens);let _e=Ere(Z.rawResponseParts);if(Z.stepFunctionCalls.length===0){W=!0;break}N=_e;for(let L of Z.stepFunctionCalls)n.addEvent("gen_ai.tool_call",{"tool.name":L.name,"tool.step":O});g.debug(`[GoogleAIStudio] Executing ${Z.stepFunctionCalls.length} function calls`),kre(c,Z.rawResponseParts,Z.stepFunctionCalls);let ve=R.length,ae=k.length,H=await Cre("[GoogleAIStudio]",Z.stepFunctionCalls,m,re,R,{abortSignal:w,originalNameMap:f,toolExecutions:k,liveTools:e.tools,declarations:h}),V=R.slice(ve),ne=k.slice(ae);if(V.length>0||ne.length>0){let L=k_(Z.rawResponseParts);ft(this.handleToolExecutionStorage(V.map((Y,ee)=>({toolName:Y.toolName,args:Y.args,...ee===0&&L?{thoughtSignature:L}:{},stepIndex:O})),ne.map(Y=>({toolName:Y.name,output:Y.output,stepIndex:O})),e,new Date),eg,"tool storage write timed out").catch(Y=>{g.warn("[GoogleAIStudio] Failed to store native tool executions",{error:Y instanceof Error?Y.message:String(Y)})})}c.push({role:"user",parts:H});try{te.noteAppendedChars(JSON.stringify(H).length)}catch{}}catch(oe){throw g.error("[GoogleAIStudio] Native SDK error",oe),this.handleProviderError(oe)}}let pe=O>=T&&!W;if(pe){let oe=Rre("[GoogleAIStudio]",O,T,"",N);oe&&C.push(oe)}let Ae=Date.now()-o;M.responseTime=Ae,M.totalToolExecutions=R.length,n.setAttribute(Pe.GEN_AI_INPUT_TOKENS,z),n.setAttribute(Pe.GEN_AI_OUTPUT_TOKENS,G),n.setAttribute(Pe.GEN_AI_FINISH_REASON,pe?"max_steps":"stop");let J=Math.max(0,z-B);P({provider:this.providerName,model:t,tokenUsage:{input:J,output:G+$,total:J+B+G+$,...B>0?{cacheReadTokens:B}:{},...$>0?{reasoning:$}:{}},requestDuration:Ae,timestamp:new Date().toISOString()}),C.close()}catch(pe){C.error(pe),I(pe)}finally{i?.cleanup()}})().catch(()=>{});let D={stream:C.iterable,provider:this.providerName,model:t,toolCalls:R,analytics:A,metadata:M};return Object.defineProperty(D,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>R.map(N=>N.toolName)}),Object.defineProperty(D,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>xv(k)}),D}},n=>n.stream,(n,o)=>({...n,stream:o}))}async executeNativeGemini3Generate(e){let t=e.model||this.modelName;return Dp({name:"neurolink.provider.generate",tracer:Oe.provider,attributes:{[Pe.GEN_AI_SYSTEM]:"google-ai",[Pe.GEN_AI_MODEL]:t,[Pe.GEN_AI_OPERATION]:"generate",[Pe.NL_PROVIDER]:this.providerName}},async n=>{let o=Date.now(),s=this.getTimeout(e),i=ei(s,this.providerName,"generate");try{let a=this.getApiKey(),l=await I_(a,this.getBaseURL());g.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});let c=e.input?.text||e.prompt||"",u=[];A_(u,e.conversationMessages);let p=await Ire(e.input,c,"[GoogleAIStudio:generate]");u.push({role:"user",parts:p});let m,f=new Gd,h=new Map,y,x=!e.disableTools,b=!!(e.output?.format==="json"||e.schema),T=pI(this.providerName,t,x,Object.keys(e.tools||{}).length);if(b&&T&&g.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),x&&!T){let pe=e.tools||{};if(Object.keys(pe).length>0){let Ae=Wj(pe);y=Ae,m=Ae.toolsConfig,f=Ae.executeMap,h=Ae.originalNameMap,g.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:m[0].functionDeclarations.length,toolNames:m[0].functionDeclarations.map(J=>J.name)})}}let w=!m&&b,C=w&&e.schema?Are(e.schema):void 0,R=Tre({...e,model:t,wantsJsonOutput:w,responseSchema:C},m),k=yv(e.abortSignal,i?.controller.signal),P=Sre(e.maxSteps),I="",A="",M=0,F=0,D=0,N=0,z=[],G=[],B=0,$=new Map,O=Yh(Nd("googleAiStudio",t));for(;B<P;){if((B===0||O.shouldStop())&&qFe(u,t,O.projectedNextPromptTokens)&&O.resetAfterReclaim(),k?.aborted)throw k.reason instanceof Error?k.reason:new Error("Request aborted");B++,y&&Jj(e.tools,y),g.debug(`[GoogleAIStudio] Native SDK generate step ${B}/${P}`);try{let pe=await l.models.generateContentStream({model:t,contents:u,config:R,...k?{httpOptions:{signal:k}}:{}}),Ae=await IFe(pe);M+=Ae.inputTokens,F+=Ae.outputTokens,D+=Ae.cacheReadTokens??0,N+=Ae.reasoningTokens??0,O.noteUsage(Ae.inputTokens,Ae.outputTokens);let J=Ere(Ae.rawResponseParts);if(Ae.stepFunctionCalls.length===0){I=J;break}A=J;for(let H of Ae.stepFunctionCalls)n.addEvent("gen_ai.tool_call",{"tool.name":H.name,"tool.step":B});g.debug(`[GoogleAIStudio] Executing ${Ae.stepFunctionCalls.length} function calls in generate`),kre(u,Ae.rawResponseParts,Ae.stepFunctionCalls);let oe=z.length,Z=G.length,_e=await Cre("[GoogleAIStudio]",Ae.stepFunctionCalls,f,$,z,{toolExecutions:G,abortSignal:k,originalNameMap:h,liveTools:e.tools,declarations:y}),ve=z.slice(oe),ae=G.slice(Z);if(ve.length>0||ae.length>0){let H=k_(Ae.rawResponseParts);ft(this.handleToolExecutionStorage(ve.map((V,ne)=>({toolName:V.toolName,args:V.args,...ne===0&&H?{thoughtSignature:H}:{},stepIndex:B})),ae.map(V=>({toolName:V.name,output:V.output,stepIndex:B})),e,new Date),eg,"tool storage write timed out").catch(V=>{g.warn("[GoogleAIStudio] Failed to store native generate tool executions",{error:V instanceof Error?V.message:String(V)})})}u.push({role:"user",parts:_e});try{O.noteAppendedChars(JSON.stringify(_e).length)}catch{}}catch(pe){throw g.error("[GoogleAIStudio] Native SDK generate error",pe),this.handleProviderError(pe)}}I=Rre("[GoogleAIStudio]",B,P,I,A);let W=Date.now()-o;n.setAttribute(Pe.GEN_AI_INPUT_TOKENS,M),n.setAttribute(Pe.GEN_AI_OUTPUT_TOKENS,F),n.setAttribute(Pe.GEN_AI_FINISH_REASON,B>=P?"max_steps":"stop");let re=Math.max(0,M-D),te={content:I,provider:this.providerName,model:t,usage:{input:re,output:F+N,total:re+D+F+N,...D>0?{cacheReadTokens:D}:{},...N>0?{reasoning:N}:{}},...N>0&&{reasoningTokens:N},responseTime:W,toolsUsed:z.map(pe=>pe.toolName),toolExecutions:vv(e,G),enhancedWithTools:z.length>0};return this.enhanceResult(te,e,o)}finally{i?.cleanup()}})}async generate(e){let t=typeof e=="string"?{prompt:e}:e,n=t.model||this.modelName;if(Np.some(p=>n.toLowerCase().startsWith(p.toLowerCase())))return g.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:n}),this.executeImageGeneration(t);if(t.tts?.enabled&&!t.tts?.useAiResponse)return g.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:n}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);let s=t.disableTools?{}:await this.getToolsForStream(t),i={...t,tools:s};(t.output?.format==="json"||t.schema)&&i.tools&&Object.keys(i.tools).length>0&&!i.disableTools&&(g.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),i={...i,disableTools:!0,tools:{}}),!i.disableTools&&i.tools&&Object.keys(i.tools).length>0&&g.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:n,totalToolCount:Object.keys(i.tools??{}).length});let c=Date.now(),u=i.input?.text||i.prompt||"";try{let p=await Je({name:"neurolink.executeGeneration",tracer:Oe.provider,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName,[Pe.GEN_AI_MODEL]:n,"neurolink.path":"native.google-genai"}},async()=>this.executeNativeGemini3Generate(i));return p=await this.synthesizeAIResponseIfNeeded(p,t),this.emitPipelineBGenerationEvent(n,p,c,!0,void 0,u),p}catch(p){throw this.emitPipelineBGenerationEvent(n,null,c,!1,p,u),p}}emitPipelineBGenerationEvent(e,t,n,o,s,i){let a=this.neurolink?.getEventEmitter();if(!a)return;let l=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),a.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-n,timestamp:Date.now(),prompt:i||"",result:{content:t?.content||"",usage:l,model:e,provider:this.providerName,finishReason:o?"stop":"error"},success:o,...s?{error:s instanceof Error?s.message:String(s)}:{}})}async executeAudioStreamViaGeminiLive(e){let t=Date.now(),n=this.getApiKey(),o;try{o=await I_(n,this.getBaseURL())}catch{throw new At("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}let s=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",i=[],a=null,l=!1,c=m=>{if(!l){if(m.type==="audio"&&a){let f=a;a=null,f({value:{type:"audio",audio:m.audio},done:!1});return}i.push(m)}},u=await o.live.connect({model:s,callbacks:{onopen:()=>{},onmessage:async m=>{try{let f=m?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(f?.data){let y={data:Buffer.from(String(f.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};c({type:"audio",audio:y})}m?.serverContent?.interrupted}catch(f){c({type:"error",error:f})}},onerror:m=>{c({type:"error",error:m})},onclose:m=>{c({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}});return(async()=>{try{let m=e.input?.audio;if(!m){g.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}for await(let f of m.frames){if(!f||f.byteLength===0){try{u.sendInput?await u.sendInput({event:"flush"}):u.sendRealtimeInput&&await u.sendRealtimeInput({event:"flush"})}catch(x){g.debug("[GeminiLive] flush control failed (non-fatal)",{error:x instanceof Error?x.message:String(x)})}continue}let h=f.toString("base64"),y=`audio/pcm;rate=${m.sampleRateHz||16e3}`;await u.sendRealtimeInput?.({media:{data:h,mimeType:y}})}try{u.sendInput?await u.sendInput({event:"flush"}):u.sendRealtimeInput&&await u.sendRealtimeInput({event:"flush"})}catch(f){g.debug("[GeminiLive] final flush failed (non-fatal)",{error:f instanceof Error?f.message:String(f)})}}catch(m){c({type:"error",error:m})}})().catch(()=>{}),{stream:{[Symbol.asyncIterator](){return{async next(){if(i.length>0){let m=i.shift();if(!m)return{value:void 0,done:!0};if(m.type==="audio")return{value:{type:"audio",audio:m.audio},done:!1};if(m.type==="end")return l=!0,{value:void 0,done:!0};if(m.type==="error")throw l=!0,m.error instanceof Error?m.error:new Error(String(m.error))}return l?{value:void 0,done:!0}:await new Promise(m=>{a=m})}}}},provider:this.providerName,model:s,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){let n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let o=this.getApiKey(),a=(await(await I_(o,this.getBaseURL())).models.embedContent({model:n,contents:[e]})).embeddings?.[0]?.values;if(!a)throw new pt("No embedding returned from Google AI",this.providerName);return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.length}),a}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=this.getApiKey(),a=((await(await I_(o,this.getBaseURL())).models.embedContent({model:n,contents:e})).embeddings||[]).map(l=>l.values||[]);return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:a.length,embeddingDimension:a[0]?.length}),a}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)}}getApiKey(){let e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new At("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){let e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}});var HFe={};ue(HFe,{GoogleAIStudioProvider:()=>Lre});var KFe=E(()=>{"use strict";VFe()});function dyr(r){let e=[],t=new Set,n=r;for(;n&&typeof n=="object"&&!t.has(n)&&e.length<uyr;){t.add(n);let o=n;e.push(o),n=o.cause}return e}function WFe(r,e){for(let t of r)if(typeof t[e]=="string")return t[e]}function pyr(r,e,t){let n=dyr(r),o=n[0],s=typeof o?.message=="string"?o.message:r instanceof Error?r.message:"Unknown error",i=n[n.length-1],a=typeof i?.message=="string"?Av(i.message):void 0,l=a&&a!==s?`${s}: ${a}`:s,c;for(let u of n)if(c=Lw(u),c!==void 0)break;return{error:r,message:l,statusCode:c,errorName:WFe(n,"name"),errorCode:WFe(n,"code"),provider:e,modelName:t}}function fr(r,e,t,n){if(r instanceof al)return new dn(`Request timed out: ${r.message}`,t);let o=pyr(r,t,n),s=e.find(a=>a.match(o));if(!s)return new pt(`${t} error: ${o.message}`,t);let i=typeof s.message=="function"?s.message(o):s.message;return new s.errorClass(i,t)}var uyr,Fr,Yo=E(()=>{"use strict";It();Il();_h();Ore();Or();uyr=5;Fr=[{match:r=>r.statusCode===401||/API_KEY_INVALID|Invalid API key|Unauthorized|invalid_api_key/i.test(r.message),errorClass:At,message:r=>`Invalid ${r.provider} API key. Please check your credentials.`},{match:r=>r.statusCode===429||/rate limit/i.test(r.message),errorClass:Yr,message:r=>`${r.provider} rate limit exceeded. Please try again later.`},{match:r=>r.statusCode===404||/model_not_found|model not found/i.test(r.message),errorClass:wr,message:r=>r.modelName?`${r.provider} model '${r.modelName}' not found.`:`${r.provider} model not found.`},{match:r=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|network|connection/i.test(r.message)||r.errorCode!==void 0&&Zj.has(r.errorCode),errorClass:dn,message:r=>`Connection error: ${r.message}`},{match:r=>r.statusCode!==void 0&&r.statusCode>=500&&r.statusCode<=599||/server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(r.message),errorClass:pt,message:r=>`${r.provider} server error: ${r.message}`}]});async function ka(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 Sg=E(()=>{"use strict"});var _Kn,EKn,CKn,RKn,Dre,myr,JFe,Ure,kKn,AKn,PKn,MKn,XFe=E(()=>{_Kn=globalThis.crypto,EKn=globalThis.ReadableStream||class{},CKn=globalThis.URL,RKn=globalThis.URLSearchParams,Dre=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Dre.custom=Symbol.for("nodejs.util.inspect.custom");Dre.colors={};Dre.styles={};myr=globalThis.TextDecoder,JFe=globalThis.TextEncoder,Ure=(r,e)=>e?.(null,"127.0.0.1",4),kKn=globalThis.performance||{now:()=>Date.now()},AKn=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 JFe().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 JFe().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 myr().decode(this)}},PKn=globalThis.clearTimeout,MKn=globalThis.clearInterval});var LKn,DKn,UKn,FKn,Fre,gyr,YFe,$Kn,BKn,ZFe,jKn,GKn,QFe=E(()=>{LKn=globalThis.crypto,DKn=globalThis.ReadableStream||class{},UKn=globalThis.URL,FKn=globalThis.URLSearchParams,Fre=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Fre.custom=Symbol.for("nodejs.util.inspect.custom");Fre.colors={};Fre.styles={};gyr=globalThis.TextDecoder,YFe=globalThis.TextEncoder,$Kn=globalThis.performance||{now:()=>Date.now()},BKn=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 YFe().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 YFe().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 gyr().decode(this)}},ZFe=()=>0,jKn=globalThis.clearTimeout,GKn=globalThis.clearInterval});function yyr(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 Qj(r){if(r.length===0)return null;let e=r.split(".");if(e.length===4){let t=e.map(yyr);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 t1e(r){if(ZFe(r)!==6)return null;let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i),t;if(e){let n=Qj(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 r1e(r){let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(e)return Qj(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 e1e(r){let[e,t,n,o]=r.split(".").map(s=>parseInt(s,10));return(e<<24|t<<16|n<<8|o)>>>0}function uP(r){let e=e1e(r);for(let[t,n]of fyr){let o=e1e(t),s=n===0?0:4294967295<<32-n>>>0;if((e&s)===(o&s))return!0}return!1}function n1e(r){return hyr.some(e=>e.length===39?r===e:r.startsWith(e))}function o1e(r){return r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r}function s1e(r){let e=Qj(r);if(e)return uP(e)?`IPv4 ${r} \u2192 ${e} is in a blocked range`:null;if(r.includes(":")){let t=r1e(r);if(t)return uP(t)?`IPv4-mapped IPv6 ${r} \u2192 ${t} is in a blocked range`:null;let n=t1e(r);return n?n1e(n)?`IPv6 ${r} is in a blocked range`:null:`IPv6 ${r} could not be parsed`}return"not-an-ip"}async function ru(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=o1e(e.hostname).toLowerCase(),n=s1e(t);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${r}" rejected: ${n}`);await i1e(r,t)}}async function i1e(r,e){let[t,n]=await Promise.allSettled([Ure(e,{family:4,all:!0}),Ure(e,{family:6,all:!0})]),o=[],s=[],i=!1;if(t.status==="fulfilled"){i=!0;for(let a of t.value)o.push(a.address)}if(n.status==="fulfilled"){i=!0;for(let a of n.value)s.push(a.address)}if(!i){let a=t.status==="rejected"?t.reason instanceof Error?t.reason.message:String(t.reason):"ok",l=n.status==="rejected"?n.reason instanceof Error?n.reason.message:String(n.reason):"ok";throw new Error(`URL "${r}" rejected: hostname ${e} could not be resolved (A: ${a}; AAAA: ${l})`)}for(let a of o)if(uP(a))throw new Error(`URL "${r}" rejected: hostname ${e} resolves to ${a} (IPv4 in blocked range)`);for(let a of s){let l=s1e(a.toLowerCase());if(l&&l!=="not-an-ip")throw new Error(`URL "${r}" rejected: hostname ${e} resolves to ${a} (IPv6 ${l})`)}return{v4:o,v6:s}}async function a1e(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=o1e(e.hostname).toLowerCase(),n=Qj(t);if(n){if(uP(n))throw new Error(`URL "${r}" rejected: IPv4 ${t} \u2192 ${n} is in a blocked range`);return{url:r,ip:n,family:4,addresses:[{ip:n,family:4}]}}if(t.includes(":")){let l=r1e(t);if(l){if(uP(l))throw new Error(`URL "${r}" rejected: IPv4-mapped IPv6 ${t} \u2192 ${l} is in a blocked range`);return{url:r,ip:l,family:4,addresses:[{ip:l,family:4}]}}let c=t1e(t);if(!c)throw new Error(`URL "${r}" rejected: IPv6 ${t} could not be parsed`);if(n1e(c))throw new Error(`URL "${r}" rejected: IPv6 ${t} is in a blocked range`);return{url:r,ip:t,family:6,addresses:[{ip:t,family:6}]}}let{v4:o,v6:s}=await i1e(r,t),i=[...o.map(l=>({ip:l,family:4})),...s.map(l=>({ip:l,family:6}))],a=i[0];if(!a)throw new Error(`URL "${r}" rejected: hostname ${t} resolved to an empty address set`);return{url:r,ip:a.ip,family:a.family,addresses:i}}var fyr,hyr,Zh=E(()=>{"use strict";XFe();QFe();fyr=[["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]],hyr=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]});var l1e={};ue(l1e,{createAnnotatedTool:()=>Bre,filterToolsByAnnotations:()=>Gre,getAnnotationSummary:()=>qre,getToolSafetyLevel:()=>jre,inferAnnotations:()=>nu,isSafeToRetry:()=>dP,mergeAnnotations:()=>eG,requiresConfirmation:()=>zre,validateAnnotations:()=>$re});function nu(r){let e=r.name,t=r.description.toLowerCase(),n={},o=(c,u)=>new RegExp(`\\b${u}\\b`,"i").test(c)?!0:c.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[_-]/).some(m=>m===u.toLowerCase());return["get","list","read","fetch","query","search","find","show","display","view","retrieve","check","inspect","look"].some(c=>o(t,c)||o(e,c))&&(n.readOnlyHint=!0),["delete","remove","drop","destroy","clear","purge","erase","wipe","truncate","reset"].some(c=>o(t,c)||o(e,c))&&(n.destructiveHint=!0,n.requiresConfirmation=!0),["set","update","put","upsert","replace"].some(c=>o(t,c)||o(e,c))&&!n.destructiveHint&&(n.idempotentHint=!0),["complex","analyze","process","generate","transform","compute","calculate"].some(c=>o(t,c)||o(e,c))?n.complexity="complex":t.length>100?n.complexity="medium":n.complexity="simple",n}function eG(...r){let e={};for(let t of r)if(t){let n=e.tags?[...e.tags]:[];if(Object.assign(e,t),n.length>0||t.tags){let o=t.tags??[];e.tags=[...new Set([...n,...o])]}}return e}function $re(r){let e=[];if(r.readOnlyHint&&r.destructiveHint&&e.push("Tool cannot be both readOnly and destructive - these are conflicting hints"),r.rateLimitHint!==void 0&&(r.rateLimitHint<0||!Number.isFinite(r.rateLimitHint))&&e.push("rateLimitHint must be a non-negative number"),r.estimatedDuration!==void 0&&(r.estimatedDuration<0||!Number.isFinite(r.estimatedDuration))&&e.push("estimatedDuration must be a non-negative number"),r.costHint!==void 0&&(r.costHint<0||!Number.isFinite(r.costHint))&&e.push("costHint must be a non-negative number"),r.tags){for(let t of r.tags)if(typeof t!="string"||t.length===0){e.push("All tags must be non-empty strings");break}}return e}function Bre(r){let e=nu(r),t=eG(e,r.annotations);return{...r,annotations:t}}function zre(r){return!!(r.annotations?.requiresConfirmation||r.annotations?.destructiveHint)}function dP(r){return!!(r.annotations?.idempotentHint||r.annotations?.readOnlyHint)}function jre(r){return r.annotations?.destructiveHint?"dangerous":r.annotations?.readOnlyHint?"safe":(r.annotations?.idempotentHint,"moderate")}function Gre(r,e){return r.filter(t=>{let n=t.annotations??{};return e(n)})}function qre(r){let e=[];return r.title&&e.push(r.title),r.readOnlyHint&&e.push("read-only"),r.destructiveHint&&e.push("DESTRUCTIVE"),r.idempotentHint&&e.push("idempotent"),r.requiresConfirmation&&e.push("requires confirmation"),r.complexity&&e.push(`${r.complexity} complexity`),r.estimatedDuration!==void 0&&e.push(`~${r.estimatedDuration}ms`),r.tags?.length&&e.push(`tags: ${r.tags.join(", ")}`),e.length>0?`[${e.join(" | ")}]`:"[no annotations]"}var P_=E(()=>{"use strict"});var Zre={};ue(Zre,{TOOL_COMPATIBILITY:()=>Yre,batchConvertToMCP:()=>Kre,batchConvertToNeuroLink:()=>Wre,createToolFromFunction:()=>Jre,mcpProtocolToolToServerTool:()=>Vre,mcpToolToNeuroLink:()=>rG,neuroLinkToolToMCP:()=>tG,sanitizeToolName:()=>pP,serverToolToMCPProtocol:()=>Hre,validateToolName:()=>Xre});function tG(r,e={}){let{inferAnnotations:t=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=e,i=s?`${s}_${r.name}`:r.name,a=t?nu({name:r.name,description:r.description}):{},l={...n,...a};r.tags?.length&&(l.tags=[...new Set([...l.tags??[],...r.tags])]);let c=r.parameters??{type:"object",properties:{}},u=o?{...r.metadata}:{};return r.category&&(u.category=r.category),r.isAsync!==void 0&&(u.isAsync=r.isAsync),{name:i,description:r.description,inputSchema:c,annotations:l,execute:r.execute,metadata:u}}function rG(r,e={}){let{removeNamespacePrefix:t}=e,n=r.name;return t&&r.name.startsWith(`${t}_`)&&(n=r.name.slice(t.length+1)),{name:n,description:r.description,parameters:r.inputSchema,execute:r.execute,category:r.metadata?.category,tags:r.annotations?.tags,metadata:r.metadata}}function Vre(r,e,t={}){let{inferAnnotations:n=!0,defaultAnnotations:o={}}=t,s=r.annotations??{},i=n?nu({name:r.name,description:r.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:r.name,description:r.description??"No description provided",inputSchema:r.inputSchema,annotations:a,execute:e}}function Hre(r){let e={};r.annotations?.title&&(e.title=r.annotations.title),r.annotations?.readOnlyHint!==void 0&&(e.readOnlyHint=r.annotations.readOnlyHint),r.annotations?.destructiveHint!==void 0&&(e.destructiveHint=r.annotations.destructiveHint),r.annotations?.idempotentHint!==void 0&&(e.idempotentHint=r.annotations.idempotentHint),r.annotations?.openWorldHint!==void 0&&(e.openWorldHint=r.annotations.openWorldHint);let t=r.inputSchema??{type:"object",properties:{}};return{name:r.name,description:r.description,inputSchema:{type:"object",properties:t.properties??{},required:"required"in t?t.required:void 0},annotations:Object.keys(e).length>0?e:void 0}}function Kre(r,e={}){return r.map(t=>tG(t,e))}function Wre(r,e={}){return r.map(t=>rG(t,e))}function Jre(r,e,t,n){let o=nu({name:r,description:e});return{name:r,description:e,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await ft(t(s,i),3e4,`Tool '${r}' execution timed out after 30000ms`),metadata:n?.metadata}}function Xre(r){let e=[];return!r||typeof r!="string"?e.push("Tool name is required and must be a string"):(r.length>64&&e.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(r)||e.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:e.length===0,errors:e}}function pP(r){let e=r.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(e)||(e=`_${e}`),e.length>64&&(e=e.slice(0,64)),e}var Yre,mP=E(()=>{"use strict";P_();co();Yre={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}});var Ii,c1e,nG,Qre,tm,gP,ene,xyr,vyr,tne,rne,u1e,d1e,p1e,m1e,byr,nne,g1e,one,f1e,fP,oG,sG,h1e,wg=E(()=>{"use strict";O1();mP();ig();cl();fi();Ii=r=>r.replace(/\/+$/,""),c1e=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,nG=(r,e)=>{if(r.every(o=>c1e.test(o)&&!e?.has(o)))return;let t=new Map,n=new Map;for(let o of r){let s=c1e.test(o)?o:pP(o);if(n.has(s)||e?.has(s)){let i=2,a;do{let l=`_${i}`;a=`${s.slice(0,64-l.length)}${l}`,i++}while(n.has(a)||e?.has(a));s=a}t.set(o,s),n.set(s,o)}return{toWire:t,fromWire:n}},Qre=(r,e,t)=>{let n=0;for(let o of r){let s=typeof o.content=="string"?o.content:tm(o.content);n+=zt(s,t)+4;let i=o.tool_calls;i&&(n+=zt(tm(i),t))}return e&&e.length>0&&(n+=zt(tm(e),t)),n},tm=r=>{try{return JSON.stringify(r??"")}catch{return String(r??"")}},gP=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r??{})}catch{return"{}"}},ene=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:tm(e.value);case"json":return tm(e.value);case"execution-denied":return`Tool execution denied${e.reason?`: ${e.reason}`:""}`;case"error-text":return typeof e.value=="string"?e.value:tm(e.value);case"error-json":return tm(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(`
1071
- `):"";default:return tm(r)}},xyr=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")}`},vyr=r=>{if(typeof r=="string")return r;if(!Array.isArray(r))return tm(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=xyr(o);s&&e.push({type:"image_url",image_url:{url:s}})}}return e.length===1&&e[0].type==="text"?e[0].text:e},tne=(r,e)=>{let t=[];for(let n of r)switch(n.role){case"system":t.push({role:"system",content:typeof n.content=="string"?n.content:tm(n.content)});break;case"user":t.push({role:"user",content:vyr(n.content)});break;case"assistant":{let o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(let l of o)if(l&&typeof l=="object"){let c=l;if(c.type==="text")s.push({type:"text",text:l.text??""});else if(c.type==="tool-call"){let u=l,p=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:e?.get(p)??p,arguments:gP(u.input)}})}}else typeof l=="string"&&s.push({type:"text",text:l});let a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;t.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(let o of n.content){if(!o||typeof o!="object")continue;let s=o;s.type==="tool-result"&&t.push({role:"tool",tool_call_id:s.toolCallId??"",content:ene(s.output)})}else typeof n.content=="string"&&t.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return t},rne=(r,e)=>{let t=Object.entries(r);if(t.length===0)return;let n=[];for(let[o,s]of t){let i=s,a=i.inputSchema??i.parameters,l=a?IQ(Rn(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:e?.get(o)??o,...i.description?{description:i.description}:{},parameters:l}})}return n},u1e=(r,e)=>{if(!r||r.length===0)return;let t=[];for(let n of r)n.type==="function"&&t.push({type:"function",function:{name:e?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:IQ(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return t.length>0?t:void 0},d1e=(r,e)=>{switch(r.type){case"auto":case"none":case"required":return r.type;case"tool":return{type:"function",function:{name:e?.get(r.toolName)??r.toolName}}}},p1e=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"},m1e=(r,e)=>{if(r){if(r==="auto"||r==="none"||r==="required")return r;if(typeof r=="object"&&r!==null){let t=r;if(t.type==="tool"&&t.toolName)return{type:"function",function:{name:e?.get(t.toolName)??t.toolName}}}}},byr=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}),nne=r=>r.response_format?.type==="json_object"&&!byr(r.messages)?{...r,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...r.messages]}:r,g1e=r=>/^(o\d|gpt-5)/i.test(r.replace(/^.*\//,"")),one=r=>{let{modelId:e,messages:t,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=r,l={model:e,messages:t,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(l.max_tokens=n.maxTokens);let c=Ea("openai-compatible",e,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return c.temperature!==void 0&&(l.temperature=c.temperature),c.topP!==void 0&&(l.top_p=c.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(l.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(l.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(l.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(l.stop=n.stopSequences),o&&(l.tools=o),s!==void 0&&(l.tool_choice=s),a&&(l.response_format=a),n.extraBody&&Object.assign(l,n.extraBody),l},f1e=async(r,e,t)=>{let n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder,s,a=VS({onEvent:c=>{let u=c.data;if(!u||u==="[DONE]")return;let p;try{p=JSON.parse(u)}catch(y){s=y instanceof Error?y:new Error(String(y));return}p.usage&&(n.usage=p.usage);let m=p.choices?.[0];if(!m)return;let f=m.delta;f?.content&&(n.text+=f.content,e(f.content));let h=f?.reasoning_content||f?.reasoning;if(h&&(n.reasoning+=h,t?.(h)),f?.tool_calls)for(let y of f.tool_calls){let x=n.toolCalls.get(y.index);x?y.id&&(x.id=y.id):(x={id:y.id??`call_${y.index}_${Date.now()}`,name:y.function?.name??"",argsBuffered:""},n.toolCalls.set(y.index,x)),y.function?.name&&(x.name=y.function.name),y.function?.arguments&&(x.argsBuffered+=y.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),l=r.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{l.releaseLock()}if(s)throw s;return n},fP=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.responseHeaders=Object.fromEntries([...t.headers.entries()].filter(([a])=>{let l=a.toLowerCase();return l==="retry-after"||l.startsWith("x-ratelimit-")})),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},oG=()=>{let r=()=>{},e=new Promise(o=>{r=o}),t=()=>{},n=new Promise(o=>{t=o});return{usagePromise:e,finishPromise:n,resolveUsage:r,resolveFinish:t}},sG=()=>{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})}},h1e=(r,e)=>{if(!r)return e;if(!e)return r;let t=(r.prompt_tokens_details?.cached_tokens??0)+(e.prompt_tokens_details?.cached_tokens??0),n=(r.completion_tokens_details?.reasoning_tokens??0)+(e.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(r.prompt_tokens??0)+(e.prompt_tokens??0),completion_tokens:(r.completion_tokens??0)+(e.completion_tokens??0),total_tokens:o(r)+o(e),...t>0?{prompt_tokens_details:{cached_tokens:t}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}});function iG(r){if(typeof r=="string")return r;if(r==null)return"";try{return JSON.stringify(r)??""}catch{return"x".repeat(2e5)}}function Syr(r,e){let t=iG(r.content);return r.role==="assistant"&&r.tool_calls&&(t+=iG(r.tool_calls)),zt(t,e)+4}function wyr(r,e){if(r.role!=="tool")return;let t=iG(r.content),n={maxBytes:y1e,maxLines:x1e};if(!KB(t,n))return;let{preview:o}=hi(t,n);return zt(o,e)+4}function _yr(r,e){return r.map(t=>{let n=Syr(t,e);if(t.role==="tool"){let o=wyr(t,e);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return t.role==="assistant"&&t.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function v1e(r){let{conversation:e,availableInputTokens:t,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=r,l=_yr(e,o),c=n+l.reduce((y,x)=>y+x.tokens,0),u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));let p=C_(l,{availableInputTokens:t,fixedOverheadTokens:n,calibration:u});if(!p.fire){a?.(c);return}let m=new Set(p.truncate),f=new Set(p.drop),h=[];for(let y=0;y<e.length;y++){if(f.has(y))continue;let x=e[y];if(m.has(y)&&x.role==="tool"){let{preview:b}=hi(iG(x.content),{maxBytes:y1e,maxLines:x1e});h.push({...x,content:b});continue}h.push(x)}if(f.size>0){let y=h.findIndex(x=>x.role==="tool"||x.role==="assistant"&&x.tool_calls);y<0&&(y=Math.min(1,h.length)),h.splice(y,0,{role:"user",content:Tyr})}return g.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:e.length,messagesAfter:h.length,toolOutputsTruncated:p.truncate.length,messagesDropped:p.drop.length,projectedTokens:p.projectedTokens,calibration:u}),a?.(p.projectedTokens),h}var y1e,x1e,Tyr,b1e=E(()=>{"use strict";fi();Rh();Vj();X();y1e=2048,x1e=60,Tyr="[Earlier tool exchanges were removed to fit the context window.]"});function hP(r){let e=sne(r);return e?T1e.some(({patterns:t})=>t.some(n=>n.test(e))):!1}function S1e(r){let e=sne(r);if(!e)return null;for(let{provider:t,patterns:n}of T1e)if(n.some(o=>o.test(e)))return t;return null}function yP(r){let e=sne(r);if(!e||e.length>2e3)return null;let t=e.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=e.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(t&&n)return{actualTokens:parseInt(t[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};let o=e.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){let a=e.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}let s=e.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};let i=e.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function sne(r){if(!r)return null;if(typeof r=="string")return r;if(r instanceof Error){let e=r.message,t=r?.cause;return t instanceof Error?`${e} ${t.message}`:e}if(typeof r=="object"){let e=r;if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){let t=e.error;if(typeof t.message=="string")return t.message}}return null}var T1e,ine=E(()=>{"use strict";T1e=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]});var Aa,ane=E(()=>{"use strict";Aa=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}});var lne,aG,cne=E(()=>{"use strict";GI();X();jw();Bp();lne=class{async collectUsage(e){try{let t=await e.usage;return t?Od(t):(g.debug("No usage data available from stream result"),jQ())}catch(t){return Sa.isInstance(t)?g.debug("No output generated from stream \u2014 returning empty usage"):g.warn("Failed to collect usage from stream result",{error:t}),jQ()}}async collectMetadata(e){try{let[t,n]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:n}}catch(t){return Sa.isInstance(t)?g.debug("No output generated from stream \u2014 returning default metadata"):g.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,n,o,s){try{let[i,a]=await Promise.all([this.collectUsage(n),this.collectMetadata(n)]),[l,c,u,p]=await Promise.all([Promise.resolve(n.text).catch(()=>""),Promise.resolve(n.finishReason).catch(()=>"error"),Promise.resolve(n.toolResults||[]).catch(()=>[]),Promise.resolve(n.toolCalls||[]).catch(()=>[])]);return qh(e,t,{usage:i,content:l,response:a,finishReason:c,toolResults:u,toolCalls:p},o,{...s,streamingMode:!0,responseId:a.id,finishReason:c})}catch(i){return g.error("Failed to create analytics from stream result",{provider:e,model:t,error:i instanceof Error?i.message:String(i)}),qh(e,t,{usage:{input:0,output:0,total:0}},o,{...s,streamingMode:!0,analyticsError:!0})}}cleanup(){let e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},aG=new lne});function lG(r,e,t){return!t||!e||Object.keys(e).length===0?"none":r.toolChoice??"auto"}var une=E(()=>{"use strict"});var dne,Ar,ri=E(()=>{"use strict";yr();Ld();b1e();ine();ane();Qc();us();cne();io();X();Or();Bp();Cj();Il();aI();une();jp();_h();zw();wg();dne=512,Ar=class extends so{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}suppressResponseFormatWithTools(){return!0}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,n,o){let s=VB(this.providerName,e),i=t;s!==void 0&&(i===void 0||i>s)&&(i!==void 0&&g.debug(`${this.providerName}: clamping max_tokens ${i} to the advertised ${e} output ceiling ${s}`),i=s);let a=_Oe(this.providerName,e);if(a!==void 0){let l=Qre(n,o,this.providerName),c=a-l-dne;if(c<=0)throw new Aa(`Estimated input (${l} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${a} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:l,availableTokens:Math.max(0,a-dne),stagesUsed:[],breakdown:{}});i!==void 0&&i>c&&(g.warn(`${this.providerName}: max_tokens ${i} cannot fit the ${e} window (${a}) with ~${l} input tokens \u2014 re-fitting to ${c}`),i=c)}return i}correctBodyAfterContextOverflow(e,t){if(!hP(t))return;let n=yP(t)??yP(t.responseBody);if(!n||n.budgetTokens<=0)return;qB(this.providerName,e.model,n.budgetTokens);let o=typeof e.max_tokens=="number"?e.max_tokens:n.requestedOutputTokens;if(o===void 0||n.actualTokens<=0)return;let s=n.budgetTokens-n.actualTokens-dne;if(!(s<=0||s>=o))return g.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:n.budgetTokens,inputTokens:n.actualTokens,previousMaxTokens:o,refitMaxTokens:s}),{...e,max_tokens:s}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ii(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{let t=`${Ii(this.config.baseURL)}/models`,o=await yt()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return o.ok?!!(await o.json().catch(()=>null))?.data?.some(i=>typeof i?.id=="string"&&i.id.trim().length>0):!1}catch(t){return g.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:Kt(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){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=yt(),o=this.getAuthHeaders.bind(this),s=this.providerName,i=this.adjustBuildBodyOptions.bind(this),a=this.adjustResponseFormat.bind(this),l=this.adjustRequestBody.bind(this),c=this.adjustBodyAfter400.bind(this),u=this.correctBodyAfterContextOverflow.bind(this),p=this.resolveWireMaxTokens.bind(this),m=this.suppressResponseFormatWithTools.bind(this),f=h=>this.getTimeout(h??{});return{specificationVersion:"v3",provider:s,modelId:e,supportedUrls:{},doGenerate:async h=>{let y=nG((h.tools??[]).filter($=>$.type==="function").map($=>$.name)),x=tne(h.prompt,y?.toWire),b=Array.isArray(h.tools)&&h.tools.length>0,T=h.responseFormat&&!(b&&m())?a(p1e(h.responseFormat),e):void 0,w=u1e(h.tools,y?.toWire),C=p(e,h.maxOutputTokens,x,w),R=nne(l(one({modelId:e,messages:x,options:i(e,{maxTokens:C,temperature:h.temperature,topP:h.topP,presencePenalty:h.presencePenalty,frequencyPenalty:h.frequencyPenalty,seed:h.seed,stopSequences:h.stopSequences}),tools:w,...h.toolChoice?{toolChoice:d1e(h.toolChoice,y?.toWire)}:{},streaming:!1,...T?{responseFormat:T}:{}}),e)),k=h.providerOptions?.neurolink?.timeoutMs,P=ei(typeof k=="number"?k:f(h),s,"generate"),{signal:I,dispose:A}=uMe(h.abortSignal,P?.controller.signal),M;try{let $=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(R),...I?{signal:I}:{}});if(!$.ok){let O=await fP(t,R,$),W=$.status===400?u(R,O)??c(R,O):void 0;if(!W)throw O;if($=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(W),...I?{signal:I}:{}}),!$.ok)throw await fP(t,W,$)}M=await $.json()}finally{P?.cleanup(),A()}let F=M.choices?.[0],D=(typeof F?.message?.content=="string"?F.message.content:"")??"",N=[],z=F?.message?.reasoning_content||F?.message?.reasoning;typeof z=="string"&&z.length>0&&N.push({type:"reasoning",text:z}),D.length>0&&N.push({type:"text",text:D});for(let $ of F?.message?.tool_calls??[])N.push({type:"tool-call",toolCallId:$.id,toolName:y?.fromWire.get($.function.name)??$.function.name,input:$.function.arguments??""});let G=F?.finish_reason;return{content:N,finishReason:{unified:G==="length"?"length":G==="tool_calls"||G==="function_call"?"tool-calls":G==="content_filter"?"content-filter":"stop",raw:G??"stop"},usage:{inputTokens:{total:M.usage?.prompt_tokens,noCache:M.usage?.prompt_tokens!==void 0&&M.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,M.usage.prompt_tokens-M.usage.prompt_tokens_details.cached_tokens):M.usage?.prompt_tokens,cacheRead:M.usage?.prompt_tokens!==void 0&&M.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(M.usage.prompt_tokens_details.cached_tokens,M.usage.prompt_tokens):M.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:M.usage?.completion_tokens,text:M.usage?.completion_tokens!==void 0&&M.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,M.usage.completion_tokens-M.usage.completion_tokens_details.reasoning_tokens):M.usage?.completion_tokens,reasoning:M.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:R},response:{...M.id?{id:M.id}:{},...M.model?{modelId:M.model}:{},headers:{},body:M}}},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=ei(o,this.providerName,"stream"),i=new AbortController,a=wB([e.abortSignal,s?.controller.signal,i.signal]).signal,l,c,u,p,m,f;try{l=await this.resolveModelName();let $=!e.disableTools&&this.supportsTools();c=$?e.tools||await this.getAllTools():{},u=$?nG(Object.keys(c)):void 0,p=$?rne(c,u?.toWire):void 0,m=m1e(lG(e,c,$),u?.toWire);let O=await this.buildMessagesForStream(e);f=tne(O,u?.toWire)}catch($){throw s?.cleanup(),$}let h=this.getChatCompletionsURL(l),y=yt(),x=e.maxSteps||cs,b=this.neurolink?.getEventEmitter(),T=[],w=[],{usagePromise:C,finishPromise:R,resolveUsage:k,resolveFinish:P}=oG(),{pushChunk:I,nextChunk:A}=sG(),M=this.onStreamStart(l),F=this.runStreamLoop({maxSteps:x,modelId:l,url:h,fetchImpl:y,abortSignal:a,options:e,conversation:f,openAITools:p,openAIToolChoice:m,toolsRecord:c,toolNameFromWire:u?.fromWire,emitter:b,toolsUsed:T,toolExecutionSummaries:w,pushChunk:I,resolveUsage:k,resolveFinish:P}),D,N=$=>{D=$};M?.onUsage&&C.then(M.onUsage).catch(()=>{}),M?.onFinish&&R.then($=>M.onFinish?.($,D)).catch(()=>{});let z=this.providerName,B={stream:async function*(){let $=0;try{for(;;){let O=await A();if("done"in O)break;"content"in O&&typeof O.content=="string"&&O.content.length>0&&$++,yield O}if(await F,$===0&&T.length===0){g.warn(`${z}: Stream produced no output \u2014 emitting enriched sentinel`);let O=new Sa({message:"Stream produced no output"}),W=await Jp(O,void 0,D);Xp(W),yield W}}catch(O){if(Sa.isInstance(O)){let re=await Jp(O,void 0,D);Xp(re),yield re;return}let W=await Jp(O,void 0,D);throw Xp(W),yield W,O}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:l,analytics:aG.createAnalytics(this.providerName,l,{textStream:(async function*(){})(),usage:C,finishReason:R},Date.now()-n,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:T,metadata:{startTime:n,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(B,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>xv(w.map($=>({toolName:$.toolName,input:$.input,output:$.output,duration:$.endTime.getTime()-$.startTime.getTime()})))}),F.finally(()=>s?.cleanup()).catch($=>{N($)}),B}async runStreamLoop(e){let{maxSteps:t,modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:l,openAITools:c,openAIToolChoice:u,toolsRecord:p,toolNameFromWire:m,emitter:f,toolsUsed:h,toolExecutionSummaries:y,pushChunk:x,resolveUsage:b,resolveFinish:T}=e,w=null,C,R=()=>{let k=C?.prompt_tokens??0,P=C?.completion_tokens??0,I=Math.min(C?.prompt_tokens_details?.cached_tokens??0,k),A=Math.min(Math.max(0,C?.completion_tokens_details?.reasoning_tokens??0),P);return{promptTokens:k-I,completionTokens:P,totalTokens:C?.total_tokens||k+P,...I>0?{cacheReadTokens:I}:{},...A>0?{reasoningTokens:A}:{}}};try{let k=m,P,I;for(let A=0;A<t;A++){if(c){let D=new Set(c.map(z=>k?.get(z.function.name)??z.function.name)),N=Object.fromEntries(Object.entries(p).filter(([z])=>!D.has(z)));if(Object.keys(N).length>0){let z=nG(Object.keys(N),new Set(c.map(G=>G.function.name)));if(z){k??=new Map;for(let[G,B]of z.fromWire)k.set(G,B)}c.push(...rne(N,z?.toWire)??[]),g.info(`${this.providerName}: ${Object.keys(N).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(N).join(", ")}`)}}let M=v1e({conversation:l,availableInputTokens:gi(this.providerName,n,a.maxTokens??void 0),fixedOverheadTokens:Qre([],c,this.providerName),provider:this.providerName,observedPromptTokens:P,previousSentEstimate:I,onSentEstimate:D=>{I=D}});M&&(l.length=0,l.push(...M));let F=await this.streamOneStep({modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:l,openAITools:c,openAIToolChoice:u,pushChunk:x});if(P=F.usage?.prompt_tokens,w=F.finishReason,F.usage&&(C=h1e(C,F.usage)),F.toolCalls.size===0)break;await this.executeToolBatch({stepResult:F,conversation:l,toolsRecord:p,toolNameFromWire:k,emitter:f,toolsUsed:h,toolExecutionSummaries:y,options:a})}return b(R()),T(w??"stop"),x({done:!0}),{finishReason:w??"stop",usage:C}}catch(k){throw g.error(`${this.providerName}: Stream error`,{error:k instanceof Error?k.message:String(k)}),b(R()),T("error"),x({done:!0}),k}}async streamOneStep(e){let t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),n=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,o=nne(this.adjustRequestBody(one({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,n),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),s=async()=>{let a=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(o),...e.abortSignal?{signal:e.abortSignal}:{}});if(!a.ok)throw await fP(e.url,o,a);return a},i;try{i=await zp(s,mt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(a){let l=a,c=l.statusCode===400?this.correctBodyAfterContextOverflow(o,l)??this.adjustBodyAfter400(o,l):void 0;if(!c)throw l;if(i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(c),...e.abortSignal?{signal:e.abortSignal}:{}}),!i.ok)throw await fP(e.url,c,i)}if(!i.body)throw new Error(`${this.providerName}: stream response had no body`);return f1e(i.body,a=>{e.pushChunk({content:a})},a=>{e.pushChunk({content:"",reasoning:a})})}async executeToolBatch(e){let{stepResult:t,conversation:n,toolsRecord:o,toolNameFromWire:s,emitter:i,toolsUsed:a,toolExecutionSummaries:l,options:c}=e,u=[];for(let[,m]of t.toolCalls)u.push({id:m.id,type:"function",function:{name:m.name,arguments:m.argsBuffered}});n.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:u});for(let[,m]of t.toolCalls){let f=new Date,h;try{h=JSON.parse(m.argsBuffered||"{}")}catch{h=m.argsBuffered}let y,x,b=s?.get(m.name)??m.name,T=o[b]??oI(o,b);if(i?.emit("tool:start",{toolName:b,toolCallId:m.id,input:h}),!T||typeof T.execute!="function")x=`Tool '${b}' is not registered.`,y={error:x};else try{y=await T.execute(h,{})}catch(C){x=C instanceof Error?C.message:String(C),y={error:x}}let w=new Date;a.push(b),l.push({toolCallId:m.id,toolName:b,input:h,output:y,...x?{error:x}:{},startTime:f,endTime:w}),n.push({role:"tool",tool_call_id:m.id,content:ene(y)})}let p=l.slice(-t.toolCalls.size);Ch(i,p.map(m=>({toolName:m.toolName,output:m.output,...m.error?{error:m.error}:{}})));try{await this.handleToolExecutionStorage(p.map(m=>({toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,output:m.output})),p.map(m=>({toolCallId:m.toolCallId,toolName:m.toolName,output:m.output})),c,new Date)}catch(m){g.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:m instanceof Error?m.message:String(m)})}}async getAvailableModels(){try{let e=`${Ii(this.config.baseURL)}/models`;g.debug(`Fetching available models from: ${e}`);let t=yt(),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(l=>l.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 w1e,Eyr,Cyr,Ryr,kyr,pne,_1e=E(()=>{"use strict";yr();io();It();X();Or();Nu();Yo();Ln();Sg();Zh();Il();wg();ri();w1e="https://api.openai.com/v1",Eyr=(r,e)=>{let t=[r,e].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??w1e;try{let n=new URL(t),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ii(n.toString())}catch{}return t},Cyr=()=>pr(rye()),Ryr=()=>br("OPENAI_MODEL","gpt-4o"),kyr=mt.getTracer("neurolink.provider.openai"),pne=class extends Ar{constructor(e,t,n,o){let s=o?.apiKey?.trim(),i=s&&s.length>0?s:Cyr(),a=Eyr(o?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:a,apiKey:i}),g.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Kt(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return Ryr()}formatProviderError(e){let t=e,n=t?.type&&typeof t.type=="string"?t.type:void 0,o=[{match:s=>s.statusCode===401||n==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(s.message),errorClass:At,message:s=>/Incorrect API key|Invalid API key/i.test(s.message)?s.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:s=>s.statusCode===429||n==="rate_limit_error"||/rate limit/i.test(s.message),errorClass:Yr,message:"OpenAI rate limit exceeded. Please try again later."},{match:s=>/model_not_found/i.test(s.message),errorClass:wr,message:s=>`Model not found: ${s.modelName}`},...Fr];return fr(e,o,this.providerName,this.modelName)}onStreamStart(e){let t=kyr.startSpan("neurolink.provider.streamText",{kind:vr.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}}),n=!1,o=()=>{n||(n=!0,t.end())};return{onUsage:s=>{t.setAttribute("gen_ai.usage.input_tokens",s.promptTokens+(s.cacheReadTokens??0)+(s.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",s.completionTokens);let i=Xo(this.providerName,e,{input:s.promptTokens,output:s.completionTokens,total:s.totalTokens,...s.cacheReadTokens?{cacheReadTokens:s.cacheReadTokens}:{},...s.cacheCreationTokens?{cacheCreationTokens:s.cacheCreationTokens}:{}});i&&i>0&&t.setAttribute("neurolink.cost",i)},onFinish:(s,i)=>{t.setAttribute("gen_ai.response.finish_reason",s||"unknown"),s==="error"&&t.setStatus({code:$e.ERROR,message:i instanceof Error?i.message:String(i??"stream error")}),o()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let[o]=await this.callEmbeddings(n,[e],"embed");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await this.callEmbeddings(n,e,"embedMany");return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}async callEmbeddings(e,t,n){let o=`${Ii(this.config.baseURL)}/embeddings`,s=yt(),i=ei(3e4,this.providerName,"generate");try{let a=await s(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!a.ok){let u=await a.text().catch(()=>""),p=`OpenAI ${n} failed with status ${a.status}`,m;if(u)try{let f=JSON.parse(u);f.error?.message&&(p=f.error.message),m=f.error?.type}catch{}throw Object.assign(new Error(p),{status:a.status,type:m})}let c=((await a.json()).data??[]).map(u=>u.embedding).filter(u=>Array.isArray(u));if(c.length===0)throw new pt(`OpenAI ${n} returned no embeddings`,this.providerName);return c}finally{i?.cleanup()}}async executeImageGeneration(e){let t=Date.now(),n=e.prompt??e.input?.text??"";if(!n.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");let o=e.model??this.modelName,s=Ii(this.config.baseURL??w1e),i=e,a=i.size??this.aspectRatioToOpenAISize(i.aspectRatio,o),l=i.numberOfImages??1,c;o==="gpt-image-1"||o.startsWith("dall-e-3")?c=1:o.startsWith("dall-e-2")?c=Math.min(Math.max(l,1),10):c=1;let p={model:o,prompt:n,n:c,size:a};o==="gpt-image-1"?i.quality&&(p.quality=i.quality):o.startsWith("dall-e-3")?(p.response_format="b64_json",i.quality&&(p.quality=i.quality),i.style&&(p.style=i.style)):p.response_format="b64_json";let m=12e4,f=new AbortController,h=setTimeout(()=>f.abort(),m),y;try{y=await yt()(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:f.signal})}catch(C){throw C instanceof Error&&C.name==="AbortError"?new Error(`OpenAI image generation timed out after ${m/1e3}s`,{cause:C}):C}finally{clearTimeout(h)}if(!y.ok){let C=await y.text();throw new Error(`OpenAI image generation failed: ${y.status} \u2014 ${C}`)}let b=(await y.json()).data?.[0];if(!b)throw new Error("OpenAI image generation returned no images");let T=b.b64_json;if(!T&&b.url){await ru(b.url);let C=yt(),R=new AbortController,k=setTimeout(()=>R.abort(),6e4),P;try{P=await C(b.url,{signal:R.signal})}catch(A){throw A instanceof Error&&A.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:A}):A}finally{clearTimeout(k)}if(!P.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${b.url} (${P.status})`);T=(await ka(P,26214400,"OpenAI image fallback")).toString("base64")}if(!T)throw new Error("OpenAI image generation returned neither b64_json nor a URL");let w=Date.now()-t;return g.info(`[OpenAIProvider] Generated image (${T.length} base64 chars) in ${w}ms \u2014 model ${o}`),{content:b.revised_prompt??n,provider:this.providerName,model:o,usage:{input:0,output:0,total:0},imageOutput:{base64:T}}}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"}}});var E1e={};ue(E1e,{OpenAIProvider:()=>pne});var C1e=E(()=>{"use strict";_1e()});function Ge(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 K(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 hc=E(()=>{});var M_,cG=E(()=>{M_=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return M_=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 qd(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var qv,Vv=E(()=>{qv=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 Ye,js,Ia,rm,O_,xP,N_,L_,D_,U_,F_,$_,B_,z_,ho=E(()=>{Vv();Ye=class extends Error{},js=class r extends Ye{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 rm({message:n,cause:qv(t)});let s=t,i=s?.error?.type;return e===400?new N_(e,s,n,o,i):e===401?new L_(e,s,n,o,i):e===403?new D_(e,s,n,o,i):e===404?new U_(e,s,n,o,i):e===409?new F_(e,s,n,o,i):e===422?new $_(e,s,n,o,i):e===429?new B_(e,s,n,o,i):e>=500?new z_(e,s,n,o,i):new r(e,s,n,o,i)}},Ia=class extends js{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},rm=class extends js{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},O_=class extends rm{constructor({message:e}={}){super({message:e??"Request timed out."})}},xP=class extends Ye{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},N_=class extends js{},L_=class extends js{},D_=class extends js{},U_=class extends js{},F_=class extends js{},$_=class extends js{},B_=class extends js{},z_=class extends js{}});function uG(r){return typeof r!="object"?{}:r??{}}function gne(r){if(!r)return!0;for(let e in r)return!1;return!0}function k1e(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Iyr,R1e,ml,mne,A1e,dG,nm=E(()=>{ho();Iyr=/^[a-z][a-z0-9+.-]*:/i,R1e=r=>Iyr.test(r),ml=r=>(ml=Array.isArray,ml(r)),mne=ml;A1e=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ye(`${r} must be an integer`);if(e<0)throw new Ye(`${r} must be a positive integer`);return e},dG=r=>{try{return JSON.parse(r)}catch{return}}});var Vd,j_=E(()=>{Vd=(r,e)=>new Promise(t=>{if(e?.aborted)return t();let n=()=>{clearTimeout(o),t()},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r);e?.addEventListener("abort",n,{once:!0})})});var Uu,vP=E(()=>{Uu="0.102.0"});function Pyr(){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 Oyr(){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 O1e,Myr,I1e,P1e,M1e,bP,pG=E(()=>{vP();O1e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Myr=()=>{let r=Pyr();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uu,"X-Stainless-OS":P1e(Deno.build.os),"X-Stainless-Arch":I1e(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":Uu,"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":Uu,"X-Stainless-OS":P1e(globalThis.process.platform??"unknown"),"X-Stainless-Arch":I1e(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Oyr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uu,"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":Uu,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};I1e=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",P1e=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"),bP=()=>M1e??(M1e=Myr())});function N1e(){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 fne(...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 mG(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return fne({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function TP(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 L1e(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 G_=E(()=>{});var D1e,U1e=E(()=>{D1e=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});var hne,yne,xne,F1e,vne=E(()=>{hne="RFC3986",yne=r=>String(r),xne={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yne},F1e="RFC1738"});function B1e(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Tne(r,e){if(ml(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var gG,om,bne,$1e,z1e=E(()=>{vne();nm();gG=(r,e)=>(gG=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),gG(r,e)),om=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),bne=1024,$1e=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=bne){let l=s.length>=bne?s.slice(a,a+bne):s,c=[];for(let u=0;u<l.length;++u){let p=l.charCodeAt(u);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===F1e&&(p===40||p===41)){c[c.length]=l.charAt(u);continue}if(p<128){c[c.length]=om[p];continue}if(p<2048){c[c.length]=om[192|p>>6]+om[128|p&63];continue}if(p<55296||p>=57344){c[c.length]=om[224|p>>12]+om[128|p>>6&63]+om[128|p&63];continue}u+=1,p=65536+((p&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=om[240|p>>18]+om[128|p>>12&63]+om[128|p>>6&63]+om[128|p&63]}i+=c.join("")}return i}});function Dyr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}function V1e(r,e,t,n,o,s,i,a,l,c,u,p,m,f,h,y,x,b){let T=r,w=b,C=0,R=!1;for(;(w=w.get(Sne))!==void 0&&!R;){let M=w.get(r);if(C+=1,typeof M<"u"){if(M===C)throw new RangeError("Cyclic object value");R=!0}typeof w.get(Sne)>"u"&&(C=0)}if(typeof c=="function"?T=c(e,T):T instanceof Date?T=m?.(T):t==="comma"&&ml(T)&&(T=Tne(T,function(M){return M instanceof Date?m?.(M):M})),T===null){if(s)return l&&!y?l(e,Pi.encoder,x,"key",f):e;T=""}if(Dyr(T)||B1e(T)){if(l){let M=y?e:l(e,Pi.encoder,x,"key",f);return[h?.(M)+"="+h?.(l(T,Pi.encoder,x,"value",f))]}return[h?.(e)+"="+h?.(String(T))]}let k=[];if(typeof T>"u")return k;let P;if(t==="comma"&&ml(T))y&&l&&(T=Tne(T,l)),P=[{value:T.length>0?T.join(",")||null:void 0}];else if(ml(c))P=c;else{let M=Object.keys(T);P=u?M.sort(u):M}let I=a?String(e).replace(/\./g,"%2E"):String(e),A=n&&ml(T)&&T.length===1?I+"[]":I;if(o&&ml(T)&&T.length===0)return A+"[]";for(let M=0;M<P.length;++M){let F=P[M],D=typeof F=="object"&&typeof F.value<"u"?F.value:T[F];if(i&&D===null)continue;let N=p&&a?F.replace(/\./g,"%2E"):F,z=ml(T)?typeof t=="function"?t(A,N):A:A+(p?"."+N:"["+N+"]");b.set(r,C);let G=new WeakMap;G.set(Sne,b),q1e(k,V1e(D,z,t,n,o,s,i,a,t==="comma"&&y&&ml(T)?null:l,c,u,p,m,f,h,y,x,G))}return k}function Uyr(r=Pi){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||Pi.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=hne;if(typeof r.format<"u"){if(!gG(xne,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=xne[t],o=Pi.filter;(typeof r.filter=="function"||ml(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in G1e?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=Pi.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Pi.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Pi.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Pi.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Pi.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Pi.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Pi.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Pi.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Pi.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Pi.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Pi.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Pi.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Pi.strictNullHandling}}function H1e(r,e={}){let t=r,n=Uyr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):ml(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof t!="object"||t===null)return"";let a=G1e[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let c=new WeakMap;for(let m=0;m<o.length;++m){let f=o[m];n.skipNulls&&t[f]===null||q1e(i,V1e(t[f],f,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}let u=i.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),u.length>0?p+u:""}var G1e,q1e,j1e,Pi,Sne,K1e=E(()=>{z1e();vne();nm();G1e={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},q1e=function(r,e){Array.prototype.push.apply(r,ml(e)?e:[e])},Pi={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:$1e,encodeValuesOnly:!1,format:hne,formatter:yne,indices:!1,serializeDate(r){return(j1e??(j1e=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};Sne={}});function W1e(r){return H1e(r,{arrayFormat:"brackets"})}var wne=E(()=>{K1e()});function hG(r){if(!r)return;let e;try{e=new URL(r)}catch(n){throw new bn(`Invalid token endpoint base URL "${r}": ${n}`)}if(e.protocol==="https:")return;let t=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(t==="localhost"||t==="127.0.0.1"||t==="::1")))throw new bn(`Refusing to send credential over non-https token endpoint "${r}"`)}async function yG(r,e){let t=await Byr(r),n;try{n=JSON.parse(t)}catch{throw new bn(`Token endpoint returned non-JSON response (status ${r.status})`,r.status,yc(t),e)}if(!n.access_token)throw new bn(`Token endpoint response missing access_token: ${JSON.stringify(yc(n))}`,r.status,yc(n),e);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new bn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,r.status,yc(n),e);return n}function yc(r){if(r==null)return r;if(typeof r=="string"){let e;try{e=JSON.parse(r)}catch{return r.length<=_ne?r:r.slice(0,_ne)+`... <${r.length-_ne} more chars>`}return JSON.stringify(yc(e))}if(typeof r=="object"&&!Array.isArray(r)){let e={};for(let[t,n]of Object.entries(r))$yr.has(t)&&(e[t]=n);return e}return null}async function xG(r,e=t=>console.warn(`anthropic-sdk: ${t}`)){if(typeof process>"u"||process.platform==="win32")return;let t=await Promise.resolve().then(()=>(Bs(),Fd)),n=r,o;try{n=await t.promises.realpath(r),o=await t.promises.stat(n)}catch{return}let s=o.mode&511;if(s&18)throw new bn(`Credentials file at ${n} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(s&36)throw new bn(`Credentials file at ${n} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&e(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function vG(r,e){let t=await Promise.resolve().then(()=>(Bs(),Fd)),o=(await Promise.resolve().then(()=>(An(),uc))).dirname(r);await t.promises.mkdir(o,{recursive:!0,mode:448});let s=`${r}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let i=await t.promises.open(s,"w",384);try{await i.writeFile(JSON.stringify(e,null,2)),await i.sync()}finally{await i.close()}await t.promises.rename(s,r)}catch(i){throw await t.promises.unlink(s).catch(()=>{}),i}try{let i=await t.promises.open(o,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function Byr(r){if(!r.body)return"";let e=r.body.getReader(),t=[],n=0;for(;;){let{done:s,value:i}=await e.read();if(s)break;if(n+i.length>J1e){let a=J1e-n;a>0&&t.push(i.subarray(0,a)),await e.cancel();break}t.push(i),n+=i.length}let o;if(t.length===1)o=t[0];else{o=new Uint8Array(t.reduce((i,a)=>i+a.length,0));let s=0;for(let i of t)o.set(i,s),s+=i.length}return new TextDecoder("utf-8").decode(o)}var X1e,Y1e,fG,Hv,Z1e,Q1e,q_,e$e,J1e,_ne,$yr,bn,V_=E(()=>{ho();X1e="urn:ietf:params:oauth:grant-type:jwt-bearer",Y1e="refresh_token",fG="/v1/oauth/token",Hv="oauth-2025-04-20",Z1e="oidc-federation-2026-04-01",Q1e=120,q_=30,e$e=5,J1e=1<<20;_ne=2e3,$yr=new Set(["error","error_description","error_uri"]);bn=class extends Ye{constructor(e,t=null,n=null,o=null){super(e),this.statusCode=t,this.body=n,this.requestId=o}}});function Hd(){return Math.floor(Date.now()/1e3)}var SP=E(()=>{});var bG,t$e=E(()=>{V_();SP();bG=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){let e=this.nextForce;this.nextForce=!1;let t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;let n=t.expiresAt-Hd();return n>Q1e?t.token:n>q_?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||Hd()-this.lastAdvisoryError<e$e||this.doRefresh().catch(e=>{this.lastAdvisoryError=Hd(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}});var Vr,wP=E(()=>{Vr=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0}});function o$e(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 H_(r){let e;return(r$e??(e=new globalThis.TextEncoder,r$e=e.encode.bind(e)))(r)}function Ene(r){let e;return(n$e??(e=new globalThis.TextDecoder,n$e=e.decode.bind(e)))(r)}var r$e,n$e,TG=E(()=>{});var s$e=E(()=>{ho();TG()});function _P(){}function SG(r,e,t){return!e||wG[r]>wG[t]?_P:e[r].bind(e)}function fn(r){let e=r.logger,t=r.logLevel??"off";if(!e)return zyr;let n=i$e.get(e);if(n&&n[0]===t)return n[1];let o={error:SG("error",e,t),warn:SG("warn",e,t),info:SG("info",e,t),debug:SG("debug",e,t)};return i$e.set(e,[t,o]),o}var wG,Cne,zyr,i$e,sm,Eg=E(()=>{nm();wG={off:0,error:200,warn:300,info:400,debug:500},Cne=(r,e,t)=>{if(r){if(k1e(wG,r))return r;fn(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(wG))}`)}};zyr={error:_P,warn:_P,info:_P,debug:_P},i$e=new WeakMap;sm=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()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r)});var Rne=E(()=>{nm();s$e();wP();Eg();cG();j_();wne()});function a$e(r){if(!r)throw new Error("profile name is empty");if(r==="."||r==="..")throw new Error(`profile name "${r}" is not allowed`);if(r.includes("/")||r.includes("\\"))throw new Error(`profile name "${r}" must not contain path separators`);if(!jyr.test(r))throw new Error(`profile name "${r}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var _G,jyr,l$e,c$e,kne,Gyr,u$e,Ane=E(()=>{pG();Rne();_G="1.0",jyr=/^[A-Za-z0-9_.-]+$/;l$e=async r=>{var e,t;let n=await kne();if(n===null)return null;let o=r??await u$e();if(o===null)return null;a$e(o);let s=await Promise.resolve().then(()=>(Bs(),Fd)),a=(await Promise.resolve().then(()=>(An(),uc))).join(n,"configs",`${o}.json`),l;try{l=await s.promises.readFile(a,"utf-8")}catch(p){if(p?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${p}`);l=null}if(l===null){let p=Vr("ANTHROPIC_ORGANIZATION_ID"),m=Vr("ANTHROPIC_IDENTITY_TOKEN_FILE"),f=Vr("ANTHROPIC_FEDERATION_RULE_ID");return f&&p?{fromFile:!1,config:{organization_id:p,workspace_id:Vr("ANTHROPIC_WORKSPACE_ID"),base_url:Vr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:f,service_account_id:Vr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Vr("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(p){throw new Error(`failed to parse config file ${a}: ${p}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);let u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=Vr("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=Vr("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=Vr("ANTHROPIC_BASE_URL")),(e=c.authentication).scope??(e.scope=Vr("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){let p=Vr("ANTHROPIC_IDENTITY_TOKEN_FILE");p&&(c.authentication.identity_token={source:"file",path:p})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=Vr("ANTHROPIC_FEDERATION_RULE_ID")??""),(t=c.authentication).service_account_id??(t.service_account_id=Vr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},c$e=async(r,e)=>{if(r?.authentication.credentials_path)return r.authentication.credentials_path;let t=await kne();if(!t)return null;let n=e??await u$e();return n?(a$e(n),(await Promise.resolve().then(()=>(An(),uc))).join(t,"credentials",`${n}.json`)):null},kne=async()=>{if(!Gyr())return null;let r=await Promise.resolve().then(()=>(An(),uc)),e=Vr("ANTHROPIC_CONFIG_DIR");if(e)return e;if(bP()["X-Stainless-OS"]==="Windows"){let s=Vr("APPDATA");if(s)return r.join(s,"Anthropic");let i=Vr("USERPROFILE");return i?r.join(i,"AppData","Roaming","Anthropic"):null}let n=Vr("XDG_CONFIG_HOME");if(n)return r.join(n,"anthropic");let o=Vr("HOME");return o?r.join(o,".config","anthropic"):null},Gyr=()=>{let r=bP()["X-Stainless-Runtime"];return r==="node"||r==="deno"},u$e=async()=>{let r=await kne();if(!r)return null;let e=Vr("ANTHROPIC_PROFILE");if(e)return e;let t=await Promise.resolve().then(()=>(Bs(),Fd)),o=(await Promise.resolve().then(()=>(An(),uc))).join(r,"active_config");try{return(await t.promises.readFile(o,"utf-8")).trim()||"default"}catch(s){if(s?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${s}`);return"default"}}});function Ine(r){if(!r)throw new Ye("Identity token file path is empty");return async()=>{let e=await Promise.resolve().then(()=>(Bs(),Fd)),t;try{t=await e.promises.readFile(r,"utf-8")}catch(o){throw new Ye(`Failed to read identity token file at ${r}: ${o}`)}let n=t.trim();if(!n)throw new Ye(`Identity token file at ${r} is empty`);return n}}function d$e(r){if(!r)throw new Ye("Identity token value is empty");return()=>r}var p$e=E(()=>{ho()});function m$e(r){return async()=>{hG(r.baseURL);let e=await r.identityTokenProvider();if(e.length>16*1024)throw new bn(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let t={grant_type:X1e,assertion:e,federation_rule_id:r.federationRuleId,organization_id:r.organizationId};r.serviceAccountId&&(t.service_account_id=r.serviceAccountId),r.workspaceId&&(t.workspace_id=r.workspaceId);let n=`${r.baseURL}${fG}`,o;try{o=await r.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Hv},${Z1e}`,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${Uu} oidcFederationProvider`},body:JSON.stringify(t)})}catch(l){throw new bn(`Failed to reach token endpoint ${n}: ${l}`)}let s=o.headers.get("Request-Id");if(!o.ok){let l=await o.text().catch(()=>""),c=yc(l),u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${r.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new bn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${c}${u}`,o.status,c,s)}let i=await yG(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new bn(`Token endpoint response missing required fields: ${JSON.stringify(yc(i))}`,o.status,yc(i),s);return{token:i.access_token,expiresAt:Hd()+a}}}var g$e=E(()=>{V_();SP();vP()});function f$e(r){return async e=>{let t=await Promise.resolve().then(()=>(Bs(),Fd));await xG(r.credentialsPath,r.onSafetyWarning);let n;try{n=await t.promises.readFile(r.credentialsPath,"utf-8")}catch(x){throw new bn(`Credentials file not found at ${r.credentialsPath}: ${x}`)}let o;try{o=JSON.parse(n)}catch(x){throw new bn(`Credentials file at ${r.credentialsPath} is not valid JSON: ${x}`)}let s=o.access_token;if(!s)throw new bn(`Credentials file at ${r.credentialsPath} must include 'access_token'`);let i=o.expires_at;if(!e?.forceRefresh&&(i==null||Hd()<i-q_))return{token:s,expiresAt:i??null};let a=o.refresh_token;if(!r.clientId||!a)throw new bn(`Access token at ${r.credentialsPath} has expired and no refresh is available (client_id ${r.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);hG(r.baseURL);let l={grant_type:Y1e,refresh_token:a,client_id:r.clientId},c=`${r.baseURL}${fG}`,u;try{u=await r.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Hv,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${Uu} userOAuthProvider`},body:JSON.stringify(l)})}catch(x){throw new bn(`User OAuth refresh failed to reach token endpoint: ${x}`)}let p=u.headers.get("Request-Id");if(!u.ok){let x=await u.text().catch(()=>"");throw new bn(`User OAuth refresh failed (HTTP ${u.status}): ${yc(x)}`,u.status,yc(x),p)}let m=await yG(u,p),f=Number(m.expires_in);if(!Number.isFinite(f))throw new bn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(yc(m))}`,u.status,yc(m),p);let h=Hd()+f,y=m.refresh_token||a;return await vG(r.credentialsPath,{...o,version:_G,type:"oauth_token",access_token:m.access_token,expires_at:h,refresh_token:y}),{token:m.access_token,expiresAt:h}}}var h$e=E(()=>{Ane();V_();SP();vP()});function Pne(r,e){let t=r.authentication.credentials_path??null,n=(r.base_url||e.baseURL).replace(/\/+$/,""),o=qyr(r,t,n,e),s={};return r.workspace_id&&r.authentication.type==="user_oauth"&&(s["anthropic-workspace-id"]=r.workspace_id),{provider:o,extraHeaders:s,baseURL:r.base_url||void 0}}async function y$e(r,e){let t=await l$e(e);if(!t)return null;let{config:n,fromFile:o}=t,s=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await c$e(n,e)??void 0}};return Pne(s,r)}function qyr(r,e,t,n){switch(r.authentication.type){case"oidc_federation":{let o=r.authentication,s=Vyr(o);if(!s)throw new bn("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new bn("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!r.organization_id)throw new bn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let i=m$e({identityTokenProvider:s,federationRuleId:o.federation_rule_id,organizationId:r.organization_id,serviceAccountId:o.service_account_id,workspaceId:r.workspace_id,baseURL:t,fetch:n.fetch,userAgent:n.userAgent});return e?Hyr(i,e,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!e)throw new bn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return f$e({credentialsPath:e,clientId:r.authentication.client_id,baseURL:t,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{let o=r.authentication.type;throw new bn(`authentication.type "${o}" is not a known authentication type`)}}}function Vyr(r){if(r.identity_token){let n=r.identity_token.source;if(n!=="file")throw new bn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!r.identity_token.path)throw new bn('identity_token.source "file" requires a non-empty path');return Ine(r.identity_token.path)}let e=Vr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return Ine(e);let t=Vr("ANTHROPIC_IDENTITY_TOKEN");return t?d$e(t):null}function Hyr(r,e,t,n){return async o=>{let s=await Promise.resolve().then(()=>(Bs(),Fd));await xG(e,n);let i;try{let l=await s.promises.readFile(e,"utf-8");i=JSON.parse(l);let c=i?.access_token;if(c&&!o?.forceRefresh){let u=i?.expires_at;if(u==null||Hd()<u-q_)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&t?.(l)}let a=await r(o);try{await vG(e,{...i??{},version:_G,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){t?.(l)}return a}}var x$e=E(()=>{wP();Ane();V_();SP();p$e();g$e();h$e()});function Kyr(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 v$e(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 ou,su,Cg,Mne=E(()=>{hc();TG();Cg=class{constructor(){ou.set(this,void 0),su.set(this,void 0),Ge(this,ou,new Uint8Array,"f"),Ge(this,su,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?H_(e):e;Ge(this,ou,o$e([K(this,ou,"f"),t]),"f");let n=[],o;for(;(o=Kyr(K(this,ou,"f"),K(this,su,"f")))!=null;){if(o.carriage&&K(this,su,"f")==null){Ge(this,su,o.index,"f");continue}if(K(this,su,"f")!=null&&(o.index!==K(this,su,"f")+1||o.carriage)){n.push(Ene(K(this,ou,"f").subarray(0,K(this,su,"f")-1))),Ge(this,ou,K(this,ou,"f").subarray(K(this,su,"f")),"f"),Ge(this,su,null,"f");continue}let s=K(this,su,"f")!==null?o.preceding-1:o.preceding,i=Ene(K(this,ou,"f").subarray(0,s));n.push(i),Ge(this,ou,K(this,ou,"f").subarray(o.index),"f"),Ge(this,su,null,"f")}return n}flush(){return K(this,ou,"f").length?this.decode(`
1071
+ `):"";default:return tm(r)}},xyr=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")}`},vyr=r=>{if(typeof r=="string")return r;if(!Array.isArray(r))return tm(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=xyr(o);s&&e.push({type:"image_url",image_url:{url:s}})}}return e.length===1&&e[0].type==="text"?e[0].text:e},tne=(r,e)=>{let t=[];for(let n of r)switch(n.role){case"system":t.push({role:"system",content:typeof n.content=="string"?n.content:tm(n.content)});break;case"user":t.push({role:"user",content:vyr(n.content)});break;case"assistant":{let o=Array.isArray(n.content)?n.content:[n.content],s=[],i=[];for(let l of o)if(l&&typeof l=="object"){let c=l;if(c.type==="text")s.push({type:"text",text:l.text??""});else if(c.type==="tool-call"){let u=l,p=u.toolName??"";i.push({id:u.toolCallId??"",type:"function",function:{name:e?.get(p)??p,arguments:gP(u.input)}})}}else typeof l=="string"&&s.push({type:"text",text:l});let a=s.length===0?null:s.length===1&&s[0].type==="text"?s[0].text:s;t.push({role:"assistant",content:a,...i.length>0?{tool_calls:i}:{}});break}case"tool":{if(Array.isArray(n.content))for(let o of n.content){if(!o||typeof o!="object")continue;let s=o;s.type==="tool-result"&&t.push({role:"tool",tool_call_id:s.toolCallId??"",content:ene(s.output)})}else typeof n.content=="string"&&t.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return t},rne=(r,e)=>{let t=Object.entries(r);if(t.length===0)return;let n=[];for(let[o,s]of t){let i=s,a=i.inputSchema??i.parameters,l=a?IQ(Rn(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:e?.get(o)??o,...i.description?{description:i.description}:{},parameters:l}})}return n},u1e=(r,e)=>{if(!r||r.length===0)return;let t=[];for(let n of r)n.type==="function"&&t.push({type:"function",function:{name:e?.get(n.name)??n.name,...n.description?{description:n.description}:{},parameters:IQ(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return t.length>0?t:void 0},d1e=(r,e)=>{switch(r.type){case"auto":case"none":case"required":return r.type;case"tool":return{type:"function",function:{name:e?.get(r.toolName)??r.toolName}}}},p1e=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"},m1e=(r,e)=>{if(r){if(r==="auto"||r==="none"||r==="required")return r;if(typeof r=="object"&&r!==null){let t=r;if(t.type==="tool"&&t.toolName)return{type:"function",function:{name:e?.get(t.toolName)??t.toolName}}}}},byr=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}),nne=r=>r.response_format?.type==="json_object"&&!byr(r.messages)?{...r,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...r.messages]}:r,g1e=r=>/^(o\d|gpt-5)/i.test(r.replace(/^.*\//,"")),one=r=>{let{modelId:e,messages:t,options:n,tools:o,toolChoice:s,streaming:i,responseFormat:a}=r,l={model:e,messages:t,...i?{stream:!0}:{},...i?{stream_options:{include_usage:!0}}:{}};n.maxTokens!==void 0&&n.maxTokens!==null&&(l.max_tokens=n.maxTokens);let c=Ea("openai-compatible",e,{...n.temperature!==void 0&&n.temperature!==null?{temperature:n.temperature}:{},...n.topP!==void 0&&n.topP!==null?{topP:n.topP}:{}},"openaiCompatible.buildBody");return c.temperature!==void 0&&(l.temperature=c.temperature),c.topP!==void 0&&(l.top_p=c.topP),n.presencePenalty!==void 0&&n.presencePenalty!==null&&(l.presence_penalty=n.presencePenalty),n.frequencyPenalty!==void 0&&n.frequencyPenalty!==null&&(l.frequency_penalty=n.frequencyPenalty),n.seed!==void 0&&n.seed!==null&&(l.seed=n.seed),n.stopSequences&&n.stopSequences.length>0&&(l.stop=n.stopSequences),o&&(l.tools=o),s!==void 0&&(l.tool_choice=s),a&&(l.response_format=a),n.extraBody&&Object.assign(l,n.extraBody),l},f1e=async(r,e,t)=>{let n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder,s,a=VS({onEvent:c=>{let u=c.data;if(!u||u==="[DONE]")return;let p;try{p=JSON.parse(u)}catch(y){s=y instanceof Error?y:new Error(String(y));return}p.usage&&(n.usage=p.usage);let m=p.choices?.[0];if(!m)return;let f=m.delta;f?.content&&(n.text+=f.content,e(f.content));let h=f?.reasoning_content||f?.reasoning;if(h&&(n.reasoning+=h,t?.(h)),f?.tool_calls)for(let y of f.tool_calls){let x=n.toolCalls.get(y.index);x?y.id&&(x.id=y.id):(x={id:y.id??`call_${y.index}_${Date.now()}`,name:y.function?.name??"",argsBuffered:""},n.toolCalls.set(y.index,x)),y.function?.name&&(x.name=y.function.name),y.function?.arguments&&(x.argsBuffered+=y.function.arguments)}m.finish_reason&&(n.finishReason=m.finish_reason)}}),l=r.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;a.feed(o.decode(u,{stream:!0}))}a.feed(o.decode())}finally{l.releaseLock()}if(s)throw s;return n},fP=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.responseHeaders=Object.fromEntries([...t.headers.entries()].filter(([a])=>{let l=a.toLowerCase();return l==="retry-after"||l.startsWith("x-ratelimit-")})),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},oG=()=>{let r=()=>{},e=new Promise(o=>{r=o}),t=()=>{},n=new Promise(o=>{t=o});return{usagePromise:e,finishPromise:n,resolveUsage:r,resolveFinish:t}},sG=()=>{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})}},h1e=(r,e)=>{if(!r)return e;if(!e)return r;let t=(r.prompt_tokens_details?.cached_tokens??0)+(e.prompt_tokens_details?.cached_tokens??0),n=(r.completion_tokens_details?.reasoning_tokens??0)+(e.completion_tokens_details?.reasoning_tokens??0),o=s=>s.total_tokens||(s.prompt_tokens??0)+(s.completion_tokens??0);return{prompt_tokens:(r.prompt_tokens??0)+(e.prompt_tokens??0),completion_tokens:(r.completion_tokens??0)+(e.completion_tokens??0),total_tokens:o(r)+o(e),...t>0?{prompt_tokens_details:{cached_tokens:t}}:{},...n>0?{completion_tokens_details:{reasoning_tokens:n}}:{}}}});function iG(r){if(typeof r=="string")return r;if(r==null)return"";try{return JSON.stringify(r)??""}catch{return"x".repeat(2e5)}}function Syr(r,e){let t=iG(r.content);return r.role==="assistant"&&r.tool_calls&&(t+=iG(r.tool_calls)),zt(t,e)+4}function wyr(r,e){if(r.role!=="tool")return;let t=iG(r.content),n={maxBytes:y1e,maxLines:x1e};if(!KB(t,n))return;let{preview:o}=hi(t,n);return zt(o,e)+4}function _yr(r,e){return r.map(t=>{let n=Syr(t,e);if(t.role==="tool"){let o=wyr(t,e);return{kind:"toolResult",tokens:n,...o!==void 0?{previewTokens:o}:{}}}return t.role==="assistant"&&t.tool_calls?.length?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function v1e(r){let{conversation:e,availableInputTokens:t,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=r,l=_yr(e,o),c=n+l.reduce((y,x)=>y+x.tokens,0),u=1;s&&s>0&&i&&i>0&&(u=Math.min(3,Math.max(1,s/i)));let p=C_(l,{availableInputTokens:t,fixedOverheadTokens:n,calibration:u});if(!p.fire){a?.(c);return}let m=new Set(p.truncate),f=new Set(p.drop),h=[];for(let y=0;y<e.length;y++){if(f.has(y))continue;let x=e[y];if(m.has(y)&&x.role==="tool"){let{preview:b}=hi(iG(x.content),{maxBytes:y1e,maxLines:x1e});h.push({...x,content:b});continue}h.push(x)}if(f.size>0){let y=h.findIndex(x=>x.role==="tool"||x.role==="assistant"&&x.tool_calls);y<0&&(y=Math.min(1,h.length)),h.splice(y,0,{role:"user",content:Tyr})}return g.info("[OpenAICompatLoopGuard] Reclaimed agent-loop context",{provider:o,messagesBefore:e.length,messagesAfter:h.length,toolOutputsTruncated:p.truncate.length,messagesDropped:p.drop.length,projectedTokens:p.projectedTokens,calibration:u}),a?.(p.projectedTokens),h}var y1e,x1e,Tyr,b1e=E(()=>{"use strict";fi();Rh();Vj();X();y1e=2048,x1e=60,Tyr="[Earlier tool exchanges were removed to fit the context window.]"});function hP(r){let e=sne(r);return e?T1e.some(({patterns:t})=>t.some(n=>n.test(e))):!1}function S1e(r){let e=sne(r);if(!e)return null;for(let{provider:t,patterns:n}of T1e)if(n.some(o=>o.test(e)))return t;return null}function yP(r){let e=sne(r);if(!e||e.length>2e3)return null;let t=e.match(/resulted\s+in\s+(\d[\d,]{0,19})\s*tokens/i),n=e.match(/maximum\s+context\s+length\s+is\s+(\d[\d,]{0,19})/i);if(t&&n)return{actualTokens:parseInt(t[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10)};let o=e.match(/prompt\s+contains\s+at\s+least\s+(\d[\d,]{0,19})\s+input\s+tokens/i);if(o&&n){let a=e.match(/requested\s+(\d[\d,]{0,19})\s+output\s+tokens/i);return{actualTokens:parseInt(o[1].replace(/,/g,""),10),budgetTokens:parseInt(n[1].replace(/,/g,""),10),...a?{requestedOutputTokens:parseInt(a[1].replace(/,/g,""),10)}:{}}}let s=e.match(/(\d[\d,]{0,19})\s*tokens?\s*[>:]\s*(\d[\d,]{0,19})/i);if(s)return{actualTokens:parseInt(s[1].replace(/,/g,""),10),budgetTokens:parseInt(s[2].replace(/,/g,""),10)};let i=e.match(/(\d[\d,]{0,19})\s*(?:>|exceeds)\s*(\d[\d,]{0,19})/i);return i?{actualTokens:parseInt(i[1].replace(/,/g,""),10),budgetTokens:parseInt(i[2].replace(/,/g,""),10)}:null}function sne(r){if(!r)return null;if(typeof r=="string")return r;if(r instanceof Error){let e=r.message,t=r?.cause;return t instanceof Error?`${e} ${t.message}`:e}if(typeof r=="object"){let e=r;if(typeof e.message=="string")return e.message;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){let t=e.error;if(typeof t.message=="string")return t.message}}return null}var T1e,ine=E(()=>{"use strict";T1e=[{provider:"openai",patterns:[/This model's maximum context length is/i,/tokens\. However, (?:your messages|you requested)/i,/reduce the length of the messages/i,/Please reduce the length/i]},{provider:"azure",patterns:[/content_length_exceeded/i]},{provider:"google",patterns:[/RESOURCE_EXHAUSTED/i,/exceeds the maximum number of tokens/i,/content is too long/i,/request payload size exceeds/i,/input token limit/i]},{provider:"bedrock",patterns:[/ValidationException.*token/i,/Input is too long/i,/exceeds the model's maximum/i]},{provider:"mistral",patterns:[/context length exceeded/i,/maximum number of tokens/i]},{provider:"openrouter",patterns:[/context_length_exceeded/i]},{provider:"anthropic",patterns:[/prompt is too long/i,/input is too long/i,/too many tokens/i,/maximum context length/i]}]});var Aa,ane=E(()=>{"use strict";Aa=class extends Error{estimatedTokens;availableTokens;stagesUsed;breakdown;constructor(e,t){super(e),this.name="ContextBudgetExceededError",this.estimatedTokens=t.estimatedTokens,this.availableTokens=t.availableTokens,this.stagesUsed=t.stagesUsed,this.breakdown=t.breakdown}}});var lne,aG,cne=E(()=>{"use strict";GI();X();jw();Bp();lne=class{async collectUsage(e){try{let t=await e.usage;return t?Od(t):(g.debug("No usage data available from stream result"),jQ())}catch(t){return Sa.isInstance(t)?g.debug("No output generated from stream \u2014 returning empty usage"):g.warn("Failed to collect usage from stream result",{error:t}),jQ()}}async collectMetadata(e){try{let[t,n]=await Promise.all([e.response,e.finishReason]);return{id:t?.id,model:t?.model,timestamp:t?.timestamp instanceof Date?t.timestamp.getTime():t?.timestamp||Date.now(),finishReason:n}}catch(t){return Sa.isInstance(t)?g.debug("No output generated from stream \u2014 returning default metadata"):g.warn("Failed to collect metadata from stream result",{error:t}),{timestamp:Date.now(),finishReason:"error"}}}async createAnalytics(e,t,n,o,s){try{let[i,a]=await Promise.all([this.collectUsage(n),this.collectMetadata(n)]),[l,c,u,p]=await Promise.all([Promise.resolve(n.text).catch(()=>""),Promise.resolve(n.finishReason).catch(()=>"error"),Promise.resolve(n.toolResults||[]).catch(()=>[]),Promise.resolve(n.toolCalls||[]).catch(()=>[])]);return qh(e,t,{usage:i,content:l,response:a,finishReason:c,toolResults:u,toolCalls:p},o,{...s,streamingMode:!0,responseId:a.id,finishReason:c})}catch(i){return g.error("Failed to create analytics from stream result",{provider:e,model:t,error:i instanceof Error?i.message:String(i)}),qh(e,t,{usage:{input:0,output:0,total:0}},o,{...s,streamingMode:!0,analyticsError:!0})}}cleanup(){let e=process.memoryUsage().heapUsed,t=500*1024*1024;typeof global<"u"&&global.gc&&e>t&&global.gc()}},aG=new lne});function lG(r,e,t){return!t||!e||Object.keys(e).length===0?"none":r.toolChoice??"auto"}var une=E(()=>{"use strict"});var dne,Ar,ri=E(()=>{"use strict";yr();Ld();b1e();ine();ane();Qc();us();cne();io();X();Or();Bp();Cj();Il();aI();une();jp();_h();zw();wg();dne=512,Ar=class extends so{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}suppressResponseFormatWithTools(){return!0}adjustRequestBody(e,t){return e}adjustBodyAfter400(e,t){}resolveWireMaxTokens(e,t,n,o){let s=VB(this.providerName,e),i=t;s!==void 0&&(i===void 0||i>s)&&(i!==void 0&&g.debug(`${this.providerName}: clamping max_tokens ${i} to the advertised ${e} output ceiling ${s}`),i=s);let a=_Oe(this.providerName,e);if(a!==void 0){let l=Qre(n,o,this.providerName),c=a-l-dne;if(c<=0)throw new Aa(`Estimated input (${l} tokens) alone exceeds the ${this.providerName}/${e} context window advertised by the serving infrastructure (${a} tokens). Reduce the prompt/conversation size \u2014 no max_tokens value can make this request fit.`,{estimatedTokens:l,availableTokens:Math.max(0,a-dne),stagesUsed:[],breakdown:{}});i!==void 0&&i>c&&(g.warn(`${this.providerName}: max_tokens ${i} cannot fit the ${e} window (${a}) with ~${l} input tokens \u2014 re-fitting to ${c}`),i=c)}return i}correctBodyAfterContextOverflow(e,t){if(!hP(t))return;let n=yP(t)??yP(t.responseBody);if(!n||n.budgetTokens<=0)return;qB(this.providerName,e.model,n.budgetTokens);let o=typeof e.max_tokens=="number"?e.max_tokens:n.requestedOutputTokens;if(o===void 0||n.actualTokens<=0)return;let s=n.budgetTokens-n.actualTokens-dne;if(!(s<=0||s>=o))return g.warn(`${this.providerName}: ${e.model} rejected the request as over-window \u2014 retrying once with max_tokens re-fit from the provider's own numbers`,{window:n.budgetTokens,inputTokens:n.actualTokens,previousMaxTokens:o,refitMaxTokens:s}),{...e,max_tokens:s}}onStreamStart(e){}shouldAutoDiscoverModel(){return!0}getChatCompletionsURL(e){return`${Ii(this.config.baseURL)}/chat/completions`}getAuthHeaders(){return{Authorization:`Bearer ${this.config.apiKey}`}}async validateConfiguration(){return typeof this.config.apiKey=="string"&&this.config.apiKey.trim().length>0}async probeModelsEndpoint(e={}){try{let t=`${Ii(this.config.baseURL)}/models`,o=await yt()(t,{headers:{...e,"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)});return o.ok?!!(await o.json().catch(()=>null))?.data?.some(i=>typeof i?.id=="string"&&i.id.trim().length>0):!1}catch(t){return g.debug(`[${this.constructor.name}] probeModelsEndpoint failed`,{baseURL:Kt(this.config.baseURL),error:t instanceof Error?t.message:String(t)}),!1}}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:this.getDefaultModel(),baseURL:this.config.baseURL}}async getAISDKModel(){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=yt(),o=this.getAuthHeaders.bind(this),s=this.providerName,i=this.adjustBuildBodyOptions.bind(this),a=this.adjustResponseFormat.bind(this),l=this.adjustRequestBody.bind(this),c=this.adjustBodyAfter400.bind(this),u=this.correctBodyAfterContextOverflow.bind(this),p=this.resolveWireMaxTokens.bind(this),m=this.suppressResponseFormatWithTools.bind(this),f=h=>this.getTimeout(h??{});return{specificationVersion:"v3",provider:s,modelId:e,supportedUrls:{},doGenerate:async h=>{let y=nG((h.tools??[]).filter($=>$.type==="function").map($=>$.name)),x=tne(h.prompt,y?.toWire),b=Array.isArray(h.tools)&&h.tools.length>0,T=h.responseFormat&&!(b&&m())?a(p1e(h.responseFormat),e):void 0,w=u1e(h.tools,y?.toWire),C=p(e,h.maxOutputTokens,x,w),R=nne(l(one({modelId:e,messages:x,options:i(e,{maxTokens:C,temperature:h.temperature,topP:h.topP,presencePenalty:h.presencePenalty,frequencyPenalty:h.frequencyPenalty,seed:h.seed,stopSequences:h.stopSequences}),tools:w,...h.toolChoice?{toolChoice:d1e(h.toolChoice,y?.toWire)}:{},streaming:!1,...T?{responseFormat:T}:{}}),e)),k=h.providerOptions?.neurolink?.timeoutMs,P=ei(typeof k=="number"?k:f(h),s,"generate"),{signal:I,dispose:A}=uMe(h.abortSignal,P?.controller.signal),M;try{let $=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(R),...I?{signal:I}:{}});if(!$.ok){let O=await fP(t,R,$),W=$.status===400?(()=>{let re=O,te=u(R,re);return c(te??R,re)??te})():void 0;if(!W)throw O;if($=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(W),...I?{signal:I}:{}}),!$.ok)throw await fP(t,W,$)}M=await $.json()}finally{P?.cleanup(),A()}let F=M.choices?.[0],D=(typeof F?.message?.content=="string"?F.message.content:"")??"",N=[],z=F?.message?.reasoning_content||F?.message?.reasoning;typeof z=="string"&&z.length>0&&N.push({type:"reasoning",text:z}),D.length>0&&N.push({type:"text",text:D});for(let $ of F?.message?.tool_calls??[])N.push({type:"tool-call",toolCallId:$.id,toolName:y?.fromWire.get($.function.name)??$.function.name,input:$.function.arguments??""});let G=F?.finish_reason;return{content:N,finishReason:{unified:G==="length"?"length":G==="tool_calls"||G==="function_call"?"tool-calls":G==="content_filter"?"content-filter":"stop",raw:G??"stop"},usage:{inputTokens:{total:M.usage?.prompt_tokens,noCache:M.usage?.prompt_tokens!==void 0&&M.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.max(0,M.usage.prompt_tokens-M.usage.prompt_tokens_details.cached_tokens):M.usage?.prompt_tokens,cacheRead:M.usage?.prompt_tokens!==void 0&&M.usage?.prompt_tokens_details?.cached_tokens!==void 0?Math.min(M.usage.prompt_tokens_details.cached_tokens,M.usage.prompt_tokens):M.usage?.prompt_tokens_details?.cached_tokens,cacheWrite:void 0},outputTokens:{total:M.usage?.completion_tokens,text:M.usage?.completion_tokens!==void 0&&M.usage?.completion_tokens_details?.reasoning_tokens!==void 0?Math.max(0,M.usage.completion_tokens-M.usage.completion_tokens_details.reasoning_tokens):M.usage?.completion_tokens,reasoning:M.usage?.completion_tokens_details?.reasoning_tokens}},warnings:[],request:{body:R},response:{...M.id?{id:M.id}:{},...M.model?{modelId:M.model}:{},headers:{},body:M}}},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=ei(o,this.providerName,"stream"),i=new AbortController,a=wB([e.abortSignal,s?.controller.signal,i.signal]).signal,l,c,u,p,m,f;try{l=await this.resolveModelName();let $=!e.disableTools&&this.supportsTools();c=$?e.tools||await this.getAllTools():{},u=$?nG(Object.keys(c)):void 0,p=$?rne(c,u?.toWire):void 0,m=m1e(lG(e,c,$),u?.toWire);let O=await this.buildMessagesForStream(e);f=tne(O,u?.toWire)}catch($){throw s?.cleanup(),$}let h=this.getChatCompletionsURL(l),y=yt(),x=e.maxSteps||cs,b=this.neurolink?.getEventEmitter(),T=[],w=[],{usagePromise:C,finishPromise:R,resolveUsage:k,resolveFinish:P}=oG(),{pushChunk:I,nextChunk:A}=sG(),M=this.onStreamStart(l),F=this.runStreamLoop({maxSteps:x,modelId:l,url:h,fetchImpl:y,abortSignal:a,options:e,conversation:f,openAITools:p,openAIToolChoice:m,toolsRecord:c,toolNameFromWire:u?.fromWire,emitter:b,toolsUsed:T,toolExecutionSummaries:w,pushChunk:I,resolveUsage:k,resolveFinish:P}),D,N=$=>{D=$};M?.onUsage&&C.then(M.onUsage).catch(()=>{}),M?.onFinish&&R.then($=>M.onFinish?.($,D)).catch(()=>{});let z=this.providerName,B={stream:async function*(){let $=0;try{for(;;){let O=await A();if("done"in O)break;"content"in O&&typeof O.content=="string"&&O.content.length>0&&$++,yield O}if(await F,$===0&&T.length===0){g.warn(`${z}: Stream produced no output \u2014 emitting enriched sentinel`);let O=new Sa({message:"Stream produced no output"}),W=await Jp(O,void 0,D);Xp(W),yield W}}catch(O){if(Sa.isInstance(O)){let re=await Jp(O,void 0,D);Xp(re),yield re;return}let W=await Jp(O,void 0,D);throw Xp(W),yield W,O}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:l,analytics:aG.createAnalytics(this.providerName,l,{textStream:(async function*(){})(),usage:C,finishReason:R},Date.now()-n,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),toolsUsed:T,metadata:{startTime:n,streamId:`${this.providerName}-${Date.now()}`}};return Object.defineProperty(B,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>xv(w.map($=>({toolName:$.toolName,input:$.input,output:$.output,duration:$.endTime.getTime()-$.startTime.getTime()})))}),F.finally(()=>s?.cleanup()).catch($=>{N($)}),B}async runStreamLoop(e){let{maxSteps:t,modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:l,openAITools:c,openAIToolChoice:u,toolsRecord:p,toolNameFromWire:m,emitter:f,toolsUsed:h,toolExecutionSummaries:y,pushChunk:x,resolveUsage:b,resolveFinish:T}=e,w=null,C,R=()=>{let k=C?.prompt_tokens??0,P=C?.completion_tokens??0,I=Math.min(C?.prompt_tokens_details?.cached_tokens??0,k),A=Math.min(Math.max(0,C?.completion_tokens_details?.reasoning_tokens??0),P);return{promptTokens:k-I,completionTokens:P,totalTokens:C?.total_tokens||k+P,...I>0?{cacheReadTokens:I}:{},...A>0?{reasoningTokens:A}:{}}};try{let k=m,P,I;for(let A=0;A<t;A++){if(c){let D=new Set(c.map(z=>k?.get(z.function.name)??z.function.name)),N=Object.fromEntries(Object.entries(p).filter(([z])=>!D.has(z)));if(Object.keys(N).length>0){let z=nG(Object.keys(N),new Set(c.map(G=>G.function.name)));if(z){k??=new Map;for(let[G,B]of z.fromWire)k.set(G,B)}c.push(...rne(N,z?.toWire)??[]),g.info(`${this.providerName}: ${Object.keys(N).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(N).join(", ")}`)}}let M=v1e({conversation:l,availableInputTokens:gi(this.providerName,n,a.maxTokens??void 0),fixedOverheadTokens:Qre([],c,this.providerName),provider:this.providerName,observedPromptTokens:P,previousSentEstimate:I,onSentEstimate:D=>{I=D}});M&&(l.length=0,l.push(...M));let F=await this.streamOneStep({modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:l,openAITools:c,openAIToolChoice:u,pushChunk:x});if(P=F.usage?.prompt_tokens,w=F.finishReason,F.usage&&(C=h1e(C,F.usage)),F.toolCalls.size===0)break;await this.executeToolBatch({stepResult:F,conversation:l,toolsRecord:p,toolNameFromWire:k,emitter:f,toolsUsed:h,toolExecutionSummaries:y,options:a})}return b(R()),T(w??"stop"),x({done:!0}),{finishReason:w??"stop",usage:C}}catch(k){throw g.error(`${this.providerName}: Stream error`,{error:k instanceof Error?k.message:String(k)}),b(R()),T("error"),x({done:!0}),k}}async streamOneStep(e){let t=this.resolveWireMaxTokens(e.modelId,e.options.maxTokens??void 0,e.conversation,e.openAITools),n=t!==e.options.maxTokens?{...e.options,maxTokens:t}:e.options,o=nne(this.adjustRequestBody(one({modelId:e.modelId,messages:e.conversation,options:this.adjustBuildBodyOptions(e.modelId,n),tools:e.openAITools,...e.openAIToolChoice!==void 0?{toolChoice:e.openAIToolChoice}:{},streaming:!0}),e.modelId)),s=async()=>{let a=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(o),...e.abortSignal?{signal:e.abortSignal}:{}});if(!a.ok)throw await fP(e.url,o,a);return a},i;try{i=await zp(s,mt.getActiveSpan()??void 0,`${this.providerName} stream`)}catch(a){let l=a,c=l.statusCode===400?(()=>{let u=this.correctBodyAfterContextOverflow(o,l);return this.adjustBodyAfter400(u??o,l)??u})():void 0;if(!c)throw l;if(i=await e.fetchImpl(e.url,{method:"POST",headers:{"Content-Type":"application/json",...this.getAuthHeaders()},body:JSON.stringify(c),...e.abortSignal?{signal:e.abortSignal}:{}}),!i.ok)throw await fP(e.url,c,i)}if(!i.body)throw new Error(`${this.providerName}: stream response had no body`);return f1e(i.body,a=>{e.pushChunk({content:a})},a=>{e.pushChunk({content:"",reasoning:a})})}async executeToolBatch(e){let{stepResult:t,conversation:n,toolsRecord:o,toolNameFromWire:s,emitter:i,toolsUsed:a,toolExecutionSummaries:l,options:c}=e,u=[];for(let[,m]of t.toolCalls)u.push({id:m.id,type:"function",function:{name:m.name,arguments:m.argsBuffered}});n.push({role:"assistant",content:t.text.length>0?t.text:null,tool_calls:u});for(let[,m]of t.toolCalls){let f=new Date,h;try{h=JSON.parse(m.argsBuffered||"{}")}catch{h=m.argsBuffered}let y,x,b=s?.get(m.name)??m.name,T=o[b]??oI(o,b);if(i?.emit("tool:start",{toolName:b,toolCallId:m.id,input:h}),!T||typeof T.execute!="function")x=`Tool '${b}' is not registered.`,y={error:x};else try{y=await T.execute(h,{})}catch(C){x=C instanceof Error?C.message:String(C),y={error:x}}let w=new Date;a.push(b),l.push({toolCallId:m.id,toolName:b,input:h,output:y,...x?{error:x}:{},startTime:f,endTime:w}),n.push({role:"tool",tool_call_id:m.id,content:ene(y)})}let p=l.slice(-t.toolCalls.size);Ch(i,p.map(m=>({toolName:m.toolName,output:m.output,...m.error?{error:m.error}:{}})));try{await this.handleToolExecutionStorage(p.map(m=>({toolCallId:m.toolCallId,toolName:m.toolName,input:m.input,output:m.output})),p.map(m=>({toolCallId:m.toolCallId,toolName:m.toolName,output:m.output})),c,new Date)}catch(m){g.warn(`[${this.constructor.name}] Failed to store tool executions`,{provider:this.providerName,error:m instanceof Error?m.message:String(m)})}}async getAvailableModels(){try{let e=`${Ii(this.config.baseURL)}/models`;g.debug(`Fetching available models from: ${e}`);let t=yt(),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(l=>l.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 w1e,Eyr,Cyr,Ryr,kyr,pne,_1e=E(()=>{"use strict";yr();io();It();X();Or();Nu();Yo();Ln();Sg();Zh();Il();wg();ri();w1e="https://api.openai.com/v1",Eyr=(r,e)=>{let t=[r,e].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??w1e;try{let n=new URL(t),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",Ii(n.toString())}catch{}return t},Cyr=()=>pr(rye()),Ryr=()=>br("OPENAI_MODEL","gpt-4o"),kyr=mt.getTracer("neurolink.provider.openai"),pne=class extends Ar{constructor(e,t,n,o){let s=o?.apiKey?.trim(),i=s&&s.length>0?s:Cyr(),a=Eyr(o?.baseURL,process.env.OPENAI_BASE_URL);super("openai",e,t,{baseURL:a,apiKey:i}),g.debug("OpenAIProvider initialized",{model:this.modelName,providerName:this.providerName,baseURL:Kt(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return Ryr()}formatProviderError(e){let t=e,n=t?.type&&typeof t.type=="string"?t.type:void 0,o=[{match:s=>s.statusCode===401||n==="invalid_api_key"||/API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(s.message),errorClass:At,message:s=>/Incorrect API key|Invalid API key/i.test(s.message)?s.message:"Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable."},{match:s=>s.statusCode===429||n==="rate_limit_error"||/rate limit/i.test(s.message),errorClass:Yr,message:"OpenAI rate limit exceeded. Please try again later."},{match:s=>/model_not_found/i.test(s.message),errorClass:wr,message:s=>`Model not found: ${s.modelName}`},...Fr];return fr(e,o,this.providerName,this.modelName)}onStreamStart(e){let t=kyr.startSpan("neurolink.provider.streamText",{kind:vr.CLIENT,attributes:{"gen_ai.system":"openai","gen_ai.request.model":e}}),n=!1,o=()=>{n||(n=!0,t.end())};return{onUsage:s=>{t.setAttribute("gen_ai.usage.input_tokens",s.promptTokens+(s.cacheReadTokens??0)+(s.cacheCreationTokens??0)),t.setAttribute("gen_ai.usage.output_tokens",s.completionTokens);let i=Xo(this.providerName,e,{input:s.promptTokens,output:s.completionTokens,total:s.totalTokens,...s.cacheReadTokens?{cacheReadTokens:s.cacheReadTokens}:{},...s.cacheCreationTokens?{cacheCreationTokens:s.cacheCreationTokens}:{}});i&&i>0&&t.setAttribute("neurolink.cost",i)},onFinish:(s,i)=>{t.setAttribute("gen_ai.response.finish_reason",s||"unknown"),s==="error"&&t.setStatus({code:$e.ERROR,message:i instanceof Error?i.message:String(i??"stream error")}),o()}}}getDefaultEmbeddingModel(){return process.env.OPENAI_EMBEDDING_MODEL||"text-embedding-3-small"}async embed(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let[o]=await this.callEmbeddings(n,[e],"embed");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:o.length}),o}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||this.getDefaultEmbeddingModel();g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await this.callEmbeddings(n,e,"embedMany");return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}async callEmbeddings(e,t,n){let o=`${Ii(this.config.baseURL)}/embeddings`,s=yt(),i=ei(3e4,this.providerName,"generate");try{let a=await s(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:e,input:t.length===1?t[0]:t}),...i?.controller.signal?{signal:i.controller.signal}:{}});if(!a.ok){let u=await a.text().catch(()=>""),p=`OpenAI ${n} failed with status ${a.status}`,m;if(u)try{let f=JSON.parse(u);f.error?.message&&(p=f.error.message),m=f.error?.type}catch{}throw Object.assign(new Error(p),{status:a.status,type:m})}let c=((await a.json()).data??[]).map(u=>u.embedding).filter(u=>Array.isArray(u));if(c.length===0)throw new pt(`OpenAI ${n} returned no embeddings`,this.providerName);return c}finally{i?.cleanup()}}async executeImageGeneration(e){let t=Date.now(),n=e.prompt??e.input?.text??"";if(!n.trim())throw new Error("OpenAI image generation requires a prompt (input.text or prompt)");let o=e.model??this.modelName,s=Ii(this.config.baseURL??w1e),i=e,a=i.size??this.aspectRatioToOpenAISize(i.aspectRatio,o),l=i.numberOfImages??1,c;o==="gpt-image-1"||o.startsWith("dall-e-3")?c=1:o.startsWith("dall-e-2")?c=Math.min(Math.max(l,1),10):c=1;let p={model:o,prompt:n,n:c,size:a};o==="gpt-image-1"?i.quality&&(p.quality=i.quality):o.startsWith("dall-e-3")?(p.response_format="b64_json",i.quality&&(p.quality=i.quality),i.style&&(p.style=i.style)):p.response_format="b64_json";let m=12e4,f=new AbortController,h=setTimeout(()=>f.abort(),m),y;try{y=await yt()(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(p),signal:f.signal})}catch(C){throw C instanceof Error&&C.name==="AbortError"?new Error(`OpenAI image generation timed out after ${m/1e3}s`,{cause:C}):C}finally{clearTimeout(h)}if(!y.ok){let C=await y.text();throw new Error(`OpenAI image generation failed: ${y.status} \u2014 ${C}`)}let b=(await y.json()).data?.[0];if(!b)throw new Error("OpenAI image generation returned no images");let T=b.b64_json;if(!T&&b.url){await ru(b.url);let C=yt(),R=new AbortController,k=setTimeout(()=>R.abort(),6e4),P;try{P=await C(b.url,{signal:R.signal})}catch(A){throw A instanceof Error&&A.name==="AbortError"?new Error("OpenAI image URL download timed out after 60s",{cause:A}):A}finally{clearTimeout(k)}if(!P.ok)throw new Error(`OpenAI image generation: failed to fetch hosted URL ${b.url} (${P.status})`);T=(await ka(P,26214400,"OpenAI image fallback")).toString("base64")}if(!T)throw new Error("OpenAI image generation returned neither b64_json nor a URL");let w=Date.now()-t;return g.info(`[OpenAIProvider] Generated image (${T.length} base64 chars) in ${w}ms \u2014 model ${o}`),{content:b.revised_prompt??n,provider:this.providerName,model:o,usage:{input:0,output:0,total:0},imageOutput:{base64:T}}}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"}}});var E1e={};ue(E1e,{OpenAIProvider:()=>pne});var C1e=E(()=>{"use strict";_1e()});function Ge(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 K(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 hc=E(()=>{});var M_,cG=E(()=>{M_=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return M_=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 qd(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var qv,Vv=E(()=>{qv=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 Ye,js,Ia,rm,O_,xP,N_,L_,D_,U_,F_,$_,B_,z_,ho=E(()=>{Vv();Ye=class extends Error{},js=class r extends Ye{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 rm({message:n,cause:qv(t)});let s=t,i=s?.error?.type;return e===400?new N_(e,s,n,o,i):e===401?new L_(e,s,n,o,i):e===403?new D_(e,s,n,o,i):e===404?new U_(e,s,n,o,i):e===409?new F_(e,s,n,o,i):e===422?new $_(e,s,n,o,i):e===429?new B_(e,s,n,o,i):e>=500?new z_(e,s,n,o,i):new r(e,s,n,o,i)}},Ia=class extends js{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},rm=class extends js{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},O_=class extends rm{constructor({message:e}={}){super({message:e??"Request timed out."})}},xP=class extends Ye{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},N_=class extends js{},L_=class extends js{},D_=class extends js{},U_=class extends js{},F_=class extends js{},$_=class extends js{},B_=class extends js{},z_=class extends js{}});function uG(r){return typeof r!="object"?{}:r??{}}function gne(r){if(!r)return!0;for(let e in r)return!1;return!0}function k1e(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Iyr,R1e,ml,mne,A1e,dG,nm=E(()=>{ho();Iyr=/^[a-z][a-z0-9+.-]*:/i,R1e=r=>Iyr.test(r),ml=r=>(ml=Array.isArray,ml(r)),mne=ml;A1e=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ye(`${r} must be an integer`);if(e<0)throw new Ye(`${r} must be a positive integer`);return e},dG=r=>{try{return JSON.parse(r)}catch{return}}});var Vd,j_=E(()=>{Vd=(r,e)=>new Promise(t=>{if(e?.aborted)return t();let n=()=>{clearTimeout(o),t()},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r);e?.addEventListener("abort",n,{once:!0})})});var Uu,vP=E(()=>{Uu="0.102.0"});function Pyr(){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 Oyr(){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 O1e,Myr,I1e,P1e,M1e,bP,pG=E(()=>{vP();O1e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Myr=()=>{let r=Pyr();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uu,"X-Stainless-OS":P1e(Deno.build.os),"X-Stainless-Arch":I1e(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":Uu,"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":Uu,"X-Stainless-OS":P1e(globalThis.process.platform??"unknown"),"X-Stainless-Arch":I1e(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Oyr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Uu,"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":Uu,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};I1e=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",P1e=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"),bP=()=>M1e??(M1e=Myr())});function N1e(){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 fne(...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 mG(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return fne({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function TP(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 L1e(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 G_=E(()=>{});var D1e,U1e=E(()=>{D1e=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});var hne,yne,xne,F1e,vne=E(()=>{hne="RFC3986",yne=r=>String(r),xne={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yne},F1e="RFC1738"});function B1e(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Tne(r,e){if(ml(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var gG,om,bne,$1e,z1e=E(()=>{vne();nm();gG=(r,e)=>(gG=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),gG(r,e)),om=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),bne=1024,$1e=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<s.length;a+=bne){let l=s.length>=bne?s.slice(a,a+bne):s,c=[];for(let u=0;u<l.length;++u){let p=l.charCodeAt(u);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===F1e&&(p===40||p===41)){c[c.length]=l.charAt(u);continue}if(p<128){c[c.length]=om[p];continue}if(p<2048){c[c.length]=om[192|p>>6]+om[128|p&63];continue}if(p<55296||p>=57344){c[c.length]=om[224|p>>12]+om[128|p>>6&63]+om[128|p&63];continue}u+=1,p=65536+((p&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=om[240|p>>18]+om[128|p>>12&63]+om[128|p>>6&63]+om[128|p&63]}i+=c.join("")}return i}});function Dyr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}function V1e(r,e,t,n,o,s,i,a,l,c,u,p,m,f,h,y,x,b){let T=r,w=b,C=0,R=!1;for(;(w=w.get(Sne))!==void 0&&!R;){let M=w.get(r);if(C+=1,typeof M<"u"){if(M===C)throw new RangeError("Cyclic object value");R=!0}typeof w.get(Sne)>"u"&&(C=0)}if(typeof c=="function"?T=c(e,T):T instanceof Date?T=m?.(T):t==="comma"&&ml(T)&&(T=Tne(T,function(M){return M instanceof Date?m?.(M):M})),T===null){if(s)return l&&!y?l(e,Pi.encoder,x,"key",f):e;T=""}if(Dyr(T)||B1e(T)){if(l){let M=y?e:l(e,Pi.encoder,x,"key",f);return[h?.(M)+"="+h?.(l(T,Pi.encoder,x,"value",f))]}return[h?.(e)+"="+h?.(String(T))]}let k=[];if(typeof T>"u")return k;let P;if(t==="comma"&&ml(T))y&&l&&(T=Tne(T,l)),P=[{value:T.length>0?T.join(",")||null:void 0}];else if(ml(c))P=c;else{let M=Object.keys(T);P=u?M.sort(u):M}let I=a?String(e).replace(/\./g,"%2E"):String(e),A=n&&ml(T)&&T.length===1?I+"[]":I;if(o&&ml(T)&&T.length===0)return A+"[]";for(let M=0;M<P.length;++M){let F=P[M],D=typeof F=="object"&&typeof F.value<"u"?F.value:T[F];if(i&&D===null)continue;let N=p&&a?F.replace(/\./g,"%2E"):F,z=ml(T)?typeof t=="function"?t(A,N):A:A+(p?"."+N:"["+N+"]");b.set(r,C);let G=new WeakMap;G.set(Sne,b),q1e(k,V1e(D,z,t,n,o,s,i,a,t==="comma"&&y&&ml(T)?null:l,c,u,p,m,f,h,y,x,G))}return k}function Uyr(r=Pi){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||Pi.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=hne;if(typeof r.format<"u"){if(!gG(xne,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=xne[t],o=Pi.filter;(typeof r.filter=="function"||ml(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in G1e?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=Pi.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Pi.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Pi.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Pi.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Pi.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Pi.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Pi.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Pi.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Pi.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Pi.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Pi.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Pi.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Pi.strictNullHandling}}function H1e(r,e={}){let t=r,n=Uyr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):ml(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof t!="object"||t===null)return"";let a=G1e[n.arrayFormat],l=a==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let c=new WeakMap;for(let m=0;m<o.length;++m){let f=o[m];n.skipNulls&&t[f]===null||q1e(i,V1e(t[f],f,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}let u=i.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),u.length>0?p+u:""}var G1e,q1e,j1e,Pi,Sne,K1e=E(()=>{z1e();vne();nm();G1e={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},q1e=function(r,e){Array.prototype.push.apply(r,ml(e)?e:[e])},Pi={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:$1e,encodeValuesOnly:!1,format:hne,formatter:yne,indices:!1,serializeDate(r){return(j1e??(j1e=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};Sne={}});function W1e(r){return H1e(r,{arrayFormat:"brackets"})}var wne=E(()=>{K1e()});function hG(r){if(!r)return;let e;try{e=new URL(r)}catch(n){throw new bn(`Invalid token endpoint base URL "${r}": ${n}`)}if(e.protocol==="https:")return;let t=e.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!(e.protocol==="http:"&&(t==="localhost"||t==="127.0.0.1"||t==="::1")))throw new bn(`Refusing to send credential over non-https token endpoint "${r}"`)}async function yG(r,e){let t=await Byr(r),n;try{n=JSON.parse(t)}catch{throw new bn(`Token endpoint returned non-JSON response (status ${r.status})`,r.status,yc(t),e)}if(!n.access_token)throw new bn(`Token endpoint response missing access_token: ${JSON.stringify(yc(n))}`,r.status,yc(n),e);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new bn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,r.status,yc(n),e);return n}function yc(r){if(r==null)return r;if(typeof r=="string"){let e;try{e=JSON.parse(r)}catch{return r.length<=_ne?r:r.slice(0,_ne)+`... <${r.length-_ne} more chars>`}return JSON.stringify(yc(e))}if(typeof r=="object"&&!Array.isArray(r)){let e={};for(let[t,n]of Object.entries(r))$yr.has(t)&&(e[t]=n);return e}return null}async function xG(r,e=t=>console.warn(`anthropic-sdk: ${t}`)){if(typeof process>"u"||process.platform==="win32")return;let t=await Promise.resolve().then(()=>(Bs(),Fd)),n=r,o;try{n=await t.promises.realpath(r),o=await t.promises.stat(n)}catch{return}let s=o.mode&511;if(s&18)throw new bn(`Credentials file at ${n} is group/world-writable (mode 0o${s.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${n}\`.`);if(s&36)throw new bn(`Credentials file at ${n} is group/world-readable (mode 0o${s.toString(8)}); run \`chmod 600 ${n}\` before retrying.`);typeof process.getuid=="function"&&o.uid!==process.getuid()&&e(`credentials file at ${n} is owned by uid ${o.uid} (current process uid ${process.getuid()}); verify this is intentional.`)}async function vG(r,e){let t=await Promise.resolve().then(()=>(Bs(),Fd)),o=(await Promise.resolve().then(()=>(An(),uc))).dirname(r);await t.promises.mkdir(o,{recursive:!0,mode:448});let s=`${r}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;try{let i=await t.promises.open(s,"w",384);try{await i.writeFile(JSON.stringify(e,null,2)),await i.sync()}finally{await i.close()}await t.promises.rename(s,r)}catch(i){throw await t.promises.unlink(s).catch(()=>{}),i}try{let i=await t.promises.open(o,"r");try{await i.sync()}finally{await i.close()}}catch{}}async function Byr(r){if(!r.body)return"";let e=r.body.getReader(),t=[],n=0;for(;;){let{done:s,value:i}=await e.read();if(s)break;if(n+i.length>J1e){let a=J1e-n;a>0&&t.push(i.subarray(0,a)),await e.cancel();break}t.push(i),n+=i.length}let o;if(t.length===1)o=t[0];else{o=new Uint8Array(t.reduce((i,a)=>i+a.length,0));let s=0;for(let i of t)o.set(i,s),s+=i.length}return new TextDecoder("utf-8").decode(o)}var X1e,Y1e,fG,Hv,Z1e,Q1e,q_,e$e,J1e,_ne,$yr,bn,V_=E(()=>{ho();X1e="urn:ietf:params:oauth:grant-type:jwt-bearer",Y1e="refresh_token",fG="/v1/oauth/token",Hv="oauth-2025-04-20",Z1e="oidc-federation-2026-04-01",Q1e=120,q_=30,e$e=5,J1e=1<<20;_ne=2e3,$yr=new Set(["error","error_description","error_uri"]);bn=class extends Ye{constructor(e,t=null,n=null,o=null){super(e),this.statusCode=t,this.body=n,this.requestId=o}}});function Hd(){return Math.floor(Date.now()/1e3)}var SP=E(()=>{});var bG,t$e=E(()=>{V_();SP();bG=class{constructor(e,t){this.cached=null,this.pendingRefresh=null,this.nextForce=!1,this.lastAdvisoryError=0,this.provider=e,this.onAdvisoryRefreshError=t}async getToken(){let e=this.nextForce;this.nextForce=!1;let t=this.cached;if(e||t==null)return(await this.refresh(e)).token;if(t.expiresAt==null)return t.token;let n=t.expiresAt-Hd();return n>Q1e?t.token:n>q_?(this.backgroundRefresh(),t.token):(await this.refresh()).token}invalidate(){this.cached=null,this.nextForce=!0}refresh(e=!1){return this.pendingRefresh&&!e?this.pendingRefresh:this.doRefresh(e)}backgroundRefresh(){this.pendingRefresh||Hd()-this.lastAdvisoryError<e$e||this.doRefresh().catch(e=>{this.lastAdvisoryError=Hd(),this.onAdvisoryRefreshError?.(e)})}doRefresh(e=!1){return this.pendingRefresh=this.provider(e?{forceRefresh:!0}:void 0).then(t=>(this.cached=t,this.pendingRefresh=null,t),t=>{throw this.pendingRefresh=null,t}),this.pendingRefresh}}});var Vr,wP=E(()=>{Vr=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0}});function o$e(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 H_(r){let e;return(r$e??(e=new globalThis.TextEncoder,r$e=e.encode.bind(e)))(r)}function Ene(r){let e;return(n$e??(e=new globalThis.TextDecoder,n$e=e.decode.bind(e)))(r)}var r$e,n$e,TG=E(()=>{});var s$e=E(()=>{ho();TG()});function _P(){}function SG(r,e,t){return!e||wG[r]>wG[t]?_P:e[r].bind(e)}function fn(r){let e=r.logger,t=r.logLevel??"off";if(!e)return zyr;let n=i$e.get(e);if(n&&n[0]===t)return n[1];let o={error:SG("error",e,t),warn:SG("warn",e,t),info:SG("info",e,t),debug:SG("debug",e,t)};return i$e.set(e,[t,o]),o}var wG,Cne,zyr,i$e,sm,Eg=E(()=>{nm();wG={off:0,error:200,warn:300,info:400,debug:500},Cne=(r,e,t)=>{if(r){if(k1e(wG,r))return r;fn(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(wG))}`)}};zyr={error:_P,warn:_P,info:_P,debug:_P},i$e=new WeakMap;sm=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()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r)});var Rne=E(()=>{nm();s$e();wP();Eg();cG();j_();wne()});function a$e(r){if(!r)throw new Error("profile name is empty");if(r==="."||r==="..")throw new Error(`profile name "${r}" is not allowed`);if(r.includes("/")||r.includes("\\"))throw new Error(`profile name "${r}" must not contain path separators`);if(!jyr.test(r))throw new Error(`profile name "${r}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var _G,jyr,l$e,c$e,kne,Gyr,u$e,Ane=E(()=>{pG();Rne();_G="1.0",jyr=/^[A-Za-z0-9_.-]+$/;l$e=async r=>{var e,t;let n=await kne();if(n===null)return null;let o=r??await u$e();if(o===null)return null;a$e(o);let s=await Promise.resolve().then(()=>(Bs(),Fd)),a=(await Promise.resolve().then(()=>(An(),uc))).join(n,"configs",`${o}.json`),l;try{l=await s.promises.readFile(a,"utf-8")}catch(p){if(p?.code!=="ENOENT")throw new Error(`failed to read config file ${a}: ${p}`);l=null}if(l===null){let p=Vr("ANTHROPIC_ORGANIZATION_ID"),m=Vr("ANTHROPIC_IDENTITY_TOKEN_FILE"),f=Vr("ANTHROPIC_FEDERATION_RULE_ID");return f&&p?{fromFile:!1,config:{organization_id:p,workspace_id:Vr("ANTHROPIC_WORKSPACE_ID"),base_url:Vr("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:f,service_account_id:Vr("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:Vr("ANTHROPIC_SCOPE")}}}:null}let c;try{c=JSON.parse(l)}catch(p){throw new Error(`failed to parse config file ${a}: ${p}`)}if(!c.authentication)throw new Error(`config file ${a} is missing "authentication"`);let u=c.authentication.type;if(u!=="oidc_federation"&&u!=="user_oauth")throw new Error(`authentication.type "${u}" is not a known authentication type`);if(c.organization_id??(c.organization_id=Vr("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=Vr("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=Vr("ANTHROPIC_BASE_URL")),(e=c.authentication).scope??(e.scope=Vr("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){let p=Vr("ANTHROPIC_IDENTITY_TOKEN_FILE");p&&(c.authentication.identity_token={source:"file",path:p})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=Vr("ANTHROPIC_FEDERATION_RULE_ID")??""),(t=c.authentication).service_account_id??(t.service_account_id=Vr("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},c$e=async(r,e)=>{if(r?.authentication.credentials_path)return r.authentication.credentials_path;let t=await kne();if(!t)return null;let n=e??await u$e();return n?(a$e(n),(await Promise.resolve().then(()=>(An(),uc))).join(t,"credentials",`${n}.json`)):null},kne=async()=>{if(!Gyr())return null;let r=await Promise.resolve().then(()=>(An(),uc)),e=Vr("ANTHROPIC_CONFIG_DIR");if(e)return e;if(bP()["X-Stainless-OS"]==="Windows"){let s=Vr("APPDATA");if(s)return r.join(s,"Anthropic");let i=Vr("USERPROFILE");return i?r.join(i,"AppData","Roaming","Anthropic"):null}let n=Vr("XDG_CONFIG_HOME");if(n)return r.join(n,"anthropic");let o=Vr("HOME");return o?r.join(o,".config","anthropic"):null},Gyr=()=>{let r=bP()["X-Stainless-Runtime"];return r==="node"||r==="deno"},u$e=async()=>{let r=await kne();if(!r)return null;let e=Vr("ANTHROPIC_PROFILE");if(e)return e;let t=await Promise.resolve().then(()=>(Bs(),Fd)),o=(await Promise.resolve().then(()=>(An(),uc))).join(r,"active_config");try{return(await t.promises.readFile(o,"utf-8")).trim()||"default"}catch(s){if(s?.code!=="ENOENT")throw new Error(`failed to read ${o}: ${s}`);return"default"}}});function Ine(r){if(!r)throw new Ye("Identity token file path is empty");return async()=>{let e=await Promise.resolve().then(()=>(Bs(),Fd)),t;try{t=await e.promises.readFile(r,"utf-8")}catch(o){throw new Ye(`Failed to read identity token file at ${r}: ${o}`)}let n=t.trim();if(!n)throw new Ye(`Identity token file at ${r} is empty`);return n}}function d$e(r){if(!r)throw new Ye("Identity token value is empty");return()=>r}var p$e=E(()=>{ho()});function m$e(r){return async()=>{hG(r.baseURL);let e=await r.identityTokenProvider();if(e.length>16*1024)throw new bn(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let t={grant_type:X1e,assertion:e,federation_rule_id:r.federationRuleId,organization_id:r.organizationId};r.serviceAccountId&&(t.service_account_id=r.serviceAccountId),r.workspaceId&&(t.workspace_id=r.workspaceId);let n=`${r.baseURL}${fG}`,o;try{o=await r.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Hv},${Z1e}`,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${Uu} oidcFederationProvider`},body:JSON.stringify(t)})}catch(l){throw new bn(`Failed to reach token endpoint ${n}: ${l}`)}let s=o.headers.get("Request-Id");if(!o.ok){let l=await o.text().catch(()=>""),c=yc(l),u="";throw o.status===401&&(u=` Ensure your federation rule matches your identity token. ${r.workspaceId?"":"If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. "}View your authentication events in the Workload identity page of Claude Console for more details.`),new bn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${c}${u}`,o.status,c,s)}let i=await yG(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new bn(`Token endpoint response missing required fields: ${JSON.stringify(yc(i))}`,o.status,yc(i),s);return{token:i.access_token,expiresAt:Hd()+a}}}var g$e=E(()=>{V_();SP();vP()});function f$e(r){return async e=>{let t=await Promise.resolve().then(()=>(Bs(),Fd));await xG(r.credentialsPath,r.onSafetyWarning);let n;try{n=await t.promises.readFile(r.credentialsPath,"utf-8")}catch(x){throw new bn(`Credentials file not found at ${r.credentialsPath}: ${x}`)}let o;try{o=JSON.parse(n)}catch(x){throw new bn(`Credentials file at ${r.credentialsPath} is not valid JSON: ${x}`)}let s=o.access_token;if(!s)throw new bn(`Credentials file at ${r.credentialsPath} must include 'access_token'`);let i=o.expires_at;if(!e?.forceRefresh&&(i==null||Hd()<i-q_))return{token:s,expiresAt:i??null};let a=o.refresh_token;if(!r.clientId||!a)throw new bn(`Access token at ${r.credentialsPath} has expired and no refresh is available (client_id ${r.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);hG(r.baseURL);let l={grant_type:Y1e,refresh_token:a,client_id:r.clientId},c=`${r.baseURL}${fG}`,u;try{u=await r.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Hv,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${Uu} userOAuthProvider`},body:JSON.stringify(l)})}catch(x){throw new bn(`User OAuth refresh failed to reach token endpoint: ${x}`)}let p=u.headers.get("Request-Id");if(!u.ok){let x=await u.text().catch(()=>"");throw new bn(`User OAuth refresh failed (HTTP ${u.status}): ${yc(x)}`,u.status,yc(x),p)}let m=await yG(u,p),f=Number(m.expires_in);if(!Number.isFinite(f))throw new bn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(yc(m))}`,u.status,yc(m),p);let h=Hd()+f,y=m.refresh_token||a;return await vG(r.credentialsPath,{...o,version:_G,type:"oauth_token",access_token:m.access_token,expires_at:h,refresh_token:y}),{token:m.access_token,expiresAt:h}}}var h$e=E(()=>{Ane();V_();SP();vP()});function Pne(r,e){let t=r.authentication.credentials_path??null,n=(r.base_url||e.baseURL).replace(/\/+$/,""),o=qyr(r,t,n,e),s={};return r.workspace_id&&r.authentication.type==="user_oauth"&&(s["anthropic-workspace-id"]=r.workspace_id),{provider:o,extraHeaders:s,baseURL:r.base_url||void 0}}async function y$e(r,e){let t=await l$e(e);if(!t)return null;let{config:n,fromFile:o}=t,s=n.authentication.credentials_path||!o?n:{...n,authentication:{...n.authentication,credentials_path:await c$e(n,e)??void 0}};return Pne(s,r)}function qyr(r,e,t,n){switch(r.authentication.type){case"oidc_federation":{let o=r.authentication,s=Vyr(o);if(!s)throw new bn("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");if(!o.federation_rule_id)throw new bn("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");if(!r.organization_id)throw new bn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let i=m$e({identityTokenProvider:s,federationRuleId:o.federation_rule_id,organizationId:r.organization_id,serviceAccountId:o.service_account_id,workspaceId:r.workspace_id,baseURL:t,fetch:n.fetch,userAgent:n.userAgent});return e?Hyr(i,e,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!e)throw new bn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return f$e({credentialsPath:e,clientId:r.authentication.client_id,baseURL:t,fetch:n.fetch,userAgent:n.userAgent,onSafetyWarning:n.onSafetyWarning})}default:{let o=r.authentication.type;throw new bn(`authentication.type "${o}" is not a known authentication type`)}}}function Vyr(r){if(r.identity_token){let n=r.identity_token.source;if(n!=="file")throw new bn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!r.identity_token.path)throw new bn('identity_token.source "file" requires a non-empty path');return Ine(r.identity_token.path)}let e=Vr("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return Ine(e);let t=Vr("ANTHROPIC_IDENTITY_TOKEN");return t?d$e(t):null}function Hyr(r,e,t,n){return async o=>{let s=await Promise.resolve().then(()=>(Bs(),Fd));await xG(e,n);let i;try{let l=await s.promises.readFile(e,"utf-8");i=JSON.parse(l);let c=i?.access_token;if(c&&!o?.forceRefresh){let u=i?.expires_at;if(u==null||Hd()<u-q_)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&t?.(l)}let a=await r(o);try{await vG(e,{...i??{},version:_G,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){t?.(l)}return a}}var x$e=E(()=>{wP();Ane();V_();SP();p$e();g$e();h$e()});function Kyr(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 v$e(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 ou,su,Cg,Mne=E(()=>{hc();TG();Cg=class{constructor(){ou.set(this,void 0),su.set(this,void 0),Ge(this,ou,new Uint8Array,"f"),Ge(this,su,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?H_(e):e;Ge(this,ou,o$e([K(this,ou,"f"),t]),"f");let n=[],o;for(;(o=Kyr(K(this,ou,"f"),K(this,su,"f")))!=null;){if(o.carriage&&K(this,su,"f")==null){Ge(this,su,o.index,"f");continue}if(K(this,su,"f")!=null&&(o.index!==K(this,su,"f")+1||o.carriage)){n.push(Ene(K(this,ou,"f").subarray(0,K(this,su,"f")-1))),Ge(this,ou,K(this,ou,"f").subarray(K(this,su,"f")),"f"),Ge(this,su,null,"f");continue}let s=K(this,su,"f")!==null?o.preceding-1:o.preceding,i=Ene(K(this,ou,"f").subarray(0,s));n.push(i),Ge(this,ou,K(this,ou,"f").subarray(o.index),"f"),Ge(this,su,null,"f")}return n}flush(){return K(this,ou,"f").length?this.decode(`
1072
1072
  `):[]}};ou=new WeakMap,su=new WeakMap;Cg.NEWLINE_CHARS=new Set([`
1073
1073
  `,"\r"]);Cg.NEWLINE_REGEXP=/\r\n|[\n\r]/g});async function*Wyr(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ye("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 Ye("Attempted to iterate over a response with no body");let t=new One,n=new Cg,o=TP(r.body);for await(let s of Jyr(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*Jyr(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"?H_(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=v$e(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}function Xyr(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var EP,Fu,One,EG=E(()=>{hc();ho();G_();Mne();G_();Vv();nm();TG();Eg();ho();Fu=class r{constructor(e,t,n){this.iterator=e,EP.set(this,void 0),this.controller=t,Ge(this,EP,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?fn(n):console;async function*i(){if(o)throw new Ye("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of Wyr(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw s.error("Could not parse message into JSON:",l.data),s.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="user.tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="session.updated"||l.event==="span.model_request_start"||l.event==="span.model_request_end"||l.event==="span.outcome_evaluation_start"||l.event==="span.outcome_evaluation_ongoing"||l.event==="span.outcome_evaluation_end"||l.event==="user.define_outcome"||l.event==="agent.thread_message_received"||l.event==="agent.thread_message_sent"||l.event==="agent.session_thread_message_received"||l.event==="agent.session_thread_message_sent"||l.event==="session.thread_created"||l.event==="session.thread_status_created"||l.event==="session.thread_status_running"||l.event==="session.thread_status_idle"||l.event==="session.thread_status_rescheduled"||l.event==="session.thread_status_terminated")try{yield JSON.parse(l.data)}catch(c){throw s.error("Could not parse message into JSON:",l.data),s.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){let c=dG(l.data)??l.data,u=c?.error?.type;throw new js(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(qd(l))return;throw l}finally{a||t.abort()}}return new r(i,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let a=new Cg,l=TP(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*i(){if(o)throw new Ye("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of s())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(qd(l))return;throw l}finally{a||t.abort()}}return new r(i,t,n)}[(EP=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,K(this,EP,"f")),new r(()=>o(t),this.controller,K(this,EP,"f"))]}toReadableStream(){let e=this,t;return fne({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=H_(JSON.stringify(o)+`
1074
1074
  `);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};One=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(`
@@ -464,15 +464,22 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
464
464
  const apiErr = await buildAPIError(url, body, res);
465
465
  // One-shot 400 retry. The overflow corrector runs FIRST (it can
466
466
  // re-fit max_tokens from the provider's own numbers and also
467
- // self-heals the runtime window registry); otherwise a subclass
468
- // may strip a rejected field and return a modified body (e.g.
469
- // NIM's chat_template / reasoning_budget). The retry runs under
470
- // the SAME timeout controller as the first attempt, so the
471
- // configured timeout caps the overall call matching the
472
- // streaming path, which reuses its composed signal for the retry.
467
+ // self-heals the runtime window registry); its output then feeds
468
+ // a subclass hook that may strip a rejected field (e.g. NIM's
469
+ // chat_template / reasoning_budget), so a body that needs BOTH
470
+ // fixes gets both a plain `??` between the two would let
471
+ // whichever ran first silently win and drop the other's fix. The
472
+ // retry runs under the SAME timeout controller as the first
473
+ // attempt, so the configured timeout caps the overall call —
474
+ // matching the streaming path, which reuses its composed signal
475
+ // for the retry.
473
476
  const retryBody = res.status === 400
474
- ? (correctBodyAfterContextOverflow(body, apiErr) ??
475
- adjustBodyAfter400(body, apiErr))
477
+ ? (() => {
478
+ const typedErr = apiErr;
479
+ const overflowCorrected = correctBodyAfterContextOverflow(body, typedErr);
480
+ return (adjustBodyAfter400(overflowCorrected ?? body, typedErr) ??
481
+ overflowCorrected);
482
+ })()
476
483
  : undefined;
477
484
  if (!retryBody) {
478
485
  throw apiErr;
@@ -967,13 +974,18 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
967
974
  // consumed inside doFetch's closure, either returned on success or
968
975
  // discarded after buildAPIError read its body on failure.
969
976
  const apiErr = err;
970
- // Overflow corrector first (re-fits max_tokens from the provider's
971
- // own numbers + self-heals the window registry), then the subclass
972
- // hook (e.g. NIM strips chat_template / reasoning_budget when a model
973
- // rejects them).
977
+ // Overflow corrector first (re-fits max_tokens from the provider's own
978
+ // numbers + self-heals the window registry); its output then feeds the
979
+ // subclass hook (e.g. NIM strips chat_template / reasoning_budget when
980
+ // a model rejects them), so a body needing BOTH fixes gets both — a
981
+ // plain `??` between the two would let whichever ran first silently
982
+ // win and drop the other's fix.
974
983
  const retryBody = apiErr.statusCode === 400
975
- ? (this.correctBodyAfterContextOverflow(body, apiErr) ??
976
- this.adjustBodyAfter400(body, apiErr))
984
+ ? (() => {
985
+ const overflowCorrected = this.correctBodyAfterContextOverflow(body, apiErr);
986
+ return (this.adjustBodyAfter400(overflowCorrected ?? body, apiErr) ??
987
+ overflowCorrected);
988
+ })()
977
989
  : undefined;
978
990
  if (!retryBody) {
979
991
  throw apiErr;
@@ -464,15 +464,22 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
464
464
  const apiErr = await buildAPIError(url, body, res);
465
465
  // One-shot 400 retry. The overflow corrector runs FIRST (it can
466
466
  // re-fit max_tokens from the provider's own numbers and also
467
- // self-heals the runtime window registry); otherwise a subclass
468
- // may strip a rejected field and return a modified body (e.g.
469
- // NIM's chat_template / reasoning_budget). The retry runs under
470
- // the SAME timeout controller as the first attempt, so the
471
- // configured timeout caps the overall call matching the
472
- // streaming path, which reuses its composed signal for the retry.
467
+ // self-heals the runtime window registry); its output then feeds
468
+ // a subclass hook that may strip a rejected field (e.g. NIM's
469
+ // chat_template / reasoning_budget), so a body that needs BOTH
470
+ // fixes gets both a plain `??` between the two would let
471
+ // whichever ran first silently win and drop the other's fix. The
472
+ // retry runs under the SAME timeout controller as the first
473
+ // attempt, so the configured timeout caps the overall call —
474
+ // matching the streaming path, which reuses its composed signal
475
+ // for the retry.
473
476
  const retryBody = res.status === 400
474
- ? (correctBodyAfterContextOverflow(body, apiErr) ??
475
- adjustBodyAfter400(body, apiErr))
477
+ ? (() => {
478
+ const typedErr = apiErr;
479
+ const overflowCorrected = correctBodyAfterContextOverflow(body, typedErr);
480
+ return (adjustBodyAfter400(overflowCorrected ?? body, typedErr) ??
481
+ overflowCorrected);
482
+ })()
476
483
  : undefined;
477
484
  if (!retryBody) {
478
485
  throw apiErr;
@@ -967,13 +974,18 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
967
974
  // consumed inside doFetch's closure, either returned on success or
968
975
  // discarded after buildAPIError read its body on failure.
969
976
  const apiErr = err;
970
- // Overflow corrector first (re-fits max_tokens from the provider's
971
- // own numbers + self-heals the window registry), then the subclass
972
- // hook (e.g. NIM strips chat_template / reasoning_budget when a model
973
- // rejects them).
977
+ // Overflow corrector first (re-fits max_tokens from the provider's own
978
+ // numbers + self-heals the window registry); its output then feeds the
979
+ // subclass hook (e.g. NIM strips chat_template / reasoning_budget when
980
+ // a model rejects them), so a body needing BOTH fixes gets both — a
981
+ // plain `??` between the two would let whichever ran first silently
982
+ // win and drop the other's fix.
974
983
  const retryBody = apiErr.statusCode === 400
975
- ? (this.correctBodyAfterContextOverflow(body, apiErr) ??
976
- this.adjustBodyAfter400(body, apiErr))
984
+ ? (() => {
985
+ const overflowCorrected = this.correctBodyAfterContextOverflow(body, apiErr);
986
+ return (this.adjustBodyAfter400(overflowCorrected ?? body, apiErr) ??
987
+ overflowCorrected);
988
+ })()
977
989
  : undefined;
978
990
  if (!retryBody) {
979
991
  throw apiErr;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "11.2.1",
3
+ "version": "11.2.2",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {
@@ -82,6 +82,7 @@
82
82
  "test:memory": "npx tsx test/continuous-test-suite-memory.ts",
83
83
  "test:openai-compat-streaming-retry": "npx tsx test/continuous-test-suite-openai-compat-streaming-retry.ts",
84
84
  "test:anthropic-streaming-retry": "npx tsx test/continuous-test-suite-anthropic-streaming-retry.ts",
85
+ "test:adjust-body-after-400": "npx tsx test/continuous-test-suite-adjust-body-after-400.ts",
85
86
  "test:error-classification-e2e": "npx tsx test/continuous-test-suite-error-classification-e2e.ts",
86
87
  "test:error-classifier-contract": "npx tsx test/continuous-test-suite-error-classifier-contract.ts",
87
88
  "test:middleware": "npx tsx test/continuous-test-suite-middleware.ts",