@juspay/neurolink 13.1.0 → 13.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -10
- package/dist/browser/neurolink.min.js +1 -1
- package/dist/cli/factories/commandFactory.js +13 -4
- package/dist/neurolink.d.ts +4 -0
- package/dist/neurolink.js +17 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,16 +1,8 @@
|
|
|
1
|
-
## [13.1.
|
|
2
|
-
|
|
3
|
-
### Features
|
|
4
|
-
|
|
5
|
-
- **(mcp):** look up servers in the official MCP Registry when enabled ([9308ddc](https://github.com/juspay/neurolink/commit/9308ddced77f15e4e5a1f424c41f591ce7a0b385))
|
|
1
|
+
## [13.1.1](https://github.com/juspay/neurolink/compare/v13.1.0...v13.1.1) (2026-10-18)
|
|
6
2
|
|
|
7
3
|
### Bug Fixes
|
|
8
4
|
|
|
9
|
-
- **(
|
|
10
|
-
- **(decide):** refuse a non-loopback http base URL for keyed decision providers ([fafb140](https://github.com/juspay/neurolink/commit/fafb140f2081e0e9439651d44d3cf0f5f8324b67))
|
|
11
|
-
- **(guardrails):** refuse regex patterns that can backtrack catastrophically ([32b37a9](https://github.com/juspay/neurolink/commit/32b37a914062a71dde8f3f399f434cf6392786c1))
|
|
12
|
-
- **(localusage):** place a re-emitted Grok prompt where the re-emit was written ([977ff75](https://github.com/juspay/neurolink/commit/977ff75971cf4abe01f80899617d21ff0c48b688))
|
|
13
|
-
- **(tooling):** launch tsx and typedoc through node instead of npx ([40fc3aa](https://github.com/juspay/neurolink/commit/40fc3aa3c963479320308ada221be21b14a48253)), closes [#1999](https://github.com/juspay/neurolink/issues/1999)
|
|
5
|
+
- **(providers):** skip Bedrock and SageMaker in the provider status probe ([228c68c](https://github.com/juspay/neurolink/commit/228c68c82ff0c1c7cecc6cfd92d6a571f2249ebc))
|
|
14
6
|
|
|
15
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
16
8
|
|
|
@@ -1967,7 +1967,7 @@ ${r}`:r}}return t?`${t}
|
|
|
1967
1967
|
|
|
1968
1968
|
${r}`:r}async retrieveKnowledgeGrounding(t){const r=this.knowledgeGroundingEngine;if(!r||!r.isEnabled()||t.useKnowledgeGrounding!==!0)return;const n=t.input?.text;if(n)try{const i=(t.conversationMessages!==void 0?t.conversationMessages:await this.fetchRecentRoutingHistory(t)).filter(s=>s.role==="user"||s.role==="assistant").slice(-KD).map(s=>({role:s.role==="assistant"?"assistant":"user",text:typeof s.content=="string"?s.content:""}));return await r.ground({query:n,recentTurns:i,scope:t.knowledgeContext})}catch(o){h.warn("[KnowledgeGrounding] grounding hook failed open",{error:String(o)});return}}async validateStreamRequestOptions(t,r){if(await this.validateStreamInput(t),t.inputValidation&&t.input?.text){const n=t.inputValidation;if(n.trimWhitespace&&(t.input.text=t.input.text.trim()),n.requireContent&&!t.input.text.trim())throw new Error("Input content is required but was empty or whitespace");if(n.minLength&&t.input.text.length<n.minLength)throw new Error(`Input text is too short (${t.input.text.length} < ${n.minLength})`);if(n.maxLength&&t.input.text.length>n.maxLength)throw new Error(`Input text is too long (${t.input.text.length} > ${n.maxLength})`)}if(t.piiDetection?.enabled&&t.input?.text){const n=await fle(t.input.text,{enabled:!0,action:t.piiDetection.action??"warn",detectTypes:t.piiDetection.detectTypes,customPatterns:t.piiDetection.customPatterns,allowList:t.piiDetection.allowList,redactionText:t.piiDetection.redactionText});if(n.action==="abort")throw new Error(n.feedback??"Request blocked: PII detected in input");t.input.text=n.text}this.enforceSessionBudget(t.maxBudgetUsd),await this.applyAuthenticatedRequestContext(t),this.emitStreamStartEvents(t,r),this.applyStreamLifecycleMiddleware(t)}async maybeHandleWorkflowStreamRequest(t){if(!t.options.workflow&&!t.options.workflowConfig)return null;const r=await this.streamWithWorkflow(t.options,t.startTime),n=r.stream,o=this;return r.stream=(async function*(){try{for await(const i of n)yield i;t.streamSpan.setStatus({code:ze.OK})}catch(i){throw t.streamSpan.setStatus({code:ze.ERROR,message:i instanceof Error?i.message:String(i)}),i}finally{o._disableToolCacheForCurrentRequest=!1,o._toolCacheKeysServedThisRequest=new Set,o._generationTurnActive=!1,t.streamSpan.setAttribute("response_time_ms",Date.now()-t.spanStartTime),t.streamSpan.end()}})(),r}async runStandardStreamRequest(t){const{options:r,streamSpan:n,spanStartTime:o,startTime:i,hrTimeStart:s,streamId:a,originalPrompt:l,ttsResolver:c,ttsMetadataSink:u}=t;h.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:r.provider,model:r.model,inputLength:r.input?.text?.length||0,disableTools:r.disableTools,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,contextKeys:r.context?Object.keys(r.context):[],optionKeys:Object.keys(r),sessionId:r.context?.sessionId});try{const{enhancedOptions:d,factoryResult:p}=await this.prepareStreamOptions(r,a,i,s);h.debug("[NeuroLink] Stream options prepared",{streamId:a,options:d,factoryResult:p,sessionId:d.context?.sessionId});const m={providerEmitted:!1};d._streamDedupContext=m;const f=await this.createMCPStream(d),{stream:g}=f,y=f.provider??"unknown",v={},{stream:w,ttsMetadata:T}=await this.createIncrementalTTSStream({stream:g,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,onComplete:$=>{v.result=$}});u?.(T);const S={finishReason:f.finishReason??"stop",toolCalls:void 0,toolResults:void 0},k=()=>S.toolCalls??f.toolCalls??[],A=()=>S.toolResults??f.toolResults??[];n.setAttribute(Le.NL_PROVIDER,y||"unknown");const{eventSequence:x,cleanup:R}=this.setupStreamEventListeners(),C={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},M=Date.now(),O=d.context?.sessionId,U={enhancedOptions:d,originalPrompt:l,startTime:i,streamStartTime:M,sessionId:O,streamSpan:n,spanStartTime:o,ttsResolver:c,incrementalStream:w,streamTtsMetadata:T,tts:v,mcpStreamOutcome:f,providerName:y,dedupContext:m,streamState:S,currentToolCalls:k,currentToolResults:A,metadata:C,eventSequence:x,cleanupListeners:R},D=this.drainStandardStreamOnce(U),N=await this.processStreamResult(D,d,p);return S.finishReason=S.finishReason||N.finishReason,Object.defineProperty(N,"finishReason",{enumerable:!0,configurable:!0,get:()=>S.finishReason,set:$=>{S.finishReason=$}}),Object.defineProperty(N,"toolCalls",{enumerable:!0,configurable:!0,get:()=>k()}),Object.defineProperty(N,"toolResults",{enumerable:!0,configurable:!0,get:()=>A()}),N.usage||(N.usage=f.usage),N.analytics||(N.analytics=f.analytics),Promise.resolve(N.analytics).then($=>{$?.cost&&$.cost>0&&(this._sessionCostUsd+=$.cost)}).catch(()=>{}),this.emitStreamEndEvents(N),this.createStreamResponse(N,D,{providerName:y,options:r,startTime:i,responseTime:Date.now()-i,streamId:a,fallback:C.fallbackAttempted,guardrailsBlocked:C.guardrailsBlocked,error:C.error,events:x,sourceResult:f})}catch(d){if(c?.(void 0),r.disableInternalFallback)throw d;return this.handleStreamError(d,r,i,a,void 0,void 0)}}drainStandardStreamOnce(t){const r=this.drainStandardStream(t);let n=!1;const o={next:()=>(n=!0,r.next()),return:async i=>(n||(n=!0,await this.settleStandardStreamDrain(t,{accumulatedContent:"",chunkCount:0,streamError:void 0,resolvedUsage:void 0})),r.return(i)),throw:i=>r.throw(i),[Symbol.asyncIterator]:()=>o};return o}async*drainStandardStream(t){const{enhancedOptions:r,originalPrompt:n,streamStartTime:o,sessionId:i,ttsResolver:s,incrementalStream:a,streamTtsMetadata:l,tts:c,mcpStreamOutcome:u,providerName:d,streamState:p,currentToolCalls:m,currentToolResults:f,metadata:g}=t;let y="",v=0,w,T,S=0;try{for await(const x of a){v++;const R=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,M=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!R&&(C||M)&&S++,x&&"content"in x&&typeof x.content=="string"&&(y+=x.content,this.emitter.emit("response:chunk",x.content),this.emitter.emit("stream:chunk",{type:"stream:chunk",content:x.content,metadata:{chunkIndex:v,totalLength:y.length,...R&&{noOutput:!0}},timestamp:Date.now()})),yield x}const k=r.fallbackOnMaxSteps===!1&&u.metadata?.stopReason==="step-cap";if(S===0&&!k&&!g.fallbackAttempted&&!r.disableInternalFallback&&m().length===0&&f().length===0){const x=this.handleStreamFallback(g,p,n,r,d,C=>{y+=C}),{stream:R}=await this.createIncrementalTTSStream({stream:x,ttsOptions:r.tts,providerName:d,fallbackProvider:r.provider,ttsMetadata:l,onComplete:C=>{c.result=C}});yield*R}s?.(c.result);const A=u.metadata?.finishReason;if(!g.fallbackAttempted&&(A==="length"||A==="tool-calls"||A==="content-filter")&&(p.finishReason=A),T=u.usage,!T&&u.analytics)try{const x=await Promise.resolve(u.analytics);x?.tokenUsage&&(T=x.tokenUsage)}catch{}T&&(u.usage=T),this.emitter.emit("stream:complete",{type:"stream:complete",content:y,provider:g.fallbackProvider??d,model:g.fallbackModel??u.model??r.model,finishReason:p.finishReason??"stop",prompt:r.input?.text||r.prompt,metadata:{chunkCount:v,totalLength:y.length,durationMs:Date.now()-o,sessionId:i,usage:T,finishReason:p.finishReason??"stop",...g.fallbackAttempted&&{primaryProvider:d,primaryModel:r.model,fallback:!0}},timestamp:Date.now()})}catch(k){throw h.debug("[NeuroLink.stream] Stream error occurred",{error:k instanceof Error?k.message:String(k),name:k instanceof Error?k.name:"UnknownError",provider:d,model:r.model,chunkCount:v,totalLength:y.length,durationMs:Date.now()-o,sessionId:i}),w=k instanceof Error?k:new Error(String(k)),this.emitter.emit("stream:error",{type:"stream:error",content:k instanceof Error?k.message:String(k),provider:d,model:r.model,metadata:{chunkCount:v,totalLength:y.length,durationMs:Date.now()-o,errorName:k instanceof Error?k.name:"UnknownError",sessionId:i},timestamp:Date.now()}),k}finally{await this.settleStandardStreamDrain(t,{accumulatedContent:y,chunkCount:v,streamError:w,resolvedUsage:T})}}async settleStandardStreamDrain(t,r){const{enhancedOptions:n,originalPrompt:o,startTime:i,streamStartTime:s,streamSpan:a,spanStartTime:l,ttsResolver:c,mcpStreamOutcome:u,providerName:d,dedupContext:p,streamState:m,currentToolCalls:f,metadata:g,eventSequence:y,cleanupListeners:v}=t,{accumulatedContent:w,chunkCount:T,streamError:S,resolvedUsage:k}=r;if(c?.(void 0),h.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:d,model:n.model,totalChunks:T,totalLength:w.length,durationMs:Date.now()-s,fallbackAttempted:g.fallbackAttempted,guardrailsBlocked:g.guardrailsBlocked,error:g.error}),!p.providerEmitted)try{const x=g.fallbackProvider??d??"unknown",R=g.fallbackModel??u.model??n.model??"unknown",C=S?"error":m.finishReason??"stop";this.emitter.emit("generation:end",{provider:x,model:R,responseTime:Date.now()-s,toolsUsed:f().map(M=>M.toolName),timestamp:Date.now(),result:{content:w,usage:k,model:R,provider:x,finishReason:C},prompt:n.input?.text||n.prompt,temperature:n.temperature,maxTokens:n.maxTokens,success:!S,error:S?.message,streamed:!0})}catch(x){h.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:x instanceof Error?x.message:String(x)})}this._disableToolCacheForCurrentRequest=!1,this._toolCacheKeysServedThisRequest=new Set,this._generationTurnActive=!1,v(),a.setAttribute("response_time_ms",Date.now()-l),a.setAttribute(Le.NL_OUTPUT_LENGTH,w.length);const A=!!(g.error||S);a.setAttribute(Le.GEN_AI_FINISH_REASON,A?"error":"stop"),g.fallbackAttempted&&(a.setAttribute("fallback_triggered",!0),g.fallbackProvider&&a.setAttribute("fallback_provider",g.fallbackProvider)),A?a.setStatus({code:ze.ERROR,message:g.error||S?.message}):a.setStatus({code:ze.OK}),a.end(),w.trim()&&h.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:d,model:n.model,responseTimeMs:Date.now()-i,contentLength:w.length,fallback:g.fallbackAttempted}),await this.storeStreamConversationMemory({enhancedOptions:n,providerName:d,originalPrompt:o,accumulatedContent:w,startTime:i,eventSequence:y,resultToolsUsed:(()=>{const x=u.toolsUsed;if(Array.isArray(x)&&x.length>0)return x;const R=f().map(C=>C.toolName);return R.length>0?R:void 0})()})}async createIncrementalTTSStream(t){const{stream:r,ttsOptions:n,providerName:o,fallbackProvider:i,onComplete:s}=t;if(!n?.enabled)return s(void 0),{stream:r};const{TTSProcessor:a}=await Promise.resolve().then(()=>(hl(),Jtt)),l=i==="auto"?void 0:i,c=n.provider??l??o,u=c&&a.supports(c)?c:void 0,d=t.ttsMetadata??{attempted:u!==void 0,success:!1};d.attempted=u!==void 0,d.success=!1,delete d.error,delete d.latency;const p=Date.now();let m=!1;const f=(g,y)=>{m||(m=!0,d.success=y===void 0&&g!==void 0,y?d.error=y:delete d.error,d.latency=Date.now()-p,s(g))};return u?{stream:drt({stream:r,provider:u,options:n,onComplete:f}),ttsMetadata:d}:(h.warn(`[NeuroLink.stream] No TTS provider resolved for incremental streaming (set tts.provider explicitly \u2014 chat provider "${c??"<unset>"}" is not a registered TTS handler)`),f(void 0),{stream:r,ttsMetadata:d})}deferProviderStreamTTS(t){return t.tts?.enabled?{...t,tts:void 0}:t}async prepareStreamOptions(t,r,n,o){if(await this.initializeConversationMemoryForGeneration(r,n,o),await this.initializeMCP(),this.shouldReadMemory(t.memory,t.context?.userId)&&t.context?.userId)try{t.input.text=await this.retrieveMemory(t.input.text??"",t.context.userId,t.memory?.additionalUsers),h.debug("Memory retrieval successful")}catch(a){h.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(t),this.enableOrchestration&&!t.provider&&!t.model)try{const a=await this.applyStreamOrchestration(t);h.debug("Stream orchestration applied",{originalProvider:t.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:t.input.text?.substring(0,100)}),t={...t,...a},a.model&&(t.model=o1(t.model,this.modelAliasConfig))}catch(a){h.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:t.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(t),t.rag?.files?.length)try{const{prepareRAGTool:a}=await Promise.resolve().then(()=>(Lle(),Nle)),l=await a(t.rag,t.provider);t.tools||(t.tools={}),t.tools[l.toolName]=l.tool;const c=[`
|
|
1969
1969
|
|
|
1970
|
-
IMPORTANT: You have a tool called "${l.toolName}" that searches through`,`${l.filesLoaded} loaded document(s) containing ${l.chunksIndexed} indexed chunks.`,`ALWAYS use the "${l.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+c,h.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){h.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const i=Lsn(t),s=Fsn(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(s.input.text=l)}return{enhancedOptions:s,factoryResult:i}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Xx(),DGt)),i=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],s=t.model;i.length>0&&s&&(i.some(l=>s.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,h.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:i.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=this.conversationEventContext.getStore(),o=new Set,i=g=>{if(!(!g||typeof g!="object"||!("payload"in g)||!g.payload||typeof g.payload!="object"||!("confirmationId"in g.payload)||typeof g.payload.confirmationId!="string"))return g.payload.confirmationId},s=(g,y,v)=>{const w=n!==void 0&&this.conversationEventContext.getStore()===n,T=v!==void 0&&o.has(v);!w&&!T||t.push({type:g,seq:r++,timestamp:Date.now(),...y&&typeof y=="object"?y:{data:y}})},a=(...g)=>{const y=g[0];s("response:chunk",{content:y})},l=(...g)=>{const y=g[0];s("tool:start",{...y,toolName:y.toolName??y.tool})},c=(...g)=>{const y=g[0],v=y.toolName??y.tool,w=y.responseTime??y.duration,T=y.success??(y.error!==void 0?!1:void 0),S={...y,toolName:v,...w!==void 0?{responseTime:w}:{},...T!==void 0?{success:T}:{},...y.error!==void 0?{error:y.error}:{}};s("tool:end",S),S.result&&S.result.uiComponent===!0&&s("ui-component",{toolName:v,componentData:S.result,timestamp:Date.now(),...T!==void 0?{success:T}:{},...w!==void 0?{responseTime:w}:{}})},u=(...g)=>{const y=g[0];y&&typeof y=="object"&&"type"in y&&typeof y.type=="string"&&"data"in y&&y.data&&typeof y.data=="object"&&!Array.isArray(y.data)&&s(y.type,{data:y.data})},d=(...g)=>{s("ui-component",g[0])},p=(...g)=>{if(n!==void 0&&this.conversationEventContext.getStore()===n){const y=i(g[0]);y!==void 0&&o.add(y),s("hitl:confirmation-request",g[0])}},m=(...g)=>{const y=i(g[0]);y!==void 0&&o.has(y)&&(s("hitl:confirmation-response",g[0],y),o.delete(y))};return this.emitter.on("response:chunk",a),this.emitter.on("tool:start",l),this.emitter.on("tool:end",c),this.emitter.on("ui-component",d),this.emitter.on("host:conversation-event",u),this.emitter.on("hitl:confirmation-request",p),this.emitter.on("hitl:confirmation-response",m),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",a),this.emitter.off("tool:start",l),this.emitter.off("tool:end",c),this.emitter.off("ui-component",d),this.emitter.off("host:conversation-event",u),this.emitter.off("hitl:confirmation-request",p),this.emitter.off("hitl:confirmation-response",m)}}}async*handleStreamFallback(t,r,n,o,i,s){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const f=this._metricsTraceContext;let g=ke.createGenerationSpan({provider:i,model:o.model||"unknown",name:`gen_ai.${i}.stream.failed`,traceId:f?.traceId,parentSpanId:f?.parentSpanId});g=ke.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),et().recordSpan(g)}catch{}const l=o.fallbackProvider?.trim()||void 0,c=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,p=HL.getFallbackRoute(n||o.input.text||"",{provider:i,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),m={...p,provider:l??u??p.provider,model:c??d??p.model};h.warn("Retrying with fallback provider",{originalProvider:i,fallbackProvider:m.provider,fallbackModel:m.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const f=await to.createProvider(m.provider,m.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));f.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,R)=>this.executeTool(x,R,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await ch(this.conversationMemory,{prompt:o.input.text,context:o.context});f.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await f.stream({...this.deferProviderStreamTTS(o),model:m.model,conversationMessages:g}),v=y.toolCalls??[],w=y.toolResults??[];(v.length>0||w.length>0)&&(r.toolCalls=v,r.toolResults=w,r.finishReason=y.finishReason??r.finishReason);let T=0,S=0;for await(const x of y.stream){T++;const R=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,M=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!R&&(C||M)&&S++,x&&"content"in x&&typeof x.content=="string"&&(s(x.content),this.emitter.emit("response:chunk",x.content)),yield x}const k=y.toolCalls??[],A=y.toolResults??[];if(S===0&&k.length===0&&A.length===0)throw new Error(`Fallback provider ${m.provider} also returned 0 real output chunks (chunkCount=${T}, sentinel-only or empty)`);r.toolCalls=k,r.toolResults=A,r.finishReason=y.finishReason??r.finishReason,t.fallbackProvider=m.provider,t.fallbackModel=m.model,t.guardrailsBlocked=!0}catch(f){const g=f instanceof Error?f.message:String(f);throw t.error=`${a}; Fallback failed: ${g}`,h.error("Fallback provider failed",{fallbackProvider:m.provider,error:g}),f}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:i,startTime:s,eventSequence:a,resultToolsUsed:l}=t;h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:iP(sP(r)),sessionId:r.context?.sessionId});const c=a.some(u=>u.type==="tool:start"||u.type==="tool:end");if(!i.trim()&&!c){h.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:iP(sP(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const u=r.context?.sessionId,d=r.context?.userId;let p;r.model&&(p={provider:n,model:r.model});const m=Date.now();try{const f=this.drainPendingSkillMessages(u);await this.conversationMemory.storeConversationTurn({sessionId:u,userId:d,userMessage:o??"",aiResponse:i,startTimeStamp:new Date(s),providerDetails:p,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...f.length>0?{skillMessages:f}:{},...r.modality?{modality:r.modality}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),h.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:u,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(f){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,f instanceof Error?f.message:String(f)),h.warn("Failed to store stream conversation turn",{error:f instanceof Error?f.message:String(f)})}}if(this.shouldWriteMemory(r.memory,r.context?.userId,i)){const u=r.context?.sessionId,d=[...new Set(l??[])];this.storeMemoryInBackground({prompt:o??"",response:i.trim(),userId:r.context?.userId,...typeof u=="string"?{sessionId:u}:{},provider:n,model:r.model,...d.length>0?{toolsUsed:d}:{}},r.memory,r.context)}}async validateStreamInput(t){const r=process.hrtime.bigint();h.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),i=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!i)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=t.provider&&t.provider!=="auto"?t.provider:this.getOrchestratedPreferredProvider(t),n=await Vb(r),o=await to.createProvider(n,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await o.ensureModelLimits?.(),o.setTraceContext(this._metricsTraceContext),o.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let i=await this.getAllAvailableTools();i=this.applyToolInfoFiltering(i,t),_r.getDescriptor(n)?.toolSupport==="none"&&(i=[]);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,i,o.supportsTools?.()??!0),a=t.conversationMessages!==void 0,l=a?t.conversationMessages:await ch(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=l;let c=l;const u=pa({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:i,compactionThreshold:t.compactionThreshold}),d=c?.length||0,p=this.getCompactionSessionId(t),m=d>0;if(!u.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:u.estimatedInputTokens,budget:u.availableInputTokens,provider:n,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Ba(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${u.estimatedInputTokens} tokens, budget: ${u.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:u.estimatedInputTokens,availableTokens:u.availableInputTokens,stagesUsed:[],breakdown:u.breakdown})}if(u.shouldCompact&&(a||this.conversationMemory)&&d>(this.lastCompactionMessageCount.get(p)??0)){const y=await new Xw({provider:n,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps(this.decisionSiteContext(t,p))).compact(c,BD(u,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});y.compacted&&(c=Nw(y.messages).messages,t.conversationMessages=c,this.lastCompactionMessageCount.set(p,c.length));const v=pa({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:i});if(!v.withinBudget){h.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:n,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=Gee(c,v.availableInputTokens,v.breakdown,n),t.conversationMessages=c;const w=pa({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:i});if(!w.withinBudget){this.lastCompactionMessageCount.delete(p);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:w.estimatedInputTokens,budget:w.availableInputTokens,provider:n,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Ba(`Stream context exceeds model budget after all compaction stages. Estimated: ${w.estimatedInputTokens} tokens, Budget: ${w.availableInputTokens} tokens.`,{estimatedTokens:w.estimatedInputTokens,availableTokens:w.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:w.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let w=null;for(let T=0;T<y;T++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const S=g.selectNext(v);if(!S)break;v.add(g.memberKey(S));const k=S.provider,A=S.model??void 0,x=S.region??void 0;h.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:A,attempt:T});try{const R=await to.createProvider(k,A,!t.disableTools,this,x,this.resolveCredentials(t.credentials));R.setTraceContext(this._metricsTraceContext),R.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(U,D)=>this.executeTool(U,D,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),R.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const C=await R.stream({...this.deferProviderStreamTTS(t),provider:k,model:A,region:x,systemPrompt:s,conversationMessages:c});h.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const M=S,O=(async function*(){try{yield*C.stream,g.recordSuccess(M)}catch(U){throw g.recordFailure(M,Hb(U)),U}})();return zw(C,{...C,stream:O,provider:k,model:C.model||A,toolCalls:C.toolCalls??[],toolResults:C.toolResults??[]})}catch(R){if(or(R))throw R;if(Vce(R)){const C=R instanceof Error?R.message:String(R);throw g.recordFailure(S,Hb(R)),new Error(`[ModelPool] non-retryable: ${C}`,{cause:R})}g.recordFailure(S,Hb(R)),w=R instanceof Error?R:new Error(String(R)),h.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:w.message})}}throw new Error(`[ModelPool] all stream members failed: ${w?.message??"no stream members available"}`)}o.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const f=await o.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:c});return h.debug("[createMCPStream] Stream created successfully",{provider:n,systemPromptPassedLength:s.length}),zw(f,{...f,provider:n,model:f.model||t.model,toolCalls:f.toolCalls??[],toolResults:f.toolResults??[]})}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){const o=n.sourceResult,i={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},s={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},i)},a=Object.getOwnPropertyDescriptor(t,"toolCalls");a&&Object.defineProperty(s,"toolCalls",a);const l=Object.getOwnPropertyDescriptor(t,"toolResults");l&&Object.defineProperty(s,"toolResults",l);const c=Object.getOwnPropertyDescriptor(t,"finishReason");if(c&&Object.defineProperty(s,"finishReason",c),!o)return s;const u=new Set(["finishReason","stopReason","rawFinishReason","toolCalls","toolResults"]);for(const d of Object.getOwnPropertyNames(o)){const p=Object.getOwnPropertyDescriptor(o,d);!u.has(d)&&p&&typeof p.get=="function"&&Object.defineProperty(s,d,p)}return Object.defineProperty(s,"metadata",{enumerable:!0,configurable:!0,get:()=>(o.metadata===void 0&&(o.metadata={}),Object.assign(o.metadata,i)),set:d=>{o.metadata=d}}),s}async handleStreamError(t,r,n,o,i,s){if(t instanceof Ba)throw t;h.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,l=Date.now()-n,c=await Vb(r.provider),u=await to.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));u.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await u.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let p="";return{stream:(async function*(f){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(p+=g.content,f.emitter.emit("response:chunk",g.content)),yield g}finally{if(p.trim()){h.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{const g=r.model||"unknown",y=Date.now()-n;f.emitter.emit("stream:complete",{content:p,provider:c,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}}),f.emitter.emit("generation:end",{provider:c,model:g,responseTime:y,timestamp:Date.now(),result:{content:p,usage:{input:0,output:0,total:0},model:g,provider:c,finishReason:"stop"},success:!0,streamed:!0})}catch{}}if(f.conversationMemory&&i?.context?.sessionId&&p.trim()){const g=i?.context?.sessionId,y=i?.context?.userId;let v;r.model&&(v={provider:c,model:r.model});const w=Date.now();try{const T=g||r.context?.sessionId,S=f.drainPendingSkillMessages(T);await f.conversationMemory.storeConversationTurn({sessionId:T,userId:y||r.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:i?.enableSummarization,requestId:i?.context?.requestId||r.context?.requestId,...S.length>0?{skillMessages:S}:{}}),f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,1)}catch(T){f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,2,T instanceof Error?T.message:String(T)),h.warn("Failed to store fallback stream conversation turn",{error:T instanceof Error?T.message:String(T)})}}}})(this),provider:c,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:l,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}fileToolRootsFor(t){return SW(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=s2({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return s2({perCall:t,instance:this.toolsConfig?.fileRoots})}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(i){const s=i instanceof Error?i.message:String(i),a=s.toLowerCase();return i instanceof W0?{provider:r,status:"denied",detail:s}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:s}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:s}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:s}:{provider:r,status:"unknown",detail:s}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,i={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,i),this.currentStreamToolExecutions.push(i),this.emitter.emit("tool:start",Yx(t,{input:r,timestamp:n,executionId:o})),h.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,i=Date.now(),s){const a=o||i-1e3,l=i-a,c=!n;let u;s?u=this.activeToolExecutions.get(s):u=Array.from(this.activeToolExecutions.values()).find(m=>m.tool===t&&!m.endTime);const d=s||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=i,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const p={tool:t,startTime:a,endTime:i,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",Yx(t,{result:r,error:n,success:c,responseTime:l,timestamp:i,duration:l,executionId:d})),h.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:l,success:c,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(CJ(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const s=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],p=d?.abortSignal,m=p?AbortSignal.any([p,u]):u,f={...d,abortSignal:m};return Promise.race([s(c[0],f),new Promise((g,y)=>{m.addEventListener("abort",()=>{u.aborted?y(pe.toolTimeout(l,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const i=Arn(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(i),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw h.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},h.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,h.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),h.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),h.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new il("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new il("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Be(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0})),r=new Map;for(const o of t){const i=o.inputSchema||o.parameters;h.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!i,effectiveSchemaType:typeof i,effectiveSchemaHasProperties:!!i?.properties,effectiveSchemaHasRequired:!!i?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(s,a)=>{const l=this.toolExecutionContext||{},c=a&&er(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return h.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(l),runtimeContextKeys:Object.keys(c),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,s,u)}})}this.cachedFileTools||(this.cachedFileTools=o7t(this.fileRegistry));const n=this.cachedFileTools;for(const[o,i]of Object.entries(n))if(!r.has(o)){const s=i,a=s.inputSchema??s.parameters;r.set(o,{name:o,description:i.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await i.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{oe.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),oe.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw oe.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>ma({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return Ue.mcp.startActiveSpan(t,{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize}},i=>(ts(i,"tool",{input:r}),this.executeToolWithSpan(t,r,n,o,i)))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),i=o?"mcp":this.getCustomTools().has(t)?"custom":"external",s=r?xv(r):"",a=Date.now(),l=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:l,externalTool:o,toolType:i,inputSize:s.length,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,i){try{const s=await this.prepareToolExecutionState(t,r,n,o),a=await this.runPreparedToolExecution(t,r,s,o,i),l=er(a)&&"isError"in a&&a.isError===!0;return ts(i,"tool",{output:a,...l&&{level:"ERROR",statusMessage:XN(a)}}),a}catch(s){const a=s instanceof Error?s.message:String(s);throw ts(i,"tool",{level:"ERROR",statusMessage:a}),s instanceof Me||(i.recordException(s instanceof Error?s:new Error(a)),i.setStatus({code:ze.ERROR,message:a})),s}finally{i.end()}}async prepareToolExecutionState(t,r,n,o){h.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:er(r)?Yrt(r):r,hasExternalManager:!!this.externalServerManager}),h.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",Yx(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const i=this.toolRegistry.getToolInfo(t),s=n?.timeout??i?.tool?.timeoutMs??Gl.EXECUTION_BATCH_MS,a=n?.maxRetries??i?.tool?.maxRetries??bi.DEFAULT,l=n?.retryDelayMs||oo.BASE_MS,c={timeout:s,maxRetries:a,totalTimeout:n?.totalTimeoutMs??i?.tool?.totalTimeoutMs??s*(a+1)+l*a,retryDelayMs:l,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:u}=await Promise.resolve().then(()=>(V1(),Jb)),d=u.getMemoryUsageMB(),m=`${o.externalTool?.serverId||i?.tool?.serverId||"unknown"}.${t}`;let f=this.toolCircuitBreakers.get(m);f||(f=new rP(PR.FAILURE_THRESHOLD,wB),this.toolCircuitBreakers.set(m,f));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:c,startMemory:d,circuitBreaker:f,breakerKey:m,metrics:g}}async runPreparedToolExecution(t,r,n,o,i){let s=0;try{oe.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=n.finalOptions.maxRetries+1,l=n.finalOptions.totalTimeout,c=Date.now(),u=c+l;let d=0;const p=await n.circuitBreaker.execute(async()=>rCe(async()=>{d++;const m=u-Date.now();if(m<=0)throw pe.toolTimeout(t,l,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c,exhausted:!0});const f=Math.min(n.finalOptions.timeout,m);return Be(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),f,pe.toolTimeout(t,f,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:m=>Date.now()+n.finalOptions.retryDelayMs<u&&F9(m),onRetry:(m,f)=>{s=m,oe.warn(`[${o.functionTag}] Retrying tool execution (attempt ${m})`,{toolName:t,error:f.message,attempt:m})}}));return i.setAttribute("tool.retry_count",s),await this.handleSuccessfulToolExecution(t,p,n,o,i)}catch(a){return i.setAttribute("tool.retry_count",s),this.handleFailedToolExecution(t,r,a,n,o,i)}}async handleSuccessfulToolExecution(t,r,n,o,i){const s=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=s,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+s)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(V1(),Jb)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&oe.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:s}),oe.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:s,memoryDelta:c,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,p=d?u?.content:void 0,m=d?p?.filter(f=>f.type==="text"&&f.text).map(f=>f.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}oe.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const f=Vmn(m??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${f})] `;if(u&&Array.isArray(p)){const w=p.map(T=>({...T}));for(const T of w)if(T.type==="text"&&T.text){T.text=g+T.text;break}u.content=w}i.setAttribute("tool.error.message",(m??"Unknown error").substring(0,500)),i.setAttribute("tool.error.category",f),i.setStatus({code:ze.ERROR,message:`MCP tool returned isError: ${(m??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-s)/(y-1):0;const v=Hmn(f);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&m?new Error(m):void 0,o.executionId),i.setAttribute("tool.result.status",d?"error":"success"),i.setAttribute("tool.duration_ms",s),r}async handleFailedToolExecution(t,r,n,o,i,s){o.metrics.failedExecutions++;const a=Date.now()-i.executionStartTime;if(n instanceof fm)return oe.warn(`[${i.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),i.executionId),s.setAttribute("tool.result.status","circuit_breaker_open"),s.setAttribute("tool.duration_ms",a),s.setAttribute("tool.circuit_breaker.state",n.breakerState),s.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),s.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),s.setStatus({code:ze.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let l;if(n instanceof Me)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=pe.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=pe.toolNotFound(t,fVr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=pe.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=pe.networkError(t,n):l=pe.toolExecutionFailed(t,n);else l=pe.toolExecutionFailed(t,new Error(String(n)));const c=l.category||"execution";throw o.metrics.errorCategories[c]=(o.metrics.errorCategories[c]||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,l,i.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new Me({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),nCe(l),s.setAttribute("tool.result.status","error"),s.setAttribute("tool.duration_ms",a),s.recordException(l),s.setStatus({code:ze.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const i="NeuroLink.executeToolInternal",s=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!s?.destructiveHint,l=this.mcpToolResultCache,c=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,c):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&l&&!d){const f=l.getCachedResult(t,c);if(f!==void 0)return h.debug(`[${i}] Cache HIT for tool: ${t}`),f}else d&&h.debug(`[${i}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const p=async f=>{if(this.mcpToolMiddlewares.length===0)return f();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:s,execute:async()=>({})},r,{toolMeta:{name:t,annotations:s}},y)}return f()};return await y()},m=async()=>{const f=this.externalServerManager.getAllTools(),g=f.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},w=this.mcpToolRouter.route(v);y=g.find(T=>T.serverId===w.serverId)||g[0],h.debug(`[${i}] Router selected server: ${w.serverId}`,{strategy:w.strategy,confidence:w.confidence})}catch(v){h.warn(`[${i}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(h.debug(`[${i}] External MCP tool search:`,{toolName:t,externalToolsCount:f.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{oe.debug(`[${i}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return h.debug(`[${i}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw h.error(`[${i}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},w=n.authContext||{},T=QS({...v,...w,hitlState:o},this.resolveFileToolRoots(void 0));h.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(T)});const S=await this.toolRegistry.executeTool(t,r,T);if(S&&typeof S=="object"&&"success"in S&&S.success===!1){const k=S.error||"Tool execution failed",A=new Error(k);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return S}catch(v){const w=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",w),v instanceof Error&&v.message.includes("not found")){const T=await this.getAllAvailableTools();throw pe.toolNotFound(t,T.map(S=>S.name))}throw pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const f=await p(m);return a&&l&&f!==void 0&&(l.cacheResult(t,c,f),h.debug(`[${i}] Cached result for tool: ${t}`)),f}catch(f){const g=s?{name:t,description:"",annotations:s,execute:async()=>({})}:void 0;if(g&&Ute(g)&&f instanceof Error&&F9(f)){h.debug(`[${i}] Tool ${t} is safe to retry, attempting once more`);try{const y=await p(m);return a&&l&&y!==void 0&&l.cacheResult(t,c,y),y}catch{}}throw f}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Tp({name:t,description:""})}invalidateToolCache(){this.toolCache=null,h.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return h.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();h.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!to,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(V1(),Jb)),i=o.getMemoryUsageMB();try{const s=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!s.has(g.name)){const y=K2(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});s.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0}));for(const g of l)if(!s.has(g.name)){const y=K2(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:ma({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const g of c)if(!s.has(g.name)){const y=K2(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});s.set(g.name,y)}const u=this.externalServerManager.getAllTools();for(const g of u)if(!s.has(g.name)){const y=K2(g,{category:ma({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const d=Array.from(s.values());oe.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const m=o.getMemoryUsageMB().heapUsed-i.heapUsed;if(m>ym.LOW_USAGE_MB&&(oe.debug(`\u{1F50D} Tool listing used ${m}MB memory (large tool registry detected)`),d.length>_be.LARGE_TOOL_COLLECTION&&oe.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=Tp({name:g.name,description:g.description||""}));const f=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:f,timestamp:Date.now()},f}catch(s){return oe.error("Failed to list available tools",{error:s}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(V1(),Jb)),n=r.getMemoryUsageMB();t?.quiet||oe.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||oe.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Ja(),DC)),{hasProviderEnvVars:i}=await Promise.resolve().then(()=>(Ih(),G1)),s=_r.getAllDescriptors().map(p=>p.name),a=Ig(Da.DEFAULT_CONCURRENCY_LIMIT),l=s.map(p=>a(async()=>{const m=Date.now();try{if(!await this.hasProviderEnvVars(p)&&p!=="ollama")return{provider:p,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-m};if(p==="ollama"){let S,k="not-run";try{const A=nA(),x=oA(A);if(x.kind==="suppressed")throw new Error(x.reason);S=x,k="transport-failure";const R=await fetch(A.url,{method:"GET",signal:AbortSignal.timeout(ql.AUTH_MS)});if(!R.ok)throw new Error("Ollama service not responding");k="protocol-failure";const C=await R.json(),M=C?.models;if(!Array.isArray(M))throw h.warn("Ollama API returned invalid models format in testProvider",{responseData:C,modelsType:typeof M}),new Error("Invalid models format from Ollama API");k="success";const O=M.filter(U=>U&&typeof U=="object"&&typeof U.name=="string");return O.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m,model:O[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-m}}catch(A){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:A instanceof Error?Vw(A):"Ollama service not running",responseTime:Date.now()-m}}finally{S&&Hw(S,k)}}const g=5e3,y=new AbortController,v=this.testProviderConnection(p,y.signal);let w;const T=new Promise((S,k)=>{w=setTimeout(()=>{k(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,T])}finally{clearTimeout(w),v.catch(()=>{}),y.abort()}return{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m}}catch(f){const g=f instanceof Error?f.message:String(f);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-m}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&oe.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),c}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(Ja(),DC));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(Ih(),G1));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(Ih(),G1));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(Ih(),G1));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),i=this.toolRegistry.getBuiltInServerInfos(),s=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+i.length+s.length,l=r.connectedServers+o.length+i.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:s.length,totalTools:c,autoDiscoveredServers:s,customToolsCount:this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return oe.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Vy(),qb));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return h.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Vy(),qb)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Vy(),qb));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Vy(),qb)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Vy(),qb));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,h.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new rP(PR.FAILURE_THRESHOLD,wB)),oe.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),oe.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(s=>s.name)),i=new Map;for(const s of n)i.has(s.name)||i.set(s.name,s.serverId||"unknown");for(const s of o){const a=this.toolExecutionMetrics.get(s),l=`${i.get(s)||"unknown"}.${s}`,c=this.toolCircuitBreakers.get(l),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!c||c.getState()==="closed")&&u>=.8;d&&r++;const p=[],m=[];if(c&&c.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),m.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(u*100).toFixed(1)}%`),m.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),m.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const f=a.errorCategories;f.timeout>0&&(p.push(`Timeout errors: ${f.timeout}`),m.push("Consider increasing the tool timeout configuration")),f.validation>0&&(p.push(`Validation errors: ${f.validation}`),m.push("Review input schemas and parameter validation")),f.network>0&&(p.push(`Network errors: ${f.network}`),m.push("Check network connectivity and endpoint availability"))}t[s]={name:s,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:c?.getState()||"closed",failureCount:c?.getFailureCount()||0},issues:p,recommendations:m}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return h.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:qe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return h.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return h.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return h.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Be(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return h.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return h.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const i=await Be(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(i.length===0)return h.debug("No messages found for session export",{sessionId:t}),null;const s=this.conversationMemory.getSession(t),a=await Be(s instanceof Promise?s:Promise.resolve(s),o,new Error("getSession operation timed out after 30s")),l=new Date().toISOString(),c={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():l,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():l,messages:i};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),h.debug("Exported conversation session",{sessionId:t,messageCount:i.length}),c}catch(i){return h.error("Failed to export conversation session",{sessionId:t,error:i instanceof Error?i.message:String(i)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,i=6e4;try{const s=await Be(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of s){const c=await Be(this.exportSession(l.id,r),i,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return h.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(s){return h.error("Failed to export all conversation sessions",{userId:t,error:s instanceof Error?s.message:String(s)}),[]}}async storeToolExecutions(t,r,n,o,i){const s=n&&n.length>0||o&&o.length>0;if(!s){h.debug("Tool execution storage skipped",{hasToolData:s,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){h.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,i)}catch(l){h.warn("Failed to store tool executions",{sessionId:t,userId:r,error:l instanceof Error?l.message:String(l)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:qe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async recordConversationTurn(t){const{sessionId:r,userId:n,turnId:o}=t;uf.assertConversationIdentity(r,n);const i={sessionId:r,userId:n,...o?{turnId:o}:{}};if(!t.userMessage.trim())return{recorded:!1,reason:"empty-user-message",...i};const s=(t.events??[]).some(l=>l.type==="tool:start"||l.type==="tool:end");if(!t.aiResponse.trim()&&!s)return{recorded:!1,reason:"empty-response",...i};if(await this.initializeConversationMemoryForGeneration(t.requestId??`record-turn-${Date.now()}`,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(await this.isOwnedByAnotherUser(r,n))throw new Me({code:qe.INVALID_PARAMETERS,message:"The conversation belongs to another user",category:"validation",severity:"medium",retriable:!1});const a=Date.now();try{await this.conversationMemory.storeConversationTurn({sessionId:r,userId:n,userMessage:t.userMessage,aiResponse:t.aiResponse,startTimeStamp:t.startTime,...t.provider&&t.model?{providerDetails:{provider:t.provider,model:t.model}}:{},enableSummarization:t.enableSummarization,events:t.events?.length?t.events:void 0,requestId:t.requestId,...t.modality?{modality:t.modality}:{},...o?{turnId:o}:{},...t.interrupted?{interrupted:!0}:{},...t.callEnded?{callEnded:!0}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,1)}catch(l){throw this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,2,l instanceof Error?l.message:String(l)),l}return this.shouldWriteMemory(t.memory,n,t.aiResponse)&&this.storeMemoryInBackground({prompt:t.userMessage,response:t.aiResponse.trim(),userId:n,sessionId:r,provider:t.provider??"",model:t.model},t.memory,{sessionId:r}),{recorded:!0,...i}}async getConversationSeed(t){const{sessionId:r,userId:n}=t,o=Math.max(0,Math.floor(t.maxTurns??10)),i=Math.max(0,Math.floor(t.maxChars??6e3));try{uf.assertConversationIdentity(r,n);const s=await this.getSessionMessages(r,n),a=[];for(const d of s)d.role!=="user"&&d.role!=="assistant"||d.metadata?.isSummary||d.metadata?.isSkill||typeof d.content!="string"||!d.content.trim()||a.push({role:d.role,content:d.content,...d.metadata?.modality?{modality:d.metadata.modality}:{}});const l=a.slice(-(o*2));let c=0,u=l.length;for(let d=l.length-1;d>=0&&(c+=l[d].content.length,!(c>i));d-=1)u=d;return l.slice(u)}catch(s){return h.warn("[NeuroLink] getConversationSeed failed, starting unseeded",{error:s instanceof Error?s.message:String(s)}),[]}}async conversationExists(t){return uf.assertConversationIdentity(t.sessionId,t.userId),(await this.getSessionMessages(t.sessionId,t.userId)).length===0?!1:!await this.isOwnedByAnotherUser(t.sessionId,t.userId)}async isOwnedByAnotherUser(t,r){const n=this.conversationMemory;if(!n||n.isRedisConfigured)return!1;const o=await n.getSession(t);return o!==void 0&&o.userId!==r}static assertConversationIdentity(t,r){const n=typeof t!="string"||!t.trim()?"sessionId must be a non-empty string":t.includes(":")?'sessionId must not contain ":"':typeof r!="string"||!r.trim()?"userId must be a non-empty string":void 0;if(n)throw new Me({code:qe.INVALID_PARAMETERS,message:n,category:"validation",severity:"medium",retriable:!1})}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:qe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let i=o.length-1;i>=0;i--)if(o[i].role==="assistant")return o[i]={...o[i],content:r(o[i].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{oe.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(oe.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new fL({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const i of o)this.mcpToolRouter.registerServer(i.id||t);h.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else oe.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?ni(r.url):void 0});return n}catch(n){throw oe.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{oe.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(oe.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?oe.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):oe.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw oe.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}getExternalMCPServerHealth(){return this.externalServerManager.getServerStatuses()}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(i=>i.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let i=r;try{i=this.resolveDirectMcpToolName(t,r),oe.debug(`[NeuroLink] Executing external MCP tool: ${i} on ${t}`);const s=this.getToolAnnotationsForExecution(i),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,l={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},c=this._generationTurnActive?this.toolCacheRepeatKey(i,l):void 0,u=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&this.mcpToolResultCache&&!u){const f=this.mcpToolResultCache.getCachedResult(i,l);if(f!==void 0)return oe.debug(`[NeuroLink] Tool result cache HIT: ${i} on ${t}`),f}const d=await this.externalServerManager.executeTool(t,i,n,o),p=d&&typeof d=="object"?d:void 0,m=!!(p&&"isError"in p&&p.isError===!0||p&&"success"in p&&p.success===!1);return a&&this.mcpToolResultCache&&!m&&d!==void 0&&this.mcpToolResultCache.cacheResult(i,l,d),oe.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${i}`),d}catch(s){throw oe.error(`[NeuroLink] External MCP tool execution failed: ${i}`,s),s}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(s=>s.name);if(o.includes(r))return r;const i=_ee(r,o);if(!i)throw new See(r,t,Mqt(r,o));return Ue.mcp.startActiveSpan("mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":i.name,"mcp.tool_name.repair_strategy":i.strategy,...i.score!==void 0?{"mcp.tool_name.repair_score":i.score}:{}}},s=>s.end()),oe.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${i.name}" (${i.strategy}) on server '${t}'`),i.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Be(Promise.resolve().then(()=>(sne(),SWt)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{oe.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),oe.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw oe.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Be(Promise.resolve().then(()=>(Nsr(),Dsr)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Be(Promise.resolve().then(()=>(zte(),b7t)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Be(Promise.resolve().then(()=>(Gte(),T7t)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Be(Promise.resolve().then(()=>(Zsr(),Hsr)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Be(Promise.resolve().then(()=>(dce(),cce)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Be(Promise.resolve().then(()=>(dce(),cce)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Be(Promise.resolve().then(()=>(iar(),tar)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Be(Promise.resolve().then(()=>(DF(),yce)),1e4),o=t.map(i=>({...i,execute:i.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Be(Promise.resolve().then(()=>(DF(),yce)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Be(Promise.resolve().then(()=>(dA(),m7t)),1e4),i=this.toolRegistry.getToolInfo(t);if(!i)return null;const s=i.tool.annotations,a=r({name:i.tool.name,description:i.tool.description??""}),l=n(a,s);return{annotations:l,summary:o(l)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async i=>{try{oe.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:i});const s=await this.externalServerManager.executeTool(n.serverId,n.name,i,{timeout:3e4});return oe.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!s,hasData:!!(s&&typeof s=="object"&&"content"in s)}),s}catch(s){throw oe.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,s),s}}};r[n.name]=o,oe.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return oe.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),oe.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){oe.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),oe.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){oe.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await omn().then(()=>har),i=await o(this.conversationMemoryConfig);this.conversationMemory=i,this.conversationMemoryNeedsInit=!1}catch(o){throw h.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);oe.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){oe.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const i=new r(o);return await Be(i.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4)),h.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),i}async decide(t){const{sessionId:r,requestId:n}=t;return this.holdTelemetry(),KE({...t.context,sessionId:r??t.context?.sessionId,requestId:n??t.context?.requestId},()=>this.runDecide(t))}resolveDecisionProviderName(t,r){return t??lP(this.resolveCredentials(r))}registeredDecisionModel(t){const r=_r.getProviderInfo(t.name)?.defaultModel;return r||(t.envVars.model?process.env[t.envVars.model]:void 0)||t.defaultModel}decisionLimits(t){const r=this.resolveDecisionProviderName(t?.provider,t?.credentials);if(!r)return null;const n=Gc.get(r.toLowerCase())??r,o=ir.get(n);if(!o)return null;const i=t?.model??this.registeredDecisionModel(o);return Ite(o,i)}decisionHookTimeout(){if(this.decisionHookTimeoutMs!==void 0)return this.decisionHookTimeoutMs;const t=this.decisionHooks?.hookTimeoutMs;let r=O4;return t!==void 0&&(typeof t=="number"&&Number.isFinite(t)&&t>0&&t<=D4?r=t:h.warn(`[Decision] decisionHooks.hookTimeoutMs must be a finite number from 1 to ${D4} ms; using the default ${O4} ms`,{configured:String(t)})),this.decisionHookTimeoutMs=r,r}emitDecisionEvent(t,r){try{this.emitter.emit(t,r)}catch(n){h.warn(`[Decision] a ${t} listener threw`,{error:n instanceof Error?n.message:String(n)})}}async siteDecide(t,r){const n={...t,credentials:r?.credentials??t.credentials,signal:r?.signal&&t.signal?AbortSignal.any([r.signal,t.signal]):r?.signal??t.signal,sessionId:r?.sessionId??t.sessionId,requestId:r?.requestId??t.requestId},o=n.site;if(!o)return this.tryRunDecide(n);if(!this.resolveDecisionProviderName(n.provider,n.credentials))return this.tryRunDecide(n);const i=new Map;let s;try{const a=n.questions,l=Object.keys(a).length,c=this.decisionHooks,u=this.decisionHookTimeout();let d;const p=()=>(d??={state:structuredClone(n.state),questions:structuredClone(a)},d),m=()=>({site:o,...p(),sessionId:n.sessionId,requestId:n.requestId});let f=a;if(c?.extendQuestions){let A;try{A=await Be(Promise.resolve(c.extendQuestions(m())),u,new Error(`extendQuestions exceeded ${u}ms`))??void 0}catch(R){h.warn(`[Decision] extendQuestions hook failed for site "${o}" \u2014 proceeding with NeuroLink's own questions`,{error:R instanceof Error?R.message:String(R)})}const x=A?Object.entries(A):[];if(x.length>0){const R=this.decisionLimits({provider:n.provider,model:n.model,credentials:n.credentials}),C=R?.maxQuestions!==void 0?Math.max(0,R.maxQuestions-l):Number.POSITIVE_INFINITY,M={...a};let O=0,U=0;for(const[D,N]of x){const $=_Yr(N);if($===void 0){O+=1;continue}if(i.size>=C){U+=1;continue}const L=dh(VD,i.size);M[L]=$,i.set(L,D)}O>0&&h.warn(`[Decision] dropped ${O} malformed host question(s) for site "${o}"`),U>0&&R&&h.warn(`[Decision] dropped ${U} host question(s) for site "${o}": ${R.provider} accepts ${R.maxQuestions} per request and NeuroLink asks ${l}`),f=M}}const g=i.size;if(this.emitter.listenerCount("decision:before")>0){const A={site:o,state:p().state,questions:g===0?p().questions:structuredClone(f),hostQuestionCount:g,sessionId:n.sessionId,requestId:n.requestId};this.emitDecisionEvent("decision:before",A)}const y=Date.now(),v=await this.tryRunDecide({...n,questions:f});s=v;const w=Object.create(null),T=Object.create(null);if(v)for(const[A,x]of Object.entries(v.answers)){const R=i.get(A);R===void 0?w[A]=x:T[R]=x}const S=v?structuredClone(v):null,k={site:o,answers:structuredClone(w),hostAnswers:structuredClone(T),latencyMs:v?.latencyMs??Date.now()-y,provider:v?.provider??this.resolveDecisionProviderName(n.provider,n.credentials),model:v?.model,result:S,sessionId:n.sessionId,requestId:n.requestId};if(this.emitDecisionEvent("decision:after",k),!v||!S)return null;if(c?.onAnswers)try{await Be(Promise.resolve(c.onAnswers({...m(),answers:structuredClone(T),result:S})),u,new Error(`onAnswers exceeded ${u}ms`))}catch(A){h.warn(`[Decision] onAnswers hook failed for site "${o}"`,{error:A instanceof Error?A.message:String(A)})}return g===0?v:{...v,answers:w}}catch(a){return h.warn(`[Decision] site "${o}" hook or event handling threw \u2014 ${s===void 0?"deciding with NeuroLink's own questions":"handing the consumer the answers already obtained"}`,{error:a instanceof Error?a.message:String(a)}),s===void 0?this.tryRunDecide(n):s?EYr(s,i):null}}async runDecide(t){const r=this.resolveDecisionProviderName(t.provider,t.credentials),n=Object.keys(t.questions),o=n.length,i=r?ir.get(Gc.get(r.toLowerCase())??r):void 0,s=t.model??(i&&this.registeredDecisionModel(i)),a=t,l=n.filter(TYr).length,c=a.site?{"decision.site":a.site,"decision.host_question_count":l}:{};return dt({name:"decide",tracer:Ue.decision,expectedFailure:()=>!r,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":o,"decision.images.count":t.images?.length??0,...c}},async u=>{if(ts(u,"generation",{model:s,input:{state:t.state,questions:t.questions},metadata:{provider:r,...a.site&&{site:a.site,host_question_count:l}}}),!r){const g=`No decision provider is configured. Set ${CLr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`;throw ts(u,"generation",{level:"WARNING",statusMessage:g}),new Error(g)}const{traceId:d,parentSpanId:p}=mg(),m=Date.now();let f=ke.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":o,"decision.images.count":t.images?.length??0,...c},p,d);try{const g=await to.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof g.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const y=await g.decide({state:t.state,questions:t.questions,images:t.images,video:t.video,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),v=Object.keys(y.answers).length,w=tc(r,y.model,{input:y.usage.inputTokens,output:y.usage.outputTokens,total:y.usage.inputTokens+y.usage.outputTokens});u.setAttribute("gen_ai.response.model",y.model),u.setAttribute("gen_ai.usage.input_tokens",y.usage.inputTokens),u.setAttribute("gen_ai.usage.output_tokens",y.usage.outputTokens),u.setAttribute("decision.answer_count",v),u.setAttribute("decision.media.bytes",y.mediaBytes??0),u.setAttribute("ai.cost.total",w),y.upstreamMs!==void 0&&u.setAttribute("decision.upstream_ms",y.upstreamMs),y.requestId&&u.setAttribute("gen_ai.response.id",y.requestId),ts(u,"generation",{model:y.model,output:y.answers,usageDetails:eK({input:y.usage.inputTokens,output:y.usage.outputTokens}),costDetails:{total:w}}),f.durationMs=Date.now()-m,f=ke.updateAttributes(f,{"ai.model":y.model,"ai.tokens.input":y.usage.inputTokens,"ai.tokens.output":y.usage.outputTokens,"ai.cost.input":w,"ai.cost.output":0,"ai.cost.total":w,"decision.answer_count":v,"decision.media.bytes":y.mediaBytes??0,"decision.latency_ms":y.latencyMs,...y.upstreamMs!==void 0?{"decision.upstream_ms":y.upstreamMs}:{}});const T=ke.endSpan(f,1);return this.metricsAggregator.recordSpan(T),et().recordSpan(T),y}catch(g){f.durationMs=Date.now()-m;const y=ke.endSpan(f,2,g instanceof Error?g.message:String(g));throw this.metricsAggregator.recordSpan(y),et().recordSpan(y),g}})}async tryDecide(t){return this.holdTelemetry(),this.siteDecide(t)}async transcribe(t){const[r,{runTranscribe:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(qar(),Ice))]);return n(t,r)}async*transcribeStream(t){const[r,{runTranscribeStream:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(zmn(),glr))]);yield*n(t,r)}resolveSTTCredentials(t){const r=this.credentials?.stt;if(!r||!t)return t??r;const n={...r};for(const[o,i]of Object.entries(t)){const s=n[o];n[o]=s&&typeof s=="object"&&i&&typeof i=="object"?{...s,...i}:i??s}return n}resolveSTTProvider(t,r){const n=t?.trim();return n?Mv(n)??n:fP(r)}async buildTranscribeDeps(t){await Id.registerAllProviders();const[{STTProcessor:r},{createSTTHandler:n},{STTError:o}]=await Promise.all([Promise.resolve().then(()=>(Wg(),PO)),Promise.resolve().then(()=>(th(),eh)),Promise.resolve().then(()=>(ws(),c_t))]),i=this.resolveSTTCredentials(t),s=l=>{const c=this.resolveSTTProvider(l,i);if(Mv(c)===void 0&&!r.supports(c)&&!fS(i)[c.trim().toLowerCase()])throw o.unknownProvider(c,p3r(i),R2e());return c},a=l=>{if(fS(i)[l.trim().toLowerCase()])return n(l,i);const c=Vf(l);return c?i?.[c.credentialsKey]!==void 0?n(c.name,i):r.getHandler(c.name)??n(c.name):r.getHandler(l)};return{...this.buildSTTCorrectionDeps(),transcribe:(l,c,u)=>r.transcribe(l,c,u,i),resolveProvider:s,getHandler:a}}buildSTTCorrectionDeps(){return{decide:async t=>{const r=await this.tryDecide({state:t.state,questions:t.questions,...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}});return r?{answers:r.answers}:null},rewrite:async t=>{const r=new AbortController,n=setTimeout(()=>r.abort(),t.timeoutMs),o=t.provider??process.env.NEUROLINK_STT_REWRITE_PROVIDER?.trim(),i=t.model??process.env.NEUROLINK_STT_REWRITE_MODEL?.trim(),s={input:{text:t.user},systemPrompt:t.system,...o?{provider:o}:{},...i?{model:i}:{},maxTokens:t.maxTokens,temperature:0,disableTools:!0,memory:{enabled:!1},abortSignal:r.signal};try{const l=(await this.generate(s)).content??"";return t.onPartial&&l&&t.onPartial(l),l}finally{clearTimeout(n)}}}}async tryRunDecide(t){try{const r=await this.decideInBatches(t);return h.shouldLog("debug")&&h.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return h.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async decideInBatches(t){const r=t.provider??lP(this.resolveCredentials(t.credentials)),n=r?Gc.get(r.toLowerCase()):void 0,o=n?ir.get(n)?.decisionLimits?.maxQuestions:void 0,i=UYr(t,o);if(i.length===1)return this.decide(t);const s=[];let a;for(let u=0;u<i.length;u+=Cte){const d=await Promise.allSettled(i.slice(u,u+Cte).map(p=>this.decide(p)));for(const p of d)p.status==="fulfilled"?s.push(p.value):a??=p.reason}const[l,...c]=s;if(l===void 0)throw a instanceof Error?a:new Error(String(a));return c.length+1<i.length&&h.debug(`decide: ${i.length-s.length} of ${i.length} batches failed; using the answers of the rest`),BYr([l,...c])}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let i;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?i={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?i={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:i=o("quality"),r?.passThreshold!==void 0&&(i.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(i.executionMode=r.executionMode);const s=new n(i);await Be(s.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await Be(s.execute(t,{correlationId:r?.correlationId}),a,pe.evaluationTimeout("pipeline execution",a));return h.debug("[NeuroLink] Evaluation completed",{pipeline:i.name,overallScore:l.overallScore,passed:l.passed,scorerCount:l.scores.length}),l}async score(t,r,n){const{ScorerRegistry:o}=await Be(Promise.resolve().then(()=>(FK(),LK)),1e4,pe.evaluationTimeout("scorer module load",1e4));await Be(o.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));const i=await Be(o.getScorer(t,n),3e4,pe.evaluationTimeout(`scorer load: ${t}`,3e4));if(!i)throw pe.scorerNotFound(t);const s=i.validateInput(r);if(!s.valid)throw pe.evaluationValidationFailed(t,s.errors);const a=await Be(i.score(r),6e4,pe.evaluationTimeout("scorer execution",6e4));return h.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Be(Promise.resolve().then(()=>(FK(),LK)),1e4,pe.evaluationTimeout("scorer module load",1e4));await Be(r.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(Nce(),wlr));return h.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(Tlr(),blr));return h.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},i={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:this.observabilityConfig,...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},s=this.workerToolsConfig(o.tools),a=new uf(s?{...i,tools:s}:i);if(t?.shareToolRegistry!==!1)for(const l of this.uncacheableTools)a.uncacheableTools.add(l);if(h.setEventEmitter(n),t?.onLog){const l=t.onLog,c=f=>{try{const g=f??{};l({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},u={emit:(f,...g)=>(f==="log-event"&&c(g[0]),!0)},d=a.logInstanceId;h.addScopedEventEmitter(d,u);const p=()=>{h.removeScopedEventEmitter(d,u),this.ownedWorkerLogBridgeDetachers.delete(p)};this.ownedWorkerLogBridgeDetachers.add(p);const m=a.dispose.bind(a);a.dispose=async()=>{p(),await m()}}return h.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(WA(),TL));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(WA(),TL));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(WA(),TL));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(JA(),kL)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=non(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return Qnn(t??gi(this))}clearTaskState(t){return eon(t??gi(this))}registerDelegationTools(t){if(_on(this,t),this.hasBackgroundDelegationTools)return;const r=Pon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return AYt(this,t)}async collectDelegates(t){return IYt(this,t)}async cancelDelegates(t){return oie(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(h.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{h.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=fJt(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,h.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":zne(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new QWt(this.mcpOutputNormalizerConfig,t)),h.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return Krn(this,t,r)}async readArtifact(t,r){return Jrn(this,t,r)}registerBackgroundCommandTools(t){if(NYt(this,t),this.hasBackgroundCommandTools)return;const r=zon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){NYt(this,t)}async startBackgroundCommand(t,r){return qYt(this,t,r)}getBackgroundCommandStatus(t){return jYt(this,t)}async awaitBackgroundCommand(t,r){return yie(this,t,r)}async killBackgroundCommand(t,r){return VYt(this,t,r)}async readBackgroundCommandOutput(t,r){return DL(this,t,r)}registerGitTools(t){if(Gon(this,t),this.hasGitTools)return;const r=Jon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return oZt(this,t,r)}async executeNetwork(t,r,n){return h.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){h.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(klr(),Slr));return h.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(Alr(),xlr));return h.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(Ilr(),Clr));return h.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){h.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await HYt(this),await oie(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error stopping background work:",r)}try{await this.releaseMemoryCondenser()}catch(r){t.push(r instanceof Error?r:new Error(String(r)))}try{h.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await this.releaseTelemetryHold(),h.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{h.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),h.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),h.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{h.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),h.clearEventEmitter(this.emitter),h.clearScopedEventEmitters(this.logInstanceId),h.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();h.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{h.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),h.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{h.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],h.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{h.debug("[NeuroLink] Shutting down TaskManager..."),await Be(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){h.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{h.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,h.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error resetting state:",r)}t.length===0?h.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):h.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw h.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new Xw({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps({sessionId:t})),i=pa({provider:r?.provider||"openai",conversationMessages:n,toolReplayMode:this.resolveToolReplayModeForBudget({})}),s=Math.floor(i.availableInputTokens*.6),a=await o.compact(n,s,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Nw(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const i=pa({provider:r||"openai",model:n,conversationMessages:o,toolReplayMode:this.resolveToolReplayModeForBudget({})});return{estimatedInputTokens:i.estimatedInputTokens,availableInputTokens:i.availableInputTokens,usageRatio:i.usageRatio,shouldCompact:i.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?pa({provider:r||"openai",model:n,conversationMessages:o.messages,toolReplayMode:this.resolveToolReplayModeForBudget({})}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:i}=await Promise.resolve().then(()=>(VF(),Rlr));r=await i.createProvider(o.type,o.config),n=o.type}this.authProvider=r,h.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(RA(),eL));r.set(t),h.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(RA(),eL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(RA(),eL)),r=t.get()?.user.id;t.clear(),r&&h.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(i=>typeof t[i]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(h.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async i=>{if(typeof t[i]=="function"){const s=await Hne(t[i],o);t[i]=s.value,h.debug(`[NeuroLink] Resolved dynamic ${i}: ${s.resolutionType}`)}})),typeof t.tools=="function"){const i=await Hne(t.tools,o);if(!Array.isArray(i.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof i.value=="object"?"object":typeof i.value}`);t.enabledToolNames=i.value,delete t.tools}}},Hce=new fT,Nlr=Hce}});function lC(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function cC(e){return lC(e)??"image/png"}var gT=E({"src/lib/utils/imageDetection.ts"(){"use strict"}});function Qmn(e){return nx(e)&&cO(e)===null?"video/mp4":Glr.every((t,r)=>e[r]===t)?"video/webm":null}function Llr(e,t,r){const n=t==="image"?lC(e):Qmn(e);return n===null?{status:"error",message:`${r} ${qlr[t]}.`}:{status:"ok",dataUrl:`data:${n};base64,${e.toString("base64")}`}}function Wce(e){return e.length<=Blr?`(${e})`:`(a ${e.length}-character string)`}async function ehn(e,t,r){try{const n=await kP.stat(e);return n.isFile()?n.size>r?{status:"error",message:`${t} ${Wce(e)} is ${n.size} bytes; a request may carry at most ${r}.`}:{status:"ok",buffer:await kP.readFile(e)}:{status:"error",message:`${t} ${Wce(e)} is not a file.`}}catch(n){const o=n instanceof Error&&"code"in n?String(n.code):"unreadable";return{status:"error",message:`Could not read ${t} ${Wce(e)}: ${o}.`}}}async function Flr(e,t,r,n){if(typeof e!="string")return e.length===0?{status:"error",message:`${r} is an empty Buffer.`}:Llr(e,t,r);const o=e.trim();if(o==="")return{status:"error",message:`${r} is an empty string.`};if($lr.test(o))return{status:"error",message:`${r} is a remote URL. Media is not fetched for you; pass a Buffer, a file path or a data: URL.`};if(/^data:/i.test(o))return zlr[t].test(o)?{status:"ok",dataUrl:o}:{status:"error",message:`${r} is a data: URL that is not base64 ${t} content.`};if(Ulr.test(o))return{status:"error",message:`${r} uses an unsupported URL scheme. Pass a Buffer, a file path or a data: URL.`};const i=await ehn(o,r,n);return i.status==="ok"?Llr(i.buffer,t,r):i}async function thn(e,t,r,n){const o=e.images??[];if(o.length===0&&e.video===void 0)return{status:"prepared",media:void 0};if(!t){const l=n.length>0?` Use a decision provider that does: ${n.join(", ")}.`:"";return{status:"refused",message:`${r} does not accept images or video.${l}`}}if(o.length>t.maxImages)return{status:"refused",message:`${r} accepts at most ${t.maxImages} images per request; this one has ${o.length}.`};if(e.video!==void 0&&!t.video)return{status:"refused",message:`${r} does not accept video.`};const i=[];for(const[l,c]of o.entries()){const u=await Flr(c,"image",`Image ${l+1}`,t.maxRequestBytes);if(u.status==="error")return{status:"refused",message:u.message};i.push(u.dataUrl)}let s;if(e.video!==void 0){const l=await Flr(e.video,"video","The video",t.maxRequestBytes);if(l.status==="error")return{status:"refused",message:l.message};s=l.dataUrl}const a=i.reduce((l,c)=>l+c.length,s?.length??0);return{status:"prepared",media:{images:i,...s?{video:s}:{},bytes:a}}}var $lr,Ulr,Blr,zlr,Glr,qlr,rhn=E({"src/lib/utils/decisionMedia.ts"(){"use strict";Kr(),gT(),uO(),$lr=/^https?:\/\//i,Ulr=/^[a-z][a-z0-9+.-]*:\/\//i,Blr=200,zlr={image:/^data:image\/[a-z0-9.+-]+;base64,/i,video:/^data:video\/[a-z0-9.+-]+;base64,/i},Glr=[26,69,223,163],qlr={image:"is not a recognised image format",video:"is not a recognised video format (MP4, MOV or WebM)"}}});function jlr(e){return e.filter(Nr).map(r=>{const n=Array.isArray(r.loc)?r.loc.filter(i=>typeof i=="string"||typeof i=="number").join("."):"",o=typeof r.msg=="string"?r.msg:"invalid";return n?`${n}: ${o}`:o}).slice(0,5).join("; ")||"unspecified field"}function uC(e,t){return(t?e.split(t).join("[redacted]"):e).replace(/\.?\s*Received API Key\s*=[\s\S]*$/,"").replace(/\bsk-[A-Za-z0-9._-]+/g,"[redacted]").replace(/\b[0-9a-f]{32,}\b/gi,"[redacted]").replace(/data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,"[media]").trim()}function nhn(e){let t=e;for(let r=0;r<5&&t instanceof Error;r++){if(t.message==="unexpected redirect")return!0;t=t.cause}return!1}var Kce,Vlr,Jce,dC,yT=E({async"src/lib/providers/systemOneDecision.ts"(){"use strict";_l(),ll(),await hu(),rn(),ct(),rhn(),z(),Lt(),Rte(),j2e(),gS(),gS(),Kce=5e3,Vlr=1,Jce=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",i,{once:!0})}),dC=class extends Ua{proxyFetch;maxRetries;authFailed=!1;constructor(e,t,r){super(e,t,Fh(r)?r:void 0),this.proxyFetch=Dt(),this.maxRetries=Vlr}missingConfigMessage(){}encodeQuestion(e){return this.dialect().encodeQuestion(e)}dialect(){return $7}readRetryAfterMs(e){}defaultTimeoutMs(e,t){return this.getDescriptorDecideMs()}readDecisionPayload(e){return e}reportedConfidence(e){return{}}resolveResponseModel(e,t){return typeof e.model=="string"?e.model:t}diagnosticContext(){return{}}getProviderName(){return this.providerName}getDefaultDecisionModel(){return this.getDefaultModel()}supportsTools(){return!1}getAISDKModel(){throw new Je(`${this.vendorDisplayName()} is a decision-only provider; it generates no text, so chat completions are not available. Use \`decide()\` instead, or pick a different provider for \`generate()\` / \`stream()\`.`,this.providerName)}async executeStream(e,t){throw new Je(`${this.vendorDisplayName()} is a decision-only provider; streaming is not available. Use \`decide()\`, or pick another provider for \`stream()\`.`,this.providerName)}formatProviderError(e){if(e instanceof Je)return e;const t=e instanceof Error?e.message:String(e);return new Je(`${this.vendorLabel()} request failed: ${t}`,this.providerName)}async decide(e){const t=this.vendorLabel();if(!this.decisionApiKey())throw this.decisionError({kind:"authentication",message:this.missingKeyMessage(),retryable:!1});const r=this.missingConfigMessage();if(r)throw this.decisionError({kind:"invalid_request",message:r,retryable:!1});if(this.authFailed)throw this.decisionError({kind:"authentication",message:`${t} rejected this API key earlier; not retrying. Fix the key and construct a new provider.`,retryable:!1});const n=Object.entries(e.questions);if(n.length===0)throw this.decisionError({kind:"invalid_request",message:"At least one question is required.",retryable:!1});const o=e.model??this.modelName??this.getDefaultModel(),i=this.assertWithinDecisionLimits(e,o,n.length),s=Object.fromEntries(n.map(([d,p])=>[d,this.encodeQuestion(p)])),a=await this.prepareMedia(e),l=JSON.stringify(this.buildDecisionBody(e.state,s,o,a));this.assertWithinRequestBytes(l);const c=e.timeoutMs??this.defaultTimeoutMs(n.length,i)??this.defaultTimeout??Kce;let u;for(let d=0;d<=this.maxRetries;d++){const p=Date.now();try{const m=AbortSignal.timeout(c),f=e.signal?AbortSignal.any([e.signal,m]):m,g=await this.proxyFetch(this.decisionEndpoint(o),{method:"POST",headers:this.decisionHeaders(),body:l,signal:f,redirect:"error"}),y=Date.now()-p,v=this.readRequestId(g.headers),w=Number(g.headers.get("x-envoy-upstream-service-time"))||void 0,T=await g.json().catch(()=>null);if(!g.ok){if(u=this.parseDecisionError(g.status,T,v),u.kind==="authentication"&&(this.authFailed=!0,h.warn(`${t}: credential not accepted \u2014 disabling this provider instance. ${u.message}`,{status:u.status,...this.diagnosticContext(),requestId:v})),!u.retryable||d===this.maxRetries)throw this.decisionError(u);const R=this.readRetryAfterMs(g.headers);if(R!==void 0&&R>c-(Date.now()-p))throw this.decisionError(u);await Jce(R??2**d*250+Math.random()*250,e.signal);continue}const S=this.readDecisionPayload(T),k=Nr(S)?this.dialect().readAnswers(S,this.reportedConfidence(S),e.questions):void 0;if(!Nr(S)||!k)throw this.decisionError({kind:"server",message:`${t} returned a response without an answers map.`,status:g.status,requestId:v,retryable:!1});for(const R of k.dropped)h.warn(`${t}: dropped unparseable answer "${R}"`,{requestId:v});for(const R of k.refused??[])h.warn(`${t}: the model declined to answer "${R}"`,{requestId:v});const A={...k.answers},x=Nr(S.usage)?S.usage:{};return{model:this.resolveResponseModel(S,o),provider:this.providerName,answers:A,usage:{inputTokens:Gs(x.input_tokens)??Gs(x.inputTokens)??0,outputTokens:Gs(x.output_tokens)??Gs(x.outputTokens)??0},requestId:v,latencyMs:y,upstreamMs:w,...a?{mediaBytes:a.bytes}:{}}}catch(m){if(m instanceof Je)throw m;const f=e.signal?.aborted===!0,g=m instanceof Error&&m.name==="TimeoutError",y=nhn(m);if(u={kind:f?"network":g?"timeout":"network",message:y?`${t} answered with a redirect, which is refused so the decision is not sent anywhere else. Point the base URL at the final address.`:uC(Av(m instanceof Error?m.message:String(m)),this.decisionApiKey()),retryable:!f&&!y},!u.retryable||d===this.maxRetries)throw this.decisionError(u);await Jce(2**d*250+Math.random()*250)}}throw this.decisionError(u??{kind:"network",message:`${t} request failed.`,retryable:!1})}async prepareMedia(e){const t=ir.get(this.providerName)?.decisionLimits,r=await thn(e,t?.media,this.vendorLabel(),ALr({video:e.video!==void 0}));if(r.status==="refused")throw this.decisionError({kind:"invalid_request",message:r.message,retryable:!1});return r.media}assertWithinRequestBytes(e){const t=ir.get(this.providerName)?.decisionLimits?.media,r=t?.maxRequestBytes;if(r===void 0)return;const n=Buffer.byteLength(e);if(n>r)throw this.decisionError({kind:"invalid_request",message:`The request is ${n} bytes; ${this.vendorLabel()} accepts at most ${r}. Send fewer or smaller images${t?.video?", or a shorter video":""}.`,retryable:!1})}assertWithinDecisionLimits(e,t,r){const n=ir.get(this.providerName),o=n?Ite(n,t):null;if(!o||!o.enforcedLocally)return 0;const i=this.vendorLabel();if(o.maxQuestions!==void 0&&r>o.maxQuestions)throw this.decisionError({kind:"max_tokens_exceeded",message:`${i} accepts at most ${o.maxQuestions} questions per request; this one has ${r}. Ask fewer, or use a decision provider without this cap.`,retryable:!1});const{maxStateTokens:s}=o,a=J9t(e.state,o);if(a>s)throw this.decisionError({kind:"max_tokens_exceeded",message:`The state is ~${a} tokens; ${i}'s "${t}" model reads at most ${s}. Shorten the state, or use a decision provider with a larger window.`,retryable:!1});return a}decisionError(e){const t=new Je(e.message,this.providerName);return Object.defineProperty(t,"cause",{value:e,enumerable:!1,writable:!0,configurable:!0}),t}}}}),Xce,ohn=E({async"src/lib/providers/decide/formatters.ts"(){"use strict";await yT(),Xce={"fastapi-validation":e=>`Request failed validation \u2014 ${jlr(Array.isArray(e)?e:[])}`}}});function Hlr(e,t){const r=t.split(".");if(r.some(o=>o===""))return;let n=e;for(const o of r){if(typeof n!="object"||n===null||Array.isArray(n))return;const i=Object.getOwnPropertyDescriptor(n,o);if(i===void 0||!("value"in i))return;n=i.value}return n}var Wlr=E({"src/lib/providers/decide/paths.ts"(){"use strict"}});function ihn(e){const t=Zce.get(e);if(t)return t;const r=new RegExp(e,"i");return Zce.set(e,r),r}function shn(e,t,r){return((e.status===void 0?[]:typeof e.status=="number"?[e.status]:e.status).includes(t)||e.statusMin!==void 0&&t>=e.statusMin)&&(e.messagePattern===void 0||ihn(e.messagePattern).test(r.slice(0,Jlr)))}function ahn(e,t){if(e.isArray)return Array.isArray(t)&&e.formatter?Xce[e.formatter](t):void 0;if(!(typeof t!="string"||t.length===0))return e.formatter?Xce[e.formatter](t):t}function lhn(e,t){for(const r of e){const n=ahn(r,Hlr(t,r.path));if(n!==void 0)return{shape:r,text:n}}}function chn(e,t){const{status:r,payload:n,requestId:o,label:i,apiKey:s}=t,a=uC(`${i} request failed with HTTP ${r}`,s),l=lhn(e.bodyShapes,n),c=l?.text&&uC(l.text,s)||a,u=e.rules.find(f=>shn(f,r,c)),d=u?.kind??e.default,p=u?.retryable??Yce(d),m=(f,g)=>({kind:f,message:c,status:r,requestId:o,retryable:g});if(l){const{shape:f}=l;return m(f.kind??d,f.retryable??(f.kind===void 0?p:Yce(f.kind)))}return m(d,p)}var Klr,Yce,Jlr,Zce,uhn=E({async"src/lib/providers/decide/errors.ts"(){"use strict";await yT(),await ohn(),Wlr(),Klr=new Set(["rate_limit","overloaded","server"]),Yce=e=>Klr.has(e),Jlr=2e3,Zce=new Map}});function dhn(e,t){if(/[{}]/.test(e.replace(Qce,"")))throw new Error(`Decide endpoint template "${e}" has an unmatched brace; write placeholders as {baseURL}.`);return e.replace(Qce,(r,n)=>{if(n!=="baseURL")throw new Error(`Decide endpoint template "${e}" uses an unknown placeholder {${n}}; the only one supported is {baseURL}.`);return t.baseURL})}var Qce,phn=E({"src/lib/providers/decide/template.ts"(){"use strict";Qce=/\{([^{}]*)\}/g}}),Xlr={};ie(Xlr,{ConfiguredDecisionProvider:()=>Ylr});var vT,Ylr,mhn=E({async"src/lib/providers/configuredDecision.ts"(){"use strict";z(),Lt(),oi(),Mm(),N7(),k3r(),await uhn(),gS(),Wlr(),phn(),await yT(),vT=e=>typeof e=="string"?e.trim():"",Ylr=class extends dC{entry;apiKey;baseURL;endpoint;constructor(e,t,r,n){super(t||Ji(Vo(e,"model"),e.models.default),e.id,r),this.entry=e,this.apiKey=vT(n?.apiKey)||vT(process.env[Vo(e,"apiKey")]),this.baseURL=h3r(vT(n?.baseURL)||vT(process.env[Vo(e,"baseURL")])||vT(e.wire.baseURL),e.decide.baseURLNormalize??[]),this.endpoint=dhn(e.decide.endpoint,{baseURL:this.baseURL}),h.debug(`${e.displayName} Provider initialized (decide only)`,{modelName:this.modelName,baseURL:this.baseURL?Qt(this.baseURL):"(not set)"})}getDefaultModel(){return Ji(Vo(this.entry,"model"),this.entry.models.default)}vendorLabel(){return this.entry.displayName}vendorDisplayName(){return this.entry.displayName}decisionApiKey(){return this.apiKey}missingKeyMessage(){return`${this.entry.displayName} requires an API key. Set ${Vo(this.entry,"apiKey")} or pass credentials.${Cv(this.entry)}.apiKey.`}missingConfigMessage(){const{baseURLRequired:e,baseURLShape:t}=this.entry.decide;return this.baseURL?t?g3r(t,this.baseURL,this.entry.displayName,`Set ${Vo(this.entry,"baseURL")} or pass credentials.${Cv(this.entry)}.baseURL to the origin, and give the key through ${Vo(this.entry,"apiKey")} or credentials.${Cv(this.entry)}.apiKey.`):void 0:e?`${this.entry.displayName} requires a base URL. Set ${Vo(this.entry,"baseURL")} or pass credentials.${Cv(this.entry)}.baseURL.`:void 0}decisionEndpoint(){return this.endpoint}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r,n){const{placement:o,alias:i}=this.entry.decide.model;return this.dialect().buildBody({state:e,questions:t,model:o==="body-unless-alias"&&r===i?void 0:r,media:n,mediaKeys:this.entry.decide.media})}parseDecisionError(e,t,r){return chn(this.entry.decide.errors,{status:e,payload:t,requestId:r,label:this.entry.displayName,apiKey:this.apiKey})}readRequestId(e){for(const t of this.entry.decide.requestIdHeaders??[]){const r=e.get(t);if(r!==null)return r}}resolveResponseModel(e,t){if(!Nr(e))return t;for(const r of this.entry.decide.response?.modelPaths??[]){const n=Hlr(e,r);if(typeof n=="string")return n}return super.resolveResponseModel(e,t)}dialect(){return H2e(this.entry.decide.dialect)}}}});async function Qy(e,t){try{await e}catch(r){h.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var eue=E({"src/lib/utils/drainDetachedPump.ts"(){"use strict";z()}});function e0(e,t,r){return async(n,o)=>{const i=()=>Promise.resolve(t(n,o));r.onProgress?.();try{const s=r.abortSignal?Ku(i(),r.abortSignal):i();return await(r.toolTimeoutMs===void 0||r.toolTimeoutMs===null?s:St(s,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var WF=E({"src/lib/core/toolExecutionGuards.ts"(){"use strict";ny()}});function hhn(e,t){const r=Qlr[e];return Math.round(t.min+r*(t.max-t.min))}function tue(e,t){if(!e?.enabled&&!e?.thinkingLevel)return;const r=e.thinkingLevel??Zlr;if(t&&!cXr(t)){const n=uXr(t);if(n)return{includeThoughts:!0,thinkingBudget:hhn(r,n)};rue.has(t)||(rue.add(t),h.warn(`[thinkingConfig] "${t}" has no verified Gemini thinkingBudget range; omitting thinkingConfig \u2014 requested thinkingLevel is silently disabled.`));return}return{includeThoughts:!0,thinkingLevel:r}}var Zlr,Qlr,rue,ecr=E({"src/lib/utils/thinkingConfig.ts"(){"use strict";RD(),z(),Zlr="high",Qlr={minimal:0,low:.25,medium:.55,high:1},rue=new Set}});function fhn(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function ghn(e){if(mcr.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>YF&&(t=t.slice(0,YF)),t}function yhn(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,i=`${e.slice(0,YF-n.length)}${n}`;if(!t(i))return i;r++}}function $h(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],i=o.filter(c=>c.type!=="null"&&c.type!=="undefined");if(i.length===1){const c=$h({...i[0]});return c.nullable=!0,e.description&&(c.description=e.description),c}const s=i.map(c=>c.type||"unknown").join(" | "),a={type:"string"},l=e.description?`${e.description} (accepts: ${s})`:`Value as string (accepts: ${s})`;return a.description=l,o.some(c=>c.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const i={};for(const[s,a]of Object.entries(o))a&&typeof a=="object"?i[s]=$h(a):i[s]=a;t[n]=i}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(i=>i&&typeof i=="object"?$h(i):i):t[n]=$h(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>$h(n))),t.not&&typeof t.not=="object"&&(t.not=$h(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=$h(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function tcr(e,t){const r=[],n=new _T,o=[],i=[],s=new Set(t??[]),a=new Map;for(const[l,c]of Object.entries(e))try{const u=ghn(l),d=yhn(u,f=>s.has(f));a.set(d,l),d!==l&&i.push({from:l,to:d});const p={name:d,description:c.description||`Tool: ${d}`},m=c;if(m.parameters||c.inputSchema){let f;const g=m.parameters||c.inputSchema;CJ(g)?f=Wo(g,"openApi3"):typeof g=="object"?f=g:f={type:"object",properties:{}},f.jsonSchema&&typeof f.jsonSchema=="object"&&!f.type&&(f=f.jsonSchema),p.parametersJsonSchema=$h(Qn(f))}r.push(p),s.add(d),c.execute&&n.set(p.name,c.execute)}catch(u){o.push(l),h.error(`[buildNativeToolDeclarations] Failed to convert tool "${l}":`,u)}return o.length>0&&h.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),i.length>0&&h.warn(`[buildNativeToolDeclarations] ${i.length} tool name(s) sanitized for Google's function-name regex: ${i.map(l=>`"${l.from}" -> "${l.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function KF(e,t,r){const n={},o=(i,s)=>r?e0(i,s,r):async(a,l)=>s(a,l);if(e){for(const[i,s]of e.originalNameMap){const a=e.executeMap.get(i);a&&(n[s]={execute:o(s,a)})}return n}for(const[i,s]of Object.entries(t??{})){const a=s?.execute;a&&(n[i]={execute:o(i,a)})}return n}function vhn(e,t){if(!e)return[];const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([i])=>!r.has(i));if(n.length===0)return[];const o=tcr(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[i,s]of o.originalNameMap)t.originalNameMap.set(i,s);for(const[i,s]of o.executeMap)t.executeMap.set(i,s);return h.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([i])=>i).join(", ")}`),n.map(([i])=>i)}function rcr(e,t){const r=qc("google-ai",e.model,{temperature:e.temperature??1,topP:e.topP},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},...r.topP!==void 0&&{topP:r.topP},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=tue(e.thinkingConfig,e.model);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function ncr(e){const t=e||ms;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),lue):Math.min(ms,lue)}function t0(e){switch(e){case"MAX_TOKENS":case"CONTINUATION":return"length";case"TOO_MANY_TOOL_CALLS":return"tool-calls";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"LANGUAGE":case"IMAGE_SAFETY":case"IMAGE_PROHIBITED_CONTENT":case"IMAGE_RECITATION":return"content-filter";default:return"stop"}}function whn(e,t){return t?e?`${e}
|
|
1970
|
+
IMPORTANT: You have a tool called "${l.toolName}" that searches through`,`${l.filesLoaded} loaded document(s) containing ${l.chunksIndexed} indexed chunks.`,`ALWAYS use the "${l.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+c,h.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){h.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const i=Lsn(t),s=Fsn(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(s.input.text=l)}return{enhancedOptions:s,factoryResult:i}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Xx(),DGt)),i=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],s=t.model;i.length>0&&s&&(i.some(l=>s.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,h.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:i.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=this.conversationEventContext.getStore(),o=new Set,i=g=>{if(!(!g||typeof g!="object"||!("payload"in g)||!g.payload||typeof g.payload!="object"||!("confirmationId"in g.payload)||typeof g.payload.confirmationId!="string"))return g.payload.confirmationId},s=(g,y,v)=>{const w=n!==void 0&&this.conversationEventContext.getStore()===n,T=v!==void 0&&o.has(v);!w&&!T||t.push({type:g,seq:r++,timestamp:Date.now(),...y&&typeof y=="object"?y:{data:y}})},a=(...g)=>{const y=g[0];s("response:chunk",{content:y})},l=(...g)=>{const y=g[0];s("tool:start",{...y,toolName:y.toolName??y.tool})},c=(...g)=>{const y=g[0],v=y.toolName??y.tool,w=y.responseTime??y.duration,T=y.success??(y.error!==void 0?!1:void 0),S={...y,toolName:v,...w!==void 0?{responseTime:w}:{},...T!==void 0?{success:T}:{},...y.error!==void 0?{error:y.error}:{}};s("tool:end",S),S.result&&S.result.uiComponent===!0&&s("ui-component",{toolName:v,componentData:S.result,timestamp:Date.now(),...T!==void 0?{success:T}:{},...w!==void 0?{responseTime:w}:{}})},u=(...g)=>{const y=g[0];y&&typeof y=="object"&&"type"in y&&typeof y.type=="string"&&"data"in y&&y.data&&typeof y.data=="object"&&!Array.isArray(y.data)&&s(y.type,{data:y.data})},d=(...g)=>{s("ui-component",g[0])},p=(...g)=>{if(n!==void 0&&this.conversationEventContext.getStore()===n){const y=i(g[0]);y!==void 0&&o.add(y),s("hitl:confirmation-request",g[0])}},m=(...g)=>{const y=i(g[0]);y!==void 0&&o.has(y)&&(s("hitl:confirmation-response",g[0],y),o.delete(y))};return this.emitter.on("response:chunk",a),this.emitter.on("tool:start",l),this.emitter.on("tool:end",c),this.emitter.on("ui-component",d),this.emitter.on("host:conversation-event",u),this.emitter.on("hitl:confirmation-request",p),this.emitter.on("hitl:confirmation-response",m),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",a),this.emitter.off("tool:start",l),this.emitter.off("tool:end",c),this.emitter.off("ui-component",d),this.emitter.off("host:conversation-event",u),this.emitter.off("hitl:confirmation-request",p),this.emitter.off("hitl:confirmation-response",m)}}}async*handleStreamFallback(t,r,n,o,i,s){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const f=this._metricsTraceContext;let g=ke.createGenerationSpan({provider:i,model:o.model||"unknown",name:`gen_ai.${i}.stream.failed`,traceId:f?.traceId,parentSpanId:f?.parentSpanId});g=ke.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),et().recordSpan(g)}catch{}const l=o.fallbackProvider?.trim()||void 0,c=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,p=HL.getFallbackRoute(n||o.input.text||"",{provider:i,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),m={...p,provider:l??u??p.provider,model:c??d??p.model};h.warn("Retrying with fallback provider",{originalProvider:i,fallbackProvider:m.provider,fallbackModel:m.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const f=await to.createProvider(m.provider,m.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));f.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(x,R)=>this.executeTool(x,R,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await ch(this.conversationMemory,{prompt:o.input.text,context:o.context});f.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await f.stream({...this.deferProviderStreamTTS(o),model:m.model,conversationMessages:g}),v=y.toolCalls??[],w=y.toolResults??[];(v.length>0||w.length>0)&&(r.toolCalls=v,r.toolResults=w,r.finishReason=y.finishReason??r.finishReason);let T=0,S=0;for await(const x of y.stream){T++;const R=x!==null&&typeof x=="object"&&"metadata"in x&&x.metadata?.noOutput===!0,C=x&&"content"in x&&typeof x.content=="string"&&x.content.length>0,M=x!==null&&typeof x=="object"&&"type"in x&&(x.type==="audio"||x.type==="tts_audio"||x.type==="image");!R&&(C||M)&&S++,x&&"content"in x&&typeof x.content=="string"&&(s(x.content),this.emitter.emit("response:chunk",x.content)),yield x}const k=y.toolCalls??[],A=y.toolResults??[];if(S===0&&k.length===0&&A.length===0)throw new Error(`Fallback provider ${m.provider} also returned 0 real output chunks (chunkCount=${T}, sentinel-only or empty)`);r.toolCalls=k,r.toolResults=A,r.finishReason=y.finishReason??r.finishReason,t.fallbackProvider=m.provider,t.fallbackModel=m.model,t.guardrailsBlocked=!0}catch(f){const g=f instanceof Error?f.message:String(f);throw t.error=`${a}; Fallback failed: ${g}`,h.error("Fallback provider failed",{fallbackProvider:m.provider,error:g}),f}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:i,startTime:s,eventSequence:a,resultToolsUsed:l}=t;h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:iP(sP(r)),sessionId:r.context?.sessionId});const c=a.some(u=>u.type==="tool:start"||u.type==="tool:end");if(!i.trim()&&!c){h.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(h.shouldLog("debug")&&h.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:iP(sP(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const u=r.context?.sessionId,d=r.context?.userId;let p;r.model&&(p={provider:n,model:r.model});const m=Date.now();try{const f=this.drainPendingSkillMessages(u);await this.conversationMemory.storeConversationTurn({sessionId:u,userId:d,userMessage:o??"",aiResponse:i,startTimeStamp:new Date(s),providerDetails:p,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...f.length>0?{skillMessages:f}:{},...r.modality?{modality:r.modality}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),h.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:u,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(f){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,f instanceof Error?f.message:String(f)),h.warn("Failed to store stream conversation turn",{error:f instanceof Error?f.message:String(f)})}}if(this.shouldWriteMemory(r.memory,r.context?.userId,i)){const u=r.context?.sessionId,d=[...new Set(l??[])];this.storeMemoryInBackground({prompt:o??"",response:i.trim(),userId:r.context?.userId,...typeof u=="string"?{sessionId:u}:{},provider:n,model:r.model,...d.length>0?{toolsUsed:d}:{}},r.memory,r.context)}}async validateStreamInput(t){const r=process.hrtime.bigint();h.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),i=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!i)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=t.provider&&t.provider!=="auto"?t.provider:this.getOrchestratedPreferredProvider(t),n=await Vb(r),o=await to.createProvider(n,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await o.ensureModelLimits?.(),o.setTraceContext(this._metricsTraceContext),o.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let i=await this.getAllAvailableTools();i=this.applyToolInfoFiltering(i,t),_r.getDescriptor(n)?.toolSupport==="none"&&(i=[]);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,i,o.supportsTools?.()??!0),a=t.conversationMessages!==void 0,l=a?t.conversationMessages:await ch(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=l;let c=l;const u=pa({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:i,compactionThreshold:t.compactionThreshold}),d=c?.length||0,p=this.getCompactionSessionId(t),m=d>0;if(!u.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:u.estimatedInputTokens,budget:u.availableInputTokens,provider:n,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Ba(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${u.estimatedInputTokens} tokens, budget: ${u.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:u.estimatedInputTokens,availableTokens:u.availableInputTokens,stagesUsed:[],breakdown:u.breakdown})}if(u.shouldCompact&&(a||this.conversationMemory)&&d>(this.lastCompactionMessageCount.get(p)??0)){const y=await new Xw({provider:n,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps(this.decisionSiteContext(t,p))).compact(c,BD(u,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});y.compacted&&(c=Nw(y.messages).messages,t.conversationMessages=c,this.lastCompactionMessageCount.set(p,c.length));const v=pa({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:i});if(!v.withinBudget){h.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:n,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=Gee(c,v.availableInputTokens,v.breakdown,n),t.conversationMessages=c;const w=pa({provider:n,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,toolReplayMode:this.resolveToolReplayModeForBudget(t),conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:i});if(!w.withinBudget){this.lastCompactionMessageCount.delete(p);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:w.estimatedInputTokens,budget:w.availableInputTokens,provider:n,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Ba(`Stream context exceeds model budget after all compaction stages. Estimated: ${w.estimatedInputTokens} tokens, Budget: ${w.availableInputTokens} tokens.`,{estimatedTokens:w.estimatedInputTokens,availableTokens:w.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:w.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let w=null;for(let T=0;T<y;T++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const S=g.selectNext(v);if(!S)break;v.add(g.memberKey(S));const k=S.provider,A=S.model??void 0,x=S.region??void 0;h.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:A,attempt:T});try{const R=await to.createProvider(k,A,!t.disableTools,this,x,this.resolveCredentials(t.credentials));R.setTraceContext(this._metricsTraceContext),R.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(U,D)=>this.executeTool(U,D,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),R.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const C=await R.stream({...this.deferProviderStreamTTS(t),provider:k,model:A,region:x,systemPrompt:s,conversationMessages:c});h.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const M=S,O=(async function*(){try{yield*C.stream,g.recordSuccess(M)}catch(U){throw g.recordFailure(M,Hb(U)),U}})();return zw(C,{...C,stream:O,provider:k,model:C.model||A,toolCalls:C.toolCalls??[],toolResults:C.toolResults??[]})}catch(R){if(or(R))throw R;if(Vce(R)){const C=R instanceof Error?R.message:String(R);throw g.recordFailure(S,Hb(R)),new Error(`[ModelPool] non-retryable: ${C}`,{cause:R})}g.recordFailure(S,Hb(R)),w=R instanceof Error?R:new Error(String(R)),h.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:w.message})}}throw new Error(`[ModelPool] all stream members failed: ${w?.message??"no stream members available"}`)}o.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const f=await o.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:c});return h.debug("[createMCPStream] Stream created successfully",{provider:n,systemPromptPassedLength:s.length}),zw(f,{...f,provider:n,model:f.model||t.model,toolCalls:f.toolCalls??[],toolResults:f.toolResults??[]})}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){const o=n.sourceResult,i={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},s={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},i)},a=Object.getOwnPropertyDescriptor(t,"toolCalls");a&&Object.defineProperty(s,"toolCalls",a);const l=Object.getOwnPropertyDescriptor(t,"toolResults");l&&Object.defineProperty(s,"toolResults",l);const c=Object.getOwnPropertyDescriptor(t,"finishReason");if(c&&Object.defineProperty(s,"finishReason",c),!o)return s;const u=new Set(["finishReason","stopReason","rawFinishReason","toolCalls","toolResults"]);for(const d of Object.getOwnPropertyNames(o)){const p=Object.getOwnPropertyDescriptor(o,d);!u.has(d)&&p&&typeof p.get=="function"&&Object.defineProperty(s,d,p)}return Object.defineProperty(s,"metadata",{enumerable:!0,configurable:!0,get:()=>(o.metadata===void 0&&(o.metadata={}),Object.assign(o.metadata,i)),set:d=>{o.metadata=d}}),s}async handleStreamError(t,r,n,o,i,s){if(t instanceof Ba)throw t;h.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,l=Date.now()-n,c=await Vb(r.provider),u=await to.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));u.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await u.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let p="";return{stream:(async function*(f){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(p+=g.content,f.emitter.emit("response:chunk",g.content)),yield g}finally{if(p.trim()){h.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{const g=r.model||"unknown",y=Date.now()-n;f.emitter.emit("stream:complete",{content:p,provider:c,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}}),f.emitter.emit("generation:end",{provider:c,model:g,responseTime:y,timestamp:Date.now(),result:{content:p,usage:{input:0,output:0,total:0},model:g,provider:c,finishReason:"stop"},success:!0,streamed:!0})}catch{}}if(f.conversationMemory&&i?.context?.sessionId&&p.trim()){const g=i?.context?.sessionId,y=i?.context?.userId;let v;r.model&&(v={provider:c,model:r.model});const w=Date.now();try{const T=g||r.context?.sessionId,S=f.drainPendingSkillMessages(T);await f.conversationMemory.storeConversationTurn({sessionId:T,userId:y||r.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:i?.enableSummarization,requestId:i?.context?.requestId||r.context?.requestId,...S.length>0?{skillMessages:S}:{}}),f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,1)}catch(T){f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,2,T instanceof Error?T.message:String(T)),h.warn("Failed to store fallback stream conversation turn",{error:T instanceof Error?T.message:String(T)})}}}})(this),provider:c,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:l,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}fileToolRootsFor(t){return SW(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=s2({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return s2({perCall:t,instance:this.toolsConfig?.fileRoots})}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(i){const s=i instanceof Error?i.message:String(i),a=s.toLowerCase();return i instanceof W0?{provider:r,status:"denied",detail:s}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:s}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:s}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:s}:{provider:r,status:"unknown",detail:s}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,i={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,i),this.currentStreamToolExecutions.push(i),this.emitter.emit("tool:start",Yx(t,{input:r,timestamp:n,executionId:o})),h.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,i=Date.now(),s){const a=o||i-1e3,l=i-a,c=!n;let u;s?u=this.activeToolExecutions.get(s):u=Array.from(this.activeToolExecutions.values()).find(m=>m.tool===t&&!m.endTime);const d=s||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=i,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const p={tool:t,startTime:a,endTime:i,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",Yx(t,{result:r,error:n,success:c,responseTime:l,timestamp:i,duration:l,executionId:d})),h.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:l,success:c,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(CJ(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const s=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],p=d?.abortSignal,m=p?AbortSignal.any([p,u]):u,f={...d,abortSignal:m};return Promise.race([s(c[0],f),new Promise((g,y)=>{m.addEventListener("abort",()=>{u.aborted?y(pe.toolTimeout(l,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const i=Arn(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(i),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw h.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},h.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,h.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),h.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),h.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new il("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new il("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Be(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0})),r=new Map;for(const o of t){const i=o.inputSchema||o.parameters;h.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!i,effectiveSchemaType:typeof i,effectiveSchemaHasProperties:!!i?.properties,effectiveSchemaHasRequired:!!i?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(s,a)=>{const l=this.toolExecutionContext||{},c=a&&er(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return h.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(l),runtimeContextKeys:Object.keys(c),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,s,u)}})}this.cachedFileTools||(this.cachedFileTools=o7t(this.fileRegistry));const n=this.cachedFileTools;for(const[o,i]of Object.entries(n))if(!r.has(o)){const s=i,a=s.inputSchema??s.parameters;r.set(o,{name:o,description:i.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await i.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{oe.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),oe.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw oe.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>ma({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return Ue.mcp.startActiveSpan(t,{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize}},i=>(ts(i,"tool",{input:r}),this.executeToolWithSpan(t,r,n,o,i)))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),i=o?"mcp":this.getCustomTools().has(t)?"custom":"external",s=r?xv(r):"",a=Date.now(),l=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:l,externalTool:o,toolType:i,inputSize:s.length,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,i){try{const s=await this.prepareToolExecutionState(t,r,n,o),a=await this.runPreparedToolExecution(t,r,s,o,i),l=er(a)&&"isError"in a&&a.isError===!0;return ts(i,"tool",{output:a,...l&&{level:"ERROR",statusMessage:XN(a)}}),a}catch(s){const a=s instanceof Error?s.message:String(s);throw ts(i,"tool",{level:"ERROR",statusMessage:a}),s instanceof Me||(i.recordException(s instanceof Error?s:new Error(a)),i.setStatus({code:ze.ERROR,message:a})),s}finally{i.end()}}async prepareToolExecutionState(t,r,n,o){h.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:er(r)?Yrt(r):r,hasExternalManager:!!this.externalServerManager}),h.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",Yx(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const i=this.toolRegistry.getToolInfo(t),s=n?.timeout??i?.tool?.timeoutMs??Gl.EXECUTION_BATCH_MS,a=n?.maxRetries??i?.tool?.maxRetries??bi.DEFAULT,l=n?.retryDelayMs||oo.BASE_MS,c={timeout:s,maxRetries:a,totalTimeout:n?.totalTimeoutMs??i?.tool?.totalTimeoutMs??s*(a+1)+l*a,retryDelayMs:l,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:u}=await Promise.resolve().then(()=>(V1(),Jb)),d=u.getMemoryUsageMB(),m=`${o.externalTool?.serverId||i?.tool?.serverId||"unknown"}.${t}`;let f=this.toolCircuitBreakers.get(m);f||(f=new rP(PR.FAILURE_THRESHOLD,wB),this.toolCircuitBreakers.set(m,f));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:c,startMemory:d,circuitBreaker:f,breakerKey:m,metrics:g}}async runPreparedToolExecution(t,r,n,o,i){let s=0;try{oe.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=n.finalOptions.maxRetries+1,l=n.finalOptions.totalTimeout,c=Date.now(),u=c+l;let d=0;const p=await n.circuitBreaker.execute(async()=>rCe(async()=>{d++;const m=u-Date.now();if(m<=0)throw pe.toolTimeout(t,l,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c,exhausted:!0});const f=Math.min(n.finalOptions.timeout,m);return Be(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),f,pe.toolTimeout(t,f,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:l,elapsedMs:Date.now()-c}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:m=>Date.now()+n.finalOptions.retryDelayMs<u&&F9(m),onRetry:(m,f)=>{s=m,oe.warn(`[${o.functionTag}] Retrying tool execution (attempt ${m})`,{toolName:t,error:f.message,attempt:m})}}));return i.setAttribute("tool.retry_count",s),await this.handleSuccessfulToolExecution(t,p,n,o,i)}catch(a){return i.setAttribute("tool.retry_count",s),this.handleFailedToolExecution(t,r,a,n,o,i)}}async handleSuccessfulToolExecution(t,r,n,o,i){const s=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=s,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+s)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(V1(),Jb)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&oe.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:s}),oe.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:s,memoryDelta:c,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,p=d?u?.content:void 0,m=d?p?.filter(f=>f.type==="text"&&f.text).map(f=>f.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}oe.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const f=Vmn(m??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${f})] `;if(u&&Array.isArray(p)){const w=p.map(T=>({...T}));for(const T of w)if(T.type==="text"&&T.text){T.text=g+T.text;break}u.content=w}i.setAttribute("tool.error.message",(m??"Unknown error").substring(0,500)),i.setAttribute("tool.error.category",f),i.setStatus({code:ze.ERROR,message:`MCP tool returned isError: ${(m??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-s)/(y-1):0;const v=Hmn(f);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&m?new Error(m):void 0,o.executionId),i.setAttribute("tool.result.status",d?"error":"success"),i.setAttribute("tool.duration_ms",s),r}async handleFailedToolExecution(t,r,n,o,i,s){o.metrics.failedExecutions++;const a=Date.now()-i.executionStartTime;if(n instanceof fm)return oe.warn(`[${i.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),i.executionId),s.setAttribute("tool.result.status","circuit_breaker_open"),s.setAttribute("tool.duration_ms",a),s.setAttribute("tool.circuit_breaker.state",n.breakerState),s.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),s.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),s.setStatus({code:ze.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let l;if(n instanceof Me)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=pe.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=pe.toolNotFound(t,fVr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=pe.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=pe.networkError(t,n):l=pe.toolExecutionFailed(t,n);else l=pe.toolExecutionFailed(t,new Error(String(n)));const c=l.category||"execution";throw o.metrics.errorCategories[c]=(o.metrics.errorCategories[c]||0)+1,this.emitToolEndEvent(t,i.executionStartTime,!1,void 0,l,i.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new Me({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),nCe(l),s.setAttribute("tool.result.status","error"),s.setAttribute("tool.duration_ms",a),s.recordException(l),s.setStatus({code:ze.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const i="NeuroLink.executeToolInternal",s=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!s?.destructiveHint,l=this.mcpToolResultCache,c=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,c):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&l&&!d){const f=l.getCachedResult(t,c);if(f!==void 0)return h.debug(`[${i}] Cache HIT for tool: ${t}`),f}else d&&h.debug(`[${i}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const p=async f=>{if(this.mcpToolMiddlewares.length===0)return f();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:s,execute:async()=>({})},r,{toolMeta:{name:t,annotations:s}},y)}return f()};return await y()},m=async()=>{const f=this.externalServerManager.getAllTools(),g=f.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},w=this.mcpToolRouter.route(v);y=g.find(T=>T.serverId===w.serverId)||g[0],h.debug(`[${i}] Router selected server: ${w.serverId}`,{strategy:w.strategy,confidence:w.confidence})}catch(v){h.warn(`[${i}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(h.debug(`[${i}] External MCP tool search:`,{toolName:t,externalToolsCount:f.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{oe.debug(`[${i}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return h.debug(`[${i}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw h.error(`[${i}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},w=n.authContext||{},T=QS({...v,...w,hitlState:o},this.resolveFileToolRoots(void 0));h.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(T)});const S=await this.toolRegistry.executeTool(t,r,T);if(S&&typeof S=="object"&&"success"in S&&S.success===!1){const k=S.error||"Tool execution failed",A=new Error(k);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return S}catch(v){const w=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",w),v instanceof Error&&v.message.includes("not found")){const T=await this.getAllAvailableTools();throw pe.toolNotFound(t,T.map(S=>S.name))}throw pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const f=await p(m);return a&&l&&f!==void 0&&(l.cacheResult(t,c,f),h.debug(`[${i}] Cached result for tool: ${t}`)),f}catch(f){const g=s?{name:t,description:"",annotations:s,execute:async()=>({})}:void 0;if(g&&Ute(g)&&f instanceof Error&&F9(f)){h.debug(`[${i}] Tool ${t} is safe to retry, attempting once more`);try{const y=await p(m);return a&&l&&y!==void 0&&l.cacheResult(t,c,y),y}catch{}}throw f}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Tp({name:t,description:""})}invalidateToolCache(){this.toolCache=null,h.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return h.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();h.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!to,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(V1(),Jb)),i=o.getMemoryUsageMB();try{const s=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!s.has(g.name)){const y=K2(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});s.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0}));for(const g of l)if(!s.has(g.name)){const y=K2(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:ma({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const g of c)if(!s.has(g.name)){const y=K2(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});s.set(g.name,y)}const u=this.externalServerManager.getAllTools();for(const g of u)if(!s.has(g.name)){const y=K2(g,{category:ma({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});s.set(g.name,y)}const d=Array.from(s.values());oe.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const m=o.getMemoryUsageMB().heapUsed-i.heapUsed;if(m>ym.LOW_USAGE_MB&&(oe.debug(`\u{1F50D} Tool listing used ${m}MB memory (large tool registry detected)`),d.length>_be.LARGE_TOOL_COLLECTION&&oe.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=Tp({name:g.name,description:g.description||""}));const f=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:f,timestamp:Date.now()},f}catch(s){return oe.error("Failed to list available tools",{error:s}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(V1(),Jb)),n=r.getMemoryUsageMB();t?.quiet||oe.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||oe.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Ja(),DC)),{hasProviderEnvVars:i}=await Promise.resolve().then(()=>(Ih(),G1)),s=_r.getAllDescriptors().map(p=>p.name),a=Ig(Da.DEFAULT_CONCURRENCY_LIMIT),l=s.map(p=>a(async()=>{const m=Date.now();try{if(!await this.hasProviderEnvVars(p)&&p!=="ollama")return{provider:p,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-m};if(p==="bedrock"||p==="sagemaker")return{provider:p,status:"not-configured",configured:!0,authenticated:!1,error:`Live status check is skipped for ${p}`,responseTime:Date.now()-m};if(p==="ollama"){let S,k="not-run";try{const A=nA(),x=oA(A);if(x.kind==="suppressed")throw new Error(x.reason);S=x,k="transport-failure";const R=await fetch(A.url,{method:"GET",signal:AbortSignal.timeout(ql.AUTH_MS)});if(!R.ok)throw new Error("Ollama service not responding");k="protocol-failure";const C=await R.json(),M=C?.models;if(!Array.isArray(M))throw h.warn("Ollama API returned invalid models format in testProvider",{responseData:C,modelsType:typeof M}),new Error("Invalid models format from Ollama API");k="success";const O=M.filter(U=>U&&typeof U=="object"&&typeof U.name=="string");return O.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m,model:O[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-m}}catch(A){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:A instanceof Error?Vw(A):"Ollama service not running",responseTime:Date.now()-m}}finally{S&&Hw(S,k)}}const g=5e3,y=new AbortController,v=this.testProviderConnection(p,y.signal);let w;const T=new Promise((S,k)=>{w=setTimeout(()=>{k(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,T])}finally{clearTimeout(w),v.catch(()=>{}),y.abort()}return{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-m}}catch(f){const g=f instanceof Error?f.message:String(f);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-m}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&oe.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),c}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(Ja(),DC));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(Ih(),G1));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(Ih(),G1));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(Ih(),G1));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),i=this.toolRegistry.getBuiltInServerInfos(),s=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+i.length+s.length,l=r.connectedServers+o.length+i.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:s.length,totalTools:c,autoDiscoveredServers:s,customToolsCount:this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(ma({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return oe.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Vy(),qb));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return h.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Vy(),qb)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Vy(),qb));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Vy(),qb)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Vy(),qb));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,h.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new rP(PR.FAILURE_THRESHOLD,wB)),oe.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),oe.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(s=>s.name)),i=new Map;for(const s of n)i.has(s.name)||i.set(s.name,s.serverId||"unknown");for(const s of o){const a=this.toolExecutionMetrics.get(s),l=`${i.get(s)||"unknown"}.${s}`,c=this.toolCircuitBreakers.get(l),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!c||c.getState()==="closed")&&u>=.8;d&&r++;const p=[],m=[];if(c&&c.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),m.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(u*100).toFixed(1)}%`),m.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),m.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const f=a.errorCategories;f.timeout>0&&(p.push(`Timeout errors: ${f.timeout}`),m.push("Consider increasing the tool timeout configuration")),f.validation>0&&(p.push(`Validation errors: ${f.validation}`),m.push("Review input schemas and parameter validation")),f.network>0&&(p.push(`Network errors: ${f.network}`),m.push("Check network connectivity and endpoint availability"))}t[s]={name:s,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:c?.getState()||"closed",failureCount:c?.getFailureCount()||0},issues:p,recommendations:m}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return h.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:qe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return h.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return h.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return h.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Be(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return h.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return h.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const i=await Be(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(i.length===0)return h.debug("No messages found for session export",{sessionId:t}),null;const s=this.conversationMemory.getSession(t),a=await Be(s instanceof Promise?s:Promise.resolve(s),o,new Error("getSession operation timed out after 30s")),l=new Date().toISOString(),c={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():l,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():l,messages:i};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),h.debug("Exported conversation session",{sessionId:t,messageCount:i.length}),c}catch(i){return h.error("Failed to export conversation session",{sessionId:t,error:i instanceof Error?i.message:String(i)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,i=6e4;try{const s=await Be(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of s){const c=await Be(this.exportSession(l.id,r),i,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return h.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(s){return h.error("Failed to export all conversation sessions",{userId:t,error:s instanceof Error?s.message:String(s)}),[]}}async storeToolExecutions(t,r,n,o,i){const s=n&&n.length>0||o&&o.length>0;if(!s){h.debug("Tool execution storage skipped",{hasToolData:s,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){h.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,i)}catch(l){h.warn("Failed to store tool executions",{sessionId:t,userId:r,error:l instanceof Error?l.message:String(l)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:qe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async recordConversationTurn(t){const{sessionId:r,userId:n,turnId:o}=t;uf.assertConversationIdentity(r,n);const i={sessionId:r,userId:n,...o?{turnId:o}:{}};if(!t.userMessage.trim())return{recorded:!1,reason:"empty-user-message",...i};const s=(t.events??[]).some(l=>l.type==="tool:start"||l.type==="tool:end");if(!t.aiResponse.trim()&&!s)return{recorded:!1,reason:"empty-response",...i};if(await this.initializeConversationMemoryForGeneration(t.requestId??`record-turn-${Date.now()}`,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(await this.isOwnedByAnotherUser(r,n))throw new Me({code:qe.INVALID_PARAMETERS,message:"The conversation belongs to another user",category:"validation",severity:"medium",retriable:!1});const a=Date.now();try{await this.conversationMemory.storeConversationTurn({sessionId:r,userId:n,userMessage:t.userMessage,aiResponse:t.aiResponse,startTimeStamp:t.startTime,...t.provider&&t.model?{providerDetails:{provider:t.provider,model:t.model}}:{},enableSummarization:t.enableSummarization,events:t.events?.length?t.events:void 0,requestId:t.requestId,...t.modality?{modality:t.modality}:{},...o?{turnId:o}:{},...t.interrupted?{interrupted:!0}:{},...t.callEnded?{callEnded:!0}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,1)}catch(l){throw this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"record"},Date.now()-a,2,l instanceof Error?l.message:String(l)),l}return this.shouldWriteMemory(t.memory,n,t.aiResponse)&&this.storeMemoryInBackground({prompt:t.userMessage,response:t.aiResponse.trim(),userId:n,sessionId:r,provider:t.provider??"",model:t.model},t.memory,{sessionId:r}),{recorded:!0,...i}}async getConversationSeed(t){const{sessionId:r,userId:n}=t,o=Math.max(0,Math.floor(t.maxTurns??10)),i=Math.max(0,Math.floor(t.maxChars??6e3));try{uf.assertConversationIdentity(r,n);const s=await this.getSessionMessages(r,n),a=[];for(const d of s)d.role!=="user"&&d.role!=="assistant"||d.metadata?.isSummary||d.metadata?.isSkill||typeof d.content!="string"||!d.content.trim()||a.push({role:d.role,content:d.content,...d.metadata?.modality?{modality:d.metadata.modality}:{}});const l=a.slice(-(o*2));let c=0,u=l.length;for(let d=l.length-1;d>=0&&(c+=l[d].content.length,!(c>i));d-=1)u=d;return l.slice(u)}catch(s){return h.warn("[NeuroLink] getConversationSeed failed, starting unseeded",{error:s instanceof Error?s.message:String(s)}),[]}}async conversationExists(t){return uf.assertConversationIdentity(t.sessionId,t.userId),(await this.getSessionMessages(t.sessionId,t.userId)).length===0?!1:!await this.isOwnedByAnotherUser(t.sessionId,t.userId)}async isOwnedByAnotherUser(t,r){const n=this.conversationMemory;if(!n||n.isRedisConfigured)return!1;const o=await n.getSession(t);return o!==void 0&&o.userId!==r}static assertConversationIdentity(t,r){const n=typeof t!="string"||!t.trim()?"sessionId must be a non-empty string":t.includes(":")?'sessionId must not contain ":"':typeof r!="string"||!r.trim()?"userId must be a non-empty string":void 0;if(n)throw new Me({code:qe.INVALID_PARAMETERS,message:n,category:"validation",severity:"medium",retriable:!1})}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:qe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:qe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let i=o.length-1;i>=0;i--)if(o[i].role==="assistant")return o[i]={...o[i],content:r(o[i].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{oe.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(oe.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new fL({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const i of o)this.mcpToolRouter.registerServer(i.id||t);h.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else oe.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?ni(r.url):void 0});return n}catch(n){throw oe.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{oe.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(oe.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?oe.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):oe.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw oe.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}getExternalMCPServerHealth(){return this.externalServerManager.getServerStatuses()}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(i=>i.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let i=r;try{i=this.resolveDirectMcpToolName(t,r),oe.debug(`[NeuroLink] Executing external MCP tool: ${i} on ${t}`);const s=this.getToolAnnotationsForExecution(i),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,l={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},c=this._generationTurnActive?this.toolCacheRepeatKey(i,l):void 0,u=c!==void 0&&this._toolCacheKeysServedThisRequest.has(c);if(c!==void 0&&this._toolCacheKeysServedThisRequest.add(c),a&&this.mcpToolResultCache&&!u){const f=this.mcpToolResultCache.getCachedResult(i,l);if(f!==void 0)return oe.debug(`[NeuroLink] Tool result cache HIT: ${i} on ${t}`),f}const d=await this.externalServerManager.executeTool(t,i,n,o),p=d&&typeof d=="object"?d:void 0,m=!!(p&&"isError"in p&&p.isError===!0||p&&"success"in p&&p.success===!1);return a&&this.mcpToolResultCache&&!m&&d!==void 0&&this.mcpToolResultCache.cacheResult(i,l,d),oe.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${i}`),d}catch(s){throw oe.error(`[NeuroLink] External MCP tool execution failed: ${i}`,s),s}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(s=>s.name);if(o.includes(r))return r;const i=_ee(r,o);if(!i)throw new See(r,t,Mqt(r,o));return Ue.mcp.startActiveSpan("mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":i.name,"mcp.tool_name.repair_strategy":i.strategy,...i.score!==void 0?{"mcp.tool_name.repair_score":i.score}:{}}},s=>s.end()),oe.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${i.name}" (${i.strategy}) on server '${t}'`),i.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Be(Promise.resolve().then(()=>(sne(),SWt)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{oe.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),oe.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw oe.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Be(Promise.resolve().then(()=>(Nsr(),Dsr)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Be(Promise.resolve().then(()=>(zte(),b7t)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Be(Promise.resolve().then(()=>(Gte(),T7t)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Be(Promise.resolve().then(()=>(Zsr(),Hsr)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Be(Promise.resolve().then(()=>(dce(),cce)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Be(Promise.resolve().then(()=>(dce(),cce)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Be(Promise.resolve().then(()=>(iar(),tar)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Be(Promise.resolve().then(()=>(DF(),yce)),1e4),o=t.map(i=>({...i,execute:i.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Be(Promise.resolve().then(()=>(DF(),yce)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Be(Promise.resolve().then(()=>(dA(),m7t)),1e4),i=this.toolRegistry.getToolInfo(t);if(!i)return null;const s=i.tool.annotations,a=r({name:i.tool.name,description:i.tool.description??""}),l=n(a,s);return{annotations:l,summary:o(l)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async i=>{try{oe.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:i});const s=await this.externalServerManager.executeTool(n.serverId,n.name,i,{timeout:3e4});return oe.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!s,hasData:!!(s&&typeof s=="object"&&"content"in s)}),s}catch(s){throw oe.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,s),s}}};r[n.name]=o,oe.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return oe.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),oe.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){oe.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),oe.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){oe.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await omn().then(()=>har),i=await o(this.conversationMemoryConfig);this.conversationMemory=i,this.conversationMemoryNeedsInit=!1}catch(o){throw h.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);oe.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){oe.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const i=new r(o);return await Be(i.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4)),h.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),i}async decide(t){const{sessionId:r,requestId:n}=t;return this.holdTelemetry(),KE({...t.context,sessionId:r??t.context?.sessionId,requestId:n??t.context?.requestId},()=>this.runDecide(t))}resolveDecisionProviderName(t,r){return t??lP(this.resolveCredentials(r))}registeredDecisionModel(t){const r=_r.getProviderInfo(t.name)?.defaultModel;return r||(t.envVars.model?process.env[t.envVars.model]:void 0)||t.defaultModel}decisionLimits(t){const r=this.resolveDecisionProviderName(t?.provider,t?.credentials);if(!r)return null;const n=Gc.get(r.toLowerCase())??r,o=ir.get(n);if(!o)return null;const i=t?.model??this.registeredDecisionModel(o);return Ite(o,i)}decisionHookTimeout(){if(this.decisionHookTimeoutMs!==void 0)return this.decisionHookTimeoutMs;const t=this.decisionHooks?.hookTimeoutMs;let r=O4;return t!==void 0&&(typeof t=="number"&&Number.isFinite(t)&&t>0&&t<=D4?r=t:h.warn(`[Decision] decisionHooks.hookTimeoutMs must be a finite number from 1 to ${D4} ms; using the default ${O4} ms`,{configured:String(t)})),this.decisionHookTimeoutMs=r,r}emitDecisionEvent(t,r){try{this.emitter.emit(t,r)}catch(n){h.warn(`[Decision] a ${t} listener threw`,{error:n instanceof Error?n.message:String(n)})}}async siteDecide(t,r){const n={...t,credentials:r?.credentials??t.credentials,signal:r?.signal&&t.signal?AbortSignal.any([r.signal,t.signal]):r?.signal??t.signal,sessionId:r?.sessionId??t.sessionId,requestId:r?.requestId??t.requestId},o=n.site;if(!o)return this.tryRunDecide(n);if(!this.resolveDecisionProviderName(n.provider,n.credentials))return this.tryRunDecide(n);const i=new Map;let s;try{const a=n.questions,l=Object.keys(a).length,c=this.decisionHooks,u=this.decisionHookTimeout();let d;const p=()=>(d??={state:structuredClone(n.state),questions:structuredClone(a)},d),m=()=>({site:o,...p(),sessionId:n.sessionId,requestId:n.requestId});let f=a;if(c?.extendQuestions){let A;try{A=await Be(Promise.resolve(c.extendQuestions(m())),u,new Error(`extendQuestions exceeded ${u}ms`))??void 0}catch(R){h.warn(`[Decision] extendQuestions hook failed for site "${o}" \u2014 proceeding with NeuroLink's own questions`,{error:R instanceof Error?R.message:String(R)})}const x=A?Object.entries(A):[];if(x.length>0){const R=this.decisionLimits({provider:n.provider,model:n.model,credentials:n.credentials}),C=R?.maxQuestions!==void 0?Math.max(0,R.maxQuestions-l):Number.POSITIVE_INFINITY,M={...a};let O=0,U=0;for(const[D,N]of x){const $=_Yr(N);if($===void 0){O+=1;continue}if(i.size>=C){U+=1;continue}const L=dh(VD,i.size);M[L]=$,i.set(L,D)}O>0&&h.warn(`[Decision] dropped ${O} malformed host question(s) for site "${o}"`),U>0&&R&&h.warn(`[Decision] dropped ${U} host question(s) for site "${o}": ${R.provider} accepts ${R.maxQuestions} per request and NeuroLink asks ${l}`),f=M}}const g=i.size;if(this.emitter.listenerCount("decision:before")>0){const A={site:o,state:p().state,questions:g===0?p().questions:structuredClone(f),hostQuestionCount:g,sessionId:n.sessionId,requestId:n.requestId};this.emitDecisionEvent("decision:before",A)}const y=Date.now(),v=await this.tryRunDecide({...n,questions:f});s=v;const w=Object.create(null),T=Object.create(null);if(v)for(const[A,x]of Object.entries(v.answers)){const R=i.get(A);R===void 0?w[A]=x:T[R]=x}const S=v?structuredClone(v):null,k={site:o,answers:structuredClone(w),hostAnswers:structuredClone(T),latencyMs:v?.latencyMs??Date.now()-y,provider:v?.provider??this.resolveDecisionProviderName(n.provider,n.credentials),model:v?.model,result:S,sessionId:n.sessionId,requestId:n.requestId};if(this.emitDecisionEvent("decision:after",k),!v||!S)return null;if(c?.onAnswers)try{await Be(Promise.resolve(c.onAnswers({...m(),answers:structuredClone(T),result:S})),u,new Error(`onAnswers exceeded ${u}ms`))}catch(A){h.warn(`[Decision] onAnswers hook failed for site "${o}"`,{error:A instanceof Error?A.message:String(A)})}return g===0?v:{...v,answers:w}}catch(a){return h.warn(`[Decision] site "${o}" hook or event handling threw \u2014 ${s===void 0?"deciding with NeuroLink's own questions":"handing the consumer the answers already obtained"}`,{error:a instanceof Error?a.message:String(a)}),s===void 0?this.tryRunDecide(n):s?EYr(s,i):null}}async runDecide(t){const r=this.resolveDecisionProviderName(t.provider,t.credentials),n=Object.keys(t.questions),o=n.length,i=r?ir.get(Gc.get(r.toLowerCase())??r):void 0,s=t.model??(i&&this.registeredDecisionModel(i)),a=t,l=n.filter(TYr).length,c=a.site?{"decision.site":a.site,"decision.host_question_count":l}:{};return dt({name:"decide",tracer:Ue.decision,expectedFailure:()=>!r,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":o,"decision.images.count":t.images?.length??0,...c}},async u=>{if(ts(u,"generation",{model:s,input:{state:t.state,questions:t.questions},metadata:{provider:r,...a.site&&{site:a.site,host_question_count:l}}}),!r){const g=`No decision provider is configured. Set ${CLr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`;throw ts(u,"generation",{level:"WARNING",statusMessage:g}),new Error(g)}const{traceId:d,parentSpanId:p}=mg(),m=Date.now();let f=ke.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":o,"decision.images.count":t.images?.length??0,...c},p,d);try{const g=await to.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof g.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const y=await g.decide({state:t.state,questions:t.questions,images:t.images,video:t.video,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),v=Object.keys(y.answers).length,w=tc(r,y.model,{input:y.usage.inputTokens,output:y.usage.outputTokens,total:y.usage.inputTokens+y.usage.outputTokens});u.setAttribute("gen_ai.response.model",y.model),u.setAttribute("gen_ai.usage.input_tokens",y.usage.inputTokens),u.setAttribute("gen_ai.usage.output_tokens",y.usage.outputTokens),u.setAttribute("decision.answer_count",v),u.setAttribute("decision.media.bytes",y.mediaBytes??0),u.setAttribute("ai.cost.total",w),y.upstreamMs!==void 0&&u.setAttribute("decision.upstream_ms",y.upstreamMs),y.requestId&&u.setAttribute("gen_ai.response.id",y.requestId),ts(u,"generation",{model:y.model,output:y.answers,usageDetails:eK({input:y.usage.inputTokens,output:y.usage.outputTokens}),costDetails:{total:w}}),f.durationMs=Date.now()-m,f=ke.updateAttributes(f,{"ai.model":y.model,"ai.tokens.input":y.usage.inputTokens,"ai.tokens.output":y.usage.outputTokens,"ai.cost.input":w,"ai.cost.output":0,"ai.cost.total":w,"decision.answer_count":v,"decision.media.bytes":y.mediaBytes??0,"decision.latency_ms":y.latencyMs,...y.upstreamMs!==void 0?{"decision.upstream_ms":y.upstreamMs}:{}});const T=ke.endSpan(f,1);return this.metricsAggregator.recordSpan(T),et().recordSpan(T),y}catch(g){f.durationMs=Date.now()-m;const y=ke.endSpan(f,2,g instanceof Error?g.message:String(g));throw this.metricsAggregator.recordSpan(y),et().recordSpan(y),g}})}async tryDecide(t){return this.holdTelemetry(),this.siteDecide(t)}async transcribe(t){const[r,{runTranscribe:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(qar(),Ice))]);return n(t,r)}async*transcribeStream(t){const[r,{runTranscribeStream:n}]=await Promise.all([this.buildTranscribeDeps(t.credentials?.stt),Promise.resolve().then(()=>(zmn(),glr))]);yield*n(t,r)}resolveSTTCredentials(t){const r=this.credentials?.stt;if(!r||!t)return t??r;const n={...r};for(const[o,i]of Object.entries(t)){const s=n[o];n[o]=s&&typeof s=="object"&&i&&typeof i=="object"?{...s,...i}:i??s}return n}resolveSTTProvider(t,r){const n=t?.trim();return n?Mv(n)??n:fP(r)}async buildTranscribeDeps(t){await Id.registerAllProviders();const[{STTProcessor:r},{createSTTHandler:n},{STTError:o}]=await Promise.all([Promise.resolve().then(()=>(Wg(),PO)),Promise.resolve().then(()=>(th(),eh)),Promise.resolve().then(()=>(ws(),c_t))]),i=this.resolveSTTCredentials(t),s=l=>{const c=this.resolveSTTProvider(l,i);if(Mv(c)===void 0&&!r.supports(c)&&!fS(i)[c.trim().toLowerCase()])throw o.unknownProvider(c,p3r(i),R2e());return c},a=l=>{if(fS(i)[l.trim().toLowerCase()])return n(l,i);const c=Vf(l);return c?i?.[c.credentialsKey]!==void 0?n(c.name,i):r.getHandler(c.name)??n(c.name):r.getHandler(l)};return{...this.buildSTTCorrectionDeps(),transcribe:(l,c,u)=>r.transcribe(l,c,u,i),resolveProvider:s,getHandler:a}}buildSTTCorrectionDeps(){return{decide:async t=>{const r=await this.tryDecide({state:t.state,questions:t.questions,...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}});return r?{answers:r.answers}:null},rewrite:async t=>{const r=new AbortController,n=setTimeout(()=>r.abort(),t.timeoutMs),o=t.provider??process.env.NEUROLINK_STT_REWRITE_PROVIDER?.trim(),i=t.model??process.env.NEUROLINK_STT_REWRITE_MODEL?.trim(),s={input:{text:t.user},systemPrompt:t.system,...o?{provider:o}:{},...i?{model:i}:{},maxTokens:t.maxTokens,temperature:0,disableTools:!0,memory:{enabled:!1},abortSignal:r.signal};try{const l=(await this.generate(s)).content??"";return t.onPartial&&l&&t.onPartial(l),l}finally{clearTimeout(n)}}}}async tryRunDecide(t){try{const r=await this.decideInBatches(t);return h.shouldLog("debug")&&h.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return h.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async decideInBatches(t){const r=t.provider??lP(this.resolveCredentials(t.credentials)),n=r?Gc.get(r.toLowerCase()):void 0,o=n?ir.get(n)?.decisionLimits?.maxQuestions:void 0,i=UYr(t,o);if(i.length===1)return this.decide(t);const s=[];let a;for(let u=0;u<i.length;u+=Cte){const d=await Promise.allSettled(i.slice(u,u+Cte).map(p=>this.decide(p)));for(const p of d)p.status==="fulfilled"?s.push(p.value):a??=p.reason}const[l,...c]=s;if(l===void 0)throw a instanceof Error?a:new Error(String(a));return c.length+1<i.length&&h.debug(`decide: ${i.length-s.length} of ${i.length} batches failed; using the answers of the rest`),BYr([l,...c])}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let i;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?i={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?i={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:i=o("quality"),r?.passThreshold!==void 0&&(i.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(i.executionMode=r.executionMode);const s=new n(i);await Be(s.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await Be(s.execute(t,{correlationId:r?.correlationId}),a,pe.evaluationTimeout("pipeline execution",a));return h.debug("[NeuroLink] Evaluation completed",{pipeline:i.name,overallScore:l.overallScore,passed:l.passed,scorerCount:l.scores.length}),l}async score(t,r,n){const{ScorerRegistry:o}=await Be(Promise.resolve().then(()=>(FK(),LK)),1e4,pe.evaluationTimeout("scorer module load",1e4));await Be(o.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));const i=await Be(o.getScorer(t,n),3e4,pe.evaluationTimeout(`scorer load: ${t}`,3e4));if(!i)throw pe.scorerNotFound(t);const s=i.validateInput(r);if(!s.valid)throw pe.evaluationValidationFailed(t,s.errors);const a=await Be(i.score(r),6e4,pe.evaluationTimeout("scorer execution",6e4));return h.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Be(Promise.resolve().then(()=>(FK(),LK)),1e4,pe.evaluationTimeout("scorer module load",1e4));await Be(r.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Be(Promise.resolve().then(()=>(Rk(),Ik)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(Nce(),wlr));return h.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(Tlr(),blr));return h.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},i={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:this.observabilityConfig,...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},s=this.workerToolsConfig(o.tools),a=new uf(s?{...i,tools:s}:i);if(t?.shareToolRegistry!==!1)for(const l of this.uncacheableTools)a.uncacheableTools.add(l);if(h.setEventEmitter(n),t?.onLog){const l=t.onLog,c=f=>{try{const g=f??{};l({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},u={emit:(f,...g)=>(f==="log-event"&&c(g[0]),!0)},d=a.logInstanceId;h.addScopedEventEmitter(d,u);const p=()=>{h.removeScopedEventEmitter(d,u),this.ownedWorkerLogBridgeDetachers.delete(p)};this.ownedWorkerLogBridgeDetachers.add(p);const m=a.dispose.bind(a);a.dispose=async()=>{p(),await m()}}return h.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(WA(),TL));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(WA(),TL));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(WA(),TL));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(JA(),kL)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=non(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return Qnn(t??gi(this))}clearTaskState(t){return eon(t??gi(this))}registerDelegationTools(t){if(_on(this,t),this.hasBackgroundDelegationTools)return;const r=Pon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return AYt(this,t)}async collectDelegates(t){return IYt(this,t)}async cancelDelegates(t){return oie(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(h.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{h.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=fJt(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,h.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":zne(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new QWt(this.mcpOutputNormalizerConfig,t)),h.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return Krn(this,t,r)}async readArtifact(t,r){return Jrn(this,t,r)}registerBackgroundCommandTools(t){if(NYt(this,t),this.hasBackgroundCommandTools)return;const r=zon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){NYt(this,t)}async startBackgroundCommand(t,r){return qYt(this,t,r)}getBackgroundCommandStatus(t){return jYt(this,t)}async awaitBackgroundCommand(t,r){return yie(this,t,r)}async killBackgroundCommand(t,r){return VYt(this,t,r)}async readBackgroundCommandOutput(t,r){return DL(this,t,r)}registerGitTools(t){if(Gon(this,t),this.hasGitTools)return;const r=Jon(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,h.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return oZt(this,t,r)}async executeNetwork(t,r,n){return h.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){h.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(klr(),Slr));return h.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(Alr(),xlr));return h.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(Ilr(),Clr));return h.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){h.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await HYt(this),await oie(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error stopping background work:",r)}try{await this.releaseMemoryCondenser()}catch(r){t.push(r instanceof Error?r:new Error(String(r)))}try{h.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await this.releaseTelemetryHold(),h.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{h.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),h.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),h.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{h.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),h.clearEventEmitter(this.emitter),h.clearScopedEventEmitters(this.logInstanceId),h.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();h.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{h.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),h.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{h.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],h.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{h.debug("[NeuroLink] Shutting down TaskManager..."),await Be(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){h.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{h.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,h.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),h.warn("[NeuroLink] Error resetting state:",r)}t.length===0?h.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):h.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw h.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new Xw({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps({sessionId:t})),i=pa({provider:r?.provider||"openai",conversationMessages:n,toolReplayMode:this.resolveToolReplayModeForBudget({})}),s=Math.floor(i.availableInputTokens*.6),a=await o.compact(n,s,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Nw(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const i=pa({provider:r||"openai",model:n,conversationMessages:o,toolReplayMode:this.resolveToolReplayModeForBudget({})});return{estimatedInputTokens:i.estimatedInputTokens,availableInputTokens:i.availableInputTokens,usageRatio:i.usageRatio,shouldCompact:i.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?pa({provider:r||"openai",model:n,conversationMessages:o.messages,toolReplayMode:this.resolveToolReplayModeForBudget({})}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:i}=await Promise.resolve().then(()=>(VF(),Rlr));r=await i.createProvider(o.type,o.config),n=o.type}this.authProvider=r,h.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(RA(),eL));r.set(t),h.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(RA(),eL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(RA(),eL)),r=t.get()?.user.id;t.clear(),r&&h.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(i=>typeof t[i]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(h.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async i=>{if(typeof t[i]=="function"){const s=await Hne(t[i],o);t[i]=s.value,h.debug(`[NeuroLink] Resolved dynamic ${i}: ${s.resolutionType}`)}})),typeof t.tools=="function"){const i=await Hne(t.tools,o);if(!Array.isArray(i.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof i.value=="object"?"object":typeof i.value}`);t.enabledToolNames=i.value,delete t.tools}}},Hce=new fT,Nlr=Hce}});function lC(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"image/gif":null}function cC(e){return lC(e)??"image/png"}var gT=E({"src/lib/utils/imageDetection.ts"(){"use strict"}});function Qmn(e){return nx(e)&&cO(e)===null?"video/mp4":Glr.every((t,r)=>e[r]===t)?"video/webm":null}function Llr(e,t,r){const n=t==="image"?lC(e):Qmn(e);return n===null?{status:"error",message:`${r} ${qlr[t]}.`}:{status:"ok",dataUrl:`data:${n};base64,${e.toString("base64")}`}}function Wce(e){return e.length<=Blr?`(${e})`:`(a ${e.length}-character string)`}async function ehn(e,t,r){try{const n=await kP.stat(e);return n.isFile()?n.size>r?{status:"error",message:`${t} ${Wce(e)} is ${n.size} bytes; a request may carry at most ${r}.`}:{status:"ok",buffer:await kP.readFile(e)}:{status:"error",message:`${t} ${Wce(e)} is not a file.`}}catch(n){const o=n instanceof Error&&"code"in n?String(n.code):"unreadable";return{status:"error",message:`Could not read ${t} ${Wce(e)}: ${o}.`}}}async function Flr(e,t,r,n){if(typeof e!="string")return e.length===0?{status:"error",message:`${r} is an empty Buffer.`}:Llr(e,t,r);const o=e.trim();if(o==="")return{status:"error",message:`${r} is an empty string.`};if($lr.test(o))return{status:"error",message:`${r} is a remote URL. Media is not fetched for you; pass a Buffer, a file path or a data: URL.`};if(/^data:/i.test(o))return zlr[t].test(o)?{status:"ok",dataUrl:o}:{status:"error",message:`${r} is a data: URL that is not base64 ${t} content.`};if(Ulr.test(o))return{status:"error",message:`${r} uses an unsupported URL scheme. Pass a Buffer, a file path or a data: URL.`};const i=await ehn(o,r,n);return i.status==="ok"?Llr(i.buffer,t,r):i}async function thn(e,t,r,n){const o=e.images??[];if(o.length===0&&e.video===void 0)return{status:"prepared",media:void 0};if(!t){const l=n.length>0?` Use a decision provider that does: ${n.join(", ")}.`:"";return{status:"refused",message:`${r} does not accept images or video.${l}`}}if(o.length>t.maxImages)return{status:"refused",message:`${r} accepts at most ${t.maxImages} images per request; this one has ${o.length}.`};if(e.video!==void 0&&!t.video)return{status:"refused",message:`${r} does not accept video.`};const i=[];for(const[l,c]of o.entries()){const u=await Flr(c,"image",`Image ${l+1}`,t.maxRequestBytes);if(u.status==="error")return{status:"refused",message:u.message};i.push(u.dataUrl)}let s;if(e.video!==void 0){const l=await Flr(e.video,"video","The video",t.maxRequestBytes);if(l.status==="error")return{status:"refused",message:l.message};s=l.dataUrl}const a=i.reduce((l,c)=>l+c.length,s?.length??0);return{status:"prepared",media:{images:i,...s?{video:s}:{},bytes:a}}}var $lr,Ulr,Blr,zlr,Glr,qlr,rhn=E({"src/lib/utils/decisionMedia.ts"(){"use strict";Kr(),gT(),uO(),$lr=/^https?:\/\//i,Ulr=/^[a-z][a-z0-9+.-]*:\/\//i,Blr=200,zlr={image:/^data:image\/[a-z0-9.+-]+;base64,/i,video:/^data:video\/[a-z0-9.+-]+;base64,/i},Glr=[26,69,223,163],qlr={image:"is not a recognised image format",video:"is not a recognised video format (MP4, MOV or WebM)"}}});function jlr(e){return e.filter(Nr).map(r=>{const n=Array.isArray(r.loc)?r.loc.filter(i=>typeof i=="string"||typeof i=="number").join("."):"",o=typeof r.msg=="string"?r.msg:"invalid";return n?`${n}: ${o}`:o}).slice(0,5).join("; ")||"unspecified field"}function uC(e,t){return(t?e.split(t).join("[redacted]"):e).replace(/\.?\s*Received API Key\s*=[\s\S]*$/,"").replace(/\bsk-[A-Za-z0-9._-]+/g,"[redacted]").replace(/\b[0-9a-f]{32,}\b/gi,"[redacted]").replace(/data:[a-z]+\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi,"[media]").trim()}function nhn(e){let t=e;for(let r=0;r<5&&t instanceof Error;r++){if(t.message==="unexpected redirect")return!0;t=t.cause}return!1}var Kce,Vlr,Jce,dC,yT=E({async"src/lib/providers/systemOneDecision.ts"(){"use strict";_l(),ll(),await hu(),rn(),ct(),rhn(),z(),Lt(),Rte(),j2e(),gS(),gS(),Kce=5e3,Vlr=1,Jce=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}const o=setTimeout(()=>{t?.removeEventListener("abort",i),r()},e);function i(){clearTimeout(o),n(t?.reason)}t?.addEventListener("abort",i,{once:!0})}),dC=class extends Ua{proxyFetch;maxRetries;authFailed=!1;constructor(e,t,r){super(e,t,Fh(r)?r:void 0),this.proxyFetch=Dt(),this.maxRetries=Vlr}missingConfigMessage(){}encodeQuestion(e){return this.dialect().encodeQuestion(e)}dialect(){return $7}readRetryAfterMs(e){}defaultTimeoutMs(e,t){return this.getDescriptorDecideMs()}readDecisionPayload(e){return e}reportedConfidence(e){return{}}resolveResponseModel(e,t){return typeof e.model=="string"?e.model:t}diagnosticContext(){return{}}getProviderName(){return this.providerName}getDefaultDecisionModel(){return this.getDefaultModel()}supportsTools(){return!1}getAISDKModel(){throw new Je(`${this.vendorDisplayName()} is a decision-only provider; it generates no text, so chat completions are not available. Use \`decide()\` instead, or pick a different provider for \`generate()\` / \`stream()\`.`,this.providerName)}async executeStream(e,t){throw new Je(`${this.vendorDisplayName()} is a decision-only provider; streaming is not available. Use \`decide()\`, or pick another provider for \`stream()\`.`,this.providerName)}formatProviderError(e){if(e instanceof Je)return e;const t=e instanceof Error?e.message:String(e);return new Je(`${this.vendorLabel()} request failed: ${t}`,this.providerName)}async decide(e){const t=this.vendorLabel();if(!this.decisionApiKey())throw this.decisionError({kind:"authentication",message:this.missingKeyMessage(),retryable:!1});const r=this.missingConfigMessage();if(r)throw this.decisionError({kind:"invalid_request",message:r,retryable:!1});if(this.authFailed)throw this.decisionError({kind:"authentication",message:`${t} rejected this API key earlier; not retrying. Fix the key and construct a new provider.`,retryable:!1});const n=Object.entries(e.questions);if(n.length===0)throw this.decisionError({kind:"invalid_request",message:"At least one question is required.",retryable:!1});const o=e.model??this.modelName??this.getDefaultModel(),i=this.assertWithinDecisionLimits(e,o,n.length),s=Object.fromEntries(n.map(([d,p])=>[d,this.encodeQuestion(p)])),a=await this.prepareMedia(e),l=JSON.stringify(this.buildDecisionBody(e.state,s,o,a));this.assertWithinRequestBytes(l);const c=e.timeoutMs??this.defaultTimeoutMs(n.length,i)??this.defaultTimeout??Kce;let u;for(let d=0;d<=this.maxRetries;d++){const p=Date.now();try{const m=AbortSignal.timeout(c),f=e.signal?AbortSignal.any([e.signal,m]):m,g=await this.proxyFetch(this.decisionEndpoint(o),{method:"POST",headers:this.decisionHeaders(),body:l,signal:f,redirect:"error"}),y=Date.now()-p,v=this.readRequestId(g.headers),w=Number(g.headers.get("x-envoy-upstream-service-time"))||void 0,T=await g.json().catch(()=>null);if(!g.ok){if(u=this.parseDecisionError(g.status,T,v),u.kind==="authentication"&&(this.authFailed=!0,h.warn(`${t}: credential not accepted \u2014 disabling this provider instance. ${u.message}`,{status:u.status,...this.diagnosticContext(),requestId:v})),!u.retryable||d===this.maxRetries)throw this.decisionError(u);const R=this.readRetryAfterMs(g.headers);if(R!==void 0&&R>c-(Date.now()-p))throw this.decisionError(u);await Jce(R??2**d*250+Math.random()*250,e.signal);continue}const S=this.readDecisionPayload(T),k=Nr(S)?this.dialect().readAnswers(S,this.reportedConfidence(S),e.questions):void 0;if(!Nr(S)||!k)throw this.decisionError({kind:"server",message:`${t} returned a response without an answers map.`,status:g.status,requestId:v,retryable:!1});for(const R of k.dropped)h.warn(`${t}: dropped unparseable answer "${R}"`,{requestId:v});for(const R of k.refused??[])h.warn(`${t}: the model declined to answer "${R}"`,{requestId:v});const A={...k.answers},x=Nr(S.usage)?S.usage:{};return{model:this.resolveResponseModel(S,o),provider:this.providerName,answers:A,usage:{inputTokens:Gs(x.input_tokens)??Gs(x.inputTokens)??0,outputTokens:Gs(x.output_tokens)??Gs(x.outputTokens)??0},requestId:v,latencyMs:y,upstreamMs:w,...a?{mediaBytes:a.bytes}:{}}}catch(m){if(m instanceof Je)throw m;const f=e.signal?.aborted===!0,g=m instanceof Error&&m.name==="TimeoutError",y=nhn(m);if(u={kind:f?"network":g?"timeout":"network",message:y?`${t} answered with a redirect, which is refused so the decision is not sent anywhere else. Point the base URL at the final address.`:uC(Av(m instanceof Error?m.message:String(m)),this.decisionApiKey()),retryable:!f&&!y},!u.retryable||d===this.maxRetries)throw this.decisionError(u);await Jce(2**d*250+Math.random()*250)}}throw this.decisionError(u??{kind:"network",message:`${t} request failed.`,retryable:!1})}async prepareMedia(e){const t=ir.get(this.providerName)?.decisionLimits,r=await thn(e,t?.media,this.vendorLabel(),ALr({video:e.video!==void 0}));if(r.status==="refused")throw this.decisionError({kind:"invalid_request",message:r.message,retryable:!1});return r.media}assertWithinRequestBytes(e){const t=ir.get(this.providerName)?.decisionLimits?.media,r=t?.maxRequestBytes;if(r===void 0)return;const n=Buffer.byteLength(e);if(n>r)throw this.decisionError({kind:"invalid_request",message:`The request is ${n} bytes; ${this.vendorLabel()} accepts at most ${r}. Send fewer or smaller images${t?.video?", or a shorter video":""}.`,retryable:!1})}assertWithinDecisionLimits(e,t,r){const n=ir.get(this.providerName),o=n?Ite(n,t):null;if(!o||!o.enforcedLocally)return 0;const i=this.vendorLabel();if(o.maxQuestions!==void 0&&r>o.maxQuestions)throw this.decisionError({kind:"max_tokens_exceeded",message:`${i} accepts at most ${o.maxQuestions} questions per request; this one has ${r}. Ask fewer, or use a decision provider without this cap.`,retryable:!1});const{maxStateTokens:s}=o,a=J9t(e.state,o);if(a>s)throw this.decisionError({kind:"max_tokens_exceeded",message:`The state is ~${a} tokens; ${i}'s "${t}" model reads at most ${s}. Shorten the state, or use a decision provider with a larger window.`,retryable:!1});return a}decisionError(e){const t=new Je(e.message,this.providerName);return Object.defineProperty(t,"cause",{value:e,enumerable:!1,writable:!0,configurable:!0}),t}}}}),Xce,ohn=E({async"src/lib/providers/decide/formatters.ts"(){"use strict";await yT(),Xce={"fastapi-validation":e=>`Request failed validation \u2014 ${jlr(Array.isArray(e)?e:[])}`}}});function Hlr(e,t){const r=t.split(".");if(r.some(o=>o===""))return;let n=e;for(const o of r){if(typeof n!="object"||n===null||Array.isArray(n))return;const i=Object.getOwnPropertyDescriptor(n,o);if(i===void 0||!("value"in i))return;n=i.value}return n}var Wlr=E({"src/lib/providers/decide/paths.ts"(){"use strict"}});function ihn(e){const t=Zce.get(e);if(t)return t;const r=new RegExp(e,"i");return Zce.set(e,r),r}function shn(e,t,r){return((e.status===void 0?[]:typeof e.status=="number"?[e.status]:e.status).includes(t)||e.statusMin!==void 0&&t>=e.statusMin)&&(e.messagePattern===void 0||ihn(e.messagePattern).test(r.slice(0,Jlr)))}function ahn(e,t){if(e.isArray)return Array.isArray(t)&&e.formatter?Xce[e.formatter](t):void 0;if(!(typeof t!="string"||t.length===0))return e.formatter?Xce[e.formatter](t):t}function lhn(e,t){for(const r of e){const n=ahn(r,Hlr(t,r.path));if(n!==void 0)return{shape:r,text:n}}}function chn(e,t){const{status:r,payload:n,requestId:o,label:i,apiKey:s}=t,a=uC(`${i} request failed with HTTP ${r}`,s),l=lhn(e.bodyShapes,n),c=l?.text&&uC(l.text,s)||a,u=e.rules.find(f=>shn(f,r,c)),d=u?.kind??e.default,p=u?.retryable??Yce(d),m=(f,g)=>({kind:f,message:c,status:r,requestId:o,retryable:g});if(l){const{shape:f}=l;return m(f.kind??d,f.retryable??(f.kind===void 0?p:Yce(f.kind)))}return m(d,p)}var Klr,Yce,Jlr,Zce,uhn=E({async"src/lib/providers/decide/errors.ts"(){"use strict";await yT(),await ohn(),Wlr(),Klr=new Set(["rate_limit","overloaded","server"]),Yce=e=>Klr.has(e),Jlr=2e3,Zce=new Map}});function dhn(e,t){if(/[{}]/.test(e.replace(Qce,"")))throw new Error(`Decide endpoint template "${e}" has an unmatched brace; write placeholders as {baseURL}.`);return e.replace(Qce,(r,n)=>{if(n!=="baseURL")throw new Error(`Decide endpoint template "${e}" uses an unknown placeholder {${n}}; the only one supported is {baseURL}.`);return t.baseURL})}var Qce,phn=E({"src/lib/providers/decide/template.ts"(){"use strict";Qce=/\{([^{}]*)\}/g}}),Xlr={};ie(Xlr,{ConfiguredDecisionProvider:()=>Ylr});var vT,Ylr,mhn=E({async"src/lib/providers/configuredDecision.ts"(){"use strict";z(),Lt(),oi(),Mm(),N7(),k3r(),await uhn(),gS(),Wlr(),phn(),await yT(),vT=e=>typeof e=="string"?e.trim():"",Ylr=class extends dC{entry;apiKey;baseURL;endpoint;constructor(e,t,r,n){super(t||Ji(Vo(e,"model"),e.models.default),e.id,r),this.entry=e,this.apiKey=vT(n?.apiKey)||vT(process.env[Vo(e,"apiKey")]),this.baseURL=h3r(vT(n?.baseURL)||vT(process.env[Vo(e,"baseURL")])||vT(e.wire.baseURL),e.decide.baseURLNormalize??[]),this.endpoint=dhn(e.decide.endpoint,{baseURL:this.baseURL}),h.debug(`${e.displayName} Provider initialized (decide only)`,{modelName:this.modelName,baseURL:this.baseURL?Qt(this.baseURL):"(not set)"})}getDefaultModel(){return Ji(Vo(this.entry,"model"),this.entry.models.default)}vendorLabel(){return this.entry.displayName}vendorDisplayName(){return this.entry.displayName}decisionApiKey(){return this.apiKey}missingKeyMessage(){return`${this.entry.displayName} requires an API key. Set ${Vo(this.entry,"apiKey")} or pass credentials.${Cv(this.entry)}.apiKey.`}missingConfigMessage(){const{baseURLRequired:e,baseURLShape:t}=this.entry.decide;return this.baseURL?t?g3r(t,this.baseURL,this.entry.displayName,`Set ${Vo(this.entry,"baseURL")} or pass credentials.${Cv(this.entry)}.baseURL to the origin, and give the key through ${Vo(this.entry,"apiKey")} or credentials.${Cv(this.entry)}.apiKey.`):void 0:e?`${this.entry.displayName} requires a base URL. Set ${Vo(this.entry,"baseURL")} or pass credentials.${Cv(this.entry)}.baseURL.`:void 0}decisionEndpoint(){return this.endpoint}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r,n){const{placement:o,alias:i}=this.entry.decide.model;return this.dialect().buildBody({state:e,questions:t,model:o==="body-unless-alias"&&r===i?void 0:r,media:n,mediaKeys:this.entry.decide.media})}parseDecisionError(e,t,r){return chn(this.entry.decide.errors,{status:e,payload:t,requestId:r,label:this.entry.displayName,apiKey:this.apiKey})}readRequestId(e){for(const t of this.entry.decide.requestIdHeaders??[]){const r=e.get(t);if(r!==null)return r}}resolveResponseModel(e,t){if(!Nr(e))return t;for(const r of this.entry.decide.response?.modelPaths??[]){const n=Hlr(e,r);if(typeof n=="string")return n}return super.resolveResponseModel(e,t)}dialect(){return H2e(this.entry.decide.dialect)}}}});async function Qy(e,t){try{await e}catch(r){h.debug(`[${t}] detached stream pump rejected; reason absorbed because the turn's own error is authoritative`,r)}}var eue=E({"src/lib/utils/drainDetachedPump.ts"(){"use strict";z()}});function e0(e,t,r){return async(n,o)=>{const i=()=>Promise.resolve(t(n,o));r.onProgress?.();try{const s=r.abortSignal?Ku(i(),r.abortSignal):i();return await(r.toolTimeoutMs===void 0||r.toolTimeoutMs===null?s:St(s,r.toolTimeoutMs,`Tool "${e}" execution timed out after ${r.toolTimeoutMs}ms`))}finally{r.onProgress?.()}}}var WF=E({"src/lib/core/toolExecutionGuards.ts"(){"use strict";ny()}});function hhn(e,t){const r=Qlr[e];return Math.round(t.min+r*(t.max-t.min))}function tue(e,t){if(!e?.enabled&&!e?.thinkingLevel)return;const r=e.thinkingLevel??Zlr;if(t&&!cXr(t)){const n=uXr(t);if(n)return{includeThoughts:!0,thinkingBudget:hhn(r,n)};rue.has(t)||(rue.add(t),h.warn(`[thinkingConfig] "${t}" has no verified Gemini thinkingBudget range; omitting thinkingConfig \u2014 requested thinkingLevel is silently disabled.`));return}return{includeThoughts:!0,thinkingLevel:r}}var Zlr,Qlr,rue,ecr=E({"src/lib/utils/thinkingConfig.ts"(){"use strict";RD(),z(),Zlr="high",Qlr={minimal:0,low:.25,medium:.55,high:1},rue=new Set}});function fhn(e){return JSON.stringify(e,(t,r)=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r).sort().reduce((n,o)=>(n[o]=r[o],n),{}):r)}function ghn(e){if(mcr.test(e))return e;let t=e.replace(/[^A-Za-z0-9_.:-]/g,"_");return/^[A-Za-z_]/.test(t)||(t=`_${t}`),t.length>YF&&(t=t.slice(0,YF)),t}function yhn(e,t){if(!t(e))return e;let r=2;for(;;){const n=`_${r}`,i=`${e.slice(0,YF-n.length)}${n}`;if(!t(i))return i;r++}}function $h(e){if(Array.isArray(e.anyOf)||Array.isArray(e.oneOf)){const n=e.anyOf?"anyOf":"oneOf",o=e[n],i=o.filter(c=>c.type!=="null"&&c.type!=="undefined");if(i.length===1){const c=$h({...i[0]});return c.nullable=!0,e.description&&(c.description=e.description),c}const s=i.map(c=>c.type||"unknown").join(" | "),a={type:"string"},l=e.description?`${e.description} (accepts: ${s})`:`Value as string (accepts: ${s})`;return a.description=l,o.some(c=>c.type==="null")&&(a.nullable=!0),a}const t={};for(const[n,o]of Object.entries(e))if(!(n==="$schema"||n==="additionalProperties"||n==="default"))if(n==="properties"&&o&&typeof o=="object"){const i={};for(const[s,a]of Object.entries(o))a&&typeof a=="object"?i[s]=$h(a):i[s]=a;t[n]=i}else n==="items"&&o&&typeof o=="object"?Array.isArray(o)?t[n]=o.map(i=>i&&typeof i=="object"?$h(i):i):t[n]=$h(o):t[n]=o;Array.isArray(t.allOf)&&(t.allOf=t.allOf.map(n=>$h(n))),t.not&&typeof t.not=="object"&&(t.not=$h(t.not));for(const n of["if","then","else"])t[n]&&typeof t[n]=="object"&&(t[n]=$h(t[n]));typeof t.exclusiveMinimum=="boolean"&&(t.exclusiveMinimum===!0&&typeof t.minimum=="number"?(t.exclusiveMinimum=t.minimum,delete t.minimum):delete t.exclusiveMinimum),typeof t.exclusiveMaximum=="boolean"&&(t.exclusiveMaximum===!0&&typeof t.maximum=="number"?(t.exclusiveMaximum=t.maximum,delete t.maximum):delete t.exclusiveMaximum);const r=2147483647;return typeof t.maximum=="number"&&t.maximum>r&&delete t.maximum,typeof t.minimum=="number"&&t.minimum<-r&&delete t.minimum,t}function tcr(e,t){const r=[],n=new _T,o=[],i=[],s=new Set(t??[]),a=new Map;for(const[l,c]of Object.entries(e))try{const u=ghn(l),d=yhn(u,f=>s.has(f));a.set(d,l),d!==l&&i.push({from:l,to:d});const p={name:d,description:c.description||`Tool: ${d}`},m=c;if(m.parameters||c.inputSchema){let f;const g=m.parameters||c.inputSchema;CJ(g)?f=Wo(g,"openApi3"):typeof g=="object"?f=g:f={type:"object",properties:{}},f.jsonSchema&&typeof f.jsonSchema=="object"&&!f.type&&(f=f.jsonSchema),p.parametersJsonSchema=$h(Qn(f))}r.push(p),s.add(d),c.execute&&n.set(p.name,c.execute)}catch(u){o.push(l),h.error(`[buildNativeToolDeclarations] Failed to convert tool "${l}":`,u)}return o.length>0&&h.warn(`[buildNativeToolDeclarations] ${o.length} tool(s) skipped due to schema errors: ${o.join(", ")}`),i.length>0&&h.warn(`[buildNativeToolDeclarations] ${i.length} tool name(s) sanitized for Google's function-name regex: ${i.map(l=>`"${l.from}" -> "${l.to}"`).join(", ")}`),{toolsConfig:[{functionDeclarations:r}],executeMap:n,originalNameMap:a}}function KF(e,t,r){const n={},o=(i,s)=>r?e0(i,s,r):async(a,l)=>s(a,l);if(e){for(const[i,s]of e.originalNameMap){const a=e.executeMap.get(i);a&&(n[s]={execute:o(s,a)})}return n}for(const[i,s]of Object.entries(t??{})){const a=s?.execute;a&&(n[i]={execute:o(i,a)})}return n}function vhn(e,t){if(!e)return[];const r=new Set(t.originalNameMap.values()),n=Object.entries(e).filter(([i])=>!r.has(i));if(n.length===0)return[];const o=tcr(Object.fromEntries(n),new Set(t.originalNameMap.keys()));t.toolsConfig[0].functionDeclarations.push(...o.toolsConfig[0].functionDeclarations);for(const[i,s]of o.originalNameMap)t.originalNameMap.set(i,s);for(const[i,s]of o.executeMap)t.executeMap.set(i,s);return h.info(`[buildNativeToolDeclarations] ${n.length} tool(s) hydrated mid-turn via discovery: ${n.map(([i])=>i).join(", ")}`),n.map(([i])=>i)}function rcr(e,t){const r=qc("google-ai",e.model,{temperature:e.temperature??1,topP:e.topP},"googleAiStudio.buildNativeConfig"),n={...r.temperature!==void 0&&{temperature:r.temperature},...r.topP!==void 0&&{topP:r.topP},maxOutputTokens:e.maxTokens};t&&(n.tools=t),e.systemPrompt&&(n.systemInstruction=e.systemPrompt);const o=tue(e.thinkingConfig,e.model);return o&&(n.thinkingConfig=o),t||((e.responseSchema||e.wantsJsonOutput)&&(n.responseMimeType="application/json"),e.responseSchema&&(n.responseSchema=e.responseSchema)),n}function ncr(e){const t=e||ms;return Number.isFinite(t)&&t>0?Math.min(Math.floor(t),lue):Math.min(ms,lue)}function t0(e){switch(e){case"MAX_TOKENS":case"CONTINUATION":return"length";case"TOO_MANY_TOOL_CALLS":return"tool-calls";case"MALFORMED_FUNCTION_CALL":case"UNEXPECTED_TOOL_CALL":return"error";case"SAFETY":case"RECITATION":case"BLOCKLIST":case"PROHIBITED_CONTENT":case"SPII":case"LANGUAGE":case"IMAGE_SAFETY":case"IMAGE_PROHIBITED_CONTENT":case"IMAGE_RECITATION":return"content-filter";default:return"stop"}}function whn(e,t){return t?e?`${e}
|
|
1971
1971
|
${t}`:t:e}async function bhn(e,t){const r=[],n=[];let o=0,i=0,s=0,a=0,l;for await(const c of e){const u=c,p=u.candidates?.[0],m=p?.finishReason;typeof m=="string"&&(l=m);const f=p?.content;if(f&&Array.isArray(f.parts))for(const y of f.parts)r.push(y),typeof y.text=="string"&&y.text.length>0&&t.push({content:y.text});c.functionCalls&&n.push(...c.functionCalls);const g=u.usageMetadata;g&&(o=Math.max(o,g.promptTokenCount||0),i=Math.max(i,g.candidatesTokenCount||0),s=Math.max(s,g.cachedContentTokenCount||0),a=Math.max(a,g.thoughtsTokenCount||0))}return{rawResponseParts:r,stepFunctionCalls:n,finishReason:l,inputTokens:o,outputTokens:i,cacheReadTokens:s,reasoningTokens:a}}function JF(e){for(let t=e.length-1;t>=0;t--){const r=e[t];if(r!=null&&typeof r=="object"&&"thoughtSignature"in r&&typeof r.thoughtSignature=="string")return r.thoughtSignature}}function Thn(e){return e.filter(t=>typeof t.text=="string").map(t=>t.text).join("")}function ocr(e,t,r,n,o){return t>=r&&!n?(h.warn(`${e} Tool call loop terminated after reaching maxSteps (${r}). Model was still calling tools. Using accumulated text from last step.`),o||Bh(r,0)):n}function Uh(e){if(!e)return!1;const t=e;return t.name==="AbortError"||typeof t.message=="string"&&/abort/i.test(t.message)||typeof DOMException<"u"&&e instanceof DOMException&&t.code===20}function Bh(e,t){return`${t>0?`I gathered information across ${t} tool call${t===1?"":"s"} but `:"I "}reached the ${e}-step limit for a single turn before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function Ec(e){return`${e>0?`I gathered information across ${e} tool call${e===1?"":"s"} but `:"I "}had to stop because the gathered material filled this turn's context window before I could finish. Please narrow the request or break it into smaller asks and I'll continue.`}function icr(e){const t=Math.max(0,Math.round(e/1e3)),r=Math.floor(t/60),n=t%60;return r>0?`${r}m ${n}s`:`${n}s`}function _hn(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop after ${icr(e)} \u2014 this turn hit its processing time limit.${r} ask me to continue and I'll pick up from there.`}function Ehn(e,t){const r=t>0?` I completed ${t} tool call${t===1?"":"s"} before stopping;`:"";return`I had to stop because this turn made no progress for ${icr(e)} \u2014 a tool or model call appears to be stuck.${r} ask me to continue and I'll pick up from there.`}function Shn(e){return`This turn was stopped before I could finish.${e>0?` I completed ${e} tool call${e===1?"":"s"} before stopping.`:""}`}function nue(e){return e.timedOut?_hn(e.elapsedMs,e.toolCallCount):e.stalled?Ehn(e.stallTimeoutMs??0,e.toolCallCount):e.wasAborted?Shn(e.toolCallCount):Bh(e.maxSteps,e.toolCallCount)}function wT(e){return"NOTE: processing time for this turn is nearly up. Consolidate what you have and "+(e?"call final_result with your best answer now.":"provide your final answer now.")}function Up(e){return e.timedOut?"time-limit":e.stalled?"stalled":e.wasAborted?"aborted":e.contextCappedWithoutAnswer?"context-cap":e.cappedWithoutAnswer?"step-cap":e.finishReason==="error"?"provider-error":"completed"}function bT(e){const t=Date.now(),r=u=>u!==void 0&&Number.isFinite(u)&&u>0,n=r(e.turnTimeoutMs)?e.turnTimeoutMs:r(e.defaultTurnTimeoutMs)?e.defaultTurnTimeoutMs:void 0,o=r(e.turnTimeoutMs)?e.wrapupTimeLeadMs??GPe:void 0;let i=!1,s=!1,a=t,l,c;if(n!==void 0&&(l=setTimeout(()=>{i=!0,e.onDeadline("timeout")},n),l.unref?.()),r(e.stallTimeoutMs)){const u=e.stallTimeoutMs,d=Math.min(Math.max(1e3,Math.floor(u/4)),15e3);c=setInterval(()=>{!s&&!i&&Date.now()-a>=u&&(s=!0,e.onDeadline("stall"))},d),c.unref?.()}return{get timedOut(){return i},get stalled(){return s},get expired(){return i||s},get turnTimeoutMs(){return n},elapsedMs(){return Date.now()-t},noteProgress(){a=Date.now()},shouldNudgeWrapup(){if(n===void 0||o===void 0)return!1;const u=n-(Date.now()-t);return u>0&&u<=o},dispose(){l&&clearTimeout(l),c&&clearInterval(c)}}}function TT(e,t=uP){const r=Math.floor(e*t);let n=0,o=0;return{get thresholdTokens(){return r},get projectedNextPromptTokens(){return n+o},noteUsage(i,s){i>0&&(n=i,o=Math.max(0,s))},noteAppendedChars(i){i>0&&(o+=Math.ceil(i/4))},resetAfterReclaim(){n=0,o=0},shouldStop(){return n>0&&n+o>=r}}}function khn(e,t,r){e.push({role:"model",parts:t.length>0?t:r.map(n=>({functionCall:n}))})}function scr(e){const t=Wo(e,"openApi3"),r=Qn(t);return r.$schema&&delete r.$schema,la(r)}function XF(e,t){if(!t||t.length===0)return;const r=new Map,n=[];let o=0;const i=a=>`${o}:${a??"undefined"}`,s=a=>{const l=i(a),c=r.get(l);if(c)return c;const u={type:"tool_step",callParts:[],resultParts:[]};return r.set(l,u),n.push(u),u};for(const a of t){if(a.role==="tool_call"){const u=s(a.metadata?.stepIndex),d={functionCall:{name:a.tool||"unknown",args:a.args||{}}};a.metadata?.thoughtSignature&&(d.thoughtSignature=a.metadata.thoughtSignature),u.callParts.push(d);continue}if(a.role==="tool_result"){const u=s(a.metadata?.stepIndex);let d;try{d=a.content!==void 0&&a.content!==null?{result:JSON.parse(a.content)}:{result:"success"}}catch{d={result:a.content??"success"}}u.resultParts.push({functionResponse:{name:a.tool||"unknown",response:d}});continue}const l=a.role==="assistant"?"model":a.role;if(l!=="user"&&l!=="model"||!a.content||a.content.trim().length===0)continue;o++;const c={text:a.content};a.metadata?.thoughtSignature&&(c.thoughtSignature=a.metadata.thoughtSignature),n.push({type:"regular",role:l,parts:[c]})}for(const a of n){if(a.type==="regular"){e.push({role:a.role,parts:a.parts});continue}if(a.callParts.length===0){a.resultParts.length>0&&h.debug("[GoogleNativeGemini3] Dropping orphan tool_result segment with no matching tool_call rows",{resultCount:a.resultParts.length});continue}e.push({role:"model",parts:a.callParts}),a.resultParts.length>0&&e.push({role:"user",parts:a.resultParts})}}function acr(e){return typeof e!="object"||e===null||!("text"in e)?!1:typeof e.text=="string"}function xhn(e){if(typeof e!="object"||e===null||!("inlineData"in e))return!1;const t=e.inlineData;return typeof t=="object"&&t!==null&&"mimeType"in t&&"data"in t}function Ahn(e){return typeof e=="object"&&e!==null&&"functionCall"in e}function lcr(e){return typeof e=="object"&&e!==null&&"functionResponse"in e}function ccr(e){if(!(typeof e!="object"||e===null||!("thoughtSignature"in e)))return typeof e.thoughtSignature=="string"?e.thoughtSignature:void 0}function oue(e,t){return t?{...e,providerOptions:{...e.providerOptions,googleAiStudio:{...e.providerOptions?.googleAiStudio,thoughtSignature:t}}}:e}function iue(e){if(typeof e!="object"||e===null)return;const t=e.googleAiStudio;if(typeof t!="object"||t===null)return;const r=t.thoughtSignature;return typeof r=="string"?r:void 0}function Chn(e){return e.length>0&&e.every(lcr)}function Ihn(e){if(lcr(e))return{type:"tool-result",toolCallId:`gemini-tool-${Jr()}`,toolName:e.functionResponse.name,output:e.functionResponse.response}}function Rhn(e){if(acr(e))return oue({type:"text",text:e.text},ccr(e));if(xhn(e))return{type:"file",data:e.inlineData.data,mediaType:e.inlineData.mimeType}}function Mhn(e){if(acr(e))return oue({type:"text",text:e.text},ccr(e));if(Ahn(e))return oue({type:"tool-call",toolCallId:`gemini-tool-${Jr()}`,toolName:e.functionCall.name,input:e.functionCall.args??{}},e.thoughtSignature)}function Phn(e){const t=[];for(const r of e){const n=Array.isArray(r.parts)?r.parts:[];if(r.role==="user"&&Chn(n)){const o=n.map(Ihn).filter(i=>i!==void 0);o.length>0&&t.push({role:"tool",content:o});continue}if(r.role==="user"){const o=n.map(Rhn).filter(i=>i!==void 0);o.length>0&&t.push({role:"user",content:o});continue}if(r.role==="model"){const o=n.map(Mhn).filter(i=>i!==void 0);o.length>0&&t.push({role:"assistant",content:o})}}return t}function ucr(e){return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):e instanceof ArrayBuffer?Buffer.from(e).toString("base64"):Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64")}function Ohn(e){if(typeof e=="string")return e.length>0?[{text:e}]:[];const t=[];for(const r of e)if(r.type==="text"){if(r.text.length>0){const n=iue(r.providerOptions);t.push(n?{text:r.text,thoughtSignature:n}:{text:r.text})}}else r.type==="image"&&!(r.image instanceof URL)?t.push({inlineData:{mimeType:r.mediaType??"application/octet-stream",data:ucr(r.image)}}):r.type==="file"&&!(r.data instanceof URL)&&t.push({inlineData:{mimeType:r.mediaType,data:ucr(r.data)}});return t}function Dhn(e){if(typeof e=="string")return e.length>0?[{text:e}]:[];const t=[];for(const r of e)if(r.type==="text"){if(r.text.length>0){const n=iue(r.providerOptions);t.push(n?{text:r.text,thoughtSignature:n}:{text:r.text})}}else if(r.type==="tool-call"){const n=iue(r.providerOptions),o={functionCall:{name:r.toolName,args:r.input??{}}};n&&(o.thoughtSignature=n),t.push(o)}return t}function Nhn(e){const t=[];for(const r of e)r.type==="tool-result"&&t.push({functionResponse:{name:r.toolName,response:r.output&&typeof r.output=="object"?r.output:{result:r.output}}});return t}function dcr(e){const t=[],r=[];for(const n of e){if(n.role==="system"){n.content.length>0&&r.push(n.content);continue}if(n.role==="user"){const i=Ohn(n.content);i.length>0&&t.push({role:"user",parts:i});continue}if(n.role==="assistant"){const i=Dhn(n.content);i.length>0&&t.push({role:"model",parts:i});continue}const o=Nhn(n.content);o.length>0&&t.push({role:"user",parts:o})}return r.length>0?{contents:t,systemText:r.join(`
|
|
1972
1972
|
|
|
1973
1973
|
`)}:{contents:t}}async function sue(e,t,r="[GeminiNative]"){if(!(!t||t.length===0))for(const n of t){const o=n.filename.split(/[\\/]/).pop()??n.filename,i=o.lastIndexOf("."),s=i>0?o.slice(i):".bin",a=await mzt(n.buffer,n.mimeType,s);if(TQ(a.mimeType)){h.warn(`${r} Skipping native audio for ${o}: ${a.mimeType} is not accepted and could not be converted. The metadata summary was still included.`);continue}e.push({inlineData:{mimeType:a.mimeType,data:a.buffer.toString("base64")}}),h.debug(`${r} Added native audio part for ${o} (${a.mimeType})`)}}async function aue(e,t,r,n,o="[GeminiNative]"){if(!t||t.length===0)return;let i=e.reduce((s,a)=>"inlineData"in a?s+Math.floor(a.inlineData.data.length*3/4):s,0);for(const s of t){const a=s.filename.split(/[\\/]/).pop()??s.filename,l=Tzt(r,s,i,n);if(!l.deliver){h.warn(`${o} Sending keyframes instead of the clip for ${a}: ${l.reason}.`);continue}i+=s.buffer.length,e.push({inlineData:{mimeType:s.mimeType,data:s.buffer.toString("base64")}}),h.debug(`${o} Added native video part for ${a} (${s.mimeType})`)}}async function pcr(e,t,r="[GeminiNative]",n){const i=[{text:typeof t=="string"?t:e?.text??""}];if(e?.pdfFiles&&e.pdfFiles.length>0){h.debug(`${r} Processing ${e.pdfFiles.length} PDF(s)`);for(const s of e.pdfFiles){let a;typeof s=="string"?Ei(s)?a=gs(s):a=Buffer.from(s,"base64"):a=s,i.push({inlineData:{mimeType:"application/pdf",data:a.toString("base64")}})}}if(e?.images&&e.images.length>0){h.debug(`${r} Processing ${e.images.length} image(s)`);for(const s of e.images){const a=s&&typeof s=="object"&&!Buffer.isBuffer(s)?s.data:s;let l,c="image/jpeg";if(typeof a=="string")if(Ei(a)){l=gs(a);const u=Lv(a).toLowerCase();u===".png"?c="image/png":u===".gif"?c="image/gif":u===".webp"&&(c="image/webp")}else if(a.startsWith("data:")){const u=a.match(/^data:([^;]+);base64,(.+)$/);if(u)c=u[1],l=Buffer.from(u[2],"base64");else continue}else if(a.startsWith("http://")||a.startsWith("https://"))try{const u=await fetch(a);if(!u.ok){h.warn(`${r} Image fetch failed: ${u.status} ${u.statusText}, skipping`,{url:a});continue}const d=await u.arrayBuffer();l=Buffer.from(d);const p=u.headers.get("content-type");p&&p.startsWith("image/")&&(c=p.split(";")[0])}catch(u){h.warn(`${r} Image URL fetch threw, skipping: ${u instanceof Error?u.message:String(u)}`,{url:a});continue}else l=Buffer.from(a,"base64");else l=a;l&&i.push({inlineData:{mimeType:c,data:l.toString("base64")}})}}return await sue(i,e?.nativeAudioFiles,r),await aue(i,e?.nativeVideoFiles,"google-ai-studio",n,r),i}var _T,mcr,YF,lue,ZF=E({"src/lib/providers/googleNativeGemini3/utils.ts"(){"use strict";$r(),Kr(),$t(),ii(),yzt(),EQ(),z(),WF(),Vc(),vs(),ecr(),_T=class extends Map{resultCache=new Map;get(e){const t=super.get(e);if(!t)return t;const r=this.resultCache;return async(o,i)=>{const s=`${e}::${fhn(o)}`;if(r.has(s))return h.warn(`[DedupExecuteMap] Tool "${e}" re-requested with identical arguments in the same turn \u2014 reusing the previous result instead of re-executing.`),r.get(s);const a=await t(o,i);return r.set(s,a),a}}},mcr=/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/,YF=128,lue=100}});function hcr(e,t){const r=t.config??{},n=r.thinkingConfig;return{provider:e,model:t.model,modelParameters:{temperature:r.temperature,maxTokens:r.maxOutputTokens,topP:r.topP,thinkingLevel:n?.thinkingLevel,thinkingBudget:n?.thinkingBudget},input:{system:r.systemInstruction,messages:t.contents}}}function QF(e){const t=o=>e.declarations?.originalNameMap?.get(o)??o,r=o=>{const i=e.declarations?.originalNameMap;if(!i)return o;for(const[s,a]of i)if(a===o)return s;return o};let n=0;return{providerLabel:e.providerLabel,maxSteps:e.maxSteps,...e.toolFailureBreaker?{toolFailureBreaker:e.toolFailureBreaker}:{},buildStepRequest(o,i){const s=e.declarations?vhn(e.liveTools,e.declarations):[],a=e.buildRequest(o,i);return{raw:a,generation:hcr(e.provider,a),...s.length>0?{hydratedToolNames:s}:{}}},...e.planReclaim?{planReclaim:(o,i)=>e.planReclaim?.(o,i)}:{},...e.enableMalformedRetry&&e.buildMalformedRetryNote?{isMalformedStep:o=>o.toolCalls.length===0&&!o.text&&o.rawStopReason==="MALFORMED_FUNCTION_CALL",buildMalformedRetryNote:e.buildMalformedRetryNote}:{},resolveToolOnMiss:o=>{const s=Fit(e.liveTools,o)?.execute;if(!s)return;const a=e.declarations?.executeMap;let l=s;return a&&(a.set(o,s),l=a.get(o)??s),{execute:e.toolGuards?e0(o,l,e.toolGuards):(async(u,d)=>l(u,d))}},async executeStep(o,i,s){const a=await e.sendStep(o.raw,s),l=e.collectStep?await e.collectStep(a,i):await bhn(a,{push:f=>i.push(f)});e.noteUsage?.(l.inputTokens,l.outputTokens);const c=Thn(l.rawResponseParts),u=l.stepFunctionCalls.map(f=>({id:`${e.providerLabel}_${n++}_${f.name}`,name:t(f.name),args:f.args})),d=e.finalResultToolName?u.find(f=>f.name===e.finalResultToolName):void 0,p=d?[]:u,m=d?JSON.stringify(d.args):c;return d&&e.onTerminalResult?.(m),{text:m,toolCalls:p,usage:{inputTokens:l.inputTokens,outputTokens:l.outputTokens,...l.cacheReadTokens?{cacheReadTokens:l.cacheReadTokens}:{},...l.reasoningTokens?{reasoningTokens:l.reasoningTokens}:{}},rawStopReason:l.finishReason,raw:{rawResponseParts:l.rawResponseParts,stepFunctionCalls:l.stepFunctionCalls}}},buildToolResultMessages(o,i,s,a){const l=[...o];return khn(l,i.raw.rawResponseParts,i.raw.stepFunctionCalls),l.push({role:"user",parts:s.map(c=>({functionResponse:{name:r(c.name),response:c.error?c.output:{result:c.output}}}))}),l},mapFinishReason(o,i){const s=t0(o);return s==="stop"||s==="tool-calls"?i?"tool-calls":"stop":s}}}var fcr=E({"src/lib/core/geminiLoopAdapter.ts"(){"use strict";WF(),Gk(),ZF()}});function ET(){const e=[];let t=!1,r,n=!1,o=null;function i(){if(o){const d=o;o=null,d()}}function s(d){t||(e.push(d),i())}function a(){t=!0,i()}function l(d){t=!0,r=d,n=!0,i()}let c=0;async function*u(){try{for(;;)if(c<e.length)yield e[c++],c>1024&&c*2>=e.length&&(e.splice(0,c),c=0);else if(t){if(n)throw r instanceof Error?r:new Error(String(r));return}else await new Promise(d=>{o=d})}finally{t=!0,e.length=0,o?.()}}return{push:s,close:a,error:l,iterable:u()}}var ST=E({"src/lib/core/streamChannel.ts"(){"use strict"}});function Lhn(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:(e.cacheReadTokens??0)+(t.cacheReadTokens??0)||void 0,cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)||void 0,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0)||void 0,cacheWrite5mTokens:(e.cacheWrite5mTokens??0)+(t.cacheWrite5mTokens??0)||void 0,cacheWrite1hTokens:(e.cacheWrite1hTokens??0)+(t.cacheWrite1hTokens??0)||void 0}}async function Fhn(e){const{name:t,execute:r,args:n,toolCallId:o,turnSignal:i,toolTimeoutMs:s}=e;if(s===null)return r(n,{toolCallId:o,abortSignal:i});const a=new AbortController,l=()=>a.abort(i.reason);i.aborted?a.abort(i.reason):i.addEventListener("abort",l,{once:!0});let c;const u=new Promise((d,p)=>{c=setTimeout(()=>{const m=new Error(`Tool "${t}" execution timed out after ${s}ms`);a.abort(m),p(m)},s)});try{return await Promise.race([Promise.resolve(r(n,{toolCallId:o,abortSignal:a.signal})),u])}finally{clearTimeout(c),i.removeEventListener("abort",l)}}async function $hn(e){const{calls:t,adapter:r,tools:n,failedTools:o,abortSignal:i,toolTimeoutMs:s}=e,a=[],l=[],c=[];let u=!1;for(const d of t){if(i.aborted){u=!0;break}c.push(d);const p=r.toolFailureBreaker,m=p?o.get(d.name):void 0;if(p&&m&&m.count>=p.maxRetries){const y={error:`TOOL_PERMANENTLY_FAILED: "${d.name}" has failed ${m.count} times. Last error: ${m.lastError}.`,status:"permanently_failed",do_not_retry:!0};a.push({...d,output:y,error:y.error,permanentlyFailed:!0}),l.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}const f=n?.[d.name];let g=f;if(!f?.execute){const y=r.resolveToolOnMiss?.(d.name);y&&(g=y,o.delete(d.name))}if(!g?.execute){const y=p?{error:`TOOL_NOT_FOUND: "${d.name}" does not exist.`,status:"permanently_failed",do_not_retry:!0}:{error:`Tool not found: ${d.name}`};a.push({...d,output:y,error:y.error,permanentlyFailed:!!p}),l.push({id:d.id,name:d.name,input:d.args,output:y,error:y.error});continue}try{const y=await Fhn({name:d.name,execute:g.execute,args:d.args,toolCallId:d.id,turnSignal:i,toolTimeoutMs:s}),v=p?.classifyResultFailure?.(y);if(p)if(v){const w=o.get(d.name)??{count:0,lastError:""};w.count++,w.lastError=v,o.set(d.name,w)}else p.consecutive&&o.delete(d.name);a.push({...d,output:y}),l.push({id:d.id,name:d.name,input:d.args,output:y})}catch(y){const v=y instanceof Error?y.message:String(y);if(p){const T=o.get(d.name)??{count:0,lastError:""};T.count++,T.lastError=v,o.set(d.name,T)}const w={error:v,status:"failed"};a.push({...d,output:w,error:v}),l.push({id:d.id,name:d.name,input:d.args,output:w,error:v})}}return{toolResults:a,executions:l,dispatched:c,abortedMidBatch:u}}async function Uhn(e,t,r,n,o){let i=!1,s;const a={push:l=>{i=!0,s??=new Date,r.push(l)}};return zm(t.generation??{},async l=>{let c;try{c=await kv(async()=>{i=!1;try{return await e.executeStep(t,a,n)}catch(u){throw i?new cue(u):u}},o,`${e.providerLabel}.step`,void 0,n)}catch(u){throw u instanceof cue?u.cause:u}return rc(l,{provider:t.generation?.provider,model:t.generation?.model,responseModel:c.model,output:{text:c.text,...c.reasoning?{reasoning:c.reasoning}:{},...c.toolCalls.length>0?{toolCalls:c.toolCalls}:{}},usage:{inputTokens:c.usage.inputTokens,outputTokens:c.usage.outputTokens,cacheReadTokens:c.usage.cacheReadTokens,cacheCreationTokens:c.usage.cacheWriteTokens,reasoningTokens:c.usage.reasoningTokens},finishReason:c.rawStopReason,aborted:n.aborted,completionStartTime:s}),c})}function Bp(e,t,r){const n=ET(),o=new AbortController,i=()=>o.abort();r.abortSignal?.addEventListener("abort",i),r.abortSignal?.aborted&&o.abort();const s=new Map;let a=!1;const l=(async()=>{let c=t,u={inputTokens:0,outputTokens:0},d="",p="",m;const f=[],g=[];let y=!1,v=e.maxSteps;const w=Date.now(),T=new m2;try{for(let A=0;A<v&&!o.signal.aborted;A++){if(T.begin(A+1),e.planReclaim){const U=e.planReclaim(c,A);if(U?.conversation!==void 0&&(c=U.conversation),U?.stop)break}const x=await e.buildStepRequest(c,A);for(const U of x.hydratedToolNames??[])s.delete(U);const R=await T.run(()=>Uhn(e,x,n,o.signal,r.span));if(u=Lhn(u,R.usage),m=R.rawStopReason,p=R.text||p,e.isMalformedStep?.(R)&&!a&&!o.signal.aborted){a=!0,h.warn(`[${e.providerLabel}] Malformed function call at step ${A+1}/${v}; retrying once.`),c=e.buildMalformedRetryNote?.(c,A)??c;continue}if(R.toolCalls.length===0){d=R.text||d;break}A===v-1&&(y=!0);const C=await T.run(()=>$hn({calls:R.toolCalls,adapter:e,tools:r.tools,failedTools:s,abortSignal:o.signal,toolTimeoutMs:zf(r.toolTimeoutMs)})),M=C.toolResults;if(f.push(...C.dispatched),g.push(...C.executions),C.abortedMidBatch)break;if(c=e.buildToolResultMessages(c,R,M,A),r.beforeStep&&!o.signal.aborted){const U=await r.beforeStep({stepIndex:A,stepsCompleted:A+1,maxSteps:v,elapsedMs:Date.now()-w,toolNames:C.dispatched.map(N=>N.name),signal:o.signal}),D=typeof U?.maxSteps=="number"&&Number.isFinite(U.maxSteps)?Math.floor(U.maxSteps):void 0;D!==void 0&&D>v&&(v=D,y=!1),U?.nudge&&e.appendPlanningNudge&&(c=e.appendPlanningNudge(c,U.nudge))}}const S=o.signal.aborted,k=e.mapFinishReason(m,y);return{text:d||(y?p:""),toolCalls:f,toolExecutions:g,usage:u,finishReason:S&&m===void 0?"other":k,rawStopReason:m,stopReason:S?"aborted":y?"step-cap":void 0,conversation:c,aborted:S}}catch(S){throw n.error(S),S}finally{T.end(),n.close(),r.abortSignal?.removeEventListener("abort",i)}})();return{stream:n.iterable,resultPromise:l}}var cue,e$=E({"src/lib/core/loopEngine.ts"(){"use strict";ST(),nc(),Cr(),z(),Zd(),ii(),cue=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.cause=e}cause}}});function Bhn(e,t){return e==="google-ai"?!0:e==="vertex"?!(t?.startsWith("claude-")??!1):!1}function zhn(e){return e==="anthropic"||e==="bedrock"}function uue(e,t,r,n){return(Bhn(e,t)||zhn(e))&&r&&n>0}function Ghn(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/cannot be combined with (a )?(tool|function)/i.test(t)||/json[\s_-]?(mode|schema|object|output)[^.]{0,60}(tool|function)/i.test(t)||/(tool|function)[\s-]?call[^.]{0,60}json[\s_-]?(mode|schema)/i.test(t)||/response_format[^.]{0,60}(tool|function)/i.test(t)}function gcr(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/too many states/i.test(t)}function qhn(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";return/does not support[^.]{0,80}response[\s_-]?format/i.test(t)||/response[\s_-]?format[^.]{0,60}(?:is )?not support/i.test(t)||/unsupported response[\s_-]?format/i.test(t)}var due=E({"src/lib/core/modules/structuredOutputPolicy.ts"(){"use strict"}});function jhn(e){return e?.kind==="toolCall"||e?.kind==="toolResult"}function Vhn(e,t,r){const n=[];let o=t;for(;o<r;){if(!jhn(e[o])){o++;continue}const i=o;for(;o<e.length&&e[o].kind==="toolCall";)o++;for(;o<e.length&&e[o].kind==="toolResult";)o++;if(o>r)break;n.push({start:i,end:o})}return n}function t$(e,t){const{availableInputTokens:r,fixedOverheadTokens:n,thresholdRatio:o=uP,lowWaterRatio:i=ycr,protectedTailCount:s=vcr,calibration:a=1}=t,l=a>0?a:1,c=Math.floor(r*o/l),u=Math.floor(r*i/l);let d=n;for(const v of e)d+=v.tokens;if(d<=c)return{fire:!1,truncate:[],drop:[],projectedTokens:d};const p=1,m=Math.max(p,e.length-s),f=[],g=new Set;for(let v=p;v<m&&d>u;v++){const w=e[v];if(w.kind!=="toolResult"||w.previewTokens===void 0)continue;const T=w.tokens-w.previewTokens;T<=0||(f.push(v),d-=T)}if(d>u){const v=Vhn(e,p,m);for(const w of v){if(d<=u)break;for(let T=w.start;T<w.end;T++){const S=e[T],k=f.includes(T)?S.previewTokens??S.tokens:S.tokens;d-=k,g.add(T)}}}const y=f.filter(v=>!g.has(v));return{fire:y.length>0||g.size>0,truncate:y,drop:[...g].sort((v,w)=>v-w),projectedTokens:d}}var ycr,vcr,r$=E({"src/lib/context/loopGuardCore.ts"(){"use strict";ii(),ycr=.6,vcr=4}});function wcr(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e)??""}catch{return"x".repeat(2e5)}}function bcr(e,t){return Array.isArray(e.parts)&&e.parts.some(r=>r&&typeof r=="object"&&t in r)}function Hhn(e){return bcr(e,"functionResponse")}function pue(e){const{preview:t}=Tl(e,{maxBytes:mue,maxLines:_cr});return t}function Whn(e,t){return Ht(wcr(e.parts),t)+bl}function Khn(e,t){return e.map(r=>{const n=Whn(r,t);if(Hhn(r)){const o=wcr(r.parts),i=o.length>mue?Ht(pue(o),t)+bl:n;return{kind:"toolResult",tokens:n,...i<n?{previewTokens:i}:{}}}return bcr(r,"functionCall")?{kind:"toolCall",tokens:n}:{kind:"other",tokens:n}})}function Tcr(e){const{contents:t,availableInputTokens:r,fixedOverheadTokens:n=0,provider:o,observedPromptTokens:i}=e,s=Khn(t,o);let a=1;if(i&&i>0){const c=n+s.reduce((u,d)=>u+d.tokens,0);c>0&&(a=Math.min(3,Math.max(1,i/c)))}const l=t$(s,{availableInputTokens:r,fixedOverheadTokens:n,calibration:a});if(l.fire)return h.info("[GeminiLoopGuard] Reclaiming agent-loop context",{provider:o,contents:t.length,toolResponsesTruncated:l.truncate.length,contentsDropped:l.drop.length,projectedTokens:l.projectedTokens,calibration:a}),l}var mue,_cr,hue,Ecr=E({"src/lib/context/geminiLoopGuard.ts"(){"use strict";fi(),ty(),r$(),z(),mue=2048,_cr=60,hue="[Earlier tool exchanges were removed to fit the context window.]"}}),Scr=E({"src/lib/providers/googleNativeGemini3/index.ts"(){"use strict";ZF()}}),fue,zp,kcr=E({"src/lib/providers/anthropic/cacheControl.ts"(){"use strict";fue=e=>{if(!e||e.length===0)return e;if(e.some(r=>r.cache_control!==void 0))return[...e];const t=e[e.length-1];return[...e.slice(0,-1),{...t,cache_control:{type:"ephemeral"}}]},zp=e=>e?.providerOptions?.anthropic?.cacheControl?.type==="ephemeral"?{type:"ephemeral"}:void 0}});function kT(e,t){if(t==="functionDeclarations")return tcr(e);const r=Object.entries(e??{});if(r.length!==0)return r.map(([n,o])=>{const i=o,s=i.inputSchema??i.parameters,a=s?Wo(s):{type:"object",properties:{}},l=zp(o);return{name:n,...i.description?{description:i.description}:{},input_schema:a,...l?{cache_control:l}:{}}})}var gue=E({"src/lib/core/nativeToolFormat.ts"(){"use strict";ZF(),kcr(),vs()}});function Jhn(e,t,r){const n=e[Symbol.asyncIterator]();return new ReadableStream({async pull(o){try{const i=await n.next();i.done?(o.enqueue(await t),o.close()):o.enqueue({type:"text-delta",delta:i.value.content})}catch(i){o.error(i)}},async cancel(){r(),await n.return?.()}})}async function*Xhn(e,t,r){const n=e.getReader();let o=!1,i=!1;try{for(;;){const s=await n.read();if(s.done){o=!0;return}const a=s.value;if(a.type==="text-delta")yield{content:a.delta};else if(a.type==="finish")i=!0,t(a);else if(a.type==="error")throw a.error}}finally{try{o||await n.cancel()}finally{n.releaseLock(),i||r?.()}}}function xcr(e,t){const r=e.systemInstruction;return[...typeof r=="string"&&r.length>0?[{role:"system",content:r}]:[],...Phn(t)]}async function xT(e,t){const n=(await Promise.resolve().then(()=>(KS(),Fv))).GoogleGenAI;if(!n)throw new Me({code:qe.INVALID_CONFIGURATION,message:"@google/genai does not export GoogleGenAI",category:"configuration",severity:"critical",retriable:!1,context:{module:"@google/genai",expectedExport:"GoogleGenAI"}});const o=n;return new o({apiKey:e,httpOptions:{...t?{baseUrl:t}:{},...YS()}})}function Acr(e,t,r){const n=Tcr({contents:e,availableInputTokens:cc("googleAiStudio",t),provider:"googleAiStudio",...r?{observedPromptTokens:r}:{}});if(!n)return!1;const o=new Set(n.drop),i=new Set(n.truncate),s=[];for(let a=0;a<e.length;a++){if(o.has(a))continue;const l=e[a];if(i.has(a)&&Array.isArray(l.parts)){s.push({...l,parts:l.parts.map(c=>{const u=c;if(!u.functionResponse)return c;const d=JSON.stringify(u.functionResponse.response)??"";return d.length<=2048?c:{functionResponse:{name:u.functionResponse.name,response:{result:pue(d)}}}})});continue}s.push(l)}if(o.size>0){let a=s.findIndex(l=>Array.isArray(l.parts)&&l.parts.some(c=>!!c.functionCall||!!c.functionResponse));a<0&&(a=Math.min(1,s.length)),s.splice(a,0,{role:"user",parts:[{text:hue}]})}return e.length=0,e.push(...s),!0}var Ccr,Yhn=E({"src/lib/providers/googleAiStudio/client.ts"(){"use strict";_l(),ii(),hD(),ic(),ct(),Qe(),z(),eue(),kg(),nc(),Cr(),fcr(),Vm(),e$(),ii(),due(),Ecr(),Zc(),oa(),ny(),fi(),sc(),dd(),Scr(),ST(),gue(),rn(),Ccr=class extends Ua{credentials;constructor(e,t,r){super(e,"google-ai",t),this.credentials=r,h.debug("GoogleAIStudioProvider initialized",{model:this.modelName,provider:this.providerName,sdkProvided:!!t})}getProviderName(){return"google-ai"}getDefaultModel(){return process.env.GOOGLE_AI_MODEL||"gemini-2.5-flash"}getAISDKModel(){throw new Me({code:qe.INVALID_CONFIGURATION,message:"GoogleAIStudioProvider no longer uses @ai-sdk/google. All models use native @google/genai SDK.",category:"configuration",severity:"critical",retriable:!1,context:{provider:this.providerName,model:this.modelName}})}formatProviderError(e){if(e instanceof Ma)return new pi(e.message,this.providerName);const t=e,r=typeof t?.message=="string"?t.message:"Unknown error",n=typeof t?.status=="number"?t.status:typeof t?.statusCode=="number"?t.statusCode:void 0;return r.includes("API_KEY_INVALID")||r.includes("Invalid API key")||n===401?new Qr("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.",this.providerName):r.includes("RATE_LIMIT_EXCEEDED")||r.includes("rate limit")||r.includes("429")||n===429?new ps("Google AI rate limit exceeded. Please try again later.",this.providerName):n===404||n===void 0&&(r.includes("model not found")||r.includes("Model not found"))?new ti(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`,this.providerName):r.includes("ECONNRESET")||r.includes("ENOTFOUND")||r.includes("ETIMEDOUT")||r.includes("ECONNREFUSED")||r.includes("network")||r.includes("connection")?new pi(`Connection error: ${r}`,this.providerName):r.includes("500")||r.includes("502")||r.includes("503")||r.includes("504")||r.includes("server error")||r.includes("Internal Server Error")||n&&n>=500&&n<600?new Je(`Google AI server error: ${r}. Please try again later.`,this.providerName):new Je(`Google AI error: ${r}`,this.providerName)}async executeImageGeneration(e){return zm({provider:this.providerName,model:e.model||this.modelName,input:{prompt:e.prompt||e.input?.text||""}},t=>this.generateImage(e,t))}async generateImage(e,t){await Hx(e.input);const r=e.prompt||e.input?.text||"",n=e.model||this.modelName,o=Date.now(),i=this.getApiKey();h.info("\u{1F3A8} Starting Google AI Studio image generation",{model:n,prompt:r.substring(0,100),provider:this.providerName});let s;try{s=await xT(i,this.getBaseURL())}catch{throw new Qr("Missing '@google/genai'. Install with: npm install @google/genai",this.providerName)}try{const a=await Promise.all((e.input?.images||[]).map(async p=>{if(typeof p=="object"&&"url"in p){const g=p.url;if(g.startsWith("http")){const w=await fetch(g);if(!w.ok)throw new Error(`Failed to fetch image from ${g}: ${w.status} ${w.statusText}`);const T=await w.arrayBuffer(),S=Buffer.from(T),k=this.detectImageType(S);return h.debug(`Downloaded and detected image MIME type: ${k}`),{inlineData:{mimeType:k,data:S.toString("base64")}}}const y=Buffer.from(g,"base64");return{inlineData:{mimeType:this.detectImageType(y),data:y.toString("base64")}}}if(typeof p=="string"&&p.startsWith("http")){const g=await fetch(p);if(!g.ok)throw new Error(`Failed to fetch image from ${p}: ${g.status} ${g.statusText}`);const y=await g.arrayBuffer(),v=Buffer.from(y),w=this.detectImageType(v);return h.debug(`Downloaded and detected image MIME type: ${w}`),{inlineData:{mimeType:w,data:v.toString("base64")}}}const m=Buffer.isBuffer(p)?p:typeof p=="string"?Buffer.from(p,"base64"):Buffer.from(""),f=this.detectImageType(m);return h.debug(`Detected image MIME type: ${f}`),{inlineData:{mimeType:f,data:m.toString("base64")}}})),l=[{role:"user",parts:[{text:r},...a]}],c={responseModalities:["IMAGE","TEXT"]};h.debug("Starting image generation request",{model:n,contentParts:l[0].parts.length,responseModalities:c.responseModalities});let u=null,d="";try{const p=await s.models.generateContentStream({model:n,contents:l,config:c});for await(const m of p){h.debug("Received chunk",{hasCandidate:!!m.candidates?.[0],hasContent:!!m.candidates?.[0]?.content,hasParts:!!m.candidates?.[0]?.content?.parts});const f=m.candidates?.[0];if(f?.content?.parts)for(const g of f.content.parts){if("inlineData"in g&&g.inlineData?.data){const y=g.inlineData.data;u=y;const v=g.inlineData.mimeType,w=v||"image/png";h.info("Image generation successful",{model:n,mimeType:w,dataLength:y.length,responseTime:Date.now()-o});const T={content:`Generated image using ${n} (${w})`,imageOutput:{base64:y,...v?{mimeType:v}:{}},provider:this.providerName,model:n,usage:{input:this.estimateTokenCount(r),output:0,total:this.estimateTokenCount(r)}};return rc(t,{responseModel:n,output:T.content,usage:T.usage,finishReason:"stop"}),await this.enhanceResult(T,e,o)}"text"in g&&g.text&&(d+=g.text,h.debug("Received text content",{text:g.text.substring(0,100)}))}}}catch(p){h.debug("Streaming failed, trying non-streaming approach",{error:p instanceof Error?p.message:String(p)})}if(!u){h.debug("Trying non-streaming approach");const m=(await s.models.generateContent({model:n,contents:l,config:c})).candidates?.[0];if(m?.content?.parts)for(const f of m.content.parts){if("inlineData"in f&&f.inlineData?.data){const g=f.inlineData.data;u=g;const y=f.inlineData.mimeType,v=y||"image/png";h.info("Image generation successful (non-streaming)",{model:n,mimeType:v,dataLength:g.length,responseTime:Date.now()-o});const w={content:`Generated image using ${n} (${v})`,imageOutput:{base64:g,...y?{mimeType:y}:{}},provider:this.providerName,model:n,usage:{input:this.estimateTokenCount(r),output:0,total:this.estimateTokenCount(r)}};return rc(t,{responseModel:n,output:w.content,usage:w.usage,finishReason:"stop"}),await this.enhanceResult(w,e,o)}"text"in f&&f.text&&(d+=f.text)}}throw h.warn("No image data found in response",{model:n,prompt:r.substring(0,100),hasTextContent:!!d,textContent:d.substring(0,200)}),new Je(d||`Image generation completed but no image data was returned. This may indicate an issue with the model "${n}" or the prompt: "${r}". Please try again or use a different model.`,this.providerName)}catch(a){throw h.error("Image generation failed",{error:a instanceof Error?a.message:String(a),model:n,prompt:r.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 Ht(e,"google-ai")}async preprocessNativeFileInput(e){if(e.input&&OQ(e.input),e.input?.files&&e.input.files.length>0)try{await DQ(e,100*1024*1024,this.providerName)}catch(t){h.warn(`[GoogleAIStudio] processUnifiedFilesArray threw, continuing without file content: ${t instanceof Error?t.message:String(t)}`)}await Hx(e.input)}async executeStream(e,t){const r=e.model||this.modelName;if(e.input?.audio)return await this.executeAudioStreamViaGeminiLive(e);await this.preprocessNativeFileInput(e);const n=!!(t||e.output?.format==="json"||e.schema),o=!e.disableTools&&this.supportsTools()&&!n,i=e.tools||{};let s={...e,tools:i};const a=e.output?.format==="json"||e.schema,l=uue(this.providerName,r,!s.disableTools,Object.keys(s.tools??{}).length);return a&&l&&(h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request."),s={...s,disableTools:!0,tools:{}}),o&&!s.disableTools&&s.tools&&Object.keys(s.tools).length>0&&h.info("[GoogleAIStudio] Routing to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(s.tools??{}).length}),this.executeNativeGemini3Stream(s)}async executeNativeGemini3Stream(e){const t=e.model||this.modelName;return YXe({name:"provider.stream",tracer:Ue.provider,detached:!0,attributes:{[Le.NL_MODEL]:t,[Le.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=Ra(o,this.providerName,"stream");{const s=this.getApiKey(),a=await xT(s,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const l=[];XF(l,e.conversationMessages);const c=await pcr(e.input,e.input.text,"[GoogleAIStudio:stream]",t);l.push({role:"user",parts:c});let u,d;if(e.tools&&Object.keys(e.tools).length>0&&!e.disableTools){const ee=kT(e.tools,"functionDeclarations");d=ee,u=ee.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK",{toolCount:u[0].functionDeclarations.length,toolNames:u[0].functionDeclarations.map(te=>te.name)})}const p=!u&&(e.output?.format==="json"||!!e.schema),m=p&&e.schema?scr(e.schema):void 0,f=rcr({...e,model:t,wantsJsonOutput:p,responseSchema:m},u),g=ncr(e.maxSteps),y=Tv(e.abortSignal,i?.controller.signal),v=new AbortController,w=()=>v.abort();y?.addEventListener("abort",w),y?.aborted&&v.abort();const T=zf(e.toolTimeoutMs),S=bT({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:ee=>{h.warn(ee==="timeout"?`[GoogleAIStudio] Native Gemini turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),v.abort()}}),k=v.signal,A=()=>S.timedOut||i?.controller.signal.aborted===!0,x=ET(),R=[],C=[];let M,O;const U=new Promise((ee,te)=>{M=ee,O=te}),D={streamId:`native-${Date.now()}`,startTime:n,responseTime:0,totalToolExecutions:0},N=async(ee,te)=>{let de="",ye=0,Ee=0,Se=0,xe=0,be=0,we=0,me=!1,Re;const Oe=TT(hd("googleAiStudio",t));try{const ot=QF({providerLabel:"GoogleAIStudio",provider:this.providerName,maxSteps:g,toolFailureBreaker:{maxRetries:Gf},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:T,abortSignal:k,onProgress:()=>S.noteProgress()},...d?{declarations:d}:{},buildRequest:ue=>({model:t,contents:ue,config:te}),sendStep:async(ue,I)=>{S.noteProgress();const H=ue;return a.models.generateContentStream({...H,config:{...H.config??{},abortSignal:I}})},noteUsage:(ue,I)=>{Oe.noteUsage(ue,I)},planReclaim:(ue,I)=>{if(I!==0&&!Oe.shouldStop())return;const H=[...ue];if(Acr(H,t,Oe.projectedNextPromptTokens))return Oe.resetAfterReclaim(),{conversation:H}}}),Ve={...ot,buildStepRequest:(ue,I)=>(we=I+1,S.noteProgress(),ot.buildStepRequest(ue,I)),buildToolResultMessages:(ue,I,H,fe)=>{be=fe+1;for(const K of I.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":K.name,"tool.step":be});de=I.text||de;for(const K of I.toolCalls)R.push({toolName:K.name,args:K.args});for(const K of H)C.push({name:K.name,input:K.args,output:K.output});if(H.length>0){const K=JF(I.raw.rawResponseParts);St(this.handleToolExecutionStorage(I.toolCalls.map((F,X)=>({toolName:F.name,args:F.args,...X===0&&K?{thoughtSignature:K}:{},stepIndex:be})),H.map(F=>({toolName:F.name,output:F.output,stepIndex:be})),e,new Date),qf,"tool storage write timed out").catch(F=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:F instanceof Error?F.message:String(F)})})}const W=ot.buildToolResultMessages(ue,I,H,fe);if(S.shouldNudgeWrapup()){const K=W[W.length-1];K&&Array.isArray(K.parts)&&K.parts.push({text:wT(!1)})}try{const K=W[W.length-1];Oe.noteAppendedChars(JSON.stringify(K?.parts??[]).length)}catch{}return W}},_e=KF(d,e.tools,{toolTimeoutMs:T,abortSignal:k,onProgress:()=>S.noteProgress()}),{stream:De,resultPromise:Q}=Bp(Ve,ee,{tools:_e,abortSignal:k,toolTimeoutMs:T}),Z=(async()=>{for await(const ue of De)S.noteProgress(),x.push(ue)})();let Ce,Y;try{Ce=await Q}catch(ue){Y=ue}if(await Qy(Z,"GoogleAIStudio"),Y!==void 0)if(S.expired||e.abortSignal?.aborted)me=!0;else throw h.error("[GoogleAIStudio] Native SDK error",Y),this.handleProviderError(Y);Ce&&(ye+=Ce.usage.inputTokens,Ee+=Ce.usage.outputTokens,Se+=Ce.usage.cacheReadTokens??0,xe+=Ce.usage.reasoningTokens??0,Re=Ce.rawStopReason??Re,Ce.aborted&&(me=!0)),k.aborted&&(me=!0);const ne=Ce!==void 0&&(Ce.toolCalls.length===0||Ce.finishReason!=="tool-calls"),ce=!me&&be>=g&&!ne;if(ce){const ue=ocr("[GoogleAIStudio]",be,g,"",de);ue&&x.push({content:ue})}else me&&!ne&&(h.warn(`[GoogleAIStudio] Tool call loop ended mid-turn (${A()?"turn time limit":S.stalled?"stall watchdog":"caller abort"}); returning an honest terminal message.`),x.push({content:nue({timedOut:A(),stalled:S.stalled,elapsedMs:S.elapsedMs(),wasAborted:me,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:g,toolCallCount:R.length})}));const ve=Date.now()-n,he=Up({timedOut:A(),stalled:S.stalled,wasAborted:me,cappedWithoutAnswer:ce,finishReason:t0(Re)});he!=="completed"&&this.emitTurnEvent({phase:he,step:we,maxSteps:g,toolCallCount:R.length,elapsedMs:S.elapsedMs()}),D.responseTime=ve,D.totalToolExecutions=R.length,D.stopReason=he,D.stepsUsed=we,Re!==void 0&&(D.rawFinishReason=Re);const ae=Math.max(0,ye-Se);M({provider:this.providerName,model:t,tokenUsage:{input:ae,output:Ee+xe,total:ae+Se+Ee+xe,...Se>0?{cacheReadTokens:Se}:{},...xe>0?{reasoning:xe}:{}},requestDuration:ve,timestamp:new Date().toISOString(),stepsUsed:we,toolCallCount:R.length,stopReason:he,elapsedMs:S.elapsedMs(),...Re!==void 0?{rawFinishReason:Re}:{}}),x.close()}catch(ot){x.error(ot),O(ot)}finally{S.dispose(),y?.removeEventListener("abort",w),i?.cleanup()}};let $;const L={prompt:xcr(f,l),...typeof f.maxOutputTokens=="number"?{maxOutputTokens:f.maxOutputTokens}:{},...typeof f.temperature=="number"?{temperature:f.temperature}:{},...typeof f.topP=="number"?{topP:f.topP}:{},abortSignal:k},G={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doGenerate:()=>{throw new Error("GoogleAIStudio: doGenerate is not implemented on the native stream model \u2014 NeuroLink streams through executeStream/doStream for this provider.")},doStream:async ee=>{const{contents:te,systemText:de}=dcr(ee.prompt),ye={...f,...typeof ee.temperature=="number"?{temperature:ee.temperature}:{},...typeof ee.maxOutputTokens=="number"?{maxOutputTokens:ee.maxOutputTokens}:{},...typeof ee.topP=="number"?{topP:ee.topP}:{}};de?ye.systemInstruction=de:delete ye.systemInstruction,$=N(te,ye),$.catch(()=>{});const Ee=U.then(Se=>({type:"finish",finishReason:{unified:t0(D.rawFinishReason)},usage:{inputTokens:{total:Se.tokenUsage.input},outputTokens:{total:Se.tokenUsage.output}}}));return Ee.catch(()=>{}),{stream:Jhn(x.iterable,Ee,()=>v.abort())}}};let B;try{const ee=await this.applyMiddlewareToModel(G,e);if(typeof ee=="string")throw new Error("GoogleAIStudio: native stream middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");({stream:B}=await ee.doStream(L))}catch(ee){throw v.abort(),x.close(),S.dispose(),y?.removeEventListener("abort",w),i?.cleanup(),this.handleProviderError(ee)}let V=!1;const j=ee=>{if($||V)return;V=!0;const te=Date.now()-n,de=Up({timedOut:!1,stalled:!1,wasAborted:!ee,cappedWithoutAnswer:!1,...ee?{finishReason:ee.finishReason.unified}:{}});D.responseTime=te,D.stopReason=de,D.stepsUsed=0,M({provider:this.providerName,model:t,tokenUsage:{input:ee?.usage.inputTokens.total??0,output:ee?.usage.outputTokens.total??0,total:(ee?.usage.inputTokens.total??0)+(ee?.usage.outputTokens.total??0)},requestDuration:te,timestamp:new Date().toISOString(),stepsUsed:0,toolCallCount:0,stopReason:de,elapsedMs:te}),S.dispose(),y?.removeEventListener("abort",w),i?.cleanup()},J={stream:Xhn(B,ee=>j(ee),()=>j()),provider:this.providerName,model:t,toolCalls:R,analytics:U,metadata:D};return Object.defineProperty(J,"toolsUsed",{enumerable:!0,configurable:!0,get:()=>R.map(ee=>ee.toolName)}),Object.defineProperty(J,"toolExecutions",{enumerable:!0,configurable:!0,get:()=>ud(C)}),J}},r=>r.stream,(r,n)=>({...r,stream:n}))}async executeNativeGemini3Generate(e){const t=e.model||this.modelName;return ck({name:"provider.generate",tracer:Ue.provider,detached:!0,attributes:{[Le.NL_MODEL]:t,[Le.NL_PROVIDER]:this.providerName}},async r=>{const n=Date.now(),o=this.getTimeout(e),i=Ra(o,this.providerName,"generate");let s=()=>{};try{const a=this.getApiKey(),l=await xT(a,this.getBaseURL());h.debug("[GoogleAIStudio] Using native @google/genai for Gemini 3 generate",{model:t,hasTools:!!e.tools&&Object.keys(e.tools).length>0});const c=e.input?.text||e.prompt||"",u=[];XF(u,e.conversationMessages);const d=await pcr(e.input,c,"[GoogleAIStudio:generate]",t);u.push({role:"user",parts:d});let p,m;const f=!e.disableTools,g=!!(e.output?.format==="json"||e.schema),y=uue(this.providerName,t,f,Object.keys(e.tools||{}).length);if(g&&y&&h.warn("[GoogleAIStudio] Gemini does not support tools and JSON schema output simultaneously. Disabling tools for this request (generate())."),f&&!(g&&y)){const J=e.tools||{};if(Object.keys(J).length>0){const ee=kT(J,"functionDeclarations");m=ee,p=ee.toolsConfig,h.debug("[GoogleAIStudio] Converted tools for native SDK generate",{toolCount:p[0].functionDeclarations.length,toolNames:p[0].functionDeclarations.map(te=>te.name)})}}const v=!p&&g,w=v&&e.schema?scr(e.schema):void 0,T=rcr({...e,model:t,wantsJsonOutput:v,responseSchema:w},p),S=Tv(e.abortSignal,i?.controller.signal),k=new AbortController,A=()=>k.abort();S?.addEventListener("abort",A),S?.aborted&&k.abort();const x=zf(e.toolTimeoutMs),R=bT({...e.turnTimeoutMs!==void 0?{turnTimeoutMs:e.turnTimeoutMs}:{},...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},...e.wrapupTimeLeadMs!==void 0?{wrapupTimeLeadMs:e.wrapupTimeLeadMs}:{},onDeadline:J=>{h.warn(J==="timeout"?`[GoogleAIStudio] Native Gemini generate turn exceeded its ${e.turnTimeoutMs}ms time budget \u2014 aborting`:`[GoogleAIStudio] Native Gemini generate turn made no progress for ${e.stallTimeoutMs}ms \u2014 aborting`),k.abort()}}),C=k.signal;s=()=>{R.dispose(),S?.removeEventListener("abort",A)};const M=()=>R.timedOut||i?.controller.signal.aborted===!0,O=ncr(e.maxSteps),U=async(J,ee)=>{let te="",de="",ye=0,Ee=0,Se=0,xe=0;const be=[],we=[];let me=0,Re=0,Oe=!1,ot;const Ve=TT(hd("googleAiStudio",t)),_e=QF({providerLabel:"GoogleAIStudio",provider:this.providerName,maxSteps:O,toolFailureBreaker:{maxRetries:Gf},liveTools:e.tools??{},toolGuards:{toolTimeoutMs:x,abortSignal:C,onProgress:()=>R.noteProgress()},...m?{declarations:m}:{},buildRequest:H=>({model:t,contents:H,config:ee}),sendStep:async(H,fe)=>{R.noteProgress();const W=H;return l.models.generateContentStream({...W,config:{...W.config??{},abortSignal:fe}})},noteUsage:(H,fe)=>{Ve.noteUsage(H,fe)},planReclaim:(H,fe)=>{if(fe!==0&&!Ve.shouldStop())return;const W=[...H];if(Acr(W,t,Ve.projectedNextPromptTokens))return Ve.resetAfterReclaim(),{conversation:W}}}),De={..._e,buildStepRequest:(H,fe)=>(Re=fe+1,R.noteProgress(),_e.buildStepRequest(H,fe)),buildToolResultMessages:(H,fe,W,K)=>{me=K+1;for(const X of fe.toolCalls)r.addEvent("gen_ai.tool_call",{"tool.name":X.name,"tool.step":me}),be.push({toolName:X.name,args:X.args});de=fe.text||de;for(const X of W)we.push({name:X.name,input:X.args,output:X.output});if(W.length>0){const X=JF(fe.raw.rawResponseParts);St(this.handleToolExecutionStorage(fe.toolCalls.map((le,Ie)=>({toolName:le.name,args:le.args,...Ie===0&&X?{thoughtSignature:X}:{},stepIndex:me})),W.map(le=>({toolName:le.name,output:le.output,stepIndex:me})),e,new Date),qf,"tool storage write timed out").catch(le=>{h.warn("[GoogleAIStudio] Failed to store native tool executions",{error:le instanceof Error?le.message:String(le)})})}const F=_e.buildToolResultMessages(H,fe,W,K);if(R.shouldNudgeWrapup()){const X=F[F.length-1];X&&Array.isArray(X.parts)&&X.parts.push({text:wT(!1)})}try{const X=F[F.length-1];Ve.noteAppendedChars(JSON.stringify(X?.parts??[]).length)}catch{}return F}},Q=KF(m,e.tools,{toolTimeoutMs:x,abortSignal:C,onProgress:()=>R.noteProgress()}),{stream:Z,resultPromise:Ce}=Bp(De,J,{tools:Q,abortSignal:C,toolTimeoutMs:x}),Y=(async()=>{for await(const H of Z)R.noteProgress()})();let ne,ce;try{ne=await Ce}catch(H){ce=H}if(await Qy(Y,"GoogleAIStudio"),ce!==void 0)if(R.expired||e.abortSignal?.aborted)Oe=!0;else throw h.error("[GoogleAIStudio] Native SDK generate error",ce),this.handleProviderError(ce);ne&&(ye+=ne.usage.inputTokens,Ee+=ne.usage.outputTokens,Se+=ne.usage.cacheReadTokens??0,xe+=ne.usage.reasoningTokens??0,ot=ne.rawStopReason??ot,te=ne.text,ne.aborted&&(Oe=!0)),C.aborted&&(Oe=!0);const ve=!Oe&&me>=O&&!te;Oe&&!te?(h.warn(`[GoogleAIStudio] Generate tool call loop ended mid-turn (${M()?"turn time limit":R.stalled?"stall watchdog":"caller abort"}); returning gathered text or an honest terminal message.`),te=de||nue({timedOut:M(),stalled:R.stalled,elapsedMs:R.elapsedMs(),wasAborted:Oe,...e.stallTimeoutMs!==void 0?{stallTimeoutMs:e.stallTimeoutMs}:{},maxSteps:O,toolCallCount:be.length})):te=ocr("[GoogleAIStudio]",me,O,te,de);const he=Date.now()-n,ae=Up({timedOut:M(),stalled:R.stalled,wasAborted:Oe,cappedWithoutAnswer:ve,finishReason:t0(ot)});ae!=="completed"&&this.emitTurnEvent({phase:ae,step:Re,maxSteps:O,toolCallCount:be.length,elapsedMs:R.elapsedMs()});const ue=Math.max(0,ye-Se);return{content:te,provider:this.providerName,model:t,stopReason:ae,stepsUsed:Re,...ot!==void 0?{rawFinishReason:ot}:{},usage:{input:ue,output:Ee+xe,total:ue+Se+Ee+xe,...Se>0?{cacheReadTokens:Se}:{},...xe>0?{reasoning:xe}:{}},...xe>0&&{reasoningTokens:xe},responseTime:he,toolsUsed:be.map(H=>H.toolName),toolExecutions:Wm(e,we),enhancedWithTools:be.length>0}};let D;const N={prompt:xcr(T,u),...typeof T.maxOutputTokens=="number"?{maxOutputTokens:T.maxOutputTokens}:{},...typeof T.temperature=="number"?{temperature:T.temperature}:{},...typeof T.topP=="number"?{topP:T.topP}:{},abortSignal:C},$={specificationVersion:"v3",provider:this.providerName,modelId:t,supportedUrls:{},doStream:()=>{throw new Error("GoogleAIStudio: doStream is not implemented on the native generate model \u2014 NeuroLink runs this provider's turn synchronously through doGenerate.")},doGenerate:async J=>{const{contents:ee,systemText:te}=dcr(J.prompt),de={...T,...typeof J.temperature=="number"?{temperature:J.temperature}:{},...typeof J.maxOutputTokens=="number"?{maxOutputTokens:J.maxOutputTokens}:{},...typeof J.topP=="number"?{topP:J.topP}:{}};te?de.systemInstruction=te:delete de.systemInstruction;const ye=await U(ee,de);return D=ye,{content:ye.content?[{type:"text",text:ye.content}]:[],finishReason:{unified:t0(ye.rawFinishReason)},usage:{inputTokens:{total:ye.usage?.input??0},outputTokens:{total:ye.usage?.output??0}}}}};let L;try{const J=await this.applyMiddlewareToModel($,e);if(typeof J=="string")throw new Error("GoogleAIStudio: native generate middleware resolved to a bare model id string, expected a LanguageModelV3 handle.");L=await J.doGenerate(N)}catch(J){throw this.handleProviderError(J)}let G="";for(const J of L.content)J.type==="text"&&(G+=J.text);const B=D?.usage,V=L.usage.inputTokens.total??0,j=L.usage.outputTokens.total??0,se={...D??{provider:this.providerName,model:t,stopReason:Up({timedOut:!1,stalled:!1,wasAborted:!1,cappedWithoutAnswer:!1,finishReason:L.finishReason.unified}),stepsUsed:0,responseTime:Date.now()-n,toolsUsed:[],toolExecutions:[],enhancedWithTools:!1},content:G,usage:{...B,input:V,output:j,total:V+j+(B?.cacheReadTokens??0)}};return this.enhanceResult(se,e,n)}finally{s(),i?.cleanup()}})}async generate(e){const t=typeof e=="string"?{prompt:e}:e,r=t.model||this.modelName;if(dS.some(d=>r.toLowerCase().startsWith(d.toLowerCase())))return h.info("[GoogleAIStudio] Routing image generation model to executeImageGeneration",{model:r}),this.executeImageGeneration(t);if(HK(t.tts))return h.info("[GoogleAIStudio] Routing TTS direct-synthesis to handleDirectTTSSynthesis",{model:r}),this.handleDirectTTSSynthesis(t,Date.now());await this.preprocessNativeFileInput(t);const o=t.disableTools?{}:await this.getToolsForStream(t);let i={...t,tools:o};const s=t.output?.format==="json"||t.schema,a=uue(this.providerName,r,!i.disableTools,Object.keys(i.tools??{}).length);s&&a&&(h.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&&h.info("[GoogleAIStudio] Routing generate to native @google/genai SDK for tool calling",{model:r,totalToolCount:Object.keys(i.tools??{}).length});const c=Date.now(),u=i.input?.text||i.prompt||"";try{let d=await dt({name:"executeGeneration",tracer:Ue.provider,detached:!0,attributes:{[Le.NL_MODEL]:r,path:"native.google-genai"}},async()=>this.executeNativeGemini3Generate(i));return d=await this.synthesizeAIResponseIfNeeded(d,t),this.emitGenerationEnd(r,d,c,!0,void 0,u),d}catch(d){throw this.emitGenerationEnd(r,null,c,!1,d,u),d}}emitGenerationEnd(e,t,r,n,o,i){const s=this.neurolink?.getEventEmitter();if(!s)return;const a=t?.usage&&typeof t.usage=="object"?t.usage:{input:0,output:0,total:0};t&&typeof t=="object"&&(t._generationEndEmitted=!0),!n&&o&&typeof o=="object"&&(o._generationEndEmitted=!0),s.emit("generation:end",{provider:this.providerName,responseTime:Date.now()-r,timestamp:Date.now(),prompt:i||"",result:{content:t?.content||"",usage:a,model:e,provider:this.providerName,finishReason:n?"stop":"error"},success:n,...o?{error:o instanceof Error?o.message:String(o)}:{}})}async executeAudioStreamViaGeminiLive(e){const t=Date.now(),r=this.getApiKey();let n;try{n=await xT(r,this.getBaseURL())}catch{throw new Qr("Missing '@google/genai'. Install with: pnpm add @google/genai",this.providerName)}const o=this.modelName||process.env.GOOGLE_VOICE_AI_MODEL||"gemini-2.5-flash-preview-native-audio-dialog",i=[];let s=null,a=!1,l=!1,c=!1,u,d=!1,p,m=()=>{};const f=()=>{const C=s;s=null,C?.()},g=()=>{if(c||(c=!0,m(),Sg(e.input?.audio?.frames),p&&(nw(p),p=void 0)),u&&!d){d=!0;try{Promise.resolve(u.close?.()).catch(()=>{})}catch{}}},y=C=>{a||l||(i.push(C),C.type!=="audio"&&(l=!0,g()),f())},v=()=>{a=!0,i.length=0,g(),f()};let w=!1,T=()=>{};const S=new Promise((C,M)=>{T=M}),k=n.live.connect({model:o,callbacks:{onopen:()=>{},onmessage:async C=>{if(!(a||l))try{const M=C?.serverContent?.modelTurn?.parts?.[0]?.inlineData;if(M?.data){const U={data:Buffer.from(String(M.data),"base64"),sampleRateHz:24e3,channels:1,encoding:"PCM16LE"};y({type:"audio",audio:U})}C?.serverContent?.interrupted}catch(M){y({type:"error",error:M})}},onerror:C=>{w||T(new Error("Gemini Live connection failed before setup completed")),y({type:"error",error:C})},onclose:C=>{w||T(new Error("Gemini Live connection closed before setup completed")),y({type:"end"})}},config:{responseModalities:["AUDIO"],speechConfig:{voiceConfig:{prebuiltVoiceConfig:{voiceName:"Orus"}}}}}),A=await Promise.race([k,S]);u=A,w=!0,c&&g();const x=e.abortSignal;if(x&&!c){const C=()=>{y({type:"error",error:x.reason instanceof Error?x.reason:new DOMException("The operation was aborted","AbortError")})};x.addEventListener("abort",C,{once:!0}),m=()=>x.removeEventListener("abort",C),x.aborted&&C()}(async()=>{try{if(c)return;const C=e.input?.audio;if(!C){h.debug("[GeminiLive] No audio spec found on input; skipping upstream send");return}const M=C.frames[Symbol.asyncIterator]();for(p=M;!c;){const O=await M.next();if(c)return;if(O.done){p=void 0;break}const U=O.value;if(!U||U.byteLength===0){try{A.sendInput?await A.sendInput({event:"flush"}):A.sendRealtimeInput&&await A.sendRealtimeInput({event:"flush"})}catch($){h.debug("[GeminiLive] flush control failed (non-fatal)",{error:$ instanceof Error?$.message:String($)})}continue}const D=U.toString("base64"),N=`audio/pcm;rate=${C.sampleRateHz||16e3}`;await A.sendRealtimeInput?.({media:{data:D,mimeType:N}})}if(c)return;try{A.sendInput?await A.sendInput({event:"flush"}):A.sendRealtimeInput&&await A.sendRealtimeInput({event:"flush"})}catch(O){h.debug("[GeminiLive] final flush failed (non-fatal)",{error:O instanceof Error?O.message:String(O)})}}catch(C){y({type:"error",error:C})}})().catch(()=>{});const R={[Symbol.asyncIterator](){return{async next(){for(;;){const C=i.shift();if(C?.type==="audio")return{value:{type:"audio",audio:C.audio},done:!1};if(C?.type==="end")return a=!0,{value:void 0,done:!0};if(C?.type==="error")throw a=!0,C.error instanceof Error?C.error:new Error(String(C.error));if(a)return{value:void 0,done:!0};await new Promise(M=>{s=M})}},async return(){return v(),{value:void 0,done:!0}}}}};return rw(R,v),{stream:R,provider:this.providerName,model:o,metadata:{startTime:t,streamId:`google-ai-audio-${Date.now()}`}}}getDefaultEmbeddingModel(){return process.env.GOOGLE_AI_EMBEDDING_MODEL||process.env.GOOGLE_EMBEDDING_MODEL||"gemini-embedding-001"}async embed(e,t){if(typeof e!="string"&&e.image)throw new Je(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating embedding",{provider:this.providerName,model:n,textLength:r.length});try{const o=this.getApiKey(),a=(await(await xT(o,this.getBaseURL())).models.embedContent({model:n,contents:[r]})).embeddings?.[0]?.values;if(!a||a.length===0)throw new Je("No embedding returned from Google AI",this.providerName);return h.debug("Embedding generated successfully",{provider:this.providerName,model:n,embeddingDimension:a.length}),a}catch(o){throw h.error("Embedding generation failed",{error:o instanceof Error?o.message:String(o),model:n,textLength:r.length}),this.handleProviderError(o)}}async embedMany(e,t){const r=t||this.getDefaultEmbeddingModel()||"gemini-embedding-001";h.debug("Generating batch embeddings",{provider:this.providerName,model:r,count:e.length});let n;try{const i=this.getApiKey(),s=await xT(i,this.getBaseURL());if(n=[],r.includes("gemini-embedding-2"))for(let l=0;l<e.length;l+=8){const c=e.slice(l,l+8),u=await Promise.all(c.map(d=>s.models.embedContent({model:r,contents:[d]})));for(const d of u)n.push(d.embeddings?.[0]?.values)}else{const a=await s.models.embedContent({model:r,contents:e});n.push(...(a.embeddings||[]).map(l=>l.values))}if(n.length!==e.length)throw new Error(`Embedding response held ${n.length} vectors for ${e.length} texts`)}catch(i){throw h.error("Batch embedding generation failed",{error:i instanceof Error?i.message:String(i),model:r,count:e.length}),this.handleProviderError(i)}const o=n.map((i,s)=>{if(!i||i.length===0)throw h.error("Batch embedding returned no values",{model:r,index:s}),new Je(`Embedding for the text at index ${s} came back without values`,this.providerName);return i});return h.debug("Batch embeddings generated successfully",{provider:this.providerName,model:r,count:o.length,embeddingDimension:o[0]?.length}),o}getApiKey(){const e=this.credentials?.apiKey||process.env.GOOGLE_AI_API_KEY||process.env.GOOGLE_GENERATIVE_AI_API_KEY;if(!e)throw new Qr("GOOGLE_AI_API_KEY or GOOGLE_GENERATIVE_AI_API_KEY environment variable is not set",this.providerName);return e}getBaseURL(){const e=this.credentials?.baseURL?.trim()||process.env.GOOGLE_AI_BASE_URL?.trim();return e&&e.length>0?e:void 0}}}}),Icr={};ie(Icr,{GoogleAIStudioProvider:()=>Ccr});var Zhn=E({"src/lib/providers/googleAiStudio/index.ts"(){"use strict";Yhn()}});function Qhn(e){const t=e?.error?.message;if(typeof t=="string"&&t.trim().length>0)return t;if(Array.isArray(t)){const r=t.map(n=>n.msg?.trim()).filter(n=>n!==void 0&&n.length>0);if(r.length>0)return r.join("; ")}return typeof e?.detail=="string"&&e.detail.trim().length>0?e.detail:void 0}var Wa,yue,n$,vue,fu,pC,wue,bue,Rcr,Tue,_ue,Mcr,Pcr,Eue,Sue,Ocr,Dcr,AT,mC,Ncr,o$,kue,Lcr,Fcr,xue,$cr,Aue,Cue,hC,Iue,Ucr,zh=E({"src/lib/providers/openaiChatCompletionsClient.ts"(){"use strict";Lre(),DF(),Vc(),vs(),fi(),Wa=e=>e.replace(/\/+$/,""),yue=/^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/,n$=(e,t)=>{if(e.every(o=>yue.test(o)&&!t?.has(o)))return;const r=new Map,n=new Map;for(const o of e){let i=yue.test(o)?o:bce(o);if(n.has(i)||t?.has(i)){let s=2,a;do{const l=`_${s}`;a=`${i.slice(0,64-l.length)}${l}`,s++}while(n.has(a)||t?.has(a));i=a}r.set(o,i),n.set(i,o)}return{toWire:r,fromWire:n}},vue=(e,t,r)=>{let n=0;for(const o of e){if(Array.isArray(o.content)){for(const a of o.content)n+=a.type==="image_url"?qx:Ht(a.text,r);n+=bl}else{const a=typeof o.content=="string"?o.content:fu(o.content);n+=Ht(a,r)+bl}const i=o.tool_calls;i&&(n+=Ht(fu(i),r));const s=o.reasoning_content;s&&(n+=Ht(s,r))}return t&&t.length>0&&(n+=Ht(fu(t),r)),n},fu=e=>{try{return JSON.stringify(e??"")}catch{return String(e??"")}},pC=e=>{if(typeof e=="string")return e;try{return JSON.stringify(e??{})}catch{return"{}"}},wue=e=>{if(e==null)return"";if(typeof e=="string")return e;if(typeof e!="object")return String(e);const t=e;switch(t.type){case"text":return typeof t.value=="string"?t.value:fu(t.value);case"json":return fu(t.value);case"execution-denied":return`Tool execution denied${t.reason?`: ${t.reason}`:""}`;case"error-text":return typeof t.value=="string"?t.value:fu(t.value);case"error-json":return fu(t.value);case"content":return Array.isArray(t.value)?t.value.map(r=>r&&typeof r=="object"&&r.type==="text"?String(r.text??""):"").filter(r=>r.length>0).join(`
|
|
@@ -2303,10 +2303,14 @@ export class CLICommandFactory {
|
|
|
2303
2303
|
}
|
|
2304
2304
|
// Use SDK's provider diagnostic method instead of manual testing
|
|
2305
2305
|
const results = await sdk.getProviderStatus({ quiet: !!argv.quiet });
|
|
2306
|
+
// A configured provider whose live check the SDK skips comes back as
|
|
2307
|
+
// "not-configured" with configured: true. It is neither working nor
|
|
2308
|
+
// unconfigured, so it is shown as skipped and left out of the count.
|
|
2309
|
+
const isSkipped = (r) => r.configured && r.status === "not-configured";
|
|
2306
2310
|
if (spinner) {
|
|
2307
2311
|
const working = results.filter((r) => r.status === "working").length;
|
|
2308
|
-
const
|
|
2309
|
-
spinner.succeed(`Provider check complete: ${working}/${
|
|
2312
|
+
const checked = results.filter((r) => r.configured && !isSkipped(r)).length;
|
|
2313
|
+
spinner.succeed(`Provider check complete: ${working}/${checked} providers working`);
|
|
2310
2314
|
}
|
|
2311
2315
|
// Display results
|
|
2312
2316
|
for (const result of results) {
|
|
@@ -2314,11 +2318,16 @@ export class CLICommandFactory {
|
|
|
2314
2318
|
? chalk.green("✅ Working")
|
|
2315
2319
|
: result.status === "failed"
|
|
2316
2320
|
? chalk.red("❌ Failed")
|
|
2317
|
-
:
|
|
2321
|
+
: isSkipped(result)
|
|
2322
|
+
? chalk.gray("⏭ Skipped")
|
|
2323
|
+
: chalk.gray("⚪ Not configured");
|
|
2318
2324
|
const time = result.responseTime ? ` (${result.responseTime}ms)` : "";
|
|
2319
2325
|
const model = result.model ? ` [${result.model}]` : "";
|
|
2320
2326
|
logger.always(`${result.provider}: ${status}${time}${model}`);
|
|
2321
|
-
if (
|
|
2327
|
+
if (isSkipped(result) && result.error) {
|
|
2328
|
+
logger.always(` ${chalk.gray(result.error)}`);
|
|
2329
|
+
}
|
|
2330
|
+
else if (argv.verbose && result.error) {
|
|
2322
2331
|
logger.always(` Error: ${chalk.red(result.error)}`);
|
|
2323
2332
|
}
|
|
2324
2333
|
}
|
package/dist/neurolink.d.ts
CHANGED
|
@@ -1845,6 +1845,10 @@ export declare class NeuroLink {
|
|
|
1845
1845
|
/**
|
|
1846
1846
|
* Get comprehensive status of all AI providers
|
|
1847
1847
|
* Primary method for provider health checking and diagnostics
|
|
1848
|
+
*
|
|
1849
|
+
* Bedrock and SageMaker are never called live: their entries come back as
|
|
1850
|
+
* `status: "not-configured"` with `configured: true` and the reason in
|
|
1851
|
+
* `error`. Use `testProvider()` to check either one explicitly.
|
|
1848
1852
|
*/
|
|
1849
1853
|
getProviderStatus(options?: {
|
|
1850
1854
|
quiet?: boolean;
|
package/dist/neurolink.js
CHANGED
|
@@ -11870,6 +11870,10 @@ Current user's request: ${currentInput}`;
|
|
|
11870
11870
|
/**
|
|
11871
11871
|
* Get comprehensive status of all AI providers
|
|
11872
11872
|
* Primary method for provider health checking and diagnostics
|
|
11873
|
+
*
|
|
11874
|
+
* Bedrock and SageMaker are never called live: their entries come back as
|
|
11875
|
+
* `status: "not-configured"` with `configured: true` and the reason in
|
|
11876
|
+
* `error`. Use `testProvider()` to check either one explicitly.
|
|
11873
11877
|
*/
|
|
11874
11878
|
async getProviderStatus(options) {
|
|
11875
11879
|
// Track memory and timing for provider status checks
|
|
@@ -11912,6 +11916,19 @@ Current user's request: ${currentInput}`;
|
|
|
11912
11916
|
responseTime: Date.now() - startTime,
|
|
11913
11917
|
};
|
|
11914
11918
|
}
|
|
11919
|
+
// These probes are billable generate() calls signed with ambient AWS
|
|
11920
|
+
// credentials, against models the account may not be allowed to
|
|
11921
|
+
// call, so they are never made here.
|
|
11922
|
+
if (providerName === "bedrock" || providerName === "sagemaker") {
|
|
11923
|
+
return {
|
|
11924
|
+
provider: providerName,
|
|
11925
|
+
status: "not-configured",
|
|
11926
|
+
configured: true,
|
|
11927
|
+
authenticated: false,
|
|
11928
|
+
error: `Live status check is skipped for ${providerName}`,
|
|
11929
|
+
responseTime: Date.now() - startTime,
|
|
11930
|
+
};
|
|
11931
|
+
}
|
|
11915
11932
|
// Special handling for Ollama
|
|
11916
11933
|
if (providerName === "ollama") {
|
|
11917
11934
|
let ollamaAttempt;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "13.1.
|
|
3
|
+
"version": "13.1.1",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
|
|
6
6
|
"author": {
|