@juspay/neurolink 12.7.4 → 12.7.6
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.6](https://github.com/juspay/neurolink/compare/v12.7.5...v12.7.6) (2026-09-01)
|
|
2
2
|
|
|
3
3
|
### Bug Fixes
|
|
4
4
|
|
|
5
|
-
- **(proxy):**
|
|
5
|
+
- **(proxy):** fold inline system-role messages into systemPrompt ([fdeefae](https://github.com/juspay/neurolink/commit/fdeefae6808eddf42df711d1d867f964751d2729))
|
|
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
|
|
|
@@ -2319,7 +2319,10 @@ ${i}`:Array.isArray(s)?`${r}${o}:
|
|
|
2319
2319
|
${i}`:`${r}${o}: ${i}`}).join(`
|
|
2320
2320
|
`)}return String(e)}};function Jnn(e){return new xA(e)}function Ynn(e,t){const r=new xA(t);return r.addRoutes(e),r.generate()}function Znn(e,t){const r=new xA({basePath:e.basePath??"/api",servers:[{url:`http://${e.host??"localhost"}:${e.port??3e3}`,description:"Configured server"}]});return t&&r.addRoutes(t),r.generate()}er(),fa(),Wr(),yr(),q();var Xnn=["request","args","result","apiKey","token","authorization","credentials","password","secret"],Qnn="[REDACTED]",eon=10;function ton(e,t){if(!t?.enabled||!e||typeof e!="object")return e;const r=t?.placeholder??Qnn,n=new Set([...Xnn,...t?.additionalFields??[]]);if(t?.preserveFields)for(const o of t.preserveFields)n.delete(o);return ron(e,n,r,t)}function ron(e,t,r,n){const o=e;switch(o.type){case"step-start":return non(e,t,r);case"tool-call":return oon(e,t,r,n);case"tool-result":return son(e,t,r,n);case"error":return ion(e,t,r);default:return aon(o,t,r)}}function non(e,t,r){if(!nle(e))return e;const{payload:n,...o}=e,s=xh(n,t,r,0);return{...o,payload:s}}function oon(e,t,r,n){if(nle(e)){const{payload:o,...s}=e;if(o.toolCall&&typeof o.toolCall=="object"){const a=o.toolCall,l=n?.redactToolArgs!==!1&&t.has("args");return{...s,payload:{...o,toolCall:{...a,args:l?r:a.args}}}}return{...s,payload:xh(o,t,r,0)}}if(ole(e)){const{data:o,...s}=e,i=n?.redactToolArgs!==!1&&t.has("args");return"arguments"in o&&i?{...s,data:{...o,arguments:r}}:{...s,data:xh(o,t,r,0)}}return e}function son(e,t,r,n){const o=n?.redactToolResults!==!1&&t.has("result");if(nle(e)){const{payload:s,...i}=e;return{...i,payload:{...s,result:o?r:s.result}}}if(ole(e)){const{data:s,...i}=e;return{...i,data:{...s,result:o?r:s.result}}}return e}function ion(e,t,r){const n=process.env.NODE_ENV==="production";if(ole(e)){const{data:l,...c}=e,{stack:u,...d}=l;return{...c,data:{...xh(d,t,r,0),...n?{}:{stack:u}}}}const o=e,{stack:s,...i}=o;return{...xh(i,t,r,0),type:"error",...n?{}:{stack:s}}}function aon(e,t,r){return xh(e,t,r,0)}function xh(e,t,r,n){if(n>eon)return e;const o={};for(const[s,i]of Object.entries(e))t.has(s.toLowerCase())?o[s]=r:i&&typeof i=="object"&&!Array.isArray(i)?o[s]=xh(i,t,r,n+1):Array.isArray(i)?o[s]=i.map(l=>l&&typeof l=="object"?xh(l,t,r,n+1):l):o[s]=i;return o}function nle(e){const t=e;return"payload"in t&&t.payload!==null&&typeof t.payload=="object"}function ole(e){return"data"in e&&e.data!==null&&typeof e.data=="object"}function lon(e){return t=>e?.enabled?ton(t,e):t}Pp();async function Nsr(e,t){if(!Array.isArray(t)||t.length===0)return;const r=new Set((await e.neurolink.getAllAvailableTools()).map(o=>o.name)),n=t.filter(o=>typeof o=="string"&&r.has(o));if(n.length>0)return n;f.warn("[agentRoutes] Ignoring request.tools \u2014 no entries match registered tool names (legacy fail-open)",{requested:t})}function sle(e){const t=e.neurolink.getSkillsManager();return t||Kt("SKILLS_UNAVAILABLE","Skills are not enabled on this server \u2014 construct NeuroLink with a `skills` config.",void 0,e.requestId)}function ile(e){const t=sle(e);return"error"in t||t.mutationsAllowed?t:Kt("SKILLS_MUTATIONS_DISABLED","Skill mutations are disabled on this server \u2014 construct NeuroLink with `skills.allowMutations: true` to enable create/update/delete.",void 0,e.requestId)}function Lsr(e="/api"){return{prefix:`${e}/agent`,routes:[{method:"POST",path:`${e}/agent/execute`,handler:async t=>{const r=gd(c$,t.body,t.requestId);if(!r.success)return r.error;const n=r.data;return gt({name:"neurolink.http.execute",tracer:He.http,attributes:{"http.route":"/api/agent/execute","ai.provider":n.provider||"default","ai.model":n.model||"default"}},async()=>{const o=typeof n.input=="string"?{text:n.input}:n.input,s=await Nsr(t,n.tools),i=await t.neurolink.generate({input:o,provider:n.provider,model:n.model,systemPrompt:n.systemPrompt,temperature:n.temperature,maxTokens:n.maxTokens,...s?{toolFilter:s}:{},context:{sessionId:t.user?t.session?.id:t.session?.id??n.sessionId,userId:t.user?t.user.id:n.userId,userEmail:t.user?.email,userRoles:t.user?.roles,requestId:t.requestId}}),a=i.toolCalls?.map(l=>({name:l.toolName,arguments:l.args}));return{content:i.content||"",provider:i.provider||n.provider||"unknown",model:i.model||n.model||"unknown",usage:i.usage,toolCalls:a}})},description:"Execute agent with prompt",tags:["agent"]},{method:"POST",path:`${e}/agent/stream`,streaming:{enabled:!0,contentType:"text/event-stream"},handler:async t=>{const r=gd(c$,t.body,t.requestId);if(!r.success)return r.error;const n=r.data,o=typeof n.input=="string"?{text:n.input}:n.input,s=await Nsr(t,n.tools),i=await t.neurolink.stream({input:o,provider:n.provider,model:n.model,systemPrompt:n.systemPrompt,temperature:n.temperature,maxTokens:n.maxTokens,...s?{toolFilter:s}:{},context:{sessionId:t.user?t.session?.id:t.session?.id??n.sessionId,userId:t.user?t.user.id:n.userId,userEmail:t.user?.email,userRoles:t.user?.roles,requestId:t.requestId}}),a=lon(t.redaction);async function*l(){const c=He.http.startSpan("neurolink.http.stream",{attributes:{"http.route":"/api/agent/stream","ai.provider":n.provider||"default","ai.model":n.model||"default"}});try{for await(const u of i.stream)yield a(u);c.setStatus({code:qe.OK})}catch(u){throw c.recordException(u instanceof Error?u:new Error(String(u))),c.setStatus({code:qe.ERROR,message:u instanceof Error?u.message:String(u)}),u}finally{c.end()}}return l()},description:"Stream agent response",tags:["agent","streaming"]},{method:"GET",path:`${e}/agent/providers`,handler:async()=>{const t=zr.getAvailableProviders();return{providers:t,total:t.length}},description:"List available AI providers",tags:["agent","providers"]},{method:"POST",path:`${e}/agent/embed`,handler:async t=>{const r=gd(_Xt,t.body,t.requestId);if(!r.success)return r.error;const n=r.data;try{const o=n.provider||"openai";return await gt({name:"neurolink.http.embed",tracer:He.http,attributes:{"http.route":"/api/agent/embed","ai.provider":o,"ai.model":n.model||"default"}},async()=>{const i=await(await zr.createProvider(o,n.model)).embed(n.text,n.model);return{embedding:i,provider:o,model:n.model||"default",dimension:i.length}})}catch(o){return Kt("EXECUTION_FAILED",o instanceof Error?o.message:"Embedding generation failed",void 0,t.requestId)}},description:"Generate embedding for a single text",tags:["agent","embeddings"]},{method:"POST",path:`${e}/agent/embed-many`,handler:async t=>{const r=gd(wXt,t.body,t.requestId);if(!r.success)return r.error;const n=r.data;try{const o=n.provider||"openai";return await gt({name:"neurolink.http.embedMany",tracer:He.http,attributes:{"http.route":"/api/agent/embed-many","ai.provider":o,"ai.model":n.model||"default","ai.embed.count":n.texts.length}},async()=>{const i=await(await zr.createProvider(o,n.model)).embedMany(n.texts,n.model);return{embeddings:i,provider:o,model:n.model||"default",count:i.length,dimension:i[0]?.length??0}})}catch(o){return Kt("EXECUTION_FAILED",o instanceof Error?o.message:"Batch embedding generation failed",void 0,t.requestId)}},description:"Generate embeddings for multiple texts in a batch",tags:["agent","embeddings"]},{method:"GET",path:`${e}/agent/skills`,handler:async t=>{const r=sle(t);if("error"in r)return r;try{const n=await r.list(t.query.scopeId);return{skills:n,count:n.length}}catch(n){return Kt("EXECUTION_FAILED",n instanceof Error?n.message:"Skills listing failed",void 0,t.requestId)}},description:"List active skills (index only \u2014 no instructions). Optional ?scopeId= filter.",tags:["agent","skills"]},{method:"GET",path:`${e}/agent/skills/:id`,handler:async t=>{const r=sle(t);if("error"in r)return r;try{const n=await r.get(t.params.id);return n||Kt("NOT_FOUND",`Skill "${t.params.id}" not found`,void 0,t.requestId)}catch(n){return Kt("EXECUTION_FAILED",n instanceof Error?n.message:"Skill lookup failed",void 0,t.requestId)}},description:"Fetch one skill (by id or exact name) with instructions",tags:["agent","skills"]},{method:"POST",path:`${e}/agent/skills`,handler:async t=>{const r=ile(t);if("error"in r)return r;const n=gd(Rie,t.body,t.requestId);if(!n.success)return n.error;const{requestedBy:o,...s}=n.data;try{return await r.requestMutation({type:"create",skill:s,...t.user?.id||o?{requestedBy:t.user?.id??o}:{}})}catch(i){return Kt("EXECUTION_FAILED",i instanceof Error?i.message:"Skill create failed",void 0,t.requestId)}},description:"Create a skill (routed through the host's onMutationRequest gate when configured)",tags:["agent","skills"]},{method:"PATCH",path:`${e}/agent/skills/:id`,handler:async t=>{const r=ile(t);if("error"in r)return r;const n=gd(bXt,t.body,t.requestId);if(!n.success)return n.error;const{requestedBy:o,...s}=n.data;try{return await r.requestMutation({type:"update",skillId:t.params.id,patch:s,...t.user?.id||o?{requestedBy:t.user?.id??o}:{}})}catch(i){const a=i instanceof Error?i.message:"Skill update failed";return Kt(a.includes("not found")?"NOT_FOUND":"EXECUTION_FAILED",a,void 0,t.requestId)}},description:"Update a skill (patch semantics; version is bumped)",tags:["agent","skills"]},{method:"DELETE",path:`${e}/agent/skills/:id`,handler:async t=>{const r=ile(t);if("error"in r)return r;try{return await r.requestMutation({type:"delete",skillId:t.params.id,...t.user?.id?{requestedBy:t.user.id}:{}})}catch(n){const o=n instanceof Error?n.message:"Skill delete failed";return Kt(o.includes("not found")?"NOT_FOUND":"EXECUTION_FAILED",o,void 0,t.requestId)}},description:"Soft-delete (deprecate) a skill",tags:["agent","skills"]}]}}Jr(),ii(),nr(),Gf(),mk(),Jr(),ii(),nr(),Oc(),q();var con=["weekly","session","unified","transient","auth"],$sr={session:300*60*1e3+900*1e3,weekly:10080*60*1e3+720*60*1e3,unified:720*60*1e3,transient:900*1e3,auth:300*1e3};Gl();var uon="account-cooldowns.json",don=new Set(con),pon=null,Fsr=!1,G$=null,Up={},ale=new sl;function lle(){return pon??St(Wa(),".neurolink",uon)}function mon(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.coolingUntil=="number"&&Number.isFinite(t.coolingUntil)&&typeof t.updatedAt=="number"&&Number.isFinite(t.updatedAt)&&typeof t.reason=="string"&&don.has(t.reason)}function hon(e,t){const r=$sr[t.reason];if(r===void 0)return t;const n=t.updatedAt+r;if(t.coolingUntil<=n)return t;const o=s=>(s/36e5).toFixed(1);return f.always(`[proxy] cooldown clamp: ${e} ${t.reason} entry healed from ${o(t.coolingUntil-t.updatedAt)}h to ${o(r)}h \u2014 the stored wait exceeded what "${t.reason}" can mean`),{...t,coolingUntil:n}}async function cle(){Fsr||(G$||(G$=(async()=>{try{const e=JSON.parse(await Kr(lle(),"utf8"));Up=Object.fromEntries(Object.entries(e).filter(t=>mon(t[1])).map(([t,r])=>[t,hon(t,r)]))}catch{Up={}}Fsr=!0})().finally(()=>{G$=null})),await G$)}async function AA(){return await cle(),ale.runExclusive(async()=>({...Up}))}async function bd(e,t,r){await ale.runExclusive(async()=>{await cle();const n=Up[e];n&&n.coolingUntil>t||(Up[e]={coolingUntil:t,reason:r,updatedAt:Date.now()},await il(lle(),Up))})}async function xy(e,t){await ale.runExclusive(async()=>{await cle();const r=Up[e];r&&(t!==void 0&&r.coolingUntil!==t||(delete Up[e],await il(lle(),Up)))})}Uie(),kr(),ma(),nn(),Oc(),Gl();function Li(e,t){if(typeof e.get=="function")return e.get(t)??void 0;const r=e;if(r[t]!==void 0)return r[t];const n=t.toLowerCase();for(const o of Object.keys(r))if(o.toLowerCase()===n)return r[o]}function fon(e,t){if(typeof e.forEach=="function"){e.forEach((r,n)=>t(n));return}for(const r of Object.keys(e))t(r)}function H$(e){return e.trim().replace(/[-_](latest)$/i,"").replace(/-\d{6,8}$/,"")}var gon=new Set(["5h","7d"]),yon=/^anthropic-ratelimit-unified-([a-z0-9_]+)-utilization$/;function von(e,t,r){if(!t)return[];const n=H$(t);if(!n)return[];const o=[];fon(e,i=>{const a=yon.exec(i.toLowerCase());a?.[1]&&!gon.has(a[1])&&o.push(a[1])});const s=[];for(const i of o){const a=`anthropic-ratelimit-unified-${i}-`,l=parseFloat(Li(e,`${a}utilization`)??"");if(Number.isNaN(l))continue;const c=Li(e,`${a}reset`),u=Li(e,`${a}status`)?.trim().toLowerCase();s.push({kind:i.startsWith("7d")?"weekly_scoped":"session_scoped",group:i.startsWith("7d")?"weekly":"session",used:l,status:u??"unknown",resetsAt:c&&parseInt(c,10)||0,scopeModel:n,scopeModelId:t,headerWindow:i,source:"headers",updatedAt:r})}return s}function V$(e){return Li(e,"anthropic-ratelimit-unified-status")?.trim().toLowerCase()||void 0}function Usr(e){const t=e?.overageStatus?.trim().toLowerCase(),r=t==="rejected"||e?.overageDisabledReason!==void 0;if(e?.overageEnabled===!0&&!r)return!0;if(!e||t!=="allowed")return!1;if(e.overageInUse===!0)return!0;const n=e.fallbackStatus?.trim().toLowerCase(),o=(e.upgradePaths??"").split(",").map(s=>s.trim().toLowerCase()).includes("overage");return n==="available"&&o?!0:n===void 0&&(e.fallbackPercentage??0)>0}function rb(e,t){const r="anthropic-ratelimit-",n=Li(e,`${r}unified-5h-utilization`),o=Li(e,`${r}unified-7d-utilization`);if(n===void 0||o===void 0)return null;const s=parseFloat(n),i=parseFloat(o);if(Number.isNaN(s)||Number.isNaN(i))return null;const a=Li(e,`${r}unified-5h-reset`),l=Li(e,`${r}unified-7d-reset`),c=Li(e,`${r}unified-fallback-percentage`),u=t?.now??Date.now(),d=von(e,t?.model,u),m=Li(e,`${r}unified-overage-disabled-reason`),h=Li(e,`${r}unified-representative-claim`);return{unifiedStatus:V$(e),sessionUsed:s,sessionStatus:Li(e,`${r}unified-5h-status`)??"unknown",sessionResetAt:a&&parseInt(a,10)||0,weeklyUsed:i,weeklyStatus:Li(e,`${r}unified-7d-status`)??"unknown",weeklyResetAt:l&&parseInt(l,10)||0,fallbackPercentage:c&&parseFloat(c)||0,fallbackStatus:Li(e,`${r}unified-fallback`)??"unknown",upgradePaths:Li(e,`${r}unified-upgrade-paths`),overageStatus:Li(e,`${r}unified-overage-status`)??"unknown",overageInUse:Li(e,`${r}unified-overage-in-use`)?.trim().toLowerCase()==="true",...m?{overageDisabledReason:m}:{},...h?{representativeClaim:h}:{},lastUpdated:u,source:"headers",...d.length>0?{windows:d}:{}}}function Bsr(e){return[e.kind,e.source??"usage-api",e.headerWindow??"",e.scopeModel??e.scopeModelId??"",e.scopeSurface??""].join("|")}function _on(e,t){if(!t?.length)return e;if(!e?.length)return t;const r=new Map,n=t.some(o=>(o.source??"usage-api")==="usage-api");for(const o of e)n&&(o.source??"usage-api")!=="headers"||r.set(Bsr(o),o);for(const o of t)r.set(Bsr(o),o);return[...r.values()]}function Ay(e,t){if(!e)return t;const r=_on(e.windows,t.windows),n={...t};r!==void 0&&(n.windows=r),n.overageEnabled===void 0&&e.overageEnabled!==void 0&&(n.overageEnabled=e.overageEnabled),n.overageDisabledReason===void 0&&e.overageDisabledReason!==void 0&&(n.overageDisabledReason=e.overageDisabledReason),n.representativeClaim===void 0&&e.representativeClaim!==void 0&&(n.representativeClaim=e.representativeClaim);const o=t.source==="usage-api"?t.windowsUpdatedAt:t.windowsUpdatedAt??e.windowsUpdatedAt;return o!==void 0&&(n.windowsUpdatedAt=o),n}var won="account-quotas.json",bon=5e3,nb={},zsr=!1,W$=null,ule=!1,dle=0,Iy=null,K$=new sl,Ton=new sl,Eon=null;function jsr(){return Eon??rr(El(),".neurolink",won)}async function Son(){await Ton.runExclusive(async()=>{let e,t=0,r="";if(await K$.runExclusive(async()=>{ule&&(e=Object.fromEntries(Object.entries(nb).map(([n,o])=>[n,{...o}])),t=dle,r=jsr())}),!!e)try{await il(r,e,384),await K$.runExclusive(async()=>{dle===t&&(ule=!1)})}catch{}})}function Con(){Iy||(Iy=setTimeout(()=>{Iy=null,Son().catch(()=>{})},bon),Iy&&typeof Iy=="object"&&"unref"in Iy&&Iy.unref())}async function qsr(){zsr||(W$||(W$=(async()=>{try{const e=await Ci.readFile(jsr(),"utf-8");nb=JSON.parse(e)}catch{nb={}}zsr=!0})().finally(()=>{W$=null})),await W$)}async function ple(){return await qsr(),K$.runExclusive(async()=>({...nb}))}async function Ry(e,t){await K$.runExclusive(async()=>{await qsr(),nb[e]=Ay(nb[e],t),ule=!0,dle+=1}),Con()}q(),rA(),mk(),q(),rA(),mk(),Gl(),pn(),wr();var kon=300*1e3,xon=6e4,mle=2e3,Td=new Map;function hle(e){return!!(e.expiresAt&&e.expiresAt<=Date.now()+kon&&e.refreshToken)}function Gsr(e){return e===400||e===401||e===403||e===404}function My(e){return Gsr(e.status)}async function Aon(e){if(!e.refreshToken)return{success:!1,error:"No refresh token available"};const t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:zX}).toString(),r={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":Ag},n=[dk,qxt];let o;for(const s of n)try{const i=await fetch(s,{method:"POST",headers:r,body:t,signal:AbortSignal.timeout(1e4)});if(!i.ok){const l=await i.text();f.warn(`[token-refresh] failed for ${e.label} at ${dn(s)}`,{status:i.status,error:l.slice(0,500)});const c={success:!1,error:l,status:i.status};if(Gsr(i.status)&&(o=c),s===dk)continue;return o??c}const a=await i.json();return e.token=a.access_token,e.expiresAt=a.expires_in!==void 0?Date.now()+a.expires_in*1e3:Date.now()+3300*1e3,a.refresh_token&&(e.refreshToken=a.refresh_token),f.debug(`[token-refresh] refreshed for ${e.label}`),{success:!0}}catch(i){if(f.warn(`[token-refresh] exception for ${e.label} at ${dn(s)}`,{error:String(i)}),s===dk)continue;return o??{success:!1,error:String(i)}}return o??{success:!1,error:"No refresh URLs available"}}async function Hsr(e){if(!e.refreshToken)return{success:!1,error:"No refresh token available"};const t=e.refreshToken;let r=Td.get(t);if(!r){const o={...e},s=Aon(o).then(i=>{const a={result:i,token:o.token,refreshToken:o.refreshToken,expiresAt:o.expiresAt};if(i.success){const l=new Set([t]),c=o.refreshToken;c&&c!==t&&!Td.has(c)&&(Td.set(c,s),l.add(c)),setTimeout(()=>{for(const d of l)Td.get(d)===s&&Td.delete(d)},xon).unref?.()}else Td.get(t)===s&&Td.delete(t);return a},i=>{throw Td.get(t)===s&&Td.delete(t),i});Td.set(t,s),r=s}const n=await r;return n.result.success&&(e.token=n.token,e.refreshToken=n.refreshToken,e.expiresAt=n.expiresAt),n.result}async function Vsr(e,t){if(!t||typeof t=="string"||!("providerKey"in t))return!1;let r;try{r=await Bt(al.peekTokens(t.providerKey),mle,"[token-refresh] peekTokens reconciliation timed out")}catch(n){return f.debug("[token-refresh] skipping persisted-state reconciliation (peek failed)",{error:n instanceof Error?n.message:String(n)}),!1}return!r||r.expiresAt<=(e.expiresAt??0)||r.accessToken===e.token&&r.refreshToken===e.refreshToken&&r.expiresAt===e.expiresAt?!1:(e.token=r.accessToken,e.refreshToken=r.refreshToken,e.expiresAt=r.expiresAt,!0)}async function J$(e,t){if(await Vsr(e,t)&&!hle(e))return{success:!0};const n=await Hsr(e);return n.success?n:await Vsr(e,t)?{success:!0}:n}async function Y$(e,t){if(typeof e!="string"&&"providerKey"in e){await Ron(e.providerKey,t);return}const r=typeof e=="string"?e:e.credPath;await Ion(r,t)}async function Ion(e,t){try{const r=await Promise.resolve().then(()=>(si(),zf)),n=JSON.parse(await r.readFile(e,"utf8"));n.oauth={...n.oauth,accessToken:t.token,expiresAt:t.expiresAt,refreshToken:t.refreshToken},n.updatedAt=Date.now(),await il(e,n,384)}catch(r){f.warn("[token-refresh] Failed to persist legacy credentials",{error:r instanceof Error?r.message:String(r)})}}async function Ron(e,t){try{const r=await Bt(al.peekTokens(e),mle,"[token-refresh] peekTokens for persistence timed out"),n={accessToken:t.token,refreshToken:t.refreshToken??r?.refreshToken,expiresAt:t.expiresAt??r?.expiresAt??Date.now()+3300*1e3,tokenType:r?.tokenType??"Bearer",...r?.scope?{scope:r.scope}:{}};await Bt(al.saveTokens(e,n),mle,"[token-refresh] saveTokens timed out")}catch(r){f.warn("[token-refresh] Failed to persist TokenStore credentials",{error:r instanceof Error?r.message:String(r)})}}Uie();var Mon="https://api.anthropic.com/api/oauth/usage",Pon=1e4;async function Wsr(e){const t=[],r=await al.listByPrefix("anthropic:");for(const n of r){if(!$ie(n,e)||await al.isDisabled(n))continue;const o=await al.loadTokens(n);if(!o)continue;const s=n.indexOf(":");t.push({key:n,label:s>=0?n.slice(s+1):n,token:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,type:o.tokenType==="Bearer"?"oauth":"api_key",persistTarget:{providerKey:n}})}return t}async function Ksr(e){try{return{response:await fetch(Mon,{method:"GET",headers:{authorization:`Bearer ${e}`,"anthropic-beta":Jxt,"user-agent":Ag,accept:"application/json"},signal:AbortSignal.timeout(Pon)})}}catch(t){return{networkError:t instanceof Error?t.message:String(t)}}}async function Don(e){if(e.type!=="oauth")return{ok:!1,reason:"not_oauth",error:"api_key accounts have no subscription usage windows"};const t=async()=>{const s=await J$(e,e.persistTarget);return s.success?(e.persistTarget&&await Y$(e.persistTarget,e),null):My(s)?{ok:!1,reason:"auth",error:"reauth required (refresh token rejected)",status:s.status}:(e.expiresAt?e.expiresAt<=Date.now():!1)?{ok:!1,reason:"auth",error:"token expired and refresh failed",status:s.status}:null};let r=!1;if(hle(e)){r=!0;const s=await t();if(s)return s}let{response:n,networkError:o}=await Ksr(e.token);if(n?.status===401&&e.refreshToken&&!r){const s=await t();if(s)return s;({response:n,networkError:o}=await Ksr(e.token))}if(!n)return{ok:!1,reason:"network",error:o??"network failure"};if(!n.ok){const s=await n.text().catch(()=>"");return f.debug(`[account-usage] usage fetch failed for ${e.label}`,{status:n.status,body:s.slice(0,300)}),{ok:!1,reason:n.status===401||n.status===403?"auth":"http",error:`usage endpoint returned HTTP ${n.status}`,status:n.status}}try{return{ok:!0,usage:await n.json()}}catch(s){return{ok:!1,reason:"parse",error:s instanceof Error?s.message:String(s)}}}var Oon=new Set(["rejected","exceeded","over_limit","blocked"]);function fle(e,t){const r=t?.trim().toLowerCase();return typeof e=="number"&&e>=100||r!==void 0&&Oon.has(r)?"rejected":"allowed"}function IA(e){if(!e)return 0;const t=Date.parse(e);return Number.isNaN(t)?0:Math.floor(t/1e3)}function gle(e){return typeof e=="number"&&Number.isFinite(e)?e/100:void 0}function Non(e,t){const r={kind:e.kind??"unknown",used:gle(e.percent)??0,status:fle(e.percent,e.severity),resetsAt:IA(e.resets_at),source:"usage-api",updatedAt:t};e.group!==void 0&&(r.group=e.group),e.severity!==null&&e.severity!==void 0&&(r.severity=e.severity),e.is_active!==null&&e.is_active!==void 0&&(r.isActive=e.is_active);const n=e.scope?.model?.display_name;n&&(r.scopeModel=n);const o=e.scope?.model?.id;o&&(r.scopeModelId=o);const s=e.scope?.surface;return s&&(r.scopeSurface=s),r}function Jsr(e,t){const r=Array.isArray(e.limits)?e.limits:[];if(!e.five_hour&&!e.seven_day&&r.length===0)return null;const{now:n,prior:o}=t,s=r.map(y=>Non(y,n)),i=r.find(y=>y.kind==="session"),a=r.find(y=>y.kind==="weekly_all"),l=e.five_hour?.utilization??i?.percent??void 0,c=e.seven_day?.utilization??a?.percent??void 0,u=IA(e.five_hour?.resets_at)||IA(i?.resets_at)||(o?.sessionResetAt??0),d=IA(e.seven_day?.resets_at)||IA(a?.resets_at)||(o?.weeklyResetAt??0),m=e.extra_usage?.is_enabled,h=m===!0?"allowed":m===!1?"rejected":o?.overageStatus??"unknown",g={sessionUsed:gle(l)??o?.sessionUsed??0,sessionStatus:fle(l,i?.severity),sessionResetAt:u,weeklyUsed:gle(c)??o?.weeklyUsed??0,weeklyStatus:fle(c,a?.severity),weeklyResetAt:d,fallbackPercentage:o?.fallbackPercentage??0,overageStatus:h,...typeof m=="boolean"?{overageEnabled:m}:{},lastUpdated:n,windows:s,windowsUpdatedAt:n,source:"usage-api"};return o?.fallbackStatus!==void 0&&(g.fallbackStatus=o.fallbackStatus),o?.upgradePaths!==void 0&&(g.upgradePaths=o.upgradePaths),g}var Lon=[3e4,2*6e4,10*6e4],$on=30*6e4,Fon=class{inFlight=new Map;states=new Map;metrics={attempted:0,succeeded:0,failed:0,coalesced:0,backoffSuppressed:0,triggerDeduplicated:0};getState(e){const t=this.states.get(e);return t?{...t,inFlight:this.inFlight.has(e)}:{inFlight:!1,consecutiveFailures:0,coalesced:0}}run(e,t,r,n={}){const o=this.inFlight.get(e.key);if(o){const l=this.getOrCreateState(e.key);return l.coalesced+=1,this.metrics.coalesced+=1,o}const s=n.now??Date.now(),i=this.getOrCreateState(e.key);if(!n.force&&i.lastCompletedTrigger===t)return this.metrics.triggerDeduplicated+=1,Promise.resolve({kind:"not_due"});if(!n.force&&s<(i.nextEligibleAt??0))return this.metrics.backoffSuppressed+=1,Promise.resolve({kind:"backoff",nextEligibleAt:i.nextEligibleAt??s});i.lastAttemptAt=s,this.metrics.attempted+=1;const a=r(e).catch(l=>({ok:!1,reason:"network",error:l instanceof Error?l.message:String(l)})).then(l=>{const c=n.now??Date.now();if(l.ok===!1){this.metrics.failed+=1,i.consecutiveFailures+=1,i.lastFailureReason=l.reason;const u=Lon[Math.max(0,i.consecutiveFailures-1)]??$on,d=.9+Math.random()*.2;i.nextEligibleAt=c+Math.round(u*d)}else this.metrics.succeeded+=1,i.lastSuccessAt=c,i.nextEligibleAt=void 0,i.consecutiveFailures=0,i.lastFailureReason=void 0,i.lastCompletedTrigger=t;return{kind:"completed",result:l,startedAt:s}}).finally(()=>{this.inFlight.delete(e.key)});return this.inFlight.set(e.key,a),a}clear(){this.inFlight.clear(),this.states.clear(),this.metrics={attempted:0,succeeded:0,failed:0,coalesced:0,backoffSuppressed:0,triggerDeduplicated:0}}getMetrics(){return{...this.metrics}}getOrCreateState(e){let t=this.states.get(e);return t||(t={inFlight:!1,consecutiveFailures:0,coalesced:0},this.states.set(e,t)),t}};pn();var Ysr=250,Uon=3e4,Bon=class{generation=0;degraded=!1;backoffUntil=0;lastErrorCode=null;lastTransportScope="shared_provider_transport";probe;async acquire(e){if(!this.degraded)return{allowed:!0,probe:!1,generation:this.generation};const t=Math.max(0,this.backoffUntil-Date.now());if(t>0&&await this.wait(t,e),!this.degraded)return{allowed:!0,probe:!1,generation:this.generation};if(this.probe){const o=await this.waitForProbe(this.probe.promise,e);return o==="recovered"?{allowed:!0,probe:!1,generation:this.generation}:o==="abandoned"?this.acquire(e):{allowed:!1,errorCode:this.lastErrorCode,transportScope:this.lastTransportScope}}let r;const n=new Promise(o=>{r=o});return this.probe={generation:this.generation,promise:n,resolve:r},{allowed:!0,probe:!0,generation:this.generation}}reportSuccess(e){!e.allowed||e.generation!==this.generation||e.probe&&this.probe?.generation!==e.generation||(this.degraded=!1,this.backoffUntil=0,this.lastErrorCode=null,this.lastTransportScope="shared_provider_transport",e.probe&&this.probe?.generation===e.generation&&(this.probe.resolve("recovered"),this.probe=void 0))}reportTransportFailure(e,t,r){!r.allowed||r.generation!==this.generation||r.probe&&this.probe?.generation!==r.generation||(this.degraded=!0,this.backoffUntil=Date.now()+Ysr,this.lastErrorCode=e??null,this.lastTransportScope=t,r.probe&&this.probe?.generation===r.generation&&(this.probe.resolve("failed"),this.probe=void 0),this.generation+=1)}reportProbeAbandoned(e){!e.allowed||!e.probe||e.generation!==this.generation||this.probe?.generation!==e.generation||(this.probe.resolve("abandoned"),this.probe=void 0,this.generation+=1)}clear(){this.probe?.resolve("failed"),this.probe=void 0,this.generation+=1,this.degraded=!1,this.backoffUntil=0,this.lastErrorCode=null,this.lastTransportScope="shared_provider_transport"}async wait(e,t){if(t?.aborted)throw t.reason;await new Promise((r,n)=>{const o={},s=()=>{o.current&&clearTimeout(o.current),n(t?.reason)};o.current=setTimeout(()=>{t?.removeEventListener("abort",s),r()},e),o.current.unref?.(),t?.addEventListener("abort",s,{once:!0})})}async waitForProbe(e,t){const r=Bt(e,Uon,"Anthropic transport recovery probe timed out");try{return await this.waitForProbeOrAbort(r,t)}catch(n){if(n instanceof Em&&this.probe?.promise===e)return this.probe.resolve("failed"),this.probe=void 0,this.generation+=1,this.backoffUntil=Date.now()+Ysr,"failed";throw n}}waitForProbeOrAbort(e,t){if(!t)return e;if(t.aborted)throw t.reason;return new Promise((r,n)=>{const o=()=>n(t.reason);t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}},zon="anthropic-ratelimit-",jon=["retry-after"],qon=4102444800;function Zsr(e){return e.replace(/[^\x20-\x7E]/g,"").trim()}function Xsr(e,t){if(!e||e<=0)return;const r=e>qon?e:e*1e3;if(!(r<=t))return Math.round((r-t)/1e3)}function yle(e){return Number.isFinite(e)?Math.max(0,Math.min(100,Math.round((1-e)*100))):0}function Gon(e){const t={},r=(n,o)=>{const s=n.toLowerCase();if(s.startsWith(zon)||jon.includes(s)){const i=Zsr(o);i&&(t[s]=i)}};if(typeof e.forEach=="function")return e.forEach((n,o)=>r(o,n)),t;for(const[n,o]of Object.entries(e))typeof o=="string"&&r(n,o);return t}function Hon(e,t=Date.now()){const r={"x-neurolink-quota-source":e.source},n=(s,i)=>{if(i==null)return;const a=Zsr(String(i));a&&(r[s]=a)};n("x-neurolink-account",e.accountLabel),n("x-neurolink-account-type",e.accountType),n("x-neurolink-served-by",e.servedBy),n("x-neurolink-attempt",e.attempt),n("x-neurolink-account-cooling-until",e.coolingUntil),n("x-neurolink-account-cooling-reason",e.coolingReason),e.pool&&(n("x-neurolink-pool-available",e.pool.available),n("x-neurolink-pool-cooling",e.pool.cooling),n("x-neurolink-pool-best-session-left",e.pool.bestSessionLeftPct));const o=e.quota;return o&&e.source!=="none"&&(n("x-neurolink-quota-session-left-pct",yle(o.sessionUsed)),n("x-neurolink-quota-session-status",o.sessionStatus),n("x-neurolink-quota-session-resets-in",Xsr(o.sessionResetAt,t)),n("x-neurolink-quota-weekly-left-pct",yle(o.weeklyUsed)),n("x-neurolink-quota-weekly-status",o.weeklyStatus),n("x-neurolink-quota-weekly-resets-in",Xsr(o.weeklyResetAt,t)),n("x-neurolink-quota-unified-status",o.unifiedStatus),n("x-neurolink-quota-overage-status",o.overageStatus),n("x-neurolink-quota-fallback-pct",Math.round((o.fallbackPercentage??0)*100)),n("x-neurolink-quota-updated-at",o.lastUpdated)),r}function Von(e){return{...e.upstreamHeaders?Gon(e.upstreamHeaders):{},...Hon(e.context,e.now)}}function Won(e,t=Date.now()){let r=0,n=0,o;for(const s of e){if(!!s.coolingUntil&&s.coolingUntil>t){n+=1;continue}if(r+=1,s.quota){const a=yle(s.quota.sessionUsed);(o===void 0||a>o)&&(o=a)}}return{available:r,cooling:n,...o!==void 0?{bestSessionLeftPct:o}:{}}}Ut(),Yi(),dc();var Qsr=0;function eir(){Qsr+=1;const e=Math.random().toString(36).slice(2,10);return`msg_${Date.now().toString(36)}${e}${Qsr}`}function Z$(){return`toolu_${pf(18).toString("base64url").slice(0,24)}`}function vle(e){let t;typeof e.system=="string"?t=e.system:Array.isArray(e.system)&&(t=e.system.map(u=>u.text).join(`
|
|
2321
2321
|
|
|
2322
|
-
`));const r=[],n=[];let o="",s=-1;for(let u=e.messages.length-1;u>=0;u--)if(e.messages[u].role==="user"){s=u;break}for(let u=0;u<e.messages.length;u++){const d=e.messages[u],m=u===s;if(
|
|
2322
|
+
`));const r=[],n=[];let o="",s=-1;for(let u=e.messages.length-1;u>=0;u--)if(e.messages[u].role==="user"){s=u;break}for(let u=0;u<e.messages.length;u++){const d=e.messages[u],m=u===s;if(d.role==="system"){const h=typeof d.content=="string"?d.content:Array.isArray(d.content)?d.content.map(g=>g.type==="text"?g.text:"").filter(g=>g.length>0).join(`
|
|
2323
|
+
`):"";h&&(t=t?`${t}
|
|
2324
|
+
|
|
2325
|
+
${h}`:h);continue}if(typeof d.content=="string")r.push({role:d.role,content:d.content}),d.role==="user"&&(o=d.content);else if(Array.isArray(d.content)){const h=[];for(const y of d.content)if(y.type==="text")h.push(y.text);else if(y.type==="image")if(m){let v="";y.source.type==="base64"&&y.source.data?v=`data:${y.source.media_type||"image/png"};base64,${y.source.data}`:y.source.type==="url"&&y.source.url&&(v=y.source.url),v&&n.push(v)}else h.push(`[image: ${y.source.type}]`);else if(y.type==="tool_use"){const v=y.input!==void 0?JSON.stringify(y.input):"{}";h.push(`[tool_use:${y.id}:${y.name}] ${v}`)}else if(y.type==="tool_result"){const v=typeof y.content=="string"?y.content:Array.isArray(y.content)?y.content.map(_=>_.type==="text"?_.text:`[${_.type}]`).join(`
|
|
2323
2326
|
`):"";h.push(`[tool_result:${y.tool_use_id}] ${v}`)}else if(y.type){const{type:v,..._}=y,b=JSON.stringify(_),T=b.length>200?b.slice(0,200)+"\u2026":b;h.push(`[${v}: ${T}]`)}const g=h.join(`
|
|
2324
2327
|
`);r.push({role:d.role,content:g}),d.role==="user"&&(o=g)}}const i={};if(e.tools)for(const u of e.tools)i[u.name]={description:u.description??"",inputSchema:fm(n8e(u.input_schema??{type:"object"}))};let a,l;if(e.tool_choice)switch(e.tool_choice.type){case"auto":a="auto";break;case"any":a="required";break;case"tool":a="required",l=e.tool_choice.name;break;case"none":a="none";break}let c;return e.thinking&&(c={enabled:e.thinking.type==="enabled"||e.thinking.type==="adaptive",budgetTokens:e.thinking.budget_tokens,...e.thinking.type==="adaptive"?{thinkingLevel:"medium"}:{}}),{model:e.model,maxTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,topK:e.top_k,systemPrompt:t,stream:e.stream===!0,prompt:o,images:n,conversationMessages:r,tools:i,toolChoice:a,toolChoiceName:l,thinkingConfig:c,metadata:e.metadata,stopSequences:e.stop_sequences}}function tir(e){switch(e){case"stop":case"end_turn":return"end_turn";case"length":case"max_tokens":return"max_tokens";case"tool-calls":case"tool_use":return"tool_use";case"content_filter":case"safety":return"stop_sequence";default:return e??"end_turn"}}function _le(e,t){const r=[],n=e.toolCalls&&e.toolCalls.length>0&&(!e.finishReason||e.finishReason==="stop")?"tool_use":e.finishReason;if(e.reasoning&&r.push({type:"thinking",thinking:e.reasoning}),e.content&&r.push({type:"text",text:e.content}),e.toolCalls&&e.toolCalls.length>0)for(const o of e.toolCalls){const s=o.args??o.parameters??o.input??{};r.push({type:"tool_use",id:Z$(),name:o.toolName,input:s})}return r.length===0&&r.push({type:"text",text:""}),{id:eir(),type:"message",role:"assistant",content:r,model:e.model??t,stop_reason:tir(n),stop_sequence:null,usage:{input_tokens:e.usage?.input??0,output_tokens:e.usage?.output??0,...e.usage?.cacheCreationTokens!==void 0&&{cache_creation_input_tokens:e.usage.cacheCreationTokens},...e.usage?.cacheReadTokens!==void 0&&{cache_read_input_tokens:e.usage.cacheReadTokens}}}}function Kon(e){switch(e){case 400:return"invalid_request_error";case 401:return"authentication_error";case 403:return"permission_error";case 404:return"not_found_error";case 413:return"request_too_large";case 429:return"rate_limit_error";case 500:case 502:case 503:return"api_error";case 529:return"overloaded_error";default:return"api_error"}}function ul(e,t,r){return{type:"error",error:{type:r??Kon(e),message:t}}}function Lc(e,t){const r=JSON.stringify(t);return`event: ${e}
|
|
2325
2328
|
data: ${r}
|
|
@@ -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
|
|
@@ -71,6 +71,28 @@ export function parseClaudeRequest(body) {
|
|
|
71
71
|
for (let msgIdx = 0; msgIdx < body.messages.length; msgIdx++) {
|
|
72
72
|
const msg = body.messages[msgIdx];
|
|
73
73
|
const isLatestUserMsg = msgIdx === lastUserMsgIdx;
|
|
74
|
+
// The Messages API restricts `messages[].role` to "user"/"assistant" —
|
|
75
|
+
// system prompts are a separate top-level field — but nothing at the
|
|
76
|
+
// wire boundary enforces that. A client that inlines a "system" message
|
|
77
|
+
// here would otherwise flow straight into conversationMessages and land
|
|
78
|
+
// at a non-leading index once translated to an OpenAI-shaped request for
|
|
79
|
+
// a fallback provider (e.g. LiteLLM/vLLM), whose chat templates reject
|
|
80
|
+
// any system message not at index 0. Fold it into systemPrompt instead,
|
|
81
|
+
// mirroring parseOpenAIRequest's handling of inline system messages.
|
|
82
|
+
if (msg.role === "system") {
|
|
83
|
+
const text = typeof msg.content === "string"
|
|
84
|
+
? msg.content
|
|
85
|
+
: Array.isArray(msg.content)
|
|
86
|
+
? msg.content
|
|
87
|
+
.map((b) => (b.type === "text" ? b.text : ""))
|
|
88
|
+
.filter((t) => t.length > 0)
|
|
89
|
+
.join("\n")
|
|
90
|
+
: "";
|
|
91
|
+
if (text) {
|
|
92
|
+
systemPrompt = systemPrompt ? `${systemPrompt}\n\n${text}` : text;
|
|
93
|
+
}
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
74
96
|
if (typeof msg.content === "string") {
|
|
75
97
|
conversationMessages.push({ role: msg.role, content: msg.content });
|
|
76
98
|
if (msg.role === "user") {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "12.7.
|
|
3
|
+
"version": "12.7.6",
|
|
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",
|