@juspay/neurolink 12.35.3 → 12.35.4

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.
@@ -2140,9 +2140,9 @@ ${k}`:d.text}}catch(C){if(!(t.input.text||""))throw C;p.warn(`[NeuroLink] Stream
2140
2140
 
2141
2141
  ${r}`:r}}return t?`${t}
2142
2142
 
2143
- ${r}`:r}async retrieveKnowledgeGrounding(t){const r=this.knowledgeGroundingEngine;if(!r||!r.isEnabled()||t.useKnowledgeGrounding!==!0)return;const n=t.input?.text;if(n)try{const s=(t.conversationMessages!==void 0?t.conversationMessages:await this.fetchRecentRoutingHistory(t)).filter(i=>i.role==="user"||i.role==="assistant").slice(-UN).map(i=>({role:i.role==="assistant"?"assistant":"user",text:typeof i.content=="string"?i.content:""}));return await r.ground({query:n,recentTurns:s,scope:t.knowledgeContext})}catch(o){p.warn("[KnowledgeGrounding] grounding hook failed open",{error:String(o)});return}}async validateStreamRequestOptions(t,r){if(await this.validateStreamInput(t),t.inputValidation&&t.input?.text){const n=t.inputValidation;if(n.trimWhitespace&&(t.input.text=t.input.text.trim()),n.requireContent&&!t.input.text.trim())throw new Error("Input content is required but was empty or whitespace");if(n.minLength&&t.input.text.length<n.minLength)throw new Error(`Input text is too short (${t.input.text.length} < ${n.minLength})`);if(n.maxLength&&t.input.text.length>n.maxLength)throw new Error(`Input text is too long (${t.input.text.length} > ${n.maxLength})`)}if(t.piiDetection?.enabled&&t.input?.text){const n=await lse(t.input.text,{enabled:!0,action:t.piiDetection.action??"warn",detectTypes:t.piiDetection.detectTypes,customPatterns:t.piiDetection.customPatterns,allowList:t.piiDetection.allowList,redactionText:t.piiDetection.redactionText});if(n.action==="abort")throw new Error(n.feedback??"Request blocked: PII detected in input");t.input.text=n.text}this.enforceSessionBudget(t.maxBudgetUsd),await this.applyAuthenticatedRequestContext(t),this.emitStreamStartEvents(t,r),this.applyStreamLifecycleMiddleware(t)}async maybeHandleWorkflowStreamRequest(t){if(!t.options.workflow&&!t.options.workflowConfig)return null;const r=await this.streamWithWorkflow(t.options,t.startTime),n=r.stream,o=this;return r.stream=(async function*(){try{for await(const s of n)yield s;t.streamSpan.setStatus({code:Ue.OK})}catch(s){throw t.streamSpan.setStatus({code:Ue.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o._disableToolCacheForCurrentRequest=!1,o._toolCacheKeysServedThisRequest=new Set,o._generationTurnActive=!1,t.streamSpan.setAttribute("neurolink.response_time_ms",Date.now()-t.spanStartTime),t.streamSpan.end()}})(),r}async runStandardStreamRequest(t){const{options:r,streamSpan:n,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:c,ttsResolver:l,ttsMetadataSink:u}=t;p.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:r.provider,model:r.model,inputLength:r.input?.text?.length||0,disableTools:r.disableTools,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,contextKeys:r.context?Object.keys(r.context):[],optionKeys:Object.keys(r),sessionId:r.context?.sessionId});try{const{enhancedOptions:d,factoryResult:m}=await this.prepareStreamOptions(r,a,s,i);p.debug("[NeuroLink] Stream options prepared",{streamId:a,options:d,factoryResult:m,sessionId:d.context?.sessionId});const h={providerEmitted:!1};d._streamDedupContext=h;const f=await this.createMCPStream(d),{stream:g}=f,y=f.provider??"unknown";let v;const{stream:w,ttsMetadata:E}=await this.createIncrementalTTSStream({stream:g,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,onComplete:N=>{v=N}});u?.(E);const _={finishReason:f.finishReason??"stop",toolCalls:f.toolCalls??[],toolResults:f.toolResults??[]};n.setAttribute(_e.NL_PROVIDER,y||"unknown");let C="",A=0;const{eventSequence:k,cleanup:R}=this.setupStreamEventListeners(),I={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},P=this,O=Date.now(),U=d.context?.sessionId,M=(async function*(){let N,L,q=0;try{for await(const V of w){A++;const G=V!==null&&typeof V=="object"&&"metadata"in V&&V.metadata?.noOutput===!0,X=V&&"content"in V&&typeof V.content=="string"&&V.content.length>0,ce=V!==null&&typeof V=="object"&&"type"in V&&(V.type==="audio"||V.type==="tts_audio"||V.type==="image");!G&&(X||ce)&&q++,V&&"content"in V&&typeof V.content=="string"&&(C+=V.content,P.emitter.emit("response:chunk",V.content),P.emitter.emit("stream:chunk",{type:"stream:chunk",content:V.content,metadata:{chunkIndex:A,totalLength:C.length,...G&&{noOutput:!0}},timestamp:Date.now()})),yield V}const B=d.fallbackOnMaxSteps===!1&&f.metadata?.stopReason==="step-cap";if(q===0&&!B&&!I.fallbackAttempted&&!d.disableInternalFallback&&_.toolCalls.length===0&&_.toolResults.length===0){const V=P.handleStreamFallback(I,_,c,d,y,X=>{C+=X}),{stream:G}=await P.createIncrementalTTSStream({stream:V,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,ttsMetadata:E,onComplete:X=>{v=X}});yield*G}if(l?.(v),L=f.usage,!L&&f.analytics)try{const V=await Promise.resolve(f.analytics);V?.tokenUsage&&(L=V.tokenUsage)}catch{}L&&(f.usage=L),P.emitter.emit("stream:complete",{type:"stream:complete",content:C,provider:I.fallbackProvider??y,model:I.fallbackModel??f.model??d.model,finishReason:_.finishReason??"stop",prompt:d.input?.text||d.prompt,metadata:{chunkCount:A,totalLength:C.length,durationMs:Date.now()-O,sessionId:U,usage:L,finishReason:_.finishReason??"stop",...I.fallbackAttempted&&{primaryProvider:y,primaryModel:d.model,fallback:!0}},timestamp:Date.now()})}catch(B){throw p.debug("[NeuroLink.stream] Stream error occurred",{error:B instanceof Error?B.message:String(B),name:B instanceof Error?B.name:"UnknownError",provider:y,model:d.model,chunkCount:A,totalLength:C.length,durationMs:Date.now()-O,sessionId:U}),N=B,P.emitter.emit("stream:error",{type:"stream:error",content:B instanceof Error?B.message:String(B),provider:y,model:d.model,metadata:{chunkCount:A,totalLength:C.length,durationMs:Date.now()-O,errorName:B instanceof Error?B.name:"UnknownError",sessionId:U},timestamp:Date.now()}),B}finally{if(l?.(void 0),p.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:y,model:d.model,totalChunks:A,totalLength:C.length,durationMs:Date.now()-O,fallbackAttempted:I.fallbackAttempted,guardrailsBlocked:I.guardrailsBlocked,error:I.error}),!h.providerEmitted)try{const V=I.fallbackProvider??y??"unknown",G=I.fallbackModel??f.model??d.model??"unknown",X=N?"error":_.finishReason??"stop";P.emitter.emit("generation:end",{provider:V,model:G,responseTime:Date.now()-O,toolsUsed:_.toolCalls?.map(ce=>ce.toolName),timestamp:Date.now(),result:{content:C,usage:L,model:G,provider:V,finishReason:X},prompt:d.input?.text||d.prompt,temperature:d.temperature,maxTokens:d.maxTokens,success:!N,error:N?N instanceof Error?N.message:String(N):void 0,pipelineAHandled:!0})}catch(V){p.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:V instanceof Error?V.message:String(V)})}P._disableToolCacheForCurrentRequest=!1,P._toolCacheKeysServedThisRequest=new Set,P._generationTurnActive=!1,R(),n.setAttribute("neurolink.response_time_ms",Date.now()-o),n.setAttribute(_e.NL_OUTPUT_LENGTH,C.length);const B=!!(I.error||N);n.setAttribute(_e.GEN_AI_FINISH_REASON,B?"error":"stop"),I.fallbackAttempted&&(n.setAttribute("neurolink.fallback_triggered",!0),I.fallbackProvider&&n.setAttribute("neurolink.fallback_provider",I.fallbackProvider)),B?n.setStatus({code:Ue.ERROR,message:I.error||(N instanceof Error?N.message:String(N))}):n.setStatus({code:Ue.OK}),n.end(),C.trim()&&p.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:y,model:d.model,responseTimeMs:Date.now()-s,contentLength:C.length,fallback:I.fallbackAttempted}),await P.storeStreamConversationMemory({enhancedOptions:d,providerName:y,originalPrompt:c,accumulatedContent:C,startTime:s,eventSequence:k})}})(),F=await this.processStreamResult(M,d,m);return F.finishReason=_.finishReason||F.finishReason,F.toolCalls=_.toolCalls,F.toolResults=_.toolResults,F.usage||(F.usage=f.usage),F.analytics||(F.analytics=f.analytics),Promise.resolve(F.analytics).then(N=>{N?.cost&&N.cost>0&&(this._sessionCostUsd+=N.cost)}).catch(()=>{}),this.emitStreamEndEvents(F),this.createStreamResponse(F,M,{providerName:y,options:r,startTime:s,responseTime:Date.now()-s,streamId:a,fallback:I.fallbackAttempted,guardrailsBlocked:I.guardrailsBlocked,error:I.error,events:k,sourceResult:f})}catch(d){if(l?.(void 0),r.disableInternalFallback)throw d;return this.handleStreamError(d,r,s,a,void 0,void 0)}}async createIncrementalTTSStream(t){const{stream:r,ttsOptions:n,providerName:o,fallbackProvider:s,onComplete:i}=t;if(!n?.enabled)return i(void 0),{stream:r};const{TTSProcessor:a}=await Promise.resolve().then(()=>(Ec(),fHe)),c=s==="auto"?void 0:s,l=n.provider??c??o,u=l&&a.supports(l)?l:void 0,d=t.ttsMetadata??{attempted:u!==void 0,success:!1};d.attempted=u!==void 0,d.success=!1,delete d.error,delete d.latency;const m=Date.now();let h=!1;const f=(g,y)=>{h||(h=!0,d.success=y===void 0&&g!==void 0,y?d.error=y:delete d.error,d.latency=Date.now()-m,i(g))};return u?{stream:AHe({stream:r,provider:u,options:n,onComplete:f}),ttsMetadata:d}:(p.warn(`[NeuroLink.stream] No TTS provider resolved for incremental streaming (set tts.provider explicitly \u2014 chat provider "${l??"<unset>"}" is not a registered TTS handler)`),f(void 0),{stream:r,ttsMetadata:d})}deferProviderStreamTTS(t){return t.tts?.enabled?{...t,tts:void 0}:t}async prepareStreamOptions(t,r,n,o){if(await this.initializeConversationMemoryForGeneration(r,n,o),await this.initializeMCP(),this.shouldReadMemory(t.memory,t.context?.userId)&&t.context?.userId)try{t.input.text=await this.retrieveMemory(t.input.text??"",t.context.userId,t.memory?.additionalUsers),p.debug("Memory retrieval successful")}catch(a){p.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(t),this.enableOrchestration&&!t.provider&&!t.model)try{const a=await this.applyStreamOrchestration(t);p.debug("Stream orchestration applied",{originalProvider:t.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:t.input.text?.substring(0,100)}),t={...t,...a},a.model&&(t.model=ik(t.model,this.modelAliasConfig))}catch(a){p.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:t.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(t),t.rag?.files?.length)try{const{prepareRAGTool:a}=await Promise.resolve().then(()=>(bse(),Sse)),c=await a(t.rag,t.provider);t.tools||(t.tools={}),t.tools[c.toolName]=c.tool;const l=[`
2143
+ ${r}`:r}async retrieveKnowledgeGrounding(t){const r=this.knowledgeGroundingEngine;if(!r||!r.isEnabled()||t.useKnowledgeGrounding!==!0)return;const n=t.input?.text;if(n)try{const s=(t.conversationMessages!==void 0?t.conversationMessages:await this.fetchRecentRoutingHistory(t)).filter(i=>i.role==="user"||i.role==="assistant").slice(-UN).map(i=>({role:i.role==="assistant"?"assistant":"user",text:typeof i.content=="string"?i.content:""}));return await r.ground({query:n,recentTurns:s,scope:t.knowledgeContext})}catch(o){p.warn("[KnowledgeGrounding] grounding hook failed open",{error:String(o)});return}}async validateStreamRequestOptions(t,r){if(await this.validateStreamInput(t),t.inputValidation&&t.input?.text){const n=t.inputValidation;if(n.trimWhitespace&&(t.input.text=t.input.text.trim()),n.requireContent&&!t.input.text.trim())throw new Error("Input content is required but was empty or whitespace");if(n.minLength&&t.input.text.length<n.minLength)throw new Error(`Input text is too short (${t.input.text.length} < ${n.minLength})`);if(n.maxLength&&t.input.text.length>n.maxLength)throw new Error(`Input text is too long (${t.input.text.length} > ${n.maxLength})`)}if(t.piiDetection?.enabled&&t.input?.text){const n=await lse(t.input.text,{enabled:!0,action:t.piiDetection.action??"warn",detectTypes:t.piiDetection.detectTypes,customPatterns:t.piiDetection.customPatterns,allowList:t.piiDetection.allowList,redactionText:t.piiDetection.redactionText});if(n.action==="abort")throw new Error(n.feedback??"Request blocked: PII detected in input");t.input.text=n.text}this.enforceSessionBudget(t.maxBudgetUsd),await this.applyAuthenticatedRequestContext(t),this.emitStreamStartEvents(t,r),this.applyStreamLifecycleMiddleware(t)}async maybeHandleWorkflowStreamRequest(t){if(!t.options.workflow&&!t.options.workflowConfig)return null;const r=await this.streamWithWorkflow(t.options,t.startTime),n=r.stream,o=this;return r.stream=(async function*(){try{for await(const s of n)yield s;t.streamSpan.setStatus({code:Ue.OK})}catch(s){throw t.streamSpan.setStatus({code:Ue.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o._disableToolCacheForCurrentRequest=!1,o._toolCacheKeysServedThisRequest=new Set,o._generationTurnActive=!1,t.streamSpan.setAttribute("neurolink.response_time_ms",Date.now()-t.spanStartTime),t.streamSpan.end()}})(),r}async runStandardStreamRequest(t){const{options:r,streamSpan:n,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:c,ttsResolver:l,ttsMetadataSink:u}=t;p.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:r.provider,model:r.model,inputLength:r.input?.text?.length||0,disableTools:r.disableTools,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,contextKeys:r.context?Object.keys(r.context):[],optionKeys:Object.keys(r),sessionId:r.context?.sessionId});try{const{enhancedOptions:d,factoryResult:m}=await this.prepareStreamOptions(r,a,s,i);p.debug("[NeuroLink] Stream options prepared",{streamId:a,options:d,factoryResult:m,sessionId:d.context?.sessionId});const h={providerEmitted:!1};d._streamDedupContext=h;const f=await this.createMCPStream(d),{stream:g}=f,y=f.provider??"unknown";let v;const{stream:w,ttsMetadata:E}=await this.createIncrementalTTSStream({stream:g,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,onComplete:N=>{v=N}});u?.(E);const _={finishReason:f.finishReason??"stop",toolCalls:f.toolCalls??[],toolResults:f.toolResults??[]};n.setAttribute(_e.NL_PROVIDER,y||"unknown");let C="",A=0;const{eventSequence:k,cleanup:R}=this.setupStreamEventListeners(),I={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},P=this,O=Date.now(),U=d.context?.sessionId,M=(async function*(){let N,L,q=0;try{for await(const V of w){A++;const G=V!==null&&typeof V=="object"&&"metadata"in V&&V.metadata?.noOutput===!0,X=V&&"content"in V&&typeof V.content=="string"&&V.content.length>0,ce=V!==null&&typeof V=="object"&&"type"in V&&(V.type==="audio"||V.type==="tts_audio"||V.type==="image");!G&&(X||ce)&&q++,V&&"content"in V&&typeof V.content=="string"&&(C+=V.content,P.emitter.emit("response:chunk",V.content),P.emitter.emit("stream:chunk",{type:"stream:chunk",content:V.content,metadata:{chunkIndex:A,totalLength:C.length,...G&&{noOutput:!0}},timestamp:Date.now()})),yield V}const B=d.fallbackOnMaxSteps===!1&&f.metadata?.stopReason==="step-cap";if(q===0&&!B&&!I.fallbackAttempted&&!d.disableInternalFallback&&_.toolCalls.length===0&&_.toolResults.length===0){const V=P.handleStreamFallback(I,_,c,d,y,X=>{C+=X}),{stream:G}=await P.createIncrementalTTSStream({stream:V,ttsOptions:d.tts,providerName:y,fallbackProvider:d.provider,ttsMetadata:E,onComplete:X=>{v=X}});yield*G}if(l?.(v),L=f.usage,!L&&f.analytics)try{const V=await Promise.resolve(f.analytics);V?.tokenUsage&&(L=V.tokenUsage)}catch{}L&&(f.usage=L),P.emitter.emit("stream:complete",{type:"stream:complete",content:C,provider:I.fallbackProvider??y,model:I.fallbackModel??f.model??d.model,finishReason:_.finishReason??"stop",prompt:d.input?.text||d.prompt,metadata:{chunkCount:A,totalLength:C.length,durationMs:Date.now()-O,sessionId:U,usage:L,finishReason:_.finishReason??"stop",...I.fallbackAttempted&&{primaryProvider:y,primaryModel:d.model,fallback:!0}},timestamp:Date.now()})}catch(B){throw p.debug("[NeuroLink.stream] Stream error occurred",{error:B instanceof Error?B.message:String(B),name:B instanceof Error?B.name:"UnknownError",provider:y,model:d.model,chunkCount:A,totalLength:C.length,durationMs:Date.now()-O,sessionId:U}),N=B,P.emitter.emit("stream:error",{type:"stream:error",content:B instanceof Error?B.message:String(B),provider:y,model:d.model,metadata:{chunkCount:A,totalLength:C.length,durationMs:Date.now()-O,errorName:B instanceof Error?B.name:"UnknownError",sessionId:U},timestamp:Date.now()}),B}finally{if(l?.(void 0),p.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:y,model:d.model,totalChunks:A,totalLength:C.length,durationMs:Date.now()-O,fallbackAttempted:I.fallbackAttempted,guardrailsBlocked:I.guardrailsBlocked,error:I.error}),!h.providerEmitted)try{const V=I.fallbackProvider??y??"unknown",G=I.fallbackModel??f.model??d.model??"unknown",X=N?"error":_.finishReason??"stop";P.emitter.emit("generation:end",{provider:V,model:G,responseTime:Date.now()-O,toolsUsed:_.toolCalls?.map(ce=>ce.toolName),timestamp:Date.now(),result:{content:C,usage:L,model:G,provider:V,finishReason:X},prompt:d.input?.text||d.prompt,temperature:d.temperature,maxTokens:d.maxTokens,success:!N,error:N?N instanceof Error?N.message:String(N):void 0,pipelineAHandled:!0})}catch(V){p.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:V instanceof Error?V.message:String(V)})}P._disableToolCacheForCurrentRequest=!1,P._toolCacheKeysServedThisRequest=new Set,P._generationTurnActive=!1,R(),n.setAttribute("neurolink.response_time_ms",Date.now()-o),n.setAttribute(_e.NL_OUTPUT_LENGTH,C.length);const B=!!(I.error||N);n.setAttribute(_e.GEN_AI_FINISH_REASON,B?"error":"stop"),I.fallbackAttempted&&(n.setAttribute("neurolink.fallback_triggered",!0),I.fallbackProvider&&n.setAttribute("neurolink.fallback_provider",I.fallbackProvider)),B?n.setStatus({code:Ue.ERROR,message:I.error||(N instanceof Error?N.message:String(N))}):n.setStatus({code:Ue.OK}),n.end(),C.trim()&&p.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:y,model:d.model,responseTimeMs:Date.now()-s,contentLength:C.length,fallback:I.fallbackAttempted}),await P.storeStreamConversationMemory({enhancedOptions:d,providerName:y,originalPrompt:c,accumulatedContent:C,startTime:s,eventSequence:k})}})(),F=await this.processStreamResult(M,d,m);return F.finishReason=_.finishReason||F.finishReason,Object.defineProperty(F,"toolCalls",{enumerable:!0,configurable:!0,get:()=>_.toolCalls}),Object.defineProperty(F,"toolResults",{enumerable:!0,configurable:!0,get:()=>_.toolResults}),F.usage||(F.usage=f.usage),F.analytics||(F.analytics=f.analytics),Promise.resolve(F.analytics).then(N=>{N?.cost&&N.cost>0&&(this._sessionCostUsd+=N.cost)}).catch(()=>{}),this.emitStreamEndEvents(F),this.createStreamResponse(F,M,{providerName:y,options:r,startTime:s,responseTime:Date.now()-s,streamId:a,fallback:I.fallbackAttempted,guardrailsBlocked:I.guardrailsBlocked,error:I.error,events:k,sourceResult:f})}catch(d){if(l?.(void 0),r.disableInternalFallback)throw d;return this.handleStreamError(d,r,s,a,void 0,void 0)}}async createIncrementalTTSStream(t){const{stream:r,ttsOptions:n,providerName:o,fallbackProvider:s,onComplete:i}=t;if(!n?.enabled)return i(void 0),{stream:r};const{TTSProcessor:a}=await Promise.resolve().then(()=>(Ec(),fHe)),c=s==="auto"?void 0:s,l=n.provider??c??o,u=l&&a.supports(l)?l:void 0,d=t.ttsMetadata??{attempted:u!==void 0,success:!1};d.attempted=u!==void 0,d.success=!1,delete d.error,delete d.latency;const m=Date.now();let h=!1;const f=(g,y)=>{h||(h=!0,d.success=y===void 0&&g!==void 0,y?d.error=y:delete d.error,d.latency=Date.now()-m,i(g))};return u?{stream:AHe({stream:r,provider:u,options:n,onComplete:f}),ttsMetadata:d}:(p.warn(`[NeuroLink.stream] No TTS provider resolved for incremental streaming (set tts.provider explicitly \u2014 chat provider "${l??"<unset>"}" is not a registered TTS handler)`),f(void 0),{stream:r,ttsMetadata:d})}deferProviderStreamTTS(t){return t.tts?.enabled?{...t,tts:void 0}:t}async prepareStreamOptions(t,r,n,o){if(await this.initializeConversationMemoryForGeneration(r,n,o),await this.initializeMCP(),this.shouldReadMemory(t.memory,t.context?.userId)&&t.context?.userId)try{t.input.text=await this.retrieveMemory(t.input.text??"",t.context.userId,t.memory?.additionalUsers),p.debug("Memory retrieval successful")}catch(a){p.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(t),this.enableOrchestration&&!t.provider&&!t.model)try{const a=await this.applyStreamOrchestration(t);p.debug("Stream orchestration applied",{originalProvider:t.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:t.input.text?.substring(0,100)}),t={...t,...a},a.model&&(t.model=ik(t.model,this.modelAliasConfig))}catch(a){p.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:t.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(t),t.rag?.files?.length)try{const{prepareRAGTool:a}=await Promise.resolve().then(()=>(bse(),Sse)),c=await a(t.rag,t.provider);t.tools||(t.tools={}),t.tools[c.toolName]=c.tool;const l=[`
2144
2144
 
