@juspay/neurolink 11.9.0 → 11.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1067,7 +1067,7 @@ Based on this analysis, provide your response.`:`Here is a video/image analysis
1067
1067
  ${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 Zm({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=Ld(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=Ws(i,this.providerName,"generate"),l=Ux(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=Sv(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 cw(()=>Ud.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 Le?{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(()=>(lz(),fee));return n()(...t)})}async executeStream(e,t){if(!this.doStream)throw new Le({code:tt.INVALID_CONFIGURATION,message:`${this.providerName} cannot stream: it neither implements doStream() nor overrides executeStream()`,category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}});let n=Date.now(),{stream:o,finishReason:s,usage:i,warnings:a}=await this.doStream(e);a?.length&&g.warn(`[${this.providerName}] doStream reported warnings`,{provider:this.providerName,count:a.length});let l={startTime:n,streamId:`${this.providerName}-${n}`},c=(async()=>{let[u,p]=await Promise.all([s,i]);return l.finishReason=u,l.rawFinishReason=u,Hp(this.providerName,this.modelName||this.getDefaultModel(),{usage:{input:p.inputTokens,output:p.outputTokens,total:p.inputTokens+p.outputTokens},stopReason:u},Date.now()-n,{streamingMode:!0})})();return{stream:o,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:c,metadata:l}}async getAISDKModelWithMiddleware(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 QA(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(wr(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=rw(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=FX(e);i!==void 0&&(o.retryAfterMs=i)}}bv(e)&&$w(t);try{let n=pt.getSpan(ur.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=Ws(n,this.providerName,t.operationType||"generate");try{return o?await Promise.race([e(),new Promise((s,i)=>{o.controller.signal.addEventListener("abort",()=>{i(new ol(`${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(()=>(Zh(),Sre)),{validateVideoGenerationInput:i,validateImageForVideo:a,validateDirectorModeInput:l}=await Promise.resolve().then(()=>(Kh(),dUe)),{ErrorFactory:c}=await Promise.resolve().then(()=>(Tt(),Qk)),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:U}=await Promise.resolve().then(()=>(DFe(),LFe)),$=e.timeout??U,L=await this.executeWithTimeout(()=>M(I,u.output?.video??{},u.output?.director??{},e.region),{timeout:$,operationType:"generate"}),z=u.input.segments.map(re=>re.prompt).join(" \u2192 "),j=L.metadata?.segmentCount??u.input.segments.length,F=L.metadata?.transitionCount??Math.max(0,j-1),B=L.metadata?.duration??0,W={content:`${z} \u2014 duration: ${B}s, segments: ${j}, transitions: ${F}`,provider:"vertex",model:e.model||"veo-3.1-generate-001",usage:{input:0,output:0,total:0},video:L};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(()=>(ei(),Il));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 Yhr(r){return r?.kind==="toolCall"||r?.kind==="toolResult"}function Zhr(r,e,t){let n=[],o=e;for(;o<t;){if(!Yhr(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 M_(r,e){let{availableInputTokens:t,fixedOverheadTokens:n,thresholdRatio:o=tv,lowWaterRatio:s=Jhr,protectedTailCount:i=Xhr,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 Jhr,Xhr,Xj=E(()=>{"use strict";cs();Jhr=.6,Xhr=4});function $Fe(r){if(typeof r=="string")return r;if(r==null)return"";try{return JSON.stringify(r)??""}catch{return"x".repeat(2e5)}}function BFe(r,e){return Array.isArray(r.parts)&&r.parts.some(t=>t&&typeof t=="object"&&e in t)}function eyr(r){return BFe(r,"functionResponse")}function cP(r){let{preview:e}=fi(r,{maxBytes:FFe,maxLines:Qhr});return e}function tyr(r,e){return zt($Fe(r.parts),e)+4}function ryr(r,e){return r.map(t=>{let n=tyr(t,e);if(eyr(t)){let o=$Fe(t.parts),s=o.length>FFe?zt(cP(o),e)+4:n;return{kind:"toolResult",tokens:n,...s<n?{previewTokens:s}:{}}}return BFe(t,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function Zj(r){let{contents:e,availableInputTokens:t,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:s}=r,i=ryr(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=M_(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 FFe,Qhr,Yj,Ere=E(()=>{"use strict";gi();Oh();Xj();X();FFe=2048,Qhr=60,Yj="[Earlier tool exchanges were removed to fit the context window.]"});var O_=E(()=>{"use strict";co()});function uP(r){if(!(!r?.enabled&&!r?.thinkingLevel))return{includeThoughts:!0,thinkingLevel:r.thinkingLevel??nyr}}var nyr,Cre=E(()=>{"use strict";nyr="high"});function oyr(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 iyr(r){if(syr.test(r))return r;let e=r.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(e)||(e=`_${e}`),e.length>Rre&&(e=e.slice(0,Rre)),e}function ayr(r,e){if(!e(r))return r;let t=2;for(;;){let n=`_${t}`,s=`${r.slice(0,Rre-n.length)}${n}`;if(!e(s))return s;t++}}function Qh(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=Qh({...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]=Qh(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"?Qh(s):s):e[n]=Qh(o):e[n]=o;Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Qh(n))),e.not&&typeof e.not=="object"&&(e.not=Qh(e.not));for(let n of["if","then","else"])e[n]&&typeof e[n]=="object"&&(e[n]=Qh(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 kre(r,e){let t=[],n=new Hd,o=[],s=[],i=new Set(e??[]),a=new Map;for(let[l,c]of Object.entries(r))try{let u=iyr(l),p=ayr(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;aI(y)?h=xn(y,"openApi3"):typeof y=="object"?h=y:h={type:"object",properties:{}},h.jsonSchema&&typeof h.jsonSchema=="object"&&!h.type&&(h=h.jsonSchema),m.parametersJsonSchema=Qh(pn(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 Qj(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=kre(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 Are(r,e){let t=_a("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=uP(r.thinkingConfig);return o&&(n.thinkingConfig=o),e||((r.responseSchema||r.wantsJsonOutput)&&(n.responseMimeType="application/json"),r.responseSchema&&(n.responseSchema=r.responseSchema)),n}function Ire(r){let e=r||Jo;return Number.isFinite(e)&&e>0?Math.min(Math.floor(e),zFe):Math.min(Jo,zFe)}function Pre(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 Mre(r,e){return e?r?`${r}
1070
- ${e}`:e:r}async function jFe(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}}async function GFe(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({content: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 N_(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 Ore(r){return r.filter(e=>typeof e.text=="string").map(e=>e.text).join("")}async function Nre(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&&mI(s.liveTools,c)?.execute){Qj(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}-${Fn()}`,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 Lre(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||Cg(t,0)):n}function tu(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 Cg(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 ru(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 qFe(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 VFe(r,e){let t=e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping;`:"";return`I had to stop after ${qFe(r)} \u2014 this turn hit its processing time limit.${t} ask me to continue and I'll pick up from there.`}function HFe(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 ${qFe(r)} \u2014 a tool or model call appears to be stuck.${t} ask me to continue and I'll pick up from there.`}function KFe(r){return`This turn was stopped before I could finish.${r>0?` I completed ${r} tool call${r===1?"":"s"} before stopping.`:""}`}function dP(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 pP(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 mP(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??qA: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 ey(r,e=tv){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 Dre(r,e,t){r.push({role:"model",parts:e.length>0?e:t.map(n=>({functionCall:n}))})}function Ure(r){let e=xn(r,"openApi3"),t=pn(e);return t.$schema&&delete t.$schema,pi(t)}function L_(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 eG(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 Cj(n.buffer,n.mimeType,i);if(zI(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 Fre(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"?xs(s)?i=vs(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(xs(i)){a=vs(i);let c=Mv(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 eG(o,r?.nativeAudioFiles,t),o}var Hd,syr,Rre,zFe,tG=E(()=>{"use strict";Sa();$s();Rn();cs();Hte();X();dg();Ea();Cre();Xw();Hd=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}::${oyr(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}}},syr=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,Rre=128;zFe=100});var $re=E(()=>{"use strict";tG()});function Fu(){let r=[],e=!1,t,n=!1,o=null;function s(){if(o){let p=o;o=null,p()}}function i(p){e||(r.push(p),s())}function a(){e=!0,s()}function l(p){e=!0,t=p,n=!0,s()}let c=0;async function*u(){try{for(;;)if(c<r.length)yield r[c++],c>1024&&c*2>=r.length&&(r.splice(0,c),c=0);else if(e){if(n)throw t instanceof Error?t:new Error(String(t));return}else await new Promise(p=>{o=p})}finally{e=!0,r.length=0,o?.()}}return{push:i,close:a,error:l,iterable:u()}}var Kv=E(()=>{"use strict"});var om,Bre=E(()=>{"use strict";om=r=>r?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0});function Rg(r,e){if(e==="functionDeclarations")return kre(r);let t=Object.entries(r??{});if(t.length!==0)return t.map(([n,o])=>{let s=o,i=s.inputSchema??s.parameters,a=i?xn(i):{type:"object",properties:{}},l=om(o);return{name:n,...s.description?{description:s.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var rG=E(()=>{"use strict";tG();Bre();Ea()});function lyr(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 WFe(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)&&lyr(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 JFe=E(()=>{"use strict";X()});async function cyr(){try{return(await Promise.resolve().then(()=>(Eg(),lre))).getLangfuseContext?.()}catch{return}}function uyr(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 YFe(r,e){let t={};gx.inject(ur.active(),t);let n=await cyr();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=uyr(r,e);for(let[s,i]of Object.entries(t))o.has(s)||o.set(s,i);return{...e,headers:o}}function pyr(r){try{let e=typeof r=="string"?r:r instanceof URL?r.href:r.url;return new URL(e).hostname}catch{return"[unknown]"}}function myr(r){let e=r;for(let t=0;t<5&&e;t++){let n=e;if(n.code&&n$.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 ZFe(r,e,t=3,n=500){let o=pyr(r);return dyr.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:ze.OK}),l}catch(l){let c=myr(l),u=l;if(!c||a===t)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:ze.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 QFe(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 zre(r){let e={};r.headers.forEach((t,n)=>{e[n]=gyr.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 fyr(r){try{let e=new URL(r),t={protocol:e.protocol,hostname:e.hostname,port:parseInt(e.port)||XFe(e.protocol),cleanUrl:`${e.protocol}//${e.hostname}:${e.port||XFe(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 XFe(r){switch(r){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function hyr(r){if(WFe(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 yyr(r){let e=fyr(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(()=>(Av(),xee));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 Ll(r){return t1e(r)??"NOT_SET"}function e1e(r){return typeof r=="string"?r:r instanceof URL?r.href:r.url}function xyr(){return async(r,e)=>{let t=await YFe(r,e),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=e1e(r);if(g.shouldLog("debug")){let{size:i,type:a}=QFe(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 ZFe(r,t);if(g.shouldLog("debug")){let{parsed:a,size:l,type:c,headers:u}=await zre(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 vyr(r,e,t){let{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=t;e=await YFe(r,e);let l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=e1e(r);if(g.shouldLog("debug")){let{size:f,type:h}=QFe(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:Ll(o),httpsProxy:Ll(n),allProxy:Ll(s),socksProxy:Ll(i),noProxy:a||"NOT_SET",initMethod:e?.method||"GET"});let p=r instanceof Request?r.clone():null;try{let f=hyr(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:Ll(f),timestamp:new Date().toISOString()}),g.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:Ll(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=A2("sha256").update(t1e(f)??f).digest("hex"),T=x.get(b)||await yyr(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(()=>(Av(),xee))).fetch(w,{...C,dispatcher:T});if(g.shouldLog("debug")){let{parsed:P,size:I,type:A,headers:M}=await zre(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 ZFe(m,e);if(g.shouldLog("debug")){let{parsed:h,size:y,type:x,headers:b}=await zre(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 byr(r){return async(e,t)=>vyr(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:Ll(c),a},{});g.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:Ll(e),httpsProxy:Ll(r),allProxy:Ll(t),socksProxy:Ll(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"),xyr()):(g.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),g.debug(`[Proxy Fetch] HTTP_PROXY: ${Ll(e)}`),g.debug(`[Proxy Fetch] HTTPS_PROXY: ${Ll(r)}`),g.debug(`[Proxy Fetch] ALL_PROXY: ${Ll(t)}`),g.debug(`[Proxy Fetch] SOCKS_PROXY: ${Ll(n)}`),g.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),byr(s))}function t1e(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 dyr,gyr,so=E(()=>{"use strict";X();gr();Ar();JFe();Sa();BX();dyr=Oe.http;gyr=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"])});async function D_(r,e){let n=(await Promise.resolve().then(()=>(ww(),Sw))).GoogleGenAI;if(!n)throw new Le({code:tt.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 r1e(r,e,t){let n=Zj({contents:r,availableInputTokens:mi("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:cP(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:Yj}]})}return r.length=0,r.push(...i),!0}var jre,n1e=E(()=>{"use strict";eu();cs();qI();ac();Dt();Tt();X();nz();Ere();$d();_l();O_();gi();Kp();cI();$re();Kv();rG();so();jre=class extends oo{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 Le({code:tt.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 ol)return new cn(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 Mt("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 qr("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 yr(`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 cn(`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 mt(`Google AI server error: ${n}. Please try again later.`,this.providerName):new mt(`Google AI error: ${n}`,this.providerName)}async executeImageGeneration(e){await Uv(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 D_(s,this.getBaseURL())}catch{throw new Mt("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 mt(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&&jI(e.input),e.input?.files&&e.input.files.length>0)try{await GI(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 Uv(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=xI(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 KA({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=Ws(s,this.providerName,"stream");{let a=this.getApiKey(),l=await D_(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=[];L_(c,e.conversationMessages);let u=await Fre(e.input,e.input.text,"[GoogleAIStudio:stream]");c.push({role:"user",parts:u});let p,m=new Hd,f=new Map,h;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){let L=Rg(e.tools,"functionDeclarations");h=L,p=L.toolsConfig,m=L.executeMap,f=L.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?Ure(e.schema):void 0,b=Are({...e,model:t,wantsJsonOutput:y,responseSchema:x},p),T=Ire(e.maxSteps),w=Ux(e.abortSignal,i?.controller.signal),C=Fu(),R=[],k=[],P,I,A=new Promise((L,z)=>{P=L,I=z}),M={streamId:`native-${Date.now()}`,startTime:o,responseTime:0,totalToolExecutions:0};(async()=>{let L="",z=0,j=0,F=0,B=0,O=0,W=!1,re=new Map,te=ey(Fd("googleAiStudio",t));try{for(;O<T;){if((O===0||te.shouldStop())&&r1e(c,t,te.projectedNextPromptTokens)&&te.resetAfterReclaim(),w?.aborted)throw w.reason instanceof Error?w.reason:new Error("Request aborted");O++,h&&Qj(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 GFe(oe,C);z+=Z.inputTokens,j+=Z.outputTokens,F+=Z.cacheReadTokens??0,B+=Z.reasoningTokens??0,te.noteUsage(Z.inputTokens,Z.outputTokens);let we=Ore(Z.rawResponseParts);if(Z.stepFunctionCalls.length===0){W=!0;break}L=we;for(let N of Z.stepFunctionCalls)n.addEvent("gen_ai.tool_call",{"tool.name":N.name,"tool.step":O});g.debug(`[GoogleAIStudio] Executing ${Z.stepFunctionCalls.length} function calls`),Dre(c,Z.rawResponseParts,Z.stepFunctionCalls);let ve=R.length,ae=k.length,H=await Nre("[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 N=N_(Z.rawResponseParts);ht(this.handleToolExecutionStorage(V.map((Y,ee)=>({toolName:Y.toolName,args:Y.args,...ee===0&&N?{thoughtSignature:N}:{},stepIndex:O})),ne.map(Y=>({toolName:Y.name,output:Y.output,stepIndex:O})),e,new Date),sg,"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=Lre("[GoogleAIStudio]",O,T,"",L);oe&&C.push({content: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,j),n.setAttribute(Pe.GEN_AI_FINISH_REASON,pe?"max_steps":"stop");let J=Math.max(0,z-F);P({provider:this.providerName,model:t,tokenUsage:{input:J,output:j+B,total:J+F+j+B,...F>0?{cacheReadTokens:F}:{},...B>0?{reasoning:B}:{}},requestDuration:Ae,timestamp:new Date().toISOString()}),C.close()}catch(pe){C.error(pe),I(pe)}finally{i?.cleanup()}})().catch(()=>{});let $={stream:C.iterable,provider:this.providerName,model:t,toolCalls:R,analytics:A,metadata:M};return Object.defineProperty($,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>R.map(L=>L.toolName)}),Object.defineProperty($,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Tv(k)}),$}},n=>n.stream,(n,o)=>({...n,stream:o}))}async executeNativeGemini3Generate(e){let t=e.model||this.modelName;return jp({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=Ws(s,this.providerName,"generate");try{let a=this.getApiKey(),l=await D_(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=[];L_(u,e.conversationMessages);let p=await Fre(e.input,c,"[GoogleAIStudio:generate]");u.push({role:"user",parts:p});let m,f=new Hd,h=new Map,y,x=!e.disableTools,b=!!(e.output?.format==="json"||e.schema),T=xI(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=Rg(pe,"functionDeclarations");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?Ure(e.schema):void 0,R=Are({...e,model:t,wantsJsonOutput:w,responseSchema:C},m),k=Ux(e.abortSignal,i?.controller.signal),P=Ire(e.maxSteps),I="",A="",M=0,U=0,$=0,L=0,z=[],j=[],F=0,B=new Map,O=ey(Fd("googleAiStudio",t));for(;F<P;){if((F===0||O.shouldStop())&&r1e(u,t,O.projectedNextPromptTokens)&&O.resetAfterReclaim(),k?.aborted)throw k.reason instanceof Error?k.reason:new Error("Request aborted");F++,y&&Qj(e.tools,y),g.debug(`[GoogleAIStudio] Native SDK generate step ${F}/${P}`);try{let pe=await l.models.generateContentStream({model:t,contents:u,config:R,...k?{httpOptions:{signal:k}}:{}}),Ae=await jFe(pe);M+=Ae.inputTokens,U+=Ae.outputTokens,$+=Ae.cacheReadTokens??0,L+=Ae.reasoningTokens??0,O.noteUsage(Ae.inputTokens,Ae.outputTokens);let J=Ore(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":F});g.debug(`[GoogleAIStudio] Executing ${Ae.stepFunctionCalls.length} function calls in generate`),Dre(u,Ae.rawResponseParts,Ae.stepFunctionCalls);let oe=z.length,Z=j.length,we=await Nre("[GoogleAIStudio]",Ae.stepFunctionCalls,f,B,z,{toolExecutions:j,abortSignal:k,originalNameMap:h,liveTools:e.tools,declarations:y}),ve=z.slice(oe),ae=j.slice(Z);if(ve.length>0||ae.length>0){let H=N_(Ae.rawResponseParts);ht(this.handleToolExecutionStorage(ve.map((V,ne)=>({toolName:V.toolName,args:V.args,...ne===0&&H?{thoughtSignature:H}:{},stepIndex:F})),ae.map(V=>({toolName:V.name,output:V.output,stepIndex:F})),e,new Date),sg,"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:we});try{O.noteAppendedChars(JSON.stringify(we).length)}catch{}}catch(pe){throw g.error("[GoogleAIStudio] Native SDK generate error",pe),this.handleProviderError(pe)}}I=Lre("[GoogleAIStudio]",F,P,I,A);let W=Date.now()-o;n.setAttribute(Pe.GEN_AI_INPUT_TOKENS,M),n.setAttribute(Pe.GEN_AI_OUTPUT_TOKENS,U),n.setAttribute(Pe.GEN_AI_FINISH_REASON,F>=P?"max_steps":"stop");let re=Math.max(0,M-$),te={content:I,provider:this.providerName,model:t,usage:{input:re,output:U+L,total:re+$+U+L,...$>0?{cacheReadTokens:$}:{},...L>0?{reasoning:L}:{}},...L>0&&{reasoningTokens:L},responseTime:W,toolsUsed:z.map(pe=>pe.toolName),toolExecutions:Sv(e,j),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(Bp.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 D_(n,this.getBaseURL())}catch{throw new Mt("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 D_(o,this.getBaseURL())).models.embedContent({model:n,contents:[e]})).embeddings?.[0]?.values;if(!a)throw new mt("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 D_(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 Mt("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 o1e={};de(o1e,{GoogleAIStudioProvider:()=>jre});var s1e=E(()=>{"use strict";n1e()});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 kg=E(()=>{"use strict"});var zKn,jKn,GKn,qKn,Gre,Tyr,i1e,qre,VKn,HKn,WKn,JKn,a1e=E(()=>{zKn=globalThis.crypto,jKn=globalThis.ReadableStream||class{},GKn=globalThis.URL,qKn=globalThis.URLSearchParams,Gre=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Gre.custom=Symbol.for("nodejs.util.inspect.custom");Gre.colors={};Gre.styles={};Tyr=globalThis.TextDecoder,i1e=globalThis.TextEncoder,qre=(r,e)=>e?.(null,"127.0.0.1",4),VKn=globalThis.performance||{now:()=>Date.now()},HKn=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 i1e().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 i1e().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 Tyr().decode(this)}},WKn=globalThis.clearTimeout,JKn=globalThis.clearInterval});var ZKn,QKn,eWn,tWn,Vre,Syr,l1e,rWn,nWn,c1e,sWn,iWn,u1e=E(()=>{ZKn=globalThis.crypto,QKn=globalThis.ReadableStream||class{},eWn=globalThis.URL,tWn=globalThis.URLSearchParams,Vre=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Vre.custom=Symbol.for("nodejs.util.inspect.custom");Vre.colors={};Vre.styles={};Syr=globalThis.TextDecoder,l1e=globalThis.TextEncoder,rWn=globalThis.performance||{now:()=>Date.now()},nWn=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 l1e().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 l1e().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 Syr().decode(this)}},c1e=()=>0,sWn=globalThis.clearTimeout,iWn=globalThis.clearInterval});function Eyr(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 nG(r){if(r.length===0)return null;let e=r.split(".");if(e.length===4){let t=e.map(Eyr);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 p1e(r){if(c1e(r)!==6)return null;let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i),t;if(e){let n=nG(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 m1e(r){let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(e)return nG(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 d1e(r){let[e,t,n,o]=r.split(".").map(s=>parseInt(s,10));return(e<<24|t<<16|n<<8|o)>>>0}function gP(r){let e=d1e(r);for(let[t,n]of wyr){let o=d1e(t),s=n===0?0:4294967295<<32-n>>>0;if((e&s)===(o&s))return!0}return!1}function g1e(r){return _yr.some(e=>e.length===39?r===e:r.startsWith(e))}function f1e(r){return r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r}function h1e(r){let e=nG(r);if(e)return gP(e)?`IPv4 ${r} \u2192 ${e} is in a blocked range`:null;if(r.includes(":")){let t=m1e(r);if(t)return gP(t)?`IPv4-mapped IPv6 ${r} \u2192 ${t} is in a blocked range`:null;let n=p1e(r);return n?g1e(n)?`IPv6 ${r} is in a blocked range`:null:`IPv6 ${r} could not be parsed`}return"not-an-ip"}async function nu(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=f1e(e.hostname).toLowerCase(),n=h1e(t);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${r}" rejected: ${n}`);await y1e(r,t)}}async function y1e(r,e){let[t,n]=await Promise.allSettled([qre(e,{family:4,all:!0}),qre(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(gP(a))throw new Error(`URL "${r}" rejected: hostname ${e} resolves to ${a} (IPv4 in blocked range)`);for(let a of s){let l=h1e(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 x1e(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=f1e(e.hostname).toLowerCase(),n=nG(t);if(n){if(gP(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=m1e(t);if(l){if(gP(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=p1e(t);if(!c)throw new Error(`URL "${r}" rejected: IPv6 ${t} could not be parsed`);if(g1e(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 y1e(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 wyr,_yr,ty=E(()=>{"use strict";a1e();u1e();wyr=[["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]],_yr=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]});var v1e={};de(v1e,{createAnnotatedTool:()=>Kre,filterToolsByAnnotations:()=>Xre,getAnnotationSummary:()=>Yre,getToolSafetyLevel:()=>Jre,inferAnnotations:()=>ou,isSafeToRetry:()=>fP,mergeAnnotations:()=>oG,requiresConfirmation:()=>Wre,validateAnnotations:()=>Hre});function ou(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 oG(...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 Hre(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 Kre(r){let e=ou(r),t=oG(e,r.annotations);return{...r,annotations:t}}function Wre(r){return!!(r.annotations?.requiresConfirmation||r.annotations?.destructiveHint)}function fP(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 Xre(r,e){return r.filter(t=>{let n=t.annotations??{};return e(n)})}function Yre(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 U_=E(()=>{"use strict"});var sne={};de(sne,{TOOL_COMPATIBILITY:()=>one,batchConvertToMCP:()=>ene,batchConvertToNeuroLink:()=>tne,createToolFromFunction:()=>rne,mcpProtocolToolToServerTool:()=>Zre,mcpToolToNeuroLink:()=>iG,neuroLinkToolToMCP:()=>sG,sanitizeToolName:()=>hP,serverToolToMCPProtocol:()=>Qre,validateToolName:()=>nne});function sG(r,e={}){let{inferAnnotations:t=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=e,i=s?`${s}_${r.name}`:r.name,a=t?ou({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 iG(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 Zre(r,e,t={}){let{inferAnnotations:n=!0,defaultAnnotations:o={}}=t,s=r.annotations??{},i=n?ou({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 Qre(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 ene(r,e={}){return r.map(t=>sG(t,e))}function tne(r,e={}){return r.map(t=>iG(t,e))}function rne(r,e,t,n){let o=ou({name:r,description:e});return{name:r,description:e,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await ht(t(s,i),3e4,`Tool '${r}' execution timed out after 30000ms`),metadata:n?.metadata}}function nne(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 hP(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 one,yP=E(()=>{"use strict";U_();co();one={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 ki,b1e,aG,ine,sm,xP,ane,Cyr,Ryr,lne,cne,T1e,S1e,w1e,_1e,kyr,une,E1e,dne,C1e,vP,lG,R1e,Ag=E(()=>{"use strict";S1();yP();dg();Ea();gi();ki=r=>r.replace(/\/+$/,""),b1e=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,aG=(r,e)=>{if(r.every(o=>b1e.test(o)&&!e?.has(o)))return;let t=new Map,n=new Map;for(let o of r){let s=b1e.test(o)?o:hP(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}},ine=(r,e,t)=>{let n=0;for(let o of r){let s=typeof o.content=="string"?o.content:sm(o.content);n+=zt(s,t)+4;let i=o.tool_calls;i&&(n+=zt(sm(i),t))}return e&&e.length>0&&(n+=zt(sm(e),t)),n},sm=r=>{try{return JSON.stringify(r??"")}catch{return String(r??"")}},xP=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r??{})}catch{return"{}"}},ane=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:sm(e.value);case"json":return sm(e.value);case"execution-denied":return`Tool execution denied${e.reason?`: ${e.reason}`:""}`;case"error-text":return typeof e.value=="string"?e.value:sm(e.value);case"error-json":return sm(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(`
1070
+ ${e}`:e:r}async function jFe(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}}async function GFe(r,e){let t=[],n=[],o=0,s=0,i=0,a=0,l;for await(let c of r){let u=c,m=u.candidates?.[0],f=m?.finishReason;typeof f=="string"&&(l=f);let h=m?.content;if(h&&Array.isArray(h.parts))for(let x of h.parts)t.push(x),typeof x.text=="string"&&x.text.length>0&&e.push({content:x.text});c.functionCalls&&n.push(...c.functionCalls);let y=u.usageMetadata;y&&(o=Math.max(o,y.promptTokenCount||0),s=Math.max(s,y.candidatesTokenCount||0),i=Math.max(i,y.cachedContentTokenCount||0),a=Math.max(a,y.thoughtsTokenCount||0))}return{rawResponseParts:t,stepFunctionCalls:n,finishReason:l,inputTokens:o,outputTokens:s,cacheReadTokens:i,reasoningTokens:a}}function N_(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 Ore(r){return r.filter(e=>typeof e.text=="string").map(e=>e.text).join("")}async function Nre(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&&mI(s.liveTools,c)?.execute){Qj(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}-${Fn()}`,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 Lre(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||Cg(t,0)):n}function tu(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 Cg(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 ru(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 qFe(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 VFe(r,e){let t=e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping;`:"";return`I had to stop after ${qFe(r)} \u2014 this turn hit its processing time limit.${t} ask me to continue and I'll pick up from there.`}function HFe(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 ${qFe(r)} \u2014 a tool or model call appears to be stuck.${t} ask me to continue and I'll pick up from there.`}function KFe(r){return`This turn was stopped before I could finish.${r>0?` I completed ${r} tool call${r===1?"":"s"} before stopping.`:""}`}function dP(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 pP(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 mP(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??qA: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 ey(r,e=tv){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 Dre(r,e,t){r.push({role:"model",parts:e.length>0?e:t.map(n=>({functionCall:n}))})}function Ure(r){let e=xn(r,"openApi3"),t=pn(e);return t.$schema&&delete t.$schema,pi(t)}function L_(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 eG(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 Cj(n.buffer,n.mimeType,i);if(zI(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 Fre(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"?xs(s)?i=vs(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(xs(i)){a=vs(i);let c=Mv(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 eG(o,r?.nativeAudioFiles,t),o}var Hd,syr,Rre,zFe,tG=E(()=>{"use strict";Sa();$s();Rn();cs();Hte();X();dg();Ea();Cre();Xw();Hd=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}::${oyr(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}}},syr=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,Rre=128;zFe=100});var $re=E(()=>{"use strict";tG()});function Fu(){let r=[],e=!1,t,n=!1,o=null;function s(){if(o){let p=o;o=null,p()}}function i(p){e||(r.push(p),s())}function a(){e=!0,s()}function l(p){e=!0,t=p,n=!0,s()}let c=0;async function*u(){try{for(;;)if(c<r.length)yield r[c++],c>1024&&c*2>=r.length&&(r.splice(0,c),c=0);else if(e){if(n)throw t instanceof Error?t:new Error(String(t));return}else await new Promise(p=>{o=p})}finally{e=!0,r.length=0,o?.()}}return{push:i,close:a,error:l,iterable:u()}}var Kv=E(()=>{"use strict"});var om,Bre=E(()=>{"use strict";om=r=>r?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0});function Rg(r,e){if(e==="functionDeclarations")return kre(r);let t=Object.entries(r??{});if(t.length!==0)return t.map(([n,o])=>{let s=o,i=s.inputSchema??s.parameters,a=i?xn(i):{type:"object",properties:{}},l=om(o);return{name:n,...s.description?{description:s.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var rG=E(()=>{"use strict";tG();Bre();Ea()});function lyr(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 WFe(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)&&lyr(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 JFe=E(()=>{"use strict";X()});async function cyr(){try{return(await Promise.resolve().then(()=>(Eg(),lre))).getLangfuseContext?.()}catch{return}}function uyr(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 YFe(r,e){let t={};gx.inject(ur.active(),t);let n=await cyr();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=uyr(r,e);for(let[s,i]of Object.entries(t))o.has(s)||o.set(s,i);return{...e,headers:o}}function pyr(r){try{let e=typeof r=="string"?r:r instanceof URL?r.href:r.url;return new URL(e).hostname}catch{return"[unknown]"}}function myr(r){let e=r;for(let t=0;t<5&&e;t++){let n=e;if(n.code&&n$.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 ZFe(r,e,t=3,n=500){let o=pyr(r);return dyr.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:ze.OK}),l}catch(l){let c=myr(l),u=l;if(!c||a===t)throw s.setAttribute("http.request.total_attempts",i),s.setStatus({code:ze.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 QFe(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 zre(r){let e={};r.headers.forEach((t,n)=>{e[n]=gyr.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 fyr(r){try{let e=new URL(r),t={protocol:e.protocol,hostname:e.hostname,port:parseInt(e.port)||XFe(e.protocol),cleanUrl:`${e.protocol}//${e.hostname}:${e.port||XFe(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 XFe(r){switch(r){case"http:":return 8080;case"https:":return 8080;case"socks4:":return 1080;case"socks5:":return 1080;default:return 8080}}function hyr(r){if(WFe(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 yyr(r){let e=fyr(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(()=>(Av(),xee));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 Ll(r){return t1e(r)??"NOT_SET"}function e1e(r){return typeof r=="string"?r:r instanceof URL?r.href:r.url}function xyr(){return async(r,e)=>{let t=await YFe(r,e),n=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,o=Date.now(),s=e1e(r);if(g.shouldLog("debug")){let{size:i,type:a}=QFe(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 ZFe(r,t);if(g.shouldLog("debug")){let{parsed:a,size:l,type:c,headers:u}=await zre(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 vyr(r,e,t){let{httpsProxy:n,httpProxy:o,allProxy:s,socksProxy:i,noProxy:a}=t;e=await YFe(r,e);let l=`req-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,c=Date.now(),u=e1e(r);if(g.shouldLog("debug")){let{size:f,type:h}=QFe(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:Ll(o),httpsProxy:Ll(n),allProxy:Ll(s),socksProxy:Ll(i),noProxy:a||"NOT_SET",initMethod:e?.method||"GET"});let p=r instanceof Request?r.clone():null;try{let f=hyr(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:Ll(f),timestamp:new Date().toISOString()}),g.debug("[Proxy Fetch] \u{1F3AF} ENHANCED PROXY AGENT CREATION",{requestId:l,proxyUrl:Ll(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=A2("sha256").update(t1e(f)??f).digest("hex"),T=x.get(b)||await yyr(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(()=>(Av(),xee))).fetch(w,{...C,dispatcher:T});if(g.shouldLog("debug")){let{parsed:P,size:I,type:A,headers:M}=await zre(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 ZFe(m,e);if(g.shouldLog("debug")){let{parsed:h,size:y,type:x,headers:b}=await zre(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 byr(r){return async(e,t)=>vyr(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:Ll(c),a},{});g.debug("[Proxy Fetch] ENHANCED_PROXY_ENV_DETECTION",{httpProxy:Ll(e),httpsProxy:Ll(r),allProxy:Ll(t),socksProxy:Ll(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"),xyr()):(g.debug("[Proxy Fetch] Configuring enhanced proxy with multiple protocol support"),g.debug(`[Proxy Fetch] HTTP_PROXY: ${Ll(e)}`),g.debug(`[Proxy Fetch] HTTPS_PROXY: ${Ll(r)}`),g.debug(`[Proxy Fetch] ALL_PROXY: ${Ll(t)}`),g.debug(`[Proxy Fetch] SOCKS_PROXY: ${Ll(n)}`),g.debug(`[Proxy Fetch] NO_PROXY: ${o||"not set"}`),byr(s))}function t1e(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 dyr,gyr,so=E(()=>{"use strict";X();gr();Ar();JFe();Sa();BX();dyr=Oe.http;gyr=new Set(["authorization","x-api-key","api-key","x-goog-api-key","proxy-authorization","cookie","set-cookie"])});async function D_(r,e){let n=(await Promise.resolve().then(()=>(ww(),Sw))).GoogleGenAI;if(!n)throw new Le({code:tt.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 r1e(r,e,t){let n=Zj({contents:r,availableInputTokens:mi("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:cP(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:Yj}]})}return r.length=0,r.push(...i),!0}var jre,n1e=E(()=>{"use strict";eu();cs();qI();ac();Dt();Tt();X();nz();Ere();$d();_l();O_();gi();Kp();cI();$re();Kv();rG();so();jre=class extends oo{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 Le({code:tt.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 ol)return new cn(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 Mt("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 qr("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 yr(`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 cn(`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 mt(`Google AI server error: ${n}. Please try again later.`,this.providerName):new mt(`Google AI error: ${n}`,this.providerName)}async executeImageGeneration(e){await Uv(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 D_(s,this.getBaseURL())}catch{throw new Mt("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 mt(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&&jI(e.input),e.input?.files&&e.input.files.length>0)try{await GI(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 Uv(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=xI(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 KA({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=Ws(s,this.providerName,"stream");{let a=this.getApiKey(),l=await D_(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=[];L_(c,e.conversationMessages);let u=await Fre(e.input,e.input.text,"[GoogleAIStudio:stream]");c.push({role:"user",parts:u});let p,m=new Hd,f=new Map,h;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){let L=Rg(e.tools,"functionDeclarations");h=L,p=L.toolsConfig,m=L.executeMap,f=L.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?Ure(e.schema):void 0,b=Are({...e,model:t,wantsJsonOutput:y,responseSchema:x},p),T=Ire(e.maxSteps),w=Ux(e.abortSignal,i?.controller.signal),C=Fu(),R=[],k=[],P,I,A=new Promise((L,z)=>{P=L,I=z}),M={streamId:`native-${Date.now()}`,startTime:o,responseTime:0,totalToolExecutions:0};(async()=>{let L="",z=0,j=0,F=0,B=0,O=0,W=!1,re=new Map,te=ey(Fd("googleAiStudio",t));try{for(;O<T;){if((O===0||te.shouldStop())&&r1e(c,t,te.projectedNextPromptTokens)&&te.resetAfterReclaim(),w?.aborted)throw w.reason instanceof Error?w.reason:new Error("Request aborted");O++,h&&Qj(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 GFe(oe,C);z+=Z.inputTokens,j+=Z.outputTokens,F+=Z.cacheReadTokens??0,B+=Z.reasoningTokens??0,te.noteUsage(Z.inputTokens,Z.outputTokens);let we=Ore(Z.rawResponseParts);if(Z.stepFunctionCalls.length===0){W=!0;break}L=we;for(let N of Z.stepFunctionCalls)n.addEvent("gen_ai.tool_call",{"tool.name":N.name,"tool.step":O});g.debug(`[GoogleAIStudio] Executing ${Z.stepFunctionCalls.length} function calls`),Dre(c,Z.rawResponseParts,Z.stepFunctionCalls);let ve=R.length,ae=k.length,H=await Nre("[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 N=N_(Z.rawResponseParts);ht(this.handleToolExecutionStorage(V.map((Y,ee)=>({toolName:Y.toolName,args:Y.args,...ee===0&&N?{thoughtSignature:N}:{},stepIndex:O})),ne.map(Y=>({toolName:Y.name,output:Y.output,stepIndex:O})),e,new Date),sg,"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=Lre("[GoogleAIStudio]",O,T,"",L);oe&&C.push({content: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,j),n.setAttribute(Pe.GEN_AI_FINISH_REASON,pe?"max_steps":"stop");let J=Math.max(0,z-F);P({provider:this.providerName,model:t,tokenUsage:{input:J,output:j+B,total:J+F+j+B,...F>0?{cacheReadTokens:F}:{},...B>0?{reasoning:B}:{}},requestDuration:Ae,timestamp:new Date().toISOString()}),C.close()}catch(pe){C.error(pe),I(pe)}finally{i?.cleanup()}})().catch(()=>{});let $={stream:C.iterable,provider:this.providerName,model:t,toolCalls:R,analytics:A,metadata:M};return Object.defineProperty($,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>R.map(L=>L.toolName)}),Object.defineProperty($,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Tv(k)}),$}},n=>n.stream,(n,o)=>({...n,stream:o}))}async executeNativeGemini3Generate(e){let t=e.model||this.modelName;return jp({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=Ws(s,this.providerName,"generate");try{let a=this.getApiKey(),l=await D_(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=[];L_(u,e.conversationMessages);let p=await Fre(e.input,c,"[GoogleAIStudio:generate]");u.push({role:"user",parts:p});let m,f=new Hd,h=new Map,y,x=!e.disableTools,b=!!(e.output?.format==="json"||e.schema),T=xI(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=Rg(pe,"functionDeclarations");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?Ure(e.schema):void 0,R=Are({...e,model:t,wantsJsonOutput:w,responseSchema:C},m),k=Ux(e.abortSignal,i?.controller.signal),P=Ire(e.maxSteps),I="",A="",M=0,U=0,$=0,L=0,z=[],j=[],F=0,B=new Map,O=ey(Fd("googleAiStudio",t));for(;F<P;){if((F===0||O.shouldStop())&&r1e(u,t,O.projectedNextPromptTokens)&&O.resetAfterReclaim(),k?.aborted)throw k.reason instanceof Error?k.reason:new Error("Request aborted");F++,y&&Qj(e.tools,y),g.debug(`[GoogleAIStudio] Native SDK generate step ${F}/${P}`);try{let pe=await l.models.generateContentStream({model:t,contents:u,config:R,...k?{httpOptions:{signal:k}}:{}}),Ae=await jFe(pe);M+=Ae.inputTokens,U+=Ae.outputTokens,$+=Ae.cacheReadTokens??0,L+=Ae.reasoningTokens??0,O.noteUsage(Ae.inputTokens,Ae.outputTokens);let J=Ore(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":F});g.debug(`[GoogleAIStudio] Executing ${Ae.stepFunctionCalls.length} function calls in generate`),Dre(u,Ae.rawResponseParts,Ae.stepFunctionCalls);let oe=z.length,Z=j.length,we=await Nre("[GoogleAIStudio]",Ae.stepFunctionCalls,f,B,z,{toolExecutions:j,abortSignal:k,originalNameMap:h,liveTools:e.tools,declarations:y}),ve=z.slice(oe),ae=j.slice(Z);if(ve.length>0||ae.length>0){let H=N_(Ae.rawResponseParts);ht(this.handleToolExecutionStorage(ve.map((V,ne)=>({toolName:V.toolName,args:V.args,...ne===0&&H?{thoughtSignature:H}:{},stepIndex:F})),ae.map(V=>({toolName:V.name,output:V.output,stepIndex:F})),e,new Date),sg,"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:we});try{O.noteAppendedChars(JSON.stringify(we).length)}catch{}}catch(pe){throw g.error("[GoogleAIStudio] Native SDK generate error",pe),this.handleProviderError(pe)}}I=Lre("[GoogleAIStudio]",F,P,I,A);let W=Date.now()-o;n.setAttribute(Pe.GEN_AI_INPUT_TOKENS,M),n.setAttribute(Pe.GEN_AI_OUTPUT_TOKENS,U),n.setAttribute(Pe.GEN_AI_FINISH_REASON,F>=P?"max_steps":"stop");let re=Math.max(0,M-$),te={content:I,provider:this.providerName,model:t,usage:{input:re,output:U+L,total:re+$+U+L,...$>0?{cacheReadTokens:$}:{},...L>0?{reasoning:L}:{}},...L>0&&{reasoningTokens:L},responseTime:W,toolsUsed:z.map(pe=>pe.toolName),toolExecutions:Sv(e,j),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(Bp.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 D_(n,this.getBaseURL())}catch{throw new Mt("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 D_(o,this.getBaseURL())).models.embedContent({model:n,contents:[e]})).embeddings?.[0]?.values;if(!a)throw new mt("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 D_(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 Mt("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 o1e={};de(o1e,{GoogleAIStudioProvider:()=>jre});var s1e=E(()=>{"use strict";n1e()});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 kg=E(()=>{"use strict"});var zKn,jKn,GKn,qKn,Gre,Tyr,i1e,qre,VKn,HKn,WKn,JKn,a1e=E(()=>{zKn=globalThis.crypto,jKn=globalThis.ReadableStream||class{},GKn=globalThis.URL,qKn=globalThis.URLSearchParams,Gre=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Gre.custom=Symbol.for("nodejs.util.inspect.custom");Gre.colors={};Gre.styles={};Tyr=globalThis.TextDecoder,i1e=globalThis.TextEncoder,qre=(r,e)=>e?.(null,"127.0.0.1",4),VKn=globalThis.performance||{now:()=>Date.now()},HKn=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 i1e().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 i1e().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 Tyr().decode(this)}},WKn=globalThis.clearTimeout,JKn=globalThis.clearInterval});var ZKn,QKn,eWn,tWn,Vre,Syr,l1e,rWn,nWn,c1e,sWn,iWn,u1e=E(()=>{ZKn=globalThis.crypto,QKn=globalThis.ReadableStream||class{},eWn=globalThis.URL,tWn=globalThis.URLSearchParams,Vre=r=>{try{return JSON.stringify(r,null,2)}catch{return String(r)}};Vre.custom=Symbol.for("nodejs.util.inspect.custom");Vre.colors={};Vre.styles={};Syr=globalThis.TextDecoder,l1e=globalThis.TextEncoder,rWn=globalThis.performance||{now:()=>Date.now()},nWn=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 l1e().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 l1e().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 Syr().decode(this)}},c1e=()=>0,sWn=globalThis.clearTimeout,iWn=globalThis.clearInterval});function Eyr(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 nG(r){if(r.length===0)return null;let e=r.split(".");if(e.length===4){let t=e.map(Eyr);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 p1e(r){if(c1e(r)!==6)return null;let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i),t;if(e){let n=nG(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 m1e(r){let e=r.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);if(e)return nG(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 d1e(r){let[e,t,n,o]=r.split(".").map(s=>parseInt(s,10));return(e<<24|t<<16|n<<8|o)>>>0}function gP(r){let e=d1e(r);for(let[t,n]of wyr){let o=d1e(t),s=n===0?0:4294967295<<32-n>>>0;if((e&s)===(o&s))return!0}return!1}function g1e(r){return _yr.some(e=>e.length===39?r===e:r.startsWith(e))}function f1e(r){return r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r}function h1e(r){let e=nG(r);if(e)return gP(e)?`IPv4 ${r} \u2192 ${e} is in a blocked range`:null;if(r.includes(":")){let t=m1e(r);if(t)return gP(t)?`IPv4-mapped IPv6 ${r} \u2192 ${t} is in a blocked range`:null;let n=p1e(r);return n?g1e(n)?`IPv6 ${r} is in a blocked range`:null:`IPv6 ${r} could not be parsed`}return"not-an-ip"}async function nu(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=f1e(e.hostname).toLowerCase(),n=h1e(t);if(n!==null){if(n!=="not-an-ip")throw new Error(`URL "${r}" rejected: ${n}`);await y1e(r,t)}}async function y1e(r,e){let[t,n]=await Promise.allSettled([qre(e,{family:4,all:!0}),qre(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(gP(a))throw new Error(`URL "${r}" rejected: hostname ${e} resolves to ${a} (IPv4 in blocked range)`);for(let a of s){let l=h1e(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 x1e(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=f1e(e.hostname).toLowerCase(),n=nG(t);if(n){if(gP(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=m1e(t);if(l){if(gP(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=p1e(t);if(!c)throw new Error(`URL "${r}" rejected: IPv6 ${t} could not be parsed`);if(g1e(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 y1e(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 wyr,_yr,ty=E(()=>{"use strict";a1e();u1e();wyr=[["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]],_yr=["0000:0000:0000:0000:0000:0000:0000:0000","0000:0000:0000:0000:0000:0000:0000:0001","fc","fd","fe8","fe9","fea","feb"]});var v1e={};de(v1e,{createAnnotatedTool:()=>Kre,filterToolsByAnnotations:()=>Xre,getAnnotationSummary:()=>Yre,getToolSafetyLevel:()=>Jre,inferAnnotations:()=>ou,isSafeToRetry:()=>fP,mergeAnnotations:()=>oG,requiresConfirmation:()=>Wre,validateAnnotations:()=>Hre});function ou(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 oG(...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 Hre(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 Kre(r){let e=ou(r),t=oG(e,r.annotations);return{...r,annotations:t}}function Wre(r){return!!(r.annotations?.requiresConfirmation||r.annotations?.destructiveHint)}function fP(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 Xre(r,e){return r.filter(t=>{let n=t.annotations??{};return e(n)})}function Yre(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 U_=E(()=>{"use strict"});var sne={};de(sne,{TOOL_COMPATIBILITY:()=>one,batchConvertToMCP:()=>ene,batchConvertToNeuroLink:()=>tne,createToolFromFunction:()=>rne,mcpProtocolToolToServerTool:()=>Zre,mcpToolToNeuroLink:()=>iG,neuroLinkToolToMCP:()=>sG,sanitizeToolName:()=>hP,serverToolToMCPProtocol:()=>Qre,validateToolName:()=>nne});function sG(r,e={}){let{inferAnnotations:t=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=e,i=s?`${s}_${r.name}`:r.name,a=t?ou({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 iG(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 Zre(r,e,t={}){let{inferAnnotations:n=!0,defaultAnnotations:o={}}=t,s=r.annotations??{},i=n?ou({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 Qre(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 ene(r,e={}){return r.map(t=>sG(t,e))}function tne(r,e={}){return r.map(t=>iG(t,e))}function rne(r,e,t,n){let o=ou({name:r,description:e});return{name:r,description:e,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await ht(t(s,i),3e4,`Tool '${r}' execution timed out after 30000ms`),metadata:n?.metadata}}function nne(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 hP(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 one,yP=E(()=>{"use strict";U_();co();one={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 ki,b1e,aG,ine,sm,xP,ane,Cyr,Ryr,lne,cne,T1e,S1e,w1e,_1e,kyr,une,E1e,dne,C1e,vP,lG,R1e,Ag=E(()=>{"use strict";S1();yP();dg();Ea();gi();ki=r=>r.replace(/\/+$/,""),b1e=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,aG=(r,e)=>{if(r.every(o=>b1e.test(o)&&!e?.has(o)))return;let t=new Map,n=new Map;for(let o of r){let s=b1e.test(o)?o:hP(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}},ine=(r,e,t)=>{let n=0;for(let o of r){let s=typeof o.content=="string"?o.content:sm(o.content);n+=zt(s,t)+4;let i=o.tool_calls;i&&(n+=zt(sm(i),t))}return e&&e.length>0&&(n+=zt(sm(e),t)),n},sm=r=>{try{return JSON.stringify(r??"")}catch{return String(r??"")}},xP=r=>{if(typeof r=="string")return r;try{return JSON.stringify(r??{})}catch{return"{}"}},ane=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:sm(e.value);case"json":return sm(e.value);case"execution-denied":return`Tool execution denied${e.reason?`: ${e.reason}`:""}`;case"error-text":return typeof e.value=="string"?e.value:sm(e.value);case"error-json":return sm(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
1071
  `):"";default:return sm(r)}},Cyr=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")}`},Ryr=r=>{if(typeof r=="string")return r;if(!Array.isArray(r))return sm(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=Cyr(o);s&&e.push({type:"image_url",image_url:{url:s}})}}return e.length===1&&e[0].type==="text"?e[0].text:e},lne=(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:sm(n.content)});break;case"user":t.push({role:"user",content:Ryr(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:xP(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:ane(s.output)})}else typeof n.content=="string"&&t.push({role:"tool",tool_call_id:n.toolCallId??"",content:n.content});break}}return t},cne=(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?GQ(xn(a)):{type:"object",properties:{}};n.push({type:"function",function:{name:e?.get(o)??o,...i.description?{description:i.description}:{},parameters:l}})}return n},T1e=(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:GQ(n.inputSchema),...n.strict!==void 0?{strict:n.strict}:{}}});return t.length>0?t:void 0},S1e=(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}}}},w1e=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"},_1e=(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}}}}},kyr=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}),une=r=>r.response_format?.type==="json_object"&&!kyr(r.messages)?{...r,messages:[{role:"system",content:"Respond with valid JSON only \u2014 no prose, no markdown fencing."},...r.messages]}:r,E1e=r=>/^(o\d|gpt-5)/i.test(r.replace(/^.*\//,"")),dne=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=_a("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},C1e=async(r,e,t)=>{let n={text:"",reasoning:"",toolCalls:new Map,finishReason:null,usage:void 0},o=new TextDecoder,s,a=jS({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},vP=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},lG=()=>{let r=()=>{},e=new Promise(o=>{r=o}),t=()=>{},n=new Promise(o=>{t=o});return{usagePromise:e,finishPromise:n,resolveUsage:r,resolveFinish:t}},R1e=(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 cG(r){if(typeof r=="string")return r;if(r==null)return"";try{return JSON.stringify(r)??""}catch{return"x".repeat(2e5)}}function Iyr(r,e){let t=cG(r.content);return r.role==="assistant"&&r.tool_calls&&(t+=cG(r.tool_calls)),zt(t,e)+4}function Pyr(r,e){if(r.role!=="tool")return;let t=cG(r.content),n={maxBytes:k1e,maxLines:A1e};if(!tz(t,n))return;let{preview:o}=fi(t,n);return zt(o,e)+4}function Myr(r,e){return r.map(t=>{let n=Iyr(t,e);if(t.role==="tool"){let o=Pyr(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 I1e(r){let{conversation:e,availableInputTokens:t,fixedOverheadTokens:n,provider:o,observedPromptTokens:s,previousSentEstimate:i,onSentEstimate:a}=r,l=Myr(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=M_(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}=fi(cG(x.content),{maxBytes:k1e,maxLines:A1e});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:Ayr})}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 k1e,A1e,Ayr,P1e=E(()=>{"use strict";gi();Oh();Xj();X();k1e=2048,A1e=60,Ayr="[Earlier tool exchanges were removed to fit the context window.]"});function bP(r){let e=pne(r);return e?M1e.some(({patterns:t})=>t.some(n=>n.test(e))):!1}function O1e(r){let e=pne(r);if(!e)return null;for(let{provider:t,patterns:n}of M1e)if(n.some(o=>o.test(e)))return t;return null}function TP(r){let e=pne(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 pne(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 M1e,mne=E(()=>{"use strict";M1e=[{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,gne=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 fne,uG,hne=E(()=>{"use strict";qw();X();Gw();Np();fne=class{async collectUsage(e){try{let t=await e.usage;return t?Ld(t):(g.debug("No usage data available from stream result"),SQ())}catch(t){return Ta.isInstance(t)?g.debug("No output generated from stream \u2014 returning empty usage"):g.warn("Failed to collect usage from stream result",{error:t}),SQ()}}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 Ta.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 Hp(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)}),Hp(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()}},uG=new fne});function dG(r,e,t){return!t||!e||Object.keys(e).length===0?"none":r.toolChoice??"auto"}var yne=E(()=>{"use strict"});var xne,$n,hc=E(()=>{"use strict";gr();$d();P1e();mne();gne();eu();cs();hne();so();X();Hr();Np();Pj();_l();XB();yne();Kp();Qm();Xw();Ag();Kv();xne=512,$n=class extends oo{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=QB(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=GOe(this.providerName,e);if(a!==void 0){let l=ine(n,o,this.providerName),c=a-l-xne;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-xne),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(!bP(t))return;let n=TP(t)??TP(t.responseBody);if(!n||n.budgetTokens<=0)return;ZB(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-xne;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`${ki(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=`${ki(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:Ir(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=aG((h.tools??[]).filter(B=>B.type==="function").map(B=>B.name)),x=lne(h.prompt,y?.toWire),b=Array.isArray(h.tools)&&h.tools.length>0,T=h.responseFormat&&!(b&&m())?a(w1e(h.responseFormat),e):void 0,w=T1e(h.tools,y?.toWire),C=p(e,h.maxOutputTokens,x,w),R=une(l(dne({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:S1e(h.toolChoice,y?.toWire)}:{},streaming:!1,...T?{responseFormat:T}:{}}),e)),k=h.providerOptions?.neurolink?.timeoutMs,P=Ws(typeof k=="number"?k:f(h),s,"generate"),{signal:I,dispose:A}=d_e(h.abortSignal,P?.controller.signal),M;try{let B=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(R),...I?{signal:I}:{}});if(!B.ok){let O=await vP(t,R,B),W=B.status===400?(()=>{let re=O,te=u(R,re);return c(te??R,re)??te})():void 0;if(!W)throw O;if(B=await n(t,{method:"POST",headers:{"Content-Type":"application/json",...o()},body:JSON.stringify(W),...I?{signal:I}:{}}),!B.ok)throw await vP(t,W,B)}M=await B.json()}finally{P?.cleanup(),A()}let U=M.choices?.[0],$=(typeof U?.message?.content=="string"?U.message.content:"")??"",L=[],z=U?.message?.reasoning_content||U?.message?.reasoning;typeof z=="string"&&z.length>0&&L.push({type:"reasoning",text:z}),$.length>0&&L.push({type:"text",text:$});for(let B of U?.message?.tool_calls??[])L.push({type:"tool-call",toolCallId:B.id,toolName:y?.fromWire.get(B.function.name)??B.function.name,input:B.function.arguments??""});let j=U?.finish_reason;return{content:L,finishReason:{unified:j==="length"?"length":j==="tool_calls"||j==="function_call"?"tool-calls":j==="content_filter"?"content-filter":"stop",raw:j??"stop"},usage:{inputTokens:{total: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=Ws(o,this.providerName,"stream"),i=new AbortController,a=f1([e.abortSignal,s?.controller.signal,i.signal]).signal,l,c,u,p,m,f;try{l=await this.resolveModelName();let F=!e.disableTools&&this.supportsTools();c=F?e.tools||await this.getAllTools():{},u=F?aG(Object.keys(c)):void 0,p=F?cne(c,u?.toWire):void 0,m=_1e(dG(e,c,F),u?.toWire);let B=await this.buildMessagesForStream(e);f=lne(B,u?.toWire)}catch(F){throw s?.cleanup(),F}let h=this.getChatCompletionsURL(l),y=yt(),x=e.maxSteps||Jo,b=this.neurolink?.getEventEmitter(),T=[],w=[],{usagePromise:C,finishPromise:R,resolveUsage:k,resolveFinish:P}=lG(),I=Fu(),A=this.onStreamStart(l),M=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.push,closeChannel:I.close,resolveUsage:k,resolveFinish:P}),U,$=F=>{U=F};A?.onUsage&&C.then(A.onUsage).catch(()=>{}),A?.onFinish&&R.then(F=>A.onFinish?.(F,U)).catch(()=>{});let L=this.providerName,j={stream:async function*(){let F=0;try{for await(let B of I.iterable)"content"in B&&typeof B.content=="string"&&B.content.length>0&&F++,yield B;if(await M,F===0&&T.length===0){g.warn(`${L}: Stream produced no output \u2014 emitting enriched sentinel`);let B=new Ta({message:"Stream produced no output"}),O=await Zp(B,void 0,U);Qp(O),yield O}}catch(B){if(Ta.isInstance(B)){let W=await Zp(B,void 0,U);Qp(W),yield W;return}let O=await Zp(B,void 0,U);throw Qp(O),yield O,B}finally{i.signal.aborted||i.abort()}}(),provider:this.providerName,model:l,analytics:uG.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(j,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>Tv(w.map(F=>({toolName:F.toolName,input:F.input,output:F.output,duration:F.endTime.getTime()-F.startTime.getTime()})))}),M.finally(()=>s?.cleanup()).catch(F=>{$(F)}),j}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,closeChannel:b,resolveUsage:T,resolveFinish:w}=e,C=null,R,k=()=>{let P=R?.prompt_tokens??0,I=R?.completion_tokens??0,A=Math.min(R?.prompt_tokens_details?.cached_tokens??0,P),M=Math.min(Math.max(0,R?.completion_tokens_details?.reasoning_tokens??0),I);return{promptTokens:P-A,completionTokens:I,totalTokens:R?.total_tokens||P+I,...A>0?{cacheReadTokens:A}:{},...M>0?{reasoningTokens:M}:{}}};try{let P=m,I,A;for(let M=0;M<t;M++){if(c){let L=new Set(c.map(j=>P?.get(j.function.name)??j.function.name)),z=Object.fromEntries(Object.entries(p).filter(([j])=>!L.has(j)));if(Object.keys(z).length>0){let j=aG(Object.keys(z),new Set(c.map(F=>F.function.name)));if(j){P??=new Map;for(let[F,B]of j.fromWire)P.set(F,B)}c.push(...cne(z,j?.toWire)??[]),g.info(`${this.providerName}: ${Object.keys(z).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(z).join(", ")}`)}}let U=I1e({conversation:l,availableInputTokens:mi(this.providerName,n,a.maxTokens??void 0),fixedOverheadTokens:ine([],c,this.providerName),provider:this.providerName,observedPromptTokens:I,previousSentEstimate:A,onSentEstimate:L=>{A=L}});U&&(l.length=0,l.push(...U));let $=await this.streamOneStep({modelId:n,url:o,fetchImpl:s,abortSignal:i,options:a,conversation:l,openAITools:c,openAIToolChoice:u,pushChunk:x});if(I=$.usage?.prompt_tokens,C=$.finishReason,$.usage&&(R=R1e(R,$.usage)),$.toolCalls.size===0)break;await this.executeToolBatch({stepResult:$,conversation:l,toolsRecord:p,toolNameFromWire:P,emitter:f,toolsUsed:h,toolExecutionSummaries:y,options:a})}return T(k()),w(C??"stop"),b(),{finishReason:C??"stop",usage:R}}catch(P){throw g.error(`${this.providerName}: Stream error`,{error:P instanceof Error?P.message:String(P)}),T(k()),w("error"),b(),P}}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=une(this.adjustRequestBody(dne({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 vP(e.url,o,a);return a},i;try{i=await Ru(s,pt.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 vP(e.url,c,i)}if(!i.body)throw new Error(`${this.providerName}: stream response had no body`);return C1e(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]??pI(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:ane(y)})}let p=l.slice(-t.toolCalls.size);Yw(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=`${ki(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 N1e,Oyr,Nyr,Lyr,Dyr,vne,L1e=E(()=>{"use strict";gr();so();Dt();X();Hr();Dd();ea();Ko();kg();ty();_l();Ag();hc();N1e="https://api.openai.com/v1",Oyr=(r,e)=>{let t=[r,e].map(n=>n?.trim()).find(n=>!!n&&n.length>0)??N1e;try{let n=new URL(t),o=n.pathname&&n.pathname!=="/";if(n.hostname==="api.openai.com"&&!o)return n.pathname="/v1",ki(n.toString())}catch{}return t},Nyr=()=>an(aye()),Lyr=()=>ln("OPENAI_MODEL","gpt-4o"),Dyr=pt.getTracer("neurolink.provider.openai"),vne=class extends $n{constructor(e,t,n,o){let s=o?.apiKey?.trim(),i=s&&s.length>0?s:Nyr(),a=Oyr(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:Ir(this.config.baseURL)})}suppressResponseFormatWithTools(){return!1}getProviderName(){return"openai"}getDefaultModel(){return Lyr()}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:Mt,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:qr,message:"OpenAI rate limit exceeded. Please try again later."},{match:s=>/model_not_found/i.test(s.message),errorClass:yr,message:s=>`Model not found: ${s.modelName}`},...tn];return en(e,o,this.providerName,this.modelName)}onStreamStart(e){let t=Dyr.startSpan("neurolink.provider.streamText",{kind:br.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=Us(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:ze.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=`${ki(this.config.baseURL)}/embeddings`,s=yt(),i=Ws(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 mt(`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=ki(this.config.baseURL??N1e),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 nu(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 D1e={};de(D1e,{OpenAIProvider:()=>vne});var U1e=E(()=>{"use strict";L1e()});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 yc=E(()=>{});var F_,pG=E(()=>{F_=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return F_=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 Kd(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Wv,Jv=E(()=>{Wv=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,zs,Ia,im,$_,SP,B_,z_,j_,G_,q_,V_,H_,K_,fo=E(()=>{Jv();Ye=class extends Error{},zs=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 im({message:n,cause:Wv(t)});let s=t,i=s?.error?.type;return e===400?new B_(e,s,n,o,i):e===401?new z_(e,s,n,o,i):e===403?new j_(e,s,n,o,i):e===404?new G_(e,s,n,o,i):e===409?new q_(e,s,n,o,i):e===422?new V_(e,s,n,o,i):e===429?new H_(e,s,n,o,i):e>=500?new K_(e,s,n,o,i):new r(e,s,n,o,i)}},Ia=class extends zs{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},im=class extends zs{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},$_=class extends im{constructor({message:e}={}){super({message:e??"Request timed out."})}},SP=class extends Ye{constructor(e,{cause:t}={}){super(e??"Retryable error."),t!==void 0&&(this.cause=t)}},B_=class extends zs{},z_=class extends zs{},j_=class extends zs{},G_=class extends zs{},q_=class extends zs{},V_=class extends zs{},H_=class extends zs{},K_=class extends zs{}});function mG(r){return typeof r!="object"?{}:r??{}}function Tne(r){if(!r)return!0;for(let e in r)return!1;return!0}function $1e(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Fyr,F1e,pl,bne,B1e,gG,am=E(()=>{fo();Fyr=/^[a-z][a-z0-9+.-]*:/i,F1e=r=>Fyr.test(r),pl=r=>(pl=Array.isArray,pl(r)),bne=pl;B1e=(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},gG=r=>{try{return JSON.parse(r)}catch{return}}});var Wd,W_=E(()=>{Wd=(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 $u,wP=E(()=>{$u="0.102.0"});function $yr(){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 zyr(){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 q1e,Byr,z1e,j1e,G1e,_P,fG=E(()=>{wP();q1e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Byr=()=>{let r=$yr();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$u,"X-Stainless-OS":j1e(Deno.build.os),"X-Stainless-Arch":z1e(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":$u,"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":$u,"X-Stainless-OS":j1e(globalThis.process.platform??"unknown"),"X-Stainless-Arch":z1e(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=zyr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$u,"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":$u,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};z1e=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",j1e=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"),_P=()=>G1e??(G1e=Byr())});function V1e(){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 Sne(...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 hG(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Sne({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function EP(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 H1e(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 J_=E(()=>{});var K1e,W1e=E(()=>{K1e=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});var wne,_ne,Ene,J1e,Cne=E(()=>{wne="RFC3986",_ne=r=>String(r),Ene={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:_ne},J1e="RFC1738"});function Y1e(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function kne(r,e){if(pl(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var yG,lm,Rne,X1e,Z1e=E(()=>{Cne();am();yG=(r,e)=>(yG=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),yG(r,e)),lm=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),Rne=1024,X1e=(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+=Rne){let l=s.length>=Rne?s.slice(a,a+Rne):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===J1e&&(p===40||p===41)){c[c.length]=l.charAt(u);continue}if(p<128){c[c.length]=lm[p];continue}if(p<2048){c[c.length]=lm[192|p>>6]+lm[128|p&63];continue}if(p<55296||p>=57344){c[c.length]=lm[224|p>>12]+lm[128|p>>6&63]+lm[128|p&63];continue}u+=1,p=65536+((p&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=lm[240|p>>18]+lm[128|p>>12&63]+lm[128|p>>6&63]+lm[128|p&63]}i+=c.join("")}return i}});function qyr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}function r$e(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(Ane))!==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(Ane)>"u"&&(C=0)}if(typeof c=="function"?T=c(e,T):T instanceof Date?T=m?.(T):t==="comma"&&pl(T)&&(T=kne(T,function(M){return M instanceof Date?m?.(M):M})),T===null){if(s)return l&&!y?l(e,Ai.encoder,x,"key",f):e;T=""}if(qyr(T)||Y1e(T)){if(l){let M=y?e:l(e,Ai.encoder,x,"key",f);return[h?.(M)+"="+h?.(l(T,Ai.encoder,x,"value",f))]}return[h?.(e)+"="+h?.(String(T))]}let k=[];if(typeof T>"u")return k;let P;if(t==="comma"&&pl(T))y&&l&&(T=kne(T,l)),P=[{value:T.length>0?T.join(",")||null:void 0}];else if(pl(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&&pl(T)&&T.length===1?I+"[]":I;if(o&&pl(T)&&T.length===0)return A+"[]";for(let M=0;M<P.length;++M){let U=P[M],$=typeof U=="object"&&typeof U.value<"u"?U.value:T[U];if(i&&$===null)continue;let L=p&&a?U.replace(/\./g,"%2E"):U,z=pl(T)?typeof t=="function"?t(A,L):A:A+(p?"."+L:"["+L+"]");b.set(r,C);let j=new WeakMap;j.set(Ane,b),t$e(k,r$e($,z,t,n,o,s,i,a,t==="comma"&&y&&pl(T)?null:l,c,u,p,m,f,h,y,x,j))}return k}function Vyr(r=Ai){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||Ai.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=wne;if(typeof r.format<"u"){if(!yG(Ene,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=Ene[t],o=Ai.filter;(typeof r.filter=="function"||pl(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in e$e?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=Ai.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:Ai.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Ai.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Ai.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Ai.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Ai.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Ai.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Ai.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Ai.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Ai.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Ai.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Ai.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Ai.strictNullHandling}}function n$e(r,e={}){let t=r,n=Vyr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):pl(n.filter)&&(s=n.filter,o=s);let i=[];if(typeof t!="object"||t===null)return"";let a=e$e[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||t$e(i,r$e(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 e$e,t$e,Q1e,Ai,Ane,o$e=E(()=>{Z1e();Cne();am();e$e={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},t$e=function(r,e){Array.prototype.push.apply(r,pl(e)?e:[e])},Ai={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:X1e,encodeValuesOnly:!1,format:wne,formatter:_ne,indices:!1,serializeDate(r){return(Q1e??(Q1e=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};Ane={}});function s$e(r){return n$e(r,{arrayFormat:"brackets"})}var Ine=E(()=>{o$e()});function vG(r){if(!r)return;let e;try{e=new URL(r)}catch(n){throw new vn(`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 vn(`Refusing to send credential over non-https token endpoint "${r}"`)}async function bG(r,e){let t=await Wyr(r),n;try{n=JSON.parse(t)}catch{throw new vn(`Token endpoint returned non-JSON response (status ${r.status})`,r.status,xc(t),e)}if(!n.access_token)throw new vn(`Token endpoint response missing access_token: ${JSON.stringify(xc(n))}`,r.status,xc(n),e);if(n.token_type&&n.token_type.toLowerCase()!=="bearer")throw new vn(`Token endpoint response: unsupported token_type "${n.token_type}" (want Bearer)`,r.status,xc(n),e);return n}function xc(r){if(r==null)return r;if(typeof r=="string"){let e;try{e=JSON.parse(r)}catch{return r.length<=Pne?r:r.slice(0,Pne)+`... <${r.length-Pne} more chars>`}return JSON.stringify(xc(e))}if(typeof r=="object"&&!Array.isArray(r)){let e={};for(let[t,n]of Object.entries(r))Kyr.has(t)&&(e[t]=n);return e}return null}async function TG(r,e=t=>console.warn(`anthropic-sdk: ${t}`)){if(typeof process>"u"||process.platform==="win32")return;let t=await Promise.resolve().then(()=>($s(),jd)),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 vn(`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 vn(`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 SG(r,e){let t=await Promise.resolve().then(()=>($s(),jd)),o=(await Promise.resolve().then(()=>(Rn(),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 Wyr(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>i$e){let a=i$e-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 a$e,l$e,xG,Xv,c$e,u$e,X_,d$e,i$e,Pne,Kyr,vn,Y_=E(()=>{fo();a$e="urn:ietf:params:oauth:grant-type:jwt-bearer",l$e="refresh_token",xG="/v1/oauth/token",Xv="oauth-2025-04-20",c$e="oidc-federation-2026-04-01",u$e=120,X_=30,d$e=5,i$e=1<<20;Pne=2e3,Kyr=new Set(["error","error_description","error_uri"]);vn=class extends Ye{constructor(e,t=null,n=null,o=null){super(e),this.statusCode=t,this.body=n,this.requestId=o}}});function Jd(){return Math.floor(Date.now()/1e3)}var CP=E(()=>{});var wG,p$e=E(()=>{Y_();CP();wG=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-Jd();return n>u$e?t.token:n>X_?(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||Jd()-this.lastAdvisoryError<d$e||this.doRefresh().catch(e=>{this.lastAdvisoryError=Jd(),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 $r,RP=E(()=>{$r=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 f$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 Z_(r){let e;return(m$e??(e=new globalThis.TextEncoder,m$e=e.encode.bind(e)))(r)}function Mne(r){let e;return(g$e??(e=new globalThis.TextDecoder,g$e=e.decode.bind(e)))(r)}var m$e,g$e,_G=E(()=>{});var h$e=E(()=>{fo();_G()});function kP(){}function EG(r,e,t){return!e||CG[r]>CG[t]?kP:e[r].bind(e)}function mn(r){let e=r.logger,t=r.logLevel??"off";if(!e)return Jyr;let n=y$e.get(e);if(n&&n[0]===t)return n[1];let o={error:EG("error",e,t),warn:EG("warn",e,t),info:EG("info",e,t),debug:EG("debug",e,t)};return y$e.set(e,[t,o]),o}var CG,One,Jyr,y$e,cm,Pg=E(()=>{am();CG={off:0,error:200,warn:300,info:400,debug:500},One=(r,e,t)=>{if(r){if($1e(CG,r))return r;mn(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(CG))}`)}};Jyr={error:kP,warn:kP,info:kP,debug:kP},y$e=new WeakMap;cm=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 Nne=E(()=>{am();h$e();RP();Pg();pG();W_();Ine()});function x$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(!Xyr.test(r))throw new Error(`profile name "${r}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`)}var RG,Xyr,v$e,b$e,Lne,Yyr,T$e,Dne=E(()=>{fG();Nne();RG="1.0",Xyr=/^[A-Za-z0-9_.-]+$/;v$e=async r=>{var e,t;let n=await Lne();if(n===null)return null;let o=r??await T$e();if(o===null)return null;x$e(o);let s=await Promise.resolve().then(()=>($s(),jd)),a=(await Promise.resolve().then(()=>(Rn(),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=$r("ANTHROPIC_ORGANIZATION_ID"),m=$r("ANTHROPIC_IDENTITY_TOKEN_FILE"),f=$r("ANTHROPIC_FEDERATION_RULE_ID");return f&&p?{fromFile:!1,config:{organization_id:p,workspace_id:$r("ANTHROPIC_WORKSPACE_ID"),base_url:$r("ANTHROPIC_BASE_URL"),authentication:{type:"oidc_federation",federation_rule_id:f,service_account_id:$r("ANTHROPIC_SERVICE_ACCOUNT_ID"),identity_token:m?{source:"file",path:m}:void 0,scope:$r("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=$r("ANTHROPIC_ORGANIZATION_ID")),c.workspace_id??(c.workspace_id=$r("ANTHROPIC_WORKSPACE_ID")),c.base_url??(c.base_url=$r("ANTHROPIC_BASE_URL")),(e=c.authentication).scope??(e.scope=$r("ANTHROPIC_SCOPE")),c.authentication.type==="oidc_federation"){if(!c.authentication.identity_token){let p=$r("ANTHROPIC_IDENTITY_TOKEN_FILE");p&&(c.authentication.identity_token={source:"file",path:p})}c.authentication.federation_rule_id||(c.authentication.federation_rule_id=$r("ANTHROPIC_FEDERATION_RULE_ID")??""),(t=c.authentication).service_account_id??(t.service_account_id=$r("ANTHROPIC_SERVICE_ACCOUNT_ID"))}return{config:c,fromFile:!0}},b$e=async(r,e)=>{if(r?.authentication.credentials_path)return r.authentication.credentials_path;let t=await Lne();if(!t)return null;let n=e??await T$e();return n?(x$e(n),(await Promise.resolve().then(()=>(Rn(),uc))).join(t,"credentials",`${n}.json`)):null},Lne=async()=>{if(!Yyr())return null;let r=await Promise.resolve().then(()=>(Rn(),uc)),e=$r("ANTHROPIC_CONFIG_DIR");if(e)return e;if(_P()["X-Stainless-OS"]==="Windows"){let s=$r("APPDATA");if(s)return r.join(s,"Anthropic");let i=$r("USERPROFILE");return i?r.join(i,"AppData","Roaming","Anthropic"):null}let n=$r("XDG_CONFIG_HOME");if(n)return r.join(n,"anthropic");let o=$r("HOME");return o?r.join(o,".config","anthropic"):null},Yyr=()=>{let r=_P()["X-Stainless-Runtime"];return r==="node"||r==="deno"},T$e=async()=>{let r=await Lne();if(!r)return null;let e=$r("ANTHROPIC_PROFILE");if(e)return e;let t=await Promise.resolve().then(()=>($s(),jd)),o=(await Promise.resolve().then(()=>(Rn(),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 Une(r){if(!r)throw new Ye("Identity token file path is empty");return async()=>{let e=await Promise.resolve().then(()=>($s(),jd)),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 S$e(r){if(!r)throw new Ye("Identity token value is empty");return()=>r}var w$e=E(()=>{fo()});function _$e(r){return async()=>{vG(r.baseURL);let e=await r.identityTokenProvider();if(e.length>16*1024)throw new vn(`Identity token is ${Math.ceil(e.length/1024)} KiB, exceeds the 16 KiB assertion limit`);let t={grant_type:a$e,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}${xG}`,o;try{o=await r.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":`${Xv},${c$e}`,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${$u} oidcFederationProvider`},body:JSON.stringify(t)})}catch(l){throw new vn(`Failed to reach token endpoint ${n}: ${l}`)}let s=o.headers.get("Request-Id");if(!o.ok){let l=await o.text().catch(()=>""),c=xc(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 vn(`Token exchange failed with status ${o.status}${s?` (request-id ${s})`:""}: ${c}${u}`,o.status,c,s)}let i=await bG(o,s),a=Number(i.expires_in);if(!Number.isFinite(a))throw new vn(`Token endpoint response missing required fields: ${JSON.stringify(xc(i))}`,o.status,xc(i),s);return{token:i.access_token,expiresAt:Jd()+a}}}var E$e=E(()=>{Y_();CP();wP()});function C$e(r){return async e=>{let t=await Promise.resolve().then(()=>($s(),jd));await TG(r.credentialsPath,r.onSafetyWarning);let n;try{n=await t.promises.readFile(r.credentialsPath,"utf-8")}catch(x){throw new vn(`Credentials file not found at ${r.credentialsPath}: ${x}`)}let o;try{o=JSON.parse(n)}catch(x){throw new vn(`Credentials file at ${r.credentialsPath} is not valid JSON: ${x}`)}let s=o.access_token;if(!s)throw new vn(`Credentials file at ${r.credentialsPath} must include 'access_token'`);let i=o.expires_at;if(!e?.forceRefresh&&(i==null||Jd()<i-X_))return{token:s,expiresAt:i??null};let a=o.refresh_token;if(!r.clientId||!a)throw new vn(`Access token at ${r.credentialsPath} has expired and no refresh is available (client_id ${r.clientId?"set":"empty"}, refresh_token ${a?"set":"empty"})`);vG(r.baseURL);let l={grant_type:l$e,refresh_token:a,client_id:r.clientId},c=`${r.baseURL}${xG}`,u;try{u=await r.fetch(c,{method:"POST",headers:{"Content-Type":"application/json","anthropic-beta":Xv,"User-Agent":r.userAgent||`anthropic-sdk-typescript/${$u} userOAuthProvider`},body:JSON.stringify(l)})}catch(x){throw new vn(`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 vn(`User OAuth refresh failed (HTTP ${u.status}): ${xc(x)}`,u.status,xc(x),p)}let m=await bG(u,p),f=Number(m.expires_in);if(!Number.isFinite(f))throw new vn(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(xc(m))}`,u.status,xc(m),p);let h=Jd()+f,y=m.refresh_token||a;return await SG(r.credentialsPath,{...o,version:RG,type:"oauth_token",access_token:m.access_token,expires_at:h,refresh_token:y}),{token:m.access_token,expiresAt:h}}}var R$e=E(()=>{Dne();Y_();CP();wP()});function Fne(r,e){let t=r.authentication.credentials_path??null,n=(r.base_url||e.baseURL).replace(/\/+$/,""),o=Zyr(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 k$e(r,e){let t=await v$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 b$e(n,e)??void 0}};return Fne(s,r)}function Zyr(r,e,t,n){switch(r.authentication.type){case"oidc_federation":{let o=r.authentication,s=Qyr(o);if(!s)throw new vn("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 vn("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 vn("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");let i=_$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?exr(i,e,n.onCacheWriteError,n.onSafetyWarning):i}case"user_oauth":{if(!e)throw new vn("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");return C$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 vn(`authentication.type "${o}" is not a known authentication type`)}}}function Qyr(r){if(r.identity_token){let n=r.identity_token.source;if(n!=="file")throw new vn(`identity_token.source "${n}" is not supported by this SDK version (only "file")`);if(!r.identity_token.path)throw new vn('identity_token.source "file" requires a non-empty path');return Une(r.identity_token.path)}let e=$r("ANTHROPIC_IDENTITY_TOKEN_FILE");if(e)return Une(e);let t=$r("ANTHROPIC_IDENTITY_TOKEN");return t?S$e(t):null}function exr(r,e,t,n){return async o=>{let s=await Promise.resolve().then(()=>($s(),jd));await TG(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||Jd()<u-X_)return{token:c,expiresAt:u??null}}}catch(l){l?.code!=="ENOENT"&&!(l instanceof SyntaxError)&&t?.(l)}let a=await r(o);try{await SG(e,{...i??{},version:RG,type:"oauth_token",access_token:a.token,expires_at:a.expiresAt})}catch(l){t?.(l)}return a}}var A$e=E(()=>{RP();Dne();Y_();CP();w$e();E$e();R$e()});function txr(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 I$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 su,iu,Mg,$ne=E(()=>{yc();_G();Mg=class{constructor(){su.set(this,void 0),iu.set(this,void 0),Ge(this,su,new Uint8Array,"f"),Ge(this,iu,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Z_(e):e;Ge(this,su,f$e([K(this,su,"f"),t]),"f");let n=[],o;for(;(o=txr(K(this,su,"f"),K(this,iu,"f")))!=null;){if(o.carriage&&K(this,iu,"f")==null){Ge(this,iu,o.index,"f");continue}if(K(this,iu,"f")!=null&&(o.index!==K(this,iu,"f")+1||o.carriage)){n.push(Mne(K(this,su,"f").subarray(0,K(this,iu,"f")-1))),Ge(this,su,K(this,su,"f").subarray(K(this,iu,"f")),"f"),Ge(this,iu,null,"f");continue}let s=K(this,iu,"f")!==null?o.preceding-1:o.preceding,i=Mne(K(this,su,"f").subarray(0,s));n.push(i),Ge(this,su,K(this,su,"f").subarray(o.index),"f"),Ge(this,iu,null,"f")}return n}flush(){return K(this,su,"f").length?this.decode(`
1072
1072
  `):[]}};su=new WeakMap,iu=new WeakMap;Mg.NEWLINE_CHARS=new Set([`
1073
1073
  `,"\r"]);Mg.NEWLINE_REGEXP=/\r\n|[\n\r]/g});async function*rxr(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 Bne,n=new Mg,o=EP(r.body);for await(let s of nxr(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*nxr(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"?Z_(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=I$e(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}function oxr(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var AP,Bu,Bne,kG=E(()=>{yc();fo();J_();$ne();J_();Jv();am();_G();Pg();fo();Bu=class r{constructor(e,t,n){this.iterator=e,AP.set(this,void 0),this.controller=t,Ge(this,AP,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?mn(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 rxr(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=gG(l.data)??l.data,u=c?.error?.type;throw new zs(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(Kd(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 Mg,l=EP(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(Kd(l))return;throw l}finally{a||t.abort()}}return new r(i,t,n)}[(AP=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,AP,"f")),new r(()=>o(t),this.controller,K(this,AP,"f"))]}toReadableStream(){let e=this,t;return Sne({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=Z_(JSON.stringify(o)+`
@@ -1126,7 +1126,7 @@ ${t[0].text}`;let n=t.length-1;t[n].text=`${t[n].text}
1126
1126
  IMPORTANT: You MUST call the 'final_result' tool to return your response in the required structured format. Do not respond with plain text - always use the final_result tool.`});var $Be,Pq,zSr,BBe,jSr,GSr,zBe,jBe,qSr,GBe,Mse,qBe=E(()=>{"use strict";loe();gr();ro();_d();Qr();NE();eu();cs();hne();yse();gBe();so();_Be();Dt();ea();X();bse();$d();gi();Hr();_se();Dd();Xw();PBe();Ko();_l();yne();XB();Np();Pj();Ea();jj();Qm();DBe();dg();Ag();Kv();rG();kse();Bre();FBe();yse();$Be=()=>an(iye()),Pq=()=>ln("ANTHROPIC_MODEL","claude-sonnet-4-6"),zSr=pt.getTracer("neurolink.provider.anthropic"),BBe=()=>{try{let e=Fr(Op(),".neurolink","anthropic-credentials.json");if(to(e)){let t=Gc(e,"utf-8"),n=JSON.parse(t);if(n.type==="oauth"&&n.oauth?.accessToken)return g.debug("[AnthropicProvider] Using OAuth token from stored credentials file"),n.oauth}}catch(e){g.debug("[AnthropicProvider] Failed to read stored credentials:",e)}let r=process.env.ANTHROPIC_OAUTH_TOKEN||process.env.CLAUDE_OAUTH_TOKEN;if(!r)return null;try{let e=JSON.parse(r);if(typeof e=="object"&&e.accessToken)return e;if(typeof e=="string")return{accessToken:e}}catch{}return{accessToken:r}},jSr=r=>{let e=process.env.ANTHROPIC_SUBSCRIPTION_TIER?.toLowerCase();if(e){let t=["free","pro","max","max_5","max_20","api"];if(t.includes(e))return g.debug("[detectSubscriptionTier] Using environment override",{tier:e}),e;g.warn("[detectSubscriptionTier] Invalid ANTHROPIC_SUBSCRIPTION_TIER",{value:e,validTiers:t})}if(r){let t=r.scopes??[],n="pro";return t.includes("max_20")?n="max_20":t.includes("max_5")?n="max_5":t.includes("max")&&(n="max"),g.debug("[detectSubscriptionTier] Detected from OAuth token",{tier:n,scopes:t}),n}return g.debug("[detectSubscriptionTier] No OAuth token, defaulting to API tier"),"api"},GSr=r=>{let e=process.env.ANTHROPIC_AUTH_METHOD?.toLowerCase();if(e==="api_key"||e==="apikey")return g.debug("[detectAuthMethod] Forced to api_key by ANTHROPIC_AUTH_METHOD env var"),"api_key";if(e==="oauth"){if(r)return g.debug("[detectAuthMethod] Forced to oauth by ANTHROPIC_AUTH_METHOD env var"),"oauth";g.warn("[detectAuthMethod] ANTHROPIC_AUTH_METHOD=oauth but no OAuth token found; falling through to auto-detection")}else e&&g.warn("[detectAuthMethod] Unrecognized ANTHROPIC_AUTH_METHOD value; falling through to auto-detection",{value:e});let t=r?"oauth":"api_key";return g.debug("[detectAuthMethod] Auth method resolved",{method:t,hasOAuthToken:!!r}),t},zBe=r=>{let e=[],t=[],n=i=>Array.isArray(i)?i:[i],o=(i,a)=>{let l=om(a);if(l&&i.length>0){let c=i[i.length-1];c.cache_control=l}};for(let i of r)switch(i.role){case"system":{let a=typeof i.content=="string"?i.content:n(i.content).map(c=>typeof c=="string"?c:String(c?.text??"")).join(`
1127
1127
  `),l=om(i);e.push({type:"text",text:a,...l?{cache_control:l}:{}});break}case"user":{let a=[];for(let l of n(i.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}let c=l;if(c?.type==="text"&&typeof c.text=="string"){let u=om(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}else if(c?.type==="image"||c?.type==="image_url"){let u=pM(c.image??c.data??c.url);if(u){let p=om(c);a.push(p?{...u,cache_control:p}:u)}}else if(c?.type==="file"){let p=typeof c=="object"&&c!==null&&("mediaType"in c?typeof c.mediaType=="string":!0)?LBe(c):void 0;if(p){let m=om(c);m&&(p.cache_control=m),a.push(p)}}}a.length>0&&(o(a,i),t.push({role:"user",content:a}));break}case"assistant":{let a=[];for(let l of n(i.content)){if(typeof l=="string"){l.length>0&&a.push({type:"text",text:l});continue}let c=l;if(c?.type==="text"&&typeof c.text=="string"){if(c.text.length>0){let u=om(c);a.push({type:"text",text:c.text,...u?{cache_control:u}:{}})}}else if(c?.type==="tool-call"){let u=c.input;if(typeof u=="string")try{u=JSON.parse(u)}catch{u={}}a.push({type:"tool_use",id:c.toolCallId??"",name:c.toolName??"",input:u??{}})}}a.length>0&&(o(a,i),t.push({role:"assistant",content:a}));break}case"tool":{let a=[];if(Array.isArray(i.content))for(let l of i.content){let c=l;c?.type==="tool-result"&&a.push({type:"tool_result",tool_use_id:c.toolCallId??"",content:Ese(c.output)})}else typeof i.content=="string"&&a.push({type:"tool_result",tool_use_id:i.toolCallId??"",content:i.content});a.length>0&&t.push({role:"user",content:a});break}}let s=e.length===0?void 0:e.some(i=>i.cache_control)?e:e.map(i=>i.text).join(`
1128
1128
 
1129
- `);return{...s!==void 0?{system:s}:{},messages:t}},jBe=r=>{if(!(!r||r==="auto")){if(r==="none")return{type:"none"};if(r==="required")return{type:"any"};if(typeof r=="object"){let e=r;if(e.type==="tool"&&e.toolName)return{type:"tool",name:e.toolName}}}},qSr=r=>{switch(r){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},GBe=6e5,Mse=class extends oo{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,n,o){let s=!!(o?.apiKey&&!o?.oauthToken),i=s?null:(o?.oauthToken?{accessToken:o.oauthToken}:null)??n?.oauthToken??BBe(),a=s?"api_key":n?.authMethod??GSr(i),l=n?.subscriptionTier??(a==="oauth"?jSr(i):"api"),c=e||Pq(),u=c;!process.env.ANTHROPIC_BASE_URL&&l!=="api"&&!uM(c,l)&&(u=Sq(l),g.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:l,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=n?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=l,this.authMethod=a;let m=this.getAuthHeaders(),f;if(g.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){g.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");let h=this.oauthToken,y=mBe(()=>h.accessToken,this.enableBetaFeatures,!1,!0);f=new Xd({apiKey:"oauth-authenticated",fetch:vse(y),timeout:GBe,maxRetries:0}),g.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),g.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{let h=o?.apiKey??n?.apiKey??$Be(),y=(()=>{let x=process.env.ANTHROPIC_BASE_URL;if(!x)return;let b=x.replace(/\/+$/,""),T=b.replace(/\/v\d+$/,"");return T!==b&&g.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:Ir(x),rewrittenTo:Ir(T)}),T})();f=new Xd({apiKey:h,defaultHeaders:m,...y&&{baseURL:y},fetch:vse(yt()),timeout:GBe,maxRetries:0}),g.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=f,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},g.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?Iq["anthropic-beta"]:"disabled"})}getAuthHeaders(){let e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){let n=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",o=[...hb,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];n&&o.push("context-1m-2025-08-07"),e["anthropic-beta"]=o.join(",")}else e["anthropic-beta"]=Iq["anthropic-beta"];return t&&(e["User-Agent"]=Yd),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return g.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;let t=uM(e,this.subscriptionTier);return t||g.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return wq(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){g.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){g.debug("Token has no expiry information, assuming valid");return}let e=Date.now(),t=this.oauthToken.expiresAt<=e,n=this.oauthToken.expiresAt<=e+3e5;if(!t&&!n){g.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Mt("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);g.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}g.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});let o=this.oauthToken,s=o.refreshToken;this.refreshPromise=(async()=>{let a=new AbortController,l=setTimeout(()=>a.abort(),3e4),c=await fetch(ME,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Yd},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:s,client_id:bq}),signal:a.signal});if(clearTimeout(l),!c.ok){let m=await c.text();throw new Mt(`Failed to refresh OAuth token: ${c.status} ${m}`,this.providerName)}let u=await c.json();o.accessToken=u.access_token,o.refreshToken=u.refresh_token||o.refreshToken,o.expiresAt=u.expires_in?Date.now()+u.expires_in*1e3:void 0,o.tokenType=u.token_type||"Bearer";let p=o;try{let m=Fr(Op(),".neurolink");to(m)||lA(m,{recursive:!0});let f=Fr(m,"anthropic-credentials.json"),h=`${f}.tmp`,x={...to(f)?JSON.parse(Gc(f,"utf-8")):{},type:"oauth",oauth:p,updatedAt:Date.now()};aA(h,JSON.stringify(x,null,2),{mode:384}),iX(h,f),g.debug("Refreshed OAuth credentials persisted to disk")}catch(m){g.warn("Failed to persist refreshed OAuth token to disk",{error:m instanceof Error?m.message:String(m)})}g.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!u.refresh_token,expiresIn:u.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof Mt?i:new Mt(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,n){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),n&&(n.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=n.inputTokens,this.usageInfo.tokensUsed+=n.inputTokens),n.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=n.outputTokens,this.usageInfo.tokensUsed+=n.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&g.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&g.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return Pq()}getAISDKModel(){let e=this.client,t=this.providerName,n=this.modelName||Pq(),o=a=>this.getTimeout(a??{}),s=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:n,supportedUrls:{},doGenerate:async a=>{await s();let l=zBe(a.prompt),c=l.messages,u=l.system,p=(a.tools??[]).filter(F=>F.type==="function").map(F=>{let B=om(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...B?{cache_control:B}:{}}});p&&p.length===0&&(p=void 0);let m=a.toolChoice?jBe(a.toolChoice.type==="tool"?{type:"tool",toolName:a.toolChoice.toolName}:a.toolChoice.type):void 0,f;if(a.responseFormat?.type==="json"){f=a.responseFormat.name??"json";let F=a.responseFormat.schema??{type:"object"};p=[{name:f,description:a.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:F}],m={type:"tool",name:f}}let h=a.providerOptions?.anthropic?.finalResultSchema,y=!1;if(!f&&h){let F=Ise(p,h);p=F.tools,y=F.applied,F.applied&&(u=Pse(u))}let x=a.providerOptions?.anthropic?.thinking,b=Sse({system:u,tools:p,messages:c}),T=wse(c,Aq-b),w=_a("anthropic",n,{...a.temperature!==void 0&&a.temperature!==null?{temperature:a.temperature}:{},...a.topP!==void 0&&a.topP!==null?{topP:a.topP}:{}},"anthropic.doGenerate"),C={model:n,messages:T,max_tokens:A_(n,a.maxOutputTokens),...u?{system:u}:{},...w.temperature!==void 0?{temperature:w.temperature}:{},...w.topP!==void 0?{top_p:w.topP}:{},...a.stopSequences&&a.stopSequences.length>0?{stop_sequences:a.stopSequences}:{},...p?{tools:p}:{},...m?{tool_choice:m}:{},...x?{thinking:x}:{}},R=a.timeout,k=R!=null,P=C.max_tokens>8192&&!k?Math.max(o(a),3e5):o(a),I=Ws(P,t,"generate"),A;try{A=await e.messages.create(C,{signal:Ux(a.abortSignal,I?.controller.signal)})}finally{I?.cleanup()}let M=[],U,$=[],L=!1;for(let F of A.content)F.type==="thinking"?M.push({type:"reasoning",text:F.thinking}):F.type==="text"?f?$.push(F.text):M.push({type:"text",text:F.text}):F.type==="tool_use"&&(f&&F.name===f?(L=!0,M.push({type:"text",text:xP(F.input)})):y&&F.name===mM?U=xP(F.input):M.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:xP(F.input)}));if(f&&!L&&$.length>0&&M.push({type:"text",text:$.join("")}),U!==void 0){let F=M.filter(B=>B.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:U}),g.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}let z=A.usage.cache_read_input_tokens??0,j=A.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:U!==void 0?"stop":qSr(A.stop_reason),raw:A.stop_reason??"stop"},usage:{inputTokens:{total:A.usage.input_tokens+z+j,noCache:A.usage.input_tokens,cacheRead:z,cacheWrite:j},outputTokens:{total:A.usage.output_tokens,text:A.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:C},response:{id:A.id,modelId:A.model,headers:bBe()??{},body:A}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return en(e,[{match:n=>n.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(n.message),errorClass:Mt,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:n=>n.statusCode===429||/rate limit|too_many_requests|429/i.test(n.message),errorClass:qr,message:"Anthropic rate limit exceeded. Please try again later."},{match:n=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(n.message),errorClass:cn,message:n=>`Connection error: ${n.message}`},{match:n=>/500|502|503|504|server error/i.test(n.message),errorClass:mt,message:n=>`Server error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`Anthropic error: ${n.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();let{result:n,snapshot:o}=await xBe(()=>super.generate(e,t));return n&&o&&(this.recordLimitSnapshot(o),n.limits=o,n.analytics&&(n.analytics.limits=o)),n}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),SBe(e),wBe(e,this.modelName)}async executeStream(e,t){return TBe(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);let n=this.getTimeout(e),o=Ws(n,this.providerName,"stream"),s=new AbortController,i=f1([e.abortSignal,o?.controller.signal,s.signal]).signal,a,l,c,u,p=!1;try{u=!e.disableTools&&this.supportsTools(),a=u?e.tools||await this.getAllTools():{},l=u?Rg(a,"input_schema"):void 0;let oe=await this.buildMessagesForStream(e);if(c=zBe(oe),e.schema&&l&&l.length>0){let Z=Ise(l,xn(e.schema));l=Z.tools,p=Z.applied,Z.applied&&(c.system=Pse(c.system))}}catch(oe){throw o?.cleanup(),this.handleProviderError(oe)}let m=this.modelName||Pq(),f=u&&l&&l.length>0?jBe(dG(e,a,u)):void 0,h=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=zSr.startSpan("neurolink.provider.streamText",{kind:br.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":m}}),x=e.maxSteps||Jo,b=this.neurolink?.getEventEmitter(),T=Fu(),{push:w}=T,{usagePromise:C,finishPromise:R,resolveUsage:k,resolveFinish:P}=lG();C.then(oe=>{y.setAttribute("gen_ai.usage.input_tokens",oe.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",oe.completionTokens||0),oe.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",oe.cacheReadTokens);let Z=Us(this.providerName,this.modelName,{input:oe.promptTokens||0,output:oe.completionTokens||0,total:oe.totalTokens||0,...oe.cacheReadTokens?{cacheReadTokens:oe.cacheReadTokens}:{},...oe.cacheCreationTokens?{cacheCreationTokens:oe.cacheCreationTokens}:{}});Z&&Z>0&&y.setAttribute("neurolink.cost",Z)}).catch(()=>{}),R.then(oe=>{y.setAttribute("gen_ai.response.finish_reason",oe||"unknown"),y.end()}).catch(()=>{y.end()});let I,A=this.client,M=[],U=Date.now(),$=0,L=0,z=0,j=0,F=null,B=()=>({promptTokens:$,completionTokens:L,totalTokens:$+z+j+L,...z>0?{cacheReadTokens:z}:{},...j>0?{cacheCreationTokens:j}:{}}),O="",W,re=(oe,Z)=>{let we=ve=>{if(typeof ve=="string")return ve;try{return JSON.stringify(ve)??""}catch{return""}};return zt(we(oe),"anthropic")+zt(we(Z),"anthropic")},pe=(async()=>{let oe=c.messages.slice(),Z,we;for(let ve=0;ve<x;ve++){if(l){let ce=new Set(l.map(_=>_.name)),Ne=Object.fromEntries(Object.entries(a).filter(([_])=>!ce.has(_)));Object.keys(Ne).length>0&&(l.push(...Rg(Ne,"input_schema")??[]),g.info(`[Anthropic] ${Object.keys(Ne).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(Ne).join(", ")}`))}let ae=Rq({conversation:oe,availableInputTokens:mi("anthropic",m,e.maxTokens??void 0),fixedOverheadTokens:re(c.system,l),provider:"anthropic",observedPromptTokens:Z,previousSentEstimate:we,onSentEstimate:ce=>{we=ce}});if(ae){let ce=new Set(ae.drop),Ne=new Set(ae.truncate),_=[];for(let G=0;G<oe.length;G++){if(ce.has(G))continue;let Q=oe[G];if(Ne.has(G)&&Array.isArray(Q.content)){_.push({...Q,content:Q.content.map(q=>q.type==="tool_result"?{...q,content:Cq(typeof q.content=="string"?q.content:JSON.stringify(q.content)??"")}:q)});continue}_.push(Q)}if(ce.size>0){let G=_.findIndex(Q=>Array.isArray(Q.content)&&Q.content.some(q=>q.type==="tool_use"||q.type==="tool_result"));G<0&&(G=Math.min(1,_.length)),_.splice(G,0,{role:"user",content:[{type:"text",text:Eq}]})}oe.length=0,oe.push(..._)}let H=Sse({system:c.system,tools:l,messages:oe}),V=wse(oe,Aq-H),ne=_a("anthropic",m,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream"),N={model:m,messages:V,max_tokens:A_(m,e.maxTokens),stream:!0,...c.system?{system:c.system}:{},...ne.temperature!==void 0?{temperature:ne.temperature}:{},...l&&l.length>0?{tools:l}:{},...f?{tool_choice:f}:{},...h?{thinking:h}:{}},Y=await Ru(()=>A.messages.create(N,{signal:i??void 0}),pt.getActiveSpan()??void 0,`${this.providerName} stream`),ee=new Map,ie=new Map,le=new Map,ye=new Map,Fe=null,Ee=0;for await(let ce of Y)if(ce.type==="message_start"){$+=ce.message.usage.input_tokens??0;let Ne=ce.message.usage.output_tokens??0;L+=Ne-Ee,Ee=Ne,z+=ce.message.usage.cache_read_input_tokens??0,j+=ce.message.usage.cache_creation_input_tokens??0,Z=(ce.message.usage.input_tokens??0)+(ce.message.usage.cache_read_input_tokens??0)+(ce.message.usage.cache_creation_input_tokens??0)}else if(ce.type==="content_block_start")ee.set(ce.index,ce.content_block.type),ce.content_block.type==="tool_use"&&ye.set(ce.index,{id:ce.content_block.id,name:ce.content_block.name,inputJson:""});else if(ce.type==="content_block_delta"){let Ne=ce.delta;if(Ne.type==="text_delta")ie.set(ce.index,(ie.get(ce.index)??"")+Ne.text),p?O+=Ne.text:w({content:Ne.text});else if(Ne.type==="thinking_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.text+=Ne.thinking,le.set(ce.index,_),w({content:"",reasoning:Ne.thinking})}else if(Ne.type==="signature_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.signature+=Ne.signature,le.set(ce.index,_)}else if(Ne.type==="input_json_delta"){let _=ye.get(ce.index);_&&(_.inputJson+=Ne.partial_json)}}else if(ce.type==="message_delta"){Fe=ce.delta.stop_reason??Fe;let Ne=ce.usage?.output_tokens??Ee;L+=Ne-Ee,Ee=Ne}if(F=Fe,p){let ce=[...ye.values()].find(Ne=>Ne.name===mM);if(ce){W=UBe(ce.inputJson),F="end_turn",g.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:W.length});break}}if(Fe!=="tool_use"||ye.size===0)break;let Rt=[],Xe=[...ee.keys()].sort((ce,Ne)=>ce-Ne);for(let ce of Xe){let Ne=ee.get(ce);if(Ne==="thinking"){let _=le.get(ce);_&&_.text.length>0&&Rt.push({type:"thinking",thinking:_.text,signature:_.signature})}else if(Ne==="text"){let _=ie.get(ce);_&&_.length>0&&Rt.push({type:"text",text:_})}else if(Ne==="tool_use"){let _=ye.get(ce);if(_){let G;try{G=_.inputJson?JSON.parse(_.inputJson):{}}catch{G={}}Rt.push({type:"tool_use",id:_.id,name:_.name,input:G})}}}oe.push({role:"assistant",content:Rt});let ue=[],qe=[],Be=[];for(let ce of ye.values()){let Ne;try{Ne=ce.inputJson?JSON.parse(ce.inputJson):{}}catch{Ne={}}qe.push({type:"tool-call",toolCallId:ce.id,toolName:ce.name,args:Ne}),M.push(ce.name);let _=a[ce.name]??pI(a,ce.name);try{if(!_?.execute)throw new Error(`Tool not found: ${ce.name}`);let G=await _.execute(Ne,{toolCallId:ce.id,messages:[]});Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,result:G}),ue.push({type:"tool_result",tool_use_id:ce.id,content:Ese(G)})}catch(G){let Q=G instanceof Error?G.message:String(G);Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,error:Q}),ue.push({type:"tool_result",tool_use_id:ce.id,content:`Error: ${Q}`,is_error:!0})}}Yw(b,Be.map(ce=>({toolName:ce.toolName,result:ce.result,error:ce.error}))),this.handleToolExecutionStorage(qe,Be,e,new Date).catch(ce=>{g.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ce instanceof Error?ce.message:String(ce)})}),oe.push({role:"user",content:ue})}k(B()),P(F??"stop")})().catch(oe=>{throw I=oe,g.error("Anthropic: Stream error",{error:oe instanceof Error?oe.message:String(oe)}),k(B()),P("error"),this.formatProviderError(oe)}).finally(()=>{if(p){let oe=W??O;oe.length>0&&w({content:oe})}o?.cleanup(),T.close()});pe.catch(()=>{});let Ae=this.providerName;return{stream:async function*(){let oe=0;try{for await(let Z of T.iterable)"content"in Z&&typeof Z.content=="string"&&Z.content.length>0&&oe++,yield Z;if(await pe,oe===0&&M.length===0){g.warn(`${Ae}: Stream produced no output \u2014 emitting enriched sentinel`);let Z=new Ta({message:"Stream produced no output"}),we=await Zp(Z,void 0,I);Qp(we),yield we}}catch(Z){let we=await Zp(Z,void 0,I);if(Qp(we),yield we,!Ta.isInstance(Z))throw Z}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],analytics:R.then(async()=>{let oe=await uG.createAnalytics(this.providerName,m,{textStream:(async function*(){})(),usage:C,finishReason:R},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Z=vBe();return Z&&oe&&(this.recordLimitSnapshot(Z),oe.limits=Z),oe})}}async isAvailable(){try{return BBe()||$Be(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}});var VBe={};de(VBe,{ANTHROPIC_BETA_HEADERS:()=>Iq,AnthropicProvider:()=>Mse,ModelAccessError:()=>jR,getModelCapabilities:()=>wq,getRecommendedModelForTier:()=>Sq,isModelAvailableForTier:()=>uM});var HBe=E(()=>{"use strict";qBe();kse()});var KBe={};de(KBe,{Agent:()=>kwr,BedrockClient:()=>HSr,BedrockRuntimeClient:()=>Ose,Blob:()=>Rwr,Client:()=>Iwr,ConverseCommand:()=>Nse,ConverseStreamCommand:()=>Lse,Cron:()=>cwr,Dispatcher:()=>Pwr,File:()=>Cwr,FlowProducer:()=>lwr,FormData:()=>Ewr,GoogleAuth:()=>YSr,HTTPException:()=>hwr,Headers:()=>_wr,Hippocampus:()=>twr,HippocampusConfig:()=>rwr,Hono:()=>gwr,ImageFormat:()=>DE,InvokeEndpointCommand:()=>JSr,InvokeEndpointWithResponseStreamCommand:()=>XSr,Job:()=>iwr,ListFoundationModelsCommand:()=>KSr,MockAgent:()=>Nwr,Pool:()=>Awr,Queue:()=>owr,QueueScheduler:()=>awr,Request:()=>Swr,Response:()=>wwr,SageMakerRuntimeClient:()=>WSr,TextToSpeechClient:()=>QSr,VertexAI:()=>ZSr,Webhook:()=>ewr,Worker:()=>swr,convertToHtml:()=>mwr,cors:()=>fwr,createClient:()=>nwr,default:()=>VSr,extractRawText:()=>pwr,fetch:()=>Twr,getGlobalDispatcher:()=>Owr,interceptors:()=>Lwr,logger:()=>ywr,parseBuffer:()=>uwr,request:()=>Dwr,secureHeaders:()=>xwr,selectCover:()=>dwr,setGlobalDispatcher:()=>Mwr,streamSSE:()=>vwr,timeout:()=>bwr});var LE,Mi,VSr,HSr,KSr,Ose,Nse,Lse,DE,WSr,JSr,XSr,YSr,ZSr,QSr,ewr,twr,rwr,nwr,owr,swr,iwr,awr,lwr,cwr,uwr,dwr,pwr,mwr,gwr,fwr,hwr,ywr,xwr,vwr,bwr,Twr,Swr,wwr,_wr,Ewr,Cwr,Rwr,kwr,Awr,Iwr,Pwr,Mwr,Owr,Nwr,Lwr,Dwr,Mq=E(()=>{LE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:LE.get}):new Proxy(function(...t){return new Proxy({},{get:LE.get})},{get:LE.get,apply(t,n,o){return new Proxy({},{get:LE.get})},construct(t,n){return new Proxy({},{get:LE.get})}})}},Mi=new Proxy({},LE),VSr=Mi,{BedrockClient:HSr,ListFoundationModelsCommand:KSr,BedrockRuntimeClient:Ose,ConverseCommand:Nse,ConverseStreamCommand:Lse,ImageFormat:DE}=Mi,{SageMakerRuntimeClient:WSr,InvokeEndpointCommand:JSr,InvokeEndpointWithResponseStreamCommand:XSr}=Mi,{GoogleAuth:YSr,VertexAI:ZSr,TextToSpeechClient:QSr}=Mi,{Webhook:ewr}=Mi,{Hippocampus:twr,HippocampusConfig:rwr}=Mi,{createClient:nwr}=Mi,{Queue:owr,Worker:swr,Job:iwr,QueueScheduler:awr,FlowProducer:lwr}=Mi,{Cron:cwr}=Mi,{parseBuffer:uwr,selectCover:dwr}=Mi,{extractRawText:pwr,convertToHtml:mwr}=Mi,{Hono:gwr}=Mi,{cors:fwr,HTTPException:hwr,logger:ywr,secureHeaders:xwr,streamSSE:vwr,timeout:bwr}=Mi,Twr=globalThis.fetch,Swr=globalThis.Request,wwr=globalThis.Response,_wr=globalThis.Headers,Ewr=globalThis.FormData,Cwr=globalThis.File,Rwr=globalThis.Blob,kwr=Mi.Agent,Awr=Mi.Pool,Iwr=Mi.Client,Pwr=Mi.Dispatcher,Mwr=()=>{},Owr=()=>Mi,Nwr=Mi.MockAgent,Lwr={redirect:()=>r=>r,retry:()=>r=>r},Dwr=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});function Uwr(r,e){return{inputTokens:r.inputTokens+e.inputTokens,outputTokens:r.outputTokens+e.outputTokens,cacheReadTokens:(r.cacheReadTokens??0)+(e.cacheReadTokens??0)||void 0,cacheWriteTokens:(r.cacheWriteTokens??0)+(e.cacheWriteTokens??0)||void 0,reasoningTokens:(r.reasoningTokens??0)+(e.reasoningTokens??0)||void 0}}function Dse(r,e,t){let n=Fu(),o=new AbortController,s=()=>o.abort();t.abortSignal?.addEventListener("abort",s),t.abortSignal?.aborted&&o.abort();let i=new Map,a=!1,l=(async()=>{let c=e,u={inputTokens:0,outputTokens:0},p="",m="",f,h=[],y=[],x=!1;try{for(let T=0;T<r.maxSteps&&!o.signal.aborted;T++){if(r.planReclaim){let I=r.planReclaim(c,T);I&&(c=I.conversation)}let w=r.buildStepRequest(c,T),C=!1,R={push:I=>{C=!0,n.push(I)}},k;try{k=await Ru(async()=>{C=!1;try{return await r.executeStep(w,R,o.signal)}catch(I){throw C?new Oq(I):I}},void 0,`${r.providerLabel}.step`)}catch(I){throw I instanceof Oq?I.cause:I}if(u=Uwr(u,k.usage),f=k.rawStopReason,m=k.text||m,r.isMalformedStep?.(k)&&!a&&!o.signal.aborted){a=!0,g.warn(`[${r.providerLabel}] Malformed function call at step ${T+1}/${r.maxSteps}; retrying once.`),c=r.buildMalformedRetryNote?.(c)??c;continue}if(k.toolCalls.length===0){p=k.text||p;break}T===r.maxSteps-1&&(x=!0);let P=[];for(let I of k.toolCalls){h.push(I);let A=r.toolFailureBreaker,M=A?i.get(I.name):void 0;if(A&&M&&M.count>=A.maxRetries){let L={error:`TOOL_PERMANENTLY_FAILED: "${I.name}" has failed ${M.count} times. Last error: ${M.lastError}.`,status:"permanently_failed",do_not_retry:!0};P.push({...I,output:L,error:L.error,permanentlyFailed:!0}),y.push({name:I.name,input:I.args,output:L});continue}let U=t.tools?.[I.name],$=U?.execute?U:r.resolveToolOnMiss?.(I.name)??U;if(!$?.execute){let L=A?{error:`TOOL_NOT_FOUND: "${I.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${I.name}`};P.push({...I,output:L,error:L.error,permanentlyFailed:!!A}),y.push({name:I.name,input:I.args,output:L});continue}try{let L=await $.execute(I.args,{toolCallId:I.id,abortSignal:o.signal});P.push({...I,output:L}),y.push({name:I.name,input:I.args,output:L})}catch(L){let z=L instanceof Error?L.message:String(L);if(A){let F=i.get(I.name)??{count:0,lastError:""};F.count++,F.lastError=z,i.set(I.name,F)}let j={error:z,status:"failed"};P.push({...I,output:j,error:z}),y.push({name:I.name,input:I.args,output:j})}}c=r.buildToolResultMessages(c,k,P)}let b=r.mapFinishReason(f,x);return{text:p||(x?m:""),toolCalls:h,toolExecutions:y,usage:u,finishReason:b,rawStopReason:f,conversation:c}}catch(b){throw n.error(b),b}finally{n.close(),t.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:l}}var Oq,WBe=E(()=>{"use strict";Kv();X();Qm();Oq=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t));this.cause=t}cause}});function $wr(r){if(/^(us|ca)-/.test(r))return"us";if(/^(eu|il|me|af)-/.test(r))return"eu";if(/^ap-northeast-[13]$/.test(r))return"jp";if(/^ap-southeast-[246]$/.test(r))return"au";if(/^ap-/.test(r))return"apac"}function Bwr(r){return/^(us|eu|au|jp|apac|global)\./.test(r)}function JBe(r){if(typeof r!="object"||r===null)return!1;let e=r,t=typeof e.name=="string"?e.name:"",n=typeof e.message=="string"?e.message:"";return!/ValidationException/i.test(t)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function zwr(r,e){if(r.startsWith("arn:")||Bwr(r))return[];let t=[],n=$wr(e);return n&&t.push(`${n}.${r}`),t.push(`${Fwr}.${r}`),t}function YBe(r,e){return`${r}::${e}`}function jwr(r,e){return XBe.get(YBe(e,r))}function Gwr(r,e,t){XBe.set(YBe(e,r),t),g.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:e})}async function Use(r,e,t){let n=jwr(r,e);if(n&&n!==r)return t(n);try{return await t(r)}catch(o){if(!JBe(o))throw o;let s=zwr(r,e);if(s.length===0)throw o;g.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:e,candidates:s.length});for(let i of s)try{let a=await t(i);return Gwr(r,e,i),a}catch(a){if(!JBe(a))throw a}throw o}}var Fwr,XBe,ZBe=E(()=>{"use strict";X();Fwr="global";XBe=new Map});function Nq(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function eze(r,e){if(r){if(r.toolUse&&r._inputBuffer){try{r.toolUse.input=JSON.parse(r._inputBuffer)}catch{r.toolUse.input={}}delete r._inputBuffer}e&&!r.toolUse&&(r.text=e)}}function tze(r){return r.filter(e=>e.toolUse).map(e=>({id:e.toolUse?.toolUseId??Nq(),name:e.toolUse?.name??"",args:e.toolUse?.input??{}}))}async function qwr(r,e,t){let n=[],o=new Map,s=new Map,i=h=>{let y=o.get(h);return y||(y={},o.set(h,y),n.push(y)),y},a="",l,c=0,u=0,p=0,m=0;if(r.stream)for await(let h of r.stream){if(t.aborted)break;let y=h;if(y.contentBlockStart&&i(y.contentBlockStart.contentBlockIndex??0),y.contentBlockDelta?.delta?.text){let x=y.contentBlockDelta.contentBlockIndex??0,b=y.contentBlockDelta.delta.text;i(x),a+=b,s.set(x,(s.get(x)??"")+b),e.push({content:b})}if(y.contentBlockStart?.start?.toolUse){let x=i(y.contentBlockStart.contentBlockIndex??0);x.toolUse={name:y.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:y.contentBlockStart.start.toolUse.toolUseId??Nq()}}if(y.contentBlockDelta?.delta?.toolUse){let x=i(y.contentBlockDelta.contentBlockIndex??0);x.toolUse??={name:"",input:{},toolUseId:Nq()};let b=y.contentBlockDelta.delta.toolUse.input;typeof b=="string"?x._inputBuffer=(x._inputBuffer??"")+b:typeof b=="object"&&b!==null&&!Array.isArray(b)&&(x.toolUse.input={...x.toolUse.input??{},...b})}if(y.contentBlockStop){let x=y.contentBlockStop.contentBlockIndex??0;eze(o.get(x),s.get(x)??"")}if(y.messageStop){l=y.messageStop.stopReason??"end_turn";continue}if(y.metadata?.usage){c+=y.metadata.usage.inputTokens??0,u+=y.metadata.usage.outputTokens??0,p+=y.metadata.usage.cacheReadInputTokens??0,m+=y.metadata.usage.cacheWriteInputTokens??0;break}}for(let[h,y]of o)eze(y,s.get(h)??"");let f=n.filter(h=>h.text||h.toolUse||h.image||h.document);return{text:a,toolCalls:tze(f),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:p,cacheWriteTokens:m},rawStopReason:l,raw:f}}function Vwr(r){let e=[],t="";for(let n of r.output?.message?.content??[]){let o={};"text"in n&&n.text&&(o.text=n.text,t+=t?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??Nq(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),e.push(o)}return{text:t,toolCalls:tze(e),usage:{inputTokens:r.usage?.inputTokens??0,outputTokens:r.usage?.outputTokens??0,cacheReadTokens:r.usage?.cacheReadInputTokens??0,cacheWriteTokens:r.usage?.cacheWriteInputTokens??0},rawStopReason:r.stopReason,raw:e}}function Fse(r){return{providerLabel:"bedrock",maxSteps:r.maxSteps,buildStepRequest(e,t){return{raw:r.buildCommandInput(e,t)}},async executeStep(e,t,n){let o=e.raw;if(!r.streaming){let i=await Use(o.modelId??"",r.region,a=>je(r.client.send(new Nse({...o,modelId:a})),QBe,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return Vwr(i)}let s=await Use(o.modelId??"",r.region,i=>je(r.client.send(new Lse({...o,modelId:i})),QBe,new Error("Bedrock streaming API call timed out")));return qwr(s,t,n)},buildToolResultMessages(e,t,n){let o={role:"assistant",content:t.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...e,o,s]},mapFinishReason(e,t){switch(e){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return t?"tool-calls":"stop"}}}}var QBe,rze=E(()=>{"use strict";Mq();Tt();ZBe();QBe=12e4});function $se(r,e,t){return{input:{text:r.input?.text||"",images:r.input?.images,content:r.input?.content,files:r.input?.files,csvFiles:r.input?.csvFiles,pdfFiles:r.input?.pdfFiles,audioFiles:r.input?.audioFiles,videoFiles:r.input?.videoFiles},csvOptions:r.csvOptions,pdfOptions:r.pdfOptions,systemPrompt:r.systemPrompt,conversationHistory:r.conversationMessages,provider:e,model:t,temperature:r.temperature,maxTokens:r.maxTokens,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,context:r.context,fileRegistry:r.fileRegistry}}var nze=E(()=>{"use strict"});var Lq,Bse=E(()=>{"use strict";ac();Lq=Oe.provider});var oze={};de(oze,{Agent:()=>O_r,BedrockClient:()=>Kwr,BedrockRuntimeClient:()=>Jwr,Blob:()=>M_r,Client:()=>L_r,ConverseCommand:()=>Xwr,ConverseStreamCommand:()=>Ywr,Cron:()=>g_r,Dispatcher:()=>D_r,File:()=>P_r,FlowProducer:()=>m_r,FormData:()=>I_r,GoogleAuth:()=>r_r,HTTPException:()=>T_r,Headers:()=>A_r,Hippocampus:()=>i_r,HippocampusConfig:()=>a_r,Hono:()=>v_r,ImageFormat:()=>Zwr,InvokeEndpointCommand:()=>e_r,InvokeEndpointWithResponseStreamCommand:()=>t_r,Job:()=>d_r,ListFoundationModelsCommand:()=>Wwr,MockAgent:()=>$_r,Pool:()=>N_r,Queue:()=>c_r,QueueScheduler:()=>p_r,Request:()=>R_r,Response:()=>k_r,SageMakerRuntimeClient:()=>Qwr,TextToSpeechClient:()=>o_r,VertexAI:()=>n_r,Webhook:()=>s_r,Worker:()=>u_r,convertToHtml:()=>x_r,cors:()=>b_r,createClient:()=>l_r,default:()=>Hwr,extractRawText:()=>y_r,fetch:()=>C_r,getGlobalDispatcher:()=>F_r,interceptors:()=>B_r,logger:()=>S_r,parseBuffer:()=>f_r,request:()=>z_r,secureHeaders:()=>w_r,selectCover:()=>h_r,setGlobalDispatcher:()=>U_r,streamSSE:()=>__r,timeout:()=>E_r});var UE,Oi,Hwr,Kwr,Wwr,Jwr,Xwr,Ywr,Zwr,Qwr,e_r,t_r,r_r,n_r,o_r,s_r,i_r,a_r,l_r,c_r,u_r,d_r,p_r,m_r,g_r,f_r,h_r,y_r,x_r,v_r,b_r,T_r,S_r,w_r,__r,E_r,C_r,R_r,k_r,A_r,I_r,P_r,M_r,O_r,N_r,L_r,D_r,U_r,F_r,$_r,B_r,z_r,sze=E(()=>{UE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:UE.get}):new Proxy(function(...t){return new Proxy({},{get:UE.get})},{get:UE.get,apply(t,n,o){return new Proxy({},{get:UE.get})},construct(t,n){return new Proxy({},{get:UE.get})}})}},Oi=new Proxy({},UE),Hwr=Oi,{BedrockClient:Kwr,ListFoundationModelsCommand:Wwr,BedrockRuntimeClient:Jwr,ConverseCommand:Xwr,ConverseStreamCommand:Ywr,ImageFormat:Zwr}=Oi,{SageMakerRuntimeClient:Qwr,InvokeEndpointCommand:e_r,InvokeEndpointWithResponseStreamCommand:t_r}=Oi,{GoogleAuth:r_r,VertexAI:n_r,TextToSpeechClient:o_r}=Oi,{Webhook:s_r}=Oi,{Hippocampus:i_r,HippocampusConfig:a_r}=Oi,{createClient:l_r}=Oi,{Queue:c_r,Worker:u_r,Job:d_r,QueueScheduler:p_r,FlowProducer:m_r}=Oi,{Cron:g_r}=Oi,{parseBuffer:f_r,selectCover:h_r}=Oi,{extractRawText:y_r,convertToHtml:x_r}=Oi,{Hono:v_r}=Oi,{cors:b_r,HTTPException:T_r,logger:S_r,secureHeaders:w_r,streamSSE:__r,timeout:E_r}=Oi,C_r=globalThis.fetch,R_r=globalThis.Request,k_r=globalThis.Response,A_r=globalThis.Headers,I_r=globalThis.FormData,P_r=globalThis.File,M_r=globalThis.Blob,O_r=Oi.Agent,N_r=Oi.Pool,L_r=Oi.Client,D_r=Oi.Dispatcher,U_r=()=>{},F_r=()=>Oi,$_r=Oi.MockAgent,B_r={redirect:()=>r=>r,retry:()=>r=>r},z_r=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});async function Dq(){return await Promise.resolve().then(()=>(sze(),oze))}var zse=E(()=>{"use strict"});var jse,ize=E(()=>{"use strict";Mq();Qr();qw();eu();cs();WBe();rze();Dt();ea();Tt();X();dg();qI();nze();Ea();gr();Bse();zse();jse=class r extends oo{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(e){return e?e.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(e,t,n,o){super(e,"bedrock",t);let s=e||process.env.BEDROCK_MODEL||this.modelName,i=r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",g.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),g.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{g.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new Ose({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),g.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw g.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){let{BedrockClient:e,ListFoundationModelsCommand:t}=await Dq(),n=new e({region:this.region});try{g.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");let o=new t({}),s=Date.now();await n.send(o);let i=Date.now()-s;g.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){let s=o instanceof Error?o.message:String(o);g.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(e){g.debug("[AmazonBedrockProvider] generate() called with conversation management");let t=Date.now(),n=typeof e=="string"?{prompt:e}:e;this.conversationHistory=[];let o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});let m=$se(n,this.providerName,this.modelName),f=await T_(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{g.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");let p={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(p)}g.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,l,c;try{({text:i,usage:a,finishReason:l,rawFinishReason:c}=await this.conversationLoop(n))}catch(p){let m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:p instanceof Error?p.message:String(p)}),p}let u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:l},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...l!==void 0&&{finishReason:l},...c!==void 0&&{rawFinishReason:c}}}async conversationLoop(e){let t=e.maxSteps||Jo,n=await this.resolveTurnTools(e.tools,e.disableTools),o=this.formatToolsForBedrock(n),s=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converse"),i=Fse({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:t,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{let{resultPromise:a}=Dse(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:e.abortSignal}),l=await a;this.conversationHistory=l.conversation;let c=l.usage.inputTokens,u=l.usage.outputTokens,p=l.usage.cacheReadTokens??0,m=l.usage.cacheWriteTokens??0;return{text:l.text||"",usage:{input:c,output:u,total:c+p+m+u,...p>0&&{cacheReadTokens:p},...m>0&&{cacheCreationTokens:m}},finishReason:l.finishReason,rawFinishReason:l.rawStopReason}}catch(a){throw g.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(e){return e.map(t=>({role:t.role,content:t.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(e,t,n,o){return Lq.startActiveSpan("bedrock.tool.execute",{kind:br.CLIENT,attributes:{"gen_ai.tool.name":t,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(g.debug(`[AmazonBedrockProvider] Executing single tool: ${t}`,{args:n}),!e[t])throw new Error(`Tool not found: ${t}`);let i=e[t];if(!i||!i.execute)throw new Error(`Tool ${t} does not have execute method`);let a=n||{};t==="list_directory"&&!a.path&&(a.path=".",g.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),g.debug("[AmazonBedrockProvider] Tool input parameters:",a);let l={};for(let[p,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(l[p]=m);let c=await i.execute(l);g.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:t,result:c});let u;if(c&&typeof c=="object"&&"success"in c)if(c.success&&c.data!==void 0)typeof c.data=="string"?u=c.data:typeof c.data=="object"?u=JSON.stringify(c.data,null,2):u=String(c.data);else if(c.error){let p=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(p)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return s.setStatus({code:ze.OK}),u}catch(i){throw g.error("[AmazonBedrockProvider] Tool execution error:",{toolName:t,error:i}),s.setStatus({code:ze.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(e,t){if(t)return{};let n=e??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(e){let t={};for(let n of Object.keys(e))t[n]={execute:o=>this.executeSingleTool(e,n,o)};return t}convertAISDKToolsToToolDefinitions(e){let t={};for(let[n,o]of Object.entries(e))if("description"in o&&o.description){let i=o.parameters??o.inputSchema;t[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return t}formatToolsForBedrock(e){if(!e||Object.keys(e).length===0)return null;let t=Object.entries(e).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=xn(o.parameters):s=o.parameters:s={type:"object",properties:{},required:[]},(!s.type||s.type!=="object")&&(s={type:"object",properties:s.properties||{},required:s.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:s}}}});return g.debug(`[AmazonBedrockProvider] Formatted ${t.length} tools for Bedrock`),{tools:t}}convertToBedrockMessages(e){return e.map(t=>{let n={role:t.role==="system"?"user":t.role,content:[]};return typeof t.content=="string"?n.content.push({text:t.content}):t.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){let s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image,i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?DE.JPEG:i==="png"?DE.PNG:i==="gif"?DE.GIF:DE.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){let a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?wd.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(e){return g.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),g.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Lq.startActiveSpan("bedrock.stream",{kind:br.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async t=>{try{if(g.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(e.input?.images?.length||e.input?.content?.length||e.input?.files?.length||e.input?.csvFiles?.length||e.input?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!e.input?.images?.length,imageCount:e.input?.images?.length||0,hasContent:!!e.input?.content?.length,contentCount:e.input?.content?.length||0,hasFiles:!!e.input?.files?.length,fileCount:e.input?.files?.length||0,hasCSVFiles:!!e.input?.csvFiles?.length,csvFileCount:e.input?.csvFiles?.length||0,hasPDFFiles:!!e.input?.pdfFiles?.length,pdfFileCount:e.input?.pdfFiles?.length||0});let s=$se(e,this.providerName,this.modelName),i=await T_(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{g.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");let s={role:"user",content:[{text:e.input.text}]};this.conversationHistory.push(s)}g.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),g.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");let o=await this.streamingConversationLoop(e,t);return g.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),t.setStatus({code:ze.OK}),t.end(),o}catch(n){g.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");let o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(g.debug("[TRACE] executeStream CATCH - checking if permission error"),g.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){g.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),g.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),t.addEvent("stream.fallback_to_generate",{reason:o.message});let i=await this.generate({prompt:e.input.text,input:e.input,maxTokens:e.maxTokens,temperature:e.temperature,systemPrompt:e.systemPrompt});if(!i)throw t.setStatus({code:ze.ERROR,message:"Generate method returned null result"}),t.end(),new Error("Generate method returned null result");t.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),t.setStatus({code:ze.OK}),t.end();let a=new ReadableStream({start(c){let p=(i.content||"").split(/(\s+)/),m="";for(let f=0;f<p.length;f++)m+=p[f],(f===p.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(c.enqueue({content:m}),m="");m.length>0&&c.enqueue({content:m}),c.close()}});return{stream:{async*[Symbol.asyncIterator](){let c=a.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u)break;yield p}}finally{c.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw t.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),t.recordException(o instanceof Error?o:new Error(String(o))),t.end(),n}})}async streamingConversationLoop(e,t){let n=Date.now(),o=e.maxSteps||Jo,s=await this.resolveTurnTools(e.tools,e.disableTools),i=this.formatToolsForBedrock(s),a=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converseStream"),l=Fse({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:P=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(P),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})}),c=!1,u,p=new Promise(P=>{u=()=>{c=!0,P()}}),m={...l,executeStep:async(P,I,A)=>{let M=await l.executeStep(P,I,A);return u(),M}};t.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});let{stream:f,resultPromise:h}=Dse(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:e.abortSignal}),y=h.then(P=>({result:P,error:void 0}),P=>({result:void 0,error:P}));if(await Promise.race([p,y]),!c){let P=await y;if(P.error)throw P.error}let x=this.neurolink?.getEventEmitter(),b=this,T={startTime:n,streamId:`bedrock-${Date.now()}`},w,C=new Promise(P=>{w=P}),R=P=>{let I=P?.inputTokens??0,A=P?.outputTokens??0,M=P?.cacheReadTokens??0,U=P?.cacheWriteTokens??0;return{input:I,output:A,total:I+M+U+A,...M>0&&{cacheReadTokens:M},...U>0&&{cacheCreationTokens:U}}};return y.then(P=>{w(Hp(this.providerName,this.modelName||this.getDefaultModel(),{usage:R(P.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let P=!1;try{yield*f}catch(I){throw P=!0,I}finally{let I=await y;I.error&&(P=!0);let A=R(I.result?.usage);I.result&&(b.conversationHistory=I.result.conversation,T.finishReason=I.result.finishReason,T.rawFinishReason=I.result.rawStopReason,t.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),x&&x.emit("generation:end",{provider:b.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:A,model:b.modelName||b.getDefaultModel(),provider:b.providerName,finishReason:P?"error":I.result?.rawStopReason},success:!P})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:C,metadata:T}}async checkBedrockHealth(){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await Dq(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{g.debug("[AmazonBedrockProvider] Starting health check...");let i=new o({}),l=(await s.send(i,{abortSignal:e.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(g.debug(`[AmazonBedrockProvider] Health check passed - Found ${c.length} active models out of ${l.length} total models`),c.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(t);let a=i;if(wr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});let l=typeof a.message=="string"?a.message:"";throw l.includes("UnauthorizedOperation")||l.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:i}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:i}):(g.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:i}))}finally{clearTimeout(t);try{s.destroy()}catch{}}}formatProviderError(e){return en(e,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Mt,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:qr,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:mt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let{InvokeModelCommand:o}=await Promise.resolve().then(()=>(Mq(),KBe)),s=JSON.stringify({inputText:e}),i=new o({modelId:n,contentType:"application/json",accept:"application/json",body:s}),a=await je(this.bedrockClient.send(i),6e4,new Error("Bedrock embedding API call timed out")),l=JSON.parse(new TextDecoder().decode(a.body));if(!l.embedding||!Array.isArray(l.embedding))throw new Error("Invalid embedding response from Bedrock");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:l.embedding.length}),l.embedding}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await Promise.all(e.map(s=>this.embed(s,n)));return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}}});var aze={};de(aze,{AmazonBedrockProvider:()=>jse,bedrockTracer:()=>Lq,loadBedrockControl:()=>Dq});var lze=E(()=>{"use strict";ize();Bse();zse()});var cze={};de(cze,{AzureOpenAIProvider:()=>Gse});var Gse,uze=E(()=>{"use strict";Dt();X();ea();Ko();Kp();hc();Ag();Gse=class extends $n{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,n,o){let s=o?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"",a;if(i)try{a=new URL(i.includes("://")?i:`https://${i}`)}catch{a=void 0}let l=a?.hostname??"",c=a?.pathname&&a.pathname!=="/"?a.pathname.replace(/\/+$/,""):"",u=/\.(openai|cognitiveservices)\.azure\.com$/.test(l),p;u?p="/openai":p=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;let m=a?.origin??"",f=o?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=o?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",y=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,x=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||an(uye()),m||an(dye()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=p,this.useMaxCompletionTokensOverride=x,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",jB({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){let t=[{match:n=>/401/.test(n.message),errorClass:Mt,message:"Invalid Azure OpenAI API key or endpoint."},...tn];return en(e,t,"azure",this.modelName)}getChatCompletionsURL(e){let t=e||this.azureDeployment,n=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${n}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){let n=this.useMaxCompletionTokensOverride??E1e(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function dze(r){return r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70?"image/gif":"image/png"}var pze=E(()=>{"use strict"});function qse(r){return r.map(e=>typeof e.content=="string"?{role:e.role,content:e.content}:{role:e.role,content:e.content.map(t=>t.type==="image"||t.type==="document"?{type:t.type,media_type:t.source.media_type,base64_chars:t.source.data.length}:t)})}var mze=E(()=>{"use strict"});var Uq,gze=E(()=>{Uq=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}});var fze=E(()=>{fo()});function Fq(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Vse,Hse,Kse=E(()=>{fze();Vse=r=>(Vse=Array.isArray,Vse(r)),Hse=Vse});function*j_r(r){if(!r)return;if(hze in r){let{values:n,nulls:o}=r;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Hse(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=Hse(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var hze,yze,xze=E(()=>{Kse();hze=Symbol.for("brand.privateNullableHeaders");yze=r=>{let e=new Headers,t=new Set;for(let n of r){let o=new Set;for(let[s,i]of j_r(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),t.add(a)):(e.append(s,i),t.delete(a))}}return{[hze]:!0,values:e,nulls:t}}});function V_r(r){let e=new dm(r);return delete e.batches,e}function H_r(r){let e=new ti(r);return delete e.messages.batches,e}var G_r,q_r,$q,Wse=E(()=>{aM();use();P_();gze();Kse();xze();aM();G_r="vertex-2023-10-16",q_r=new Set(["/v1/messages","/v1/messages?beta=true"]),$q=class extends Jn{constructor({baseURL:e=Uq("ANTHROPIC_VERTEX_BASE_URL"),region:t=Uq("CLOUD_ML_REGION")??null,projectId:n=Uq("ANTHROPIC_VERTEX_PROJECT_ID")??null,...o}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...o}),this.messages=V_r(this),this.beta=H_r(this),this.region=t,this.projectId=n,this.accessToken=o.accessToken??null,o.authClient&&o.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");o.authClient?this._authClientPromise=Promise.resolve(o.authClient):(this._auth=o.googleAuth??new iP({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){let t=await this._authClientPromise,n=await t.getRequestHeaders(),o=t.projectId??n["x-goog-user-project"];!this.projectId&&o&&(this.projectId=o),e.headers=yze([n,e.headers])}async buildRequest(e){if(Fq(e.body)&&(e.body={...e.body}),Fq(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=G_r)),q_r.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!Fq(e.body))throw new Error("Expected request body to be an object for post /v1/messages");let t=e.body.model;e.body.model=void 0;let o=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${o}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}});var Jse={};de(Jse,{AnthropicVertex:()=>$q,BaseAnthropic:()=>Jn,default:()=>$q});var Xse=E(()=>{Wse();Wse()});async function K_r(){return Yse||(Yse=await Promise.resolve().then(()=>(Xse(),Jse))),Yse}function J_r(r){let e=[],t=new Map,n=0,o=s=>{let i=`${n}:${s??"x"}`,a=t.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},t.set(i,a),e.push(a)),a};for(let s of r){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}let i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,e.push({type:"regular",role:i,parts:[s.content]}))}return e}function Zse(r,e,t){let n=r[r.length-1];n&&n.role===e&&Array.isArray(n.content)?n.content.push(...t):r.push({role:e,content:[...t]})}function X_r(r,e){let t=r.callParts,n=r.resultParts,o=Math.min(t.length,n.length);(o!==t.length||o!==n.length)&&g.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:t.length,results:n.length,paired:o});let s=[],i=[];for(let a=0;a<o;a++){let l=`hist_${e}_${a}`;s.push({type:"tool_use",id:l,name:t[a].name,input:t[a].input}),i.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:s,results:i}}function Y_r(r){let e=t=>Array.isArray(t.content)&&t.content.length>0&&t.content.every(n=>n.type==="tool_result");for(;r.length>0&&(r[0].role!=="user"||e(r[0]));)r.shift()}function eie(r){let e=[],t=0;for(let n of J_r(r)){if(n.type==="regular"){Zse(e,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}let{uses:o,results:s}=X_r(n,t);o.length!==0&&(t++,Zse(e,"assistant",o),Zse(e,"user",s))}if(Y_r(e),g.shouldLog("debug")){let n=e.flatMap(o=>Array.isArray(o.content)?o.content:[]);g.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:e.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return e}function tie(r,e){let t=r[r.length-1];if(t&&t.role==="user"){let n=Array.isArray(t.content)?t.content:[{type:"text",text:t.content}],o=Array.isArray(e)?e:[{type:"text",text:e}];t.content=[...n,...o];return}r.push({role:"user",content:e})}function py(r){if(!r||typeof r!="object")return;let e=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(let n of e)n in r&&delete r[n];typeof r.exclusiveMinimum=="boolean"&&(r.exclusiveMinimum===!0&&typeof r.minimum=="number"?(r.exclusiveMinimum=r.minimum,delete r.minimum):delete r.exclusiveMinimum),typeof r.exclusiveMaximum=="boolean"&&(r.exclusiveMaximum===!0&&typeof r.maximum=="number"?(r.exclusiveMaximum=r.maximum,delete r.maximum):delete r.exclusiveMaximum);let t=2147483647;if(typeof r.maximum=="number"&&r.maximum>t&&delete r.maximum,typeof r.minimum=="number"&&r.minimum<-t&&delete r.minimum,r.properties&&typeof r.properties=="object")for(let n of Object.values(r.properties))n&&typeof n=="object"&&py(n);if(r.items&&typeof r.items=="object")if(Array.isArray(r.items))for(let n of r.items)n&&typeof n=="object"&&py(n);else py(r.items);for(let n of["allOf","anyOf","oneOf"])if(Array.isArray(r[n]))for(let o of r[n])o&&typeof o=="object"&&py(o)}function vze(r,e,t){let n=Zj({contents:r,availableInputTokens:mi("vertex",e),provider:"vertex",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=>{if(!("functionResponse"in c))return c;let u=c.functionResponse,p=JSON.stringify(u.response)??"";return p.length<=eEr?c:{functionResponse:{name:u.name,response:{result:cP(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:Yj}]})}return r.length=0,r.push(...i),!0}function bze(r,e,t){let n=Rq({conversation:r,availableInputTokens:mi("vertex",e),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:t,observedDescribesCurrentPayload:!0});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.content)){i.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;let u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:Cq(u)}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.content)&&l.content.some(c=>c.type==="tool_use"||c.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:Eq}]})}return r.length=0,r.push(...i),!0}var Yse,W_r,rie,Bq,zq,gM,FE,Z_r,Q_r,Qse,eEr,nie,oie=E(()=>{"use strict";ro();Qr();eu();Pz();tG();tte();cs();Ph();nz();Hr();so();Dt();ea();Tt();_se();qte();qI();X();Ere();bse();zj();pze();jj();Ko();Ea();Cre();O_();_l();$re();Kv();rG();$d();Xw();ac();gr();Dd();Kp();cI();dg();mze();YI();Yse=null;W_r=()=>!0;rie=()=>an(zL()),Bq=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",zq=(r,e)=>{let t=e||Bq();if(!r)return t;let n=r.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||S2.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":t},gM=zq,FE=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",Z_r=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),Q_r=async(r,e)=>{let t=r||Bq();return{projectId:rie(),region:t,...e!==void 0&&{timeout:e},maxRetries:0}},Qse=r=>r.toLowerCase().includes("claude"),eEr=2048;nie=class r extends oo{projectId;location;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(e,t,n,o,s){super(e,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey))),Z_r()||an(Cye()),this.projectId=s?.projectId||rie(),this.location=o||s?.location||Bq(),g.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),g.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return FE()}async getAISDKModel(){throw new Le({code:tt.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(e){this.validateStreamOptions(e)}async preprocessNativeFileInput(e){if(e.input&&jI(e.input),e.input?.files?.length)try{await GI(e,100*1024*1024,this.providerName)}catch(t){g.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Uv(e.input)}async executeStream(e,t){let n=e.model||this.modelName||FE();return KA({name:"neurolink.provider.stream",tracer:Oe.provider,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName,[Pe.GEN_AI_MODEL]:n,[Pe.GEN_AI_OPERATION]:"stream",[Pe.NL_PROVIDER]:this.providerName}},async o=>{let s=Date.now(),i=e.tools||{};await this.preprocessNativeFileInput(e);let l={...await Je({name:"neurolink.message.build",tracer:Oe.provider,attributes:{[Pe.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(e)),tools:i};try{let c;Qse(n)?(g.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(g.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeGemini3Stream(l)),this.attachUsageAndCostAttributes(o,n,c?.usage);let u=this.wrapStreamResultWithLifecycle(e,c,s);return this.emitStreamEnd(n,s,!0,void 0,c.finishReason),u}catch(c){throw this.fireGenerateOnError(e,c,s),this.emitStreamEnd(n,s,!1,c),c}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(e,t,n,o,s){let i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:e,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(e){let t=rie(),n=e||this.location||Bq(),s=(await Promise.resolve().then(()=>(ww(),Sw))).GoogleGenAI;if(!s)throw new Le({code:tt.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});let i=s;return new i({vertexai:!0,project:t,location:n,httpOptions:{fetch:yt()}})}buildGeminiFunctionDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`},s=t.parameters||t.inputSchema;if(s){let i=xn(s,"openApi3"),a=pn(i);a.$schema&&delete a.$schema;let l=pi(a);py(l),n.parametersJsonSchema=l}return n}refreshGeminiToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildGeminiFunctionDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Gemini declarations.`))}resolveGeminiToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildGeminiFunctionDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}buildAnthropicToolDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`,input_schema:{type:"object"}},s=t.parameters||t.inputSchema;if(s){let i=xn(s),a=pn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildAnthropicToolDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}async executeNativeGemini3Stream(e){let t=e.model||this.modelName||FE(),n=gM(t,e.region),o=await this.createVertexGenAIClient(n);g.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0,project:this.projectId,location:n});let s=[],i=[{text:e.input.text??""}],a=e.input;if(a?.pdfFiles&&a.pdfFiles.length>0){g.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(let ye of a.pdfFiles){let Fe;typeof ye=="string"?wn.existsSync(ye)?Fe=wn.readFileSync(ye):Fe=Buffer.from(ye,"base64"):Fe=ye;let Ee=Fe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:Ee}})}}if(await eG(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){g.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(let ye of a.images){let Fe=i_(ye),Ee,Rt="image/jpeg";if(typeof Fe=="string")if(wn.existsSync(Fe)){Ee=wn.readFileSync(Fe);let ue=Ov(Fe);Rt=ue.startsWith("image/")?ue:this.detectImageType(Ee)}else if(Fe.startsWith("data:")){let ue=Fe.match(/^data:([^;]+);base64,(.+)$/);if(ue)Rt=ue[1],Ee=Buffer.from(ue[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{let ue=await fetch(Fe);if(!ue.ok){g.warn(`[GoogleVertex] Image fetch failed: ${ue.status} ${ue.statusText}, skipping`,{url:Wr(Fe)});continue}let qe=await ue.arrayBuffer();Ee=Buffer.from(qe);let Be=ue.headers.get("content-type");Be&&Be.startsWith("image/")&&(Rt=Be.split(";")[0])}catch(ue){g.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ue instanceof Error?ue.message:String(ue)}`,{url:Wr(Fe)});continue}else Ee=Buffer.from(Fe,"base64"),Rt=this.detectImageType(Ee);else Ee=Fe,Rt=this.detectImageType(Ee);let Xe=Ee.toString("base64");i.push({inlineData:{mimeType:Rt,data:Xe}})}}L_(s,e.conversationMessages),s.push({role:"user",parts:i});let l,c=new Hd;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){let ye=Rg(e.tools,"functionDeclarations");l=ye.toolsConfig;for(let[Fe,Ee]of ye.executeMap)c.set(Fe,Ee);g.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ye.toolsConfig[0].functionDeclarations.length,toolNames:ye.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}let u=e,p=!1;if(u.schema&&l){p=!0;let ye=xn(u.schema,"openApi3"),Fe=pn(ye);Fe.$schema&&delete Fe.$schema;let Ee=pi(Fe),Rt=l[0]?.functionDeclarations||[];Rt.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Ee}),l=[{functionDeclarations:Rt}],g.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(Ee),totalTools:Rt.length})}let m=_a(this.providerName,t,{temperature:e.temperature??1,...e.topP!==void 0&&{topP:e.topP}},"vertex.gemini"),f={...m.temperature!==void 0&&{temperature:m.temperature},maxOutputTokens:e.maxTokens};nP(t)&&(f.maxOutputTokens&&f.maxOutputTokens>Nl&&(g.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Nl} for ${t}`),f.maxOutputTokens=Nl),f.maxOutputTokens||(f.maxOutputTokens=Nl)),m.topP!==void 0&&(f.topP=m.topP),e.topK!==void 0&&(f.topK=e.topK),e.stopSequences&&e.stopSequences.length>0&&(f.stopSequences=e.stopSequences),l&&(f.tools=l);let h=e.systemPrompt||"";p&&(h=h+`
1129
+ `);return{...s!==void 0?{system:s}:{},messages:t}},jBe=r=>{if(!(!r||r==="auto")){if(r==="none")return{type:"none"};if(r==="required")return{type:"any"};if(typeof r=="object"){let e=r;if(e.type==="tool"&&e.toolName)return{type:"tool",name:e.toolName}}}},qSr=r=>{switch(r){case"max_tokens":return"length";case"tool_use":return"tool-calls";case"refusal":return"content-filter";default:return"stop"}},GBe=6e5,Mse=class extends oo{client;authMethod;subscriptionTier;enableBetaFeatures;oauthToken;lastResponseMetadata=null;usageInfo=null;refreshPromise;constructor(e,t,n,o){let s=!!(o?.apiKey&&!o?.oauthToken),i=s?null:(o?.oauthToken?{accessToken:o.oauthToken}:null)??n?.oauthToken??BBe(),a=s?"api_key":n?.authMethod??GSr(i),l=n?.subscriptionTier??(a==="oauth"?jSr(i):"api"),c=e||Pq(),u=c;!process.env.ANTHROPIC_BASE_URL&&l!=="api"&&!uM(c,l)&&(u=Sq(l),g.warn("Model not available for subscription tier, using recommended model",{requestedModel:c,subscriptionTier:l,recommendedModel:u})),super(u,"anthropic",t),this.enableBetaFeatures=n?.enableBetaFeatures??!0,this.oauthToken=i,this.subscriptionTier=l,this.authMethod=a;let m=this.getAuthHeaders(),f;if(g.debug("[AnthropicProvider] Constructor - checking OAuth:",{authMethod:this.authMethod,hasOAuthToken:!!this.oauthToken,hasAccessToken:!!this.oauthToken?.accessToken}),this.authMethod==="oauth"&&this.oauthToken){g.debug("[AnthropicProvider] Creating OAuth fetch wrapper...");let h=this.oauthToken,y=mBe(()=>h.accessToken,this.enableBetaFeatures,!1,!0);f=new Xd({apiKey:"oauth-authenticated",fetch:vse(y),timeout:GBe,maxRetries:0}),g.debug("[AnthropicProvider] Anthropic SDK client created with OAuth fetch wrapper"),g.debug("Anthropic Provider initialized with OAuth",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,hasRefreshToken:!!this.oauthToken.refreshToken,tokenExpiry:this.oauthToken.expiresAt?new Date(this.oauthToken.expiresAt).toISOString():"none"})}else{let h=o?.apiKey??n?.apiKey??$Be(),y=(()=>{let x=process.env.ANTHROPIC_BASE_URL;if(!x)return;let b=x.replace(/\/+$/,""),T=b.replace(/\/v\d+$/,"");return T!==b&&g.debug("[AnthropicProvider] Stripping the version suffix from ANTHROPIC_BASE_URL \u2014 the official Anthropic SDK appends /v1 to the base URL itself.",{baseURL:Ir(x),rewrittenTo:Ir(T)}),T})();f=new Xd({apiKey:h,defaultHeaders:m,...y&&{baseURL:y},fetch:vse(yt()),timeout:GBe,maxRetries:0}),g.debug("Anthropic Provider initialized with API key",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures})}this.client=f,this.usageInfo={messagesUsed:0,messagesRemaining:-1,tokensUsed:0,tokensRemaining:-1,inputTokensUsed:0,outputTokensUsed:0,lastRequestTimestamp:0,isRateLimited:!1,requestCount:0,messageQuotaPercent:0,tokenQuotaPercent:0},g.debug("Anthropic Provider v2 initialized",{modelName:this.modelName,provider:this.providerName,authMethod:this.authMethod,subscriptionTier:this.subscriptionTier,enableBetaFeatures:this.enableBetaFeatures,betaFeatures:this.enableBetaFeatures?Iq["anthropic-beta"]:"disabled"})}getAuthHeaders(){let e={},t=!!process.env.ANTHROPIC_BASE_URL;if(this.enableBetaFeatures)if(t){let n=process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="1"||process.env.ANTHROPIC_ENABLE_LONG_CONTEXT_BETA==="true",o=[...hb,"fine-grained-tool-streaming-2025-05-14","interleaved-thinking-2025-05-14","redact-thinking-2026-02-12"];n&&o.push("context-1m-2025-08-07"),e["anthropic-beta"]=o.join(",")}else e["anthropic-beta"]=Iq["anthropic-beta"];return t&&(e["User-Agent"]=Yd),this.subscriptionTier!=="api"&&(e["x-subscription-tier"]=this.subscriptionTier),e}validateModelAccess(e){if(process.env.ANTHROPIC_BASE_URL)return g.debug("[validateModelAccess] Bypassing tier check (ANTHROPIC_BASE_URL set \u2014 proxy enforces access)",{model:e}),!0;if(this.subscriptionTier==="api")return!0;let t=uM(e,this.subscriptionTier);return t||g.debug("[validateModelAccess] Model not available for tier",{model:e,tier:this.subscriptionTier}),t}getUsageInfo(){return this.usageInfo}areBetaFeaturesEnabled(){return this.enableBetaFeatures}getModelCapabilities(){return wq(this.modelName||this.getDefaultModel())}getSubscriptionTier(){return this.subscriptionTier}getAuthMethod(){return this.authMethod}async refreshAuthIfNeeded(){if(this.authMethod!=="oauth"||!this.oauthToken){g.debug("Token refresh not applicable for API key authentication");return}if(!this.oauthToken.expiresAt){g.debug("Token has no expiry information, assuming valid");return}let e=Date.now(),t=this.oauthToken.expiresAt<=e,n=this.oauthToken.expiresAt<=e+3e5;if(!t&&!n){g.debug("OAuth token is still valid",{expiresInMs:this.oauthToken.expiresAt-e});return}if(!this.oauthToken.refreshToken){if(t)throw new Mt("OAuth token expired and no refresh token available. Please re-authenticate.",this.providerName);g.warn("OAuth token expiring soon but no refresh token available",{expiresInMs:this.oauthToken.expiresAt-e});return}if(this.refreshPromise){await this.refreshPromise;return}g.info("Refreshing OAuth token",{isExpired:t,expiresInMs:this.oauthToken.expiresAt-e});let o=this.oauthToken,s=o.refreshToken;this.refreshPromise=(async()=>{let a=new AbortController,l=setTimeout(()=>a.abort(),3e4),c=await fetch(ME,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Yd},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:s,client_id:bq}),signal:a.signal});if(clearTimeout(l),!c.ok){let m=await c.text();throw new Mt(`Failed to refresh OAuth token: ${c.status} ${m}`,this.providerName)}let u=await c.json();o.accessToken=u.access_token,o.refreshToken=u.refresh_token||o.refreshToken,o.expiresAt=u.expires_in?Date.now()+u.expires_in*1e3:void 0,o.tokenType=u.token_type||"Bearer";let p=o;try{let m=Fr(Op(),".neurolink");to(m)||lA(m,{recursive:!0});let f=Fr(m,"anthropic-credentials.json"),h=`${f}.tmp`,x={...to(f)?JSON.parse(Gc(f,"utf-8")):{},type:"oauth",oauth:p,updatedAt:Date.now()};aA(h,JSON.stringify(x,null,2),{mode:384}),iX(h,f),g.debug("Refreshed OAuth credentials persisted to disk")}catch(m){g.warn("Failed to persist refreshed OAuth token to disk",{error:m instanceof Error?m.message:String(m)})}g.info("OAuth token refreshed successfully",{hasNewRefreshToken:!!u.refresh_token,expiresIn:u.expires_in})})();try{await this.refreshPromise}catch(i){throw i instanceof Mt?i:new Mt(`Failed to refresh OAuth token: ${i instanceof Error?i.message:String(i)}`,this.providerName)}finally{this.refreshPromise=void 0}}getLastResponseMetadata(){return this.lastResponseMetadata}updateResponseMetadata(e,t,n){this.lastResponseMetadata={rateLimit:e,...t?{requestId:t}:{}},this.usageInfo&&(this.usageInfo.requestCount++,this.usageInfo.messagesUsed++,this.usageInfo.lastRequestTimestamp=Date.now(),n&&(n.inputTokens!==void 0&&(this.usageInfo.inputTokensUsed+=n.inputTokens,this.usageInfo.tokensUsed+=n.inputTokens),n.outputTokens!==void 0&&(this.usageInfo.outputTokensUsed+=n.outputTokens,this.usageInfo.tokensUsed+=n.outputTokens)),e?.requestsRemaining!==void 0&&(this.usageInfo.messagesRemaining=e.requestsRemaining),e?.tokensRemaining!==void 0&&(this.usageInfo.tokensRemaining=e.tokensRemaining),e?.requestsLimit&&e.requestsLimit>0&&(this.usageInfo.messageQuotaPercent=Math.round((e.requestsLimit-(e.requestsRemaining??0))/e.requestsLimit*100)),e?.tokensLimit&&e.tokensLimit>0&&(this.usageInfo.tokenQuotaPercent=Math.round((e.tokensLimit-(e.tokensRemaining??0))/e.tokensLimit*100)),e?.retryAfter!==void 0?(this.usageInfo.isRateLimited=!0,this.usageInfo.rateLimitExpiresAt=Date.now()+e.retryAfter*1e3):(this.usageInfo.isRateLimited=!1,this.usageInfo.rateLimitExpiresAt=void 0)),e?.requestsRemaining!==void 0&&e.requestsRemaining<=5&&g.warn("Approaching Anthropic request rate limit",{remaining:e.requestsRemaining,limit:e.requestsLimit,reset:e.requestsReset}),e?.tokensRemaining!==void 0&&e.tokensLimit&&e.tokensRemaining<e.tokensLimit*.1&&g.warn("Approaching Anthropic token rate limit",{remaining:e.tokensRemaining,limit:e.tokensLimit,reset:e.tokensReset})}getProviderName(){return"anthropic"}getDefaultModel(){return Pq()}getAISDKModel(){let e=this.client,t=this.providerName,n=this.modelName||Pq(),o=a=>this.getTimeout(a??{}),s=()=>this.refreshAuthIfNeeded();return{specificationVersion:"v3",provider:t,modelId:n,supportedUrls:{},doGenerate:async a=>{await s();let l=zBe(a.prompt),c=l.messages,u=l.system,p=(a.tools??[]).filter(F=>F.type==="function").map(F=>{let B=om(F);return{name:F.name,...F.description?{description:F.description}:{},input_schema:F.inputSchema??{type:"object",properties:{}},...B?{cache_control:B}:{}}});p&&p.length===0&&(p=void 0);let m=a.toolChoice?jBe(a.toolChoice.type==="tool"?{type:"tool",toolName:a.toolChoice.toolName}:a.toolChoice.type):void 0,f;if(a.responseFormat?.type==="json"){f=a.responseFormat.name??"json";let F=a.responseFormat.schema??{type:"object"};p=[{name:f,description:a.responseFormat.description??"Respond by calling this tool with the answer as its input.",input_schema:F}],m={type:"tool",name:f}}let h=a.providerOptions?.anthropic?.finalResultSchema,y=!1;if(!f&&h){let F=Ise(p,h);p=F.tools,y=F.applied,F.applied&&(u=Pse(u))}let x=a.providerOptions?.anthropic?.thinking,b=Sse({system:u,tools:p,messages:c}),T=wse(c,Aq-b),w=_a("anthropic",n,{...a.temperature!==void 0&&a.temperature!==null?{temperature:a.temperature}:{},...a.topP!==void 0&&a.topP!==null?{topP:a.topP}:{}},"anthropic.doGenerate"),C={model:n,messages:T,max_tokens:A_(n,a.maxOutputTokens),...u?{system:u}:{},...w.temperature!==void 0?{temperature:w.temperature}:{},...w.topP!==void 0?{top_p:w.topP}:{},...a.stopSequences&&a.stopSequences.length>0?{stop_sequences:a.stopSequences}:{},...p?{tools:p}:{},...m?{tool_choice:m}:{},...x?{thinking:x}:{}},R=a.timeout,k=R!=null,P=C.max_tokens>8192&&!k?Math.max(o(a),3e5):o(a),I=Ws(P,t,"generate"),A;try{A=await e.messages.create(C,{signal:Ux(a.abortSignal,I?.controller.signal)})}finally{I?.cleanup()}let M=[],U,$=[],L=!1;for(let F of A.content)F.type==="thinking"?M.push({type:"reasoning",text:F.thinking}):F.type==="text"?f?$.push(F.text):M.push({type:"text",text:F.text}):F.type==="tool_use"&&(f&&F.name===f?(L=!0,M.push({type:"text",text:xP(F.input)})):y&&F.name===mM?U=xP(F.input):M.push({type:"tool-call",toolCallId:F.id,toolName:F.name,input:xP(F.input)}));if(f&&!L&&$.length>0&&M.push({type:"text",text:$.join("")}),U!==void 0){let F=M.filter(B=>B.type==="reasoning");M.length=0,M.push(...F,{type:"text",text:U}),g.debug("[Anthropic] Extracted structured output from final_result tool (generate)",{chars:U.length})}let z=A.usage.cache_read_input_tokens??0,j=A.usage.cache_creation_input_tokens??0;return{content:M,finishReason:{unified:U!==void 0?"stop":qSr(A.stop_reason),raw:A.stop_reason??"stop"},usage:{inputTokens:{total:A.usage.input_tokens+z+j,noCache:A.usage.input_tokens,cacheRead:z,cacheWrite:j},outputTokens:{total:A.usage.output_tokens,text:A.usage.output_tokens,reasoning:void 0}},warnings:[],request:{body:C},response:{id:A.id,modelId:A.model,headers:bBe()??{},body:A}}},doStream:()=>{throw new Error(`${t}: doStream is not implemented on the delegating model \u2014 the streaming path uses executeStream directly.`)}}}formatProviderError(e){return en(e,[{match:n=>n.statusCode===401||/API_KEY_INVALID|Invalid API key/i.test(n.message),errorClass:Mt,message:"Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."},{match:n=>n.statusCode===429||/rate limit|too_many_requests|429/i.test(n.message),errorClass:qr,message:"Anthropic rate limit exceeded. Please try again later."},{match:n=>/ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(n.message),errorClass:cn,message:n=>`Connection error: ${n.message}`},{match:n=>/500|502|503|504|server error/i.test(n.message),errorClass:mt,message:n=>`Server error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`Anthropic error: ${n.message}`}],this.providerName,this.modelName)}async generate(e,t){await this.refreshAuthIfNeeded();let{result:n,snapshot:o}=await xBe(()=>super.generate(e,t));return n&&o&&(this.recordLimitSnapshot(o),n.limits=o,n.analytics&&(n.analytics.limits=o)),n}recordLimitSnapshot(e){this.updateResponseMetadata(e.rateLimit,e.requestId),SBe(e),wBe(e,this.modelName)}async executeStream(e,t){return TBe(()=>this.executeStreamInCaptureScope(e,t))}async executeStreamInCaptureScope(e,t){await this.refreshAuthIfNeeded(),this.validateStreamOptions(e);let n=this.getTimeout(e),o=Ws(n,this.providerName,"stream"),s=new AbortController,i=f1([e.abortSignal,o?.controller.signal,s.signal]).signal,a,l,c,u,p=!1;try{u=!e.disableTools&&this.supportsTools(),a=u?e.tools||await this.getAllTools():{},l=u?Rg(a,"input_schema"):void 0;let oe=await this.buildMessagesForStream(e);if(c=zBe(oe),e.schema&&l&&l.length>0){let Z=Ise(l,xn(e.schema));l=Z.tools,p=Z.applied,Z.applied&&(c.system=Pse(c.system))}}catch(oe){throw o?.cleanup(),this.handleProviderError(oe)}let m=this.modelName||Pq(),f=u&&l&&l.length>0?jBe(dG(e,a,u)):void 0,h=e.thinkingConfig?.enabled&&e.thinkingConfig.budgetTokens?{type:"enabled",budget_tokens:e.thinkingConfig.budgetTokens}:void 0,y=zSr.startSpan("neurolink.provider.streamText",{kind:br.CLIENT,attributes:{"gen_ai.system":"anthropic","gen_ai.request.model":m}}),x=e.maxSteps||Jo,b=this.neurolink?.getEventEmitter(),T=Fu(),{push:w}=T,{usagePromise:C,finishPromise:R,resolveUsage:k,resolveFinish:P}=lG();C.then(oe=>{y.setAttribute("gen_ai.usage.input_tokens",oe.promptTokens||0),y.setAttribute("gen_ai.usage.output_tokens",oe.completionTokens||0),oe.cacheReadTokens&&y.setAttribute("gen_ai.usage.cached_input_tokens",oe.cacheReadTokens);let Z=Us(this.providerName,this.modelName,{input:oe.promptTokens||0,output:oe.completionTokens||0,total:oe.totalTokens||0,...oe.cacheReadTokens?{cacheReadTokens:oe.cacheReadTokens}:{},...oe.cacheCreationTokens?{cacheCreationTokens:oe.cacheCreationTokens}:{}});Z&&Z>0&&y.setAttribute("neurolink.cost",Z)}).catch(()=>{}),R.then(oe=>{y.setAttribute("gen_ai.response.finish_reason",oe||"unknown"),y.end()}).catch(()=>{y.end()});let I,A=this.client,M=[],U=Date.now(),$=0,L=0,z=0,j=0,F=null,B=()=>({promptTokens:$,completionTokens:L,totalTokens:$+z+j+L,...z>0?{cacheReadTokens:z}:{},...j>0?{cacheCreationTokens:j}:{}}),O="",W,re=(oe,Z)=>{let we=ve=>{if(typeof ve=="string")return ve;try{return JSON.stringify(ve)??""}catch{return""}};return zt(we(oe),"anthropic")+zt(we(Z),"anthropic")},pe=(async()=>{let oe=c.messages.slice(),Z,we;for(let ve=0;ve<x;ve++){if(l){let ce=new Set(l.map(_=>_.name)),Ne=Object.fromEntries(Object.entries(a).filter(([_])=>!ce.has(_)));Object.keys(Ne).length>0&&(l.push(...Rg(Ne,"input_schema")??[]),g.info(`[Anthropic] ${Object.keys(Ne).length} tool(s) hydrated mid-turn via discovery: ${Object.keys(Ne).join(", ")}`))}let ae=Rq({conversation:oe,availableInputTokens:mi("anthropic",m,e.maxTokens??void 0),fixedOverheadTokens:re(c.system,l),provider:"anthropic",observedPromptTokens:Z,previousSentEstimate:we,onSentEstimate:ce=>{we=ce}});if(ae){let ce=new Set(ae.drop),Ne=new Set(ae.truncate),_=[];for(let G=0;G<oe.length;G++){if(ce.has(G))continue;let Q=oe[G];if(Ne.has(G)&&Array.isArray(Q.content)){_.push({...Q,content:Q.content.map(q=>q.type==="tool_result"?{...q,content:Cq(typeof q.content=="string"?q.content:JSON.stringify(q.content)??"")}:q)});continue}_.push(Q)}if(ce.size>0){let G=_.findIndex(Q=>Array.isArray(Q.content)&&Q.content.some(q=>q.type==="tool_use"||q.type==="tool_result"));G<0&&(G=Math.min(1,_.length)),_.splice(G,0,{role:"user",content:[{type:"text",text:Eq}]})}oe.length=0,oe.push(..._)}let H=Sse({system:c.system,tools:l,messages:oe}),V=wse(oe,Aq-H),ne=_a("anthropic",m,e.temperature!==void 0&&e.temperature!==null?{temperature:e.temperature}:{},"anthropic.executeStream"),N={model:m,messages:V,max_tokens:A_(m,e.maxTokens),stream:!0,...c.system?{system:c.system}:{},...ne.temperature!==void 0?{temperature:ne.temperature}:{},...l&&l.length>0?{tools:l}:{},...f?{tool_choice:f}:{},...h?{thinking:h}:{}},Y=await Ru(()=>A.messages.create(N,{signal:i??void 0}),pt.getActiveSpan()??void 0,`${this.providerName} stream`),ee=new Map,ie=new Map,le=new Map,ye=new Map,Fe=null,Ee=0;for await(let ce of Y)if(ce.type==="message_start"){$+=ce.message.usage.input_tokens??0;let Ne=ce.message.usage.output_tokens??0;L+=Ne-Ee,Ee=Ne,z+=ce.message.usage.cache_read_input_tokens??0,j+=ce.message.usage.cache_creation_input_tokens??0,Z=(ce.message.usage.input_tokens??0)+(ce.message.usage.cache_read_input_tokens??0)+(ce.message.usage.cache_creation_input_tokens??0)}else if(ce.type==="content_block_start")ee.set(ce.index,ce.content_block.type),ce.content_block.type==="tool_use"&&ye.set(ce.index,{id:ce.content_block.id,name:ce.content_block.name,inputJson:""});else if(ce.type==="content_block_delta"){let Ne=ce.delta;if(Ne.type==="text_delta")ie.set(ce.index,(ie.get(ce.index)??"")+Ne.text),p?O+=Ne.text:w({content:Ne.text});else if(Ne.type==="thinking_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.text+=Ne.thinking,le.set(ce.index,_),w({content:"",reasoning:Ne.thinking})}else if(Ne.type==="signature_delta"){let _=le.get(ce.index)??{text:"",signature:""};_.signature+=Ne.signature,le.set(ce.index,_)}else if(Ne.type==="input_json_delta"){let _=ye.get(ce.index);_&&(_.inputJson+=Ne.partial_json)}}else if(ce.type==="message_delta"){Fe=ce.delta.stop_reason??Fe;let Ne=ce.usage?.output_tokens??Ee;L+=Ne-Ee,Ee=Ne}if(F=Fe,p){let ce=[...ye.values()].find(Ne=>Ne.name===mM);if(ce){W=UBe(ce.inputJson),F="end_turn",g.debug("[Anthropic] Extracted structured output from final_result tool (stream)",{chars:W.length});break}}if(Fe!=="tool_use"||ye.size===0)break;let Rt=[],Xe=[...ee.keys()].sort((ce,Ne)=>ce-Ne);for(let ce of Xe){let Ne=ee.get(ce);if(Ne==="thinking"){let _=le.get(ce);_&&_.text.length>0&&Rt.push({type:"thinking",thinking:_.text,signature:_.signature})}else if(Ne==="text"){let _=ie.get(ce);_&&_.length>0&&Rt.push({type:"text",text:_})}else if(Ne==="tool_use"){let _=ye.get(ce);if(_){let G;try{G=_.inputJson?JSON.parse(_.inputJson):{}}catch{G={}}Rt.push({type:"tool_use",id:_.id,name:_.name,input:G})}}}oe.push({role:"assistant",content:Rt});let ue=[],qe=[],Be=[];for(let ce of ye.values()){let Ne;try{Ne=ce.inputJson?JSON.parse(ce.inputJson):{}}catch{Ne={}}qe.push({type:"tool-call",toolCallId:ce.id,toolName:ce.name,args:Ne}),M.push(ce.name);let _=a[ce.name]??pI(a,ce.name);try{if(!_?.execute)throw new Error(`Tool not found: ${ce.name}`);let G=await _.execute(Ne,{toolCallId:ce.id,messages:[]});Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,result:G}),ue.push({type:"tool_result",tool_use_id:ce.id,content:Ese(G)})}catch(G){let Q=G instanceof Error?G.message:String(G);Be.push({type:"tool-result",toolCallId:ce.id,toolName:ce.name,error:Q}),ue.push({type:"tool_result",tool_use_id:ce.id,content:`Error: ${Q}`,is_error:!0})}}Yw(b,Be.map(ce=>({toolName:ce.toolName,result:ce.result,error:ce.error}))),this.handleToolExecutionStorage(qe,Be,e,new Date).catch(ce=>{g.warn("[AnthropicProvider] Failed to store tool executions",{provider:this.providerName,error:ce instanceof Error?ce.message:String(ce)})}),oe.push({role:"user",content:ue})}k(B()),P(F??"stop")})().catch(oe=>{throw I=oe,g.error("Anthropic: Stream error",{error:oe instanceof Error?oe.message:String(oe)}),k(B()),P("error"),this.formatProviderError(oe)}).finally(()=>{if(p){let oe=W??O;oe.length>0&&w({content:oe})}o?.cleanup(),T.close()});pe.catch(()=>{});let Ae=this.providerName;return{stream:async function*(){let oe=0;try{for await(let Z of T.iterable)"content"in Z&&typeof Z.content=="string"&&Z.content.length>0&&oe++,yield Z;if(await pe,oe===0&&M.length===0){g.warn(`${Ae}: Stream produced no output \u2014 emitting enriched sentinel`);let Z=new Ta({message:"Stream produced no output"}),we=await Zp(Z,void 0,I);Qp(we),yield we}}catch(Z){let we=await Zp(Z,void 0,I);if(Qp(we),yield we,!Ta.isInstance(Z))throw Z}finally{s.signal.aborted||s.abort()}}(),provider:this.providerName,model:this.modelName,toolCalls:[],toolResults:[],analytics:R.then(async()=>{let oe=await uG.createAnalytics(this.providerName,m,{textStream:(async function*(){})(),usage:C,finishReason:R},Date.now()-U,{requestId:e.requestId??`${this.providerName}-stream-${Date.now()}`,streamingMode:!0}),Z=vBe();return Z&&oe&&(this.recordLimitSnapshot(Z),oe.limits=Z),oe})}}async isAvailable(){try{return BBe()||$Be(),!0}catch{return!1}}getModel(){return this.getAISDKModel()}}});var VBe={};de(VBe,{ANTHROPIC_BETA_HEADERS:()=>Iq,AnthropicProvider:()=>Mse,ModelAccessError:()=>jR,getModelCapabilities:()=>wq,getRecommendedModelForTier:()=>Sq,isModelAvailableForTier:()=>uM});var HBe=E(()=>{"use strict";qBe();kse()});var KBe={};de(KBe,{Agent:()=>kwr,BedrockClient:()=>HSr,BedrockRuntimeClient:()=>Ose,Blob:()=>Rwr,Client:()=>Iwr,ConverseCommand:()=>Nse,ConverseStreamCommand:()=>Lse,Cron:()=>cwr,Dispatcher:()=>Pwr,File:()=>Cwr,FlowProducer:()=>lwr,FormData:()=>Ewr,GoogleAuth:()=>YSr,HTTPException:()=>hwr,Headers:()=>_wr,Hippocampus:()=>twr,HippocampusConfig:()=>rwr,Hono:()=>gwr,ImageFormat:()=>DE,InvokeEndpointCommand:()=>JSr,InvokeEndpointWithResponseStreamCommand:()=>XSr,Job:()=>iwr,ListFoundationModelsCommand:()=>KSr,MockAgent:()=>Nwr,Pool:()=>Awr,Queue:()=>owr,QueueScheduler:()=>awr,Request:()=>Swr,Response:()=>wwr,SageMakerRuntimeClient:()=>WSr,TextToSpeechClient:()=>QSr,VertexAI:()=>ZSr,Webhook:()=>ewr,Worker:()=>swr,convertToHtml:()=>mwr,cors:()=>fwr,createClient:()=>nwr,default:()=>VSr,extractRawText:()=>pwr,fetch:()=>Twr,getGlobalDispatcher:()=>Owr,interceptors:()=>Lwr,logger:()=>ywr,parseBuffer:()=>uwr,request:()=>Dwr,secureHeaders:()=>xwr,selectCover:()=>dwr,setGlobalDispatcher:()=>Mwr,streamSSE:()=>vwr,timeout:()=>bwr});var LE,Mi,VSr,HSr,KSr,Ose,Nse,Lse,DE,WSr,JSr,XSr,YSr,ZSr,QSr,ewr,twr,rwr,nwr,owr,swr,iwr,awr,lwr,cwr,uwr,dwr,pwr,mwr,gwr,fwr,hwr,ywr,xwr,vwr,bwr,Twr,Swr,wwr,_wr,Ewr,Cwr,Rwr,kwr,Awr,Iwr,Pwr,Mwr,Owr,Nwr,Lwr,Dwr,Mq=E(()=>{LE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:LE.get}):new Proxy(function(...t){return new Proxy({},{get:LE.get})},{get:LE.get,apply(t,n,o){return new Proxy({},{get:LE.get})},construct(t,n){return new Proxy({},{get:LE.get})}})}},Mi=new Proxy({},LE),VSr=Mi,{BedrockClient:HSr,ListFoundationModelsCommand:KSr,BedrockRuntimeClient:Ose,ConverseCommand:Nse,ConverseStreamCommand:Lse,ImageFormat:DE}=Mi,{SageMakerRuntimeClient:WSr,InvokeEndpointCommand:JSr,InvokeEndpointWithResponseStreamCommand:XSr}=Mi,{GoogleAuth:YSr,VertexAI:ZSr,TextToSpeechClient:QSr}=Mi,{Webhook:ewr}=Mi,{Hippocampus:twr,HippocampusConfig:rwr}=Mi,{createClient:nwr}=Mi,{Queue:owr,Worker:swr,Job:iwr,QueueScheduler:awr,FlowProducer:lwr}=Mi,{Cron:cwr}=Mi,{parseBuffer:uwr,selectCover:dwr}=Mi,{extractRawText:pwr,convertToHtml:mwr}=Mi,{Hono:gwr}=Mi,{cors:fwr,HTTPException:hwr,logger:ywr,secureHeaders:xwr,streamSSE:vwr,timeout:bwr}=Mi,Twr=globalThis.fetch,Swr=globalThis.Request,wwr=globalThis.Response,_wr=globalThis.Headers,Ewr=globalThis.FormData,Cwr=globalThis.File,Rwr=globalThis.Blob,kwr=Mi.Agent,Awr=Mi.Pool,Iwr=Mi.Client,Pwr=Mi.Dispatcher,Mwr=()=>{},Owr=()=>Mi,Nwr=Mi.MockAgent,Lwr={redirect:()=>r=>r,retry:()=>r=>r},Dwr=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});function Uwr(r,e){return{inputTokens:r.inputTokens+e.inputTokens,outputTokens:r.outputTokens+e.outputTokens,cacheReadTokens:(r.cacheReadTokens??0)+(e.cacheReadTokens??0)||void 0,cacheWriteTokens:(r.cacheWriteTokens??0)+(e.cacheWriteTokens??0)||void 0,reasoningTokens:(r.reasoningTokens??0)+(e.reasoningTokens??0)||void 0}}function Dse(r,e,t){let n=Fu(),o=new AbortController,s=()=>o.abort();t.abortSignal?.addEventListener("abort",s),t.abortSignal?.aborted&&o.abort();let i=new Map,a=!1,l=(async()=>{let c=e,u={inputTokens:0,outputTokens:0},p="",m="",f,h=[],y=[],x=!1;try{for(let T=0;T<r.maxSteps&&!o.signal.aborted;T++){if(r.planReclaim){let I=r.planReclaim(c,T);I&&(c=I.conversation)}let w=r.buildStepRequest(c,T),C=!1,R={push:I=>{C=!0,n.push(I)}},k;try{k=await Ru(async()=>{C=!1;try{return await r.executeStep(w,R,o.signal)}catch(I){throw C?new Oq(I):I}},void 0,`${r.providerLabel}.step`)}catch(I){throw I instanceof Oq?I.cause:I}if(u=Uwr(u,k.usage),f=k.rawStopReason,m=k.text||m,r.isMalformedStep?.(k)&&!a&&!o.signal.aborted){a=!0,g.warn(`[${r.providerLabel}] Malformed function call at step ${T+1}/${r.maxSteps}; retrying once.`),c=r.buildMalformedRetryNote?.(c)??c;continue}if(k.toolCalls.length===0){p=k.text||p;break}T===r.maxSteps-1&&(x=!0);let P=[];for(let I of k.toolCalls){h.push(I);let A=r.toolFailureBreaker,M=A?i.get(I.name):void 0;if(A&&M&&M.count>=A.maxRetries){let L={error:`TOOL_PERMANENTLY_FAILED: "${I.name}" has failed ${M.count} times. Last error: ${M.lastError}.`,status:"permanently_failed",do_not_retry:!0};P.push({...I,output:L,error:L.error,permanentlyFailed:!0}),y.push({id:I.id,name:I.name,input:I.args,output:L,error:L.error});continue}let U=t.tools?.[I.name],$=U?.execute?U:r.resolveToolOnMiss?.(I.name)??U;if(!$?.execute){let L=A?{error:`TOOL_NOT_FOUND: "${I.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${I.name}`};P.push({...I,output:L,error:L.error,permanentlyFailed:!!A}),y.push({id:I.id,name:I.name,input:I.args,output:L,error:L.error});continue}try{let L=await $.execute(I.args,{toolCallId:I.id,abortSignal:o.signal});P.push({...I,output:L}),y.push({id:I.id,name:I.name,input:I.args,output:L})}catch(L){let z=L instanceof Error?L.message:String(L);if(A){let F=i.get(I.name)??{count:0,lastError:""};F.count++,F.lastError=z,i.set(I.name,F)}let j={error:z,status:"failed"};P.push({...I,output:j,error:z}),y.push({id:I.id,name:I.name,input:I.args,output:j,error:z})}}c=r.buildToolResultMessages(c,k,P)}let b=r.mapFinishReason(f,x);return{text:p||(x?m:""),toolCalls:h,toolExecutions:y,usage:u,finishReason:b,rawStopReason:f,conversation:c}}catch(b){throw n.error(b),b}finally{n.close(),t.abortSignal?.removeEventListener("abort",s)}})();return{stream:n.iterable,resultPromise:l}}var Oq,WBe=E(()=>{"use strict";Kv();X();Qm();Oq=class extends Error{constructor(t){super(t instanceof Error?t.message:String(t));this.cause=t}cause}});function $wr(r){if(/^(us|ca)-/.test(r))return"us";if(/^(eu|il|me|af)-/.test(r))return"eu";if(/^ap-northeast-[13]$/.test(r))return"jp";if(/^ap-southeast-[246]$/.test(r))return"au";if(/^ap-/.test(r))return"apac"}function Bwr(r){return/^(us|eu|au|jp|apac|global)\./.test(r)}function JBe(r){if(typeof r!="object"||r===null)return!1;let e=r,t=typeof e.name=="string"?e.name:"",n=typeof e.message=="string"?e.message:"";return!/ValidationException/i.test(t)&&!/ValidationException/i.test(n)?!1:/inference profile/i.test(n)&&/on-demand throughput/i.test(n)}function zwr(r,e){if(r.startsWith("arn:")||Bwr(r))return[];let t=[],n=$wr(e);return n&&t.push(`${n}.${r}`),t.push(`${Fwr}.${r}`),t}function YBe(r,e){return`${r}::${e}`}function jwr(r,e){return XBe.get(YBe(e,r))}function Gwr(r,e,t){XBe.set(YBe(e,r),t),g.debug("[Bedrock] Cached inference-profile resolution for subsequent calls",{region:e})}async function Use(r,e,t){let n=jwr(r,e);if(n&&n!==r)return t(n);try{return await t(r)}catch(o){if(!JBe(o))throw o;let s=zwr(r,e);if(s.length===0)throw o;g.warn("[Bedrock] Model requires a cross-region inference profile in this region; retrying with a prefixed id",{region:e,candidates:s.length});for(let i of s)try{let a=await t(i);return Gwr(r,e,i),a}catch(a){if(!JBe(a))throw a}throw o}}var Fwr,XBe,ZBe=E(()=>{"use strict";X();Fwr="global";XBe=new Map});function Nq(){return`tool_${Date.now()}_${Math.random().toString(36).substring(2,11)}`}function eze(r,e){if(r){if(r.toolUse&&r._inputBuffer){try{r.toolUse.input=JSON.parse(r._inputBuffer)}catch{r.toolUse.input={}}delete r._inputBuffer}e&&!r.toolUse&&(r.text=e)}}function tze(r){return r.filter(e=>e.toolUse).map(e=>({id:e.toolUse?.toolUseId??Nq(),name:e.toolUse?.name??"",args:e.toolUse?.input??{}}))}async function qwr(r,e,t){let n=[],o=new Map,s=new Map,i=h=>{let y=o.get(h);return y||(y={},o.set(h,y),n.push(y)),y},a="",l,c=0,u=0,p=0,m=0;if(r.stream)for await(let h of r.stream){if(t.aborted)break;let y=h;if(y.contentBlockStart&&i(y.contentBlockStart.contentBlockIndex??0),y.contentBlockDelta?.delta?.text){let x=y.contentBlockDelta.contentBlockIndex??0,b=y.contentBlockDelta.delta.text;i(x),a+=b,s.set(x,(s.get(x)??"")+b),e.push({content:b})}if(y.contentBlockStart?.start?.toolUse){let x=i(y.contentBlockStart.contentBlockIndex??0);x.toolUse={name:y.contentBlockStart.start.toolUse.name??"",input:{},toolUseId:y.contentBlockStart.start.toolUse.toolUseId??Nq()}}if(y.contentBlockDelta?.delta?.toolUse){let x=i(y.contentBlockDelta.contentBlockIndex??0);x.toolUse??={name:"",input:{},toolUseId:Nq()};let b=y.contentBlockDelta.delta.toolUse.input;typeof b=="string"?x._inputBuffer=(x._inputBuffer??"")+b:typeof b=="object"&&b!==null&&!Array.isArray(b)&&(x.toolUse.input={...x.toolUse.input??{},...b})}if(y.contentBlockStop){let x=y.contentBlockStop.contentBlockIndex??0;eze(o.get(x),s.get(x)??"")}if(y.messageStop){l=y.messageStop.stopReason??"end_turn";continue}if(y.metadata?.usage){c+=y.metadata.usage.inputTokens??0,u+=y.metadata.usage.outputTokens??0,p+=y.metadata.usage.cacheReadInputTokens??0,m+=y.metadata.usage.cacheWriteInputTokens??0;break}}for(let[h,y]of o)eze(y,s.get(h)??"");let f=n.filter(h=>h.text||h.toolUse||h.image||h.document);return{text:a,toolCalls:tze(f),usage:{inputTokens:c,outputTokens:u,cacheReadTokens:p,cacheWriteTokens:m},rawStopReason:l,raw:f}}function Vwr(r){let e=[],t="";for(let n of r.output?.message?.content??[]){let o={};"text"in n&&n.text&&(o.text=n.text,t+=t?` ${n.text}`:n.text),"toolUse"in n&&n.toolUse&&(o.toolUse={toolUseId:n.toolUse.toolUseId??Nq(),name:n.toolUse.name??"",input:n.toolUse.input??{}}),e.push(o)}return{text:t,toolCalls:tze(e),usage:{inputTokens:r.usage?.inputTokens??0,outputTokens:r.usage?.outputTokens??0,cacheReadTokens:r.usage?.cacheReadInputTokens??0,cacheWriteTokens:r.usage?.cacheWriteInputTokens??0},rawStopReason:r.stopReason,raw:e}}function Fse(r){return{providerLabel:"bedrock",maxSteps:r.maxSteps,buildStepRequest(e,t){return{raw:r.buildCommandInput(e,t)}},async executeStep(e,t,n){let o=e.raw;if(!r.streaming){let i=await Use(o.modelId??"",r.region,a=>je(r.client.send(new Nse({...o,modelId:a})),QBe,new Error("Bedrock API call timed out")));if(!i.output?.message)throw new Error("Invalid response structure from Bedrock API");return Vwr(i)}let s=await Use(o.modelId??"",r.region,i=>je(r.client.send(new Lse({...o,modelId:i})),QBe,new Error("Bedrock streaming API call timed out")));return qwr(s,t,n)},buildToolResultMessages(e,t,n){let o={role:"assistant",content:t.raw},s={role:"user",content:n.map(i=>({toolResult:{toolUseId:i.id,content:[{text:i.error?`Error executing tool ${i.name}: ${i.error}`:String(typeof i.output=="string"?i.output:JSON.stringify(i.output))}],status:i.error?"error":"success"}}))};return[...e,o,s]},mapFinishReason(e,t){switch(e){case"end_turn":case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"tool-calls";default:return t?"tool-calls":"stop"}}}}var QBe,rze=E(()=>{"use strict";Mq();Tt();ZBe();QBe=12e4});function $se(r,e,t){return{input:{text:r.input?.text||"",images:r.input?.images,content:r.input?.content,files:r.input?.files,csvFiles:r.input?.csvFiles,pdfFiles:r.input?.pdfFiles,audioFiles:r.input?.audioFiles,videoFiles:r.input?.videoFiles},csvOptions:r.csvOptions,pdfOptions:r.pdfOptions,systemPrompt:r.systemPrompt,conversationHistory:r.conversationMessages,provider:e,model:t,temperature:r.temperature,maxTokens:r.maxTokens,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,context:r.context,fileRegistry:r.fileRegistry}}var nze=E(()=>{"use strict"});var Lq,Bse=E(()=>{"use strict";ac();Lq=Oe.provider});var oze={};de(oze,{Agent:()=>O_r,BedrockClient:()=>Kwr,BedrockRuntimeClient:()=>Jwr,Blob:()=>M_r,Client:()=>L_r,ConverseCommand:()=>Xwr,ConverseStreamCommand:()=>Ywr,Cron:()=>g_r,Dispatcher:()=>D_r,File:()=>P_r,FlowProducer:()=>m_r,FormData:()=>I_r,GoogleAuth:()=>r_r,HTTPException:()=>T_r,Headers:()=>A_r,Hippocampus:()=>i_r,HippocampusConfig:()=>a_r,Hono:()=>v_r,ImageFormat:()=>Zwr,InvokeEndpointCommand:()=>e_r,InvokeEndpointWithResponseStreamCommand:()=>t_r,Job:()=>d_r,ListFoundationModelsCommand:()=>Wwr,MockAgent:()=>$_r,Pool:()=>N_r,Queue:()=>c_r,QueueScheduler:()=>p_r,Request:()=>R_r,Response:()=>k_r,SageMakerRuntimeClient:()=>Qwr,TextToSpeechClient:()=>o_r,VertexAI:()=>n_r,Webhook:()=>s_r,Worker:()=>u_r,convertToHtml:()=>x_r,cors:()=>b_r,createClient:()=>l_r,default:()=>Hwr,extractRawText:()=>y_r,fetch:()=>C_r,getGlobalDispatcher:()=>F_r,interceptors:()=>B_r,logger:()=>S_r,parseBuffer:()=>f_r,request:()=>z_r,secureHeaders:()=>w_r,selectCover:()=>h_r,setGlobalDispatcher:()=>U_r,streamSSE:()=>__r,timeout:()=>E_r});var UE,Oi,Hwr,Kwr,Wwr,Jwr,Xwr,Ywr,Zwr,Qwr,e_r,t_r,r_r,n_r,o_r,s_r,i_r,a_r,l_r,c_r,u_r,d_r,p_r,m_r,g_r,f_r,h_r,y_r,x_r,v_r,b_r,T_r,S_r,w_r,__r,E_r,C_r,R_r,k_r,A_r,I_r,P_r,M_r,O_r,N_r,L_r,D_r,U_r,F_r,$_r,B_r,z_r,sze=E(()=>{UE={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:UE.get}):new Proxy(function(...t){return new Proxy({},{get:UE.get})},{get:UE.get,apply(t,n,o){return new Proxy({},{get:UE.get})},construct(t,n){return new Proxy({},{get:UE.get})}})}},Oi=new Proxy({},UE),Hwr=Oi,{BedrockClient:Kwr,ListFoundationModelsCommand:Wwr,BedrockRuntimeClient:Jwr,ConverseCommand:Xwr,ConverseStreamCommand:Ywr,ImageFormat:Zwr}=Oi,{SageMakerRuntimeClient:Qwr,InvokeEndpointCommand:e_r,InvokeEndpointWithResponseStreamCommand:t_r}=Oi,{GoogleAuth:r_r,VertexAI:n_r,TextToSpeechClient:o_r}=Oi,{Webhook:s_r}=Oi,{Hippocampus:i_r,HippocampusConfig:a_r}=Oi,{createClient:l_r}=Oi,{Queue:c_r,Worker:u_r,Job:d_r,QueueScheduler:p_r,FlowProducer:m_r}=Oi,{Cron:g_r}=Oi,{parseBuffer:f_r,selectCover:h_r}=Oi,{extractRawText:y_r,convertToHtml:x_r}=Oi,{Hono:v_r}=Oi,{cors:b_r,HTTPException:T_r,logger:S_r,secureHeaders:w_r,streamSSE:__r,timeout:E_r}=Oi,C_r=globalThis.fetch,R_r=globalThis.Request,k_r=globalThis.Response,A_r=globalThis.Headers,I_r=globalThis.FormData,P_r=globalThis.File,M_r=globalThis.Blob,O_r=Oi.Agent,N_r=Oi.Pool,L_r=Oi.Client,D_r=Oi.Dispatcher,U_r=()=>{},F_r=()=>Oi,$_r=Oi.MockAgent,B_r={redirect:()=>r=>r,retry:()=>r=>r},z_r=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});async function Dq(){return await Promise.resolve().then(()=>(sze(),oze))}var zse=E(()=>{"use strict"});var jse,ize=E(()=>{"use strict";Mq();Qr();qw();eu();cs();WBe();rze();Dt();ea();Tt();X();dg();qI();nze();Ea();gr();Bse();zse();jse=class r extends oo{bedrockClient;conversationHistory=[];region;static extractRegionFromArn(e){return e?e.match(/^arn:aws[a-z0-9-]*:bedrock:([^:]+):/)?.[1]??null:null}constructor(e,t,n,o){super(e,"bedrock",t);let s=e||process.env.BEDROCK_MODEL||this.modelName,i=r.extractRegionFromArn(s);this.region=o?.region||n||i||process.env.AWS_REGION||"us-east-1",g.debug("[AmazonBedrockProvider] Starting constructor with extensive logging for debugging"),g.debug(`[AmazonBedrockProvider] Environment check: AWS_REGION=${process.env.AWS_REGION||"undefined"}, AWS_ACCESS_KEY_ID=${process.env.AWS_ACCESS_KEY_ID?"SET":"undefined"}, AWS_SECRET_ACCESS_KEY=${process.env.AWS_SECRET_ACCESS_KEY?"SET":"undefined"}`);try{g.debug("[AmazonBedrockProvider] Creating BedrockRuntimeClient with clean configuration"),this.bedrockClient=new Ose({region:this.region,...o?.accessKeyId&&o?.secretAccessKey?{credentials:{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,...o.sessionToken?{sessionToken:o.sessionToken}:{}}}:{}}),g.debug(`[AmazonBedrockProvider] Successfully created BedrockRuntimeClient with model: ${this.modelName}, region: ${this.region}`)}catch(a){throw g.error("[AmazonBedrockProvider] CRITICAL: Failed to initialize BedrockRuntimeClient:",a),a}}async performInitialHealthCheck(){let{BedrockClient:e,ListFoundationModelsCommand:t}=await Dq(),n=new e({region:this.region});try{g.debug("[AmazonBedrockProvider] Starting initial health check to validate credentials and connectivity");let o=new t({}),s=Date.now();await n.send(o);let i=Date.now()-s;g.debug(`[AmazonBedrockProvider] Health check PASSED - credentials valid, connectivity good, responseTime: ${i}ms`)}catch(o){let s=o instanceof Error?o.message:String(o);g.error("[AmazonBedrockProvider] Health check FAILED - this will cause production failures:",{error:s,errorType:o instanceof Error?o.constructor.name:"Unknown",region:process.env.AWS_REGION||"us-east-1",hasAccessKey:!!process.env.AWS_ACCESS_KEY_ID,hasSecretKey:!!process.env.AWS_SECRET_ACCESS_KEY})}finally{try{n.destroy()}catch{}}}getAISDKModel(){throw new Error("AmazonBedrockProvider does not use AI SDK models")}getProviderName(){return"bedrock"}getDefaultModel(){return process.env.BEDROCK_MODEL||"anthropic.claude-sonnet-4-6"}getDefaultEmbeddingModel(){return process.env.BEDROCK_EMBEDDING_MODEL||process.env.AWS_EMBEDDING_MODEL||"amazon.titan-embed-text-v2:0"}async generate(e){g.debug("[AmazonBedrockProvider] generate() called with conversation management");let t=Date.now(),n=typeof e=="string"?{prompt:e}:e;this.conversationHistory=[];let o=n.input;if(!!(o?.images?.length||o?.content?.length||o?.files?.length||o?.csvFiles?.length||o?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input in generate(), using multimodal message builder",{hasImages:!!o?.images?.length,imageCount:o?.images?.length||0,hasContent:!!o?.content?.length,contentCount:o?.content?.length||0,hasFiles:!!o?.files?.length,fileCount:o?.files?.length||0,hasCSVFiles:!!o?.csvFiles?.length,csvFileCount:o?.csvFiles?.length||0,hasPDFFiles:!!o?.pdfFiles?.length,pdfFileCount:o?.pdfFiles?.length||0});let m=$se(n,this.providerName,this.modelName),f=await T_(m,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(f)}else{g.debug("[AmazonBedrockProvider] Text-only input in generate(), using simple message builder");let p={role:"user",content:[{text:n.prompt}]};this.conversationHistory.push(p)}g.debug(`[AmazonBedrockProvider] Starting conversation with ${this.conversationHistory.length} message(s)`);let i,a,l,c;try{({text:i,usage:a,finishReason:l,rawFinishReason:c}=await this.conversationLoop(n))}catch(p){let m=this.neurolink?.getEventEmitter();throw m&&m.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:"error"},success:!1,error:p instanceof Error?p.message:String(p)}),p}let u=this.neurolink?.getEventEmitter();return u&&u.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.providerName,finishReason:l},success:!0}),{content:i,usage:a,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),...l!==void 0&&{finishReason:l},...c!==void 0&&{rawFinishReason:c}}}async conversationLoop(e){let t=e.maxSteps||Jo,n=await this.resolveTurnTools(e.tools,e.disableTools),o=this.formatToolsForBedrock(n),s=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converse"),i=Fse({client:this.bedrockClient,streaming:!1,region:this.region,maxSteps:t,buildCommandInput:a=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(a),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...s.temperature!==void 0&&{temperature:s.temperature}},...o?{toolConfig:o}:{}})});try{let{resultPromise:a}=Dse(i,this.conversationHistory,{tools:this.toEngineTools(n),abortSignal:e.abortSignal}),l=await a;this.conversationHistory=l.conversation;let c=l.usage.inputTokens,u=l.usage.outputTokens,p=l.usage.cacheReadTokens??0,m=l.usage.cacheWriteTokens??0;return{text:l.text||"",usage:{input:c,output:u,total:c+p+m+u,...p>0&&{cacheReadTokens:p},...m>0&&{cacheCreationTokens:m}},finishReason:l.finishReason,rawFinishReason:l.rawStopReason}}catch(a){throw g.error("[AmazonBedrockProvider] Error in conversation loop:",a),this.handleProviderError(a)}}convertToAWSMessages(e){return e.map(t=>({role:t.role,content:t.content.map(n=>n.text?{text:n.text}:n.image?{image:n.image}:n.document?{document:n.document}:n.toolUse?{toolUse:{toolUseId:n.toolUse.toolUseId,name:n.toolUse.name,input:n.toolUse.input}}:n.toolResult?{toolResult:{toolUseId:n.toolResult.toolUseId,content:n.toolResult.content,status:n.toolResult.status}}:{text:""})}))}async executeSingleTool(e,t,n,o){return Lq.startActiveSpan("bedrock.tool.execute",{kind:br.CLIENT,attributes:{"gen_ai.tool.name":t,"gen_ai.system":"aws.bedrock"}},async s=>{try{if(g.debug(`[AmazonBedrockProvider] Executing single tool: ${t}`,{args:n}),!e[t])throw new Error(`Tool not found: ${t}`);let i=e[t];if(!i||!i.execute)throw new Error(`Tool ${t} does not have execute method`);let a=n||{};t==="list_directory"&&!a.path&&(a.path=".",g.debug("[AmazonBedrockProvider] Added default path '.' for list_directory tool")),g.debug("[AmazonBedrockProvider] Tool input parameters:",a);let l={};for(let[p,m]of Object.entries(a))(m===null||typeof m=="string"||typeof m=="number"||typeof m=="boolean"||typeof m=="object"&&m!==null)&&(l[p]=m);let c=await i.execute(l);g.debug("[AmazonBedrockProvider] Tool execution result:",{toolName:t,result:c});let u;if(c&&typeof c=="object"&&"success"in c)if(c.success&&c.data!==void 0)typeof c.data=="string"?u=c.data:typeof c.data=="object"?u=JSON.stringify(c.data,null,2):u=String(c.data);else if(c.error){let p=typeof c.error=="string"?c.error:c.error.message||"Tool execution failed";throw new Error(p)}else u="";else typeof c=="string"?u=c:typeof c=="object"?u=JSON.stringify(c,null,2):u=String(c);return s.setStatus({code:ze.OK}),u}catch(i){throw g.error("[AmazonBedrockProvider] Tool execution error:",{toolName:t,error:i}),s.setStatus({code:ze.ERROR,message:i.message}),s.recordException(i),i}finally{s.end()}})}async resolveTurnTools(e,t){if(t)return{};let n=e??await this.getAllTools();return this.convertAISDKToolsToToolDefinitions(n)}toEngineTools(e){let t={};for(let n of Object.keys(e))t[n]={execute:o=>this.executeSingleTool(e,n,o)};return t}convertAISDKToolsToToolDefinitions(e){let t={};for(let[n,o]of Object.entries(e))if("description"in o&&o.description){let i=o.parameters??o.inputSchema;t[n]={description:o.description,parameters:i,execute:async a=>{if("execute"in o&&o.execute)return{success:!0,data:await o.execute(a,{toolCallId:`tool_${Date.now()}`,messages:[]})};throw new Error(`Tool ${n} has no execute method`)}}}return t}formatToolsForBedrock(e){if(!e||Object.keys(e).length===0)return null;let t=Object.entries(e).map(([n,o])=>{let s;return o.parameters&&typeof o.parameters=="object"?"_def"in o.parameters?s=xn(o.parameters):s=o.parameters:s={type:"object",properties:{},required:[]},(!s.type||s.type!=="object")&&(s={type:"object",properties:s.properties||{},required:s.required||[]}),{toolSpec:{name:n,description:o.description,inputSchema:{json:s}}}});return g.debug(`[AmazonBedrockProvider] Formatted ${t.length} tools for Bedrock`),{tools:t}}convertToBedrockMessages(e){return e.map(t=>{let n={role:t.role==="system"?"user":t.role,content:[]};return typeof t.content=="string"?n.content.push({text:t.content}):t.content.forEach(o=>{if(o.type==="text"&&o.text)n.content.push({text:o.text});else if(o.type==="image"&&o.image){let s=typeof o.image=="string"?Buffer.from(o.image.replace(/^data:image\/\w+;base64,/,""),"base64"):o.image,i=o.mimeType?.split("/")[1]||"png";i==="jpg"&&(i="jpeg"),n.content.push({image:{format:i==="jpeg"?DE.JPEG:i==="png"?DE.PNG:i==="gif"?DE.GIF:DE.WEBP,source:{bytes:s}}})}else if(o.type==="document"||o.type==="pdf"||o.type==="file"&&o.mimeType?.toLowerCase().startsWith("application/pdf")){let s;if(typeof o.data=="string"){let a=o.data.replace(/^data:application\/pdf;base64,/i,"");s=Buffer.from(a,"base64")}else s=o.data;let i=typeof o.name=="string"&&o.name?wd.basename(o.name):"document-pdf";i=i.replace(/\.[^.]+$/,""),i=i.replace(/[^a-zA-Z0-9\s\-()[\]]/g,"-"),i=i.replace(/-+/g,"-").trim().replace(/^-+|-+$/g,""),i=i||"document",n.content.push({document:{format:"pdf",name:i,source:{bytes:s}}})}}),n})}getBedrockClient(){return this.bedrockClient}async executeStream(e){return g.debug("[TRACE] executeStream ENTRY - starting streaming attempt"),g.info("[AmazonBedrockProvider] Attempting real streaming with ConverseStreamCommand"),Lq.startActiveSpan("bedrock.stream",{kind:br.CLIENT,attributes:{"gen_ai.system":"aws.bedrock","gen_ai.request.model":this.modelName||this.getDefaultModel(),"gen_ai.operation.name":"stream"}},async t=>{try{if(g.debug("[TRACE] executeStream TRY block - about to call streamingConversationLoop"),this.conversationHistory=[],!!(e.input?.images?.length||e.input?.content?.length||e.input?.files?.length||e.input?.csvFiles?.length||e.input?.pdfFiles?.length)){g.debug("[AmazonBedrockProvider] Detected multimodal input, using multimodal message builder",{hasImages:!!e.input?.images?.length,imageCount:e.input?.images?.length||0,hasContent:!!e.input?.content?.length,contentCount:e.input?.content?.length||0,hasFiles:!!e.input?.files?.length,fileCount:e.input?.files?.length||0,hasCSVFiles:!!e.input?.csvFiles?.length,csvFileCount:e.input?.csvFiles?.length||0,hasPDFFiles:!!e.input?.pdfFiles?.length,pdfFileCount:e.input?.pdfFiles?.length||0});let s=$se(e,this.providerName,this.modelName),i=await T_(s,this.providerName,this.modelName);this.conversationHistory=this.convertToBedrockMessages(i)}else{g.debug("[AmazonBedrockProvider] Text-only input, using simple message builder");let s={role:"user",content:[{text:e.input.text}]};this.conversationHistory.push(s)}g.debug(`[AmazonBedrockProvider] Starting streaming conversation with ${this.conversationHistory.length} message(s)`),g.debug("[TRACE] executeStream - calling streamingConversationLoop NOW");let o=await this.streamingConversationLoop(e,t);return g.debug("[TRACE] executeStream - streamingConversationLoop SUCCESS, returning result"),t.setStatus({code:ze.OK}),t.end(),o}catch(n){g.debug("[TRACE] executeStream CATCH - error caught from streamingConversationLoop");let o=n,s=o?.name==="AccessDeniedException"||o?.name==="UnauthorizedOperation"||o?.message?.includes("bedrock:InvokeModelWithResponseStream")||o?.message?.includes("streaming")||o?.message?.includes("ConverseStream");if(g.debug("[TRACE] executeStream CATCH - checking if permission error"),g.debug(`[TRACE] executeStream CATCH - isPermissionError=${s}`),s){g.debug("[TRACE] executeStream CATCH - PERMISSION ERROR DETECTED, starting fallback"),g.warn(`[AmazonBedrockProvider] Streaming permissions not available, falling back to generate method: ${o.message}`),t.addEvent("stream.fallback_to_generate",{reason:o.message});let i=await this.generate({prompt:e.input.text,input:e.input,maxTokens:e.maxTokens,temperature:e.temperature,systemPrompt:e.systemPrompt});if(!i)throw t.setStatus({code:ze.ERROR,message:"Generate method returned null result"}),t.end(),new Error("Generate method returned null result");t.setAttribute("gen_ai.response.stop_reason","fallback_end_turn"),t.setStatus({code:ze.OK}),t.end();let a=new ReadableStream({start(c){let p=(i.content||"").split(/(\s+)/),m="";for(let f=0;f<p.length;f++)m+=p[f],(f===p.length-1||m.length>50||/[.!?;,]\s*$/.test(m))&&m.length>0&&(c.enqueue({content:m}),m="");m.length>0&&c.enqueue({content:m}),c.close()}});return{stream:{async*[Symbol.asyncIterator](){let c=a.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u)break;yield p}}finally{c.releaseLock()}}},usage:i.usage,model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),metadata:{fallback:!0}}}throw t.setStatus({code:ze.ERROR,message:o instanceof Error?o.message:String(o)}),t.recordException(o instanceof Error?o:new Error(String(o))),t.end(),n}})}async streamingConversationLoop(e,t){let n=Date.now(),o=e.maxSteps||Jo,s=await this.resolveTurnTools(e.tools,e.disableTools),i=this.formatToolsForBedrock(s),a=_a(this.providerName,this.modelName||this.getDefaultModel(),{temperature:e.temperature??.7},"bedrock.converseStream"),l=Fse({client:this.bedrockClient,streaming:!0,region:this.region,maxSteps:o,buildCommandInput:P=>({modelId:this.modelName||this.getDefaultModel(),messages:this.convertToAWSMessages(P),system:[{text:e.systemPrompt||"You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information."}],inferenceConfig:{maxTokens:e.maxTokens,...a.temperature!==void 0&&{temperature:a.temperature}},...i?{toolConfig:i}:{}})}),c=!1,u,p=new Promise(P=>{u=()=>{c=!0,P()}}),m={...l,executeStep:async(P,I,A)=>{let M=await l.executeStep(P,I,A);return u(),M}};t.addEvent("stream.api_call",{"bedrock.tool_count":i?.tools?.length??0});let{stream:f,resultPromise:h}=Dse(m,this.conversationHistory,{tools:this.toEngineTools(s),abortSignal:e.abortSignal}),y=h.then(P=>({result:P,error:void 0}),P=>({result:void 0,error:P}));if(await Promise.race([p,y]),!c){let P=await y;if(P.error)throw P.error}let x=this.neurolink?.getEventEmitter(),b=this,T={startTime:n,streamId:`bedrock-${Date.now()}`},w,C=new Promise(P=>{w=P}),R=P=>{let I=P?.inputTokens??0,A=P?.outputTokens??0,M=P?.cacheReadTokens??0,U=P?.cacheWriteTokens??0;return{input:I,output:A,total:I+M+U+A,...M>0&&{cacheReadTokens:M},...U>0&&{cacheCreationTokens:U}}};return y.then(P=>{w(Hp(this.providerName,this.modelName||this.getDefaultModel(),{usage:R(P.result?.usage)},Date.now()-n,{requestId:`bedrock-stream-${Date.now()}`,streamingMode:!0}))}),{stream:{async*[Symbol.asyncIterator](){let P=!1;try{yield*f}catch(I){throw P=!0,I}finally{let I=await y;I.error&&(P=!0);let A=R(I.result?.usage);I.result&&(b.conversationHistory=I.result.conversation,T.finishReason=I.result.finishReason,T.rawFinishReason=I.result.rawStopReason,t.setAttribute("gen_ai.response.stop_reason",I.result.rawStopReason??"unknown")),x&&x.emit("generation:end",{provider:b.providerName,responseTime:Date.now()-n,timestamp:Date.now(),result:{content:"",usage:A,model:b.modelName||b.getDefaultModel(),provider:b.providerName,finishReason:P?"error":I.result?.rawStopReason},success:!P})}}},model:this.modelName||this.getDefaultModel(),provider:this.getProviderName(),analytics:C,metadata:T}}async checkBedrockHealth(){let e=new AbortController,t=setTimeout(()=>e.abort(),1e4),{BedrockClient:n,ListFoundationModelsCommand:o}=await Dq(),s=new n({region:process.env.AWS_REGION||"us-east-1"});try{g.debug("[AmazonBedrockProvider] Starting health check...");let i=new o({}),l=(await s.send(i,{abortSignal:e.signal})).modelSummaries||[],c=l.filter(u=>u.modelLifecycle?.status==="ACTIVE");if(g.debug(`[AmazonBedrockProvider] Health check passed - Found ${c.length} active models out of ${l.length} total models`),c.length===0)throw new Error("No active foundation models available in the region")}catch(i){clearTimeout(t);let a=i;if(wr(i))throw new Error("Bedrock health check timed out after 10 seconds",{cause:i});let l=typeof a.message=="string"?a.message:"";throw l.includes("UnauthorizedOperation")||l.includes("AccessDenied")?new Error("Bedrock access denied. Check your AWS credentials and IAM permissions for bedrock:ListFoundationModels",{cause:i}):a.code==="ECONNREFUSED"||a.code==="ENOTFOUND"?new Error("Unable to connect to Bedrock service. Check your network connectivity and AWS region configuration",{cause:i}):(g.error("[AmazonBedrockProvider] Health check failed:",i),new Error(`Bedrock health check failed: ${l||"Unknown error"}`,{cause:i}))}finally{clearTimeout(t);try{s.destroy()}catch{}}}formatProviderError(e){return en(e,[{match:n=>/AccessDeniedException/i.test(n.message),errorClass:Mt,message:"AWS Bedrock access denied. Check your credentials and permissions."},{match:n=>n.errorName==="ThrottlingException"||n.errorCode==="ThrottlingException",errorClass:qr,message:n=>`Bedrock rate limit (throttled): ${n.message}`},{match:n=>/ValidationException/i.test(n.message),errorClass:mt,message:n=>`Validation error: ${n.message}`},{match:()=>!0,errorClass:mt,message:n=>`AWS Bedrock error: ${n.message}`}],this.providerName,this.modelName)}async embed(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating embedding",{provider:this.providerName,model:n,textLength:e.length});try{let{InvokeModelCommand:o}=await Promise.resolve().then(()=>(Mq(),KBe)),s=JSON.stringify({inputText:e}),i=new o({modelId:n,contentType:"application/json",accept:"application/json",body:s}),a=await je(this.bedrockClient.send(i),6e4,new Error("Bedrock embedding API call timed out")),l=JSON.parse(new TextDecoder().decode(a.body));if(!l.embedding||!Array.isArray(l.embedding))throw new Error("Invalid embedding response from Bedrock");return g.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:l.embedding.length}),l.embedding}catch(o){throw g.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:e.length}),this.handleProviderError(o)}}async embedMany(e,t){let n=t||"amazon.titan-embed-text-v2:0";g.debug("Generating batch embeddings",{provider:this.providerName,model:n,count:e.length});try{let o=await Promise.all(e.map(s=>this.embed(s,n)));return g.debug("Batch embeddings generated successfully",{provider:this.providerName,model:n,count:o.length,embeddingDimension:o[0]?.length}),o}catch(o){throw g.error("Batch embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,count:e.length}),this.handleProviderError(o)}}}});var aze={};de(aze,{AmazonBedrockProvider:()=>jse,bedrockTracer:()=>Lq,loadBedrockControl:()=>Dq});var lze=E(()=>{"use strict";ize();Bse();zse()});var cze={};de(cze,{AzureOpenAIProvider:()=>Gse});var Gse,uze=E(()=>{"use strict";Dt();X();ea();Ko();Kp();hc();Ag();Gse=class extends $n{azureDeployment;azureApiVersion;azureResourceOrigin;azureDeploymentPathPrefix;useMaxCompletionTokensOverride;constructor(e,t,n,o){let s=o?.apiKey||process.env.AZURE_OPENAI_API_KEY||"",i=process.env.AZURE_OPENAI_ENDPOINT||"",a;if(i)try{a=new URL(i.includes("://")?i:`https://${i}`)}catch{a=void 0}let l=a?.hostname??"",c=a?.pathname&&a.pathname!=="/"?a.pathname.replace(/\/+$/,""):"",u=/\.(openai|cognitiveservices)\.azure\.com$/.test(l),p;u?p="/openai":p=/\/openai(?:\/v\d+)?$/.test(c)?c:`${c}/openai`;let m=a?.origin??"",f=o?.deploymentName||e||process.env.AZURE_OPENAI_MODEL||process.env.AZURE_OPENAI_DEPLOYMENT||process.env.AZURE_OPENAI_DEPLOYMENT_ID||"gpt-4o",h=o?.apiVersion||process.env.AZURE_API_VERSION||"2025-04-01-preview",y=process.env.AZURE_OPENAI_USE_MAX_COMPLETION_TOKENS,x=o?.useMaxCompletionTokens??(y===void 0?void 0:/^(1|true|yes)$/i.test(y));s||an(uye()),m||an(dye()),super("azure",e,t,{baseURL:m,apiKey:s}),this.azureDeployment=f,this.azureApiVersion=h,this.azureResourceOrigin=m,this.azureDeploymentPathPrefix=p,this.useMaxCompletionTokensOverride=x,g.shouldLog("debug")&&g.debug("Azure OpenAI Provider initialized",jB({deployment:this.azureDeployment,resourceOrigin:this.azureResourceOrigin,deploymentPathPrefix:this.azureDeploymentPathPrefix,apiVersion:this.azureApiVersion,provider:"azure"}))}suppressResponseFormatWithTools(){return!1}getProviderName(){return"azure"}getDefaultModel(){return this.azureDeployment}formatProviderError(e){let t=[{match:n=>/401/.test(n.message),errorClass:Mt,message:"Invalid Azure OpenAI API key or endpoint."},...tn];return en(e,t,"azure",this.modelName)}getChatCompletionsURL(e){let t=e||this.azureDeployment,n=this.azureDeploymentPathPrefix.replace(/\/+$/,"");return`${this.azureResourceOrigin}${n}/deployments/${t}/chat/completions?api-version=${this.azureApiVersion}`}getAuthHeaders(){return{"api-key":this.config.apiKey}}adjustRequestBody(e,t){let n=this.useMaxCompletionTokensOverride??E1e(t);return e.max_tokens!==void 0&&n?{...e,max_completion_tokens:e.max_tokens,max_tokens:void 0}:e}}});function dze(r){return r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70?"image/gif":"image/png"}var pze=E(()=>{"use strict"});function qse(r){return r.map(e=>typeof e.content=="string"?{role:e.role,content:e.content}:{role:e.role,content:e.content.map(t=>t.type==="image"||t.type==="document"?{type:t.type,media_type:t.source.media_type,base64_chars:t.source.data.length}:t)})}var mze=E(()=>{"use strict"});var Uq,gze=E(()=>{Uq=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}});var fze=E(()=>{fo()});function Fq(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Vse,Hse,Kse=E(()=>{fze();Vse=r=>(Vse=Array.isArray,Vse(r)),Hse=Vse});function*j_r(r){if(!r)return;if(hze in r){let{values:n,nulls:o}=r;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Hse(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=Hse(n[1])?n[1]:[n[1]],i=!1;for(let a of s)a!==void 0&&(e&&!i&&(i=!0,yield[o,null]),yield[o,a])}}var hze,yze,xze=E(()=>{Kse();hze=Symbol.for("brand.privateNullableHeaders");yze=r=>{let e=new Headers,t=new Set;for(let n of r){let o=new Set;for(let[s,i]of j_r(n)){let a=s.toLowerCase();o.has(a)||(e.delete(s),o.add(a)),i===null?(e.delete(s),t.add(a)):(e.append(s,i),t.delete(a))}}return{[hze]:!0,values:e,nulls:t}}});function V_r(r){let e=new dm(r);return delete e.batches,e}function H_r(r){let e=new ti(r);return delete e.messages.batches,e}var G_r,q_r,$q,Wse=E(()=>{aM();use();P_();gze();Kse();xze();aM();G_r="vertex-2023-10-16",q_r=new Set(["/v1/messages","/v1/messages?beta=true"]),$q=class extends Jn{constructor({baseURL:e=Uq("ANTHROPIC_VERTEX_BASE_URL"),region:t=Uq("CLOUD_ML_REGION")??null,projectId:n=Uq("ANTHROPIC_VERTEX_PROJECT_ID")??null,...o}={}){if(!t)throw new Error("No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.");if(!e)switch(t){case"global":e="https://aiplatform.googleapis.com/v1";break;case"us":e="https://aiplatform.us.rep.googleapis.com/v1";break;case"eu":e="https://aiplatform.eu.rep.googleapis.com/v1";break;default:e=`https://${t}-aiplatform.googleapis.com/v1`}if(super({baseURL:e,...o}),this.messages=V_r(this),this.beta=H_r(this),this.region=t,this.projectId=n,this.accessToken=o.accessToken??null,o.authClient&&o.googleAuth)throw new Error("You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.");o.authClient?this._authClientPromise=Promise.resolve(o.authClient):(this._auth=o.googleAuth??new iP({scopes:"https://www.googleapis.com/auth/cloud-platform"}),this._authClientPromise=this._auth.getClient())}validateHeaders(){}async prepareOptions(e){let t=await this._authClientPromise,n=await t.getRequestHeaders(),o=t.projectId??n["x-goog-user-project"];!this.projectId&&o&&(this.projectId=o),e.headers=yze([n,e.headers])}async buildRequest(e){if(Fq(e.body)&&(e.body={...e.body}),Fq(e.body)&&(e.body.anthropic_version||(e.body.anthropic_version=G_r)),q_r.has(e.path)&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");if(!Fq(e.body))throw new Error("Expected request body to be an object for post /v1/messages");let t=e.body.model;e.body.model=void 0;let o=e.body.stream??!1?"streamRawPredict":"rawPredict";e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${t}:${o}`}if(e.path==="/v1/messages/count_tokens"||e.path=="/v1/messages/count_tokens?beta=true"&&e.method==="post"){if(!this.projectId)throw new Error("No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.");e.path=`/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`}return super.buildRequest(e)}}});var Jse={};de(Jse,{AnthropicVertex:()=>$q,BaseAnthropic:()=>Jn,default:()=>$q});var Xse=E(()=>{Wse();Wse()});async function K_r(){return Yse||(Yse=await Promise.resolve().then(()=>(Xse(),Jse))),Yse}function J_r(r){let e=[],t=new Map,n=0,o=s=>{let i=`${n}:${s??"x"}`,a=t.get(i);return a||(a={type:"tool_step",callParts:[],resultParts:[]},t.set(i,a),e.push(a)),a};for(let s of r){if(s.role==="tool_call"){o(s.metadata?.stepIndex).callParts.push({name:s.tool||"unknown",input:s.args||{}});continue}if(s.role==="tool_result"){o(s.metadata?.stepIndex).resultParts.push(s.content&&s.content.length>0?s.content:"(no output)");continue}let i=s.role==="assistant"?"assistant":s.role==="user"?"user":null;!i||!s.content||s.content.trim().length===0||(n++,e.push({type:"regular",role:i,parts:[s.content]}))}return e}function Zse(r,e,t){let n=r[r.length-1];n&&n.role===e&&Array.isArray(n.content)?n.content.push(...t):r.push({role:e,content:[...t]})}function X_r(r,e){let t=r.callParts,n=r.resultParts,o=Math.min(t.length,n.length);(o!==t.length||o!==n.length)&&g.debug("[GoogleVertex] Unbalanced tool step in Claude history replay",{calls:t.length,results:n.length,paired:o});let s=[],i=[];for(let a=0;a<o;a++){let l=`hist_${e}_${a}`;s.push({type:"tool_use",id:l,name:t[a].name,input:t[a].input}),i.push({type:"tool_result",tool_use_id:l,content:n[a]})}return{uses:s,results:i}}function Y_r(r){let e=t=>Array.isArray(t.content)&&t.content.length>0&&t.content.every(n=>n.type==="tool_result");for(;r.length>0&&(r[0].role!=="user"||e(r[0]));)r.shift()}function eie(r){let e=[],t=0;for(let n of J_r(r)){if(n.type==="regular"){Zse(e,n.role==="assistant"?"assistant":"user",[{type:"text",text:String(n.parts[0]??"")}]);continue}let{uses:o,results:s}=X_r(n,t);o.length!==0&&(t++,Zse(e,"assistant",o),Zse(e,"user",s))}if(Y_r(e),g.shouldLog("debug")){let n=e.flatMap(o=>Array.isArray(o.content)?o.content:[]);g.debug("[GoogleVertex] Replayed Claude history with tool turns",{historyMessages:e.length,toolUseBlocks:n.filter(o=>o.type==="tool_use").length,toolResultBlocks:n.filter(o=>o.type==="tool_result").length})}return e}function tie(r,e){let t=r[r.length-1];if(t&&t.role==="user"){let n=Array.isArray(t.content)?t.content:[{type:"text",text:t.content}],o=Array.isArray(e)?e:[{type:"text",text:e}];t.content=[...n,...o];return}r.push({role:"user",content:e})}function py(r){if(!r||typeof r!="object")return;let e=["additionalProperties","default","$schema","$id","$ref","definitions","$defs","examples","errorMessage"];for(let n of e)n in r&&delete r[n];typeof r.exclusiveMinimum=="boolean"&&(r.exclusiveMinimum===!0&&typeof r.minimum=="number"?(r.exclusiveMinimum=r.minimum,delete r.minimum):delete r.exclusiveMinimum),typeof r.exclusiveMaximum=="boolean"&&(r.exclusiveMaximum===!0&&typeof r.maximum=="number"?(r.exclusiveMaximum=r.maximum,delete r.maximum):delete r.exclusiveMaximum);let t=2147483647;if(typeof r.maximum=="number"&&r.maximum>t&&delete r.maximum,typeof r.minimum=="number"&&r.minimum<-t&&delete r.minimum,r.properties&&typeof r.properties=="object")for(let n of Object.values(r.properties))n&&typeof n=="object"&&py(n);if(r.items&&typeof r.items=="object")if(Array.isArray(r.items))for(let n of r.items)n&&typeof n=="object"&&py(n);else py(r.items);for(let n of["allOf","anyOf","oneOf"])if(Array.isArray(r[n]))for(let o of r[n])o&&typeof o=="object"&&py(o)}function vze(r,e,t){let n=Zj({contents:r,availableInputTokens:mi("vertex",e),provider:"vertex",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=>{if(!("functionResponse"in c))return c;let u=c.functionResponse,p=JSON.stringify(u.response)??"";return p.length<=eEr?c:{functionResponse:{name:u.name,response:{result:cP(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:Yj}]})}return r.length=0,r.push(...i),!0}function bze(r,e,t){let n=Rq({conversation:r,availableInputTokens:mi("vertex",e),fixedOverheadTokens:0,provider:"vertex",observedPromptTokens:t,observedDescribesCurrentPayload:!0});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.content)){i.push({...l,content:l.content.map(c=>{if(c.type!=="tool_result")return c;let u=typeof c.content=="string"?c.content:JSON.stringify(c.content)??"";return{...c,content:Cq(u)}})});continue}i.push(l)}if(o.size>0){let a=i.findIndex(l=>Array.isArray(l.content)&&l.content.some(c=>c.type==="tool_use"||c.type==="tool_result"));a<0&&(a=Math.min(1,i.length)),i.splice(a,0,{role:"user",content:[{type:"text",text:Eq}]})}return r.length=0,r.push(...i),!0}var Yse,W_r,rie,Bq,zq,gM,FE,Z_r,Q_r,Qse,eEr,nie,oie=E(()=>{"use strict";ro();Qr();eu();Pz();tG();tte();cs();Ph();nz();Hr();so();Dt();ea();Tt();_se();qte();qI();X();Ere();bse();zj();pze();jj();Ko();Ea();Cre();O_();_l();$re();Kv();rG();$d();Xw();ac();gr();Dd();Kp();cI();dg();mze();YI();Yse=null;W_r=()=>!0;rie=()=>an(zL()),Bq=()=>process.env.GOOGLE_CLOUD_LOCATION||process.env.VERTEX_LOCATION||process.env.GOOGLE_VERTEX_LOCATION||"us-central1",zq=(r,e)=>{let t=e||Bq();if(!r)return t;let n=r.toLowerCase();return n.startsWith("gemini-")||n.includes("/gemini-")||S2.some(s=>n===s.toLowerCase()||n.includes(s.toLowerCase())||s.toLowerCase().includes(n))?process.env.GOOGLE_VERTEX_GLOBAL_LOCATION||"global":t},gM=zq,FE=()=>process.env.VERTEX_MODEL||"gemini-2.5-flash",Z_r=()=>!!(process.env.GOOGLE_APPLICATION_CREDENTIALS_NEUROLINK||process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.GOOGLE_SERVICE_ACCOUNT_KEY||process.env.GOOGLE_AUTH_CLIENT_EMAIL&&process.env.GOOGLE_AUTH_PRIVATE_KEY),Q_r=async(r,e)=>{let t=r||Bq();return{projectId:rie(),region:t,...e!==void 0&&{timeout:e},maxRetries:0}},Qse=r=>r.toLowerCase().includes("claude"),eEr=2048;nie=class r extends oo{projectId;location;registeredTools=new Map;toolContext={};static modelConfigCache=new Map;static modelConfigCacheTime=0;static CACHE_DURATION=300*1e3;static MAX_CACHE_SIZE=50;static maxTokensCache=new Map;static maxTokensCacheTime=0;constructor(e,t,n,o,s){super(e,"vertex",n),s&&(s.projectId&&(process.env.GOOGLE_CLOUD_PROJECT=String(s.projectId)),s.location&&(process.env.GOOGLE_CLOUD_LOCATION=String(s.location)),s.apiKey&&(process.env.GOOGLE_API_KEY=String(s.apiKey))),Z_r()||an(Cye()),this.projectId=s?.projectId||rie(),this.location=o||s?.location||Bq(),g.debug("[GoogleVertexProvider] Constructor initialized",{regionParam:o,resolvedLocation:this.location,projectId:this.projectId}),g.debug("Google Vertex AI BaseProvider v2 initialized",{modelName:this.modelName,projectId:this.projectId,location:this.location,provider:this.providerName})}getProviderName(){return"vertex"}getDefaultModel(){return FE()}async getAISDKModel(){throw new Le({code:tt.INVALID_CONFIGURATION,message:"GoogleVertexProvider no longer uses @ai-sdk/google-vertex. All models use native SDKs: @google/genai for Gemini, @anthropic-ai/vertex-sdk for Claude.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}validateStreamOptionsOnly(e){this.validateStreamOptions(e)}async preprocessNativeFileInput(e){if(e.input&&jI(e.input),e.input?.files?.length)try{await GI(e,100*1024*1024,this.providerName)}catch(t){g.warn(`[GoogleVertex] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Uv(e.input)}async executeStream(e,t){let n=e.model||this.modelName||FE();return KA({name:"neurolink.provider.stream",tracer:Oe.provider,attributes:{[Pe.GEN_AI_SYSTEM]:this.providerName,[Pe.GEN_AI_MODEL]:n,[Pe.GEN_AI_OPERATION]:"stream",[Pe.NL_PROVIDER]:this.providerName}},async o=>{let s=Date.now(),i=e.tools||{};await this.preprocessNativeFileInput(e);let l={...await Je({name:"neurolink.message.build",tracer:Oe.provider,attributes:{[Pe.NL_PROVIDER]:this.providerName,"message.count":1,"message.build.count":1,"message.build.path":"vertex.native.stream"}},async()=>this.processCSVFilesForNativeSDK(e)),tools:i};try{let c;Qse(n)?(g.info("[GoogleVertex] Routing Claude model to native @anthropic-ai/vertex-sdk",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeAnthropicStream(l)):(g.info("[GoogleVertex] Routing Gemini model to native @google/genai",{model:n,totalToolCount:Object.keys(i).length}),c=await this.executeNativeGemini3Stream(l)),this.attachUsageAndCostAttributes(o,n,c?.usage);let u=this.wrapStreamResultWithLifecycle(e,c,s);return this.emitStreamEnd(n,s,!0,void 0,c.finishReason),u}catch(c){throw this.fireGenerateOnError(e,c,s),this.emitStreamEnd(n,s,!1,c),c}},o=>o.stream,(o,s)=>this.preserveStreamResultAccessors(o,{...o,stream:s}))}emitStreamEnd(e,t,n,o,s){let i=this.neurolink?.getEventEmitter();i&&i.emit("stream:end",{provider:this.providerName,responseTime:Date.now()-t,timestamp:Date.now(),result:{content:"",usage:{input:0,output:0,total:0},model:e,provider:this.providerName,finishReason:n?s??"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async createVertexGenAIClient(e){let t=rie(),n=e||this.location||Bq(),s=(await Promise.resolve().then(()=>(ww(),Sw))).GoogleGenAI;if(!s)throw new Le({code:tt.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});let i=s;return new i({vertexai:!0,project:t,location:n,httpOptions:{fetch:yt()}})}buildGeminiFunctionDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`},s=t.parameters||t.inputSchema;if(s){let i=xn(s,"openApi3"),a=pn(i);a.$schema&&delete a.$schema;let l=pi(a);py(l),n.parametersJsonSchema=l}return n}refreshGeminiToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildGeminiFunctionDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Gemini declarations.`))}resolveGeminiToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildGeminiFunctionDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}buildAnthropicToolDeclaration(e,t){let n={name:e,description:t.description||`Tool: ${e}`,input_schema:{type:"object"}},s=t.parameters||t.inputSchema;if(s){let i=xn(s),a=pn(i);n.input_schema={type:"object",properties:a.properties||{},required:a.required||[]}}return n}refreshAnthropicToolDeclarations(e,t,n,o){if(!e||!t)return;let s=new Set(t.map(i=>i.name));for(let[i,a]of Object.entries(e))s.has(i)||(t.push(this.buildAnthropicToolDeclaration(i,a)),a.execute&&n.set(i,a.execute),o.delete(i),g.info(`[GoogleVertex] Tool "${i}" hydrated mid-turn via discovery \u2014 added to Anthropic declarations.`))}resolveAnthropicToolOnMiss(e,t,n,o,s){if(!n)return;let i=mI(t,e);if(i?.execute)return n.some(a=>a.name===e)||n.push(this.buildAnthropicToolDeclaration(e,i)),o.set(e,i.execute),s.delete(e),g.info(`[GoogleVertex] Tool "${e}" resolved mid-turn via discovery \u2014 executing.`),o.get(e)}async executeNativeGemini3Stream(e){let t=e.model||this.modelName||FE(),n=gM(t,e.region),o=await this.createVertexGenAIClient(n);g.debug("[GoogleVertex] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0,project:this.projectId,location:n});let s=[],i=[{text:e.input.text??""}],a=e.input;if(a?.pdfFiles&&a.pdfFiles.length>0){g.debug(`[GoogleVertex] Processing ${a.pdfFiles.length} PDF file(s) for native stream`);for(let ye of a.pdfFiles){let Fe;typeof ye=="string"?wn.existsSync(ye)?Fe=wn.readFileSync(ye):Fe=Buffer.from(ye,"base64"):Fe=ye;let Ee=Fe.toString("base64");i.push({inlineData:{mimeType:"application/pdf",data:Ee}})}}if(await eG(i,a?.nativeAudioFiles,"[GoogleVertex]"),a?.images&&a.images.length>0){g.debug(`[GoogleVertex] Processing ${a.images.length} image(s) for native stream`);for(let ye of a.images){let Fe=i_(ye),Ee,Rt="image/jpeg";if(typeof Fe=="string")if(wn.existsSync(Fe)){Ee=wn.readFileSync(Fe);let ue=Ov(Fe);Rt=ue.startsWith("image/")?ue:this.detectImageType(Ee)}else if(Fe.startsWith("data:")){let ue=Fe.match(/^data:([^;]+);base64,(.+)$/);if(ue)Rt=ue[1],Ee=Buffer.from(ue[2],"base64");else continue}else if(Fe.startsWith("http://")||Fe.startsWith("https://"))try{let ue=await fetch(Fe);if(!ue.ok){g.warn(`[GoogleVertex] Image fetch failed: ${ue.status} ${ue.statusText}, skipping`,{url:Wr(Fe)});continue}let qe=await ue.arrayBuffer();Ee=Buffer.from(qe);let Be=ue.headers.get("content-type");Be&&Be.startsWith("image/")&&(Rt=Be.split(";")[0])}catch(ue){g.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${ue instanceof Error?ue.message:String(ue)}`,{url:Wr(Fe)});continue}else Ee=Buffer.from(Fe,"base64"),Rt=this.detectImageType(Ee);else Ee=Fe,Rt=this.detectImageType(Ee);let Xe=Ee.toString("base64");i.push({inlineData:{mimeType:Rt,data:Xe}})}}L_(s,e.conversationMessages),s.push({role:"user",parts:i});let l,c=new Hd;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){let ye=Rg(e.tools,"functionDeclarations");l=ye.toolsConfig;for(let[Fe,Ee]of ye.executeMap)c.set(Fe,Ee);g.debug("[GoogleVertex] Converted tools for native SDK",{toolCount:ye.toolsConfig[0].functionDeclarations.length,toolNames:ye.toolsConfig[0].functionDeclarations.map(Fe=>Fe.name)})}let u=e,p=!1;if(u.schema&&l){p=!0;let ye=xn(u.schema,"openApi3"),Fe=pn(ye);Fe.$schema&&delete Fe.$schema;let Ee=pi(Fe),Rt=l[0]?.functionDeclarations||[];Rt.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Ee}),l=[{functionDeclarations:Rt}],g.debug("[GoogleVertex] Added final_result tool for structured output with tools (stream)",{schemaKeys:Object.keys(Ee),totalTools:Rt.length})}let m=_a(this.providerName,t,{temperature:e.temperature??1,...e.topP!==void 0&&{topP:e.topP}},"vertex.gemini"),f={...m.temperature!==void 0&&{temperature:m.temperature},maxOutputTokens:e.maxTokens};nP(t)&&(f.maxOutputTokens&&f.maxOutputTokens>Nl&&(g.warn(`[GoogleVertex] Capping maxOutputTokens from ${f.maxOutputTokens} to ${Nl} for ${t}`),f.maxOutputTokens=Nl),f.maxOutputTokens||(f.maxOutputTokens=Nl)),m.topP!==void 0&&(f.topP=m.topP),e.topK!==void 0&&(f.topK=e.topK),e.stopSequences&&e.stopSequences.length>0&&(f.stopSequences=e.stopSequences),l&&(f.tools=l);let h=e.systemPrompt||"";p&&(h=h+`
1130
1130
 
1131
1131
  IMPORTANT: When you have gathered all necessary information and are ready to provide your final answer, you MUST call the 'final_result' tool with the structured data. Do not return the final answer as plain text - always use the final_result tool.`),h&&(f.systemInstruction=h);let y=uP(e.thinkingConfig);if(y&&(f.thinkingConfig=y),(u.output?.format==="json"||u.schema)&&!p&&!l&&(f.responseMimeType="application/json",u.schema)){let ye=xn(u.schema,"openApi3"),Fe=pn(ye);Fe.$schema&&delete Fe.$schema;let Ee=pi(Fe);py(Ee),f.responseSchema=Ee,g.debug("[GoogleVertex] Added responseSchema for JSON output (stream)",{schemaKeys:Object.keys(Ee)})}let x=Date.now(),b=e.maxSteps||Jo,T=Number.isFinite(b)&&b>0?Math.min(Math.floor(b),100):Math.min(Jo,100),w=[...s],C="",R,k=[],P=[],I=0,A,M=new Map,U=ey(Fd("vertex",t)),$=!1,L=0,z=0,j=0,F=0,B=[],O=sl(e.timeout)??_w,W=e.toolTimeoutMs??Ew,re=e.turnTimeoutMs??O,te=new AbortController,pe=()=>te.abort();e.abortSignal?.addEventListener("abort",pe);let Ae=mP({turnTimeoutMs:e.turnTimeoutMs,defaultTurnTimeoutMs:O,stallTimeoutMs:e.stallTimeoutMs,wrapupTimeLeadMs:e.wrapupTimeLeadMs,onDeadline:ye=>{g.warn(ye==="timeout"?`[GoogleVertex] Native Gemini turn exceeded its ${re}ms time budget \u2014 aborting`:`[GoogleVertex] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),te.abort()}}),J=te.signal;e.abortSignal?.aborted&&te.abort();let oe=!1,Z=0,we=!1,ve=!1;try{for(;I<T;){if(J.aborted){oe=!0;break}if(U.shouldStop())if(vze(w,t,U.projectedNextPromptTokens))U.resetAfterReclaim();else{$=!0,g.warn(`[GoogleVertex] Gemini turn stopped by the context guard: projected prompt ~${U.projectedNextPromptTokens} tokens >= threshold ${U.thresholdTokens} (step ${I}) \u2014 synthesizing a final answer.`);break}I++,Ae.noteProgress(),this.refreshGeminiToolDeclarations(e.tools,l?.[0]?.functionDeclarations,c,M),g.debug(`[GoogleVertex] Native SDK step ${I}/${T}`);try{let ye=await o.models.generateContentStream({model:t,contents:w,config:{...f,abortSignal:J}}),Fe=[],Ee=[],Rt,Xe=0,ue=0,qe=0,Be=0;for await(let Q of ye){Ae.noteProgress();let q=Q,Ce=q.candidates?.[0],D=Ce?.finishReason;typeof D=="string"&&D&&(R=D,Rt=D);let ge=Ce?.content;if(ge&&Array.isArray(ge.parts))for(let se of ge.parts)Ee.push(se),typeof se.text=="string"&&se.text.length>0&&B.push(se.text);Q.functionCalls&&Fe.push(...Q.functionCalls);let Se=q.usageMetadata;if(Se){if(Se.promptTokenCount!==void 0&&Se.promptTokenCount>0){L+=Se.promptTokenCount-Xe,Xe=Se.promptTokenCount,U.noteUsage(Se.promptTokenCount,Se.candidatesTokenCount??0);let se=Math.min(Se.cachedContentTokenCount??0,Se.promptTokenCount);j+=se-qe,qe=se}Se.candidatesTokenCount!==void 0&&Se.candidatesTokenCount>0&&(z+=Se.candidatesTokenCount-ue,ue=Se.candidatesTokenCount),Se.thoughtsTokenCount!==void 0&&Se.thoughtsTokenCount>0&&(F+=Se.thoughtsTokenCount-Be,Be=Se.thoughtsTokenCount)}}let ce=Ee.filter(Q=>typeof Q.text=="string").map(Q=>Q.text).join("");if(Fe.length===0&&!ce&&Rt==="MALFORMED_FUNCTION_CALL"&&Z<1&&!J.aborted){Z++,g.warn(`[GoogleVertex] Model returned MALFORMED_FUNCTION_CALL at step ${I}/${T}; retrying once with a corrective note.`),this.emitTurnEvent({phase:"malformed-retry",step:I,maxSteps:T}),Ee.length>0&&w.push({role:"model",parts:Ee}),w.push({role:"user",parts:[{text:"Your previous function call was malformed and could not be parsed. Re-issue it as a single valid function call, or answer in plain text."}]});continue}if(Fe.length===0){C=ce;break}if(p){let Q=Fe.find(q=>q.name==="final_result");if(Q){A=Q.args,g.debug("[GoogleVertex] Received final_result tool call with structured output (stream)",{outputKeys:Object.keys(A)}),C=JSON.stringify(A);break}}g.debug(`[GoogleVertex] Executing ${Fe.length} function calls`),w.push({role:"model",parts:Ee.length>0?Ee:Fe.map(Q=>({functionCall:Q}))});let Ne=[],_=[],G=[];for(let Q of Fe){if(J.aborted){oe=!0;break}k.push({toolName:Q.name,args:Q.args}),_.push({toolName:Q.name,args:Q.args});let q=M.get(Q.name);if(q&&q.count>=Kn){g.warn(`[GoogleVertex] Tool "${Q.name}" has exceeded retry limit (${Kn}), skipping execution`);let Ce={error:`TOOL_PERMANENTLY_FAILED: The tool "${Q.name}" has failed ${q.count} times and will not be retried. Last error: ${q.lastError}. Please proceed without using this tool or inform the user that this functionality is unavailable.`,status:"permanently_failed",do_not_retry:!0};Ne.push({functionResponse:{name:Q.name,response:Ce}}),P.push({name:Q.name,input:Q.args,output:Ce}),G.push({toolName:Q.name,output:Ce});continue}let he=c.get(Q.name);if(he||(he=this.resolveGeminiToolOnMiss(Q.name,e.tools,l?.[0]?.functionDeclarations,c,M)),he)try{let Ce={toolCallId:`${Q.name}-${Date.now()}`,messages:[],abortSignal:J};Ae.noteProgress();let D=await ht(Sh(Promise.resolve(he(Q.args,Ce)),J),W,`Tool "${Q.name}" execution timed out after ${W}ms`);Ae.noteProgress();let ge=XI(D);if(ge){let Se=M.get(Q.name)||{count:0,lastError:""};Se.count++,Se.lastError=ge,M.set(Q.name,Se)}else M.delete(Q.name);P.push({name:Q.name,input:Q.args,output:D}),Ne.push({functionResponse:{name:Q.name,response:{result:D}}}),G.push({toolName:Q.name,output:D})}catch(Ce){if(J.aborted||tu(Ce)){oe=!0;break}Ae.noteProgress(),Ce instanceof na&&this.emitTurnEvent({phase:"tool-timeout",step:I,maxSteps:T,toolName:Q.name});let D=Ce instanceof Error?Ce.message:"Unknown error",ge=M.get(Q.name)||{count:0,lastError:""};ge.count++,ge.lastError=D,M.set(Q.name,ge),g.warn(`[GoogleVertex] Tool "${Q.name}" failed (attempt ${ge.count}/${Kn}): ${D}`);let Se=ge.count>=Kn,se={error:Se?`TOOL_PERMANENTLY_FAILED: The tool "${Q.name}" has failed ${ge.count} times with error: ${D}. This tool will not be retried. Please proceed without using this tool or inform the user that this functionality is unavailable.`:`TOOL_EXECUTION_ERROR: ${D}. Retry attempt ${ge.count}/${Kn}.`,status:Se?"permanently_failed":"failed",do_not_retry:Se,retry_count:ge.count,max_retries:Kn};Ne.push({functionResponse:{name:Q.name,response:se}}),P.push({name:Q.name,input:Q.args,output:se}),G.push({toolName:Q.name,output:se})}else{let Ce={error:`TOOL_NOT_FOUND: The tool "${Q.name}" does not exist. Do not attempt to call this tool again.`,status:"permanently_failed",do_not_retry:!0},D=M.get(Q.name)||{count:0,lastError:""};D.count++,D.lastError=Ce.error,M.set(Q.name,D),Ne.push({functionResponse:{name:Q.name,response:Ce}}),P.push({name:Q.name,input:Q.args,output:Ce}),G.push({toolName:Q.name,output:Ce})}}if(oe)break;if(_.length>0||G.length>0){let Q=N_(Ee);ht(this.handleToolExecutionStorage(_.map((q,he)=>({...q,...he===0&&Q?{thoughtSignature:Q}:{},stepIndex:I})),G.map(q=>({...q,stepIndex:I})),e,new Date),sg,"tool storage write timed out").catch(q=>{g.warn("[GoogleVertex] Failed to store native Gemini stream tool executions",{error:q instanceof Error?q.message:String(q)})})}Ae.shouldNudgeWrapup()&&Ne.push({text:dP(p)}),w.push({role:"user",parts:Ne});try{U.noteAppendedChars(JSON.stringify(Ne).length)}catch{}}catch(ye){if(J.aborted||tu(ye)){oe=!0;break}throw g.error("[GoogleVertex] Native SDK error",ye),this.handleProviderError(ye)}}if(!C&&(I>=T||oe||$)){we=I>=T&&!oe;let ye=k.filter(Fe=>Fe.toolName!=="final_result").length;if(B.length>0)g.warn($?"[GoogleVertex] Tool call loop stopped by the context guard; returning text already gathered from prior steps.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${T}); returning text already gathered from prior steps.`);else if(oe)g.warn(`[GoogleVertex] Tool call loop ended mid-turn (${Ae.timedOut?"turn time limit":Ae.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),C=this.buildLoopExitMessage({turnClock:Ae,wasAborted:oe,stallTimeoutMs:e.stallTimeoutMs,maxSteps:T,toolCallCount:ye});else{g.warn($?"[GoogleVertex] Tool call loop stopped by the context guard with no text; synthesizing a final answer with tools disabled.":`[GoogleVertex] Tool call loop terminated after reaching maxSteps (${T}) with no text; synthesizing a final answer with tools disabled.`);let Fe=await this.synthesizeFinalAnswerWithoutTools(o,t,f,w,p,sl(e.timeout)??_w,J);Fe.text?(ve=!0,C=Fe.text,B.push(Fe.text),L+=Fe.inputTokens,z+=Fe.outputTokens,F+=Fe.reasoningTokens??0,Fe.finishReason&&(R=Fe.finishReason)):C=$?ru(ye):Cg(T,ye)}}}finally{Ae.dispose(),e.abortSignal?.removeEventListener("abort",pe)}let ae=we&&!ve?"tool-calls":Pre(R),H=pP({timedOut:Ae.timedOut,stalled:Ae.stalled,wasAborted:oe,cappedWithoutAnswer:we&&!ve,contextCappedWithoutAnswer:$&&!ve,finishReason:ae});H!=="completed"&&this.emitTurnEvent({phase:H,step:I,maxSteps:T,toolCallCount:k.filter(ye=>ye.toolName!=="final_result").length,elapsedMs:Ae.elapsedMs()});let V=Date.now()-x,ne=A?[C]:B.length>0?B:[C];async function*N(){for(let ye of ne)ye.length>0&&(yield{content:ye})}let Y=k.filter(ye=>ye.toolName!=="final_result"),ee=P.filter(ye=>ye.name!=="final_result"),ie=Math.max(0,L-j),le={stream:N(),provider:this.providerName,model:t,finishReason:ae,stopReason:H,rawFinishReason:R,usage:{input:ie,output:z+F,total:ie+j+z+F,...j>0&&{cacheReadTokens:j},...F>0&&{reasoning:F}},toolCalls:Y.map(ye=>({toolName:ye.toolName,args:ye.args})),toolsUsed:Y.map(ye=>ye.toolName),toolExecutions:Tv(ee),metadata:{streamId:`native-vertex-${Date.now()}`,startTime:x,responseTime:V,totalToolExecutions:Y.length,stopReason:H,rawFinishReason:R,stepsUsed:I}};return A&&(le.structuredOutput=A),le}async executeNativeGemini3Generate(e){let t=e.model||this.modelName||FE(),n=gM(t,e.region),o=await this.createVertexGenAIClient(n);g.debug("[GoogleVertex] Using native @google/genai for Gemini 3 generate",{model:t,project:this.projectId,location:n});let s=e.input?.text||e.prompt||"Please respond.",i=[],a=[{text:s}],l=e.input;if(l?.pdfFiles&&l.pdfFiles.length>0){g.debug(`[GoogleVertex] Processing ${l.pdfFiles.length} PDF file(s) for native generate`);for(let le of l.pdfFiles){let ye;typeof le=="string"?wn.existsSync(le)?ye=wn.readFileSync(le):ye=Buffer.from(le,"base64"):ye=le;let Fe=ye.toString("base64");a.push({inlineData:{mimeType:"application/pdf",data:Fe}})}}if(await eG(a,l?.nativeAudioFiles,"[GoogleVertex]"),l?.images&&l.images.length>0){g.debug(`[GoogleVertex] Processing ${l.images.length} image(s) for native generate`);for(let le of l.images){let ye=i_(le),Fe,Ee="image/jpeg";if(typeof ye=="string")if(wn.existsSync(ye)){Fe=wn.readFileSync(ye);let Xe=Ov(ye);Ee=Xe.startsWith("image/")?Xe:this.detectImageType(Fe)}else if(ye.startsWith("data:")){let Xe=ye.match(/^data:([^;]+);base64,(.+)$/);if(Xe)Ee=Xe[1],Fe=Buffer.from(Xe[2],"base64");else continue}else if(ye.startsWith("http://")||ye.startsWith("https://"))try{let Xe=await fetch(ye);if(!Xe.ok){g.warn(`[GoogleVertex] Image fetch failed: ${Xe.status} ${Xe.statusText}, skipping`,{url:Wr(ye)});continue}let ue=await Xe.arrayBuffer();Fe=Buffer.from(ue);let qe=Xe.headers.get("content-type");qe&&qe.startsWith("image/")&&(Ee=qe.split(";")[0])}catch(Xe){g.warn(`[GoogleVertex] Image URL fetch threw, skipping: ${Xe instanceof Error?Xe.message:String(Xe)}`,{url:Wr(ye)});continue}else Fe=Buffer.from(ye,"base64"),Ee=this.detectImageType(Fe);else Fe=ye,Ee=this.detectImageType(Fe);let Rt=Fe.toString("base64");a.push({inlineData:{mimeType:Ee,data:Rt}})}}L_(i,e.conversationMessages),i.push({role:"user",parts:a});let c=e.disableTools?{}:e.tools||{},u,p=new Hd;if(Object.keys(c).length>0){let le=Rg(c,"functionDeclarations");u=le.toolsConfig;for(let[ye,Fe]of le.executeMap)p.set(ye,Fe);g.debug("[GoogleVertex] Converted tools for native SDK generate",{toolCount:le.toolsConfig[0].functionDeclarations.length,toolNames:le.toolsConfig[0].functionDeclarations.map(ye=>ye.name)})}let m=!1;if(e.schema&&u){m=!0;let le=xn(e.schema,"openApi3"),ye=pn(le);ye.$schema&&delete ye.$schema;let Fe=pi(ye),Ee=u[0]?.functionDeclarations||[];Ee.push({name:"final_result",description:"Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.",parametersJsonSchema:Fe}),u=[{functionDeclarations:Ee}],g.debug("[GoogleVertex] Added final_result tool for structured output with tools (generate)",{schemaKeys:Object.keys(Fe),totalTools:Ee.length})}let f=_a(this.providerName,t,{temperature:e.temperature??1,...e.topP!==void 0&&{topP:e.topP}},"vertex.gemini"),h={...f.temperature!==void 0&&{temperature:f.temperature},maxOutputTokens:e.maxTokens};nP(t)&&(h.maxOutputTokens&&h.maxOutputTokens>Nl&&(g.warn(`[GoogleVertex] Capping maxOutputTokens from ${h.maxOutputTokens} to ${Nl} for ${t}`),h.maxOutputTokens=Nl),h.maxOutputTokens||(h.maxOutputTokens=Nl)),f.topP!==void 0&&(h.topP=f.topP),e.topK!==void 0&&(h.topK=e.topK),e.stopSequences&&e.stopSequences.length>0&&(h.stopSequences=e.stopSequences),u&&(h.tools=u);let y=e.systemPrompt||"";m&&(y=y+`
1132
1132