@juspay/neurolink 9.87.0 → 9.87.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 +6 -0
- package/dist/browser/neurolink.min.js +1 -1
- package/dist/lib/utils/safeFetch.js +11 -1
- package/dist/utils/safeFetch.js +11 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
## [9.87.1](https://github.com/juspay/neurolink/compare/v9.87.0...v9.87.1) (2026-07-14)
|
|
2
|
+
|
|
3
|
+
### Bug Fixes
|
|
4
|
+
|
|
5
|
+
- **(utils):** safeFetch pinned-agent lookup honors options.all (autoSelectFamily) ([a18af4a](https://github.com/juspay/neurolink/commit/a18af4a688a90c7f085dd878235b6d7ee4a573e5))
|
|
6
|
+
|
|
1
7
|
## [9.87.0](https://github.com/juspay/neurolink/compare/v9.86.5...v9.87.0) (2026-07-14)
|
|
2
8
|
|
|
3
9
|
### Features
|
|
@@ -2203,7 +2203,7 @@ IMPORTANT: You are a general-purpose AI assistant. Answer all requests directly
|
|
|
2203
2203
|
|
|
2204
2204
|
${A}`:d.text}}catch(k){if(!(e.input.text||""))throw k;g.warn(`[NeuroLink] Stream STT transcription failed, falling back to text: ${k instanceof Error?k.message:String(k)}`)}}let p=e.input?.text??"";e.fileRegistry=this.fileRegistry,await this.validateStreamRequestOptions(e,s),o4(t,e.context,n);let f=await this.maybeHandleWorkflowStreamRequest({options:e,startTime:s,streamSpan:t,spanStartTime:o});if(f)return f;let h=Tt.setSpan(wr.active(),t);await wr.with(h,()=>this.setLangfuseContextFromOptions(e,()=>this.applyToolRoutingExclusions(e,p))),await this.applyClassifierRouting(e,p,!e.disableTools&&(!!(e.tools&&Object.keys(e.tools).length>0)||this.getCustomTools().size>0),!!(e.input?.images&&e.input.images.length>0),e.thinking?.thinkingLevel),await this.applyRequestRouter(e,p,!e.disableTools&&(!!(e.tools&&Object.keys(e.tools).length>0)||this.getCustomTools().size>0),!!(e.input?.images&&e.input.images.length>0),e.thinking?.thinkingLevel);let y=e.tts,x=!!(y?.enabled&&y?.useAiResponse),b,T=x?new Promise(k=>{b=k}):void 0,w=await wr.with(h,()=>this.setLangfuseContextFromOptions(e,()=>this.runStandardStreamRequest({options:e,streamSpan:t,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:p,ttsResolver:b})));return d&&(w.transcription=d),T&&(w.audio=T),w}catch(s){throw t.setStatus({code:Ie.ERROR,message:s instanceof Error?s.message:String(s)}),s instanceof Error&&t.recordException(s),t.end(),s}}async applyToolRoutingExclusions(e,t){let n=this.toolRoutingConfig;if(!n?.enabled||e.disableTools)return;let o=n.servers??[];if(o.length!==0)try{let s=Array.from(this.getCustomTools().keys()),i=Zce(o,s);if(i.length===0)return;let a=await this.fetchRecentRoutingHistory(e),c=a.length>0?Qce(a,t):t,l=n.cache,u=l?.enabled===!0,d=n.stickiness?.enabled===!0;(u||d)&&!this.toolRoutingCacheInstance&&(this.toolRoutingCacheInstance=new IN({ttlMs:l?.ttlMs,maxEntries:l?.maxEntries,stickyTurns:n.stickiness?.turns}));let p=this.toolRoutingCacheInstance,f=e.context,h=typeof f?.sessionId=="string"?f.sessionId:"",y=u&&h?`${h}:${c}`:void 0,x=i.filter(P=>!(n.alwaysIncludeServerIds??[]).includes(P.id)).length,b=Date.now(),T=P=>{try{let R=Tt.getActiveSpan();if(!R)return;R.setAttribute("tool_routing.outcome",P.outcome),R.setAttribute("tool_routing.routable_server_count",P.routableServerCount),R.setAttribute("tool_routing.selected_server_ids",Do(P.selectedServerIds)),R.setAttribute("tool_routing.excluded_server_ids",Do(P.excludedServerIds)),R.setAttribute("tool_routing.hallucinated_ids",Do(P.hallucinatedIds)),R.setAttribute("tool_routing.excluded_tool_count",P.excludedToolCount),R.setAttribute("tool_routing.cache_hit",P.cacheHit),R.setAttribute("tool_routing.duration_ms",P.durationMs),P.embeddingActivated!==void 0&&R.setAttribute("tool_routing.embedding_activated",P.embeddingActivated),P.candidateToolCount!==void 0&&R.setAttribute("tool_routing.candidate_tool_count",P.candidateToolCount),P.granularity!==void 0&&R.setAttribute("tool_routing.granularity",P.granularity)}catch{}};if(u&&p&&y!==void 0){let P=p.get(y);if(P){let R=P.excludedToolNames;if(d&&h)try{let O=p.getStickyServerIds(h);O.length>0&&(R=R.filter(F=>!O.some(D=>F.startsWith(`${D}_`))))}catch{}let I=new Set(P.selectedServerIds),M=i.map(O=>O.id).filter(O=>!I.has(O));T({outcome:"cache-hit",selectedServerIds:P.selectedServerIds,excludedServerIds:M,hallucinatedIds:[],excludedToolCount:R.length,routableServerCount:x,cacheHit:!0,durationMs:Date.now()-b}),g.debug("[ToolRouting] Cache hit, skipping router LLM",{hasSessionId:!!h,routingQueryLength:c.length}),R.length>0&&(e.excludeTools=[...e.excludeTools??[],...R]);return}}let w=this._disableToolCacheForCurrentRequest,k,C;try{let P=M=>{C=M,T(M)},R,I=n.embedding;if(I?.enabled===!0)try{let M=I.provider??(e.provider&&e.provider!=="auto"?e.provider:void 0)??n.routerModel?.provider;if(M){let O=await dn.createProvider(M,I.model,!0,this,void 0,this.resolveCredentials(e.credentials));R=F=>Ke(O.embedMany(F,I.model),I.timeoutMs??1e4),this.toolRoutingVectorCache||(this.toolRoutingVectorCache=new Map)}}catch(M){g.debug("[ToolRouting] Embedding provider setup failed, L2 path disabled for this turn",{error:M instanceof Error?M.message:String(M)})}k=await ele({catalog:i,alwaysIncludeServerIds:n.alwaysIncludeServerIds??[],userQuery:c,routerPromptPrefix:n.routerPromptPrefix,routerModel:{provider:n.routerModel?.provider??e.provider,model:n.routerModel?.model??e.model,region:n.routerModel?.region??e.region,temperature:n.routerModel?.temperature},timeoutMs:n.timeoutMs??MX,generateFn:M=>this.generate({...M,abortSignal:e.abortSignal}),emitDecision:P,embedFn:R,embeddingConfig:I,granularity:n.granularity??"server",embeddingVectorCache:R!==void 0?this.toolRoutingVectorCache:void 0})}finally{this._disableToolCacheForCurrentRequest=w}if(e.abortSignal?.aborted)return;let A=k;if(d&&p&&h)try{let P=p.getStickyServerIds(h);if(P.length>0){let R=P.map(I=>`${I}_`);k=k.filter(I=>!R.some(M=>I.startsWith(M)))}}catch{}if(C?.outcome==="applied"&&p){if(u&&y!==void 0)try{p.set(y,{excludedToolNames:A,selectedServerIds:C.selectedServerIds})}catch{}if(d&&h)try{p.recordSelection(h,C.selectedServerIds)}catch{}}k.length>0&&(e.excludeTools=[...e.excludeTools??[],...k])}catch(s){if(Hr(s))throw s;g.warn("[ToolRouting] Routing setup failed, failing open",{error:s instanceof Error?s.message:String(s)})}}async fetchRecentRoutingHistory(e){try{let t=e.context;if(e.conversationMessages&&e.conversationMessages.length>0)return e.conversationMessages;let n=t?.sessionId;if(typeof n!="string"||!n)return[];await this.initializeConversationMemoryForGeneration(`tool-routing-${Date.now()}`,Date.now(),process.hrtime.bigint());let o=this.conversationMemory;if(!o)return[];let s=await Og(o,{...e,enableSummarization:!1});return g.debug("[ToolRouting] Loaded conversation history for router",{sessionId:n,messageCount:s.length}),s}catch(t){return g.debug("[ToolRouting] Failed to load conversation history; routing on current query only",{error:t instanceof Error?t.message:String(t)}),[]}}setToolRoutingServers(e){if(!this.toolRoutingConfig){g.warn("[ToolRouting] setToolRoutingServers called without toolRouting constructor config \u2014 servers stored but routing stays disabled"),this.toolRoutingConfig={enabled:!1,servers:e};return}this.toolRoutingConfig.servers=e,this.toolRoutingVectorCache=void 0,this.toolRoutingCacheInstance=void 0}async validateStreamRequestOptions(e,t){if(await this.validateStreamInput(e),e.inputValidation&&e.input?.text){let n=e.inputValidation;if(n.trimWhitespace&&(e.input.text=e.input.text.trim()),n.requireContent&&!e.input.text.trim())throw new Error("Input content is required but was empty or whitespace");if(n.minLength&&e.input.text.length<n.minLength)throw new Error(`Input text is too short (${e.input.text.length} < ${n.minLength})`);if(n.maxLength&&e.input.text.length>n.maxLength)throw new Error(`Input text is too long (${e.input.text.length} > ${n.maxLength})`)}if(e.piiDetection?.enabled&&e.input?.text){let n=await tW(e.input.text,{enabled:!0,action:e.piiDetection.action??"warn",detectTypes:e.piiDetection.detectTypes,customPatterns:e.piiDetection.customPatterns,allowList:e.piiDetection.allowList,redactionText:e.piiDetection.redactionText});if(n.action==="abort")throw new Error(n.feedback??"Request blocked: PII detected in input");e.input.text=n.text}this.enforceSessionBudget(e.maxBudgetUsd),await this.applyAuthenticatedRequestContext(e),this.emitStreamStartEvents(e,t),this.applyStreamLifecycleMiddleware(e)}async maybeHandleWorkflowStreamRequest(e){if(!e.options.workflow&&!e.options.workflowConfig)return null;let t=await this.streamWithWorkflow(e.options,e.startTime),n=t.stream,o=this;return t.stream=(async function*(){try{for await(let s of n)yield s;e.streamSpan.setStatus({code:Ie.OK})}catch(s){throw e.streamSpan.setStatus({code:Ie.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o._disableToolCacheForCurrentRequest=!1,e.streamSpan.setAttribute("neurolink.response_time_ms",Date.now()-e.spanStartTime),e.streamSpan.end()}})(),t}async runStandardStreamRequest(e){let{options:t,streamSpan:n,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:c,ttsResolver:l}=e;g.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:t.provider,model:t.model,inputLength:t.input?.text?.length||0,disableTools:t.disableTools,enableAnalytics:t.enableAnalytics,enableEvaluation:t.enableEvaluation,contextKeys:t.context?Object.keys(t.context):[],optionKeys:Object.keys(t),sessionId:t.context?.sessionId});try{let{enhancedOptions:u,factoryResult:d}=await this.prepareStreamOptions(t,a,s,i);g.debug("[NeuroLink] Stream options prepared",{streamId:a,options:u,factoryResult:d,sessionId:u.context?.sessionId});let{stream:p,provider:f,usage:h,model:y,finishReason:x,toolCalls:b,toolResults:T,analytics:w,metadata:k}=await this.createMCPStream(u),C={finishReason:x??"stop",toolCalls:b,toolResults:T};n.setAttribute(Se.NL_PROVIDER,f||"unknown");let A="",P=0,{eventSequence:R,cleanup:I}=this.setupStreamEventListeners(),M={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},O=this,F=Date.now(),D=u.context?.sessionId,j={providerEmitted:!1};u._streamDedupContext=j;let $=(async function*(){let V,B,K=0;try{for await(let q of p){P++;let pe=q!==null&&typeof q=="object"&&"metadata"in q&&q.metadata?.noOutput===!0,De=q&&"content"in q&&typeof q.content=="string"&&q.content.length>0,ne=q!==null&&typeof q=="object"&&"type"in q&&(q.type==="audio"||q.type==="tts_audio"||q.type==="image");!pe&&(De||ne)&&K++,q&&"content"in q&&typeof q.content=="string"&&(A+=q.content,O.emitter.emit("response:chunk",q.content),O.emitter.emit("stream:chunk",{type:"stream:chunk",content:q.content,metadata:{chunkIndex:P,totalLength:A.length,...pe&&{noOutput:!0}},timestamp:Date.now()})),yield q}K===0&&!M.fallbackAttempted&&!u.disableInternalFallback&&C.toolCalls.length===0&&C.toolResults.length===0&&(yield*O.handleStreamFallback(M,C,c,u,f,q=>{A+=q}));let te=await O.synthesizeStreamModeTwo({ttsOptions:u.tts,providerName:f,fallbackProvider:u.provider,accumulatedContent:A,ttsResolver:l});if(te.audioChunk&&(yield te.audioChunk),B=h,!B&&w)try{let q=await Promise.resolve(w);q?.tokenUsage&&(B=q.tokenUsage)}catch{}O.emitter.emit("stream:complete",{type:"stream:complete",content:A,provider:M.fallbackProvider??f,model:M.fallbackModel??y??u.model,finishReason:C.finishReason??"stop",prompt:u.input?.text||u.prompt,metadata:{chunkCount:P,totalLength:A.length,durationMs:Date.now()-F,sessionId:D,usage:B,finishReason:C.finishReason??"stop",...M.fallbackAttempted&&{primaryProvider:f,primaryModel:u.model,fallback:!0}},timestamp:Date.now()})}catch(te){throw g.debug("[NeuroLink.stream] Stream error occurred",{error:te instanceof Error?te.message:String(te),name:te instanceof Error?te.name:"UnknownError",provider:f,model:u.model,chunkCount:P,totalLength:A.length,durationMs:Date.now()-F,sessionId:D}),V=te,O.emitter.emit("stream:error",{type:"stream:error",content:te instanceof Error?te.message:String(te),provider:f,model:u.model,metadata:{chunkCount:P,totalLength:A.length,durationMs:Date.now()-F,errorName:te instanceof Error?te.name:"UnknownError",sessionId:D},timestamp:Date.now()}),te}finally{if(l?.(void 0),g.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:f,model:u.model,totalChunks:P,totalLength:A.length,durationMs:Date.now()-F,fallbackAttempted:M.fallbackAttempted,guardrailsBlocked:M.guardrailsBlocked,error:M.error}),!j.providerEmitted)try{let q=M.fallbackProvider??f??"unknown",pe=M.fallbackModel??y??u.model??"unknown",De=V?"error":C.finishReason??"stop";O.emitter.emit("generation:end",{provider:q,model:pe,responseTime:Date.now()-F,toolsUsed:C.toolCalls?.map(ne=>ne.toolName),timestamp:Date.now(),result:{content:A,usage:B,model:pe,provider:q,finishReason:De},prompt:u.input?.text||u.prompt,temperature:u.temperature,maxTokens:u.maxTokens,success:!V,error:V?V instanceof Error?V.message:String(V):void 0,pipelineAHandled:!0})}catch(q){g.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:q instanceof Error?q.message:String(q)})}O._disableToolCacheForCurrentRequest=!1,I(),n.setAttribute("neurolink.response_time_ms",Date.now()-o),n.setAttribute(Se.NL_OUTPUT_LENGTH,A.length);let te=!!(M.error||V);n.setAttribute(Se.GEN_AI_FINISH_REASON,te?"error":"stop"),M.fallbackAttempted&&(n.setAttribute("neurolink.fallback_triggered",!0),M.fallbackProvider&&n.setAttribute("neurolink.fallback_provider",M.fallbackProvider)),te?n.setStatus({code:Ie.ERROR,message:M.error||(V instanceof Error?V.message:String(V))}):n.setStatus({code:Ie.OK}),n.end(),A.trim()&&g.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:f,model:u.model,responseTimeMs:Date.now()-s,contentLength:A.length,fallback:M.fallbackAttempted}),await O.storeStreamConversationMemory({enhancedOptions:u,providerName:f,originalPrompt:c,accumulatedContent:A,startTime:s,eventSequence:R})}})(),U=await this.processStreamResult($,u,d);return U.finishReason=C.finishReason||U.finishReason,U.toolCalls=C.toolCalls,U.toolResults=C.toolResults,U.usage||(U.usage=h),U.analytics||(U.analytics=w),Promise.resolve(U.analytics).then(V=>{V?.cost&&V.cost>0&&(this._sessionCostUsd+=V.cost)}).catch(()=>{}),this.emitStreamEndEvents(U),this.createStreamResponse(U,$,{providerName:f,options:t,startTime:s,responseTime:Date.now()-s,streamId:a,fallback:M.fallbackAttempted,guardrailsBlocked:M.guardrailsBlocked,error:M.error,events:R,providerMetadata:k})}catch(u){if(t.disableInternalFallback)throw u;return this.handleStreamError(u,t,s,a,void 0,void 0)}}async synthesizeStreamModeTwo(e){let{ttsOptions:t,providerName:n,fallbackProvider:o,accumulatedContent:s,ttsResolver:i}=e;if(!t?.enabled||!t.useAiResponse||s.trim().length===0)return i?.(void 0),{};try{let{TTSProcessor:a}=await Promise.resolve().then(()=>(ha(),py)),c=t.provider??o??n,l=c&&a.supports(c)?c:void 0;if(!l)throw new Error(`No TTS provider resolved for stream Mode 2 (set tts.provider explicitly \u2014 chat provider "${c??"<unset>"}" is not a registered TTS handler)`);let u=await a.synthesize(s,l,t);return i?.(u),{audioChunk:{type:"tts_audio",audio:{data:u.buffer,format:u.format,index:0,isFinal:!0,cumulativeSize:u.size,voice:u.voice,sampleRate:u.sampleRate}}}}catch(a){return g.warn(`[NeuroLink.stream] Stream TTS Mode 2 synthesis failed: ${a instanceof Error?a.message:String(a)}`),i?.(void 0),{}}}async prepareStreamOptions(e,t,n,o){if(await this.initializeConversationMemoryForGeneration(t,n,o),await this.initializeMCP(),this.shouldReadMemory(e.memory,e.context?.userId)&&e.context?.userId)try{e.input.text=await this.retrieveMemory(e.input.text??"",e.context.userId,e.memory?.additionalUsers),g.debug("Memory retrieval successful")}catch(a){g.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(e),this.enableOrchestration&&!e.provider&&!e.model)try{let a=await this.applyStreamOrchestration(e);g.debug("Stream orchestration applied",{originalProvider:e.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:e.input.text?.substring(0,100)}),e={...e,...a},a.model&&(e.model=Qk(e.model,this.modelAliasConfig))}catch(a){g.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:e.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(e),e.rag?.files?.length)try{let{prepareRAGTool:a}=await Promise.resolve().then(()=>(pW(),zpe)),c=await a(e.rag,e.provider);e.tools||(e.tools={}),e.tools[c.toolName]=c.tool;let l=[`
|
|
2205
2205
|
|
|
2206
|
-
IMPORTANT: You have a tool called "${c.toolName}" that searches through`,`${c.filesLoaded} loaded document(s) containing ${c.chunksIndexed} indexed chunks.`,`ALWAYS use the "${c.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(" ");e.systemPrompt=(e.systemPrompt||"")+l,g.info("[RAG] Tool injected into stream()",{toolName:c.toolName,filesLoaded:c.filesLoaded,chunksIndexed:c.chunksIndexed})}catch(a){g.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}let s=U3e(e),i=F3e(e);if(e.input?.text){let{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(e.input.text,void 0);c!==e.input.text&&(i.input.text=c)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(e){if((e.provider==="ollama"||e.provider?.toLowerCase().includes("ollama"))&&!e.disableTools){let{ModelConfigurationManager:t}=await Promise.resolve().then(()=>(Xy(),fUe)),s=t.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=e.model;s.length>0&&i&&(s.some(c=>i.toLowerCase().includes(c.toLowerCase()))||(e.disableTools=!0,g.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:e.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){let e=[],t=0,n=(d,p)=>{e.push({type:d,seq:t++,timestamp:Date.now(),...p&&typeof p=="object"?p:{data:p}})},o=(...d)=>{let p=d[0];n("response:chunk",{content:p})},s=(...d)=>{let p=d[0];n("tool:start",{...p,toolName:p.toolName??p.tool})},i=(...d)=>{let p=d[0],f=p.toolName??p.tool,h=p.responseTime??p.duration,y=p.success??(p.error!==void 0?!1:void 0),x={...p,toolName:f,...h!==void 0?{responseTime:h}:{},...y!==void 0?{success:y}:{},...p.error!==void 0?{error:p.error}:{}};n("tool:end",x),x.result&&x.result.uiComponent===!0&&n("ui-component",{toolName:f,componentData:x.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...h!==void 0?{responseTime:h}:{}})},a=(...d)=>{n("ui-component",d[0])},c=(...d)=>{n("hitl:confirmation-request",d[0])},l=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",c),this.emitter.on("hitl:confirmation-response",l),{eventSequence:e,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",c),this.emitter.off("hitl:confirmation-response",l)}}}async*handleStreamFallback(e,t,n,o,s,i){e.fallbackAttempted=!0;let a="Stream completed with 0 chunks (possible guardrails block)";e.error=a;try{let h=this._metricsTraceContext,y=xe.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:h?.traceId,parentSpanId:h?.parentSpanId});y=xe.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),Ze().recordSpan(y)}catch{}let c=o.fallbackProvider?.trim()||void 0,l=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,p=tC.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),f={...p,provider:c??u??p.provider,model:l??d??p.model};g.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:f.provider,fallbackModel:f.model,fallbackSource:c||l?"options":u||d?"env":"model_config",reason:a});try{let h=await dn.createProvider(f.provider,f.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));h.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,A)=>this.executeTool(C,A,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");let y=o.conversationMessages!==void 0?o.conversationMessages:await Og(this.conversationMemory,{prompt:o.input.text,context:o.context}),x=await h.stream({...o,model:f.model,conversationMessages:y}),b=x.toolCalls??[],T=x.toolResults??[];(b.length>0||T.length>0)&&(t.toolCalls=b,t.toolResults=T,t.finishReason=x.finishReason??t.finishReason);let w=0,k=0;for await(let C of x.stream){w++;let A=C!==null&&typeof C=="object"&&"metadata"in C&&C.metadata?.noOutput===!0,P=C&&"content"in C&&typeof C.content=="string"&&C.content.length>0,R=C!==null&&typeof C=="object"&&"type"in C&&(C.type==="audio"||C.type==="tts_audio"||C.type==="image");!A&&(P||R)&&k++,C&&"content"in C&&typeof C.content=="string"&&(i(C.content),this.emitter.emit("response:chunk",C.content)),yield C}if(k===0&&b.length===0&&T.length===0)throw new Error(`Fallback provider ${f.provider} also returned 0 real output chunks (chunkCount=${w}, sentinel-only or empty)`);e.fallbackProvider=f.provider,e.fallbackModel=f.model,e.guardrailsBlocked=!0}catch(h){let y=h instanceof Error?h.message:String(h);throw e.error=`${a}; Fallback failed: ${y}`,g.error("Fallback provider failed",{fallbackProvider:f.provider,error:y}),h}}async storeStreamConversationMemory(e){let{enhancedOptions:t,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=e;g.shouldLog("debug")&&g.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:m0(f0(t)),sessionId:t.context?.sessionId});let c=a.some(l=>l.type==="tool:start"||l.type==="tool:end");if(!s.trim()&&!c){g.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:t.context?.sessionId});return}if(g.shouldLog("debug")&&g.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:m0(f0(t)),sessionId:t.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&t.context?.sessionId){let l=t.context?.sessionId,u=t.context?.userId,d;t.model&&(d={provider:n,model:t.model});let p=Date.now();try{let f=this.drainPendingSkillMessages(l);await this.conversationMemory.storeConversationTurn({sessionId:l,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:t.enableSummarization,events:a.length>0?a:void 0,requestId:t.context?.requestId,...f.length>0?{skillMessages:f}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,1),g.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:l,eventCount:a.length,eventTypes:[...new Set(a.map(h=>h.type))]})}catch(f){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,2,f instanceof Error?f.message:String(f)),g.warn("Failed to store stream conversation turn",{error:f instanceof Error?f.message:String(f)})}}this.shouldWriteMemory(t.memory,t.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),t.context?.userId,t.memory?.additionalUsers,t.context)}async validateStreamInput(e){let t=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:t.toString(),message:"Starting comprehensive input validation process"});let n=typeof e?.input?.text=="string"&&e.input.text.trim().length>0,o=!!(e?.input?.audio&&e.input.audio.frames&&typeof e.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(e?.stt?.enabled&&e?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(e,t){this.emitter.emit("stream:start",{provider:e.provider||"auto",timestamp:t}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${e.provider||"auto"} stream...`)}async createMCPStream(e){let t=await Nx(e.provider),n=await dn.createProvider(t,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(h,y)=>this.executeTool(h,y,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,e);let s=e.skipToolPromptInjection?e.systemPrompt||"":this.createToolAwareSystemPrompt(e.systemPrompt,o),i=e.conversationMessages!==void 0,a=i?e.conversationMessages:await Og(this.conversationMemory,{...e,prompt:e.input.text,context:e.context});e.conversationMessages=a;let c=a,l=Qc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o}),u=c?.length||0,d=this.getCompactionSessionId(e),p=u>0;if(!l.withinBudget&&!p){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:l.estimatedInputTokens,budget:l.availableInputTokens,provider:t,model:e.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new ql(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${l.estimatedInputTokens} tokens, budget: ${l.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:l.estimatedInputTokens,availableTokens:l.availableInputTokens,stagesUsed:[],breakdown:l.breakdown})}if(l.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){let y=await new bx({provider:t,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(c,l.availableInputTokens,this.conversationMemoryConfig?.conversationMemory,e.context?.requestId);y.compacted&&(c=xk(y.messages).messages,e.conversationMessages=c,this.lastCompactionMessageCount.set(d,c.length));let x=Qc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!x.withinBudget){g.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:x.estimatedInputTokens,availableTokens:x.availableInputTokens,overagePercent:Math.round((x.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:x.estimatedInputTokens,budget:x.availableInputTokens,provider:t,model:e.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=fH(c,x.availableInputTokens,x.breakdown,t),e.conversationMessages=c;let b=Qc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!b.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:b.estimatedInputTokens,budget:b.availableInputTokens,provider:t,model:e.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new ql(`Stream context exceeds model budget after all compaction stages. Estimated: ${b.estimatedInputTokens} tokens, Budget: ${b.availableInputTokens} tokens.`,{estimatedTokens:b.estimatedInputTokens,availableTokens:b.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:b.breakdown})}}}if(this.modelPool){let h=this.modelPool,y=h.maxAttempts,x=new Set,b=null;for(let T=0;T<y;T++){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let w=h.selectNext(x);if(!w)break;x.add(h.memberKey(w));let k=w.provider,C=w.model??void 0,A=w.region??void 0;g.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:C,attempt:T});try{let P=await dn.createProvider(k,C,!e.disableTools,this,A,this.resolveCredentials(e.credentials));P.setTraceContext(this._metricsTraceContext),P.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(O,F)=>this.executeTool(O,F,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let R=await P.stream({...e,provider:k,model:C,region:A,systemPrompt:s,conversationMessages:c});g.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});let I=w;return{stream:(async function*(){try{yield*R.stream,h.recordSuccess(I)}catch(O){throw h.recordFailure(I,Ux(O)),O}})(),provider:k,usage:R.usage,model:R.model||C,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics,metadata:R.metadata}}catch(P){if(Hr(P))throw P;if(DW(P)){let R=P instanceof Error?P.message:String(P);throw h.recordFailure(w,Ux(P)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:P})}h.recordFailure(w,Ux(P)),b=P instanceof Error?P:new Error(String(P)),g.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:b.message})}}throw new Error(`[ModelPool] all stream members failed: ${b?.message??"no stream members available"}`)}let f=await n.stream({...e,systemPrompt:s,conversationMessages:c});return g.debug("[createMCPStream] Stream created successfully",{provider:t,systemPromptPassedLength:s.length}),{stream:f.stream,provider:t,usage:f.usage,model:f.model||e.model,finishReason:f.finishReason,toolCalls:f.toolCalls??[],toolResults:f.toolResults??[],analytics:f.analytics,metadata:f.metadata}}async processStreamResult(e,t,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(e){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",e.content||"")}createStreamResponse(e,t,n){return{stream:t,provider:n.providerName,model:n.options.model,usage:e.usage,finishReason:e.finishReason,toolCalls:e.toolCalls,toolResults:e.toolResults,analytics:e.analytics,evaluation:e.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:Object.assign(n.providerMetadata??{},{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error})}}async handleStreamError(e,t,n,o,s,i){if(e instanceof ql)throw e;g.error("Stream generation failed, attempting fallback",{error:e instanceof Error?e.message:String(e)});try{this.emitter.emit("stream:error",{content:e instanceof Error?e.message:String(e),metadata:{errorName:e instanceof Error?e.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:t.provider||"unknown",model:t.model||"unknown"})}catch{}let a=t.input.text,c=Date.now()-n,l=await Nx(t.provider),d=await(await dn.createProvider(l,t.model,!0,void 0,void 0,this.resolveCredentials(t.credentials))).stream({input:{text:t.input.text},model:t.model,temperature:t.temperature,maxTokens:t.maxTokens,conversationMessages:t.conversationMessages}),p="";return{stream:(async function*(h){try{for await(let y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(p+=y.content,h.emitter.emit("response:chunk",y.content)),yield y}finally{if(p.trim()){g.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:t.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{h.emitter.emit("stream:complete",{content:p,provider:l,model:t.model||"unknown",finishReason:"stop",metadata:{durationMs:Date.now()-n,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}})}catch{}}if(h.conversationMemory&&s?.context?.sessionId&&p.trim()){let y=s?.context?.sessionId,x=s?.context?.userId,b;t.model&&(b={provider:l,model:t.model});let T=Date.now();try{let w=y||t.context?.sessionId,k=h.drainPendingSkillMessages(w);await h.conversationMemory.storeConversationTurn({sessionId:w,userId:x||t.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:b,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||t.context?.requestId,...k.length>0?{skillMessages:k}:{}}),h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,1)}catch(w){h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,2,w instanceof Error?w.message:String(w)),g.warn("Failed to store fallback stream conversation turn",{error:w instanceof Error?w.message:String(w)})}}}})(this),provider:l,model:t.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:c,fallback:!0}}}getEventEmitter(){return this.emitter}getToolDedupConfig(){return this.toolDedupConfig}async checkCredentials(e){let{provider:t,model:n}=e,o="ping";try{return await this.generate({provider:t,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:t,status:"ok",detail:"credentials valid"}}catch(s){let i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof um?{provider:t,status:"denied",detail:i}: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:t,status:"expired",detail:i}: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:t,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:t,status:"network",detail:i}:{provider:t,status:"unknown",detail:i}}}emitToolStart(e,t,n=Date.now()){let o=`${e}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:e,startTime:n,metadata:{inputType:typeof t,hasInput:t!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",Hf(e,{input:t,timestamp:n,executionId:o})),g.debug(`tool:start emitted for ${e}`,{toolName:e,executionId:o,timestamp:n,inputProvided:t!==void 0}),o}emitToolEnd(e,t,n,o,s=Date.now(),i){let a=o||s-1e3,c=s-a,l=!n,u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(f=>f.tool===e&&!f.endTime);let d=i||u?.executionId||`${e}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=t,u.error=n,this.activeToolExecutions.delete(u.executionId));let p={tool:e,startTime:a,endTime:s,duration:c,success:l,result:t,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",Hf(e,{result:t,error:n,success:l,responseTime:c,timestamp:s,duration:c,executionId:d})),g.debug(`tool:end emitted for ${e}`,{toolName:e,executionId:d,duration:c,success:l,hasResult:t!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(e,t,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:e,timestamp:Date.now()});try{if(!e||typeof e!="string")throw new Error("Invalid tool name");if(!t||typeof t!="object")throw new Error(`Invalid tool object provided for tool: ${e}`);if(typeof t.execute!="function")throw new Error(`Tool '${e}' must have an execute method.`);if(e.trim()==="")throw new Error("Tool name cannot be empty");if(e.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(e))throw new Error("Tool name contains invalid control characters");let o={name:t.name||e,description:t.description||e,execute:t.execute,inputSchema:"parameters"in t&&t.parameters&&(pP(t.parameters)||typeof t.parameters=="object")?t.parameters:t.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){let i=o.execute,a=n.timeout,c=e;o.execute=async(...l)=>{let u=AbortSignal.timeout(a),d=l[1],p=d?.abortSignal,f=p?AbortSignal.any([p,u]):u,h={...d,abortSignal:f};return Promise.race([i(l[0],h),new Promise((y,x)=>{f.addEventListener("abort",()=>{u.aborted?x(me.toolTimeout(c,a)):x(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}let s=Nqe(e,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),this.emitter.emit("tools-register:end",{toolName:e,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw g.error(`Failed to register tool ${e}:`,o),o}}setToolContext(e){this.toolExecutionContext={...e},g.debug("Tool execution context updated",{sessionId:e.sessionId,contextKeys:Object.keys(e),hasJuspayToken:!!e.juspayToken,hasShopId:!!e.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,g.debug("Tool execution context cleared")}registerTools(e){if(Array.isArray(e))for(let{name:t,tool:n}of e)this.registerTool(t,n);else for(let[t,n]of Object.entries(e))this.registerTool(t,n)}unregisterTool(e){this.invalidateToolCache();let t=`custom-tool-${e}`,n=this.toolRegistry.unregisterServer(t);return n&&g.info(`Unregistered custom tool: ${e}`),n}useToolMiddleware(e){return this.mcpToolMiddlewares.push(e),g.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(e,t,n){if(!this.conversationMemory)throw new Tc("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Tc("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ke(this.conversationMemory.updateAgenticLoopReport(e,n,t),5e3)}getCustomTools(){let e=this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0})),t=new Map;for(let o of e){let s=o.inputSchema||o.parameters;g.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:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),t.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(i,a)=>{let c=this.toolExecutionContext||{},l=a&&_r(a)?a:{},u={...c,...l,sessionId:l.sessionId||c.sessionId||`fallback-${Date.now()}`};return g.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(c),runtimeContextKeys:Object.keys(l),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=nle(this.fileRegistry));let n=this.cachedFileTools;for(let[o,s]of Object.entries(n))if(!t.has(o)){let i=s,a=i.inputSchema??i.parameters;t.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async c=>await s.execute(c,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return t}async addInMemoryMCPServer(e,t){this.invalidateToolCache();try{ie.debug(`[NeuroLink] Registering in-memory MCP server: ${e}`),t.tools||(t.tools=[]),await this.toolRegistry.registerServer(t),ie.info(`[NeuroLink] Successfully registered in-memory server: ${e}`,{category:t.metadata?.category,provider:t.metadata?.provider,version:t.metadata?.version})}catch(n){throw ie.error(`[NeuroLink] Failed to register in-memory server ${e}:`,n),n}}getInMemoryServers(){let e=this.getInMemoryServerInfos(),t=new Map;for(let n of e)t.set(n.id,n);return t}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(t=>Aa({existingCategory:t.metadata?.category,serverId:t.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(e,t={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(e,t);let o=this.createToolExecutionContext(e,t,n);return _e.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":e,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(e,t,n,o,s))}createToolExecutionContext(e,t,n){let o=this.externalServerManager.getAllTools().find(l=>l.name===e),s=o?"mcp":this.getCustomTools().has(e)?"custom":"external",i=t?jm(t):"",a=Date.now(),c=`${e}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:c,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(e,t,n,o,s){try{let i=await this.prepareToolExecutionState(e,t,n,o);return await this.runPreparedToolExecution(e,t,i,o,s)}catch(i){if(!(i instanceof Fe)){let a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:Ie.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(e,t,n,o){g.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:e,params:_r(t)?XB(t):t,hasExternalManager:!!this.externalServerManager}),g.debug("Tool execution detailed analysis",{toolName:e,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof t,isNull:t===null,isUndefined:t===void 0,isEmpty:t&&typeof t=="object"&&Object.keys(t).length===0,keys:t&&typeof t=="object"?Object.keys(t):"NOT_OBJECT",keysLength:t&&typeof t=="object"?Object.keys(t).length:0},isTargetTool:e==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",Hf(e,{timestamp:o.executionStartTime,input:t,executionId:o.executionId}));let s=this.toolRegistry.getToolInfo(e),i={timeout:n?.timeout??s?.tool?.timeoutMs??gl.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??Ko.DEFAULT,retryDelayMs:n?.retryDelayMs||Qn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(dC(),uC)),c=a.getMemoryUsageMB(),u=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${e}`,d=this.toolCircuitBreakers.get(u);d||(d=new mE(GI.FAILURE_THRESHOLD,j2),this.toolCircuitBreakers.set(u,d));let p=this.toolExecutionMetrics.get(e);return p||(p={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(e,p)),p.totalExecutions++,{finalOptions:i,startMemory:c,circuitBreaker:d,breakerKey:u,metrics:p}}async runPreparedToolExecution(e,t,n,o,s){let i=0;try{ie.debug(`[${o.functionTag}] Executing tool: ${e}`,{toolName:e,params:t,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});let a=await n.circuitBreaker.execute(async()=>$Z(async()=>Ke(this.executeToolInternal(e,t,n.finalOptions,o.hitlState),n.finalOptions.timeout,me.toolTimeout(e,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:eB,onRetry:(c,l)=>{i=c,ie.warn(`[${o.functionTag}] Retrying tool execution (attempt ${c})`,{toolName:e,error:l.message,attempt:c})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(e,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(e,t,a,n,o,s)}}async handleSuccessfulToolExecution(e,t,n,o,s){let i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;let{MemoryManager:a}=await Promise.resolve().then(()=>(dC(),uC)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&ie.warn(`Tool '${e}' used excessive memory: ${l}MB`,{toolName:e,memoryDelta:l,executionTime:i}),ie.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:e,executionTime:i,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});let u=t&&typeof t=="object"?t:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,p=d?u?.content:void 0,f=d?p?.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${e} returned isError:true`)})}catch{}ie.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:e,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});let h=WCr(f??"Unknown error"),y=`[TOOL_ERROR: ${e} failed (${h})] `;if(u&&Array.isArray(p)){let T=p.map(w=>({...w}));for(let w of T)if(w.type==="text"&&w.text){w.text=y+w.text;break}u.content=T}s.setAttribute("tool.error.message",(f??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",h),s.setStatus({code:Ie.ERROR,message:`MCP tool returned isError: ${(f??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;let x=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=x>1?(n.metrics.averageExecutionTime*x-i)/(x-1):0;let b=KCr(h);n.metrics.errorCategories[b]=(n.metrics.errorCategories[b]||0)+1}return this.emitToolEndEvent(e,o.executionStartTime,!d,t,d&&f?new Error(f):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),t}async handleFailedToolExecution(e,t,n,o,s,i){o.metrics.failedExecutions++;let a=Date.now()-s.executionStartTime;if(n instanceof bc)return ie.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${e}`,{toolName:e,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(e,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${e} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:Ie.ERROR,message:`Circuit breaker open for ${e}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" 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 c;if(n instanceof Fe)c=n;else if(n instanceof Error)if(n.message.includes("timeout"))c=me.toolTimeout(e,o.finalOptions.timeout);else if(n.message.includes("not found")){let u=await this.getAllAvailableTools();c=me.toolNotFound(e,APe(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?c=me.invalidParameters(e,n,t):n.message.includes("network")||n.message.includes("connection")?c=me.networkError(e,n):c=me.toolExecutionFailed(e,n);else c=me.toolExecutionFailed(e,new Error(String(n)));let l=c.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,c,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",c),c=new Fe({...c,context:{...c.context,executionTime:a,params:t,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),BZ(c),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(c),i.setStatus({code:Ie.ERROR,message:c.message}),c}async executeToolInternal(e,t,n,o){let s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(e),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,c=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:t,__ctx:n.authContext??this.toolExecutionContext}:t;if(a&&c){let p=c.getCachedResult(e,l);if(p!==void 0)return g.debug(`[${s}] Cache HIT for tool: ${e}`),p}let u=async p=>{if(this.mcpToolMiddlewares.length===0)return p();let f=0,h=async()=>{if(f<this.mcpToolMiddlewares.length){let y=this.mcpToolMiddlewares[f++];return y({name:e,description:"",inputSchema:{},annotations:i,execute:async()=>({})},t,{toolMeta:{name:e,annotations:i}},h)}return p()};return await h()},d=async()=>{let p=this.externalServerManager.getAllTools(),f=p.filter(y=>y.name===e&&y.isAvailable),h;if(f.length>1&&this.mcpToolRouter)try{let y={name:e,description:f[0].description??"",serverId:f[0].serverId,inputSchema:{}},x=this.mcpToolRouter.route(y);h=f.find(b=>b.serverId===x.serverId)||f[0],g.debug(`[${s}] Router selected server: ${x.serverId}`,{strategy:x.strategy,confidence:x.confidence})}catch(y){g.warn(`[${s}] Router failed, falling back to first match`,{error:y}),h=f[0]}else h=f[0];if(g.debug(`[${s}] External MCP tool search:`,{toolName:e,externalToolsCount:p.length,foundTool:!!h,isAvailable:h?.isAvailable,serverId:h?.serverId}),h&&h.isAvailable)try{ie.debug(`[${s}] Executing external MCP tool: ${e} from ${h.serverId}`);let y=await this.externalServerManager.executeTool(h.serverId,e,t,{timeout:n.timeout});return g.debug(`[${s}] External MCP tool execution successful:`,{toolName:e,serverId:h.serverId,resultType:typeof y}),y}catch(y){throw g.error(`[${s}] External MCP tool execution failed:`,{toolName:e,serverId:h.serverId,error:y instanceof Error?y.message:String(y)}),me.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)),h.serverId)}try{let y=this.toolExecutionContext||{},x=n.authContext||{},b={...y,...x,hitlState:o};g.debug("[Using merged context for unified registry tool:",{toolName:e,storedContextKeys:Object.keys(y),finalContextKeys:Object.keys(b)});let T=await this.toolRegistry.executeTool(e,t,b);if(T&&typeof T=="object"&&"success"in T&&T.success===!1){let w=T.error||"Tool execution failed",k=new Error(w);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",k)}return T}catch(y){let x=y instanceof Error?y:new Error(String(y));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",x),y instanceof Error&&y.message.includes("not found")){let b=await this.getAllAvailableTools();throw me.toolNotFound(e,b.map(T=>T.name))}throw me.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)))}};try{let p=await u(d);return a&&c&&p!==void 0&&(c.cacheResult(e,l,p),g.debug(`[${s}] Cached result for tool: ${e}`)),p}catch(p){let f=i?{name:e,description:"",annotations:i,execute:async()=>({})}:void 0;if(f&&ON(f)&&p instanceof Error&&eB(p)){g.debug(`[${s}] Tool ${e} is safe to retry, attempting once more`);try{let h=await u(d);return a&&c&&h!==void 0&&c.cacheResult(e,l,h),h}catch{}}throw p}}getToolAnnotationsForExecution(e){if(this.toolCache?.tools){let t=this.toolCache.tools.find(n=>n.name===e);if(t?.annotations)return t.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Du({name:e,description:""})}invalidateToolCache(){this.toolCache=null,g.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return g.debug("Returning available tools from cache"),this.toolCache.tools;let e=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,t=Date.now(),n=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:e,timestamp:new Date().toISOString(),getAllToolsStartTime:t,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:!!dn,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});let{MemoryManager:o}=await Promise.resolve().then(()=>(dC(),uC)),s=o.getMemoryUsageMB();try{let i=new Map,a=await this.toolRegistry.listTools();for(let y of a)if(!i.has(y.name)){let x=mP(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,x)}let c=this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0}));for(let y of c)if(!i.has(y.name)){let x=mP(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:Aa({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let l=this.toolRegistry.getToolsByCategory("in-memory");for(let y of l)if(!i.has(y.name)){let x=mP(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,x)}let u=this.externalServerManager.getAllTools();for(let y of u)if(!i.has(y.name)){let x=mP(y,{category:Aa({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let d=Array.from(i.values());ie.debug("Tool discovery results",{mcpTools:a.length,customTools:c.length,inMemoryTools:l.length,externalMCPTools:u.length,total:d.length});let f=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(f>cm.LOW_USAGE_MB&&(ie.debug(`\u{1F50D} Tool listing used ${f}MB memory (large tool registry detected)`),d.length>hZ.LARGE_TOOL_COLLECTION&&ie.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(let y of d)y.annotations||(y.annotations=Du({name:y.name,description:y.description||""}));let h=d;return this.toolCache={tools:h,timestamp:Date.now()},h}catch(i){return ie.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(e){let{MemoryManager:t}=await Promise.resolve().then(()=>(dC(),uC)),n=t.getMemoryUsageMB();e?.quiet||ie.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),e?.quiet||ie.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);let{AIProviderFactory:o}=await Promise.resolve().then(()=>(gu(),bW)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(zg(),ID)),i=["openai","bedrock","vertex","googleVertex","anthropic","azure","google-ai","huggingface","ollama","mistral","litellm"],a=zm(fl.DEFAULT_CONCURRENCY_LIMIT),c=i.map(p=>a(async()=>{let f=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()-f};if(p==="ollama")try{let T=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(hl.AUTH_MS)});if(!T.ok)throw new Error("Ollama service not responding");let w=await T.json(),k=w?.models;if(!Array.isArray(k))throw g.warn("Ollama API returned invalid models format in testProvider",{responseData:w,modelsType:typeof k}),new Error("Invalid models format from Ollama API");let C=k.filter(A=>A&&typeof A=="object"&&typeof A.name=="string");return C.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f,model:C[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-f}}catch(T){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:T instanceof Error?T.message:"Ollama service not running",responseTime:Date.now()-f}}let y=5e3,x=this.testProviderConnection(p),b=new Promise((T,w)=>{setTimeout(()=>w(new Error("Provider test timeout (5s)")),y)});return await Promise.race([x,b]),{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f}}catch(h){let y=h instanceof Error?h.message:String(h);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-f}}})),l=await Promise.all(c),d=t.getMemoryUsageMB().heapUsed-n.heapUsed;return!e?.quiet&&d>20&&ie.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&t.forceGC(),l}async testProvider(e){try{return await this.testProviderConnection(e),!0}catch{return!1}}async testProviderConnection(e){let{AIProviderFactory:t}=await Promise.resolve().then(()=>(gu(),bW));await(await t.createProvider(e,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(e){let{getBestProvider:t}=await Promise.resolve().then(()=>(zg(),ID));return t(e)}async getAvailableProviders(){let{getAvailableProviders:e}=await Promise.resolve().then(()=>(zg(),ID));return e()}async isValidProvider(e){let{isValidProvider:t}=await Promise.resolve().then(()=>(zg(),ID));return t(e)}async getMCPStatus(){try{await this.initializeMCP();let e=await this.toolRegistry.listTools(),t=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,c=t.connectedServers+o.length+s.length,l=e.length+t.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:c,autoDiscoveredCount:i.length,totalTools:l,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:t.connectedServers,externalMCPFailedCount:t.failedServers,externalMCPServers:n}}catch(e){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:e instanceof Error?e.message:String(e)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(e){try{if(e==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;let t=this.getInMemoryServers();if(t.has(e)){let o=t.get(e);return!!(o?.tools&&o.tools.length>0)}let n=this.externalServerManager.getServer(e);return n?n.status==="connected"&&n.client!==null:!1}catch(t){return ie.error(`[NeuroLink] Error testing MCP server ${e}:`,t),!1}}async hasProviderEnvVars(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Ox(),rC));try{let n=await t.checkProviderHealth(e,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return g.warn(`Provider env var check failed for ${e}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(e,t={}){let{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Ox(),rC)),o=await n.checkProviderHealth(e,t);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(e={}){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Ox(),rC));return(await t.checkAllProvidersHealth(e)).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(){let{ProviderHealthChecker:e}=await Promise.resolve().then(()=>(Ox(),rC)),t=await e.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=e.getHealthSummary(t),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(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Ox(),rC));t.clearHealthCache(e)}getToolExecutionMetrics(){let e={};for(let[t,n]of this.toolExecutionMetrics.entries())e[t]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return e}setModelAliasConfig(e){this.modelAliasConfig=e,g.info(`[ModelAlias] Configured ${Object.keys(e.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){let e={};for(let[t,n]of this.toolCircuitBreakers.entries())e[t]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return e}resetToolCircuitBreaker(e){this.toolCircuitBreakers.has(e)&&(this.toolCircuitBreakers.set(e,new mE(GI.FAILURE_THRESHOLD,j2)),ie.info(`Circuit breaker reset for tool: ${e}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),ie.info("All tool execution metrics cleared")}async getToolHealthReport(){let e={},t=0,n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(let i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(let i of o){let a=this.toolExecutionMetrics.get(i),c=`${s.get(i)||"unknown"}.${i}`,l=this.toolCircuitBreakers.get(c),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!l||l.getState()==="closed")&&u>=.8;d&&t++;let p=[],f=[];if(l&&l.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),f.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(u*100).toFixed(1)}%`),f.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),f.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){let h=a.errorCategories;h.timeout>0&&(p.push(`Timeout errors: ${h.timeout}`),f.push("Consider increasing the tool timeout configuration")),h.validation>0&&(p.push(`Validation errors: ${h.validation}`),f.push("Review input schemas and parameter validation")),h.network>0&&(p.push(`Network errors: ${h.network}`),f.push("Check network connectivity and endpoint availability"))}e[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:l?.getState()||"closed",failureCount:l?.getFailureCount()||0},issues:p,recommendations:f}}return{totalTools:o.size,healthyTools:t,unhealthyTools:o.size-t,tools:e}}async ensureConversationMemoryInitialized(){try{let e=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(e){return g.error("Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e)}),!1}}async getConversationStats(){let e=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(e){let t=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Fe({code:ut.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});try{let n=await this.conversationMemory.buildContextMessages(e);return g.debug("Retrieved conversation history",{sessionId:e,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return g.error("Failed to retrieve conversation history",{sessionId:e,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(e){let t=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(e),await this.conversationMemory.clearSession(e)}async clearAllConversations(){let e=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async storeToolExecutions(e,t,n,o,s){let i=n&&n.length>0||o&&o.length>0;if(!i){g.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}let a=this.conversationMemory;try{await a.storeToolExecution(e,t,n,o,s)}catch(c){g.warn("Failed to store tool executions",{sessionId:e,userId:t,error:c instanceof Error?c.message:String(c)})}}isToolExecutionStorageAvailable(){let e=process.env.STORAGE_TYPE==="redis",t=this.conversationMemory&&this.conversationMemory.constructor.name==="RedisConversationMemoryManager";return!!(e&&t)}async getSessionMessages(e,t){let n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Fe({code:ut.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});return await this.conversationMemory.getSessionMessages(e,t)}async setSessionMessages(e,t,n){let o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Fe({code:ut.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});await this.conversationMemory.setSessionMessages(e,t,n)}async modifyLastAssistantMessage(e,t,n){let o=await this.getSessionMessages(e,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:t(o[s].content)},await this.setSessionMessages(e,o,n),!0;return!1}async addExternalMCPServer(e,t){this.invalidateToolCache();try{ie.info(`[NeuroLink] Adding external MCP server: ${e}`,{command:t.command,transport:t.transport});let n=await this.externalServerManager.addServer(e,t);if(n.success){if(ie.info(`[NeuroLink] External MCP server added successfully: ${e}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){let o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new Ix({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(let s of o)this.mcpToolRouter.registerServer(s.id||e);g.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(e)}this.emitter.emit("externalMCP:serverAdded",{serverId:e,serverName:t.name||e,config:t,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else ie.error(`[NeuroLink] Failed to add external MCP server: ${e}`,{error:n.error,transport:t.transport,command:t.command,url:t.url?mr(t.url):void 0});return n}catch(n){throw ie.error(`[NeuroLink] Error adding external MCP server: ${e}`,n),n}}async removeExternalMCPServer(e){this.invalidateToolCache();try{ie.info(`[NeuroLink] Removing external MCP server: ${e}`);let t=this.externalServerManager.getServerName(e),n=await this.externalServerManager.removeServer(e);return n.success?(ie.info(`[NeuroLink] External MCP server removed successfully: ${e}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:e,serverName:t,timestamp:Date.now()})):n.error?.includes("not found")?ie.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${e}`):ie.error(`[NeuroLink] Failed to remove external MCP server: ${e}`,{error:n.error}),n}catch(t){throw ie.error(`[NeuroLink] Error removing external MCP server: ${e}`,t),t}}listExternalMCPServers(){let e=this.externalServerManager.getServerStatuses(),t=this.externalServerManager.listServers();return e.map(n=>{let o=t.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(e){return this.externalServerManager.getServer(e)}async executeExternalMCPTool(e,t,n,o){try{ie.debug(`[NeuroLink] Executing external MCP tool: ${t} on ${e}`);let s=this.getToolAnnotationsForExecution(t),i=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,a={__serverId:e,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}};if(i&&this.mcpToolResultCache){let d=this.mcpToolResultCache.getCachedResult(t,a);if(d!==void 0)return ie.debug(`[NeuroLink] Tool result cache HIT: ${t} on ${e}`),d}let c=await this.externalServerManager.executeTool(e,t,n,o),l=c&&typeof c=="object"?c:void 0,u=!!(l&&"isError"in l&&l.isError===!0||l&&"success"in l&&l.success===!1);return i&&this.mcpToolResultCache&&!u&&c!==void 0&&this.mcpToolResultCache.cacheResult(t,a,c),ie.debug(`[NeuroLink] External MCP tool ${u?"returned error":"executed successfully"}: ${t}`),c}catch(s){throw ie.error(`[NeuroLink] External MCP tool execution failed: ${t}`,s),s}}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(e){return this.externalServerManager.getServerTools(e)}async testExternalMCPConnection(e){try{let{MCPClientFactory:t}=await Ke(Promise.resolve().then(()=>(r3(),Aqe)),1e4),n=await t.testConnection(e,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{ie.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),ie.info("[NeuroLink] All external MCP servers shut down successfully")}catch(e){throw ie.error("[NeuroLink] Error shutting down external MCP servers:",e),e}}async getElicitationManager(){return(await Ke(Promise.resolve().then(()=>(pme(),mKe)),1e4)).globalElicitationManager}async registerElicitationHandler(e){(await this.getElicitationManager()).registerHandler(e)}async getMultiServerManager(){return(await Ke(Promise.resolve().then(()=>(SH(),$Ve)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){let e=await Ke(Promise.resolve().then(()=>(wH(),BVe)),1e4);return new e.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ke(Promise.resolve().then(()=>(hme(),fKe)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(e,t){return(await Ke(Promise.resolve().then(()=>(CW(),bme)),1e4)).exposeAgentAsTool(e,t)}async exposeWorkflowAsTool(e,t){return(await Ke(Promise.resolve().then(()=>(CW(),bme)),1e4)).exposeWorkflowAsTool(e,t)}async getToolIntegrationManager(){return(await Ke(Promise.resolve().then(()=>(Rme(),gKe)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(e,t={}){let n=await Ke(Promise.resolve().then(()=>(PW(),Ume)),1e4),o=e.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,t)}async convertToolsFromMCPFormat(e,t={}){return(await Ke(Promise.resolve().then(()=>(PW(),Ume)),1e4)).batchConvertToNeuroLink(e,t)}async getToolAnnotations(e){let{inferAnnotations:t,mergeAnnotations:n,getAnnotationSummary:o}=await Ke(Promise.resolve().then(()=>(Sk(),FVe)),1e4),s=this.toolRegistry.getToolInfo(e);if(!s)return null;let i=s.tool.annotations,a=t({name:s.tool.name,description:s.tool.description??""}),c=n(a,i);return{annotations:c,summary:o(c)}}convertExternalMCPToolsToAISDKFormat(){let e=this.externalServerManager.getAllTools(),t={};for(let n of e)if(n.isAvailable){let o={description:n.description,execute:async s=>{try{ie.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});let i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return ie.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw ie.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};t[n.name]=o,ie.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return ie.info(`[NeuroLink] Converted ${Object.keys(t).length} external MCP tools to AI SDK format`),t}convertJSONSchemaToAISDKFormat(e){}unregisterExternalMCPToolsFromRegistry(e){try{let t=this.externalServerManager.getServerTools(e);for(let n of t)this.toolRegistry.removeTool(n.name),ie.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(t){ie.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${e}:`,t)}}unregisterExternalMCPToolFromRegistry(e){try{this.toolRegistry.removeTool(e),ie.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${e}`)}catch(t){ie.error(`[NeuroLink] Failed to unregister external MCP tool ${e} from registry:`,t)}}async lazyInitializeConversationMemory(e,t,n){try{let{initializeConversationMemory:o}=await TKe().then(()=>bKe),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw g.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,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{let e=this.externalServerManager.getAllTools();for(let t of e)this.toolRegistry.removeTool(t.name);ie.debug(`[NeuroLink] Unregistered ${e.length} external MCP tools from main registry`)}catch(e){ie.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",e)}}async createEvaluationPipeline(e){let{EvaluationPipeline:t,getPreset:n}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4)),o;typeof e=="string"?o=n(e):o=e;let s=new t(o);return await Ke(s.initialize(),3e4,me.evaluationTimeout("pipeline initialization",3e4)),g.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(e,t){let{EvaluationPipeline:n,getPreset:o}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4)),s;if(t?.pipeline&&t?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(t?.scorers&&t.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.");t?.pipeline?s={...o(t.pipeline)}:t?.scorers&&t.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:t.scorers.map(l=>({id:l})),executionMode:t.executionMode??"parallel",passThreshold:t.passThreshold??.7}:s=o("quality"),t?.passThreshold!==void 0&&(s.passThreshold=t.passThreshold),t?.executionMode!==void 0&&(s.executionMode=t.executionMode);let i=new n(s);await Ke(i.initialize(),3e4,me.evaluationTimeout("pipeline initialization",3e4));let a=t?.timeoutMs??6e4,c=await Ke(i.execute(e,{correlationId:t?.correlationId}),a,me.evaluationTimeout("pipeline execution",a));return g.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:c.overallScore,passed:c.passed,scorerCount:c.scores.length}),c}async score(e,t,n){let{ScorerRegistry:o}=await Ke(Promise.resolve().then(()=>(CB(),T7)),1e4,me.evaluationTimeout("scorer module load",1e4));await Ke(o.registerBuiltInScorers(),3e4,me.evaluationTimeout("scorer bootstrap",3e4));let s=await Ke(o.getScorer(e,n),3e4,me.evaluationTimeout(`scorer load: ${e}`,3e4));if(!s)throw me.scorerNotFound(e);let i=s.validateInput(t);if(!i.valid)throw me.evaluationValidationFailed(e,i.errors);let a=await Ke(s.score(t),6e4,me.evaluationTimeout("scorer execution",6e4));return g.debug("[NeuroLink] Scoring completed",{scorerId:e,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(e){let{ScorerRegistry:t}=await Ke(Promise.resolve().then(()=>(CB(),T7)),1e4,me.evaluationTimeout("scorer module load",1e4));await Ke(t.registerBuiltInScorers(),3e4,me.evaluationTimeout("scorer bootstrap",3e4));let n=t.list();return e?.category&&(n=n.filter(o=>o.category===e.category)),e?.type&&(n=n.filter(o=>o.type===e.type)),n}async getEvaluationPresets(){let{getPresetNames:e}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4));return e()}async getEvaluationPreset(e){let{getPreset:t}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4));return t(e)}async createAgent(e){let{Agent:t}=await Promise.resolve().then(()=>(OW(),SKe));return g.debug("[NeuroLink] Creating agent",{id:e.id,name:e.name,tools:e.tools?.length||0}),new t(e,this)}async createNetwork(e){let{AgentNetwork:t}=await Promise.resolve().then(()=>(Bme(),wKe));return g.debug("[NeuroLink] Creating agent network",{name:e.name,agentCount:e.agents.length,workflowCount:e.workflows?.length||0,toolCount:e.tools?.length||0}),new t(e,this)}async executeNetwork(e,t,n){return g.debug("[NeuroLink] Executing agent network",{networkId:e.id,networkName:e.name,hasContext:!!t.context}),e.execute(t,n)}async*streamNetwork(e,t,n){g.debug("[NeuroLink] Streaming agent network",{networkId:e.id,networkName:e.name,hasContext:!!t.context}),yield*e.stream(t,n)}async createOrchestrator(e){let{NetworkOrchestrator:t}=await Promise.resolve().then(()=>(Gme(),kKe));return g.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:e?.maxConcurrentExecutions,defaultMode:e?.defaultMode}),new t(this,e)}async createCoordinator(e){let{AgentCoordinator:t}=await Promise.resolve().then(()=>(Vme(),AKe));return g.debug("[NeuroLink] Creating agent coordinator",{strategy:e?.strategy,maxConcurrency:e?.maxConcurrency}),new t(e)}async createMessageBus(e){let{MessageBus:t}=await Promise.resolve().then(()=>(qme(),IKe));return g.debug("[NeuroLink] Creating message bus",{maxHistorySize:e?.maxHistorySize}),new t(e)}async dispose(){g.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();let e=[];try{try{g.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await hO(),await yO(),g.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`OpenTelemetry shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down OpenTelemetry:",t)}if(this.externalServerManager)try{g.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),g.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`External server shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down external MCP servers:",t)}if(this.emitter)try{g.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),g.clearEventEmitter(),g.debug("[NeuroLink] Event listeners removed successfully")}catch(t){let n=t instanceof Error?t:new Error(`Event emitter cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error removing event listeners:",t)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{g.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),g.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Circuit breaker cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing circuit breakers:",t)}try{g.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=[],g.debug("[NeuroLink] Maps and caches cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Cache cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing caches:",t)}if(this._taskManager)try{g.debug("[NeuroLink] Shutting down TaskManager..."),await Ke(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(t){g.warn("[NeuroLink] TaskManager shutdown error:",t)}finally{this._taskManager=void 0}try{g.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,g.debug("[NeuroLink] Initialization state reset successfully")}catch(t){let n=t instanceof Error?t:new Error(`State reset error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error resetting state:",t)}e.length===0?g.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):g.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${e.length} errors`,{errors:e.map(t=>t.message)})}catch(t){throw g.error("[NeuroLink] Critical error during disposal:",t),t}}getToolRegistry(){return this.toolRegistry}async compactSession(e,t){if(!this.conversationMemory)return null;let n=await this.conversationMemory.buildContextMessages(e);if(!n||n.length===0)return null;let o=new bx({...t,summarizationProvider:t?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:t?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=Qc({provider:t?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&xk(a.messages),a}async getContextStats(e,t,n){if(!this.conversationMemory)return null;let o=await this.conversationMemory.buildContextMessages(e);if(!o||o.length===0)return null;let s=Qc({provider:t||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(e,t,n){if(!this.conversationMemory)return!1;let o=this.conversationMemory.getSession?.(e);return o?Qc({provider:t||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(e){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(e)}async initializeAuthProviderFromConfig(e){let t,n;if("authenticateToken"in e&&typeof e.authenticateToken=="function")t=e,n=t.type;else if("provider"in e)t=e.provider,n=t.type;else{let o=e,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(JD(),PKe));t=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=t,g.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:t.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;let e=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(e),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===e)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(e){let{globalAuthContext:t}=await Promise.resolve().then(()=>(qk(),d3));t.set(e),g.debug("Auth context set",{userId:e.user.id,provider:e.provider,sessionId:e.session?.id})}async getAuthContext(){let{getAuthContext:e}=await Promise.resolve().then(()=>(qk(),d3));return e()}async clearAuthContext(){let{globalAuthContext:e}=await Promise.resolve().then(()=>(qk(),d3)),t=e.get()?.user.id;e.clear(),t&&g.debug(`Auth context cleared for user: ${t}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(e,t){return{requestContext:t||{},signal:e}}async resolveDynamicOptions(e){let t=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(t.some(s=>typeof e[s]=="function")||typeof e.tools=="function"))return;let o=e.dynamicContext;await this.resolveDynamicFields(e,t,o)}async resolveDynamicFields(e,t,n){let o=this.buildResolutionContext(e.abortSignal,n);if(g.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(t.map(async s=>{if(typeof e[s]=="function"){let i=await tde(e[s],o);e[s]=i.value,g.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof e.tools=="function"){let s=await tde(e.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);e.enabledToolNames=s.value,delete e.tools}}},MKe=new rS,XCr=MKe});var NKe={};ee(NKe,{VoyageProvider:()=>UW,default:()=>eRr});var ZCr,OKe,QCr,Jme,UW,eRr,DKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();It();W();po();ZCr="https://api.voyageai.com/v1",OKe=6e4,QCr=()=>Mr(D$e()),Jme=()=>Or("VOYAGE_MODEL","voyage-3.5"),UW=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"voyage",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:QCr(),this.baseURL=o?.baseURL??process.env.VOYAGE_BASE_URL??ZCr,this.proxyFetch=vt(),g.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Jme()}supportsTools(){return!1}getDefaultEmbeddingModel(){return Jme()}getAISDKModel(){throw new Ve("Voyage AI is an embedding-only provider; chat completions are not available. Use `embed()` or `embedMany()` instead, or pick a different provider for `generate()` / `stream()`.","voyage")}async executeStream(e,t){throw new Ve("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new Mt("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Zt(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new Ve(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Ve("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];let n=128,o=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),a=await this.callEmbeddings(i,t);o.push(...a)}return o}async callEmbeddings(e,t){let n=t??this.modelName,o;try{o=await Ke(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n})}),OKe,new Ve(`Voyage embeddings request timed out after ${OKe/1e3}s`,"voyage"))}catch(a){throw a instanceof Ve?a:this.formatProviderError(a)}if(!o.ok){let a=await o.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${o.status} \u2014 ${a}`))}let s=await o.json();if(!s.data||s.data.length===0)throw new Ve("Voyage embeddings response missing data","voyage");if(s.data.length!==e.length)throw new Ve(`Voyage embeddings response count mismatch: expected ${e.length}, got ${s.data.length}`,"voyage");let i=s.data.slice().sort((a,c)=>a.index-c.index);for(let a=0;a<i.length;a++)if(i[a].index!==a)throw new Ve(`Voyage embeddings response has unexpected index ordering: position ${a} has index ${i[a].index}`,"voyage");return i.map(a=>a.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Jme(),baseURL:this.baseURL}}},eRr=UW});var LKe={};ee(LKe,{JinaProvider:()=>$W,default:()=>nRr});var tRr,FW,rRr,Yme,$W,nRr,UKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();W();po();tRr="https://api.jina.ai/v1",FW=6e4,rRr=()=>Mr(L$e()),Yme=()=>Or("JINA_MODEL","jina-embeddings-v3"),$W=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"jina",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:rRr(),this.baseURL=o?.baseURL??process.env.JINA_BASE_URL??tRr,this.proxyFetch=vt(),g.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Yme()}supportsTools(){return!1}getDefaultEmbeddingModel(){return Yme()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mt("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Zt(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new Ve(`Jina AI error: ${t}`,"jina")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Error("Jina AI returned no embedding for the provided text");return n[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,n={}){if(t.length===0)return[];let o=n.model??"jina-reranker-v2-base-multilingual",s=n.credentials,i=s?.apiKey?.trim()||this.apiKey,a=s?.baseURL||this.baseURL,c=new AbortController,l=setTimeout(()=>c.abort(),FW),u;try{u=await this.proxyFetch(`${a}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({model:o,query:e,documents:t,top_n:n.topN??t.length}),signal:c.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${FW/1e3}s`)):this.formatProviderError(p)}finally{clearTimeout(l)}if(!u.ok){let p=await u.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${u.status} \u2014 ${p}`))}return((await u.json()).results??[]).map(p=>({index:p.index,score:p.relevance_score,document:t[p.index]??p.document?.text??""}))}async callEmbeddings(e,t,n){let o=t??this.modelName,s=n?.apiKey?.trim()||this.apiKey,i=n?.baseURL||this.baseURL,a=new AbortController,c=setTimeout(()=>a.abort(),FW),l;try{l=await this.proxyFetch(`${i}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:o}),signal:a.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${FW/1e3}s`)):this.formatProviderError(p)}finally{clearTimeout(c)}if(!l.ok){let p=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${p}`))}let u=await l.json();if(!u.data||u.data.length===0)throw new Error("Jina embeddings response missing data");if(u.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${u.data.length}`);let d=u.data.slice().sort((p,f)=>p.index-f.index);for(let p=0;p<d.length;p++)if(d[p].index!==p)throw new Error(`Jina embeddings response has unexpected index ordering: position ${p} has index ${d[p].index}`);return d.map(p=>p.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Yme(),baseURL:this.baseURL}}},nRr=$W});var BKe={};ee(BKe,{StabilityProvider:()=>BW,default:()=>iRr});var oRr,FKe,sRr,$Ke,BW,iRr,zKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();W();po();oRr="https://api.stability.ai",FKe=12e4,sRr=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,$Ke=()=>Or("STABILITY_MODEL","stable-image-ultra"),BW=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"stability",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:sRr(),this.baseURL=o?.baseURL??process.env.STABILITY_BASE_URL??oRr,this.proxyFetch=vt(),g.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return $Ke()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mt("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new Ve("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Zt(`Stability AI model '${this.modelName}' not found. Use stable-image-ultra, stable-image-core, sd3.5-large, sd3.5-large-turbo, or sd3.5-medium.`,"stability"):new Ve(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.stability,o=n?.apiKey?.trim()||this.apiKey;if(!o)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");let s=o,i=n?.baseURL||this.baseURL,a=e.prompt??e.input?.text??"";if(!a.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");let c=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,u=new FormData;u.append("prompt",a),u.append("output_format","png"),l.aspectRatio&&u.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&u.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&u.append("model",this.modelName),l.seed!==void 0&&u.append("seed",String(l.seed));let d=new AbortController,p=setTimeout(()=>d.abort(),FKe),f;try{f=await this.proxyFetch(`${i}/v2beta/stable-image/generate/${c}`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/json"},body:u,signal:d.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${FKe/1e3}s`)):this.formatProviderError(x)}finally{clearTimeout(p)}if(!f.ok){let x=await f.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${f.status} \u2014 ${x}`))}let h=await f.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);let y=Date.now()-t;return g.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:$Ke(),baseURL:this.baseURL}}},iRr=BW});var VKe={};ee(VKe,{IdeogramProvider:()=>zW,default:()=>lRr});var aRr,jKe,cRr,GKe,zW,lRr,qKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();W();po();aRr="https://api.ideogram.ai",jKe=12e4,cRr=()=>Mr(U$e()),GKe=()=>Or("IDEOGRAM_MODEL","V_3"),zW=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"ideogram",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:cRr(),this.baseURL=o?.baseURL??process.env.IDEOGRAM_BASE_URL??aRr,this.proxyFetch=vt(),g.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return GKe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mt("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new Ve("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new Ve(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.ideogram,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");let a=e,c={prompt:i,model:this.modelName,magic_prompt:a.magicPrompt??"AUTO"};a.aspectRatio&&(c.aspect_ratio=a.aspectRatio),a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.seed!==void 0&&(c.seed=a.seed),a.style&&(c.style_type=a.style);let l=new AbortController,u=setTimeout(()=>l.abort(),jKe),d;try{d=await this.proxyFetch(`${s}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":o,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(k){throw k instanceof Error&&k.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${jKe/1e3}s`)):this.formatProviderError(k)}finally{clearTimeout(u)}if(!d.ok){let k=await d.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${d.status} \u2014 ${k}`))}let f=(await d.json()).data?.[0]?.url;if(!f)throw new Error("Ideogram returned no image URL");let h=new AbortController,y=setTimeout(()=>h.abort(),6e4),x;try{x=await this.proxyFetch(f,{signal:h.signal})}catch(k){throw k instanceof Error&&k.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:k}):k}finally{clearTimeout(y)}if(!x.ok)throw new Error(`Failed to download Ideogram image: ${x.status}`);let b=Buffer.from(await x.arrayBuffer()),T=b.toString("base64"),w=Date.now()-t;return g.info(`[IdeogramProvider] Generated image (${b.length} bytes) in ${w}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:T}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:GKe(),baseURL:this.baseURL}}},lRr=zW});function Od(r){let e=(r?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return e?{apiToken:e,baseUrl:(r?.baseUrl??process.env.REPLICATE_BASE_URL??uRr).replace(/\/$/,"")}:null}var uRr,YD=_(()=>{"use strict";uRr="https://api.replicate.com"});function pRr(r,e,t){return new Nte({connect:{lookup:(n,o,s)=>{if(n.toLowerCase()!==r.toLowerCase()){s(new Error(`safeFetch: refusing to resolve "${n}" \u2014 expected "${r}"`),"",0);return}s(null,e,t)}}})}async function zx(r,e){let{url:t,ip:n,family:o}=await Q$e(r),i=new URL(t).hostname.replace(/^\[|\]$/g,""),a=pRr(i,n,o),c=new AbortController,l=setTimeout(()=>c.abort(),e.timeoutMs??dRr),u=e.signal?AbortSignal.any([e.signal,c.signal]):c.signal,d;try{d=await Ote(t,{method:"GET",signal:u,redirect:"manual",dispatcher:a})}finally{clearTimeout(l),a.close().catch(()=>{})}if(d.status>=300&&d.status<400)throw new Error(`safeDownload(${e.label}): refused to follow redirect ${d.status} \u2192 ${d.headers.get("location")??"<no-location>"} (for ${r})`);if(!d.ok)throw new Error(`safeDownload(${e.label}) failed: HTTP ${d.status} for ${r}`);return Ha(d,e.maxBytes,e.label)}var dRr,XD=_(()=>{"use strict";zE();vg();cx();dRr=6e4});async function gRr(r,e){let t=r.baseUrl??"https://api.replicate.com",[n,o]=e.model.split(":",2),s=o?`${t}/v1/predictions`:`${t}/v1/models/${n}/predictions`,i=o?{version:o,input:e.input}:{input:e.input};e.webhook&&(i.webhook=e.webhook),e.webhookEventsFilter&&e.webhookEventsFilter.length>0&&(i.webhook_events_filter=e.webhookEventsFilter);let a=new AbortController,c=setTimeout(()=>a.abort(),ZD),l;try{l=await fetch(s,{method:"POST",headers:{Authorization:`Token ${r.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(i),signal:a.signal})}catch(u){throw u instanceof Fe?u:u instanceof Error&&u.name==="AbortError"?new Fe({code:ut.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${ZD/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:u}):u}finally{clearTimeout(c)}if(!l.ok){let u=await l.text();throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${l.status} \u2014 ${Ms(u,500)}`,category:"network",severity:"high",retriable:l.status>=500})}return await l.json()}async function hRr(r,e,t={}){let n=r.baseUrl??"https://api.replicate.com",o=Date.now(),s=t.timeoutMs??fRr,i=t.pollIntervalMs??mRr;for(;Date.now()-o<s;){if(t.abortSignal?.aborted)throw new Fe({code:ut.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});let a=new AbortController,c=setTimeout(()=>a.abort(),ZD),l=()=>a.abort();t.abortSignal?.addEventListener("abort",l,{once:!0});let u;try{u=await fetch(`${n}/v1/predictions/${e}`,{method:"GET",headers:{Authorization:`Token ${r.apiToken}`},signal:a.signal})}catch(p){throw p instanceof Fe?p:p instanceof Error&&p.name==="AbortError"?t.abortSignal?.aborted?new Fe({code:ut.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:p}):new Fe({code:ut.OPERATION_ABORTED,message:`Replicate poll request timed out after ${ZD/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:p}):p}finally{t.abortSignal?.removeEventListener("abort",l),clearTimeout(c)}if(!u.ok){let p=await u.text();throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${u.status} \u2014 ${Ms(p,500)}`,category:"network",severity:"high",retriable:u.status>=500})}let d=await u.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((p,f)=>{let h=()=>{clearTimeout(y),f(new Fe({code:ut.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},y=setTimeout(()=>{t.abortSignal?.removeEventListener("abort",h),p()},i);t.abortSignal?.addEventListener("abort",h,{once:!0})})}throw new Fe({code:ut.OPERATION_ABORTED,message:`Replicate prediction ${e} did not complete within ${Math.round(s/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function Wg(r,e,t={}){let n=await gRr(r,e);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return hRr(r,n.id,t)}async function jx(r,e=268435456){let t=r.output,n=Array.isArray(t)?t[0]:t;if(typeof n!="string")throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${r.id} output is not a URL: ${typeof t}`,category:"execution",severity:"high",retriable:!1});try{let o=await zx(n,{maxBytes:e,label:`Replicate prediction ${r.id}`,timeoutMs:ZD});return g.debug(`[Replicate] Downloaded prediction ${r.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof Fe)throw o;let s=o instanceof Error?o.message:String(o);throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${s} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var ZD,mRr,fRr,QD=_(()=>{"use strict";W();It();Pn();XD();ZD=9e4,mRr=2e3,fRr=5*6e4});var WKe={};ee(WKe,{ReplicateProvider:()=>jW,default:()=>vRr});function yRr(r){let e=r,t=e.prompt??e.input?.text??"",n=e.systemPrompt;return n?`${n}
|
|
2206
|
+
IMPORTANT: You have a tool called "${c.toolName}" that searches through`,`${c.filesLoaded} loaded document(s) containing ${c.chunksIndexed} indexed chunks.`,`ALWAYS use the "${c.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(" ");e.systemPrompt=(e.systemPrompt||"")+l,g.info("[RAG] Tool injected into stream()",{toolName:c.toolName,filesLoaded:c.filesLoaded,chunksIndexed:c.chunksIndexed})}catch(a){g.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}let s=U3e(e),i=F3e(e);if(e.input?.text){let{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(e.input.text,void 0);c!==e.input.text&&(i.input.text=c)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(e){if((e.provider==="ollama"||e.provider?.toLowerCase().includes("ollama"))&&!e.disableTools){let{ModelConfigurationManager:t}=await Promise.resolve().then(()=>(Xy(),fUe)),s=t.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=e.model;s.length>0&&i&&(s.some(c=>i.toLowerCase().includes(c.toLowerCase()))||(e.disableTools=!0,g.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:e.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){let e=[],t=0,n=(d,p)=>{e.push({type:d,seq:t++,timestamp:Date.now(),...p&&typeof p=="object"?p:{data:p}})},o=(...d)=>{let p=d[0];n("response:chunk",{content:p})},s=(...d)=>{let p=d[0];n("tool:start",{...p,toolName:p.toolName??p.tool})},i=(...d)=>{let p=d[0],f=p.toolName??p.tool,h=p.responseTime??p.duration,y=p.success??(p.error!==void 0?!1:void 0),x={...p,toolName:f,...h!==void 0?{responseTime:h}:{},...y!==void 0?{success:y}:{},...p.error!==void 0?{error:p.error}:{}};n("tool:end",x),x.result&&x.result.uiComponent===!0&&n("ui-component",{toolName:f,componentData:x.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...h!==void 0?{responseTime:h}:{}})},a=(...d)=>{n("ui-component",d[0])},c=(...d)=>{n("hitl:confirmation-request",d[0])},l=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",c),this.emitter.on("hitl:confirmation-response",l),{eventSequence:e,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",c),this.emitter.off("hitl:confirmation-response",l)}}}async*handleStreamFallback(e,t,n,o,s,i){e.fallbackAttempted=!0;let a="Stream completed with 0 chunks (possible guardrails block)";e.error=a;try{let h=this._metricsTraceContext,y=xe.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:h?.traceId,parentSpanId:h?.parentSpanId});y=xe.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),Ze().recordSpan(y)}catch{}let c=o.fallbackProvider?.trim()||void 0,l=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,p=tC.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),f={...p,provider:c??u??p.provider,model:l??d??p.model};g.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:f.provider,fallbackModel:f.model,fallbackSource:c||l?"options":u||d?"env":"model_config",reason:a});try{let h=await dn.createProvider(f.provider,f.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));h.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,A)=>this.executeTool(C,A,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");let y=o.conversationMessages!==void 0?o.conversationMessages:await Og(this.conversationMemory,{prompt:o.input.text,context:o.context}),x=await h.stream({...o,model:f.model,conversationMessages:y}),b=x.toolCalls??[],T=x.toolResults??[];(b.length>0||T.length>0)&&(t.toolCalls=b,t.toolResults=T,t.finishReason=x.finishReason??t.finishReason);let w=0,k=0;for await(let C of x.stream){w++;let A=C!==null&&typeof C=="object"&&"metadata"in C&&C.metadata?.noOutput===!0,P=C&&"content"in C&&typeof C.content=="string"&&C.content.length>0,R=C!==null&&typeof C=="object"&&"type"in C&&(C.type==="audio"||C.type==="tts_audio"||C.type==="image");!A&&(P||R)&&k++,C&&"content"in C&&typeof C.content=="string"&&(i(C.content),this.emitter.emit("response:chunk",C.content)),yield C}if(k===0&&b.length===0&&T.length===0)throw new Error(`Fallback provider ${f.provider} also returned 0 real output chunks (chunkCount=${w}, sentinel-only or empty)`);e.fallbackProvider=f.provider,e.fallbackModel=f.model,e.guardrailsBlocked=!0}catch(h){let y=h instanceof Error?h.message:String(h);throw e.error=`${a}; Fallback failed: ${y}`,g.error("Fallback provider failed",{fallbackProvider:f.provider,error:y}),h}}async storeStreamConversationMemory(e){let{enhancedOptions:t,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=e;g.shouldLog("debug")&&g.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:m0(f0(t)),sessionId:t.context?.sessionId});let c=a.some(l=>l.type==="tool:start"||l.type==="tool:end");if(!s.trim()&&!c){g.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:t.context?.sessionId});return}if(g.shouldLog("debug")&&g.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:m0(f0(t)),sessionId:t.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&t.context?.sessionId){let l=t.context?.sessionId,u=t.context?.userId,d;t.model&&(d={provider:n,model:t.model});let p=Date.now();try{let f=this.drainPendingSkillMessages(l);await this.conversationMemory.storeConversationTurn({sessionId:l,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:t.enableSummarization,events:a.length>0?a:void 0,requestId:t.context?.requestId,...f.length>0?{skillMessages:f}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,1),g.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:l,eventCount:a.length,eventTypes:[...new Set(a.map(h=>h.type))]})}catch(f){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-p,2,f instanceof Error?f.message:String(f)),g.warn("Failed to store stream conversation turn",{error:f instanceof Error?f.message:String(f)})}}this.shouldWriteMemory(t.memory,t.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),t.context?.userId,t.memory?.additionalUsers,t.context)}async validateStreamInput(e){let t=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:t.toString(),message:"Starting comprehensive input validation process"});let n=typeof e?.input?.text=="string"&&e.input.text.trim().length>0,o=!!(e?.input?.audio&&e.input.audio.frames&&typeof e.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(e?.stt?.enabled&&e?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(e,t){this.emitter.emit("stream:start",{provider:e.provider||"auto",timestamp:t}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${e.provider||"auto"} stream...`)}async createMCPStream(e){let t=await Nx(e.provider),n=await dn.createProvider(t,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(h,y)=>this.executeTool(h,y,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,e);let s=e.skipToolPromptInjection?e.systemPrompt||"":this.createToolAwareSystemPrompt(e.systemPrompt,o),i=e.conversationMessages!==void 0,a=i?e.conversationMessages:await Og(this.conversationMemory,{...e,prompt:e.input.text,context:e.context});e.conversationMessages=a;let c=a,l=Qc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o}),u=c?.length||0,d=this.getCompactionSessionId(e),p=u>0;if(!l.withinBudget&&!p){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:l.estimatedInputTokens,budget:l.availableInputTokens,provider:t,model:e.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new ql(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${l.estimatedInputTokens} tokens, budget: ${l.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:l.estimatedInputTokens,availableTokens:l.availableInputTokens,stagesUsed:[],breakdown:l.breakdown})}if(l.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){let y=await new bx({provider:t,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(c,l.availableInputTokens,this.conversationMemoryConfig?.conversationMemory,e.context?.requestId);y.compacted&&(c=xk(y.messages).messages,e.conversationMessages=c,this.lastCompactionMessageCount.set(d,c.length));let x=Qc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!x.withinBudget){g.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:x.estimatedInputTokens,availableTokens:x.availableInputTokens,overagePercent:Math.round((x.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:x.estimatedInputTokens,budget:x.availableInputTokens,provider:t,model:e.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=fH(c,x.availableInputTokens,x.breakdown,t),e.conversationMessages=c;let b=Qc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!b.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:b.estimatedInputTokens,budget:b.availableInputTokens,provider:t,model:e.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new ql(`Stream context exceeds model budget after all compaction stages. Estimated: ${b.estimatedInputTokens} tokens, Budget: ${b.availableInputTokens} tokens.`,{estimatedTokens:b.estimatedInputTokens,availableTokens:b.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:b.breakdown})}}}if(this.modelPool){let h=this.modelPool,y=h.maxAttempts,x=new Set,b=null;for(let T=0;T<y;T++){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let w=h.selectNext(x);if(!w)break;x.add(h.memberKey(w));let k=w.provider,C=w.model??void 0,A=w.region??void 0;g.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:C,attempt:T});try{let P=await dn.createProvider(k,C,!e.disableTools,this,A,this.resolveCredentials(e.credentials));P.setTraceContext(this._metricsTraceContext),P.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(O,F)=>this.executeTool(O,F,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let R=await P.stream({...e,provider:k,model:C,region:A,systemPrompt:s,conversationMessages:c});g.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});let I=w;return{stream:(async function*(){try{yield*R.stream,h.recordSuccess(I)}catch(O){throw h.recordFailure(I,Ux(O)),O}})(),provider:k,usage:R.usage,model:R.model||C,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics,metadata:R.metadata}}catch(P){if(Hr(P))throw P;if(DW(P)){let R=P instanceof Error?P.message:String(P);throw h.recordFailure(w,Ux(P)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:P})}h.recordFailure(w,Ux(P)),b=P instanceof Error?P:new Error(String(P)),g.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:b.message})}}throw new Error(`[ModelPool] all stream members failed: ${b?.message??"no stream members available"}`)}let f=await n.stream({...e,systemPrompt:s,conversationMessages:c});return g.debug("[createMCPStream] Stream created successfully",{provider:t,systemPromptPassedLength:s.length}),{stream:f.stream,provider:t,usage:f.usage,model:f.model||e.model,finishReason:f.finishReason,toolCalls:f.toolCalls??[],toolResults:f.toolResults??[],analytics:f.analytics,metadata:f.metadata}}async processStreamResult(e,t,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(e){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",e.content||"")}createStreamResponse(e,t,n){return{stream:t,provider:n.providerName,model:n.options.model,usage:e.usage,finishReason:e.finishReason,toolCalls:e.toolCalls,toolResults:e.toolResults,analytics:e.analytics,evaluation:e.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:Object.assign(n.providerMetadata??{},{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error})}}async handleStreamError(e,t,n,o,s,i){if(e instanceof ql)throw e;g.error("Stream generation failed, attempting fallback",{error:e instanceof Error?e.message:String(e)});try{this.emitter.emit("stream:error",{content:e instanceof Error?e.message:String(e),metadata:{errorName:e instanceof Error?e.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:t.provider||"unknown",model:t.model||"unknown"})}catch{}let a=t.input.text,c=Date.now()-n,l=await Nx(t.provider),d=await(await dn.createProvider(l,t.model,!0,void 0,void 0,this.resolveCredentials(t.credentials))).stream({input:{text:t.input.text},model:t.model,temperature:t.temperature,maxTokens:t.maxTokens,conversationMessages:t.conversationMessages}),p="";return{stream:(async function*(h){try{for await(let y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(p+=y.content,h.emitter.emit("response:chunk",y.content)),yield y}finally{if(p.trim()){g.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:t.model,responseTimeMs:Date.now()-n,contentLength:p.length});try{h.emitter.emit("stream:complete",{content:p,provider:l,model:t.model||"unknown",finishReason:"stop",metadata:{durationMs:Date.now()-n,chunkCount:0,totalLength:p.length,isFallback:!0,finishReason:"stop"}})}catch{}}if(h.conversationMemory&&s?.context?.sessionId&&p.trim()){let y=s?.context?.sessionId,x=s?.context?.userId,b;t.model&&(b={provider:l,model:t.model});let T=Date.now();try{let w=y||t.context?.sessionId,k=h.drainPendingSkillMessages(w);await h.conversationMemory.storeConversationTurn({sessionId:w,userId:x||t.context?.userId,userMessage:a??"",aiResponse:p,startTimeStamp:new Date(n),providerDetails:b,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||t.context?.requestId,...k.length>0?{skillMessages:k}:{}}),h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,1)}catch(w){h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,2,w instanceof Error?w.message:String(w)),g.warn("Failed to store fallback stream conversation turn",{error:w instanceof Error?w.message:String(w)})}}}})(this),provider:l,model:t.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:c,fallback:!0}}}getEventEmitter(){return this.emitter}getToolDedupConfig(){return this.toolDedupConfig}async checkCredentials(e){let{provider:t,model:n}=e,o="ping";try{return await this.generate({provider:t,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:t,status:"ok",detail:"credentials valid"}}catch(s){let i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof um?{provider:t,status:"denied",detail:i}: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:t,status:"expired",detail:i}: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:t,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:t,status:"network",detail:i}:{provider:t,status:"unknown",detail:i}}}emitToolStart(e,t,n=Date.now()){let o=`${e}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:e,startTime:n,metadata:{inputType:typeof t,hasInput:t!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",Hf(e,{input:t,timestamp:n,executionId:o})),g.debug(`tool:start emitted for ${e}`,{toolName:e,executionId:o,timestamp:n,inputProvided:t!==void 0}),o}emitToolEnd(e,t,n,o,s=Date.now(),i){let a=o||s-1e3,c=s-a,l=!n,u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(f=>f.tool===e&&!f.endTime);let d=i||u?.executionId||`${e}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=t,u.error=n,this.activeToolExecutions.delete(u.executionId));let p={tool:e,startTime:a,endTime:s,duration:c,success:l,result:t,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(p),this.emitter.emit("tool:end",Hf(e,{result:t,error:n,success:l,responseTime:c,timestamp:s,duration:c,executionId:d})),g.debug(`tool:end emitted for ${e}`,{toolName:e,executionId:d,duration:c,success:l,hasResult:t!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(e,t,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:e,timestamp:Date.now()});try{if(!e||typeof e!="string")throw new Error("Invalid tool name");if(!t||typeof t!="object")throw new Error(`Invalid tool object provided for tool: ${e}`);if(typeof t.execute!="function")throw new Error(`Tool '${e}' must have an execute method.`);if(e.trim()==="")throw new Error("Tool name cannot be empty");if(e.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(e))throw new Error("Tool name contains invalid control characters");let o={name:t.name||e,description:t.description||e,execute:t.execute,inputSchema:"parameters"in t&&t.parameters&&(pP(t.parameters)||typeof t.parameters=="object")?t.parameters:t.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){let i=o.execute,a=n.timeout,c=e;o.execute=async(...l)=>{let u=AbortSignal.timeout(a),d=l[1],p=d?.abortSignal,f=p?AbortSignal.any([p,u]):u,h={...d,abortSignal:f};return Promise.race([i(l[0],h),new Promise((y,x)=>{f.addEventListener("abort",()=>{u.aborted?x(me.toolTimeout(c,a)):x(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}let s=Nqe(e,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),this.emitter.emit("tools-register:end",{toolName:e,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw g.error(`Failed to register tool ${e}:`,o),o}}setToolContext(e){this.toolExecutionContext={...e},g.debug("Tool execution context updated",{sessionId:e.sessionId,contextKeys:Object.keys(e),hasJuspayToken:!!e.juspayToken,hasShopId:!!e.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,g.debug("Tool execution context cleared")}registerTools(e){if(Array.isArray(e))for(let{name:t,tool:n}of e)this.registerTool(t,n);else for(let[t,n]of Object.entries(e))this.registerTool(t,n)}unregisterTool(e){this.invalidateToolCache();let t=`custom-tool-${e}`,n=this.toolRegistry.unregisterServer(t);return n&&g.info(`Unregistered custom tool: ${e}`),n}useToolMiddleware(e){return this.mcpToolMiddlewares.push(e),g.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(e,t,n){if(!this.conversationMemory)throw new Tc("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Tc("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ke(this.conversationMemory.updateAgenticLoopReport(e,n,t),5e3)}getCustomTools(){let e=this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0})),t=new Map;for(let o of e){let s=o.inputSchema||o.parameters;g.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:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),t.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(i,a)=>{let c=this.toolExecutionContext||{},l=a&&_r(a)?a:{},u={...c,...l,sessionId:l.sessionId||c.sessionId||`fallback-${Date.now()}`};return g.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(c),runtimeContextKeys:Object.keys(l),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=nle(this.fileRegistry));let n=this.cachedFileTools;for(let[o,s]of Object.entries(n))if(!t.has(o)){let i=s,a=i.inputSchema??i.parameters;t.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async c=>await s.execute(c,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return t}async addInMemoryMCPServer(e,t){this.invalidateToolCache();try{ie.debug(`[NeuroLink] Registering in-memory MCP server: ${e}`),t.tools||(t.tools=[]),await this.toolRegistry.registerServer(t),ie.info(`[NeuroLink] Successfully registered in-memory server: ${e}`,{category:t.metadata?.category,provider:t.metadata?.provider,version:t.metadata?.version})}catch(n){throw ie.error(`[NeuroLink] Failed to register in-memory server ${e}:`,n),n}}getInMemoryServers(){let e=this.getInMemoryServerInfos(),t=new Map;for(let n of e)t.set(n.id,n);return t}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(t=>Aa({existingCategory:t.metadata?.category,serverId:t.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(e,t={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(e,t);let o=this.createToolExecutionContext(e,t,n);return _e.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":e,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(e,t,n,o,s))}createToolExecutionContext(e,t,n){let o=this.externalServerManager.getAllTools().find(l=>l.name===e),s=o?"mcp":this.getCustomTools().has(e)?"custom":"external",i=t?jm(t):"",a=Date.now(),c=`${e}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:c,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(e,t,n,o,s){try{let i=await this.prepareToolExecutionState(e,t,n,o);return await this.runPreparedToolExecution(e,t,i,o,s)}catch(i){if(!(i instanceof Fe)){let a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:Ie.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(e,t,n,o){g.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:e,params:_r(t)?XB(t):t,hasExternalManager:!!this.externalServerManager}),g.debug("Tool execution detailed analysis",{toolName:e,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof t,isNull:t===null,isUndefined:t===void 0,isEmpty:t&&typeof t=="object"&&Object.keys(t).length===0,keys:t&&typeof t=="object"?Object.keys(t):"NOT_OBJECT",keysLength:t&&typeof t=="object"?Object.keys(t).length:0},isTargetTool:e==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",Hf(e,{timestamp:o.executionStartTime,input:t,executionId:o.executionId}));let s=this.toolRegistry.getToolInfo(e),i={timeout:n?.timeout??s?.tool?.timeoutMs??gl.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??Ko.DEFAULT,retryDelayMs:n?.retryDelayMs||Qn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(dC(),uC)),c=a.getMemoryUsageMB(),u=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${e}`,d=this.toolCircuitBreakers.get(u);d||(d=new mE(GI.FAILURE_THRESHOLD,j2),this.toolCircuitBreakers.set(u,d));let p=this.toolExecutionMetrics.get(e);return p||(p={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(e,p)),p.totalExecutions++,{finalOptions:i,startMemory:c,circuitBreaker:d,breakerKey:u,metrics:p}}async runPreparedToolExecution(e,t,n,o,s){let i=0;try{ie.debug(`[${o.functionTag}] Executing tool: ${e}`,{toolName:e,params:t,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});let a=await n.circuitBreaker.execute(async()=>$Z(async()=>Ke(this.executeToolInternal(e,t,n.finalOptions,o.hitlState),n.finalOptions.timeout,me.toolTimeout(e,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:eB,onRetry:(c,l)=>{i=c,ie.warn(`[${o.functionTag}] Retrying tool execution (attempt ${c})`,{toolName:e,error:l.message,attempt:c})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(e,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(e,t,a,n,o,s)}}async handleSuccessfulToolExecution(e,t,n,o,s){let i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;let{MemoryManager:a}=await Promise.resolve().then(()=>(dC(),uC)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&ie.warn(`Tool '${e}' used excessive memory: ${l}MB`,{toolName:e,memoryDelta:l,executionTime:i}),ie.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:e,executionTime:i,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});let u=t&&typeof t=="object"?t:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,p=d?u?.content:void 0,f=d?p?.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${e} returned isError:true`)})}catch{}ie.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:e,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});let h=WCr(f??"Unknown error"),y=`[TOOL_ERROR: ${e} failed (${h})] `;if(u&&Array.isArray(p)){let T=p.map(w=>({...w}));for(let w of T)if(w.type==="text"&&w.text){w.text=y+w.text;break}u.content=T}s.setAttribute("tool.error.message",(f??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",h),s.setStatus({code:Ie.ERROR,message:`MCP tool returned isError: ${(f??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;let x=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=x>1?(n.metrics.averageExecutionTime*x-i)/(x-1):0;let b=KCr(h);n.metrics.errorCategories[b]=(n.metrics.errorCategories[b]||0)+1}return this.emitToolEndEvent(e,o.executionStartTime,!d,t,d&&f?new Error(f):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),t}async handleFailedToolExecution(e,t,n,o,s,i){o.metrics.failedExecutions++;let a=Date.now()-s.executionStartTime;if(n instanceof bc)return ie.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${e}`,{toolName:e,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(e,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${e} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:Ie.ERROR,message:`Circuit breaker open for ${e}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" 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 c;if(n instanceof Fe)c=n;else if(n instanceof Error)if(n.message.includes("timeout"))c=me.toolTimeout(e,o.finalOptions.timeout);else if(n.message.includes("not found")){let u=await this.getAllAvailableTools();c=me.toolNotFound(e,APe(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?c=me.invalidParameters(e,n,t):n.message.includes("network")||n.message.includes("connection")?c=me.networkError(e,n):c=me.toolExecutionFailed(e,n);else c=me.toolExecutionFailed(e,new Error(String(n)));let l=c.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,c,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",c),c=new Fe({...c,context:{...c.context,executionTime:a,params:t,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),BZ(c),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(c),i.setStatus({code:Ie.ERROR,message:c.message}),c}async executeToolInternal(e,t,n,o){let s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(e),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,c=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:t,__ctx:n.authContext??this.toolExecutionContext}:t;if(a&&c){let p=c.getCachedResult(e,l);if(p!==void 0)return g.debug(`[${s}] Cache HIT for tool: ${e}`),p}let u=async p=>{if(this.mcpToolMiddlewares.length===0)return p();let f=0,h=async()=>{if(f<this.mcpToolMiddlewares.length){let y=this.mcpToolMiddlewares[f++];return y({name:e,description:"",inputSchema:{},annotations:i,execute:async()=>({})},t,{toolMeta:{name:e,annotations:i}},h)}return p()};return await h()},d=async()=>{let p=this.externalServerManager.getAllTools(),f=p.filter(y=>y.name===e&&y.isAvailable),h;if(f.length>1&&this.mcpToolRouter)try{let y={name:e,description:f[0].description??"",serverId:f[0].serverId,inputSchema:{}},x=this.mcpToolRouter.route(y);h=f.find(b=>b.serverId===x.serverId)||f[0],g.debug(`[${s}] Router selected server: ${x.serverId}`,{strategy:x.strategy,confidence:x.confidence})}catch(y){g.warn(`[${s}] Router failed, falling back to first match`,{error:y}),h=f[0]}else h=f[0];if(g.debug(`[${s}] External MCP tool search:`,{toolName:e,externalToolsCount:p.length,foundTool:!!h,isAvailable:h?.isAvailable,serverId:h?.serverId}),h&&h.isAvailable)try{ie.debug(`[${s}] Executing external MCP tool: ${e} from ${h.serverId}`);let y=await this.externalServerManager.executeTool(h.serverId,e,t,{timeout:n.timeout});return g.debug(`[${s}] External MCP tool execution successful:`,{toolName:e,serverId:h.serverId,resultType:typeof y}),y}catch(y){throw g.error(`[${s}] External MCP tool execution failed:`,{toolName:e,serverId:h.serverId,error:y instanceof Error?y.message:String(y)}),me.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)),h.serverId)}try{let y=this.toolExecutionContext||{},x=n.authContext||{},b={...y,...x,hitlState:o};g.debug("[Using merged context for unified registry tool:",{toolName:e,storedContextKeys:Object.keys(y),finalContextKeys:Object.keys(b)});let T=await this.toolRegistry.executeTool(e,t,b);if(T&&typeof T=="object"&&"success"in T&&T.success===!1){let w=T.error||"Tool execution failed",k=new Error(w);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",k)}return T}catch(y){let x=y instanceof Error?y:new Error(String(y));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",x),y instanceof Error&&y.message.includes("not found")){let b=await this.getAllAvailableTools();throw me.toolNotFound(e,b.map(T=>T.name))}throw me.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)))}};try{let p=await u(d);return a&&c&&p!==void 0&&(c.cacheResult(e,l,p),g.debug(`[${s}] Cached result for tool: ${e}`)),p}catch(p){let f=i?{name:e,description:"",annotations:i,execute:async()=>({})}:void 0;if(f&&ON(f)&&p instanceof Error&&eB(p)){g.debug(`[${s}] Tool ${e} is safe to retry, attempting once more`);try{let h=await u(d);return a&&c&&h!==void 0&&c.cacheResult(e,l,h),h}catch{}}throw p}}getToolAnnotationsForExecution(e){if(this.toolCache?.tools){let t=this.toolCache.tools.find(n=>n.name===e);if(t?.annotations)return t.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Du({name:e,description:""})}invalidateToolCache(){this.toolCache=null,g.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return g.debug("Returning available tools from cache"),this.toolCache.tools;let e=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,t=Date.now(),n=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:e,timestamp:new Date().toISOString(),getAllToolsStartTime:t,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:!!dn,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});let{MemoryManager:o}=await Promise.resolve().then(()=>(dC(),uC)),s=o.getMemoryUsageMB();try{let i=new Map,a=await this.toolRegistry.listTools();for(let y of a)if(!i.has(y.name)){let x=mP(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,x)}let c=this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0}));for(let y of c)if(!i.has(y.name)){let x=mP(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:Aa({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let l=this.toolRegistry.getToolsByCategory("in-memory");for(let y of l)if(!i.has(y.name)){let x=mP(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,x)}let u=this.externalServerManager.getAllTools();for(let y of u)if(!i.has(y.name)){let x=mP(y,{category:Aa({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let d=Array.from(i.values());ie.debug("Tool discovery results",{mcpTools:a.length,customTools:c.length,inMemoryTools:l.length,externalMCPTools:u.length,total:d.length});let f=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(f>cm.LOW_USAGE_MB&&(ie.debug(`\u{1F50D} Tool listing used ${f}MB memory (large tool registry detected)`),d.length>hZ.LARGE_TOOL_COLLECTION&&ie.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(let y of d)y.annotations||(y.annotations=Du({name:y.name,description:y.description||""}));let h=d;return this.toolCache={tools:h,timestamp:Date.now()},h}catch(i){return ie.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(e){let{MemoryManager:t}=await Promise.resolve().then(()=>(dC(),uC)),n=t.getMemoryUsageMB();e?.quiet||ie.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),e?.quiet||ie.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);let{AIProviderFactory:o}=await Promise.resolve().then(()=>(gu(),bW)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(zg(),ID)),i=["openai","bedrock","vertex","googleVertex","anthropic","azure","google-ai","huggingface","ollama","mistral","litellm"],a=zm(fl.DEFAULT_CONCURRENCY_LIMIT),c=i.map(p=>a(async()=>{let f=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()-f};if(p==="ollama")try{let T=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(hl.AUTH_MS)});if(!T.ok)throw new Error("Ollama service not responding");let w=await T.json(),k=w?.models;if(!Array.isArray(k))throw g.warn("Ollama API returned invalid models format in testProvider",{responseData:w,modelsType:typeof k}),new Error("Invalid models format from Ollama API");let C=k.filter(A=>A&&typeof A=="object"&&typeof A.name=="string");return C.length>0?{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f,model:C[0].name}:{provider:p,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-f}}catch(T){return{provider:p,status:"failed",configured:!1,authenticated:!1,error:T instanceof Error?T.message:"Ollama service not running",responseTime:Date.now()-f}}let y=5e3,x=this.testProviderConnection(p),b=new Promise((T,w)=>{setTimeout(()=>w(new Error("Provider test timeout (5s)")),y)});return await Promise.race([x,b]),{provider:p,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f}}catch(h){let y=h instanceof Error?h.message:String(h);return{provider:p,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-f}}})),l=await Promise.all(c),d=t.getMemoryUsageMB().heapUsed-n.heapUsed;return!e?.quiet&&d>20&&ie.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&t.forceGC(),l}async testProvider(e){try{return await this.testProviderConnection(e),!0}catch{return!1}}async testProviderConnection(e){let{AIProviderFactory:t}=await Promise.resolve().then(()=>(gu(),bW));await(await t.createProvider(e,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(e){let{getBestProvider:t}=await Promise.resolve().then(()=>(zg(),ID));return t(e)}async getAvailableProviders(){let{getAvailableProviders:e}=await Promise.resolve().then(()=>(zg(),ID));return e()}async isValidProvider(e){let{isValidProvider:t}=await Promise.resolve().then(()=>(zg(),ID));return t(e)}async getMCPStatus(){try{await this.initializeMCP();let e=await this.toolRegistry.listTools(),t=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,c=t.connectedServers+o.length+s.length,l=e.length+t.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:c,autoDiscoveredCount:i.length,totalTools:l,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:t.connectedServers,externalMCPFailedCount:t.failedServers,externalMCPServers:n}}catch(e){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Aa({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:e instanceof Error?e.message:String(e)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(e){try{if(e==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;let t=this.getInMemoryServers();if(t.has(e)){let o=t.get(e);return!!(o?.tools&&o.tools.length>0)}let n=this.externalServerManager.getServer(e);return n?n.status==="connected"&&n.client!==null:!1}catch(t){return ie.error(`[NeuroLink] Error testing MCP server ${e}:`,t),!1}}async hasProviderEnvVars(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Ox(),rC));try{let n=await t.checkProviderHealth(e,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return g.warn(`Provider env var check failed for ${e}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(e,t={}){let{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Ox(),rC)),o=await n.checkProviderHealth(e,t);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(e={}){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Ox(),rC));return(await t.checkAllProvidersHealth(e)).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(){let{ProviderHealthChecker:e}=await Promise.resolve().then(()=>(Ox(),rC)),t=await e.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=e.getHealthSummary(t),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(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Ox(),rC));t.clearHealthCache(e)}getToolExecutionMetrics(){let e={};for(let[t,n]of this.toolExecutionMetrics.entries())e[t]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return e}setModelAliasConfig(e){this.modelAliasConfig=e,g.info(`[ModelAlias] Configured ${Object.keys(e.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){let e={};for(let[t,n]of this.toolCircuitBreakers.entries())e[t]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return e}resetToolCircuitBreaker(e){this.toolCircuitBreakers.has(e)&&(this.toolCircuitBreakers.set(e,new mE(GI.FAILURE_THRESHOLD,j2)),ie.info(`Circuit breaker reset for tool: ${e}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),ie.info("All tool execution metrics cleared")}async getToolHealthReport(){let e={},t=0,n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(let i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(let i of o){let a=this.toolExecutionMetrics.get(i),c=`${s.get(i)||"unknown"}.${i}`,l=this.toolCircuitBreakers.get(c),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!l||l.getState()==="closed")&&u>=.8;d&&t++;let p=[],f=[];if(l&&l.getState()==="open"&&(p.push("Circuit breaker is open due to repeated failures"),f.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(p.push(`Low success rate: ${(u*100).toFixed(1)}%`),f.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(p.push("High average execution time"),f.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){let h=a.errorCategories;h.timeout>0&&(p.push(`Timeout errors: ${h.timeout}`),f.push("Consider increasing the tool timeout configuration")),h.validation>0&&(p.push(`Validation errors: ${h.validation}`),f.push("Review input schemas and parameter validation")),h.network>0&&(p.push(`Network errors: ${h.network}`),f.push("Check network connectivity and endpoint availability"))}e[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:l?.getState()||"closed",failureCount:l?.getFailureCount()||0},issues:p,recommendations:f}}return{totalTools:o.size,healthyTools:t,unhealthyTools:o.size-t,tools:e}}async ensureConversationMemoryInitialized(){try{let e=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(e){return g.error("Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e)}),!1}}async getConversationStats(){let e=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(e){let t=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Fe({code:ut.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});try{let n=await this.conversationMemory.buildContextMessages(e);return g.debug("Retrieved conversation history",{sessionId:e,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return g.error("Failed to retrieve conversation history",{sessionId:e,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(e){let t=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(e),await this.conversationMemory.clearSession(e)}async clearAllConversations(){let e=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async storeToolExecutions(e,t,n,o,s){let i=n&&n.length>0||o&&o.length>0;if(!i){g.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}let a=this.conversationMemory;try{await a.storeToolExecution(e,t,n,o,s)}catch(c){g.warn("Failed to store tool executions",{sessionId:e,userId:t,error:c instanceof Error?c.message:String(c)})}}isToolExecutionStorageAvailable(){let e=process.env.STORAGE_TYPE==="redis",t=this.conversationMemory&&this.conversationMemory.constructor.name==="RedisConversationMemoryManager";return!!(e&&t)}async getSessionMessages(e,t){let n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Fe({code:ut.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});return await this.conversationMemory.getSessionMessages(e,t)}async setSessionMessages(e,t,n){let o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new Fe({code:ut.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});await this.conversationMemory.setSessionMessages(e,t,n)}async modifyLastAssistantMessage(e,t,n){let o=await this.getSessionMessages(e,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:t(o[s].content)},await this.setSessionMessages(e,o,n),!0;return!1}async addExternalMCPServer(e,t){this.invalidateToolCache();try{ie.info(`[NeuroLink] Adding external MCP server: ${e}`,{command:t.command,transport:t.transport});let n=await this.externalServerManager.addServer(e,t);if(n.success){if(ie.info(`[NeuroLink] External MCP server added successfully: ${e}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){let o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new Ix({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(let s of o)this.mcpToolRouter.registerServer(s.id||e);g.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(e)}this.emitter.emit("externalMCP:serverAdded",{serverId:e,serverName:t.name||e,config:t,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else ie.error(`[NeuroLink] Failed to add external MCP server: ${e}`,{error:n.error,transport:t.transport,command:t.command,url:t.url?mr(t.url):void 0});return n}catch(n){throw ie.error(`[NeuroLink] Error adding external MCP server: ${e}`,n),n}}async removeExternalMCPServer(e){this.invalidateToolCache();try{ie.info(`[NeuroLink] Removing external MCP server: ${e}`);let t=this.externalServerManager.getServerName(e),n=await this.externalServerManager.removeServer(e);return n.success?(ie.info(`[NeuroLink] External MCP server removed successfully: ${e}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:e,serverName:t,timestamp:Date.now()})):n.error?.includes("not found")?ie.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${e}`):ie.error(`[NeuroLink] Failed to remove external MCP server: ${e}`,{error:n.error}),n}catch(t){throw ie.error(`[NeuroLink] Error removing external MCP server: ${e}`,t),t}}listExternalMCPServers(){let e=this.externalServerManager.getServerStatuses(),t=this.externalServerManager.listServers();return e.map(n=>{let o=t.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(e){return this.externalServerManager.getServer(e)}async executeExternalMCPTool(e,t,n,o){try{ie.debug(`[NeuroLink] Executing external MCP tool: ${t} on ${e}`);let s=this.getToolAnnotationsForExecution(t),i=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,a={__serverId:e,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}};if(i&&this.mcpToolResultCache){let d=this.mcpToolResultCache.getCachedResult(t,a);if(d!==void 0)return ie.debug(`[NeuroLink] Tool result cache HIT: ${t} on ${e}`),d}let c=await this.externalServerManager.executeTool(e,t,n,o),l=c&&typeof c=="object"?c:void 0,u=!!(l&&"isError"in l&&l.isError===!0||l&&"success"in l&&l.success===!1);return i&&this.mcpToolResultCache&&!u&&c!==void 0&&this.mcpToolResultCache.cacheResult(t,a,c),ie.debug(`[NeuroLink] External MCP tool ${u?"returned error":"executed successfully"}: ${t}`),c}catch(s){throw ie.error(`[NeuroLink] External MCP tool execution failed: ${t}`,s),s}}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(e){return this.externalServerManager.getServerTools(e)}async testExternalMCPConnection(e){try{let{MCPClientFactory:t}=await Ke(Promise.resolve().then(()=>(r3(),Aqe)),1e4),n=await t.testConnection(e,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{ie.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),ie.info("[NeuroLink] All external MCP servers shut down successfully")}catch(e){throw ie.error("[NeuroLink] Error shutting down external MCP servers:",e),e}}async getElicitationManager(){return(await Ke(Promise.resolve().then(()=>(pme(),mKe)),1e4)).globalElicitationManager}async registerElicitationHandler(e){(await this.getElicitationManager()).registerHandler(e)}async getMultiServerManager(){return(await Ke(Promise.resolve().then(()=>(SH(),$Ve)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){let e=await Ke(Promise.resolve().then(()=>(wH(),BVe)),1e4);return new e.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ke(Promise.resolve().then(()=>(hme(),fKe)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(e,t){return(await Ke(Promise.resolve().then(()=>(CW(),bme)),1e4)).exposeAgentAsTool(e,t)}async exposeWorkflowAsTool(e,t){return(await Ke(Promise.resolve().then(()=>(CW(),bme)),1e4)).exposeWorkflowAsTool(e,t)}async getToolIntegrationManager(){return(await Ke(Promise.resolve().then(()=>(Rme(),gKe)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(e,t={}){let n=await Ke(Promise.resolve().then(()=>(PW(),Ume)),1e4),o=e.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,t)}async convertToolsFromMCPFormat(e,t={}){return(await Ke(Promise.resolve().then(()=>(PW(),Ume)),1e4)).batchConvertToNeuroLink(e,t)}async getToolAnnotations(e){let{inferAnnotations:t,mergeAnnotations:n,getAnnotationSummary:o}=await Ke(Promise.resolve().then(()=>(Sk(),FVe)),1e4),s=this.toolRegistry.getToolInfo(e);if(!s)return null;let i=s.tool.annotations,a=t({name:s.tool.name,description:s.tool.description??""}),c=n(a,i);return{annotations:c,summary:o(c)}}convertExternalMCPToolsToAISDKFormat(){let e=this.externalServerManager.getAllTools(),t={};for(let n of e)if(n.isAvailable){let o={description:n.description,execute:async s=>{try{ie.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});let i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return ie.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw ie.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};t[n.name]=o,ie.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return ie.info(`[NeuroLink] Converted ${Object.keys(t).length} external MCP tools to AI SDK format`),t}convertJSONSchemaToAISDKFormat(e){}unregisterExternalMCPToolsFromRegistry(e){try{let t=this.externalServerManager.getServerTools(e);for(let n of t)this.toolRegistry.removeTool(n.name),ie.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(t){ie.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${e}:`,t)}}unregisterExternalMCPToolFromRegistry(e){try{this.toolRegistry.removeTool(e),ie.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${e}`)}catch(t){ie.error(`[NeuroLink] Failed to unregister external MCP tool ${e} from registry:`,t)}}async lazyInitializeConversationMemory(e,t,n){try{let{initializeConversationMemory:o}=await TKe().then(()=>bKe),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw g.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,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{let e=this.externalServerManager.getAllTools();for(let t of e)this.toolRegistry.removeTool(t.name);ie.debug(`[NeuroLink] Unregistered ${e.length} external MCP tools from main registry`)}catch(e){ie.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",e)}}async createEvaluationPipeline(e){let{EvaluationPipeline:t,getPreset:n}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4)),o;typeof e=="string"?o=n(e):o=e;let s=new t(o);return await Ke(s.initialize(),3e4,me.evaluationTimeout("pipeline initialization",3e4)),g.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(e,t){let{EvaluationPipeline:n,getPreset:o}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4)),s;if(t?.pipeline&&t?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(t?.scorers&&t.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.");t?.pipeline?s={...o(t.pipeline)}:t?.scorers&&t.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:t.scorers.map(l=>({id:l})),executionMode:t.executionMode??"parallel",passThreshold:t.passThreshold??.7}:s=o("quality"),t?.passThreshold!==void 0&&(s.passThreshold=t.passThreshold),t?.executionMode!==void 0&&(s.executionMode=t.executionMode);let i=new n(s);await Ke(i.initialize(),3e4,me.evaluationTimeout("pipeline initialization",3e4));let a=t?.timeoutMs??6e4,c=await Ke(i.execute(e,{correlationId:t?.correlationId}),a,me.evaluationTimeout("pipeline execution",a));return g.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:c.overallScore,passed:c.passed,scorerCount:c.scores.length}),c}async score(e,t,n){let{ScorerRegistry:o}=await Ke(Promise.resolve().then(()=>(CB(),T7)),1e4,me.evaluationTimeout("scorer module load",1e4));await Ke(o.registerBuiltInScorers(),3e4,me.evaluationTimeout("scorer bootstrap",3e4));let s=await Ke(o.getScorer(e,n),3e4,me.evaluationTimeout(`scorer load: ${e}`,3e4));if(!s)throw me.scorerNotFound(e);let i=s.validateInput(t);if(!i.valid)throw me.evaluationValidationFailed(e,i.errors);let a=await Ke(s.score(t),6e4,me.evaluationTimeout("scorer execution",6e4));return g.debug("[NeuroLink] Scoring completed",{scorerId:e,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(e){let{ScorerRegistry:t}=await Ke(Promise.resolve().then(()=>(CB(),T7)),1e4,me.evaluationTimeout("scorer module load",1e4));await Ke(t.registerBuiltInScorers(),3e4,me.evaluationTimeout("scorer bootstrap",3e4));let n=t.list();return e?.category&&(n=n.filter(o=>o.category===e.category)),e?.type&&(n=n.filter(o=>o.type===e.type)),n}async getEvaluationPresets(){let{getPresetNames:e}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4));return e()}async getEvaluationPreset(e){let{getPreset:t}=await Ke(Promise.resolve().then(()=>(xE(),tP)),1e4,me.evaluationTimeout("evaluation module load",1e4));return t(e)}async createAgent(e){let{Agent:t}=await Promise.resolve().then(()=>(OW(),SKe));return g.debug("[NeuroLink] Creating agent",{id:e.id,name:e.name,tools:e.tools?.length||0}),new t(e,this)}async createNetwork(e){let{AgentNetwork:t}=await Promise.resolve().then(()=>(Bme(),wKe));return g.debug("[NeuroLink] Creating agent network",{name:e.name,agentCount:e.agents.length,workflowCount:e.workflows?.length||0,toolCount:e.tools?.length||0}),new t(e,this)}async executeNetwork(e,t,n){return g.debug("[NeuroLink] Executing agent network",{networkId:e.id,networkName:e.name,hasContext:!!t.context}),e.execute(t,n)}async*streamNetwork(e,t,n){g.debug("[NeuroLink] Streaming agent network",{networkId:e.id,networkName:e.name,hasContext:!!t.context}),yield*e.stream(t,n)}async createOrchestrator(e){let{NetworkOrchestrator:t}=await Promise.resolve().then(()=>(Gme(),kKe));return g.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:e?.maxConcurrentExecutions,defaultMode:e?.defaultMode}),new t(this,e)}async createCoordinator(e){let{AgentCoordinator:t}=await Promise.resolve().then(()=>(Vme(),AKe));return g.debug("[NeuroLink] Creating agent coordinator",{strategy:e?.strategy,maxConcurrency:e?.maxConcurrency}),new t(e)}async createMessageBus(e){let{MessageBus:t}=await Promise.resolve().then(()=>(qme(),IKe));return g.debug("[NeuroLink] Creating message bus",{maxHistorySize:e?.maxHistorySize}),new t(e)}async dispose(){g.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();let e=[];try{try{g.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await hO(),await yO(),g.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`OpenTelemetry shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down OpenTelemetry:",t)}if(this.externalServerManager)try{g.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),g.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`External server shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down external MCP servers:",t)}if(this.emitter)try{g.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),g.clearEventEmitter(),g.debug("[NeuroLink] Event listeners removed successfully")}catch(t){let n=t instanceof Error?t:new Error(`Event emitter cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error removing event listeners:",t)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{g.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),g.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Circuit breaker cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing circuit breakers:",t)}try{g.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=[],g.debug("[NeuroLink] Maps and caches cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Cache cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing caches:",t)}if(this._taskManager)try{g.debug("[NeuroLink] Shutting down TaskManager..."),await Ke(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(t){g.warn("[NeuroLink] TaskManager shutdown error:",t)}finally{this._taskManager=void 0}try{g.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,g.debug("[NeuroLink] Initialization state reset successfully")}catch(t){let n=t instanceof Error?t:new Error(`State reset error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error resetting state:",t)}e.length===0?g.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):g.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${e.length} errors`,{errors:e.map(t=>t.message)})}catch(t){throw g.error("[NeuroLink] Critical error during disposal:",t),t}}getToolRegistry(){return this.toolRegistry}async compactSession(e,t){if(!this.conversationMemory)return null;let n=await this.conversationMemory.buildContextMessages(e);if(!n||n.length===0)return null;let o=new bx({...t,summarizationProvider:t?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:t?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=Qc({provider:t?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&xk(a.messages),a}async getContextStats(e,t,n){if(!this.conversationMemory)return null;let o=await this.conversationMemory.buildContextMessages(e);if(!o||o.length===0)return null;let s=Qc({provider:t||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(e,t,n){if(!this.conversationMemory)return!1;let o=this.conversationMemory.getSession?.(e);return o?Qc({provider:t||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(e){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(e)}async initializeAuthProviderFromConfig(e){let t,n;if("authenticateToken"in e&&typeof e.authenticateToken=="function")t=e,n=t.type;else if("provider"in e)t=e.provider,n=t.type;else{let o=e,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(JD(),PKe));t=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=t,g.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:t.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;let e=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(e),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===e)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(e){let{globalAuthContext:t}=await Promise.resolve().then(()=>(qk(),d3));t.set(e),g.debug("Auth context set",{userId:e.user.id,provider:e.provider,sessionId:e.session?.id})}async getAuthContext(){let{getAuthContext:e}=await Promise.resolve().then(()=>(qk(),d3));return e()}async clearAuthContext(){let{globalAuthContext:e}=await Promise.resolve().then(()=>(qk(),d3)),t=e.get()?.user.id;e.clear(),t&&g.debug(`Auth context cleared for user: ${t}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(e,t){return{requestContext:t||{},signal:e}}async resolveDynamicOptions(e){let t=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(t.some(s=>typeof e[s]=="function")||typeof e.tools=="function"))return;let o=e.dynamicContext;await this.resolveDynamicFields(e,t,o)}async resolveDynamicFields(e,t,n){let o=this.buildResolutionContext(e.abortSignal,n);if(g.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(t.map(async s=>{if(typeof e[s]=="function"){let i=await tde(e[s],o);e[s]=i.value,g.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof e.tools=="function"){let s=await tde(e.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);e.enabledToolNames=s.value,delete e.tools}}},MKe=new rS,XCr=MKe});var NKe={};ee(NKe,{VoyageProvider:()=>UW,default:()=>eRr});var ZCr,OKe,QCr,Jme,UW,eRr,DKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();It();W();po();ZCr="https://api.voyageai.com/v1",OKe=6e4,QCr=()=>Mr(D$e()),Jme=()=>Or("VOYAGE_MODEL","voyage-3.5"),UW=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"voyage",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:QCr(),this.baseURL=o?.baseURL??process.env.VOYAGE_BASE_URL??ZCr,this.proxyFetch=vt(),g.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Jme()}supportsTools(){return!1}getDefaultEmbeddingModel(){return Jme()}getAISDKModel(){throw new Ve("Voyage AI is an embedding-only provider; chat completions are not available. Use `embed()` or `embedMany()` instead, or pick a different provider for `generate()` / `stream()`.","voyage")}async executeStream(e,t){throw new Ve("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new Mt("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Zt(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new Ve(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Ve("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];let n=128,o=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),a=await this.callEmbeddings(i,t);o.push(...a)}return o}async callEmbeddings(e,t){let n=t??this.modelName,o;try{o=await Ke(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n})}),OKe,new Ve(`Voyage embeddings request timed out after ${OKe/1e3}s`,"voyage"))}catch(a){throw a instanceof Ve?a:this.formatProviderError(a)}if(!o.ok){let a=await o.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${o.status} \u2014 ${a}`))}let s=await o.json();if(!s.data||s.data.length===0)throw new Ve("Voyage embeddings response missing data","voyage");if(s.data.length!==e.length)throw new Ve(`Voyage embeddings response count mismatch: expected ${e.length}, got ${s.data.length}`,"voyage");let i=s.data.slice().sort((a,c)=>a.index-c.index);for(let a=0;a<i.length;a++)if(i[a].index!==a)throw new Ve(`Voyage embeddings response has unexpected index ordering: position ${a} has index ${i[a].index}`,"voyage");return i.map(a=>a.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Jme(),baseURL:this.baseURL}}},eRr=UW});var LKe={};ee(LKe,{JinaProvider:()=>$W,default:()=>nRr});var tRr,FW,rRr,Yme,$W,nRr,UKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();W();po();tRr="https://api.jina.ai/v1",FW=6e4,rRr=()=>Mr(L$e()),Yme=()=>Or("JINA_MODEL","jina-embeddings-v3"),$W=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"jina",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:rRr(),this.baseURL=o?.baseURL??process.env.JINA_BASE_URL??tRr,this.proxyFetch=vt(),g.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Yme()}supportsTools(){return!1}getDefaultEmbeddingModel(){return Yme()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mt("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Zt(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new Ve(`Jina AI error: ${t}`,"jina")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Error("Jina AI returned no embedding for the provided text");return n[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,n={}){if(t.length===0)return[];let o=n.model??"jina-reranker-v2-base-multilingual",s=n.credentials,i=s?.apiKey?.trim()||this.apiKey,a=s?.baseURL||this.baseURL,c=new AbortController,l=setTimeout(()=>c.abort(),FW),u;try{u=await this.proxyFetch(`${a}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({model:o,query:e,documents:t,top_n:n.topN??t.length}),signal:c.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${FW/1e3}s`)):this.formatProviderError(p)}finally{clearTimeout(l)}if(!u.ok){let p=await u.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${u.status} \u2014 ${p}`))}return((await u.json()).results??[]).map(p=>({index:p.index,score:p.relevance_score,document:t[p.index]??p.document?.text??""}))}async callEmbeddings(e,t,n){let o=t??this.modelName,s=n?.apiKey?.trim()||this.apiKey,i=n?.baseURL||this.baseURL,a=new AbortController,c=setTimeout(()=>a.abort(),FW),l;try{l=await this.proxyFetch(`${i}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:o}),signal:a.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${FW/1e3}s`)):this.formatProviderError(p)}finally{clearTimeout(c)}if(!l.ok){let p=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${p}`))}let u=await l.json();if(!u.data||u.data.length===0)throw new Error("Jina embeddings response missing data");if(u.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${u.data.length}`);let d=u.data.slice().sort((p,f)=>p.index-f.index);for(let p=0;p<d.length;p++)if(d[p].index!==p)throw new Error(`Jina embeddings response has unexpected index ordering: position ${p} has index ${d[p].index}`);return d.map(p=>p.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Yme(),baseURL:this.baseURL}}},nRr=$W});var BKe={};ee(BKe,{StabilityProvider:()=>BW,default:()=>iRr});var oRr,FKe,sRr,$Ke,BW,iRr,zKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();W();po();oRr="https://api.stability.ai",FKe=12e4,sRr=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,$Ke=()=>Or("STABILITY_MODEL","stable-image-ultra"),BW=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"stability",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:sRr(),this.baseURL=o?.baseURL??process.env.STABILITY_BASE_URL??oRr,this.proxyFetch=vt(),g.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return $Ke()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mt("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new Ve("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Zt(`Stability AI model '${this.modelName}' not found. Use stable-image-ultra, stable-image-core, sd3.5-large, sd3.5-large-turbo, or sd3.5-medium.`,"stability"):new Ve(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.stability,o=n?.apiKey?.trim()||this.apiKey;if(!o)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");let s=o,i=n?.baseURL||this.baseURL,a=e.prompt??e.input?.text??"";if(!a.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");let c=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,u=new FormData;u.append("prompt",a),u.append("output_format","png"),l.aspectRatio&&u.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&u.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&u.append("model",this.modelName),l.seed!==void 0&&u.append("seed",String(l.seed));let d=new AbortController,p=setTimeout(()=>d.abort(),FKe),f;try{f=await this.proxyFetch(`${i}/v2beta/stable-image/generate/${c}`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/json"},body:u,signal:d.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${FKe/1e3}s`)):this.formatProviderError(x)}finally{clearTimeout(p)}if(!f.ok){let x=await f.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${f.status} \u2014 ${x}`))}let h=await f.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);let y=Date.now()-t;return g.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:$Ke(),baseURL:this.baseURL}}},iRr=BW});var VKe={};ee(VKe,{IdeogramProvider:()=>zW,default:()=>lRr});var aRr,jKe,cRr,GKe,zW,lRr,qKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();W();po();aRr="https://api.ideogram.ai",jKe=12e4,cRr=()=>Mr(U$e()),GKe=()=>Or("IDEOGRAM_MODEL","V_3"),zW=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"ideogram",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:cRr(),this.baseURL=o?.baseURL??process.env.IDEOGRAM_BASE_URL??aRr,this.proxyFetch=vt(),g.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return GKe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mt("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new Ve("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new Ve(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.ideogram,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");let a=e,c={prompt:i,model:this.modelName,magic_prompt:a.magicPrompt??"AUTO"};a.aspectRatio&&(c.aspect_ratio=a.aspectRatio),a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.seed!==void 0&&(c.seed=a.seed),a.style&&(c.style_type=a.style);let l=new AbortController,u=setTimeout(()=>l.abort(),jKe),d;try{d=await this.proxyFetch(`${s}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":o,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(k){throw k instanceof Error&&k.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${jKe/1e3}s`)):this.formatProviderError(k)}finally{clearTimeout(u)}if(!d.ok){let k=await d.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${d.status} \u2014 ${k}`))}let f=(await d.json()).data?.[0]?.url;if(!f)throw new Error("Ideogram returned no image URL");let h=new AbortController,y=setTimeout(()=>h.abort(),6e4),x;try{x=await this.proxyFetch(f,{signal:h.signal})}catch(k){throw k instanceof Error&&k.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:k}):k}finally{clearTimeout(y)}if(!x.ok)throw new Error(`Failed to download Ideogram image: ${x.status}`);let b=Buffer.from(await x.arrayBuffer()),T=b.toString("base64"),w=Date.now()-t;return g.info(`[IdeogramProvider] Generated image (${b.length} bytes) in ${w}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:T}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:GKe(),baseURL:this.baseURL}}},lRr=zW});function Od(r){let e=(r?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return e?{apiToken:e,baseUrl:(r?.baseUrl??process.env.REPLICATE_BASE_URL??uRr).replace(/\/$/,"")}:null}var uRr,YD=_(()=>{"use strict";uRr="https://api.replicate.com"});function pRr(r,e,t){return new Nte({connect:{lookup:(n,o,s)=>{if(n.toLowerCase()!==r.toLowerCase()){s(new Error(`safeFetch: refusing to resolve "${n}" \u2014 expected "${r}"`),"",0);return}if(o?.all){s(null,[{address:e,family:t}]);return}s(null,e,t)}}})}async function zx(r,e){let{url:t,ip:n,family:o}=await Q$e(r),i=new URL(t).hostname.replace(/^\[|\]$/g,""),a=pRr(i,n,o),c=new AbortController,l=setTimeout(()=>c.abort(),e.timeoutMs??dRr),u=e.signal?AbortSignal.any([e.signal,c.signal]):c.signal,d;try{d=await Ote(t,{method:"GET",signal:u,redirect:"manual",dispatcher:a})}finally{clearTimeout(l),a.close().catch(()=>{})}if(d.status>=300&&d.status<400)throw new Error(`safeDownload(${e.label}): refused to follow redirect ${d.status} \u2192 ${d.headers.get("location")??"<no-location>"} (for ${r})`);if(!d.ok)throw new Error(`safeDownload(${e.label}) failed: HTTP ${d.status} for ${r}`);return Ha(d,e.maxBytes,e.label)}var dRr,XD=_(()=>{"use strict";zE();vg();cx();dRr=6e4});async function gRr(r,e){let t=r.baseUrl??"https://api.replicate.com",[n,o]=e.model.split(":",2),s=o?`${t}/v1/predictions`:`${t}/v1/models/${n}/predictions`,i=o?{version:o,input:e.input}:{input:e.input};e.webhook&&(i.webhook=e.webhook),e.webhookEventsFilter&&e.webhookEventsFilter.length>0&&(i.webhook_events_filter=e.webhookEventsFilter);let a=new AbortController,c=setTimeout(()=>a.abort(),ZD),l;try{l=await fetch(s,{method:"POST",headers:{Authorization:`Token ${r.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(i),signal:a.signal})}catch(u){throw u instanceof Fe?u:u instanceof Error&&u.name==="AbortError"?new Fe({code:ut.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${ZD/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:u}):u}finally{clearTimeout(c)}if(!l.ok){let u=await l.text();throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${l.status} \u2014 ${Ms(u,500)}`,category:"network",severity:"high",retriable:l.status>=500})}return await l.json()}async function hRr(r,e,t={}){let n=r.baseUrl??"https://api.replicate.com",o=Date.now(),s=t.timeoutMs??fRr,i=t.pollIntervalMs??mRr;for(;Date.now()-o<s;){if(t.abortSignal?.aborted)throw new Fe({code:ut.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});let a=new AbortController,c=setTimeout(()=>a.abort(),ZD),l=()=>a.abort();t.abortSignal?.addEventListener("abort",l,{once:!0});let u;try{u=await fetch(`${n}/v1/predictions/${e}`,{method:"GET",headers:{Authorization:`Token ${r.apiToken}`},signal:a.signal})}catch(p){throw p instanceof Fe?p:p instanceof Error&&p.name==="AbortError"?t.abortSignal?.aborted?new Fe({code:ut.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:p}):new Fe({code:ut.OPERATION_ABORTED,message:`Replicate poll request timed out after ${ZD/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:p}):p}finally{t.abortSignal?.removeEventListener("abort",l),clearTimeout(c)}if(!u.ok){let p=await u.text();throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${u.status} \u2014 ${Ms(p,500)}`,category:"network",severity:"high",retriable:u.status>=500})}let d=await u.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((p,f)=>{let h=()=>{clearTimeout(y),f(new Fe({code:ut.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},y=setTimeout(()=>{t.abortSignal?.removeEventListener("abort",h),p()},i);t.abortSignal?.addEventListener("abort",h,{once:!0})})}throw new Fe({code:ut.OPERATION_ABORTED,message:`Replicate prediction ${e} did not complete within ${Math.round(s/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function Wg(r,e,t={}){let n=await gRr(r,e);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return hRr(r,n.id,t)}async function jx(r,e=268435456){let t=r.output,n=Array.isArray(t)?t[0]:t;if(typeof n!="string")throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${r.id} output is not a URL: ${typeof t}`,category:"execution",severity:"high",retriable:!1});try{let o=await zx(n,{maxBytes:e,label:`Replicate prediction ${r.id}`,timeoutMs:ZD});return g.debug(`[Replicate] Downloaded prediction ${r.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof Fe)throw o;let s=o instanceof Error?o.message:String(o);throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${s} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var ZD,mRr,fRr,QD=_(()=>{"use strict";W();It();Pn();XD();ZD=9e4,mRr=2e3,fRr=5*6e4});var WKe={};ee(WKe,{ReplicateProvider:()=>jW,default:()=>vRr});function yRr(r){let e=r,t=e.prompt??e.input?.text??"",n=e.systemPrompt;return n?`${n}
|
|
2207
2207
|
|
|
2208
2208
|
${t}`:t}function xRr(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:"").join(""):""}var HKe,jW,vRr,KKe=_(async()=>{"use strict";Cu();YD();QD();await $p();W();It();po();HKe=()=>Or("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct");jW=class extends uo{apiToken;baseURL;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"replicate",s);let i=o?.apiToken?.trim();this.apiToken=i&&i.length>0?i:Mr(P$e()),this.baseURL=o?.baseUrl,g.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return HKe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Replicate routes through the predictions API, not the AI SDK chat models. Streaming uses the predict-then-stream path inside executeStream.")}async generate(e,t){let n=typeof e=="string"?{prompt:e}:e,{IMAGE_GENERATION_MODELS:o}=await Promise.resolve().then(()=>(ga(),Ike));if(n.output?.mode==="video"||n.output?.mode==="avatar"||n.output?.mode==="music")return super.generate(n,t);let s=o.some(p=>this.modelName.includes(p)),i=n.output?.format==="json"||n.output?.format==="structured"||n.output?.format==="text";if(s&&!i)return super.generate(n,t);if(n.output?.format==="json"||n.output?.format==="structured"||t!=null)throw new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:"Replicate models do not support structured-output / JSON schema. Remove output.format or _analysisSchema, or use a provider that implements the OpenAI chat-completions contract (e.g. openai, anthropic).",category:"validation",severity:"medium",retriable:!1});let a=n.prompt??n.input?.text??"",c=Date.now(),l=await this.executeStream({input:{text:a},systemPrompt:n.systemPrompt,maxTokens:n.maxTokens,temperature:n.temperature,abortSignal:n.abortSignal,timeout:n.timeout}),u="";for await(let p of l.stream)"content"in p&&typeof p.content=="string"&&(u+=p.content);let d={content:u,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}};return g.info(`[ReplicateProvider] generate() complete in ${Date.now()-c}ms \u2014 ${u.length} chars`),d}async executeStream(e,t){let n=Date.now(),o=e.credentials?.replicate,s=o?.apiToken?.trim()||this.apiToken,i=o?.baseUrl||this.baseURL,a=Od({apiToken:s,baseUrl:i});if(!a)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let c=yRr(e);if(!c.trim())throw new Fe({code:ut.INVALID_PARAMETERS,message:"Replicate predictions require a prompt (input.text or prompt)",category:"validation",severity:"medium",retriable:!1});let l={prompt:c,...e.maxTokens!==void 0&&{max_new_tokens:e.maxTokens},temperature:e.temperature,top_p:1},u;try{u=await Wg(a,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let d=xRr(u.output);if(!d)throw new Error(`Replicate prediction ${u.id} returned empty output`);let p={async*[Symbol.asyncIterator](){yield{content:d}}};return g.info(`[ReplicateProvider] Generated ${d.length} chars in ${Date.now()-n}ms \u2014 model ${this.modelName} (prediction ${u.id})`),{stream:p,provider:this.providerName,model:this.modelName,finishReason:"stop",metadata:{startTime:n,streamId:`replicate-${u.id}`}}}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.replicate,o=n?.apiToken?.trim()||this.apiToken,s=n?.baseUrl||this.baseURL,i=Od({apiToken:o,baseUrl:s});if(!i)throw new Fe({code:ut.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let a=e.prompt??e.input?.text??"";if(!a.trim())throw new Fe({code:ut.INVALID_PARAMETERS,message:"Replicate image-gen requires a prompt",category:"validation",severity:"medium",retriable:!1});let c=e,l={prompt:a,output_format:"png"};c.aspectRatio&&(l.aspect_ratio=c.aspectRatio),c.negativePrompt&&(l.negative_prompt=c.negativePrompt),c.seed!==void 0&&(l.seed=c.seed);let u;try{u=await Wg(i,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let d;try{d=await jx(u,26214400)}catch(f){throw this.handleProviderError(f)}let p=d.toString("base64");return g.info(`[ReplicateProvider] Generated image (${d.length} bytes) in ${Date.now()-t}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0},imageOutput:{base64:p}}}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error",n=e instanceof Error?e:void 0;return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.toLowerCase().includes("invalid token")?new Fe({code:ut.PROVIDER_AUTH_FAILED,message:"Invalid Replicate API token. Get one at https://replicate.com/account/api-tokens",category:"configuration",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("402")||t.toLowerCase().includes("insufficient credit")?new Fe({code:ut.PROVIDER_QUOTA_EXCEEDED,message:"Replicate insufficient credit. Top up at https://replicate.com/account/billing \u2014 most image/music models require a paid balance.",category:"resource",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("429")||t.toLowerCase().includes("rate limit")?new Fe({code:ut.PROVIDER_QUOTA_EXCEEDED,message:"Replicate rate limit exceeded. Back off and retry.",category:"resource",severity:"high",retriable:!0,context:{provider:"replicate"},originalError:n}):t.toLowerCase().includes("not found")||t.includes("404")?new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate model '${this.modelName}' not found. Use owner/name or owner/name:version format. Browse https://replicate.com/explore`,category:"validation",severity:"medium",retriable:!1,context:{provider:"replicate",model:this.modelName},originalError:n}):new Fe({code:ut.PROVIDER_NOT_AVAILABLE,message:`Replicate error: ${t}`,category:"execution",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n})}async validateConfiguration(){return typeof this.apiToken=="string"&&this.apiToken.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:HKe(),baseURL:this.baseURL}}},vRr=jW});var XKe={};ee(XKe,{RecraftProvider:()=>GW,default:()=>SRr});var bRr,JKe,TRr,YKe,GW,SRr,ZKe=_(async()=>{"use strict";Cu();await $p();wo();Nt();W();po();vg();cx();bRr="https://external.api.recraft.ai/v1",JKe=12e4,TRr=()=>Mr(F$e()),YKe=()=>Or("RECRAFT_MODEL","recraftv3"),GW=class extends uo{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Bu(t)?t:void 0;super(e,"recraft",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:TRr(),this.baseURL=o?.baseURL??process.env.RECRAFT_BASE_URL??bRr,this.proxyFetch=vt(),g.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return YKe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Recraft is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Recraft is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mt("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new er("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new Zt(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new Ve(`Recraft error: ${t}`,"recraft")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.recraft,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");let a=e,c={model:e.model??this.modelName,prompt:i,n:1,response_format:"b64_json"};a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.style&&(c.style=a.style),a.styleId&&(c.style_id=a.styleId),a.size&&(c.size=a.size);let l=new AbortController,u=setTimeout(()=>l.abort(),JKe),d;try{d=await this.proxyFetch(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${JKe/1e3}s`)):this.formatProviderError(x)}finally{clearTimeout(u)}if(!d.ok){let x=await d.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${d.status} \u2014 ${x}`))}let f=(await d.json()).data?.[0];if(!f)throw new Error("Recraft returned no image data");let h;if(f.b64_json)h=f.b64_json;else if(f.url){await Bl(f.url);let x=new AbortController,b=setTimeout(()=>x.abort(),6e4),T;try{T=await this.proxyFetch(f.url,{signal:x.signal})}catch(k){throw k instanceof Error&&k.name==="AbortError"?new Error("Recraft image download timed out after 60s",{cause:k}):k}finally{clearTimeout(b)}if(!T.ok)throw new Error(`Failed to download Recraft image: ${T.status}`);h=(await Ha(T,26214400,"Recraft image")).toString("base64")}else throw new Error("Recraft response missing both b64_json and url");let y=Date.now()-t;return g.info(`[RecraftProvider] Generated image (${h.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:YKe(),baseURL:this.baseURL}}},SRr=GW});var kC,sc,efo,tfo,rfo,nfo,ofo,sfo,ifo,afo,cfo,lfo,ufo,QKe,dfo,pfo,mfo,ffo,gfo,hfo,yfo,xfo,vfo,bfo,Tfo,Sfo,wfo,Efo,_fo,kfo,Cfo,Rfo,Afo,Ifo,Pfo,Mfo,Ofo,Nfo,Dfo,Lfo,Ufo,Ffo,$fo,Bfo,zfo,jfo,Gfo,e6e=_(()=>{kC={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:kC.get}):new Proxy(function(...t){return new Proxy({},{get:kC.get})},{get:kC.get,apply(t,n,o){return new Proxy({},{get:kC.get})},construct(t,n){return new Proxy({},{get:kC.get})}})}},sc=new Proxy({},kC),{BedrockClient:efo,ListFoundationModelsCommand:tfo,BedrockRuntimeClient:rfo,ConverseCommand:nfo,ConverseStreamCommand:ofo,ImageFormat:sfo}=sc,{SageMakerRuntimeClient:ifo,InvokeEndpointCommand:afo,InvokeEndpointWithResponseStreamCommand:cfo}=sc,{GoogleAuth:lfo,VertexAI:ufo,TextToSpeechClient:QKe}=sc,{Webhook:dfo}=sc,{Hippocampus:pfo,HippocampusConfig:mfo}=sc,{createClient:ffo}=sc,{Queue:gfo,Worker:hfo,Job:yfo,QueueScheduler:xfo,FlowProducer:vfo}=sc,{Cron:bfo}=sc,{parseBuffer:Tfo,selectCover:Sfo}=sc,{extractRawText:wfo,convertToHtml:Efo}=sc,{Hono:_fo}=sc,{cors:kfo,HTTPException:Cfo,logger:Rfo,secureHeaders:Afo,streamSSE:Ifo,timeout:Pfo}=sc,Mfo=globalThis.fetch,Ofo=globalThis.Request,Nfo=globalThis.Response,Dfo=globalThis.Headers,Lfo=globalThis.FormData,Ufo=globalThis.File,Ffo=globalThis.Blob,$fo=sc.Agent,Bfo=sc.Pool,zfo=sc.Client,jfo=sc.Dispatcher,Gfo=sc.MockAgent});var t6e={};ee(t6e,{GoogleTTSHandler:()=>sS});var sS,VW=_(()=>{"use strict";e6e();ha();W();yo();sS=class r{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=r.DEFAULT_MAX_TEXT_LENGTH;constructor(e){let t=e??process.env.GOOGLE_APPLICATION_CREDENTIALS;t&&(this.client=new QKe({keyFilename:t}))}isConfigured(){return this.client!==null}async getVoices(e){if(!this.client)throw new qt({code:pr.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let t=xe.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e){let i=xe.endSpan(t,1);return Ze().recordSpan(i),this.voicesCache.voices}let[n]=await this.client.listVoices(e?{languageCode:e}:{});if(!n.voices||n.voices.length===0){g.warn("Google Cloud TTS returned no voices");let i=xe.endSpan(t,1);return Ze().recordSpan(i),[]}let o=[];for(let i of n.voices??[]){if(!i.name||!Array.isArray(i.languageCodes)||i.languageCodes.length===0){g.warn("Skipping voice with missing required fields",{name:i.name,languageCodesCount:i.languageCodes?.length});continue}let a=i.name,c=i.languageCodes,l=c[0],u=this.detectVoiceType(a),d=i.ssmlGender==="MALE"?"male":i.ssmlGender==="FEMALE"?"female":"neutral";o.push({id:a,name:a,languageCode:l,languageCodes:c,gender:d,type:u,naturalSampleRateHertz:i.naturalSampleRateHertz??void 0})}e||(this.voicesCache={voices:o,timestamp:Date.now()});let s=xe.endSpan(t,1);return Ze().recordSpan(s),o}catch(n){let o=xe.endSpan(t,2,n instanceof Error?n.message:"Unknown error");Ze().recordSpan(o);let s=n instanceof Error?n.message:"Unknown error";return g.error(`Failed to fetch Google TTS voices: ${s}`),[]}}async synthesize(e,t){if(!this.client)throw new qt({code:pr.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let n=t.voice??"en-US-Neural2-C",o=xe.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":n,"tts.format":t.format??"mp3"}),s=Date.now();try{let i=e.startsWith("<speak>")&&e.endsWith("</speak>");if(e.startsWith("<speak>")&&!e.endsWith("</speak>")||!e.startsWith("<speak>")&&e.endsWith("</speak>"))throw new qt({code:pr.INVALID_INPUT,message:"Malformed SSML: missing opening <speak> or closing </speak> tag.",category:"validation",severity:"medium",retriable:!1});let a=this.extractLanguageCode(n),c=this.mapFormat(t.format??"mp3"),l={input:i?{ssml:e}:{text:e},voice:{name:n,languageCode:a},audioConfig:{audioEncoding:c,speakingRate:t.speed??1,pitch:t.pitch??0,volumeGainDb:t.volumeGainDb??0}},[u]=await this.client.synthesizeSpeech(l,{timeout:r.DEFAULT_API_TIMEOUT_MS}),d=u.audioContent;if(!d)throw new qt({code:pr.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});let p=d instanceof Uint8Array?Buffer.from(d):typeof d=="string"?Buffer.from(d,"base64"):(()=>{throw new qt({code:pr.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof d}})})(),f=Date.now()-s,h=xe.endSpan(o,1);return Ze().recordSpan(h),{buffer:p,format:t.format??"mp3",size:p.length,voice:n,metadata:{latency:f,provider:"google-ai"}}}catch(i){let a=xe.endSpan(o,2,i instanceof Error?i.message:String(i));if(Ze().recordSpan(a),i instanceof qt)throw i;let c=Date.now()-s,l=i instanceof Error?i.message:"Unknown error";throw new qt({code:pr.SYNTHESIS_FAILED,message:`Google TTS failed after ${c}ms: ${l}`,category:"execution",severity:"high",retriable:!0,context:{latency:c},originalError:i instanceof Error?i:void 0})}}extractLanguageCode(e){let t=e.split("-");if(t.length>=2)return`${t[0]}-${t[1]}`;throw new qt({code:pr.INVALID_INPUT,message:`Invalid Google TTS voiceId format: "${e}". Expected format like "en-US-Neural2-C".`,category:"validation",severity:"medium",retriable:!1,context:{voiceId:e}})}mapFormat(e){switch(e.toLowerCase()){case"mp3":return"MP3";case"wav":return"LINEAR16";case"ogg":case"opus":return"OGG_OPUS";default:throw new qt({code:pr.INVALID_INPUT,message:`Unsupported audio format: ${e}`,category:"validation",severity:"medium",retriable:!1,context:{format:e}})}}detectVoiceType(e){let t=e.toLowerCase().split("-");return t.some(n=>n.startsWith("chirp"))?"chirp":t.includes("neural2")?"neural":t.includes("wavenet")?"wavenet":t.includes("standard")?"standard":"unknown"}}});var r6e={};ee(r6e,{OpenAITTS:()=>Kg});var Kg,qW=_(()=>{"use strict";W();ha();Kg=class r{apiKey;baseUrl="https://api.openai.com/v1";maxTextLength=4096;static VOICES=[{id:"alloy",name:"Alloy",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"echo",name:"Echo",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"fable",name:"Fable",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"onyx",name:"Onyx",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"nova",name:"Nova",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"},{id:"shimmer",name:"Shimmer",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"}];constructor(e){let t=(e??process.env.OPENAI_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){return e&&!e.startsWith("en"),r.VOICES}async synthesize(e,t={}){if(!this.apiKey)throw new qt({code:pr.PROVIDER_NOT_CONFIGURED,message:"OpenAI TTS API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=o.model??(t.quality==="hd"?"tts-1-hd":"tts-1"),i=t.voice??"alloy",a=this.mapFormat(t.format??"mp3"),c={model:s,input:e,voice:i,response_format:a,speed:t.speed??1},l=new AbortController,u=setTimeout(()=>l.abort(),3e4),d;try{d=await fetch(`${this.baseUrl}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(b){throw b instanceof Error&&b.name==="AbortError"?new qt({code:pr.SYNTHESIS_FAILED,message:"OpenAI TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:b}):b}finally{clearTimeout(u)}if(!d.ok){let T=(await d.json().catch(()=>Object.create(null))).error?.message||`HTTP ${d.status}`,w=d.status===408||d.status===429||d.status>=500;throw new qt({code:pr.SYNTHESIS_FAILED,message:T,category:w?"network":"execution",severity:"high",retriable:w,context:{status:d.status,model:s,responseFormat:a}})}let p=Date.now()-n,f=await d.arrayBuffer(),h=Buffer.from(f),y=this.effectiveFormat(a),x={buffer:h,format:y,size:h.length,voice:i,sampleRate:this.getSampleRate(y),metadata:{latency:p,provider:"openai-tts",model:s,requestedFormat:t.format,responseFormat:a}};return g.info(`[OpenAITTSHandler] Synthesized ${h.length} bytes in ${p}ms`),x}catch(s){if(s instanceof qt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[OpenAITTSHandler] Synthesis failed: ${i}`),new qt({code:pr.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapFormat(e){let n={mp3:"mp3",wav:"wav",ogg:"opus",opus:"opus",pcm16:"pcm"}[e];return n===void 0?(g.warn(`[OpenAITTSHandler] Unsupported format "${e}" \u2014 falling back to "mp3". Supported formats: mp3, wav, ogg, opus, pcm16.`),"mp3"):n}getSampleRate(e){switch(e){case"opus":case"ogg":return 48e3;default:return 24e3}}effectiveFormat(e){switch(e){case"mp3":return"mp3";case"wav":return"wav";case"opus":return"opus";case"pcm":return"pcm16";default:return"mp3"}}}});var n6e={};ee(n6e,{ElevenLabsTTS:()=>Jg});var Jg,HW=_(()=>{"use strict";W();ha();Jg=class r{apiKey;baseUrl="https://api.elevenlabs.io/v1";voicesCache=null;static CACHE_TTL_MS=300*1e3;maxTextLength=5e3;constructor(e){let t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){if(!this.apiKey)throw new qt({code:pr.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`${this.baseUrl}/voices`,{method:"GET",headers:{"xi-api-key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new qt({code:pr.SYNTHESIS_FAILED,message:"ElevenLabs voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).voices.map(a=>({id:a.voice_id,name:a.name,languageCode:"en",languageCodes:["en","es","fr","de","it","pt","pl","hi","ar","zh","ja","ko"],gender:this.mapGender(a.labels?.gender),type:"neural",description:a.labels?.description}));if(e){let a=e.toLowerCase(),c=a.split("-")[0];i=i.filter(l=>l.languageCodes?.some(u=>{let d=u.toLowerCase();return d===a||d===c||d.startsWith(c)}))}return e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Failed to get voices: ${n}`),new qt({code:pr.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new qt({code:pr.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"21m00Tcm4TlvDq8ikWAM",i=o.model??"eleven_multilingual_v2",a={text:e,model_id:i,voice_settings:{stability:o.stability??.5,similarity_boost:o.similarityBoost??.75,style:o.style??0,use_speaker_boost:o.useSpeakerBoost??!0}},c=this.mapFormat(t.format??"mp3"),l=new AbortController,u=setTimeout(()=>l.abort(),3e4),d;try{d=await fetch(`${this.baseUrl}/text-to-speech/${s}?output_format=${c}`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?new qt({code:pr.SYNTHESIS_FAILED,message:"ElevenLabs TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:x}):x}finally{clearTimeout(u)}if(!d.ok){let b=(await d.json().catch(()=>Object.create(null))).detail?.message||`HTTP ${d.status}`;throw new Error(b)}let p=Date.now()-n,f=await d.arrayBuffer(),h=Buffer.from(f),y={buffer:h,format:this.effectiveFormat(c),size:h.length,voice:s,sampleRate:this.getSampleRate(c),metadata:{latency:p,provider:"elevenlabs-tts",model:i,requestedFormat:t.format,outputFormat:c}};return g.info(`[ElevenLabsTTSHandler] Synthesized ${h.length} bytes in ${p}ms`),y}catch(s){if(s instanceof qt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Synthesis failed: ${i}`),new qt({code:pr.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapGender(e){if(!e)return"neutral";let t=e.toLowerCase();return t.includes("male")&&!t.includes("female")?"male":t.includes("female")?"female":"neutral"}mapFormat(e){return{mp3:"mp3_44100_128",wav:"pcm_44100",ogg:"ogg_22050",opus:"ogg_22050"}[e]??"mp3_44100_128"}getSampleRate(e){return e.includes("44100")?44100:e.includes("22050")?22050:e.includes("24000")?24e3:44100}effectiveFormat(e){return e.startsWith("mp3")?"mp3":e.startsWith("pcm")?"pcm16":e.startsWith("ogg")?"opus":"mp3"}}});var o6e={};ee(o6e,{AzureTTS:()=>Yg});var Yg,WW=_(()=>{"use strict";W();ha();Yg=class r{apiKey;region;voicesCache=null;static CACHE_TTL_MS=1800*1e3;maxTextLength=1e4;constructor(e,t){let n=(e??process.env.AZURE_SPEECH_KEY??"").trim();this.apiKey=n.length>0?n:null;let o=(t??process.env.AZURE_SPEECH_REGION??"").trim();this.region=o.length>0?o:"eastus"}isConfigured(){return this.apiKey!==null&&this.region.length>0}async getVoices(e){if(!this.apiKey)throw new qt({code:pr.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/voices/list`,{method:"GET",headers:{"Ocp-Apim-Subscription-Key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new qt({code:pr.SYNTHESIS_FAILED,message:"Azure TTS voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).map(a=>({id:a.ShortName,name:a.DisplayName,languageCode:a.Locale,languageCodes:[a.Locale],gender:this.mapGender(a.Gender),type:a.VoiceType.toLowerCase().includes("neural")?"neural":"standard",description:a.LocaleName}));return e&&(i=i.filter(a=>a.languageCode.toLowerCase().startsWith(e.toLowerCase())||a.languageCode.toLowerCase()===e.toLowerCase())),e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){if(t instanceof qt)throw t;let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new qt({code:pr.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new qt({code:pr.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"en-US-JennyNeural",i=o.outputFormat??this.mapFormat(t.format??"mp3"),a=this.buildSSML(e,s,t),c=new AbortController,l=setTimeout(()=>c.abort(),3e4),u;try{u=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.apiKey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":i},body:a,signal:c.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new qt({code:pr.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(l)}if(!u.ok){let y=await u.text();throw new Error(`HTTP ${u.status}: ${y}`)}let d=Date.now()-n,p=await u.arrayBuffer(),f=Buffer.from(p),h={buffer:f,format:this.effectiveFormat(i),size:f.length,voice:s,sampleRate:this.getSampleRate(i),metadata:{latency:d,provider:"azure-tts",requestedFormat:t.format,outputFormat:i,region:this.region}};return g.info(`[AzureTTSHandler] Synthesized ${f.length} bytes in ${d}ms`),h}catch(s){if(s instanceof qt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[AzureTTSHandler] Synthesis failed: ${i}`),new qt({code:pr.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}buildSSML(e,t,n){let o=n;if(o.ssmlTemplate)return o.ssmlTemplate.replace("{text}",this.escapeXml(e)).replace("{voice}",this.escapeXml(t));if(o.allowRawSSML&&e.trim().startsWith("<speak"))return e;let s=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",i=n.pitch??0,a=i>=0?`+${Math.round(i)}st`:`${Math.round(i)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(t))}">
|
|
2209
2209
|
<voice name="${this.escapeXml(t)}">
|
|
@@ -28,13 +28,23 @@ const DEFAULT_TIMEOUT_MS = 60_000;
|
|
|
28
28
|
function buildPinnedAgent(hostname, ip, family) {
|
|
29
29
|
return new Agent({
|
|
30
30
|
connect: {
|
|
31
|
-
lookup: (host,
|
|
31
|
+
lookup: (host, options, callback) => {
|
|
32
32
|
if (host.toLowerCase() !== hostname.toLowerCase()) {
|
|
33
33
|
// The host the connect layer asks for differs from the URL host —
|
|
34
34
|
// this happens for absolute Host headers etc. Reject defensively.
|
|
35
35
|
callback(new Error(`safeFetch: refusing to resolve "${host}" — expected "${hostname}"`), "", 0);
|
|
36
36
|
return;
|
|
37
37
|
}
|
|
38
|
+
// Node ≥20 enables autoSelectFamily (Happy Eyeballs) by default, and
|
|
39
|
+
// its lookup contract passes `all: true` expecting an address ARRAY.
|
|
40
|
+
// Answering with the string form there fails the connection with
|
|
41
|
+
// "Invalid IP address: undefined" — which broke every safeDownload
|
|
42
|
+
// (Replicate / Runway / Kling asset fetches) on modern Node while
|
|
43
|
+
// plain curl of the same URL succeeded.
|
|
44
|
+
if (options?.all) {
|
|
45
|
+
callback(null, [{ address: ip, family }]);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
38
48
|
callback(null, ip, family);
|
|
39
49
|
},
|
|
40
50
|
},
|
package/dist/utils/safeFetch.js
CHANGED
|
@@ -28,13 +28,23 @@ const DEFAULT_TIMEOUT_MS = 60_000;
|
|
|
28
28
|
function buildPinnedAgent(hostname, ip, family) {
|
|
29
29
|
return new Agent({
|
|
30
30
|
connect: {
|
|
31
|
-
lookup: (host,
|
|
31
|
+
lookup: (host, options, callback) => {
|
|
32
32
|
if (host.toLowerCase() !== hostname.toLowerCase()) {
|
|
33
33
|
// The host the connect layer asks for differs from the URL host —
|
|
34
34
|
// this happens for absolute Host headers etc. Reject defensively.
|
|
35
35
|
callback(new Error(`safeFetch: refusing to resolve "${host}" — expected "${hostname}"`), "", 0);
|
|
36
36
|
return;
|
|
37
37
|
}
|
|
38
|
+
// Node ≥20 enables autoSelectFamily (Happy Eyeballs) by default, and
|
|
39
|
+
// its lookup contract passes `all: true` expecting an address ARRAY.
|
|
40
|
+
// Answering with the string form there fails the connection with
|
|
41
|
+
// "Invalid IP address: undefined" — which broke every safeDownload
|
|
42
|
+
// (Replicate / Runway / Kling asset fetches) on modern Node while
|
|
43
|
+
// plain curl of the same URL succeeded.
|
|
44
|
+
if (options?.all) {
|
|
45
|
+
callback(null, [{ address: ip, family }]);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
38
48
|
callback(null, ip, family);
|
|
39
49
|
},
|
|
40
50
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "9.87.
|
|
3
|
+
"version": "9.87.1",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (58+ servers), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|