@juspay/neurolink 12.7.4 → 12.7.5
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
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
## [12.7.
|
|
1
|
+
## [12.7.5](https://github.com/juspay/neurolink/compare/v12.7.4...v12.7.5) (2026-09-01)
|
|
2
2
|
|
|
3
3
|
### Bug Fixes
|
|
4
4
|
|
|
5
|
-
- **(
|
|
5
|
+
- **(memory):** guard retrieve_context on Redis capability ([f94b9d2](https://github.com/juspay/neurolink/commit/f94b9d2eb7dcce6374473c79bb5165373c1a52ab))
|
|
6
6
|
|
|
7
7
|
## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
|
|
8
8
|
|
|
@@ -1489,7 +1489,7 @@ Original size: ${Yk(n)} | Externalized \u2014 use retrieve_context with artifact
|
|
|
1489
1489
|
\u2022 Review previous assistant responses
|
|
1490
1490
|
\u2022 Search through conversation history
|
|
1491
1491
|
Supports filtering by role, pagination for large content, and regex search.
|
|
1492
|
-
To fetch an externalized artifact, provide \`artifactId\` (omit sessionId).`,inputSchema:p.object({sessionId:p.string().optional().describe("Session ID for conversation history retrieval. Required unless artifactId is provided."),artifactId:p.string().optional().describe("Artifact ID from an externalized MCP tool output (visible in the tool output as neurolinkArtifactId=<id>). When provided, returns the full stored payload directly."),messageId:p.string().optional().describe("Specific message ID to retrieve"),role:p.enum(["user","assistant","system","tool_call","tool_result"]).optional().describe("Filter messages by role"),lastN:p.number().int().positive().optional().describe("Retrieve the last N messages matching the filter"),offset:p.number().int().nonnegative().optional().describe("Character offset for paginated reading of large content (default: 0)"),limit:p.number().int().positive().optional().describe("Max characters to return per message (default: 50000)"),search:p.string().optional().describe("Regex pattern to search within message content. Returns matching lines with line numbers.")}),execute:async r=>gt({name:"neurolink.memory.retrieve_context",tracer:He.memory,attributes:{"memory.operation":r.artifactId?"artifact.fetch":"session.retrieve","memory.has_artifact_id":!!r.artifactId,"memory.has_session_id":!!r.sessionId,"memory.role":r.role??"any","memory.search":!!r.search}},async n=>Bjr(r,e,t,n))}}}async function Bjr(e,t,r,n){if(e.artifactId){if(!r)return f.warn("[MemoryRetrievalTools] retrieve_context called with artifactId but no ArtifactStore is configured"),n.setStatus({code:qe.ERROR,message:"Artifact store not configured"}),{error:"Artifact store not configured \u2014 mcp.outputLimits.strategy must be set to 'externalize' to use artifactId retrieval",artifactId:e.artifactId};const a=await Ze(r.retrieve(e.artifactId),1e4,new Error(`ArtifactStore.retrieve() timed out for artifact "${e.artifactId}"`));if(a===null)return n.setStatus({code:qe.ERROR,message:"Artifact not found or has expired"}),{error:"Artifact not found or has expired",artifactId:e.artifactId};const l=Math.min(e.limit??ore,sre),c=e.offset??0,u=a.slice(c,c+l);return n.setAttribute("memory.artifact_size",a.length),n.setAttribute("memory.returned_bytes",u.length),{artifactId:e.artifactId,content:u,totalSize:a.length,hasMore:c+l<a.length,offset:c,limit:l}}if(!e.sessionId)return n.setStatus({code:qe.ERROR,message:"sessionId is required when artifactId is not provided"}),{error:"sessionId is required when artifactId is not provided"};if(!t)return n.setStatus({code:qe.ERROR,message:"Memory manager not configured"}),{error:"Session history retrieval requires Redis conversation memory \u2014 enable mcp.conversationMemory with a Redis backend, or use artifactId to retrieve an externalized MCP tool output."};const o=Oe.createSpan("memory","memory.retrieve",{"memory.operation":"retrieve","memory.store":"redis","memory.query":e.search||e.messageId||`lastN:${e.lastN??"all"}`}),s=Date.now(),i=String(e.sessionId);try{const a=await Ze(t.getSessionRaw(i),1e4,new Error(`getSessionRaw() timed out for session "${i}"`));if(!a){const m=Oe.endSpan(o,2,`Session not found: ${i}`);return ut().recordSpan(m),{error:"Session not found",sessionId:i}}let l=a.messages;if(e.messageId){const m=l.find(h=>h.id===e.messageId);if(!m){const h=Oe.endSpan(o,2,`Message not found: ${e.messageId}`);return ut().recordSpan(h),{error:"Message not found",messageId:e.messageId}}l=[m]}e.role&&(l=l.filter(m=>m.role===e.role)),e.lastN&&(l=l.slice(-e.lastN));const c=Math.min(e.limit??ore,sre),u=l.map(m=>{const h=m.content??"";if(e.search)try{const _=e.search;if(_.length>200)return{id:m.id,error:"Search pattern too long (max 200 chars)"};const b=_.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),T=new RegExp(b,"i"),x=h.split(`
|
|
1492
|
+
To fetch an externalized artifact, provide \`artifactId\` (omit sessionId).`,inputSchema:p.object({sessionId:p.string().optional().describe("Session ID for conversation history retrieval. Required unless artifactId is provided."),artifactId:p.string().optional().describe("Artifact ID from an externalized MCP tool output (visible in the tool output as neurolinkArtifactId=<id>). When provided, returns the full stored payload directly."),messageId:p.string().optional().describe("Specific message ID to retrieve"),role:p.enum(["user","assistant","system","tool_call","tool_result"]).optional().describe("Filter messages by role"),lastN:p.number().int().positive().optional().describe("Retrieve the last N messages matching the filter"),offset:p.number().int().nonnegative().optional().describe("Character offset for paginated reading of large content (default: 0)"),limit:p.number().int().positive().optional().describe("Max characters to return per message (default: 50000)"),search:p.string().optional().describe("Regex pattern to search within message content. Returns matching lines with line numbers.")}),execute:async r=>gt({name:"neurolink.memory.retrieve_context",tracer:He.memory,attributes:{"memory.operation":r.artifactId?"artifact.fetch":"session.retrieve","memory.has_artifact_id":!!r.artifactId,"memory.has_session_id":!!r.sessionId,"memory.role":r.role??"any","memory.search":!!r.search}},async n=>Bjr(r,e,t,n))}}}async function Bjr(e,t,r,n){if(e.artifactId){if(!r)return f.warn("[MemoryRetrievalTools] retrieve_context called with artifactId but no ArtifactStore is configured"),n.setStatus({code:qe.ERROR,message:"Artifact store not configured"}),{error:"Artifact store not configured \u2014 mcp.outputLimits.strategy must be set to 'externalize' to use artifactId retrieval",artifactId:e.artifactId};const a=await Ze(r.retrieve(e.artifactId),1e4,new Error(`ArtifactStore.retrieve() timed out for artifact "${e.artifactId}"`));if(a===null)return n.setStatus({code:qe.ERROR,message:"Artifact not found or has expired"}),{error:"Artifact not found or has expired",artifactId:e.artifactId};const l=Math.min(e.limit??ore,sre),c=e.offset??0,u=a.slice(c,c+l);return n.setAttribute("memory.artifact_size",a.length),n.setAttribute("memory.returned_bytes",u.length),{artifactId:e.artifactId,content:u,totalSize:a.length,hasMore:c+l<a.length,offset:c,limit:l}}if(!e.sessionId)return n.setStatus({code:qe.ERROR,message:"sessionId is required when artifactId is not provided"}),{error:"sessionId is required when artifactId is not provided"};if(!t||!("getSessionRaw"in t))return n.setStatus({code:qe.ERROR,message:t?"Conversation memory backend is not Redis":"Memory manager not configured"}),{error:"Session history retrieval requires Redis conversation memory \u2014 enable mcp.conversationMemory with a Redis backend, or use artifactId to retrieve an externalized MCP tool output."};const o=Oe.createSpan("memory","memory.retrieve",{"memory.operation":"retrieve","memory.store":"redis","memory.query":e.search||e.messageId||`lastN:${e.lastN??"all"}`}),s=Date.now(),i=String(e.sessionId);try{const a=await Ze(t.getSessionRaw(i),1e4,new Error(`getSessionRaw() timed out for session "${i}"`));if(!a){const m=Oe.endSpan(o,2,`Session not found: ${i}`);return ut().recordSpan(m),{error:"Session not found",sessionId:i}}let l=a.messages;if(e.messageId){const m=l.find(h=>h.id===e.messageId);if(!m){const h=Oe.endSpan(o,2,`Message not found: ${e.messageId}`);return ut().recordSpan(h),{error:"Message not found",messageId:e.messageId}}l=[m]}e.role&&(l=l.filter(m=>m.role===e.role)),e.lastN&&(l=l.slice(-e.lastN));const c=Math.min(e.limit??ore,sre),u=l.map(m=>{const h=m.content??"";if(e.search)try{const _=e.search;if(_.length>200)return{id:m.id,error:"Search pattern too long (max 200 chars)"};const b=_.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),T=new RegExp(b,"i"),x=h.split(`
|
|
1493
1493
|
`).map((I,M)=>({line:M+1,text:I})).filter(I=>T.test(I.text)).slice(0,XNt);return{id:m.id,role:m.role,tool:m.tool,matchCount:x.length,matches:x,totalSize:h.length}}catch{return{id:m.id,error:"Invalid regex pattern"}}const g=e.offset??0,y=g+c,v=h.slice(g,y);return{id:m.id,role:m.role,tool:m.tool,content:v,totalSize:h.length,hasMore:y<h.length}});o.durationMs=Date.now()-s;const d=Oe.endSpan(o,1);return ut().recordSpan(d),n.setAttribute("memory.message_count",u.length),{messages:u,totalMessages:u.length}}catch(a){o.durationMs=Date.now()-s;const l=Oe.endSpan(o,2);return l.statusMessage=a instanceof Error?a.message:String(a),ut().recordSpan(l),f.error("[MemoryRetrievalTools] Error retrieving context",{error:a instanceof Error?a.message:String(a)}),n.setStatus({code:qe.ERROR,message:a instanceof Error?a.message:String(a)}),n.recordException(a instanceof Error?a:new Error(String(a))),{error:"Failed to retrieve context"}}}var ore,sre,XNt,zjr=S({"src/lib/memory/memoryRetrievalTools.ts"(){"use strict";er(),Gr(),q(),at(),eo(),Wr(),yr(),dc(),ore=5e4,sre=2e5,XNt=50}});function Xk(e){const{instructions:t,...r}=e;return r}function jjr(e){return[...e].sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0)}function QNt(e,t){const r=t.query?.toLowerCase(),n=t.tag?.toLowerCase(),o=e.filter(s=>!((s.status??"active")!=="active"||s.scope==="scoped"&&(!t.scopeId||!(s.scopeIds??[]).includes(t.scopeId))||r&&!(s.name.toLowerCase().includes(r)||(s.displayName??"").toLowerCase().includes(r)||s.description.toLowerCase().includes(r))||n&&!(s.tags??[]).some(a=>a.toLowerCase().includes(n))));return t.limit!==void 0?o.slice(0,t.limit):o}function eLt(e){const t=e.replace(/\\/g,"/");return t.length>0&&!t.startsWith("/")&&!t.split("/").some(r=>r===".."||r==="")}function ire(e,t){return e.scope!=="scoped"?!0:t?(e.scopeIds??[]).includes(t):!1}function tLt(e){const t=e.match(/^[^.!?]*[.!?]/);return t?t[0].trim():e}function qjr(e,t){if(e.length===0)return null;const r=i=>["<available_skills>",...e.map(l=>{const c=l.tags&&l.tags.length>0?` [tags: ${l.tags.join(", ")}]`:"";return`- ${l.name}: ${i(l)}${c}`}),"</available_skills>"].join(`
|
|
1494
1494
|
`),n=r(i=>i.description);if(n.length<=t)return n;const o=r(i=>tLt(i.description));if(o.length<=t)return o;const s=80;return r(i=>{const a=tLt(i.description);return a.length>s?`${a.slice(0,s-1)}\u2026`:a})}function Gjr(e,t){if(e.length===0||t<=0)return null;const r=e.slice(0,t),n=r.map(s=>{const i=s.displayName?`${s.name} (${s.displayName})`:s.name,a=s.tags&&s.tags.length>0?` [tags: ${s.tags.join(", ")}]`:"";return`- ${i}: ${s.description}${a}`}),o=e.length>r.length?`
|
|
1495
1495
|
(${e.length-r.length} more skills exist \u2014 use list_skills to discover them.)`:"";return["## Available Skills","The following team-defined skills (SOPs, playbooks, workflows) are available.","Before answering from general knowledge, check whether one applies to the user's request.","To use a skill, call the use_skill tool with its name to load the full instructions, then follow them exactly.","",...n].join(`
|
|
@@ -2115,7 +2115,7 @@ Use the appropriate agent tool(s) to handle the task. Return a clear, complete f
|
|
|
2115
2115
|
|
|
2116
2116
|
`),errors:o,duration:Date.now()-t,metadata:{executionId:r,strategy:"custom",agentsExecuted:i.size,agentsFailed:o.length}}}updateConfig(e){this.config={...this.config,...e}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}}}}),q2,rBt=S({"src/lib/agent/communication/message-bus.ts"(){"use strict";vn(),Ut(),q(),q2=class{subscriptions=new Map;messageHistory=[];pendingRequests=new Map;deadLetterQueue=[];config;emitter;constructor(e){this.config={maxHistorySize:1e3,defaultTtl:6e4,enablePersistence:!1,enableDeadLetterQueue:!0,requestTimeout:3e4,...e},this.emitter=new sn,this.emitter.setMaxListeners(100),f.debug("[MessageBus] Created with config",{maxHistorySize:this.config.maxHistorySize,enableDeadLetterQueue:this.config.enableDeadLetterQueue})}subscribe(e,t,r,n){const o=st(),s={id:o,topic:e,handler:r,options:n??{},messageCount:0,subscriberId:t},i=this.subscriptions.get(e)??[];return i.push(s),this.subscriptions.set(e,i),f.debug("[MessageBus] Subscription created",{subscriptionId:o,topic:e,subscriberId:t}),this.emitter.emit("subscription:created",{subscriptionId:o,topic:e,subscriberId:t}),o}unsubscribe(e){for(const[t,r]of this.subscriptions){const n=r.findIndex(o=>o.id===e);if(n!==-1)return r.splice(n,1),r.length===0&&this.subscriptions.delete(t),f.debug("[MessageBus] Subscription removed",{subscriptionId:e,topic:t}),!0}return!1}unsubscribeAll(e){let t=0;for(const[r,n]of this.subscriptions){const o=n.filter(s=>s.subscriberId!==e);t+=n.length-o.length,o.length===0?this.subscriptions.delete(r):this.subscriptions.set(r,o)}return t}async publish(e,t,r,n){const o={id:st(),type:n?.type??"event",topic:e,senderId:t,payload:r,priority:n?.priority??"normal",timestamp:Date.now(),ttl:n?.ttl??this.config.defaultTtl,recipientId:n?.recipientId,correlationId:n?.correlationId,replyTo:n?.replyTo,metadata:n?.metadata};await this.deliverMessage(o)}async sendDirect(e,t,r,n){const o=`direct:${t}`,s={id:st(),type:"direct",topic:o,senderId:e,recipientId:t,payload:r,priority:n?.priority??"normal",timestamp:Date.now(),ttl:n?.ttl??this.config.defaultTtl,metadata:n?.metadata};await this.deliverMessage(s)}async request(e,t,r,n){const o=st(),s=`reply:${o}`,i=new Promise((a,l)=>{const c=n??this.config.requestTimeout,u=setTimeout(()=>{this.pendingRequests.delete(o),this.unsubscribeByTopic(s,t),l(new Error(`Request timed out after ${c}ms`))},c);this.pendingRequests.set(o,{resolve:a,reject:l,timeout:u})});return this.subscribe(s,t,a=>{const l=this.pendingRequests.get(o);l&&(clearTimeout(l.timeout),this.pendingRequests.delete(o),this.unsubscribeByTopic(s,t),l.resolve(a))}),await this.publish(e,t,r,{type:"request",correlationId:o,replyTo:s}),i}async reply(e,t,r){if(!e.replyTo)throw new Error("Cannot reply to message without replyTo field");await this.publish(e.replyTo,t,r,{type:"response",correlationId:e.correlationId})}async broadcast(e,t,r){const n={id:st(),type:"broadcast",topic:"broadcast",senderId:e,payload:t,priority:"normal",timestamp:Date.now(),ttl:this.config.defaultTtl};for(const o of this.subscriptions.keys())r?.includes(o)||o.startsWith("reply:")||o.startsWith("direct:")||await this.deliverMessage({...n,topic:o})}async deliverMessage(e){if(this.messageHistory.push(e),this.messageHistory.length>this.config.maxHistorySize&&this.messageHistory.shift(),e.ttl&&Date.now()-e.timestamp>e.ttl){f.debug("[MessageBus] Message expired",{messageId:e.id});return}const t=this.subscriptions.get(e.topic)??[],r=[];for(const n of t)this.shouldDeliver(e,n)&&(n.options.maxMessages!==void 0&&n.options.maxMessages!==-1&&n.messageCount>=n.options.maxMessages||(n.messageCount++,r.push(Promise.resolve(n.handler(e)).catch(o=>{f.error("[MessageBus] Message delivery failed",{messageId:e.id,subscriptionId:n.id,error:o instanceof Error?o.message:String(o)}),this.config.enableDeadLetterQueue&&this.deadLetterQueue.push(e)}))));await Promise.all(r),this.emitter.emit("message:delivered",{messageId:e.id,topic:e.topic})}shouldDeliver(e,t){const r=t.options;return!(r.filterBySender&&!r.filterBySender.includes(e.senderId)||r.filterByType&&!r.filterByType.includes(e.type)||r.filterByPriority&&!r.filterByPriority.includes(e.priority)||r.customFilter&&!r.customFilter(e)||e.type==="direct"&&e.recipientId!==t.subscriberId)}unsubscribeByTopic(e,t){const r=this.subscriptions.get(e);if(r){const n=r.filter(o=>o.subscriberId!==t);n.length===0?this.subscriptions.delete(e):this.subscriptions.set(e,n)}}getHistory(e,t){let r=e?this.messageHistory.filter(n=>n.topic===e):this.messageHistory;return t&&(r=r.slice(-t)),r}getDeadLetterQueue(){return[...this.deadLetterQueue]}clearDeadLetterQueue(){this.deadLetterQueue=[]}async replayHistory(e,t,r){const n=this.messageHistory.filter(s=>s.topic===e&&(!r||s.timestamp>=r)),o=this.subscriptions.get(e)?.filter(s=>s.subscriberId===t)??[];for(const s of n)for(const i of o)this.shouldDeliver(s,i)&&await Promise.resolve(i.handler(s)).catch(()=>{})}getTopics(){return Array.from(this.subscriptions.keys())}getSubscriberCount(e){return this.subscriptions.get(e)?.length??0}getStats(){let e=0;for(const t of this.subscriptions.values())e+=t.length;return{topicCount:this.subscriptions.size,totalSubscriptions:e,historySize:this.messageHistory.length,deadLetterQueueSize:this.deadLetterQueue.length,pendingRequests:this.pendingRequests.size}}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}shutdown(){for(const[,e]of this.pendingRequests)clearTimeout(e.timeout),e.reject(new Error("Message bus shutdown"));this.pendingRequests.clear(),this.subscriptions.clear(),f.debug("[MessageBus] Shutdown complete")}}}}),pse,s9r=S({"src/lib/agent/orchestration/orchestrator.ts"(){"use strict";vn(),Ut(),tBt(),rBt(),q(),pse=class{neurolink;networks=new Map;networkInfo=new Map;coordinators=new Map;messageBus;config;emitter;executionQueue=[];activeExecutions=new Map;constructor(e,t){this.neurolink=e,this.config={defaultMode:"autonomous",maxConcurrentExecutions:5,defaultTimeout:12e4,enableHierarchy:!0,maxHierarchyDepth:3,enableSharedMessageBus:!0,resourceLimits:{maxNetworks:10,maxAgentsPerNetwork:20,maxTotalAgents:100},...t},this.emitter=new sn,this.messageBus=new q2,f.info("[NetworkOrchestrator] Initialized",{maxConcurrentExecutions:this.config.maxConcurrentExecutions,enableHierarchy:this.config.enableHierarchy})}async createNetwork(e,t){if(this.config.resourceLimits?.maxNetworks&&this.networks.size>=this.config.resourceLimits.maxNetworks)throw new Error("Maximum number of networks reached");if(this.config.resourceLimits?.maxAgentsPerNetwork&&e.agents.length>this.config.resourceLimits.maxAgentsPerNetwork)throw new Error(`Maximum agents per network (${this.config.resourceLimits.maxAgentsPerNetwork}) exceeded`);if(this.config.resourceLimits?.maxTotalAgents&&Array.from(this.networkInfo.values()).reduce((i,a)=>i+a.agentCount,0)+e.agents.length>this.config.resourceLimits.maxTotalAgents)throw new Error(`Maximum total agents (${this.config.resourceLimits.maxTotalAgents}) exceeded`);const r=await this.neurolink.createNetwork(e),n={id:r.id,name:r.name,state:"ready",agentCount:e.agents.length,mode:t??this.config.defaultMode,createdAt:Date.now(),executionCount:0,childNetworkIds:[]};this.networkInfo.set(r.id,n),this.networks.set(r.id,r);const o=new j2({strategy:"sequential",maxConcurrency:3});for(const s of r.getAllAgents())o.registerAgent(s);return this.coordinators.set(r.id,o),this.emitter.emit("network:created",{networkId:r.id,name:r.name}),f.info(`[NetworkOrchestrator] Network created: ${r.name}`,{networkId:r.id,agentCount:e.agents.length}),r}async createHierarchicalNetwork(e,t){if(!this.config.enableHierarchy)throw new Error("Hierarchical networks are disabled");if(t){const n=this.networkInfo.get(t);if(!n)throw new Error(`Parent network not found: ${t}`);let o=0,s=n;for(;s.parentNetworkId;)if(o++,s=this.networkInfo.get(s.parentNetworkId),o>=this.config.maxHierarchyDepth)throw new Error(`Maximum hierarchy depth (${this.config.maxHierarchyDepth}) exceeded`)}const r=await this.createNetwork(e,e.supervisionMode??"hierarchical");if(t){const n=this.networkInfo.get(r.id);n.parentNetworkId=t,this.networkInfo.get(t).childNetworkIds.push(r.id)}return r}getNetwork(e){return this.networks.get(e)}getNetworkInfo(e){return this.networkInfo.get(e)}getAllNetworks(){return Array.from(this.networkInfo.values())}async executeNetwork(e,t,r){const n=this.networks.get(e);if(!n)throw new Error(`Network not found: ${e}`);const o=this.networkInfo.get(e);if(o.state==="paused")throw new Error(`Network is paused: ${e}`);if(o.state==="shutdown")throw new Error(`Network is shut down: ${e}`);return o.state==="executing"?this.queueExecution({networkId:e,input:t,options:r}):this.activeExecutions.size>=this.config.maxConcurrentExecutions?this.queueExecution({networkId:e,input:t,options:r}):this.executeNetworkInternal(n,o,t,r)}async executeNetworkInternal(e,t,r,n){t.state="executing",t.executionCount++;const o=(async()=>{try{this.emitter.emit("network:execution:start",{networkId:e.id,input:r});const s=await e.execute(r,{...n,timeout:n?.timeout??this.config.defaultTimeout});return t.lastExecutionAt=Date.now(),t.state="ready",this.emitter.emit("network:execution:complete",{networkId:e.id,result:s}),s}catch(s){throw t.state="error",this.emitter.emit("network:execution:error",{networkId:e.id,error:s instanceof Error?s.message:String(s)}),s}finally{this.activeExecutions.delete(e.id),this.processExecutionQueue()}})();return this.activeExecutions.set(e.id,o),o}async queueExecution(e){return new Promise((t,r)=>{const n={...e,resolve:t,reject:r};this.executionQueue.push(n),this.executionQueue.sort((o,s)=>{const i={high:0,normal:1,low:2};return(i[o.priority??"normal"]??1)-(i[s.priority??"normal"]??1)}),this.emitter.emit("execution:queued",{networkId:e.networkId})})}async processExecutionQueue(){for(;this.executionQueue.length>0&&this.activeExecutions.size<this.config.maxConcurrentExecutions;){const e=this.executionQueue.shift(),t=this.networks.get(e.networkId),r=this.networkInfo.get(e.networkId);t&&r&&r.state!=="executing"?this.executeNetworkInternal(t,r,e.input,e.options).then(n=>e.resolve?.(n)).catch(n=>e.reject?.(n)):e.reject&&e.reject(new Error(`Network unavailable for execution: ${e.networkId}`))}}async*streamNetwork(e,t,r){const n=this.networks.get(e);if(!n)throw new Error(`Network not found: ${e}`);const o=this.networkInfo.get(e);if(o.state==="paused")throw new Error(`Network is paused: ${e}`);if(o.state==="shutdown")throw new Error(`Network is shut down: ${e}`);if(o.state==="executing")throw new Error(`Network is already executing: ${e}. Streaming does not support queuing.`);if(this.activeExecutions.size>=this.config.maxConcurrentExecutions)throw new Error(`Maximum concurrent executions (${this.config.maxConcurrentExecutions}) reached. Streaming does not support queuing.`);o.state="executing",o.executionCount++;const s=Promise.resolve();this.activeExecutions.set(e,s);try{yield*n.stream(t,r),o.lastExecutionAt=Date.now()}finally{o.state="ready",this.activeExecutions.delete(e),this.processExecutionQueue()}}async executeHierarchical(e,t,r){const n=this.networks.get(e),o=this.networkInfo.get(e);if(!n||!o)throw new Error(`Network not found: ${e}`);const i={traceId:st(),steps:[],routingDecisions:[],startTime:Date.now(),hierarchyLevel:0,childTraces:[]};let a=o;for(;a.parentNetworkId;)i.hierarchyLevel++,i.parentTraceId=a.parentNetworkId,a=this.networkInfo.get(a.parentNetworkId);const l=await this.executeNetwork(e,t,r);i.steps=l.trace.steps,i.routingDecisions=l.trace.routingDecisions,i.endTime=Date.now();for(const c of o.childNetworkIds)if(this.networks.get(c)){const d=await this.executeHierarchical(c,{message:l.content,context:t.context},r);i.childTraces?.push(d)}return i}pauseNetwork(e){const t=this.networkInfo.get(e);t&&t.state==="ready"&&(t.state="paused",this.emitter.emit("network:paused",{networkId:e}))}resumeNetwork(e){const t=this.networkInfo.get(e);t&&t.state==="paused"&&(t.state="ready",this.emitter.emit("network:resumed",{networkId:e}))}async shutdownNetwork(e){const t=this.networkInfo.get(e);if(t){for(const r of t.childNetworkIds)await this.shutdownNetwork(r);if(t.parentNetworkId){const r=this.networkInfo.get(t.parentNetworkId);r&&(r.childNetworkIds=r.childNetworkIds.filter(n=>n!==e))}t.state="shutdown",this.networks.delete(e),this.networkInfo.delete(e),this.coordinators.delete(e),this.emitter.emit("network:shutdown",{networkId:e}),f.info(`[NetworkOrchestrator] Network shutdown: ${e}`)}}async coordinateNetworks(e,t,r="parallel"){const n=new Map;switch(r){case"sequential":case"pipeline":{let o=t;for(const s of e){const i=await this.executeNetwork(s,{message:o});n.set(s,i),o=i.content}break}case"parallel":{await Promise.all(e.map(async o=>{const s=await this.executeNetwork(o,{message:t});n.set(o,s)}));break}default:throw new Error(`Unsupported coordination strategy: ${r}`)}return n}getStats(){const e={idle:0,initializing:0,ready:0,executing:0,paused:0,error:0,shutdown:0};let t=0;for(const r of this.networkInfo.values())e[r.state]++,t+=r.executionCount;return{totalNetworks:this.networks.size,activeExecutions:this.activeExecutions.size,queuedExecutions:this.executionQueue.length,totalExecutions:t,networksByState:e}}getMessageBus(){return this.messageBus}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}async shutdown(){for(const e of this.networks.keys())await this.shutdownNetwork(e);this.messageBus.shutdown(),f.info("[NetworkOrchestrator] Shutdown complete")}}}}),G2,mse,i9r=S({"src/lib/agent/orchestration/topology.ts"(){"use strict";Ut(),q(),G2=class{nodes=new Map;edges=new Map;config;topologyId;constructor(e){this.config=e,this.topologyId=st(),f.debug(`[NetworkTopology] Created with type: ${e.type}`)}buildFromAgents(e){this.nodes.clear(),this.edges.clear();for(const t of e)this.addNode(t);switch(this.config.type){case"star":this.buildStarTopology(e);break;case"mesh":this.buildMeshTopology(e);break;case"hierarchical":this.buildHierarchicalTopology(e);break;case"ring":this.buildRingTopology(e);break;case"custom":this.buildCustomTopology(e);break}f.info(`[NetworkTopology] Built ${this.config.type} topology`,{nodes:this.nodes.size,edges:this.edges.size})}addNode(e,t){const r={id:`node-${e.id}`,agentId:e.id,agentName:e.name,role:t??"worker",connections:[],childIds:[]};return this.nodes.set(r.id,r),r}removeNode(e){if(!this.nodes.get(e))return!1;for(const r of[...this.edges.keys()]){const n=this.edges.get(r);(n.sourceId===e||n.targetId===e)&&this.edges.delete(r)}for(const r of this.nodes.values())r.connections=r.connections.filter(n=>n!==e),r.childIds=r.childIds.filter(n=>n!==e),r.parentId===e&&(r.parentId=void 0);return this.nodes.delete(e),!0}addEdge(e,t,r="bidirectional",n=1){const o=this.nodes.get(e),s=this.nodes.get(t);if(!o||!s){f.warn("[NetworkTopology] Cannot add edge: node not found");return}const i={id:`edge-${e}-${t}`,sourceId:e,targetId:t,type:r,weight:n};return this.edges.set(i.id,i),o.connections.includes(t)||o.connections.push(t),r==="bidirectional"&&!s.connections.includes(e)&&s.connections.push(e),i}removeEdge(e){const t=this.edges.get(e);if(!t)return!1;const r=this.nodes.get(t.sourceId),n=this.nodes.get(t.targetId);return r&&(r.connections=r.connections.filter(o=>o!==t.targetId)),n&&t.type==="bidirectional"&&(n.connections=n.connections.filter(o=>o!==t.sourceId)),this.edges.delete(e),!0}buildStarTopology(e){if(e.length===0)return;let t;this.config.coordinatorId&&(t=Array.from(this.nodes.values()).find(r=>r.agentId===this.config.coordinatorId)),t||(t=Array.from(this.nodes.values())[0]),t.role="coordinator";for(const r of this.nodes.values())r.id!==t.id&&(r.role="worker",this.addEdge(t.id,r.id))}buildMeshTopology(e){const t=Array.from(this.nodes.values());for(let r=0;r<t.length;r++){t[r].role="peer";for(let n=r+1;n<t.length;n++)this.addEdge(t[r].id,t[n].id)}}buildHierarchicalTopology(e){if(e.length===0)return;const t=Array.from(this.nodes.values()),r=this.config.maxChildren??3;if(r<1)throw new Error(`[NetworkTopology] maxChildren must be >= 1, got ${r}. A value of 0 or less would orphan every non-root node because no children can ever be assigned to a parent.`);let n;this.config.rootId&&(n=t.find(a=>a.agentId===this.config.rootId)),n||(n=t[0]),n.role="supervisor";const o=new Set([n.id]),s=[n];let i=1;for(;s.length>0&&i<t.length;){const a=s.shift();let l=0;for(;l<r&&i<t.length;){const c=t[i];o.has(c.id)||(c.parentId=a.id,a.childIds.push(c.id),c.role=i<t.length-r?"supervisor":"worker",this.addEdge(a.id,c.id,"unidirectional"),o.add(c.id),s.push(c),l++),i++}}}buildRingTopology(e){const t=Array.from(this.nodes.values());if(t.length!==0)for(let r=0;r<t.length;r++){t[r].role="peer";const n=(r+1)%t.length;this.addEdge(t[r].id,t[n].id,"unidirectional")}}buildCustomTopology(e){if(!this.config.customEdges)return;const t=new Map;for(const r of this.nodes.values())t.set(r.agentId,r),r.role="peer";for(const r of this.config.customEdges){const n=t.get(r.source),o=t.get(r.target);n&&o&&this.addEdge(n.id,o.id,r.bidirectional!==!1?"bidirectional":"unidirectional")}}getNode(e){return this.nodes.get(e)}getNodeByAgentId(e){for(const t of this.nodes.values())if(t.agentId===e)return t}getAllNodes(){return Array.from(this.nodes.values())}getAllEdges(){return Array.from(this.edges.values())}getConnectedNodes(e){const t=this.nodes.get(e);return t?t.connections.map(r=>this.nodes.get(r)).filter(r=>r!==void 0):[]}findShortestPath(e,t){if(e===t)return[e];const r=new Set,n=[{nodeId:e,path:[e]}];for(;n.length>0;){const{nodeId:o,path:s}=n.shift();if(r.has(o))continue;r.add(o);const i=this.nodes.get(o);if(i)for(const a of i.connections){if(a===t)return[...s,t];r.has(a)||n.push({nodeId:a,path:[...s,a]})}}}areConnected(e,t){return this.findShortestPath(e,t)!==void 0}getNodesByRole(e){return Array.from(this.nodes.values()).filter(t=>t.role===e)}getCoordinator(){return Array.from(this.nodes.values()).find(e=>e.role==="coordinator")||Array.from(this.nodes.values()).find(e=>e.role==="supervisor"&&!e.parentId)}getStats(){const e=Array.from(this.nodes.values()),t=e.length,r=this.edges.size;if(t===0)return{nodeCount:0,edgeCount:0,avgConnections:0,maxConnections:0,minConnections:0,diameter:0,density:0};const n=e.map(u=>u.connections.length),o=Math.max(...n),s=Math.min(...n),i=n.reduce((u,d)=>u+d,0)/t;let a=0;for(const u of e)for(const d of e)if(u.id!==d.id){const m=this.findShortestPath(u.id,d.id);m&&m.length-1>a&&(a=m.length-1)}const l=t*(t-1)/2,c=l>0?r/l:0;return{nodeCount:t,edgeCount:r,avgConnections:i,maxConnections:o,minConnections:s,diameter:a,density:c}}toJSON(){return{id:this.topologyId,type:this.config.type,nodes:Array.from(this.nodes.values()),edges:Array.from(this.edges.values())}}fromJSON(e){e.id!==void 0&&(this.topologyId=e.id),this.config.type=e.type,this.nodes.clear(),this.edges.clear();for(const t of e.nodes)this.nodes.set(t.id,t);for(const t of e.edges)this.edges.set(t.id,t)}getType(){return this.config.type}getId(){return this.topologyId}},mse=class{agents=[];config;constructor(e){this.config={type:e}}addAgent(e){return this.agents.push(e),this}addAgents(e){return this.agents.push(...e),this}setCoordinator(e){return this.config.coordinatorId=e,this}setRoot(e){return this.config.rootId=e,this}setMaxChildren(e){return this.config.maxChildren=e,this}addCustomEdge(e,t,r=!0){return this.config.customEdges||(this.config.customEdges=[]),this.config.customEdges.push({source:e,target:t,bidirectional:r}),this}build(){const e=new G2(this.config);return e.buildFromAgents(this.agents),e}}}}),nBt={};fe(nBt,{NetworkOrchestrator:()=>pse,NetworkTopology:()=>G2,TopologyBuilder:()=>mse});var oBt=S({"src/lib/agent/orchestration/index.ts"(){"use strict";s9r(),i9r()}}),hse,fse,a9r=S({"src/lib/agent/coordination/task-distributor.ts"(){"use strict";vn(),q(),pn(),hse={critical:5,high:4,normal:3,low:2,background:1},fse=class{agents=new Map;capabilities=new Map;taskQueue=[];activeResults=new Map;config;emitter;isProcessing=!1;constructor(e){this.config={maxQueueSize:1e3,maxRetries:3,retryDelay:1e3,taskTimeout:6e4,enableDecomposition:!1,...e},this.emitter=new sn,f.debug("[TaskDistributor] Created with config",{strategy:e.strategy,maxQueueSize:this.config.maxQueueSize})}registerAgent(e,t){this.agents.set(e.id,e);const r=t?.skills??e.tools??[];this.capabilities.set(e.id,{agentId:e.id,skills:r,currentLoad:0,avgResponseTime:0,successRate:1,affinityTags:t?.affinityTags}),f.debug(`[TaskDistributor] Registered agent: ${e.name}`,{skills:r.length})}unregisterAgent(e){this.agents.delete(e),this.capabilities.delete(e)}updateCapability(e,t){const r=this.capabilities.get(e);r&&this.capabilities.set(e,{...r,...t})}async submitTask(e){if(this.config.maxQueueSize&&this.taskQueue.length>=this.config.maxQueueSize)throw new Error("Task queue is full");const t={taskId:e.id,agentId:"",distributedAt:Date.now(),status:"pending"};this.activeResults.set(e.id,t);const r=new Promise(n=>{const o=i=>{i.taskId===e.id&&(this.emitter.off("task:completed",o),this.emitter.off("task:failed",s),n(this.activeResults.get(e.id)??t))},s=i=>{i.taskId===e.id&&(this.emitter.off("task:completed",o),this.emitter.off("task:failed",s),n(this.activeResults.get(e.id)??t))};this.emitter.on("task:completed",o),this.emitter.on("task:failed",s)});return this.taskQueue.push({task:e,addedAt:Date.now(),attempts:0}),this.emitter.emit("task:submitted",{taskId:e.id}),await this.processQueue(),r}async submitTasks(e){return Promise.all(e.map(t=>this.submitTask(t)))}async decomposeTask(e,t){if(!this.config.enableDecomposition)return[e];const r=[];for(let n=0;n<t.requirements.length;n++){const o=t.requirements[n];o.mandatory&&r.push({id:`${e.id}-subtask-${n}`,input:`${e.input}
|
|
2117
2117
|
|
|
2118
|
-
Focus on: ${o.description}`,priority:e.priority,requiredSkills:o.type==="tool"?[o.description]:void 0,parentTaskId:e.id,metadata:{...e.metadata,subtaskIndex:n,requirementType:o.type}})}return r.length===0?[e]:r}async processQueue(){if(!(this.isProcessing||this.taskQueue.length===0)){this.isProcessing=!0;try{this.taskQueue.sort((t,r)=>{const n=hse[r.task.priority]-hse[t.task.priority];return n!==0?n:t.task.deadline&&r.task.deadline?t.task.deadline-r.task.deadline:t.addedAt-r.addedAt});let e=0;for(;this.taskQueue.length>0;){const t=this.taskQueue[0];if(t.task.dependencies&&t.task.dependencies.length>0){const n=t.task.dependencies.find(s=>{const i=this.activeResults.get(s);return i?.status==="failed"||!i});if(n){this.taskQueue.shift(),e=0;const s=this.activeResults.get(t.task.id);s&&(s.status="failed",s.error=`Dependency '${n}' failed or not found`),this.emitter.emit("task:failed",{taskId:t.task.id,error:`Dependency '${n}' failed or not found`});continue}if(!t.task.dependencies.every(s=>this.activeResults.get(s)?.status==="completed")){if(this.taskQueue.shift(),this.taskQueue.push(t),e++,e>=this.taskQueue.length){this.failAllQueuedTasks("Circular or unresolvable dependency detected");break}continue}}const r=await this.selectAgent(t.task);if(!r){if(t.attempts<(this.config.maxRetries??3)){t.attempts++,await this.delay(this.config.retryDelay??1e3);continue}this.taskQueue.shift();const n=this.activeResults.get(t.task.id);n&&(n.status="failed",n.error="No suitable agent found"),this.emitter.emit("task:failed",{taskId:t.task.id,error:"No suitable agent found"});continue}this.taskQueue.shift(),e=0,await this.executeTask(t.task,r)}}finally{this.isProcessing=!1,this.taskQueue.length>0&&(await new Promise(e=>setTimeout(e,0)),await this.processQueue())}}}async selectAgent(e){const t=Array.from(this.agents.values());if(t.length!==0)switch(this.config.strategy){case"skillBased":return this.selectBySkill(e,t);case"loadBalanced":return this.selectByLoad(t);case"priority":return this.selectByPriority(e,t);case"affinity":return this.selectByAffinity(e,t);case"broadcast":return t[0];default:return t[0]}}selectBySkill(e,t){if(!e.requiredSkills||e.requiredSkills.length===0)return t[0];let r,n=0;for(const o of t){const s=this.capabilities.get(o.id);if(!s)continue;let i=0;if(this.config.skillMatcher)i=this.config.skillMatcher(e,o);else for(const a of e.requiredSkills)s.skills.some(c=>c.toLowerCase().includes(a.toLowerCase())||a.toLowerCase().includes(c.toLowerCase()))&&i++;i*=s.successRate,i*=1-s.currentLoad,i>n&&(n=i,r=o)}return r??t[0]}selectByLoad(e){let t,r=1/0;for(const n of e){const o=this.capabilities.get(n.id);o&&o.currentLoad<r&&(r=o.currentLoad,t=n)}return t??e[0]}selectByPriority(e,t){if(e.priority==="critical"||e.priority==="high"){let r,n=0;for(const o of t){const s=this.capabilities.get(o.id);s&&s.successRate>n&&(n=s.successRate,r=o)}return r??t[0]}return this.selectByLoad(t)}selectByAffinity(e,t){if(e.preferredAgent){const r=this.agents.get(e.preferredAgent);if(r)return r}if(e.metadata?.affinityTags){const r=e.metadata.affinityTags;for(const n of t){const o=this.capabilities.get(n.id);if(o?.affinityTags&&r.some(i=>o.affinityTags.includes(i)))return n}}return this.selectByLoad(t)}async executeTask(e,t){const r=this.activeResults.get(e.id);if(!r)return;r.agentId=t.id,r.status="running";const n=this.capabilities.get(t.id);n&&(n.currentLoad=Math.min(1,n.currentLoad+.2)),this.emitter.emit("task:started",{taskId:e.id,agentId:t.id});const o=Date.now();try{const s=await Bt(t.execute(e.input,{context:e.metadata,timeout:e.deadline?e.deadline-Date.now():this.config.taskTimeout}),this.config.taskTimeout??6e4,"Task execution timeout");if(r.result=s,r.completedAt=Date.now(),r.status=s.status==="success"?"completed":"failed",r.error=s.error,n){const i=Date.now()-o;n.avgResponseTime=(n.avgResponseTime+i)/2,s.status==="success"?n.successRate=n.successRate*.9+1*.1:n.successRate=n.successRate*.9}this.emitter.emit("task:completed",{taskId:e.id,agentId:t.id,status:r.status})}catch(s){r.status="failed",r.error=s instanceof Error?s.message:String(s),r.completedAt=Date.now(),n&&(n.successRate=n.successRate*.9),this.emitter.emit("task:failed",{taskId:e.id,agentId:t.id,error:r.error})}finally{n&&(n.currentLoad=Math.max(0,n.currentLoad-.2))}}async broadcastTask(e){const t=new Map,n=Array.from(this.agents.values()).map(async o=>{const s={...e,id:`${e.id}-${o.id}`},i={taskId:s.id,agentId:o.id,distributedAt:Date.now(),status:"running"};try{const a=await o.execute(s.input);i.result=a,i.status=a.status==="success"?"completed":"failed",i.completedAt=Date.now()}catch(a){i.status="failed",i.error=a instanceof Error?a.message:String(a),i.completedAt=Date.now()}t.set(o.id,i)});return await Promise.all(n),t}getTaskResult(e){return this.activeResults.get(e)}getQueueStatus(){let e=0,t=0,r=0;for(const n of this.activeResults.values())switch(n.status){case"completed":e++;break;case"failed":t++;break;case"running":r++;break}return{pending:this.taskQueue.length,active:r,completed:e,failed:t}}clearCompleted(){for(const[e,t]of this.activeResults)(t.status==="completed"||t.status==="failed")&&this.activeResults.delete(e)}failAllQueuedTasks(e){for(;this.taskQueue.length>0;){const t=this.taskQueue.shift(),r=this.activeResults.get(t.task.id);r&&(r.status="failed",r.error=e),this.emitter.emit("task:failed",{taskId:t.task.id,error:e})}}delay(e){return new Promise(t=>setTimeout(t,e))}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}}}}),sBt={};fe(sBt,{AgentCoordinator:()=>j2,TaskDistributor:()=>fse});var iBt=S({"src/lib/agent/coordination/index.ts"(){"use strict";tBt(),a9r()}}),aBt={};fe(aBt,{MessageBus:()=>q2});var lBt=S({"src/lib/agent/communication/index.ts"(){"use strict";rBt()}}),cBt={};fe(cBt,{AuthProviderFactory:()=>Ni,createAuthProvider:()=>uBt});async function uBt(e,t){return Ni.createProvider(e,t)}var Ni,H2=S({"src/lib/auth/AuthProviderFactory.ts"(){"use strict";q(),ta(),Ni=class Pa{static providers=new Map;static aliasMap=new Map;static registerProvider(t,r,n=[],o){Pa.providers.set(t,{factory:r,aliases:n,metadata:o});for(const s of n)Pa.aliasMap.set(s.toLowerCase(),t);f.debug(`Registered auth provider: ${t}`)}static async createProvider(t,r){const n=Pa.resolveType(t),o=Pa.providers.get(n);if(!o)throw At.create("PROVIDER_NOT_FOUND",`Auth provider not found: ${t}. Available: ${Pa.getAvailableProviders().join(", ")}`);try{return await o.factory(r)}catch(s){throw At.create("CREATION_FAILED",`Failed to create auth provider ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s instanceof Error?s:void 0})}}static hasProvider(t){return Pa.providers.has(t)||Pa.aliasMap.has(t.toLowerCase())}static getAvailableProviders(){return Array.from(Pa.providers.keys())}static getProviderMetadata(t){const r=Pa.resolveType(t);return Pa.providers.get(r)?.metadata}static getAllProviderInfo(){return Array.from(Pa.providers.entries()).map(([t,r])=>({type:t,aliases:r.aliases,metadata:r.metadata}))}static clearRegistrations(){Pa.providers.clear(),Pa.aliasMap.clear()}static resolveType(t){return Pa.aliasMap.get(t.toLowerCase())||t}}}}),gse={};fe(gse,{NEUROLINK_BRAND:()=>V2,NeuroLink:()=>Ox,STREAM_DEDUP_CONTEXT_KEY:()=>dBt,default:()=>pBt,isNeuroLink:()=>dy,markStreamProviderEmittedGenerationEnd:()=>u9r,neurolink:()=>wse});function l9r(e){const t=e.toLowerCase();return t.includes("not found")||t.includes("404")||t.includes("does not exist")||t.includes("no such")?"not_found":t.includes("permission")||t.includes("forbidden")||t.includes("403")||t.includes("unauthorized")||t.includes("401")||t.includes("access denied")?"permission_denied":t.includes("timeout")||t.includes("timed out")||t.includes("deadline exceeded")?"timeout":t.includes("rate limit")||t.includes("429")||t.includes("too many requests")||t.includes("throttl")?"rate_limited":t.includes("invalid")||t.includes("validation")||t.includes("bad request")||t.includes("400")?"validation_error":"unknown"}function c9r(e){switch(e){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 u9r(e){const t=e?._streamDedupContext;t&&(t.providerEmitted=!0)}function d9r(e){return zr.getDescriptor(e)?.toolSupport!=="native"}function dy(e){return typeof e=="object"&&e!==null&&e[V2]===!0}function p9r(){return new sn}var yse,vse,_se,Dx,dBt,V2,Ox,wse,pBt,md=S({async"src/lib/neurolink.ts"(){"use strict";er(),dC(),vn(),E4(),Gpr(),vUr(),BUr(),zd(),zUr(),qbt(),Gbt(),TN(),Xo(),fMt(),IMt(),OMt(),pPt(),ql(),SP(),c9(),fa(),Jx(),JUr(),t6r(),bPt(),SPt(),xPt(),$ee(),INt(),PNt(),Tjr(),xjr(),jNt(),Pjr(),bC(),Gte(),Ljr(),Ujr(),zjr(),G_(),sLt(),u$t(),p$t(),i7(),Rqr(),yt(),QM(),Wm(),zL(),yGr(),wFt(),LGr(),Q8r(),rHr(),AP(),yr(),E_(),at(),V7(),gGe(),eGe(),nHr(),LVe(),uHr(),q(),wr(),pC(),Bte(),dHr(),bHr(),yh(),Yi(),r9(),F7e(),KM(),T3t(),Jd(),zP(),vf(),M3t(),poe(),vUt(),yUt(),tUt(),wm(),TUt(),CUt();try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";const{config:e}=await Promise.resolve().then(()=>sa(L7r(),1));e({quiet:!0})}catch{}yse=moe,vse=eUt,_se=E7r,Dx=new L0,dBt="_streamDedupContext",V2=Symbol.for("@juspay/neurolink/sdk-brand"),Ox=class UF{[V2]=!0;mcpInitialized=!1;mcpSkipped=!1;mcpInitPromise=null;emitter=p9r();_taskManager;_taskManagerConfig;toolRegistry;autoDiscoveredServerInfos=[];externalServerManager;toolCache=null;toolCacheDuration;modelAliasConfig;lastCompactionMessageCount=new Map;getCompactionSessionId(t){return t.context?.sessionId||"__default__"}mcpToolResultCache;mcpToolRouter;mcpToolBatcher;mcpEnhancedDiscovery;mcpToolMiddlewares=[];mcpArtifactStore;_disableToolCacheForCurrentRequest=!1;_toolCacheKeysServedThisRequest=new Set;_generationTurnActive=!1;mcpEnhancementsConfig;toolCircuitBreakers=new Map;toolExecutionMetrics=new Map;currentStreamToolExecutions=[];toolExecutionHistory=[];activeToolExecutions=new Map;emitToolEndEvent(t,r,n,o,s,i){this.emitter.emit("tool:end",v0(t,{responseTime:Date.now()-r,success:n,timestamp:Date.now(),result:o,error:s?s.message:void 0,executionId:i}))}conversationMemory;conversationMemoryNeedsInit=!1;conversationMemoryConfig;toolRoutingConfig;toolRoutingCacheInstance;toolRoutingVectorCache;knowledgeGroundingEngine;toolDedupConfig;toolsConfig;discoveryPins=new Map;enableOrchestration;authProvider;pendingAuthConfig;authInitPromise;credentials;fallbackConfig={};modelPool;requestRouter;classifierRouter;resolveCredentials(t){if(!this.credentials&&!t)return;if(!this.credentials)return t;if(!t)return this.credentials;const r={...this.credentials};for(const n of Object.keys(t)){const o=this.credentials[n],s=t[n];o&&s&&typeof o=="object"&&typeof s=="object"?r[n]={...o,...s}:r[n]=s??o}return r}hitlManager;_sessionCostUsd=0;fileRegistry;cachedFileTools=null;memoryInstance;memorySDKConfig;skillsManagerInstance;skillsConfig;async setLangfuseContextFromOptions(t,r){if(t.context&&typeof t.context=="object"&&t.context!==null){let n=!1;try{const o=t.context;if(o.userId||o.sessionId||o.conversationId||o.requestId||o.traceName||o.metadata){let s;if(o.metadata&&typeof o.metadata=="object"){const i=o.metadata,a={};for(const[l,c]of Object.entries(i))(typeof c=="string"||typeof c=="number"||typeof c=="boolean")&&(a[l]=c);Object.keys(a).length>0&&(s=a)}return await new Promise((i,a)=>{$0({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;const l=await r();i(l)}catch(l){a(l)}})})}}catch(o){if(n)throw o;f.warn("Failed to set Langfuse context from options",{error:o instanceof Error?o.message:String(o)})}}return await r()}createMetricsTraceContext(){const t=vt.getSpan(Sr.active());if(t){const r=t.spanContext();if(r.traceId&&r.traceId!=="00000000000000000000000000000000")return{traceId:r.traceId,parentSpanId:r.spanId}}return{traceId:crypto.randomUUID().replace(/-/g,""),parentSpanId:crypto.randomUUID().replace(/-/g,"").substring(0,16)}}enforceSessionBudget(t){if(!(t===void 0||t<=0||this._sessionCostUsd<t))throw new Ne({code:"SESSION_BUDGET_EXCEEDED",message:`Session budget exceeded: spent $${this._sessionCostUsd.toFixed(4)} of $${t.toFixed(4)} limit`,category:"validation",severity:"high",retriable:!1,context:{spent:this._sessionCostUsd,limit:t}})}assertInputText(t,r){if(!t||typeof t!="string")throw new Error(r)}async applyAuthenticatedRequestContext(t){if(t.auth?.token){const{AuthError:n}=await Promise.resolve().then(()=>(ta(),yNt));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 Ze(this.authProvider.authenticateToken(t.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");t.context={...t.context||{},userId:o.user.id,userEmail:o.user.email,userRoles:o.user.roles}}if(!t.requestContext)return;const r=t.auth?.token&&this.authProvider?{userId:t.context?.userId,userEmail:t.context?.userEmail,userRoles:t.context?.userRoles}:{};t.context={...t.context||{},...t.requestContext,...r}}applyGenerateLifecycleMiddleware(t){!t.onFinish&&!t.onError||(t.middleware={...t.middleware,middlewareConfig:{...t.middleware?.middlewareConfig,lifecycle:{...t.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...t.middleware?.middlewareConfig?.lifecycle?.config,...t.onFinish!==void 0?{onFinish:t.onFinish}:{},...t.onError!==void 0?{onError:t.onError}:{}}}}})}applyStreamLifecycleMiddleware(t){!t.onFinish&&!t.onError&&!t.onChunk||(t.middleware={...t.middleware,middlewareConfig:{...t.middleware?.middlewareConfig,lifecycle:{...t.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...t.middleware?.middlewareConfig?.lifecycle?.config,...t.onFinish!==void 0?{onFinish:t.onFinish}:{},...t.onError!==void 0?{onError:t.onError}:{},...t.onChunk!==void 0?{onChunk:t.onChunk}:{}}}}})}initializeMemoryConfig(){const t=this.conversationMemoryConfig?.conversationMemory?.memory;return t?.enabled?(this.memorySDKConfig=t,!0):!1}ensureMemoryReady(){return this.memoryInstance!==void 0?this.memoryInstance:this.initializeMemoryConfig()?this.memorySDKConfig?(this.memoryInstance=Fjr(this.memorySDKConfig),this.memoryInstance):(this.memoryInstance=null,null):(this.memoryInstance=null,null)}toolExecutionContext;hasAgentTools=!1;uncacheableTools=new Set;hasTaskChecklistTools=!1;hasBackgroundDelegationTools=!1;hasBackgroundCommandTools=!1;hasGitTools=!1;retrieveContextRegistered=!1;observabilityConfig;metricsAggregator=new eP;analyticsService;get _metricsTraceContext(){return Dx.getStore()??null}constructor(t){this.toolRegistry=t?.toolRegistry||new RL,this.fileRegistry=new vPt,this.observabilityConfig=t?.observability,this.analyticsService=new g$t,this.enableOrchestration=t?.enableOrchestration??!1,t?.modelAliasConfig&&(this.modelAliasConfig=t.modelAliasConfig),t?.providerFallback&&(this.fallbackConfig.providerFallback=t.providerFallback),t?.modelChain&&(this.fallbackConfig.modelChain=t.modelChain),t?.toolRouting&&(this.toolRoutingConfig={...t.toolRouting});const r=t?.knowledgeGrounding;r?.enabled&&(Array.isArray(r.sources)&&r.sources.length>0?this.knowledgeGroundingEngine=new Aee(r):f.warn("[KnowledgeGrounding] enabled but no sources were provided; grounding disabled for this instance")),t?.toolDedup&&(this.toolDedupConfig={...t.toolDedup}),t?.tools&&(this.toolsConfig={...t.tools}),this.modelPool=t?.modelPool?new hoe(t.modelPool):null,this.requestRouter=t?.requestRouter??null,this.classifierRouter=t?.classifierRouter?.enabled?new _oe(t.classifierRouter,{generate:a=>this.generate({...a}),logger:{debug:(a,l)=>f.debug(a,l),warn:(a,l)=>f.warn(a,l)}}):null,f.setEventEmitter(this.emitter);const n=process.env.NEUROLINK_TOOL_CACHE_DURATION;this.toolCacheDuration=n?parseInt(n,10):2e4;const o=Date.now(),s=process.hrtime.bigint(),i=`neurolink-constructor-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.initializeProviderRegistry(i,o,s),this.initializeConversationMemory(t,i,o,s),this.initializeExternalServerManager(i,o,s),this.initializeHITL(t,i,o,s),this.initializeMCPEnhancements(t),this.registerFileTools(),this.registerMemoryRetrievalTools(),t?.skills?.enabled&&(this.skillsConfig=t.skills,this.registerSkillTools()),this.initializeLangfuse(i,o,s),this.initializeMetricsListeners(),this.logConstructorComplete(i,o,s),t?.auth&&(this.pendingAuthConfig=t.auth),t?.credentials&&(this.credentials=t.credentials),this._taskManagerConfig=t?.tasks,this._taskManagerConfig&&(this._taskManager=new Wne(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerSchedulerTaskTools(this._taskManager))}get tasks(){return this._taskManager||(this._taskManager=new Wne(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerSchedulerTaskTools(this._taskManager)),this._taskManager}initializeProviderRegistry(t,r,n){const o=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3D7}\uFE0F LOG_POINT_C002_PROVIDER_REGISTRY_SETUP_START",{logPoint:"C002_PROVIDER_REGISTRY_SETUP_START",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),registrySetupStartTimeNs:o.toString(),message:"Starting ProviderRegistry configuration for security"}),Mp.setOptions({enableManualMCP:!1})}initializeConversationMemory(t,r,n,o){if(t?.conversationMemory?.enabled){const s=process.hrtime.bigint();this.conversationMemoryConfig=t,this.conversationMemoryNeedsInit=!0;const a=process.hrtime.bigint()-s;f.debug("[NeuroLink] \u2705 LOG_POINT_C006_MEMORY_INIT_FLAG_SET_SUCCESS",{logPoint:"C006_MEMORY_INIT_FLAG_SET_SUCCESS",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),memoryInitDurationNs:a.toString(),memoryInitDurationMs:Number(a)/zu,message:"Conversation memory initialization flag set successfully for lazy loading"})}else f.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C008_MEMORY_DISABLED",{logPoint:"C008_MEMORY_DISABLED",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!t,hasMemoryConfig:!!t?.conversationMemory,memoryEnabled:t?.conversationMemory?.enabled||!1,reason:t?t.conversationMemory?t.conversationMemory.enabled?"UNKNOWN":"MEMORY_DISABLED":"NO_MEMORY_CONFIG":"NO_CONFIG",message:"Conversation memory not enabled - skipping initialization"})}initializeHITL(t,r,n,o){if(t?.hitl?.enabled){const s=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E1}\uFE0F LOG_POINT_C015_HITL_INIT_START",{logPoint:"C015_HITL_INIT_START",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitStartTimeNs:s.toString(),hitlConfig:{enabled:t.hitl.enabled,dangerousActions:t.hitl.dangerousActions||[],timeout:t.hitl.timeout||3e4,allowArgumentModification:t.hitl.allowArgumentModification??!0,auditLogging:t.hitl.auditLogging??!1},message:"Starting HITL (Human-in-the-Loop) initialization"});try{this.hitlManager=new Pee(t.hitl),this.toolRegistry.setHITLManager(this.hitlManager),this.externalServerManager.setHITLManager(this.hitlManager),this.setupHITLEventForwarding();const a=process.hrtime.bigint()-s;f.debug("[NeuroLink] \u2705 LOG_POINT_C016_HITL_INIT_SUCCESS",{logPoint:"C016_HITL_INIT_SUCCESS",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:a.toString(),hitlInitDurationMs:Number(a)/zu,hasHitlManager:!!this.hitlManager,message:"HITL (Human-in-the-Loop) initialized successfully"}),f.info("[NeuroLink] HITL safety features enabled",{dangerousActions:t.hitl.dangerousActions?.length||0,timeout:t.hitl.timeout||3e4,allowArgumentModification:t.hitl.allowArgumentModification??!0,auditLogging:t.hitl.auditLogging??!1})}catch(i){const l=process.hrtime.bigint()-s;throw f.error("[NeuroLink] \u274C LOG_POINT_C017_HITL_INIT_ERROR",{logPoint:"C017_HITL_INIT_ERROR",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:l.toString(),hitlInitDurationMs:Number(l)/zu,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 f.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C018_HITL_DISABLED",{logPoint:"C018_HITL_DISABLED",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!t,hasHitlConfig:!!t?.hitl,hitlEnabled:t?.hitl?.enabled||!1,reason:t?t.hitl?t.hitl.enabled?"UNKNOWN":"HITL_DISABLED":"NO_HITL_CONFIG":"NO_CONFIG",message:"HITL (Human-in-the-Loop) not enabled - skipping initialization"})}initializeMCPEnhancements(t){const r=t?.mcp;if(this.mcpEnhancementsConfig=r,r?.cache?.enabled!==!1&&(this.mcpToolResultCache=new PN({ttl:r?.cache?.ttl??3e5,maxSize:r?.cache?.maxSize??500,strategy:r?.cache?.strategy??"lru"}),f.debug("[NeuroLink] MCP tool result cache initialized",{ttl:r?.cache?.ttl??3e5,maxSize:r?.cache?.maxSize??500,strategy:r?.cache?.strategy??"lru"})),r?.batcher?.enabled&&(this.mcpToolBatcher=new MN({maxBatchSize:r.batcher.maxBatchSize??10,maxWaitMs:r.batcher.maxWaitMs??100}),this.mcpToolBatcher.setToolExecutor(async(n,o)=>this.executeToolInternal(n,o,{timeout:ec.EXECUTION_DEFAULT_MS,maxRetries:is.DEFAULT,retryDelayMs:bn.BASE_MS})),f.debug("[NeuroLink] MCP tool call batcher initialized")),r?.discovery?.enabled!==!1&&(this.mcpEnhancedDiscovery=new DN,f.debug("[NeuroLink] Enhanced tool discovery initialized")),r?.middleware?.length&&(this.mcpToolMiddlewares=[...r.middleware],f.debug("[NeuroLink] MCP tool middlewares registered",{count:this.mcpToolMiddlewares.length})),r?.outputLimits){const n=r.outputLimits.strategy??"externalize",o=r.outputLimits.maxBytes??RNt,s=r.outputLimits.warnBytes??Jte;let i;n==="externalize"&&(i=new Zte,this.mcpArtifactStore=i,f.debug("[NeuroLink] MCP artifact store initialized (local-temp)"));const a=new MNt({strategy:n,maxBytes:o,warnBytes:s},i);this.externalServerManager.setOutputNormalizer(a),f.debug("[NeuroLink] MCP output normalizer initialized",{strategy:n,maxBytes:o,warnBytes:s})}}registerFileTools(){const t=_Pt(this.fileRegistry),r=Object.entries(t).map(async([n,o])=>{const s=`direct.${n}`,i=js(o.inputSchema??o.parameters),a={name:n,description:o.description||`File tool: ${n}`,inputSchema:i,serverId:"direct",category:"built-in"};await this.toolRegistry.registerTool(s,a,{execute:async l=>{try{return{success:!0,data:await o.execute(l,{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(r).then(()=>{f.debug(`[NeuroLink] Registered ${Object.keys(t).length} file reference tools`)},n=>{f.warn("[NeuroLink] File tool registration failed",{error:n instanceof Error?n.message:String(n)})})}registerSchedulerTaskTools(t){const r=tHr(t);for(const[n,o]of Object.entries(r)){const 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(l){return{success:!1,error:l instanceof Error?l.message:String(l),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}}).catch(a=>{f.warn("[NeuroLink] Task tool registration failed",{toolId:s,error:a instanceof Error?a.message:String(a)})})}f.debug(`[NeuroLink] Registered ${Object.keys(r).length} task tools`)}registerMemoryRetrievalTools(){if(this.retrieveContextRegistered)return;const t=this.conversationMemoryConfig?.conversationMemory,r=!!t?.redisConfig||t&&"redis"in t&&!!t.redis||process.env.STORAGE_TYPE==="redis",n=!!this.mcpArtifactStore;if((!t?.enabled||!r)&&!n){f.debug("[NeuroLink] Skipping memory retrieval tools \u2014 requires Redis conversation memory or an artifact store");return}const s=ZNt(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=>{const a=this.conversationMemory,l=ZNt(a,this.mcpArtifactStore);return await Ze(l.retrieve_context.execute(i,{toolCallId:"memory-retrieval",messages:[]}),ec.EXECUTION_DEFAULT_MS,ke.toolTimeout("retrieve_context",ec.EXECUTION_DEFAULT_MS))}}),this.retrieveContextRegistered=!0,f.info("[NeuroLink] Memory retrieval tools registered")}ensureSkillsReady(){if(this.skillsManagerInstance!==void 0)return this.skillsManagerInstance;if(!this.skillsConfig?.enabled)return this.skillsManagerInstance=null,null;try{this.skillsManagerInstance=new zre(this.skillsConfig)}catch(t){f.warn("[NeuroLink] Skills initialization failed \u2014 skills disabled for this instance",{error:t instanceof Error?t.message:String(t)}),this.skillsManagerInstance=null}return this.skillsManagerInstance}registerSkillTools(){const t=d$t(()=>this.ensureSkillsReady(),{allowMutations:this.skillsConfig?.allowMutations===!0});for(const[r,n]of Object.entries(t))this.registerTool(r,{name:r,description:n.description??r,inputSchema:n.inputSchema,execute:async o=>Ze(n.execute(o,{toolCallId:"skill-tool",messages:[]}),ec.EXECUTION_DEFAULT_MS,ke.toolTimeout(r,ec.EXECUTION_DEFAULT_MS))});f.info(`[NeuroLink] Registered ${Object.keys(t).length} skill tools`,{allowMutations:this.skillsConfig?.allowMutations===!0})}async applySkillsAugmentation(t){if(!this.skillsConfig?.enabled||t.skills?.enabled===!1)return;const r=t.output?.mode;if(!(r==="avatar"||r==="music"||r==="video"||r==="ppt"))try{const n=this.ensureSkillsReady();if(!n)return;const o=t.skills?.discovery??this.skillsConfig.discovery??"tool",s=t.skills?.scopeId??this.skillsConfig.defaultScopeId,i=t.skills?.tags,a=this.resolveSkillSessionId(t.context)??this.resolveSkillSessionId(t),l=this.resolveSkillUserId(t.context)??this.resolveSkillUserId(t),c=!!this.conversationMemory||!!this.conversationMemoryConfig?.conversationMemory?.enabled,u=(this.skillsConfig.sessionPersistence??!0)&&!!a&&c,d={...s!==void 0?{scopeId:s}:{},...i!==void 0?{tags:i}:{}};if(o==="system-prompt"){const g=await n.buildPromptIndex(d);g&&(t.systemPrompt=t.systemPrompt?`${t.systemPrompt}
|
|
2118
|
+
Focus on: ${o.description}`,priority:e.priority,requiredSkills:o.type==="tool"?[o.description]:void 0,parentTaskId:e.id,metadata:{...e.metadata,subtaskIndex:n,requirementType:o.type}})}return r.length===0?[e]:r}async processQueue(){if(!(this.isProcessing||this.taskQueue.length===0)){this.isProcessing=!0;try{this.taskQueue.sort((t,r)=>{const n=hse[r.task.priority]-hse[t.task.priority];return n!==0?n:t.task.deadline&&r.task.deadline?t.task.deadline-r.task.deadline:t.addedAt-r.addedAt});let e=0;for(;this.taskQueue.length>0;){const t=this.taskQueue[0];if(t.task.dependencies&&t.task.dependencies.length>0){const n=t.task.dependencies.find(s=>{const i=this.activeResults.get(s);return i?.status==="failed"||!i});if(n){this.taskQueue.shift(),e=0;const s=this.activeResults.get(t.task.id);s&&(s.status="failed",s.error=`Dependency '${n}' failed or not found`),this.emitter.emit("task:failed",{taskId:t.task.id,error:`Dependency '${n}' failed or not found`});continue}if(!t.task.dependencies.every(s=>this.activeResults.get(s)?.status==="completed")){if(this.taskQueue.shift(),this.taskQueue.push(t),e++,e>=this.taskQueue.length){this.failAllQueuedTasks("Circular or unresolvable dependency detected");break}continue}}const r=await this.selectAgent(t.task);if(!r){if(t.attempts<(this.config.maxRetries??3)){t.attempts++,await this.delay(this.config.retryDelay??1e3);continue}this.taskQueue.shift();const n=this.activeResults.get(t.task.id);n&&(n.status="failed",n.error="No suitable agent found"),this.emitter.emit("task:failed",{taskId:t.task.id,error:"No suitable agent found"});continue}this.taskQueue.shift(),e=0,await this.executeTask(t.task,r)}}finally{this.isProcessing=!1,this.taskQueue.length>0&&(await new Promise(e=>setTimeout(e,0)),await this.processQueue())}}}async selectAgent(e){const t=Array.from(this.agents.values());if(t.length!==0)switch(this.config.strategy){case"skillBased":return this.selectBySkill(e,t);case"loadBalanced":return this.selectByLoad(t);case"priority":return this.selectByPriority(e,t);case"affinity":return this.selectByAffinity(e,t);case"broadcast":return t[0];default:return t[0]}}selectBySkill(e,t){if(!e.requiredSkills||e.requiredSkills.length===0)return t[0];let r,n=0;for(const o of t){const s=this.capabilities.get(o.id);if(!s)continue;let i=0;if(this.config.skillMatcher)i=this.config.skillMatcher(e,o);else for(const a of e.requiredSkills)s.skills.some(c=>c.toLowerCase().includes(a.toLowerCase())||a.toLowerCase().includes(c.toLowerCase()))&&i++;i*=s.successRate,i*=1-s.currentLoad,i>n&&(n=i,r=o)}return r??t[0]}selectByLoad(e){let t,r=1/0;for(const n of e){const o=this.capabilities.get(n.id);o&&o.currentLoad<r&&(r=o.currentLoad,t=n)}return t??e[0]}selectByPriority(e,t){if(e.priority==="critical"||e.priority==="high"){let r,n=0;for(const o of t){const s=this.capabilities.get(o.id);s&&s.successRate>n&&(n=s.successRate,r=o)}return r??t[0]}return this.selectByLoad(t)}selectByAffinity(e,t){if(e.preferredAgent){const r=this.agents.get(e.preferredAgent);if(r)return r}if(e.metadata?.affinityTags){const r=e.metadata.affinityTags;for(const n of t){const o=this.capabilities.get(n.id);if(o?.affinityTags&&r.some(i=>o.affinityTags.includes(i)))return n}}return this.selectByLoad(t)}async executeTask(e,t){const r=this.activeResults.get(e.id);if(!r)return;r.agentId=t.id,r.status="running";const n=this.capabilities.get(t.id);n&&(n.currentLoad=Math.min(1,n.currentLoad+.2)),this.emitter.emit("task:started",{taskId:e.id,agentId:t.id});const o=Date.now();try{const s=await Bt(t.execute(e.input,{context:e.metadata,timeout:e.deadline?e.deadline-Date.now():this.config.taskTimeout}),this.config.taskTimeout??6e4,"Task execution timeout");if(r.result=s,r.completedAt=Date.now(),r.status=s.status==="success"?"completed":"failed",r.error=s.error,n){const i=Date.now()-o;n.avgResponseTime=(n.avgResponseTime+i)/2,s.status==="success"?n.successRate=n.successRate*.9+1*.1:n.successRate=n.successRate*.9}this.emitter.emit("task:completed",{taskId:e.id,agentId:t.id,status:r.status})}catch(s){r.status="failed",r.error=s instanceof Error?s.message:String(s),r.completedAt=Date.now(),n&&(n.successRate=n.successRate*.9),this.emitter.emit("task:failed",{taskId:e.id,agentId:t.id,error:r.error})}finally{n&&(n.currentLoad=Math.max(0,n.currentLoad-.2))}}async broadcastTask(e){const t=new Map,n=Array.from(this.agents.values()).map(async o=>{const s={...e,id:`${e.id}-${o.id}`},i={taskId:s.id,agentId:o.id,distributedAt:Date.now(),status:"running"};try{const a=await o.execute(s.input);i.result=a,i.status=a.status==="success"?"completed":"failed",i.completedAt=Date.now()}catch(a){i.status="failed",i.error=a instanceof Error?a.message:String(a),i.completedAt=Date.now()}t.set(o.id,i)});return await Promise.all(n),t}getTaskResult(e){return this.activeResults.get(e)}getQueueStatus(){let e=0,t=0,r=0;for(const n of this.activeResults.values())switch(n.status){case"completed":e++;break;case"failed":t++;break;case"running":r++;break}return{pending:this.taskQueue.length,active:r,completed:e,failed:t}}clearCompleted(){for(const[e,t]of this.activeResults)(t.status==="completed"||t.status==="failed")&&this.activeResults.delete(e)}failAllQueuedTasks(e){for(;this.taskQueue.length>0;){const t=this.taskQueue.shift(),r=this.activeResults.get(t.task.id);r&&(r.status="failed",r.error=e),this.emitter.emit("task:failed",{taskId:t.task.id,error:e})}}delay(e){return new Promise(t=>setTimeout(t,e))}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}}}}),sBt={};fe(sBt,{AgentCoordinator:()=>j2,TaskDistributor:()=>fse});var iBt=S({"src/lib/agent/coordination/index.ts"(){"use strict";tBt(),a9r()}}),aBt={};fe(aBt,{MessageBus:()=>q2});var lBt=S({"src/lib/agent/communication/index.ts"(){"use strict";rBt()}}),cBt={};fe(cBt,{AuthProviderFactory:()=>Ni,createAuthProvider:()=>uBt});async function uBt(e,t){return Ni.createProvider(e,t)}var Ni,H2=S({"src/lib/auth/AuthProviderFactory.ts"(){"use strict";q(),ta(),Ni=class Pa{static providers=new Map;static aliasMap=new Map;static registerProvider(t,r,n=[],o){Pa.providers.set(t,{factory:r,aliases:n,metadata:o});for(const s of n)Pa.aliasMap.set(s.toLowerCase(),t);f.debug(`Registered auth provider: ${t}`)}static async createProvider(t,r){const n=Pa.resolveType(t),o=Pa.providers.get(n);if(!o)throw At.create("PROVIDER_NOT_FOUND",`Auth provider not found: ${t}. Available: ${Pa.getAvailableProviders().join(", ")}`);try{return await o.factory(r)}catch(s){throw At.create("CREATION_FAILED",`Failed to create auth provider ${t}: ${s instanceof Error?s.message:String(s)}`,{cause:s instanceof Error?s:void 0})}}static hasProvider(t){return Pa.providers.has(t)||Pa.aliasMap.has(t.toLowerCase())}static getAvailableProviders(){return Array.from(Pa.providers.keys())}static getProviderMetadata(t){const r=Pa.resolveType(t);return Pa.providers.get(r)?.metadata}static getAllProviderInfo(){return Array.from(Pa.providers.entries()).map(([t,r])=>({type:t,aliases:r.aliases,metadata:r.metadata}))}static clearRegistrations(){Pa.providers.clear(),Pa.aliasMap.clear()}static resolveType(t){return Pa.aliasMap.get(t.toLowerCase())||t}}}}),gse={};fe(gse,{NEUROLINK_BRAND:()=>V2,NeuroLink:()=>Ox,STREAM_DEDUP_CONTEXT_KEY:()=>dBt,default:()=>pBt,isNeuroLink:()=>dy,markStreamProviderEmittedGenerationEnd:()=>u9r,neurolink:()=>wse});function l9r(e){const t=e.toLowerCase();return t.includes("not found")||t.includes("404")||t.includes("does not exist")||t.includes("no such")?"not_found":t.includes("permission")||t.includes("forbidden")||t.includes("403")||t.includes("unauthorized")||t.includes("401")||t.includes("access denied")?"permission_denied":t.includes("timeout")||t.includes("timed out")||t.includes("deadline exceeded")?"timeout":t.includes("rate limit")||t.includes("429")||t.includes("too many requests")||t.includes("throttl")?"rate_limited":t.includes("invalid")||t.includes("validation")||t.includes("bad request")||t.includes("400")?"validation_error":"unknown"}function c9r(e){switch(e){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 u9r(e){const t=e?._streamDedupContext;t&&(t.providerEmitted=!0)}function d9r(e){return zr.getDescriptor(e)?.toolSupport!=="native"}function dy(e){return typeof e=="object"&&e!==null&&e[V2]===!0}function p9r(){return new sn}var yse,vse,_se,Dx,dBt,V2,Ox,wse,pBt,md=S({async"src/lib/neurolink.ts"(){"use strict";er(),dC(),vn(),E4(),Gpr(),vUr(),BUr(),zd(),zUr(),qbt(),Gbt(),TN(),Xo(),fMt(),IMt(),OMt(),pPt(),ql(),SP(),c9(),fa(),Jx(),JUr(),t6r(),bPt(),SPt(),xPt(),$ee(),INt(),PNt(),Tjr(),xjr(),jNt(),Pjr(),bC(),Gte(),Ljr(),Ujr(),zjr(),G_(),sLt(),u$t(),p$t(),i7(),Rqr(),yt(),QM(),Wm(),zL(),yGr(),wFt(),LGr(),Q8r(),rHr(),AP(),yr(),E_(),at(),V7(),gGe(),eGe(),nHr(),LVe(),uHr(),q(),wr(),pC(),Bte(),dHr(),bHr(),yh(),Yi(),r9(),F7e(),KM(),T3t(),Jd(),zP(),vf(),M3t(),poe(),vUt(),yUt(),tUt(),wm(),TUt(),CUt();try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";const{config:e}=await Promise.resolve().then(()=>sa(L7r(),1));e({quiet:!0})}catch{}yse=moe,vse=eUt,_se=E7r,Dx=new L0,dBt="_streamDedupContext",V2=Symbol.for("@juspay/neurolink/sdk-brand"),Ox=class UF{[V2]=!0;mcpInitialized=!1;mcpSkipped=!1;mcpInitPromise=null;emitter=p9r();_taskManager;_taskManagerConfig;toolRegistry;autoDiscoveredServerInfos=[];externalServerManager;toolCache=null;toolCacheDuration;modelAliasConfig;lastCompactionMessageCount=new Map;getCompactionSessionId(t){return t.context?.sessionId||"__default__"}mcpToolResultCache;mcpToolRouter;mcpToolBatcher;mcpEnhancedDiscovery;mcpToolMiddlewares=[];mcpArtifactStore;_disableToolCacheForCurrentRequest=!1;_toolCacheKeysServedThisRequest=new Set;_generationTurnActive=!1;mcpEnhancementsConfig;toolCircuitBreakers=new Map;toolExecutionMetrics=new Map;currentStreamToolExecutions=[];toolExecutionHistory=[];activeToolExecutions=new Map;emitToolEndEvent(t,r,n,o,s,i){this.emitter.emit("tool:end",v0(t,{responseTime:Date.now()-r,success:n,timestamp:Date.now(),result:o,error:s?s.message:void 0,executionId:i}))}conversationMemory;conversationMemoryNeedsInit=!1;conversationMemoryConfig;toolRoutingConfig;toolRoutingCacheInstance;toolRoutingVectorCache;knowledgeGroundingEngine;toolDedupConfig;toolsConfig;discoveryPins=new Map;enableOrchestration;authProvider;pendingAuthConfig;authInitPromise;credentials;fallbackConfig={};modelPool;requestRouter;classifierRouter;resolveCredentials(t){if(!this.credentials&&!t)return;if(!this.credentials)return t;if(!t)return this.credentials;const r={...this.credentials};for(const n of Object.keys(t)){const o=this.credentials[n],s=t[n];o&&s&&typeof o=="object"&&typeof s=="object"?r[n]={...o,...s}:r[n]=s??o}return r}hitlManager;_sessionCostUsd=0;fileRegistry;cachedFileTools=null;memoryInstance;memorySDKConfig;skillsManagerInstance;skillsConfig;async setLangfuseContextFromOptions(t,r){if(t.context&&typeof t.context=="object"&&t.context!==null){let n=!1;try{const o=t.context;if(o.userId||o.sessionId||o.conversationId||o.requestId||o.traceName||o.metadata){let s;if(o.metadata&&typeof o.metadata=="object"){const i=o.metadata,a={};for(const[l,c]of Object.entries(i))(typeof c=="string"||typeof c=="number"||typeof c=="boolean")&&(a[l]=c);Object.keys(a).length>0&&(s=a)}return await new Promise((i,a)=>{$0({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;const l=await r();i(l)}catch(l){a(l)}})})}}catch(o){if(n)throw o;f.warn("Failed to set Langfuse context from options",{error:o instanceof Error?o.message:String(o)})}}return await r()}createMetricsTraceContext(){const t=vt.getSpan(Sr.active());if(t){const r=t.spanContext();if(r.traceId&&r.traceId!=="00000000000000000000000000000000")return{traceId:r.traceId,parentSpanId:r.spanId}}return{traceId:crypto.randomUUID().replace(/-/g,""),parentSpanId:crypto.randomUUID().replace(/-/g,"").substring(0,16)}}enforceSessionBudget(t){if(!(t===void 0||t<=0||this._sessionCostUsd<t))throw new Ne({code:"SESSION_BUDGET_EXCEEDED",message:`Session budget exceeded: spent $${this._sessionCostUsd.toFixed(4)} of $${t.toFixed(4)} limit`,category:"validation",severity:"high",retriable:!1,context:{spent:this._sessionCostUsd,limit:t}})}assertInputText(t,r){if(!t||typeof t!="string")throw new Error(r)}async applyAuthenticatedRequestContext(t){if(t.auth?.token){const{AuthError:n}=await Promise.resolve().then(()=>(ta(),yNt));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 Ze(this.authProvider.authenticateToken(t.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");t.context={...t.context||{},userId:o.user.id,userEmail:o.user.email,userRoles:o.user.roles}}if(!t.requestContext)return;const r=t.auth?.token&&this.authProvider?{userId:t.context?.userId,userEmail:t.context?.userEmail,userRoles:t.context?.userRoles}:{};t.context={...t.context||{},...t.requestContext,...r}}applyGenerateLifecycleMiddleware(t){!t.onFinish&&!t.onError||(t.middleware={...t.middleware,middlewareConfig:{...t.middleware?.middlewareConfig,lifecycle:{...t.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...t.middleware?.middlewareConfig?.lifecycle?.config,...t.onFinish!==void 0?{onFinish:t.onFinish}:{},...t.onError!==void 0?{onError:t.onError}:{}}}}})}applyStreamLifecycleMiddleware(t){!t.onFinish&&!t.onError&&!t.onChunk||(t.middleware={...t.middleware,middlewareConfig:{...t.middleware?.middlewareConfig,lifecycle:{...t.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...t.middleware?.middlewareConfig?.lifecycle?.config,...t.onFinish!==void 0?{onFinish:t.onFinish}:{},...t.onError!==void 0?{onError:t.onError}:{},...t.onChunk!==void 0?{onChunk:t.onChunk}:{}}}}})}initializeMemoryConfig(){const t=this.conversationMemoryConfig?.conversationMemory?.memory;return t?.enabled?(this.memorySDKConfig=t,!0):!1}ensureMemoryReady(){return this.memoryInstance!==void 0?this.memoryInstance:this.initializeMemoryConfig()?this.memorySDKConfig?(this.memoryInstance=Fjr(this.memorySDKConfig),this.memoryInstance):(this.memoryInstance=null,null):(this.memoryInstance=null,null)}toolExecutionContext;hasAgentTools=!1;uncacheableTools=new Set;hasTaskChecklistTools=!1;hasBackgroundDelegationTools=!1;hasBackgroundCommandTools=!1;hasGitTools=!1;retrieveContextRegistered=!1;observabilityConfig;metricsAggregator=new eP;analyticsService;get _metricsTraceContext(){return Dx.getStore()??null}constructor(t){this.toolRegistry=t?.toolRegistry||new RL,this.fileRegistry=new vPt,this.observabilityConfig=t?.observability,this.analyticsService=new g$t,this.enableOrchestration=t?.enableOrchestration??!1,t?.modelAliasConfig&&(this.modelAliasConfig=t.modelAliasConfig),t?.providerFallback&&(this.fallbackConfig.providerFallback=t.providerFallback),t?.modelChain&&(this.fallbackConfig.modelChain=t.modelChain),t?.toolRouting&&(this.toolRoutingConfig={...t.toolRouting});const r=t?.knowledgeGrounding;r?.enabled&&(Array.isArray(r.sources)&&r.sources.length>0?this.knowledgeGroundingEngine=new Aee(r):f.warn("[KnowledgeGrounding] enabled but no sources were provided; grounding disabled for this instance")),t?.toolDedup&&(this.toolDedupConfig={...t.toolDedup}),t?.tools&&(this.toolsConfig={...t.tools}),this.modelPool=t?.modelPool?new hoe(t.modelPool):null,this.requestRouter=t?.requestRouter??null,this.classifierRouter=t?.classifierRouter?.enabled?new _oe(t.classifierRouter,{generate:a=>this.generate({...a}),logger:{debug:(a,l)=>f.debug(a,l),warn:(a,l)=>f.warn(a,l)}}):null,f.setEventEmitter(this.emitter);const n=process.env.NEUROLINK_TOOL_CACHE_DURATION;this.toolCacheDuration=n?parseInt(n,10):2e4;const o=Date.now(),s=process.hrtime.bigint(),i=`neurolink-constructor-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.initializeProviderRegistry(i,o,s),this.initializeConversationMemory(t,i,o,s),this.initializeExternalServerManager(i,o,s),this.initializeHITL(t,i,o,s),this.initializeMCPEnhancements(t),this.registerFileTools(),this.registerMemoryRetrievalTools(),t?.skills?.enabled&&(this.skillsConfig=t.skills,this.registerSkillTools()),this.initializeLangfuse(i,o,s),this.initializeMetricsListeners(),this.logConstructorComplete(i,o,s),t?.auth&&(this.pendingAuthConfig=t.auth),t?.credentials&&(this.credentials=t.credentials),this._taskManagerConfig=t?.tasks,this._taskManagerConfig&&(this._taskManager=new Wne(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerSchedulerTaskTools(this._taskManager))}get tasks(){return this._taskManager||(this._taskManager=new Wne(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerSchedulerTaskTools(this._taskManager)),this._taskManager}initializeProviderRegistry(t,r,n){const o=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3D7}\uFE0F LOG_POINT_C002_PROVIDER_REGISTRY_SETUP_START",{logPoint:"C002_PROVIDER_REGISTRY_SETUP_START",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),registrySetupStartTimeNs:o.toString(),message:"Starting ProviderRegistry configuration for security"}),Mp.setOptions({enableManualMCP:!1})}initializeConversationMemory(t,r,n,o){if(t?.conversationMemory?.enabled){const s=process.hrtime.bigint();this.conversationMemoryConfig=t,this.conversationMemoryNeedsInit=!0;const a=process.hrtime.bigint()-s;f.debug("[NeuroLink] \u2705 LOG_POINT_C006_MEMORY_INIT_FLAG_SET_SUCCESS",{logPoint:"C006_MEMORY_INIT_FLAG_SET_SUCCESS",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),memoryInitDurationNs:a.toString(),memoryInitDurationMs:Number(a)/zu,message:"Conversation memory initialization flag set successfully for lazy loading"})}else f.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C008_MEMORY_DISABLED",{logPoint:"C008_MEMORY_DISABLED",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!t,hasMemoryConfig:!!t?.conversationMemory,memoryEnabled:t?.conversationMemory?.enabled||!1,reason:t?t.conversationMemory?t.conversationMemory.enabled?"UNKNOWN":"MEMORY_DISABLED":"NO_MEMORY_CONFIG":"NO_CONFIG",message:"Conversation memory not enabled - skipping initialization"})}initializeHITL(t,r,n,o){if(t?.hitl?.enabled){const s=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E1}\uFE0F LOG_POINT_C015_HITL_INIT_START",{logPoint:"C015_HITL_INIT_START",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitStartTimeNs:s.toString(),hitlConfig:{enabled:t.hitl.enabled,dangerousActions:t.hitl.dangerousActions||[],timeout:t.hitl.timeout||3e4,allowArgumentModification:t.hitl.allowArgumentModification??!0,auditLogging:t.hitl.auditLogging??!1},message:"Starting HITL (Human-in-the-Loop) initialization"});try{this.hitlManager=new Pee(t.hitl),this.toolRegistry.setHITLManager(this.hitlManager),this.externalServerManager.setHITLManager(this.hitlManager),this.setupHITLEventForwarding();const a=process.hrtime.bigint()-s;f.debug("[NeuroLink] \u2705 LOG_POINT_C016_HITL_INIT_SUCCESS",{logPoint:"C016_HITL_INIT_SUCCESS",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:a.toString(),hitlInitDurationMs:Number(a)/zu,hasHitlManager:!!this.hitlManager,message:"HITL (Human-in-the-Loop) initialized successfully"}),f.info("[NeuroLink] HITL safety features enabled",{dangerousActions:t.hitl.dangerousActions?.length||0,timeout:t.hitl.timeout||3e4,allowArgumentModification:t.hitl.allowArgumentModification??!0,auditLogging:t.hitl.auditLogging??!1})}catch(i){const l=process.hrtime.bigint()-s;throw f.error("[NeuroLink] \u274C LOG_POINT_C017_HITL_INIT_ERROR",{logPoint:"C017_HITL_INIT_ERROR",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:l.toString(),hitlInitDurationMs:Number(l)/zu,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 f.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C018_HITL_DISABLED",{logPoint:"C018_HITL_DISABLED",constructorId:r,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!t,hasHitlConfig:!!t?.hitl,hitlEnabled:t?.hitl?.enabled||!1,reason:t?t.hitl?t.hitl.enabled?"UNKNOWN":"HITL_DISABLED":"NO_HITL_CONFIG":"NO_CONFIG",message:"HITL (Human-in-the-Loop) not enabled - skipping initialization"})}initializeMCPEnhancements(t){const r=t?.mcp;if(this.mcpEnhancementsConfig=r,r?.cache?.enabled!==!1&&(this.mcpToolResultCache=new PN({ttl:r?.cache?.ttl??3e5,maxSize:r?.cache?.maxSize??500,strategy:r?.cache?.strategy??"lru"}),f.debug("[NeuroLink] MCP tool result cache initialized",{ttl:r?.cache?.ttl??3e5,maxSize:r?.cache?.maxSize??500,strategy:r?.cache?.strategy??"lru"})),r?.batcher?.enabled&&(this.mcpToolBatcher=new MN({maxBatchSize:r.batcher.maxBatchSize??10,maxWaitMs:r.batcher.maxWaitMs??100}),this.mcpToolBatcher.setToolExecutor(async(n,o)=>this.executeToolInternal(n,o,{timeout:ec.EXECUTION_DEFAULT_MS,maxRetries:is.DEFAULT,retryDelayMs:bn.BASE_MS})),f.debug("[NeuroLink] MCP tool call batcher initialized")),r?.discovery?.enabled!==!1&&(this.mcpEnhancedDiscovery=new DN,f.debug("[NeuroLink] Enhanced tool discovery initialized")),r?.middleware?.length&&(this.mcpToolMiddlewares=[...r.middleware],f.debug("[NeuroLink] MCP tool middlewares registered",{count:this.mcpToolMiddlewares.length})),r?.outputLimits){const n=r.outputLimits.strategy??"externalize",o=r.outputLimits.maxBytes??RNt,s=r.outputLimits.warnBytes??Jte;let i;n==="externalize"&&(i=new Zte,this.mcpArtifactStore=i,f.debug("[NeuroLink] MCP artifact store initialized (local-temp)"));const a=new MNt({strategy:n,maxBytes:o,warnBytes:s},i);this.externalServerManager.setOutputNormalizer(a),f.debug("[NeuroLink] MCP output normalizer initialized",{strategy:n,maxBytes:o,warnBytes:s})}}registerFileTools(){const t=_Pt(this.fileRegistry),r=Object.entries(t).map(async([n,o])=>{const s=`direct.${n}`,i=js(o.inputSchema??o.parameters),a={name:n,description:o.description||`File tool: ${n}`,inputSchema:i,serverId:"direct",category:"built-in"};await this.toolRegistry.registerTool(s,a,{execute:async l=>{try{return{success:!0,data:await o.execute(l,{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(r).then(()=>{f.debug(`[NeuroLink] Registered ${Object.keys(t).length} file reference tools`)},n=>{f.warn("[NeuroLink] File tool registration failed",{error:n instanceof Error?n.message:String(n)})})}registerSchedulerTaskTools(t){const r=tHr(t);for(const[n,o]of Object.entries(r)){const 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(l){return{success:!1,error:l instanceof Error?l.message:String(l),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}}).catch(a=>{f.warn("[NeuroLink] Task tool registration failed",{toolId:s,error:a instanceof Error?a.message:String(a)})})}f.debug(`[NeuroLink] Registered ${Object.keys(r).length} task tools`)}registerMemoryRetrievalTools(){if(this.retrieveContextRegistered)return;const t=this.conversationMemoryConfig?.conversationMemory,r=!!t?.redisConfig||t&&"redis"in t&&!!t.redis||process.env.STORAGE_TYPE==="redis",n=!!this.mcpArtifactStore;if((!t?.enabled||!r)&&!n){f.debug("[NeuroLink] Skipping memory retrieval tools \u2014 requires Redis conversation memory or an artifact store");return}const s=ZNt(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=>{const a=ZNt(this.conversationMemory??void 0,this.mcpArtifactStore);return await Ze(a.retrieve_context.execute(i,{toolCallId:"memory-retrieval",messages:[]}),ec.EXECUTION_DEFAULT_MS,ke.toolTimeout("retrieve_context",ec.EXECUTION_DEFAULT_MS))}}),this.retrieveContextRegistered=!0,f.info("[NeuroLink] Memory retrieval tools registered")}ensureSkillsReady(){if(this.skillsManagerInstance!==void 0)return this.skillsManagerInstance;if(!this.skillsConfig?.enabled)return this.skillsManagerInstance=null,null;try{this.skillsManagerInstance=new zre(this.skillsConfig)}catch(t){f.warn("[NeuroLink] Skills initialization failed \u2014 skills disabled for this instance",{error:t instanceof Error?t.message:String(t)}),this.skillsManagerInstance=null}return this.skillsManagerInstance}registerSkillTools(){const t=d$t(()=>this.ensureSkillsReady(),{allowMutations:this.skillsConfig?.allowMutations===!0});for(const[r,n]of Object.entries(t))this.registerTool(r,{name:r,description:n.description??r,inputSchema:n.inputSchema,execute:async o=>Ze(n.execute(o,{toolCallId:"skill-tool",messages:[]}),ec.EXECUTION_DEFAULT_MS,ke.toolTimeout(r,ec.EXECUTION_DEFAULT_MS))});f.info(`[NeuroLink] Registered ${Object.keys(t).length} skill tools`,{allowMutations:this.skillsConfig?.allowMutations===!0})}async applySkillsAugmentation(t){if(!this.skillsConfig?.enabled||t.skills?.enabled===!1)return;const r=t.output?.mode;if(!(r==="avatar"||r==="music"||r==="video"||r==="ppt"))try{const n=this.ensureSkillsReady();if(!n)return;const o=t.skills?.discovery??this.skillsConfig.discovery??"tool",s=t.skills?.scopeId??this.skillsConfig.defaultScopeId,i=t.skills?.tags,a=this.resolveSkillSessionId(t.context)??this.resolveSkillSessionId(t),l=this.resolveSkillUserId(t.context)??this.resolveSkillUserId(t),c=!!this.conversationMemory||!!this.conversationMemoryConfig?.conversationMemory?.enabled,u=(this.skillsConfig.sessionPersistence??!0)&&!!a&&c,d={...s!==void 0?{scopeId:s}:{},...i!==void 0?{tags:i}:{}};if(o==="system-prompt"){const g=await n.buildPromptIndex(d);g&&(t.systemPrompt=t.systemPrompt?`${t.systemPrompt}
|
|
2119
2119
|
|
|
2120
2120
|
${g}`:g)}const m=o==="tool"?await n.buildToolListing(d):null,h=Cqr(()=>this.ensureSkillsReady(),{...a?{sessionId:a}:{},...s!==void 0?{scopeId:s}:{},sessionPersistence:u,discovery:o,listing:m,getStoredMessages:async g=>this.conversationMemory?await this.conversationMemory.getSessionMessages(g,l):[]});t.tools={...h,...t.tools??{}},t.skills?.preload?.length&&await this.preloadSkills(n,t,t.skills.preload,{...a?{sessionId:a}:{},...l?{userId:l}:{},sessionPersistence:u,...s!==void 0?{scopeId:s}:{}}),f.debug("[NeuroLink] Skills augmentation applied",{discovery:o,listingLength:m?.length??0,sessionPersistence:u,preloadCount:t.skills?.preload?.length??0})}catch(n){f.warn("[NeuroLink] Skills augmentation failed \u2014 continuing without skills",{error:n instanceof Error?n.message:String(n)})}}resolveSkillSessionId(t){const r=t?.sessionId;return typeof r=="string"&&r?r:void 0}resolveSkillUserId(t){const r=t?.userId;return typeof r=="string"&&r?r:void 0}async preloadSkills(t,r,n,o){const{sessionId:s,userId:i,sessionPersistence:a,scopeId:l}=o;for(const c of n){const u=await t.get(c);if(!u||!ire(u,l)){f.warn("[NeuroLink] Preload skill not found \u2014 skipping",{skill:c});continue}let d;if(s&&a){if(t.sessions.hydrate(s,this.conversationMemory?await this.conversationMemory.getSessionMessages(s,i):[]),t.sessions.isActive(s,u.id,u.name))continue;d=t.sessions.recordActivation(s,u).content}else d=rLt(u).content;r.systemPrompt=r.systemPrompt?`${r.systemPrompt}
|
|
2121
2121
|
|
|
@@ -1,13 +1,16 @@
|
|
|
1
|
+
import type { ConversationMemoryManager } from "../core/conversationMemoryManager.js";
|
|
1
2
|
import type { RedisConversationMemoryManager } from "../core/redisConversationMemoryManager.js";
|
|
2
3
|
import type { ArtifactStore, Tool } from "../types/index.js";
|
|
3
4
|
/**
|
|
4
5
|
* Factory function that creates memory retrieval tools bound to a memory manager.
|
|
5
6
|
*
|
|
6
|
-
* @param memoryManager
|
|
7
|
+
* @param memoryManager Conversation memory manager instance. Session history
|
|
8
|
+
* retrieval requires the Redis-backed manager; with the
|
|
9
|
+
* in-memory manager the tool returns a descriptive error.
|
|
7
10
|
* @param artifactStore Optional artifact store for externalized MCP outputs.
|
|
8
11
|
* When provided, retrieve_context gains an `artifactId`
|
|
9
12
|
* parameter that fetches the full payload written by
|
|
10
13
|
* McpOutputNormalizer under strategy="externalize".
|
|
11
14
|
* @returns Record of tool name to Vercel AI SDK tool definition
|
|
12
15
|
*/
|
|
13
|
-
export declare function createMemoryRetrievalTools(memoryManager: RedisConversationMemoryManager | undefined, artifactStore?: ArtifactStore): Record<string, Tool>;
|
|
16
|
+
export declare function createMemoryRetrievalTools(memoryManager: ConversationMemoryManager | RedisConversationMemoryManager | undefined, artifactStore?: ArtifactStore): Record<string, Tool>;
|
|
@@ -15,7 +15,9 @@ const MAX_SEARCH_MATCHES = 50;
|
|
|
15
15
|
/**
|
|
16
16
|
* Factory function that creates memory retrieval tools bound to a memory manager.
|
|
17
17
|
*
|
|
18
|
-
* @param memoryManager
|
|
18
|
+
* @param memoryManager Conversation memory manager instance. Session history
|
|
19
|
+
* retrieval requires the Redis-backed manager; with the
|
|
20
|
+
* in-memory manager the tool returns a descriptive error.
|
|
19
21
|
* @param artifactStore Optional artifact store for externalized MCP outputs.
|
|
20
22
|
* When provided, retrieve_context gains an `artifactId`
|
|
21
23
|
* parameter that fetches the full payload written by
|
|
@@ -146,10 +148,16 @@ async function executeRetrieveContext(args, memoryManager, artifactStore, otelSp
|
|
|
146
148
|
error: "sessionId is required when artifactId is not provided",
|
|
147
149
|
};
|
|
148
150
|
}
|
|
149
|
-
|
|
151
|
+
// getSessionRaw exists only on the Redis-backed manager. A truthy manager
|
|
152
|
+
// can still be the in-memory one (tool registered for an artifact store, or
|
|
153
|
+
// Redis init fell back to in-memory), so guard on capability — not just
|
|
154
|
+
// presence — instead of throwing "getSessionRaw is not a function".
|
|
155
|
+
if (!memoryManager || !("getSessionRaw" in memoryManager)) {
|
|
150
156
|
otelSpan.setStatus({
|
|
151
157
|
code: SpanStatusCode.ERROR,
|
|
152
|
-
message:
|
|
158
|
+
message: memoryManager
|
|
159
|
+
? "Conversation memory backend is not Redis"
|
|
160
|
+
: "Memory manager not configured",
|
|
153
161
|
});
|
|
154
162
|
return {
|
|
155
163
|
error: "Session history retrieval requires Redis conversation memory — " +
|
package/dist/neurolink.js
CHANGED
|
@@ -1401,10 +1401,11 @@ export class NeuroLink {
|
|
|
1401
1401
|
inputSchema: retrieveContextDef.inputSchema,
|
|
1402
1402
|
execute: async (params) => {
|
|
1403
1403
|
// Lazy: conversationMemory is initialized on the first generate() call.
|
|
1404
|
-
//
|
|
1405
|
-
//
|
|
1406
|
-
|
|
1407
|
-
|
|
1404
|
+
// It may be undefined (artifact-store-only), the Redis manager, or the
|
|
1405
|
+
// in-memory manager (no Redis config, or Redis init fell back) —
|
|
1406
|
+
// createMemoryRetrievalTools guards session retrieval on getSessionRaw
|
|
1407
|
+
// capability and returns a descriptive error otherwise.
|
|
1408
|
+
const tools = createMemoryRetrievalTools(this.conversationMemory ?? undefined, this.mcpArtifactStore);
|
|
1408
1409
|
// Return the result directly so the LLM receives clean output instead
|
|
1409
1410
|
// of a nested { success, data, metadata } wrapper.
|
|
1410
1411
|
// Bounded by TOOL_TIMEOUTS.EXECUTION_DEFAULT_MS so a stalled Redis or
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.7.
|
|
3
|
+
"version": "12.7.5",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
|
|
6
6
|
"author": {
|
|
@@ -407,7 +407,7 @@
|
|
|
407
407
|
"zod-to-json-schema": "^3.25.1"
|
|
408
408
|
},
|
|
409
409
|
"peerDependencies": {
|
|
410
|
-
"@juspay/hippocampus": ">=0.1.
|
|
410
|
+
"@juspay/hippocampus": ">=0.1.8",
|
|
411
411
|
"@opentelemetry/api": "^1.9.0",
|
|
412
412
|
"@opentelemetry/sdk-trace-node": "^2.6.0",
|
|
413
413
|
"react": ">=18.0.0",
|