@juspay/neurolink 9.78.0 → 9.79.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/browser/neurolink.min.js +3 -3
- package/dist/lib/neurolink.js +14 -5
- package/dist/lib/tasks/autoresearchTaskExecutor.js +1 -1
- package/dist/lib/workflow/core/ensembleExecutor.js +0 -2
- package/dist/neurolink.js +14 -5
- package/dist/tasks/autoresearchTaskExecutor.js +1 -1
- package/dist/workflow/core/ensembleExecutor.js +0 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
## [9.79.0](https://github.com/juspay/neurolink/compare/v9.78.0...v9.79.0) (2026-06-23)
|
|
2
|
+
|
|
3
|
+
### Features
|
|
4
|
+
|
|
5
|
+
- **(tools):** emit per-invocation executionId on tool start/end events ([6b142e4](https://github.com/juspay/neurolink/commit/6b142e49433e59698d6a39733d4abfcebf0cdfd5))
|
|
6
|
+
|
|
1
7
|
## [9.78.0](https://github.com/juspay/neurolink/compare/v9.77.0...v9.78.0) (2026-06-20)
|
|
2
8
|
|
|
3
9
|
### Features
|
|
@@ -1593,7 +1593,7 @@ FAIL`,s=1,g.error("[Autoresearch] Experiment spawn failed",{error:c})}try{ig(e,n
|
|
|
1593
1593
|
`).replace(/\\t/g," ").replace(/\\\\/g,"\\"),g.warn(`[researchTools] Detected literal escape sequences in write content for ${i}. Fixed ${u} literal \\n \u2192 real newlines.`));let d=ur.join(e.repoPath,i);return ig(d,c,"utf-8"),{success:!0,path:i,bytesWritten:Buffer.byteLength(c,"utf-8")}}catch(c){return g.error("[researchTools] research_write_candidate failed",{path:i,error:String(c)}),{success:!1,error:c instanceof Error?c.message:String(c),path:i}}}},research_diff:{description:"Get the git diff showing changes to mutablePaths only. Returns empty string if no changes.",inputSchema:p.object({}),execute:async()=>{try{let i=[];for(let c of e.mutablePaths)try{let l=hi("git",["diff","--",c],{cwd:e.repoPath,encoding:"utf-8"});l.trim()&&i.push(l)}catch(l){let u=ur.join(e.repoPath,c);if(!Ps(u))continue;throw l}let a=i.join(`
|
|
1594
1594
|
`);return{success:!0,diff:a,hasChanges:a.length>0}}catch(i){return g.error("[researchTools] research_diff failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}},research_commit_candidate:{description:"Commit staged changes as a candidate experiment. Validates branch and paths, stages mutablePaths, creates commit, and updates state with candidateCommit.",inputSchema:p.object({message:p.string().describe("Git commit message")}),execute:async({message:i})=>{try{let a=await t.load();if(!a)return{success:!1,error:"No research state found."};for(let u of e.mutablePaths)try{hi("git",["add","--",u],{cwd:e.repoPath,encoding:"utf-8"})}catch(d){let m=d instanceof Error?d.message:String(d);if(!m.includes("did not match any files")&&!m.includes("pathspec"))throw d}let c=await n.validateCommit(a.branch);if(!c.valid){for(let u of e.mutablePaths)try{hi("git",["restore","--staged","--",u],{cwd:e.repoPath,encoding:"utf-8"})}catch{}return{success:!1,error:`Commit validation failed: ${c.violations.join(", ")}`,violations:c.violations}}hi("git",["commit","--no-verify","-m",i],{cwd:e.repoPath,encoding:"utf-8"});let l=hi("git",["rev-parse","--short=7","HEAD"],{cwd:e.repoPath,encoding:"utf-8"}).trim();return await t.update({candidateCommit:l,lastSummary:null,lastStatus:null}),{success:!0,candidateCommit:l,message:i}}catch(a){return g.error("[researchTools] research_commit_candidate failed",{error:String(a)}),{success:!1,error:a instanceof Error?a.message:String(a)}}}},research_run_experiment:{description:"Run the configured experiment command with timeout. Returns structured summary with metric, memory, and crash status.",inputSchema:p.object({description:p.string().describe("Description of this experiment run")}),execute:async({description:i})=>{try{g.info("[researchTools] Starting experiment",{description:i});let a=await ke(o.run(),e.timeoutMs+3e4,new Error("Experiment runner exceeded safety timeout")),c=await t.load();return c&&await t.update({runCount:c.runCount+1,lastSummary:a}),{success:!0,description:i,summary:a}}catch(a){return g.error("[researchTools] research_run_experiment failed",{error:String(a)}),{success:!1,error:a instanceof Error?a.message:String(a)}}}},research_parse_log:{description:"Parse the run.log file to extract structured experiment summary (metric, memory, crash status, etc.)",inputSchema:p.object({}),execute:async()=>{try{let i=ur.join(e.repoPath,e.logPath),a=Pa(i,"utf-8");return{success:!0,summary:Tq(a,e.metric,e.memoryMetric)}}catch(i){return g.error("[researchTools] research_parse_log failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}},research_record:{description:"Record the result of an experiment to results.tsv and runs.jsonl. Status is computed deterministically from the experiment outcome.",inputSchema:p.object({description:p.string().describe("Description of the experiment")}),execute:async({description:i})=>{try{let a=await t.load();if(!a)return{success:!1,error:"No research state found."};let c=a.lastSummary;if(!c)return{success:!1,error:"No experiment summary found. Run research_run_experiment first."};let l=c.metric??null,u=c.memoryValue??null,d;c?.timedOut?d="timeout":c?.crashed||l===null?d="crash":a.bestMetric===null?d="keep":d=(e.metric.direction==="lower"?l<a.bestMetric:l>a.bestMetric)?"keep":"discard";let f={commit:a.candidateCommit||a.acceptedCommit||"unknown",metric:l,memoryGb:u,status:d,description:i,timestamp:new Date().toISOString()};return await s.appendTsv(f),await s.appendJsonl(f),await t.update({lastStatus:d}),{success:!0,record:f}}catch(a){return g.error("[researchTools] research_record failed",{error:String(a)}),{success:!1,error:a instanceof Error?a.message:String(a)}}}},research_accept:{description:"Accept the candidate commit as the new best. Updates acceptedCommit to candidateCommit, updates bestMetric from latest metric, and increments keepCount.",inputSchema:p.object({}),execute:async()=>{try{let i=await t.load();if(!i)return{success:!1,error:"No research state found."};if(!i.candidateCommit)return{success:!1,error:"No candidate commit to accept."};let a=i.lastSummary;if(!a||a.metric===null)return{success:!1,error:"No valid experiment summary to accept. Run an experiment first."};if(a.crashed||a.timedOut)return{success:!1,error:`Cannot accept a ${a.crashed?"crashed":"timed-out"} experiment. Use research_revert instead.`};if(i.lastStatus!=="keep")return{success:!1,error:`Cannot accept: last recorded status is "${i.lastStatus}". Only "keep" experiments can be accepted.`};let c=i.bestMetric;return i.bestMetric!==null&&!(e.metric.direction==="lower"?a.metric<i.bestMetric:a.metric>i.bestMetric)?{success:!1,error:`Metric ${a.metric} is not better than current best ${i.bestMetric} (direction: ${e.metric.direction}). Use research_revert instead.`}:(c=a.metric,await t.update({acceptedCommit:i.candidateCommit,bestMetric:c,baselineMetric:i.baselineMetric??c,keepCount:i.keepCount+1,candidateCommit:null}),{success:!0,acceptedCommit:i.candidateCommit,bestMetric:c,keepCount:i.keepCount+1})}catch(i){return g.error("[researchTools] research_accept failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}},research_revert:{description:"Revert repository to the accepted commit (git reset --hard). Clears candidateCommit from state.",inputSchema:p.object({}),execute:async()=>{try{let i=await t.load();return i?i.acceptedCommit?(hi("git",["reset","--hard",i.acceptedCommit],{cwd:e.repoPath,encoding:"utf-8"}),await t.update({candidateCommit:null}),{success:!0,revertedTo:i.acceptedCommit}):{success:!1,error:"No accepted commit to revert to."}:{success:!1,error:"No research state found."}}catch(i){return g.error("[researchTools] research_revert failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}},research_inspect_failure:{description:"Inspect the last 50 lines of run.log to debug experiment failures.",inputSchema:p.object({}),execute:async()=>{try{let i=ur.join(e.repoPath,e.logPath),c=Pa(i,"utf-8").split(`
|
|
1595
1595
|
`);return{success:!0,tail:c.slice(-50).join(`
|
|
1596
|
-
`),totalLines:c.length}}catch(i){return g.error("[researchTools] research_inspect_failure failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}},research_checkpoint:{description:"Save the current research state to disk. Call periodically to ensure progress is not lost.",inputSchema:p.object({}),execute:async()=>{try{let i=await t.load();return i?(await t.save(i),{success:!0,checkpointedAt:new Date().toISOString(),phase:i.currentPhase,runCount:i.runCount}):{success:!1,error:"No research state to checkpoint."}}catch(i){return g.error("[researchTools] research_checkpoint failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}}}}var WGe=E(()=>{"use strict";Gy();Os();bo();yo();lt();q();hle()});function KGe(r,e,t){return t==="lower"?r<e:r>e}function yxr(r,e,t,n,o){return t?"timeout":e||r===null?"crash":n===null||KGe(r,n,o)?"keep":"discard"}var Eq,JGe=E(()=>{"use strict";Gy();vI();br();cn();lt();q();BGe();_N();gle();zGe();jGe();GGe();VGe();HGe();WGe();Eq=class{config;stateStore;repoPolicy;runner;recorder;promptCompiler;initialized=!1;emitter;constructor(e){this.config=$Ge(e),this.stateStore=new wq(this.config.repoPath,this.config.statePath),this.repoPolicy=new vq(this.config),this.runner=new Sq(this.config),this.recorder=new bq(this.config),this.promptCompiler=new xq(this.config)}setEmitter(e){this.emitter=e}emit(e,...t){this.emitter?.emit(e,...t)}async initialize(e){return Ce({name:"autoresearch.initialize",tracer:me.autoresearch,attributes:{[de.AR_TAG]:e,[de.AR_BRANCH]:`${this.config.branchPrefix}${e}`}},async t=>{fle(this.config);let n=`${this.config.branchPrefix}${e}`;try{if(hi("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:this.config.repoPath,encoding:"utf-8"}).trim()!==n)try{hi("git",["checkout","-b",n],{cwd:this.config.repoPath,stdio:"ignore"})}catch{hi("git",["checkout",n],{cwd:this.config.repoPath,stdio:"ignore"})}}catch(s){throw this.emitError(e,"BRANCH_ERROR",`Failed to setup branch ${n}`),kr.create("BRANCH_ERROR",`Failed to setup branch ${n}`,{cause:s instanceof Error?s:void 0})}let o=await this.stateStore.initialize(e,n);return await this.recorder.ensureResultsFile(),this.initialized=!0,t.setAttribute(de.AR_PHASE,o.currentPhase),g.info("[Autoresearch] Worker initialized",{tag:e,branch:n}),this.emit("autoresearch:initialized",{tag:e,branch:n,config:{repoPath:this.config.repoPath,runCommand:this.config.runCommand,metric:this.config.metric,timeoutMs:this.config.timeoutMs}}),o})}async resume(){return Ce({name:"autoresearch.resume",tracer:me.autoresearch},async e=>{let t=await this.stateStore.load();if(!t)throw kr.create("STATE_NOT_FOUND","No state file found. Run initialize() first.");fle(this.config);try{hi("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:this.config.repoPath,encoding:"utf-8"}).trim()!==t.branch&&hi("git",["checkout",t.branch],{cwd:this.config.repoPath,stdio:"ignore"})}catch(n){throw g.error("[Autoresearch] Failed to restore branch",{expected:t.branch,error:n instanceof Error?n.message:String(n)}),kr.create("BRANCH_ERROR",`Failed to checkout branch ${t.branch} during resume`,{cause:n instanceof Error?n:void 0})}return this.initialized=!0,e.setAttribute(de.AR_TAG,t.tag),e.setAttribute(de.AR_BRANCH,t.branch),e.setAttribute(de.AR_RUN_COUNT,t.runCount),e.setAttribute(de.AR_PHASE,t.currentPhase),this.emit("autoresearch:resumed",{tag:t.tag,branch:t.branch,runCount:t.runCount,currentPhase:t.currentPhase}),t})}async runExperimentCycle(e){if(!this.initialized)throw kr.create("WORKER_NOT_INITIALIZED","Call initialize() or resume() first");let t=await this.stateStore.load();if(!t)throw kr.create("STATE_NOT_FOUND","State file missing");return Ce({name:"autoresearch.experiment_cycle",tracer:me.autoresearch,attributes:{[de.AR_TAG]:t.tag,[de.AR_RUN_COUNT]:t.runCount,[de.AR_DESCRIPTION]:e}},async n=>{let o=Date.now();this.emit("autoresearch:experiment-started",{tag:t.tag,runCount:t.runCount,description:e}),await this.advancePhase("run"),g.info("[Autoresearch] Running experiment",{runCount:t.runCount,description:e});let s=await Ce({name:"autoresearch.experiment_run",tracer:me.autoresearch,attributes:{[de.AR_TAG]:t.tag}},async()=>ke(this.runner.run(),this.config.timeoutMs+3e4,new Error("Experiment runner exceeded safety timeout")));await this.advancePhase("evaluate");let i=yxr(s.metric,s.crashed,s.timedOut,t.bestMetric,this.config.metric.direction),a=this.repoPolicy.getHeadCommit()||"unknown",c={commit:a,metric:s.metric,memoryGb:s.memoryValue,status:i,description:e,timestamp:new Date().toISOString()};if(await this.recorder.appendTsv(c),await this.recorder.appendJsonl(c),await this.advancePhase("accept_or_revert"),i==="keep")await this.stateStore.update({acceptedCommit:a,bestMetric:s.metric,baselineMetric:t.baselineMetric??s.metric,keepCount:t.keepCount+1,runCount:t.runCount+1,lastStatus:i,candidateCommit:null}),s.metric!==null&&t.bestMetric!==null&&KGe(s.metric,t.bestMetric,this.config.metric.direction)&&this.emit("autoresearch:metric-improved",{tag:t.tag,previousBest:t.bestMetric,newBest:s.metric,commit:a,direction:this.config.metric.direction,runCount:t.runCount+1});else{if(t.acceptedCommit){this.emit("autoresearch:revert",{tag:t.tag,targetCommit:t.acceptedCommit,reason:i,runCount:t.runCount});try{hi("git",["reset","--hard",t.acceptedCommit],{cwd:this.config.repoPath,stdio:"ignore"})}catch(d){let m=d instanceof Error?d.message:String(d);throw g.error("[Autoresearch] Revert failed \u2014 state NOT updated",{error:m}),this.emit("autoresearch:revert-failed",{tag:t.tag,targetCommit:t.acceptedCommit,error:m,runCount:t.runCount}),this.emitError(t.tag,"REVERT_FAILED",`Failed to revert to ${t.acceptedCommit}. Manual intervention required.`,t.currentPhase,t.runCount),kr.create("REVERT_FAILED",`Failed to revert to ${t.acceptedCommit}. Manual intervention required.`,{cause:d instanceof Error?d:void 0})}}await this.stateStore.update({runCount:t.runCount+1,lastStatus:i,candidateCommit:null})}let l=Date.now()-o;n.setAttribute(de.AR_STATUS,i),s.metric!==null&&n.setAttribute(de.AR_METRIC,s.metric),n.setAttribute(de.AR_COMMIT,a),n.setAttribute(de.AR_DURATION_MS,l),g.info("[Autoresearch] Experiment complete",{status:i,metric:s.metric,runCount:t.runCount+1}),this.emit("autoresearch:experiment-completed",{tag:t.tag,runCount:t.runCount+1,status:i,metric:s.metric,commit:a,description:e,durationMs:l});let u=await this.stateStore.load();return u&&this.emit("autoresearch:state-updated",{tag:u.tag,phase:u.currentPhase,runCount:u.runCount,keepCount:u.keepCount,bestMetric:u.bestMetric}),await this.advancePhase("propose"),c})}getTools(){return qGe({config:this.config,stateStore:this.stateStore,repoPolicy:this.repoPolicy,runner:this.runner,recorder:this.recorder})}async getSystemPrompt(){return this.promptCompiler.buildSystemPrompt()}async getCyclePrompt(){let e=await this.stateStore.load();if(!e)throw kr.create("STATE_NOT_FOUND","No state");let t=await this.recorder.readAll();return this.promptCompiler.buildCyclePrompt(e,t)}async getState(){return this.stateStore.load()}async getStats(){return this.recorder.getStats()}getConfig(){return this.config}async advancePhase(e){let t=await this.stateStore.load(),n=t?.currentPhase??"bootstrap";await this.stateStore.update({currentPhase:e}),g.debug("[Autoresearch] Phase advanced",{phase:e}),n!==e&&this.emit("autoresearch:phase-changed",{from:n,to:e,runCount:t?.runCount??0,tag:t?.tag??""})}async getPhaseToolPolicy(){let e=await this.stateStore.load();if(!e)throw kr.create("STATE_NOT_FOUND","No state for getPhaseToolPolicy");return yq(e.currentPhase)}async getToolFilterForCurrentPhase(){return{include:[...(await this.getPhaseToolPolicy()).activeTools]}}emitError(e,t,n,o,s){this.emit("autoresearch:error",{tag:e,error:n,code:t,phase:o,runCount:s})}}});function XGe(){_q.clear(),g.debug("[AutoresearchExecutor] Worker cache cleared")}function xxr(r,e){if(e.length===0)return null;function t(o,s){switch(o){case"research_get_context":return s==="bootstrap"||s==="propose"?"propose":s;case"research_read_file":return s==="propose"?"edit":s;case"research_write_candidate":return"commit";case"research_commit_candidate":return"run";case"research_run_experiment":return"evaluate";case"research_parse_log":return"record";case"research_record":return"accept_or_revert";case"research_accept":return"propose";case"research_revert":return"propose";default:return s}}let n=r;for(let o of e)n=t(o,n);return n!==r?n:null}async function vxr(r,e){let t=`task-${r.id}`,n=_q.get(t);if(n){e&&n.setEmitter(e);try{return await n.resume(),n}catch(i){let a=i instanceof Error?i.message:String(i);if(a.includes("STATE_NOT_FOUND")||a.includes("No state file"))_q.delete(t);else throw i}}let o=r.autoresearch,s=new Eq({repoPath:o.repoPath,mutablePaths:o.mutablePaths,runCommand:o.runCommand,metric:o.metric,...o.immutablePaths?{immutablePaths:o.immutablePaths}:{},...o.timeoutMs?{timeoutMs:o.timeoutMs}:{},...o.provider?{provider:o.provider}:{},...o.model?{model:o.model}:{},...o.thinkingLevel?{thinkingLevel:o.thinkingLevel}:{},...o.maxExperiments?{maxExperiments:o.maxExperiments}:{},...o.programPath?{programPath:o.programPath}:{},...o.resultsPath?{resultsPath:o.resultsPath}:{},...o.statePath?{statePath:o.statePath}:{},...o.logPath?{logPath:o.logPath}:{},...o.branchPrefix?{branchPrefix:o.branchPrefix}:{},...o.memoryMetric?{memoryMetric:o.memoryMetric}:{}});e&&s.setEmitter(e);try{await s.resume()}catch(i){let a=i instanceof Error?i.message:String(i);if(a.includes("STATE_NOT_FOUND")||a.includes("No state file"))await s.initialize(t);else throw i}return _q.set(t,s),s}async function YGe(r,e,t){let n=Date.now(),o=`ar_${Date.now()}`;if(!r.autoresearch)return{taskId:r.id,runId:o,status:"error",error:`Task ${r.id} has type=autoresearch but no autoresearch config`,durationMs:Date.now()-n,timestamp:new Date().toISOString()};try{let s=await vxr(r,t),i=s.getTools(),a=await s.getToolFilterForCurrentPhase(),c=await s.getSystemPrompt(),l=await s.getCyclePrompt(),u=e;if(typeof u.registerTool=="function")for(let[k,I]of Object.entries(i))u.registerTool(k,I);let d=await s.getPhaseToolPolicy(),m=r.autoresearch,f=r.timeout??12e4,h=new AbortController,y=setTimeout(()=>h.abort(),f),x={input:{text:l},systemPrompt:c,tools:!0,skipToolPromptInjection:!0,maxSteps:20,abortSignal:h.signal,...m?.provider?{provider:m.provider}:{},...m?.model?{model:m.model}:{},...m?.thinkingLevel||r.thinkingLevel?{thinkingConfig:{thinkingLevel:m?.thinkingLevel??r.thinkingLevel}}:{},...r.timeout?{timeout:r.timeout}:{},toolFilter:a,...d.forcedTool?{prepareStep:({stepNumber:k})=>k===0?{toolChoice:{type:"tool",toolName:d.forcedTool}}:{}}:{},requestId:o,...r.metadata?.maxBudgetUsd?{maxBudgetUsd:r.metadata.maxBudgetUsd}:{}},b;try{b=await ke(e.generate(x),f,new Error(`Autoresearch tick exceeded ${f}ms timeout`))}finally{clearTimeout(y)}let T=(b.toolExecutions??[]).map(k=>{let I=k;return typeof I.name=="string"?I.name:""}).filter(Boolean),_=(await s.getState())?.currentPhase??"bootstrap",C=xxr(_,T);return C&&(await s.advancePhase(C),g.debug("[AutoresearchExecutor] Phase advanced",{from:_,to:C,calledTools:T})),{taskId:r.id,runId:o,status:"success",output:b.content,toolCalls:b.toolExecutions?.map(k=>({name:k.name,input:k.input,output:k.output})),tokensUsed:b.usage?{input:b.usage.input??0,output:b.usage.output??0}:void 0,durationMs:Date.now()-n,timestamp:new Date().toISOString()}}catch(s){let i=s instanceof Error?s.message:String(s);return g.error("[AutoresearchExecutor] Tick failed",{taskId:r.id,runId:o,error:i}),{taskId:r.id,runId:o,status:"error",error:i,durationMs:Date.now()-n,timestamp:new Date().toISOString()}}}var _q,yle=E(()=>{"use strict";JGe();lt();q();_q=new Map});var bxr,Wr,kT=E(()=>{"use strict";Uw();bxr={TASK_NOT_FOUND:"TASK-001",BACKEND_NOT_INITIALIZED:"TASK-002",BACKEND_UNKNOWN:"TASK-003",INVALID_TASK_STATUS:"TASK-004",TASK_LIMIT_REACHED:"TASK-005",TASK_DISABLED:"TASK-006",SCHEDULE_FAILED:"TASK-007",TASK_VALIDATION_FAILED:"TASK-008"},Wr=il("Task",bxr)});var ZGe={};J(ZGe,{Agent:()=>cvr,BedrockClient:()=>Sxr,BedrockRuntimeClient:()=>Exr,Blob:()=>avr,Client:()=>uvr,ConverseCommand:()=>_xr,ConverseStreamCommand:()=>Cxr,Cron:()=>Gxr,Dispatcher:()=>dvr,File:()=>ivr,FlowProducer:()=>jxr,FormData:()=>svr,GoogleAuth:()=>Pxr,HTTPException:()=>Xxr,Headers:()=>ovr,Hippocampus:()=>Dxr,HippocampusConfig:()=>Lxr,Hono:()=>Kxr,ImageFormat:()=>kxr,InvokeEndpointCommand:()=>Axr,InvokeEndpointWithResponseStreamCommand:()=>Ixr,Job:()=>Bxr,ListFoundationModelsCommand:()=>wxr,MockAgent:()=>fvr,Pool:()=>lvr,Queue:()=>Fxr,QueueScheduler:()=>zxr,Request:()=>rvr,Response:()=>nvr,SageMakerRuntimeClient:()=>Rxr,TextToSpeechClient:()=>Mxr,VertexAI:()=>Oxr,Webhook:()=>Nxr,Worker:()=>$xr,convertToHtml:()=>Wxr,cors:()=>Jxr,createClient:()=>Uxr,default:()=>Txr,extractRawText:()=>qxr,fetch:()=>tvr,getGlobalDispatcher:()=>mvr,interceptors:()=>gvr,logger:()=>Yxr,parseBuffer:()=>Vxr,request:()=>hvr,secureHeaders:()=>Zxr,selectCover:()=>Hxr,setGlobalDispatcher:()=>pvr,streamSSE:()=>Qxr,timeout:()=>evr});var gC,Ci,Txr,Sxr,wxr,Exr,_xr,Cxr,kxr,Rxr,Axr,Ixr,Pxr,Oxr,Mxr,Nxr,Dxr,Lxr,Uxr,Fxr,$xr,Bxr,zxr,jxr,Gxr,Vxr,Hxr,qxr,Wxr,Kxr,Jxr,Xxr,Yxr,Zxr,Qxr,evr,tvr,rvr,nvr,ovr,svr,ivr,avr,cvr,lvr,uvr,dvr,pvr,mvr,fvr,gvr,hvr,QGe=E(()=>{gC={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:gC.get}):new Proxy(function(...t){return new Proxy({},{get:gC.get})},{get:gC.get,apply(t,n,o){return new Proxy({},{get:gC.get})},construct(t,n){return new Proxy({},{get:gC.get})}})}},Ci=new Proxy({},gC),Txr=Ci,{BedrockClient:Sxr,ListFoundationModelsCommand:wxr,BedrockRuntimeClient:Exr,ConverseCommand:_xr,ConverseStreamCommand:Cxr,ImageFormat:kxr}=Ci,{SageMakerRuntimeClient:Rxr,InvokeEndpointCommand:Axr,InvokeEndpointWithResponseStreamCommand:Ixr}=Ci,{GoogleAuth:Pxr,VertexAI:Oxr,TextToSpeechClient:Mxr}=Ci,{Webhook:Nxr}=Ci,{Hippocampus:Dxr,HippocampusConfig:Lxr}=Ci,{createClient:Uxr}=Ci,{Queue:Fxr,Worker:$xr,Job:Bxr,QueueScheduler:zxr,FlowProducer:jxr}=Ci,{Cron:Gxr}=Ci,{parseBuffer:Vxr,selectCover:Hxr}=Ci,{extractRawText:qxr,convertToHtml:Wxr}=Ci,{Hono:Kxr}=Ci,{cors:Jxr,HTTPException:Xxr,logger:Yxr,secureHeaders:Zxr,streamSSE:Qxr,timeout:evr}=Ci,tvr=globalThis.fetch,rvr=globalThis.Request,nvr=globalThis.Response,ovr=globalThis.Headers,svr=globalThis.FormData,ivr=globalThis.File,avr=globalThis.Blob,cvr=Ci.Agent,lvr=Ci.Pool,uvr=Ci.Client,dvr=Ci.Dispatcher,pvr=()=>{},mvr=()=>Ci,fvr=Ci.MockAgent,gvr={redirect:()=>r=>r,retry:()=>r=>r},hvr=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});var tVe={};J(tVe,{BullMQBackend:()=>xle});async function yvr(){try{return await Promise.resolve().then(()=>(QGe(),ZGe))}catch(r){let e=r instanceof Error?r:null;throw e?.code==="ERR_MODULE_NOT_FOUND"&&e.message.includes("bullmq")?new Error(`BullMQ task backend requires the "bullmq" package. Install it with:
|
|
1596
|
+
`),totalLines:c.length}}catch(i){return g.error("[researchTools] research_inspect_failure failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}},research_checkpoint:{description:"Save the current research state to disk. Call periodically to ensure progress is not lost.",inputSchema:p.object({}),execute:async()=>{try{let i=await t.load();return i?(await t.save(i),{success:!0,checkpointedAt:new Date().toISOString(),phase:i.currentPhase,runCount:i.runCount}):{success:!1,error:"No research state to checkpoint."}}catch(i){return g.error("[researchTools] research_checkpoint failed",{error:String(i)}),{success:!1,error:i instanceof Error?i.message:String(i)}}}}}}var WGe=E(()=>{"use strict";Gy();Os();bo();yo();lt();q();hle()});function KGe(r,e,t){return t==="lower"?r<e:r>e}function yxr(r,e,t,n,o){return t?"timeout":e||r===null?"crash":n===null||KGe(r,n,o)?"keep":"discard"}var Eq,JGe=E(()=>{"use strict";Gy();vI();br();cn();lt();q();BGe();_N();gle();zGe();jGe();GGe();VGe();HGe();WGe();Eq=class{config;stateStore;repoPolicy;runner;recorder;promptCompiler;initialized=!1;emitter;constructor(e){this.config=$Ge(e),this.stateStore=new wq(this.config.repoPath,this.config.statePath),this.repoPolicy=new vq(this.config),this.runner=new Sq(this.config),this.recorder=new bq(this.config),this.promptCompiler=new xq(this.config)}setEmitter(e){this.emitter=e}emit(e,...t){this.emitter?.emit(e,...t)}async initialize(e){return Ce({name:"autoresearch.initialize",tracer:me.autoresearch,attributes:{[de.AR_TAG]:e,[de.AR_BRANCH]:`${this.config.branchPrefix}${e}`}},async t=>{fle(this.config);let n=`${this.config.branchPrefix}${e}`;try{if(hi("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:this.config.repoPath,encoding:"utf-8"}).trim()!==n)try{hi("git",["checkout","-b",n],{cwd:this.config.repoPath,stdio:"ignore"})}catch{hi("git",["checkout",n],{cwd:this.config.repoPath,stdio:"ignore"})}}catch(s){throw this.emitError(e,"BRANCH_ERROR",`Failed to setup branch ${n}`),kr.create("BRANCH_ERROR",`Failed to setup branch ${n}`,{cause:s instanceof Error?s:void 0})}let o=await this.stateStore.initialize(e,n);return await this.recorder.ensureResultsFile(),this.initialized=!0,t.setAttribute(de.AR_PHASE,o.currentPhase),g.info("[Autoresearch] Worker initialized",{tag:e,branch:n}),this.emit("autoresearch:initialized",{tag:e,branch:n,config:{repoPath:this.config.repoPath,runCommand:this.config.runCommand,metric:this.config.metric,timeoutMs:this.config.timeoutMs}}),o})}async resume(){return Ce({name:"autoresearch.resume",tracer:me.autoresearch},async e=>{let t=await this.stateStore.load();if(!t)throw kr.create("STATE_NOT_FOUND","No state file found. Run initialize() first.");fle(this.config);try{hi("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:this.config.repoPath,encoding:"utf-8"}).trim()!==t.branch&&hi("git",["checkout",t.branch],{cwd:this.config.repoPath,stdio:"ignore"})}catch(n){throw g.error("[Autoresearch] Failed to restore branch",{expected:t.branch,error:n instanceof Error?n.message:String(n)}),kr.create("BRANCH_ERROR",`Failed to checkout branch ${t.branch} during resume`,{cause:n instanceof Error?n:void 0})}return this.initialized=!0,e.setAttribute(de.AR_TAG,t.tag),e.setAttribute(de.AR_BRANCH,t.branch),e.setAttribute(de.AR_RUN_COUNT,t.runCount),e.setAttribute(de.AR_PHASE,t.currentPhase),this.emit("autoresearch:resumed",{tag:t.tag,branch:t.branch,runCount:t.runCount,currentPhase:t.currentPhase}),t})}async runExperimentCycle(e){if(!this.initialized)throw kr.create("WORKER_NOT_INITIALIZED","Call initialize() or resume() first");let t=await this.stateStore.load();if(!t)throw kr.create("STATE_NOT_FOUND","State file missing");return Ce({name:"autoresearch.experiment_cycle",tracer:me.autoresearch,attributes:{[de.AR_TAG]:t.tag,[de.AR_RUN_COUNT]:t.runCount,[de.AR_DESCRIPTION]:e}},async n=>{let o=Date.now();this.emit("autoresearch:experiment-started",{tag:t.tag,runCount:t.runCount,description:e}),await this.advancePhase("run"),g.info("[Autoresearch] Running experiment",{runCount:t.runCount,description:e});let s=await Ce({name:"autoresearch.experiment_run",tracer:me.autoresearch,attributes:{[de.AR_TAG]:t.tag}},async()=>ke(this.runner.run(),this.config.timeoutMs+3e4,new Error("Experiment runner exceeded safety timeout")));await this.advancePhase("evaluate");let i=yxr(s.metric,s.crashed,s.timedOut,t.bestMetric,this.config.metric.direction),a=this.repoPolicy.getHeadCommit()||"unknown",c={commit:a,metric:s.metric,memoryGb:s.memoryValue,status:i,description:e,timestamp:new Date().toISOString()};if(await this.recorder.appendTsv(c),await this.recorder.appendJsonl(c),await this.advancePhase("accept_or_revert"),i==="keep")await this.stateStore.update({acceptedCommit:a,bestMetric:s.metric,baselineMetric:t.baselineMetric??s.metric,keepCount:t.keepCount+1,runCount:t.runCount+1,lastStatus:i,candidateCommit:null}),s.metric!==null&&t.bestMetric!==null&&KGe(s.metric,t.bestMetric,this.config.metric.direction)&&this.emit("autoresearch:metric-improved",{tag:t.tag,previousBest:t.bestMetric,newBest:s.metric,commit:a,direction:this.config.metric.direction,runCount:t.runCount+1});else{if(t.acceptedCommit){this.emit("autoresearch:revert",{tag:t.tag,targetCommit:t.acceptedCommit,reason:i,runCount:t.runCount});try{hi("git",["reset","--hard",t.acceptedCommit],{cwd:this.config.repoPath,stdio:"ignore"})}catch(d){let m=d instanceof Error?d.message:String(d);throw g.error("[Autoresearch] Revert failed \u2014 state NOT updated",{error:m}),this.emit("autoresearch:revert-failed",{tag:t.tag,targetCommit:t.acceptedCommit,error:m,runCount:t.runCount}),this.emitError(t.tag,"REVERT_FAILED",`Failed to revert to ${t.acceptedCommit}. Manual intervention required.`,t.currentPhase,t.runCount),kr.create("REVERT_FAILED",`Failed to revert to ${t.acceptedCommit}. Manual intervention required.`,{cause:d instanceof Error?d:void 0})}}await this.stateStore.update({runCount:t.runCount+1,lastStatus:i,candidateCommit:null})}let l=Date.now()-o;n.setAttribute(de.AR_STATUS,i),s.metric!==null&&n.setAttribute(de.AR_METRIC,s.metric),n.setAttribute(de.AR_COMMIT,a),n.setAttribute(de.AR_DURATION_MS,l),g.info("[Autoresearch] Experiment complete",{status:i,metric:s.metric,runCount:t.runCount+1}),this.emit("autoresearch:experiment-completed",{tag:t.tag,runCount:t.runCount+1,status:i,metric:s.metric,commit:a,description:e,durationMs:l});let u=await this.stateStore.load();return u&&this.emit("autoresearch:state-updated",{tag:u.tag,phase:u.currentPhase,runCount:u.runCount,keepCount:u.keepCount,bestMetric:u.bestMetric}),await this.advancePhase("propose"),c})}getTools(){return qGe({config:this.config,stateStore:this.stateStore,repoPolicy:this.repoPolicy,runner:this.runner,recorder:this.recorder})}async getSystemPrompt(){return this.promptCompiler.buildSystemPrompt()}async getCyclePrompt(){let e=await this.stateStore.load();if(!e)throw kr.create("STATE_NOT_FOUND","No state");let t=await this.recorder.readAll();return this.promptCompiler.buildCyclePrompt(e,t)}async getState(){return this.stateStore.load()}async getStats(){return this.recorder.getStats()}getConfig(){return this.config}async advancePhase(e){let t=await this.stateStore.load(),n=t?.currentPhase??"bootstrap";await this.stateStore.update({currentPhase:e}),g.debug("[Autoresearch] Phase advanced",{phase:e}),n!==e&&this.emit("autoresearch:phase-changed",{from:n,to:e,runCount:t?.runCount??0,tag:t?.tag??""})}async getPhaseToolPolicy(){let e=await this.stateStore.load();if(!e)throw kr.create("STATE_NOT_FOUND","No state for getPhaseToolPolicy");return yq(e.currentPhase)}async getToolFilterForCurrentPhase(){return{include:[...(await this.getPhaseToolPolicy()).activeTools]}}emitError(e,t,n,o,s){this.emit("autoresearch:error",{tag:e,error:n,code:t,phase:o,runCount:s})}}});function XGe(){_q.clear(),g.debug("[AutoresearchExecutor] Worker cache cleared")}function xxr(r,e){if(e.length===0)return null;function t(o,s){switch(o){case"research_get_context":return s==="bootstrap"||s==="propose"?"propose":s;case"research_read_file":return s==="propose"?"edit":s;case"research_write_candidate":return"commit";case"research_commit_candidate":return"run";case"research_run_experiment":return"evaluate";case"research_parse_log":return"record";case"research_record":return"accept_or_revert";case"research_accept":return"propose";case"research_revert":return"propose";default:return s}}let n=r;for(let o of e)n=t(o,n);return n!==r?n:null}async function vxr(r,e){let t=`task-${r.id}`,n=_q.get(t);if(n){e&&n.setEmitter(e);try{return await n.resume(),n}catch(i){let a=i instanceof Error?i.message:String(i);if(a.includes("STATE_NOT_FOUND")||a.includes("No state file"))_q.delete(t);else throw i}}let o=r.autoresearch,s=new Eq({repoPath:o.repoPath,mutablePaths:o.mutablePaths,runCommand:o.runCommand,metric:o.metric,...o.immutablePaths?{immutablePaths:o.immutablePaths}:{},...o.timeoutMs?{timeoutMs:o.timeoutMs}:{},...o.provider?{provider:o.provider}:{},...o.model?{model:o.model}:{},...o.thinkingLevel?{thinkingLevel:o.thinkingLevel}:{},...o.maxExperiments?{maxExperiments:o.maxExperiments}:{},...o.programPath?{programPath:o.programPath}:{},...o.resultsPath?{resultsPath:o.resultsPath}:{},...o.statePath?{statePath:o.statePath}:{},...o.logPath?{logPath:o.logPath}:{},...o.branchPrefix?{branchPrefix:o.branchPrefix}:{},...o.memoryMetric?{memoryMetric:o.memoryMetric}:{}});e&&s.setEmitter(e);try{await s.resume()}catch(i){let a=i instanceof Error?i.message:String(i);if(a.includes("STATE_NOT_FOUND")||a.includes("No state file"))await s.initialize(t);else throw i}return _q.set(t,s),s}async function YGe(r,e,t){let n=Date.now(),o=`ar_${Date.now()}`;if(!r.autoresearch)return{taskId:r.id,runId:o,status:"error",error:`Task ${r.id} has type=autoresearch but no autoresearch config`,durationMs:Date.now()-n,timestamp:new Date().toISOString()};try{let s=await vxr(r,t),i=s.getTools(),a=await s.getToolFilterForCurrentPhase(),c=await s.getSystemPrompt(),l=await s.getCyclePrompt(),u=e;if(typeof u.registerTool=="function")for(let[k,I]of Object.entries(i))u.registerTool(k,I);let d=await s.getPhaseToolPolicy(),m=r.autoresearch,f=r.timeout??12e4,h=new AbortController,y=setTimeout(()=>h.abort(),f),x={input:{text:l},systemPrompt:c,tools:!0,skipToolPromptInjection:!0,maxSteps:20,abortSignal:h.signal,...m?.provider?{provider:m.provider}:{},...m?.model?{model:m.model}:{},...m?.thinkingLevel||r.thinkingLevel?{thinkingConfig:{thinkingLevel:m?.thinkingLevel??r.thinkingLevel}}:{},...r.timeout?{timeout:r.timeout}:{},toolFilter:a,...d.forcedTool?{prepareStep:({stepNumber:k})=>k===0&&d.forcedTool?{toolChoice:{type:"tool",toolName:d.forcedTool}}:{}}:{},requestId:o,...r.metadata?.maxBudgetUsd?{maxBudgetUsd:r.metadata.maxBudgetUsd}:{}},b;try{b=await ke(e.generate(x),f,new Error(`Autoresearch tick exceeded ${f}ms timeout`))}finally{clearTimeout(y)}let T=(b.toolExecutions??[]).map(k=>{let I=k;return typeof I.name=="string"?I.name:""}).filter(Boolean),_=(await s.getState())?.currentPhase??"bootstrap",C=xxr(_,T);return C&&(await s.advancePhase(C),g.debug("[AutoresearchExecutor] Phase advanced",{from:_,to:C,calledTools:T})),{taskId:r.id,runId:o,status:"success",output:b.content,toolCalls:b.toolExecutions?.map(k=>({name:k.name,input:k.input,output:k.output})),tokensUsed:b.usage?{input:b.usage.input??0,output:b.usage.output??0}:void 0,durationMs:Date.now()-n,timestamp:new Date().toISOString()}}catch(s){let i=s instanceof Error?s.message:String(s);return g.error("[AutoresearchExecutor] Tick failed",{taskId:r.id,runId:o,error:i}),{taskId:r.id,runId:o,status:"error",error:i,durationMs:Date.now()-n,timestamp:new Date().toISOString()}}}var _q,yle=E(()=>{"use strict";JGe();lt();q();_q=new Map});var bxr,Wr,kT=E(()=>{"use strict";Uw();bxr={TASK_NOT_FOUND:"TASK-001",BACKEND_NOT_INITIALIZED:"TASK-002",BACKEND_UNKNOWN:"TASK-003",INVALID_TASK_STATUS:"TASK-004",TASK_LIMIT_REACHED:"TASK-005",TASK_DISABLED:"TASK-006",SCHEDULE_FAILED:"TASK-007",TASK_VALIDATION_FAILED:"TASK-008"},Wr=il("Task",bxr)});var ZGe={};J(ZGe,{Agent:()=>cvr,BedrockClient:()=>Sxr,BedrockRuntimeClient:()=>Exr,Blob:()=>avr,Client:()=>uvr,ConverseCommand:()=>_xr,ConverseStreamCommand:()=>Cxr,Cron:()=>Gxr,Dispatcher:()=>dvr,File:()=>ivr,FlowProducer:()=>jxr,FormData:()=>svr,GoogleAuth:()=>Pxr,HTTPException:()=>Xxr,Headers:()=>ovr,Hippocampus:()=>Dxr,HippocampusConfig:()=>Lxr,Hono:()=>Kxr,ImageFormat:()=>kxr,InvokeEndpointCommand:()=>Axr,InvokeEndpointWithResponseStreamCommand:()=>Ixr,Job:()=>Bxr,ListFoundationModelsCommand:()=>wxr,MockAgent:()=>fvr,Pool:()=>lvr,Queue:()=>Fxr,QueueScheduler:()=>zxr,Request:()=>rvr,Response:()=>nvr,SageMakerRuntimeClient:()=>Rxr,TextToSpeechClient:()=>Mxr,VertexAI:()=>Oxr,Webhook:()=>Nxr,Worker:()=>$xr,convertToHtml:()=>Wxr,cors:()=>Jxr,createClient:()=>Uxr,default:()=>Txr,extractRawText:()=>qxr,fetch:()=>tvr,getGlobalDispatcher:()=>mvr,interceptors:()=>gvr,logger:()=>Yxr,parseBuffer:()=>Vxr,request:()=>hvr,secureHeaders:()=>Zxr,selectCover:()=>Hxr,setGlobalDispatcher:()=>pvr,streamSSE:()=>Qxr,timeout:()=>evr});var gC,Ci,Txr,Sxr,wxr,Exr,_xr,Cxr,kxr,Rxr,Axr,Ixr,Pxr,Oxr,Mxr,Nxr,Dxr,Lxr,Uxr,Fxr,$xr,Bxr,zxr,jxr,Gxr,Vxr,Hxr,qxr,Wxr,Kxr,Jxr,Xxr,Yxr,Zxr,Qxr,evr,tvr,rvr,nvr,ovr,svr,ivr,avr,cvr,lvr,uvr,dvr,pvr,mvr,fvr,gvr,hvr,QGe=E(()=>{gC={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:gC.get}):new Proxy(function(...t){return new Proxy({},{get:gC.get})},{get:gC.get,apply(t,n,o){return new Proxy({},{get:gC.get})},construct(t,n){return new Proxy({},{get:gC.get})}})}},Ci=new Proxy({},gC),Txr=Ci,{BedrockClient:Sxr,ListFoundationModelsCommand:wxr,BedrockRuntimeClient:Exr,ConverseCommand:_xr,ConverseStreamCommand:Cxr,ImageFormat:kxr}=Ci,{SageMakerRuntimeClient:Rxr,InvokeEndpointCommand:Axr,InvokeEndpointWithResponseStreamCommand:Ixr}=Ci,{GoogleAuth:Pxr,VertexAI:Oxr,TextToSpeechClient:Mxr}=Ci,{Webhook:Nxr}=Ci,{Hippocampus:Dxr,HippocampusConfig:Lxr}=Ci,{createClient:Uxr}=Ci,{Queue:Fxr,Worker:$xr,Job:Bxr,QueueScheduler:zxr,FlowProducer:jxr}=Ci,{Cron:Gxr}=Ci,{parseBuffer:Vxr,selectCover:Hxr}=Ci,{extractRawText:qxr,convertToHtml:Wxr}=Ci,{Hono:Kxr}=Ci,{cors:Jxr,HTTPException:Xxr,logger:Yxr,secureHeaders:Zxr,streamSSE:Qxr,timeout:evr}=Ci,tvr=globalThis.fetch,rvr=globalThis.Request,nvr=globalThis.Response,ovr=globalThis.Headers,svr=globalThis.FormData,ivr=globalThis.File,avr=globalThis.Blob,cvr=Ci.Agent,lvr=Ci.Pool,uvr=Ci.Client,dvr=Ci.Dispatcher,pvr=()=>{},mvr=()=>Ci,fvr=Ci.MockAgent,gvr={redirect:()=>r=>r,retry:()=>r=>r},hvr=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});var tVe={};J(tVe,{BullMQBackend:()=>xle});async function yvr(){try{return await Promise.resolve().then(()=>(QGe(),ZGe))}catch(r){let e=r instanceof Error?r:null;throw e?.code==="ERR_MODULE_NOT_FOUND"&&e.message.includes("bullmq")?new Error(`BullMQ task backend requires the "bullmq" package. Install it with:
|
|
1597
1597
|
pnpm add bullmq`,{cause:r}):r}}var eVe,xle,rVe=E(()=>{"use strict";q();kT();dt();eVe="neurolink-tasks",xle=class{name="bullmq";queue=null;worker=null;executors=new Map;config;constructor(e){this.config=e}async initialize(){let{Queue:e,Worker:t}=await yvr(),n=this.getConnectionConfig();this.queue=new e(eVe,{connection:n}),this.worker=new t(eVe,async o=>{let s=o.data.taskId,i=o.data.task,a=this.executors.get(s);if(!a){g.warn("[BullMQ] No executor found for task",{taskId:s});return}return g.info("[BullMQ] Executing task",{taskId:s,name:i.name}),await a(i)},{connection:n,concurrency:this.config.maxConcurrentRuns??Wn.maxConcurrentRuns}),this.worker.on("failed",(o,s)=>{g.error("[BullMQ] Job failed",{taskId:o?.data?.taskId,error:String(s)})}),this.worker.on("error",o=>{g.error("[BullMQ] Worker error",{error:String(o)})}),g.info("[BullMQ] Backend initialized")}async shutdown(){this.worker&&(await this.worker.close(),this.worker=null),this.queue&&(await this.queue.close(),this.queue=null),this.executors.clear(),g.info("[BullMQ] Backend shut down")}async schedule(e,t){let n=this.getQueue();this.executors.set(e.id,t);try{let o={taskId:e.id,task:e},s=e.schedule;if(s.type==="cron")await n.upsertJobScheduler(e.id,{pattern:s.expression,...s.timezone?{tz:s.timezone}:{}},{name:e.name,data:o});else if(s.type==="interval")await n.upsertJobScheduler(e.id,{every:s.every},{name:e.name,data:o});else if(s.type==="once"){let i=typeof s.at=="string"?new Date(s.at):s.at,a=Math.max(0,i.getTime()-Date.now());await n.add(e.name,o,{jobId:e.id,delay:a})}}catch(o){throw this.executors.delete(e.id),o}g.info("[BullMQ] Task scheduled",{taskId:e.id,type:e.schedule.type})}async cancel(e){let t=this.getQueue();this.executors.delete(e);try{await t.removeJobScheduler(e)}catch{}try{let n=await t.getJob(e);n&&await n.remove()}catch{}g.info("[BullMQ] Task cancelled",{taskId:e})}async pause(e){await this.cancel(e),g.info("[BullMQ] Task paused (cancelled pending jobs; TaskManager will re-schedule on resume)",{taskId:e})}async resume(e){g.info("[BullMQ] Task resume requested (awaiting re-schedule from TaskManager)",{taskId:e})}async isHealthy(){if(!this.queue)return!1;try{return await this.queue.getJobCounts(),!0}catch{return!1}}getConnectionConfig(){let e=this.config.redis??{};if(e.url){let t=new URL(e.url),n={host:t.hostname||"localhost",port:Number(t.port)||6379,db:t.pathname&&Number(t.pathname.slice(1))||0};return t.password&&(n.password=decodeURIComponent(t.password)),t.username&&(n.username=decodeURIComponent(t.username)),t.protocol==="rediss:"&&(n.tls={}),n}return{host:e.host??Wn.redis.host,port:e.port??Wn.redis.port,...e.password?{password:e.password}:{},db:e.db??0}}ensureInitialized(){if(!this.queue)throw Wr.create("BACKEND_NOT_INITIALIZED","[BullMQ] Backend not initialized. Call initialize() first.")}getQueue(){if(this.ensureInitialized(),!this.queue)throw Wr.create("BACKEND_NOT_INITIALIZED","[BullMQ] Queue is unavailable after initialization.");return this.queue}}});var hC,ja,v7n,b7n,T7n,S7n,w7n,E7n,_7n,C7n,k7n,R7n,A7n,I7n,P7n,O7n,M7n,N7n,D7n,L7n,U7n,F7n,$7n,nVe,B7n,z7n,j7n,G7n,V7n,H7n,q7n,W7n,K7n,J7n,X7n,Y7n,Z7n,Q7n,eQn,tQn,rQn,nQn,oQn,sQn,iQn,aQn,cQn,oVe=E(()=>{hC={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:hC.get}):new Proxy(function(...t){return new Proxy({},{get:hC.get})},{get:hC.get,apply(t,n,o){return new Proxy({},{get:hC.get})},construct(t,n){return new Proxy({},{get:hC.get})}})}},ja=new Proxy({},hC),{BedrockClient:v7n,ListFoundationModelsCommand:b7n,BedrockRuntimeClient:T7n,ConverseCommand:S7n,ConverseStreamCommand:w7n,ImageFormat:E7n}=ja,{SageMakerRuntimeClient:_7n,InvokeEndpointCommand:C7n,InvokeEndpointWithResponseStreamCommand:k7n}=ja,{GoogleAuth:R7n,VertexAI:A7n,TextToSpeechClient:I7n}=ja,{Webhook:P7n}=ja,{Hippocampus:O7n,HippocampusConfig:M7n}=ja,{createClient:N7n}=ja,{Queue:D7n,Worker:L7n,Job:U7n,QueueScheduler:F7n,FlowProducer:$7n}=ja,{Cron:nVe}=ja,{parseBuffer:B7n,selectCover:z7n}=ja,{extractRawText:j7n,convertToHtml:G7n}=ja,{Hono:V7n}=ja,{cors:H7n,HTTPException:q7n,logger:W7n,secureHeaders:K7n,streamSSE:J7n,timeout:X7n}=ja,Y7n=globalThis.fetch,Z7n=globalThis.Request,Q7n=globalThis.Response,eQn=globalThis.Headers,tQn=globalThis.FormData,rQn=globalThis.File,nQn=globalThis.Blob,oQn=ja.Agent,sQn=ja.Pool,iQn=ja.Client,aQn=ja.Dispatcher,cQn=ja.MockAgent});var sVe={};J(sVe,{NodeTimeoutBackend:()=>vle});var vle,iVe=E(()=>{"use strict";oVe();q();dt();vle=class{name="node-timeout";scheduled=new Map;paused=new Map;disposed=!1;activeRuns=0;maxConcurrentRuns;constructor(e){this.maxConcurrentRuns=e.maxConcurrentRuns??Wn.maxConcurrentRuns}async initialize(){g.info("[NodeTimeout] Backend initialized")}async shutdown(){this.disposed=!0;for(let e of this.scheduled.values())this.clearEntry(e);this.scheduled.clear(),this.paused.clear(),g.info("[NodeTimeout] Backend shut down")}async schedule(e,t){await this.cancel(e.id);let n={taskId:e.id,executor:t,task:e},o=e.schedule;if(o.type==="cron")n.cronJob=new nVe(o.expression,{timezone:o.timezone,catch:s=>{g.error("[NodeTimeout] Cron execution error",{taskId:e.id,error:String(s)})}},()=>{this.executeTask(n)});else if(o.type==="interval")n.intervalId=setInterval(()=>{this.executeTask(n)},o.every);else if(o.type==="once"){let s=typeof o.at=="string"?new Date(o.at):o.at,i=Math.max(0,s.getTime()-Date.now());n.timeoutId=setTimeout(()=>{this.executeTask(n),this.scheduled.delete(e.id)},i)}this.scheduled.set(e.id,n),g.info("[NodeTimeout] Task scheduled",{taskId:e.id,type:o.type})}async cancel(e){let t=this.scheduled.get(e);t&&(this.clearEntry(t),this.scheduled.delete(e)),this.paused.delete(e),g.debug("[NodeTimeout] Task cancelled",{taskId:e})}async pause(e){let t=this.scheduled.get(e);t&&(this.clearEntry(t),this.scheduled.delete(e),this.paused.set(e,t),g.info("[NodeTimeout] Task paused",{taskId:e}))}async resume(e){let t=this.paused.get(e);t&&(this.paused.delete(e),await this.schedule(t.task,t.executor),g.info("[NodeTimeout] Task resumed",{taskId:e}))}async isHealthy(){return!this.disposed}executeTask(e){if(this.activeRuns>=this.maxConcurrentRuns){g.warn("[NodeTimeout] Max concurrent runs reached, skipping tick",{taskId:e.taskId,activeRuns:this.activeRuns,maxConcurrentRuns:this.maxConcurrentRuns});return}this.activeRuns++,e.executor(e.task).catch(t=>{g.error("[NodeTimeout] Task execution failed",{taskId:e.taskId,error:String(t)})}).finally(()=>{this.activeRuns--})}clearEntry(e){e.cronJob&&e.cronJob.stop(),e.intervalId!==void 0&&clearInterval(e.intervalId),e.timeoutId!==void 0&&clearTimeout(e.timeoutId)}}});var Cq,aVe=E(()=>{"use strict";q();kT();Cq=class r{static factories=new Map;static registered=!1;static register(e,t){r.factories.set(e,t),g.debug(`[TaskBackendRegistry] Registered backend: ${e}`)}static registerDefaults(){r.registered||(r.registered=!0,r.register("bullmq",async e=>{let{BullMQBackend:t}=await Promise.resolve().then(()=>(rVe(),tVe));return new t(e)}),r.register("node-timeout",async e=>{let{NodeTimeoutBackend:t}=await Promise.resolve().then(()=>(iVe(),sVe));return new t(e)}),g.debug("[TaskBackendRegistry] Registered default backends"))}static async create(e,t){r.registerDefaults();let n=r.factories.get(e);if(!n){let o=Array.from(r.factories.keys());throw Wr.create("BACKEND_UNKNOWN",`Unknown task backend: "${e}". Available: ${o.join(", ")}`)}return n(t)}static has(e){return r.registerDefaults(),r.factories.has(e)}static getAvailable(){return r.registerDefaults(),Array.from(r.factories.keys())}}});function vvr(r){let e=String(r).toLowerCase();return xvr.some(t=>e.includes(t))}function bvr(r){return new Promise(e=>setTimeout(e,r))}var xvr,kq,cVe=E(()=>{"use strict";wO();q();yle();xvr=["rate limit","rate_limit","too many requests","429","503","502","504","timeout","econnreset","econnrefused","network","overloaded"];kq=class{constructor(e,t,n){this.neurolink=e;this.store=t;this.emitter=n}neurolink;store;emitter;async execute(e){let t=`run_${Rm(12)}`,n=Date.now(),o;for(let i=1;i<=e.retry.maxAttempts;i++)try{return await this.executeOnce(e,t)}catch(a){o=String(a);let c=i<e.retry.maxAttempts&&vvr(a);if(g.warn("[TaskExecutor] Execution attempt failed",{taskId:e.id,runId:t,attempt:i,willRetry:c,error:o}),!c)break;let l=Math.min(i-1,e.retry.backoffMs.length-1),u=e.retry.backoffMs[l];await bvr(u)}return{taskId:e.id,runId:t,status:"error",error:o,durationMs:Date.now()-n,timestamp:new Date().toISOString()}}async executeOnce(e,t){if(e.type==="autoresearch")return YGe(e,this.neurolink,this.emitter);let n=Date.now(),o={input:{text:e.prompt},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.systemPrompt?{systemPrompt:e.systemPrompt}:{},...e.maxTokens?{maxTokens:e.maxTokens}:{},...e.temperature!==void 0?{temperature:e.temperature}:{},...e.timeout?{timeout:e.timeout}:{},...e.tools?{}:{disableTools:!0}};if(e.thinkingLevel&&(o.thinkingConfig={thinkingLevel:e.thinkingLevel}),e.mode==="continuation"&&e.sessionId){let a=await this.store.getHistory(e.id);a.length>0&&(o.conversationMessages=a.map((u,d)=>({id:`${e.sessionId}_${d}`,role:u.role,content:u.content,timestamp:u.timestamp})));let c=Math.floor(a.length/2),l=c>0?`This is a continuation task (run ${c+1}). Your previous ${c} exchange(s) are provided as conversation history.`:"This is a continuation task. This is the first execution \u2014 no prior history exists yet.";o.systemPrompt=e.systemPrompt?`${e.systemPrompt}
|
|
1598
1598
|
|
|
1599
1599
|
${l}`:l}let s=await this.neurolink.generate(o),i={taskId:e.id,runId:t,status:"success",output:s.content,toolCalls:s.toolExecutions?.map(a=>({name:a.name,input:a.input,output:a.output})),tokensUsed:s.usage?{input:s.usage.input??0,output:s.usage.output??0}:void 0,durationMs:Date.now()-n,timestamp:new Date().toISOString()};if(e.mode==="continuation"&&e.sessionId){let a=[{role:"user",content:e.prompt,timestamp:new Date(n).toISOString()},{role:"assistant",content:s.content,timestamp:i.timestamp}];await this.store.appendHistory(e.id,a)}return i}}});var lVe={};J(lVe,{Agent:()=>abr,BedrockClient:()=>Svr,BedrockRuntimeClient:()=>Evr,Blob:()=>ibr,Client:()=>lbr,ConverseCommand:()=>_vr,ConverseStreamCommand:()=>Cvr,Cron:()=>jvr,Dispatcher:()=>ubr,File:()=>sbr,FlowProducer:()=>zvr,FormData:()=>obr,GoogleAuth:()=>Pvr,HTTPException:()=>Jvr,Headers:()=>nbr,Hippocampus:()=>Dvr,HippocampusConfig:()=>Lvr,Hono:()=>Wvr,ImageFormat:()=>kvr,InvokeEndpointCommand:()=>Avr,InvokeEndpointWithResponseStreamCommand:()=>Ivr,Job:()=>$vr,ListFoundationModelsCommand:()=>wvr,MockAgent:()=>mbr,Pool:()=>cbr,Queue:()=>Uvr,QueueScheduler:()=>Bvr,Request:()=>tbr,Response:()=>rbr,SageMakerRuntimeClient:()=>Rvr,TextToSpeechClient:()=>Mvr,VertexAI:()=>Ovr,Webhook:()=>Nvr,Worker:()=>Fvr,convertToHtml:()=>qvr,cors:()=>Kvr,createClient:()=>CN,default:()=>Tvr,extractRawText:()=>Hvr,fetch:()=>ebr,getGlobalDispatcher:()=>pbr,interceptors:()=>fbr,logger:()=>Xvr,parseBuffer:()=>Gvr,request:()=>gbr,secureHeaders:()=>Yvr,selectCover:()=>Vvr,setGlobalDispatcher:()=>dbr,streamSSE:()=>Zvr,timeout:()=>Qvr});var yC,ki,Tvr,Svr,wvr,Evr,_vr,Cvr,kvr,Rvr,Avr,Ivr,Pvr,Ovr,Mvr,Nvr,Dvr,Lvr,CN,Uvr,Fvr,$vr,Bvr,zvr,jvr,Gvr,Vvr,Hvr,qvr,Wvr,Kvr,Jvr,Xvr,Yvr,Zvr,Qvr,ebr,tbr,rbr,nbr,obr,sbr,ibr,abr,cbr,lbr,ubr,dbr,pbr,mbr,fbr,gbr,Rq=E(()=>{yC={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:yC.get}):new Proxy(function(...t){return new Proxy({},{get:yC.get})},{get:yC.get,apply(t,n,o){return new Proxy({},{get:yC.get})},construct(t,n){return new Proxy({},{get:yC.get})}})}},ki=new Proxy({},yC),Tvr=ki,{BedrockClient:Svr,ListFoundationModelsCommand:wvr,BedrockRuntimeClient:Evr,ConverseCommand:_vr,ConverseStreamCommand:Cvr,ImageFormat:kvr}=ki,{SageMakerRuntimeClient:Rvr,InvokeEndpointCommand:Avr,InvokeEndpointWithResponseStreamCommand:Ivr}=ki,{GoogleAuth:Pvr,VertexAI:Ovr,TextToSpeechClient:Mvr}=ki,{Webhook:Nvr}=ki,{Hippocampus:Dvr,HippocampusConfig:Lvr}=ki,{createClient:CN}=ki,{Queue:Uvr,Worker:Fvr,Job:$vr,QueueScheduler:Bvr,FlowProducer:zvr}=ki,{Cron:jvr}=ki,{parseBuffer:Gvr,selectCover:Vvr}=ki,{extractRawText:Hvr,convertToHtml:qvr}=ki,{Hono:Wvr}=ki,{cors:Kvr,HTTPException:Jvr,logger:Xvr,secureHeaders:Yvr,streamSSE:Zvr,timeout:Qvr}=ki,ebr=globalThis.fetch,tbr=globalThis.Request,rbr=globalThis.Response,nbr=globalThis.Headers,obr=globalThis.FormData,sbr=globalThis.File,ibr=globalThis.Blob,abr=ki.Agent,cbr=ki.Pool,lbr=ki.Client,ubr=ki.Dispatcher,dbr=()=>{},pbr=()=>ki,mbr=ki.MockAgent,fbr={redirect:()=>r=>r,retry:()=>r=>r},gbr=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});var uVe={};J(uVe,{RedisTaskStore:()=>ble});function Aq(r){return`${Tle}task:${r}:runs`}function RN(r){return`${Tle}task:${r}:history`}var Tle,kN,ble,dVe=E(()=>{"use strict";Rq();q();kT();dt();Tle="neurolink:",kN=`${Tle}tasks`;ble=class{constructor(e){this.config=e;this.maxRunLogs=e.maxRunLogs??Wn.maxRunLogs,this.maxHistoryEntries=e.maxHistoryEntries??Wn.maxHistoryEntries,this.retentionConfig={...Wn.retention,...e.taskRetention}}config;type="redis";client=null;maxRunLogs;maxHistoryEntries;retentionConfig;async initialize(){let e=this.config.redis??{},t=e.url??`redis://${e.host??Wn.redis.host}:${e.port??Wn.redis.port}/${e.db??0}`;this.client=CN({url:t,...e.password?{password:e.password}:{}}),this.client.on("error",n=>{g.error("[TaskStore:Redis] Connection error",{error:String(n)})}),await this.client.connect(),g.info("[TaskStore:Redis] Connected")}async shutdown(){this.client?.isOpen&&(await this.client.quit(),g.info("[TaskStore:Redis] Disconnected")),this.client=null}async save(e){let t=this.getClient();await t.hSet(kN,e.id,JSON.stringify(e)),this.applyRetentionTTL(e,t)}async get(e){let n=await this.getClient().hGet(kN,e);return n?JSON.parse(String(n)):null}async list(e){let n=await this.getClient().hGetAll(kN),o=Object.values(n).map(s=>JSON.parse(String(s)));return e?.status&&(o=o.filter(s=>s.status===e.status)),o.sort((s,i)=>new Date(i.updatedAt).getTime()-new Date(s.updatedAt).getTime())}async update(e,t){let n=this.getClient(),o=await this.get(e);if(!o)throw Wr.create("TASK_NOT_FOUND",`Task not found: ${e}`);let s={...o,...t,id:o.id,updatedAt:new Date().toISOString()};return await n.hSet(kN,e,JSON.stringify(s)),this.applyRetentionTTL(s,n),s}async delete(e){let t=this.getClient();await Promise.all([t.hDel(kN,e),t.del(Aq(e)),t.del(RN(e))])}async appendRun(e,t){let n=this.getClient(),o=Aq(e);await n.lPush(o,JSON.stringify(t)),await n.lTrim(o,0,this.maxRunLogs-1)}async getRuns(e,t){let n=this.getClient(),o=t?.limit??20,s=Aq(e),i=t?.status?-1:o-1,c=(await n.lRange(s,0,i)).map(l=>JSON.parse(String(l)));return t?.status&&(c=c.filter(l=>l.status===t.status)),c.slice(0,o)}async appendHistory(e,t){let n=this.getClient(),o=RN(e),s=t.map(i=>JSON.stringify(i));s.length>0&&(await n.rPush(o,s),await n.lTrim(o,-this.maxHistoryEntries,-1))}async getHistory(e){let t=this.getClient(),n=RN(e);return(await t.lRange(n,0,-1)).map(s=>JSON.parse(String(s)))}async clearHistory(e){await this.getClient().del(RN(e))}ensureConnected(){if(!this.client?.isOpen)throw Wr.create("BACKEND_NOT_INITIALIZED","[TaskStore:Redis] Not connected. Call initialize() first.")}getClient(){if(this.ensureConnected(),!this.client)throw Wr.create("BACKEND_NOT_INITIALIZED","[TaskStore:Redis] Client is unavailable after initialization.");return this.client}applyRetentionTTL(e,t){let o={completed:this.retentionConfig.completedTTL,failed:this.retentionConfig.failedTTL,cancelled:this.retentionConfig.cancelledTTL}[e.status];if(!o||!t.isOpen)return;let s=Math.ceil(o/1e3);(async()=>{let i=Aq(e.id);for(let a=1;a<=3;a++)try{await t.expire(i,s);break}catch(c){a===3?g.warn("[TaskStore:Redis] expire failed after 3 attempts on task runs key \u2014 task data may outlive retention window",{taskId:e.id,key:i,ttlSeconds:s,err:String(c)}):await new Promise(l=>setTimeout(l,100*a))}})(),(async()=>{let i=RN(e.id);for(let a=1;a<=3;a++)try{await t.expire(i,s);break}catch(c){a===3?g.warn("[TaskStore:Redis] expire failed after 3 attempts on task history key \u2014 task data may outlive retention window",{taskId:e.id,key:i,ttlSeconds:s,err:String(c)}):await new Promise(l=>setTimeout(l,100*a))}})()}}});var pVe={};J(pVe,{FileTaskStore:()=>Sle});var Sle,mVe=E(()=>{"use strict";Os();uc();bo();q();kT();dt();Sle=class{type="file";storePath;logsPath;maxRunLogs;maxHistoryEntries;tasks=new Map;history=new Map;flushQueue=Promise.resolve();constructor(e){this.storePath=e.storePath??Wn.storePath,this.logsPath=e.logsPath??Wn.logsPath,this.maxRunLogs=e.maxRunLogs??Wn.maxRunLogs,this.maxHistoryEntries=e.maxHistoryEntries??Wn.maxHistoryEntries}async initialize(){if(Tp(Ic(this.storePath),{recursive:!0}),Tp(this.logsPath,{recursive:!0}),Ps(this.storePath))try{let e=Pa(this.storePath,"utf-8"),t=JSON.parse(e);for(let[n,o]of Object.entries(t.tasks))this.tasks.set(n,o);g.info("[TaskStore:File] Loaded tasks",{count:this.tasks.size})}catch(e){g.error("[TaskStore:File] Failed to load tasks file",{error:String(e)})}}async shutdown(){await this.flush(),this.tasks.clear(),this.history.clear()}async save(e){this.tasks.set(e.id,e),await this.flush()}async get(e){return this.tasks.get(e)??null}async list(e){let t=Array.from(this.tasks.values());return e?.status&&(t=t.filter(n=>n.status===e.status)),t.sort((n,o)=>new Date(o.updatedAt).getTime()-new Date(n.updatedAt).getTime())}async update(e,t){let n=this.tasks.get(e);if(!n)throw Wr.create("TASK_NOT_FOUND",`Task not found: ${e}`);let o={...n,...t,id:n.id,updatedAt:new Date().toISOString()};return this.tasks.set(e,o),await this.flush(),o}async delete(e){this.tasks.delete(e),this.history.delete(e);let t=dr(this.logsPath,`${e}.jsonl`);try{await am(t)}catch{}await this.flush()}async appendRun(e,t){let n=dr(this.logsPath,`${e}.jsonl`);Tp(Ic(n),{recursive:!0}),await EZ(n,JSON.stringify(t)+`
|
|
@@ -2103,7 +2103,7 @@ Do not say you cannot create a title. Always return a valid title.
|
|
|
2103
2103
|
|
|
2104
2104
|
User message: "${e}"`,o=process.env.NEUROLINK_TITLE_PROMPT,s=o?o.replace(/\$\{userMessage\}/g,e):n,i=await t.generate({input:{text:s},provider:this.config.summarizationProvider||"vertex",model:this.config.summarizationModel||"gemini-2.5-flash",disableTools:!0}),a=i.content?.trim()||"New Conversation";return a=a.replace(/^(Title:|Here's a title:|The title is:)\s*/i,""),a=a.replace(/['"]/g,""),a=a.replace(/\.$/,""),a.length<3&&(a="New Conversation"),g.info("[RedisConversationMemoryManager] Generated conversation title",{originalLength:i.content?.length||0,cleanedTitle:a,titleLength:a.length}),a}catch(t){return g.error("[RedisConversationMemoryManager] Failed to generate conversation title",{error:t instanceof Error?t.message:String(t),userMessagePreview:e.substring(0,100)}),e.length>30?e.substring(0,30)+"...":e||"New Conversation"}}createSummarySystemMessage(e,t,n){return{id:`summary-${je()}`,role:"system",content:`Summary of previous conversation turns:
|
|
2105
2105
|
|
|
2106
|
-
${e}`,timestamp:new Date().toISOString(),metadata:{isSummary:!0,summarizesFrom:t,summarizesTo:n}}}async getSessionMessages(e,t){if(await this.ensureInitialized(),!this.redisClient)return[];try{let n=Eu(this.redisConfig,e,t),o=await this.redisClient.get(n);return _u(o||null)?.messages??[]}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get session messages",{sessionId:e,userId:t,error:n instanceof Error?n.message:String(n)}),[]}}async setSessionMessages(e,t,n){if(await this.ensureInitialized(),!this.redisClient)throw new ac("Redis client not initialized","STORAGE_ERROR",{sessionId:e});try{let o=Eu(this.redisConfig,e,n),s=await this.redisClient.get(o),i=_u(s||null);if(!i)throw new ac(`Session ${e} not found`,"STORAGE_ERROR",{sessionId:e});i.messages=t,i.updatedAt=new Date().toISOString(),i.summarizedUpToMessageId=void 0,i.summarizedMessage=void 0,i.lastTokenCount=void 0,i.lastCountedAt=void 0;let a=FC(i);await this.redisClient.set(o,a),this.redisConfig.ttl>0&&await this.redisClient.expire(o,this.redisConfig.ttl),g.debug("[RedisConversationMemoryManager] Session messages replaced",{sessionId:e,userId:n,messageCount:t.length})}catch(o){throw o instanceof ac?o:new ac(`Failed to set session messages for session ${e}`,"STORAGE_ERROR",{sessionId:e,error:o instanceof Error?o.message:String(o)})}}async close(){this.redisClient&&(await WHe(this.redisConfig),this.redisClient=null,this.isInitialized=!1,g.info("Redis connection closed"))}async getStats(){if(await this.ensureInitialized(),!this.redisClient)return{totalSessions:0,totalTurns:0};let e=`${this.redisConfig.keyPrefix}*`,t=await x3(this.redisClient,e);g.debug("[RedisConversationMemoryManager] Got session keys with SCAN",{pattern:e,keyCount:t.length});let n=0;for(let o of t){let s=await this.redisClient.get(o),i=_u(s);i?.messages&&(n+=i.messages.length/2)}return{totalSessions:t.length,totalTurns:n}}async clearSession(e,t){if(await this.ensureInitialized(),!this.redisClient)return!1;let n=this.redisClient;return WN.startActiveSpan("neurolink.memory.clear",{kind:Zt.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async o=>{try{let s=Eu(this.redisConfig,e,t),i=await ke(n.del(s),ide);return Number(i)>0?(t&&await this.removeUserSession(t,e),o.setAttribute("session.deleted",!0),o.setStatus({code:he.OK}),g.info("Redis session cleared",{sessionId:e}),!0):(o.setAttribute("session.deleted",!1),o.setStatus({code:he.OK}),!1)}catch(s){throw o.setStatus({code:he.ERROR,message:s instanceof Error?s.message:String(s)}),o.recordException(s instanceof Error?s:new Error(String(s))),s}finally{o.end()}})}async clearAllSessions(){if(await this.ensureInitialized(),!this.redisClient)return;let e=`${this.redisConfig.keyPrefix}*`,t=`${this.redisConfig.userSessionsKeyPrefix}*`,n=await x3(this.redisClient,e),o=await x3(this.redisClient,t),s=[...n,...o];if(g.debug("[RedisConversationMemoryManager] Got all keys with SCAN for clearing",{conversationPattern:e,userSessionsPattern:t,conversationKeyCount:n.length,userSessionsKeyCount:o.length,totalKeyCount:s.length}),s.length>0){for(let a=0;a<s.length;a+=100){let c=s.slice(a,a+100);await this.redisClient.del(c),g.debug("[RedisConversationMemoryManager] Cleared batch of sessions and user mappings",{batchIndex:Math.floor(a/100)+1,batchSize:c.length,totalProcessed:a+c.length,totalKeys:s.length})}g.info("All Redis sessions and user session mappings cleared",{clearedCount:s.length,conversationSessions:n.length,userSessionMappings:o.length})}}async ensureInitialized(){g.debug("[RedisConversationMemoryManager] Ensuring initialization"),this.isInitialized?g.debug("[RedisConversationMemoryManager] Already initialized"):(g.debug("[RedisConversationMemoryManager] Not initialized, initializing now"),await this.initialize())}async getUserAllSessionsHistory(e){if(await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];let t=[];try{let n=await this.getUserSessions(e);if(n.length===0)return t;for(let o of n)try{let s=await this.getUserSessionMetadata(e,o);s?t.push(s):(g.debug("[RedisConversationMemoryManager] Empty or missing session metadata - removing from user history",{userId:e,sessionId:o}),await this.removeUserSession(e,o))}catch(s){g.error("[RedisConversationMemoryManager] Failed to get session metadata",{userId:e,sessionId:o,error:s instanceof Error?s.message:String(s)})}return t}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get user all sessions metadata",{userId:e,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),t}}cleanupStalePendingData(){let e=Date.now()-3e5,t=[];for(let[n,o]of this.pendingToolExecutions)o.timestamp<e&&t.push(n);t.length>0&&(g.debug("[RedisConversationMemoryManager] Cleaning up stale pending tool data",{stalePendingKeys:t.length,totalPendingKeys:this.pendingToolExecutions.size}),t.forEach(n=>this.pendingToolExecutions.delete(n)))}async flushPendingToolData(e,t,n){let o=`${t}:${n}`,s=this.pendingToolExecutions.get(o);if(!s){g.debug("[RedisConversationMemoryManager] No pending tool data to flush",{sessionId:t,userId:n,pendingKey:o});return}g.debug("[RedisConversationMemoryManager] Flushing pending tool data",{sessionId:t,userId:n,toolCallsCount:s.toolCalls.length,toolResultsCount:s.toolResults.length});try{let i=new Map;for(let a of s.toolCalls){let c=a.toolCallId??"",l=a.toolName??"";i.set(c,l);let u={id:je(),timestamp:a.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_call",content:"",tool:l,args:a.args||a.arguments||a.parameters||{},metadata:{...a.thoughtSignature?{thoughtSignature:String(a.thoughtSignature)}:{},...a.stepIndex!==null&&a.stepIndex!==void 0?{stepIndex:Number(a.stepIndex)}:{}}};e.messages.push(u)}for(let a of s.toolResults){let c=String(a.toolCallId||a.id||"unknown"),l=i.get(c)||String(a.toolName||"unknown"),u=a,m=("output"in u?"output":"result")==="output"?u.output:a.result,f;if(typeof m=="string")f=m;else if(m==null)f=String(m??"null");else try{f=JSON.stringify(m,null,2)}catch(C){f=`[Serialization failed: ${C instanceof Error?C.message:String(C)}]`}let{preview:h,truncated:y,originalSize:x}=sg(f,{maxBytes:this.config?.contextCompaction?.maxToolOutputBytes,maxLines:this.config?.contextCompaction?.maxToolOutputLines}),b;try{let C=m;if(C&&typeof C=="object"){let k=C._meta;if(k&&typeof k=="object"){let I=k[pq];typeof I=="string"&&(b=I)}}}catch{}let T={truncated:y,...y&&{toolOutputPreview:h},...y&&{originalSize:x},...b&&{artifactId:b},...a.stepIndex!==null&&a.stepIndex!==void 0?{stepIndex:Number(a.stepIndex)}:{}},w={success:!a.error,error:a.error?String(a.error):void 0},_={id:je(),timestamp:a.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_result",content:f,tool:l,result:w,metadata:T};e.messages.push(_)}g.debug("[RedisConversationMemoryManager] Successfully flushed pending tool data",{sessionId:t,userId:n,toolMessagesAdded:s.toolCalls.length+s.toolResults.length,totalMessages:e.messages.length})}finally{this.pendingToolExecutions.delete(o)}}async updateAgenticLoopReport(e,t,n){if(g.debug("[RedisConversationMemoryManager] Updating agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,reportType:n.reportType,reportStatus:n.reportStatus}),await this.ensureInitialized(),!this.redisClient){g.warn("[RedisConversationMemoryManager] Redis client not available for report update",{sessionId:e,userId:t});return}try{let o=Eu(this.redisConfig,e,t||void 0),s=await ke(this.redisClient.get(o),5e3);if(!s){g.warn("[RedisConversationMemoryManager] No conversation found for report update",{sessionId:e,userId:t});return}let i=_u(s);if(!i){g.warn("[RedisConversationMemoryManager] Failed to deserialize conversation for report update",{sessionId:e,userId:t});return}i.additionalMetadata||(i.additionalMetadata={}),i.additionalMetadata.agenticLoopReports||(i.additionalMetadata.agenticLoopReports=[]);let a=i.additionalMetadata.agenticLoopReports.findIndex(l=>l.reportId===n.reportId);a>=0?(i.additionalMetadata.agenticLoopReports[a]=n,g.debug("[RedisConversationMemoryManager] Updated existing agentic loop report",{sessionId:e,reportId:n.reportId})):(i.additionalMetadata.agenticLoopReports.push(n),g.debug("[RedisConversationMemoryManager] Added new agentic loop report",{sessionId:e,reportId:n.reportId})),i.updatedAt=new Date().toISOString();let c=FC(i);await ke(this.redisClient.set(o,c),5e3),this.redisConfig.ttl>0&&await ke(this.redisClient.expire(o,this.redisConfig.ttl),5e3),g.info("[RedisConversationMemoryManager] Successfully updated agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,reportStatus:n.reportStatus})}catch(o){throw g.error("[RedisConversationMemoryManager] Failed to update agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,error:o instanceof Error?o.message:String(o)}),new ac("Failed to update agentic loop report","STORAGE_ERROR",{sessionId:e,userId:t,reportId:n.reportId,error:o instanceof Error?o.message:String(o)})}}}});function ade(r,e="memory",t){if(g.debug("[conversationMemoryFactory] Creating conversation memory manager",{storageType:e,config:{enabled:r.enabled,maxSessions:r.maxSessions,enableSummarization:r.enableSummarization,summarizationProvider:r.summarizationProvider,summarizationModel:r.summarizationModel},hasRedisConfig:!!t}),e==="memory"||!e){g.debug("[conversationMemoryFactory] Creating in-memory conversation manager");let o=new dT(r);return g.debug("[conversationMemoryFactory] In-memory conversation manager created successfully",{managerType:o.constructor.name}),o}if(e==="redis"){g.debug("[conversationMemoryFactory] Creating Redis conversation manager",{host:t?.host||"localhost",port:t?.port||6379,keyPrefix:t?.keyPrefix||"neurolink:conversation:",ttl:t?.ttl||86400,hasConnectionOptions:!!t?.connectionOptions});let o=new v3(r,t);return g.debug("[conversationMemoryFactory] Redis conversation manager created successfully",{managerType:o.constructor.name,config:{maxSessions:r.maxSessions,maxTurnsPerSession:r.maxTurnsPerSession}}),o}g.warn(`[conversationMemoryFactory] Unknown storage type: ${e}, falling back to memory storage`);let n=new dT(r);return g.debug("[conversationMemoryFactory] Fallback memory manager created successfully",{managerType:n.constructor.name}),n}function XHe(){let r=process.env.STORAGE_TYPE;if(!r)return g.debug("[conversationMemoryFactory] No storage type configured, using default",{storageType:"memory",fromEnv:!1}),"memory";let e=r.trim().toLowerCase(),t=["memory","redis"];return t.includes(e)?(g.debug("[conversationMemoryFactory] Determined storage type",{storageType:e,fromEnv:!0,envValue:r,normalized:e!==r}),e):(g.warn(`[conversationMemoryFactory] Unrecognized storage type in environment: "${r}", falling back to "memory"`,{providedValue:r,normalizedValue:e,validValues:t,usingDefault:!0}),"memory")}function YHe(){g.debug("[conversationMemoryFactory] Reading Redis configuration from environment",{REDIS_URL:process.env.REDIS_URL?"******":"(not set)",REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",REDIS_CONNECT_TIMEOUT:process.env.REDIS_CONNECT_TIMEOUT||"(not set)",REDIS_MAX_RETRIES:process.env.REDIS_MAX_RETRIES||"(not set)",REDIS_RETRY_DELAY:process.env.REDIS_RETRY_DELAY||"(not set)"});let r={host:process.env.REDIS_HOST,port:process.env.REDIS_PORT?Number(process.env.REDIS_PORT):void 0,password:process.env.REDIS_PASSWORD,db:process.env.REDIS_DB?Number(process.env.REDIS_DB):void 0,keyPrefix:process.env.REDIS_KEY_PREFIX,ttl:process.env.REDIS_TTL?Number(process.env.REDIS_TTL):void 0,connectionOptions:{connectTimeout:process.env.REDIS_CONNECT_TIMEOUT?Number(process.env.REDIS_CONNECT_TIMEOUT):void 0,maxRetriesPerRequest:process.env.REDIS_MAX_RETRIES?Number(process.env.REDIS_MAX_RETRIES):void 0,retryDelayOnFailover:process.env.REDIS_RETRY_DELAY?Number(process.env.REDIS_RETRY_DELAY):void 0}};return process.env.REDIS_URL&&(g.debug("[conversationMemoryFactory] Using REDIS_URL for connection"),r.url=process.env.REDIS_URL),g.debug("[conversationMemoryFactory] Redis configuration normalized",{host:r.host||"localhost",port:r.port||6379,hasPassword:!!r.password,db:r.db||0,keyPrefix:r.keyPrefix||"neurolink:conversation:",ttl:r.ttl||86400,hasConnectionOptions:!!r.connectionOptions}),r}var ZHe=E(async()=>{"use strict";q();sae();await JHe()});var QHe={};J(QHe,{initializeConversationMemory:()=>qwr});async function qwr(r){if(g.debug("[conversationMemoryInitializer] Initialize conversation memory called",{hasConfig:!!r,hasMemoryConfig:!!r?.conversationMemory,memoryEnabled:r?.conversationMemory?.enabled||!1,storageType:process.env.STORAGE_TYPE||"memory"}),!r?.conversationMemory?.enabled)return g.debug("[conversationMemoryInitializer] Conversation memory not enabled - skipping initialization"),null;try{g.debug("[conversationMemoryInitializer] Applying conversation memory defaults");let e=VBe(r.conversationMemory);g.debug("[conversationMemoryInitializer] Memory configuration processed",{enabled:e.enabled,maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession,enableSummarization:e.enableSummarization});let t=!!r.conversationMemory?.redisConfig,n=t?"redis":XHe();if(g.debug("[conversationMemoryInitializer] Storage type determined",{storageType:n,fromConfig:t,fromEnv:!t&&!!process.env.STORAGE_TYPE}),n==="redis"){g.info("[conversationMemoryInitializer] Initializing Redis-based conversation memory manager"),g.debug("[conversationMemoryInitializer] Getting Redis configuration");let o=r.conversationMemory?.redisConfig||YHe(),s=r.conversationMemory?.redisConfig?"SDK input (from Lighthouse)":"environment variables (NeuroLink)";g.debug("[conversationMemoryInitializer] Redis configuration retrieved",{configSource:s,host:o.host||"localhost",port:o.port||6379,hasPassword:!!o.password,db:o.db||0,keyPrefix:o.keyPrefix||"neurolink:conversation:",ttl:o.ttl||86400}),g.debug("[conversationMemoryInitializer] Creating Redis conversation memory manager");let i=ade(e,"redis",o);return g.debug("[conversationMemoryInitializer] Checking Redis manager creation result",{managerType:i?.constructor?.name||"unknown",isRedisType:i?.constructor?.name==="RedisConversationMemoryManager",hasConfig:!!i?.config}),g.info("[conversationMemoryInitializer] Redis conversation memory manager created successfully"),i?.constructor?.name!=="RedisConversationMemoryManager"&&g.warn("[conversationMemoryInitializer] Created manager is not of RedisConversationMemoryManager type",{actualType:i?.constructor?.name}),i}else{g.info("[conversationMemoryInitializer] Initializing in-memory conversation memory manager"),g.debug("[conversationMemoryInitializer] Creating in-memory conversation memory manager");let o=ade(e);return g.debug("[conversationMemoryInitializer] Checking memory manager creation result",{managerType:o?.constructor?.name||"unknown",isInMemoryType:o?.constructor?.name==="ConversationMemoryManager",hasConfig:!!o?.config}),g.info("[conversationMemoryInitializer] In-memory conversation memory manager created successfully",{maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession,managerType:o?.constructor?.name}),o}}catch(e){throw g.error("[conversationMemoryInitializer] Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e),errorName:e instanceof Error?e.name:"UnknownError",errorStack:e instanceof Error?e.stack:void 0,storageType:process.env.STORAGE_TYPE||"memory",memoryConfig:{enabled:r?.conversationMemory?.enabled,maxSessions:r?.conversationMemory?.maxSessions,maxTurnsPerSession:r?.conversationMemory?.maxTurnsPerSession},redisConfig:{host:process.env.REDIS_HOST||"(not set)",port:process.env.REDIS_PORT||"(not set)",hasPassword:!!process.env.REDIS_PASSWORD,keyPrefix:process.env.REDIS_KEY_PREFIX||"(not set)"}}),process.env.STORAGE_TYPE==="redis"&&g.error("[conversationMemoryInitializer] Redis configuration error details",{REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",errorMessage:e instanceof Error?e.message:String(e)}),e}}var eqe=E(async()=>{"use strict";uT();q();await ZHe()});var tqe={};J(tqe,{AuthProviderFactory:()=>hs,createAuthProvider:()=>cde});async function cde(r,e){return hs.createProvider(r,e)}var hs,KN=E(()=>{"use strict";q();za();hs=class r{static providers=new Map;static aliasMap=new Map;static registerProvider(e,t,n=[],o){r.providers.set(e,{factory:t,aliases:n,metadata:o});for(let s of n)r.aliasMap.set(s.toLowerCase(),e);g.debug(`Registered auth provider: ${e}`)}static async createProvider(e,t){let n=r.resolveType(e),o=r.providers.get(n);if(!o)throw ot.create("PROVIDER_NOT_FOUND",`Auth provider not found: ${e}. Available: ${r.getAvailableProviders().join(", ")}`);try{return await o.factory(t)}catch(s){throw ot.create("CREATION_FAILED",`Failed to create auth provider ${e}: ${s instanceof Error?s.message:String(s)}`,{cause:s instanceof Error?s:void 0})}}static hasProvider(e){return r.providers.has(e)||r.aliasMap.has(e.toLowerCase())}static getAvailableProviders(){return Array.from(r.providers.keys())}static getProviderMetadata(e){let t=r.resolveType(e);return r.providers.get(t)?.metadata}static getAllProviderInfo(){return Array.from(r.providers.entries()).map(([e,t])=>({type:e,aliases:t.aliases,metadata:t.metadata}))}static clearRegistrations(){r.providers.clear(),r.aliasMap.clear()}static resolveType(e){return r.aliasMap.get(e.toLowerCase())||e}}});var tae={};J(tae,{NEUROLINK_BRAND:()=>ude,NeuroLink:()=>NT,STREAM_DEDUP_CONTEXT_KEY:()=>Jwr,default:()=>Ywr,isNeuroLink:()=>Cu,markStreamProviderEmittedGenerationEnd:()=>Xwr,neurolink:()=>rqe});function Wwr(r){let e=r.toLowerCase();return e.includes("not found")||e.includes("404")||e.includes("does not exist")||e.includes("no such")?"not_found":e.includes("permission")||e.includes("forbidden")||e.includes("403")||e.includes("unauthorized")||e.includes("401")||e.includes("access denied")?"permission_denied":e.includes("timeout")||e.includes("timed out")||e.includes("deadline exceeded")?"timeout":e.includes("rate limit")||e.includes("429")||e.includes("too many requests")||e.includes("throttl")?"rate_limited":e.includes("invalid")||e.includes("validation")||e.includes("bad request")||e.includes("400")?"validation_error":"unknown"}function Kwr(r){switch(r){case"not_found":return"validation";case"permission_denied":return"permission";case"timeout":return"timeout";case"rate_limited":return"resource";case"validation_error":return"validation";case"unknown":return"execution"}}function Xwr(r){let e=r?._streamDedupContext;e&&(e.providerEmitted=!0)}function Cu(r){return typeof r=="object"&&r!==null&&r[ude]===!0}var lde,b3,T3,Jwr,ude,NT,rqe,Ywr,Cp=E(async()=>{"use strict";fr();_O();ws();UO();M_e();RBe();KBe();um();JBe();QBe();eze();tze();ea();sae();pae();mae();ou();cz();jw();fze();hze();gae();xae();Tae();SH();ele();rle();EGe();ole();RGe();G0();dq();MGe();DGe();FGe();Q$();dt();sI();og();fVe();hVe();vI();br();uT();lt();F2();nZ();yVe();QQ();_Ve();q();CO();sq();CVe();UVe();Ag();Xd();Rle();Jh();kb();Dle();$q();zle();$le();try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";let{config:r}=await Promise.resolve().then(()=>go(P4e(),1));r({quiet:!0})}catch{}lde=Bq,b3=T4e,T3=new Pb,Jwr="_streamDedupContext";ude=Symbol.for("@juspay/neurolink/sdk-brand");NT=class r{[ude]=!0;mcpInitialized=!1;mcpSkipped=!1;mcpInitPromise=null;emitter=new Ur;_taskManager;_taskManagerConfig;toolRegistry;autoDiscoveredServerInfos=[];externalServerManager;toolCache=null;toolCacheDuration;modelAliasConfig;lastCompactionMessageCount=new Map;getCompactionSessionId(e){return e.context?.sessionId||"__default__"}mcpToolResultCache;mcpToolRouter;mcpToolBatcher;mcpEnhancedDiscovery;mcpToolMiddlewares=[];mcpArtifactStore;_disableToolCacheForCurrentRequest=!1;mcpEnhancementsConfig;toolCircuitBreakers=new Map;toolExecutionMetrics=new Map;currentStreamToolExecutions=[];toolExecutionHistory=[];activeToolExecutions=new Map;emitToolEndEvent(e,t,n,o,s){this.emitter.emit("tool:end",Nf(e,{responseTime:Date.now()-t,success:n,timestamp:Date.now(),result:o,error:s?s.message:void 0}))}conversationMemory;conversationMemoryNeedsInit=!1;conversationMemoryConfig;toolRoutingConfig;toolRoutingCacheInstance;toolRoutingVectorCache;toolDedupConfig;enableOrchestration;authProvider;pendingAuthConfig;authInitPromise;credentials;fallbackConfig={};modelPool;requestRouter;resolveCredentials(e){if(!this.credentials&&!e)return;if(!this.credentials)return e;if(!e)return this.credentials;let t={...this.credentials};for(let n of Object.keys(e)){let o=this.credentials[n],s=e[n];o&&s&&typeof o=="object"&&typeof s=="object"?t[n]={...o,...s}:t[n]=s??o}return t}hitlManager;_sessionCostUsd=0;fileRegistry;cachedFileTools=null;memoryInstance;memorySDKConfig;async setLangfuseContextFromOptions(e,t){if(e.context&&typeof e.context=="object"&&e.context!==null){let n=!1;try{let o=e.context;if(o.userId||o.sessionId||o.conversationId||o.requestId||o.traceName||o.metadata){let s;if(o.metadata&&typeof o.metadata=="object"){let i=o.metadata,a={};for(let[c,l]of Object.entries(i))(typeof l=="string"||typeof l=="number"||typeof l=="boolean")&&(a[c]=l);Object.keys(a).length>0&&(s=a)}return await new Promise((i,a)=>{By({userId:typeof o.userId=="string"?o.userId:null,sessionId:typeof o.sessionId=="string"?o.sessionId:null,conversationId:typeof o.conversationId=="string"?o.conversationId:null,requestId:typeof o.requestId=="string"?o.requestId:null,traceName:typeof o.traceName=="string"?o.traceName:null,metadata:o.metadata&&typeof o.metadata=="object"?o.metadata:null,...s!==void 0&&{customAttributes:s}},async()=>{try{n=!0;let c=await t();i(c)}catch(c){a(c)}})})}}catch(o){if(n)throw o;g.warn("Failed to set Langfuse context from options",{error:o instanceof Error?o.message:String(o)})}}return await t()}createMetricsTraceContext(){let e=rt.getSpan(Wt.active());if(e){let t=e.spanContext();if(t.traceId&&t.traceId!=="00000000000000000000000000000000")return{traceId:t.traceId,parentSpanId:t.spanId}}return{traceId:crypto.randomUUID().replace(/-/g,""),parentSpanId:crypto.randomUUID().replace(/-/g,"").substring(0,16)}}enforceSessionBudget(e){if(!(e===void 0||e<=0||this._sessionCostUsd<e))throw new be({code:"SESSION_BUDGET_EXCEEDED",message:`Session budget exceeded: spent $${this._sessionCostUsd.toFixed(4)} of $${e.toFixed(4)} limit`,category:"validation",severity:"high",retriable:!1,context:{spent:this._sessionCostUsd,limit:e}})}assertInputText(e,t){if(!e||typeof e!="string")throw new Error(t)}async applyAuthenticatedRequestContext(e){if(e.auth?.token){let{AuthError:n}=await Promise.resolve().then(()=>(za(),xGe));if(await this.ensureAuthProvider(),!this.authProvider)throw n.create("PROVIDER_ERROR","No auth provider configured. Set auth in constructor or via setAuthProvider() before using auth: { token }.");let o;try{o=await ke(this.authProvider.authenticateToken(e.auth.token),5e3,n.create("PROVIDER_ERROR","Auth token validation timed out after 5000ms"))}catch(s){throw s instanceof Error&&"feature"in s&&s.feature==="Auth"?s:n.create("PROVIDER_ERROR",`Auth token validation failed: ${s instanceof Error?s.message:String(s)}`)}if(!o.valid)throw n.create("INVALID_TOKEN",o.error||"Token validation failed");if(!o.user)throw n.create("INVALID_TOKEN","Token validated but no user identity returned");if(!o.user.id)throw n.create("INVALID_TOKEN","Token validated but user identity missing required 'id' field");e.context={...e.context||{},userId:o.user.id,userEmail:o.user.email,userRoles:o.user.roles}}if(!e.requestContext)return;let t=e.auth?.token&&this.authProvider?{userId:e.context?.userId,userEmail:e.context?.userEmail,userRoles:e.context?.userRoles}:{};e.context={...e.context||{},...e.requestContext,...t}}applyGenerateLifecycleMiddleware(e){!e.onFinish&&!e.onError||(e.middleware={...e.middleware,middlewareConfig:{...e.middleware?.middlewareConfig,lifecycle:{...e.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...e.middleware?.middlewareConfig?.lifecycle?.config,...e.onFinish!==void 0?{onFinish:e.onFinish}:{},...e.onError!==void 0?{onError:e.onError}:{}}}}})}applyStreamLifecycleMiddleware(e){!e.onFinish&&!e.onError&&!e.onChunk||(e.middleware={...e.middleware,middlewareConfig:{...e.middleware?.middlewareConfig,lifecycle:{...e.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...e.middleware?.middlewareConfig?.lifecycle?.config,...e.onFinish!==void 0?{onFinish:e.onFinish}:{},...e.onError!==void 0?{onError:e.onError}:{},...e.onChunk!==void 0?{onChunk:e.onChunk}:{}}}}})}initializeMemoryConfig(){let e=this.conversationMemoryConfig?.conversationMemory?.memory;return e?.enabled?(this.memorySDKConfig=e,!0):!1}ensureMemoryReady(){return this.memoryInstance!==void 0?this.memoryInstance:this.initializeMemoryConfig()?this.memorySDKConfig?(this.memoryInstance=NGe(this.memorySDKConfig),this.memoryInstance):(this.memoryInstance=null,null):(this.memoryInstance=null,null)}toolExecutionContext;observabilityConfig;metricsAggregator=new _v;get _metricsTraceContext(){return T3.getStore()??null}constructor(e){this.toolRegistry=e?.toolRegistry||new CT,this.fileRegistry=new yH,this.observabilityConfig=e?.observability,this.enableOrchestration=e?.enableOrchestration??!1,e?.modelAliasConfig&&(this.modelAliasConfig=e.modelAliasConfig),e?.providerFallback&&(this.fallbackConfig.providerFallback=e.providerFallback),e?.modelChain&&(this.fallbackConfig.modelChain=e.modelChain),e?.toolRouting&&(this.toolRoutingConfig={...e.toolRouting}),e?.toolDedup&&(this.toolDedupConfig={...e.toolDedup}),this.modelPool=e?.modelPool?new EC(e.modelPool):null,this.requestRouter=e?.requestRouter??null,g.setEventEmitter(this.emitter);let t=process.env.NEUROLINK_TOOL_CACHE_DURATION;this.toolCacheDuration=t?parseInt(t,10):2e4;let n=Date.now(),o=process.hrtime.bigint(),s=`neurolink-constructor-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.initializeProviderRegistry(s,n,o),this.initializeConversationMemory(e,s,n,o),this.initializeExternalServerManager(s,n,o),this.initializeHITL(e,s,n,o),this.initializeMCPEnhancements(e),this.registerFileTools(),this.registerMemoryRetrievalTools(),this.initializeLangfuse(s,n,o),this.initializeMetricsListeners(),this.logConstructorComplete(s,n,o),e?.auth&&(this.pendingAuthConfig=e.auth),e?.credentials&&(this.credentials=e.credentials),this._taskManagerConfig=e?.tasks,this._taskManagerConfig&&(this._taskManager=new AN(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerTaskTools(this._taskManager))}get tasks(){return this._taskManager||(this._taskManager=new AN(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerTaskTools(this._taskManager)),this._taskManager}initializeProviderRegistry(e,t,n){let o=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3D7}\uFE0F LOG_POINT_C002_PROVIDER_REGISTRY_SETUP_START",{logPoint:"C002_PROVIDER_REGISTRY_SETUP_START",constructorId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),registrySetupStartTimeNs:o.toString(),message:"Starting ProviderRegistry configuration for security"}),al.setOptions({enableManualMCP:!1})}initializeConversationMemory(e,t,n,o){if(e?.conversationMemory?.enabled){let s=process.hrtime.bigint();this.conversationMemoryConfig=e,this.conversationMemoryNeedsInit=!0;let a=process.hrtime.bigint()-s;g.debug("[NeuroLink] \u2705 LOG_POINT_C006_MEMORY_INIT_FLAG_SET_SUCCESS",{logPoint:"C006_MEMORY_INIT_FLAG_SET_SUCCESS",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),memoryInitDurationNs:a.toString(),memoryInitDurationMs:Number(a)/Wd,message:"Conversation memory initialization flag set successfully for lazy loading"})}else g.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C008_MEMORY_DISABLED",{logPoint:"C008_MEMORY_DISABLED",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!e,hasMemoryConfig:!!e?.conversationMemory,memoryEnabled:e?.conversationMemory?.enabled||!1,reason:e?e.conversationMemory?e.conversationMemory.enabled?"UNKNOWN":"MEMORY_DISABLED":"NO_MEMORY_CONFIG":"NO_CONFIG",message:"Conversation memory not enabled - skipping initialization"})}initializeHITL(e,t,n,o){if(e?.hitl?.enabled){let s=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E1}\uFE0F LOG_POINT_C015_HITL_INIT_START",{logPoint:"C015_HITL_INIT_START",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitStartTimeNs:s.toString(),hitlConfig:{enabled:e.hitl.enabled,dangerousActions:e.hitl.dangerousActions||[],timeout:e.hitl.timeout||3e4,allowArgumentModification:e.hitl.allowArgumentModification??!0,auditLogging:e.hitl.auditLogging??!1},message:"Starting HITL (Human-in-the-Loop) initialization"});try{this.hitlManager=new BM(e.hitl),this.toolRegistry.setHITLManager(this.hitlManager),this.externalServerManager.setHITLManager(this.hitlManager),this.setupHITLEventForwarding();let a=process.hrtime.bigint()-s;g.debug("[NeuroLink] \u2705 LOG_POINT_C016_HITL_INIT_SUCCESS",{logPoint:"C016_HITL_INIT_SUCCESS",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:a.toString(),hitlInitDurationMs:Number(a)/Wd,hasHitlManager:!!this.hitlManager,message:"HITL (Human-in-the-Loop) initialized successfully"}),g.info("[NeuroLink] HITL safety features enabled",{dangerousActions:e.hitl.dangerousActions?.length||0,timeout:e.hitl.timeout||3e4,allowArgumentModification:e.hitl.allowArgumentModification??!0,auditLogging:e.hitl.auditLogging??!1})}catch(i){let c=process.hrtime.bigint()-s;throw g.error("[NeuroLink] \u274C LOG_POINT_C017_HITL_INIT_ERROR",{logPoint:"C017_HITL_INIT_ERROR",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:c.toString(),hitlInitDurationMs:Number(c)/Wd,error:i instanceof Error?i.message:String(i),errorName:i instanceof Error?i.name:"UnknownError",errorStack:i instanceof Error?i.stack:void 0,message:"HITL (Human-in-the-Loop) initialization failed"}),i}}else g.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C018_HITL_DISABLED",{logPoint:"C018_HITL_DISABLED",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!e,hasHitlConfig:!!e?.hitl,hitlEnabled:e?.hitl?.enabled||!1,reason:e?e.hitl?e.hitl.enabled?"UNKNOWN":"HITL_DISABLED":"NO_HITL_CONFIG":"NO_CONFIG",message:"HITL (Human-in-the-Loop) not enabled - skipping initialization"})}initializeMCPEnhancements(e){let t=e?.mcp;if(this.mcpEnhancementsConfig=t,t?.cache?.enabled!==!1&&(this.mcpToolResultCache=new sx({ttl:t?.cache?.ttl??3e5,maxSize:t?.cache?.maxSize??500,strategy:t?.cache?.strategy??"lru"}),g.debug("[NeuroLink] MCP tool result cache initialized",{ttl:t?.cache?.ttl??3e5,maxSize:t?.cache?.maxSize??500,strategy:t?.cache?.strategy??"lru"})),t?.batcher?.enabled&&(this.mcpToolBatcher=new ox({maxBatchSize:t.batcher.maxBatchSize??10,maxWaitMs:t.batcher.maxWaitMs??100}),this.mcpToolBatcher.setToolExecutor(async(n,o)=>this.executeToolInternal(n,o,{timeout:zu.EXECUTION_DEFAULT_MS,maxRetries:Oo.DEFAULT,retryDelayMs:Mn.BASE_MS})),g.debug("[NeuroLink] MCP tool call batcher initialized")),t?.discovery?.enabled!==!1&&(this.mcpEnhancedDiscovery=new fT,g.debug("[NeuroLink] Enhanced tool discovery initialized")),t?.middleware?.length&&(this.mcpToolMiddlewares=[...t.middleware],g.debug("[NeuroLink] MCP tool middlewares registered",{count:this.mcpToolMiddlewares.length})),t?.outputLimits){let n=t.outputLimits.strategy??"externalize",o=t.outputLimits.maxBytes??TGe,s=t.outputLimits.warnBytes??tle,i;n==="externalize"&&(i=new fq,this.mcpArtifactStore=i,g.debug("[NeuroLink] MCP artifact store initialized (local-temp)"));let a=new mq({strategy:n,maxBytes:o,warnBytes:s},i);this.externalServerManager.setOutputNormalizer(a),g.debug("[NeuroLink] MCP output normalizer initialized",{strategy:n,maxBytes:o,warnBytes:s})}}registerFileTools(){let e=fae(this.fileRegistry),t=Object.entries(e).map(async([n,o])=>{let s=`direct.${n}`,i={name:n,description:o.description||`File tool: ${n}`,inputSchema:{},serverId:"direct",category:"built-in"};await this.toolRegistry.registerTool(s,i,{execute:async a=>{try{return{success:!0,data:await o.execute(a,{toolCallId:"file-tool",messages:[]}),metadata:{toolName:n,serverId:"direct",executionTime:0}}}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}})});Promise.all(t).then(()=>{g.debug(`[NeuroLink] Registered ${Object.keys(e).length} file reference tools`)})}registerTaskTools(e){let t=gVe(e);for(let[n,o]of Object.entries(t)){let s=`direct.${n}`,i={name:n,description:o.description||`Task tool: ${n}`,inputSchema:{},serverId:"direct",category:"built-in"};this.toolRegistry.registerTool(s,i,{execute:async a=>{try{return{success:!0,data:await o.execute(a,{toolCallId:"task-tool",messages:[]}),metadata:{toolName:n,serverId:"direct",executionTime:0}}}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}})}g.debug(`[NeuroLink] Registered ${Object.keys(t).length} task tools`)}registerMemoryRetrievalTools(){let e=this.conversationMemoryConfig?.conversationMemory,t=!!e?.redisConfig||e&&"redis"in e&&!!e.redis||process.env.STORAGE_TYPE==="redis",n=!!this.mcpArtifactStore;if((!e?.enabled||!t)&&!n){g.debug("[NeuroLink] Skipping memory retrieval tools \u2014 requires Redis conversation memory or an artifact store");return}let s=mle(void 0,this.mcpArtifactStore).retrieve_context;this.registerTool("retrieve_context",{name:"retrieve_context",description:s.description??"Retrieve context or artifacts",inputSchema:s.inputSchema,execute:async i=>{let a=this.conversationMemory,c=mle(a,this.mcpArtifactStore);return await ke(c.retrieve_context.execute(i,{toolCallId:"memory-retrieval",messages:[]}),zu.EXECUTION_DEFAULT_MS,ae.toolTimeout("retrieve_context",zu.EXECUTION_DEFAULT_MS))}}),g.info("[NeuroLink] Memory retrieval tools registered")}formatMemoryContext(e,t){return`Context from previous conversations:
|
|
2106
|
+
${e}`,timestamp:new Date().toISOString(),metadata:{isSummary:!0,summarizesFrom:t,summarizesTo:n}}}async getSessionMessages(e,t){if(await this.ensureInitialized(),!this.redisClient)return[];try{let n=Eu(this.redisConfig,e,t),o=await this.redisClient.get(n);return _u(o||null)?.messages??[]}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get session messages",{sessionId:e,userId:t,error:n instanceof Error?n.message:String(n)}),[]}}async setSessionMessages(e,t,n){if(await this.ensureInitialized(),!this.redisClient)throw new ac("Redis client not initialized","STORAGE_ERROR",{sessionId:e});try{let o=Eu(this.redisConfig,e,n),s=await this.redisClient.get(o),i=_u(s||null);if(!i)throw new ac(`Session ${e} not found`,"STORAGE_ERROR",{sessionId:e});i.messages=t,i.updatedAt=new Date().toISOString(),i.summarizedUpToMessageId=void 0,i.summarizedMessage=void 0,i.lastTokenCount=void 0,i.lastCountedAt=void 0;let a=FC(i);await this.redisClient.set(o,a),this.redisConfig.ttl>0&&await this.redisClient.expire(o,this.redisConfig.ttl),g.debug("[RedisConversationMemoryManager] Session messages replaced",{sessionId:e,userId:n,messageCount:t.length})}catch(o){throw o instanceof ac?o:new ac(`Failed to set session messages for session ${e}`,"STORAGE_ERROR",{sessionId:e,error:o instanceof Error?o.message:String(o)})}}async close(){this.redisClient&&(await WHe(this.redisConfig),this.redisClient=null,this.isInitialized=!1,g.info("Redis connection closed"))}async getStats(){if(await this.ensureInitialized(),!this.redisClient)return{totalSessions:0,totalTurns:0};let e=`${this.redisConfig.keyPrefix}*`,t=await x3(this.redisClient,e);g.debug("[RedisConversationMemoryManager] Got session keys with SCAN",{pattern:e,keyCount:t.length});let n=0;for(let o of t){let s=await this.redisClient.get(o),i=_u(s);i?.messages&&(n+=i.messages.length/2)}return{totalSessions:t.length,totalTurns:n}}async clearSession(e,t){if(await this.ensureInitialized(),!this.redisClient)return!1;let n=this.redisClient;return WN.startActiveSpan("neurolink.memory.clear",{kind:Zt.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async o=>{try{let s=Eu(this.redisConfig,e,t),i=await ke(n.del(s),ide);return Number(i)>0?(t&&await this.removeUserSession(t,e),o.setAttribute("session.deleted",!0),o.setStatus({code:he.OK}),g.info("Redis session cleared",{sessionId:e}),!0):(o.setAttribute("session.deleted",!1),o.setStatus({code:he.OK}),!1)}catch(s){throw o.setStatus({code:he.ERROR,message:s instanceof Error?s.message:String(s)}),o.recordException(s instanceof Error?s:new Error(String(s))),s}finally{o.end()}})}async clearAllSessions(){if(await this.ensureInitialized(),!this.redisClient)return;let e=`${this.redisConfig.keyPrefix}*`,t=`${this.redisConfig.userSessionsKeyPrefix}*`,n=await x3(this.redisClient,e),o=await x3(this.redisClient,t),s=[...n,...o];if(g.debug("[RedisConversationMemoryManager] Got all keys with SCAN for clearing",{conversationPattern:e,userSessionsPattern:t,conversationKeyCount:n.length,userSessionsKeyCount:o.length,totalKeyCount:s.length}),s.length>0){for(let a=0;a<s.length;a+=100){let c=s.slice(a,a+100);await this.redisClient.del(c),g.debug("[RedisConversationMemoryManager] Cleared batch of sessions and user mappings",{batchIndex:Math.floor(a/100)+1,batchSize:c.length,totalProcessed:a+c.length,totalKeys:s.length})}g.info("All Redis sessions and user session mappings cleared",{clearedCount:s.length,conversationSessions:n.length,userSessionMappings:o.length})}}async ensureInitialized(){g.debug("[RedisConversationMemoryManager] Ensuring initialization"),this.isInitialized?g.debug("[RedisConversationMemoryManager] Already initialized"):(g.debug("[RedisConversationMemoryManager] Not initialized, initializing now"),await this.initialize())}async getUserAllSessionsHistory(e){if(await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];let t=[];try{let n=await this.getUserSessions(e);if(n.length===0)return t;for(let o of n)try{let s=await this.getUserSessionMetadata(e,o);s?t.push(s):(g.debug("[RedisConversationMemoryManager] Empty or missing session metadata - removing from user history",{userId:e,sessionId:o}),await this.removeUserSession(e,o))}catch(s){g.error("[RedisConversationMemoryManager] Failed to get session metadata",{userId:e,sessionId:o,error:s instanceof Error?s.message:String(s)})}return t}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get user all sessions metadata",{userId:e,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),t}}cleanupStalePendingData(){let e=Date.now()-3e5,t=[];for(let[n,o]of this.pendingToolExecutions)o.timestamp<e&&t.push(n);t.length>0&&(g.debug("[RedisConversationMemoryManager] Cleaning up stale pending tool data",{stalePendingKeys:t.length,totalPendingKeys:this.pendingToolExecutions.size}),t.forEach(n=>this.pendingToolExecutions.delete(n)))}async flushPendingToolData(e,t,n){let o=`${t}:${n}`,s=this.pendingToolExecutions.get(o);if(!s){g.debug("[RedisConversationMemoryManager] No pending tool data to flush",{sessionId:t,userId:n,pendingKey:o});return}g.debug("[RedisConversationMemoryManager] Flushing pending tool data",{sessionId:t,userId:n,toolCallsCount:s.toolCalls.length,toolResultsCount:s.toolResults.length});try{let i=new Map;for(let a of s.toolCalls){let c=a.toolCallId??"",l=a.toolName??"";i.set(c,l);let u={id:je(),timestamp:a.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_call",content:"",tool:l,args:a.args||a.arguments||a.parameters||{},metadata:{...a.thoughtSignature?{thoughtSignature:String(a.thoughtSignature)}:{},...a.stepIndex!==null&&a.stepIndex!==void 0?{stepIndex:Number(a.stepIndex)}:{}}};e.messages.push(u)}for(let a of s.toolResults){let c=String(a.toolCallId||a.id||"unknown"),l=i.get(c)||String(a.toolName||"unknown"),u=a,m=("output"in u?"output":"result")==="output"?u.output:a.result,f;if(typeof m=="string")f=m;else if(m==null)f=String(m??"null");else try{f=JSON.stringify(m,null,2)}catch(C){f=`[Serialization failed: ${C instanceof Error?C.message:String(C)}]`}let{preview:h,truncated:y,originalSize:x}=sg(f,{maxBytes:this.config?.contextCompaction?.maxToolOutputBytes,maxLines:this.config?.contextCompaction?.maxToolOutputLines}),b;try{let C=m;if(C&&typeof C=="object"){let k=C._meta;if(k&&typeof k=="object"){let I=k[pq];typeof I=="string"&&(b=I)}}}catch{}let T={truncated:y,...y&&{toolOutputPreview:h},...y&&{originalSize:x},...b&&{artifactId:b},...a.stepIndex!==null&&a.stepIndex!==void 0?{stepIndex:Number(a.stepIndex)}:{}},w={success:!a.error,error:a.error?String(a.error):void 0},_={id:je(),timestamp:a.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_result",content:f,tool:l,result:w,metadata:T};e.messages.push(_)}g.debug("[RedisConversationMemoryManager] Successfully flushed pending tool data",{sessionId:t,userId:n,toolMessagesAdded:s.toolCalls.length+s.toolResults.length,totalMessages:e.messages.length})}finally{this.pendingToolExecutions.delete(o)}}async updateAgenticLoopReport(e,t,n){if(g.debug("[RedisConversationMemoryManager] Updating agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,reportType:n.reportType,reportStatus:n.reportStatus}),await this.ensureInitialized(),!this.redisClient){g.warn("[RedisConversationMemoryManager] Redis client not available for report update",{sessionId:e,userId:t});return}try{let o=Eu(this.redisConfig,e,t||void 0),s=await ke(this.redisClient.get(o),5e3);if(!s){g.warn("[RedisConversationMemoryManager] No conversation found for report update",{sessionId:e,userId:t});return}let i=_u(s);if(!i){g.warn("[RedisConversationMemoryManager] Failed to deserialize conversation for report update",{sessionId:e,userId:t});return}i.additionalMetadata||(i.additionalMetadata={}),i.additionalMetadata.agenticLoopReports||(i.additionalMetadata.agenticLoopReports=[]);let a=i.additionalMetadata.agenticLoopReports.findIndex(l=>l.reportId===n.reportId);a>=0?(i.additionalMetadata.agenticLoopReports[a]=n,g.debug("[RedisConversationMemoryManager] Updated existing agentic loop report",{sessionId:e,reportId:n.reportId})):(i.additionalMetadata.agenticLoopReports.push(n),g.debug("[RedisConversationMemoryManager] Added new agentic loop report",{sessionId:e,reportId:n.reportId})),i.updatedAt=new Date().toISOString();let c=FC(i);await ke(this.redisClient.set(o,c),5e3),this.redisConfig.ttl>0&&await ke(this.redisClient.expire(o,this.redisConfig.ttl),5e3),g.info("[RedisConversationMemoryManager] Successfully updated agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,reportStatus:n.reportStatus})}catch(o){throw g.error("[RedisConversationMemoryManager] Failed to update agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,error:o instanceof Error?o.message:String(o)}),new ac("Failed to update agentic loop report","STORAGE_ERROR",{sessionId:e,userId:t,reportId:n.reportId,error:o instanceof Error?o.message:String(o)})}}}});function ade(r,e="memory",t){if(g.debug("[conversationMemoryFactory] Creating conversation memory manager",{storageType:e,config:{enabled:r.enabled,maxSessions:r.maxSessions,enableSummarization:r.enableSummarization,summarizationProvider:r.summarizationProvider,summarizationModel:r.summarizationModel},hasRedisConfig:!!t}),e==="memory"||!e){g.debug("[conversationMemoryFactory] Creating in-memory conversation manager");let o=new dT(r);return g.debug("[conversationMemoryFactory] In-memory conversation manager created successfully",{managerType:o.constructor.name}),o}if(e==="redis"){g.debug("[conversationMemoryFactory] Creating Redis conversation manager",{host:t?.host||"localhost",port:t?.port||6379,keyPrefix:t?.keyPrefix||"neurolink:conversation:",ttl:t?.ttl||86400,hasConnectionOptions:!!t?.connectionOptions});let o=new v3(r,t);return g.debug("[conversationMemoryFactory] Redis conversation manager created successfully",{managerType:o.constructor.name,config:{maxSessions:r.maxSessions,maxTurnsPerSession:r.maxTurnsPerSession}}),o}g.warn(`[conversationMemoryFactory] Unknown storage type: ${e}, falling back to memory storage`);let n=new dT(r);return g.debug("[conversationMemoryFactory] Fallback memory manager created successfully",{managerType:n.constructor.name}),n}function XHe(){let r=process.env.STORAGE_TYPE;if(!r)return g.debug("[conversationMemoryFactory] No storage type configured, using default",{storageType:"memory",fromEnv:!1}),"memory";let e=r.trim().toLowerCase(),t=["memory","redis"];return t.includes(e)?(g.debug("[conversationMemoryFactory] Determined storage type",{storageType:e,fromEnv:!0,envValue:r,normalized:e!==r}),e):(g.warn(`[conversationMemoryFactory] Unrecognized storage type in environment: "${r}", falling back to "memory"`,{providedValue:r,normalizedValue:e,validValues:t,usingDefault:!0}),"memory")}function YHe(){g.debug("[conversationMemoryFactory] Reading Redis configuration from environment",{REDIS_URL:process.env.REDIS_URL?"******":"(not set)",REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",REDIS_CONNECT_TIMEOUT:process.env.REDIS_CONNECT_TIMEOUT||"(not set)",REDIS_MAX_RETRIES:process.env.REDIS_MAX_RETRIES||"(not set)",REDIS_RETRY_DELAY:process.env.REDIS_RETRY_DELAY||"(not set)"});let r={host:process.env.REDIS_HOST,port:process.env.REDIS_PORT?Number(process.env.REDIS_PORT):void 0,password:process.env.REDIS_PASSWORD,db:process.env.REDIS_DB?Number(process.env.REDIS_DB):void 0,keyPrefix:process.env.REDIS_KEY_PREFIX,ttl:process.env.REDIS_TTL?Number(process.env.REDIS_TTL):void 0,connectionOptions:{connectTimeout:process.env.REDIS_CONNECT_TIMEOUT?Number(process.env.REDIS_CONNECT_TIMEOUT):void 0,maxRetriesPerRequest:process.env.REDIS_MAX_RETRIES?Number(process.env.REDIS_MAX_RETRIES):void 0,retryDelayOnFailover:process.env.REDIS_RETRY_DELAY?Number(process.env.REDIS_RETRY_DELAY):void 0}};return process.env.REDIS_URL&&(g.debug("[conversationMemoryFactory] Using REDIS_URL for connection"),r.url=process.env.REDIS_URL),g.debug("[conversationMemoryFactory] Redis configuration normalized",{host:r.host||"localhost",port:r.port||6379,hasPassword:!!r.password,db:r.db||0,keyPrefix:r.keyPrefix||"neurolink:conversation:",ttl:r.ttl||86400,hasConnectionOptions:!!r.connectionOptions}),r}var ZHe=E(async()=>{"use strict";q();sae();await JHe()});var QHe={};J(QHe,{initializeConversationMemory:()=>qwr});async function qwr(r){if(g.debug("[conversationMemoryInitializer] Initialize conversation memory called",{hasConfig:!!r,hasMemoryConfig:!!r?.conversationMemory,memoryEnabled:r?.conversationMemory?.enabled||!1,storageType:process.env.STORAGE_TYPE||"memory"}),!r?.conversationMemory?.enabled)return g.debug("[conversationMemoryInitializer] Conversation memory not enabled - skipping initialization"),null;try{g.debug("[conversationMemoryInitializer] Applying conversation memory defaults");let e=VBe(r.conversationMemory);g.debug("[conversationMemoryInitializer] Memory configuration processed",{enabled:e.enabled,maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession,enableSummarization:e.enableSummarization});let t=!!r.conversationMemory?.redisConfig,n=t?"redis":XHe();if(g.debug("[conversationMemoryInitializer] Storage type determined",{storageType:n,fromConfig:t,fromEnv:!t&&!!process.env.STORAGE_TYPE}),n==="redis"){g.info("[conversationMemoryInitializer] Initializing Redis-based conversation memory manager"),g.debug("[conversationMemoryInitializer] Getting Redis configuration");let o=r.conversationMemory?.redisConfig||YHe(),s=r.conversationMemory?.redisConfig?"SDK input (from Lighthouse)":"environment variables (NeuroLink)";g.debug("[conversationMemoryInitializer] Redis configuration retrieved",{configSource:s,host:o.host||"localhost",port:o.port||6379,hasPassword:!!o.password,db:o.db||0,keyPrefix:o.keyPrefix||"neurolink:conversation:",ttl:o.ttl||86400}),g.debug("[conversationMemoryInitializer] Creating Redis conversation memory manager");let i=ade(e,"redis",o);return g.debug("[conversationMemoryInitializer] Checking Redis manager creation result",{managerType:i?.constructor?.name||"unknown",isRedisType:i?.constructor?.name==="RedisConversationMemoryManager",hasConfig:!!i?.config}),g.info("[conversationMemoryInitializer] Redis conversation memory manager created successfully"),i?.constructor?.name!=="RedisConversationMemoryManager"&&g.warn("[conversationMemoryInitializer] Created manager is not of RedisConversationMemoryManager type",{actualType:i?.constructor?.name}),i}else{g.info("[conversationMemoryInitializer] Initializing in-memory conversation memory manager"),g.debug("[conversationMemoryInitializer] Creating in-memory conversation memory manager");let o=ade(e);return g.debug("[conversationMemoryInitializer] Checking memory manager creation result",{managerType:o?.constructor?.name||"unknown",isInMemoryType:o?.constructor?.name==="ConversationMemoryManager",hasConfig:!!o?.config}),g.info("[conversationMemoryInitializer] In-memory conversation memory manager created successfully",{maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession,managerType:o?.constructor?.name}),o}}catch(e){throw g.error("[conversationMemoryInitializer] Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e),errorName:e instanceof Error?e.name:"UnknownError",errorStack:e instanceof Error?e.stack:void 0,storageType:process.env.STORAGE_TYPE||"memory",memoryConfig:{enabled:r?.conversationMemory?.enabled,maxSessions:r?.conversationMemory?.maxSessions,maxTurnsPerSession:r?.conversationMemory?.maxTurnsPerSession},redisConfig:{host:process.env.REDIS_HOST||"(not set)",port:process.env.REDIS_PORT||"(not set)",hasPassword:!!process.env.REDIS_PASSWORD,keyPrefix:process.env.REDIS_KEY_PREFIX||"(not set)"}}),process.env.STORAGE_TYPE==="redis"&&g.error("[conversationMemoryInitializer] Redis configuration error details",{REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",errorMessage:e instanceof Error?e.message:String(e)}),e}}var eqe=E(async()=>{"use strict";uT();q();await ZHe()});var tqe={};J(tqe,{AuthProviderFactory:()=>hs,createAuthProvider:()=>cde});async function cde(r,e){return hs.createProvider(r,e)}var hs,KN=E(()=>{"use strict";q();za();hs=class r{static providers=new Map;static aliasMap=new Map;static registerProvider(e,t,n=[],o){r.providers.set(e,{factory:t,aliases:n,metadata:o});for(let s of n)r.aliasMap.set(s.toLowerCase(),e);g.debug(`Registered auth provider: ${e}`)}static async createProvider(e,t){let n=r.resolveType(e),o=r.providers.get(n);if(!o)throw ot.create("PROVIDER_NOT_FOUND",`Auth provider not found: ${e}. Available: ${r.getAvailableProviders().join(", ")}`);try{return await o.factory(t)}catch(s){throw ot.create("CREATION_FAILED",`Failed to create auth provider ${e}: ${s instanceof Error?s.message:String(s)}`,{cause:s instanceof Error?s:void 0})}}static hasProvider(e){return r.providers.has(e)||r.aliasMap.has(e.toLowerCase())}static getAvailableProviders(){return Array.from(r.providers.keys())}static getProviderMetadata(e){let t=r.resolveType(e);return r.providers.get(t)?.metadata}static getAllProviderInfo(){return Array.from(r.providers.entries()).map(([e,t])=>({type:e,aliases:t.aliases,metadata:t.metadata}))}static clearRegistrations(){r.providers.clear(),r.aliasMap.clear()}static resolveType(e){return r.aliasMap.get(e.toLowerCase())||e}}});var tae={};J(tae,{NEUROLINK_BRAND:()=>ude,NeuroLink:()=>NT,STREAM_DEDUP_CONTEXT_KEY:()=>Jwr,default:()=>Ywr,isNeuroLink:()=>Cu,markStreamProviderEmittedGenerationEnd:()=>Xwr,neurolink:()=>rqe});function Wwr(r){let e=r.toLowerCase();return e.includes("not found")||e.includes("404")||e.includes("does not exist")||e.includes("no such")?"not_found":e.includes("permission")||e.includes("forbidden")||e.includes("403")||e.includes("unauthorized")||e.includes("401")||e.includes("access denied")?"permission_denied":e.includes("timeout")||e.includes("timed out")||e.includes("deadline exceeded")?"timeout":e.includes("rate limit")||e.includes("429")||e.includes("too many requests")||e.includes("throttl")?"rate_limited":e.includes("invalid")||e.includes("validation")||e.includes("bad request")||e.includes("400")?"validation_error":"unknown"}function Kwr(r){switch(r){case"not_found":return"validation";case"permission_denied":return"permission";case"timeout":return"timeout";case"rate_limited":return"resource";case"validation_error":return"validation";case"unknown":return"execution"}}function Xwr(r){let e=r?._streamDedupContext;e&&(e.providerEmitted=!0)}function Cu(r){return typeof r=="object"&&r!==null&&r[ude]===!0}var lde,b3,T3,Jwr,ude,NT,rqe,Ywr,Cp=E(async()=>{"use strict";fr();_O();ws();UO();M_e();RBe();KBe();um();JBe();QBe();eze();tze();ea();sae();pae();mae();ou();cz();jw();fze();hze();gae();xae();Tae();SH();ele();rle();EGe();ole();RGe();G0();dq();MGe();DGe();FGe();Q$();dt();sI();og();fVe();hVe();vI();br();uT();lt();F2();nZ();yVe();QQ();_Ve();q();CO();sq();CVe();UVe();Ag();Xd();Rle();Jh();kb();Dle();$q();zle();$le();try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";let{config:r}=await Promise.resolve().then(()=>go(P4e(),1));r({quiet:!0})}catch{}lde=Bq,b3=T4e,T3=new Pb,Jwr="_streamDedupContext";ude=Symbol.for("@juspay/neurolink/sdk-brand");NT=class r{[ude]=!0;mcpInitialized=!1;mcpSkipped=!1;mcpInitPromise=null;emitter=new Ur;_taskManager;_taskManagerConfig;toolRegistry;autoDiscoveredServerInfos=[];externalServerManager;toolCache=null;toolCacheDuration;modelAliasConfig;lastCompactionMessageCount=new Map;getCompactionSessionId(e){return e.context?.sessionId||"__default__"}mcpToolResultCache;mcpToolRouter;mcpToolBatcher;mcpEnhancedDiscovery;mcpToolMiddlewares=[];mcpArtifactStore;_disableToolCacheForCurrentRequest=!1;mcpEnhancementsConfig;toolCircuitBreakers=new Map;toolExecutionMetrics=new Map;currentStreamToolExecutions=[];toolExecutionHistory=[];activeToolExecutions=new Map;emitToolEndEvent(e,t,n,o,s,i){this.emitter.emit("tool:end",Nf(e,{responseTime:Date.now()-t,success:n,timestamp:Date.now(),result:o,error:s?s.message:void 0,executionId:i}))}conversationMemory;conversationMemoryNeedsInit=!1;conversationMemoryConfig;toolRoutingConfig;toolRoutingCacheInstance;toolRoutingVectorCache;toolDedupConfig;enableOrchestration;authProvider;pendingAuthConfig;authInitPromise;credentials;fallbackConfig={};modelPool;requestRouter;resolveCredentials(e){if(!this.credentials&&!e)return;if(!this.credentials)return e;if(!e)return this.credentials;let t={...this.credentials};for(let n of Object.keys(e)){let o=this.credentials[n],s=e[n];o&&s&&typeof o=="object"&&typeof s=="object"?t[n]={...o,...s}:t[n]=s??o}return t}hitlManager;_sessionCostUsd=0;fileRegistry;cachedFileTools=null;memoryInstance;memorySDKConfig;async setLangfuseContextFromOptions(e,t){if(e.context&&typeof e.context=="object"&&e.context!==null){let n=!1;try{let o=e.context;if(o.userId||o.sessionId||o.conversationId||o.requestId||o.traceName||o.metadata){let s;if(o.metadata&&typeof o.metadata=="object"){let i=o.metadata,a={};for(let[c,l]of Object.entries(i))(typeof l=="string"||typeof l=="number"||typeof l=="boolean")&&(a[c]=l);Object.keys(a).length>0&&(s=a)}return await new Promise((i,a)=>{By({userId:typeof o.userId=="string"?o.userId:null,sessionId:typeof o.sessionId=="string"?o.sessionId:null,conversationId:typeof o.conversationId=="string"?o.conversationId:null,requestId:typeof o.requestId=="string"?o.requestId:null,traceName:typeof o.traceName=="string"?o.traceName:null,metadata:o.metadata&&typeof o.metadata=="object"?o.metadata:null,...s!==void 0&&{customAttributes:s}},async()=>{try{n=!0;let c=await t();i(c)}catch(c){a(c)}})})}}catch(o){if(n)throw o;g.warn("Failed to set Langfuse context from options",{error:o instanceof Error?o.message:String(o)})}}return await t()}createMetricsTraceContext(){let e=rt.getSpan(Wt.active());if(e){let t=e.spanContext();if(t.traceId&&t.traceId!=="00000000000000000000000000000000")return{traceId:t.traceId,parentSpanId:t.spanId}}return{traceId:crypto.randomUUID().replace(/-/g,""),parentSpanId:crypto.randomUUID().replace(/-/g,"").substring(0,16)}}enforceSessionBudget(e){if(!(e===void 0||e<=0||this._sessionCostUsd<e))throw new be({code:"SESSION_BUDGET_EXCEEDED",message:`Session budget exceeded: spent $${this._sessionCostUsd.toFixed(4)} of $${e.toFixed(4)} limit`,category:"validation",severity:"high",retriable:!1,context:{spent:this._sessionCostUsd,limit:e}})}assertInputText(e,t){if(!e||typeof e!="string")throw new Error(t)}async applyAuthenticatedRequestContext(e){if(e.auth?.token){let{AuthError:n}=await Promise.resolve().then(()=>(za(),xGe));if(await this.ensureAuthProvider(),!this.authProvider)throw n.create("PROVIDER_ERROR","No auth provider configured. Set auth in constructor or via setAuthProvider() before using auth: { token }.");let o;try{o=await ke(this.authProvider.authenticateToken(e.auth.token),5e3,n.create("PROVIDER_ERROR","Auth token validation timed out after 5000ms"))}catch(s){throw s instanceof Error&&"feature"in s&&s.feature==="Auth"?s:n.create("PROVIDER_ERROR",`Auth token validation failed: ${s instanceof Error?s.message:String(s)}`)}if(!o.valid)throw n.create("INVALID_TOKEN",o.error||"Token validation failed");if(!o.user)throw n.create("INVALID_TOKEN","Token validated but no user identity returned");if(!o.user.id)throw n.create("INVALID_TOKEN","Token validated but user identity missing required 'id' field");e.context={...e.context||{},userId:o.user.id,userEmail:o.user.email,userRoles:o.user.roles}}if(!e.requestContext)return;let t=e.auth?.token&&this.authProvider?{userId:e.context?.userId,userEmail:e.context?.userEmail,userRoles:e.context?.userRoles}:{};e.context={...e.context||{},...e.requestContext,...t}}applyGenerateLifecycleMiddleware(e){!e.onFinish&&!e.onError||(e.middleware={...e.middleware,middlewareConfig:{...e.middleware?.middlewareConfig,lifecycle:{...e.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...e.middleware?.middlewareConfig?.lifecycle?.config,...e.onFinish!==void 0?{onFinish:e.onFinish}:{},...e.onError!==void 0?{onError:e.onError}:{}}}}})}applyStreamLifecycleMiddleware(e){!e.onFinish&&!e.onError&&!e.onChunk||(e.middleware={...e.middleware,middlewareConfig:{...e.middleware?.middlewareConfig,lifecycle:{...e.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...e.middleware?.middlewareConfig?.lifecycle?.config,...e.onFinish!==void 0?{onFinish:e.onFinish}:{},...e.onError!==void 0?{onError:e.onError}:{},...e.onChunk!==void 0?{onChunk:e.onChunk}:{}}}}})}initializeMemoryConfig(){let e=this.conversationMemoryConfig?.conversationMemory?.memory;return e?.enabled?(this.memorySDKConfig=e,!0):!1}ensureMemoryReady(){return this.memoryInstance!==void 0?this.memoryInstance:this.initializeMemoryConfig()?this.memorySDKConfig?(this.memoryInstance=NGe(this.memorySDKConfig),this.memoryInstance):(this.memoryInstance=null,null):(this.memoryInstance=null,null)}toolExecutionContext;observabilityConfig;metricsAggregator=new _v;get _metricsTraceContext(){return T3.getStore()??null}constructor(e){this.toolRegistry=e?.toolRegistry||new CT,this.fileRegistry=new yH,this.observabilityConfig=e?.observability,this.enableOrchestration=e?.enableOrchestration??!1,e?.modelAliasConfig&&(this.modelAliasConfig=e.modelAliasConfig),e?.providerFallback&&(this.fallbackConfig.providerFallback=e.providerFallback),e?.modelChain&&(this.fallbackConfig.modelChain=e.modelChain),e?.toolRouting&&(this.toolRoutingConfig={...e.toolRouting}),e?.toolDedup&&(this.toolDedupConfig={...e.toolDedup}),this.modelPool=e?.modelPool?new EC(e.modelPool):null,this.requestRouter=e?.requestRouter??null,g.setEventEmitter(this.emitter);let t=process.env.NEUROLINK_TOOL_CACHE_DURATION;this.toolCacheDuration=t?parseInt(t,10):2e4;let n=Date.now(),o=process.hrtime.bigint(),s=`neurolink-constructor-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.initializeProviderRegistry(s,n,o),this.initializeConversationMemory(e,s,n,o),this.initializeExternalServerManager(s,n,o),this.initializeHITL(e,s,n,o),this.initializeMCPEnhancements(e),this.registerFileTools(),this.registerMemoryRetrievalTools(),this.initializeLangfuse(s,n,o),this.initializeMetricsListeners(),this.logConstructorComplete(s,n,o),e?.auth&&(this.pendingAuthConfig=e.auth),e?.credentials&&(this.credentials=e.credentials),this._taskManagerConfig=e?.tasks,this._taskManagerConfig&&(this._taskManager=new AN(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerTaskTools(this._taskManager))}get tasks(){return this._taskManager||(this._taskManager=new AN(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerTaskTools(this._taskManager)),this._taskManager}initializeProviderRegistry(e,t,n){let o=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3D7}\uFE0F LOG_POINT_C002_PROVIDER_REGISTRY_SETUP_START",{logPoint:"C002_PROVIDER_REGISTRY_SETUP_START",constructorId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),registrySetupStartTimeNs:o.toString(),message:"Starting ProviderRegistry configuration for security"}),al.setOptions({enableManualMCP:!1})}initializeConversationMemory(e,t,n,o){if(e?.conversationMemory?.enabled){let s=process.hrtime.bigint();this.conversationMemoryConfig=e,this.conversationMemoryNeedsInit=!0;let a=process.hrtime.bigint()-s;g.debug("[NeuroLink] \u2705 LOG_POINT_C006_MEMORY_INIT_FLAG_SET_SUCCESS",{logPoint:"C006_MEMORY_INIT_FLAG_SET_SUCCESS",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),memoryInitDurationNs:a.toString(),memoryInitDurationMs:Number(a)/Wd,message:"Conversation memory initialization flag set successfully for lazy loading"})}else g.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C008_MEMORY_DISABLED",{logPoint:"C008_MEMORY_DISABLED",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!e,hasMemoryConfig:!!e?.conversationMemory,memoryEnabled:e?.conversationMemory?.enabled||!1,reason:e?e.conversationMemory?e.conversationMemory.enabled?"UNKNOWN":"MEMORY_DISABLED":"NO_MEMORY_CONFIG":"NO_CONFIG",message:"Conversation memory not enabled - skipping initialization"})}initializeHITL(e,t,n,o){if(e?.hitl?.enabled){let s=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E1}\uFE0F LOG_POINT_C015_HITL_INIT_START",{logPoint:"C015_HITL_INIT_START",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitStartTimeNs:s.toString(),hitlConfig:{enabled:e.hitl.enabled,dangerousActions:e.hitl.dangerousActions||[],timeout:e.hitl.timeout||3e4,allowArgumentModification:e.hitl.allowArgumentModification??!0,auditLogging:e.hitl.auditLogging??!1},message:"Starting HITL (Human-in-the-Loop) initialization"});try{this.hitlManager=new BM(e.hitl),this.toolRegistry.setHITLManager(this.hitlManager),this.externalServerManager.setHITLManager(this.hitlManager),this.setupHITLEventForwarding();let a=process.hrtime.bigint()-s;g.debug("[NeuroLink] \u2705 LOG_POINT_C016_HITL_INIT_SUCCESS",{logPoint:"C016_HITL_INIT_SUCCESS",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:a.toString(),hitlInitDurationMs:Number(a)/Wd,hasHitlManager:!!this.hitlManager,message:"HITL (Human-in-the-Loop) initialized successfully"}),g.info("[NeuroLink] HITL safety features enabled",{dangerousActions:e.hitl.dangerousActions?.length||0,timeout:e.hitl.timeout||3e4,allowArgumentModification:e.hitl.allowArgumentModification??!0,auditLogging:e.hitl.auditLogging??!1})}catch(i){let c=process.hrtime.bigint()-s;throw g.error("[NeuroLink] \u274C LOG_POINT_C017_HITL_INIT_ERROR",{logPoint:"C017_HITL_INIT_ERROR",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:c.toString(),hitlInitDurationMs:Number(c)/Wd,error:i instanceof Error?i.message:String(i),errorName:i instanceof Error?i.name:"UnknownError",errorStack:i instanceof Error?i.stack:void 0,message:"HITL (Human-in-the-Loop) initialization failed"}),i}}else g.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C018_HITL_DISABLED",{logPoint:"C018_HITL_DISABLED",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!e,hasHitlConfig:!!e?.hitl,hitlEnabled:e?.hitl?.enabled||!1,reason:e?e.hitl?e.hitl.enabled?"UNKNOWN":"HITL_DISABLED":"NO_HITL_CONFIG":"NO_CONFIG",message:"HITL (Human-in-the-Loop) not enabled - skipping initialization"})}initializeMCPEnhancements(e){let t=e?.mcp;if(this.mcpEnhancementsConfig=t,t?.cache?.enabled!==!1&&(this.mcpToolResultCache=new sx({ttl:t?.cache?.ttl??3e5,maxSize:t?.cache?.maxSize??500,strategy:t?.cache?.strategy??"lru"}),g.debug("[NeuroLink] MCP tool result cache initialized",{ttl:t?.cache?.ttl??3e5,maxSize:t?.cache?.maxSize??500,strategy:t?.cache?.strategy??"lru"})),t?.batcher?.enabled&&(this.mcpToolBatcher=new ox({maxBatchSize:t.batcher.maxBatchSize??10,maxWaitMs:t.batcher.maxWaitMs??100}),this.mcpToolBatcher.setToolExecutor(async(n,o)=>this.executeToolInternal(n,o,{timeout:zu.EXECUTION_DEFAULT_MS,maxRetries:Oo.DEFAULT,retryDelayMs:Mn.BASE_MS})),g.debug("[NeuroLink] MCP tool call batcher initialized")),t?.discovery?.enabled!==!1&&(this.mcpEnhancedDiscovery=new fT,g.debug("[NeuroLink] Enhanced tool discovery initialized")),t?.middleware?.length&&(this.mcpToolMiddlewares=[...t.middleware],g.debug("[NeuroLink] MCP tool middlewares registered",{count:this.mcpToolMiddlewares.length})),t?.outputLimits){let n=t.outputLimits.strategy??"externalize",o=t.outputLimits.maxBytes??TGe,s=t.outputLimits.warnBytes??tle,i;n==="externalize"&&(i=new fq,this.mcpArtifactStore=i,g.debug("[NeuroLink] MCP artifact store initialized (local-temp)"));let a=new mq({strategy:n,maxBytes:o,warnBytes:s},i);this.externalServerManager.setOutputNormalizer(a),g.debug("[NeuroLink] MCP output normalizer initialized",{strategy:n,maxBytes:o,warnBytes:s})}}registerFileTools(){let e=fae(this.fileRegistry),t=Object.entries(e).map(async([n,o])=>{let s=`direct.${n}`,i={name:n,description:o.description||`File tool: ${n}`,inputSchema:{},serverId:"direct",category:"built-in"};await this.toolRegistry.registerTool(s,i,{execute:async a=>{try{return{success:!0,data:await o.execute(a,{toolCallId:"file-tool",messages:[]}),metadata:{toolName:n,serverId:"direct",executionTime:0}}}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}})});Promise.all(t).then(()=>{g.debug(`[NeuroLink] Registered ${Object.keys(e).length} file reference tools`)})}registerTaskTools(e){let t=gVe(e);for(let[n,o]of Object.entries(t)){let s=`direct.${n}`,i={name:n,description:o.description||`Task tool: ${n}`,inputSchema:{},serverId:"direct",category:"built-in"};this.toolRegistry.registerTool(s,i,{execute:async a=>{try{return{success:!0,data:await o.execute(a,{toolCallId:"task-tool",messages:[]}),metadata:{toolName:n,serverId:"direct",executionTime:0}}}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}})}g.debug(`[NeuroLink] Registered ${Object.keys(t).length} task tools`)}registerMemoryRetrievalTools(){let e=this.conversationMemoryConfig?.conversationMemory,t=!!e?.redisConfig||e&&"redis"in e&&!!e.redis||process.env.STORAGE_TYPE==="redis",n=!!this.mcpArtifactStore;if((!e?.enabled||!t)&&!n){g.debug("[NeuroLink] Skipping memory retrieval tools \u2014 requires Redis conversation memory or an artifact store");return}let s=mle(void 0,this.mcpArtifactStore).retrieve_context;this.registerTool("retrieve_context",{name:"retrieve_context",description:s.description??"Retrieve context or artifacts",inputSchema:s.inputSchema,execute:async i=>{let a=this.conversationMemory,c=mle(a,this.mcpArtifactStore);return await ke(c.retrieve_context.execute(i,{toolCallId:"memory-retrieval",messages:[]}),zu.EXECUTION_DEFAULT_MS,ae.toolTimeout("retrieve_context",zu.EXECUTION_DEFAULT_MS))}}),g.info("[NeuroLink] Memory retrieval tools registered")}formatMemoryContext(e,t){return`Context from previous conversations:
|
|
2107
2107
|
|
|
2108
2108
|
${e}
|
|
2109
2109
|
|
|
@@ -2132,7 +2132,7 @@ IMPORTANT: You are a general-purpose AI assistant. Answer all requests directly
|
|
|
2132
2132
|
|
|
2133
2133
|
${k}`:d.text}}catch(_){if(!(e.input.text||""))throw _;g.warn(`[NeuroLink] Stream STT transcription failed, falling back to text: ${_ instanceof Error?_.message:String(_)}`)}}let m=e.input?.text??"";e.fileRegistry=this.fileRegistry,await this.validateStreamRequestOptions(e,s),aV(t,e.context,n);let f=await this.maybeHandleWorkflowStreamRequest({options:e,startTime:s,streamSpan:t,spanStartTime:o});if(f)return f;let h=rt.setSpan(Wt.active(),t);await Wt.with(h,()=>this.setLangfuseContextFromOptions(e,()=>this.applyToolRoutingExclusions(e,m))),await this.applyRequestRouter(e,m,!e.disableTools&&(!!(e.tools&&Object.keys(e.tools).length>0)||this.getCustomTools().size>0),!!(e.input?.images&&e.input.images.length>0),e.thinking?.thinkingLevel);let y=e.tts,x=!!(y?.enabled&&y?.useAiResponse),b,T=x?new Promise(_=>{b=_}):void 0,w=await Wt.with(h,()=>this.setLangfuseContextFromOptions(e,()=>this.runStandardStreamRequest({options:e,streamSpan:t,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:m,ttsResolver:b})));return d&&(w.transcription=d),T&&(w.audio=T),w}catch(s){throw t.setStatus({code:he.ERROR,message:s instanceof Error?s.message:String(s)}),s instanceof Error&&t.recordException(s),t.end(),s}}async applyToolRoutingExclusions(e,t){let n=this.toolRoutingConfig;if(!n?.enabled||e.disableTools)return;let o=n.servers??[];if(o.length!==0)try{let s=Array.from(this.getCustomTools().keys()),i=lae(o,s);if(i.length===0)return;let a=await this.fetchRecentRoutingHistory(e),c=a.length>0?uae(a,t):t,l=n.cache,u=l?.enabled===!0,d=n.stickiness?.enabled===!0;(u||d)&&!this.toolRoutingCacheInstance&&(this.toolRoutingCacheInstance=new FM({ttlMs:l?.ttlMs,maxEntries:l?.maxEntries,stickyTurns:n.stickiness?.turns}));let m=this.toolRoutingCacheInstance,f=e.context,h=typeof f?.sessionId=="string"?f.sessionId:"",y=u&&h?`${h}:${c}`:void 0,x=i.filter(I=>!(n.alwaysIncludeServerIds??[]).includes(I.id)).length,b=Date.now(),T=I=>{try{let R=rt.getActiveSpan();if(!R)return;R.setAttribute("tool_routing.outcome",I.outcome),R.setAttribute("tool_routing.routable_server_count",I.routableServerCount),R.setAttribute("tool_routing.selected_server_ids",xo(I.selectedServerIds)),R.setAttribute("tool_routing.excluded_server_ids",xo(I.excludedServerIds)),R.setAttribute("tool_routing.hallucinated_ids",xo(I.hallucinatedIds)),R.setAttribute("tool_routing.excluded_tool_count",I.excludedToolCount),R.setAttribute("tool_routing.cache_hit",I.cacheHit),R.setAttribute("tool_routing.duration_ms",I.durationMs),I.embeddingActivated!==void 0&&R.setAttribute("tool_routing.embedding_activated",I.embeddingActivated),I.candidateToolCount!==void 0&&R.setAttribute("tool_routing.candidate_tool_count",I.candidateToolCount),I.granularity!==void 0&&R.setAttribute("tool_routing.granularity",I.granularity)}catch{}};if(u&&m&&y!==void 0){let I=m.get(y);if(I){let R=I.excludedToolNames;if(d&&h)try{let D=m.getStickyServerIds(h);D.length>0&&(R=R.filter(j=>!D.some(L=>j.startsWith(`${L}_`))))}catch{}let A=new Set(I.selectedServerIds),P=i.map(D=>D.id).filter(D=>!A.has(D));T({outcome:"cache-hit",selectedServerIds:I.selectedServerIds,excludedServerIds:P,hallucinatedIds:[],excludedToolCount:R.length,routableServerCount:x,cacheHit:!0,durationMs:Date.now()-b}),g.debug("[ToolRouting] Cache hit, skipping router LLM",{hasSessionId:!!h,routingQueryLength:c.length}),R.length>0&&(e.excludeTools=[...e.excludeTools??[],...R]);return}}let w=this._disableToolCacheForCurrentRequest,_,C;try{let I=P=>{C=P,T(P)},R,A=n.embedding;if(A?.enabled===!0)try{let P=A.provider??(e.provider&&e.provider!=="auto"?e.provider:void 0)??n.routerModel?.provider;if(P){let D=await Vr.createProvider(P,A.model,!0,this,void 0,this.resolveCredentials(e.credentials));R=j=>ke(D.embedMany(j,A.model),A.timeoutMs??1e4),this.toolRoutingVectorCache||(this.toolRoutingVectorCache=new Map)}}catch(P){g.debug("[ToolRouting] Embedding provider setup failed, L2 path disabled for this turn",{error:P instanceof Error?P.message:String(P)})}_=await dae({catalog:i,alwaysIncludeServerIds:n.alwaysIncludeServerIds??[],userQuery:c,routerPromptPrefix:n.routerPromptPrefix,routerModel:{provider:n.routerModel?.provider??e.provider,model:n.routerModel?.model??e.model,region:n.routerModel?.region??e.region,temperature:n.routerModel?.temperature},timeoutMs:n.timeoutMs??eX,generateFn:P=>this.generate({...P,abortSignal:e.abortSignal}),emitDecision:I,embedFn:R,embeddingConfig:A,granularity:n.granularity??"server",embeddingVectorCache:R!==void 0?this.toolRoutingVectorCache:void 0})}finally{this._disableToolCacheForCurrentRequest=w}if(e.abortSignal?.aborted)return;let k=_;if(d&&m&&h)try{let I=m.getStickyServerIds(h);if(I.length>0){let R=I.map(A=>`${A}_`);_=_.filter(A=>!R.some(P=>A.startsWith(P)))}}catch{}if(C?.outcome==="applied"&&m){if(u&&y!==void 0)try{m.set(y,{excludedToolNames:k,selectedServerIds:C.selectedServerIds})}catch{}if(d&&h)try{m.recordSelection(h,C.selectedServerIds)}catch{}}_.length>0&&(e.excludeTools=[...e.excludeTools??[],..._])}catch(s){if(Sr(s))throw s;g.warn("[ToolRouting] Routing setup failed, failing open",{error:s instanceof Error?s.message:String(s)})}}async fetchRecentRoutingHistory(e){try{let t=e.context;if(e.conversationMessages&&e.conversationMessages.length>0)return e.conversationMessages;let n=t?.sessionId;if(typeof n!="string"||!n)return[];await this.initializeConversationMemoryForGeneration(`tool-routing-${Date.now()}`,Date.now(),process.hrtime.bigint());let o=this.conversationMemory;if(!o)return[];let s=await Tg(o,{...e,enableSummarization:!1});return g.debug("[ToolRouting] Loaded conversation history for router",{sessionId:n,messageCount:s.length}),s}catch(t){return g.debug("[ToolRouting] Failed to load conversation history; routing on current query only",{error:t instanceof Error?t.message:String(t)}),[]}}setToolRoutingServers(e){if(!this.toolRoutingConfig){g.warn("[ToolRouting] setToolRoutingServers called without toolRouting constructor config \u2014 servers stored but routing stays disabled"),this.toolRoutingConfig={enabled:!1,servers:e};return}this.toolRoutingConfig.servers=e,this.toolRoutingVectorCache=void 0,this.toolRoutingCacheInstance=void 0}async validateStreamRequestOptions(e,t){await this.validateStreamInput(e),this.enforceSessionBudget(e.maxBudgetUsd),await this.applyAuthenticatedRequestContext(e),this.emitStreamStartEvents(e,t),this.applyStreamLifecycleMiddleware(e)}async maybeHandleWorkflowStreamRequest(e){if(!e.options.workflow&&!e.options.workflowConfig)return null;let t=await this.streamWithWorkflow(e.options,e.startTime),n=t.stream,o=this;return t.stream=(async function*(){try{for await(let s of n)yield s;e.streamSpan.setStatus({code:he.OK})}catch(s){throw e.streamSpan.setStatus({code:he.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o._disableToolCacheForCurrentRequest=!1,e.streamSpan.setAttribute("neurolink.response_time_ms",Date.now()-e.spanStartTime),e.streamSpan.end()}})(),t}async runStandardStreamRequest(e){let{options:t,streamSpan:n,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:c,ttsResolver:l}=e;g.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:t.provider,model:t.model,inputLength:t.input?.text?.length||0,disableTools:t.disableTools,enableAnalytics:t.enableAnalytics,enableEvaluation:t.enableEvaluation,contextKeys:t.context?Object.keys(t.context):[],optionKeys:Object.keys(t),sessionId:t.context?.sessionId});try{let{enhancedOptions:u,factoryResult:d}=await this.prepareStreamOptions(t,a,s,i);g.debug("[NeuroLink] Stream options prepared",{streamId:a,options:u,factoryResult:d,sessionId:u.context?.sessionId});let{stream:m,provider:f,usage:h,model:y,finishReason:x,toolCalls:b,toolResults:T,analytics:w}=await this.createMCPStream(u),_={finishReason:x??"stop",toolCalls:b,toolResults:T};n.setAttribute(de.NL_PROVIDER,f||"unknown");let C="",k=0,{eventSequence:I,cleanup:R}=this.setupStreamEventListeners(),A={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},P=this,D=Date.now(),j=u.context?.sessionId,L={providerEmitted:!1};u._streamDedupContext=L;let H=(async function*(){let B,z,U=0;try{for await(let F of m){k++;let G=F!==null&&typeof F=="object"&&"metadata"in F&&F.metadata?.noOutput===!0,ie=F&&"content"in F&&typeof F.content=="string"&&F.content.length>0,re=F!==null&&typeof F=="object"&&"type"in F&&(F.type==="audio"||F.type==="tts_audio"||F.type==="image");!G&&(ie||re)&&U++,F&&"content"in F&&typeof F.content=="string"&&(C+=F.content,P.emitter.emit("response:chunk",F.content),P.emitter.emit("stream:chunk",{type:"stream:chunk",content:F.content,metadata:{chunkIndex:k,totalLength:C.length,...G&&{noOutput:!0}},timestamp:Date.now()})),yield F}U===0&&!A.fallbackAttempted&&!u.disableInternalFallback&&_.toolCalls.length===0&&_.toolResults.length===0&&(yield*P.handleStreamFallback(A,_,c,u,f,F=>{C+=F}));let O=await P.synthesizeStreamModeTwo({ttsOptions:u.tts,providerName:f,fallbackProvider:u.provider,accumulatedContent:C,ttsResolver:l});if(O.audioChunk&&(yield O.audioChunk),z=h,!z&&w)try{let F=await Promise.resolve(w);F?.tokenUsage&&(z=F.tokenUsage)}catch{}P.emitter.emit("stream:complete",{type:"stream:complete",content:C,provider:A.fallbackProvider??f,model:A.fallbackModel??y??u.model,finishReason:_.finishReason??"stop",prompt:u.input?.text||u.prompt,metadata:{chunkCount:k,totalLength:C.length,durationMs:Date.now()-D,sessionId:j,usage:z,finishReason:_.finishReason??"stop",...A.fallbackAttempted&&{primaryProvider:f,primaryModel:u.model,fallback:!0}},timestamp:Date.now()})}catch(O){throw g.debug("[NeuroLink.stream] Stream error occurred",{error:O instanceof Error?O.message:String(O),name:O instanceof Error?O.name:"UnknownError",provider:f,model:u.model,chunkCount:k,totalLength:C.length,durationMs:Date.now()-D,sessionId:j}),B=O,P.emitter.emit("stream:error",{type:"stream:error",content:O instanceof Error?O.message:String(O),provider:f,model:u.model,metadata:{chunkCount:k,totalLength:C.length,durationMs:Date.now()-D,errorName:O instanceof Error?O.name:"UnknownError",sessionId:j},timestamp:Date.now()}),O}finally{if(l?.(void 0),g.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:f,model:u.model,totalChunks:k,totalLength:C.length,durationMs:Date.now()-D,fallbackAttempted:A.fallbackAttempted,guardrailsBlocked:A.guardrailsBlocked,error:A.error}),!L.providerEmitted)try{let F=A.fallbackProvider??f??"unknown",G=A.fallbackModel??y??u.model??"unknown",ie=B?"error":_.finishReason??"stop";P.emitter.emit("generation:end",{provider:F,model:G,responseTime:Date.now()-D,toolsUsed:_.toolCalls?.map(re=>re.toolName),timestamp:Date.now(),result:{content:C,usage:z,model:G,provider:F,finishReason:ie},prompt:u.input?.text||u.prompt,temperature:u.temperature,maxTokens:u.maxTokens,success:!B,error:B?B instanceof Error?B.message:String(B):void 0,pipelineAHandled:!0})}catch(F){g.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:F instanceof Error?F.message:String(F)})}P._disableToolCacheForCurrentRequest=!1,R(),n.setAttribute("neurolink.response_time_ms",Date.now()-o),n.setAttribute(de.NL_OUTPUT_LENGTH,C.length);let O=!!(A.error||B);n.setAttribute(de.GEN_AI_FINISH_REASON,O?"error":"stop"),A.fallbackAttempted&&(n.setAttribute("neurolink.fallback_triggered",!0),A.fallbackProvider&&n.setAttribute("neurolink.fallback_provider",A.fallbackProvider)),O?n.setStatus({code:he.ERROR,message:A.error||(B instanceof Error?B.message:String(B))}):n.setStatus({code:he.OK}),n.end(),C.trim()&&g.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:f,model:u.model,responseTimeMs:Date.now()-s,contentLength:C.length,fallback:A.fallbackAttempted}),await P.storeStreamConversationMemory({enhancedOptions:u,providerName:f,originalPrompt:c,accumulatedContent:C,startTime:s,eventSequence:I})}})(),N=await this.processStreamResult(H,u,d);return N.finishReason=_.finishReason||N.finishReason,N.toolCalls=_.toolCalls,N.toolResults=_.toolResults,N.usage||(N.usage=h),N.analytics||(N.analytics=w),Promise.resolve(N.analytics).then(B=>{B?.cost&&B.cost>0&&(this._sessionCostUsd+=B.cost)}).catch(()=>{}),this.emitStreamEndEvents(N),this.createStreamResponse(N,H,{providerName:f,options:t,startTime:s,responseTime:Date.now()-s,streamId:a,fallback:A.fallbackAttempted,guardrailsBlocked:A.guardrailsBlocked,error:A.error,events:I})}catch(u){if(t.disableInternalFallback)throw u;return this.handleStreamError(u,t,s,a,void 0,void 0)}}async synthesizeStreamModeTwo(e){let{ttsOptions:t,providerName:n,fallbackProvider:o,accumulatedContent:s,ttsResolver:i}=e;if(!t?.enabled||!t.useAiResponse||s.trim().length===0)return i?.(void 0),{};try{let{TTSProcessor:a}=await Promise.resolve().then(()=>(ra(),Xh)),c=t.provider??o??n,l=c&&a.supports(c)?c:void 0;if(!l)throw new Error(`No TTS provider resolved for stream Mode 2 (set tts.provider explicitly \u2014 chat provider "${c??"<unset>"}" is not a registered TTS handler)`);let u=await a.synthesize(s,l,t);return i?.(u),{audioChunk:{type:"tts_audio",audio:{data:u.buffer,format:u.format,index:0,isFinal:!0,cumulativeSize:u.size,voice:u.voice,sampleRate:u.sampleRate}}}}catch(a){return g.warn(`[NeuroLink.stream] Stream TTS Mode 2 synthesis failed: ${a instanceof Error?a.message:String(a)}`),i?.(void 0),{}}}async prepareStreamOptions(e,t,n,o){if(await this.initializeConversationMemoryForGeneration(t,n,o),await this.initializeMCP(),this.shouldReadMemory(e.memory,e.context?.userId)&&e.context?.userId)try{e.input.text=await this.retrieveMemory(e.input.text??"",e.context.userId,e.memory?.additionalUsers),g.debug("Memory retrieval successful")}catch(a){g.warn("Memory retrieval failed:",a)}if(this.enableOrchestration&&!e.provider&&!e.model)try{let a=await this.applyStreamOrchestration(e);g.debug("Stream orchestration applied",{originalProvider:e.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:e.input.text?.substring(0,100)}),e={...e,...a},a.model&&(e.model=xC(e.model,this.modelAliasConfig))}catch(a){g.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:e.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(e),e.rag?.files?.length)try{let{prepareRAGTool:a}=await Promise.resolve().then(()=>(Yq(),iue)),c=await a(e.rag,e.provider);e.tools||(e.tools={}),e.tools[c.toolName]=c.tool;let l=[`
|
|
2134
2134
|
|
|
2135
|
-
IMPORTANT: You have a tool called "${c.toolName}" that searches through`,`${c.filesLoaded} loaded document(s) containing ${c.chunksIndexed} indexed chunks.`,`ALWAYS use the "${c.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");e.systemPrompt=(e.systemPrompt||"")+l,g.info("[RAG] Tool injected into stream()",{toolName:c.toolName,filesLoaded:c.filesLoaded,chunksIndexed:c.chunksIndexed})}catch(a){g.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}let s=SVe(e),i=wVe(e);if(e.input?.text){let{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(e.input.text,void 0);c!==e.input.text&&(i.input.text=c)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(e){if((e.provider==="ollama"||e.provider?.toLowerCase().includes("ollama"))&&!e.disableTools){let{ModelConfigurationManager:t}=await Promise.resolve().then(()=>(Dy(),oDe)),s=t.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=e.model;s.length>0&&i&&(s.some(c=>i.toLowerCase().includes(c.toLowerCase()))||(e.disableTools=!0,g.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:e.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){let e=[],t=0,n=(d,m)=>{e.push({type:d,seq:t++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{let m=d[0];n("response:chunk",{content:m})},s=(...d)=>{let m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{let m=d[0],f=m.toolName??m.tool,h=m.responseTime??m.duration,y=m.success??(m.error!==void 0?!1:void 0),x={...m,toolName:f,...h!==void 0?{responseTime:h}:{},...y!==void 0?{success:y}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",x),x.result&&x.result.uiComponent===!0&&n("ui-component",{toolName:f,componentData:x.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...h!==void 0?{responseTime:h}:{}})},a=(...d)=>{n("ui-component",d[0])},c=(...d)=>{n("hitl:confirmation-request",d[0])},l=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",c),this.emitter.on("hitl:confirmation-response",l),{eventSequence:e,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",c),this.emitter.off("hitl:confirmation-response",l)}}}async*handleStreamFallback(e,t,n,o,s,i){e.fallbackAttempted=!0;let a="Stream completed with 0 chunks (possible guardrails block)";e.error=a;try{let h=this._metricsTraceContext,y=le.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:h?.traceId,parentSpanId:h?.parentSpanId});y=le.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),Pe().recordSpan(y)}catch{}let c=o.fallbackProvider?.trim()||void 0,l=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,m=bC.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),f={...m,provider:c??u??m.provider,model:l??d??m.model};g.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:f.provider,fallbackModel:f.model,fallbackSource:c||l?"options":u||d?"env":"model_config",reason:a});try{let h=await Vr.createProvider(f.provider,f.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));h.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,k)=>this.executeTool(C,k,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");let y=o.conversationMessages!==void 0?o.conversationMessages:await Tg(this.conversationMemory,{prompt:o.input.text,context:o.context}),x=await h.stream({...o,model:f.model,conversationMessages:y}),b=x.toolCalls??[],T=x.toolResults??[];(b.length>0||T.length>0)&&(t.toolCalls=b,t.toolResults=T,t.finishReason=x.finishReason??t.finishReason);let w=0,_=0;for await(let C of x.stream){w++;let k=C!==null&&typeof C=="object"&&"metadata"in C&&C.metadata?.noOutput===!0,I=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");!k&&(I||R)&&_++,C&&"content"in C&&typeof C.content=="string"&&(i(C.content),this.emitter.emit("response:chunk",C.content)),yield C}if(_===0&&b.length===0&&T.length===0)throw new Error(`Fallback provider ${f.provider} also returned 0 real output chunks (chunkCount=${w}, sentinel-only or empty)`);e.fallbackProvider=f.provider,e.fallbackModel=f.model,e.guardrailsBlocked=!0}catch(h){let y=h instanceof Error?h.message:String(h);throw e.error=`${a}; Fallback failed: ${y}`,g.error("Fallback provider failed",{fallbackProvider:f.provider,error:y}),h}}async storeStreamConversationMemory(e){let{enhancedOptions:t,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=e;g.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:JSON.stringify(t),sessionId:t.context?.sessionId});let c=a.some(l=>l.type==="tool:start"||l.type==="tool:end");if(!s.trim()&&!c){g.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:t.context?.sessionId});return}if(g.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:JSON.stringify(t),sessionId:t.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&t.context?.sessionId){let l=t.context?.sessionId,u=t.context?.userId,d;t.model&&(d={provider:n,model:t.model});let m=Date.now();try{await this.conversationMemory.storeConversationTurn({sessionId:l,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:t.enableSummarization,events:a.length>0?a:void 0,requestId:t.context?.requestId}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),g.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:l,eventCount:a.length,eventTypes:[...new Set(a.map(f=>f.type))]})}catch(f){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,f instanceof Error?f.message:String(f)),g.warn("Failed to store stream conversation turn",{error:f instanceof Error?f.message:String(f)})}}this.shouldWriteMemory(t.memory,t.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),t.context?.userId,t.memory?.additionalUsers,t.context)}async validateStreamInput(e){let t=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:t.toString(),message:"Starting comprehensive input validation process"});let n=typeof e?.input?.text=="string"&&e.input.text.trim().length>0,o=!!(e?.input?.audio&&e.input.audio.frames&&typeof e.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(e?.stt?.enabled&&e?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(e,t){this.emitter.emit("stream:start",{provider:e.provider||"auto",timestamp:t}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${e.provider||"auto"} stream...`)}async createMCPStream(e){let t=await gx(e.provider),n=await Vr.createProvider(t,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(h,y)=>this.executeTool(h,y,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,e);let s=e.skipToolPromptInjection?e.systemPrompt||"":this.createToolAwareSystemPrompt(e.systemPrompt,o),i=e.conversationMessages!==void 0,a=i?e.conversationMessages:await Tg(this.conversationMemory,{...e,prompt:e.input.text,context:e.context});e.conversationMessages=a;let c=a,l=Bc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o}),u=c?.length||0,d=this.getCompactionSessionId(e),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:t,model:e.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Pl(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${l.estimatedInputTokens} tokens, budget: ${l.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:l.estimatedInputTokens,availableTokens:l.availableInputTokens,stagesUsed:[],breakdown:l.breakdown})}if(l.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){let y=await new nx({provider:t,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(c,l.availableInputTokens,this.conversationMemoryConfig?.conversationMemory,e.context?.requestId);y.compacted&&(c=$0(y.messages).messages,e.conversationMessages=c,this.lastCompactionMessageCount.set(d,c.length));let x=Bc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!x.withinBudget){g.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:x.estimatedInputTokens,availableTokens:x.availableInputTokens,overagePercent:Math.round((x.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:x.estimatedInputTokens,budget:x.availableInputTokens,provider:t,model:e.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=mH(c,x.availableInputTokens,x.breakdown,t),e.conversationMessages=c;let b=Bc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!b.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:b.estimatedInputTokens,budget:b.availableInputTokens,provider:t,model:e.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Pl(`Stream context exceeds model budget after all compaction stages. Estimated: ${b.estimatedInputTokens} tokens, Budget: ${b.availableInputTokens} tokens.`,{estimatedTokens:b.estimatedInputTokens,availableTokens:b.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:b.breakdown})}}}if(this.modelPool){let h=this.modelPool,y=h.maxAttempts,x=new Set,b=null;for(let T=0;T<y;T++){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let w=h.selectNext(x);if(!w)break;x.add(h.memberKey(w));let _=w.provider,C=w.model??void 0,k=w.region??void 0;g.debug(`[createMCPStream] ModelPool: attempting member ${_}`,{model:C,attempt:T});try{let I=await Vr.createProvider(_,C,!e.disableTools,this,k,this.resolveCredentials(e.credentials));I.setTraceContext(this._metricsTraceContext),I.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(D,j)=>this.executeTool(D,j,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let R=await I.stream({...e,provider:_,model:C,region:k,systemPrompt:s,conversationMessages:c});g.debug("[createMCPStream] ModelPool stream handle obtained",{provider:_});let A=w;return{stream:(async function*(){try{yield*R.stream,h.recordSuccess(A)}catch(D){throw h.recordFailure(A,xx(D)),D}})(),provider:_,usage:R.usage,model:R.model||C,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics}}catch(I){if(Sr(I))throw I;if(b3(I)){let R=I instanceof Error?I.message:String(I);throw h.recordFailure(w,xx(I)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:I})}h.recordFailure(w,xx(I)),b=I instanceof Error?I:new Error(String(I)),g.warn(`[createMCPStream] ModelPool: member ${_} failed`,{error:b.message})}}throw new Error(`[ModelPool] all stream members failed: ${b?.message??"no stream members available"}`)}let f=await n.stream({...e,systemPrompt:s,conversationMessages:c});return g.debug("[createMCPStream] Stream created successfully",{provider:t,systemPromptPassedLength:s.length}),{stream:f.stream,provider:t,usage:f.usage,model:f.model||e.model,finishReason:f.finishReason,toolCalls:f.toolCalls??[],toolResults:f.toolResults??[],analytics:f.analytics}}async processStreamResult(e,t,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(e){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",e.content||"")}createStreamResponse(e,t,n){return{stream:t,provider:n.providerName,model:n.options.model,usage:e.usage,finishReason:e.finishReason,toolCalls:e.toolCalls,toolResults:e.toolResults,analytics:e.analytics,evaluation:e.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error}}}async handleStreamError(e,t,n,o,s,i){if(e instanceof Pl)throw e;g.error("Stream generation failed, attempting fallback",{error:e instanceof Error?e.message:String(e)});try{this.emitter.emit("stream:error",{content:e instanceof Error?e.message:String(e),metadata:{errorName:e instanceof Error?e.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:t.provider||"unknown",model:t.model||"unknown"})}catch{}let a=t.input.text,c=Date.now()-n,l=await gx(t.provider),d=await(await Vr.createProvider(l,t.model,!0,void 0,void 0,this.resolveCredentials(t.credentials))).stream({input:{text:t.input.text},model:t.model,temperature:t.temperature,maxTokens:t.maxTokens,conversationMessages:t.conversationMessages}),m="";return{stream:(async function*(h){try{for await(let y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(m+=y.content,h.emitter.emit("response:chunk",y.content)),yield y}finally{if(m.trim()){g.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:t.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{h.emitter.emit("stream:complete",{content:m,provider:l,model:t.model||"unknown",finishReason:"stop",metadata:{durationMs:Date.now()-n,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}})}catch{}}if(h.conversationMemory&&s?.context?.sessionId&&m.trim()){let y=s?.context?.sessionId,x=s?.context?.userId,b;t.model&&(b={provider:l,model:t.model});let T=Date.now();try{await h.conversationMemory.storeConversationTurn({sessionId:y||t.context?.sessionId,userId:x||t.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:b,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||t.context?.requestId}),h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,1)}catch(w){h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,2,w instanceof Error?w.message:String(w)),g.warn("Failed to store fallback stream conversation turn",{error:w instanceof Error?w.message:String(w)})}}}})(this),provider:l,model:t.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:c,fallback:!0}}}getEventEmitter(){return this.emitter}getToolDedupConfig(){return this.toolDedupConfig}async checkCredentials(e){let{provider:t,model:n}=e,o="ping";try{return await this.generate({provider:t,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:t,status:"ok",detail:"credentials valid"}}catch(s){let i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof Zp?{provider:t,status:"denied",detail:i}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:t,status:"expired",detail:i}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:t,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:t,status:"network",detail:i}:{provider:t,status:"unknown",detail:i}}}emitToolStart(e,t,n=Date.now()){let o=`${e}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:e,startTime:n,metadata:{inputType:typeof t,hasInput:t!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",Nf(e,{input:t,timestamp:n,executionId:o})),g.debug(`tool:start emitted for ${e}`,{toolName:e,executionId:o,timestamp:n,inputProvided:t!==void 0}),o}emitToolEnd(e,t,n,o,s=Date.now(),i){let a=o||s-1e3,c=s-a,l=!n,u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(f=>f.tool===e&&!f.endTime);let d=i||u?.executionId||`${e}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=t,u.error=n,this.activeToolExecutions.delete(u.executionId));let m={tool:e,startTime:a,endTime:s,duration:c,success:l,result:t,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",Nf(e,{result:t,error:n,success:l,responseTime:c,timestamp:s,duration:c,executionId:d})),g.debug(`tool:end emitted for ${e}`,{toolName:e,executionId:d,duration:c,success:l,hasResult:t!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(e,t,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:e,timestamp:Date.now()});try{if(!e||typeof e!="string")throw new Error("Invalid tool name");if(!t||typeof t!="object")throw new Error(`Invalid tool object provided for tool: ${e}`);if(typeof t.execute!="function")throw new Error(`Tool '${e}' must have an execute method.`);if(e.trim()==="")throw new Error("Tool name cannot be empty");if(e.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(e))throw new Error("Tool name contains invalid control characters");let o={name:t.name||e,description:t.description||e,execute:t.execute,inputSchema:"parameters"in t&&t.parameters&&(CI(t.parameters)||typeof t.parameters=="object")?t.parameters:t.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){let i=o.execute,a=n.timeout,c=e;o.execute=async(...l)=>{let u=AbortSignal.timeout(a),d=l[1],m=d?.abortSignal,f=m?AbortSignal.any([m,u]):u,h={...d,abortSignal:f};return Promise.race([i(l[0],h),new Promise((y,x)=>{f.addEventListener("abort",()=>{u.aborted?x(ae.toolTimeout(c,a)):x(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}let s=hGe(e,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),this.emitter.emit("tools-register:end",{toolName:e,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw g.error(`Failed to register tool ${e}:`,o),o}}setToolContext(e){this.toolExecutionContext={...e},g.debug("Tool execution context updated",{sessionId:e.sessionId,contextKeys:Object.keys(e),hasJuspayToken:!!e.juspayToken,hasShopId:!!e.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,g.debug("Tool execution context cleared")}registerTools(e){if(Array.isArray(e))for(let{name:t,tool:n}of e)this.registerTool(t,n);else for(let[t,n]of Object.entries(e))this.registerTool(t,n)}unregisterTool(e){this.invalidateToolCache();let t=`custom-tool-${e}`,n=this.toolRegistry.unregisterServer(t);return n&&g.info(`Unregistered custom tool: ${e}`),n}useToolMiddleware(e){return this.mcpToolMiddlewares.push(e),g.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(e,t,n){if(!this.conversationMemory)throw new ac("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new ac("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await ke(this.conversationMemory.updateAgenticLoopReport(e,n,t),5e3)}getCustomTools(){let e=this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0})),t=new Map;for(let o of e){let s=o.inputSchema||o.parameters;g.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),t.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{let c=this.toolExecutionContext||{},l=a&&Jt(a)?a:{},u={...c,...l,sessionId:l.sessionId||c.sessionId||`fallback-${Date.now()}`};return g.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(c),runtimeContextKeys:Object.keys(l),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=fae(this.fileRegistry));let n=this.cachedFileTools;for(let[o,s]of Object.entries(n))if(!t.has(o)){let i=s,a=i.inputSchema??i.parameters;t.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async c=>await s.execute(c,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return t}async addInMemoryMCPServer(e,t){this.invalidateToolCache();try{te.debug(`[NeuroLink] Registering in-memory MCP server: ${e}`),t.tools||(t.tools=[]),await this.toolRegistry.registerServer(t),te.info(`[NeuroLink] Successfully registered in-memory server: ${e}`,{category:t.metadata?.category,provider:t.metadata?.provider,version:t.metadata?.version})}catch(n){throw te.error(`[NeuroLink] Failed to register in-memory server ${e}:`,n),n}}getInMemoryServers(){let e=this.getInMemoryServerInfos(),t=new Map;for(let n of e)t.set(n.id,n);return t}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(t=>ga({existingCategory:t.metadata?.category,serverId:t.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(e,t={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(e,t);let o=this.createToolExecutionContext(e,t,n);return me.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":e,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(e,t,n,o,s))}createToolExecutionContext(e,t,n){let o=this.externalServerManager.getAllTools().find(a=>a.name===e),s=o?"mcp":this.getCustomTools().has(e)?"custom":"external",i=typeof t=="string"?t:t?JSON.stringify(t):"";return{functionTag:"NeuroLink.executeTool",executionStartTime:Date.now(),externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(e,t,n,o,s){try{let i=await this.prepareToolExecutionState(e,t,n,o);return await this.runPreparedToolExecution(e,t,i,o,s)}catch(i){if(!(i instanceof be)){let a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:he.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(e,t,n,o){g.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:e,params:Jt(t)?rB(t):t,hasExternalManager:!!this.externalServerManager}),g.debug("Tool execution detailed analysis",{toolName:e,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof t,isNull:t===null,isUndefined:t===void 0,isEmpty:t&&typeof t=="object"&&Object.keys(t).length===0,keys:t&&typeof t=="object"?Object.keys(t):"NOT_OBJECT",keysLength:t&&typeof t=="object"?Object.keys(t).length:0},isTargetTool:e==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",Nf(e,{timestamp:o.executionStartTime,input:t}));let s=this.toolRegistry.getToolInfo(e),i={timeout:n?.timeout??s?.tool?.timeoutMs??zu.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??Oo.DEFAULT,retryDelayMs:n?.retryDelayMs||Mn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(kC(),CC)),c=a.getMemoryUsageMB(),u=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${e}`,d=this.toolCircuitBreakers.get(u);d||(d=new zw(nI.FAILURE_THRESHOLD,W$),this.toolCircuitBreakers.set(u,d));let m=this.toolExecutionMetrics.get(e);return m||(m={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(e,m)),m.totalExecutions++,{finalOptions:i,startMemory:c,circuitBreaker:d,breakerKey:u,metrics:m}}async runPreparedToolExecution(e,t,n,o,s){let i=0;try{te.debug(`[${o.functionTag}] Executing tool: ${e}`,{toolName:e,params:t,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});let a=await n.circuitBreaker.execute(async()=>iY(async()=>ke(this.executeToolInternal(e,t,n.finalOptions,o.hitlState),n.finalOptions.timeout,ae.toolTimeout(e,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:s2,onRetry:(c,l)=>{i=c,te.warn(`[${o.functionTag}] Retrying tool execution (attempt ${c})`,{toolName:e,error:l.message,attempt:c})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(e,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(e,t,a,n,o,s)}}async handleSuccessfulToolExecution(e,t,n,o,s){let i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;let{MemoryManager:a}=await Promise.resolve().then(()=>(kC(),CC)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&te.warn(`Tool '${e}' used excessive memory: ${l}MB`,{toolName:e,memoryDelta:l,executionTime:i}),te.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:e,executionTime:i,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});let u=t&&typeof t=="object"?t:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,f=d?m?.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${e} returned isError:true`)})}catch{}te.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:e,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});let h=Wwr(f??"Unknown error"),y=`[TOOL_ERROR: ${e} failed (${h})] `;if(u&&Array.isArray(m)){let T=m.map(w=>({...w}));for(let w of T)if(w.type==="text"&&w.text){w.text=y+w.text;break}u.content=T}s.setAttribute("tool.error.message",(f??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",h),s.setStatus({code:he.ERROR,message:`MCP tool returned isError: ${(f??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;let x=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=x>1?(n.metrics.averageExecutionTime*x-i)/(x-1):0;let b=Kwr(h);n.metrics.errorCategories[b]=(n.metrics.errorCategories[b]||0)+1}return this.emitToolEndEvent(e,o.executionStartTime,!d,t,d&&f?new Error(f):void 0),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),t}async handleFailedToolExecution(e,t,n,o,s,i){o.metrics.failedExecutions++;let a=Date.now()-s.executionStartTime;if(n instanceof ic)return te.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${e}`,{toolName:e,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${e} (state=${n.breakerState}, failures=${n.failureCount})`)),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:he.ERROR,message:`Circuit breaker open for ${e}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let c;if(n instanceof be)c=n;else if(n instanceof Error)if(n.message.includes("timeout"))c=ae.toolTimeout(e,o.finalOptions.timeout);else if(n.message.includes("not found")){let u=await this.getAllAvailableTools();c=ae.toolNotFound(e,TRe(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?c=ae.invalidParameters(e,n,t):n.message.includes("network")||n.message.includes("connection")?c=ae.networkError(e,n):c=ae.toolExecutionFailed(e,n);else c=ae.toolExecutionFailed(e,new Error(String(n)));let l=c.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,c),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",c),c=new be({...c,context:{...c.context,executionTime:a,params:t,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),aY(c),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(c),i.setStatus({code:he.ERROR,message:c.message}),c}async executeToolInternal(e,t,n,o){let s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(e),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,c=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:t,__ctx:n.authContext??this.toolExecutionContext}:t;if(a&&c){let m=c.getCachedResult(e,l);if(m!==void 0)return g.debug(`[${s}] Cache HIT for tool: ${e}`),m}let u=async m=>{if(this.mcpToolMiddlewares.length===0)return m();let f=0,h=async()=>{if(f<this.mcpToolMiddlewares.length){let y=this.mcpToolMiddlewares[f++];return y({name:e,description:"",inputSchema:{},annotations:i,execute:async()=>({})},t,{toolMeta:{name:e,annotations:i}},h)}return m()};return await h()},d=async()=>{let m=this.externalServerManager.getAllTools(),f=m.filter(y=>y.name===e&&y.isAvailable),h;if(f.length>1&&this.mcpToolRouter)try{let y={name:e,description:f[0].description??"",serverId:f[0].serverId,inputSchema:{}},x=this.mcpToolRouter.route(y);h=f.find(b=>b.serverId===x.serverId)||f[0],g.debug(`[${s}] Router selected server: ${x.serverId}`,{strategy:x.strategy,confidence:x.confidence})}catch(y){g.warn(`[${s}] Router failed, falling back to first match`,{error:y}),h=f[0]}else h=f[0];if(g.debug(`[${s}] External MCP tool search:`,{toolName:e,externalToolsCount:m.length,foundTool:!!h,isAvailable:h?.isAvailable,serverId:h?.serverId}),h&&h.isAvailable)try{te.debug(`[${s}] Executing external MCP tool: ${e} from ${h.serverId}`);let y=await this.externalServerManager.executeTool(h.serverId,e,t,{timeout:n.timeout});return g.debug(`[${s}] External MCP tool execution successful:`,{toolName:e,serverId:h.serverId,resultType:typeof y}),y}catch(y){throw g.error(`[${s}] External MCP tool execution failed:`,{toolName:e,serverId:h.serverId,error:y instanceof Error?y.message:String(y)}),ae.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)),h.serverId)}try{let y=this.toolExecutionContext||{},x=n.authContext||{},b={...y,...x,hitlState:o};g.debug("[Using merged context for unified registry tool:",{toolName:e,storedContextKeys:Object.keys(y),finalContextKeys:Object.keys(b)});let T=await this.toolRegistry.executeTool(e,t,b);if(T&&typeof T=="object"&&"success"in T&&T.success===!1){let w=T.error||"Tool execution failed",_=new Error(w);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",_)}return T}catch(y){let x=y instanceof Error?y:new Error(String(y));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",x),y instanceof Error&&y.message.includes("not found")){let b=await this.getAllAvailableTools();throw ae.toolNotFound(e,b.map(T=>T.name))}throw ae.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)))}};try{let m=await u(d);return a&&c&&m!==void 0&&(c.cacheResult(e,l,m),g.debug(`[${s}] Cached result for tool: ${e}`)),m}catch(m){let f=i?{name:e,description:"",annotations:i,execute:async()=>({})}:void 0;if(f&&zM(f)&&m instanceof Error&&s2(m)){g.debug(`[${s}] Tool ${e} is safe to retry, attempting once more`);try{let h=await u(d);return a&&c&&h!==void 0&&c.cacheResult(e,l,h),h}catch{}}throw m}}getToolAnnotationsForExecution(e){if(this.toolCache?.tools){let t=this.toolCache.tools.find(n=>n.name===e);if(t?.annotations)return t.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Tu({name:e,description:""})}invalidateToolCache(){this.toolCache=null,g.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return g.debug("Returning available tools from cache"),this.toolCache.tools;let e=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,t=Date.now(),n=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:e,timestamp:new Date().toISOString(),getAllToolsStartTime:t,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!Vr,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});let{MemoryManager:o}=await Promise.resolve().then(()=>(kC(),CC)),s=o.getMemoryUsageMB();try{let i=new Map,a=await this.toolRegistry.listTools();for(let y of a)if(!i.has(y.name)){let x=kI(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,x)}let c=this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0}));for(let y of c)if(!i.has(y.name)){let x=kI(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:ga({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let l=this.toolRegistry.getToolsByCategory("in-memory");for(let y of l)if(!i.has(y.name)){let x=kI(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,x)}let u=this.externalServerManager.getAllTools();for(let y of u)if(!i.has(y.name)){let x=kI(y,{category:ga({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let d=Array.from(i.values());te.debug("Tool discovery results",{mcpTools:a.length,customTools:c.length,inMemoryTools:l.length,externalMCPTools:u.length,total:d.length});let f=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(f>Xp.LOW_USAGE_MB&&(te.debug(`\u{1F50D} Tool listing used ${f}MB memory (large tool registry detected)`),d.length>FX.LARGE_TOOL_COLLECTION&&te.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(let y of d)y.annotations||(y.annotations=Tu({name:y.name,description:y.description||""}));let h=d;return this.toolCache={tools:h,timestamp:Date.now()},h}catch(i){return te.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(e){let{MemoryManager:t}=await Promise.resolve().then(()=>(kC(),CC)),n=t.getMemoryUsageMB();e?.quiet||te.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),e?.quiet||te.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);let{AIProviderFactory:o}=await Promise.resolve().then(()=>(ou(),s3)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(Ag(),IN)),i=["openai","bedrock","vertex","googleVertex","anthropic","azure","google-ai","huggingface","ollama","mistral","litellm"],a=Am(nl.DEFAULT_CONCURRENCY_LIMIT),c=i.map(m=>a(async()=>{let f=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()-f};if(m==="ollama")try{let T=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(ol.AUTH_MS)});if(!T.ok)throw new Error("Ollama service not responding");let w=await T.json(),_=w?.models;if(!Array.isArray(_))throw g.warn("Ollama API returned invalid models format in testProvider",{responseData:w,modelsType:typeof _}),new Error("Invalid models format from Ollama API");let C=_.filter(k=>k&&typeof k=="object"&&typeof k.name=="string");return C.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f,model:C[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-f}}catch(T){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:T instanceof Error?T.message:"Ollama service not running",responseTime:Date.now()-f}}let y=5e3,x=this.testProviderConnection(m),b=new Promise((T,w)=>{setTimeout(()=>w(new Error("Provider test timeout (5s)")),y)});return await Promise.race([x,b]),{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f}}catch(h){let y=h instanceof Error?h.message:String(h);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-f}}})),l=await Promise.all(c),d=t.getMemoryUsageMB().heapUsed-n.heapUsed;return!e?.quiet&&d>20&&te.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&t.forceGC(),l}async testProvider(e){try{return await this.testProviderConnection(e),!0}catch{return!1}}async testProviderConnection(e){let{AIProviderFactory:t}=await Promise.resolve().then(()=>(ou(),s3));await(await t.createProvider(e,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(e){let{getBestProvider:t}=await Promise.resolve().then(()=>(Ag(),IN));return t(e)}async getAvailableProviders(){let{getAvailableProviders:e}=await Promise.resolve().then(()=>(Ag(),IN));return e()}async isValidProvider(e){let{isValidProvider:t}=await Promise.resolve().then(()=>(Ag(),IN));return t(e)}async getMCPStatus(){try{await this.initializeMCP();let e=await this.toolRegistry.listTools(),t=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,c=t.connectedServers+o.length+s.length,l=e.length+t.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:c,autoDiscoveredCount:i.length,totalTools:l,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:t.connectedServers,externalMCPFailedCount:t.failedServers,externalMCPServers:n}}catch(e){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:e instanceof Error?e.message:String(e)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(e){try{if(e==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;let t=this.getInMemoryServers();if(t.has(e)){let o=t.get(e);return!!(o?.tools&&o.tools.length>0)}let n=this.externalServerManager.getServer(e);return n?n.status==="connected"&&n.client!==null:!1}catch(t){return te.error(`[NeuroLink] Error testing MCP server ${e}:`,t),!1}}async hasProviderEnvVars(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(fx(),TC));try{let n=await t.checkProviderHealth(e,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return g.warn(`Provider env var check failed for ${e}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(e,t={}){let{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(fx(),TC)),o=await n.checkProviderHealth(e,t);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(e={}){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(fx(),TC));return(await t.checkAllProvidersHealth(e)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){let{ProviderHealthChecker:e}=await Promise.resolve().then(()=>(fx(),TC)),t=await e.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=e.getHealthSummary(t),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(fx(),TC));t.clearHealthCache(e)}getToolExecutionMetrics(){let e={};for(let[t,n]of this.toolExecutionMetrics.entries())e[t]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return e}setModelAliasConfig(e){this.modelAliasConfig=e,g.info(`[ModelAlias] Configured ${Object.keys(e.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){let e={};for(let[t,n]of this.toolCircuitBreakers.entries())e[t]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return e}resetToolCircuitBreaker(e){this.toolCircuitBreakers.has(e)&&(this.toolCircuitBreakers.set(e,new zw(nI.FAILURE_THRESHOLD,W$)),te.info(`Circuit breaker reset for tool: ${e}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),te.info("All tool execution metrics cleared")}async getToolHealthReport(){let e={},t=0,n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(let i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(let i of o){let a=this.toolExecutionMetrics.get(i),c=`${s.get(i)||"unknown"}.${i}`,l=this.toolCircuitBreakers.get(c),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!l||l.getState()==="closed")&&u>=.8;d&&t++;let m=[],f=[];if(l&&l.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),f.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),f.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),f.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){let h=a.errorCategories;h.timeout>0&&(m.push(`Timeout errors: ${h.timeout}`),f.push("Consider increasing the tool timeout configuration")),h.validation>0&&(m.push(`Validation errors: ${h.validation}`),f.push("Review input schemas and parameter validation")),h.network>0&&(m.push(`Network errors: ${h.network}`),f.push("Check network connectivity and endpoint availability"))}e[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:l?.getState()||"closed",failureCount:l?.getFailureCount()||0},issues:m,recommendations:f}}return{totalTools:o.size,healthyTools:t,unhealthyTools:o.size-t,tools:e}}async ensureConversationMemoryInitialized(){try{let e=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(e){return g.error("Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e)}),!1}}async getConversationStats(){let e=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(e){let t=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new be({code:Ge.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});try{let n=await this.conversationMemory.buildContextMessages(e);return g.debug("Retrieved conversation history",{sessionId:e,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return g.error("Failed to retrieve conversation history",{sessionId:e,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(e){let t=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(e),await this.conversationMemory.clearSession(e)}async clearAllConversations(){let e=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async storeToolExecutions(e,t,n,o,s){let i=n&&n.length>0||o&&o.length>0;if(!i){g.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}let a=this.conversationMemory;try{await a.storeToolExecution(e,t,n,o,s)}catch(c){g.warn("Failed to store tool executions",{sessionId:e,userId:t,error:c instanceof Error?c.message:String(c)})}}isToolExecutionStorageAvailable(){let e=process.env.STORAGE_TYPE==="redis",t=this.conversationMemory&&this.conversationMemory.constructor.name==="RedisConversationMemoryManager";return!!(e&&t)}async getSessionMessages(e,t){let n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new be({code:Ge.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});return await this.conversationMemory.getSessionMessages(e,t)}async setSessionMessages(e,t,n){let o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new be({code:Ge.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});await this.conversationMemory.setSessionMessages(e,t,n)}async modifyLastAssistantMessage(e,t,n){let o=await this.getSessionMessages(e,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:t(o[s].content)},await this.setSessionMessages(e,o,n),!0;return!1}async addExternalMCPServer(e,t){this.invalidateToolCache();try{te.info(`[NeuroLink] Adding external MCP server: ${e}`,{command:t.command,transport:t.transport});let n=await this.externalServerManager.addServer(e,t);if(n.success){if(te.info(`[NeuroLink] External MCP server added successfully: ${e}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){let o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new mx({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(let s of o)this.mcpToolRouter.registerServer(s.id||e);g.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(e)}this.emitter.emit("externalMCP:serverAdded",{serverId:e,serverName:t.name||e,config:t,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else te.error(`[NeuroLink] Failed to add external MCP server: ${e}`,{error:n.error});return n}catch(n){throw te.error(`[NeuroLink] Error adding external MCP server: ${e}`,n),n}}async removeExternalMCPServer(e){this.invalidateToolCache();try{te.info(`[NeuroLink] Removing external MCP server: ${e}`);let t=this.externalServerManager.getServerName(e),n=await this.externalServerManager.removeServer(e);return n.success?(te.info(`[NeuroLink] External MCP server removed successfully: ${e}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:e,serverName:t,timestamp:Date.now()})):te.error(`[NeuroLink] Failed to remove external MCP server: ${e}`,{error:n.error}),n}catch(t){throw te.error(`[NeuroLink] Error removing external MCP server: ${e}`,t),t}}listExternalMCPServers(){let e=this.externalServerManager.getServerStatuses(),t=this.externalServerManager.listServers();return e.map(n=>{let o=t.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(e){return this.externalServerManager.getServer(e)}async executeExternalMCPTool(e,t,n,o){try{te.debug(`[NeuroLink] Executing external MCP tool: ${t} on ${e}`);let s=this.getToolAnnotationsForExecution(t),i=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,a={__serverId:e,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}};if(i&&this.mcpToolResultCache){let l=this.mcpToolResultCache.getCachedResult(t,a);if(l!==void 0)return te.debug(`[NeuroLink] Tool result cache HIT: ${t} on ${e}`),l}let c=await this.externalServerManager.executeTool(e,t,n,o);return i&&this.mcpToolResultCache&&this.mcpToolResultCache.cacheResult(t,a,c),te.debug(`[NeuroLink] External MCP tool executed successfully: ${t}`),c}catch(s){throw te.error(`[NeuroLink] External MCP tool execution failed: ${t}`,s),s}}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(e){return this.externalServerManager.getServerTools(e)}async testExternalMCPConnection(e){try{let{MCPClientFactory:t}=await ke(Promise.resolve().then(()=>(tq(),dGe)),1e4),n=await t.testConnection(e,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{te.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),te.info("[NeuroLink] All external MCP servers shut down successfully")}catch(e){throw te.error("[NeuroLink] Error shutting down external MCP servers:",e),e}}async getElicitationManager(){return(await ke(Promise.resolve().then(()=>(Pue(),GHe)),1e4)).globalElicitationManager}async registerElicitationHandler(e){(await this.getElicitationManager()).registerHandler(e)}async getMultiServerManager(){return(await ke(Promise.resolve().then(()=>(TH(),Tze)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){let e=await ke(Promise.resolve().then(()=>(SH(),Sze)),1e4);return new e.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await ke(Promise.resolve().then(()=>(Due(),VHe)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(e,t){return(await ke(Promise.resolve().then(()=>(p3(),$ue)),1e4)).exposeAgentAsTool(e,t)}async exposeWorkflowAsTool(e,t){return(await ke(Promise.resolve().then(()=>(p3(),$ue)),1e4)).exposeWorkflowAsTool(e,t)}async getToolIntegrationManager(){return(await ke(Promise.resolve().then(()=>(Wue(),HHe)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(e,t={}){let n=await ke(Promise.resolve().then(()=>(h3(),rde)),1e4),o=e.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,t)}async convertToolsFromMCPFormat(e,t={}){return(await ke(Promise.resolve().then(()=>(h3(),rde)),1e4)).batchConvertToNeuroLink(e,t)}async getToolAnnotations(e){let{inferAnnotations:t,mergeAnnotations:n,getAnnotationSummary:o}=await ke(Promise.resolve().then(()=>(G0(),bze)),1e4),s=this.toolRegistry.getToolInfo(e);if(!s)return null;let i=s.tool.annotations,a=t({name:s.tool.name,description:s.tool.description??""}),c=n(a,i);return{annotations:c,summary:o(c)}}convertExternalMCPToolsToAISDKFormat(){let e=this.externalServerManager.getAllTools(),t={};for(let n of e)if(n.isAvailable){let o={description:n.description,execute:async s=>{try{te.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});let i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return te.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw te.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};t[n.name]=o,te.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return te.info(`[NeuroLink] Converted ${Object.keys(t).length} external MCP tools to AI SDK format`),t}convertJSONSchemaToAISDKFormat(e){}unregisterExternalMCPToolsFromRegistry(e){try{let t=this.externalServerManager.getServerTools(e);for(let n of t)this.toolRegistry.removeTool(n.name),te.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(t){te.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${e}:`,t)}}unregisterExternalMCPToolFromRegistry(e){try{this.toolRegistry.removeTool(e),te.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${e}`)}catch(t){te.error(`[NeuroLink] Failed to unregister external MCP tool ${e} from registry:`,t)}}async lazyInitializeConversationMemory(e,t,n){try{let{initializeConversationMemory:o}=await eqe().then(()=>QHe),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw g.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{let e=this.externalServerManager.getAllTools();for(let t of e)this.toolRegistry.removeTool(t.name);te.debug(`[NeuroLink] Unregistered ${e.length} external MCP tools from main registry`)}catch(e){te.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",e)}}async createEvaluationPipeline(e){let{EvaluationPipeline:t,getPreset:n}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4)),o;typeof e=="string"?o=n(e):o=e;let s=new t(o);return await ke(s.initialize(),3e4,ae.evaluationTimeout("pipeline initialization",3e4)),g.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(e,t){let{EvaluationPipeline:n,getPreset:o}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4)),s;if(t?.pipeline&&t?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(t?.scorers&&t.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");t?.pipeline?s={...o(t.pipeline)}:t?.scorers&&t.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:t.scorers.map(l=>({id:l})),executionMode:t.executionMode??"parallel",passThreshold:t.passThreshold??.7}:s=o("quality"),t?.passThreshold!==void 0&&(s.passThreshold=t.passThreshold),t?.executionMode!==void 0&&(s.executionMode=t.executionMode);let i=new n(s);await ke(i.initialize(),3e4,ae.evaluationTimeout("pipeline initialization",3e4));let a=t?.timeoutMs??6e4,c=await ke(i.execute(e,{correlationId:t?.correlationId}),a,ae.evaluationTimeout("pipeline execution",a));return g.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:c.overallScore,passed:c.passed,scorerCount:c.scores.length}),c}async score(e,t,n){let{ScorerRegistry:o}=await ke(Promise.resolve().then(()=>(O2(),jY)),1e4,ae.evaluationTimeout("scorer module load",1e4));await ke(o.registerBuiltInScorers(),3e4,ae.evaluationTimeout("scorer bootstrap",3e4));let s=await ke(o.getScorer(e,n),3e4,ae.evaluationTimeout(`scorer load: ${e}`,3e4));if(!s)throw ae.scorerNotFound(e);let i=s.validateInput(t);if(!i.valid)throw ae.evaluationValidationFailed(e,i.errors);let a=await ke(s.score(t),6e4,ae.evaluationTimeout("scorer execution",6e4));return g.debug("[NeuroLink] Scoring completed",{scorerId:e,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(e){let{ScorerRegistry:t}=await ke(Promise.resolve().then(()=>(O2(),jY)),1e4,ae.evaluationTimeout("scorer module load",1e4));await ke(t.registerBuiltInScorers(),3e4,ae.evaluationTimeout("scorer bootstrap",3e4));let n=t.list();return e?.category&&(n=n.filter(o=>o.category===e.category)),e?.type&&(n=n.filter(o=>o.type===e.type)),n}async getEvaluationPresets(){let{getPresetNames:e}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4));return e()}async getEvaluationPreset(e){let{getPreset:t}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4));return t(e)}async dispose(){g.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();let e=[];try{try{g.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await RO(),await AO(),g.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`OpenTelemetry shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down OpenTelemetry:",t)}if(this.externalServerManager)try{g.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),g.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`External server shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down external MCP servers:",t)}if(this.emitter)try{g.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),g.clearEventEmitter(),g.debug("[NeuroLink] Event listeners removed successfully")}catch(t){let n=t instanceof Error?t:new Error(`Event emitter cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error removing event listeners:",t)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{g.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),g.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Circuit breaker cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing circuit breakers:",t)}try{g.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],g.debug("[NeuroLink] Maps and caches cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Cache cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing caches:",t)}if(this._taskManager)try{g.debug("[NeuroLink] Shutting down TaskManager..."),await ke(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(t){g.warn("[NeuroLink] TaskManager shutdown error:",t)}finally{this._taskManager=void 0}try{g.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,g.debug("[NeuroLink] Initialization state reset successfully")}catch(t){let n=t instanceof Error?t:new Error(`State reset error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error resetting state:",t)}e.length===0?g.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):g.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${e.length} errors`,{errors:e.map(t=>t.message)})}catch(t){throw g.error("[NeuroLink] Critical error during disposal:",t),t}}getToolRegistry(){return this.toolRegistry}async compactSession(e,t){if(!this.conversationMemory)return null;let n=await this.conversationMemory.buildContextMessages(e);if(!n||n.length===0)return null;let o=new nx({...t,summarizationProvider:t?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:t?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=Bc({provider:t?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&$0(a.messages),a}async getContextStats(e,t,n){if(!this.conversationMemory)return null;let o=await this.conversationMemory.buildContextMessages(e);if(!o||o.length===0)return null;let s=Bc({provider:t||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(e,t,n){if(!this.conversationMemory)return!1;let o=this.conversationMemory.getSession?.(e);return o?Bc({provider:t||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(e){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(e)}async initializeAuthProviderFromConfig(e){let t,n;if("authenticateToken"in e&&typeof e.authenticateToken=="function")t=e,n=t.type;else if("provider"in e)t=e.provider,n=t.type;else{let o=e,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(KN(),tqe));t=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=t,g.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:t.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;let e=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(e),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===e)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(e){let{globalAuthContext:t}=await Promise.resolve().then(()=>(pC(),uq));t.set(e),g.debug("Auth context set",{userId:e.user.id,provider:e.provider,sessionId:e.session?.id})}async getAuthContext(){let{getAuthContext:e}=await Promise.resolve().then(()=>(pC(),uq));return e()}async clearAuthContext(){let{globalAuthContext:e}=await Promise.resolve().then(()=>(pC(),uq)),t=e.get()?.user.id;e.clear(),t&&g.debug(`Auth context cleared for user: ${t}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(e,t){return{requestContext:t||{},signal:e}}async resolveDynamicOptions(e){let t=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(t.some(s=>typeof e[s]=="function")||typeof e.tools=="function"))return;let o=e.dynamicContext;await this.resolveDynamicFields(e,t,o)}async resolveDynamicFields(e,t,n){let o=this.buildResolutionContext(e.abortSignal,n);if(g.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(t.map(async s=>{if(typeof e[s]=="function"){let i=await ple(e[s],o);e[s]=i.value,g.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof e.tools=="function"){let s=await ple(e.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);e.enabledToolNames=s.value,delete e.tools}}},rqe=new NT,Ywr=rqe});var oqe={};J(oqe,{VoyageProvider:()=>S3,default:()=>eEr});var Zwr,nqe,Qwr,dde,S3,eEr,sqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();lt();q();Gn();Zwr="https://api.voyageai.com/v1",nqe=6e4,Qwr=()=>nr(S1e()),dde=()=>or("VOYAGE_MODEL","voyage-3.5"),S3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"voyage",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:Qwr(),this.baseURL=o?.baseURL??process.env.VOYAGE_BASE_URL??Zwr,this.proxyFetch=et(),g.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return dde()}supportsTools(){return!1}getDefaultEmbeddingModel(){return dde()}getAISDKModel(){throw new Ee("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 Ee("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new ct("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new kt(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new Ee(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Ee("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];let n=128,o=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),a=await this.callEmbeddings(i,t);o.push(...a)}return o}async callEmbeddings(e,t){let n=t??this.modelName,o;try{o=await ke(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n})}),nqe,new Ee(`Voyage embeddings request timed out after ${nqe/1e3}s`,"voyage"))}catch(a){throw a instanceof Ee?a:this.formatProviderError(a)}if(!o.ok){let a=await o.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${o.status} \u2014 ${a}`))}let s=await o.json();if(!s.data||s.data.length===0)throw new Ee("Voyage embeddings response missing data","voyage");if(s.data.length!==e.length)throw new Ee(`Voyage embeddings response count mismatch: expected ${e.length}, got ${s.data.length}`,"voyage");let i=s.data.slice().sort((a,c)=>a.index-c.index);for(let a=0;a<i.length;a++)if(i[a].index!==a)throw new Ee(`Voyage embeddings response has unexpected index ordering: position ${a} has index ${i[a].index}`,"voyage");return i.map(a=>a.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:dde(),baseURL:this.baseURL}}},eEr=S3});var iqe={};J(iqe,{JinaProvider:()=>E3,default:()=>nEr});var tEr,w3,rEr,pde,E3,nEr,aqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();q();Gn();tEr="https://api.jina.ai/v1",w3=6e4,rEr=()=>nr(w1e()),pde=()=>or("JINA_MODEL","jina-embeddings-v3"),E3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"jina",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:rEr(),this.baseURL=o?.baseURL??process.env.JINA_BASE_URL??tEr,this.proxyFetch=et(),g.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return pde()}supportsTools(){return!1}getDefaultEmbeddingModel(){return pde()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new ct("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new kt(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new Ee(`Jina AI error: ${t}`,"jina")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Error("Jina AI returned no embedding for the provided text");return n[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,n={}){if(t.length===0)return[];let o=n.model??"jina-reranker-v2-base-multilingual",s=n.credentials,i=s?.apiKey?.trim()||this.apiKey,a=s?.baseURL||this.baseURL,c=new AbortController,l=setTimeout(()=>c.abort(),w3),u;try{u=await this.proxyFetch(`${a}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({model:o,query:e,documents:t,top_n:n.topN??t.length}),signal:c.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${w3/1e3}s`)):this.formatProviderError(m)}finally{clearTimeout(l)}if(!u.ok){let m=await u.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${u.status} \u2014 ${m}`))}return((await u.json()).results??[]).map(m=>({index:m.index,score:m.relevance_score,document:t[m.index]??m.document?.text??""}))}async callEmbeddings(e,t,n){let o=t??this.modelName,s=n?.apiKey?.trim()||this.apiKey,i=n?.baseURL||this.baseURL,a=new AbortController,c=setTimeout(()=>a.abort(),w3),l;try{l=await this.proxyFetch(`${i}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:o}),signal:a.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${w3/1e3}s`)):this.formatProviderError(m)}finally{clearTimeout(c)}if(!l.ok){let m=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${m}`))}let u=await l.json();if(!u.data||u.data.length===0)throw new Error("Jina embeddings response missing data");if(u.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${u.data.length}`);let d=u.data.slice().sort((m,f)=>m.index-f.index);for(let m=0;m<d.length;m++)if(d[m].index!==m)throw new Error(`Jina embeddings response has unexpected index ordering: position ${m} has index ${d[m].index}`);return d.map(m=>m.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:pde(),baseURL:this.baseURL}}},nEr=E3});var uqe={};J(uqe,{StabilityProvider:()=>_3,default:()=>iEr});var oEr,cqe,sEr,lqe,_3,iEr,dqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();q();Gn();oEr="https://api.stability.ai",cqe=12e4,sEr=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,lqe=()=>or("STABILITY_MODEL","stable-image-ultra"),_3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"stability",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:sEr(),this.baseURL=o?.baseURL??process.env.STABILITY_BASE_URL??oEr,this.proxyFetch=et(),g.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return lqe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new ct("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new Ee("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new kt(`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 Ee(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.stability,o=n?.apiKey?.trim()||this.apiKey;if(!o)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");let s=o,i=n?.baseURL||this.baseURL,a=e.prompt??e.input?.text??"";if(!a.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");let c=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,u=new FormData;u.append("prompt",a),u.append("output_format","png"),l.aspectRatio&&u.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&u.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&u.append("model",this.modelName),l.seed!==void 0&&u.append("seed",String(l.seed));let d=new AbortController,m=setTimeout(()=>d.abort(),cqe),f;try{f=await this.proxyFetch(`${i}/v2beta/stable-image/generate/${c}`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/json"},body:u,signal:d.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${cqe/1e3}s`)):this.formatProviderError(x)}finally{clearTimeout(m)}if(!f.ok){let x=await f.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${f.status} \u2014 ${x}`))}let h=await f.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);let y=Date.now()-t;return g.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:lqe(),baseURL:this.baseURL}}},iEr=_3});var fqe={};J(fqe,{IdeogramProvider:()=>C3,default:()=>lEr});var aEr,pqe,cEr,mqe,C3,lEr,gqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();q();Gn();aEr="https://api.ideogram.ai",pqe=12e4,cEr=()=>nr(E1e()),mqe=()=>or("IDEOGRAM_MODEL","V_3"),C3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"ideogram",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:cEr(),this.baseURL=o?.baseURL??process.env.IDEOGRAM_BASE_URL??aEr,this.proxyFetch=et(),g.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return mqe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new ct("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new Ee("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new Ee(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.ideogram,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");let a=e,c={prompt:i,model:this.modelName,magic_prompt:a.magicPrompt??"AUTO"};a.aspectRatio&&(c.aspect_ratio=a.aspectRatio),a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.seed!==void 0&&(c.seed=a.seed),a.style&&(c.style_type=a.style);let l=new AbortController,u=setTimeout(()=>l.abort(),pqe),d;try{d=await this.proxyFetch(`${s}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":o,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(_){throw _ instanceof Error&&_.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${pqe/1e3}s`)):this.formatProviderError(_)}finally{clearTimeout(u)}if(!d.ok){let _=await d.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${d.status} \u2014 ${_}`))}let f=(await d.json()).data?.[0]?.url;if(!f)throw new Error("Ideogram returned no image URL");let h=new AbortController,y=setTimeout(()=>h.abort(),6e4),x;try{x=await this.proxyFetch(f,{signal:h.signal})}catch(_){throw _ instanceof Error&&_.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:_}):_}finally{clearTimeout(y)}if(!x.ok)throw new Error(`Failed to download Ideogram image: ${x.status}`);let b=Buffer.from(await x.arrayBuffer()),T=b.toString("base64"),w=Date.now()-t;return g.info(`[IdeogramProvider] Generated image (${b.length} bytes) in ${w}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:T}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:mqe(),baseURL:this.baseURL}}},lEr=C3});function xd(r){let e=(r?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return e?{apiToken:e,baseUrl:(r?.baseUrl??process.env.REPLICATE_BASE_URL??uEr).replace(/\/$/,"")}:null}var uEr,JN=E(()=>{"use strict";uEr="https://api.replicate.com"});function pEr(r,e,t){return new tee({connect:{lookup:(n,o,s)=>{if(n.toLowerCase()!==r.toLowerCase()){s(new Error(`safeFetch: refusing to resolve "${n}" \u2014 expected "${r}"`),"",0);return}s(null,e,t)}}})}async function bx(r,e){let{url:t,ip:n,family:o}=await B1e(r),i=new URL(t).hostname.replace(/^\[|\]$/g,""),a=pEr(i,n,o),c=new AbortController,l=setTimeout(()=>c.abort(),e.timeoutMs??dEr),u=e.signal?AbortSignal.any([e.signal,c.signal]):c.signal,d;try{d=await eee(t,{method:"GET",signal:u,redirect:"manual",dispatcher:a})}finally{clearTimeout(l),a.close().catch(()=>{})}if(d.status>=300&&d.status<400)throw new Error(`safeDownload(${e.label}): refused to follow redirect ${d.status} \u2192 ${d.headers.get("location")??"<no-location>"} (for ${r})`);if(!d.ok)throw new Error(`safeDownload(${e.label}) failed: HTTP ${d.status} for ${r}`);return Oa(d,e.maxBytes,e.label)}var dEr,XN=E(()=>{"use strict";fE();ag();qy();dEr=6e4});async function gEr(r,e){let t=r.baseUrl??"https://api.replicate.com",[n,o]=e.model.split(":",2),s=o?`${t}/v1/predictions`:`${t}/v1/models/${n}/predictions`,i=o?{version:o,input:e.input}:{input:e.input};e.webhook&&(i.webhook=e.webhook),e.webhookEventsFilter&&e.webhookEventsFilter.length>0&&(i.webhook_events_filter=e.webhookEventsFilter);let a=new AbortController,c=setTimeout(()=>a.abort(),YN),l;try{l=await fetch(s,{method:"POST",headers:{Authorization:`Token ${r.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(i),signal:a.signal})}catch(u){throw u instanceof be?u:u instanceof Error&&u.name==="AbortError"?new be({code:Ge.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${YN/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:u}):u}finally{clearTimeout(c)}if(!l.ok){let u=await l.text();throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${l.status} \u2014 ${Ms(u,500)}`,category:"network",severity:"high",retriable:l.status>=500})}return await l.json()}async function hEr(r,e,t={}){let n=r.baseUrl??"https://api.replicate.com",o=Date.now(),s=t.timeoutMs??fEr,i=t.pollIntervalMs??mEr;for(;Date.now()-o<s;){if(t.abortSignal?.aborted)throw new be({code:Ge.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});let a=new AbortController,c=setTimeout(()=>a.abort(),YN),l=()=>a.abort();t.abortSignal?.addEventListener("abort",l,{once:!0});let u;try{u=await fetch(`${n}/v1/predictions/${e}`,{method:"GET",headers:{Authorization:`Token ${r.apiToken}`},signal:a.signal})}catch(m){throw m instanceof be?m:m instanceof Error&&m.name==="AbortError"?t.abortSignal?.aborted?new be({code:Ge.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:m}):new be({code:Ge.OPERATION_ABORTED,message:`Replicate poll request timed out after ${YN/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:m}):m}finally{t.abortSignal?.removeEventListener("abort",l),clearTimeout(c)}if(!u.ok){let m=await u.text();throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${u.status} \u2014 ${Ms(m,500)}`,category:"network",severity:"high",retriable:u.status>=500})}let d=await u.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((m,f)=>{let h=()=>{clearTimeout(y),f(new be({code:Ge.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},y=setTimeout(()=>{t.abortSignal?.removeEventListener("abort",h),m()},i);t.abortSignal?.addEventListener("abort",h,{once:!0})})}throw new be({code:Ge.OPERATION_ABORTED,message:`Replicate prediction ${e} did not complete within ${Math.round(s/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function Ng(r,e,t={}){let n=await gEr(r,e);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return hEr(r,n.id,t)}async function Tx(r,e=268435456){let t=r.output,n=Array.isArray(t)?t[0]:t;if(typeof n!="string")throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${r.id} output is not a URL: ${typeof t}`,category:"execution",severity:"high",retriable:!1});try{let o=await bx(n,{maxBytes:e,label:`Replicate prediction ${r.id}`,timeoutMs:YN});return g.debug(`[Replicate] Downloaded prediction ${r.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof be)throw o;let s=o instanceof Error?o.message:String(o);throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${s} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var YN,mEr,fEr,ZN=E(()=>{"use strict";q();lt();Un();XN();YN=9e4,mEr=2e3,fEr=5*6e4});var yqe={};J(yqe,{ReplicateProvider:()=>k3,default:()=>vEr});function yEr(r){let e=r,t=e.prompt??e.input?.text??"",n=e.systemPrompt;return n?`${n}
|
|
2135
|
+
IMPORTANT: You have a tool called "${c.toolName}" that searches through`,`${c.filesLoaded} loaded document(s) containing ${c.chunksIndexed} indexed chunks.`,`ALWAYS use the "${c.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");e.systemPrompt=(e.systemPrompt||"")+l,g.info("[RAG] Tool injected into stream()",{toolName:c.toolName,filesLoaded:c.filesLoaded,chunksIndexed:c.chunksIndexed})}catch(a){g.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}let s=SVe(e),i=wVe(e);if(e.input?.text){let{toolResults:a,enhancedPrompt:c}=await this.detectAndExecuteTools(e.input.text,void 0);c!==e.input.text&&(i.input.text=c)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(e){if((e.provider==="ollama"||e.provider?.toLowerCase().includes("ollama"))&&!e.disableTools){let{ModelConfigurationManager:t}=await Promise.resolve().then(()=>(Dy(),oDe)),s=t.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=e.model;s.length>0&&i&&(s.some(c=>i.toLowerCase().includes(c.toLowerCase()))||(e.disableTools=!0,g.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:e.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){let e=[],t=0,n=(d,m)=>{e.push({type:d,seq:t++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{let m=d[0];n("response:chunk",{content:m})},s=(...d)=>{let m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{let m=d[0],f=m.toolName??m.tool,h=m.responseTime??m.duration,y=m.success??(m.error!==void 0?!1:void 0),x={...m,toolName:f,...h!==void 0?{responseTime:h}:{},...y!==void 0?{success:y}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",x),x.result&&x.result.uiComponent===!0&&n("ui-component",{toolName:f,componentData:x.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...h!==void 0?{responseTime:h}:{}})},a=(...d)=>{n("ui-component",d[0])},c=(...d)=>{n("hitl:confirmation-request",d[0])},l=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",c),this.emitter.on("hitl:confirmation-response",l),{eventSequence:e,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",c),this.emitter.off("hitl:confirmation-response",l)}}}async*handleStreamFallback(e,t,n,o,s,i){e.fallbackAttempted=!0;let a="Stream completed with 0 chunks (possible guardrails block)";e.error=a;try{let h=this._metricsTraceContext,y=le.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:h?.traceId,parentSpanId:h?.parentSpanId});y=le.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),Pe().recordSpan(y)}catch{}let c=o.fallbackProvider?.trim()||void 0,l=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,m=bC.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),f={...m,provider:c??u??m.provider,model:l??d??m.model};g.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:f.provider,fallbackModel:f.model,fallbackSource:c||l?"options":u||d?"env":"model_config",reason:a});try{let h=await Vr.createProvider(f.provider,f.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));h.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(C,k)=>this.executeTool(C,k,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");let y=o.conversationMessages!==void 0?o.conversationMessages:await Tg(this.conversationMemory,{prompt:o.input.text,context:o.context}),x=await h.stream({...o,model:f.model,conversationMessages:y}),b=x.toolCalls??[],T=x.toolResults??[];(b.length>0||T.length>0)&&(t.toolCalls=b,t.toolResults=T,t.finishReason=x.finishReason??t.finishReason);let w=0,_=0;for await(let C of x.stream){w++;let k=C!==null&&typeof C=="object"&&"metadata"in C&&C.metadata?.noOutput===!0,I=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");!k&&(I||R)&&_++,C&&"content"in C&&typeof C.content=="string"&&(i(C.content),this.emitter.emit("response:chunk",C.content)),yield C}if(_===0&&b.length===0&&T.length===0)throw new Error(`Fallback provider ${f.provider} also returned 0 real output chunks (chunkCount=${w}, sentinel-only or empty)`);e.fallbackProvider=f.provider,e.fallbackModel=f.model,e.guardrailsBlocked=!0}catch(h){let y=h instanceof Error?h.message:String(h);throw e.error=`${a}; Fallback failed: ${y}`,g.error("Fallback provider failed",{fallbackProvider:f.provider,error:y}),h}}async storeStreamConversationMemory(e){let{enhancedOptions:t,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=e;g.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:JSON.stringify(t),sessionId:t.context?.sessionId});let c=a.some(l=>l.type==="tool:start"||l.type==="tool:end");if(!s.trim()&&!c){g.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:t.context?.sessionId});return}if(g.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:JSON.stringify(t),sessionId:t.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&t.context?.sessionId){let l=t.context?.sessionId,u=t.context?.userId,d;t.model&&(d={provider:n,model:t.model});let m=Date.now();try{await this.conversationMemory.storeConversationTurn({sessionId:l,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:t.enableSummarization,events:a.length>0?a:void 0,requestId:t.context?.requestId}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),g.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:l,eventCount:a.length,eventTypes:[...new Set(a.map(f=>f.type))]})}catch(f){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,f instanceof Error?f.message:String(f)),g.warn("Failed to store stream conversation turn",{error:f instanceof Error?f.message:String(f)})}}this.shouldWriteMemory(t.memory,t.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),t.context?.userId,t.memory?.additionalUsers,t.context)}async validateStreamInput(e){let t=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:t.toString(),message:"Starting comprehensive input validation process"});let n=typeof e?.input?.text=="string"&&e.input.text.trim().length>0,o=!!(e?.input?.audio&&e.input.audio.frames&&typeof e.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(e?.stt?.enabled&&e?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(e,t){this.emitter.emit("stream:start",{provider:e.provider||"auto",timestamp:t}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${e.provider||"auto"} stream...`)}async createMCPStream(e){let t=await gx(e.provider),n=await Vr.createProvider(t,e.model,!e.disableTools,this,e.region,this.resolveCredentials(e.credentials));n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(h,y)=>this.executeTool(h,y,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,e);let s=e.skipToolPromptInjection?e.systemPrompt||"":this.createToolAwareSystemPrompt(e.systemPrompt,o),i=e.conversationMessages!==void 0,a=i?e.conversationMessages:await Tg(this.conversationMemory,{...e,prompt:e.input.text,context:e.context});e.conversationMessages=a;let c=a,l=Bc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o}),u=c?.length||0,d=this.getCompactionSessionId(e),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:t,model:e.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Pl(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${l.estimatedInputTokens} tokens, budget: ${l.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:l.estimatedInputTokens,availableTokens:l.availableInputTokens,stagesUsed:[],breakdown:l.breakdown})}if(l.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){let y=await new nx({provider:t,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(c,l.availableInputTokens,this.conversationMemoryConfig?.conversationMemory,e.context?.requestId);y.compacted&&(c=$0(y.messages).messages,e.conversationMessages=c,this.lastCompactionMessageCount.set(d,c.length));let x=Bc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!x.withinBudget){g.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:x.estimatedInputTokens,availableTokens:x.availableInputTokens,overagePercent:Math.round((x.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:x.estimatedInputTokens,budget:x.availableInputTokens,provider:t,model:e.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}c=mH(c,x.availableInputTokens,x.breakdown,t),e.conversationMessages=c;let b=Bc({provider:t,model:e.model,maxTokens:e.maxTokens,systemPrompt:s,conversationMessages:c,currentPrompt:e.input.text,toolDefinitions:o});if(!b.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:b.estimatedInputTokens,budget:b.availableInputTokens,provider:t,model:e.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Pl(`Stream context exceeds model budget after all compaction stages. Estimated: ${b.estimatedInputTokens} tokens, Budget: ${b.availableInputTokens} tokens.`,{estimatedTokens:b.estimatedInputTokens,availableTokens:b.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:b.breakdown})}}}if(this.modelPool){let h=this.modelPool,y=h.maxAttempts,x=new Set,b=null;for(let T=0;T<y;T++){if(e.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");let w=h.selectNext(x);if(!w)break;x.add(h.memberKey(w));let _=w.provider,C=w.model??void 0,k=w.region??void 0;g.debug(`[createMCPStream] ModelPool: attempting member ${_}`,{model:C,attempt:T});try{let I=await Vr.createProvider(_,C,!e.disableTools,this,k,this.resolveCredentials(e.credentials));I.setTraceContext(this._metricsTraceContext),I.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(D,j)=>this.executeTool(D,j,{disableToolCache:e.disableToolCache})},"NeuroLink.createMCPStream");let R=await I.stream({...e,provider:_,model:C,region:k,systemPrompt:s,conversationMessages:c});g.debug("[createMCPStream] ModelPool stream handle obtained",{provider:_});let A=w;return{stream:(async function*(){try{yield*R.stream,h.recordSuccess(A)}catch(D){throw h.recordFailure(A,xx(D)),D}})(),provider:_,usage:R.usage,model:R.model||C,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics}}catch(I){if(Sr(I))throw I;if(b3(I)){let R=I instanceof Error?I.message:String(I);throw h.recordFailure(w,xx(I)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:I})}h.recordFailure(w,xx(I)),b=I instanceof Error?I:new Error(String(I)),g.warn(`[createMCPStream] ModelPool: member ${_} failed`,{error:b.message})}}throw new Error(`[ModelPool] all stream members failed: ${b?.message??"no stream members available"}`)}let f=await n.stream({...e,systemPrompt:s,conversationMessages:c});return g.debug("[createMCPStream] Stream created successfully",{provider:t,systemPromptPassedLength:s.length}),{stream:f.stream,provider:t,usage:f.usage,model:f.model||e.model,finishReason:f.finishReason,toolCalls:f.toolCalls??[],toolResults:f.toolResults??[],analytics:f.analytics}}async processStreamResult(e,t,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(e){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",e.content||"")}createStreamResponse(e,t,n){return{stream:t,provider:n.providerName,model:n.options.model,usage:e.usage,finishReason:e.finishReason,toolCalls:e.toolCalls,toolResults:e.toolResults,analytics:e.analytics,evaluation:e.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error}}}async handleStreamError(e,t,n,o,s,i){if(e instanceof Pl)throw e;g.error("Stream generation failed, attempting fallback",{error:e instanceof Error?e.message:String(e)});try{this.emitter.emit("stream:error",{content:e instanceof Error?e.message:String(e),metadata:{errorName:e instanceof Error?e.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:t.provider||"unknown",model:t.model||"unknown"})}catch{}let a=t.input.text,c=Date.now()-n,l=await gx(t.provider),d=await(await Vr.createProvider(l,t.model,!0,void 0,void 0,this.resolveCredentials(t.credentials))).stream({input:{text:t.input.text},model:t.model,temperature:t.temperature,maxTokens:t.maxTokens,conversationMessages:t.conversationMessages}),m="";return{stream:(async function*(h){try{for await(let y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(m+=y.content,h.emitter.emit("response:chunk",y.content)),yield y}finally{if(m.trim()){g.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:l,model:t.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{h.emitter.emit("stream:complete",{content:m,provider:l,model:t.model||"unknown",finishReason:"stop",metadata:{durationMs:Date.now()-n,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}})}catch{}}if(h.conversationMemory&&s?.context?.sessionId&&m.trim()){let y=s?.context?.sessionId,x=s?.context?.userId,b;t.model&&(b={provider:l,model:t.model});let T=Date.now();try{await h.conversationMemory.storeConversationTurn({sessionId:y||t.context?.sessionId,userId:x||t.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:b,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||t.context?.requestId}),h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,1)}catch(w){h.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-T,2,w instanceof Error?w.message:String(w)),g.warn("Failed to store fallback stream conversation turn",{error:w instanceof Error?w.message:String(w)})}}}})(this),provider:l,model:t.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:c,fallback:!0}}}getEventEmitter(){return this.emitter}getToolDedupConfig(){return this.toolDedupConfig}async checkCredentials(e){let{provider:t,model:n}=e,o="ping";try{return await this.generate({provider:t,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:t,status:"ok",detail:"credentials valid"}}catch(s){let i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof Zp?{provider:t,status:"denied",detail:i}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:t,status:"expired",detail:i}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:t,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:t,status:"network",detail:i}:{provider:t,status:"unknown",detail:i}}}emitToolStart(e,t,n=Date.now()){let o=`${e}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:e,startTime:n,metadata:{inputType:typeof t,hasInput:t!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",Nf(e,{input:t,timestamp:n,executionId:o})),g.debug(`tool:start emitted for ${e}`,{toolName:e,executionId:o,timestamp:n,inputProvided:t!==void 0}),o}emitToolEnd(e,t,n,o,s=Date.now(),i){let a=o||s-1e3,c=s-a,l=!n,u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(f=>f.tool===e&&!f.endTime);let d=i||u?.executionId||`${e}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=t,u.error=n,this.activeToolExecutions.delete(u.executionId));let m={tool:e,startTime:a,endTime:s,duration:c,success:l,result:t,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",Nf(e,{result:t,error:n,success:l,responseTime:c,timestamp:s,duration:c,executionId:d})),g.debug(`tool:end emitted for ${e}`,{toolName:e,executionId:d,duration:c,success:l,hasResult:t!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(e,t,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:e,timestamp:Date.now()});try{if(!e||typeof e!="string")throw new Error("Invalid tool name");if(!t||typeof t!="object")throw new Error(`Invalid tool object provided for tool: ${e}`);if(typeof t.execute!="function")throw new Error(`Tool '${e}' must have an execute method.`);if(e.trim()==="")throw new Error("Tool name cannot be empty");if(e.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(e))throw new Error("Tool name contains invalid control characters");let o={name:t.name||e,description:t.description||e,execute:t.execute,inputSchema:"parameters"in t&&t.parameters&&(CI(t.parameters)||typeof t.parameters=="object")?t.parameters:t.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){let i=o.execute,a=n.timeout,c=e;o.execute=async(...l)=>{let u=AbortSignal.timeout(a),d=l[1],m=d?.abortSignal,f=m?AbortSignal.any([m,u]):u,h={...d,abortSignal:f};return Promise.race([i(l[0],h),new Promise((y,x)=>{f.addEventListener("abort",()=>{u.aborted?x(ae.toolTimeout(c,a)):x(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}let s=hGe(e,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),this.emitter.emit("tools-register:end",{toolName:e,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw g.error(`Failed to register tool ${e}:`,o),o}}setToolContext(e){this.toolExecutionContext={...e},g.debug("Tool execution context updated",{sessionId:e.sessionId,contextKeys:Object.keys(e),hasJuspayToken:!!e.juspayToken,hasShopId:!!e.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,g.debug("Tool execution context cleared")}registerTools(e){if(Array.isArray(e))for(let{name:t,tool:n}of e)this.registerTool(t,n);else for(let[t,n]of Object.entries(e))this.registerTool(t,n)}unregisterTool(e){this.invalidateToolCache();let t=`custom-tool-${e}`,n=this.toolRegistry.unregisterServer(t);return n&&g.info(`Unregistered custom tool: ${e}`),n}useToolMiddleware(e){return this.mcpToolMiddlewares.push(e),g.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(e,t,n){if(!this.conversationMemory)throw new ac("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new ac("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await ke(this.conversationMemory.updateAgenticLoopReport(e,n,t),5e3)}getCustomTools(){let e=this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0})),t=new Map;for(let o of e){let s=o.inputSchema||o.parameters;g.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),t.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{let c=this.toolExecutionContext||{},l=a&&Jt(a)?a:{},u={...c,...l,sessionId:l.sessionId||c.sessionId||`fallback-${Date.now()}`};return g.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(c),runtimeContextKeys:Object.keys(l),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=fae(this.fileRegistry));let n=this.cachedFileTools;for(let[o,s]of Object.entries(n))if(!t.has(o)){let i=s,a=i.inputSchema??i.parameters;t.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async c=>await s.execute(c,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return t}async addInMemoryMCPServer(e,t){this.invalidateToolCache();try{te.debug(`[NeuroLink] Registering in-memory MCP server: ${e}`),t.tools||(t.tools=[]),await this.toolRegistry.registerServer(t),te.info(`[NeuroLink] Successfully registered in-memory server: ${e}`,{category:t.metadata?.category,provider:t.metadata?.provider,version:t.metadata?.version})}catch(n){throw te.error(`[NeuroLink] Failed to register in-memory server ${e}:`,n),n}}getInMemoryServers(){let e=this.getInMemoryServerInfos(),t=new Map;for(let n of e)t.set(n.id,n);return t}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(t=>ga({existingCategory:t.metadata?.category,serverId:t.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(e,t={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(e,t);let o=this.createToolExecutionContext(e,t,n);return me.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":e,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(e,t,n,o,s))}createToolExecutionContext(e,t,n){let o=this.externalServerManager.getAllTools().find(l=>l.name===e),s=o?"mcp":this.getCustomTools().has(e)?"custom":"external",i=typeof t=="string"?t:t?JSON.stringify(t):"",a=Date.now(),c=`${e}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:c,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(e,t,n,o,s){try{let i=await this.prepareToolExecutionState(e,t,n,o);return await this.runPreparedToolExecution(e,t,i,o,s)}catch(i){if(!(i instanceof be)){let a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:he.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(e,t,n,o){g.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:e,params:Jt(t)?rB(t):t,hasExternalManager:!!this.externalServerManager}),g.debug("Tool execution detailed analysis",{toolName:e,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof t,isNull:t===null,isUndefined:t===void 0,isEmpty:t&&typeof t=="object"&&Object.keys(t).length===0,keys:t&&typeof t=="object"?Object.keys(t):"NOT_OBJECT",keysLength:t&&typeof t=="object"?Object.keys(t).length:0},isTargetTool:e==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",Nf(e,{timestamp:o.executionStartTime,input:t,executionId:o.executionId}));let s=this.toolRegistry.getToolInfo(e),i={timeout:n?.timeout??s?.tool?.timeoutMs??zu.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??Oo.DEFAULT,retryDelayMs:n?.retryDelayMs||Mn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(kC(),CC)),c=a.getMemoryUsageMB(),u=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${e}`,d=this.toolCircuitBreakers.get(u);d||(d=new zw(nI.FAILURE_THRESHOLD,W$),this.toolCircuitBreakers.set(u,d));let m=this.toolExecutionMetrics.get(e);return m||(m={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(e,m)),m.totalExecutions++,{finalOptions:i,startMemory:c,circuitBreaker:d,breakerKey:u,metrics:m}}async runPreparedToolExecution(e,t,n,o,s){let i=0;try{te.debug(`[${o.functionTag}] Executing tool: ${e}`,{toolName:e,params:t,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});let a=await n.circuitBreaker.execute(async()=>iY(async()=>ke(this.executeToolInternal(e,t,n.finalOptions,o.hitlState),n.finalOptions.timeout,ae.toolTimeout(e,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:s2,onRetry:(c,l)=>{i=c,te.warn(`[${o.functionTag}] Retrying tool execution (attempt ${c})`,{toolName:e,error:l.message,attempt:c})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(e,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(e,t,a,n,o,s)}}async handleSuccessfulToolExecution(e,t,n,o,s){let i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;let{MemoryManager:a}=await Promise.resolve().then(()=>(kC(),CC)),l=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;l>20&&te.warn(`Tool '${e}' used excessive memory: ${l}MB`,{toolName:e,memoryDelta:l,executionTime:i}),te.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:e,executionTime:i,memoryDelta:l,circuitBreakerState:n.circuitBreaker.getState()});let u=t&&typeof t=="object"?t:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,f=d?m?.filter(h=>h.type==="text"&&h.text).map(h=>h.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${e} returned isError:true`)})}catch{}te.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:e,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});let h=Wwr(f??"Unknown error"),y=`[TOOL_ERROR: ${e} failed (${h})] `;if(u&&Array.isArray(m)){let T=m.map(w=>({...w}));for(let w of T)if(w.type==="text"&&w.text){w.text=y+w.text;break}u.content=T}s.setAttribute("tool.error.message",(f??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",h),s.setStatus({code:he.ERROR,message:`MCP tool returned isError: ${(f??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;let x=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=x>1?(n.metrics.averageExecutionTime*x-i)/(x-1):0;let b=Kwr(h);n.metrics.errorCategories[b]=(n.metrics.errorCategories[b]||0)+1}return this.emitToolEndEvent(e,o.executionStartTime,!d,t,d&&f?new Error(f):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),t}async handleFailedToolExecution(e,t,n,o,s,i){o.metrics.failedExecutions++;let a=Date.now()-s.executionStartTime;if(n instanceof ic)return te.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${e}`,{toolName:e,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${e} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:he.ERROR,message:`Circuit breaker open for ${e}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let c;if(n instanceof be)c=n;else if(n instanceof Error)if(n.message.includes("timeout"))c=ae.toolTimeout(e,o.finalOptions.timeout);else if(n.message.includes("not found")){let u=await this.getAllAvailableTools();c=ae.toolNotFound(e,TRe(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?c=ae.invalidParameters(e,n,t):n.message.includes("network")||n.message.includes("connection")?c=ae.networkError(e,n):c=ae.toolExecutionFailed(e,n);else c=ae.toolExecutionFailed(e,new Error(String(n)));let l=c.category||"execution";throw o.metrics.errorCategories[l]=(o.metrics.errorCategories[l]||0)+1,this.emitToolEndEvent(e,s.executionStartTime,!1,void 0,c,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",c),c=new be({...c,context:{...c.context,executionTime:a,params:t,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),aY(c),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(c),i.setStatus({code:he.ERROR,message:c.message}),c}async executeToolInternal(e,t,n,o){let s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(e),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!i?.destructiveHint,c=this.mcpToolResultCache,l=n.authContext||this.toolExecutionContext?{__args:t,__ctx:n.authContext??this.toolExecutionContext}:t;if(a&&c){let m=c.getCachedResult(e,l);if(m!==void 0)return g.debug(`[${s}] Cache HIT for tool: ${e}`),m}let u=async m=>{if(this.mcpToolMiddlewares.length===0)return m();let f=0,h=async()=>{if(f<this.mcpToolMiddlewares.length){let y=this.mcpToolMiddlewares[f++];return y({name:e,description:"",inputSchema:{},annotations:i,execute:async()=>({})},t,{toolMeta:{name:e,annotations:i}},h)}return m()};return await h()},d=async()=>{let m=this.externalServerManager.getAllTools(),f=m.filter(y=>y.name===e&&y.isAvailable),h;if(f.length>1&&this.mcpToolRouter)try{let y={name:e,description:f[0].description??"",serverId:f[0].serverId,inputSchema:{}},x=this.mcpToolRouter.route(y);h=f.find(b=>b.serverId===x.serverId)||f[0],g.debug(`[${s}] Router selected server: ${x.serverId}`,{strategy:x.strategy,confidence:x.confidence})}catch(y){g.warn(`[${s}] Router failed, falling back to first match`,{error:y}),h=f[0]}else h=f[0];if(g.debug(`[${s}] External MCP tool search:`,{toolName:e,externalToolsCount:m.length,foundTool:!!h,isAvailable:h?.isAvailable,serverId:h?.serverId}),h&&h.isAvailable)try{te.debug(`[${s}] Executing external MCP tool: ${e} from ${h.serverId}`);let y=await this.externalServerManager.executeTool(h.serverId,e,t,{timeout:n.timeout});return g.debug(`[${s}] External MCP tool execution successful:`,{toolName:e,serverId:h.serverId,resultType:typeof y}),y}catch(y){throw g.error(`[${s}] External MCP tool execution failed:`,{toolName:e,serverId:h.serverId,error:y instanceof Error?y.message:String(y)}),ae.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)),h.serverId)}try{let y=this.toolExecutionContext||{},x=n.authContext||{},b={...y,...x,hitlState:o};g.debug("[Using merged context for unified registry tool:",{toolName:e,storedContextKeys:Object.keys(y),finalContextKeys:Object.keys(b)});let T=await this.toolRegistry.executeTool(e,t,b);if(T&&typeof T=="object"&&"success"in T&&T.success===!1){let w=T.error||"Tool execution failed",_=new Error(w);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",_)}return T}catch(y){let x=y instanceof Error?y:new Error(String(y));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",x),y instanceof Error&&y.message.includes("not found")){let b=await this.getAllAvailableTools();throw ae.toolNotFound(e,b.map(T=>T.name))}throw ae.toolExecutionFailed(e,y instanceof Error?y:new Error(String(y)))}};try{let m=await u(d);return a&&c&&m!==void 0&&(c.cacheResult(e,l,m),g.debug(`[${s}] Cached result for tool: ${e}`)),m}catch(m){let f=i?{name:e,description:"",annotations:i,execute:async()=>({})}:void 0;if(f&&zM(f)&&m instanceof Error&&s2(m)){g.debug(`[${s}] Tool ${e} is safe to retry, attempting once more`);try{let h=await u(d);return a&&c&&h!==void 0&&c.cacheResult(e,l,h),h}catch{}}throw m}}getToolAnnotationsForExecution(e){if(this.toolCache?.tools){let t=this.toolCache.tools.find(n=>n.name===e);if(t?.annotations)return t.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return Tu({name:e,description:""})}invalidateToolCache(){this.toolCache=null,g.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return g.debug("Returning available tools from cache"),this.toolCache.tools;let e=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,t=Date.now(),n=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:e,timestamp:new Date().toISOString(),getAllToolsStartTime:t,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!Vr,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});let{MemoryManager:o}=await Promise.resolve().then(()=>(kC(),CC)),s=o.getMemoryUsageMB();try{let i=new Map,a=await this.toolRegistry.listTools();for(let y of a)if(!i.has(y.name)){let x=kI(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,x)}let c=this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0}));for(let y of c)if(!i.has(y.name)){let x=kI(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:ga({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let l=this.toolRegistry.getToolsByCategory("in-memory");for(let y of l)if(!i.has(y.name)){let x=kI(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,x)}let u=this.externalServerManager.getAllTools();for(let y of u)if(!i.has(y.name)){let x=kI(y,{category:ga({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,x)}let d=Array.from(i.values());te.debug("Tool discovery results",{mcpTools:a.length,customTools:c.length,inMemoryTools:l.length,externalMCPTools:u.length,total:d.length});let f=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(f>Xp.LOW_USAGE_MB&&(te.debug(`\u{1F50D} Tool listing used ${f}MB memory (large tool registry detected)`),d.length>FX.LARGE_TOOL_COLLECTION&&te.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(let y of d)y.annotations||(y.annotations=Tu({name:y.name,description:y.description||""}));let h=d;return this.toolCache={tools:h,timestamp:Date.now()},h}catch(i){return te.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(e){let{MemoryManager:t}=await Promise.resolve().then(()=>(kC(),CC)),n=t.getMemoryUsageMB();e?.quiet||te.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),e?.quiet||te.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);let{AIProviderFactory:o}=await Promise.resolve().then(()=>(ou(),s3)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(Ag(),IN)),i=["openai","bedrock","vertex","googleVertex","anthropic","azure","google-ai","huggingface","ollama","mistral","litellm"],a=Am(nl.DEFAULT_CONCURRENCY_LIMIT),c=i.map(m=>a(async()=>{let f=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()-f};if(m==="ollama")try{let T=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(ol.AUTH_MS)});if(!T.ok)throw new Error("Ollama service not responding");let w=await T.json(),_=w?.models;if(!Array.isArray(_))throw g.warn("Ollama API returned invalid models format in testProvider",{responseData:w,modelsType:typeof _}),new Error("Invalid models format from Ollama API");let C=_.filter(k=>k&&typeof k=="object"&&typeof k.name=="string");return C.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f,model:C[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-f}}catch(T){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:T instanceof Error?T.message:"Ollama service not running",responseTime:Date.now()-f}}let y=5e3,x=this.testProviderConnection(m),b=new Promise((T,w)=>{setTimeout(()=>w(new Error("Provider test timeout (5s)")),y)});return await Promise.race([x,b]),{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-f}}catch(h){let y=h instanceof Error?h.message:String(h);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-f}}})),l=await Promise.all(c),d=t.getMemoryUsageMB().heapUsed-n.heapUsed;return!e?.quiet&&d>20&&te.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&t.forceGC(),l}async testProvider(e){try{return await this.testProviderConnection(e),!0}catch{return!1}}async testProviderConnection(e){let{AIProviderFactory:t}=await Promise.resolve().then(()=>(ou(),s3));await(await t.createProvider(e,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(e){let{getBestProvider:t}=await Promise.resolve().then(()=>(Ag(),IN));return t(e)}async getAvailableProviders(){let{getAvailableProviders:e}=await Promise.resolve().then(()=>(Ag(),IN));return e()}async isValidProvider(e){let{isValidProvider:t}=await Promise.resolve().then(()=>(Ag(),IN));return t(e)}async getMCPStatus(){try{await this.initializeMCP();let e=await this.toolRegistry.listTools(),t=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,c=t.connectedServers+o.length+s.length,l=e.length+t.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:c,autoDiscoveredCount:i.length,totalTools:l,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:t.connectedServers,externalMCPFailedCount:t.failedServers,externalMCPServers:n}}catch(e){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(ga({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:e instanceof Error?e.message:String(e)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(e){try{if(e==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;let t=this.getInMemoryServers();if(t.has(e)){let o=t.get(e);return!!(o?.tools&&o.tools.length>0)}let n=this.externalServerManager.getServer(e);return n?n.status==="connected"&&n.client!==null:!1}catch(t){return te.error(`[NeuroLink] Error testing MCP server ${e}:`,t),!1}}async hasProviderEnvVars(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(fx(),TC));try{let n=await t.checkProviderHealth(e,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return g.warn(`Provider env var check failed for ${e}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(e,t={}){let{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(fx(),TC)),o=await n.checkProviderHealth(e,t);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(e={}){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(fx(),TC));return(await t.checkAllProvidersHealth(e)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){let{ProviderHealthChecker:e}=await Promise.resolve().then(()=>(fx(),TC)),t=await e.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=e.getHealthSummary(t),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(e){let{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(fx(),TC));t.clearHealthCache(e)}getToolExecutionMetrics(){let e={};for(let[t,n]of this.toolExecutionMetrics.entries())e[t]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return e}setModelAliasConfig(e){this.modelAliasConfig=e,g.info(`[ModelAlias] Configured ${Object.keys(e.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){let e={};for(let[t,n]of this.toolCircuitBreakers.entries())e[t]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return e}resetToolCircuitBreaker(e){this.toolCircuitBreakers.has(e)&&(this.toolCircuitBreakers.set(e,new zw(nI.FAILURE_THRESHOLD,W$)),te.info(`Circuit breaker reset for tool: ${e}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),te.info("All tool execution metrics cleared")}async getToolHealthReport(){let e={},t=0,n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(let i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(let i of o){let a=this.toolExecutionMetrics.get(i),c=`${s.get(i)||"unknown"}.${i}`,l=this.toolCircuitBreakers.get(c),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!l||l.getState()==="closed")&&u>=.8;d&&t++;let m=[],f=[];if(l&&l.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),f.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),f.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),f.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){let h=a.errorCategories;h.timeout>0&&(m.push(`Timeout errors: ${h.timeout}`),f.push("Consider increasing the tool timeout configuration")),h.validation>0&&(m.push(`Validation errors: ${h.validation}`),f.push("Review input schemas and parameter validation")),h.network>0&&(m.push(`Network errors: ${h.network}`),f.push("Check network connectivity and endpoint availability"))}e[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:l?.getState()||"closed",failureCount:l?.getFailureCount()||0},issues:m,recommendations:f}}return{totalTools:o.size,healthyTools:t,unhealthyTools:o.size-t,tools:e}}async ensureConversationMemoryInitialized(){try{let e=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(e){return g.error("Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e)}),!1}}async getConversationStats(){let e=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(e){let t=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new be({code:Ge.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});try{let n=await this.conversationMemory.buildContextMessages(e);return g.debug("Retrieved conversation history",{sessionId:e,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return g.error("Failed to retrieve conversation history",{sessionId:e,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(e){let t=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(e),await this.conversationMemory.clearSession(e)}async clearAllConversations(){let e=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(e,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async storeToolExecutions(e,t,n,o,s){let i=n&&n.length>0||o&&o.length>0;if(!i){g.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}let a=this.conversationMemory;try{await a.storeToolExecution(e,t,n,o,s)}catch(c){g.warn("Failed to store tool executions",{sessionId:e,userId:t,error:c instanceof Error?c.message:String(c)})}}isToolExecutionStorageAvailable(){let e=process.env.STORAGE_TYPE==="redis",t=this.conversationMemory&&this.conversationMemory.constructor.name==="RedisConversationMemoryManager";return!!(e&&t)}async getSessionMessages(e,t){let n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new be({code:Ge.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});return await this.conversationMemory.getSessionMessages(e,t)}async setSessionMessages(e,t,n){let o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!e||typeof e!="string")throw new be({code:Ge.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:e}});await this.conversationMemory.setSessionMessages(e,t,n)}async modifyLastAssistantMessage(e,t,n){let o=await this.getSessionMessages(e,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:t(o[s].content)},await this.setSessionMessages(e,o,n),!0;return!1}async addExternalMCPServer(e,t){this.invalidateToolCache();try{te.info(`[NeuroLink] Adding external MCP server: ${e}`,{command:t.command,transport:t.transport});let n=await this.externalServerManager.addServer(e,t);if(n.success){if(te.info(`[NeuroLink] External MCP server added successfully: ${e}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){let o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new mx({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(let s of o)this.mcpToolRouter.registerServer(s.id||e);g.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(e)}this.emitter.emit("externalMCP:serverAdded",{serverId:e,serverName:t.name||e,config:t,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else te.error(`[NeuroLink] Failed to add external MCP server: ${e}`,{error:n.error});return n}catch(n){throw te.error(`[NeuroLink] Error adding external MCP server: ${e}`,n),n}}async removeExternalMCPServer(e){this.invalidateToolCache();try{te.info(`[NeuroLink] Removing external MCP server: ${e}`);let t=this.externalServerManager.getServerName(e),n=await this.externalServerManager.removeServer(e);return n.success?(te.info(`[NeuroLink] External MCP server removed successfully: ${e}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:e,serverName:t,timestamp:Date.now()})):te.error(`[NeuroLink] Failed to remove external MCP server: ${e}`,{error:n.error}),n}catch(t){throw te.error(`[NeuroLink] Error removing external MCP server: ${e}`,t),t}}listExternalMCPServers(){let e=this.externalServerManager.getServerStatuses(),t=this.externalServerManager.listServers();return e.map(n=>{let o=t.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(e){return this.externalServerManager.getServer(e)}async executeExternalMCPTool(e,t,n,o){try{te.debug(`[NeuroLink] Executing external MCP tool: ${t} on ${e}`);let s=this.getToolAnnotationsForExecution(t),i=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,a={__serverId:e,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}};if(i&&this.mcpToolResultCache){let l=this.mcpToolResultCache.getCachedResult(t,a);if(l!==void 0)return te.debug(`[NeuroLink] Tool result cache HIT: ${t} on ${e}`),l}let c=await this.externalServerManager.executeTool(e,t,n,o);return i&&this.mcpToolResultCache&&this.mcpToolResultCache.cacheResult(t,a,c),te.debug(`[NeuroLink] External MCP tool executed successfully: ${t}`),c}catch(s){throw te.error(`[NeuroLink] External MCP tool execution failed: ${t}`,s),s}}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(e){return this.externalServerManager.getServerTools(e)}async testExternalMCPConnection(e){try{let{MCPClientFactory:t}=await ke(Promise.resolve().then(()=>(tq(),dGe)),1e4),n=await t.testConnection(e,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{te.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),te.info("[NeuroLink] All external MCP servers shut down successfully")}catch(e){throw te.error("[NeuroLink] Error shutting down external MCP servers:",e),e}}async getElicitationManager(){return(await ke(Promise.resolve().then(()=>(Pue(),GHe)),1e4)).globalElicitationManager}async registerElicitationHandler(e){(await this.getElicitationManager()).registerHandler(e)}async getMultiServerManager(){return(await ke(Promise.resolve().then(()=>(TH(),Tze)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){let e=await ke(Promise.resolve().then(()=>(SH(),Sze)),1e4);return new e.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await ke(Promise.resolve().then(()=>(Due(),VHe)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(e,t){return(await ke(Promise.resolve().then(()=>(p3(),$ue)),1e4)).exposeAgentAsTool(e,t)}async exposeWorkflowAsTool(e,t){return(await ke(Promise.resolve().then(()=>(p3(),$ue)),1e4)).exposeWorkflowAsTool(e,t)}async getToolIntegrationManager(){return(await ke(Promise.resolve().then(()=>(Wue(),HHe)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(e,t={}){let n=await ke(Promise.resolve().then(()=>(h3(),rde)),1e4),o=e.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,t)}async convertToolsFromMCPFormat(e,t={}){return(await ke(Promise.resolve().then(()=>(h3(),rde)),1e4)).batchConvertToNeuroLink(e,t)}async getToolAnnotations(e){let{inferAnnotations:t,mergeAnnotations:n,getAnnotationSummary:o}=await ke(Promise.resolve().then(()=>(G0(),bze)),1e4),s=this.toolRegistry.getToolInfo(e);if(!s)return null;let i=s.tool.annotations,a=t({name:s.tool.name,description:s.tool.description??""}),c=n(a,i);return{annotations:c,summary:o(c)}}convertExternalMCPToolsToAISDKFormat(){let e=this.externalServerManager.getAllTools(),t={};for(let n of e)if(n.isAvailable){let o={description:n.description,execute:async s=>{try{te.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});let i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return te.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw te.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};t[n.name]=o,te.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return te.info(`[NeuroLink] Converted ${Object.keys(t).length} external MCP tools to AI SDK format`),t}convertJSONSchemaToAISDKFormat(e){}unregisterExternalMCPToolsFromRegistry(e){try{let t=this.externalServerManager.getServerTools(e);for(let n of t)this.toolRegistry.removeTool(n.name),te.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(t){te.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${e}:`,t)}}unregisterExternalMCPToolFromRegistry(e){try{this.toolRegistry.removeTool(e),te.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${e}`)}catch(t){te.error(`[NeuroLink] Failed to unregister external MCP tool ${e} from registry:`,t)}}async lazyInitializeConversationMemory(e,t,n){try{let{initializeConversationMemory:o}=await eqe().then(()=>QHe),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw g.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{let e=this.externalServerManager.getAllTools();for(let t of e)this.toolRegistry.removeTool(t.name);te.debug(`[NeuroLink] Unregistered ${e.length} external MCP tools from main registry`)}catch(e){te.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",e)}}async createEvaluationPipeline(e){let{EvaluationPipeline:t,getPreset:n}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4)),o;typeof e=="string"?o=n(e):o=e;let s=new t(o);return await ke(s.initialize(),3e4,ae.evaluationTimeout("pipeline initialization",3e4)),g.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(e,t){let{EvaluationPipeline:n,getPreset:o}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4)),s;if(t?.pipeline&&t?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(t?.scorers&&t.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");t?.pipeline?s={...o(t.pipeline)}:t?.scorers&&t.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:t.scorers.map(l=>({id:l})),executionMode:t.executionMode??"parallel",passThreshold:t.passThreshold??.7}:s=o("quality"),t?.passThreshold!==void 0&&(s.passThreshold=t.passThreshold),t?.executionMode!==void 0&&(s.executionMode=t.executionMode);let i=new n(s);await ke(i.initialize(),3e4,ae.evaluationTimeout("pipeline initialization",3e4));let a=t?.timeoutMs??6e4,c=await ke(i.execute(e,{correlationId:t?.correlationId}),a,ae.evaluationTimeout("pipeline execution",a));return g.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:c.overallScore,passed:c.passed,scorerCount:c.scores.length}),c}async score(e,t,n){let{ScorerRegistry:o}=await ke(Promise.resolve().then(()=>(O2(),jY)),1e4,ae.evaluationTimeout("scorer module load",1e4));await ke(o.registerBuiltInScorers(),3e4,ae.evaluationTimeout("scorer bootstrap",3e4));let s=await ke(o.getScorer(e,n),3e4,ae.evaluationTimeout(`scorer load: ${e}`,3e4));if(!s)throw ae.scorerNotFound(e);let i=s.validateInput(t);if(!i.valid)throw ae.evaluationValidationFailed(e,i.errors);let a=await ke(s.score(t),6e4,ae.evaluationTimeout("scorer execution",6e4));return g.debug("[NeuroLink] Scoring completed",{scorerId:e,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(e){let{ScorerRegistry:t}=await ke(Promise.resolve().then(()=>(O2(),jY)),1e4,ae.evaluationTimeout("scorer module load",1e4));await ke(t.registerBuiltInScorers(),3e4,ae.evaluationTimeout("scorer bootstrap",3e4));let n=t.list();return e?.category&&(n=n.filter(o=>o.category===e.category)),e?.type&&(n=n.filter(o=>o.type===e.type)),n}async getEvaluationPresets(){let{getPresetNames:e}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4));return e()}async getEvaluationPreset(e){let{getPreset:t}=await ke(Promise.resolve().then(()=>(qw(),gI)),1e4,ae.evaluationTimeout("evaluation module load",1e4));return t(e)}async dispose(){g.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();let e=[];try{try{g.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await RO(),await AO(),g.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`OpenTelemetry shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down OpenTelemetry:",t)}if(this.externalServerManager)try{g.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),g.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(t){let n=t instanceof Error?t:new Error(`External server shutdown error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error shutting down external MCP servers:",t)}if(this.emitter)try{g.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),g.clearEventEmitter(),g.debug("[NeuroLink] Event listeners removed successfully")}catch(t){let n=t instanceof Error?t:new Error(`Event emitter cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error removing event listeners:",t)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{g.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),g.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Circuit breaker cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing circuit breakers:",t)}try{g.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],g.debug("[NeuroLink] Maps and caches cleared successfully")}catch(t){let n=t instanceof Error?t:new Error(`Cache cleanup error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error clearing caches:",t)}if(this._taskManager)try{g.debug("[NeuroLink] Shutting down TaskManager..."),await ke(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(t){g.warn("[NeuroLink] TaskManager shutdown error:",t)}finally{this._taskManager=void 0}try{g.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,g.debug("[NeuroLink] Initialization state reset successfully")}catch(t){let n=t instanceof Error?t:new Error(`State reset error: ${String(t)}`);e.push(n),g.warn("[NeuroLink] Error resetting state:",t)}e.length===0?g.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):g.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${e.length} errors`,{errors:e.map(t=>t.message)})}catch(t){throw g.error("[NeuroLink] Critical error during disposal:",t),t}}getToolRegistry(){return this.toolRegistry}async compactSession(e,t){if(!this.conversationMemory)return null;let n=await this.conversationMemory.buildContextMessages(e);if(!n||n.length===0)return null;let o=new nx({...t,summarizationProvider:t?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:t?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=Bc({provider:t?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&$0(a.messages),a}async getContextStats(e,t,n){if(!this.conversationMemory)return null;let o=await this.conversationMemory.buildContextMessages(e);if(!o||o.length===0)return null;let s=Bc({provider:t||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(e,t,n){if(!this.conversationMemory)return!1;let o=this.conversationMemory.getSession?.(e);return o?Bc({provider:t||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(e){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(e)}async initializeAuthProviderFromConfig(e){let t,n;if("authenticateToken"in e&&typeof e.authenticateToken=="function")t=e,n=t.type;else if("provider"in e)t=e.provider,n=t.type;else{let o=e,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(KN(),tqe));t=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=t,g.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:t.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;let e=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(e),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===e)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(e){let{globalAuthContext:t}=await Promise.resolve().then(()=>(pC(),uq));t.set(e),g.debug("Auth context set",{userId:e.user.id,provider:e.provider,sessionId:e.session?.id})}async getAuthContext(){let{getAuthContext:e}=await Promise.resolve().then(()=>(pC(),uq));return e()}async clearAuthContext(){let{globalAuthContext:e}=await Promise.resolve().then(()=>(pC(),uq)),t=e.get()?.user.id;e.clear(),t&&g.debug(`Auth context cleared for user: ${t}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(e,t){return{requestContext:t||{},signal:e}}async resolveDynamicOptions(e){let t=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(t.some(s=>typeof e[s]=="function")||typeof e.tools=="function"))return;let o=e.dynamicContext;await this.resolveDynamicFields(e,t,o)}async resolveDynamicFields(e,t,n){let o=this.buildResolutionContext(e.abortSignal,n);if(g.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(t.map(async s=>{if(typeof e[s]=="function"){let i=await ple(e[s],o);e[s]=i.value,g.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof e.tools=="function"){let s=await ple(e.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);e.enabledToolNames=s.value,delete e.tools}}},rqe=new NT,Ywr=rqe});var oqe={};J(oqe,{VoyageProvider:()=>S3,default:()=>eEr});var Zwr,nqe,Qwr,dde,S3,eEr,sqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();lt();q();Gn();Zwr="https://api.voyageai.com/v1",nqe=6e4,Qwr=()=>nr(S1e()),dde=()=>or("VOYAGE_MODEL","voyage-3.5"),S3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"voyage",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:Qwr(),this.baseURL=o?.baseURL??process.env.VOYAGE_BASE_URL??Zwr,this.proxyFetch=et(),g.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return dde()}supportsTools(){return!1}getDefaultEmbeddingModel(){return dde()}getAISDKModel(){throw new Ee("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 Ee("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new ct("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new kt(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new Ee(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Ee("Voyage AI returned no embedding for the provided text","voyage");return n[0]}async embedMany(e,t){if(e.length===0)return[];let n=128,o=[];for(let s=0;s<e.length;s+=n){let i=e.slice(s,s+n),a=await this.callEmbeddings(i,t);o.push(...a)}return o}async callEmbeddings(e,t){let n=t??this.modelName,o;try{o=await ke(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n})}),nqe,new Ee(`Voyage embeddings request timed out after ${nqe/1e3}s`,"voyage"))}catch(a){throw a instanceof Ee?a:this.formatProviderError(a)}if(!o.ok){let a=await o.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${o.status} \u2014 ${a}`))}let s=await o.json();if(!s.data||s.data.length===0)throw new Ee("Voyage embeddings response missing data","voyage");if(s.data.length!==e.length)throw new Ee(`Voyage embeddings response count mismatch: expected ${e.length}, got ${s.data.length}`,"voyage");let i=s.data.slice().sort((a,c)=>a.index-c.index);for(let a=0;a<i.length;a++)if(i[a].index!==a)throw new Ee(`Voyage embeddings response has unexpected index ordering: position ${a} has index ${i[a].index}`,"voyage");return i.map(a=>a.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:dde(),baseURL:this.baseURL}}},eEr=S3});var iqe={};J(iqe,{JinaProvider:()=>E3,default:()=>nEr});var tEr,w3,rEr,pde,E3,nEr,aqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();q();Gn();tEr="https://api.jina.ai/v1",w3=6e4,rEr=()=>nr(w1e()),pde=()=>or("JINA_MODEL","jina-embeddings-v3"),E3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"jina",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:rEr(),this.baseURL=o?.baseURL??process.env.JINA_BASE_URL??tEr,this.proxyFetch=et(),g.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return pde()}supportsTools(){return!1}getDefaultEmbeddingModel(){return pde()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new ct("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new kt(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new Ee(`Jina AI error: ${t}`,"jina")}async embed(e,t){let n=await this.callEmbeddings([e],t);if(!n[0])throw new Error("Jina AI returned no embedding for the provided text");return n[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,n={}){if(t.length===0)return[];let o=n.model??"jina-reranker-v2-base-multilingual",s=n.credentials,i=s?.apiKey?.trim()||this.apiKey,a=s?.baseURL||this.baseURL,c=new AbortController,l=setTimeout(()=>c.abort(),w3),u;try{u=await this.proxyFetch(`${a}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({model:o,query:e,documents:t,top_n:n.topN??t.length}),signal:c.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${w3/1e3}s`)):this.formatProviderError(m)}finally{clearTimeout(l)}if(!u.ok){let m=await u.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${u.status} \u2014 ${m}`))}return((await u.json()).results??[]).map(m=>({index:m.index,score:m.relevance_score,document:t[m.index]??m.document?.text??""}))}async callEmbeddings(e,t,n){let o=t??this.modelName,s=n?.apiKey?.trim()||this.apiKey,i=n?.baseURL||this.baseURL,a=new AbortController,c=setTimeout(()=>a.abort(),w3),l;try{l=await this.proxyFetch(`${i}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:o}),signal:a.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${w3/1e3}s`)):this.formatProviderError(m)}finally{clearTimeout(c)}if(!l.ok){let m=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${m}`))}let u=await l.json();if(!u.data||u.data.length===0)throw new Error("Jina embeddings response missing data");if(u.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${u.data.length}`);let d=u.data.slice().sort((m,f)=>m.index-f.index);for(let m=0;m<d.length;m++)if(d[m].index!==m)throw new Error(`Jina embeddings response has unexpected index ordering: position ${m} has index ${d[m].index}`);return d.map(m=>m.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:pde(),baseURL:this.baseURL}}},nEr=E3});var uqe={};J(uqe,{StabilityProvider:()=>_3,default:()=>iEr});var oEr,cqe,sEr,lqe,_3,iEr,dqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();q();Gn();oEr="https://api.stability.ai",cqe=12e4,sEr=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,lqe=()=>or("STABILITY_MODEL","stable-image-ultra"),_3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"stability",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:sEr(),this.baseURL=o?.baseURL??process.env.STABILITY_BASE_URL??oEr,this.proxyFetch=et(),g.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return lqe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new ct("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new Ee("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new kt(`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 Ee(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.stability,o=n?.apiKey?.trim()||this.apiKey;if(!o)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");let s=o,i=n?.baseURL||this.baseURL,a=e.prompt??e.input?.text??"";if(!a.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");let c=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,u=new FormData;u.append("prompt",a),u.append("output_format","png"),l.aspectRatio&&u.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&u.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&u.append("model",this.modelName),l.seed!==void 0&&u.append("seed",String(l.seed));let d=new AbortController,m=setTimeout(()=>d.abort(),cqe),f;try{f=await this.proxyFetch(`${i}/v2beta/stable-image/generate/${c}`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/json"},body:u,signal:d.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${cqe/1e3}s`)):this.formatProviderError(x)}finally{clearTimeout(m)}if(!f.ok){let x=await f.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${f.status} \u2014 ${x}`))}let h=await f.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);let y=Date.now()-t;return g.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:lqe(),baseURL:this.baseURL}}},iEr=_3});var fqe={};J(fqe,{IdeogramProvider:()=>C3,default:()=>lEr});var aEr,pqe,cEr,mqe,C3,lEr,gqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();q();Gn();aEr="https://api.ideogram.ai",pqe=12e4,cEr=()=>nr(E1e()),mqe=()=>or("IDEOGRAM_MODEL","V_3"),C3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"ideogram",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:cEr(),this.baseURL=o?.baseURL??process.env.IDEOGRAM_BASE_URL??aEr,this.proxyFetch=et(),g.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return mqe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new ct("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new Ee("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new Ee(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.ideogram,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");let a=e,c={prompt:i,model:this.modelName,magic_prompt:a.magicPrompt??"AUTO"};a.aspectRatio&&(c.aspect_ratio=a.aspectRatio),a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.seed!==void 0&&(c.seed=a.seed),a.style&&(c.style_type=a.style);let l=new AbortController,u=setTimeout(()=>l.abort(),pqe),d;try{d=await this.proxyFetch(`${s}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":o,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(_){throw _ instanceof Error&&_.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${pqe/1e3}s`)):this.formatProviderError(_)}finally{clearTimeout(u)}if(!d.ok){let _=await d.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${d.status} \u2014 ${_}`))}let f=(await d.json()).data?.[0]?.url;if(!f)throw new Error("Ideogram returned no image URL");let h=new AbortController,y=setTimeout(()=>h.abort(),6e4),x;try{x=await this.proxyFetch(f,{signal:h.signal})}catch(_){throw _ instanceof Error&&_.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:_}):_}finally{clearTimeout(y)}if(!x.ok)throw new Error(`Failed to download Ideogram image: ${x.status}`);let b=Buffer.from(await x.arrayBuffer()),T=b.toString("base64"),w=Date.now()-t;return g.info(`[IdeogramProvider] Generated image (${b.length} bytes) in ${w}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:T}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:mqe(),baseURL:this.baseURL}}},lEr=C3});function xd(r){let e=(r?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return e?{apiToken:e,baseUrl:(r?.baseUrl??process.env.REPLICATE_BASE_URL??uEr).replace(/\/$/,"")}:null}var uEr,JN=E(()=>{"use strict";uEr="https://api.replicate.com"});function pEr(r,e,t){return new tee({connect:{lookup:(n,o,s)=>{if(n.toLowerCase()!==r.toLowerCase()){s(new Error(`safeFetch: refusing to resolve "${n}" \u2014 expected "${r}"`),"",0);return}s(null,e,t)}}})}async function bx(r,e){let{url:t,ip:n,family:o}=await B1e(r),i=new URL(t).hostname.replace(/^\[|\]$/g,""),a=pEr(i,n,o),c=new AbortController,l=setTimeout(()=>c.abort(),e.timeoutMs??dEr),u=e.signal?AbortSignal.any([e.signal,c.signal]):c.signal,d;try{d=await eee(t,{method:"GET",signal:u,redirect:"manual",dispatcher:a})}finally{clearTimeout(l),a.close().catch(()=>{})}if(d.status>=300&&d.status<400)throw new Error(`safeDownload(${e.label}): refused to follow redirect ${d.status} \u2192 ${d.headers.get("location")??"<no-location>"} (for ${r})`);if(!d.ok)throw new Error(`safeDownload(${e.label}) failed: HTTP ${d.status} for ${r}`);return Oa(d,e.maxBytes,e.label)}var dEr,XN=E(()=>{"use strict";fE();ag();qy();dEr=6e4});async function gEr(r,e){let t=r.baseUrl??"https://api.replicate.com",[n,o]=e.model.split(":",2),s=o?`${t}/v1/predictions`:`${t}/v1/models/${n}/predictions`,i=o?{version:o,input:e.input}:{input:e.input};e.webhook&&(i.webhook=e.webhook),e.webhookEventsFilter&&e.webhookEventsFilter.length>0&&(i.webhook_events_filter=e.webhookEventsFilter);let a=new AbortController,c=setTimeout(()=>a.abort(),YN),l;try{l=await fetch(s,{method:"POST",headers:{Authorization:`Token ${r.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(i),signal:a.signal})}catch(u){throw u instanceof be?u:u instanceof Error&&u.name==="AbortError"?new be({code:Ge.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${YN/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:u}):u}finally{clearTimeout(c)}if(!l.ok){let u=await l.text();throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${l.status} \u2014 ${Ms(u,500)}`,category:"network",severity:"high",retriable:l.status>=500})}return await l.json()}async function hEr(r,e,t={}){let n=r.baseUrl??"https://api.replicate.com",o=Date.now(),s=t.timeoutMs??fEr,i=t.pollIntervalMs??mEr;for(;Date.now()-o<s;){if(t.abortSignal?.aborted)throw new be({code:Ge.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});let a=new AbortController,c=setTimeout(()=>a.abort(),YN),l=()=>a.abort();t.abortSignal?.addEventListener("abort",l,{once:!0});let u;try{u=await fetch(`${n}/v1/predictions/${e}`,{method:"GET",headers:{Authorization:`Token ${r.apiToken}`},signal:a.signal})}catch(m){throw m instanceof be?m:m instanceof Error&&m.name==="AbortError"?t.abortSignal?.aborted?new be({code:Ge.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:m}):new be({code:Ge.OPERATION_ABORTED,message:`Replicate poll request timed out after ${YN/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:m}):m}finally{t.abortSignal?.removeEventListener("abort",l),clearTimeout(c)}if(!u.ok){let m=await u.text();throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${u.status} \u2014 ${Ms(m,500)}`,category:"network",severity:"high",retriable:u.status>=500})}let d=await u.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((m,f)=>{let h=()=>{clearTimeout(y),f(new be({code:Ge.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},y=setTimeout(()=>{t.abortSignal?.removeEventListener("abort",h),m()},i);t.abortSignal?.addEventListener("abort",h,{once:!0})})}throw new be({code:Ge.OPERATION_ABORTED,message:`Replicate prediction ${e} did not complete within ${Math.round(s/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function Ng(r,e,t={}){let n=await gEr(r,e);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return hEr(r,n.id,t)}async function Tx(r,e=268435456){let t=r.output,n=Array.isArray(t)?t[0]:t;if(typeof n!="string")throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${r.id} output is not a URL: ${typeof t}`,category:"execution",severity:"high",retriable:!1});try{let o=await bx(n,{maxBytes:e,label:`Replicate prediction ${r.id}`,timeoutMs:YN});return g.debug(`[Replicate] Downloaded prediction ${r.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof be)throw o;let s=o instanceof Error?o.message:String(o);throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${s} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var YN,mEr,fEr,ZN=E(()=>{"use strict";q();lt();Un();XN();YN=9e4,mEr=2e3,fEr=5*6e4});var yqe={};J(yqe,{ReplicateProvider:()=>k3,default:()=>vEr});function yEr(r){let e=r,t=e.prompt??e.input?.text??"",n=e.systemPrompt;return n?`${n}
|
|
2136
2136
|
|
|
2137
2137
|
${t}`:t}function xEr(r){return typeof r=="string"?r:Array.isArray(r)?r.map(e=>typeof e=="string"?e:"").join(""):""}var hqe,k3,vEr,xqe=E(async()=>{"use strict";gu();JN();ZN();await Cp();q();lt();Gn();hqe=()=>or("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct");k3=class extends jn{apiToken;baseURL;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"replicate",s);let i=o?.apiToken?.trim();this.apiToken=i&&i.length>0?i:nr(x1e()),this.baseURL=o?.baseUrl,g.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return hqe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Replicate routes through the predictions API, not the AI SDK chat models. Streaming uses the predict-then-stream path inside executeStream.")}async generate(e,t){let n=typeof e=="string"?{prompt:e}:e,{IMAGE_GENERATION_MODELS:o}=await Promise.resolve().then(()=>(ea(),CEe));if(n.output?.mode==="video"||n.output?.mode==="avatar"||n.output?.mode==="music")return super.generate(n,t);let s=o.some(m=>this.modelName.includes(m)),i=n.output?.format==="json"||n.output?.format==="structured"||n.output?.format==="text";if(s&&!i)return super.generate(n,t);if(n.output?.format==="json"||n.output?.format==="structured"||t!=null)throw new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:"Replicate models do not support structured-output / JSON schema. Remove output.format or _analysisSchema, or use a provider that implements the OpenAI chat-completions contract (e.g. openai, anthropic).",category:"validation",severity:"medium",retriable:!1});let a=n.prompt??n.input?.text??"",c=Date.now(),l=await this.executeStream({input:{text:a},systemPrompt:n.systemPrompt,maxTokens:n.maxTokens,temperature:n.temperature,abortSignal:n.abortSignal,timeout:n.timeout}),u="";for await(let m of l.stream)"content"in m&&typeof m.content=="string"&&(u+=m.content);let d={content:u,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}};return g.info(`[ReplicateProvider] generate() complete in ${Date.now()-c}ms \u2014 ${u.length} chars`),d}async executeStream(e,t){let n=Date.now(),o=e.credentials?.replicate,s=o?.apiToken?.trim()||this.apiToken,i=o?.baseUrl||this.baseURL,a=xd({apiToken:s,baseUrl:i});if(!a)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let c=yEr(e);if(!c.trim())throw new be({code:Ge.INVALID_PARAMETERS,message:"Replicate predictions require a prompt (input.text or prompt)",category:"validation",severity:"medium",retriable:!1});let l={prompt:c,...e.maxTokens!==void 0&&{max_new_tokens:e.maxTokens},temperature:e.temperature,top_p:1},u;try{u=await Ng(a,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let d=xEr(u.output);if(!d)throw new Error(`Replicate prediction ${u.id} returned empty output`);let m={async*[Symbol.asyncIterator](){yield{content:d}}};return g.info(`[ReplicateProvider] Generated ${d.length} chars in ${Date.now()-n}ms \u2014 model ${this.modelName} (prediction ${u.id})`),{stream:m,provider:this.providerName,model:this.modelName,finishReason:"stop",metadata:{startTime:n,streamId:`replicate-${u.id}`}}}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.replicate,o=n?.apiToken?.trim()||this.apiToken,s=n?.baseUrl||this.baseURL,i=xd({apiToken:o,baseUrl:s});if(!i)throw new be({code:Ge.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});let a=e.prompt??e.input?.text??"";if(!a.trim())throw new be({code:Ge.INVALID_PARAMETERS,message:"Replicate image-gen requires a prompt",category:"validation",severity:"medium",retriable:!1});let c=e,l={prompt:a,output_format:"png"};c.aspectRatio&&(l.aspect_ratio=c.aspectRatio),c.negativePrompt&&(l.negative_prompt=c.negativePrompt),c.seed!==void 0&&(l.seed=c.seed);let u;try{u=await Ng(i,{model:this.modelName,input:l},{abortSignal:e.abortSignal})}catch(f){throw this.handleProviderError(f)}let d;try{d=await Tx(u,26214400)}catch(f){throw this.handleProviderError(f)}let m=d.toString("base64");return g.info(`[ReplicateProvider] Generated image (${d.length} bytes) in ${Date.now()-t}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0},imageOutput:{base64:m}}}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error",n=e instanceof Error?e:void 0;return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.toLowerCase().includes("invalid token")?new be({code:Ge.PROVIDER_AUTH_FAILED,message:"Invalid Replicate API token. Get one at https://replicate.com/account/api-tokens",category:"configuration",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("402")||t.toLowerCase().includes("insufficient credit")?new be({code:Ge.PROVIDER_QUOTA_EXCEEDED,message:"Replicate insufficient credit. Top up at https://replicate.com/account/billing \u2014 most image/music models require a paid balance.",category:"resource",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n}):t.includes("429")||t.toLowerCase().includes("rate limit")?new be({code:Ge.PROVIDER_QUOTA_EXCEEDED,message:"Replicate rate limit exceeded. Back off and retry.",category:"resource",severity:"high",retriable:!0,context:{provider:"replicate"},originalError:n}):t.toLowerCase().includes("not found")||t.includes("404")?new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate model '${this.modelName}' not found. Use owner/name or owner/name:version format. Browse https://replicate.com/explore`,category:"validation",severity:"medium",retriable:!1,context:{provider:"replicate",model:this.modelName},originalError:n}):new be({code:Ge.PROVIDER_NOT_AVAILABLE,message:`Replicate error: ${t}`,category:"execution",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:n})}async validateConfiguration(){return typeof this.apiToken=="string"&&this.apiToken.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:hqe(),baseURL:this.baseURL}}},vEr=k3});var Tqe={};J(Tqe,{RecraftProvider:()=>R3,default:()=>SEr});var bEr,vqe,TEr,bqe,R3,SEr,Sqe=E(async()=>{"use strict";gu();await Cp();Zn();dt();q();Gn();ag();qy();bEr="https://external.api.recraft.ai/v1",vqe=12e4,TEr=()=>nr(_1e()),bqe=()=>or("RECRAFT_MODEL","recraftv3"),R3=class extends jn{apiKey;baseURL;proxyFetch;constructor(e,t,n,o){let s=Cu(t)?t:void 0;super(e,"recraft",s);let i=o?.apiKey?.trim();this.apiKey=i&&i.length>0?i:TEr(),this.baseURL=o?.baseURL??process.env.RECRAFT_BASE_URL??bEr,this.proxyFetch=et(),g.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return bqe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Recraft is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Recraft is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){let t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new ct("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new At("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new kt(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new Ee(`Recraft error: ${t}`,"recraft")}async executeImageGeneration(e){let t=Date.now(),n=e.credentials?.recraft,o=n?.apiKey?.trim()||this.apiKey,s=n?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");let a=e,c={model:e.model??this.modelName,prompt:i,n:1,response_format:"b64_json"};a.negativePrompt&&(c.negative_prompt=a.negativePrompt),a.style&&(c.style=a.style),a.styleId&&(c.style_id=a.styleId),a.size&&(c.size=a.size);let l=new AbortController,u=setTimeout(()=>l.abort(),vqe),d;try{d=await this.proxyFetch(`${s}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${vqe/1e3}s`)):this.formatProviderError(x)}finally{clearTimeout(u)}if(!d.ok){let x=await d.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${d.status} \u2014 ${x}`))}let f=(await d.json()).data?.[0];if(!f)throw new Error("Recraft returned no image data");let h;if(f.b64_json)h=f.b64_json;else if(f.url){await Cl(f.url);let x=new AbortController,b=setTimeout(()=>x.abort(),6e4),T;try{T=await this.proxyFetch(f.url,{signal:x.signal})}catch(_){throw _ instanceof Error&&_.name==="AbortError"?new Error("Recraft image download timed out after 60s",{cause:_}):_}finally{clearTimeout(b)}if(!T.ok)throw new Error(`Failed to download Recraft image: ${T.status}`);h=(await Oa(T,26214400,"Recraft image")).toString("base64")}else throw new Error("Recraft response missing both b64_json and url");let y=Date.now()-t;return g.info(`[RecraftProvider] Generated image (${h.length} base64 chars) in ${y}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:bqe(),baseURL:this.baseURL}}},SEr=R3});var $C,Ha,Gso,Vso,Hso,qso,Wso,Kso,Jso,Xso,Yso,Zso,Qso,wqe,eio,tio,rio,nio,oio,sio,iio,aio,cio,lio,uio,dio,pio,mio,fio,gio,hio,yio,xio,vio,bio,Tio,Sio,wio,Eio,_io,Cio,kio,Rio,Aio,Iio,Pio,Oio,Eqe=E(()=>{$C={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:$C.get}):new Proxy(function(...t){return new Proxy({},{get:$C.get})},{get:$C.get,apply(t,n,o){return new Proxy({},{get:$C.get})},construct(t,n){return new Proxy({},{get:$C.get})}})}},Ha=new Proxy({},$C),{BedrockClient:Gso,ListFoundationModelsCommand:Vso,BedrockRuntimeClient:Hso,ConverseCommand:qso,ConverseStreamCommand:Wso,ImageFormat:Kso}=Ha,{SageMakerRuntimeClient:Jso,InvokeEndpointCommand:Xso,InvokeEndpointWithResponseStreamCommand:Yso}=Ha,{GoogleAuth:Zso,VertexAI:Qso,TextToSpeechClient:wqe}=Ha,{Webhook:eio}=Ha,{Hippocampus:tio,HippocampusConfig:rio}=Ha,{createClient:nio}=Ha,{Queue:oio,Worker:sio,Job:iio,QueueScheduler:aio,FlowProducer:cio}=Ha,{Cron:lio}=Ha,{parseBuffer:uio,selectCover:dio}=Ha,{extractRawText:pio,convertToHtml:mio}=Ha,{Hono:fio}=Ha,{cors:gio,HTTPException:hio,logger:yio,secureHeaders:xio,streamSSE:vio,timeout:bio}=Ha,Tio=globalThis.fetch,Sio=globalThis.Request,wio=globalThis.Response,Eio=globalThis.Headers,_io=globalThis.FormData,Cio=globalThis.File,kio=globalThis.Blob,Rio=Ha.Agent,Aio=Ha.Pool,Iio=Ha.Client,Pio=Ha.Dispatcher,Oio=Ha.MockAgent});var _qe={};J(_qe,{GoogleTTSHandler:()=>LT});var LT,A3=E(()=>{"use strict";Eqe();ra();q();Kn();LT=class r{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=r.DEFAULT_MAX_TEXT_LENGTH;constructor(e){let t=e??process.env.GOOGLE_APPLICATION_CREDENTIALS;t&&(this.client=new wqe({keyFilename:t}))}isConfigured(){return this.client!==null}async getVoices(e){if(!this.client)throw new bt({code:Ut.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let t=le.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e){let i=le.endSpan(t,1);return Pe().recordSpan(i),this.voicesCache.voices}let[n]=await this.client.listVoices(e?{languageCode:e}:{});if(!n.voices||n.voices.length===0){g.warn("Google Cloud TTS returned no voices");let i=le.endSpan(t,1);return Pe().recordSpan(i),[]}let o=[];for(let i of n.voices??[]){if(!i.name||!Array.isArray(i.languageCodes)||i.languageCodes.length===0){g.warn("Skipping voice with missing required fields",{name:i.name,languageCodesCount:i.languageCodes?.length});continue}let a=i.name,c=i.languageCodes,l=c[0],u=this.detectVoiceType(a),d=i.ssmlGender==="MALE"?"male":i.ssmlGender==="FEMALE"?"female":"neutral";o.push({id:a,name:a,languageCode:l,languageCodes:c,gender:d,type:u,naturalSampleRateHertz:i.naturalSampleRateHertz??void 0})}e||(this.voicesCache={voices:o,timestamp:Date.now()});let s=le.endSpan(t,1);return Pe().recordSpan(s),o}catch(n){let o=le.endSpan(t,2,n instanceof Error?n.message:"Unknown error");Pe().recordSpan(o);let s=n instanceof Error?n.message:"Unknown error";return g.error(`Failed to fetch Google TTS voices: ${s}`),[]}}async synthesize(e,t){if(!this.client)throw new bt({code:Ut.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});let n=t.voice??"en-US-Neural2-C",o=le.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":n,"tts.format":t.format??"mp3"}),s=Date.now();try{let i=e.startsWith("<speak>")&&e.endsWith("</speak>");if(e.startsWith("<speak>")&&!e.endsWith("</speak>")||!e.startsWith("<speak>")&&e.endsWith("</speak>"))throw new bt({code:Ut.INVALID_INPUT,message:"Malformed SSML: missing opening <speak> or closing </speak> tag.",category:"validation",severity:"medium",retriable:!1});let a=this.extractLanguageCode(n),c=this.mapFormat(t.format??"mp3"),l={input:i?{ssml:e}:{text:e},voice:{name:n,languageCode:a},audioConfig:{audioEncoding:c,speakingRate:t.speed??1,pitch:t.pitch??0,volumeGainDb:t.volumeGainDb??0}},[u]=await this.client.synthesizeSpeech(l,{timeout:r.DEFAULT_API_TIMEOUT_MS}),d=u.audioContent;if(!d)throw new bt({code:Ut.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});let m=d instanceof Uint8Array?Buffer.from(d):typeof d=="string"?Buffer.from(d,"base64"):(()=>{throw new bt({code:Ut.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof d}})})(),f=Date.now()-s,h=le.endSpan(o,1);return Pe().recordSpan(h),{buffer:m,format:t.format??"mp3",size:m.length,voice:n,metadata:{latency:f,provider:"google-ai"}}}catch(i){let a=le.endSpan(o,2,i instanceof Error?i.message:String(i));if(Pe().recordSpan(a),i instanceof bt)throw i;let c=Date.now()-s,l=i instanceof Error?i.message:"Unknown error";throw new bt({code:Ut.SYNTHESIS_FAILED,message:`Google TTS failed after ${c}ms: ${l}`,category:"execution",severity:"high",retriable:!0,context:{latency:c},originalError:i instanceof Error?i:void 0})}}extractLanguageCode(e){let t=e.split("-");if(t.length>=2)return`${t[0]}-${t[1]}`;throw new bt({code:Ut.INVALID_INPUT,message:`Invalid Google TTS voiceId format: "${e}". Expected format like "en-US-Neural2-C".`,category:"validation",severity:"medium",retriable:!1,context:{voiceId:e}})}mapFormat(e){switch(e.toLowerCase()){case"mp3":return"MP3";case"wav":return"LINEAR16";case"ogg":case"opus":return"OGG_OPUS";default:throw new bt({code:Ut.INVALID_INPUT,message:`Unsupported audio format: ${e}`,category:"validation",severity:"medium",retriable:!1,context:{format:e}})}}detectVoiceType(e){let t=e.toLowerCase().split("-");return t.some(n=>n.startsWith("chirp"))?"chirp":t.includes("neural2")?"neural":t.includes("wavenet")?"wavenet":t.includes("standard")?"standard":"unknown"}}});var Cqe={};J(Cqe,{OpenAITTS:()=>Dg});var Dg,I3=E(()=>{"use strict";q();ra();Dg=class r{apiKey;baseUrl="https://api.openai.com/v1";maxTextLength=4096;static VOICES=[{id:"alloy",name:"Alloy",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"echo",name:"Echo",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"fable",name:"Fable",languageCode:"en",languageCodes:["en"],gender:"neutral",type:"neural"},{id:"onyx",name:"Onyx",languageCode:"en",languageCodes:["en"],gender:"male",type:"neural"},{id:"nova",name:"Nova",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"},{id:"shimmer",name:"Shimmer",languageCode:"en",languageCodes:["en"],gender:"female",type:"neural"}];constructor(e){let t=(e??process.env.OPENAI_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){return e&&!e.startsWith("en"),r.VOICES}async synthesize(e,t={}){if(!this.apiKey)throw new bt({code:Ut.PROVIDER_NOT_CONFIGURED,message:"OpenAI TTS API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=o.model??(t.quality==="hd"?"tts-1-hd":"tts-1"),i=t.voice??"alloy",a=this.mapFormat(t.format??"mp3"),c={model:s,input:e,voice:i,response_format:a,speed:t.speed??1},l=new AbortController,u=setTimeout(()=>l.abort(),3e4),d;try{d=await fetch(`${this.baseUrl}/audio/speech`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(c),signal:l.signal})}catch(b){throw b instanceof Error&&b.name==="AbortError"?new bt({code:Ut.SYNTHESIS_FAILED,message:"OpenAI TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:b}):b}finally{clearTimeout(u)}if(!d.ok){let T=(await d.json().catch(()=>Object.create(null))).error?.message||`HTTP ${d.status}`,w=d.status===408||d.status===429||d.status>=500;throw new bt({code:Ut.SYNTHESIS_FAILED,message:T,category:w?"network":"execution",severity:"high",retriable:w,context:{status:d.status,model:s,responseFormat:a}})}let m=Date.now()-n,f=await d.arrayBuffer(),h=Buffer.from(f),y=this.effectiveFormat(a),x={buffer:h,format:y,size:h.length,voice:i,sampleRate:this.getSampleRate(y),metadata:{latency:m,provider:"openai-tts",model:s,requestedFormat:t.format,responseFormat:a}};return g.info(`[OpenAITTSHandler] Synthesized ${h.length} bytes in ${m}ms`),x}catch(s){if(s instanceof bt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[OpenAITTSHandler] Synthesis failed: ${i}`),new bt({code:Ut.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapFormat(e){let n={mp3:"mp3",wav:"wav",ogg:"opus",opus:"opus",pcm16:"pcm"}[e];return n===void 0?(g.warn(`[OpenAITTSHandler] Unsupported format "${e}" \u2014 falling back to "mp3". Supported formats: mp3, wav, ogg, opus, pcm16.`),"mp3"):n}getSampleRate(e){switch(e){case"opus":case"ogg":return 48e3;default:return 24e3}}effectiveFormat(e){switch(e){case"mp3":return"mp3";case"wav":return"wav";case"opus":return"opus";case"pcm":return"pcm16";default:return"mp3"}}}});var kqe={};J(kqe,{ElevenLabsTTS:()=>Lg});var Lg,P3=E(()=>{"use strict";q();ra();Lg=class r{apiKey;baseUrl="https://api.elevenlabs.io/v1";voicesCache=null;static CACHE_TTL_MS=300*1e3;maxTextLength=5e3;constructor(e){let t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null}isConfigured(){return this.apiKey!==null}async getVoices(e){if(!this.apiKey)throw new bt({code:Ut.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`${this.baseUrl}/voices`,{method:"GET",headers:{"xi-api-key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new bt({code:Ut.SYNTHESIS_FAILED,message:"ElevenLabs voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).voices.map(a=>({id:a.voice_id,name:a.name,languageCode:"en",languageCodes:["en","es","fr","de","it","pt","pl","hi","ar","zh","ja","ko"],gender:this.mapGender(a.labels?.gender),type:"neural",description:a.labels?.description}));if(e){let a=e.toLowerCase(),c=a.split("-")[0];i=i.filter(l=>l.languageCodes?.some(u=>{let d=u.toLowerCase();return d===a||d===c||d.startsWith(c)}))}return e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Failed to get voices: ${n}`),new bt({code:Ut.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new bt({code:Ut.PROVIDER_NOT_CONFIGURED,message:"ElevenLabs API key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"21m00Tcm4TlvDq8ikWAM",i=o.model??"eleven_multilingual_v2",a={text:e,model_id:i,voice_settings:{stability:o.stability??.5,similarity_boost:o.similarityBoost??.75,style:o.style??0,use_speaker_boost:o.useSpeakerBoost??!0}},c=this.mapFormat(t.format??"mp3"),l=new AbortController,u=setTimeout(()=>l.abort(),3e4),d;try{d=await fetch(`${this.baseUrl}/text-to-speech/${s}?output_format=${c}`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(x){throw x instanceof Error&&x.name==="AbortError"?new bt({code:Ut.SYNTHESIS_FAILED,message:"ElevenLabs TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:x}):x}finally{clearTimeout(u)}if(!d.ok){let b=(await d.json().catch(()=>Object.create(null))).detail?.message||`HTTP ${d.status}`;throw new Error(b)}let m=Date.now()-n,f=await d.arrayBuffer(),h=Buffer.from(f),y={buffer:h,format:this.effectiveFormat(c),size:h.length,voice:s,sampleRate:this.getSampleRate(c),metadata:{latency:m,provider:"elevenlabs-tts",model:i,requestedFormat:t.format,outputFormat:c}};return g.info(`[ElevenLabsTTSHandler] Synthesized ${h.length} bytes in ${m}ms`),y}catch(s){if(s instanceof bt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[ElevenLabsTTSHandler] Synthesis failed: ${i}`),new bt({code:Ut.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}mapGender(e){if(!e)return"neutral";let t=e.toLowerCase();return t.includes("male")&&!t.includes("female")?"male":t.includes("female")?"female":"neutral"}mapFormat(e){return{mp3:"mp3_44100_128",wav:"pcm_44100",ogg:"ogg_22050",opus:"ogg_22050"}[e]??"mp3_44100_128"}getSampleRate(e){return e.includes("44100")?44100:e.includes("22050")?22050:e.includes("24000")?24e3:44100}effectiveFormat(e){return e.startsWith("mp3")?"mp3":e.startsWith("pcm")?"pcm16":e.startsWith("ogg")?"opus":"mp3"}}});var Rqe={};J(Rqe,{AzureTTS:()=>Ug});var Ug,O3=E(()=>{"use strict";q();ra();Ug=class r{apiKey;region;voicesCache=null;static CACHE_TTL_MS=1800*1e3;maxTextLength=1e4;constructor(e,t){let n=(e??process.env.AZURE_SPEECH_KEY??"").trim();this.apiKey=n.length>0?n:null;let o=(t??process.env.AZURE_SPEECH_REGION??"").trim();this.region=o.length>0?o:"eastus"}isConfigured(){return this.apiKey!==null&&this.region.length>0}async getVoices(e){if(!this.apiKey)throw new bt({code:Ut.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<r.CACHE_TTL_MS&&!e)return this.voicesCache.voices;try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),o;try{o=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/voices/list`,{method:"GET",headers:{"Ocp-Apim-Subscription-Key":this.apiKey},signal:t.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new bt({code:Ut.SYNTHESIS_FAILED,message:"Azure TTS voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).map(a=>({id:a.ShortName,name:a.DisplayName,languageCode:a.Locale,languageCodes:[a.Locale],gender:this.mapGender(a.Gender),type:a.VoiceType.toLowerCase().includes("neural")?"neural":"standard",description:a.LocaleName}));return e&&(i=i.filter(a=>a.languageCode.toLowerCase().startsWith(e.toLowerCase())||a.languageCode.toLowerCase()===e.toLowerCase())),e||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(t){if(t instanceof bt)throw t;let n=t instanceof Error?t.message:String(t||"Unknown error");throw g.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new bt({code:Ut.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:t instanceof Error?t:void 0})}}async synthesize(e,t={}){if(!this.apiKey)throw new bt({code:Ut.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});let n=Date.now(),o=t;try{let s=t.voice??"en-US-JennyNeural",i=o.outputFormat??this.mapFormat(t.format??"mp3"),a=this.buildSSML(e,s,t),c=new AbortController,l=setTimeout(()=>c.abort(),3e4),u;try{u=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.apiKey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":i},body:a,signal:c.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new bt({code:Ut.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(l)}if(!u.ok){let y=await u.text();throw new Error(`HTTP ${u.status}: ${y}`)}let d=Date.now()-n,m=await u.arrayBuffer(),f=Buffer.from(m),h={buffer:f,format:this.effectiveFormat(i),size:f.length,voice:s,sampleRate:this.getSampleRate(i),metadata:{latency:d,provider:"azure-tts",requestedFormat:t.format,outputFormat:i,region:this.region}};return g.info(`[AzureTTSHandler] Synthesized ${f.length} bytes in ${d}ms`),h}catch(s){if(s instanceof bt)throw s;let i=s instanceof Error?s.message:String(s||"Unknown error");throw g.error(`[AzureTTSHandler] Synthesis failed: ${i}`),new bt({code:Ut.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:e.length},originalError:s instanceof Error?s:void 0})}}buildSSML(e,t,n){let o=n;if(o.ssmlTemplate)return o.ssmlTemplate.replace("{text}",this.escapeXml(e)).replace("{voice}",this.escapeXml(t));if(o.allowRawSSML&&e.trim().startsWith("<speak"))return e;let s=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",i=n.pitch??0,a=i>=0?`+${Math.round(i)}st`:`${Math.round(i)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(t))}">
|
|
2138
2138
|
<voice name="${this.escapeXml(t)}">
|
package/dist/lib/neurolink.js
CHANGED
|
@@ -340,7 +340,7 @@ export class NeuroLink {
|
|
|
340
340
|
* @param result - The result of the tool execution (optional)
|
|
341
341
|
* @param error - The error if execution failed (optional)
|
|
342
342
|
*/
|
|
343
|
-
emitToolEndEvent(toolName, startTime, success, result, error) {
|
|
343
|
+
emitToolEndEvent(toolName, startTime, success, result, error, executionId) {
|
|
344
344
|
// Emit tool end event (NeuroLink format - enhanced with result/error)
|
|
345
345
|
// Serialize error to string for consumer compatibility (event listeners
|
|
346
346
|
// commonly check `typeof event.error === "string"`).
|
|
@@ -350,6 +350,7 @@ export class NeuroLink {
|
|
|
350
350
|
timestamp: Date.now(),
|
|
351
351
|
result,
|
|
352
352
|
error: error ? error.message : undefined,
|
|
353
|
+
executionId,
|
|
353
354
|
}));
|
|
354
355
|
}
|
|
355
356
|
// Conversation memory support
|
|
@@ -8576,9 +8577,16 @@ Current user's request: ${currentInput}`;
|
|
|
8576
8577
|
: params
|
|
8577
8578
|
? JSON.stringify(params)
|
|
8578
8579
|
: "";
|
|
8580
|
+
const executionStartTime = Date.now();
|
|
8581
|
+
// Per-invocation id so consumers can correlate a tool:start with its matching
|
|
8582
|
+
// tool:end even when the same tool runs multiple times concurrently.
|
|
8583
|
+
const executionId = `${toolName}-${executionStartTime}-${Math.random()
|
|
8584
|
+
.toString(36)
|
|
8585
|
+
.slice(2, 11)}`;
|
|
8579
8586
|
return {
|
|
8580
8587
|
functionTag: "NeuroLink.executeTool",
|
|
8581
|
-
executionStartTime
|
|
8588
|
+
executionStartTime,
|
|
8589
|
+
executionId,
|
|
8582
8590
|
externalTool,
|
|
8583
8591
|
toolType,
|
|
8584
8592
|
inputSize: inputStr.length,
|
|
@@ -8636,6 +8644,7 @@ Current user's request: ${currentInput}`;
|
|
|
8636
8644
|
this.emitter.emit("tool:start", createToolEventPayload(toolName, {
|
|
8637
8645
|
timestamp: executionContext.executionStartTime,
|
|
8638
8646
|
input: params,
|
|
8647
|
+
executionId: executionContext.executionId,
|
|
8639
8648
|
}));
|
|
8640
8649
|
const toolInfo = this.toolRegistry.getToolInfo(toolName);
|
|
8641
8650
|
const finalOptions = {
|
|
@@ -8801,7 +8810,7 @@ Current user's request: ${currentInput}`;
|
|
|
8801
8810
|
prepared.metrics.errorCategories[mappedCategory] =
|
|
8802
8811
|
(prepared.metrics.errorCategories[mappedCategory] || 0) + 1;
|
|
8803
8812
|
}
|
|
8804
|
-
this.emitToolEndEvent(toolName, executionContext.executionStartTime, !isToolError, result, isToolError && errorText ? new Error(errorText) : undefined);
|
|
8813
|
+
this.emitToolEndEvent(toolName, executionContext.executionStartTime, !isToolError, result, isToolError && errorText ? new Error(errorText) : undefined, executionContext.executionId);
|
|
8805
8814
|
toolSpan.setAttribute("tool.result.status", isToolError ? "error" : "success");
|
|
8806
8815
|
toolSpan.setAttribute("tool.duration_ms", executionTime);
|
|
8807
8816
|
return result;
|
|
@@ -8820,7 +8829,7 @@ Current user's request: ${currentInput}`;
|
|
|
8820
8829
|
});
|
|
8821
8830
|
prepared.metrics.errorCategories[ErrorCategory.EXECUTION] =
|
|
8822
8831
|
(prepared.metrics.errorCategories[ErrorCategory.EXECUTION] || 0) + 1;
|
|
8823
|
-
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, new Error(`Circuit breaker open for ${toolName} (state=${error.breakerState}, failures=${error.failureCount})`));
|
|
8832
|
+
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, new Error(`Circuit breaker open for ${toolName} (state=${error.breakerState}, failures=${error.failureCount})`), executionContext.executionId);
|
|
8824
8833
|
toolSpan.setAttribute("tool.result.status", "circuit_breaker_open");
|
|
8825
8834
|
toolSpan.setAttribute("tool.duration_ms", executionTime);
|
|
8826
8835
|
toolSpan.setAttribute("tool.circuit_breaker.state", error.breakerState);
|
|
@@ -8875,7 +8884,7 @@ Current user's request: ${currentInput}`;
|
|
|
8875
8884
|
const category = structuredError.category || ErrorCategory.EXECUTION;
|
|
8876
8885
|
prepared.metrics.errorCategories[category] =
|
|
8877
8886
|
(prepared.metrics.errorCategories[category] || 0) + 1;
|
|
8878
|
-
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, structuredError);
|
|
8887
|
+
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, structuredError, executionContext.executionId);
|
|
8879
8888
|
// Gate on listenerCount: Node EventEmitter rethrows the original error
|
|
8880
8889
|
// from emit("error", e) when no listener is registered, which would
|
|
8881
8890
|
// short-circuit the surrounding flow and surface as an unhandled
|
|
@@ -220,7 +220,7 @@ export async function executeAutoresearchTick(task, neurolink, emitter) {
|
|
|
220
220
|
...(phasePolicy.forcedTool
|
|
221
221
|
? {
|
|
222
222
|
prepareStep: ({ stepNumber }) => {
|
|
223
|
-
if (stepNumber === 0) {
|
|
223
|
+
if (stepNumber === 0 && phasePolicy.forcedTool) {
|
|
224
224
|
return {
|
|
225
225
|
toolChoice: {
|
|
226
226
|
type: "tool",
|
|
@@ -128,7 +128,6 @@ async function executeModel(options, workflowDefaultSystemPrompt) {
|
|
|
128
128
|
let result;
|
|
129
129
|
let attempts = 0;
|
|
130
130
|
const MAX_ATTEMPTS = 2;
|
|
131
|
-
/* eslint-disable no-constant-condition */
|
|
132
131
|
while (true) {
|
|
133
132
|
attempts++;
|
|
134
133
|
result = await executeWithTimeout(async () => {
|
|
@@ -145,7 +144,6 @@ async function executeModel(options, workflowDefaultSystemPrompt) {
|
|
|
145
144
|
}
|
|
146
145
|
logger.warn(`[${functionTag}] Model returned empty content — retrying once`, { provider: model.provider, model: model.model, attempt: attempts });
|
|
147
146
|
}
|
|
148
|
-
/* eslint-enable no-constant-condition */
|
|
149
147
|
const responseTime = Date.now() - startTime;
|
|
150
148
|
logger.debug(`[${functionTag}] Model execution successful`, {
|
|
151
149
|
provider: model.provider,
|
package/dist/neurolink.js
CHANGED
|
@@ -340,7 +340,7 @@ export class NeuroLink {
|
|
|
340
340
|
* @param result - The result of the tool execution (optional)
|
|
341
341
|
* @param error - The error if execution failed (optional)
|
|
342
342
|
*/
|
|
343
|
-
emitToolEndEvent(toolName, startTime, success, result, error) {
|
|
343
|
+
emitToolEndEvent(toolName, startTime, success, result, error, executionId) {
|
|
344
344
|
// Emit tool end event (NeuroLink format - enhanced with result/error)
|
|
345
345
|
// Serialize error to string for consumer compatibility (event listeners
|
|
346
346
|
// commonly check `typeof event.error === "string"`).
|
|
@@ -350,6 +350,7 @@ export class NeuroLink {
|
|
|
350
350
|
timestamp: Date.now(),
|
|
351
351
|
result,
|
|
352
352
|
error: error ? error.message : undefined,
|
|
353
|
+
executionId,
|
|
353
354
|
}));
|
|
354
355
|
}
|
|
355
356
|
// Conversation memory support
|
|
@@ -8576,9 +8577,16 @@ Current user's request: ${currentInput}`;
|
|
|
8576
8577
|
: params
|
|
8577
8578
|
? JSON.stringify(params)
|
|
8578
8579
|
: "";
|
|
8580
|
+
const executionStartTime = Date.now();
|
|
8581
|
+
// Per-invocation id so consumers can correlate a tool:start with its matching
|
|
8582
|
+
// tool:end even when the same tool runs multiple times concurrently.
|
|
8583
|
+
const executionId = `${toolName}-${executionStartTime}-${Math.random()
|
|
8584
|
+
.toString(36)
|
|
8585
|
+
.slice(2, 11)}`;
|
|
8579
8586
|
return {
|
|
8580
8587
|
functionTag: "NeuroLink.executeTool",
|
|
8581
|
-
executionStartTime
|
|
8588
|
+
executionStartTime,
|
|
8589
|
+
executionId,
|
|
8582
8590
|
externalTool,
|
|
8583
8591
|
toolType,
|
|
8584
8592
|
inputSize: inputStr.length,
|
|
@@ -8636,6 +8644,7 @@ Current user's request: ${currentInput}`;
|
|
|
8636
8644
|
this.emitter.emit("tool:start", createToolEventPayload(toolName, {
|
|
8637
8645
|
timestamp: executionContext.executionStartTime,
|
|
8638
8646
|
input: params,
|
|
8647
|
+
executionId: executionContext.executionId,
|
|
8639
8648
|
}));
|
|
8640
8649
|
const toolInfo = this.toolRegistry.getToolInfo(toolName);
|
|
8641
8650
|
const finalOptions = {
|
|
@@ -8801,7 +8810,7 @@ Current user's request: ${currentInput}`;
|
|
|
8801
8810
|
prepared.metrics.errorCategories[mappedCategory] =
|
|
8802
8811
|
(prepared.metrics.errorCategories[mappedCategory] || 0) + 1;
|
|
8803
8812
|
}
|
|
8804
|
-
this.emitToolEndEvent(toolName, executionContext.executionStartTime, !isToolError, result, isToolError && errorText ? new Error(errorText) : undefined);
|
|
8813
|
+
this.emitToolEndEvent(toolName, executionContext.executionStartTime, !isToolError, result, isToolError && errorText ? new Error(errorText) : undefined, executionContext.executionId);
|
|
8805
8814
|
toolSpan.setAttribute("tool.result.status", isToolError ? "error" : "success");
|
|
8806
8815
|
toolSpan.setAttribute("tool.duration_ms", executionTime);
|
|
8807
8816
|
return result;
|
|
@@ -8820,7 +8829,7 @@ Current user's request: ${currentInput}`;
|
|
|
8820
8829
|
});
|
|
8821
8830
|
prepared.metrics.errorCategories[ErrorCategory.EXECUTION] =
|
|
8822
8831
|
(prepared.metrics.errorCategories[ErrorCategory.EXECUTION] || 0) + 1;
|
|
8823
|
-
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, new Error(`Circuit breaker open for ${toolName} (state=${error.breakerState}, failures=${error.failureCount})`));
|
|
8832
|
+
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, new Error(`Circuit breaker open for ${toolName} (state=${error.breakerState}, failures=${error.failureCount})`), executionContext.executionId);
|
|
8824
8833
|
toolSpan.setAttribute("tool.result.status", "circuit_breaker_open");
|
|
8825
8834
|
toolSpan.setAttribute("tool.duration_ms", executionTime);
|
|
8826
8835
|
toolSpan.setAttribute("tool.circuit_breaker.state", error.breakerState);
|
|
@@ -8875,7 +8884,7 @@ Current user's request: ${currentInput}`;
|
|
|
8875
8884
|
const category = structuredError.category || ErrorCategory.EXECUTION;
|
|
8876
8885
|
prepared.metrics.errorCategories[category] =
|
|
8877
8886
|
(prepared.metrics.errorCategories[category] || 0) + 1;
|
|
8878
|
-
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, structuredError);
|
|
8887
|
+
this.emitToolEndEvent(toolName, executionContext.executionStartTime, false, undefined, structuredError, executionContext.executionId);
|
|
8879
8888
|
// Gate on listenerCount: Node EventEmitter rethrows the original error
|
|
8880
8889
|
// from emit("error", e) when no listener is registered, which would
|
|
8881
8890
|
// short-circuit the surrounding flow and surface as an unhandled
|
|
@@ -220,7 +220,7 @@ export async function executeAutoresearchTick(task, neurolink, emitter) {
|
|
|
220
220
|
...(phasePolicy.forcedTool
|
|
221
221
|
? {
|
|
222
222
|
prepareStep: ({ stepNumber }) => {
|
|
223
|
-
if (stepNumber === 0) {
|
|
223
|
+
if (stepNumber === 0 && phasePolicy.forcedTool) {
|
|
224
224
|
return {
|
|
225
225
|
toolChoice: {
|
|
226
226
|
type: "tool",
|
|
@@ -128,7 +128,6 @@ async function executeModel(options, workflowDefaultSystemPrompt) {
|
|
|
128
128
|
let result;
|
|
129
129
|
let attempts = 0;
|
|
130
130
|
const MAX_ATTEMPTS = 2;
|
|
131
|
-
/* eslint-disable no-constant-condition */
|
|
132
131
|
while (true) {
|
|
133
132
|
attempts++;
|
|
134
133
|
result = await executeWithTimeout(async () => {
|
|
@@ -145,7 +144,6 @@ async function executeModel(options, workflowDefaultSystemPrompt) {
|
|
|
145
144
|
}
|
|
146
145
|
logger.warn(`[${functionTag}] Model returned empty content — retrying once`, { provider: model.provider, model: model.model, attempt: attempts });
|
|
147
146
|
}
|
|
148
|
-
/* eslint-enable no-constant-condition */
|
|
149
147
|
const responseTime = Date.now() - startTime;
|
|
150
148
|
logger.debug(`[${functionTag}] Model execution successful`, {
|
|
151
149
|
provider: model.provider,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.79.0",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "Universal AI Development Platform with working MCP integration, multi-provider support, voice (TTS/STT/realtime), and professional CLI. 58+ external MCP servers discoverable, multimodal file processing, RAG pipelines. Build, test, and deploy AI applications with 21+ providers: OpenAI, Anthropic, Google AI Studio, Google Vertex, AWS Bedrock, Azure OpenAI, Mistral, LiteLLM, SageMaker, Hugging Face, Ollama, OpenAI-compatible, OpenRouter, DeepSeek, NVIDIA NIM, LM Studio, llama.cpp, plus voice (OpenAI TTS, ElevenLabs, Deepgram, Azure Speech).",
|
|
6
6
|
"author": {
|