2145
- 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(" ");t.systemPrompt=(t.systemPrompt||"")+l,p.info("[RAG] Tool injected into stream()",{toolName:c.toolName,filesLoaded:c.filesLoaded,chunksIndexed:c.chunksIndexed})}catch(a){p.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const s=sYr(t),i=iYr(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(t.input.text,void 0);c!==t.input.text&&(i.input.text=c)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(ef(),iHe)),s=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=t.model;s.length>0&&i&&(s.some(c=>i.toLowerCase().includes(c.toLowerCase()))||(t.disableTools=!0,p.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,m)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{const m=d[0];n("response:chunk",{content:m})},s=(...d)=>{const m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{const m=d[0],h=m.toolName??m.tool,f=m.responseTime??m.duration,g=m.success??(m.error!==void 0?!1:void 0),y={...m,toolName:h,...f!==void 0?{responseTime:f}:{},...g!==void 0?{success:g}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",y),y.result&&y.result.uiComponent===!0&&n("ui-component",{toolName:h,componentData:y.result,timestamp:Date.now(),...g!==void 0?{success:g}:{},...f!==void 0?{responseTime:f}:{}})},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:t,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(t,r,n,o,s,i){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const f=this._metricsTraceContext;let g=Ce.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:f?.traceId,parentSpanId:f?.parentSpanId});g=Ce.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),rt().recordSpan(g)}catch{}const 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,m=I2.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),h={...m,provider:c??u??m.provider,model:l??d??m.model};p.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:h.provider,fallbackModel:h.model,fallbackSource:c||l?"options":u||d?"env":"model_config",reason:a});try{const f=await Nn.createProvider(h.provider,h.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));f.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,A)=>this.executeTool(C,A,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await Sp(this.conversationMemory,{prompt:o.input.text,context:o.context});f.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await f.stream({...this.deferProviderStreamTTS(o),model:h.model,conversationMessages:g}),v=y.toolCalls??[],w=y.toolResults??[];(v.length>0||w.length>0)&&(r.toolCalls=v,r.toolResults=w,r.finishReason=y.finishReason??r.finishReason);let E=0,_=0;for await(const C of y.stream){E++;const A=C!==null&&typeof C=="object"&&"metadata"in C&&C.metadata?.noOutput===!0,k=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&&(k||R)&&_++,C&&"content"in C&&typeof C.content=="string"&&(i(C.content),this.emitter.emit("response:chunk",C.content)),yield C}if(_===0&&v.length===0&&w.length===0)throw new Error(`Fallback provider ${h.provider} also returned 0 real output chunks (chunkCount=${E}, sentinel-only or empty)`);t.fallbackProvider=h.provider,t.fallbackModel=h.model,t.guardrailsBlocked=!0}catch(f){const g=f instanceof Error?f.message:String(f);throw t.error=`${a}; Fallback failed: ${g}`,p.error("Fallback provider failed",{fallbackProvider:h.provider,error:g}),f}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=t;p.shouldLog("debug")&&p.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:P1(O1(r)),sessionId:r.context?.sessionId});const c=a.some(l=>l.type==="tool:start"||l.type==="tool:end");if(!s.trim()&&!c){p.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(p.shouldLog("debug")&&p.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:P1(O1(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const l=r.context?.sessionId,u=r.context?.userId;let d;r.model&&(d={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(l);await this.conversationMemory.storeConversationTurn({sessionId:l,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),p.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:l,eventCount:a.length,eventTypes:[...new Set(a.map(f=>f.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),p.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}this.shouldWriteMemory(r.memory,r.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();p.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=await pT(t.provider),n=await Nn.createProvider(r,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await n.ensureModelLimits?.(),n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(f,g)=>this.executeTool(f,g,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),i=t.conversationMessages!==void 0,a=i?t.conversationMessages:await Sp(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=a;let c=a;const l=Vi({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:o,compactionThreshold:t.compactionThreshold}),u=c?.length||0,d=this.getCompactionSessionId(t),m=u>0;if(!l.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:l.estimatedInputTokens,budget:l.availableInputTokens,provider:r,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Ta(`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)){const g=await new Uv({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()).compact(c,PN(l,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});g.compacted&&(c=Fv(g.messages).messages,t.conversationMessages=c,this.lastCompactionMessageCount.set(d,c.length));const y=Vi({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:o});if(!y.withinBudget){p.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:y.estimatedInputTokens,availableTokens:y.availableInputTokens,overagePercent:Math.round((y.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:y.estimatedInputTokens,budget:y.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=uee(c,y.availableInputTokens,y.breakdown,r),t.conversationMessages=c;const v=Vi({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Ta(`Stream context exceeds model budget after all compaction stages. Estimated: ${v.estimatedInputTokens} tokens, Budget: ${v.availableInputTokens} tokens.`,{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,stagesUsed:g.stagesUsed,breakdown:v.breakdown})}}}if(this.modelPool){const f=this.modelPool,g=f.maxAttempts,y=new Set;let v=null;for(let w=0;w<g;w++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const E=f.selectNext(y);if(!E)break;y.add(f.memberKey(E));const _=E.provider,C=E.model??void 0,A=E.region??void 0;p.debug(`[createMCPStream] ModelPool: attempting member ${_}`,{model:C,attempt:w});try{const k=await Nn.createProvider(_,C,!t.disableTools,this,A,this.resolveCredentials(t.credentials));k.setTraceContext(this._metricsTraceContext),k.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(O,U)=>this.executeTool(O,U,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),k.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const R=await k.stream({...this.deferProviderStreamTTS(t),provider:_,model:C,region:A,systemPrompt:s,conversationMessages:c});p.debug("[createMCPStream] ModelPool stream handle obtained",{provider:_});const I=E,P=(async function*(){try{yield*R.stream,f.recordSuccess(I)}catch(O){throw f.recordFailure(I,hT(O)),O}})();return CO(R,{...R,stream:P,provider:_,model:R.model||C,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[]})}catch(k){if(cr(k))throw k;if(uie(k)){const R=k instanceof Error?k.message:String(k);throw f.recordFailure(E,hT(k)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:k})}f.recordFailure(E,hT(k)),v=k instanceof Error?k:new Error(String(k)),p.warn(`[createMCPStream] ModelPool: member ${_} failed`,{error:v.message})}}throw new Error(`[ModelPool] all stream members failed: ${v?.message??"no stream members available"}`)}n.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const h=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:c});return p.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:s.length}),CO(h,{...h,provider:r,model:h.model||t.model,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[]})}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){const o=n.sourceResult,s={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},i={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,toolCalls:t.toolCalls,toolResults:t.toolResults,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},s)};if(!o)return i;const a=new Set(["finishReason","stopReason","rawFinishReason"]);for(const c of Object.getOwnPropertyNames(o)){const l=Object.getOwnPropertyDescriptor(o,c);!a.has(c)&&l&&typeof l.get=="function"&&Object.defineProperty(i,c,l)}return Object.defineProperty(i,"metadata",{enumerable:!0,configurable:!0,get:()=>Object.assign(o.metadata??{},s),set:c=>{o.metadata=c}}),i}async handleStreamError(t,r,n,o,s,i){if(t instanceof Ta)throw t;p.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,c=Date.now()-n,l=await pT(r.provider),u=await Nn.createProvider(l,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));u.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await u.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let m="";return{stream:(async function*(f){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(m+=g.content,f.emitter.emit("response:chunk",g.content)),yield g}finally{if(m.trim()){p.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:r.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{const g=r.model||"unknown",y=Date.now()-n;f.emitter.emit("stream:complete",{content:m,provider:l,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}}),f.emitter.emit("generation:end",{provider:l,model:g,responseTime:y,timestamp:Date.now(),result:{content:m,usage:{input:0,output:0,total:0},model:g,provider:l,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(f.conversationMemory&&s?.context?.sessionId&&m.trim()){const g=s?.context?.sessionId,y=s?.context?.userId;let v;r.model&&(v={provider:l,model:r.model});const w=Date.now();try{const E=g||r.context?.sessionId,_=f.drainPendingSkillMessages(E);await f.conversationMemory.storeConversationTurn({sessionId:E,userId:y||r.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||r.context?.requestId,..._.length>0?{skillMessages:_}:{}}),f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,1)}catch(E){f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,2,E instanceof Error?E.message:String(E)),p.warn("Failed to store fallback stream conversation turn",{error:E instanceof Error?E.message:String(E)})}}}})(this),provider:l,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:c,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}fileToolRootsFor(t){return Wj(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=PP({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return PP({perCall:t,instance:this.toolsConfig?.fileRoots})}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(s){const i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof yy?{provider:r,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:r,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:r,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:r,status:"network",detail:i}:{provider:r,status:"unknown",detail:i}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",K0(t,{input:r,timestamp:n,executionId:o})),p.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,s=Date.now(),i){const a=o||s-1e3,c=s-a,l=!n;let u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(h=>h.tool===t&&!h.endTime);const d=i||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const m={tool:t,startTime:a,endTime:s,duration:c,success:l,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",K0(t,{result:r,error:n,success:l,responseTime:c,timestamp:s,duration:c,executionId:d})),p.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:c,success:l,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(e7(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const i=o.execute,a=n.timeout,c=t;o.execute=async(...l)=>{const u=AbortSignal.timeout(a),d=l[1],m=d?.abortSignal,h=m?AbortSignal.any([m,u]):u,f={...d,abortSignal:h};return Promise.race([i(l[0],f),new Promise((g,y)=>{h.addEventListener("abort",()=>{u.aborted?y(pe.toolTimeout(c,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const s=u9r(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(s),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw p.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},p.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,p.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),p.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),p.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new Da("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Da("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await ze(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0})),r=new Map;for(const o of t){const s=o.inputSchema||o.parameters;p.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()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{const c=this.toolExecutionContext||{},l=a&&Zt(a)?a:{},u={...c,...l,sessionId:l.sessionId||c.sessionId||`fallback-${Date.now()}`};return p.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=xLt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,s]of Object.entries(n))if(!r.has(o)){const i=s,a=i.inputSchema??i.parameters;r.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 r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{ne.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),ne.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw ne.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>Hi({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return Be.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(t,r,n,o,s))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(l=>l.name===t),s=o?"mcp":this.getCustomTools().has(t)?"custom":"external",i=r?Hy(r):"",a=Date.now(),c=`${t}-${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(t,r,n,o,s){try{const i=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,i,o,s)}catch(i){if(!(i instanceof Me)){const a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:Ue.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(t,r,n,o){p.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:Zt(r)?w7e(r):r,hasExternalManager:!!this.externalServerManager}),p.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",K0(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const s=this.toolRegistry.getToolInfo(t),i=n?.timeout??s?.tool?.timeoutMs??mc.EXECUTION_BATCH_MS,a=n?.maxRetries??s?.tool?.maxRetries??Qo.DEFAULT,c=n?.retryDelayMs||Fn.BASE_MS,l={timeout:i,maxRetries:a,totalTimeout:n?.totalTimeoutMs??s?.tool?.totalTimeoutMs??i*(a+1)+c*a,retryDelayMs:c,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:u}=await Promise.resolve().then(()=>(uk(),yT)),d=u.getMemoryUsageMB(),h=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${t}`;let f=this.toolCircuitBreakers.get(h);f||(f=new x1(AI.FAILURE_THRESHOLD,cU),this.toolCircuitBreakers.set(h,f));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:l,startMemory:d,circuitBreaker:f,breakerKey:h,metrics:g}}async runPreparedToolExecution(t,r,n,o,s){let i=0;try{ne.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=n.finalOptions.maxRetries+1,c=n.finalOptions.totalTimeout,l=Date.now(),u=l+c;let d=0;const m=await n.circuitBreaker.execute(async()=>bve(async()=>{d++;const h=u-Date.now();if(h<=0)throw pe.toolTimeout(t,c,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:c,elapsedMs:Date.now()-l,exhausted:!0});const f=Math.min(n.finalOptions.timeout,h);return ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),f,pe.toolTimeout(t,f,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:c,elapsedMs:Date.now()-l}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:h=>Date.now()+n.finalOptions.retryDelayMs<u&&Uz(h),onRetry:(h,f)=>{i=h,ne.warn(`[${o.functionTag}] Retrying tool execution (attempt ${h})`,{toolName:t,error:f.message,attempt:h})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(t,m,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(t,r,a,n,o,s)}}async handleSuccessfulToolExecution(t,r,n,o,s){const 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;const{MemoryManager:a}=await Promise.resolve().then(()=>(uk(),yT)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&ne.warn(`Tool '${t}' used excessive memory: ${l}MB`,{toolName:t,memoryDelta:l,executionTime:i}),ne.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:i,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,h=d?m?.filter(f=>f.type==="text"&&f.text).map(f=>f.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}ne.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const f=aQr(h??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${f})] `;if(u&&Array.isArray(m)){const w=m.map(E=>({...E}));for(const E of w)if(E.type==="text"&&E.text){E.text=g+E.text;break}u.content=w}s.setAttribute("tool.error.message",(h??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",f),s.setStatus({code:Ue.ERROR,message:`MCP tool returned isError: ${(h??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-i)/(y-1):0;const v=cQr(f);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&h?new Error(h):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),r}async handleFailedToolExecution(t,r,n,o,s,i){o.metrics.failedExecutions++;const a=Date.now()-s.executionStartTime;if(n instanceof Sm)return ne.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (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:Ue.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let c;if(n instanceof Me)c=n;else if(n instanceof Error)if(n.message.includes("timeout"))c=pe.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();c=pe.toolNotFound(t,BNr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?c=pe.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?c=pe.networkError(t,n):c=pe.toolExecutionFailed(t,n);else c=pe.toolExecutionFailed(t,new Error(String(n)));const l=c.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,c,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",c),c=new Me({...c,context:{...c.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),_ve(c),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(c),i.setStatus({code:Ue.ERROR,message:c.message}),c}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!i?.destructiveHint,c=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,l):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&c&&!d){const f=c.getCachedResult(t,l);if(f!==void 0)return p.debug(`[${s}] Cache HIT for tool: ${t}`),f}else d&&p.debug(`[${s}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const m=async f=>{if(this.mcpToolMiddlewares.length===0)return f();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:i,execute:async()=>({})},r,{toolMeta:{name:t,annotations:i}},y)}return f()};return await y()},h=async()=>{const f=this.externalServerManager.getAllTools(),g=f.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},w=this.mcpToolRouter.route(v);y=g.find(E=>E.serverId===w.serverId)||g[0],p.debug(`[${s}] Router selected server: ${w.serverId}`,{strategy:w.strategy,confidence:w.confidence})}catch(v){p.warn(`[${s}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(p.debug(`[${s}] External MCP tool search:`,{toolName:t,externalToolsCount:f.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{ne.debug(`[${s}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return p.debug(`[${s}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw p.error(`[${s}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},w=n.authContext||{},E=nb({...v,...w,hitlState:o},this.resolveFileToolRoots(void 0));p.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(E)});const _=await this.toolRegistry.executeTool(t,r,E);if(_&&typeof _=="object"&&"success"in _&&_.success===!1){const C=_.error||"Tool execution failed",A=new Error(C);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return _}catch(v){const w=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",w),v instanceof Error&&v.message.includes("not found")){const E=await this.getAllAvailableTools();throw pe.toolNotFound(t,E.map(_=>_.name))}throw pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const f=await m(h);return a&&c&&f!==void 0&&(c.cacheResult(t,l,f),p.debug(`[${s}] Cached result for tool: ${t}`)),f}catch(f){const g=i?{name:t,description:"",annotations:i,execute:async()=>({})}:void 0;if(g&&iY(g)&&f instanceof Error&&Uz(f)){p.debug(`[${s}] Tool ${t} is safe to retry, attempting once more`);try{const y=await m(h);return a&&c&&y!==void 0&&c.cacheResult(t,l,y),y}catch{}}throw f}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Od({name:t,description:""})}invalidateToolCache(){this.toolCache=null,p.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return p.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();p.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!Nn,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(uk(),yT)),s=o.getMemoryUsageMB();try{const i=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!i.has(g.name)){const y=PM(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});i.set(g.name,y)}const c=this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0}));for(const g of c)if(!i.has(g.name)){const y=PM(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:Hi({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});i.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory("in-memory");for(const g of l)if(!i.has(g.name)){const y=PM(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(g.name,y)}const u=this.externalServerManager.getAllTools();for(const g of u)if(!i.has(g.name)){const y=PM(g,{category:Hi({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});i.set(g.name,y)}const d=Array.from(i.values());ne.debug("Tool discovery results",{mcpTools:a.length,customTools:c.length,inMemoryTools:l.length,externalMCPTools:u.length,total:d.length});const h=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(h>_m.LOW_USAGE_MB&&(ne.debug(`\u{1F50D} Tool listing used ${h}MB memory (large tool registry detected)`),d.length>whe.LARGE_TOOL_COLLECTION&&ne.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=Od({name:g.name,description:g.description||""}));const f=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:f,timestamp:Date.now()},f}catch(i){return ne.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(uk(),yT)),n=r.getMemoryUsageMB();t?.quiet||ne.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||ne.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Aa(),Lk)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(Op(),ak)),i=kr.getAllDescriptors().map(m=>m.name),a=af(la.DEFAULT_CONCURRENCY_LIMIT),c=i.map(m=>a(async()=>{const h=Date.now();try{if(!await this.hasProviderEnvVars(m)&&m!=="ollama")return{provider:m,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-h};if(m==="ollama")try{const _=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(pc.AUTH_MS)});if(!_.ok)throw new Error("Ollama service not responding");const C=await _.json(),A=C?.models;if(!Array.isArray(A))throw p.warn("Ollama API returned invalid models format in testProvider",{responseData:C,modelsType:typeof A}),new Error("Invalid models format from Ollama API");const k=A.filter(R=>R&&typeof R=="object"&&typeof R.name=="string");return k.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h,model:k[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-h}}catch(_){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:_ instanceof Error?_.message:"Ollama service not running",responseTime:Date.now()-h}}const g=5e3,y=new AbortController,v=this.testProviderConnection(m,y.signal);let w;const E=new Promise((_,C)=>{w=setTimeout(()=>{C(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,E])}finally{clearTimeout(w),v.catch(()=>{}),y.abort()}return{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h}}catch(f){const g=f instanceof Error?f.message:String(f);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-h}}})),l=await Promise.all(c),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&ne.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),l}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(Aa(),Lk));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(Op(),ak));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(Op(),ak));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(Op(),ak));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,c=r.connectedServers+o.length+s.length,l=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:c,autoDiscoveredCount:i.length,totalTools:l,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return ne.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Rg(),dT));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return p.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Rg(),dT)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Rg(),dT));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Rg(),dT)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Rg(),dT));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,p.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new x1(AI.FAILURE_THRESHOLD,cU)),ne.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),ne.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(const i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(const i of o){const 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&&r++;const m=[],h=[];if(l&&l.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),h.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),h.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),h.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const f=a.errorCategories;f.timeout>0&&(m.push(`Timeout errors: ${f.timeout}`),h.push("Consider increasing the tool timeout configuration")),f.validation>0&&(m.push(`Validation errors: ${f.validation}`),h.push("Review input schemas and parameter validation")),f.network>0&&(m.push(`Network errors: ${f.network}`),h.push("Check network connectivity and endpoint availability"))}t[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:m,recommendations:h}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return p.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:je.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return p.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return p.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return p.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await ze(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return p.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return p.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const s=await ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(s.length===0)return p.debug("No messages found for session export",{sessionId:t}),null;const i=this.conversationMemory.getSession(t),a=await ze(i instanceof Promise?i:Promise.resolve(i),o,new Error("getSession operation timed out after 30s")),c=new Date().toISOString(),l={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():c,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():c,messages:s};return r.includeMetadata&&(l.exportMetadata={exportedAt:c,exportFormat:r.format||"json"}),p.debug("Exported conversation session",{sessionId:t,messageCount:s.length}),l}catch(s){return p.error("Failed to export conversation session",{sessionId:t,error:s instanceof Error?s.message:String(s)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,s=6e4;try{const i=await ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const c of i){const l=await ze(this.exportSession(c.id,r),s,new Error(`exportSession operation timed out after 60s for session ${c.id}`));l&&a.push(l)}return p.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(i){return p.error("Failed to export all conversation sessions",{userId:t,error:i instanceof Error?i.message:String(i)}),[]}}async storeToolExecutions(t,r,n,o,s){const i=n&&n.length>0||o&&o.length>0;if(!i){p.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){p.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,s)}catch(c){p.warn("Failed to store tool executions",{sessionId:t,userId:r,error:c instanceof Error?c.message:String(c)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:je.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:je.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:r(o[s].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{ne.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(ne.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new t2({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const s of o)this.mcpToolRouter.registerServer(s.id||t);p.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else ne.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?No(r.url):void 0});return n}catch(n){throw ne.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{ne.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(ne.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?ne.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):ne.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw ne.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.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(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let s=r;try{s=this.resolveDirectMcpToolName(t,r),ne.debug(`[NeuroLink] Executing external MCP tool: ${s} on ${t}`);const i=this.getToolAnnotationsForExecution(s),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,c={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},l=this._generationTurnActive?this.toolCacheRepeatKey(s,c):void 0,u=l!==void 0&&this._toolCacheKeysServedThisRequest.has(l);if(l!==void 0&&this._toolCacheKeysServedThisRequest.add(l),a&&this.mcpToolResultCache&&!u){const f=this.mcpToolResultCache.getCachedResult(s,c);if(f!==void 0)return ne.debug(`[NeuroLink] Tool result cache HIT: ${s} on ${t}`),f}const d=await this.externalServerManager.executeTool(t,s,n,o),m=d&&typeof d=="object"?d:void 0,h=!!(m&&"isError"in m&&m.isError===!0||m&&"success"in m&&m.success===!1);return a&&this.mcpToolResultCache&&!h&&d!==void 0&&this.mcpToolResultCache.cacheResult(s,c,d),ne.debug(`[NeuroLink] External MCP tool ${h?"returned error":"executed successfully"}: ${s}`),d}catch(i){throw ne.error(`[NeuroLink] External MCP tool execution failed: ${s}`,i),i}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(i=>i.name);if(o.includes(r))return r;const s=AJ(r,o);if(!s)throw new xJ(r,t,w_t(r,o));return Be.mcp.startActiveSpan("neurolink.mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":s.name,"mcp.tool_name.repair_strategy":s.strategy,...s.score!==void 0?{"mcp.tool_name.repair_score":s.score}:{}}},i=>i.end()),ne.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${s.name}" (${s.strategy}) on server '${t}'`),s.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await ze(Promise.resolve().then(()=>(ire(),C3t)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{ne.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),ne.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw ne.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await ze(Promise.resolve().then(()=>(Ojt(),Mjt)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await ze(Promise.resolve().then(()=>(Qee(),FLt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await ze(Promise.resolve().then(()=>(ete(),$Lt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await ze(Promise.resolve().then(()=>(Fjt(),Djt)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Jse(),Wse)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Jse(),Wse)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await ze(Promise.resolve().then(()=>(jjt(),Bjt)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await ze(Promise.resolve().then(()=>(GO(),aY)),1e4),o=t.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await ze(Promise.resolve().then(()=>(GO(),aY)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await ze(Promise.resolve().then(()=>(eC(),LCt)),1e4),s=this.toolRegistry.getToolInfo(t);if(!s)return null;const i=s.tool.annotations,a=r({name:s.tool.name,description:s.tool.description??""}),c=n(a,i);return{annotations:c,summary:o(c)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async s=>{try{ne.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});const i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return ne.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw ne.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};r[n.name]=o,ne.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return ne.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),ne.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){ne.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),ne.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){ne.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await nQr().then(()=>Wjt),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw p.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);ne.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){ne.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const s=new r(o);return await ze(s.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4)),p.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async decide(t){const r=t.provider??D1(this.resolveCredentials(t.credentials));if(!r)throw new Error(`No decision provider is configured. Set ${PCr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`);const n=Object.keys(t.questions).length;return dt({name:`gen_ai.${r}.decide`,tracer:Be.decision,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":n}},async o=>{const{traceId:s,parentSpanId:i}=zh(),a=Date.now();let c=Ce.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":n},i,s);try{const l=await Nn.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof l.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const u=await l.decide({state:t.state,questions:t.questions,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),d=Object.keys(u.answers).length,m=Ei(r,u.model,{input:u.usage.inputTokens,output:u.usage.outputTokens,total:u.usage.inputTokens+u.usage.outputTokens});o.setAttribute("gen_ai.response.model",u.model),o.setAttribute("gen_ai.usage.input_tokens",u.usage.inputTokens),o.setAttribute("gen_ai.usage.output_tokens",u.usage.outputTokens),o.setAttribute("decision.answer_count",d),o.setAttribute("ai.cost.total",m),u.upstreamMs!==void 0&&o.setAttribute("decision.upstream_ms",u.upstreamMs),u.requestId&&o.setAttribute("gen_ai.response.id",u.requestId),c.durationMs=Date.now()-a,c=Ce.updateAttributes(c,{"ai.model":u.model,"ai.tokens.input":u.usage.inputTokens,"ai.tokens.output":u.usage.outputTokens,"ai.cost.input":m,"ai.cost.output":0,"ai.cost.total":m,"decision.answer_count":d,"decision.latency_ms":u.latencyMs,...u.upstreamMs!==void 0?{"decision.upstream_ms":u.upstreamMs}:{}});const h=Ce.endSpan(c,1);return this.metricsAggregator.recordSpan(h),rt().recordSpan(h),u}catch(l){c.durationMs=Date.now()-a;const u=Ce.endSpan(c,2,l instanceof Error?l.message:String(l));throw this.metricsAggregator.recordSpan(u),rt().recordSpan(u),l}})}async tryDecide(t){try{const r=await this.decide(t);return p.shouldLog("debug")&&p.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return p.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let s;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?s={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(l=>({id:l})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:s=o("quality"),r?.passThreshold!==void 0&&(s.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(s.executionMode=r.executionMode);const i=new n(s);await ze(i.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,c=await ze(i.execute(t,{correlationId:r?.correlationId}),a,pe.evaluationTimeout("pipeline execution",a));return p.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:c.overallScore,passed:c.passed,scorerCount:c.scores.length}),c}async score(t,r,n){const{ScorerRegistry:o}=await ze(Promise.resolve().then(()=>(ZV(),XV)),1e4,pe.evaluationTimeout("scorer module load",1e4));await ze(o.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));const s=await ze(o.getScorer(t,n),3e4,pe.evaluationTimeout(`scorer load: ${t}`,3e4));if(!s)throw pe.scorerNotFound(t);const i=s.validateInput(r);if(!i.valid)throw pe.evaluationValidationFailed(t,i.errors);const a=await ze(s.score(r),6e4,pe.evaluationTimeout("scorer execution",6e4));return p.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await ze(Promise.resolve().then(()=>(ZV(),XV)),1e4,pe.evaluationTimeout("scorer module load",1e4));await ze(r.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(tie(),Kjt));return p.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(Yjt(),Jjt));return p.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},s={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:{...this.observabilityConfig??{},langfuse:{...this.observabilityConfig?.langfuse??{},autoDetectExternalProvider:!0,skipLangfuseSpanProcessor:!0}},...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},i=this.workerToolsConfig(o.tools),a=new b3(i?{...s,tools:i}:s);if(t?.shareToolRegistry!==!1)for(const c of this.uncacheableTools)a.uncacheableTools.add(c);if(p.setEventEmitter(n),t?.onLog){const c=t.onLog,l=f=>{try{const g=f??{};c({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},u={emit:(f,...g)=>(f==="log-event"&&l(g[0]),!0)},d=a.logInstanceId;p.addScopedEventEmitter(d,u);const m=()=>{p.removeScopedEventEmitter(d,u),this.ownedWorkerLogBridgeDetachers.delete(m)};this.ownedWorkerLogBridgeDetachers.add(m);const h=a.dispose.bind(a);a.dispose=async()=>{m(),await h()}}return p.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(YA(),a2));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(YA(),a2));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(YA(),a2));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(ZA(),d2)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=zWr(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return FWr(t??Jo(this))}clearTaskState(t){return $Wr(t??Jo(this))}registerDelegationTools(t){if(iKr(this,t),this.hasBackgroundDelegationTools)return;const r=gKr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return _Bt(this,t)}async collectDelegates(t){return ABt(this,t)}async cancelDelegates(t){return Qne(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(p.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{p.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=g5t(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,p.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":$re(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new eUt(this.mcpOutputNormalizerConfig,t)),p.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return P9r(this,t,r)}async readArtifact(t,r){return M9r(this,t,r)}registerBackgroundCommandTools(t){if(MBt(this,t),this.hasBackgroundCommandTools)return;const r=CKr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){MBt(this,t)}async startBackgroundCommand(t,r){return BBt(this,t,r)}getBackgroundCommandStatus(t){return zBt(this,t)}async awaitBackgroundCommand(t,r){return moe(this,t,r)}async killBackgroundCommand(t,r){return qBt(this,t,r)}async readBackgroundCommandOutput(t,r){return w2(this,t,r)}registerGitTools(t){if(AKr(this,t),this.hasGitTools)return;const r=OKr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return tzt(this,t,r)}async executeNetwork(t,r,n){return p.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){p.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(eVt(),Qjt));return p.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(rVt(),tVt));return p.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(oVt(),nVt));return p.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){p.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await GBt(this),await Qne(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error stopping background work:",r)}try{p.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await hO(),await fO(),p.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{p.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),p.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),p.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{p.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),p.clearEventEmitter(this.emitter),p.clearScopedEventEmitters(this.logInstanceId),p.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();p.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{p.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),p.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{p.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=[],p.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{p.debug("[NeuroLink] Shutting down TaskManager..."),await ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){p.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{p.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,p.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error resetting state:",r)}t.length===0?p.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):p.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw p.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new Uv({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()),s=Vi({provider:r?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Fv(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const s=Vi({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?Vi({provider:r||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(cF(),sVt));r=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=r,p.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(OA(),BL));r.set(t),p.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(OA(),BL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(OA(),BL)),r=t.get()?.user.id;t.clear(),r&&p.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(s=>typeof t[s]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(p.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async s=>{if(typeof t[s]=="function"){const i=await Gre(t[s],o);t[s]=i.value,p.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof t.tools=="function"){const s=await Gre(t.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}`);t.enabledToolNames=s.value,delete t.tools}}},die=new $T,lVt=die}});function uVt(e,t,r,n){const o=typeof e=="object"&&e!==null?e.data:void 0;if(!Array.isArray(o)||o.length===0)throw n(`${r} embeddings response missing data`);if(o.length!==t)throw n(`${r} embeddings response count mismatch: expected ${t}, got ${o.length}`);const s=o.findIndex(a=>!dVt(a));if(s!==-1)throw n(`${r} embeddings response entry ${s} is not an {index, embedding: number[]} object`);const i=o.slice().sort((a,c)=>a.index-c.index);for(let a=0;a<i.length;a++)if(i[a].index!==a)throw n(`${r} embeddings response has unexpected index ordering: position ${a} has index ${i[a].index}`);return i.map(a=>a.embedding)}var dVt,mVt=b({"src/lib/providers/embeddingResponseParsing.ts"(){"use strict";dVt=e=>{if(typeof e!="object"||e===null)return!1;const{embedding:t,index:r}=e;return Number.isInteger(r)&&Array.isArray(t)&&t.every(n=>typeof n=="number"&&Number.isFinite(n))}}}),pVt={};ee(pVt,{VoyageProvider:()=>gVt});var hVt,mie,fVt,uF,gVt,mQr=b({async"src/lib/providers/voyage.ts"(){"use strict";Wa(),await Dl(),mVt(),On(),ut(),Ze(),z(),ts(),hVt="https://api.voyageai.com/v1",mie=6e4,fVt=()=>ca(TCr()),uF=()=>yi("VOYAGE_MODEL","voyage-3.5"),gVt=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"voyage",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:fVt(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??hVt,this.proxyFetch=Pt(),p.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return uF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return uF()}getAISDKModel(){throw new ot("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 ot("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){const 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 Mr("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Oo(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new ot(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],t);if(!n[0])throw new ot("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const s=e.slice(o,o+r),i=await this.callEmbeddings(s,t);n.push(...i)}return n}async callEmbeddings(e,t){const r=t??this.modelName;let n;try{n=await ze(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:r})}),mie,new ot(`Voyage embeddings request timed out after ${mie/1e3}s`,"voyage"))}catch(s){throw s instanceof ot?s:this.formatProviderError(s)}if(!n.ok){const s=await n.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${n.status} \u2014 ${s}`))}const o=await n.json();return uVt(o,e.length,"Voyage",s=>new ot(s,"voyage"))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:uF(),baseURL:this.baseURL}}}}}),yVt={};ee(yVt,{JinaProvider:()=>wVt});var vVt,Ek,TVt,dF,wVt,pQr=b({async"src/lib/providers/jina.ts"(){"use strict";Wa(),await Dl(),mVt(),On(),ut(),z(),ts(),vVt="https://api.jina.ai/v1",Ek=6e4,TVt=()=>ca(wCr()),dF=()=>yi("JINA_MODEL","jina-embeddings-v3"),wVt=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"jina",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:TVt(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??vVt,this.proxyFetch=Pt(),p.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return dF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return dF()}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){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mr("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Oo(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new ot(`Jina AI error: ${t}`,"jina")}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],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,r={}){if(t.length===0)return[];const n=r.model??"jina-reranker-v2-base-multilingual",o=r.credentials,s=o?.apiKey?.trim()||this.apiKey,i=o?.baseURL||this.baseURL,a=new AbortController,c=setTimeout(()=>a.abort(),Ek);let l;try{l=await this.proxyFetch(`${i}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({model:n,query:e,documents:t,top_n:r.topN??t.length}),signal:a.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${Ek/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(c)}if(!l.ok){const d=await l.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${l.status} \u2014 ${d}`))}return((await l.json()).results??[]).map(d=>({index:d.index,score:d.relevance_score,document:t[d.index]??d.document?.text??""}))}async callEmbeddings(e,t,r){const n=t??this.modelName,o=r?.apiKey?.trim()||this.apiKey,s=r?.baseURL||this.baseURL,i=new AbortController,a=setTimeout(()=>i.abort(),Ek);let c;try{c=await this.proxyFetch(`${s}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:i.signal})}catch(u){throw u instanceof Error&&u.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${Ek/1e3}s`)):this.formatProviderError(u)}finally{clearTimeout(a)}if(!c.ok){const u=await c.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${c.status} \u2014 ${u}`))}const l=await c.json();return uVt(l,e.length,"Jina",u=>new Error(u))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:dF(),baseURL:this.baseURL}}}}}),EVt={};ee(EVt,{StabilityProvider:()=>fie,default:()=>_Vt});var SVt,pie,bVt,hie,fie,_Vt,hQr=b({async"src/lib/providers/stability.ts"(){"use strict";Wa(),await Dl(),On(),ut(),z(),ts(),SVt="https://api.stability.ai",pie=12e4,bVt=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,hie=()=>yi("STABILITY_MODEL","stable-image-ultra"),fie=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"stability",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:bVt(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??SVt,this.proxyFetch=Pt(),p.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return hie()}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){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mr("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new ot("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Oo(`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 ot(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.stability,n=r?.apiKey?.trim()||this.apiKey;if(!n)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");const o=n,s=r?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");const a=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,c=e,l=new FormData;l.append("prompt",i),l.append("output_format","png"),c.aspectRatio&&l.append("aspect_ratio",String(c.aspectRatio)),c.negativePrompt&&l.append("negative_prompt",c.negativePrompt),this.modelName.startsWith("sd3.5-")&&l.append("model",this.modelName),c.seed!==void 0&&l.append("seed",String(c.seed));const u=new AbortController,d=setTimeout(()=>u.abort(),pie);let m;try{m=await this.proxyFetch(`${s}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:l,signal:u.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${pie/1e3}s`)):this.formatProviderError(g)}finally{clearTimeout(d)}if(!m.ok){const g=await m.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${m.status} \u2014 ${g}`))}const h=await m.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);const f=Date.now()-t;return p.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${f}ms \u2014 model ${this.modelName}`),{content:i,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:hie(),baseURL:this.baseURL}}},_Vt=fie}}),CVt={};ee(CVt,{IdeogramProvider:()=>vie,default:()=>xVt});var AVt,gie,kVt,yie,vie,xVt,fQr=b({async"src/lib/providers/ideogram.ts"(){"use strict";Wa(),await Dl(),On(),ut(),z(),ts(),ya(),mp(),AVt="https://api.ideogram.ai",gie=12e4,kVt=()=>ca(ECr()),yie=()=>yi("IDEOGRAM_MODEL","V_3"),vie=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"ideogram",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:kVt(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??AVt,this.proxyFetch=Pt(),p.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return yie()}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){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mr("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new ot("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new ot(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.ideogram,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const i=e,a={prompt:s,model:this.modelName,magic_prompt:i.magicPrompt??"AUTO"};i.aspectRatio&&(a.aspect_ratio=i.aspectRatio),i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.seed!==void 0&&(a.seed=i.seed),i.style&&(a.style_type=i.style);const c=new AbortController,l=setTimeout(()=>c.abort(),gie);let u;try{u=await this.proxyFetch(`${o}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":n,"Content-Type":"application/json"},body:JSON.stringify(a),signal:c.signal})}catch(E){throw E instanceof Error&&E.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${gie/1e3}s`)):this.formatProviderError(E)}finally{clearTimeout(l)}if(!u.ok){const E=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${E}`))}const m=(await u.json()).data?.[0]?.url;if(!m)throw new Error("Ideogram returned no image URL");await dp(m);const h=new AbortController,f=setTimeout(()=>h.abort(),6e4);let g;try{g=await this.proxyFetch(m,{signal:h.signal})}catch(E){throw E instanceof Error&&E.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:E}):E}finally{clearTimeout(f)}if(!g.ok)throw new Error(`Failed to download Ideogram image: ${g.status}`);const y=await Eu(g,up,"Ideogram image"),v=y.toString("base64"),w=Date.now()-t;return p.info(`[IdeogramProvider] Generated image (${y.length} bytes) in ${w}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:v}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:yie(),baseURL:this.baseURL}}},xVt=vie}}),IVt={};ee(IVt,{ReplicateProvider:()=>RVt});function gQr(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
2145
+ 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(" ");t.systemPrompt=(t.systemPrompt||"")+l,p.info("[RAG] Tool injected into stream()",{toolName:c.toolName,filesLoaded:c.filesLoaded,chunksIndexed:c.chunksIndexed})}catch(a){p.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const s=sYr(t),i=iYr(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(t.input.text,void 0);c!==t.input.text&&(i.input.text=c)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(ef(),iHe)),s=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=t.model;s.length>0&&i&&(s.some(c=>i.toLowerCase().includes(c.toLowerCase()))||(t.disableTools=!0,p.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,m)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{const m=d[0];n("response:chunk",{content:m})},s=(...d)=>{const m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{const m=d[0],h=m.toolName??m.tool,f=m.responseTime??m.duration,g=m.success??(m.error!==void 0?!1:void 0),y={...m,toolName:h,...f!==void 0?{responseTime:f}:{},...g!==void 0?{success:g}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",y),y.result&&y.result.uiComponent===!0&&n("ui-component",{toolName:h,componentData:y.result,timestamp:Date.now(),...g!==void 0?{success:g}:{},...f!==void 0?{responseTime:f}:{}})},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:t,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(t,r,n,o,s,i){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const f=this._metricsTraceContext;let g=Ce.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:f?.traceId,parentSpanId:f?.parentSpanId});g=Ce.endSpan(g,2),g.statusMessage=a,g.durationMs=0,this.metricsAggregator.recordSpan(g),rt().recordSpan(g)}catch{}const 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,m=I2.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),h={...m,provider:c??u??m.provider,model:l??d??m.model};p.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:h.provider,fallbackModel:h.model,fallbackSource:c||l?"options":u||d?"env":"model_config",reason:a});try{const f=await Nn.createProvider(h.provider,h.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));f.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,A)=>this.executeTool(C,A,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const g=o.conversationMessages!==void 0?o.conversationMessages:await Sp(this.conversationMemory,{prompt:o.input.text,context:o.context});f.setFileToolRootPolicy?.(this.fileToolRootsFor(o));const y=await f.stream({...this.deferProviderStreamTTS(o),model:h.model,conversationMessages:g}),v=y.toolCalls??[],w=y.toolResults??[];(v.length>0||w.length>0)&&(r.toolCalls=v,r.toolResults=w,r.finishReason=y.finishReason??r.finishReason);let E=0,_=0;for await(const C of y.stream){E++;const A=C!==null&&typeof C=="object"&&"metadata"in C&&C.metadata?.noOutput===!0,k=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&&(k||R)&&_++,C&&"content"in C&&typeof C.content=="string"&&(i(C.content),this.emitter.emit("response:chunk",C.content)),yield C}if(_===0&&v.length===0&&w.length===0)throw new Error(`Fallback provider ${h.provider} also returned 0 real output chunks (chunkCount=${E}, sentinel-only or empty)`);t.fallbackProvider=h.provider,t.fallbackModel=h.model,t.guardrailsBlocked=!0}catch(f){const g=f instanceof Error?f.message:String(f);throw t.error=`${a}; Fallback failed: ${g}`,p.error("Fallback provider failed",{fallbackProvider:h.provider,error:g}),f}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=t;p.shouldLog("debug")&&p.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:P1(O1(r)),sessionId:r.context?.sessionId});const c=a.some(l=>l.type==="tool:start"||l.type==="tool:end");if(!s.trim()&&!c){p.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(p.shouldLog("debug")&&p.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:P1(O1(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const l=r.context?.sessionId,u=r.context?.userId;let d;r.model&&(d={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(l);await this.conversationMemory.storeConversationTurn({sessionId:l,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),p.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:l,eventCount:a.length,eventTypes:[...new Set(a.map(f=>f.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),p.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}this.shouldWriteMemory(r.memory,r.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();p.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=await pT(t.provider),n=await Nn.createProvider(r,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await n.ensureModelLimits?.(),n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(f,g)=>this.executeTool(f,g,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),i=t.conversationMessages!==void 0,a=i?t.conversationMessages:await Sp(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=a;let c=a;const l=Vi({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:o,compactionThreshold:t.compactionThreshold}),u=c?.length||0,d=this.getCompactionSessionId(t),m=u>0;if(!l.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:l.estimatedInputTokens,budget:l.availableInputTokens,provider:r,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Ta(`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)){const g=await new Uv({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()).compact(c,PN(l,t.compactionThreshold),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId,{currentRequest:t.input.text});g.compacted&&(c=Fv(g.messages).messages,t.conversationMessages=c,this.lastCompactionMessageCount.set(d,c.length));const y=Vi({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:o});if(!y.withinBudget){p.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:y.estimatedInputTokens,availableTokens:y.availableInputTokens,overagePercent:Math.round((y.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:y.estimatedInputTokens,budget:y.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=uee(c,y.availableInputTokens,y.breakdown,r),t.conversationMessages=c;const v=Vi({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:g.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Ta(`Stream context exceeds model budget after all compaction stages. Estimated: ${v.estimatedInputTokens} tokens, Budget: ${v.availableInputTokens} tokens.`,{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,stagesUsed:g.stagesUsed,breakdown:v.breakdown})}}}if(this.modelPool){const f=this.modelPool,g=f.maxAttempts,y=new Set;let v=null;for(let w=0;w<g;w++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const E=f.selectNext(y);if(!E)break;y.add(f.memberKey(E));const _=E.provider,C=E.model??void 0,A=E.region??void 0;p.debug(`[createMCPStream] ModelPool: attempting member ${_}`,{model:C,attempt:w});try{const k=await Nn.createProvider(_,C,!t.disableTools,this,A,this.resolveCredentials(t.credentials));k.setTraceContext(this._metricsTraceContext),k.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(O,U)=>this.executeTool(O,U,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream"),k.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const R=await k.stream({...this.deferProviderStreamTTS(t),provider:_,model:C,region:A,systemPrompt:s,conversationMessages:c});p.debug("[createMCPStream] ModelPool stream handle obtained",{provider:_});const I=E,P=(async function*(){try{yield*R.stream,f.recordSuccess(I)}catch(O){throw f.recordFailure(I,hT(O)),O}})();return CO(R,{...R,stream:P,provider:_,model:R.model||C,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[]})}catch(k){if(cr(k))throw k;if(uie(k)){const R=k instanceof Error?k.message:String(k);throw f.recordFailure(E,hT(k)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:k})}f.recordFailure(E,hT(k)),v=k instanceof Error?k:new Error(String(k)),p.warn(`[createMCPStream] ModelPool: member ${_} failed`,{error:v.message})}}throw new Error(`[ModelPool] all stream members failed: ${v?.message??"no stream members available"}`)}n.setFileToolRootPolicy?.(this.fileToolRootsFor(t));const h=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:c});return p.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:s.length}),CO(h,{...h,provider:r,model:h.model||t.model,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[]})}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){const o=n.sourceResult,s={streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error},i={...o??{},stream:r,provider:o?.provider??n.providerName,model:o?.model??n.options.model,usage:t.usage,finishReason:t.finishReason,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:o?void 0:Object.assign({},s)},a=Object.getOwnPropertyDescriptor(t,"toolCalls");a&&Object.defineProperty(i,"toolCalls",a);const c=Object.getOwnPropertyDescriptor(t,"toolResults");if(c&&Object.defineProperty(i,"toolResults",c),!o)return i;const l=new Set(["finishReason","stopReason","rawFinishReason","toolCalls","toolResults"]);for(const u of Object.getOwnPropertyNames(o)){const d=Object.getOwnPropertyDescriptor(o,u);!l.has(u)&&d&&typeof d.get=="function"&&Object.defineProperty(i,u,d)}return Object.defineProperty(i,"metadata",{enumerable:!0,configurable:!0,get:()=>(o.metadata===void 0&&(o.metadata={}),Object.assign(o.metadata,s)),set:u=>{o.metadata=u}}),i}async handleStreamError(t,r,n,o,s,i){if(t instanceof Ta)throw t;p.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,c=Date.now()-n,l=await pT(r.provider),u=await Nn.createProvider(l,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials));u.setFileToolRootPolicy?.(this.fileToolRootsFor(r));const d=await u.stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let m="";return{stream:(async function*(f){try{for await(const g of d.stream)g&&"content"in g&&typeof g.content=="string"&&(m+=g.content,f.emitter.emit("response:chunk",g.content)),yield g}finally{if(m.trim()){p.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:r.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{const g=r.model||"unknown",y=Date.now()-n;f.emitter.emit("stream:complete",{content:m,provider:l,model:g,finishReason:"stop",metadata:{durationMs:y,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}}),f.emitter.emit("generation:end",{provider:l,model:g,responseTime:y,timestamp:Date.now(),result:{content:m,usage:{input:0,output:0,total:0},model:g,provider:l,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(f.conversationMemory&&s?.context?.sessionId&&m.trim()){const g=s?.context?.sessionId,y=s?.context?.userId;let v;r.model&&(v={provider:l,model:r.model});const w=Date.now();try{const E=g||r.context?.sessionId,_=f.drainPendingSkillMessages(E);await f.conversationMemory.storeConversationTurn({sessionId:E,userId:y||r.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:v,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||r.context?.requestId,..._.length>0?{skillMessages:_}:{}}),f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,1)}catch(E){f.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-w,2,E instanceof Error?E.message:String(E)),p.warn("Failed to store fallback stream conversation turn",{error:E instanceof Error?E.message:String(E)})}}}})(this),provider:l,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:c,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}fileToolRootsFor(t){return Wj(t)??this.resolveFileToolRoots(t.toolRoots)}workerToolsConfig(t){const r=this.toolsConfig?.fileRoots;if(t?.fileRoots===void 0)return r===void 0?t:{...t,fileRoots:r};const n=PP({perCall:t.fileRoots,instance:r}).roots;return{...t,fileRoots:n?[...n]:[]}}resolveFileToolRoots(t){return PP({perCall:t,instance:this.toolsConfig?.fileRoots})}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(s){const i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof yy?{provider:r,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:r,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:r,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:r,status:"network",detail:i}:{provider:r,status:"unknown",detail:i}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",K0(t,{input:r,timestamp:n,executionId:o})),p.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,s=Date.now(),i){const a=o||s-1e3,c=s-a,l=!n;let u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(h=>h.tool===t&&!h.endTime);const d=i||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const m={tool:t,startTime:a,endTime:s,duration:c,success:l,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",K0(t,{result:r,error:n,success:l,responseTime:c,timestamp:s,duration:c,executionId:d})),p.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:c,success:l,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(e7(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const i=o.execute,a=n.timeout,c=t;o.execute=async(...l)=>{const u=AbortSignal.timeout(a),d=l[1],m=d?.abortSignal,h=m?AbortSignal.any([m,u]):u,f={...d,abortSignal:h};return Promise.race([i(l[0],f),new Promise((g,y)=>{h.addEventListener("abort",()=>{u.aborted?y(pe.toolTimeout(c,a)):y(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const s=u9r(t,o,n?.timeout,n?.maxRetries,n?.totalTimeoutMs);this.toolRegistry.registerServer(s),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw p.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},p.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,p.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),p.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),p.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new Da("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new Da("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await ze(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0})),r=new Map;for(const o of t){const s=o.inputSchema||o.parameters;p.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()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{const c=this.toolExecutionContext||{},l=a&&Zt(a)?a:{},u={...c,...l,sessionId:l.sessionId||c.sessionId||`fallback-${Date.now()}`};return p.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=xLt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,s]of Object.entries(n))if(!r.has(o)){const i=s,a=i.inputSchema??i.parameters;r.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 r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{ne.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),ne.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw ne.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>Hi({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return Be.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(t,r,n,o,s))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(l=>l.name===t),s=o?"mcp":this.getCustomTools().has(t)?"custom":"external",i=r?Hy(r):"",a=Date.now(),c=`${t}-${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(t,r,n,o,s){try{const i=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,i,o,s)}catch(i){if(!(i instanceof Me)){const a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:Ue.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(t,r,n,o){p.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:Zt(r)?w7e(r):r,hasExternalManager:!!this.externalServerManager}),p.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",K0(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const s=this.toolRegistry.getToolInfo(t),i=n?.timeout??s?.tool?.timeoutMs??mc.EXECUTION_BATCH_MS,a=n?.maxRetries??s?.tool?.maxRetries??Qo.DEFAULT,c=n?.retryDelayMs||Fn.BASE_MS,l={timeout:i,maxRetries:a,totalTimeout:n?.totalTimeoutMs??s?.tool?.totalTimeoutMs??i*(a+1)+c*a,retryDelayMs:c,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:u}=await Promise.resolve().then(()=>(uk(),yT)),d=u.getMemoryUsageMB(),h=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${t}`;let f=this.toolCircuitBreakers.get(h);f||(f=new x1(AI.FAILURE_THRESHOLD,cU),this.toolCircuitBreakers.set(h,f));let g=this.toolExecutionMetrics.get(t);return g||(g={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,g)),g.totalExecutions++,{finalOptions:l,startMemory:d,circuitBreaker:f,breakerKey:h,metrics:g}}async runPreparedToolExecution(t,r,n,o,s){let i=0;try{ne.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=n.finalOptions.maxRetries+1,c=n.finalOptions.totalTimeout,l=Date.now(),u=l+c;let d=0;const m=await n.circuitBreaker.execute(async()=>bve(async()=>{d++;const h=u-Date.now();if(h<=0)throw pe.toolTimeout(t,c,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:c,elapsedMs:Date.now()-l,exhausted:!0});const f=Math.min(n.finalOptions.timeout,h);return ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),f,pe.toolTimeout(t,f,void 0,{attempt:d,maxAttempts:a,attemptTimeoutMs:n.finalOptions.timeout,totalTimeoutMs:c,elapsedMs:Date.now()-l}))},{maxAttempts:a,delayMs:n.finalOptions.retryDelayMs,isRetriable:h=>Date.now()+n.finalOptions.retryDelayMs<u&&Uz(h),onRetry:(h,f)=>{i=h,ne.warn(`[${o.functionTag}] Retrying tool execution (attempt ${h})`,{toolName:t,error:f.message,attempt:h})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(t,m,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(t,r,a,n,o,s)}}async handleSuccessfulToolExecution(t,r,n,o,s){const 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;const{MemoryManager:a}=await Promise.resolve().then(()=>(uk(),yT)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&ne.warn(`Tool '${t}' used excessive memory: ${l}MB`,{toolName:t,memoryDelta:l,executionTime:i}),ne.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:i,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,h=d?m?.filter(f=>f.type==="text"&&f.text).map(f=>f.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}ne.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const f=aQr(h??"Unknown error"),g=`[TOOL_ERROR: ${t} failed (${f})] `;if(u&&Array.isArray(m)){const w=m.map(E=>({...E}));for(const E of w)if(E.type==="text"&&E.text){E.text=g+E.text;break}u.content=w}s.setAttribute("tool.error.message",(h??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",f),s.setStatus({code:Ue.ERROR,message:`MCP tool returned isError: ${(h??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const y=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=y>1?(n.metrics.averageExecutionTime*y-i)/(y-1):0;const v=cQr(f);n.metrics.errorCategories[v]=(n.metrics.errorCategories[v]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&h?new Error(h):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),r}async handleFailedToolExecution(t,r,n,o,s,i){o.metrics.failedExecutions++;const a=Date.now()-s.executionStartTime;if(n instanceof Sm)return ne.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (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:Ue.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let c;if(n instanceof Me)c=n;else if(n instanceof Error)if(n.message.includes("timeout"))c=pe.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();c=pe.toolNotFound(t,BNr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?c=pe.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?c=pe.networkError(t,n):c=pe.toolExecutionFailed(t,n);else c=pe.toolExecutionFailed(t,new Error(String(n)));const l=c.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,c,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",c),c=new Me({...c,context:{...c.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),_ve(c),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(c),i.setStatus({code:Ue.ERROR,message:c.message}),c}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!i?.destructiveHint,c=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,l):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&c&&!d){const f=c.getCachedResult(t,l);if(f!==void 0)return p.debug(`[${s}] Cache HIT for tool: ${t}`),f}else d&&p.debug(`[${s}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const m=async f=>{if(this.mcpToolMiddlewares.length===0)return f();let g=0;const y=async()=>{if(g<this.mcpToolMiddlewares.length){const v=this.mcpToolMiddlewares[g++];return v({name:t,description:"",inputSchema:{},annotations:i,execute:async()=>({})},r,{toolMeta:{name:t,annotations:i}},y)}return f()};return await y()},h=async()=>{const f=this.externalServerManager.getAllTools(),g=f.filter(v=>v.name===t&&v.isAvailable);let y;if(g.length>1&&this.mcpToolRouter)try{const v={name:t,description:g[0].description??"",serverId:g[0].serverId,inputSchema:{}},w=this.mcpToolRouter.route(v);y=g.find(E=>E.serverId===w.serverId)||g[0],p.debug(`[${s}] Router selected server: ${w.serverId}`,{strategy:w.strategy,confidence:w.confidence})}catch(v){p.warn(`[${s}] Router failed, falling back to first match`,{error:v}),y=g[0]}else y=g[0];if(p.debug(`[${s}] External MCP tool search:`,{toolName:t,externalToolsCount:f.length,foundTool:!!y,isAvailable:y?.isAvailable,serverId:y?.serverId}),y&&y.isAvailable)try{ne.debug(`[${s}] Executing external MCP tool: ${t} from ${y.serverId}`);const v=await this.externalServerManager.executeTool(y.serverId,t,r,{timeout:n.timeout});return p.debug(`[${s}] External MCP tool execution successful:`,{toolName:t,serverId:y.serverId,resultType:typeof v}),v}catch(v){throw p.error(`[${s}] External MCP tool execution failed:`,{toolName:t,serverId:y.serverId,error:v instanceof Error?v.message:String(v)}),pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)),y.serverId)}try{const v=this.toolExecutionContext||{},w=n.authContext||{},E=nb({...v,...w,hitlState:o},this.resolveFileToolRoots(void 0));p.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(v),finalContextKeys:Object.keys(E)});const _=await this.toolRegistry.executeTool(t,r,E);if(_&&typeof _=="object"&&"success"in _&&_.success===!1){const C=_.error||"Tool execution failed",A=new Error(C);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",A)}return _}catch(v){const w=v instanceof Error?v:new Error(String(v));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",w),v instanceof Error&&v.message.includes("not found")){const E=await this.getAllAvailableTools();throw pe.toolNotFound(t,E.map(_=>_.name))}throw pe.toolExecutionFailed(t,v instanceof Error?v:new Error(String(v)))}};try{const f=await m(h);return a&&c&&f!==void 0&&(c.cacheResult(t,l,f),p.debug(`[${s}] Cached result for tool: ${t}`)),f}catch(f){const g=i?{name:t,description:"",annotations:i,execute:async()=>({})}:void 0;if(g&&iY(g)&&f instanceof Error&&Uz(f)){p.debug(`[${s}] Tool ${t} is safe to retry, attempting once more`);try{const y=await m(h);return a&&c&&y!==void 0&&c.cacheResult(t,l,y),y}catch{}}throw f}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Od({name:t,description:""})}invalidateToolCache(){this.toolCache=null,p.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return p.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();p.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!Nn,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(uk(),yT)),s=o.getMemoryUsageMB();try{const i=new Map,a=await this.toolRegistry.listTools();for(const g of a)if(!i.has(g.name)){const y=PM(g,{serverId:g.serverId==="direct"?"neurolink-direct":g.serverId});i.set(g.name,y)}const c=this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0}));for(const g of c)if(!i.has(g.name)){const y=PM(g,{description:"Custom tool",serverId:`custom-tool-${g.name}`,category:Hi({isCustomTool:!0,serverId:g.serverId}),inputSchema:{}});i.set(g.name,y)}const l=this.toolRegistry.getToolsByCategory("in-memory");for(const g of l)if(!i.has(g.name)){const y=PM(g,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(g.name,y)}const u=this.externalServerManager.getAllTools();for(const g of u)if(!i.has(g.name)){const y=PM(g,{category:Hi({existingCategory:typeof g.metadata?.category=="string"?g.metadata.category:void 0,isExternal:!0,serverId:g.serverId}),inputSchema:{}});i.set(g.name,y)}const d=Array.from(i.values());ne.debug("Tool discovery results",{mcpTools:a.length,customTools:c.length,inMemoryTools:l.length,externalMCPTools:u.length,total:d.length});const h=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(h>_m.LOW_USAGE_MB&&(ne.debug(`\u{1F50D} Tool listing used ${h}MB memory (large tool registry detected)`),d.length>whe.LARGE_TOOL_COLLECTION&&ne.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const g of d)g.annotations||(g.annotations=Od({name:g.name,description:g.description||""}));const f=d.sort((g,y)=>g.name<y.name?-1:g.name>y.name?1:0);return this.toolCache={tools:f,timestamp:Date.now()},f}catch(i){return ne.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(uk(),yT)),n=r.getMemoryUsageMB();t?.quiet||ne.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||ne.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Aa(),Lk)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(Op(),ak)),i=kr.getAllDescriptors().map(m=>m.name),a=af(la.DEFAULT_CONCURRENCY_LIMIT),c=i.map(m=>a(async()=>{const h=Date.now();try{if(!await this.hasProviderEnvVars(m)&&m!=="ollama")return{provider:m,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-h};if(m==="ollama")try{const _=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(pc.AUTH_MS)});if(!_.ok)throw new Error("Ollama service not responding");const C=await _.json(),A=C?.models;if(!Array.isArray(A))throw p.warn("Ollama API returned invalid models format in testProvider",{responseData:C,modelsType:typeof A}),new Error("Invalid models format from Ollama API");const k=A.filter(R=>R&&typeof R=="object"&&typeof R.name=="string");return k.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h,model:k[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-h}}catch(_){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:_ instanceof Error?_.message:"Ollama service not running",responseTime:Date.now()-h}}const g=5e3,y=new AbortController,v=this.testProviderConnection(m,y.signal);let w;const E=new Promise((_,C)=>{w=setTimeout(()=>{C(new Error("Provider test timeout (5s)"))},g)});try{await Promise.race([v,E])}finally{clearTimeout(w),v.catch(()=>{}),y.abort()}return{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h}}catch(f){const g=f instanceof Error?f.message:String(f);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:g,responseTime:Date.now()-h}}})),l=await Promise.all(c),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&ne.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),l}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t,r){const{AIProviderFactory:n}=await Promise.resolve().then(()=>(Aa(),Lk));await(await n.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0,abortSignal:r})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(Op(),ak));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(Op(),ak));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(Op(),ak));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,c=r.connectedServers+o.length+s.length,l=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:c,autoDiscoveredCount:i.length,totalTools:l,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(Hi({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return ne.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Rg(),dT));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return p.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(Rg(),dT)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Rg(),dT));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(Rg(),dT)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(Rg(),dT));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,p.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new x1(AI.FAILURE_THRESHOLD,cU)),ne.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),ne.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(const i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(const i of o){const 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&&r++;const m=[],h=[];if(l&&l.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),h.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),h.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),h.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const f=a.errorCategories;f.timeout>0&&(m.push(`Timeout errors: ${f.timeout}`),h.push("Consider increasing the tool timeout configuration")),f.validation>0&&(m.push(`Validation errors: ${f.validation}`),h.push("Review input schemas and parameter validation")),f.network>0&&(m.push(`Network errors: ${f.network}`),h.push("Check network connectivity and endpoint availability"))}t[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:m,recommendations:h}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return p.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:je.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return p.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return p.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return p.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await ze(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return p.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return p.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const s=await ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(s.length===0)return p.debug("No messages found for session export",{sessionId:t}),null;const i=this.conversationMemory.getSession(t),a=await ze(i instanceof Promise?i:Promise.resolve(i),o,new Error("getSession operation timed out after 30s")),c=new Date().toISOString(),l={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():c,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():c,messages:s};return r.includeMetadata&&(l.exportMetadata={exportedAt:c,exportFormat:r.format||"json"}),p.debug("Exported conversation session",{sessionId:t,messageCount:s.length}),l}catch(s){return p.error("Failed to export conversation session",{sessionId:t,error:s instanceof Error?s.message:String(s)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,s=6e4;try{const i=await ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const c of i){const l=await ze(this.exportSession(c.id,r),s,new Error(`exportSession operation timed out after 60s for session ${c.id}`));l&&a.push(l)}return p.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(i){return p.error("Failed to export all conversation sessions",{userId:t,error:i instanceof Error?i.message:String(i)}),[]}}async storeToolExecutions(t,r,n,o,s){const i=n&&n.length>0||o&&o.length>0;if(!i){p.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){p.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,s)}catch(c){p.warn("Failed to store tool executions",{sessionId:t,userId:r,error:c instanceof Error?c.message:String(c)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:je.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Me({code:je.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Me({code:je.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:r(o[s].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{ne.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(ne.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new t2({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const s of o)this.mcpToolRouter.registerServer(s.id||t);p.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else ne.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?No(r.url):void 0});return n}catch(n){throw ne.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{ne.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(ne.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?ne.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):ne.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw ne.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.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(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){let s=r;try{s=this.resolveDirectMcpToolName(t,r),ne.debug(`[NeuroLink] Executing external MCP tool: ${s} on ${t}`);const i=this.getToolAnnotationsForExecution(s),a=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,c={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},l=this._generationTurnActive?this.toolCacheRepeatKey(s,c):void 0,u=l!==void 0&&this._toolCacheKeysServedThisRequest.has(l);if(l!==void 0&&this._toolCacheKeysServedThisRequest.add(l),a&&this.mcpToolResultCache&&!u){const f=this.mcpToolResultCache.getCachedResult(s,c);if(f!==void 0)return ne.debug(`[NeuroLink] Tool result cache HIT: ${s} on ${t}`),f}const d=await this.externalServerManager.executeTool(t,s,n,o),m=d&&typeof d=="object"?d:void 0,h=!!(m&&"isError"in m&&m.isError===!0||m&&"success"in m&&m.success===!1);return a&&this.mcpToolResultCache&&!h&&d!==void 0&&this.mcpToolResultCache.cacheResult(s,c,d),ne.debug(`[NeuroLink] External MCP tool ${h?"returned error":"executed successfully"}: ${s}`),d}catch(i){throw ne.error(`[NeuroLink] External MCP tool execution failed: ${s}`,i),i}}resolveDirectMcpToolName(t,r){const n=this.getExternalMCPServer(t);if(!n||n.status!=="connected"||!n.client)return r;const o=this.getExternalMCPServerTools(t).map(i=>i.name);if(o.includes(r))return r;const s=AJ(r,o);if(!s)throw new xJ(r,t,w_t(r,o));return Be.mcp.startActiveSpan("neurolink.mcp.toolNameRepair",{attributes:{"mcp.server_id":t,"mcp.tool_name.requested":r,"mcp.tool_name.resolved":s.name,"mcp.tool_name.repair_strategy":s.strategy,...s.score!==void 0?{"mcp.tool_name.repair_score":s.score}:{}}},i=>i.end()),ne.info(`[NeuroLink] Repaired external MCP tool name at direct execution boundary: "${r}" \u2192 "${s.name}" (${s.strategy}) on server '${t}'`),s.name}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await ze(Promise.resolve().then(()=>(ire(),C3t)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{ne.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),ne.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw ne.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await ze(Promise.resolve().then(()=>(Ojt(),Mjt)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await ze(Promise.resolve().then(()=>(Qee(),FLt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await ze(Promise.resolve().then(()=>(ete(),$Lt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await ze(Promise.resolve().then(()=>(Fjt(),Djt)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Jse(),Wse)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await ze(Promise.resolve().then(()=>(Jse(),Wse)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await ze(Promise.resolve().then(()=>(jjt(),Bjt)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await ze(Promise.resolve().then(()=>(GO(),aY)),1e4),o=t.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await ze(Promise.resolve().then(()=>(GO(),aY)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await ze(Promise.resolve().then(()=>(eC(),LCt)),1e4),s=this.toolRegistry.getToolInfo(t);if(!s)return null;const i=s.tool.annotations,a=r({name:s.tool.name,description:s.tool.description??""}),c=n(a,i);return{annotations:c,summary:o(c)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async s=>{try{ne.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});const i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return ne.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw ne.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};r[n.name]=o,ne.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return ne.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),ne.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){ne.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),ne.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){ne.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await nQr().then(()=>Wjt),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw p.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);ne.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){ne.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const s=new r(o);return await ze(s.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4)),p.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async decide(t){const r=t.provider??D1(this.resolveCredentials(t.credentials));if(!r)throw new Error(`No decision provider is configured. Set ${PCr()} (in the environment or in \`credentials\`), or pass \`provider\` explicitly.`);const n=Object.keys(t.questions).length;return dt({name:`gen_ai.${r}.decide`,tracer:Be.decision,attributes:{"gen_ai.system":r,"gen_ai.operation.name":"decide","ai.provider":r,"decision.question_count":n}},async o=>{const{traceId:s,parentSpanId:i}=zh(),a=Date.now();let c=Ce.createSpan("model.decision",`decision.${r}`,{"ai.provider":r,"ai.model":t.model??"","decision.question_count":n},i,s);try{const l=await Nn.createProvider(r,t.model,!1,this,void 0,this.resolveCredentials(t.credentials));if(typeof l.decide!="function")throw new Error(`Provider "${r}" does not serve the decide inference type.`);const u=await l.decide({state:t.state,questions:t.questions,model:t.model,signal:t.signal,timeoutMs:t.timeoutMs}),d=Object.keys(u.answers).length,m=Ei(r,u.model,{input:u.usage.inputTokens,output:u.usage.outputTokens,total:u.usage.inputTokens+u.usage.outputTokens});o.setAttribute("gen_ai.response.model",u.model),o.setAttribute("gen_ai.usage.input_tokens",u.usage.inputTokens),o.setAttribute("gen_ai.usage.output_tokens",u.usage.outputTokens),o.setAttribute("decision.answer_count",d),o.setAttribute("ai.cost.total",m),u.upstreamMs!==void 0&&o.setAttribute("decision.upstream_ms",u.upstreamMs),u.requestId&&o.setAttribute("gen_ai.response.id",u.requestId),c.durationMs=Date.now()-a,c=Ce.updateAttributes(c,{"ai.model":u.model,"ai.tokens.input":u.usage.inputTokens,"ai.tokens.output":u.usage.outputTokens,"ai.cost.input":m,"ai.cost.output":0,"ai.cost.total":m,"decision.answer_count":d,"decision.latency_ms":u.latencyMs,...u.upstreamMs!==void 0?{"decision.upstream_ms":u.upstreamMs}:{}});const h=Ce.endSpan(c,1);return this.metricsAggregator.recordSpan(h),rt().recordSpan(h),u}catch(l){c.durationMs=Date.now()-a;const u=Ce.endSpan(c,2,l instanceof Error?l.message:String(l));throw this.metricsAggregator.recordSpan(u),rt().recordSpan(u),l}})}async tryDecide(t){try{const r=await this.decide(t);return p.shouldLog("debug")&&p.debug(`decide: ${Object.keys(r.answers).length} answers in ${r.latencyMs}ms`+(r.upstreamMs?` (upstream ${r.upstreamMs}ms)`:""),{provider:r.provider,model:r.model,requestId:r.requestId,usage:r.usage}),r}catch(r){return p.debug(`decide unavailable: ${r instanceof Error?r.message:String(r)} \u2014 falling back`),null}}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));let s;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?s={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(l=>({id:l})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:s=o("quality"),r?.passThreshold!==void 0&&(s.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(s.executionMode=r.executionMode);const i=new n(s);await ze(i.initialize(),3e4,pe.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,c=await ze(i.execute(t,{correlationId:r?.correlationId}),a,pe.evaluationTimeout("pipeline execution",a));return p.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:c.overallScore,passed:c.passed,scorerCount:c.scores.length}),c}async score(t,r,n){const{ScorerRegistry:o}=await ze(Promise.resolve().then(()=>(ZV(),XV)),1e4,pe.evaluationTimeout("scorer module load",1e4));await ze(o.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));const s=await ze(o.getScorer(t,n),3e4,pe.evaluationTimeout(`scorer load: ${t}`,3e4));if(!s)throw pe.scorerNotFound(t);const i=s.validateInput(r);if(!i.valid)throw pe.evaluationValidationFailed(t,i.errors);const a=await ze(s.score(r),6e4,pe.evaluationTimeout("scorer execution",6e4));return p.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await ze(Promise.resolve().then(()=>(ZV(),XV)),1e4,pe.evaluationTimeout("scorer module load",1e4));await ze(r.registerBuiltInScorers(),3e4,pe.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await ze(Promise.resolve().then(()=>(Rb(),Ib)),1e4,pe.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(tie(),Kjt));return p.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(Yjt(),Jjt));return p.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},s={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:{...this.observabilityConfig??{},langfuse:{...this.observabilityConfig?.langfuse??{},autoDetectExternalProvider:!0,skipLangfuseSpanProcessor:!0}},...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},i=this.workerToolsConfig(o.tools),a=new b3(i?{...s,tools:i}:s);if(t?.shareToolRegistry!==!1)for(const c of this.uncacheableTools)a.uncacheableTools.add(c);if(p.setEventEmitter(n),t?.onLog){const c=t.onLog,l=f=>{try{const g=f??{};c({tag:r,level:String(g.level??"info"),message:String(g.message??""),timestamp:typeof g.timestamp=="number"?g.timestamp:Date.now(),data:g.data})}catch{}},u={emit:(f,...g)=>(f==="log-event"&&l(g[0]),!0)},d=a.logInstanceId;p.addScopedEventEmitter(d,u);const m=()=>{p.removeScopedEventEmitter(d,u),this.ownedWorkerLogBridgeDetachers.delete(m)};this.ownedWorkerLogBridgeDetachers.add(m);const h=a.dispose.bind(a);a.dispose=async()=>{m(),await h()}}return p.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),a}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(YA(),a2));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(YA(),a2));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(YA(),a2));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(ZA(),d2)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=zWr(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return FWr(t??Jo(this))}clearTaskState(t){return $Wr(t??Jo(this))}registerDelegationTools(t){if(iKr(this,t),this.hasBackgroundDelegationTools)return;const r=gKr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return _Bt(this,t)}async collectDelegates(t){return ABt(this,t)}async cancelDelegates(t){return Qne(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=this.createConfiguredArtifactStore()),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}setArtifactStore(t){const r=this.mcpArtifactStore;r!==t&&(r&&(p.warn("[NeuroLink] Artifact store replaced \u2014 artifacts already written to the previous store will not resolve through this instance"),this.ownsArtifactStore&&r.close&&r.close().catch(n=>{p.warn("[NeuroLink] Previous artifact store close failed",{error:n instanceof Error?n.message:String(n)})})),this.mcpArtifactStore=t,this.ownsArtifactStore=!1,this.installOutputNormalizer(t),this.registerMemoryRetrievalTools())}createConfiguredArtifactStore(){const t=this.artifactsConfig?.store!==void 0,r=g5t(this.artifactsConfig,this.conversationMemoryConfig?.conversationMemory?.redisConfig);return this.ownsArtifactStore=!t,p.debug("[NeuroLink] Artifact store initialized",{backend:t?"custom":$re(this.artifactsConfig)}),r}installOutputNormalizer(t){this.mcpOutputNormalizerConfig&&(this.externalServerManager.setOutputNormalizer(new eUt(this.mcpOutputNormalizerConfig,t)),p.debug("[NeuroLink] MCP output normalizer initialized",{...this.mcpOutputNormalizerConfig,hasArtifactStore:t!==void 0}))}async bankArtifact(t,r){return P9r(this,t,r)}async readArtifact(t,r){return M9r(this,t,r)}registerBackgroundCommandTools(t){if(MBt(this,t),this.hasBackgroundCommandTools)return;const r=CKr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){MBt(this,t)}async startBackgroundCommand(t,r){return BBt(this,t,r)}getBackgroundCommandStatus(t){return zBt(this,t)}async awaitBackgroundCommand(t,r){return moe(this,t,r)}async killBackgroundCommand(t,r){return qBt(this,t,r)}async readBackgroundCommandOutput(t,r){return w2(this,t,r)}registerGitTools(t){if(AKr(this,t),this.hasGitTools)return;const r=OKr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,p.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return tzt(this,t,r)}async executeNetwork(t,r,n){return p.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){p.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(eVt(),Qjt));return p.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(rVt(),tVt));return p.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(oVt(),nVt));return p.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){p.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await GBt(this),await Qne(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error stopping background work:",r)}try{p.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await hO(),await fO(),p.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{p.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),p.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.ownsArtifactStore&&this.mcpArtifactStore?.close)try{await this.mcpArtifactStore.close(),p.debug("[NeuroLink] Artifact store closed")}catch(r){const n=r instanceof Error?r:new Error(`Artifact store close error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error closing artifact store:",r)}if(this.emitter)try{p.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),p.clearEventEmitter(this.emitter),p.clearScopedEventEmitters(this.logInstanceId),p.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error removing event listeners:",r)}if(this.ownedWorkerLogBridgeDetachers.size>0)try{const r=this.ownedWorkerLogBridgeDetachers.size;for(const n of[...this.ownedWorkerLogBridgeDetachers])n();p.debug(`[NeuroLink] Detached ${r} undisposed worker log bridge(s)`)}catch(r){const n=r instanceof Error?r:new Error(`Worker log bridge cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error detaching worker log bridges:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{p.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),p.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{p.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=[],p.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{p.debug("[NeuroLink] Shutting down TaskManager..."),await ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){p.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{p.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,p.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),p.warn("[NeuroLink] Error resetting state:",r)}t.length===0?p.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):p.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw p.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new Uv({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel},this.contextCompactorDeps()),s=Vi({provider:r?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&Fv(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const s=Vi({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?Vi({provider:r||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(cF(),sVt));r=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=r,p.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(OA(),BL));r.set(t),p.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(OA(),BL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(OA(),BL)),r=t.get()?.user.id;t.clear(),r&&p.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(s=>typeof t[s]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(p.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async s=>{if(typeof t[s]=="function"){const i=await Gre(t[s],o);t[s]=i.value,p.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof t.tools=="function"){const s=await Gre(t.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}`);t.enabledToolNames=s.value,delete t.tools}}},die=new $T,lVt=die}});function uVt(e,t,r,n){const o=typeof e=="object"&&e!==null?e.data:void 0;if(!Array.isArray(o)||o.length===0)throw n(`${r} embeddings response missing data`);if(o.length!==t)throw n(`${r} embeddings response count mismatch: expected ${t}, got ${o.length}`);const s=o.findIndex(a=>!dVt(a));if(s!==-1)throw n(`${r} embeddings response entry ${s} is not an {index, embedding: number[]} object`);const i=o.slice().sort((a,c)=>a.index-c.index);for(let a=0;a<i.length;a++)if(i[a].index!==a)throw n(`${r} embeddings response has unexpected index ordering: position ${a} has index ${i[a].index}`);return i.map(a=>a.embedding)}var dVt,mVt=b({"src/lib/providers/embeddingResponseParsing.ts"(){"use strict";dVt=e=>{if(typeof e!="object"||e===null)return!1;const{embedding:t,index:r}=e;return Number.isInteger(r)&&Array.isArray(t)&&t.every(n=>typeof n=="number"&&Number.isFinite(n))}}}),pVt={};ee(pVt,{VoyageProvider:()=>gVt});var hVt,mie,fVt,uF,gVt,mQr=b({async"src/lib/providers/voyage.ts"(){"use strict";Wa(),await Dl(),mVt(),On(),ut(),Ze(),z(),ts(),hVt="https://api.voyageai.com/v1",mie=6e4,fVt=()=>ca(TCr()),uF=()=>yi("VOYAGE_MODEL","voyage-3.5"),gVt=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"voyage",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:fVt(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??hVt,this.proxyFetch=Pt(),p.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return uF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return uF()}getAISDKModel(){throw new ot("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 ot("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){const 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 Mr("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Oo(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new ot(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],t);if(!n[0])throw new ot("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const s=e.slice(o,o+r),i=await this.callEmbeddings(s,t);n.push(...i)}return n}async callEmbeddings(e,t){const r=t??this.modelName;let n;try{n=await ze(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:r})}),mie,new ot(`Voyage embeddings request timed out after ${mie/1e3}s`,"voyage"))}catch(s){throw s instanceof ot?s:this.formatProviderError(s)}if(!n.ok){const s=await n.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${n.status} \u2014 ${s}`))}const o=await n.json();return uVt(o,e.length,"Voyage",s=>new ot(s,"voyage"))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:uF(),baseURL:this.baseURL}}}}}),yVt={};ee(yVt,{JinaProvider:()=>wVt});var vVt,Ek,TVt,dF,wVt,pQr=b({async"src/lib/providers/jina.ts"(){"use strict";Wa(),await Dl(),mVt(),On(),ut(),z(),ts(),vVt="https://api.jina.ai/v1",Ek=6e4,TVt=()=>ca(wCr()),dF=()=>yi("JINA_MODEL","jina-embeddings-v3"),wVt=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"jina",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:TVt(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??vVt,this.proxyFetch=Pt(),p.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return dF()}supportsTools(){return!1}getDefaultEmbeddingModel(){return dF()}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){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mr("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new Oo(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new ot(`Jina AI error: ${t}`,"jina")}async embed(e,t){if(typeof e!="string"&&e.image)throw new ot(`${this.providerName} does not support image embeddings; provide text input`,this.providerName);const r=typeof e=="string"?e:e.text??"",n=await this.callEmbeddings([r],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,r={}){if(t.length===0)return[];const n=r.model??"jina-reranker-v2-base-multilingual",o=r.credentials,s=o?.apiKey?.trim()||this.apiKey,i=o?.baseURL||this.baseURL,a=new AbortController,c=setTimeout(()=>a.abort(),Ek);let l;try{l=await this.proxyFetch(`${i}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({model:n,query:e,documents:t,top_n:r.topN??t.length}),signal:a.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${Ek/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(c)}if(!l.ok){const d=await l.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${l.status} \u2014 ${d}`))}return((await l.json()).results??[]).map(d=>({index:d.index,score:d.relevance_score,document:t[d.index]??d.document?.text??""}))}async callEmbeddings(e,t,r){const n=t??this.modelName,o=r?.apiKey?.trim()||this.apiKey,s=r?.baseURL||this.baseURL,i=new AbortController,a=setTimeout(()=>i.abort(),Ek);let c;try{c=await this.proxyFetch(`${s}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:i.signal})}catch(u){throw u instanceof Error&&u.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${Ek/1e3}s`)):this.formatProviderError(u)}finally{clearTimeout(a)}if(!c.ok){const u=await c.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${c.status} \u2014 ${u}`))}const l=await c.json();return uVt(l,e.length,"Jina",u=>new Error(u))}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:dF(),baseURL:this.baseURL}}}}}),EVt={};ee(EVt,{StabilityProvider:()=>fie,default:()=>_Vt});var SVt,pie,bVt,hie,fie,_Vt,hQr=b({async"src/lib/providers/stability.ts"(){"use strict";Wa(),await Dl(),On(),ut(),z(),ts(),SVt="https://api.stability.ai",pie=12e4,bVt=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,hie=()=>yi("STABILITY_MODEL","stable-image-ultra"),fie=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"stability",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:bVt(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??SVt,this.proxyFetch=Pt(),p.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return hie()}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){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mr("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new ot("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new Oo(`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 ot(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.stability,n=r?.apiKey?.trim()||this.apiKey;if(!n)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");const o=n,s=r?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");const a=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,c=e,l=new FormData;l.append("prompt",i),l.append("output_format","png"),c.aspectRatio&&l.append("aspect_ratio",String(c.aspectRatio)),c.negativePrompt&&l.append("negative_prompt",c.negativePrompt),this.modelName.startsWith("sd3.5-")&&l.append("model",this.modelName),c.seed!==void 0&&l.append("seed",String(c.seed));const u=new AbortController,d=setTimeout(()=>u.abort(),pie);let m;try{m=await this.proxyFetch(`${s}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:l,signal:u.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${pie/1e3}s`)):this.formatProviderError(g)}finally{clearTimeout(d)}if(!m.ok){const g=await m.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${m.status} \u2014 ${g}`))}const h=await m.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);const f=Date.now()-t;return p.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${f}ms \u2014 model ${this.modelName}`),{content:i,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:hie(),baseURL:this.baseURL}}},_Vt=fie}}),CVt={};ee(CVt,{IdeogramProvider:()=>vie,default:()=>xVt});var AVt,gie,kVt,yie,vie,xVt,fQr=b({async"src/lib/providers/ideogram.ts"(){"use strict";Wa(),await Dl(),On(),ut(),z(),ts(),ya(),mp(),AVt="https://api.ideogram.ai",gie=12e4,kVt=()=>ca(ECr()),yie=()=>yi("IDEOGRAM_MODEL","V_3"),vie=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"ideogram",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:kVt(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??AVt,this.proxyFetch=Pt(),p.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return yie()}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){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mr("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new ot("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new ot(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.ideogram,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const i=e,a={prompt:s,model:this.modelName,magic_prompt:i.magicPrompt??"AUTO"};i.aspectRatio&&(a.aspect_ratio=i.aspectRatio),i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.seed!==void 0&&(a.seed=i.seed),i.style&&(a.style_type=i.style);const c=new AbortController,l=setTimeout(()=>c.abort(),gie);let u;try{u=await this.proxyFetch(`${o}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":n,"Content-Type":"application/json"},body:JSON.stringify(a),signal:c.signal})}catch(E){throw E instanceof Error&&E.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${gie/1e3}s`)):this.formatProviderError(E)}finally{clearTimeout(l)}if(!u.ok){const E=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${E}`))}const m=(await u.json()).data?.[0]?.url;if(!m)throw new Error("Ideogram returned no image URL");await dp(m);const h=new AbortController,f=setTimeout(()=>h.abort(),6e4);let g;try{g=await this.proxyFetch(m,{signal:h.signal})}catch(E){throw E instanceof Error&&E.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:E}):E}finally{clearTimeout(f)}if(!g.ok)throw new Error(`Failed to download Ideogram image: ${g.status}`);const y=await Eu(g,up,"Ideogram image"),v=y.toString("base64"),w=Date.now()-t;return p.info(`[IdeogramProvider] Generated image (${y.length} bytes) in ${w}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:v}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:yie(),baseURL:this.baseURL}}},xVt=vie}}),IVt={};ee(IVt,{ReplicateProvider:()=>RVt});function gQr(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
2146
2146
 
2147
2147
  ${r}`:r}function yQr(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:"").join(""):""}function Tie(e){const t=e?.apiKey?.trim()||e?.apiToken?.trim(),r=e?.baseURL||e?.baseUrl;return{apiToken:t,baseUrl:r}}var wie,RVt,vQr=b({async"src/lib/providers/replicate.ts"(){"use strict";Wa(),Xh(),H2(),K2(),ya(),await Dl(),z(),Ze(),ts(),wie=()=>yi("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct"),RVt=class extends ga{apiToken;baseURL;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"replicate",o);const{apiToken:s,baseUrl:i}=Tie(n);this.apiToken=s&&s.length>0?s:ca(vCr()),this.baseURL=i,p.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return wie()}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){const r=typeof e=="string"?{prompt:e}:e,n=fd(r,this.modelName);if(n==="video"||n==="avatar"||n==="music"||n==="image")return super.generate(r,t);if(r.output?.format==="json"||r.output?.format==="structured"||t!=null)throw new Me({code:je.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});const o=r.prompt??r.input?.text??"",s=Date.now(),i=await this.executeStream({input:{text:o},systemPrompt:r.systemPrompt,maxTokens:r.maxTokens,temperature:r.temperature,abortSignal:r.abortSignal,timeout:r.timeout});let a="";for await(const l of i.stream)"content"in l&&typeof l.content=="string"&&(a+=l.content);const c={content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}};return p.info(`[ReplicateProvider] generate() complete in ${Date.now()-s}ms \u2014 ${a.length} chars`),c}async executeStream(e,t){const r=Date.now(),n=e.credentials?.replicate,o=Tie(n),s=o.apiToken||this.apiToken,i=o.baseUrl||this.baseURL,a=Lp({apiToken:s,baseUrl:i});if(!a)throw new Me({code:je.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const c=gQr(e);if(!c.trim())throw new Me({code:je.INVALID_PARAMETERS,message:"Replicate predictions require a prompt (input.text or prompt)",category:"validation",severity:"medium",retriable:!1});const l={prompt:c,...e.maxTokens!==void 0&&{max_new_tokens:e.maxTokens},temperature:e.temperature,top_p:1};let u;try{u=await vk(a,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(h){throw this.handleProviderError(h)}const d=yQr(u.output);if(!d)throw new Error(`Replicate prediction ${u.id} returned empty output`);const m={async*[Symbol.asyncIterator](){yield{content:d}}};return p.info(`[ReplicateProvider] Generated ${d.length} chars in ${Date.now()-r}ms \u2014 model ${this.modelName} (prediction ${u.id})`),{stream:m,provider:this.providerName,model:this.modelName,finishReason:"stop",metadata:{startTime:r,streamId:`replicate-${u.id}`}}}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.replicate,n=Tie(r),o=n.apiToken||this.apiToken,s=n.baseUrl||this.baseURL,i=Lp({apiToken:o,baseUrl:s});if(!i)throw new Me({code:je.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const a=e.prompt??e.input?.text??"";if(!a.trim())throw new Me({code:je.INVALID_PARAMETERS,message:"Replicate image-gen requires a prompt",category:"validation",severity:"medium",retriable:!1});const 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 vk(i,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(h){throw this.handleProviderError(h)}let d;try{d=await W2(u,up)}catch(h){throw this.handleProviderError(h)}const m=d.toString("base64");return p.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:m}}}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error",r=e instanceof Error?e:void 0;return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.toLowerCase().includes("invalid token")?new Me({code:je.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:r}):t.includes("402")||t.toLowerCase().includes("insufficient credit")?new Me({code:je.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:r}):t.includes("429")||t.toLowerCase().includes("rate limit")?new Me({code:je.PROVIDER_QUOTA_EXCEEDED,message:"Replicate rate limit exceeded. Back off and retry.",category:"resource",severity:"high",retriable:!0,context:{provider:"replicate"},originalError:r}):t.toLowerCase().includes("not found")||t.includes("404")?new Me({code:je.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:r}):new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate error: ${t}`,category:"execution",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:r})}async validateConfiguration(){return typeof this.apiToken=="string"&&this.apiToken.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:wie(),baseURL:this.baseURL}}}}}),PVt={};ee(PVt,{RecraftProvider:()=>bie,default:()=>DVt});var MVt,Eie,OVt,Sie,bie,DVt,TQr=b({async"src/lib/providers/recraft.ts"(){"use strict";Wa(),await Dl(),On(),ut(),z(),ts(),ya(),mp(),gN(),MVt="https://external.api.recraft.ai/v1",Eie=12e4,OVt=()=>ca(SCr()),Sie=()=>yi("RECRAFT_MODEL","recraftv3"),bie=class extends ga{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=$p(t)?t:void 0;super(e,"recraft",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:OVt(),this.baseURL=n?.baseURL??process.env.RECRAFT_BASE_URL??MVt,this.proxyFetch=Pt(),p.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Sie()}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){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new Mr("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new $s("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new Oo(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new ot(`Recraft error: ${t}`,"recraft")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.recraft,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");const i=e,a={model:e.model??this.modelName,prompt:s,n:1,response_format:"b64_json"};i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.style&&(a.style=i.style),i.styleId&&(a.style_id=i.styleId),i.size&&(a.size=i.size);const c=new AbortController,l=setTimeout(()=>c.abort(),Eie);let u;try{u=await this.proxyFetch(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(a),signal:c.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${Eie/1e3}s`)):this.formatProviderError(g)}finally{clearTimeout(l)}if(!u.ok){const g=await u.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${u.status} \u2014 ${g}`))}const m=(await u.json()).data?.[0];if(!m)throw new Error("Recraft returned no image data");let h;if(m.b64_json)h=m.b64_json;else if(m.url){await dp(m.url);const g=new AbortController,y=setTimeout(()=>g.abort(),6e4);let v;try{v=await this.proxyFetch(m.url,{signal:g.signal})}catch(E){throw E instanceof Error&&E.name==="AbortError"?new Error("Recraft image download timed out after 60s",{cause:E}):E}finally{clearTimeout(y)}if(!v.ok)throw new Error(`Failed to download Recraft image: ${v.status}`);h=(await Eu(v,up,"Recraft image")).toString("base64")}else throw new Error("Recraft response missing both b64_json and url");const f=Date.now()-t;return p.info(`[RecraftProvider] Generated image (${h.length} base64 chars) in ${f}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h,mimeType:tA(Buffer.from(h.slice(0,64),"base64"))}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Sie(),baseURL:this.baseURL}}},DVt=bie}});function NVt(e){const t=Object.values(e);return t.length>0?Math.max(...t):0}function wQr(e,t){if(!Io(e))return null;switch(e.type){case"noul":case"boolean":{const r=zc(e.noul)??zc(e.probability);return r===void 0?null:{type:"boolean",probability:r}}case"choice":{const r=Cie(e.probabilities);return typeof e.choice!="string"||!r?null:{type:"choice",choice:e.choice,confidence:zc(e.confidence)??t??NVt(r),probabilities:r}}case"score":{const r=zc(e.score),n=$Vt(e.legend),o=Cie(e.probabilities);return r===void 0||!n||!o?null:{type:"score",score:r,confidence:zc(e.confidence)??t??NVt(o),legend:n,probabilities:o}}default:return null}}function LVt(e){return e.filter(Io).map(r=>{const n=Array.isArray(r.loc)?r.loc.filter(s=>typeof s=="string"||typeof s=="number").join("."):"",o=typeof r.msg=="string"?r.msg:"invalid";return n?`${n}: ${o}`:o}).slice(0,5).join("; ")||"unspecified field"}function EQr(e,t){if(t===void 0)return Gt(e);const r=[...e],n=i=>(i.codePointAt(0)??0)<=127,o=r.filter(n).join(""),s=r.length-o.length;return Gt(o)+Math.ceil(s*t)}var _ie,FVt,Io,zc,Cie,$Vt,Aie,kie,UVt=b({async"src/lib/providers/systemOneDecision.ts"(){"use strict";Wa(),vc(),await Dl(),On(),ut(),z(),Ko(),_ie=5e3,FVt=1,Io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zc=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Cie=e=>{if(!Io(e))return;const t={};for(const[r,n]of Object.entries(e)){const o=zc(n);if(o===void 0)return;t[r]=o}return t},$Vt=e=>{if(!Io(e))return;const t={};for(const[r,n]of Object.entries(e)){if(typeof n!="string")return;t[r]=n}return t},Aie=e=>new Promise(t=>setTimeout(t,e)),kie=class extends ga{proxyFetch;maxRetries;authFailed=!1;constructor(e,t,r){super(e,t,$p(r)?r:void 0),this.proxyFetch=Pt(),this.maxRetries=FVt}missingConfigMessage(){}encodeQuestion(e){return e.type==="boolean"?{type:"noul",instructions:e.instructions,...e.criteria?{criteria:e.criteria}:{}}:e}reportedConfidence(e){return{}}resolveResponseModel(e,t){return typeof e.model=="string"?e.model:t}diagnosticContext(){return{}}getProviderName(){return this.providerName}getDefaultDecisionModel(){return this.getDefaultModel()}supportsTools(){return!1}getAISDKModel(){throw new ot(`${this.vendorDisplayName()} is a decision-only provider; it generates no text, so chat completions are not available. Use \`decide()\` instead, or pick a different provider for \`generate()\` / \`stream()\`.`,this.providerName)}async executeStream(e,t){throw new ot(`${this.vendorDisplayName()} is a decision-only provider; streaming is not available. Use \`decide()\`, or pick another provider for \`stream()\`.`,this.providerName)}formatProviderError(e){if(e instanceof ot)return e;const t=e instanceof Error?e.message:String(e);return new ot(`${this.vendorLabel()} request failed: ${t}`,this.providerName)}async decide(e){const t=this.vendorLabel();if(!this.decisionApiKey())throw this.decisionError({kind:"authentication",message:this.missingKeyMessage(),retryable:!1});const r=this.missingConfigMessage();if(r)throw this.decisionError({kind:"invalid_request",message:r,retryable:!1});if(this.authFailed)throw this.decisionError({kind:"authentication",message:`${t} rejected this API key earlier; not retrying. Fix the key and construct a new provider.`,retryable:!1});const n=Object.entries(e.questions);if(n.length===0)throw this.decisionError({kind:"invalid_request",message:"At least one question is required.",retryable:!1});const o=e.model??this.modelName??this.getDefaultModel();this.assertWithinDecisionLimits(e,o,n.length);const s=Object.fromEntries(n.map(([l,u])=>[l,this.encodeQuestion(u)])),i=JSON.stringify(this.buildDecisionBody(e.state,s,o)),a=e.timeoutMs??this.getDescriptorDecideMs()??this.defaultTimeout??_ie;let c;for(let l=0;l<=this.maxRetries;l++){const u=Date.now();try{const d=AbortSignal.timeout(a),m=e.signal?AbortSignal.any([e.signal,d]):d,h=await this.proxyFetch(this.decisionEndpoint(),{method:"POST",headers:this.decisionHeaders(),body:i,signal:m}),f=Date.now()-u,g=this.readRequestId(h.headers),y=Number(h.headers.get("x-envoy-upstream-service-time"))||void 0,v=await h.json().catch(()=>null);if(!h.ok){if(c=this.parseDecisionError(h.status,v,g),c.kind==="authentication"&&(this.authFailed=!0,p.warn(`${t}: credential not accepted \u2014 disabling this provider instance. ${c.message}`,{status:c.status,...this.diagnosticContext(),requestId:g})),!c.retryable||l===this.maxRetries)throw this.decisionError(c);await Aie(2**l*250+Math.random()*250);continue}if(!Io(v)||!Io(v.answers))throw this.decisionError({kind:"server",message:`${t} returned a response without an answers map.`,status:h.status,requestId:g,retryable:!1});const w=this.reportedConfidence(v),E={};for(const[C,A]of Object.entries(v.answers)){const k=wQr(A,w[C]);k?E[C]=k:p.warn(`${t}: dropped unparseable answer "${C}"`,{requestId:g})}const _=Io(v.usage)?v.usage:{};return{model:this.resolveResponseModel(v,o),provider:this.providerName,answers:E,usage:{inputTokens:zc(_.input_tokens)??zc(_.inputTokens)??0,outputTokens:zc(_.output_tokens)??zc(_.outputTokens)??0},requestId:g,latencyMs:f,upstreamMs:y}}catch(d){if(d instanceof ot)throw d;const m=e.signal?.aborted===!0,h=d instanceof Error&&d.name==="TimeoutError";if(c={kind:m?"network":h?"timeout":"network",message:d instanceof Error?d.message:String(d),retryable:!m},m||l===this.maxRetries)throw this.decisionError(c);await Aie(2**l*250+Math.random()*250)}}throw this.decisionError(c??{kind:"network",message:`${t} request failed.`,retryable:!1})}assertWithinDecisionLimits(e,t,r){const n=Ar.get(this.providerName)?.decisionLimits;if(!n)return;const o=this.vendorLabel();if(r>n.maxQuestions)throw this.decisionError({kind:"max_tokens_exceeded",message:`${o} accepts at most ${n.maxQuestions} questions per request; this one has ${r}. Ask fewer, or use a decision provider without this cap.`,retryable:!1});const s=n.models?.[t],i=s?.maxStateTokens??n.maxStateTokens,a=EQr(M_(e.state),s?.nonAsciiTokensPerChar??n.nonAsciiTokensPerChar);if(a>i)throw this.decisionError({kind:"max_tokens_exceeded",message:`The state is ~${a} tokens; ${o}'s "${t}" model reads at most ${i}. Shorten the state, or use a decision provider with a larger window.`,retryable:!1})}decisionError(e){const t=new ot(e.message,this.providerName);return Object.defineProperty(t,"cause",{value:e,enumerable:!1,writable:!0,configurable:!0}),t}}}}),BVt={};ee(BVt,{TYPESAFE_MAX_REQUEST_TOKENS:()=>pF,TYPESAFE_MAX_STATE_TOKENS:()=>mF,TypeSafeProvider:()=>KVt});function SQr(e){if(!Io(e)||!Io(e.providerMetadata))return{};const t=e.providerMetadata.typesafe;if(!Io(t)||!Io(t.confidence))return{};const r={};for(const[n,o]of Object.entries(t.confidence)){const s=zc(o);s!==void 0&&(r[n]=s)}return r}function bQr(e,t,r,n){const o=typeof t.type=="string"?t.type:void 0,s=(o?WVt[o]:void 0)??(e===401||e===403?"authentication":e===429?"rate_limit":e>=500?"server":"invalid_request"),i=typeof t.message=="string"&&t.message.length>0?t.message:o??`AI Gateway request failed with HTTP ${e}`;return{kind:s,message:i,status:e,requestId:r,retryable:n}}function zVt(e,t,r){const n=e===429||e===529||e>=500,o=Io(t)&&Io(t.error)?t.error:void 0;if(o)return bQr(e,o,r,n);const s=Io(t)?t.detail:void 0;if(Array.isArray(s))return{kind:"invalid_request",message:`Request failed validation \u2014 ${LVt(s)}`,status:e,requestId:r,retryable:!1};const i=Io(s)&&typeof s.error_type=="string"?s.error_type:void 0,a=i==="max_tokens_exceeded"?"max_tokens_exceeded":e===401||e===403?"authentication":e===429?"rate_limit":e===529?"overloaded":e>=500?"server":"invalid_request",c=a==="max_tokens_exceeded"?`State plus questions exceeded the model's input limit: keep state plus the longest single question under ~${mF} tokens, and state plus all questions under ~${pF}.`:i??`TypeSafe request failed with HTTP ${e}`,l=Io(s)&&typeof s.message=="string"?s.message:c;return{kind:a,message:l,status:e,requestId:r,retryable:n}}var qVt,GVt,jVt,VVt,HVt,mF,pF,WVt,KVt,JVt=b({async"src/lib/providers/typesafe.ts"(){"use strict";z(),Ut(),ts(),await UVt(),qVt="https://api.typesafe.ai",GVt="https://ai-gateway.vercel.sh/v4/ai/evaluation-model",jVt="typesafe-ai/jev",VVt="0.0.1",HVt="4",mF=33e3,pF=64e3,WVt={authentication_error:"authentication",customer_verification_required:"authentication",invalid_request_error:"invalid_request",rate_limit_exceeded:"rate_limit",internal_server_error:"server"},KVt=class extends kie{apiKey;baseURL;gatewayURL;transport;constructor(e,t,r,n){super(e,"typesafe",t);const o=n?.apiKey?.trim()||(process.env.TYPESAFE_API_KEY?.trim()??""),s=n?.gatewayApiKey?.trim()||(process.env.AI_GATEWAY_API_KEY?.trim()??""),i=n?.transport??process.env.TYPESAFE_TRANSPORT?.trim();this.transport=i==="gateway"||i==="direct"?i:!o&&s?"gateway":"direct",this.apiKey=this.transport==="gateway"?s:o,this.baseURL=(n?.baseURL??process.env.TYPESAFE_BASE_URL??qVt).replace(/\/+$/,""),this.gatewayURL=(n?.gatewayURL?.trim()||process.env.TYPESAFE_GATEWAY_URL?.trim()||GVt).replace(/\/+$/,""),p.debug("TypeSafe Provider initialized (decide only)",{modelName:this.modelName,transport:this.transport,baseURL:rr(this.transport==="gateway"?this.gatewayURL:this.baseURL)})}getDefaultModel(){return yi("TYPESAFE_MODEL","jev-latest")}vendorLabel(){return"TypeSafe"}vendorDisplayName(){return"TypeSafe (Jev)"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return this.transport==="gateway"?"The TypeSafe gateway transport requires a Vercel AI Gateway key. Set AI_GATEWAY_API_KEY or pass credentials.typesafe.gatewayApiKey.":"TypeSafe requires an API key. Set TYPESAFE_API_KEY or pass credentials.typesafe.apiKey."}encodeQuestion(e){return this.transport==="gateway"?e:super.encodeQuestion(e)}buildDecisionBody(e,t,r){return this.transport==="gateway"?{state:e,questions:t}:{model:r,state:e,questions:t}}parseDecisionError(e,t,r){return zVt(e,t,r)}reportedConfidence(e){return SQr(e)}readRequestId(e){return e.get("x-typesafe-request-id")??void 0}diagnosticContext(){return{transport:this.transport}}decisionEndpoint(){return this.transport==="gateway"?this.gatewayURL:`${this.baseURL}/v1/systemone`}decisionHeaders(){const e={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};return this.transport==="gateway"?{...e,"ai-gateway-auth-method":"api-key","ai-gateway-protocol-version":VVt,"ai-model-id":jVt,"ai-evaluation-model-specification-version":HVt}:e}getDecisionTransport(){return this.transport}async listDecisionModels(){if(this.transport==="gateway")throw this.decisionError({kind:"invalid_request",message:"Model listing is a TypeSafe API operation; the gateway transport has no equivalent endpoint.",retryable:!1});const e=await this.proxyFetch(`${this.baseURL}/v1/models`,{headers:{Authorization:`Bearer ${this.apiKey}`},signal:AbortSignal.timeout(this.defaultTimeout??_ie)}),t=await e.json().catch(()=>null);if(!e.ok)throw this.decisionError(zVt(e.status,t,e.headers.get("x-typesafe-request-id")??void 0));return(Io(t)&&Array.isArray(t.models)?t.models:[]).filter(Io).map(n=>({name:typeof n.name=="string"?n.name:"",description:typeof n.description=="string"?n.description:"",releaseDate:typeof n.release_date=="string"?n.release_date:""}))}}}}),YVt={};ee(YVt,{LayaProvider:()=>XVt});function _Qr(e,t){return(t?e.split(t).join("[redacted]"):e).replace(/\.?\s*Received API Key\s*=[\s\S]*$/,"").replace(/\bsk-[A-Za-z0-9._-]+/g,"[redacted]").replace(/\b[0-9a-f]{32,}\b/gi,"[redacted]").trim()}function CQr(e,t,r){const n=e===429||e>=500,o=e===401||e===403?"authentication":e===413?"max_tokens_exceeded":e===429?"rate_limit":e===503?"overloaded":e>=500?"server":"invalid_request",s=Io(t)&&Io(t.error)?t.error:void 0;if(s&&typeof s.message=="string"&&s.message.length>0)return{kind:o,message:s.message,status:e,requestId:r,retryable:n};const i=Io(t)?t.detail:void 0;return Array.isArray(i)?{kind:"invalid_request",message:`Request failed validation \u2014 ${LVt(i)}`,status:e,requestId:r,retryable:!1}:typeof i=="string"&&i.length>0?{kind:o,message:i,status:e,requestId:r,retryable:n}:{kind:o,message:`Laya request failed with HTTP ${e}`,status:e,requestId:r,retryable:n}}var XVt,AQr=b({async"src/lib/providers/laya.ts"(){"use strict";z(),Ut(),ts(),await UVt(),XVt=class extends kie{apiKey;baseURL;constructor(e,t,r,n){super(e,"laya",t),this.apiKey=n?.apiKey?.trim()||(process.env.LAYA_API_KEY?.trim()??""),this.baseURL=(n?.baseURL?.trim()||process.env.LAYA_BASE_URL?.trim()||"").replace(/\/+$/,""),p.debug("Laya Provider initialized (decide only)",{modelName:this.modelName,baseURL:this.baseURL?rr(this.baseURL):"(not set)"})}getDefaultModel(){return yi("LAYA_MODEL","typed-decisions")}vendorLabel(){return"Laya"}vendorDisplayName(){return"Laya"}decisionApiKey(){return this.apiKey}missingKeyMessage(){return"Laya requires an API key. Set LAYA_API_KEY or pass credentials.laya.apiKey."}missingConfigMessage(){return this.baseURL?void 0:"Laya requires a base URL. Set LAYA_BASE_URL or pass credentials.laya.baseURL."}decisionEndpoint(){return`${this.baseURL}/predict`}decisionHeaders(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}buildDecisionBody(e,t,r){return r==="auto"?{state:e,questions:t}:{model:r,state:e,questions:t}}parseDecisionError(e,t,r){const n=CQr(e,t,r),o=_Qr(n.message,this.apiKey);return{...n,message:o||`Laya request failed with HTTP ${e}`}}readRequestId(e){return e.get("x-litellm-call-id")??void 0}resolveResponseModel(e,t){const r=e.routing;return Io(r)&&typeof r.model=="string"?r.model:super.resolveResponseModel(e,t)}}}}),ZVt={};ee(ZVt,{Agent:()=>zHt,BedrockClient:()=>eHt,BedrockRuntimeClient:()=>rHt,Blob:()=>BHt,Client:()=>GHt,ConverseCommand:()=>nHt,ConverseStreamCommand:()=>oHt,Cron:()=>SHt,Dispatcher:()=>jHt,File:()=>UHt,FlowProducer:()=>EHt,FormData:()=>$Ht,GoogleAuth:()=>uHt,HTTPException:()=>IHt,Headers:()=>FHt,Hippocampus:()=>hHt,HippocampusConfig:()=>fHt,Hono:()=>kHt,ImageFormat:()=>sHt,InvokeEndpointCommand:()=>cHt,InvokeEndpointWithResponseStreamCommand:()=>lHt,InvokeModelCommand:()=>iHt,Job:()=>THt,ListFoundationModelsCommand:()=>tHt,MockAgent:()=>WHt,Pool:()=>qHt,Queue:()=>yHt,QueueScheduler:()=>wHt,Request:()=>NHt,Response:()=>LHt,SageMakerRuntimeClient:()=>aHt,TextToSpeechClient:()=>mHt,VertexAI:()=>dHt,Webhook:()=>pHt,Worker:()=>vHt,convertToHtml:()=>AHt,cors:()=>xHt,createClient:()=>gHt,default:()=>QVt,extractRawText:()=>CHt,fetch:()=>DHt,getGlobalDispatcher:()=>HHt,interceptors:()=>KHt,logger:()=>RHt,parseBuffer:()=>bHt,request:()=>JHt,secureHeaders:()=>PHt,selectCover:()=>_Ht,setGlobalDispatcher:()=>VHt,streamSSE:()=>MHt,timeout:()=>OHt});var Lg,hs,QVt,eHt,tHt,rHt,nHt,oHt,sHt,iHt,aHt,cHt,lHt,uHt,dHt,mHt,pHt,hHt,fHt,gHt,yHt,vHt,THt,wHt,EHt,SHt,bHt,_Ht,CHt,AHt,kHt,xHt,IHt,RHt,PHt,MHt,OHt,DHt,NHt,LHt,FHt,$Ht,UHt,BHt,zHt,qHt,GHt,jHt,VHt,HHt,WHt,KHt,JHt,kQr=b({"npm-stub:@google-cloud/text-to-speech"(){Lg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Lg.get}):new Proxy(function(...r){return new Proxy({},{get:Lg.get})},{get:Lg.get,apply(r,n,o){return new Proxy({},{get:Lg.get})},construct(r,n){return new Proxy({},{get:Lg.get})}})}},hs=new Proxy({},Lg),QVt=hs,{BedrockClient:eHt,ListFoundationModelsCommand:tHt,BedrockRuntimeClient:rHt,ConverseCommand:nHt,ConverseStreamCommand:oHt,ImageFormat:sHt,InvokeModelCommand:iHt}=hs,{SageMakerRuntimeClient:aHt,InvokeEndpointCommand:cHt,InvokeEndpointWithResponseStreamCommand:lHt}=hs,{GoogleAuth:uHt,VertexAI:dHt,TextToSpeechClient:mHt}=hs,{Webhook:pHt}=hs,{Hippocampus:hHt,HippocampusConfig:fHt}=hs,{createClient:gHt}=hs,{Queue:yHt,Worker:vHt,Job:THt,QueueScheduler:wHt,FlowProducer:EHt}=hs,{Cron:SHt}=hs,{parseBuffer:bHt,selectCover:_Ht}=hs,{extractRawText:CHt,convertToHtml:AHt}=hs,{Hono:kHt}=hs,{cors:xHt,HTTPException:IHt,logger:RHt,secureHeaders:PHt,streamSSE:MHt,timeout:OHt}=hs,DHt=globalThis.fetch,NHt=globalThis.Request,LHt=globalThis.Response,FHt=globalThis.Headers,$Ht=globalThis.FormData,UHt=globalThis.File,BHt=globalThis.Blob,zHt=hs.Agent,qHt=hs.Pool,GHt=hs.Client,jHt=hs.Dispatcher,VHt=()=>{},HHt=()=>hs,WHt=hs.MockAgent,KHt={redirect:()=>e=>e,retry:()=>e=>e},JHt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),hF,YHt=b({"src/lib/adapters/tts/googleTTSHandler.ts"(){"use strict";Ec(),z(),qb(),To(),hF=class ju{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=ju.DEFAULT_MAX_TEXT_LENGTH;credentialsPath;constructor(t){this.credentialsPath=t??process.env.GOOGLE_APPLICATION_CREDENTIALS}isConfigured(){return this.credentialsPath!==void 0}async getClient(){if(!this.client){const{TextToSpeechClient:t}=await Promise.resolve().then(()=>(kQr(),ZVt));this.client=new t({keyFilename:this.credentialsPath})}return this.client}async getVoices(t){if(!this.isConfigured())throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});const r=await this.getClient(),n=Ce.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<ju.CACHE_TTL_MS&&!t){const a=Ce.endSpan(n,1);return rt().recordSpan(a),this.voicesCache.voices}const[o]=await r.listVoices(t?{languageCode:t}:{});if(!o.voices||o.voices.length===0){p.warn("Google Cloud TTS returned no voices");const a=Ce.endSpan(n,1);return rt().recordSpan(a),[]}const s=[];for(const a of o.voices??[]){if(!a.name||!Array.isArray(a.languageCodes)||a.languageCodes.length===0){p.warn("Skipping voice with missing required fields",{name:a.name,languageCodesCount:a.languageCodes?.length});continue}const c=a.name,l=a.languageCodes,u=l[0],d=this.detectVoiceType(c),m=a.ssmlGender==="MALE"?"male":a.ssmlGender==="FEMALE"?"female":"neutral";s.push({id:c,name:c,languageCode:u,languageCodes:l,gender:m,type:d,naturalSampleRateHertz:a.naturalSampleRateHertz??void 0})}t||(this.voicesCache={voices:s,timestamp:Date.now()});const i=Ce.endSpan(n,1);return rt().recordSpan(i),s}catch(o){const s=Ce.endSpan(n,2,o instanceof Error?o.message:"Unknown error");rt().recordSpan(s);const i=o instanceof Error?o.message:"Unknown error";return p.error(`Failed to fetch Google TTS voices: ${i}`),[]}}async synthesize(t,r){if(!this.isConfigured())throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});const n=await this.getClient(),o=r.voice??"en-US-Neural2-C",s=Ce.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":o,"tts.format":r.format??"mp3"}),i=Date.now();try{const a=t.startsWith("<speak>")&&t.endsWith("</speak>");if(t.startsWith("<speak>")&&!t.endsWith("</speak>")||!t.startsWith("<speak>")&&t.endsWith("</speak>"))throw new Et({code:At.INVALID_INPUT,message:"Malformed SSML: missing opening <speak> or closing </speak> tag.",category:"validation",severity:"medium",retriable:!1});const c=this.extractLanguageCode(o),l=this.mapFormat(r.format??"mp3"),u={input:a?{ssml:t}:{text:t},voice:{name:o,languageCode:c},audioConfig:{audioEncoding:l,speakingRate:r.speed??1,pitch:r.pitch??0,volumeGainDb:r.volumeGainDb??0}},[d]=await n.synthesizeSpeech(u,{timeout:ju.DEFAULT_API_TIMEOUT_MS}),m=d.audioContent;if(!m)throw new Et({code:At.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});const h=m instanceof Uint8Array?Buffer.from(m):typeof m=="string"?Buffer.from(m,"base64"):(()=>{throw new Et({code:At.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof m}})})(),f=Date.now()-i,g=Ce.endSpan(s,1);return rt().recordSpan(g),{buffer:h,format:r.format??"mp3",size:h.length,voice:o,metadata:{latency:f,provider:"google-ai"}}}catch(a){const c=Ce.endSpan(s,2,a instanceof Error?a.message:String(a));if(rt().recordSpan(c),a instanceof Et)throw a;const l=Date.now()-i,u=a instanceof Error?a.message:"Unknown error";throw new Et({code:At.SYNTHESIS_FAILED,message:`Google TTS failed after ${l}ms: ${u}`,category:"execution",severity:"high",retriable:!0,context:{latency:l},originalError:a instanceof Error?a:void 0})}}static STREAMING_VOICE_PATTERN=/^[a-z]{2,3}-[A-Z]{2}-(?:Chirp3-HD|Chirp-HD|Journey)-/;static STREAMING_SAMPLE_RATE_HZ=24e3;static STREAMING_IDLE_TIMEOUT_MS=30*1e3;static mapStreamingFormat(t){switch(t){case"pcm16":return"PCM";case"ogg":case"opus":return"OGG_OPUS";default:return}}static streamedAudio(t){if(t===null||typeof t!="object")return;const r=t.audioContent;if(r instanceof Uint8Array)return r.byteLength>0?Buffer.from(r.buffer,r.byteOffset,r.byteLength):void 0;if(typeof r=="string"&&r.length>0){const n=Buffer.from(r,"base64");return n.length>0?n:void 0}}synthesizeStream(t,r={}){const n=r.voice;if(n===void 0||!ju.STREAMING_VOICE_PATTERN.test(n))return;const o=r.format??"mp3",s=ju.mapStreamingFormat(o);if(s===void 0||t.trimStart().startsWith("<speak"))return;const i=this.extractLanguageCode(n),a=ju.STREAMING_SAMPLE_RATE_HZ,c=this;let l,u=!1,d=!1;const m=(async function*(){const h=await c.getClient();if(u)return;const f=Date.now(),g=h.streamingSynthesize();l=g;let y;const v=()=>{clearTimeout(y),y=setTimeout(()=>{d=!0,g.cancel()},ju.STREAMING_IDLE_TIMEOUT_MS)};let w=0,E=0;try{g.write({streamingConfig:{voice:{name:n,languageCode:i},streamingAudioConfig:{audioEncoding:s,sampleRateHertz:a,speakingRate:r.speed??1}}}),g.write({input:{text:t}}),g.end(),v();for await(const _ of g){clearTimeout(y);const C=ju.streamedAudio(_);if(C===void 0){v();continue}E+=C.length,yield{data:C,format:o,index:w++,isFinal:!1,cumulativeSize:E,voice:n,sampleRate:a},v()}p.debug(`[GoogleTTSHandler] Streamed ${E} bytes in ${Date.now()-f}ms`)}catch(_){if(u)return;if(_ instanceof Et)throw _;const C=_ instanceof Error?_.message:"Unknown error";throw new Et({code:At.SYNTHESIS_FAILED,message:d?`Google TTS streaming synthesis stalled for ${ju.STREAMING_IDLE_TIMEOUT_MS}ms`:`Google TTS streaming synthesis failed: ${C}`,category:d?"network":"execution",severity:"high",retriable:!0,context:{voice:n,audioEncoding:s},originalError:_ instanceof Error?_:void 0})}finally{clearTimeout(y),l=void 0,g.cancel()}})();return zb(m,()=>{u=!0,l?.cancel()})}extractLanguageCode(t){const r=t.split("-");if(r.length>=2)return`${r[0]}-${r[1]}`;throw new Et({code:At.INVALID_INPUT,message:`Invalid Google TTS voiceId format: "${t}". Expected format like "en-US-Neural2-C".`,category:"validation",severity:"medium",retriable:!1,context:{voiceId:t}})}mapFormat(t){switch(t.toLowerCase()){case"mp3":return"MP3";case"wav":return"LINEAR16";case"ogg":case"opus":return"OGG_OPUS";case"pcm16":throw new Et({code:At.INVALID_INPUT,message:"Google Cloud TTS's buffered synthesis does not support pcm16 output. pcm16 is only delivered via native streaming, which requires a Chirp3-HD, Chirp-HD, or Journey voice and plain (non-SSML) text \u2014 check that both conditions hold, or request a different format.",category:"validation",severity:"medium",retriable:!1,context:{format:t}});default:throw new Et({code:At.INVALID_INPUT,message:`Unsupported audio format: ${t}`,category:"validation",severity:"medium",retriable:!1,context:{format:t}})}}detectVoiceType(t){const r=t.toLowerCase().split("-");return r.some(n=>n.startsWith("chirp"))?"chirp":r.includes("neural2")?"neural":r.includes("wavenet")?"wavenet":r.includes("standard")?"standard":"unknown"}}}}),UT,Sk,fF=b({"src/lib/voice/RealtimeVoiceAPI.ts"(){"use strict";z(),_d(),ut(),T0(),UT=class{static registry=new tf("RealtimeProcessor");static sessions=new Map;static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),p.debug(`[RealtimeProcessor] Registered Realtime handler for provider: ${r}`)}static getHandler(e){return this.registry.get(e)}static supports(e){return this.registry.supports(e)}static getProviders(){return this.registry.list()}static async connect(e,t,r){const n=this.getHandler(e);if(!n)throw Qt.providerNotSupported(e,this.registry.list());if(!n.isConfigured())throw Qt.providerNotConfigured(e);if(n.isConnected())throw Qt.sessionAlreadyActive(e);const o={...w1,...t};r&&n.on(r);try{p.debug(`[RealtimeProcessor] Connecting to provider: ${e}`);const s=await n.connect(o);return this.sessions.set(e.toLowerCase(),s),p.info(`[RealtimeProcessor] Connected to ${e} session: ${s.id}`),s}catch(s){if(r&&n.off(),s instanceof Qt)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw Qt.connectionFailed(i,e,s instanceof Error?s:void 0)}}static async disconnect(e){const t=this.getHandler(e);if(!t)throw Qt.providerNotSupported(e,this.registry.list());if(!t.isConnected()){p.warn(`[RealtimeProcessor] No active session for provider: ${e}`);return}try{await t.disconnect(),this.sessions.delete(e.toLowerCase()),t.off(),p.info(`[RealtimeProcessor] Disconnected from ${e}`)}catch(r){if(r instanceof Qt)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw Qt.protocolError(`Disconnect failed: ${n}`,e,r instanceof Error?r:void 0)}}static async sendAudio(e,t){const r=this.getHandler(e);if(!r)throw Qt.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw Qt.sessionNotActive(e);try{await r.sendAudio(t)}catch(n){if(n instanceof Qt)throw n;const o=n instanceof Error?n.message:String(n||"Unknown error");throw Qt.audioStreamError(o,e)}}static async sendText(e,t){const r=this.getHandler(e);if(!r)throw Qt.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw Qt.sessionNotActive(e);if(!r.sendText)throw new Qt({code:Us.PROTOCOL_ERROR,message:`Provider "${e}" does not support text input`,category:"validation",severity:"medium",context:{provider:e}});try{await r.sendText(t)}catch(n){throw n instanceof Qt?n:new Qt({code:Us.PROTOCOL_ERROR,message:`sendText failed: ${n instanceof Error?n.message:String(n)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:n instanceof Error?n:void 0})}}static async triggerResponse(e){const t=this.getHandler(e);if(!t)throw Qt.providerNotSupported(e,this.registry.list());if(!t.isConnected())throw Qt.sessionNotActive(e);if(t.triggerResponse)try{await t.triggerResponse()}catch(r){throw r instanceof Qt?r:new Qt({code:Us.PROTOCOL_ERROR,message:`triggerResponse failed: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:r instanceof Error?r:void 0})}}static async cancelResponse(e){const t=this.getHandler(e);if(!t)throw Qt.providerNotSupported(e,this.registry.list());if(t.isConnected()&&t.cancelResponse)try{await t.cancelResponse()}catch(r){throw r instanceof Qt?r:new Qt({code:Us.PROTOCOL_ERROR,message:`cancelResponse failed: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:r instanceof Error?r:void 0})}}static getSession(e){return this.getHandler(e)?.getSession()??null}static isConnected(e){return this.getHandler(e)?.isConnected()??!1}static getSupportedFormats(e){return this.getHandler(e)?.getSupportedFormats()??[]}static clearHandlers(){for(const[e]of this.sessions){const t=this.registry.get(e);t?.isConnected()&&t.disconnect().catch(()=>{})}this.sessions.clear(),this.registry.clear(),p.debug("[RealtimeProcessor] Cleared all handlers and sessions")}},Sk=class{session=null;eventHandlers=null;state="disconnected";isConnected(){return this.state==="connected"}getSession(){return this.session}on(e){this.eventHandlers=e}off(){this.eventHandlers=null}emitStateChange(e){this.state=e,this.session&&(this.session.state=e,this.session.lastActivityAt=new Date),this.eventHandlers?.onStateChange?.(e)}emitAudio(e){this.eventHandlers?.onAudio?.(e)}emitTranscript(e,t){this.eventHandlers?.onTranscript?.(e,t)}emitText(e,t){this.eventHandlers?.onText?.(e,t)}async emitFunctionCall(e,t){if(this.eventHandlers?.onFunctionCall)return this.eventHandlers.onFunctionCall(e,t)}emitError(e){this.eventHandlers?.onError?.(e)}emitTurnStart(){this.eventHandlers?.onTurnStart?.()}emitTurnEnd(){this.eventHandlers?.onTurnEnd?.()}createSession(e,t){return{id:e,state:"connected",provider:this.name,model:t.model,createdAt:new Date,lastActivityAt:new Date,config:t}}}}});function XHt(e){if(e.length<12)return null;if(e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===65&&e[10]===86&&e[11]===69)return"wav";if(e[0]===73&&e[1]===68&&e[2]===51||e[0]===255&&(e[1]&224)===224)return"mp3";if(e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83){const t=e.indexOf("OpusHead");return t!==-1&&t<200?"opus":"ogg"}return null}function xQr(e){return aS[e]?.mimeType??"application/octet-stream"}function IQr(e){return aS[e]?.extension??".bin"}function RQr(e,t,r){const n=t??XHt(e);if(n)try{switch(n){case"wav":return PQr(e);case"mp3":return MQr(e);case"ogg":case"opus":return OQr(e);default:return r?e.length/(r*2):void 0}}catch(o){p.debug(`[audio-utils] Failed to calculate duration: ${o instanceof Error?o.message:String(o)}`);return}}function PQr(e){if(e.length<44)return;let t=12;for(;t<e.length-8;){const r=e.toString("ascii",t,t+4),n=e.readUInt32LE(t+4);if(r==="fmt "){const o=e.readUInt16LE(t+10),s=e.readUInt32LE(t+12),i=e.readUInt16LE(t+22);let a=t+8+n+n%2;for(;a<e.length-8;){const c=e.toString("ascii",a,a+4),l=e.readUInt32LE(a+4);if(c==="data"){const u=i/8*o;return l/u/s}a+=8+l+l%2}}t+=8+n+n%2}}function MQr(e){let t=0;for(e[0]===73&&e[1]===68&&e[2]===51&&(t=10+((e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127));t<e.length-4;){if(e[t]===255&&(e[t+1]&224)===224){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,o=e[t+2]>>4&15,s=e[t+2]>>2&3,a={3:[44100,48e3,32e3],2:[22050,24e3,16e3],0:[11025,12e3,8e3]}[r]?.[s],l=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0][o];if(a&&l)return(e.length-t)*8/(l*1e3);break}t++}return e.length*8/128e3}function OQr(e){return e.length*8/64e3}async function DQr(e,t,r,n={}){if(t===r)return e;throw p.warn(`[audio-utils] Audio format conversion from ${t} to ${r} is not implemented.`),new Error(`Audio format conversion from ${t} to ${r} is not implemented. Convert with ffmpeg before passing to NeuroLink.`)}function NQr(e,t=16e3,r=16){const n=r/8,o=Buffer.alloc(e.length*n);for(let s=0;s<e.length;s++){const i=Math.max(-1,Math.min(1,e[s])),a=s*n;switch(r){case 8:o.writeUInt8(Math.round((i+1)*127.5),a);break;case 16:o.writeInt16LE(Math.round(i*32767),a);break;case 24:{const c=Math.round(i*8388607);o.writeUInt8(c&255,a),o.writeUInt8(c>>8&255,a+1),o.writeUInt8(c>>16&255,a+2);break}case 32:o.writeInt32LE(Math.round(i*2147483647),a);break}}return o}function LQr(e,t=16){const r=t/8,n=Math.floor(e.length/r),o=[];for(let s=0;s<n;s++){const i=s*r;switch(t){case 8:o.push(e.readUInt8(i)/127.5-1);break;case 16:o.push(e.readInt16LE(i)/32767);break;case 24:{const a=e.readUInt8(i)|e.readUInt8(i+1)<<8|e.readUInt8(i+2)<<16;o.push((a>8388607?a-16777216:a)/8388607);break}case 32:o.push(e.readInt32LE(i)/2147483647);break}}return o}function FQr(e,t,r){if(t<=0||r<=0||t===r)return e;const n=t/r,o=Math.round(e.length/n),s=[];for(let i=0;i<o;i++){const a=i*n,c=Math.floor(a),l=Math.min(c+1,e.length-1),u=a-c,d=e[c]*(1-u)+e[l]*u;s.push(d)}return s}function $Qr(e,t=.95){if(e.length===0)return e;let r=0;for(const o of e)r=Math.max(r,Math.abs(o));if(r===0)return e;const n=t/r;return e.map(o=>o*n)}function ZHt(e,t=16e3,r=1,n=16){const o=Buffer.alloc(44),s=t*r*(n/8),i=r*(n/8);return o.write("RIFF",0),o.writeUInt32LE(36+e,4),o.write("WAVE",8),o.write("fmt ",12),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(t,24),o.writeUInt32LE(s,28),o.writeUInt16LE(i,32),o.writeUInt16LE(n,34),o.write("data",36),o.writeUInt32LE(e,40),o}function UQr(e,t=16e3,r=1,n=16){const o=ZHt(e.length,t,r,n);return Buffer.concat([o,e])}function BQr(e,t,r=16e3,n=2){if(t<=0||r<=0||n<=0)return[e];const o=r*n/1e3,s=Math.round(t*o);if(s<=0)return[e];const i=[];for(let a=0;a<e.length;a+=s){const c=Math.min(a+s,e.length);i.push(e.subarray(a,c))}return i}var QHt,e7t,zQr=b({"src/lib/voice/audio-utils.ts"(){"use strict";ut(),z(),QHt={wav:Buffer.from([82,73,70,70]),mp3:{id3:Buffer.from([73,68,51]),frameSync:Buffer.from([255,224])},ogg:Buffer.from([79,103,103,83])},e7t={wav:"audio/wav",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus"}}});function qQr(e){return{[Symbol.asyncIterator](){const t=[];let r=null,n=null,o=!1,s=null;const i=u=>{r?(r({value:u,done:!1}),r=null,n=null):t.push(u)},a=()=>{o=!0,r&&(r({value:void 0,done:!0}),r=null,n=null)},c=u=>{s=u,n&&(n(u),r=null,n=null)};e.on("chunk",i),e.on("end",a),e.on("error",c);const l=()=>{e.off("chunk",i),e.off("end",a),e.off("error",c)};return{async next(){if(s)throw s;if(t.length>0){const u=t.shift();if(u!==void 0)return{value:u,done:!1}}return o?{value:void 0,done:!0}:new Promise((u,d)=>{r=u,n=d})},async return(){return l(),o=!0,{value:void 0,done:!0}}}}}}async function GQr(e,t={}){const r=new BT(t);return(async()=>{try{for await(const n of e)r.write(n)||await new Promise(s=>r.once("drain",s));r.end()}catch(n){r.emit("error",n instanceof Error?n:new Error(String(n)))}})(),r}var xie,BT,t7t,r7t,jQr=b({"src/lib/voice/stream-handler.ts"(){"use strict";Mn(),z(),xie={chunkDurationMs:100,sampleRate:16e3,bytesPerSample:2,format:"wav",highWaterMark:64*1024,bufferTimeoutMs:5e3},BT=class extends Kr{config;chunkSize;buffer;chunkIndex;timestampMs;isPaused;isEnded;pendingData;bufferTimeout;constructor(e={}){if(super(),this.config={...xie,...e},this.config.sampleRate<=0)throw new Error("Invalid stream configuration: sampleRate must be positive");if(this.config.bytesPerSample<=0)throw new Error("Invalid stream configuration: bytesPerSample must be positive");const t=this.config.sampleRate*this.config.bytesPerSample/1e3;if(this.chunkSize=Math.round(this.config.chunkDurationMs*t),this.chunkSize<=0)throw new Error("Invalid stream configuration: chunkSize must be positive (check chunkDurationMs, sampleRate, bytesPerSample)");this.buffer=Buffer.alloc(0),this.chunkIndex=0,this.timestampMs=0,this.isPaused=!1,this.isEnded=!1,this.pendingData=[],this.bufferTimeout=null}write(e){if(this.isEnded)throw new Error("Cannot write to ended stream");return this.buffer.length+e.length>this.config.highWaterMark?(this.isPaused||(this.isPaused=!0,this.emit("pause")),this.pendingData.push(e),!1):(this.processData(e),!0)}processData(e){for(this.buffer=Buffer.concat([this.buffer,e]),this.resetBufferTimeout();this.buffer.length>=this.chunkSize;){const t=this.buffer.subarray(0,this.chunkSize);this.buffer=this.buffer.subarray(this.chunkSize);const r={data:t,index:this.chunkIndex++,isFinal:!1,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:this.config.chunkDurationMs};this.timestampMs+=this.config.chunkDurationMs,this.emit("chunk",r)}if(this.isPaused&&this.buffer.length<this.config.highWaterMark/2)for(this.isPaused=!1,this.emit("resume"),this.emit("drain");this.pendingData.length>0&&!this.isPaused;){const t=this.pendingData.shift();if(t===void 0||!this.write(t))break}}end(){if(!this.isEnded){this.isEnded=!0,this.clearBufferTimeout();for(const e of this.pendingData)this.buffer=Buffer.concat([this.buffer,e]);if(this.pendingData=[],this.buffer.length>0){const e=this.buffer.length/this.config.bytesPerSample/this.config.sampleRate*1e3,t={data:this.buffer,index:this.chunkIndex++,isFinal:!0,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:e};this.emit("chunk",t)}else{const e={data:Buffer.alloc(0),index:this.chunkIndex,isFinal:!0,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:0};this.emit("chunk",e)}this.emit("end"),this.cleanup()}}resetBufferTimeout(){this.clearBufferTimeout(),this.bufferTimeout=setTimeout(()=>{this.buffer.length>0&&!this.isEnded&&(p.warn(`[ChunkedAudioStream] Buffer timeout, forcing flush of ${this.buffer.length} bytes`),this.end())},this.config.bufferTimeoutMs)}clearBufferTimeout(){this.bufferTimeout&&(clearTimeout(this.bufferTimeout),this.bufferTimeout=null)}cleanup(){this.clearBufferTimeout(),this.buffer=Buffer.alloc(0),this.pendingData=[]}getStats(){return{chunksEmitted:this.chunkIndex,bufferedBytes:this.buffer.length,pendingChunks:this.pendingData.length,totalDurationMs:this.timestampMs,isPaused:this.isPaused,isEnded:this.isEnded}}},t7t=class extends Kr{streams;config;constructor(e={}){super(),this.streams=new Map,this.config={...xie,...e}}addStream(e){if(this.streams.has(e))throw new Error(`Stream ${e} already exists`);const t=new BT(this.config);return t.on("chunk",r=>{this.emit("chunk",{id:e,chunk:r})}),t.on("end",()=>{this.emit("streamEnd",e),this.streams.delete(e),this.streams.size===0&&this.emit("end")}),t.on("error",r=>{this.emit("error",{id:e,error:r})}),this.streams.set(e,t),t}removeStream(e){const t=this.streams.get(e);t&&(t.end(),this.streams.delete(e))}write(e,t){const r=this.streams.get(e);if(!r)throw new Error(`Stream ${e} not found`);return r.write(t)}endAll(){for(const e of this.streams.values())e.end()}get activeStreams(){return this.streams.size}},r7t=class extends Kr{consumers;input;constructor(e={}){super(),this.consumers=new Map,this.input=new BT(e),this.input.on("chunk",t=>{for(const[r,n]of this.consumers)try{n(t)}catch(o){this.emit("error",{consumerId:r,error:o instanceof Error?o:new Error(String(o))})}}),this.input.on("end",()=>{this.emit("end")}),this.input.on("error",t=>{this.emit("error",{error:t})})}write(e){return this.input.write(e)}end(){this.input.end()}addConsumer(e,t){if(this.consumers.has(e))throw new Error(`Consumer ${e} already exists`);this.consumers.set(e,t)}removeConsumer(e){this.consumers.delete(e)}get consumerCount(){return this.consumers.size}}}}),zT,n7t=b({"src/lib/voice/providers/AzureTTS.ts"(){"use strict";z(),Ec(),zT=class m0r{apiKey;region;voicesCache=null;static CACHE_TTL_MS=1800*1e3;maxTextLength=1e4;constructor(t,r){const n=(t??process.env.AZURE_SPEECH_KEY??"").trim();this.apiKey=n.length>0?n:null;const o=(r??process.env.AZURE_SPEECH_REGION??"").trim();this.region=o.length>0?o:"eastus"}isConfigured(){return this.apiKey!==null&&this.region.length>0}async getVoices(t){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<m0r.CACHE_TTL_MS&&!t)return this.voicesCache.voices;try{const r=new AbortController,n=setTimeout(()=>r.abort(),3e4);let 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:r.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new Et({code:At.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 t&&(i=i.filter(a=>a.languageCode.toLowerCase().startsWith(t.toLowerCase())||a.languageCode.toLowerCase()===t.toLowerCase())),t||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(r){if(r instanceof Et)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw p.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new Et({code:At.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:r instanceof Error?r:void 0})}}async synthesize(t,r={}){if(!this.apiKey)throw new Et({code:At.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});const n=Date.now(),o=r;try{const s=r.voice??"en-US-JennyNeural",i=o.outputFormat??this.mapFormat(r.format??"mp3"),a=this.buildSSML(t,s,r),c=new AbortController,l=setTimeout(()=>c.abort(),3e4);let 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(g){throw g instanceof Error&&g.name==="AbortError"?new Et({code:At.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:g}):g}finally{clearTimeout(l)}if(!u.ok){const g=await u.text();throw new Error(`HTTP ${u.status}: ${g}`)}const d=Date.now()-n,m=await u.arrayBuffer(),h=Buffer.from(m),f={buffer:h,format:this.effectiveFormat(i),size:h.length,voice:s,sampleRate:this.getSampleRate(i),metadata:{latency:d,provider:"azure-tts",requestedFormat:r.format,outputFormat:i,region:this.region}};return p.info(`[AzureTTSHandler] Synthesized ${h.length} bytes in ${d}ms`),f}catch(s){if(s instanceof Et)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw p.error(`[AzureTTSHandler] Synthesis failed: ${i}`),new Et({code:At.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:t.length},originalError:s instanceof Error?s:void 0})}}buildSSML(t,r,n){const o=n;if(o.ssmlTemplate)return o.ssmlTemplate.replace("{text}",this.escapeXml(t)).replace("{voice}",this.escapeXml(r));if(o.allowRawSSML&&t.trim().startsWith("<speak"))return t;const 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(r))}">
2148
2148
  <voice name="${this.escapeXml(r)}">