@juspay/neurolink 12.4.3 → 12.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +3 -3
- package/dist/browser/neurolink.min.js +2 -2
- package/dist/hitl/hitlManager.d.ts +14 -0
- package/dist/hitl/hitlManager.js +16 -0
- package/dist/neurolink.d.ts +37 -0
- package/dist/neurolink.js +39 -0
- package/dist/types/hitl.d.ts +2 -0
- package/package.json +1 -1
|
@@ -1476,7 +1476,7 @@ Audio processing failed. Error: ${n instanceof Error?n.message:String(n)}`}}asyn
|
|
|
1476
1476
|
- ARCHIVE (zip): Use entry_path to extract a specific file from the archive
|
|
1477
1477
|
- TEXT/CODE: Use page_range as line range for targeted reading
|
|
1478
1478
|
|
|
1479
|
-
For video extraction, the result includes images (frames) that will be visible to you. Always call list_attached_files first to discover file IDs.`,inputSchema:p.object({file_id:p.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:p.number().optional().describe("Start timestamp in seconds (video only)"),end_time:p.number().optional().describe("End timestamp in seconds (video only)"),frame_count:p.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:p.array(p.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:p.object({start:p.number().int().min(1),end:p.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:p.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:p.object({start:p.number().int().min(1),end:p.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:p.array(p.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:p.string().optional().describe("File path within archive to extract (archive only)"),format:p.enum(["text","detailed","summary"]).optional().describe("Output format hint (default: text)")}),execute:async t=>{try{const r={...t,sheet:t.sheet!==void 0?/^\d+$/.test(t.sheet)?parseInt(t.sheet,10):t.sheet:void 0},n=await e.extractContent(r);return n.success?{success:!0,text:n.text,metadata:n.metadata,imageCount:n.images?.length??0,_images:n.images,error:void 0}:{success:!1,error:n.error,text:void 0,metadata:void 0,imageCount:0,_images:void 0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),text:void 0,metadata:void 0,imageCount:0,_images:void 0}}},toModelOutput:({output:t})=>{const r=[];if(t.text?r.push({type:"text",text:t.text}):t.error&&r.push({type:"text",text:`Error: ${t.error}`}),t._images&&t._images.length>0)for(const n of t._images)r.push({type:"image-data",data:n.toString("base64"),mediaType:"image/jpeg"});return r.length===0&&r.push({type:"text",text:"(No content extracted)"}),{type:"content",value:r}}}}function DMt(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(2)} GB`}var N3r=S({"src/lib/files/fileTools.ts"(){"use strict";jr(),lc()}}),y_,ree,nee,OMt=S({"src/lib/hitl/hitlManager.ts"(){"use strict";vn(),Ft(),a1(),q(),y_=3e4,ree=!1,nee=class extends nn{config;pendingConfirmations=new Map;statistics={totalRequests:0,pendingRequests:0,averageResponseTime:0,approvedRequests:0,rejectedRequests:0,timedOutRequests:0};constructor(e){super(),this.config=this.validateConfig(e),this.setupEventHandlers()}validateConfig(e){const t={enabled:e.enabled,dangerousActions:e.dangerousActions,timeout:e.timeout??y_,confirmationMethod:e.confirmationMethod??"event",allowArgumentModification:e.allowArgumentModification??ree,autoApproveOnTimeout:e.autoApproveOnTimeout??!1,auditLogging:e.auditLogging??!1,customRules:e.customRules??[]};if(!t.enabled)return t;if(!Array.isArray(t.dangerousActions))throw new ET("dangerousActions must be an array of strings");if(typeof t.timeout!="number"||t.timeout<=0)throw new ET("timeout must be a positive number (milliseconds)");if(t.confirmationMethod!=="event")throw new ET("confirmationMethod must be 'event' (only supported method)");if(typeof t.allowArgumentModification!="boolean")throw new ET("allowArgumentModification must be a boolean");return t}requiresConfirmation(e,t){if(!this.config.enabled)return!1;const r=e.toLowerCase();for(const n of this.config.dangerousActions)if(r.includes(n.toLowerCase()))return!0;if(this.config.customRules){for(const n of this.config.customRules)if(n.requiresConfirmation)try{if(n.condition(e,t))return!0}catch(o){this.logAuditEvent("rule-evaluation-error",{ruleName:n.name,toolName:e,error:o instanceof Error?o.message:String(o)})}}return!1}async requestConfirmation(e,t,r){const n=this.generateConfirmationId(),o=Date.now();return this.statistics.totalRequests++,this.statistics.pendingRequests++,new Promise((s,i)=>{const a=setTimeout(()=>{this.handleTimeout(n)},this.config.timeout),l={confirmationId:n,toolName:e,arguments:t,timestamp:o,timeoutHandle:a,resolve:s,reject:i};this.pendingConfirmations.set(n,l);const c={type:"hitl:confirmation-request",payload:{confirmationId:n,toolName:e,serverId:r?.serverId,actionType:this.generateActionDescription(e,t),arguments:t,metadata:{timestamp:new Date(o).toISOString(),sessionId:r?.sessionId,userId:r?.userId,dangerousKeywords:this.getTriggeredKeywords(e,t)},timeoutMs:this.config.timeout??y_,allowModification:this.config.allowArgumentModification??ree}};this.emit("hitl:confirmation-request",c),this.config.auditLogging&&this.logAuditEvent("confirmation-requested",{confirmationId:n,toolName:e,userId:r?.userId,sessionId:r?.sessionId,timestamp:o,arguments:t})})}processUserResponse(e,t){const r=this.pendingConfirmations.get(e);if(!r){f.warn(`No pending confirmation found for ID: ${e}`);return}clearTimeout(r.timeoutHandle),this.pendingConfirmations.delete(e),this.statistics.pendingRequests--;const n=t.responseTime||Date.now()-r.timestamp;t.approved?this.statistics.approvedRequests++:this.statistics.rejectedRequests++;const o=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(o-1)+n)/o;const s={approved:t.approved,reason:t.reason,modifiedArguments:t.modifiedArguments,responseTime:n};this.config.auditLogging&&this.logAuditEvent(t.approved?"confirmation-approved":"confirmation-rejected",{confirmationId:e,toolName:r.toolName,approved:t.approved,reason:t.reason,userId:t.userId,responseTime:n,arguments:r.arguments}),r.resolve(s)}handleTimeout(e){const t=this.pendingConfirmations.get(e);if(!t)return;this.pendingConfirmations.delete(e),this.statistics.pendingRequests--,this.statistics.timedOutRequests++;const r=Date.now()-t.timestamp,n=this.config.autoApproveOnTimeout===!0;this.config.auditLogging&&this.logAuditEvent("confirmation-timeout",{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??y_,arguments:t.arguments,autoApproved:n});const o={type:"hitl:timeout",payload:{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??y_}};if(this.emit("hitl:timeout",o),n){this.statistics.approvedRequests++;const s=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(s-1)+r)/s,this.config.auditLogging&&this.logAuditEvent("confirmation-auto-approved",{confirmationId:e,toolName:t.toolName,reason:"Auto-approved due to timeout",responseTime:r,arguments:t.arguments});const i={approved:!0,reason:"Auto-approved due to timeout",responseTime:r};t.resolve(i)}else t.reject(new TT(`Confirmation timeout for tool: ${t.toolName}`,e,this.config.timeout??y_))}setupEventHandlers(){this.on("hitl:confirmation-response",e=>{e.payload?.confirmationId&&this.processUserResponse(e.payload.confirmationId,{approved:e.payload.approved,reason:e.payload.reason,modifiedArguments:e.payload.modifiedArguments,responseTime:e.payload.metadata?.responseTime,userId:e.payload.metadata?.userId})})}generateConfirmationId(){return`hitl-${Date.now()}-${st()}`}generateActionDescription(e,t){const r=e.toLowerCase();if(r.includes("delete"))return"Delete Operation";if(r.includes("remove"))return"Remove Operation";if(r.includes("update"))return"Update Operation";if(r.includes("create"))return"Create Operation";if(r.includes("drop"))return"Drop Operation";if(r.includes("truncate"))return"Truncate Operation";if(r.includes("restart"))return"Restart Operation";if(r.includes("stop"))return"Stop Operation";if(r.includes("kill"))return"Kill Operation";if(this.config.customRules)for(const n of this.config.customRules)try{if(n.condition(e,t)&&n.customMessage)return n.customMessage}catch{}return`Execute ${e}`}getTriggeredKeywords(e,t){const r=[],n=e.toLowerCase();for(const o of this.config.dangerousActions)n.includes(o.toLowerCase())&&r.push(o);if(this.config.customRules)for(const o of this.config.customRules)try{o.requiresConfirmation&&o.condition(e,t)&&r.push(o.name)}catch{}return r}logAuditEvent(e,t){const r={timestamp:new Date().toISOString(),eventType:e,toolName:t.toolName,userId:t.userId,sessionId:t.sessionId,arguments:t.arguments,reason:t.reason,responseTime:t.responseTime,...t};f.info(`[HITL Audit] ${e}:`,r),this.emit("hitl:audit",r)}getStatistics(){return{...this.statistics}}getConfig(){return{...this.config}}updateConfig(e){const t={...this.config,...e};this.config=this.validateConfig(t),this.config.auditLogging&&this.logAuditEvent("configuration-updated",{oldConfig:this.config,newConfig:t})}cleanup(){for(const[e,t]of this.pendingConfirmations)clearTimeout(t.timeoutHandle),t.reject(new Error(`HITL cleanup: confirmation ${e} cancelled`));this.pendingConfirmations.clear(),this.statistics.pendingRequests=0,this.config.auditLogging&&this.logAuditEvent("manager-cleanup",{clearedConfirmations:this.pendingConfirmations.size})}isEnabled(){return this.config.enabled}getPendingCount(){return this.pendingConfirmations.size}}}}),lN,NMt,oee,cN,LMt,L3r=S({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";vn(),q(),ct(),Vr(),yr(),lN=class extends nn{config;pending=new Map;serverQueues=new Map;flushTimer;executor;activeBatches=0;batchCounter=0;requestCounter=0;isDestroyed=!1;constructor(e){super(),this.config={maxBatchSize:e.maxBatchSize,maxWaitMs:e.maxWaitMs,enableParallel:e.enableParallel??!0,maxConcurrentBatches:e.maxConcurrentBatches??5,groupByServer:e.groupByServer??!0}}setExecutor(e){this.executor=e}async add(e,t,r){if(this.isDestroyed)throw xe.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw xe.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before adding requests"});const n=this.generateRequestId();return new Promise((o,s)=>{const i={id:n,tool:e,args:t,serverId:r,resolve:o,reject:s,addedAt:Date.now()};if(this.pending.set(n,i),this.config.groupByServer&&r){this.serverQueues.has(r)||this.serverQueues.set(r,new Set);const a=this.serverQueues.get(r);a&&a.add(n)}this.emit("requestQueued",{requestId:n,queueSize:this.pending.size}),this.pending.size>=this.config.maxBatchSize?this.scheduleFlush("size"):this.flushTimer||(this.flushTimer=setTimeout(()=>{this.scheduleFlush("timeout")},this.config.maxWaitMs))})}async flush(){this.clearFlushTimer(),this.pending.size!==0&&(this.emit("flushTriggered",{reason:"manual",queueSize:this.pending.size}),await this.executeBatch())}get queueSize(){return this.pending.size}get activeBatchCount(){return this.activeBatches}get isIdle(){return this.pending.size===0&&this.activeBatches===0}async drain(){await this.flush();const e=3e4,t=Date.now()+e;for(;!this.isIdle;){if(Date.now()>=t)throw xe.toolTimeout("batchDrain",e);await new Promise(r=>setTimeout(r,10))}}destroy(){this.isDestroyed=!0,this.clearFlushTimer();for(const e of this.pending.values())e.reject(xe.invalidConfiguration("batcher","Batcher was destroyed before request could complete"));this.pending.clear(),this.serverQueues.clear()}generateRequestId(){return`req-${Date.now()}-${++this.requestCounter}`}generateBatchId(){return`batch-${Date.now()}-${++this.batchCounter}`}scheduleFlush(e){this.clearFlushTimer(),this.emit("flushTriggered",{reason:e,queueSize:this.pending.size}),setImmediate(()=>{this.executeBatch().catch(t=>{f.error("Batch execution failed:",t)})})}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}async executeBatch(){if(this.pending.size===0)return;if(this.activeBatches>=this.config.maxConcurrentBatches){this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Rescheduled batch execution failed:",n)})},10);return}const e=this.selectBatchRequests();if(e.length===0)return;const t=this.generateBatchId(),r=Date.now();this.activeBatches++,this.emit("batchStarted",{batchId:t,size:e.length}),await gt({name:"neurolink.mcp.batch.execute",tracer:He.mcp,attributes:{"mcp.batch.id":t,"mcp.batch.size":e.length,"mcp.batch.active_batches":this.activeBatches}},async n=>{let o=0,s=0;try{if(!this.executor)throw xe.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before executing batches"});const i=this.executor(e.map(m=>({tool:m.tool,args:m.args,serverId:m.serverId}))),a=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4);let l;const c=new Promise((m,h)=>{l=setTimeout(()=>h(xe.toolTimeout("batchExecution",a)),a)});i.catch(m=>{});const u=await Promise.race([i,c]).finally(()=>{l&&clearTimeout(l)}),d=[];for(let m=0;m<e.length;m++){const h=e[m],g=u[m],y=Date.now()-r;if(!g){const v=xe.toolExecutionFailed(h.tool,new Error(`Batch executor returned no result for request ${m}`));h.reject(v),d.push({id:h.id,success:!1,error:v,executionTime:y}),s++;continue}if(g.success)h.resolve(g.result),d.push({id:h.id,success:!0,result:g.result,executionTime:y}),o++;else{const v=g.error??xe.toolExecutionFailed(h.tool,new Error("Unknown batch execution error"));h.reject(v),d.push({id:h.id,success:!1,error:v,executionTime:y}),s++}}n.setAttribute("mcp.batch.success_count",o),n.setAttribute("mcp.batch.error_count",s),this.emit("batchCompleted",{batchId:t,results:d})}catch(i){const a=i instanceof Error?i:xe.toolExecutionFailed("batch",new Error(String(i)));for(const l of e)l.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{f.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Follow-up batch execution failed:",n)})},0))}selectBatchRequests(){const e=[];if(this.config.groupByServer&&this.serverQueues.size>0){const[t,r]=this.serverQueues.entries().next().value;for(const n of r){if(e.length>=this.config.maxBatchSize)break;const o=this.pending.get(n);o&&(e.push(o),this.pending.delete(n),r.delete(n))}r.size===0&&this.serverQueues.delete(t)}else{const t=Array.from(this.pending.values()).sort((r,n)=>r.addedAt-n.addedAt);for(const r of t){if(e.length>=this.config.maxBatchSize)break;e.push(r),this.pending.delete(r.id)}}return e}},NMt=e=>new lN(e),oee={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},cN=class{batcher;toolExecutor;constructor(e){this.batcher=new lN({...oee,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw xe.missingConfiguration("toolExecutor",{hint:"Call setToolExecutor() before executing tool calls"});const r=this.toolExecutor;return await Promise.all(t.map(async o=>{try{return{success:!0,result:await r(o.tool,o.args,o.serverId)}}catch(s){return{success:!1,error:s instanceof Error?s:xe.toolExecutionFailed(o.tool,new Error(String(s)))}}}))})}setToolExecutor(e){this.toolExecutor=e}async execute(e,t,r){return this.batcher.add(e,t,r)}async flush(){return this.batcher.flush()}async drain(){return this.batcher.drain()}get queueSize(){return this.batcher.queueSize}get isIdle(){return this.batcher.isIdle}destroy(){this.batcher.destroy()}},LMt=e=>new cN(e)}}),$Mt=S({"src/lib/mcp/batching/index.ts"(){"use strict";L3r()}}),xg,FMt,see,uN,UMt,$3r=S({"src/lib/mcp/caching/toolCache.ts"(){"use strict";Ft(),vn(),yn(),xg=class extends nn{cache=new Map;config;stats;cleanupTimer;constructor(e){super(),this.config={ttl:e.ttl,maxSize:e.maxSize,strategy:e.strategy,enableAutoCleanup:e.enableAutoCleanup??!0,cleanupInterval:e.cleanupInterval??6e4,namespace:e.namespace??""},this.stats={hits:0,misses:0,evictions:0,size:0,maxSize:this.config.maxSize,hitRate:0},this.config.enableAutoCleanup&&this.startAutoCleanup()}get(e){const t=this.getFullKey(e),r=this.cache.get(t);if(!r){this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}if(this.isExpired(r)){this.deleteWithReason(t,"expired"),this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}return r.accessedAt=Date.now(),r.accessCount++,this.stats.hits++,this.updateHitRate(),this.emit("hit",{key:t,value:r.value}),r.value}set(e,t,r){const n=this.getFullKey(e),o=r??this.config.ttl,s=Date.now();this.cache.size>=this.config.maxSize&&!this.cache.has(n)&&this.evictOne();const i={value:t,expires:s+o,createdAt:s,accessedAt:s,accessCount:1,key:n};this.cache.set(n,i),this.stats.size=this.cache.size,this.emit("set",{key:n,value:t,ttl:o})}has(e){const t=this.getFullKey(e),r=this.cache.get(t);return r?this.isExpired(r)?(this.deleteWithReason(t,"expired"),!1):!0:!1}delete(e){const t=this.getFullKey(e),r=this.cache.delete(t);return r&&(this.stats.size=this.cache.size,this.emit("evict",{key:t,reason:"manual"})),r}invalidate(e){const t=this.getFullKey(e),r=this.patternToRegex(t);let n=0;for(const o of this.cache.keys())r.test(o)&&(this.cache.delete(o),n++,this.emit("evict",{key:o,reason:"manual"}));return this.stats.size=this.cache.size,n}clear(){const e=this.cache.size;this.cache.clear(),this.stats.size=0,this.emit("clear",{entriesRemoved:e})}async getOrSet(e,t,r){const n=this.get(e);if(n!==void 0)return n;const o=3e4,s=await zt(Promise.resolve(t()),o,`ToolCache getOrSet factory timed out after ${o}ms for key "${e}"`);return s===void 0||this.set(e,s,r),s}getStats(){return{...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0,this.stats.evictions=0,this.updateHitRate()}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}static generateKey(e,t){const r=(o,s=new WeakSet)=>{if(o===null||typeof o!="object")return JSON.stringify(o);if(o instanceof Date)return`{"$date":${JSON.stringify(o.toISOString())}}`;if(s.has(o))throw new TypeError("Circular structures are not supported in cache keys");if(s.add(o),Array.isArray(o)){const l="["+o.map(c=>r(c,s)).join(",")+"]";return s.delete(o),l}const a=Object.keys(o).sort().map(l=>JSON.stringify(l)+":"+r(o[l],s));return s.delete(o),"{"+a.join(",")+"}"},n=Kc("sha256").update(r(t)).digest("hex").substring(0,16);return`${e}:${n}`}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear()}getFullKey(e){return this.config.namespace?`${this.config.namespace}:${e}`:e}isExpired(e){return Date.now()>e.expires}deleteWithReason(e,t){const r=this.cache.delete(e);return r&&(this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e,reason:t})),r}evictOne(){const e=this.selectEvictionCandidate();e&&(this.cache.delete(e.key),this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e.key,reason:"capacity"}))}selectEvictionCandidate(){if(this.cache.size!==0)switch(this.config.strategy){case"lru":return this.findLRU();case"fifo":return this.findFIFO();case"lfu":return this.findLFU();default:return this.findLRU()}}findLRU(){let e,t=1/0;for(const r of this.cache.values())r.accessedAt<t&&(t=r.accessedAt,e=r);return e}findFIFO(){let e,t=1/0;for(const r of this.cache.values())r.createdAt<t&&(t=r.createdAt,e=r);return e}findLFU(){let e,t=1/0;for(const r of this.cache.values())r.accessCount<t&&(t=r.accessCount,e=r);return e}patternToRegex(e){const r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^:]*");return new RegExp(`^${r}$`)}updateHitRate(){const e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0}startAutoCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},this.config.cleanupInterval),this.cleanupTimer.unref&&this.cleanupTimer.unref()}cleanupExpired(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expires&&(this.cache.delete(t),this.stats.evictions++,this.emit("evict",{key:t,reason:"expired"}));this.stats.size=this.cache.size}},FMt=e=>new xg(e),see={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},uN=class{cache;constructor(e){this.cache=new xg({...see,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=xg.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=xg.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=xg.generateKey(e,t);return this.cache.has(r)}invalidateTool(e){return this.cache.invalidate(`${e}:*`)}getStats(){return this.cache.getStats()}clear(){this.cache.clear()}destroy(){this.cache.destroy()}},UMt=e=>new uN(e)}}),BMt=S({"src/lib/mcp/caching/index.ts"(){"use strict";$3r()}}),zMt={};he(zMt,{MultiServerManager:()=>ck,globalMultiServerManager:()=>iee});var ck,iee,aee=S({"src/lib/mcp/multiServerManager.ts"(){"use strict";vn(),q(),ct(),ck=class extends nn{config;servers=new Map;groups=new Map;metrics=new Map;roundRobinCounters=new Map;toolPreferences=new Map;constructor(e={}){super(),this.config={defaultStrategy:e.defaultStrategy??"round-robin",healthAwareRouting:e.healthAwareRouting??!0,healthCheckInterval:e.healthCheckInterval??3e4,maxFailoverRetries:e.maxFailoverRetries??3,namespaceSeparator:e.namespaceSeparator??".",autoNamespace:e.autoNamespace??!1,conflictResolution:e.conflictResolution??"first-wins"}}addServer(e){this.servers.set(e.id,e),this.metrics.set(e.id,{activeRequests:0,totalRequests:0,completedRequests:0,averageResponseTime:0,errorRate:0,isHealthy:e.status==="connected"}),this.emit("serverAdded",{serverId:e.id,server:e}),f.debug(`[MultiServerManager] Added server: ${e.id} (${e.name})`)}removeServer(e){if(!this.servers.get(e))return!1;for(const[r,n]of this.groups){const o=n.servers.indexOf(e);o!==-1&&(n.servers.splice(o,1),n.servers.length===0&&(this.groups.delete(r),this.roundRobinCounters.delete(r)))}this.servers.delete(e),this.metrics.delete(e);for(const[r,n]of this.toolPreferences)n===e&&this.toolPreferences.delete(r);return this.emit("serverRemoved",{serverId:e}),f.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw xe.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e});const n={...r,...t,id:e};this.servers.set(e,n);const o=this.metrics.get(e);o&&t.status!==void 0&&(o.isHealthy=t.status==="connected"),this.emit("serverUpdated",{serverId:e,server:n})}createGroup(e){for(const t of e.servers)if(!this.servers.has(t))throw xe.invalidConfiguration("serverGroup.servers",`Server '${t}' not found when creating group '${e.id}'`,{serverId:t,groupId:e.id});this.groups.set(e.id,e),this.roundRobinCounters.set(e.id,0),this.emit("groupCreated",{group:e}),f.debug(`[MultiServerManager] Created group: ${e.id} with ${e.servers.length} servers`)}removeGroup(e){const t=this.groups.delete(e);return t&&(this.roundRobinCounters.delete(e),this.emit("groupRemoved",{groupId:e})),t}addServerToGroup(e,t){const r=this.groups.get(t);if(!r)throw xe.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw xe.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e,groupId:t});r.servers.includes(e)||(r.servers.push(e),this.emit("serverAddedToGroup",{serverId:e,groupId:t}))}removeServerFromGroup(e,t){const r=this.groups.get(t);if(!r)return!1;const n=r.servers.indexOf(e);return n!==-1?(r.servers.splice(n,1),this.emit("serverRemovedFromGroup",{serverId:e,groupId:t}),!0):!1}getUnifiedTools(){const e=new Map;for(const[t,r]of this.servers){const o=this.metrics.get(t)?.isHealthy??!0;if(!(this.config.healthAwareRouting&&!o))for(const s of r.tools||[]){const i=e.get(s.name);i?(i.hasConflict=!0,i.servers.push({serverId:t,serverName:r.name,inputSchema:s.inputSchema,priority:this.getServerPriority(t)})):e.set(s.name,{name:s.name,description:s.description,servers:[{serverId:t,serverName:r.name,inputSchema:s.inputSchema,priority:this.getServerPriority(t)}],hasConflict:!1,preferredServerId:this.toolPreferences.get(s.name)})}}for(const t of e.values())t.servers.sort((r,n)=>r.priority-n.priority),!t.preferredServerId&&t.servers.length>0&&(t.preferredServerId=t.servers[0].serverId);return Array.from(e.values())}getNamespacedTools(){const e=[];for(const[t,r]of this.servers)if(!(this.config.healthAwareRouting&&!(this.metrics.get(t)?.isHealthy??!0)))for(const n of r.tools||[])e.push({fullName:`${t}${this.config.namespaceSeparator}${n.name}`,toolName:n.name,serverId:t,serverName:r.name,description:n.description,inputSchema:n.inputSchema});return e}setToolPreference(e,t){if(!this.servers.has(t))throw xe.invalidConfiguration("serverId",`Server '${t}' not found`,{serverId:t,toolName:e});this.toolPreferences.set(e,t),this.emit("toolPreferenceSet",{toolName:e,serverId:t})}clearToolPreference(e){this.toolPreferences.delete(e)}selectServer(e,t){const r=this.toolPreferences.get(e);if(r){const l=this.servers.get(r),c=this.metrics.get(r);if(l&&(!this.config.healthAwareRouting||c?.isHealthy)&&l.tools?.some(u=>u.name===e))return{serverId:r,server:l}}let n;if(t){const l=this.groups.get(t);if(!l)return f.warn(`[MultiServerManager] Group '${t}' not found`),null;n=l.servers.filter(c=>this.servers.get(c)?.tools?.some(d=>d.name===e))}else{n=[];for(const[l,c]of this.servers)c.tools?.some(u=>u.name===e)&&n.push(l)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(l=>this.metrics.get(l)?.isHealthy??!0),n.length===0))return f.warn(`[MultiServerManager] No healthy servers available for tool '${e}'`),null;const s=t?this.groups.get(t)?.strategy??this.config.defaultStrategy:this.config.defaultStrategy,i=this.applyStrategy(s,n,t);if(!i)return null;const a=this.servers.get(i);return a?{serverId:i,server:a}:null}applyStrategy(e,t,r){if(t.length===0)return null;if(t.length===1)return t[0];switch(e){case"round-robin":{const n=r??"default",o=this.roundRobinCounters.get(n)??0,s=t[o%t.length];return this.roundRobinCounters.set(n,o+1),s}case"least-loaded":{let n=1/0,o=t[0];for(const s of t){const a=this.metrics.get(s)?.activeRequests??0;a<n&&(n=a,o=s)}return o}case"random":{const n=Math.floor(Math.random()*t.length);return t[n]}case"weighted":{if(!r){const l=Math.floor(Math.random()*t.length);return t[l]}const n=this.groups.get(r);if(!n?.weights){const l=Math.floor(Math.random()*t.length);return t[l]}const o=1,s=t.map(l=>{const u=(n.weights??[]).find(d=>d.serverId===l);return{serverId:l,weight:u?.weight??o}}),i=s.reduce((l,c)=>l+c.weight,0);if(i===0){const l=Math.floor(Math.random()*t.length);return t[l]}let a=Math.random()*i;for(const l of s)if(a-=l.weight,a<=0)return l.serverId;return t[0]}case"failover-only":return t.map(o=>({id:o,priority:this.getServerPriority(o,r)})).sort((o,s)=>o.priority-s.priority)[0]?.id??null;default:return t[0]}}getServerPriority(e,t){if(t){const n=this.groups.get(t);if(n?.weights){const o=n.weights.find(s=>s.serverId===e);if(o)return o.priority}}for(const n of this.groups.values())if(n.weights){const o=n.weights.find(s=>s.serverId===e);if(o)return o.priority}return Array.from(this.servers.keys()).indexOf(e)}updateMetrics(e,t){const r=this.metrics.get(e);r&&(Object.assign(r,t),this.emit("metricsUpdated",{serverId:e,metrics:{...r}}))}requestStarted(e){const t=this.metrics.get(e);t&&(t.activeRequests++,t.totalRequests++)}requestCompleted(e,t,r){const n=this.metrics.get(e);if(n){n.activeRequests=Math.max(0,n.activeRequests-1),n.completedRequests++;const o=n.averageResponseTime*(n.completedRequests-1)+t;n.averageResponseTime=o/n.completedRequests;const s=.1;n.errorRate=n.errorRate*(1-s)+(r?0:1)*s}}getServers(){return Array.from(this.servers.values())}getServer(e){return this.servers.get(e)}getGroups(){return Array.from(this.groups.values())}getGroup(e){return this.groups.get(e)}getServerMetrics(e){return this.metrics.get(e)}getAllMetrics(){return new Map(this.metrics)}getStatistics(){let e=0,t=0,r=0;for(const s of this.metrics.values())s.isHealthy&&e++,t+=s.totalRequests,r+=s.activeRequests;const n=this.getUnifiedTools(),o=n.filter(s=>s.hasConflict).length;return{totalServers:this.servers.size,healthyServers:e,totalGroups:this.groups.size,totalTools:n.length,conflictingTools:o,totalRequests:t,activeRequests:r}}},iee=new ck}}),jMt={};he(jMt,{EnhancedToolDiscovery:()=>dN});var dN,lee=S({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";vn(),q(),yn(),ct(),rC(),aee(),dN=class extends nn{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new ck}async discoverToolsWithAnnotations(e,t,r=1e4){const n=Date.now();if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-n,serverId:e};this.discoveryInProgress.add(e);try{f.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await zt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw xe.toolExecutionFailed("discoverTools",new Error("No tools returned from server"),e);this.clearServerTools(e);const s=[];for(const i of o.tools){const a=this.createEnhancedToolInfo(e,i),l=this.createToolKey(e,i.name);this.toolRegistry.set(l,a);let c=this.serverToolsMap.get(e);c||(c=new Set,this.serverToolsMap.set(e,c)),c.add(i.name),s.push(a),this.emit("toolDiscovered",{serverId:e,toolName:i.name,annotations:a.annotations,timestamp:new Date})}return f.info(`[EnhancedToolDiscovery] Discovered ${s.length} tools with annotations from ${e}`),{success:!0,toolCount:s.length,tools:s,duration:Date.now()-n,serverId:e}}catch(o){const s=o instanceof Error?o.message:String(o);return f.error(`[EnhancedToolDiscovery] Discovery failed for ${e}:`,o),{success:!1,error:s,toolCount:0,tools:[],duration:Date.now()-n,serverId:e}}finally{this.discoveryInProgress.delete(e)}}createEnhancedToolInfo(e,t){const r=ap({name:t.name,description:t.description??""});return{name:t.name,description:t.description??"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,annotations:r,version:"1.0.0",stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferCategory(t),deprecated:!1}}}inferCategory(e){const t=e.name.toLowerCase(),r=(e.description??"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")?"api":t.includes("data")||t.includes("query")?"data":t.includes("auth")||t.includes("login")?"authentication":t.includes("deploy")||t.includes("build")?"deployment":"general"}searchTools(e){const t=Date.now();let r=Array.from(this.toolRegistry.values());if(e.name){const o=e.name.toLowerCase();r=r.filter(s=>s.name.toLowerCase().includes(o))}if(e.description){const o=e.description.toLowerCase().split(/\s+/);r=r.filter(s=>{const i=s.description.toLowerCase();return o.some(a=>i.includes(a))})}if(e.serverIds?.length){const o=e.serverIds;r=r.filter(s=>o.includes(s.serverId))}if(e.category&&(r=r.filter(o=>o.metadata?.category===e.category)),e.tags?.length){const o=e.tags;r=r.filter(s=>{const i=s.annotations?.tags??[];return o.some(a=>i.includes(a))})}if(e.annotations){const o=e.annotations;r=r.filter(s=>{if(!s.annotations)return!1;for(const[i,a]of Object.entries(o)){const l=i;if(s.annotations[l]!==a)return!1}return!0})}if(e.includeUnavailable||(r=r.filter(o=>o.isAvailable)),e.sortBy){const o=e.sortDirection==="desc"?-1:1;r.sort((s,i)=>{let a=0;switch(e.sortBy){case"name":a=s.name.localeCompare(i.name);break;case"calls":a=s.stats.totalCalls-i.stats.totalCalls;break;case"successRate":{const l=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0,c=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0;a=l-c;break}case"avgExecutionTime":a=s.stats.averageExecutionTime-i.stats.averageExecutionTime;break}return a*o})}const n=r.length;return e.limit&&e.limit>0&&(r=r.slice(0,e.limit)),{tools:r,totalCount:n,criteria:e,executionTime:Date.now()-t}}getToolsBySafetyLevel(e){return Array.from(this.toolRegistry.values()).filter(t=>{const r=t.annotations??{};switch(e){case"dangerous":return r.destructiveHint===!0;case"safe":return r.readOnlyHint===!0;case"moderate":return!r.destructiveHint&&!r.readOnlyHint;default:return!1}})}getToolsRequiringConfirmation(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.requiresConfirmation===!0||e.annotations?.destructiveHint===!0)}getReadOnlyTools(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.readOnlyHint===!0)}getUnifiedTools(){return this.multiServerManager.getUnifiedTools()}registerServer(e){this.multiServerManager.addServer(e)}updateToolAnnotations(e,t,r){const n=this.createToolKey(e,t),o=this.toolRegistry.get(n);return o?(o.annotations={...o.annotations,...r},this.emit("annotationsUpdated",{serverId:e,toolName:t,annotations:o.annotations,timestamp:new Date}),!0):!1}checkCompatibility(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n),s=[],i=[],a=[];if(!o)return{compatible:!1,issues:[`Tool '${e}' not found on server '${t}'`],warnings:[],recommendations:[]};if(r&&o.version){const l=o.version.split(".").map(Number),c=r.split(".").map(Number);l.some(isNaN)||c.some(isNaN)?i.push(`Non-standard version format: tool=${o.version}, target=${r}`):l[0]!==c[0]?s.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):l[1]<c[1]&&i.push(`Minor version mismatch: tool is v${o.version}, target is v${r}`)}return o.metadata?.deprecated&&(i.push("This tool is marked as deprecated"),a.push("Consider using an alternative tool if available")),o.annotations?.securityLevel==="restricted"&&a.push("This tool requires elevated permissions"),{compatible:s.length===0,issues:s,warnings:i,recommendations:a}}getTool(e,t){return this.toolRegistry.get(this.createToolKey(e,t))}getAllTools(){return Array.from(this.toolRegistry.values())}getServerTools(e){const t=this.serverToolsMap.get(e);return t?Array.from(t).map(r=>this.getTool(e,r)).filter(r=>r!==void 0):[]}clearServerTools(e){const t=this.serverToolsMap.get(e);if(t){for(const r of t)this.toolRegistry.delete(this.createToolKey(e,r));this.serverToolsMap.delete(e)}}createToolKey(e,t){return`${e}:${t}`}getStatistics(){const e={},t={},r={safe:0,moderate:0,dangerous:0};let n=0,o=0;for(const s of this.toolRegistry.values()){e[s.serverId]=(e[s.serverId]??0)+1;const i=s.metadata?.category??"general";t[i]=(t[i]??0)+1,s.annotations?.destructiveHint?r.dangerous++:s.annotations?.readOnlyHint?r.safe++:r.moderate++,s.annotations&&Object.keys(s.annotations).length>0&&n++,s.metadata?.deprecated&&o++}return{totalTools:this.toolRegistry.size,toolsByServer:e,toolsByCategory:t,toolsBySafetyLevel:r,toolsWithAnnotations:n,deprecatedTools:o}}}}}),qMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/parse.js"(){cs()}}),cee=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/schemas.js"(){cs(),kt(),qMt()}}),F3r=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/checks.js"(){cs()}}),GMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/iso.js"(){cs(),cee()}}),U3r=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/coerce.js"(){cs(),cee()}}),HMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/external.js"(){cs(),qMt(),cee(),F3r(),cs(),Vb(),k6(),GMt(),GMt(),U3r()}}),VMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4-mini/index.js"(){HMt(),HMt()}});function pN(e){return!!e._zod}function ih(e,t){return pN(e)?wI(e,t):e.safeParse(t)}function WMt(e){if(!e)return;let t;if(pN(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function B3r(e){if(pN(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}var uee=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"(){Fh(),VMt()}}),uk,KMt,ah,dk,ui,dee,pee,z3r,JMt,YMt,mN,tl,v_,ZMt,di,Ll,$l,pi,pk,mee,hN,hee,XMt,fN,__,Yt,gN,QMt,Ag,j3r,Ig,ePt,yN,tPt,w_,Rg,fee,rPt,nPt,oPt,sPt,iPt,aPt,lPt,cPt,gee,yee,uPt,vN,dPt,pPt,_N,mPt,b_,T_,hPt,E_,S_,fPt,mk,wN,bN,TN,q3r,EN,SN,CN,gPt,vee,_ee,kN,wee,C_,Mg,bee,yPt,vPt,Tee,_Pt,Eee,xN,wPt,bPt,See,Cee,TPt,EPt,SPt,CPt,kPt,xPt,APt,IPt,RPt,kee,MPt,PPt,AN,IN,RN,DPt,OPt,NPt,MN,LPt,xee,Aee,$Pt,FPt,Iee,UPt,Ree,hk,G3r,BPt,zPt,Mee,jPt,Pee,qPt,GPt,HPt,VPt,WPt,KPt,JPt,YPt,ZPt,fk,XPt,QPt,Dee,Oee,Nee,eDt,tDt,rDt,nDt,oDt,sDt,iDt,aDt,lDt,cDt,uDt,dDt,pDt,mDt,hDt,Lee,fDt,gDt,$ee,yDt,vDt,_Dt,wDt,Fee,bDt,TDt,EDt,SDt,H3r,V3r,W3r,K3r,J3r,Y3r,Lt,CDt,lh=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"(){ut(),uk="2025-11-25",KMt=[uk,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ah="io.modelcontextprotocol/related-task",dk="2.0",ui=uB(e=>e!==null&&(typeof e=="object"||typeof e=="function")),dee=tn([le(),Ir().int()]),pee=le(),z3r=Ps({ttl:tn([Ir(),Wb()]).optional(),pollInterval:Ir().optional()}),JMt=ot({ttl:Ir().optional()}),YMt=ot({taskId:le()}),mN=Ps({progressToken:dee.optional(),[ah]:YMt.optional()}),tl=ot({_meta:mN.optional()}),v_=tl.extend({task:JMt.optional()}),ZMt=e=>v_.safeParse(e).success,di=ot({method:le(),params:tl.loose().optional()}),Ll=ot({_meta:mN.optional()}),$l=ot({method:le(),params:Ll.loose().optional()}),pi=Ps({_meta:mN.optional()}),pk=tn([le(),Ir().int()]),mee=ot({jsonrpc:Tt(dk),id:pk,...di.shape}).strict(),hN=e=>mee.safeParse(e).success,hee=ot({jsonrpc:Tt(dk),...$l.shape}).strict(),XMt=e=>hee.safeParse(e).success,fN=ot({jsonrpc:Tt(dk),id:pk,result:pi}).strict(),__=e=>fN.safeParse(e).success,(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Yt||(Yt={})),gN=ot({jsonrpc:Tt(dk),id:pk.optional(),error:ot({code:Ir().int(),message:le(),data:cn().optional()})}).strict(),QMt=e=>gN.safeParse(e).success,Ag=tn([mee,hee,fN,gN]),j3r=tn([fN,gN]),Ig=pi.strict(),ePt=Ll.extend({requestId:pk.optional(),reason:le().optional()}),yN=$l.extend({method:Tt("notifications/cancelled"),params:ePt}),tPt=ot({src:le(),mimeType:le().optional(),sizes:rt(le()).optional(),theme:Gi(["light","dark"]).optional()}),w_=ot({icons:rt(tPt).optional()}),Rg=ot({name:le(),title:le().optional()}),fee=Rg.extend({...Rg.shape,...w_.shape,version:le(),websiteUrl:le().optional(),description:le().optional()}),rPt=Kb(ot({applyDefaults:en().optional()}),fn(le(),cn())),nPt=bR(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Kb(ot({form:rPt.optional(),url:ui.optional()}),fn(le(),cn()).optional())),oPt=Ps({list:ui.optional(),cancel:ui.optional(),requests:Ps({sampling:Ps({createMessage:ui.optional()}).optional(),elicitation:Ps({create:ui.optional()}).optional()}).optional()}),sPt=Ps({list:ui.optional(),cancel:ui.optional(),requests:Ps({tools:Ps({call:ui.optional()}).optional()}).optional()}),iPt=ot({experimental:fn(le(),ui).optional(),sampling:ot({context:ui.optional(),tools:ui.optional()}).optional(),elicitation:nPt.optional(),roots:ot({listChanged:en().optional()}).optional(),tasks:oPt.optional()}),aPt=tl.extend({protocolVersion:le(),capabilities:iPt,clientInfo:fee}),lPt=di.extend({method:Tt("initialize"),params:aPt}),cPt=ot({experimental:fn(le(),ui).optional(),logging:ui.optional(),completions:ui.optional(),prompts:ot({listChanged:en().optional()}).optional(),resources:ot({subscribe:en().optional(),listChanged:en().optional()}).optional(),tools:ot({listChanged:en().optional()}).optional(),tasks:sPt.optional()}),gee=pi.extend({protocolVersion:le(),capabilities:cPt,serverInfo:fee,instructions:le().optional()}),yee=$l.extend({method:Tt("notifications/initialized"),params:Ll.optional()}),uPt=e=>yee.safeParse(e).success,vN=di.extend({method:Tt("ping"),params:tl.optional()}),dPt=ot({progress:Ir(),total:En(Ir()),message:En(le())}),pPt=ot({...Ll.shape,...dPt.shape,progressToken:dee}),_N=$l.extend({method:Tt("notifications/progress"),params:pPt}),mPt=tl.extend({cursor:pee.optional()}),b_=di.extend({params:mPt.optional()}),T_=pi.extend({nextCursor:pee.optional()}),hPt=Gi(["working","input_required","completed","failed","cancelled"]),E_=ot({taskId:le(),status:hPt,ttl:tn([Ir(),Wb()]),createdAt:le(),lastUpdatedAt:le(),pollInterval:En(Ir()),statusMessage:En(le())}),S_=pi.extend({task:E_}),fPt=Ll.merge(E_),mk=$l.extend({method:Tt("notifications/tasks/status"),params:fPt}),wN=di.extend({method:Tt("tasks/get"),params:tl.extend({taskId:le()})}),bN=pi.merge(E_),TN=di.extend({method:Tt("tasks/result"),params:tl.extend({taskId:le()})}),q3r=pi.loose(),EN=b_.extend({method:Tt("tasks/list")}),SN=T_.extend({tasks:rt(E_)}),CN=di.extend({method:Tt("tasks/cancel"),params:tl.extend({taskId:le()})}),gPt=pi.merge(E_),vee=ot({uri:le(),mimeType:En(le()),_meta:fn(le(),cn()).optional()}),_ee=vee.extend({text:le()}),kN=le().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),wee=vee.extend({blob:kN}),C_=Gi(["user","assistant"]),Mg=ot({audience:rt(C_).optional(),priority:Ir().min(0).max(1).optional(),lastModified:cR.datetime({offset:!0}).optional()}),bee=ot({...Rg.shape,...w_.shape,uri:le(),description:En(le()),mimeType:En(le()),annotations:Mg.optional(),_meta:En(Ps({}))}),yPt=ot({...Rg.shape,...w_.shape,uriTemplate:le(),description:En(le()),mimeType:En(le()),annotations:Mg.optional(),_meta:En(Ps({}))}),vPt=b_.extend({method:Tt("resources/list")}),Tee=T_.extend({resources:rt(bee)}),_Pt=b_.extend({method:Tt("resources/templates/list")}),Eee=T_.extend({resourceTemplates:rt(yPt)}),xN=tl.extend({uri:le()}),wPt=xN,bPt=di.extend({method:Tt("resources/read"),params:wPt}),See=pi.extend({contents:rt(tn([_ee,wee]))}),Cee=$l.extend({method:Tt("notifications/resources/list_changed"),params:Ll.optional()}),TPt=xN,EPt=di.extend({method:Tt("resources/subscribe"),params:TPt}),SPt=xN,CPt=di.extend({method:Tt("resources/unsubscribe"),params:SPt}),kPt=Ll.extend({uri:le()}),xPt=$l.extend({method:Tt("notifications/resources/updated"),params:kPt}),APt=ot({name:le(),description:En(le()),required:En(en())}),IPt=ot({...Rg.shape,...w_.shape,description:En(le()),arguments:En(rt(APt)),_meta:En(Ps({}))}),RPt=b_.extend({method:Tt("prompts/list")}),kee=T_.extend({prompts:rt(IPt)}),MPt=tl.extend({name:le(),arguments:fn(le(),le()).optional()}),PPt=di.extend({method:Tt("prompts/get"),params:MPt}),AN=ot({type:Tt("text"),text:le(),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),IN=ot({type:Tt("image"),data:kN,mimeType:le(),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),RN=ot({type:Tt("audio"),data:kN,mimeType:le(),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),DPt=ot({type:Tt("tool_use"),name:le(),id:le(),input:fn(le(),cn()),_meta:fn(le(),cn()).optional()}),OPt=ot({type:Tt("resource"),resource:tn([_ee,wee]),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),NPt=bee.extend({type:Tt("resource_link")}),MN=tn([AN,IN,RN,NPt,OPt]),LPt=ot({role:C_,content:MN}),xee=pi.extend({description:le().optional(),messages:rt(LPt)}),Aee=$l.extend({method:Tt("notifications/prompts/list_changed"),params:Ll.optional()}),$Pt=ot({title:le().optional(),readOnlyHint:en().optional(),destructiveHint:en().optional(),idempotentHint:en().optional(),openWorldHint:en().optional()}),FPt=ot({taskSupport:Gi(["required","optional","forbidden"]).optional()}),Iee=ot({...Rg.shape,...w_.shape,description:le().optional(),inputSchema:ot({type:Tt("object"),properties:fn(le(),ui).optional(),required:rt(le()).optional()}).catchall(cn()),outputSchema:ot({type:Tt("object"),properties:fn(le(),ui).optional(),required:rt(le()).optional()}).catchall(cn()).optional(),annotations:$Pt.optional(),execution:FPt.optional(),_meta:fn(le(),cn()).optional()}),UPt=b_.extend({method:Tt("tools/list")}),Ree=T_.extend({tools:rt(Iee)}),hk=pi.extend({content:rt(MN).default([]),structuredContent:fn(le(),cn()).optional(),isError:en().optional()}),G3r=hk.or(pi.extend({toolResult:cn()})),BPt=v_.extend({name:le(),arguments:fn(le(),cn()).optional()}),zPt=di.extend({method:Tt("tools/call"),params:BPt}),Mee=$l.extend({method:Tt("notifications/tools/list_changed"),params:Ll.optional()}),jPt=ot({autoRefresh:en().default(!0),debounceMs:Ir().int().nonnegative().default(300)}),Pee=Gi(["debug","info","notice","warning","error","critical","alert","emergency"]),qPt=tl.extend({level:Pee}),GPt=di.extend({method:Tt("logging/setLevel"),params:qPt}),HPt=Ll.extend({level:Pee,logger:le().optional(),data:cn()}),VPt=$l.extend({method:Tt("notifications/message"),params:HPt}),WPt=ot({name:le().optional()}),KPt=ot({hints:rt(WPt).optional(),costPriority:Ir().min(0).max(1).optional(),speedPriority:Ir().min(0).max(1).optional(),intelligencePriority:Ir().min(0).max(1).optional()}),JPt=ot({mode:Gi(["auto","required","none"]).optional()}),YPt=ot({type:Tt("tool_result"),toolUseId:le().describe("The unique identifier for the corresponding tool call."),content:rt(MN).default([]),structuredContent:ot({}).loose().optional(),isError:en().optional(),_meta:fn(le(),cn()).optional()}),ZPt=vR("type",[AN,IN,RN]),fk=vR("type",[AN,IN,RN,DPt,YPt]),XPt=ot({role:C_,content:tn([fk,rt(fk)]),_meta:fn(le(),cn()).optional()}),QPt=v_.extend({messages:rt(XPt),modelPreferences:KPt.optional(),systemPrompt:le().optional(),includeContext:Gi(["none","thisServer","allServers"]).optional(),temperature:Ir().optional(),maxTokens:Ir().int(),stopSequences:rt(le()).optional(),metadata:ui.optional(),tools:rt(Iee).optional(),toolChoice:JPt.optional()}),Dee=di.extend({method:Tt("sampling/createMessage"),params:QPt}),Oee=pi.extend({model:le(),stopReason:En(Gi(["endTurn","stopSequence","maxTokens"]).or(le())),role:C_,content:ZPt}),Nee=pi.extend({model:le(),stopReason:En(Gi(["endTurn","stopSequence","maxTokens","toolUse"]).or(le())),role:C_,content:tn([fk,rt(fk)])}),eDt=ot({type:Tt("boolean"),title:le().optional(),description:le().optional(),default:en().optional()}),tDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),minLength:Ir().optional(),maxLength:Ir().optional(),format:Gi(["email","uri","date","date-time"]).optional(),default:le().optional()}),rDt=ot({type:Gi(["number","integer"]),title:le().optional(),description:le().optional(),minimum:Ir().optional(),maximum:Ir().optional(),default:Ir().optional()}),nDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),enum:rt(le()),default:le().optional()}),oDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),oneOf:rt(ot({const:le(),title:le()})),default:le().optional()}),sDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),enum:rt(le()),enumNames:rt(le()).optional(),default:le().optional()}),iDt=tn([nDt,oDt]),aDt=ot({type:Tt("array"),title:le().optional(),description:le().optional(),minItems:Ir().optional(),maxItems:Ir().optional(),items:ot({type:Tt("string"),enum:rt(le())}),default:rt(le()).optional()}),lDt=ot({type:Tt("array"),title:le().optional(),description:le().optional(),minItems:Ir().optional(),maxItems:Ir().optional(),items:ot({anyOf:rt(ot({const:le(),title:le()}))}),default:rt(le()).optional()}),cDt=tn([aDt,lDt]),uDt=tn([sDt,iDt,cDt]),dDt=tn([uDt,eDt,tDt,rDt]),pDt=v_.extend({mode:Tt("form").optional(),message:le(),requestedSchema:ot({type:Tt("object"),properties:fn(le(),dDt),required:rt(le()).optional()})}),mDt=v_.extend({mode:Tt("url"),message:le(),elicitationId:le(),url:le().url()}),hDt=tn([pDt,mDt]),Lee=di.extend({method:Tt("elicitation/create"),params:hDt}),fDt=Ll.extend({elicitationId:le()}),gDt=$l.extend({method:Tt("notifications/elicitation/complete"),params:fDt}),$ee=pi.extend({action:Gi(["accept","decline","cancel"]),content:bR(e=>e===null?void 0:e,fn(le(),tn([le(),Ir(),en(),rt(le())])).optional())}),yDt=ot({type:Tt("ref/resource"),uri:le()}),vDt=ot({type:Tt("ref/prompt"),name:le()}),_Dt=tl.extend({ref:tn([vDt,yDt]),argument:ot({name:le(),value:le()}),context:ot({arguments:fn(le(),le()).optional()}).optional()}),wDt=di.extend({method:Tt("completion/complete"),params:_Dt}),Fee=pi.extend({completion:Ps({values:rt(le()).max(100),total:En(Ir().int()),hasMore:En(en())})}),bDt=ot({uri:le().startsWith("file://"),name:le().optional(),_meta:fn(le(),cn()).optional()}),TDt=di.extend({method:Tt("roots/list"),params:tl.optional()}),EDt=pi.extend({roots:rt(bDt)}),SDt=$l.extend({method:Tt("notifications/roots/list_changed"),params:Ll.optional()}),H3r=tn([vN,lPt,wDt,GPt,PPt,RPt,vPt,_Pt,bPt,EPt,CPt,zPt,UPt,wN,TN,EN,CN]),V3r=tn([yN,_N,yee,SDt,mk]),W3r=tn([Ig,Oee,Nee,$ee,EDt,bN,SN,S_]),K3r=tn([vN,Dee,Lee,TDt,wN,TN,EN,CN]),J3r=tn([yN,_N,VPt,xPt,Cee,Mee,Aee,mk,gDt]),Y3r=tn([Ig,gee,Fee,xee,kee,Tee,Eee,See,hk,Ree,bN,SN,S_]),Lt=class scr extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===Yt.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new CDt(o.elicitations,r)}return new scr(t,r,n)}},CDt=class extends Lt{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Yt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function Pg(e){return e==="completed"||e==="failed"||e==="cancelled"}var Z3r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"(){}});function kDt(e){const r=WMt(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=B3r(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function xDt(e,t){const r=ih(e,t);if(!r.success)throw r.error;return r.data}var X3r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"(){VMt(),uee(),XF()}});function ADt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Q3r(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const i=r[o];ADt(i)&&ADt(s)?r[o]={...i,...s}:r[o]=s}return r}var IDt,RDt,eUr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"(){uee(),lh(),Z3r(),X3r(),IDt=6e4,RDt=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(yN,t=>{this._oncancel(t)}),this.setNotificationHandler(_N,t=>{this._onprogress(t)}),this.setRequestHandler(vN,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wN,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Lt(Yt.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(TN,async(t,r)=>{const n=async()=>{const o=t.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(i.type==="response"||i.type==="error"){const a=i.message,l=a.id,c=this._requestResolvers.get(l);if(c)if(this._requestResolvers.delete(l),i.type==="response")c(a);else{const u=a,d=new Lt(u.error.code,u.error.message,u.error.data);c(d)}else{const u=i.type==="response"?"Response":"Error";this._onerror(new Error(`${u} handler missing for request ${l}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}const s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new Lt(Yt.InvalidParams,`Task not found: ${o}`);if(!Pg(s.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(Pg(s.status)){const i=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[ah]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(EN,async(t,r)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Lt(Yt.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(CN,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Lt(Yt.InvalidParams,`Task not found: ${t.params.taskId}`);if(Pg(n.status))throw new Lt(Yt.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);const o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Lt(Yt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Lt?n:new Lt(Yt.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Lt.fromError(Yt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{n?.(o,s),__(o)||QMt(o)?this._onresponse(o):hN(o)?this._onrequest(o,s):XMt(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Lt.fromError(Yt.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[ah]?.taskId;if(r===void 0){const c={jsonrpc:"2.0",id:e.id,error:{code:Yt.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:c,timestamp:Date.now()},n?.sessionId).catch(u=>this._onerror(new Error(`Failed to enqueue error response: ${u}`))):n?.send(c).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}const s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);const i=ZMt(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,l={signal:s.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async c=>{if(s.signal.aborted)return;const u={relatedRequestId:e.id};o&&(u.relatedTask={taskId:o}),await this.notification(c,u)},sendRequest:async(c,u,d)=>{if(s.signal.aborted)throw new Lt(Yt.ConnectionClosed,"Request was cancelled");const m={...d,relatedRequestId:e.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});const h=m.relatedTask?.taskId??o;return h&&a&&await a.updateTaskStatus(h,"input_required"),await this.request(c,u,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:i?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,l)).then(async c=>{if(s.signal.aborted)return;const u={result:c,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:u,timestamp:Date.now()},n?.sessionId):await n?.send(u)},async c=>{if(s.signal.aborted)return;const u={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:Yt.InternalError,message:c.message??"Internal error",...c.data!==void 0&&{data:c.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},n?.sessionId):await n?.send(u)}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const s=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(a);return}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),__(e))r(e);else{const s=new Lt(e.error.code,e.error.message,e.error.data);r(s)}return}const n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(__(e)&&e.result&&typeof e.result=="object"){const s=e.result;if(s.task&&typeof s.task=="object"){const i=s.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,t))}}if(o||this._progressHandlers.delete(t),__(e))n(e);else{const s=Lt.fromError(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(s){yield{type:"error",error:s instanceof Lt?s:new Lt(Yt.InternalError,String(s))}}return}let o;try{const s=await this.request(e,S_,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Lt(Yt.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:i},Pg(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:i.status==="failed"?yield{type:"error",error:new Lt(Yt.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new Lt(Yt.InternalError,`Task ${o} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}const a=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,a)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Lt?s:new Lt(Yt.InternalError,String(s))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:i,relatedTask:a}=r??{};return new Promise((l,c)=>{const u=_=>{c(_)};if(!this._transport){u(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(_){u(_);return}r?.signal?.throwIfAborted();const d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),i&&(m.params={...m.params,task:i}),a&&(m.params={...m.params,_meta:{...m.params?._meta||{},[ah]:a}});const h=_=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(_)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const b=_ instanceof Lt?_:new Lt(Yt.RequestTimeout,String(_));c(b)};this._responseHandlers.set(d,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return c(_);try{const b=ih(t,_.result);b.success?l(b.data):c(b.error)}catch(b){c(b)}}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});const g=r?.timeout??IDt,y=()=>h(Lt.fromError(Yt.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(d,g,r?.maxTotalTimeout,y,r?.resetTimeoutOnProgress??!1);const v=a?.taskId;if(v){const _=b=>{const T=this._responseHandlers.get(d);T?T(b):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,_),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(d),c(b)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(_=>{this._cleanupTimeout(d),c(_)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},bN,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},SN,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},gPt,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ah]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ah]:t.relatedTask}}}),this._transport?.send(i,t).catch(a=>this._onerror(a))});return}let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ah]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){const r=kDt(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const s=xDt(e,n);return Promise.resolve(t(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=kDt(e);this._notificationHandlers.set(r,n=>{const o=xDt(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const n of r)if(n.type==="request"&&hN(n.message)){const o=n.message.id,s=this._requestResolvers.get(o);s?(s(new Lt(Yt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(e);n?.pollInterval&&(r=n.pollInterval)}catch{}return new Promise((n,o)=>{if(t.aborted){o(new Lt(Yt.InvalidRequest,"Request cancelled"));return}const s=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(s),o(new Lt(Yt.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async n=>{const o=await r.getTask(n,t);if(!o)throw new Lt(Yt.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,s)=>{await r.storeTaskResult(n,o,s,t);const i=await r.getTask(n,t);if(i){const a=mk.parse({method:"notifications/tasks/status",params:i});await this.notification(a),Pg(i.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,s)=>{const i=await r.getTask(n,t);if(!i)throw new Lt(Yt.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Pg(i.status))throw new Lt(Yt.InvalidParams,`Cannot update task "${n}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,s,t);const a=await r.getTask(n,t);if(a){const l=mk.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Pg(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),Dg,Ws,MDt,tUr,rUr,nUr,oUr,sUr,iUr,aUr,lUr,cUr,uUr,dUr,pUr,mUr,hUr,fUr,gUr,yUr,vUr,_Ur,wUr,bUr,TUr,EUr,SUr,CUr,kUr,xUr,AUr,IUr,RUr,MUr,PUr,DUr,OUr,NUr,LUr,$Ur,FUr,UUr,BUr,zUr,jUr,qUr,GUr,HUr,VUr,WUr=S({"npm-stub:ajv"(){Dg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Dg.get}):new Proxy(function(...r){return new Proxy({},{get:Dg.get})},{get:Dg.get,apply(r,n,o){return new Proxy({},{get:Dg.get})},construct(r,n){return new Proxy({},{get:Dg.get})}})}},Ws=new Proxy({},Dg),MDt=Ws,{BedrockClient:tUr,ListFoundationModelsCommand:rUr,BedrockRuntimeClient:nUr,ConverseCommand:oUr,ConverseStreamCommand:sUr,ImageFormat:iUr,InvokeModelCommand:aUr}=Ws,{SageMakerRuntimeClient:lUr,InvokeEndpointCommand:cUr,InvokeEndpointWithResponseStreamCommand:uUr}=Ws,{GoogleAuth:dUr,VertexAI:pUr,TextToSpeechClient:mUr}=Ws,{Webhook:hUr}=Ws,{Hippocampus:fUr,HippocampusConfig:gUr}=Ws,{createClient:yUr}=Ws,{Queue:vUr,Worker:_Ur,Job:wUr,QueueScheduler:bUr,FlowProducer:TUr}=Ws,{Cron:EUr}=Ws,{parseBuffer:SUr,selectCover:CUr}=Ws,{extractRawText:kUr,convertToHtml:xUr}=Ws,{Hono:AUr}=Ws,{cors:IUr,HTTPException:RUr,logger:MUr,secureHeaders:PUr,streamSSE:DUr,timeout:OUr}=Ws,NUr=globalThis.fetch,LUr=globalThis.Request,$Ur=globalThis.Response,FUr=globalThis.Headers,UUr=globalThis.FormData,BUr=globalThis.File,zUr=globalThis.Blob,jUr=Ws.Agent,qUr=Ws.Pool,GUr=Ws.Client,HUr=Ws.Dispatcher,VUr=Ws.MockAgent}}),Og,Ks,PDt,KUr,JUr,YUr,ZUr,XUr,QUr,e6r,t6r,r6r,n6r,o6r,s6r,i6r,a6r,l6r,c6r,u6r,d6r,p6r,m6r,h6r,f6r,g6r,y6r,v6r,_6r,w6r,b6r,T6r,E6r,S6r,C6r,k6r,x6r,A6r,I6r,R6r,M6r,P6r,D6r,O6r,N6r,L6r,$6r,F6r,U6r,B6r=S({"npm-stub:ajv-formats"(){Og={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Og.get}):new Proxy(function(...r){return new Proxy({},{get:Og.get})},{get:Og.get,apply(r,n,o){return new Proxy({},{get:Og.get})},construct(r,n){return new Proxy({},{get:Og.get})}})}},Ks=new Proxy({},Og),PDt=Ks,{BedrockClient:KUr,ListFoundationModelsCommand:JUr,BedrockRuntimeClient:YUr,ConverseCommand:ZUr,ConverseStreamCommand:XUr,ImageFormat:QUr,InvokeModelCommand:e6r}=Ks,{SageMakerRuntimeClient:t6r,InvokeEndpointCommand:r6r,InvokeEndpointWithResponseStreamCommand:n6r}=Ks,{GoogleAuth:o6r,VertexAI:s6r,TextToSpeechClient:i6r}=Ks,{Webhook:a6r}=Ks,{Hippocampus:l6r,HippocampusConfig:c6r}=Ks,{createClient:u6r}=Ks,{Queue:d6r,Worker:p6r,Job:m6r,QueueScheduler:h6r,FlowProducer:f6r}=Ks,{Cron:g6r}=Ks,{parseBuffer:y6r,selectCover:v6r}=Ks,{extractRawText:_6r,convertToHtml:w6r}=Ks,{Hono:b6r}=Ks,{cors:T6r,HTTPException:E6r,logger:S6r,secureHeaders:C6r,streamSSE:k6r,timeout:x6r}=Ks,A6r=globalThis.fetch,I6r=globalThis.Request,R6r=globalThis.Response,M6r=globalThis.Headers,P6r=globalThis.FormData,D6r=globalThis.File,O6r=globalThis.Blob,N6r=Ks.Agent,L6r=Ks.Pool,$6r=Ks.Client,F6r=Ks.Dispatcher,U6r=Ks.MockAgent}});function z6r(){const e=new MDt({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return PDt(e),e}var DDt,j6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"(){WUr(),B6r(),DDt=class{constructor(e){this._ajv=e??z6r()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>t(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}}),ODt,q6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"(){lh(),ODt=class{constructor(e){this._client=e}async*callToolStream(e,t=hk,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},s=n.requestStream({method:"tools/call",params:e},t,o),i=n.getToolOutputValidator(e.name);for await(const a of s){if(a.type==="result"&&i){const l=a.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new Lt(Yt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const c=i(l.structuredContent);if(!c.valid){yield{type:"error",error:new Lt(Yt.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)};return}}catch(c){if(c instanceof Lt){yield{type:"error",error:c};return}yield{type:"error",error:new Lt(Yt.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)};return}}yield a}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}}});function G6r(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function H6r(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var V6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"(){}});function PN(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&PN(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&PN(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&PN(r,t)}}function W6r(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var NDt,K6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"(){eUr(),lh(),j6r(),uee(),q6r(),V6r(),NDt=class extends RDt{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new DDt,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Mee,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Aee,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Cee,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ODt(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Q3r(this._capabilities,e)}setRequestHandler(e,t){const n=WMt(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let o;if(pN(n)){const i=n;o=i._zod?.def?.value??i.value}else{const i=n;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");const s=o;if(s==="elicitation/create"){const i=async(a,l)=>{const c=ih(Lee,a);if(!c.success){const _=c.error instanceof Error?c.error.message:String(c.error);throw new Lt(Yt.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:u}=c.data;u.mode=u.mode??"form";const{supportsFormMode:d,supportsUrlMode:m}=W6r(this._capabilities.elicitation);if(u.mode==="form"&&!d)throw new Lt(Yt.InvalidParams,"Client does not support form-mode elicitation requests");if(u.mode==="url"&&!m)throw new Lt(Yt.InvalidParams,"Client does not support URL-mode elicitation requests");const h=await Promise.resolve(t(a,l));if(u.task){const _=ih(S_,h);if(!_.success){const b=_.error instanceof Error?_.error.message:String(_.error);throw new Lt(Yt.InvalidParams,`Invalid task creation result: ${b}`)}return _.data}const g=ih($ee,h);if(!g.success){const _=g.error instanceof Error?g.error.message:String(g.error);throw new Lt(Yt.InvalidParams,`Invalid elicitation result: ${_}`)}const y=g.data,v=u.mode==="form"?u.requestedSchema:void 0;if(u.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{PN(v,y.content)}catch{}return y};return super.setRequestHandler(e,i)}if(s==="sampling/createMessage"){const i=async(a,l)=>{const c=ih(Dee,a);if(!c.success){const y=c.error instanceof Error?c.error.message:String(c.error);throw new Lt(Yt.InvalidParams,`Invalid sampling request: ${y}`)}const{params:u}=c.data,d=await Promise.resolve(t(a,l));if(u.task){const y=ih(S_,d);if(!y.success){const v=y.error instanceof Error?y.error.message:String(y.error);throw new Lt(Yt.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}const h=u.tools||u.toolChoice?Nee:Oee,g=ih(h,d);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new Lt(Yt.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:uk,capabilities:this._capabilities,clientInfo:this._clientInfo}},gee,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!KMt.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){G6r(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&H6r(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ig,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Fee,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Ig,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},xee,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},kee,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Tee,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Eee,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},See,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Ig,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Ig,t)}async callTool(e,t=hk,r){if(this.isToolTaskRequired(e.name))throw new Lt(Yt.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Lt(Yt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const s=o(n.structuredContent);if(!s.valid)throw new Lt(Yt.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof Lt?s:new Lt(Yt.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}const r=t.execution?.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(t.name),r==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Ree,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=jPt.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:i}=o.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{const u=await n();a(null,u)}catch(u){const d=u instanceof Error?u:new Error(String(u));a(d,null)}},c=()=>{if(i){const u=this._listChangedDebounceTimers.get(e);u&&clearTimeout(u);const d=setTimeout(l,i);this._listChangedDebounceTimers.set(e,d)}else l()};this.setNotificationHandler(t,c)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}}),LDt={};he(LDt,{Agent:()=>C4t,BedrockClient:()=>FDt,BedrockRuntimeClient:()=>BDt,Blob:()=>S4t,Client:()=>x4t,ConverseCommand:()=>zDt,ConverseStreamCommand:()=>jDt,Cron:()=>i4t,Dispatcher:()=>A4t,File:()=>E4t,FlowProducer:()=>s4t,FormData:()=>T4t,GoogleAuth:()=>KDt,HTTPException:()=>m4t,Headers:()=>b4t,Hippocampus:()=>XDt,HippocampusConfig:()=>QDt,Hono:()=>d4t,ImageFormat:()=>qDt,InvokeEndpointCommand:()=>VDt,InvokeEndpointWithResponseStreamCommand:()=>WDt,InvokeModelCommand:()=>GDt,Job:()=>n4t,ListFoundationModelsCommand:()=>UDt,MockAgent:()=>M4t,Pool:()=>k4t,Queue:()=>t4t,QueueScheduler:()=>o4t,Request:()=>_4t,Response:()=>w4t,SageMakerRuntimeClient:()=>HDt,TextToSpeechClient:()=>YDt,VertexAI:()=>JDt,Webhook:()=>ZDt,Worker:()=>r4t,convertToHtml:()=>u4t,cors:()=>p4t,createClient:()=>e4t,default:()=>$Dt,extractRawText:()=>c4t,fetch:()=>v4t,getGlobalDispatcher:()=>R4t,interceptors:()=>P4t,logger:()=>h4t,parseBuffer:()=>a4t,request:()=>D4t,secureHeaders:()=>f4t,selectCover:()=>l4t,setGlobalDispatcher:()=>I4t,streamSSE:()=>g4t,timeout:()=>y4t});var Ng,Ss,$Dt,FDt,UDt,BDt,zDt,jDt,qDt,GDt,HDt,VDt,WDt,KDt,JDt,YDt,ZDt,XDt,QDt,e4t,t4t,r4t,n4t,o4t,s4t,i4t,a4t,l4t,c4t,u4t,d4t,p4t,m4t,h4t,f4t,g4t,y4t,v4t,_4t,w4t,b4t,T4t,E4t,S4t,C4t,k4t,x4t,A4t,I4t,R4t,M4t,P4t,D4t,J6r=S({"npm-stub:which"(){Ng={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Ng.get}):new Proxy(function(...r){return new Proxy({},{get:Ng.get})},{get:Ng.get,apply(r,n,o){return new Proxy({},{get:Ng.get})},construct(r,n){return new Proxy({},{get:Ng.get})}})}},Ss=new Proxy({},Ng),$Dt=Ss,{BedrockClient:FDt,ListFoundationModelsCommand:UDt,BedrockRuntimeClient:BDt,ConverseCommand:zDt,ConverseStreamCommand:jDt,ImageFormat:qDt,InvokeModelCommand:GDt}=Ss,{SageMakerRuntimeClient:HDt,InvokeEndpointCommand:VDt,InvokeEndpointWithResponseStreamCommand:WDt}=Ss,{GoogleAuth:KDt,VertexAI:JDt,TextToSpeechClient:YDt}=Ss,{Webhook:ZDt}=Ss,{Hippocampus:XDt,HippocampusConfig:QDt}=Ss,{createClient:e4t}=Ss,{Queue:t4t,Worker:r4t,Job:n4t,QueueScheduler:o4t,FlowProducer:s4t}=Ss,{Cron:i4t}=Ss,{parseBuffer:a4t,selectCover:l4t}=Ss,{extractRawText:c4t,convertToHtml:u4t}=Ss,{Hono:d4t}=Ss,{cors:p4t,HTTPException:m4t,logger:h4t,secureHeaders:f4t,streamSSE:g4t,timeout:y4t}=Ss,v4t=globalThis.fetch,_4t=globalThis.Request,w4t=globalThis.Response,b4t=globalThis.Headers,T4t=globalThis.FormData,E4t=globalThis.File,S4t=globalThis.Blob,C4t=Ss.Agent,k4t=Ss.Pool,x4t=Ss.Client,A4t=Ss.Dispatcher,I4t=()=>{},R4t=()=>Ss,M4t=Ss.MockAgent,P4t={redirect:()=>e=>e,retry:()=>e=>e},D4t=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),Y6r=gr({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){"use strict";var r=(n={})=>{const o=n.env||process.env;return(n.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(i=>i.toUpperCase()==="PATH")||"Path"};t.exports=r,t.exports.default=r}}),Z6r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(Lr(),wr(Hc)),n=(J6r(),wr(LDt)),o=Y6r();function s(a,l){const c=a.options.env||process.env,u=process.cwd(),d=a.options.cwd!=null,m=d&&process.chdir!==void 0&&!process.chdir.disabled;if(m)try{process.chdir(a.options.cwd)}catch{}let h;try{h=n.sync(a.command,{path:c[o({env:c})],pathExt:l?r.delimiter:void 0})}catch{}finally{m&&process.chdir(u)}return h&&(h=r.resolve(d?a.options.cwd:"",h)),h}function i(a){return s(a)||s(a,!0)}t.exports=i}}),X6r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function n(s){return s=s.replace(r,"^$1"),s}function o(s,i){return s=`${s}`,s=s.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),s=s.replace(/(?=(\\+?)?)\1$/,"$1$1"),s=`"${s}"`,s=s.replace(r,"^$1"),i&&(s=s.replace(r,"^$1")),s}t.exports.command=n,t.exports.argument=o}}),Q6r=gr({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),e5r=gr({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=Q6r();t.exports=(n="")=>{const o=n.match(r);if(!o)return null;const[s,i]=o[0].replace(/#! ?/,"").split(" "),a=s.split("/").pop();return a==="env"?i:i?`${a} ${i}`:a}}}),t5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(gn(),wr(_l)),n=e5r();function o(s){const a=Buffer.alloc(150);let l;try{l=r.openSync(s,"r"),r.readSync(l,a,0,150,0),r.closeSync(l)}catch{}return n(a.toString())}t.exports=o}}),r5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(Lr(),wr(Hc)),n=Z6r(),o=X6r(),s=t5r(),i=process.platform==="win32",a=/\.(?:com|exe)$/i,l=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function c(m){m.file=n(m);const h=m.file&&s(m.file);return h?(m.args.unshift(m.file),m.command=h,n(m)):m.file}function u(m){if(!i)return m;const h=c(m),g=!a.test(h);if(m.options.forceShell||g){const y=l.test(h);m.command=r.normalize(m.command),m.command=o.command(m.command),m.args=m.args.map(_=>o.argument(_,y));const v=[m.command].concat(m.args).join(" ");m.args=["/d","/s","/c",`"${v}"`],m.command=process.env.comspec||"cmd.exe",m.options.windowsVerbatimArguments=!0}return m}function d(m,h,g){h&&!Array.isArray(h)&&(g=h,h=null),h=h?h.slice(0):[],g=Object.assign({},g);const y={command:m,args:h,options:g,file:void 0,original:{command:m,args:h}};return g.shell?y:u(y)}t.exports=d}}),n5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function n(a,l){return Object.assign(new Error(`${l} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${l} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,l){if(!r)return;const c=a.emit;a.emit=function(u,d){if(u==="exit"){const m=s(d,l);if(m)return c.call(a,"error",m)}return c.apply(a,arguments)}}function s(a,l){return r&&a===1&&!l.file?n(l.original,"spawn"):null}function i(a,l){return r&&a===1&&!l.file?n(l.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:s,verifyENOENTSync:i,notFoundError:n}}}),o5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(Lq(),wr(r1e)),n=r5r(),o=n5r();function s(a,l,c){const u=n(a,l,c),d=r.spawn(u.command,u.args,u.options);return o.hookChildProcess(d,u),d}function i(a,l,c){const u=n(a,l,c),d=r.spawnSync(u.command,u.args,u.options);return d.error=d.error||o.verifyENOENTSync(d.status,u),d}t.exports=s,t.exports.spawn=s,t.exports.sync=i,t.exports._parse=n,t.exports._enoent=o}}),gk,s5r,i5r,a5r,l5r,DN,O4t,Uee,c5r,u5r,d5r,p5r,m5r=S({"node-stub:node:process"(){gk={},s5r=globalThis.crypto,i5r=globalThis.ReadableStream||class{},a5r=globalThis.URL,l5r=globalThis.URLSearchParams,DN=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},DN.custom=Symbol.for("nodejs.util.inspect.custom"),DN.colors={},DN.styles={},O4t=globalThis.TextDecoder,Uee=globalThis.TextEncoder,c5r=globalThis.performance||{now:()=>Date.now()},u5r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new Uee().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new Uee().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new O4t().decode(this)}},d5r=globalThis.clearTimeout,p5r=globalThis.clearInterval}});function h5r(e){return Ag.parse(JSON.parse(e))}function f5r(e){return JSON.stringify(e)+`
|
|
1479
|
+
For video extraction, the result includes images (frames) that will be visible to you. Always call list_attached_files first to discover file IDs.`,inputSchema:p.object({file_id:p.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:p.number().optional().describe("Start timestamp in seconds (video only)"),end_time:p.number().optional().describe("End timestamp in seconds (video only)"),frame_count:p.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:p.array(p.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:p.object({start:p.number().int().min(1),end:p.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:p.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:p.object({start:p.number().int().min(1),end:p.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:p.array(p.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:p.string().optional().describe("File path within archive to extract (archive only)"),format:p.enum(["text","detailed","summary"]).optional().describe("Output format hint (default: text)")}),execute:async t=>{try{const r={...t,sheet:t.sheet!==void 0?/^\d+$/.test(t.sheet)?parseInt(t.sheet,10):t.sheet:void 0},n=await e.extractContent(r);return n.success?{success:!0,text:n.text,metadata:n.metadata,imageCount:n.images?.length??0,_images:n.images,error:void 0}:{success:!1,error:n.error,text:void 0,metadata:void 0,imageCount:0,_images:void 0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r),text:void 0,metadata:void 0,imageCount:0,_images:void 0}}},toModelOutput:({output:t})=>{const r=[];if(t.text?r.push({type:"text",text:t.text}):t.error&&r.push({type:"text",text:`Error: ${t.error}`}),t._images&&t._images.length>0)for(const n of t._images)r.push({type:"image-data",data:n.toString("base64"),mediaType:"image/jpeg"});return r.length===0&&r.push({type:"text",text:"(No content extracted)"}),{type:"content",value:r}}}}function DMt(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(2)} GB`}var N3r=S({"src/lib/files/fileTools.ts"(){"use strict";jr(),lc()}}),y_,ree,nee,OMt=S({"src/lib/hitl/hitlManager.ts"(){"use strict";vn(),Ft(),a1(),q(),y_=3e4,ree=!1,nee=class extends nn{config;pendingConfirmations=new Map;statistics={totalRequests:0,pendingRequests:0,averageResponseTime:0,approvedRequests:0,rejectedRequests:0,timedOutRequests:0};constructor(e){super(),this.config=this.validateConfig(e),this.setupEventHandlers()}validateConfig(e){const t={enabled:e.enabled,dangerousActions:e.dangerousActions,timeout:e.timeout??y_,confirmationMethod:e.confirmationMethod??"event",allowArgumentModification:e.allowArgumentModification??ree,autoApproveOnTimeout:e.autoApproveOnTimeout??!1,auditLogging:e.auditLogging??!1,customRules:e.customRules??[]};if(!t.enabled)return t;if(!Array.isArray(t.dangerousActions))throw new ET("dangerousActions must be an array of strings");if(typeof t.timeout!="number"||t.timeout<=0)throw new ET("timeout must be a positive number (milliseconds)");if(t.confirmationMethod!=="event")throw new ET("confirmationMethod must be 'event' (only supported method)");if(typeof t.allowArgumentModification!="boolean")throw new ET("allowArgumentModification must be a boolean");return t}requiresConfirmation(e,t){if(!this.config.enabled)return!1;const r=e.toLowerCase();for(const n of this.config.dangerousActions)if(r.includes(n.toLowerCase()))return!0;if(this.config.customRules){for(const n of this.config.customRules)if(n.requiresConfirmation)try{if(n.condition(e,t))return!0}catch(o){this.logAuditEvent("rule-evaluation-error",{ruleName:n.name,toolName:e,error:o instanceof Error?o.message:String(o)})}}return!1}async requestConfirmation(e,t,r){const n=this.generateConfirmationId(),o=Date.now();return this.statistics.totalRequests++,this.statistics.pendingRequests++,new Promise((s,i)=>{const a=setTimeout(()=>{this.handleTimeout(n)},this.config.timeout),l={confirmationId:n,toolName:e,arguments:t,timestamp:o,timeoutHandle:a,resolve:s,reject:i};this.pendingConfirmations.set(n,l);const c={type:"hitl:confirmation-request",payload:{confirmationId:n,toolName:e,serverId:r?.serverId,actionType:this.generateActionDescription(e,t),arguments:t,metadata:{timestamp:new Date(o).toISOString(),sessionId:r?.sessionId,userId:r?.userId,dangerousKeywords:this.getTriggeredKeywords(e,t)},timeoutMs:this.config.timeout??y_,allowModification:this.config.allowArgumentModification??ree}};this.emit("hitl:confirmation-request",c),this.config.auditLogging&&this.logAuditEvent("confirmation-requested",{confirmationId:n,toolName:e,userId:r?.userId,sessionId:r?.sessionId,timestamp:o,arguments:t})})}processUserResponse(e,t){const r=this.pendingConfirmations.get(e);if(!r){f.warn(`No pending confirmation found for ID: ${e}`);return}clearTimeout(r.timeoutHandle),this.pendingConfirmations.delete(e),this.statistics.pendingRequests--;const n=t.responseTime||Date.now()-r.timestamp;t.approved?this.statistics.approvedRequests++:this.statistics.rejectedRequests++;const o=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(o-1)+n)/o;const s={approved:t.approved,reason:t.reason,modifiedArguments:t.modifiedArguments,responseTime:n};this.config.auditLogging&&this.logAuditEvent(t.approved?"confirmation-approved":"confirmation-rejected",{confirmationId:e,toolName:r.toolName,approved:t.approved,reason:t.reason,userId:t.userId,responseTime:n,arguments:r.arguments}),r.resolve(s)}handleTimeout(e){const t=this.pendingConfirmations.get(e);if(!t)return;this.pendingConfirmations.delete(e),this.statistics.pendingRequests--,this.statistics.timedOutRequests++;const r=Date.now()-t.timestamp,n=this.config.autoApproveOnTimeout===!0;this.config.auditLogging&&this.logAuditEvent("confirmation-timeout",{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??y_,arguments:t.arguments,autoApproved:n});const o={type:"hitl:timeout",payload:{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??y_}};if(this.emit("hitl:timeout",o),n){this.statistics.approvedRequests++;const s=this.statistics.approvedRequests+this.statistics.rejectedRequests;this.statistics.averageResponseTime=(this.statistics.averageResponseTime*(s-1)+r)/s,this.config.auditLogging&&this.logAuditEvent("confirmation-auto-approved",{confirmationId:e,toolName:t.toolName,reason:"Auto-approved due to timeout",responseTime:r,arguments:t.arguments});const i={approved:!0,reason:"Auto-approved due to timeout",responseTime:r};t.resolve(i)}else t.reject(new TT(`Confirmation timeout for tool: ${t.toolName}`,e,this.config.timeout??y_))}setupEventHandlers(){this.on("hitl:confirmation-response",e=>{e.payload?.confirmationId&&this.processUserResponse(e.payload.confirmationId,{approved:e.payload.approved,reason:e.payload.reason,modifiedArguments:e.payload.modifiedArguments,responseTime:e.payload.metadata?.responseTime,userId:e.payload.metadata?.userId})})}generateConfirmationId(){return`hitl-${Date.now()}-${st()}`}generateActionDescription(e,t){const r=e.toLowerCase();if(r.includes("delete"))return"Delete Operation";if(r.includes("remove"))return"Remove Operation";if(r.includes("update"))return"Update Operation";if(r.includes("create"))return"Create Operation";if(r.includes("drop"))return"Drop Operation";if(r.includes("truncate"))return"Truncate Operation";if(r.includes("restart"))return"Restart Operation";if(r.includes("stop"))return"Stop Operation";if(r.includes("kill"))return"Kill Operation";if(this.config.customRules)for(const n of this.config.customRules)try{if(n.condition(e,t)&&n.customMessage)return n.customMessage}catch{}return`Execute ${e}`}getTriggeredKeywords(e,t){const r=[],n=e.toLowerCase();for(const o of this.config.dangerousActions)n.includes(o.toLowerCase())&&r.push(o);if(this.config.customRules)for(const o of this.config.customRules)try{o.requiresConfirmation&&o.condition(e,t)&&r.push(o.name)}catch{}return r}logAuditEvent(e,t){const r={timestamp:new Date().toISOString(),eventType:e,toolName:t.toolName,userId:t.userId,sessionId:t.sessionId,arguments:t.arguments,reason:t.reason,responseTime:t.responseTime,...t};f.info(`[HITL Audit] ${e}:`,r),this.emit("hitl:audit",r)}getStatistics(){return{...this.statistics}}getConfig(){return{...this.config}}updateConfig(e){const t={...this.config,...e};this.config=this.validateConfig(t),this.config.auditLogging&&this.logAuditEvent("configuration-updated",{oldConfig:this.config,newConfig:t})}cleanup(){for(const[e,t]of this.pendingConfirmations)clearTimeout(t.timeoutHandle),t.reject(new Error(`HITL cleanup: confirmation ${e} cancelled`));this.pendingConfirmations.clear(),this.statistics.pendingRequests=0,this.config.auditLogging&&this.logAuditEvent("manager-cleanup",{clearedConfirmations:this.pendingConfirmations.size})}isEnabled(){return this.config.enabled}getPendingCount(){return this.pendingConfirmations.size}hasPendingConfirmation(e){return this.pendingConfirmations.has(e)}}}}),lN,NMt,oee,cN,LMt,L3r=S({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";vn(),q(),ct(),Vr(),yr(),lN=class extends nn{config;pending=new Map;serverQueues=new Map;flushTimer;executor;activeBatches=0;batchCounter=0;requestCounter=0;isDestroyed=!1;constructor(e){super(),this.config={maxBatchSize:e.maxBatchSize,maxWaitMs:e.maxWaitMs,enableParallel:e.enableParallel??!0,maxConcurrentBatches:e.maxConcurrentBatches??5,groupByServer:e.groupByServer??!0}}setExecutor(e){this.executor=e}async add(e,t,r){if(this.isDestroyed)throw xe.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw xe.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before adding requests"});const n=this.generateRequestId();return new Promise((o,s)=>{const i={id:n,tool:e,args:t,serverId:r,resolve:o,reject:s,addedAt:Date.now()};if(this.pending.set(n,i),this.config.groupByServer&&r){this.serverQueues.has(r)||this.serverQueues.set(r,new Set);const a=this.serverQueues.get(r);a&&a.add(n)}this.emit("requestQueued",{requestId:n,queueSize:this.pending.size}),this.pending.size>=this.config.maxBatchSize?this.scheduleFlush("size"):this.flushTimer||(this.flushTimer=setTimeout(()=>{this.scheduleFlush("timeout")},this.config.maxWaitMs))})}async flush(){this.clearFlushTimer(),this.pending.size!==0&&(this.emit("flushTriggered",{reason:"manual",queueSize:this.pending.size}),await this.executeBatch())}get queueSize(){return this.pending.size}get activeBatchCount(){return this.activeBatches}get isIdle(){return this.pending.size===0&&this.activeBatches===0}async drain(){await this.flush();const e=3e4,t=Date.now()+e;for(;!this.isIdle;){if(Date.now()>=t)throw xe.toolTimeout("batchDrain",e);await new Promise(r=>setTimeout(r,10))}}destroy(){this.isDestroyed=!0,this.clearFlushTimer();for(const e of this.pending.values())e.reject(xe.invalidConfiguration("batcher","Batcher was destroyed before request could complete"));this.pending.clear(),this.serverQueues.clear()}generateRequestId(){return`req-${Date.now()}-${++this.requestCounter}`}generateBatchId(){return`batch-${Date.now()}-${++this.batchCounter}`}scheduleFlush(e){this.clearFlushTimer(),this.emit("flushTriggered",{reason:e,queueSize:this.pending.size}),setImmediate(()=>{this.executeBatch().catch(t=>{f.error("Batch execution failed:",t)})})}clearFlushTimer(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0)}async executeBatch(){if(this.pending.size===0)return;if(this.activeBatches>=this.config.maxConcurrentBatches){this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Rescheduled batch execution failed:",n)})},10);return}const e=this.selectBatchRequests();if(e.length===0)return;const t=this.generateBatchId(),r=Date.now();this.activeBatches++,this.emit("batchStarted",{batchId:t,size:e.length}),await gt({name:"neurolink.mcp.batch.execute",tracer:He.mcp,attributes:{"mcp.batch.id":t,"mcp.batch.size":e.length,"mcp.batch.active_batches":this.activeBatches}},async n=>{let o=0,s=0;try{if(!this.executor)throw xe.missingConfiguration("batchExecutor",{hint:"Call setExecutor() before executing batches"});const i=this.executor(e.map(m=>({tool:m.tool,args:m.args,serverId:m.serverId}))),a=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4);let l;const c=new Promise((m,h)=>{l=setTimeout(()=>h(xe.toolTimeout("batchExecution",a)),a)});i.catch(m=>{});const u=await Promise.race([i,c]).finally(()=>{l&&clearTimeout(l)}),d=[];for(let m=0;m<e.length;m++){const h=e[m],g=u[m],y=Date.now()-r;if(!g){const v=xe.toolExecutionFailed(h.tool,new Error(`Batch executor returned no result for request ${m}`));h.reject(v),d.push({id:h.id,success:!1,error:v,executionTime:y}),s++;continue}if(g.success)h.resolve(g.result),d.push({id:h.id,success:!0,result:g.result,executionTime:y}),o++;else{const v=g.error??xe.toolExecutionFailed(h.tool,new Error("Unknown batch execution error"));h.reject(v),d.push({id:h.id,success:!1,error:v,executionTime:y}),s++}}n.setAttribute("mcp.batch.success_count",o),n.setAttribute("mcp.batch.error_count",s),this.emit("batchCompleted",{batchId:t,results:d})}catch(i){const a=i instanceof Error?i:xe.toolExecutionFailed("batch",new Error(String(i)));for(const l of e)l.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{f.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{f.error("Follow-up batch execution failed:",n)})},0))}selectBatchRequests(){const e=[];if(this.config.groupByServer&&this.serverQueues.size>0){const[t,r]=this.serverQueues.entries().next().value;for(const n of r){if(e.length>=this.config.maxBatchSize)break;const o=this.pending.get(n);o&&(e.push(o),this.pending.delete(n),r.delete(n))}r.size===0&&this.serverQueues.delete(t)}else{const t=Array.from(this.pending.values()).sort((r,n)=>r.addedAt-n.addedAt);for(const r of t){if(e.length>=this.config.maxBatchSize)break;e.push(r),this.pending.delete(r.id)}}return e}},NMt=e=>new lN(e),oee={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},cN=class{batcher;toolExecutor;constructor(e){this.batcher=new lN({...oee,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw xe.missingConfiguration("toolExecutor",{hint:"Call setToolExecutor() before executing tool calls"});const r=this.toolExecutor;return await Promise.all(t.map(async o=>{try{return{success:!0,result:await r(o.tool,o.args,o.serverId)}}catch(s){return{success:!1,error:s instanceof Error?s:xe.toolExecutionFailed(o.tool,new Error(String(s)))}}}))})}setToolExecutor(e){this.toolExecutor=e}async execute(e,t,r){return this.batcher.add(e,t,r)}async flush(){return this.batcher.flush()}async drain(){return this.batcher.drain()}get queueSize(){return this.batcher.queueSize}get isIdle(){return this.batcher.isIdle}destroy(){this.batcher.destroy()}},LMt=e=>new cN(e)}}),$Mt=S({"src/lib/mcp/batching/index.ts"(){"use strict";L3r()}}),xg,FMt,see,uN,UMt,$3r=S({"src/lib/mcp/caching/toolCache.ts"(){"use strict";Ft(),vn(),yn(),xg=class extends nn{cache=new Map;config;stats;cleanupTimer;constructor(e){super(),this.config={ttl:e.ttl,maxSize:e.maxSize,strategy:e.strategy,enableAutoCleanup:e.enableAutoCleanup??!0,cleanupInterval:e.cleanupInterval??6e4,namespace:e.namespace??""},this.stats={hits:0,misses:0,evictions:0,size:0,maxSize:this.config.maxSize,hitRate:0},this.config.enableAutoCleanup&&this.startAutoCleanup()}get(e){const t=this.getFullKey(e),r=this.cache.get(t);if(!r){this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}if(this.isExpired(r)){this.deleteWithReason(t,"expired"),this.stats.misses++,this.updateHitRate(),this.emit("miss",{key:t});return}return r.accessedAt=Date.now(),r.accessCount++,this.stats.hits++,this.updateHitRate(),this.emit("hit",{key:t,value:r.value}),r.value}set(e,t,r){const n=this.getFullKey(e),o=r??this.config.ttl,s=Date.now();this.cache.size>=this.config.maxSize&&!this.cache.has(n)&&this.evictOne();const i={value:t,expires:s+o,createdAt:s,accessedAt:s,accessCount:1,key:n};this.cache.set(n,i),this.stats.size=this.cache.size,this.emit("set",{key:n,value:t,ttl:o})}has(e){const t=this.getFullKey(e),r=this.cache.get(t);return r?this.isExpired(r)?(this.deleteWithReason(t,"expired"),!1):!0:!1}delete(e){const t=this.getFullKey(e),r=this.cache.delete(t);return r&&(this.stats.size=this.cache.size,this.emit("evict",{key:t,reason:"manual"})),r}invalidate(e){const t=this.getFullKey(e),r=this.patternToRegex(t);let n=0;for(const o of this.cache.keys())r.test(o)&&(this.cache.delete(o),n++,this.emit("evict",{key:o,reason:"manual"}));return this.stats.size=this.cache.size,n}clear(){const e=this.cache.size;this.cache.clear(),this.stats.size=0,this.emit("clear",{entriesRemoved:e})}async getOrSet(e,t,r){const n=this.get(e);if(n!==void 0)return n;const o=3e4,s=await zt(Promise.resolve(t()),o,`ToolCache getOrSet factory timed out after ${o}ms for key "${e}"`);return s===void 0||this.set(e,s,r),s}getStats(){return{...this.stats}}resetStats(){this.stats.hits=0,this.stats.misses=0,this.stats.evictions=0,this.updateHitRate()}keys(){return Array.from(this.cache.keys())}get size(){return this.cache.size}static generateKey(e,t){const r=(o,s=new WeakSet)=>{if(o===null||typeof o!="object")return JSON.stringify(o);if(o instanceof Date)return`{"$date":${JSON.stringify(o.toISOString())}}`;if(s.has(o))throw new TypeError("Circular structures are not supported in cache keys");if(s.add(o),Array.isArray(o)){const l="["+o.map(c=>r(c,s)).join(",")+"]";return s.delete(o),l}const a=Object.keys(o).sort().map(l=>JSON.stringify(l)+":"+r(o[l],s));return s.delete(o),"{"+a.join(",")+"}"},n=Kc("sha256").update(r(t)).digest("hex").substring(0,16);return`${e}:${n}`}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear()}getFullKey(e){return this.config.namespace?`${this.config.namespace}:${e}`:e}isExpired(e){return Date.now()>e.expires}deleteWithReason(e,t){const r=this.cache.delete(e);return r&&(this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e,reason:t})),r}evictOne(){const e=this.selectEvictionCandidate();e&&(this.cache.delete(e.key),this.stats.evictions++,this.stats.size=this.cache.size,this.emit("evict",{key:e.key,reason:"capacity"}))}selectEvictionCandidate(){if(this.cache.size!==0)switch(this.config.strategy){case"lru":return this.findLRU();case"fifo":return this.findFIFO();case"lfu":return this.findLFU();default:return this.findLRU()}}findLRU(){let e,t=1/0;for(const r of this.cache.values())r.accessedAt<t&&(t=r.accessedAt,e=r);return e}findFIFO(){let e,t=1/0;for(const r of this.cache.values())r.createdAt<t&&(t=r.createdAt,e=r);return e}findLFU(){let e,t=1/0;for(const r of this.cache.values())r.accessCount<t&&(t=r.accessCount,e=r);return e}patternToRegex(e){const r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^:]*");return new RegExp(`^${r}$`)}updateHitRate(){const e=this.stats.hits+this.stats.misses;this.stats.hitRate=e>0?this.stats.hits/e:0}startAutoCleanup(){this.cleanupTimer=setInterval(()=>{this.cleanupExpired()},this.config.cleanupInterval),this.cleanupTimer.unref&&this.cleanupTimer.unref()}cleanupExpired(){const e=Date.now();for(const[t,r]of this.cache.entries())e>r.expires&&(this.cache.delete(t),this.stats.evictions++,this.emit("evict",{key:t,reason:"expired"}));this.stats.size=this.cache.size}},FMt=e=>new xg(e),see={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},uN=class{cache;constructor(e){this.cache=new xg({...see,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=xg.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=xg.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=xg.generateKey(e,t);return this.cache.has(r)}invalidateTool(e){return this.cache.invalidate(`${e}:*`)}getStats(){return this.cache.getStats()}clear(){this.cache.clear()}destroy(){this.cache.destroy()}},UMt=e=>new uN(e)}}),BMt=S({"src/lib/mcp/caching/index.ts"(){"use strict";$3r()}}),zMt={};he(zMt,{MultiServerManager:()=>ck,globalMultiServerManager:()=>iee});var ck,iee,aee=S({"src/lib/mcp/multiServerManager.ts"(){"use strict";vn(),q(),ct(),ck=class extends nn{config;servers=new Map;groups=new Map;metrics=new Map;roundRobinCounters=new Map;toolPreferences=new Map;constructor(e={}){super(),this.config={defaultStrategy:e.defaultStrategy??"round-robin",healthAwareRouting:e.healthAwareRouting??!0,healthCheckInterval:e.healthCheckInterval??3e4,maxFailoverRetries:e.maxFailoverRetries??3,namespaceSeparator:e.namespaceSeparator??".",autoNamespace:e.autoNamespace??!1,conflictResolution:e.conflictResolution??"first-wins"}}addServer(e){this.servers.set(e.id,e),this.metrics.set(e.id,{activeRequests:0,totalRequests:0,completedRequests:0,averageResponseTime:0,errorRate:0,isHealthy:e.status==="connected"}),this.emit("serverAdded",{serverId:e.id,server:e}),f.debug(`[MultiServerManager] Added server: ${e.id} (${e.name})`)}removeServer(e){if(!this.servers.get(e))return!1;for(const[r,n]of this.groups){const o=n.servers.indexOf(e);o!==-1&&(n.servers.splice(o,1),n.servers.length===0&&(this.groups.delete(r),this.roundRobinCounters.delete(r)))}this.servers.delete(e),this.metrics.delete(e);for(const[r,n]of this.toolPreferences)n===e&&this.toolPreferences.delete(r);return this.emit("serverRemoved",{serverId:e}),f.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw xe.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e});const n={...r,...t,id:e};this.servers.set(e,n);const o=this.metrics.get(e);o&&t.status!==void 0&&(o.isHealthy=t.status==="connected"),this.emit("serverUpdated",{serverId:e,server:n})}createGroup(e){for(const t of e.servers)if(!this.servers.has(t))throw xe.invalidConfiguration("serverGroup.servers",`Server '${t}' not found when creating group '${e.id}'`,{serverId:t,groupId:e.id});this.groups.set(e.id,e),this.roundRobinCounters.set(e.id,0),this.emit("groupCreated",{group:e}),f.debug(`[MultiServerManager] Created group: ${e.id} with ${e.servers.length} servers`)}removeGroup(e){const t=this.groups.delete(e);return t&&(this.roundRobinCounters.delete(e),this.emit("groupRemoved",{groupId:e})),t}addServerToGroup(e,t){const r=this.groups.get(t);if(!r)throw xe.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw xe.invalidConfiguration("serverId",`Server '${e}' not found`,{serverId:e,groupId:t});r.servers.includes(e)||(r.servers.push(e),this.emit("serverAddedToGroup",{serverId:e,groupId:t}))}removeServerFromGroup(e,t){const r=this.groups.get(t);if(!r)return!1;const n=r.servers.indexOf(e);return n!==-1?(r.servers.splice(n,1),this.emit("serverRemovedFromGroup",{serverId:e,groupId:t}),!0):!1}getUnifiedTools(){const e=new Map;for(const[t,r]of this.servers){const o=this.metrics.get(t)?.isHealthy??!0;if(!(this.config.healthAwareRouting&&!o))for(const s of r.tools||[]){const i=e.get(s.name);i?(i.hasConflict=!0,i.servers.push({serverId:t,serverName:r.name,inputSchema:s.inputSchema,priority:this.getServerPriority(t)})):e.set(s.name,{name:s.name,description:s.description,servers:[{serverId:t,serverName:r.name,inputSchema:s.inputSchema,priority:this.getServerPriority(t)}],hasConflict:!1,preferredServerId:this.toolPreferences.get(s.name)})}}for(const t of e.values())t.servers.sort((r,n)=>r.priority-n.priority),!t.preferredServerId&&t.servers.length>0&&(t.preferredServerId=t.servers[0].serverId);return Array.from(e.values())}getNamespacedTools(){const e=[];for(const[t,r]of this.servers)if(!(this.config.healthAwareRouting&&!(this.metrics.get(t)?.isHealthy??!0)))for(const n of r.tools||[])e.push({fullName:`${t}${this.config.namespaceSeparator}${n.name}`,toolName:n.name,serverId:t,serverName:r.name,description:n.description,inputSchema:n.inputSchema});return e}setToolPreference(e,t){if(!this.servers.has(t))throw xe.invalidConfiguration("serverId",`Server '${t}' not found`,{serverId:t,toolName:e});this.toolPreferences.set(e,t),this.emit("toolPreferenceSet",{toolName:e,serverId:t})}clearToolPreference(e){this.toolPreferences.delete(e)}selectServer(e,t){const r=this.toolPreferences.get(e);if(r){const l=this.servers.get(r),c=this.metrics.get(r);if(l&&(!this.config.healthAwareRouting||c?.isHealthy)&&l.tools?.some(u=>u.name===e))return{serverId:r,server:l}}let n;if(t){const l=this.groups.get(t);if(!l)return f.warn(`[MultiServerManager] Group '${t}' not found`),null;n=l.servers.filter(c=>this.servers.get(c)?.tools?.some(d=>d.name===e))}else{n=[];for(const[l,c]of this.servers)c.tools?.some(u=>u.name===e)&&n.push(l)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(l=>this.metrics.get(l)?.isHealthy??!0),n.length===0))return f.warn(`[MultiServerManager] No healthy servers available for tool '${e}'`),null;const s=t?this.groups.get(t)?.strategy??this.config.defaultStrategy:this.config.defaultStrategy,i=this.applyStrategy(s,n,t);if(!i)return null;const a=this.servers.get(i);return a?{serverId:i,server:a}:null}applyStrategy(e,t,r){if(t.length===0)return null;if(t.length===1)return t[0];switch(e){case"round-robin":{const n=r??"default",o=this.roundRobinCounters.get(n)??0,s=t[o%t.length];return this.roundRobinCounters.set(n,o+1),s}case"least-loaded":{let n=1/0,o=t[0];for(const s of t){const a=this.metrics.get(s)?.activeRequests??0;a<n&&(n=a,o=s)}return o}case"random":{const n=Math.floor(Math.random()*t.length);return t[n]}case"weighted":{if(!r){const l=Math.floor(Math.random()*t.length);return t[l]}const n=this.groups.get(r);if(!n?.weights){const l=Math.floor(Math.random()*t.length);return t[l]}const o=1,s=t.map(l=>{const u=(n.weights??[]).find(d=>d.serverId===l);return{serverId:l,weight:u?.weight??o}}),i=s.reduce((l,c)=>l+c.weight,0);if(i===0){const l=Math.floor(Math.random()*t.length);return t[l]}let a=Math.random()*i;for(const l of s)if(a-=l.weight,a<=0)return l.serverId;return t[0]}case"failover-only":return t.map(o=>({id:o,priority:this.getServerPriority(o,r)})).sort((o,s)=>o.priority-s.priority)[0]?.id??null;default:return t[0]}}getServerPriority(e,t){if(t){const n=this.groups.get(t);if(n?.weights){const o=n.weights.find(s=>s.serverId===e);if(o)return o.priority}}for(const n of this.groups.values())if(n.weights){const o=n.weights.find(s=>s.serverId===e);if(o)return o.priority}return Array.from(this.servers.keys()).indexOf(e)}updateMetrics(e,t){const r=this.metrics.get(e);r&&(Object.assign(r,t),this.emit("metricsUpdated",{serverId:e,metrics:{...r}}))}requestStarted(e){const t=this.metrics.get(e);t&&(t.activeRequests++,t.totalRequests++)}requestCompleted(e,t,r){const n=this.metrics.get(e);if(n){n.activeRequests=Math.max(0,n.activeRequests-1),n.completedRequests++;const o=n.averageResponseTime*(n.completedRequests-1)+t;n.averageResponseTime=o/n.completedRequests;const s=.1;n.errorRate=n.errorRate*(1-s)+(r?0:1)*s}}getServers(){return Array.from(this.servers.values())}getServer(e){return this.servers.get(e)}getGroups(){return Array.from(this.groups.values())}getGroup(e){return this.groups.get(e)}getServerMetrics(e){return this.metrics.get(e)}getAllMetrics(){return new Map(this.metrics)}getStatistics(){let e=0,t=0,r=0;for(const s of this.metrics.values())s.isHealthy&&e++,t+=s.totalRequests,r+=s.activeRequests;const n=this.getUnifiedTools(),o=n.filter(s=>s.hasConflict).length;return{totalServers:this.servers.size,healthyServers:e,totalGroups:this.groups.size,totalTools:n.length,conflictingTools:o,totalRequests:t,activeRequests:r}}},iee=new ck}}),jMt={};he(jMt,{EnhancedToolDiscovery:()=>dN});var dN,lee=S({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";vn(),q(),yn(),ct(),rC(),aee(),dN=class extends nn{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new ck}async discoverToolsWithAnnotations(e,t,r=1e4){const n=Date.now();if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-n,serverId:e};this.discoveryInProgress.add(e);try{f.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await zt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw xe.toolExecutionFailed("discoverTools",new Error("No tools returned from server"),e);this.clearServerTools(e);const s=[];for(const i of o.tools){const a=this.createEnhancedToolInfo(e,i),l=this.createToolKey(e,i.name);this.toolRegistry.set(l,a);let c=this.serverToolsMap.get(e);c||(c=new Set,this.serverToolsMap.set(e,c)),c.add(i.name),s.push(a),this.emit("toolDiscovered",{serverId:e,toolName:i.name,annotations:a.annotations,timestamp:new Date})}return f.info(`[EnhancedToolDiscovery] Discovered ${s.length} tools with annotations from ${e}`),{success:!0,toolCount:s.length,tools:s,duration:Date.now()-n,serverId:e}}catch(o){const s=o instanceof Error?o.message:String(o);return f.error(`[EnhancedToolDiscovery] Discovery failed for ${e}:`,o),{success:!1,error:s,toolCount:0,tools:[],duration:Date.now()-n,serverId:e}}finally{this.discoveryInProgress.delete(e)}}createEnhancedToolInfo(e,t){const r=ap({name:t.name,description:t.description??""});return{name:t.name,description:t.description??"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,annotations:r,version:"1.0.0",stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferCategory(t),deprecated:!1}}}inferCategory(e){const t=e.name.toLowerCase(),r=(e.description??"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")?"api":t.includes("data")||t.includes("query")?"data":t.includes("auth")||t.includes("login")?"authentication":t.includes("deploy")||t.includes("build")?"deployment":"general"}searchTools(e){const t=Date.now();let r=Array.from(this.toolRegistry.values());if(e.name){const o=e.name.toLowerCase();r=r.filter(s=>s.name.toLowerCase().includes(o))}if(e.description){const o=e.description.toLowerCase().split(/\s+/);r=r.filter(s=>{const i=s.description.toLowerCase();return o.some(a=>i.includes(a))})}if(e.serverIds?.length){const o=e.serverIds;r=r.filter(s=>o.includes(s.serverId))}if(e.category&&(r=r.filter(o=>o.metadata?.category===e.category)),e.tags?.length){const o=e.tags;r=r.filter(s=>{const i=s.annotations?.tags??[];return o.some(a=>i.includes(a))})}if(e.annotations){const o=e.annotations;r=r.filter(s=>{if(!s.annotations)return!1;for(const[i,a]of Object.entries(o)){const l=i;if(s.annotations[l]!==a)return!1}return!0})}if(e.includeUnavailable||(r=r.filter(o=>o.isAvailable)),e.sortBy){const o=e.sortDirection==="desc"?-1:1;r.sort((s,i)=>{let a=0;switch(e.sortBy){case"name":a=s.name.localeCompare(i.name);break;case"calls":a=s.stats.totalCalls-i.stats.totalCalls;break;case"successRate":{const l=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0,c=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0;a=l-c;break}case"avgExecutionTime":a=s.stats.averageExecutionTime-i.stats.averageExecutionTime;break}return a*o})}const n=r.length;return e.limit&&e.limit>0&&(r=r.slice(0,e.limit)),{tools:r,totalCount:n,criteria:e,executionTime:Date.now()-t}}getToolsBySafetyLevel(e){return Array.from(this.toolRegistry.values()).filter(t=>{const r=t.annotations??{};switch(e){case"dangerous":return r.destructiveHint===!0;case"safe":return r.readOnlyHint===!0;case"moderate":return!r.destructiveHint&&!r.readOnlyHint;default:return!1}})}getToolsRequiringConfirmation(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.requiresConfirmation===!0||e.annotations?.destructiveHint===!0)}getReadOnlyTools(){return Array.from(this.toolRegistry.values()).filter(e=>e.annotations?.readOnlyHint===!0)}getUnifiedTools(){return this.multiServerManager.getUnifiedTools()}registerServer(e){this.multiServerManager.addServer(e)}updateToolAnnotations(e,t,r){const n=this.createToolKey(e,t),o=this.toolRegistry.get(n);return o?(o.annotations={...o.annotations,...r},this.emit("annotationsUpdated",{serverId:e,toolName:t,annotations:o.annotations,timestamp:new Date}),!0):!1}checkCompatibility(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n),s=[],i=[],a=[];if(!o)return{compatible:!1,issues:[`Tool '${e}' not found on server '${t}'`],warnings:[],recommendations:[]};if(r&&o.version){const l=o.version.split(".").map(Number),c=r.split(".").map(Number);l.some(isNaN)||c.some(isNaN)?i.push(`Non-standard version format: tool=${o.version}, target=${r}`):l[0]!==c[0]?s.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):l[1]<c[1]&&i.push(`Minor version mismatch: tool is v${o.version}, target is v${r}`)}return o.metadata?.deprecated&&(i.push("This tool is marked as deprecated"),a.push("Consider using an alternative tool if available")),o.annotations?.securityLevel==="restricted"&&a.push("This tool requires elevated permissions"),{compatible:s.length===0,issues:s,warnings:i,recommendations:a}}getTool(e,t){return this.toolRegistry.get(this.createToolKey(e,t))}getAllTools(){return Array.from(this.toolRegistry.values())}getServerTools(e){const t=this.serverToolsMap.get(e);return t?Array.from(t).map(r=>this.getTool(e,r)).filter(r=>r!==void 0):[]}clearServerTools(e){const t=this.serverToolsMap.get(e);if(t){for(const r of t)this.toolRegistry.delete(this.createToolKey(e,r));this.serverToolsMap.delete(e)}}createToolKey(e,t){return`${e}:${t}`}getStatistics(){const e={},t={},r={safe:0,moderate:0,dangerous:0};let n=0,o=0;for(const s of this.toolRegistry.values()){e[s.serverId]=(e[s.serverId]??0)+1;const i=s.metadata?.category??"general";t[i]=(t[i]??0)+1,s.annotations?.destructiveHint?r.dangerous++:s.annotations?.readOnlyHint?r.safe++:r.moderate++,s.annotations&&Object.keys(s.annotations).length>0&&n++,s.metadata?.deprecated&&o++}return{totalTools:this.toolRegistry.size,toolsByServer:e,toolsByCategory:t,toolsBySafetyLevel:r,toolsWithAnnotations:n,deprecatedTools:o}}}}}),qMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/parse.js"(){cs()}}),cee=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/schemas.js"(){cs(),kt(),qMt()}}),F3r=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/checks.js"(){cs()}}),GMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/iso.js"(){cs(),cee()}}),U3r=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/coerce.js"(){cs(),cee()}}),HMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/external.js"(){cs(),qMt(),cee(),F3r(),cs(),Vb(),k6(),GMt(),GMt(),U3r()}}),VMt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4-mini/index.js"(){HMt(),HMt()}});function pN(e){return!!e._zod}function ih(e,t){return pN(e)?wI(e,t):e.safeParse(t)}function WMt(e){if(!e)return;let t;if(pN(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function B3r(e){if(pN(e)){const s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}const r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}const n=e.value;if(n!==void 0)return n}var uee=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js"(){Fh(),VMt()}}),uk,KMt,ah,dk,ui,dee,pee,z3r,JMt,YMt,mN,tl,v_,ZMt,di,Ll,$l,pi,pk,mee,hN,hee,XMt,fN,__,Yt,gN,QMt,Ag,j3r,Ig,ePt,yN,tPt,w_,Rg,fee,rPt,nPt,oPt,sPt,iPt,aPt,lPt,cPt,gee,yee,uPt,vN,dPt,pPt,_N,mPt,b_,T_,hPt,E_,S_,fPt,mk,wN,bN,TN,q3r,EN,SN,CN,gPt,vee,_ee,kN,wee,C_,Mg,bee,yPt,vPt,Tee,_Pt,Eee,xN,wPt,bPt,See,Cee,TPt,EPt,SPt,CPt,kPt,xPt,APt,IPt,RPt,kee,MPt,PPt,AN,IN,RN,DPt,OPt,NPt,MN,LPt,xee,Aee,$Pt,FPt,Iee,UPt,Ree,hk,G3r,BPt,zPt,Mee,jPt,Pee,qPt,GPt,HPt,VPt,WPt,KPt,JPt,YPt,ZPt,fk,XPt,QPt,Dee,Oee,Nee,eDt,tDt,rDt,nDt,oDt,sDt,iDt,aDt,lDt,cDt,uDt,dDt,pDt,mDt,hDt,Lee,fDt,gDt,$ee,yDt,vDt,_Dt,wDt,Fee,bDt,TDt,EDt,SDt,H3r,V3r,W3r,K3r,J3r,Y3r,Lt,CDt,lh=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js"(){ut(),uk="2025-11-25",KMt=[uk,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ah="io.modelcontextprotocol/related-task",dk="2.0",ui=uB(e=>e!==null&&(typeof e=="object"||typeof e=="function")),dee=tn([le(),Ir().int()]),pee=le(),z3r=Ps({ttl:tn([Ir(),Wb()]).optional(),pollInterval:Ir().optional()}),JMt=ot({ttl:Ir().optional()}),YMt=ot({taskId:le()}),mN=Ps({progressToken:dee.optional(),[ah]:YMt.optional()}),tl=ot({_meta:mN.optional()}),v_=tl.extend({task:JMt.optional()}),ZMt=e=>v_.safeParse(e).success,di=ot({method:le(),params:tl.loose().optional()}),Ll=ot({_meta:mN.optional()}),$l=ot({method:le(),params:Ll.loose().optional()}),pi=Ps({_meta:mN.optional()}),pk=tn([le(),Ir().int()]),mee=ot({jsonrpc:Tt(dk),id:pk,...di.shape}).strict(),hN=e=>mee.safeParse(e).success,hee=ot({jsonrpc:Tt(dk),...$l.shape}).strict(),XMt=e=>hee.safeParse(e).success,fN=ot({jsonrpc:Tt(dk),id:pk,result:pi}).strict(),__=e=>fN.safeParse(e).success,(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Yt||(Yt={})),gN=ot({jsonrpc:Tt(dk),id:pk.optional(),error:ot({code:Ir().int(),message:le(),data:cn().optional()})}).strict(),QMt=e=>gN.safeParse(e).success,Ag=tn([mee,hee,fN,gN]),j3r=tn([fN,gN]),Ig=pi.strict(),ePt=Ll.extend({requestId:pk.optional(),reason:le().optional()}),yN=$l.extend({method:Tt("notifications/cancelled"),params:ePt}),tPt=ot({src:le(),mimeType:le().optional(),sizes:rt(le()).optional(),theme:Gi(["light","dark"]).optional()}),w_=ot({icons:rt(tPt).optional()}),Rg=ot({name:le(),title:le().optional()}),fee=Rg.extend({...Rg.shape,...w_.shape,version:le(),websiteUrl:le().optional(),description:le().optional()}),rPt=Kb(ot({applyDefaults:en().optional()}),fn(le(),cn())),nPt=bR(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Kb(ot({form:rPt.optional(),url:ui.optional()}),fn(le(),cn()).optional())),oPt=Ps({list:ui.optional(),cancel:ui.optional(),requests:Ps({sampling:Ps({createMessage:ui.optional()}).optional(),elicitation:Ps({create:ui.optional()}).optional()}).optional()}),sPt=Ps({list:ui.optional(),cancel:ui.optional(),requests:Ps({tools:Ps({call:ui.optional()}).optional()}).optional()}),iPt=ot({experimental:fn(le(),ui).optional(),sampling:ot({context:ui.optional(),tools:ui.optional()}).optional(),elicitation:nPt.optional(),roots:ot({listChanged:en().optional()}).optional(),tasks:oPt.optional()}),aPt=tl.extend({protocolVersion:le(),capabilities:iPt,clientInfo:fee}),lPt=di.extend({method:Tt("initialize"),params:aPt}),cPt=ot({experimental:fn(le(),ui).optional(),logging:ui.optional(),completions:ui.optional(),prompts:ot({listChanged:en().optional()}).optional(),resources:ot({subscribe:en().optional(),listChanged:en().optional()}).optional(),tools:ot({listChanged:en().optional()}).optional(),tasks:sPt.optional()}),gee=pi.extend({protocolVersion:le(),capabilities:cPt,serverInfo:fee,instructions:le().optional()}),yee=$l.extend({method:Tt("notifications/initialized"),params:Ll.optional()}),uPt=e=>yee.safeParse(e).success,vN=di.extend({method:Tt("ping"),params:tl.optional()}),dPt=ot({progress:Ir(),total:En(Ir()),message:En(le())}),pPt=ot({...Ll.shape,...dPt.shape,progressToken:dee}),_N=$l.extend({method:Tt("notifications/progress"),params:pPt}),mPt=tl.extend({cursor:pee.optional()}),b_=di.extend({params:mPt.optional()}),T_=pi.extend({nextCursor:pee.optional()}),hPt=Gi(["working","input_required","completed","failed","cancelled"]),E_=ot({taskId:le(),status:hPt,ttl:tn([Ir(),Wb()]),createdAt:le(),lastUpdatedAt:le(),pollInterval:En(Ir()),statusMessage:En(le())}),S_=pi.extend({task:E_}),fPt=Ll.merge(E_),mk=$l.extend({method:Tt("notifications/tasks/status"),params:fPt}),wN=di.extend({method:Tt("tasks/get"),params:tl.extend({taskId:le()})}),bN=pi.merge(E_),TN=di.extend({method:Tt("tasks/result"),params:tl.extend({taskId:le()})}),q3r=pi.loose(),EN=b_.extend({method:Tt("tasks/list")}),SN=T_.extend({tasks:rt(E_)}),CN=di.extend({method:Tt("tasks/cancel"),params:tl.extend({taskId:le()})}),gPt=pi.merge(E_),vee=ot({uri:le(),mimeType:En(le()),_meta:fn(le(),cn()).optional()}),_ee=vee.extend({text:le()}),kN=le().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),wee=vee.extend({blob:kN}),C_=Gi(["user","assistant"]),Mg=ot({audience:rt(C_).optional(),priority:Ir().min(0).max(1).optional(),lastModified:cR.datetime({offset:!0}).optional()}),bee=ot({...Rg.shape,...w_.shape,uri:le(),description:En(le()),mimeType:En(le()),annotations:Mg.optional(),_meta:En(Ps({}))}),yPt=ot({...Rg.shape,...w_.shape,uriTemplate:le(),description:En(le()),mimeType:En(le()),annotations:Mg.optional(),_meta:En(Ps({}))}),vPt=b_.extend({method:Tt("resources/list")}),Tee=T_.extend({resources:rt(bee)}),_Pt=b_.extend({method:Tt("resources/templates/list")}),Eee=T_.extend({resourceTemplates:rt(yPt)}),xN=tl.extend({uri:le()}),wPt=xN,bPt=di.extend({method:Tt("resources/read"),params:wPt}),See=pi.extend({contents:rt(tn([_ee,wee]))}),Cee=$l.extend({method:Tt("notifications/resources/list_changed"),params:Ll.optional()}),TPt=xN,EPt=di.extend({method:Tt("resources/subscribe"),params:TPt}),SPt=xN,CPt=di.extend({method:Tt("resources/unsubscribe"),params:SPt}),kPt=Ll.extend({uri:le()}),xPt=$l.extend({method:Tt("notifications/resources/updated"),params:kPt}),APt=ot({name:le(),description:En(le()),required:En(en())}),IPt=ot({...Rg.shape,...w_.shape,description:En(le()),arguments:En(rt(APt)),_meta:En(Ps({}))}),RPt=b_.extend({method:Tt("prompts/list")}),kee=T_.extend({prompts:rt(IPt)}),MPt=tl.extend({name:le(),arguments:fn(le(),le()).optional()}),PPt=di.extend({method:Tt("prompts/get"),params:MPt}),AN=ot({type:Tt("text"),text:le(),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),IN=ot({type:Tt("image"),data:kN,mimeType:le(),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),RN=ot({type:Tt("audio"),data:kN,mimeType:le(),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),DPt=ot({type:Tt("tool_use"),name:le(),id:le(),input:fn(le(),cn()),_meta:fn(le(),cn()).optional()}),OPt=ot({type:Tt("resource"),resource:tn([_ee,wee]),annotations:Mg.optional(),_meta:fn(le(),cn()).optional()}),NPt=bee.extend({type:Tt("resource_link")}),MN=tn([AN,IN,RN,NPt,OPt]),LPt=ot({role:C_,content:MN}),xee=pi.extend({description:le().optional(),messages:rt(LPt)}),Aee=$l.extend({method:Tt("notifications/prompts/list_changed"),params:Ll.optional()}),$Pt=ot({title:le().optional(),readOnlyHint:en().optional(),destructiveHint:en().optional(),idempotentHint:en().optional(),openWorldHint:en().optional()}),FPt=ot({taskSupport:Gi(["required","optional","forbidden"]).optional()}),Iee=ot({...Rg.shape,...w_.shape,description:le().optional(),inputSchema:ot({type:Tt("object"),properties:fn(le(),ui).optional(),required:rt(le()).optional()}).catchall(cn()),outputSchema:ot({type:Tt("object"),properties:fn(le(),ui).optional(),required:rt(le()).optional()}).catchall(cn()).optional(),annotations:$Pt.optional(),execution:FPt.optional(),_meta:fn(le(),cn()).optional()}),UPt=b_.extend({method:Tt("tools/list")}),Ree=T_.extend({tools:rt(Iee)}),hk=pi.extend({content:rt(MN).default([]),structuredContent:fn(le(),cn()).optional(),isError:en().optional()}),G3r=hk.or(pi.extend({toolResult:cn()})),BPt=v_.extend({name:le(),arguments:fn(le(),cn()).optional()}),zPt=di.extend({method:Tt("tools/call"),params:BPt}),Mee=$l.extend({method:Tt("notifications/tools/list_changed"),params:Ll.optional()}),jPt=ot({autoRefresh:en().default(!0),debounceMs:Ir().int().nonnegative().default(300)}),Pee=Gi(["debug","info","notice","warning","error","critical","alert","emergency"]),qPt=tl.extend({level:Pee}),GPt=di.extend({method:Tt("logging/setLevel"),params:qPt}),HPt=Ll.extend({level:Pee,logger:le().optional(),data:cn()}),VPt=$l.extend({method:Tt("notifications/message"),params:HPt}),WPt=ot({name:le().optional()}),KPt=ot({hints:rt(WPt).optional(),costPriority:Ir().min(0).max(1).optional(),speedPriority:Ir().min(0).max(1).optional(),intelligencePriority:Ir().min(0).max(1).optional()}),JPt=ot({mode:Gi(["auto","required","none"]).optional()}),YPt=ot({type:Tt("tool_result"),toolUseId:le().describe("The unique identifier for the corresponding tool call."),content:rt(MN).default([]),structuredContent:ot({}).loose().optional(),isError:en().optional(),_meta:fn(le(),cn()).optional()}),ZPt=vR("type",[AN,IN,RN]),fk=vR("type",[AN,IN,RN,DPt,YPt]),XPt=ot({role:C_,content:tn([fk,rt(fk)]),_meta:fn(le(),cn()).optional()}),QPt=v_.extend({messages:rt(XPt),modelPreferences:KPt.optional(),systemPrompt:le().optional(),includeContext:Gi(["none","thisServer","allServers"]).optional(),temperature:Ir().optional(),maxTokens:Ir().int(),stopSequences:rt(le()).optional(),metadata:ui.optional(),tools:rt(Iee).optional(),toolChoice:JPt.optional()}),Dee=di.extend({method:Tt("sampling/createMessage"),params:QPt}),Oee=pi.extend({model:le(),stopReason:En(Gi(["endTurn","stopSequence","maxTokens"]).or(le())),role:C_,content:ZPt}),Nee=pi.extend({model:le(),stopReason:En(Gi(["endTurn","stopSequence","maxTokens","toolUse"]).or(le())),role:C_,content:tn([fk,rt(fk)])}),eDt=ot({type:Tt("boolean"),title:le().optional(),description:le().optional(),default:en().optional()}),tDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),minLength:Ir().optional(),maxLength:Ir().optional(),format:Gi(["email","uri","date","date-time"]).optional(),default:le().optional()}),rDt=ot({type:Gi(["number","integer"]),title:le().optional(),description:le().optional(),minimum:Ir().optional(),maximum:Ir().optional(),default:Ir().optional()}),nDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),enum:rt(le()),default:le().optional()}),oDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),oneOf:rt(ot({const:le(),title:le()})),default:le().optional()}),sDt=ot({type:Tt("string"),title:le().optional(),description:le().optional(),enum:rt(le()),enumNames:rt(le()).optional(),default:le().optional()}),iDt=tn([nDt,oDt]),aDt=ot({type:Tt("array"),title:le().optional(),description:le().optional(),minItems:Ir().optional(),maxItems:Ir().optional(),items:ot({type:Tt("string"),enum:rt(le())}),default:rt(le()).optional()}),lDt=ot({type:Tt("array"),title:le().optional(),description:le().optional(),minItems:Ir().optional(),maxItems:Ir().optional(),items:ot({anyOf:rt(ot({const:le(),title:le()}))}),default:rt(le()).optional()}),cDt=tn([aDt,lDt]),uDt=tn([sDt,iDt,cDt]),dDt=tn([uDt,eDt,tDt,rDt]),pDt=v_.extend({mode:Tt("form").optional(),message:le(),requestedSchema:ot({type:Tt("object"),properties:fn(le(),dDt),required:rt(le()).optional()})}),mDt=v_.extend({mode:Tt("url"),message:le(),elicitationId:le(),url:le().url()}),hDt=tn([pDt,mDt]),Lee=di.extend({method:Tt("elicitation/create"),params:hDt}),fDt=Ll.extend({elicitationId:le()}),gDt=$l.extend({method:Tt("notifications/elicitation/complete"),params:fDt}),$ee=pi.extend({action:Gi(["accept","decline","cancel"]),content:bR(e=>e===null?void 0:e,fn(le(),tn([le(),Ir(),en(),rt(le())])).optional())}),yDt=ot({type:Tt("ref/resource"),uri:le()}),vDt=ot({type:Tt("ref/prompt"),name:le()}),_Dt=tl.extend({ref:tn([vDt,yDt]),argument:ot({name:le(),value:le()}),context:ot({arguments:fn(le(),le()).optional()}).optional()}),wDt=di.extend({method:Tt("completion/complete"),params:_Dt}),Fee=pi.extend({completion:Ps({values:rt(le()).max(100),total:En(Ir().int()),hasMore:En(en())})}),bDt=ot({uri:le().startsWith("file://"),name:le().optional(),_meta:fn(le(),cn()).optional()}),TDt=di.extend({method:Tt("roots/list"),params:tl.optional()}),EDt=pi.extend({roots:rt(bDt)}),SDt=$l.extend({method:Tt("notifications/roots/list_changed"),params:Ll.optional()}),H3r=tn([vN,lPt,wDt,GPt,PPt,RPt,vPt,_Pt,bPt,EPt,CPt,zPt,UPt,wN,TN,EN,CN]),V3r=tn([yN,_N,yee,SDt,mk]),W3r=tn([Ig,Oee,Nee,$ee,EDt,bN,SN,S_]),K3r=tn([vN,Dee,Lee,TDt,wN,TN,EN,CN]),J3r=tn([yN,_N,VPt,xPt,Cee,Mee,Aee,mk,gDt]),Y3r=tn([Ig,gee,Fee,xee,kee,Tee,Eee,See,hk,Ree,bN,SN,S_]),Lt=class scr extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===Yt.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new CDt(o.elicitations,r)}return new scr(t,r,n)}},CDt=class extends Lt{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Yt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function Pg(e){return e==="completed"||e==="failed"||e==="cancelled"}var Z3r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js"(){}});function kDt(e){const r=WMt(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=B3r(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function xDt(e,t){const r=ih(e,t);if(!r.success)throw r.error;return r.data}var X3r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js"(){VMt(),uee(),XF()}});function ADt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Q3r(e,t){const r={...e};for(const n in t){const o=n,s=t[o];if(s===void 0)continue;const i=r[o];ADt(i)&&ADt(s)?r[o]={...i,...s}:r[o]=s}return r}var IDt,RDt,eUr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js"(){uee(),lh(),Z3r(),X3r(),IDt=6e4,RDt=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(yN,t=>{this._oncancel(t)}),this.setNotificationHandler(_N,t=>{this._onprogress(t)}),this.setRequestHandler(vN,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wN,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Lt(Yt.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(TN,async(t,r)=>{const n=async()=>{const o=t.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(i.type==="response"||i.type==="error"){const a=i.message,l=a.id,c=this._requestResolvers.get(l);if(c)if(this._requestResolvers.delete(l),i.type==="response")c(a);else{const u=a,d=new Lt(u.error.code,u.error.message,u.error.data);c(d)}else{const u=i.type==="response"?"Response":"Error";this._onerror(new Error(`${u} handler missing for request ${l}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}const s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new Lt(Yt.InvalidParams,`Task not found: ${o}`);if(!Pg(s.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(Pg(s.status)){const i=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[ah]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(EN,async(t,r)=>{try{const{tasks:n,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,r.sessionId);return{tasks:n,nextCursor:o,_meta:{}}}catch(n){throw new Lt(Yt.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(CN,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new Lt(Yt.InvalidParams,`Task not found: ${t.params.taskId}`);if(Pg(n.status))throw new Lt(Yt.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(t.params.taskId);const o=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!o)throw new Lt(Yt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof Lt?n:new Lt(Yt.InvalidRequest,`Failed to cancel task: ${n instanceof Error?n.message:String(n)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,r,n,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Lt.fromError(Yt.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};const n=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{n?.(o,s),__(o)||QMt(o)?this._onresponse(o):hN(o)?this._onrequest(o,s):XMt(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Lt.fromError(Yt.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,o=e.params?._meta?.[ah]?.taskId;if(r===void 0){const c={jsonrpc:"2.0",id:e.id,error:{code:Yt.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:c,timestamp:Date.now()},n?.sessionId).catch(u=>this._onerror(new Error(`Failed to enqueue error response: ${u}`))):n?.send(c).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}const s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);const i=ZMt(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,l={signal:s.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async c=>{if(s.signal.aborted)return;const u={relatedRequestId:e.id};o&&(u.relatedTask={taskId:o}),await this.notification(c,u)},sendRequest:async(c,u,d)=>{if(s.signal.aborted)throw new Lt(Yt.ConnectionClosed,"Request was cancelled");const m={...d,relatedRequestId:e.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});const h=m.relatedTask?.taskId??o;return h&&a&&await a.updateTaskStatus(h,"input_required"),await this.request(c,u,m)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:a,taskRequestedTtl:i?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,l)).then(async c=>{if(s.signal.aborted)return;const u={result:c,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:u,timestamp:Date.now()},n?.sessionId):await n?.send(u)},async c=>{if(s.signal.aborted)return;const u={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(c.code)?c.code:Yt.InternalError,message:c.message??"Internal error",...c.data!==void 0&&{data:c.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},n?.sessionId):await n?.send(u)}).catch(c=>this._onerror(new Error(`Failed to send response: ${c}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),o=this._progressHandlers.get(n);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}const s=this._responseHandlers.get(n),i=this._timeoutInfo.get(n);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),s(a);return}o(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),__(e))r(e);else{const s=new Lt(e.error.code,e.error.message,e.error.data);r(s)}return}const n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(__(e)&&e.result&&typeof e.result=="object"){const s=e.result;if(s.task&&typeof s.task=="object"){const i=s.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,t))}}if(o||this._progressHandlers.delete(t),__(e))n(e);else{const s=Lt.fromError(e.error.code,e.error.message,e.error.data);n(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{yield{type:"result",result:await this.request(e,t,r)}}catch(s){yield{type:"error",error:s instanceof Lt?s:new Lt(Yt.InternalError,String(s))}}return}let o;try{const s=await this.request(e,S_,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Lt(Yt.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:i},Pg(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:i.status==="failed"?yield{type:"error",error:new Lt(Yt.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new Lt(Yt.InternalError,`Task ${o} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)};return}const a=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,a)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Lt?s:new Lt(Yt.InternalError,String(s))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:i,relatedTask:a}=r??{};return new Promise((l,c)=>{const u=_=>{c(_)};if(!this._transport){u(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(_){u(_);return}r?.signal?.throwIfAborted();const d=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:d};r?.onprogress&&(this._progressHandlers.set(d,r.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),i&&(m.params={...m.params,task:i}),a&&(m.params={...m.params,_meta:{...m.params?._meta||{},[ah]:a}});const h=_=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(_)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`)));const b=_ instanceof Lt?_:new Lt(Yt.RequestTimeout,String(_));c(b)};this._responseHandlers.set(d,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return c(_);try{const b=ih(t,_.result);b.success?l(b.data):c(b.error)}catch(b){c(b)}}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});const g=r?.timeout??IDt,y=()=>h(Lt.fromError(Yt.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(d,g,r?.maxTotalTimeout,y,r?.resetTimeoutOnProgress??!1);const v=a?.taskId;if(v){const _=b=>{const T=this._responseHandlers.get(d);T?T(b):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,_),this._enqueueTaskMessage(v,{type:"request",message:m,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(d),c(b)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(_=>{this._cleanupTimeout(d),c(_)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},bN,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},SN,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},gPt,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[ah]:t.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};t?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[ah]:t.relatedTask}}}),this._transport?.send(i,t).catch(a=>this._onerror(a))});return}let s={...e,jsonrpc:"2.0"};t?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[ah]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){const r=kDt(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const s=xDt(e,n);return Promise.resolve(t(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=kDt(e);this._notificationHandlers.set(r,n=>{const o=xDt(e,n);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const n of r)if(n.type==="request"&&hN(n.message)){const o=n.message.id,s=this._requestResolvers.get(o);s?(s(new Lt(Yt.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let r=this._options?.defaultTaskPollInterval??1e3;try{const n=await this._taskStore?.getTask(e);n?.pollInterval&&(r=n.pollInterval)}catch{}return new Promise((n,o)=>{if(t.aborted){o(new Lt(Yt.InvalidRequest,"Request cancelled"));return}const s=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(s),o(new Lt(Yt.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async n=>{const o=await r.getTask(n,t);if(!o)throw new Lt(Yt.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(n,o,s)=>{await r.storeTaskResult(n,o,s,t);const i=await r.getTask(n,t);if(i){const a=mk.parse({method:"notifications/tasks/status",params:i});await this.notification(a),Pg(i.status)&&this._cleanupTaskProgressHandler(n)}},getTaskResult:n=>r.getTaskResult(n,t),updateTaskStatus:async(n,o,s)=>{const i=await r.getTask(n,t);if(!i)throw new Lt(Yt.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(Pg(i.status))throw new Lt(Yt.InvalidParams,`Cannot update task "${n}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(n,o,s,t);const a=await r.getTask(n,t);if(a){const l=mk.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Pg(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),Dg,Ws,MDt,tUr,rUr,nUr,oUr,sUr,iUr,aUr,lUr,cUr,uUr,dUr,pUr,mUr,hUr,fUr,gUr,yUr,vUr,_Ur,wUr,bUr,TUr,EUr,SUr,CUr,kUr,xUr,AUr,IUr,RUr,MUr,PUr,DUr,OUr,NUr,LUr,$Ur,FUr,UUr,BUr,zUr,jUr,qUr,GUr,HUr,VUr,WUr=S({"npm-stub:ajv"(){Dg={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Dg.get}):new Proxy(function(...r){return new Proxy({},{get:Dg.get})},{get:Dg.get,apply(r,n,o){return new Proxy({},{get:Dg.get})},construct(r,n){return new Proxy({},{get:Dg.get})}})}},Ws=new Proxy({},Dg),MDt=Ws,{BedrockClient:tUr,ListFoundationModelsCommand:rUr,BedrockRuntimeClient:nUr,ConverseCommand:oUr,ConverseStreamCommand:sUr,ImageFormat:iUr,InvokeModelCommand:aUr}=Ws,{SageMakerRuntimeClient:lUr,InvokeEndpointCommand:cUr,InvokeEndpointWithResponseStreamCommand:uUr}=Ws,{GoogleAuth:dUr,VertexAI:pUr,TextToSpeechClient:mUr}=Ws,{Webhook:hUr}=Ws,{Hippocampus:fUr,HippocampusConfig:gUr}=Ws,{createClient:yUr}=Ws,{Queue:vUr,Worker:_Ur,Job:wUr,QueueScheduler:bUr,FlowProducer:TUr}=Ws,{Cron:EUr}=Ws,{parseBuffer:SUr,selectCover:CUr}=Ws,{extractRawText:kUr,convertToHtml:xUr}=Ws,{Hono:AUr}=Ws,{cors:IUr,HTTPException:RUr,logger:MUr,secureHeaders:PUr,streamSSE:DUr,timeout:OUr}=Ws,NUr=globalThis.fetch,LUr=globalThis.Request,$Ur=globalThis.Response,FUr=globalThis.Headers,UUr=globalThis.FormData,BUr=globalThis.File,zUr=globalThis.Blob,jUr=Ws.Agent,qUr=Ws.Pool,GUr=Ws.Client,HUr=Ws.Dispatcher,VUr=Ws.MockAgent}}),Og,Ks,PDt,KUr,JUr,YUr,ZUr,XUr,QUr,e6r,t6r,r6r,n6r,o6r,s6r,i6r,a6r,l6r,c6r,u6r,d6r,p6r,m6r,h6r,f6r,g6r,y6r,v6r,_6r,w6r,b6r,T6r,E6r,S6r,C6r,k6r,x6r,A6r,I6r,R6r,M6r,P6r,D6r,O6r,N6r,L6r,$6r,F6r,U6r,B6r=S({"npm-stub:ajv-formats"(){Og={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Og.get}):new Proxy(function(...r){return new Proxy({},{get:Og.get})},{get:Og.get,apply(r,n,o){return new Proxy({},{get:Og.get})},construct(r,n){return new Proxy({},{get:Og.get})}})}},Ks=new Proxy({},Og),PDt=Ks,{BedrockClient:KUr,ListFoundationModelsCommand:JUr,BedrockRuntimeClient:YUr,ConverseCommand:ZUr,ConverseStreamCommand:XUr,ImageFormat:QUr,InvokeModelCommand:e6r}=Ks,{SageMakerRuntimeClient:t6r,InvokeEndpointCommand:r6r,InvokeEndpointWithResponseStreamCommand:n6r}=Ks,{GoogleAuth:o6r,VertexAI:s6r,TextToSpeechClient:i6r}=Ks,{Webhook:a6r}=Ks,{Hippocampus:l6r,HippocampusConfig:c6r}=Ks,{createClient:u6r}=Ks,{Queue:d6r,Worker:p6r,Job:m6r,QueueScheduler:h6r,FlowProducer:f6r}=Ks,{Cron:g6r}=Ks,{parseBuffer:y6r,selectCover:v6r}=Ks,{extractRawText:_6r,convertToHtml:w6r}=Ks,{Hono:b6r}=Ks,{cors:T6r,HTTPException:E6r,logger:S6r,secureHeaders:C6r,streamSSE:k6r,timeout:x6r}=Ks,A6r=globalThis.fetch,I6r=globalThis.Request,R6r=globalThis.Response,M6r=globalThis.Headers,P6r=globalThis.FormData,D6r=globalThis.File,O6r=globalThis.Blob,N6r=Ks.Agent,L6r=Ks.Pool,$6r=Ks.Client,F6r=Ks.Dispatcher,U6r=Ks.MockAgent}});function z6r(){const e=new MDt({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return PDt(e),e}var DDt,j6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js"(){WUr(),B6r(),DDt=class{constructor(e){this._ajv=e??z6r()}getValidator(e){const t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>t(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}}}}),ODt,q6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js"(){lh(),ODt=class{constructor(e){this._client=e}async*callToolStream(e,t=hk,r){const n=this._client,o={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},s=n.requestStream({method:"tools/call",params:e},t,o),i=n.getToolOutputValidator(e.name);for await(const a of s){if(a.type==="result"&&i){const l=a.result;if(!l.structuredContent&&!l.isError){yield{type:"error",error:new Lt(Yt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(l.structuredContent)try{const c=i(l.structuredContent);if(!c.valid){yield{type:"error",error:new Lt(Yt.InvalidParams,`Structured content does not match the tool's output schema: ${c.errorMessage}`)};return}}catch(c){if(c instanceof Lt){yield{type:"error",error:c};return}yield{type:"error",error:new Lt(Yt.InvalidParams,`Failed to validate structured content: ${c instanceof Error?c.message:String(c)}`)};return}}yield a}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}}});function G6r(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function H6r(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var V6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js"(){}});function PN(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){const r=t,n=e.properties;for(const o of Object.keys(n)){const s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&PN(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&PN(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&PN(r,t)}}function W6r(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=e.form!==void 0,r=e.url!==void 0;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}var NDt,K6r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js"(){eUr(),lh(),j6r(),uee(),q6r(),V6r(),NDt=class extends RDt{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new DDt,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Mee,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Aee,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Cee,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ODt(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Q3r(this._capabilities,e)}setRequestHandler(e,t){const n=WMt(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let o;if(pN(n)){const i=n;o=i._zod?.def?.value??i.value}else{const i=n;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");const s=o;if(s==="elicitation/create"){const i=async(a,l)=>{const c=ih(Lee,a);if(!c.success){const _=c.error instanceof Error?c.error.message:String(c.error);throw new Lt(Yt.InvalidParams,`Invalid elicitation request: ${_}`)}const{params:u}=c.data;u.mode=u.mode??"form";const{supportsFormMode:d,supportsUrlMode:m}=W6r(this._capabilities.elicitation);if(u.mode==="form"&&!d)throw new Lt(Yt.InvalidParams,"Client does not support form-mode elicitation requests");if(u.mode==="url"&&!m)throw new Lt(Yt.InvalidParams,"Client does not support URL-mode elicitation requests");const h=await Promise.resolve(t(a,l));if(u.task){const _=ih(S_,h);if(!_.success){const b=_.error instanceof Error?_.error.message:String(_.error);throw new Lt(Yt.InvalidParams,`Invalid task creation result: ${b}`)}return _.data}const g=ih($ee,h);if(!g.success){const _=g.error instanceof Error?g.error.message:String(g.error);throw new Lt(Yt.InvalidParams,`Invalid elicitation result: ${_}`)}const y=g.data,v=u.mode==="form"?u.requestedSchema:void 0;if(u.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{PN(v,y.content)}catch{}return y};return super.setRequestHandler(e,i)}if(s==="sampling/createMessage"){const i=async(a,l)=>{const c=ih(Dee,a);if(!c.success){const y=c.error instanceof Error?c.error.message:String(c.error);throw new Lt(Yt.InvalidParams,`Invalid sampling request: ${y}`)}const{params:u}=c.data,d=await Promise.resolve(t(a,l));if(u.task){const y=ih(S_,d);if(!y.success){const v=y.error instanceof Error?y.error.message:String(y.error);throw new Lt(Yt.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}const h=u.tools||u.toolChoice?Nee:Oee,g=ih(h,d);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new Lt(Yt.InvalidParams,`Invalid sampling result: ${y}`)}return g.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{const r=await this.request({method:"initialize",params:{protocolVersion:uk,capabilities:this._capabilities,clientInfo:this._clientInfo}},gee,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!KMt.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){G6r(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&H6r(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Ig,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Fee,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Ig,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},xee,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},kee,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},Tee,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Eee,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},See,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Ig,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Ig,t)}async callTool(e,t=hk,r){if(this.isToolTaskRequired(e.name))throw new Lt(Yt.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),o=this.getToolOutputValidator(e.name);if(o){if(!n.structuredContent&&!n.isError)throw new Lt(Yt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const s=o(n.structuredContent);if(!s.valid)throw new Lt(Yt.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof Lt?s:new Lt(Yt.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}const r=t.execution?.taskSupport;(r==="required"||r==="optional")&&this._cachedKnownTaskTools.add(t.name),r==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},Ree,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=jPt.safeParse(r);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof r.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:s,debounceMs:i}=o.data,{onChanged:a}=r,l=async()=>{if(!s){a(null,null);return}try{const u=await n();a(null,u)}catch(u){const d=u instanceof Error?u:new Error(String(u));a(d,null)}},c=()=>{if(i){const u=this._listChangedDebounceTimers.get(e);u&&clearTimeout(u);const d=setTimeout(l,i);this._listChangedDebounceTimers.set(e,d)}else l()};this.setNotificationHandler(t,c)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}}),LDt={};he(LDt,{Agent:()=>C4t,BedrockClient:()=>FDt,BedrockRuntimeClient:()=>BDt,Blob:()=>S4t,Client:()=>x4t,ConverseCommand:()=>zDt,ConverseStreamCommand:()=>jDt,Cron:()=>i4t,Dispatcher:()=>A4t,File:()=>E4t,FlowProducer:()=>s4t,FormData:()=>T4t,GoogleAuth:()=>KDt,HTTPException:()=>m4t,Headers:()=>b4t,Hippocampus:()=>XDt,HippocampusConfig:()=>QDt,Hono:()=>d4t,ImageFormat:()=>qDt,InvokeEndpointCommand:()=>VDt,InvokeEndpointWithResponseStreamCommand:()=>WDt,InvokeModelCommand:()=>GDt,Job:()=>n4t,ListFoundationModelsCommand:()=>UDt,MockAgent:()=>M4t,Pool:()=>k4t,Queue:()=>t4t,QueueScheduler:()=>o4t,Request:()=>_4t,Response:()=>w4t,SageMakerRuntimeClient:()=>HDt,TextToSpeechClient:()=>YDt,VertexAI:()=>JDt,Webhook:()=>ZDt,Worker:()=>r4t,convertToHtml:()=>u4t,cors:()=>p4t,createClient:()=>e4t,default:()=>$Dt,extractRawText:()=>c4t,fetch:()=>v4t,getGlobalDispatcher:()=>R4t,interceptors:()=>P4t,logger:()=>h4t,parseBuffer:()=>a4t,request:()=>D4t,secureHeaders:()=>f4t,selectCover:()=>l4t,setGlobalDispatcher:()=>I4t,streamSSE:()=>g4t,timeout:()=>y4t});var Ng,Ss,$Dt,FDt,UDt,BDt,zDt,jDt,qDt,GDt,HDt,VDt,WDt,KDt,JDt,YDt,ZDt,XDt,QDt,e4t,t4t,r4t,n4t,o4t,s4t,i4t,a4t,l4t,c4t,u4t,d4t,p4t,m4t,h4t,f4t,g4t,y4t,v4t,_4t,w4t,b4t,T4t,E4t,S4t,C4t,k4t,x4t,A4t,I4t,R4t,M4t,P4t,D4t,J6r=S({"npm-stub:which"(){Ng={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Ng.get}):new Proxy(function(...r){return new Proxy({},{get:Ng.get})},{get:Ng.get,apply(r,n,o){return new Proxy({},{get:Ng.get})},construct(r,n){return new Proxy({},{get:Ng.get})}})}},Ss=new Proxy({},Ng),$Dt=Ss,{BedrockClient:FDt,ListFoundationModelsCommand:UDt,BedrockRuntimeClient:BDt,ConverseCommand:zDt,ConverseStreamCommand:jDt,ImageFormat:qDt,InvokeModelCommand:GDt}=Ss,{SageMakerRuntimeClient:HDt,InvokeEndpointCommand:VDt,InvokeEndpointWithResponseStreamCommand:WDt}=Ss,{GoogleAuth:KDt,VertexAI:JDt,TextToSpeechClient:YDt}=Ss,{Webhook:ZDt}=Ss,{Hippocampus:XDt,HippocampusConfig:QDt}=Ss,{createClient:e4t}=Ss,{Queue:t4t,Worker:r4t,Job:n4t,QueueScheduler:o4t,FlowProducer:s4t}=Ss,{Cron:i4t}=Ss,{parseBuffer:a4t,selectCover:l4t}=Ss,{extractRawText:c4t,convertToHtml:u4t}=Ss,{Hono:d4t}=Ss,{cors:p4t,HTTPException:m4t,logger:h4t,secureHeaders:f4t,streamSSE:g4t,timeout:y4t}=Ss,v4t=globalThis.fetch,_4t=globalThis.Request,w4t=globalThis.Response,b4t=globalThis.Headers,T4t=globalThis.FormData,E4t=globalThis.File,S4t=globalThis.Blob,C4t=Ss.Agent,k4t=Ss.Pool,x4t=Ss.Client,A4t=Ss.Dispatcher,I4t=()=>{},R4t=()=>Ss,M4t=Ss.MockAgent,P4t={redirect:()=>e=>e,retry:()=>e=>e},D4t=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),Y6r=gr({"node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js"(e,t){"use strict";var r=(n={})=>{const o=n.env||process.env;return(n.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(i=>i.toUpperCase()==="PATH")||"Path"};t.exports=r,t.exports.default=r}}),Z6r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(Lr(),wr(Hc)),n=(J6r(),wr(LDt)),o=Y6r();function s(a,l){const c=a.options.env||process.env,u=process.cwd(),d=a.options.cwd!=null,m=d&&process.chdir!==void 0&&!process.chdir.disabled;if(m)try{process.chdir(a.options.cwd)}catch{}let h;try{h=n.sync(a.command,{path:c[o({env:c})],pathExt:l?r.delimiter:void 0})}catch{}finally{m&&process.chdir(u)}return h&&(h=r.resolve(d?a.options.cwd:"",h)),h}function i(a){return s(a)||s(a,!0)}t.exports=i}}),X6r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js"(e,t){"use strict";var r=/([()\][%!^"`<>&|;, *?])/g;function n(s){return s=s.replace(r,"^$1"),s}function o(s,i){return s=`${s}`,s=s.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),s=s.replace(/(?=(\\+?)?)\1$/,"$1$1"),s=`"${s}"`,s=s.replace(r,"^$1"),i&&(s=s.replace(r,"^$1")),s}t.exports.command=n,t.exports.argument=o}}),Q6r=gr({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),e5r=gr({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=Q6r();t.exports=(n="")=>{const o=n.match(r);if(!o)return null;const[s,i]=o[0].replace(/#! ?/,"").split(" "),a=s.split("/").pop();return a==="env"?i:i?`${a} ${i}`:a}}}),t5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(gn(),wr(_l)),n=e5r();function o(s){const a=Buffer.alloc(150);let l;try{l=r.openSync(s,"r"),r.readSync(l,a,0,150,0),r.closeSync(l)}catch{}return n(a.toString())}t.exports=o}}),r5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(Lr(),wr(Hc)),n=Z6r(),o=X6r(),s=t5r(),i=process.platform==="win32",a=/\.(?:com|exe)$/i,l=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function c(m){m.file=n(m);const h=m.file&&s(m.file);return h?(m.args.unshift(m.file),m.command=h,n(m)):m.file}function u(m){if(!i)return m;const h=c(m),g=!a.test(h);if(m.options.forceShell||g){const y=l.test(h);m.command=r.normalize(m.command),m.command=o.command(m.command),m.args=m.args.map(_=>o.argument(_,y));const v=[m.command].concat(m.args).join(" ");m.args=["/d","/s","/c",`"${v}"`],m.command=process.env.comspec||"cmd.exe",m.options.windowsVerbatimArguments=!0}return m}function d(m,h,g){h&&!Array.isArray(h)&&(g=h,h=null),h=h?h.slice(0):[],g=Object.assign({},g);const y={command:m,args:h,options:g,file:void 0,original:{command:m,args:h}};return g.shell?y:u(y)}t.exports=d}}),n5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js"(e,t){"use strict";var r=process.platform==="win32";function n(a,l){return Object.assign(new Error(`${l} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${l} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,l){if(!r)return;const c=a.emit;a.emit=function(u,d){if(u==="exit"){const m=s(d,l);if(m)return c.call(a,"error",m)}return c.apply(a,arguments)}}function s(a,l){return r&&a===1&&!l.file?n(l.original,"spawn"):null}function i(a,l){return r&&a===1&&!l.file?n(l.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:s,verifyENOENTSync:i,notFoundError:n}}}),o5r=gr({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(Lq(),wr(r1e)),n=r5r(),o=n5r();function s(a,l,c){const u=n(a,l,c),d=r.spawn(u.command,u.args,u.options);return o.hookChildProcess(d,u),d}function i(a,l,c){const u=n(a,l,c),d=r.spawnSync(u.command,u.args,u.options);return d.error=d.error||o.verifyENOENTSync(d.status,u),d}t.exports=s,t.exports.spawn=s,t.exports.sync=i,t.exports._parse=n,t.exports._enoent=o}}),gk,s5r,i5r,a5r,l5r,DN,O4t,Uee,c5r,u5r,d5r,p5r,m5r=S({"node-stub:node:process"(){gk={},s5r=globalThis.crypto,i5r=globalThis.ReadableStream||class{},a5r=globalThis.URL,l5r=globalThis.URLSearchParams,DN=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},DN.custom=Symbol.for("nodejs.util.inspect.custom"),DN.colors={},DN.styles={},O4t=globalThis.TextDecoder,Uee=globalThis.TextEncoder,c5r=globalThis.performance||{now:()=>Date.now()},u5r=globalThis.Buffer||class extends Uint8Array{static from(t,r){if(typeof t=="string"){const n=(r||"utf8").toLowerCase();if(n==="base64"){const o=atob(t),s=new Uint8Array(o.length);for(let i=0;i<o.length;i++)s[i]=o.charCodeAt(i);return s}if(n==="hex"){const o=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2)o[s/2]=parseInt(t.substr(s,2),16);return o}return new Uee().encode(t)}return new Uint8Array(t)}static alloc(t){return new Uint8Array(t)}static isBuffer(t){return t instanceof Uint8Array}static concat(t){const r=t.reduce((s,i)=>s+i.length,0),n=new Uint8Array(r);let o=0;for(const s of t)n.set(s,o),o+=s.length;return n}static byteLength(t,r){return r==="base64"?Math.ceil(t.length*3/4):new Uee().encode(t).length}toString(t){const r=(t||"utf8").toLowerCase();if(r==="hex")return Array.from(new Uint8Array(this.buffer,this.byteOffset,this.byteLength)).map(n=>n.toString(16).padStart(2,"0")).join("");if(r==="base64"){let n="";for(let o=0;o<this.length;o++)n+=String.fromCharCode(this[o]);return btoa(n)}return new O4t().decode(this)}},d5r=globalThis.clearTimeout,p5r=globalThis.clearInterval}});function h5r(e){return Ag.parse(JSON.parse(e))}function f5r(e){return JSON.stringify(e)+`
|
|
1480
1480
|
`}var N4t,g5r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js"(){lh(),N4t=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
|
|
1481
1481
|
`);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),h5r(t)}clear(){this._buffer=void 0}}}});function y5r(){const e={};for(const t of $4t){const r=gk.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}function v5r(){return"type"in gk}var L4t,$4t,F4t,_5r=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js"(){L4t=sa(o5r(),1),m5r(),tEt(),g5r(),$4t=gk.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],F4t=class{constructor(e){this._readBuffer=new N4t,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new QTt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._process=(0,L4t.default)(this._serverParams.command,this._serverParams.args??[],{env:{...y5r(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:gk.platform==="win32"&&v5r(),cwd:this._serverParams.cwd}),this._process.on("error",r=>{t(r),this.onerror?.(r)}),this._process.on("spawn",()=>{e()}),this._process.on("close",r=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",r=>{this.onerror?.(r)}),this._process.stdout?.on("data",r=>{this._readBuffer.append(r),this.processReadBuffer()}),this._process.stdout?.on("error",r=>{this.onerror?.(r)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{const e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){const e=this._process;this._process=void 0;const t=new Promise(r=>{e.once("close",()=>{r()})});try{e.stdin?.end()}catch{}if(await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([t,new Promise(r=>setTimeout(r,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(t=>{if(!this._process?.stdin)throw new Error("Not connected");const r=f5r(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}}});function w5r(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Bee(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Bee).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Bee(e.cause)}`:e.message:`${e}`}function U4t(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function b5r(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}var zee,jee,ON,fr,Cs,Gn,od,rl,Lg,k_,NN,LN,yk,x_,vk,ch,A_,I_,R_,_k,uu,qee,Gee,Hee,B4t,Vee,Wee,wk,Kee,Jee,bk,T5r=S({"node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"(){dz(),zee=class extends Event{constructor(e,t){var r,n;super(e),this.code=(r=t?.code)!=null?r:void 0,this.message=(n=t?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(U4t(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(U4t(this),t)}},jee=e=>{throw TypeError(e)},ON=(e,t,r)=>t.has(e)||jee("Cannot "+r),fr=(e,t,r)=>(ON(e,t,"read from private field"),r?r.call(e):t.get(e)),Cs=(e,t,r)=>t.has(e)?jee("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Gn=(e,t,r,n)=>(ON(e,t,"write to private field"),t.set(e,r),r),od=(e,t,r)=>(ON(e,t,"access private method"),r),bk=class extends EventTarget{constructor(e,t){var r,n;super(),Cs(this,uu),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Cs(this,rl),Cs(this,Lg),Cs(this,k_),Cs(this,NN),Cs(this,LN),Cs(this,yk),Cs(this,x_),Cs(this,vk,null),Cs(this,ch),Cs(this,A_),Cs(this,I_,null),Cs(this,R_,null),Cs(this,_k,null),Cs(this,Gee,async o=>{var s;fr(this,A_).reset();const{body:i,redirected:a,status:l,headers:c}=o;if(l===204){od(this,uu,wk).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Gn(this,k_,new URL(o.url)):Gn(this,k_,void 0),l!==200){od(this,uu,wk).call(this,`Non-200 status code (${l})`,l);return}if(!(c.get("content-type")||"").startsWith("text/event-stream")){od(this,uu,wk).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(fr(this,rl)===this.CLOSED)return;Gn(this,rl,this.OPEN);const u=new Event("open");if((s=fr(this,_k))==null||s.call(this,u),this.dispatchEvent(u),typeof i!="object"||!i||!("getReader"in i)){od(this,uu,wk).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}const d=new TextDecoder,m=i.getReader();let h=!0;do{const{done:g,value:y}=await m.read();y&&fr(this,A_).feed(d.decode(y,{stream:!g})),g&&(h=!1,fr(this,A_).reset(),od(this,uu,Kee).call(this))}while(h)}),Cs(this,Hee,o=>{Gn(this,ch,void 0),!(o.name==="AbortError"||o.type==="aborted")&&od(this,uu,Kee).call(this,Bee(o))}),Cs(this,Vee,o=>{typeof o.id=="string"&&Gn(this,vk,o.id);const s=new MessageEvent(o.event||"message",{data:o.data,origin:fr(this,k_)?fr(this,k_).origin:fr(this,Lg).origin,lastEventId:o.id||""});fr(this,R_)&&(!o.event||o.event==="message")&&fr(this,R_).call(this,s),this.dispatchEvent(s)}),Cs(this,Wee,o=>{Gn(this,yk,o)}),Cs(this,Jee,()=>{Gn(this,x_,void 0),fr(this,rl)===this.CONNECTING&&od(this,uu,qee).call(this)});try{if(e instanceof URL)Gn(this,Lg,e);else if(typeof e=="string")Gn(this,Lg,new URL(e,b5r()));else throw new Error("Invalid URL")}catch{throw w5r("An invalid or illegal string was specified")}Gn(this,A_,lz({onEvent:fr(this,Vee),onRetry:fr(this,Wee)})),Gn(this,rl,this.CONNECTING),Gn(this,yk,3e3),Gn(this,LN,(r=t?.fetch)!=null?r:globalThis.fetch),Gn(this,NN,(n=t?.withCredentials)!=null?n:!1),od(this,uu,qee).call(this)}get readyState(){return fr(this,rl)}get url(){return fr(this,Lg).href}get withCredentials(){return fr(this,NN)}get onerror(){return fr(this,I_)}set onerror(e){Gn(this,I_,e)}get onmessage(){return fr(this,R_)}set onmessage(e){Gn(this,R_,e)}get onopen(){return fr(this,_k)}set onopen(e){Gn(this,_k,e)}addEventListener(e,t,r){const n=t;super.addEventListener(e,n,r)}removeEventListener(e,t,r){const n=t;super.removeEventListener(e,n,r)}close(){fr(this,x_)&&clearTimeout(fr(this,x_)),fr(this,rl)!==this.CLOSED&&(fr(this,ch)&&fr(this,ch).abort(),Gn(this,rl,this.CLOSED),Gn(this,ch,void 0))}},rl=new WeakMap,Lg=new WeakMap,k_=new WeakMap,NN=new WeakMap,LN=new WeakMap,yk=new WeakMap,x_=new WeakMap,vk=new WeakMap,ch=new WeakMap,A_=new WeakMap,I_=new WeakMap,R_=new WeakMap,_k=new WeakMap,uu=new WeakSet,qee=function(){Gn(this,rl,this.CONNECTING),Gn(this,ch,new AbortController),fr(this,LN)(fr(this,Lg),od(this,uu,B4t).call(this)).then(fr(this,Gee)).catch(fr(this,Hee))},Gee=new WeakMap,Hee=new WeakMap,B4t=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...fr(this,vk)?{"Last-Event-ID":fr(this,vk)}:void 0},cache:"no-store",signal:(e=fr(this,ch))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Vee=new WeakMap,Wee=new WeakMap,wk=function(e,t){var r;fr(this,rl)!==this.CLOSED&&Gn(this,rl,this.CLOSED);const n=new zee("error",{code:t,message:e});(r=fr(this,I_))==null||r.call(this,n),this.dispatchEvent(n)},Kee=function(e,t){var r;if(fr(this,rl)===this.CLOSED)return;Gn(this,rl,this.CONNECTING);const n=new zee("error",{code:t,message:e});(r=fr(this,I_))==null||r.call(this,n),this.dispatchEvent(n),Gn(this,x_,setTimeout(fr(this,Jee),fr(this,yk)))},Jee=new WeakMap,bk.CONNECTING=0,bk.OPEN=1,bk.CLOSED=2}});function $N(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function z4t(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...$N(t.headers),...$N(n.headers)}:t.headers};return e(r,o)}:e}var j4t=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js"(){}}),$g,Js,q4t,E5r,S5r,C5r,k5r,x5r,A5r,I5r,R5r,M5r,P5r,D5r,O5r,N5r,L5r,$5r,F5r,U5r,B5r,z5r,j5r,q5r,G5r,H5r,V5r,W5r,K5r,J5r,Y5r,Z5r,X5r,Q5r,eBr,tBr,rBr,nBr,oBr,sBr,iBr,aBr,lBr,cBr,uBr,dBr,pBr,mBr,hBr,fBr=S({"npm-stub:pkce-challenge"(){$g={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:$g.get}):new Proxy(function(...r){return new Proxy({},{get:$g.get})},{get:$g.get,apply(r,n,o){return new Proxy({},{get:$g.get})},construct(r,n){return new Proxy({},{get:$g.get})}})}},Js=new Proxy({},$g),q4t=Js,{BedrockClient:E5r,ListFoundationModelsCommand:S5r,BedrockRuntimeClient:C5r,ConverseCommand:k5r,ConverseStreamCommand:x5r,ImageFormat:A5r,InvokeModelCommand:I5r}=Js,{SageMakerRuntimeClient:R5r,InvokeEndpointCommand:M5r,InvokeEndpointWithResponseStreamCommand:P5r}=Js,{GoogleAuth:D5r,VertexAI:O5r,TextToSpeechClient:N5r}=Js,{Webhook:L5r}=Js,{Hippocampus:$5r,HippocampusConfig:F5r}=Js,{createClient:U5r}=Js,{Queue:B5r,Worker:z5r,Job:j5r,QueueScheduler:q5r,FlowProducer:G5r}=Js,{Cron:H5r}=Js,{parseBuffer:V5r,selectCover:W5r}=Js,{extractRawText:K5r,convertToHtml:J5r}=Js,{Hono:Y5r}=Js,{cors:Z5r,HTTPException:X5r,logger:Q5r,secureHeaders:eBr,streamSSE:tBr,timeout:rBr}=Js,nBr=globalThis.fetch,oBr=globalThis.Request,sBr=globalThis.Response,iBr=globalThis.Headers,aBr=globalThis.FormData,lBr=globalThis.File,cBr=globalThis.Blob,uBr=Js.Agent,dBr=Js.Pool,pBr=Js.Client,mBr=Js.Dispatcher,hBr=Js.MockAgent}}),mi,G4t,Yee,H4t,V4t,W4t,K4t,Zee,J4t,Y4t,Z4t,gBr,yBr,X4t=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js"(){ut(),mi=eB().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:gB.custom,message:"URL must be parseable",fatal:!0}),uI}).refine(e=>{const t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),G4t=Ps({resource:le().url(),authorization_servers:rt(mi).optional(),jwks_uri:le().url().optional(),scopes_supported:rt(le()).optional(),bearer_methods_supported:rt(le()).optional(),resource_signing_alg_values_supported:rt(le()).optional(),resource_name:le().optional(),resource_documentation:le().optional(),resource_policy_uri:le().url().optional(),resource_tos_uri:le().url().optional(),tls_client_certificate_bound_access_tokens:en().optional(),authorization_details_types_supported:rt(le()).optional(),dpop_signing_alg_values_supported:rt(le()).optional(),dpop_bound_access_tokens_required:en().optional()}),Yee=Ps({issuer:le(),authorization_endpoint:mi,token_endpoint:mi,registration_endpoint:mi.optional(),scopes_supported:rt(le()).optional(),response_types_supported:rt(le()),response_modes_supported:rt(le()).optional(),grant_types_supported:rt(le()).optional(),token_endpoint_auth_methods_supported:rt(le()).optional(),token_endpoint_auth_signing_alg_values_supported:rt(le()).optional(),service_documentation:mi.optional(),revocation_endpoint:mi.optional(),revocation_endpoint_auth_methods_supported:rt(le()).optional(),revocation_endpoint_auth_signing_alg_values_supported:rt(le()).optional(),introspection_endpoint:le().optional(),introspection_endpoint_auth_methods_supported:rt(le()).optional(),introspection_endpoint_auth_signing_alg_values_supported:rt(le()).optional(),code_challenge_methods_supported:rt(le()).optional(),client_id_metadata_document_supported:en().optional()}),H4t=Ps({issuer:le(),authorization_endpoint:mi,token_endpoint:mi,userinfo_endpoint:mi.optional(),jwks_uri:mi,registration_endpoint:mi.optional(),scopes_supported:rt(le()).optional(),response_types_supported:rt(le()),response_modes_supported:rt(le()).optional(),grant_types_supported:rt(le()).optional(),acr_values_supported:rt(le()).optional(),subject_types_supported:rt(le()),id_token_signing_alg_values_supported:rt(le()),id_token_encryption_alg_values_supported:rt(le()).optional(),id_token_encryption_enc_values_supported:rt(le()).optional(),userinfo_signing_alg_values_supported:rt(le()).optional(),userinfo_encryption_alg_values_supported:rt(le()).optional(),userinfo_encryption_enc_values_supported:rt(le()).optional(),request_object_signing_alg_values_supported:rt(le()).optional(),request_object_encryption_alg_values_supported:rt(le()).optional(),request_object_encryption_enc_values_supported:rt(le()).optional(),token_endpoint_auth_methods_supported:rt(le()).optional(),token_endpoint_auth_signing_alg_values_supported:rt(le()).optional(),display_values_supported:rt(le()).optional(),claim_types_supported:rt(le()).optional(),claims_supported:rt(le()).optional(),service_documentation:le().optional(),claims_locales_supported:rt(le()).optional(),ui_locales_supported:rt(le()).optional(),claims_parameter_supported:en().optional(),request_parameter_supported:en().optional(),request_uri_parameter_supported:en().optional(),require_request_uri_registration:en().optional(),op_policy_uri:mi.optional(),op_tos_uri:mi.optional(),client_id_metadata_document_supported:en().optional()}),V4t=ot({...H4t.shape,...Yee.pick({code_challenge_methods_supported:!0}).shape}),W4t=ot({access_token:le(),id_token:le().optional(),token_type:le(),expires_in:vB.number().optional(),scope:le().optional(),refresh_token:le().optional()}).strip(),K4t=ot({error:le(),error_description:le().optional(),error_uri:le().optional()}),Zee=mi.optional().or(Tt("").transform(()=>{})),J4t=ot({redirect_uris:rt(mi),token_endpoint_auth_method:le().optional(),grant_types:rt(le()).optional(),response_types:rt(le()).optional(),client_name:le().optional(),client_uri:mi.optional(),logo_uri:Zee,scope:le().optional(),contacts:rt(le()).optional(),tos_uri:Zee,policy_uri:le().optional(),jwks_uri:mi.optional(),jwks:tB().optional(),software_id:le().optional(),software_version:le().optional(),software_statement:le().optional()}).strip(),Y4t=ot({client_id:le(),client_secret:le().optional(),client_id_issued_at:Ir().optional(),client_secret_expires_at:Ir().optional()}).strip(),Z4t=J4t.merge(Y4t),gBr=ot({error:le(),error_description:le().optional()}).strip(),yBr=ot({token:le(),token_type_hint:le().optional()}).strip()}});function vBr(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function _Br({requestedResource:e,configuredResource:t}){const r=typeof e=="string"?new URL(e):new URL(e.href),n=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;const o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var wBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js"(){}}),Ys,FN,Tk,Ek,Sk,UN,BN,zN,Fg,jN,qN,GN,HN,VN,WN,Ck,KN,JN,Q4t,bBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js"(){Ys=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},FN=class extends Ys{},FN.errorCode="invalid_request",Tk=class extends Ys{},Tk.errorCode="invalid_client",Ek=class extends Ys{},Ek.errorCode="invalid_grant",Sk=class extends Ys{},Sk.errorCode="unauthorized_client",UN=class extends Ys{},UN.errorCode="unsupported_grant_type",BN=class extends Ys{},BN.errorCode="invalid_scope",zN=class extends Ys{},zN.errorCode="access_denied",Fg=class extends Ys{},Fg.errorCode="server_error",jN=class extends Ys{},jN.errorCode="temporarily_unavailable",qN=class extends Ys{},qN.errorCode="unsupported_response_type",GN=class extends Ys{},GN.errorCode="unsupported_token_type",HN=class extends Ys{},HN.errorCode="invalid_token",VN=class extends Ys{},VN.errorCode="method_not_allowed",WN=class extends Ys{},WN.errorCode="too_many_requests",Ck=class extends Ys{},Ck.errorCode="invalid_client_metadata",KN=class extends Ys{},KN.errorCode="insufficient_scope",JN=class extends Ys{},JN.errorCode="invalid_target",Q4t={[FN.errorCode]:FN,[Tk.errorCode]:Tk,[Ek.errorCode]:Ek,[Sk.errorCode]:Sk,[UN.errorCode]:UN,[BN.errorCode]:BN,[zN.errorCode]:zN,[Fg.errorCode]:Fg,[jN.errorCode]:jN,[qN.errorCode]:qN,[GN.errorCode]:GN,[HN.errorCode]:HN,[VN.errorCode]:VN,[WN.errorCode]:WN,[Ck.errorCode]:Ck,[KN.errorCode]:KN,[JN.errorCode]:JN}}});function TBr(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function EBr(e,t){const r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&TBr(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}function SBr(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":CBr(o,s,r);return;case"client_secret_post":kBr(o,s,n);return;case"none":xBr(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function CBr(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}function kBr(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function xBr(e,t){t.set("client_id",e)}async function eOt(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=K4t.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=Q4t[o]||Fg;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Fg(o)}}async function Ug(e,t){try{return await Xee(e,t)}catch(r){if(r instanceof Tk||r instanceof Sk)return await e.invalidateCredentials?.("all"),await Xee(e,t);if(r instanceof Ek)return await e.invalidateCredentials?.("tokens"),await Xee(e,t);throw r}}async function Xee(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){const i=await e.discoveryState?.();let a,l,c,u=o;if(!u&&i?.resourceMetadataUrl&&(u=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(l=i.authorizationServerUrl,a=i.resourceMetadata,c=i.authorizationServerMetadata??await nOt(l,{fetchFn:s}),!a)try{a=await tOt(t,{resourceMetadataUrl:u},s)}catch{}(c!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:c})}else{const T=await OBr(t,{resourceMetadataUrl:u,fetchFn:s});l=T.authorizationServerUrl,c=T.authorizationServerMetadata,a=T.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:c})}const d=await IBr(t,e,a),m=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope;let h=await Promise.resolve(e.clientInformation());if(!h){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const T=c?.client_id_metadata_document_supported===!0,k=e.clientMetadataUrl;if(k&&!ABr(k))throw new Ck(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${k}`);if(T&&k)h={client_id:k},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const I=await UBr(l,{metadata:c,clientMetadata:e.clientMetadata,scope:m,fetchFn:s});await e.saveClientInformation(I),h=I}}const g=!e.redirectUrl;if(r!==void 0||g){const T=await FBr(e,l,{metadata:c,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens(T),"AUTHORIZED"}const y=await e.tokens();if(y?.refresh_token)try{const T=await $Br(l,{metadata:c,clientInformation:h,refreshToken:y.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(T),"AUTHORIZED"}catch(T){if(!(!(T instanceof Ys)||T instanceof Fg))throw T}const v=e.state?await e.state():void 0,{authorizationUrl:_,codeVerifier:b}=await NBr(l,{metadata:c,clientInformation:h,state:v,redirectUrl:e.redirectUrl,scope:m,resource:d});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(_),"REDIRECT"}function ABr(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function IBr(e,t,r){const n=vBr(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!_Br({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function YN(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=Qee(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=Qee(e,"scope")||void 0,a=Qee(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Qee(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function tOt(e,t,r=fetch){const n=await PBr(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return G4t.parse(await n.json())}async function ete(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?ete(e,void 0,r):void 0;throw n}}function RBr(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function rOt(e,t,r=fetch){return await ete(e,{"MCP-Protocol-Version":t},r)}function MBr(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function PBr(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??uk;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const l=RBr(t,o.pathname);i=new URL(l,n?.metadataServerUrl??o),i.search=o.search}let a=await rOt(i,s,r);if(!n?.metadataUrl&&MBr(a,o.pathname)){const l=new URL(`/.well-known/${t}`,o);a=await rOt(l,s,r)}return a}function DBr(e){const t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),n;let o=t.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,t.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,t.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,t.origin),type:"oidc"}),n}async function nOt(e,{fetchFn:t=fetch,protocolVersion:r=uk}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=DBr(e);for(const{url:s,type:i}of o){const a=await ete(s,n,t);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?Yee.parse(await a.json()):V4t.parse(await a.json())}}}async function OBr(e,t){let r,n;try{r=await tOt(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",e)));const o=await nOt(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function NBr(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(ZN))throw new Error(`Incompatible auth server: does not support response type ${ZN}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(XN))throw new Error(`Incompatible auth server: does not support code challenge method ${XN}`)}else a=new URL("/authorize",e);const l=await q4t(),c=l.code_verifier,u=l.code_challenge;return a.searchParams.set("response_type",ZN),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",XN),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:c}}function LBr(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function oOt(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(l,r,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],d=EBr(n,u);SBr(d,n,l,r)}const c=await(i??fetch)(a,{method:"POST",headers:l,body:r});if(!c.ok)throw await eOt(c);return W4t.parse(await c.json())}async function $Br(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),l=await oOt(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...l}}async function FBr(e,t,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){const i=e.clientMetadata.scope;let a;if(e.prepareTokenRequest&&(a=await e.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");const c=await e.codeVerifier();a=LBr(o,c,e.redirectUrl)}const l=await e.clientInformation();return oOt(t,{metadata:r,tokenRequestParams:a,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function UBr(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:o}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);const i=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await eOt(i);return Z4t.parse(await i.json())}var kc,ZN,XN,sOt=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js"(){fBr(),lh(),X4t(),X4t(),wBr(),bBr(),kc=class extends Error{constructor(e){super(e??"Unauthorized")}},ZN="code",XN="S256"}}),iOt,aOt,BBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js"(){T5r(),j4t(),lh(),sOt(),iOt=class extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}},aOt=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=z4t(t?.fetch,t?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new kc("No auth provider");let e;try{e=await Ug(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new kc;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=$N(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,r)=>{this._eventSource=new bk(this._url.href,{...this._eventSourceInit,fetch:async(n,o)=>{const s=await this._commonHeaders();s.set("Accept","text/event-stream");const i=await e(n,{...o,headers:s});if(i.status===401&&i.headers.has("www-authenticate")){const{resourceMetadataUrl:a,scope:l}=YN(i);this._resourceMetadataUrl=a,this._scope=l}return i}}),this._abortController=new AbortController,this._eventSource.onerror=n=>{if(n.code===401&&this._authProvider){this._authThenStart().then(t,r);return}const o=new iOt(n.code,n.message,n);r(o),this.onerror?.(o)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",n=>{const o=n;try{if(this._endpoint=new URL(o.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(s){r(s),this.onerror?.(s),this.close();return}t()}),this._eventSource.onmessage=n=>{const o=n;let s;try{s=Ag.parse(JSON.parse(o.data))}catch(i){this.onerror?.(i);return}this.onmessage?.(s)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new kc("No auth provider");if(await Ug(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kc("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const t=await this._commonHeaders();t.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._endpoint,r);if(!n.ok){const o=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){const{resourceMetadataUrl:s,scope:i}=YN(n);if(this._resourceMetadataUrl=s,this._scope=i,await Ug(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kc;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${o}`)}await n.body?.cancel()}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(e){this._protocolVersion=e}}}}),lOt,cOt,zBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/websocket.js"(){lh(),lOt="mcp",cOt=class{constructor(e){this._url=e}start(){if(this._socket)throw new Error("WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{this._socket=new WebSocket(this._url,lOt),this._socket.onerror=r=>{const n="error"in r?r.error:new Error(`WebSocket error: ${JSON.stringify(r)}`);t(n),this.onerror?.(n)},this._socket.onopen=()=>{e()},this._socket.onclose=()=>{this.onclose?.()},this._socket.onmessage=r=>{let n;try{n=Ag.parse(JSON.parse(r.data))}catch(o){this.onerror?.(o);return}this.onmessage?.(n)}})}async close(){this._socket?.close()}send(e){return new Promise((t,r)=>{if(!this._socket){r(new Error("Not connected"));return}this._socket?.send(JSON.stringify(e)),t()})}}}}),uOt,Bg,dOt,jBr=S({"node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_@cfworker+json-schema@4.1.1_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js"(){j4t(),lh(),sOt(),jye(),uOt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Bg=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},dOt=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=z4t(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??uOt}async _authThenStart(){if(!this._authProvider)throw new kc("No auth provider");let e;try{e=await Ug(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new kc;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(e.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=$N(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const n=await(this._fetch??fetch)(this._url,{method:"GET",headers:r,signal:this._abortController?.signal});if(!n.ok){if(await n.body?.cancel(),n.status===401&&this._authProvider)return await this._authThenStart();if(n.status===405)return;throw new Bg(n.status,`Failed to open SSE stream: ${n.statusText}`)}this._handleSseStream(n.body,e,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const t=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(r,e),n)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r){this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const n=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(o=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${o instanceof Error?o.message:String(o)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:o}=t;let s,i=!1,a=!1;(async()=>{try{const c=e.pipeThrough(new TextDecoderStream).pipeThrough(new pz({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){const{value:m,done:h}=await c.read();if(h)break;if(m.id&&(s=m.id,i=!0,n?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{const g=Ag.parse(JSON.parse(m.data));__(g)&&(a=!0,o!==void 0&&(g.id=o)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(r||i)&&!a&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:o},0)}catch(c){if(this.onerror?.(new Error(`SSE stream disconnected: ${c}`)),(r||i)&&!a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:o},0)}catch(m){this.onerror?.(new Error(`Failed to reconnect: ${m instanceof Error?m.message:String(m)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new kc("No auth provider");if(await Ug(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kc("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:r,onresumptiontoken:n}=t||{};if(r){this._startOrAuthSse({resumptionToken:r,replayMessageId:hN(e)?e.id:void 0}).catch(d=>this.onerror?.(d));return}const o=await this._commonHeaders();o.set("content-type","application/json"),o.set("accept","application/json, text/event-stream");const s={...this._requestInit,method:"POST",headers:o,body:JSON.stringify(e),signal:this._abortController?.signal},i=await(this._fetch??fetch)(this._url,s),a=i.headers.get("mcp-session-id");if(a&&(this._sessionId=a),!i.ok){const d=await i.text().catch(()=>null);if(i.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Bg(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:h}=YN(i);if(this._resourceMetadataUrl=m,this._scope=h,await Ug(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new kc;return this._hasCompletedAuthFlow=!0,this.send(e)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:h,error:g}=YN(i);if(g==="insufficient_scope"){const y=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===y)throw new Bg(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=y??void 0,await Ug(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new kc;return this.send(e)}}throw new Bg(i.status,`Error POSTing to endpoint: ${d}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),uPt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(d=>this.onerror?.(d));return}const c=(Array.isArray(e)?e:[e]).filter(d=>"method"in d&&"id"in d&&d.id!==void 0).length>0,u=i.headers.get("content-type");if(c)if(u?.includes("text/event-stream"))this._handleSseStream(i.body,{onresumptiontoken:n},!1);else if(u?.includes("application/json")){const d=await i.json(),m=Array.isArray(d)?d.map(h=>Ag.parse(h)):[Ag.parse(d)];for(const h of m)this.onmessage?.(h)}else throw await i.body?.cancel(),new Bg(-1,`Unexpected content type: ${u}`);else await i.body?.cancel()}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await(this._fetch??fetch)(this._url,t);if(await r.body?.cancel(),!r.ok&&r.status!==405)throw new Bg(r.status,`Failed to terminate session: ${r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}}}),pOt,tte,rte,kk,nte=S({"src/lib/mcp/mcpCircuitBreaker.ts"(){"use strict";vn(),er(),q(),vt(),vt(),pOt=Math.max(1e4,Number(process.env.MCP_OPERATION_TIMEOUT)||6e4),tte=class extends nn{constructor(e,t={}){super(),this.name=e,this.config={failureThreshold:t.failureThreshold??5,resetTimeout:t.resetTimeout??6e4,halfOpenMaxCalls:t.halfOpenMaxCalls??3,operationTimeout:t.operationTimeout??pOt,minimumCallsBeforeCalculation:t.minimumCallsBeforeCalculation??10,statisticsWindowSize:t.statisticsWindowSize??3e5},this.cleanupTimer=setInterval(()=>this.cleanupCallHistory(),6e4)}name;state="closed";config;callHistory=[];lastFailureTime=0;halfOpenCalls=0;lastStateChange=new Date;cleanupTimer;async execute(e){const t=Date.now();try{if(this.state==="open"){const n=this.config.resetTimeout-(Date.now()-this.lastFailureTime);if(n>0)throw new Xp({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:n,breakerState:"open",failureCount:this.getStats().failedCalls});this.changeState("half-open","Reset timeout reached")}if(this.state==="half-open"&&this.halfOpenCalls>=this.config.halfOpenMaxCalls)throw this.lastFailureTime=Date.now(),this.changeState("open","Half-open call limit reached, reverting to open"),new Xp({breakerName:this.name,retryAfter:new Date(this.lastFailureTime+this.config.resetTimeout),retryAfterMs:this.config.resetTimeout,breakerState:"open",failureCount:this.getStats().failedCalls});if(this.state==="half-open"){const n=_t.getActiveSpan();n&&n.addEvent("circuit.half_open_test",{"circuit.name":this.name,"circuit.half_open_call":this.halfOpenCalls+1,"circuit.half_open_max_calls":this.config.halfOpenMaxCalls})}const r=await Promise.race([e(),this.timeoutPromise(this.config.operationTimeout)]);return this.recordCall(!0,Date.now()-t),this.state==="half-open"&&(this.halfOpenCalls++,this.halfOpenCalls>=this.config.halfOpenMaxCalls&&this.changeState("closed","Half-open test successful")),r}catch(r){const n=Date.now()-t;this.recordCall(!1,n);const o=r instanceof Error?r.message:String(r);throw this.emit("callFailure",{error:o,duration:n,timestamp:new Date}),this.state==="half-open"?this.changeState("open",`Half-open test failed: ${o}`):this.state==="closed"&&this.checkFailureThreshold(),r}}recordCall(e,t){const r=Date.now();this.callHistory.push({timestamp:r,success:e,duration:t}),e&&this.emit("callSuccess",{duration:t,timestamp:new Date}),e||(this.lastFailureTime=r)}checkFailureThreshold(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(o=>o.timestamp>=e);if(t.length<this.config.minimumCallsBeforeCalculation)return;const r=t.filter(o=>!o.success).length,n=r/t.length;de.debug(`[CircuitBreaker:${this.name}] Failure rate: ${(n*100).toFixed(1)}% (${r}/${t.length})`),r>=this.config.failureThreshold&&(this.changeState("open",`Failure threshold exceeded: ${r} failures`),this.emit("circuitOpen",{failureRate:n,totalCalls:t.length,timestamp:new Date}))}changeState(e,t){const r=this.state;this.state=e,this.lastStateChange=new Date;const n=_t.getActiveSpan();n&&n.addEvent("circuit.state_change",{"circuit.name":this.name,"circuit.from_state":r,"circuit.to_state":e,"circuit.reason":t.slice(0,128),"circuit.failure_count":this.callHistory.filter(o=>!o.success).length}),e==="half-open"?(this.halfOpenCalls=0,this.emit("circuitHalfOpen",{timestamp:new Date})):e==="closed"&&(this.halfOpenCalls=0,this.emit("circuitClosed",{timestamp:new Date})),de.info(`[CircuitBreaker:${this.name}] State changed: ${r} -> ${e} (${t})`),this.emit("stateChange",{oldState:r,newState:e,reason:t,timestamp:new Date})}timeoutPromise(e){return new Promise((t,r)=>{setTimeout(()=>{r(new Error(`Operation timed out after ${e}ms`))},e)})}cleanupCallHistory(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.length;this.callHistory=this.callHistory.filter(n=>n.timestamp>=e);const r=t-this.callHistory.length;r>0&&de.debug(`[CircuitBreaker:${this.name}] Cleaned up ${r} old call records`)}getStats(){const e=Date.now()-this.config.statisticsWindowSize,t=this.callHistory.filter(s=>s.timestamp>=e),r=t.filter(s=>s.success).length,n=t.length-r,o=t.length>0?n/t.length:0;return{state:this.state,totalCalls:this.callHistory.length,successfulCalls:this.callHistory.filter(s=>s.success).length,failedCalls:this.callHistory.filter(s=>!s.success).length,failureRate:o,windowCalls:t.length,lastStateChange:this.lastStateChange,nextRetryTime:this.state==="open"?new Date(this.lastFailureTime+this.config.resetTimeout):void 0,halfOpenCalls:this.halfOpenCalls}}reset(){this.changeState("closed","Manual reset"),this.callHistory=[],this.lastFailureTime=0,this.halfOpenCalls=0}forceOpen(e="Manual force open"){this.changeState("open",e),this.lastFailureTime=Date.now()}getName(){return this.name}isOpen(){return this.state==="open"}isClosed(){return this.state==="closed"}isHalfOpen(){return this.state==="half-open"}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0,de.debug(`[CircuitBreaker:${this.name}] Cleanup timer cleared`)),this.removeAllListeners(),this.callHistory=[],de.debug(`[CircuitBreaker:${this.name}] Destroyed and cleaned up`)}},rte=class{breakers=new Map;getBreaker(e,t){if(!this.breakers.has(e)){const n=new tte(e,t);this.breakers.set(e,n),de.debug(`[CircuitBreakerManager] Created circuit breaker: ${e}`)}const r=this.breakers.get(e);if(!r)throw new Error(`Circuit breaker ${e} not found after creation`);return r}removeBreaker(e){const t=this.breakers.get(e);return t?(t.destroy(),this.breakers.delete(e),de.debug(`[CircuitBreakerManager] Removed and cleaned up circuit breaker: ${e}`),!0):!1}getBreakerNames(){return Array.from(this.breakers.keys())}getAllStats(){const e={};for(const[t,r]of this.breakers)e[t]=r.getStats();return e}resetAll(){for(const e of this.breakers.values())e.reset();de.info("[CircuitBreakerManager] Reset all circuit breakers")}getHealthSummary(){let e=0,t=0,r=0;const n=[];for(const[o,s]of this.breakers)switch(s.getStats().state){case"closed":e++;break;case"open":t++,n.push(o);break;case"half-open":r++;break}return{totalBreakers:this.breakers.size,closedBreakers:e,openBreakers:t,halfOpenBreakers:r,unhealthyBreakers:n}}destroyAll(){for(const e of this.breakers.values())e.destroy();this.breakers.clear(),de.info("[CircuitBreakerManager] Destroyed all circuit breakers")}},kk=new rte}});function qBr(e){return new Promise(t=>setTimeout(t,e))}function QN(e,t=sd){return t.retryableStatusCodes.includes(e)}function mOt(e,t=sd){if(!e||typeof e!="object")return!1;const r=e;if(qr(e))return!1;if(r.name==="TimeoutError"||r.code==="TIMEOUT"||r.code==="ETIMEDOUT"||r.code==="ECONNRESET"||r.code==="ENOTFOUND"||r.code==="ECONNREFUSED"||r.code==="ECONNABORTED"||r.code==="EPIPE"||r.code==="ENETUNREACH"||r.code==="EHOSTUNREACH")return!0;if(r.name==="TypeError"&&typeof r.message=="string"){const n=r.message.toLowerCase();if(n.includes("fetch")||n.includes("network")||n.includes("connection"))return!0}return typeof r.status=="number"?QN(r.status,t):r.response&&typeof r.response=="object"&&typeof r.response.status=="number"?QN(r.response.status,t):typeof r.statusCode=="number"?QN(r.statusCode,t):!1}async function hOt(e,t={}){const r={...sd,...t},{traceId:n,parentSpanId:o}=Kv(),s=Oe.createSpan("mcp.transport","mcp.retry",{"mcp.transport":"http","mcp.operation":"retry","mcp.maxAttempts":r.maxAttempts},o,n),i=Date.now();let a,l=0;for(let u=1;u<=r.maxAttempts;u++){l=u;try{const d=await e();s.durationMs=Date.now()-i,s.attributes["mcp.retryAttempt"]=u;const m=Oe.endSpan(s,1);return dt().recordSpan(m),d}catch(d){if(a=d,u===r.maxAttempts){f.debug(`HTTP retry: All ${r.maxAttempts} attempts exhausted`);break}if(!mOt(d,r)){f.debug("HTTP retry: Non-retryable error encountered",d instanceof Error?d.message:String(d));break}const m=Got(u,r.initialDelay,r.backoffMultiplier,r.maxDelay,!0),h=d instanceof Error?d.message:String(d);f.warn(`HTTP retry: Attempt ${u}/${r.maxAttempts} failed: ${h}. Retrying in ${Math.round(m)}ms...`),await qBr(m)}}s.durationMs=Date.now()-i,s.attributes["mcp.retryAttempt"]=l;const c=Oe.endSpan(s,2);throw c.statusMessage=a instanceof Error?a.message:String(a),dt().recordSpan(c),a}var sd,fOt=S({"src/lib/mcp/httpRetryHandler.ts"(){"use strict";ct(),Jot(),q(),Qn(),Jv(),sd={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:[408,429,500,502,503,504]}}}),ote,ste,ite,ate,gOt=S({"src/lib/mcp/httpRateLimiter.ts"(){"use strict";q(),_q(),Qn(),Jv(),ote={requestsPerWindow:60,windowMs:6e4,useTokenBucket:!0,refillRate:1,maxBurst:10},ste=class{tokens;lastRefill;config;waitQueue=[];processingQueue=!1;constructor(e={}){this.config={...ote,...e},this.tokens=this.config.maxBurst,this.lastRefill=Date.now(),de.debug("[HTTPRateLimiter] Initialized with config:",{requestsPerWindow:this.config.requestsPerWindow,windowMs:this.config.windowMs,useTokenBucket:this.config.useTokenBucket,refillRate:this.config.refillRate,maxBurst:this.config.maxBurst})}refillTokens(){const e=Date.now(),n=(e-this.lastRefill)/1e3*this.config.refillRate;if(n>=1){const o=this.tokens;this.tokens=Math.min(this.config.maxBurst,this.tokens+n),this.lastRefill=e,this.tokens>o&&de.debug(`[HTTPRateLimiter] Refilled tokens: ${o.toFixed(2)} -> ${this.tokens.toFixed(2)} (+${n.toFixed(2)})`)}}async acquire(){const{traceId:e,parentSpanId:t}=Kv(),r=Oe.createSpan("mcp.transport","mcp.rateLimit",{"mcp.transport":"http","mcp.operation":"rateLimit","mcp.rateLimit.tokensAvailable":this.tokens,"mcp.rateLimit.maxBurst":this.config.maxBurst},t,e),n=Date.now();try{if(this.tryAcquire()){r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!1;const s=Oe.endSpan(r,1);dt().recordSpan(s);return}await new Promise((s,i)=>{this.waitQueue.push({resolve:s,reject:i}),de.debug(`[HTTPRateLimiter] Request queued, queue length: ${this.waitQueue.length}`),this.processingQueue||this.processQueue()}),r.durationMs=Date.now()-n,r.attributes["mcp.rateLimit.waited"]=!0;const o=Oe.endSpan(r,1);dt().recordSpan(o)}catch(o){r.durationMs=Date.now()-n;const s=Oe.endSpan(r,2);throw s.statusMessage=o instanceof Error?o.message:String(o),dt().recordSpan(s),o}}async processQueue(){if(!this.processingQueue){for(this.processingQueue=!0;this.waitQueue.length>0;)if(this.refillTokens(),this.tokens>=1){const e=this.waitQueue.shift();e&&(this.tokens-=1,de.debug(`[HTTPRateLimiter] Token granted from queue, remaining: ${this.tokens.toFixed(2)}, queue: ${this.waitQueue.length}`),e.resolve())}else{const t=(1-this.tokens)/this.config.refillRate*1e3,r=Math.max(10,Math.ceil(t));de.debug(`[HTTPRateLimiter] Waiting ${r}ms for token refill`),await this.sleep(r)}this.processingQueue=!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}tryAcquire(){return this.refillTokens(),this.tokens>=1?(this.tokens-=1,de.debug(`[HTTPRateLimiter] Token acquired, remaining: ${this.tokens.toFixed(2)}`),!0):(de.debug(`[HTTPRateLimiter] No tokens available, current: ${this.tokens.toFixed(2)}`),!1)}handleRateLimitResponse(e){const t=BT(e),r=e.get("Retry-After");if(r&&t!==void 0){const s=parseInt(r,10);if(isNaN(s)){const i=new Date(r);if(!isNaN(i.getTime()))return de.info(`[HTTPRateLimiter] Server requested retry at ${i.toISOString()} (${t}ms)`),t}else return de.info(`[HTTPRateLimiter] Server requested retry after ${s} seconds`),t}const n=e.get("X-RateLimit-Reset");if(n&&t!==void 0){const s=parseInt(n,10);if(!isNaN(s)){const i=s>1e12?s:s*1e3;return de.info(`[HTTPRateLimiter] Rate limit resets at ${new Date(i).toISOString()} (${t}ms)`),t}}return e.get("X-RateLimit-Remaining")==="0"&&t!==void 0?(de.info(`[HTTPRateLimiter] Rate limit exhausted, using default backoff: ${t}ms`),t):t??0}getRemainingTokens(){return this.refillTokens(),this.tokens}reset(){for(this.tokens=this.config.maxBurst,this.lastRefill=Date.now();this.waitQueue.length>0;){const e=this.waitQueue.shift();e&&e.reject(new Error("Rate limiter was reset"))}de.info(`[HTTPRateLimiter] Reset to initial state, tokens: ${this.tokens}`)}getStats(){return this.refillTokens(),{tokens:this.tokens,maxBurst:this.config.maxBurst,refillRate:this.config.refillRate,queueLength:this.waitQueue.length,lastRefill:new Date(this.lastRefill)}}updateConfig(e){Object.assign(this.config,e),de.info("[HTTPRateLimiter] Configuration updated:",e)}getConfig(){return{...this.config}}},ite=class{limiters=new Map;getLimiter(e,t){let r=this.limiters.get(e);return r?t&&r.updateConfig(t):(r=new ste(t),this.limiters.set(e,r),de.debug(`[RateLimiterManager] Created rate limiter for server: ${e}`)),r}hasLimiter(e){return this.limiters.has(e)}removeLimiter(e){const t=this.limiters.get(e);t&&(t.reset(),this.limiters.delete(e),de.debug(`[RateLimiterManager] Removed rate limiter for server: ${e}`))}getServerIds(){return Array.from(this.limiters.keys())}getAllStats(){const e={};for(const[t,r]of this.limiters)e[t]=r.getStats();return e}resetAll(){for(const e of this.limiters.values())e.reset();de.info("[RateLimiterManager] Reset all rate limiters")}destroyAll(){for(const e of this.limiters.values())e.reset();this.limiters.clear(),de.info("[RateLimiterManager] Destroyed all rate limiters")}getHealthSummary(){const e=[];let t=0,r=0;for(const[o,s]of this.limiters){const i=s.getStats();i.queueLength>0&&(e.push(o),t+=i.queueLength),r+=i.tokens}const n=this.limiters.size>0?r/this.limiters.size:0;return{totalLimiters:this.limiters.size,serversWithQueuedRequests:e,totalQueuedRequests:t,averageTokensAvailable:n}}},ate=new ite}});function yOt(e,t=60){if(!e.expiresAt)return!1;const r=t*1e3,n=Date.now();return e.expiresAt-r<=n}function lte(e){return Date.now()+e*1e3}var eL,vOt,_Ot=S({"src/lib/mcp/auth/tokenStorage.ts"(){"use strict";q(),eL=class{tokens=new Map;async getTokens(e){return this.tokens.get(e)??null}async saveTokens(e,t){this.tokens.set(e,t)}async deleteTokens(e){this.tokens.delete(e)}async hasTokens(e){return this.tokens.has(e)}async clearAll(){this.tokens.clear()}get size(){return this.tokens.size}getServerIds(){return Array.from(this.tokens.keys())}},vOt=class{filePath;tokens=new Map;loaded=!1;constructor(e){this.filePath=e}async loadTokens(){if(!this.loaded)try{const t=await(await Promise.resolve().then(()=>(ya(),Nf))).readFile(this.filePath,"utf-8"),r=JSON.parse(t);this.tokens=new Map(Object.entries(r)),this.loaded=!0}catch(e){e instanceof Error&&"code"in e&&e.code!=="ENOENT"&&f.warn(`[FileTokenStorage] Error loading tokens: ${e.message}`),this.tokens=new Map,this.loaded=!0}}async saveToFile(){try{const e=await Promise.resolve().then(()=>(ya(),Nf)),r=(await Promise.resolve().then(()=>(Lr(),Hc))).dirname(this.filePath);await e.mkdir(r,{recursive:!0});const n=Object.fromEntries(this.tokens.entries());await e.writeFile(this.filePath,JSON.stringify(n,null,2),"utf-8")}catch(e){throw f.error(`[FileTokenStorage] Error saving tokens: ${e instanceof Error?e.message:String(e)}`),e}}async getTokens(e){return await this.loadTokens(),this.tokens.get(e)??null}async saveTokens(e,t){await this.loadTokens(),this.tokens.set(e,t),await this.saveToFile()}async deleteTokens(e){await this.loadTokens(),this.tokens.delete(e),await this.saveToFile()}async hasTokens(e){return await this.loadTokens(),this.tokens.has(e)}async clearAll(){this.tokens.clear(),await this.saveToFile()}}}});function GBr(e,t){return new tL({clientId:e.clientId,clientSecret:e.clientSecret,authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,redirectUrl:e.redirectUrl,scope:e.scope,usePKCE:e.usePKCE??!0},t)}var zg,tL,HBr=S({"src/lib/mcp/auth/oauthClientProvider.ts"(){"use strict";Ft(),_Ot(),q(),ct(),zg=3e4,tL=class{config;storage;pendingChallenges=new Map;pendingStates=new Set;constructor(e,t){this.config={...e,usePKCE:e.usePKCE??!0},this.storage=t??new eL}async tokens(e){const t=await this.storage.getTokens(e);if(!t)return null;if(yOt(t)){if(t.refreshToken)try{return await this.refreshTokens(e,t.refreshToken)}catch(r){return f.warn(`[NeuroLinkOAuthProvider] Token refresh failed: ${r instanceof Error?r.message:String(r)}`),await this.storage.deleteTokens(e),null}return await this.storage.deleteTokens(e),null}return t}async saveTokens(e,t){await this.storage.saveTokens(e,t)}async deleteTokens(e){await this.storage.deleteTokens(e)}clientInformation(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.config.redirectUrl}}redirectToAuthorization(e){const t=this.generateState();this.pendingStates.add(t);const r=new URL(this.config.authorizationUrl);r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.config.clientId),r.searchParams.set("redirect_uri",this.config.redirectUrl),r.searchParams.set("state",t),this.config.scope&&r.searchParams.set("scope",this.config.scope);let n;if(this.config.usePKCE){const o=this.generatePKCE();n=o.codeVerifier,this.pendingChallenges.set(t,o),r.searchParams.set("code_challenge",o.codeChallenge),r.searchParams.set("code_challenge_method",o.codeChallengeMethod)}if(this.config.additionalParams)for(const[o,s]of Object.entries(this.config.additionalParams))r.searchParams.set(o,s);return{url:r.toString(),state:t,codeVerifier:n}}async exchangeCode(e,t){if(!this.pendingStates.has(t.state))throw new Error("Invalid or expired state parameter");this.pendingStates.delete(t.state);let r=t.codeVerifier;if(this.config.usePKCE&&!r){const a=this.pendingChallenges.get(t.state);a&&(r=a.codeVerifier,this.pendingChallenges.delete(t.state))}const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",t.code),n.set("redirect_uri",this.config.redirectUrl),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret),r&&n.set("code_verifier",r);const o=await Ze(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n.toString()}),zg,new Error(`OAuth token exchange timed out after ${zg}ms`));if(!o.ok){const a=await o.text();throw new Error(`Token exchange failed: ${o.status} ${o.statusText} - ${a}`)}const s=await o.json(),i={accessToken:s.access_token,refreshToken:s.refresh_token,expiresAt:s.expires_in?lte(s.expires_in):void 0,tokenType:s.token_type??"Bearer",scope:s.scope};return await this.saveTokens(e,i),i}async refreshTokens(e,t){const r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t),r.set("client_id",this.config.clientId),this.config.clientSecret&&r.set("client_secret",this.config.clientSecret);const n=await Ze(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()}),zg,new Error(`OAuth token refresh timed out after ${zg}ms`));if(!n.ok){const i=await n.text();throw new Error(`Token refresh failed: ${n.status} ${n.statusText} - ${i}`)}const o=await n.json(),s={accessToken:o.access_token,refreshToken:o.refresh_token??t,expiresAt:o.expires_in?lte(o.expires_in):void 0,tokenType:o.token_type??"Bearer",scope:o.scope};return await this.saveTokens(e,s),s}async revokeTokens(e,t){const r=await this.storage.getTokens(e);if(!r)return;const n=new URLSearchParams;n.set("token",r.accessToken),n.set("client_id",this.config.clientId),this.config.clientSecret&&n.set("client_secret",this.config.clientSecret);try{await Ze(fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),zg,new Error(`OAuth token revocation timed out after ${zg}ms`))}catch(o){f.warn(`[NeuroLinkOAuthProvider] Token revocation failed: ${o instanceof Error?o.message:String(o)}`)}await this.storage.deleteTokens(e)}async getAuthorizationHeader(e){const t=await this.tokens(e);return t?`${t.tokenType} ${t.accessToken}`:null}async hasValidTokens(e){return await this.tokens(e)!==null}generateState(){return af(32).toString("base64url")}generatePKCE(){const e=af(32).toString("base64url"),t=Kc("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t,codeChallengeMethod:"S256"}}getConfig(){return{...this.config}}getStorage(){return this.storage}cleanupPendingRequests(){this.pendingStates.size>100&&this.pendingStates.clear(),this.pendingChallenges.size>100&&this.pendingChallenges.clear()}}}}),wOt=S({"src/lib/mcp/auth/index.ts"(){"use strict";_Ot(),HBr()}}),bOt={};he(bOt,{MCPClientFactory:()=>xk});var TOt,xk,cte=S({"src/lib/mcp/mcpClientFactory.ts"(){"use strict";K6r(),_5r(),BBr(),zBr(),jBr(),Lq(),q(),nte(),vt(),fOt(),gOt(),wOt(),Qn(),Jv(),TOt=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4),xk=class{static NEUROLINK_IMPLEMENTATION={name:"neurolink-sdk",version:"1.0.0"};static DEFAULT_CAPABILITIES={sampling:{},roots:{listChanged:!1}};static async createClient(e,t=TOt){const r=Date.now(),{traceId:n,parentSpanId:o}=Kv(),s=Oe.createSpan("mcp.transport","mcp.connect",{"mcp.transport":e.transport,"mcp.operation":"connect","mcp.server_id":e.id},o,n);try{de.info(`[MCPClientFactory] Creating client for ${e.id}`,{transport:e.transport,command:e.command,hasRetryConfig:!!e.retryConfig,hasRateLimiting:!!e.rateLimiting,hasAuth:!!e.auth}),(e.transport==="http"||e.transport==="sse")&&e.rateLimiting&&(await ate.getLimiter(e.id,{requestsPerWindow:e.rateLimiting.requestsPerMinute??60,windowMs:6e4,maxBurst:e.rateLimiting.maxBurst??10,useTokenBucket:e.rateLimiting.useTokenBucket??!0,refillRate:(e.rateLimiting.requestsPerMinute??60)/60}).acquire(),de.debug(`[MCPClientFactory] Rate limit token acquired for ${e.id}`));const i=kk.getBreaker(`mcp-client-${e.id}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:t}),a=async()=>await i.execute(async()=>await this.createClientInternal(e,t));let l;(e.transport==="http"||e.transport==="sse")&&e.retryConfig?(de.debug(`[MCPClientFactory] Using retry logic for ${e.id}`,{maxAttempts:e.retryConfig.maxAttempts??sd.maxAttempts}),l=await hOt(a,{maxAttempts:e.retryConfig.maxAttempts??sd.maxAttempts,initialDelay:e.retryConfig.initialDelay??sd.initialDelay,maxDelay:e.retryConfig.maxDelay??sd.maxDelay,backoffMultiplier:e.retryConfig.backoffMultiplier??sd.backoffMultiplier})):l=await a(),de.info(`[MCPClientFactory] Client created successfully for ${e.id}`,{duration:Date.now()-r,capabilities:l.capabilities}),s.durationMs=Date.now()-r;const c=Oe.endSpan(s,1);return dt().recordSpan(c),{...l,success:!0,duration:Date.now()-r}}catch(i){const a=i instanceof Error?i.message:String(i);if(i instanceof Xp){de.warn(`[MCPClientFactory] Client creation blocked by circuit breaker for ${e.id}`,{serverId:e.id,breakerState:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}),s.durationMs=Date.now()-r;const c=Oe.endSpan(s,2);return c.statusMessage=`Circuit breaker open: ${a}`,dt().recordSpan(c),{success:!1,error:a,duration:Date.now()-r}}de.debug(`[MCPClientFactory] Failed to create client for ${e.id}:`,i),s.durationMs=Date.now()-r;const l=Oe.endSpan(s,2);return l.statusMessage=a,dt().recordSpan(l),{success:!1,error:a,duration:Date.now()-r}}}static async createClientInternal(e,t){const r=await this.createTransport(e),n=r.transport,o=r.process;try{const s=new NDt(this.NEUROLINK_IMPLEMENTATION,{capabilities:this.DEFAULT_CAPABILITIES});await Promise.race([s.connect(n),this.createTimeoutPromise(t,`Client connection timeout for ${e.id}`)]);const i=await this.performHandshake(s,t);return de.debug(`[MCPClientFactory] Handshake completed for ${e.id}`,{capabilities:i}),{client:s,transport:n,process:o,capabilities:i}}catch(s){try{await n.close()}catch(i){de.debug("[MCPClientFactory] Error closing transport during cleanup:",i)}throw o&&!o.killed&&o.kill("SIGTERM"),s}}static async createTransport(e){switch(e.transport){case"stdio":return this.createStdioTransport(e);case"sse":return this.createSSETransport(e);case"websocket":return this.createWebSocketTransport(e);case"http":return this.createHTTPTransport(e);default:throw new Error(`Unsupported transport type: ${e.transport}`)}}static async createStdioTransport(e){if(de.debug(`[MCPClientFactory] Creating stdio transport for ${e.id}`,{command:e.command,args:e.args}),!e.command)throw new Error("Command is required for stdio transport");const t=Mq(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:Object.fromEntries(Object.entries({...process.env,...e.env}).filter(([,i])=>i!==void 0).map(([i,a])=>[i,String(a)])),cwd:e.cwd}),r=new Promise((i,a)=>{t.on("error",l=>{a(new Error(`Process spawn error: ${l.message}`))}),t.on("exit",(l,c)=>{l!==0&&a(new Error(`Process exited with code ${l}, signal ${c}`))})}),n=new AbortController,o=setTimeout(()=>{n.abort()},1e3);try{await Promise.race([new Promise(i=>{const a=()=>{n.signal.aborted?i():setTimeout(a,100)};a()}),r])}finally{clearTimeout(o)}if(t.killed||t.exitCode!==null)throw new Error("Process failed to start or exited immediately");if(!e.command)throw new Error("Command is required for stdio transport");return{transport:new F4t({command:e.command,args:e.args||[],env:Object.fromEntries(Object.entries({...process.env,...e.env}).filter(([,i])=>i!==void 0).map(([i,a])=>[i,String(a)])),cwd:e.cwd,stderr:"ignore"}),process:t}}static async createSSETransport(e){if(!e.url)throw new Error("URL is required for SSE transport");de.debug(`[MCPClientFactory] Creating SSE transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url);return{transport:new aOt(t)}}catch(t){throw new Error(`Invalid SSE URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createWebSocketTransport(e){if(!e.url)throw new Error("URL is required for WebSocket transport");de.debug(`[MCPClientFactory] Creating WebSocket transport for ${e.id}`,{url:e.url});try{const t=new URL(e.url);return{transport:new cOt(t)}}catch(t){throw new Error(`Invalid WebSocket URL: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}static async createHTTPTransport(e){if(!e.url)throw new Error("URL is required for HTTP transport");const t={connectionTimeout:e.httpOptions?.connectionTimeout??3e4,requestTimeout:e.httpOptions?.requestTimeout??6e4,idleTimeout:e.httpOptions?.idleTimeout??12e4,keepAliveTimeout:e.httpOptions?.keepAliveTimeout??3e4};de.debug(`[MCPClientFactory] Creating HTTP transport for ${e.id}`,{url:e.url,hasHeaders:!!e.headers,hasAuth:!!e.auth,authType:e.auth?.type,httpOptions:t});try{const r=new URL(e.url),n=await this.setupAuthProvider(e),o={...e.headers??{}};if(e.auth){const l=await this.getAuthorizationHeader(e,n);l&&(o.Authorization=l)}const s=this.createEnhancedFetch(e,t.requestTimeout,n),i={headers:Object.keys(o).length>0?o:void 0};return{transport:new dOt(r,{requestInit:i,fetch:s})}}catch(r){throw new Error(`Invalid HTTP URL: ${r instanceof Error?r.message:String(r)}`,{cause:r})}}static createFetchWithTimeout(e){return async(t,r)=>{const n=new AbortController,o=setTimeout(()=>n.abort(),e);try{return await fetch(t,{...r,signal:n.signal})}finally{clearTimeout(o)}}}static createEnhancedFetch(e,t,r){const n=this.createFetchWithTimeout(t);return async(o,s)=>{if(r&&e.auth?.type==="oauth2")try{const i=await r.getAuthorizationHeader(e.id);if(i){const a=s?.headers??{},l=new Headers(a);l.set("Authorization",i),s={...s,headers:l}}}catch(i){de.warn(`[MCPClientFactory] OAuth token refresh failed for ${e.id}:`,i instanceof Error?i.message:String(i))}return n(o,s)}}static async setupAuthProvider(e){if(e.auth?.type==="oauth2"&&e.auth.oauth){const t=new eL,r={clientId:e.auth.oauth.clientId,clientSecret:e.auth.oauth.clientSecret,authorizationUrl:e.auth.oauth.authorizationUrl,tokenUrl:e.auth.oauth.tokenUrl,redirectUrl:e.auth.oauth.redirectUrl,scope:e.auth.oauth.scope,usePKCE:e.auth.oauth.usePKCE??!0},n=new tL(r,t);return de.debug(`[MCPClientFactory] OAuth provider created for ${e.id}`,{clientId:r.clientId,usePKCE:r.usePKCE}),n}}static async getAuthorizationHeader(e,t){if(e.auth)switch(e.auth.type){case"oauth2":return t?await t.getAuthorizationHeader(e.id)??void 0:void 0;case"bearer":return e.auth.token?`Bearer ${e.auth.token}`:void 0;case"api-key":return;default:return}}static async performHandshake(e,t){try{const r=await Promise.race([this.getServerInfo(e),this.createTimeoutPromise(t,"Handshake timeout")]);return this.extractCapabilities(r)}catch(r){return de.warn("[MCPClientFactory] Handshake failed, but connection may still be valid:",r),this.DEFAULT_CAPABILITIES}}static async getServerInfo(e){try{return{tools:(await e.listTools()).tools||[],capabilities:this.DEFAULT_CAPABILITIES}}catch{return de.debug("[MCPClientFactory] Tool listing failed, server may not support tools yet"),{tools:[],capabilities:this.DEFAULT_CAPABILITIES}}}static extractCapabilities(e){return{...this.DEFAULT_CAPABILITIES,...e.tools?{tools:{}}:{}}}static createTimeoutPromise(e,t,r){return new Promise((n,o)=>{const s=setTimeout(()=>{o(new Error(t))},e);r&&r.addEventListener("abort",()=>{clearTimeout(s),o(new Error(`Operation aborted: ${t}`))})})}static async closeClient(e,t,r){const n=[];try{await e.close()}catch(o){n.push(`Client close error: ${o instanceof Error?o.message:String(o)}`)}try{await t.close()}catch(o){n.push(`Transport close error: ${o instanceof Error?o.message:String(o)}`)}if(r&&!r.killed)try{r.kill("SIGTERM"),await new Promise(o=>{const s=setTimeout(()=>{if(!r.killed){de.warn("[MCPClientFactory] Force killing process");try{r.kill("SIGKILL")}catch(i){de.debug("[MCPClientFactory] Error in force kill:",i)}}o()},5e3);r.on("exit",()=>{clearTimeout(s),o()})})}catch(o){n.push(`Process kill error: ${o instanceof Error?o.message:String(o)}`)}n.length>0&&de.warn("[MCPClientFactory] Errors during client cleanup:",n)}static async testConnection(e,t=5e3){let r,n,o;try{const s=await this.createClient(e,t);if(!s.success)return{success:!1,error:s.error};if(r=s.client,n=s.transport,o=s.process,r)try{await r.listTools()}catch{de.debug("[MCPClientFactory] Tool listing failed during test, but connection may be valid")}return{success:!0,capabilities:s.capabilities}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}finally{if(r&&n)try{await this.closeClient(r,n,o)}catch(s){de.debug("[MCPClientFactory] Error cleaning up test connection:",s)}}}static validateClientConfig(e){const t=[];if(e.command||t.push("Command is required"),e.transport||t.push("Transport is required"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be stdio, sse, websocket, or http"),e.transport==="sse"||e.transport==="websocket"||e.transport==="http")if(!e.url)t.push(`URL is required for ${e.transport} transport`);else try{new URL(e.url)}catch{t.push(`Invalid URL for ${e.transport} transport`)}return e.transport==="stdio"&&(Array.isArray(e.args)||t.push("Args array is required for stdio transport")),{isValid:t.length===0,errors:t}}static getSupportedTransports(){return["stdio","sse","websocket","http"]}static getDefaultCapabilities(){return{...this.DEFAULT_CAPABILITIES}}}}});function EOt(e,t){if(t<=0)return"";try{const r=JSON.stringify(e);return typeof r!="string"?"":r.length<=t?r:r.slice(0,Math.max(0,t-1))+"\u2026"}catch{return""}}function rL(e,t=0){if(t>10)return"[...]";if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>rL(n,t+1));const r={};for(const[n,o]of Object.entries(e))COt.test(n)?r[n]="[REDACTED]":r[n]=rL(o,t+1);return r}var SOt,COt,ute,kOt,VBr=S({"src/lib/mcp/toolDiscoveryService.ts"(){"use strict";vn(),q(),nte(),pf(),eg(),ct(),i9(),WS(),er(),yr(),Vr(),SOt=He.mcp,COt=/^(password|passwd|secret|token|api[_-]?key|apikey|access[_-]?key|authorization|auth|bearer|credential|cookie|session[_-]?id|private[_-]?key|client[_-]?secret|refresh[_-]?token|x-api-key)$/i,ute=Math.max(5e3,Number(process.env.MCP_TOOL_TIMEOUT)||6e4),kOt=class extends nn{serverToolStorage=new Map;toolRegistry=new Map;serverTools=new Map;discoveryInProgress=new Set;outputNormalizer;constructor(){super()}setOutputNormalizer(e){this.outputNormalizer=e}async discoverTools(e,t,r=ute){return gt({name:"neurolink.mcp.discoverTools",tracer:He.mcp,attributes:{"mcp.server_id":e}},async n=>{const o=Date.now();try{if(this.discoveryInProgress.has(e))return{success:!1,error:`Discovery already in progress for server: ${e}`,toolCount:0,tools:[],duration:Date.now()-o,serverId:e};this.discoveryInProgress.add(e),de.info(`[ToolDiscoveryService] Starting tool discovery for server: ${e}`);const i=await kk.getBreaker(`tool-discovery-${e}`,{failureThreshold:2,resetTimeout:6e4,operationTimeout:r}).execute(async()=>await this.performToolDiscovery(e,t,r)),a=await this.registerDiscoveredTools(e,i);n.setAttribute("mcp.tools_discovered",a.length);const l={success:!0,toolCount:a.length,tools:a,duration:Date.now()-o,serverId:e};return this.emit("discoveryCompleted",{serverId:e,toolCount:a.length,duration:l.duration,timestamp:new Date}),de.info(`[ToolDiscoveryService] Discovery completed for ${e}: ${a.length} tools`),l}catch(s){const i=s instanceof Error?s.message:String(s);return n.setStatus({code:qe.ERROR,message:i}),n.recordException(s instanceof Error?s:new Error(i)),de.error(`[ToolDiscoveryService] Discovery failed for ${e}:`,s),this.emit("discoveryFailed",{serverId:e,error:i,timestamp:new Date}),{success:!1,error:i,toolCount:0,tools:[],duration:Date.now()-o,serverId:e}}finally{this.discoveryInProgress.delete(e)}})}async performToolDiscovery(e,t,r){const n=t.listTools(),o=this.createTimeoutPromise(r,"Tool discovery timeout"),s=await Promise.race([n,o]);if(!s||!s.tools)throw new Error("No tools returned from server");return de.debug(`[ToolDiscoveryService] Discovered ${s.tools.length} tools from ${e}`),s.tools}async registerDiscoveredTools(e,t){const r=[];this.clearServerTools(e);for(const n of t)try{const o=await this.createToolInfo(e,n),s=this.validateTool(o);if(!s.isValid){de.warn(`[ToolDiscoveryService] Skipping invalid tool ${n.name} from ${e}:`,s.errors);continue}s.metadata&&(o.metadata={...o.metadata,...s.metadata});const i=this.createToolKey(e,n.name);this.toolRegistry.set(i,o),this.serverToolStorage.has(e)||this.serverToolStorage.set(e,[]);const a=this.serverToolStorage.get(e);if(!a)throw new Error(`Server tools storage not found for ${e}`);a.find(c=>c.name===n.name)||a.push({name:n.name,description:n.description||"",inputSchema:n.inputSchema}),this.serverTools.has(e)||this.serverTools.set(e,new Set);const l=this.serverTools.get(e);l&&l.add(n.name),r.push(o),this.emit("toolRegistered",{serverId:e,toolName:n.name,toolInfo:o,timestamp:new Date}),de.debug(`[ToolDiscoveryService] Registered tool: ${n.name} from ${e}`)}catch(o){de.error(`[ToolDiscoveryService] Failed to register tool ${n.name} from ${e}:`,o)}return r}async createToolInfo(e,t){return{name:t.name,description:t.description||"No description provided",serverId:e,inputSchema:t.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},metadata:{category:this.inferToolCategory(t),version:"1.0.0",deprecated:!1}}}inferToolCategory(e){const t=e.name.toLowerCase(),r=(e.description||"").toLowerCase();return t.includes("git")||r.includes("git")?"version-control":t.includes("file")||t.includes("read")||t.includes("write")?"file-system":t.includes("api")||t.includes("http")||t.includes("request")?"api":t.includes("data")||t.includes("query")||t.includes("search")?"data":t.includes("auth")||t.includes("login")||t.includes("token")?"authentication":t.includes("deploy")||t.includes("build")||t.includes("ci")?"deployment":"general"}validateTool(e){const t=[],r=[],n=GS(e.name);n&&t.push(n.message);const o=MD(e.description);if(o&&r.push(o.message),e.serverId||t.push("Server ID is required"),e.inputSchema)try{JSON.stringify(e.inputSchema)}catch{t.push("Input schema is not valid JSON")}const s={category:typeof e.metadata?.category=="string"?e.metadata.category:"general",complexity:this.inferComplexity(e),requiresAuth:this.inferAuthRequirement(e),isDeprecated:typeof e.metadata?.deprecated=="boolean"?e.metadata.deprecated:!1};return{isValid:t.length===0,errors:t,warnings:r,metadata:s}}inferComplexity(e){const t=e.inputSchema;if(!t||!t.properties)return"simple";const r=Object.keys(t.properties).length;return r<=2?"simple":r<=5?"moderate":"complex"}inferAuthRequirement(e){const t=e.name.toLowerCase(),r=e.description.toLowerCase();return t.includes("auth")||t.includes("login")||t.includes("token")||r.includes("authentication")||r.includes("credentials")||r.includes("permission")}async executeTool(e,t,r,n,o={}){const s=Date.now();try{const i=this.createToolKey(t,e),a=this.toolRegistry.get(i);if(!a)throw new Error(`Tool '${e}' not found for server '${t}'`);if(!a.isAvailable)throw new Error(`Tool '${e}' is not available`);let l=n;o.validateInput!==!1&&(l=this.validateToolParameters(a,n)),de.debug(`[ToolDiscoveryService] Executing tool: ${e} on ${t}`,{parameters:l});const c=o.timeout||ute,d=await kk.getBreaker(`tool-execution-${t}-${e}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:c}).execute(async()=>SOt.startActiveSpan("neurolink.mcp.callTool",{kind:Br.CLIENT,attributes:{"mcp.server_id":t,"mcp.tool_name":e,"mcp.timeout_ms":c,"ai.tool.name":e,"gen_ai.tool.name":e,"gen_ai.request":EOt({name:e,arguments:rL(l)},2048)}},async h=>{try{const g=c,y=await Ze(r.callTool({name:e,arguments:l},void 0,{timeout:c}),g,new Error(`Tool execution timeout: ${e}`)),v=y;if(v&&v.isError===!0){const T=BD(v);h.setStatus({code:qe.ERROR,message:T||`Tool ${e} returned isError`})}else h.setStatus({code:qe.OK});let _=y,b=y;if(this.outputNormalizer)try{const T=await this.outputNormalizer.normalize(y,{toolName:e,serverId:t});h.setAttribute("mcp.output.strategy",T.isExternalized?"externalize":"inline"),T.isExternalized&&h.setAttribute("mcp.output.original_bytes",T.originalBytes),_=T.result,b=T.result}catch(T){de.warn(`[ToolDiscoveryService] McpOutputNormalizer failed for ${e}: ${T instanceof Error?T.message:String(T)} \u2014 returning raw result`)}return h.setAttribute("gen_ai.response",EOt(rL(_),2048)),b}catch(g){throw h.setStatus({code:qe.ERROR,message:g.message}),h.recordException(g),g}finally{h.end()}})),m=Date.now()-s;return this.updateToolStats(i,!0,m),o.validateOutput!==!1&&this.validateToolOutput(d),de.debug(`[ToolDiscoveryService] Tool execution completed: ${e}`,{duration:m,hasContent:!!d?.content}),{success:!0,data:d,duration:m,metadata:{toolName:e,serverId:t,timestamp:Date.now()}}}catch(i){const a=Date.now()-s,l=i instanceof Error?i.message:String(i),c=this.createToolKey(t,e);return this.updateToolStats(c,!1,a),i instanceof Xp?(de.warn(`[ToolDiscoveryService] Tool blocked by circuit breaker: ${e} on ${t}`,{breakerState:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}),{success:!1,error:i.message,data:{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${e}" has been disabled after ${i.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(i.retryAfterMs/1e3)} seconds (at ${i.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]},duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now(),circuitBreaker:{state:i.breakerState,retryAfter:i.retryAfter,retryAfterMs:i.retryAfterMs,failureCount:i.failureCount}}}):(de.error(`[ToolDiscoveryService] Tool execution failed: ${e}`,i),{success:!1,error:l,duration:a,metadata:{toolName:e,serverId:t,timestamp:Date.now()}})}}validateToolParameters(e,t){if(!e.inputSchema)return t;const r=e.inputSchema,n=r.properties&&typeof r.properties=="object"?r.properties:{},o=Array.isArray(r.required)?r.required.filter(l=>typeof l=="string"):[],s=()=>Object.entries(n).map(([l,c])=>`${l}${o.includes(l)?"":"?"}: ${c.type??"any"}`).join(", "),i=o.filter(l=>!(l in t));if(i.length>0)throw new Error(`Missing required parameter${i.length>1?"s":""}: ${i.join(", ")}. Expected arguments: { ${s()} }; received keys: [${Object.keys(t).join(", ")}]`);let a;for(const[l,c]of Object.entries(n))if(l in t){const u=t[l],d=s9(u,c);d!==u&&(de.debug(`[ToolDiscoveryService] Coerced parameter '${l}' for tool '${e.name}': ${typeof u} \u2192 ${typeof d}`),a=a??{...t},a[l]=d),this.validateParameterType(l,a?a[l]:u,c)}return a??t}validateParameterType(e,t,r){if(!r.type)return;const n=r.type,o=typeof t;switch(n){case"string":if(o!=="string")throw new Error(`Parameter '${e}' must be a string, got ${o}`);break;case"number":if(o!=="number")throw new Error(`Parameter '${e}' must be a number, got ${o}`);break;case"integer":if(o!=="number"||!Number.isInteger(t))throw new Error(`Parameter '${e}' must be an integer, got ${o==="number"?String(t):o}`);break;case"boolean":if(o!=="boolean")throw new Error(`Parameter '${e}' must be a boolean, got ${o}`);break;case"array":if(!Array.isArray(t))throw new Error(`Parameter '${e}' must be an array, got ${o}`);break;case"object":if(o!=="object"||t===null||Array.isArray(t))throw new Error(`Parameter '${e}' must be an object, got ${o}`);break}}validateToolOutput(e){if(T_r(e)){de.debug("[ToolDiscoveryService] Tool returned null/undefined, treating as empty response");return}de.debug("[ToolDiscoveryService] Tool response received",{type:typeof e,isArray:Array.isArray(e),isObject:G1(e),hasKeys:G1(e)?Object.keys(e).length:0,fullResponse:e})}updateToolStats(e,t,r){const n=this.toolRegistry.get(e);if(!n)return;n.stats.totalCalls++,n.lastCalled=new Date,n.stats.lastExecutionTime=r,t?n.stats.successfulCalls++:n.stats.failedCalls++;const o=n.stats.averageExecutionTime*(n.stats.totalCalls-1)+r;n.stats.averageExecutionTime=o/n.stats.totalCalls}getTool(e,t){const r=this.createToolKey(t,e);return this.toolRegistry.get(r)}getServerTools(e){const t=this.serverToolStorage.get(e);if(t)return t.map(o=>({name:o.name,description:o.description,serverId:e,inputSchema:o.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}}));const r=[],n=this.serverTools.get(e);if(n)for(const o of n){const s=this.createToolKey(e,o),i=this.toolRegistry.get(s);i&&r.push(i)}return r}getAllTools(){const e=[];for(const[r,n]of this.serverToolStorage.entries())for(const o of n)e.push({name:o.name,description:o.description,serverId:r,inputSchema:o.inputSchema,isAvailable:!0,stats:{totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0}});const t=Array.from(this.toolRegistry.values()).filter(r=>!e.some(n=>n.name===r.name&&n.serverId===r.serverId));return[...e,...t]}clearServerTools(e){const t=this.serverToolStorage.get(e);if(t){for(const n of t)this.emit("toolUnregistered",{serverId:e,toolName:n.name,timestamp:new Date});this.serverToolStorage.delete(e)}const r=this.serverTools.get(e);if(r){for(const n of r){const o=this.createToolKey(e,n);this.toolRegistry.delete(o),(!t||!t.find(s=>s.name===n))&&this.emit("toolUnregistered",{serverId:e,toolName:n,timestamp:new Date})}this.serverTools.delete(e)}de.debug(`[ToolDiscoveryService] Cleared tools for server: ${e}`)}updateToolAvailability(e,t,r){const n=this.createToolKey(t,e),o=this.toolRegistry.get(n);o&&(o.isAvailable=r,de.debug(`[ToolDiscoveryService] Updated availability for ${e}: ${r}`))}createToolKey(e,t){return`${e}:${t}`}createTimeoutPromise(e,t){return new Promise((r,n)=>{setTimeout(()=>{n(new Error(t))},e)})}destroy(){de.debug("[ToolDiscoveryService] Starting cleanup..."),this.removeAllListeners(),this.serverToolStorage.clear(),this.toolRegistry.clear(),this.serverTools.clear(),this.discoveryInProgress.clear(),de.debug("[ToolDiscoveryService] Destroyed and cleaned up")}resetStatistics(){for(const e of this.toolRegistry.values())e.stats={totalCalls:0,successfulCalls:0,failedCalls:0,averageExecutionTime:0,lastExecutionTime:0},e.lastCalled=void 0;de.debug("[ToolDiscoveryService] Statistics reset for all tools")}getListenerCount(){const e=["discoveryCompleted","discoveryFailed","toolRegistered","toolUnregistered"];let t=0;for(const r of e)t+=this.listenerCount(r);return t}getStatistics(){const e={},t={};let r=0,n=0;for(const o of this.toolRegistry.values()){e[o.serverId]=(e[o.serverId]||0)+1;const s=typeof o.metadata?.category=="string"?o.metadata.category:"unknown";t[s]=(t[s]||0)+1,o.isAvailable?r++:n++}return{totalTools:this.toolRegistry.size,availableTools:r,unavailableTools:n,totalServers:this.serverTools.size,toolsByServer:e,toolsByCategory:t}}}}}),xOt,WBr=S({"src/lib/mcp/registry.ts"(){"use strict";q(),xOt=class{plugins=new Map;register(e){this.plugins.set(e.metadata.name,e),dr.debug(`Registered plugin: ${e.metadata.name}`)}unregister(e){const t=this.plugins.delete(e);return t&&dr.debug(`Unregistered plugin: ${e}`),t}get(e){return this.plugins.get(e)}list(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}clear(){this.plugins.clear(),dr.info("Registry cleared")}async registerServer(e,t,r){const n={metadata:{name:e,description:typeof t=="object"&&t&&t.description||"No description"},tools:typeof t=="object"&&t?t.tools:{},configuration:typeof t=="object"&&t?t:{}};this.register(n)}async executeTool(e,t,r){return dr.info(`Executing tool: ${e}`),{result:`Mock execution of ${e}`,args:t}}async listTools(e){return this.list().map(r=>({name:r.metadata.name,description:r.metadata.description||"No description",serverId:r.metadata.name,category:"general"}))}registerServerSync(e){this.register(e)}executeToolSync(e,t){return dr.info(`Executing tool (sync): ${e}`),{result:`Mock execution of ${e}`,args:t}}listToolsSync(){return this.list().map(t=>({name:t.metadata.name,description:t.metadata.description||"No description"}))}listServers(){return Array.from(this.plugins.keys())}}}});function xa(e){return e.existingCategory&&["external","in-memory","built-in","user-defined"].includes(e.existingCategory)?e.existingCategory:e.isCustomTool?"user-defined":e.isBuiltIn?"built-in":e.isExternal?"external":e.serverId?.startsWith("custom-tool-")?"user-defined":e.serverId?.includes("external")?"external":e.serverId==="direct"?"built-in":"in-memory"}function KBr(e,t){switch(t){case"external":return`External MCP server: ${e}`;case"built-in":return`Built-in tool server: ${e}`;case"custom":case"user-defined":return`Custom tool server: ${e}`;case"in-memory":return`In-memory MCP server: ${e}`;default:return e}}function AOt(e){const t=e.id||`server-${e.name}`,r=e.category||xa({isCustomTool:e.isCustomTool,isExternal:e.isExternal,isBuiltIn:e.isBuiltIn,serverId:t}),n=e.tools||(e.tool?[e.tool]:[]);return{id:t,name:e.name,transport:e.transport||"stdio",status:e.status||"connected",tools:n,description:e.description||KBr(e.name,r),...e.command&&{command:e.command},...e.args&&{args:e.args},...e.env&&{env:e.env},metadata:{category:r,toolCount:n.length}}}function JBr(e,t,r,n){const o=AOt({id:`custom-tool-${e}`,name:e,tool:{name:e,description:t.description||e,inputSchema:t.inputSchema||{},execute:t.execute},isCustomTool:!0});return o.metadata&&(r!==void 0&&(o.metadata.toolTimeoutMs=r),n!==void 0&&(o.metadata.toolMaxRetries=n)),o}var dte=S({"src/lib/utils/mcpDefaults.ts"(){"use strict"}}),IOt,YBr=S({"src/lib/mcp/flexibleToolValidator.ts"(){"use strict";q(),IOt=class{static MAX_TOOL_NAME_LENGTH=1e3;static MIN_TOOL_NAME_LENGTH=1;static validateToolName(e){const t=[];if(!e||typeof e!="string")return{isValid:!1,error:"Tool name is required and must be a string"};if(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(e))return{isValid:!1,error:"Tool name contains control characters that could break systems"};const n=e.trim();return n.length===0?{isValid:!1,error:"Tool name cannot be empty or whitespace-only"}:n.length<this.MIN_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name must be at least ${this.MIN_TOOL_NAME_LENGTH} character long`}:n.length>this.MAX_TOOL_NAME_LENGTH?{isValid:!1,error:`Tool name exceeds maximum length of ${this.MAX_TOOL_NAME_LENGTH} characters`}:(n!==e&&t.push("Tool name has leading/trailing whitespace (will be trimmed)"),n.length>200&&t.push("Tool name is unusually long but allowed"),dr.debug(`\u2705 FlexibleToolValidator: Tool '${e}' passed universal safety checks`),{isValid:!0,warnings:t.length>0?t:void 0})}static validateToolInfo(e,t){const r=this.validateToolName(e);if(!r.isValid)return r;const n=[...r.warnings||[]];return t.description&&typeof t.description!="string"?{isValid:!1,error:"Tool description must be a string if provided"}:t.serverId&&typeof t.serverId!="string"?{isValid:!1,error:"Tool serverId must be a string if provided"}:(dr.debug(`\u2705 FlexibleToolValidator: Tool info for '${e}' passed validation`),{isValid:!0,warnings:n.length>0?n:void 0})}static getValidationInfo(){return{philosophy:"Maximum flexibility with universal safety only - following Anthropic's MCP specification",checks:["Empty or whitespace-only names","Excessive length (over 1000 characters)","Control characters that could break systems"],whatIsAllowed:["Dots (github.create_repo, filesystem.read_file)","Hyphens and underscores (my-tool, user_helper)","Numbers (tool1, my_tool_v2)","Unicode characters (\u{1F680}_tool, caf\xE9_manager)","Mixed case (createRepo, ReadFile)","Long descriptive names (enterprise_database_connection_manager)","Any legitimate MCP tool naming pattern"],examples:{valid:["github.create_repo","filesystem.read_file","my-custom-tool","user_helper","tool1","\u{1F680}_rocket_tool","enterprise.database.connection.manager","UPPERCASE_TOOL","mixed_Case.Tool-Name_123"],invalid:[""," ","tool\0","a".repeat(1001)]}}}}}}),ROt={};he(ROt,{AuthError:()=>At,AuthErrorCodes:()=>nL});var nL,At,ta=S({"src/lib/auth/errors.ts"(){"use strict";vE(),nL={INVALID_TOKEN:"AUTH-001",EXPIRED_TOKEN:"AUTH-002",MISSING_TOKEN:"AUTH-003",TOKEN_DECODE_FAILED:"AUTH-004",INVALID_SIGNATURE:"AUTH-005",SESSION_NOT_FOUND:"AUTH-010",SESSION_EXPIRED:"AUTH-011",SESSION_REVOKED:"AUTH-012",INSUFFICIENT_PERMISSIONS:"AUTH-020",INSUFFICIENT_ROLES:"AUTH-021",ACCESS_DENIED:"AUTH-022",USER_NOT_FOUND:"AUTH-030",USER_DISABLED:"AUTH-031",EMAIL_NOT_VERIFIED:"AUTH-032",MFA_REQUIRED:"AUTH-033",PROVIDER_ERROR:"AUTH-040",PROVIDER_NOT_FOUND:"AUTH-041",PROVIDER_INIT_FAILED:"AUTH-042",CONFIGURATION_ERROR:"AUTH-043",CREATION_FAILED:"AUTH-050",REGISTRATION_FAILED:"AUTH-051",DUPLICATE_REGISTRATION:"AUTH-052",MIDDLEWARE_ERROR:"AUTH-060",RATE_LIMITED:"AUTH-061",JWKS_FETCH_FAILED:"AUTH-070",JWKS_KEY_NOT_FOUND:"AUTH-071"},At=_f("Auth",nL)}}),oL={};he(oL,{AuthContextHolder:()=>aL,createAuthenticatedContext:()=>UOt,getAuthContext:()=>sL,getCurrentSession:()=>POt,getCurrentUser:()=>Ak,globalAuthContext:()=>jg,hasAllPermissions:()=>LOt,hasAnyRole:()=>NOt,hasPermission:()=>iL,hasRole:()=>mte,isAuthenticated:()=>DOt,requireAuth:()=>pte,requirePermission:()=>$Ot,requireRole:()=>FOt,requireUser:()=>OOt,runWithAuthContext:()=>MOt});function MOt(e,t){return M_.run(e,t)}function sL(){return M_.getStore()??jg.get()}function Ak(){return(M_.getStore()??jg.get())?.user}function POt(){return(M_.getStore()??jg.get())?.session}function DOt(){return M_.getStore()!==void 0||jg.isAuthenticated()}function pte(){const e=sL();if(!e)throw At.create("MISSING_TOKEN","Authentication required");return e}function OOt(e){const t=pte();if(t.user.id!==e)throw At.create("ACCESS_DENIED","User mismatch");return t}function iL(e){const t=Ak();if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}function mte(e){return Ak()?.roles.includes(e)??!1}function NOt(e){const t=Ak();return t?e.some(r=>t.roles.includes(r)):!1}function LOt(e){return e.every(t=>iL(t))}function $Ot(e){if(!iL(e))throw At.create("INSUFFICIENT_PERMISSIONS",`Permission denied: ${e}`)}function FOt(e){if(!mte(e))throw At.create("INSUFFICIENT_ROLES",`Role required: ${e}`)}function UOt(e,t,r,n){return{...r,user:e,session:t,request:r,authenticatedAt:new Date,provider:n}}var M_,aL,jg,Ik=S({"src/lib/auth/authContext.ts"(){"use strict";VS(),ta(),M_=new C0,aL=class{context;set(e){this.context=e}get(){return this.context}clear(){this.context=void 0}getUser(){return this.context?.user}getSession(){return this.context?.session}isAuthenticated(){return this.context!==void 0}hasPermission(e){const t=this.context?.user;if(!t)return!1;if(t.permissions.includes(e)||t.permissions.includes("*"))return!0;const r=e.split(":");for(let n=r.length-1;n>0;n--){const o=[...r.slice(0,n),"*"].join(":");if(t.permissions.includes(o))return!0}return!1}hasRole(e){return this.context?.user.roles.includes(e)??!1}},jg=new aL}}),lL,hte,fte=S({"src/lib/mcp/toolRegistry.ts"(){"use strict";WBr(),q(),Ft(),W1(),kM(),Yi(),dte(),YBr(),ct(),a1(),Cl(),er(),Ik(),lL=class extends xOt{tools=new Map;toolImplementations=new Map;toolExecutionStats=new Map;builtInServerInfos=[];hitlManager;constructor(){super(),Zq()||this.registerDirectTools()}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?dr.info("HITL safety mechanisms enabled for tool execution"):dr.debug("HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}registerDirectTools(){dr.debug("Auto-registering direct tools...");for(const[e,t]of Object.entries(gf)){if(!t){dr.warn(`Skipping undefined tool during registration: ${e}`);continue}const r=`direct.${e}`,n=js(t.inputSchema),o={name:e,description:t.description||`Direct tool: ${e}`,inputSchema:n,serverId:"direct",category:xa({isBuiltIn:!0,serverId:"direct"})};this.tools.set(r,o),this.toolImplementations.set(r,{execute:async(s,i)=>{try{return{success:!0,data:await t.execute(s,{toolCallId:i?.sessionId||"unknown",messages:[]}),metadata:{toolName:e,serverId:"direct",executionTime:0}}}catch(a){return{success:!1,error:a instanceof Error?a.message:String(a),metadata:{toolName:e,serverId:"direct",executionTime:0}}}},description:t.description,inputSchema:n}),dr.debug(`Registered direct tool: ${e} as ${r}`)}dr.debug(`Auto-registered ${Object.keys(gf).length} direct tools`)}async registerServer(e,t,r){let n;if(typeof e=="string"){const l=e;n=AOt({id:l,name:l,tools:[],isExternal:!0})}else n=e;const o=n.id,s={};for(const l of n.tools)s[l.name]={execute:l.execute||(async()=>{throw new Error(`Tool ${l.name} has no execute function`)}),description:l.description,inputSchema:l.inputSchema,category:xa({existingCategory:n.metadata?.category,serverId:n.id})};const i={metadata:{name:n.name,description:n.description,category:xa({existingCategory:n.metadata?.category,serverId:n.id})},tools:s,configuration:{}};this.register(i);const a=n.tools;for(const l of a){const u=o.startsWith("custom-tool-")?l.name:`${o}.${l.name}`,d=n.metadata?.toolTimeoutMs,m=n.metadata?.toolMaxRetries,h={name:l.name,description:l.description,inputSchema:l.inputSchema,outputSchema:void 0,serverId:o,category:xa({existingCategory:n.metadata?.category,serverId:n.id}),permissions:[],...d!==void 0&&{timeoutMs:d},...m!==void 0&&{maxRetries:m}};this.tools.set(u,h),this.toolImplementations.set(u,{execute:l.execute||(async()=>{throw new Error(`Tool ${l.name} has no execute function`)}),description:l.description,inputSchema:l.inputSchema,category:xa({existingCategory:n.metadata?.category,serverId:n.id}),...d!==void 0&&{timeoutMs:d},...m!==void 0&&{maxRetries:m}})}if(a.length>0){const l=xa({existingCategory:n.metadata?.category,serverId:n.id});l==="in-memory"&&(this.builtInServerInfos.push(n),dr.debug(`Added ${l} server to builtInServerInfos: ${o} with ${a.length} tools`))}}async executeTool(e,t,r){const n=Date.now();let o;const s=this.tools.get(e);if(s)o=s.serverId;else for(const i of this.tools.values())if(i.name===e){o=i.serverId;break}return gt({name:"neurolink.tool.registry.execute",tracer:He.mcp,attributes:{[Pe.GEN_AI_TOOL_NAME]:e,[Pe.MCP_SERVER_ID]:o||"builtin","langfuse.internal":!0}},async i=>{try{dr.info(`\u{1F527} [TOOL_EXECUTION] Starting execution: ${e}`,{hasArgs:t!==void 0,hasContext:r!==void 0,sessionId:r?.sessionId});const{tool:a,toolId:l}=this.resolveToolExecutionTarget(e);if(!a)throw new Error(`Tool '${e}' not found in registry`);const c=a.serverId||"unknown",u=c==="direct"?"builtin":c.startsWith("custom-tool-")?"custom":"mcp";i.setAttribute("tool.type",u),i.setAttribute(Pe.MCP_SERVER_ID,c);const d=this.createExecutionContext(r),m=this.toolImplementations.get(l);if(dr.debug(`Looking for tool '${e}' (toolId: '${l}'), found: ${!!m}, type: ${typeof m?.execute}`),dr.debug("Available tools:",Array.from(this.toolImplementations.keys())),!m||typeof m?.execute!="function")throw new Error(`Tool '${e}' implementation not found or not executable`);let h;try{h=JSON.stringify(t).slice(0,4096)}catch{h="[unserializable]"}i.setAttribute("tool.arguments_present",t!==void 0),i.setAttribute("tool.arguments_size",h.length);let g=t;const y=r?.hitlState;if(!y?.triggered&&this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(e,t)){dr.info(`Tool '${e}' requires HITL confirmation`),i.addEvent("tool.hitl_requested");try{y&&(y.triggered=!0);const A=await this.hitlManager.requestConfirmation(e,t,{serverId:a.serverId,sessionId:d.sessionId,userId:d.userId});if(!A.approved)throw i.addEvent("tool.hitl_rejected"),new bT(`Tool execution rejected by user: ${A.reason||"No reason provided"}`,e,A.reason);i.addEvent("tool.hitl_approved"),A.modifiedArguments!==void 0&&(g=A.modifiedArguments,dr.info(`Tool '${e}' arguments modified by user`)),dr.info(`Tool '${e}' approved for execution (response time: ${A.responseTime}ms)`)}catch(A){throw A instanceof TT?(dr.warn(`Tool '${e}' execution timed out waiting for user confirmation`),A):A instanceof bT?(dr.info(`Tool '${e}' execution rejected by user`),A):(dr.error(`HITL confirmation failed for tool '${e}':`,A),new Error(`HITL confirmation failed: ${A instanceof Error?A.message:String(A)}`,{cause:A}))}}else dr.debug(`Tool '${e}' does not require HITL confirmation`);dr.debug(`Executing tool '${e}' with args:`,g);const v=await m.execute(g,d);let _;if(v&&typeof v=="object"&&"success"in v&&typeof v.success=="boolean"){const k=v;_={...k,usage:{...k.usage||{},executionTime:Date.now()-n},metadata:{...k.metadata||{},toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}}}else _={success:!0,data:v,usage:{executionTime:Date.now()-n},metadata:{toolName:e,serverId:a.serverId,sessionId:d.sessionId,executionTime:Date.now()-n}};const b=Date.now()-n;this.updateStats(e,b);let T;try{T=JSON.stringify(_.data)??"undefined"}catch{T="[unserializable]"}return i.setAttribute("tool.result_length",T.length),i.setAttribute("tool.success",!0),dr.debug(`Tool '${e}' executed successfully in ${b}ms`),_}catch(a){dr.error(`Tool execution failed: ${e}`,a),i.setAttribute("tool.success",!1);const l=a instanceof Error?a.message:String(a);if(l.includes("not found in registry")||l.includes("not executable"))throw a;return i.setStatus({code:qe.ERROR,message:l}),a instanceof Error&&i.recordException(a),{success:!1,data:null,error:a instanceof Error?a.message:String(a),usage:{executionTime:Date.now()-n},metadata:{toolName:e,sessionId:r?.sessionId}}}})}async listTools(e){const t=new Map;for(const o of this.tools.values()){const s=`${o.serverId||"unknown"}.${o.name}`;t.has(s)||t.set(s,o)}let r=Array.from(t.values()),n;return e&&("sessionId"in e||"userId"in e?n=void 0:n=e),n&&(n.category&&(r=r.filter(o=>o.category===n.category)),n.serverId&&(r=r.filter(o=>o.serverId===n.serverId)),n.serverCategory&&(r=r.filter(o=>this.get(o.serverId||"")?.metadata?.category===n.serverCategory)),n.permissions&&n.permissions.length>0&&(r=r.filter(o=>{const s=o.permissions||[];return n.permissions?.some(i=>s.includes(i))??!1}))),dr.debug(`Listed ${r.length} unique tools (${n?"filtered":"unfiltered"})`),r}resolveToolExecutionTarget(e){let t=this.tools.get(e);dr.info(`\u{1F50D} [TOOL_LOOKUP] Direct lookup result for '${e}':`,!!t);let r=e;if(!t){const n=Array.from(this.tools.entries()).filter(([,o])=>o.name===e);if(n.length>1)throw xe.toolExecutionFailed(e,new Error(`Ambiguous tool name '${e}'. Use fully-qualified name 'serverId.${e}'.`));n.length===1&&([r,t]=n[0])}return{tool:t,toolId:r}}createExecutionContext(e){let t;try{t=sL()?.user?.id}catch{}return{...e,sessionId:e?.sessionId??st(),userId:e?.userId??t}}getToolInfo(e){let t=this.tools.get(e);if(!t){for(const r of this.tools.values())if(r.name===e){t=r;break}}if(t)return{tool:t,server:{id:t.serverId||"unknown-server"}}}updateStats(e,t){const r=this.toolExecutionStats.get(e)||{count:0,totalTime:0};r.count+=1,r.totalTime+=t,this.toolExecutionStats.set(e,r)}getExecutionStats(){const e={};for(const[t,r]of this.toolExecutionStats.entries())e[t]={count:r.count,totalTime:r.totalTime,averageTime:r.totalTime/r.count};return e}clearStats(){this.toolExecutionStats.clear()}getBuiltInServerInfos(){return this.builtInServerInfos}getToolsByCategory(e){const t=new Map;for(const[r,n]of this.tools.entries())n.category===e&&!t.has(r)&&t.set(r,n);return Array.from(t.values())}getAvailableTools(e){const t=Array.from(this.tools.values()),r=[],n=[];for(const o of t){const s=`${o.serverId||"unknown"}.${o.name}`,i=e.get(s);i&&i.getState()==="open"?r.push(o.name):n.push(o)}return{tools:n,unavailableTools:r}}hasTool(e){if(this.tools.has(e))return!0;for(const t of this.tools.values())if(t.name===e)return!0;return!1}async registerTool(e,t,r){dr.debug(`Registering tool: ${e}`);const n=IOt.validateToolInfo(e,{description:t.description,serverId:t.serverId});if(!n.isValid)throw dr.error(`Tool registration failed for ${e}: ${n.error}`),new Error(`Tool validation failed: ${n.error}`);n.warnings&&n.warnings.length>0&&dr.warn(`Tool registration warnings for ${e}:`,n.warnings),dr.debug(`\u2705 Tool '${e}' passed flexible validation - registration proceeding`),this.tools.set(e,t),this.toolImplementations.set(e,r),dr.debug(`Successfully registered tool: ${e}`)}removeTool(e){let t=!1;if(this.tools.has(e))this.tools.delete(e),this.toolImplementations.delete(e),this.toolExecutionStats.delete(e),dr.info(`Removed tool: ${e}`),t=!0;else for(const[r,n]of Array.from(this.tools.entries()))n.name===e&&(this.tools.delete(r),this.toolImplementations.delete(r),this.toolExecutionStats.delete(r),dr.info(`Removed tool: ${r}`),t=!0);return t}getToolCount(){return this.tools.size}getStats(){const e=this.list(),t=Array.from(this.tools.values()),r={};for(const o of e){const s=o.metadata?.category||"uncategorized";r[s]=(r[s]||0)+1}const n={};for(const o of t){const s=o.category||"uncategorized";n[s]=(n[s]||0)+1}return{totalServers:e.length,totalTools:t.length,serversByCategory:r,toolsByCategory:n,executionStats:this.getExecutionStats()}}unregisterServer(e){const t=[];for(const[s,i]of this.tools.entries())i.serverId===e&&(this.tools.delete(s),this.toolImplementations.delete(s),this.toolExecutionStats.delete(s),t.push(s));const r=this.builtInServerInfos.length;this.builtInServerInfos=this.builtInServerInfos.filter(s=>s.id!==e);const n=r>this.builtInServerInfos.length,o=this.unregister(e);return dr.info(`Unregistered server ${e}, removed ${t.length} tools${n?" and server from builtInServerInfos":""}`),o}},hte=new lL}});function P_(e){if(typeof e=="string")return e.replace(/\$\{([^}]+)\}/g,(t,r)=>{const n=process.env[r.trim()];return n===void 0?(de.warn(`[ExternalServerManager] Environment variable ${r} is not defined, using empty string`),""):n});if(Array.isArray(e))return e.map(t=>P_(t));if(ar(e)){const t={};for(const[r,n]of Object.entries(e))t[r]=P_(n);return t}return e}function ZBr(e){if(!e||e.length===0)return e;const t=[...e];for(let r=0;r<t.length;r++){const n=t[r].indexOf("=");if(n!==-1){const o=t[r].substring(0,n);yte.test(o)&&(t[r]=`${o}=[REDACTED]`);continue}yte.test(t[r])&&r+1<t.length&&!t[r+1].startsWith("--")&&(t[r+1]="[REDACTED]",r++)}return t}function gte(e){return G1(e)?Object.values(e).every(r=>r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?!0:Array.isArray(r)?r.every(n=>gte(n)||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||n===null):ar(r)?gte(r):!1):!1}function Rk(e){return gte(e)?e:void 0}function BOt(e){if(!ar(e))return!1;const t=e;if(t.blockedTools!==void 0&&(!Array.isArray(t.blockedTools)||!t.blockedTools.every(o=>typeof o=="string")))return!1;const r=typeof t.command=="string",n=typeof t.url=="string";return!r&&!n?!1:(t.command===void 0||typeof t.command=="string")&&(t.args===void 0||Array.isArray(t.args))&&(t.env===void 0||ar(t.env))&&(t.transport===void 0||typeof t.transport=="string")&&(t.timeout===void 0||typeof t.timeout=="number")&&(t.retries===void 0||typeof t.retries=="number")&&(t.healthCheckInterval===void 0||typeof t.healthCheckInterval=="number")&&(t.autoRestart===void 0||typeof t.autoRestart=="boolean")&&(t.cwd===void 0||typeof t.cwd=="string")&&(t.url===void 0||typeof t.url=="string")&&(t.headers===void 0||ar(t.headers))&&(t.httpOptions===void 0||ar(t.httpOptions))&&(t.retryConfig===void 0||ar(t.retryConfig))&&(t.rateLimiting===void 0||ar(t.rateLimiting))&&(t.metadata===void 0||ar(t.metadata))}var yte,cL,vte,uL,zOt,_te,jOt=S({"src/lib/mcp/externalServerManager.ts"(){"use strict";vn(),q(),cte(),VBr(),fte(),a1(),dte(),pf(),KE(),yr(),er(),yte=/^--(api-key|token|secret|password|key|figma-api-key|access-token|auth|credential)$/i,cL=new Set,vte=!1,uL=()=>{for(const e of cL)e.shutdown()},zOt=e=>{cL.add(e),vte||(vte=!0,process.on("SIGINT",uL),process.on("SIGTERM",uL),process.on("beforeExit",uL))},_te=class extends nn{servers=new Map;config;isShuttingDown=!1;toolDiscovery;enableMainRegistryIntegration;hitlManager;constructor(e={},t={}){super();const r=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4);this.config={maxServers:e.maxServers??10,defaultTimeout:e.defaultTimeout??r,defaultHealthCheckInterval:e.defaultHealthCheckInterval??3e4,enableAutoRestart:e.enableAutoRestart??!0,maxRestartAttempts:e.maxRestartAttempts??3,restartBackoffMultiplier:e.restartBackoffMultiplier??2,enablePerformanceMonitoring:e.enablePerformanceMonitoring??!0,logLevel:e.logLevel??"info"},this.enableMainRegistryIntegration=t.enableMainRegistryIntegration??!1,this.toolDiscovery=new kOt,this.toolDiscovery.on("toolRegistered",n=>{this.emit("toolDiscovered",{...n,serverName:this.getServerName(n.serverId)})}),this.toolDiscovery.on("toolUnregistered",n=>{this.emit("toolRemoved",{...n,serverName:this.getServerName(n.serverId)})}),zOt(this)}setOutputNormalizer(e){this.toolDiscovery.setOutputNormalizer(e),de.debug("[ExternalServerManager] MCP output normalizer attached to ToolDiscoveryService")}setHITLManager(e){this.hitlManager=e,e&&e.isEnabled()?de.info("[ExternalServerManager] HITL safety mechanisms enabled for external tool execution"):de.debug("[ExternalServerManager] HITL safety mechanisms disabled or not configured")}getHITLManager(){return this.hitlManager}getServerName(e){return this.servers.get(e)?.config?.name||e}async loadMCPConfiguration(e,t={}){return t.parallel?this.loadMCPConfigurationParallel(e):this.loadMCPConfigurationSequential(e)}async loadMCPConfigurationParallel(e){const t=await Promise.resolve().then(()=>(gn(),_l)),r=await Promise.resolve().then(()=>(Lr(),Hc)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return de.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};de.debug(`[ExternalServerManager] Loading MCP configuration in PARALLEL mode from ${n}`);try{const o=t.readFileSync(n,"utf8"),s=JSON.parse(o);if(!s.mcpServers||typeof s.mcpServers!="object")return de.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};const i=Object.entries(s.mcpServers).map(async([u,d])=>{try{if(!BOt(d))throw new Error(`Invalid server config for ${u}: missing required properties or wrong types`);const m={id:u,name:u,description:typeof d.description=="string"?d.description:`External MCP server: ${u}`,transport:typeof d.transport=="string"?d.transport:"stdio",status:"initializing",tools:[],command:typeof d.command=="string"?d.command:void 0,args:Array.isArray(d.args)?d.args:[],env:ar(d.env)?P_(d.env):{},timeout:typeof d.timeout=="number"?d.timeout:void 0,retries:typeof d.retries=="number"?d.retries:void 0,healthCheckInterval:typeof d.healthCheckInterval=="number"?d.healthCheckInterval:void 0,autoRestart:typeof d.autoRestart=="boolean"?d.autoRestart:void 0,cwd:typeof d.cwd=="string"?d.cwd:void 0,url:typeof d.url=="string"?d.url:void 0,headers:ar(d.headers)?P_(d.headers):void 0,httpOptions:ar(d.httpOptions)?d.httpOptions:void 0,retryConfig:ar(d.retryConfig)?d.retryConfig:void 0,rateLimiting:ar(d.rateLimiting)?d.rateLimiting:void 0,blockedTools:Array.isArray(d.blockedTools)?d.blockedTools:void 0,metadata:Rk(d.metadata)},h=await this.addServer(u,m);return{serverId:u,result:h}}catch(m){const h=`Failed to load MCP server ${u}: ${m instanceof Error?m.message:String(m)}`;return{serverId:u,error:h}}}),a=await Promise.allSettled(i);let l=0;const c=[];for(const u of a)if(u.status==="fulfilled"){const{serverId:d,result:m,error:h}=u.value;if(m&&m.success)l++,de.debug(`[ExternalServerManager] Successfully loaded MCP server in parallel: ${d}`);else if(h)c.push(h),de.error(`[ExternalServerManager] Failed to load server ${d}: ${h}`);else if(m&&!m.success){const g=`Failed to load server ${d}: ${m.error}`;c.push(g),de.error(`[ExternalServerManager] ${g}`)}}else{const d=`Unexpected error during parallel loading: ${u.reason}`;c.push(d),de.error(`[ExternalServerManager] ${d}`)}return de.info(`[ExternalServerManager] PARALLEL MCP configuration loading complete: ${l} servers loaded, ${c.length} errors`),{serversLoaded:l,errors:c}}catch(o){const s=`Failed to load MCP configuration in parallel mode: ${o instanceof Error?o.message:String(o)}`;return de.error(`[ExternalServerManager] ${s}`),{serversLoaded:0,errors:[s]}}}async loadMCPConfigurationSequential(e){const t=await Promise.resolve().then(()=>(gn(),_l)),r=await Promise.resolve().then(()=>(Lr(),Hc)),n=e||r.join(process.cwd(),".mcp-config.json");if(!t.existsSync(n))return de.debug(`[ExternalServerManager] No MCP config found at ${n}`),{serversLoaded:0,errors:[]};de.debug(`[ExternalServerManager] Loading MCP configuration from ${n}`);try{const o=t.readFileSync(n,"utf8"),s=JSON.parse(o);if(!s.mcpServers||typeof s.mcpServers!="object")return de.debug("[ExternalServerManager] No mcpServers found in configuration"),{serversLoaded:0,errors:[]};let i=0;const a=[];for(const[l,c]of Object.entries(s.mcpServers))try{if(!BOt(c))throw new Error(`Invalid server config for ${l}: missing required properties or wrong types`);const u={id:l,name:l,description:typeof c.description=="string"?c.description:`External MCP server: ${l}`,transport:typeof c.transport=="string"?c.transport:"stdio",status:"initializing",tools:[],command:typeof c.command=="string"?c.command:void 0,args:Array.isArray(c.args)?c.args:[],env:ar(c.env)?P_(c.env):{},timeout:typeof c.timeout=="number"?c.timeout:void 0,retries:typeof c.retries=="number"?c.retries:void 0,healthCheckInterval:typeof c.healthCheckInterval=="number"?c.healthCheckInterval:void 0,autoRestart:typeof c.autoRestart=="boolean"?c.autoRestart:void 0,cwd:typeof c.cwd=="string"?c.cwd:void 0,url:typeof c.url=="string"?c.url:void 0,headers:ar(c.headers)?P_(c.headers):void 0,httpOptions:ar(c.httpOptions)?c.httpOptions:void 0,retryConfig:ar(c.retryConfig)?c.retryConfig:void 0,rateLimiting:ar(c.rateLimiting)?c.rateLimiting:void 0,blockedTools:Array.isArray(c.blockedTools)?c.blockedTools:void 0,metadata:Rk(c.metadata)},d=await this.addServer(l,u);if(d.success)i++,de.debug(`[ExternalServerManager] Successfully loaded MCP server: ${l}`);else{const m=`Failed to load server ${l}: ${d.error}`;a.push(m),de.error(`[ExternalServerManager] ${m}`)}}catch(u){const d=`Failed to load MCP server ${l}: ${u instanceof Error?u.message:String(u)}`;a.push(d),de.error(`[ExternalServerManager] ${d}`)}return de.info(`[ExternalServerManager] MCP configuration loading complete: ${i} servers loaded, ${a.length} errors`),{serversLoaded:i,errors:a}}catch(o){const s=`Failed to load MCP configuration: ${o instanceof Error?o.message:String(o)}`;return de.error(`[ExternalServerManager] ${s}`),{serversLoaded:0,errors:[s]}}}validateConfig(e){const t=[],r=[],n=[];return(!e.id||typeof e.id!="string")&&t.push("Server ID is required and must be a string"),["stdio","sse","websocket","http"].includes(e.transport)||t.push("Transport must be one of: stdio, sse, websocket, http"),e.transport==="stdio"?((!e.command||typeof e.command!="string")&&t.push("Command is required and must be a string for stdio transport"),Array.isArray(e.args)||t.push("Args must be an array")):(e.transport==="sse"||e.transport==="websocket"||e.transport==="http")&&(!e.url||typeof e.url!="string")&&t.push(`URL is required for ${e.transport} transport`),e.timeout&&e.timeout<5e3&&r.push("Timeout less than 5 seconds may cause connection issues"),e.retries&&e.retries>5&&r.push("High retry count may slow down error recovery"),e.healthCheckInterval||n.push("Consider setting a health check interval for better reliability"),e.autoRestart===void 0&&n.push("Consider enabling auto-restart for production use"),{isValid:t.length===0,errors:t,warnings:r,suggestions:n}}convertConfigToMCPServerInfo(e,t){return{id:e,name:String(t.metadata?.title||e),description:`External MCP server (${t.transport})`,status:"initializing",transport:t.transport,command:t.command,args:t.args,env:t.env,tools:[],blockedTools:t.blockedTools,timeout:t.timeout,retries:t.retries,healthCheckInterval:t.healthCheckInterval,autoRestart:t.autoRestart,cwd:t.cwd,url:t.url,metadata:{category:"external",...Rk(t.metadata)||{}}}}async addServer(e,t){const r=Date.now();try{const n="transport"in t&&"command"in t&&!("tools"in t)?this.convertConfigToMCPServerInfo(e,t):t;if(this.servers.size>=this.config.maxServers)return{success:!1,error:`Maximum number of servers (${this.config.maxServers}) reached`,serverId:e,duration:Date.now()-r};const o={id:e,name:n.name,description:n.description,transport:n.transport,status:n.status,tools:n.tools,command:n.command||"",args:n.args||[],env:n.env||{},timeout:n.timeout,retries:n.retries,healthCheckInterval:n.healthCheckInterval,autoRestart:n.autoRestart,cwd:n.cwd,url:n.url,blockedTools:n.blockedTools,metadata:Rk(n.metadata),headers:n.headers,httpOptions:n.httpOptions,retryConfig:n.retryConfig,rateLimiting:n.rateLimiting},s=this.validateConfig(o);if(!s.isValid)return{success:!1,error:`Configuration validation failed: ${s.errors.join(", ")}`,serverId:e,duration:Date.now()-r};if(this.servers.has(e))return{success:!1,error:`Server with ID '${e}' already exists`,serverId:e,duration:Date.now()-r};de.info(`[ExternalServerManager] Adding server: ${e}`,{command:n.command,transport:n.transport});const i={...n,process:null,client:null,transportInstance:null,status:"initializing",reconnectAttempts:0,maxReconnectAttempts:this.config.maxRestartAttempts,toolsMap:new Map,metrics:{totalConnections:0,totalDisconnections:0,totalErrors:0,totalToolCalls:0,averageResponseTime:0,lastResponseTime:0},config:o};this.servers.set(e,i),await this.startServer(e);const a=this.servers.get(e);if(!a)throw new Error(`Server ${e} not found after registration`);return{success:!0,data:{config:a.config,process:a.process,client:a.client,transport:a.transportInstance,status:a.status,lastError:a.lastError,startTime:a.startTime,lastHealthCheck:a.lastHealthCheck,reconnectAttempts:a.reconnectAttempts,maxReconnectAttempts:a.maxReconnectAttempts,tools:a.toolsMap,toolsArray:a.toolsArray,capabilities:a.capabilities,healthTimer:a.healthTimer,restartTimer:a.restartTimer,metrics:a.metrics},serverId:e,duration:Date.now()-r,metadata:{timestamp:Date.now(),operation:"addServer",toolsDiscovered:a.tools.length}}}catch(n){return de.debug(`[ExternalServerManager] Failed to add server ${e}:`,n),this.servers.delete(e),{success:!1,error:n instanceof Error?n.message:String(n),serverId:e,duration:Date.now()-r}}}async removeServer(e){const t=Date.now();try{if(!this.servers.get(e))return{success:!1,error:`Server '${e}' not found`,serverId:e,duration:Date.now()-t};de.info(`[ExternalServerManager] Removing server: ${e}`);const n=this.getServerName(e);return await this.stopServer(e),this.servers.delete(e),this.emit("disconnected",{serverId:e,serverName:n,reason:"Manually removed",timestamp:new Date}),{success:!0,serverId:e,duration:Date.now()-t,metadata:{timestamp:Date.now(),operation:"removeServer"}}}catch(r){return de.error(`[ExternalServerManager] Failed to remove server ${e}:`,r),{success:!1,error:r instanceof Error?r.message:String(r),serverId:e,duration:Date.now()-t}}}async startServer(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);const r=t.config,n=He.mcp.startSpan("neurolink.mcp.server.start",{attributes:{"mcp.server_id":e,"mcp.transport":r.transport,"mcp.command_name":r.command&&r.command.split(/[\\/]/).pop()||"","mcp.command_present":!!r.command}});try{this.updateServerStatus(e,"connecting"),de.debug(`[ExternalServerManager] Starting server: ${e}`,{command:r.command,args:ZBr(r.args),transport:r.transport});const o=await xk.createClient(r,r.timeout||this.config.defaultTimeout);if(!o.success||!o.client||!o.transport)throw new Error(`Failed to create MCP client: ${o.error}`);t.client=o.client,t.transportInstance=o.transport,t.process=o.process||null,t.capabilities=Rk(o.capabilities),t.startTime=new Date,t.lastHealthCheck=new Date,t.metrics.totalConnections++,t.process&&(t.process.on("error",s=>{de.error(`[ExternalServerManager] Process error for ${e}:`,s),this.handleServerError(e,s)}),t.process.on("exit",(s,i)=>{de.warn(`[ExternalServerManager] Process exited for ${e}`,{code:s,signal:i}),this.handleServerDisconnection(e,`Process exited with code ${s}`)}),t.process.stderr?.on("data",s=>{const i=s.toString().trim();i&&de.debug(`[ExternalServerManager] ${e} stderr:`,i)})),this.updateServerStatus(e,"connected"),await this.discoverServerTools(e),this.enableMainRegistryIntegration&&await this.registerServerToolsWithMainRegistry(e),this.startHealthMonitoring(e),this.emit("connected",{serverId:e,serverName:this.getServerName(e),toolCount:t.toolsMap.size,timestamp:new Date}),n.setAttribute("mcp.tool_count",t.toolsMap.size),n.setStatus({code:qe.OK}),de.info(`[ExternalServerManager] Server started successfully: ${e}`)}catch(o){throw de.debug(`[ExternalServerManager] Failed to start server ${e}:`,o),this.updateServerStatus(e,"failed"),t.lastError=o instanceof Error?o.message:String(o),n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:qe.ERROR,message:o instanceof Error?o.message:String(o)}),o}finally{n.end()}}async stopServer(e){const t=this.servers.get(e);if(!t)return;const r=He.mcp.startSpan("neurolink.mcp.server.stop",{attributes:{"mcp.server_id":e}});try{if(this.updateServerStatus(e,"stopping"),t.healthTimer&&(clearInterval(t.healthTimer),t.healthTimer=void 0),t.restartTimer&&(clearTimeout(t.restartTimer),t.restartTimer=void 0),this.enableMainRegistryIntegration&&this.unregisterServerToolsFromMainRegistry(e),this.toolDiscovery.clearServerTools(e),t.client&&t.transportInstance){try{await xk.closeClient(t.client,t.transportInstance,t.process||void 0)}catch(n){de.debug(`[ExternalServerManager] Error closing client for ${e}:`,n)}t.client=null,t.transportInstance=null,t.process=null}this.updateServerStatus(e,"stopped"),r.setStatus({code:qe.OK}),de.info(`[ExternalServerManager] Server stopped: ${e}`)}catch(n){de.error(`[ExternalServerManager] Error stopping server ${e}:`,n),this.updateServerStatus(e,"failed"),r.recordException(n instanceof Error?n:new Error(String(n))),r.setStatus({code:qe.ERROR,message:n instanceof Error?n.message:String(n)})}finally{r.end()}}updateServerStatus(e,t){const r=this.servers.get(e);if(!r)return;const n=r.status,o=t==="connecting"||t==="restarting"?"initializing":t==="stopping"||t==="stopped"?"stopping":t==="connected"?"connected":t==="disconnected"?"disconnected":"failed";r.status=o,this.emit("statusChanged",{serverId:e,serverName:this.getServerName(e),oldStatus:n,newStatus:t,timestamp:new Date}),de.debug(`[ExternalServerManager] Status changed for ${e}: ${n} -> ${t}`)}handleServerError(e,t){const r=this.servers.get(e);r&&(r.lastError=t.message,r.metrics.totalErrors++,de.error(`[ExternalServerManager] Server error for ${e}:`,t),this.emit("failed",{serverId:e,serverName:this.getServerName(e),error:t.message,timestamp:new Date}),this.config.enableAutoRestart&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"failed"))}handleServerDisconnection(e,t){const r=this.servers.get(e);r&&(r.metrics.totalDisconnections++,de.warn(`[ExternalServerManager] Server disconnected ${e}: ${t}`),this.emit("disconnected",{serverId:e,serverName:this.getServerName(e),reason:t,timestamp:new Date}),(r.config.autoRestart??this.config.enableAutoRestart)&&!this.isShuttingDown?this.scheduleRestart(e):this.updateServerStatus(e,"disconnected"))}scheduleRestart(e){const t=this.servers.get(e);if(!t)return;if(t.reconnectAttempts>=t.maxReconnectAttempts){de.error(`[ExternalServerManager] Max restart attempts reached for ${e}`),this.updateServerStatus(e,"failed");return}t.reconnectAttempts++,this.updateServerStatus(e,"restarting");const r=Math.min(1e3*Math.pow(this.config.restartBackoffMultiplier,t.reconnectAttempts-1),3e4);de.info(`[ExternalServerManager] Scheduling restart for ${e} in ${r}ms (attempt ${t.reconnectAttempts})`),!t.restartTimer&&(t.restartTimer=setTimeout(async()=>{const n=He.mcp.startSpan("neurolink.mcp.server.restart",{attributes:{"mcp.server_id":e,"mcp.restart_attempt":t.reconnectAttempts,"mcp.restart_delay_ms":r}});try{await this.stopServer(e),await this.startServer(e),t.reconnectAttempts=0,n.setStatus({code:qe.OK})}catch(o){de.error(`[ExternalServerManager] Restart failed for ${e}:`,o),n.recordException(o instanceof Error?o:new Error(String(o))),n.setStatus({code:qe.ERROR,message:o instanceof Error?o.message:String(o)}),this.scheduleRestart(e)}finally{n.end()}},r))}startHealthMonitoring(e){const t=this.servers.get(e);if(!t||!this.config.enablePerformanceMonitoring)return;const r=t.config.healthCheckInterval??this.config.defaultHealthCheckInterval;t.healthTimer=setInterval(async()=>{await this.performHealthCheck(e)},r)}async performHealthCheck(e){const t=this.servers.get(e);if(!t||t.status!=="connected")return;const r=Date.now();try{let n=!0;const o=[];t.process&&t.process.killed&&(n=!1,o.push("Process is killed"));const s=Date.now()-r;t.lastHealthCheck=new Date;const i={serverId:e,isHealthy:n,status:t.status,checkedAt:new Date,responseTime:s,toolCount:t.toolsMap.size,issues:o,performance:{uptime:t.startTime?Date.now()-t.startTime.getTime():0,averageResponseTime:t.metrics.averageResponseTime}};this.emit("healthCheck",{serverId:e,serverName:this.getServerName(e),health:i,timestamp:new Date}),n||(de.warn(`[ExternalServerManager] Health check failed for ${e}:`,o),this.handleServerError(e,new Error(`Health check failed: ${o.join(", ")}`)))}catch(n){de.error(`[ExternalServerManager] Health check error for ${e}:`,n),this.handleServerError(e,n instanceof Error?n:new Error(String(n)))}}getServer(e){const t=this.servers.get(e);if(t)return{config:t.config,process:t.process,client:t.client,transport:t.transportInstance,status:t.status,lastError:t.lastError,startTime:t.startTime,lastHealthCheck:t.lastHealthCheck,reconnectAttempts:t.reconnectAttempts,maxReconnectAttempts:t.maxReconnectAttempts,tools:t.toolsMap,toolsArray:t.toolsArray,capabilities:t.capabilities,healthTimer:t.healthTimer,restartTimer:t.restartTimer,metrics:t.metrics}}getAllServers(){const e=new Map;for(const[t,r]of this.servers.entries())e.set(t,{config:r.config,process:r.process,client:r.client,transport:r.transportInstance,status:r.status,lastError:r.lastError,startTime:r.startTime,lastHealthCheck:r.lastHealthCheck,reconnectAttempts:r.reconnectAttempts,maxReconnectAttempts:r.maxReconnectAttempts,tools:r.toolsMap,toolsArray:r.toolsArray,capabilities:r.capabilities,healthTimer:r.healthTimer,restartTimer:r.restartTimer,metrics:r.metrics});return e}listServers(){return Array.from(this.servers.values())}getServerStatuses(){const e=[];for(const[t,r]of Array.from(this.servers.entries())){const n=r.startTime?Date.now()-r.startTime.getTime():0;e.push({serverId:t,isHealthy:r.status==="connected",status:r.status,checkedAt:r.lastHealthCheck||new Date,toolCount:r.toolsMap.size,issues:r.lastError?[r.lastError]:[],performance:{uptime:n,averageResponseTime:r.metrics.averageResponseTime}})}return e}async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0,cL.delete(this),de.info("[ExternalServerManager] Shutting down all servers...");const e=Array.from(this.servers.keys()).map(t=>this.stopServer(t).catch(r=>{de.error(`[ExternalServerManager] Error shutting down ${t}:`,r)}));await Promise.all(e),this.servers.clear(),this.toolDiscovery.destroy(),this.removeAllListeners(),de.info("[ExternalServerManager] All servers shut down and resources cleaned up")}async destroy(){return this.shutdown()}getStatistics(){let e=0,t=0,r=0,n=0,o=0;for(const s of Array.from(this.servers.values()))s.status==="connected"?e++:s.status==="failed"&&t++,r+=s.toolsMap.size,n+=s.metrics.totalConnections,o+=s.metrics.totalErrors;return{totalServers:this.servers.size,connectedServers:e,failedServers:t,totalTools:r,totalConnections:n,totalErrors:o}}async discoverServerTools(e){const t=this.servers.get(e);if(!t||!t.client)throw new Error(`Server '${e}' not found or not connected`);try{de.debug(`[ExternalServerManager] Discovering tools for server: ${e}`);const r=await this.toolDiscovery.discoverTools(e,t.client,t.config.timeout||this.config.defaultTimeout);if(r.success){t.toolsMap.clear(),t.toolsArray=void 0,t.tools=[];const n=t.blockedTools||[];let o=0;for(const s of r.tools){if(n.includes(s.name)){de.info(`[ExternalServerManager] Blocking tool '${s.name}' from server '${e}' (configured in blockedTools)`),o++;continue}t.toolsMap.set(s.name,s),t.tools.push({name:s.name,description:s.description,inputSchema:s.inputSchema})}de.info(`[ExternalServerManager] Discovered ${r.toolCount} tools for ${e} (${o} blocked, ${t.toolsMap.size} available)`)}else de.warn(`[ExternalServerManager] Tool discovery failed for ${e}: ${r.error}`)}catch(r){de.error(`[ExternalServerManager] Tool discovery error for ${e}:`,r)}}async registerServerToolsWithMainRegistry(e){const t=this.servers.get(e);if(!t)throw new Error(`Server '${e}' not found`);try{de.debug(`[ExternalServerManager] Registering ${t.toolsMap.size} tools with main registry for server: ${e}`);const r=[];for(const[i,a]of t.toolsMap.entries()){const l=`${e}.${i}`,c={name:i,description:a.description||i,inputSchema:a.inputSchema||{},serverId:e,category:xa({isExternal:!0,serverId:e})};try{r.push(hte.registerTool(l,c,{execute:async(u,d)=>await this.executeTool(e,i,u,{timeout:t.config.timeout||this.config.defaultTimeout})})),de.debug(`[ExternalServerManager] Registered tool with main registry: ${l}`)}catch(u){de.warn(`[ExternalServerManager] Failed to register tool ${l} with main registry:`,u)}}const n=await Promise.allSettled(r),o=n.filter(i=>i.status==="fulfilled").length,s=n.length-o;de.info(`[ExternalServerManager] Registered ${o}/${n.length} tools with main registry for ${e}${s?` (${s} failed)`:""}`)}catch(r){de.error(`[ExternalServerManager] Failed to register tools with main registry for ${e}:`,r)}}unregisterServerToolsFromMainRegistry(e){const t=this.servers.get(e);if(!(!t||!this.enableMainRegistryIntegration))try{de.debug(`[ExternalServerManager] Unregistering tools from main registry for server: ${e}`);for(const[r]of t.toolsMap.entries()){const n=`${e}.${r}`;try{hte.removeTool(n),de.debug(`[ExternalServerManager] Unregistered tool from main registry: ${n}`)}catch(o){de.debug(`[ExternalServerManager] Failed to unregister tool ${n}:`,o)}}de.debug(`[ExternalServerManager] Completed unregistering tools from main registry for ${e}`)}catch(r){de.error(`[ExternalServerManager] Error unregistering tools from main registry for ${e}:`,r)}}async executeTool(e,t,r,n){const o=this.servers.get(e);if(!o)throw new Error(`Server '${e}' not found`);if(!o.client)throw new Error(`Server '${e}' is not connected`);if(o.status!=="connected")throw new Error(`Server '${e}' is not in connected state: ${o.status}`);if((o.blockedTools||[]).includes(t))throw new Error(`Tool '${t}' is blocked on server '${e}' by configuration`);const i=Date.now();try{let a=r;if(this.hitlManager&&this.hitlManager.isEnabled())if(this.hitlManager.requiresConfirmation(t,r)){de.info(`[ExternalServerManager] External tool '${t}' on server '${e}' requires HITL confirmation`);try{const m=await this.hitlManager.requestConfirmation(t,r,{serverId:e,sessionId:`external-${e}-${Date.now()}`,userId:void 0});if(!m.approved)throw new bT(`External tool execution rejected by user: ${m.reason||"No reason provided"}`,t,m.reason);m.modifiedArguments!==void 0&&(a=m.modifiedArguments,de.info(`[ExternalServerManager] External tool '${t}' arguments modified by user`)),de.info(`[ExternalServerManager] External tool '${t}' approved for execution (response time: ${m.responseTime}ms)`)}catch(m){throw m instanceof TT?(de.warn(`[ExternalServerManager] External tool '${t}' execution timed out waiting for user confirmation`),m):m instanceof bT?(de.info(`[ExternalServerManager] External tool '${t}' execution rejected by user`),m):(de.error(`[ExternalServerManager] HITL confirmation failed for external tool '${t}':`,m),new Error(`HITL confirmation failed: ${m instanceof Error?m.message:String(m)}`,{cause:m}))}}else de.debug(`[ExternalServerManager] External tool '${t}' does not require HITL confirmation`);const l=await this.toolDiscovery.executeTool(t,e,o.client,a,{timeout:n?.timeout||o.config.timeout||this.config.defaultTimeout}),c=Date.now()-i;o.metrics.totalToolCalls++,o.metrics.lastResponseTime=c;const u=o.metrics.averageResponseTime*(o.metrics.totalToolCalls-1)+c;if(o.metrics.averageResponseTime=u/o.metrics.totalToolCalls,l.success){de.debug(`[ExternalServerManager] Tool executed successfully: ${t} on ${e}`,{duration:c});try{kf.getInstance()?.recordMCPToolCall(t,c,!0)}catch{}return l.data}else throw new Error(l.error||"Tool execution failed")}catch(a){o.metrics.totalErrors++;try{const l=Date.now()-i;kf.getInstance()?.recordMCPToolCall(t,l,!1)}catch{}throw de.error(`[ExternalServerManager] Tool execution failed: ${t} on ${e}`,a),a}}getAllTools(){return this.toolDiscovery.getAllTools()}getServerTools(e){return this.toolDiscovery.getServerTools(e)}getToolDiscovery(){return this.toolDiscovery}}}});function XBr(e,t,r,n){return{content:[{type:"text",text:`[MCP Tool Output \u2014 ${r.toolName} | ${r.serverId}]
|
|
1482
1482
|
Original size: ${Mk(n)} | Externalized \u2014 use retrieve_context with artifactId="${t}" to read the full output (supports offset + limit pagination)
|
|
@@ -2158,7 +2158,7 @@ ${r}`:r}}return t?`${t}
|
|
|
2158
2158
|
|
|
2159
2159
|
${r}`:r}async retrieveKnowledgeGrounding(t){const r=this.knowledgeGroundingEngine;if(!r||!r.isEnabled()||t.useKnowledgeGrounding!==!0)return;const n=t.input?.text;if(n)try{const s=(t.conversationMessages!==void 0?t.conversationMessages:await this.fetchRecentRoutingHistory(t)).filter(i=>i.role==="user"||i.role==="assistant").slice(-nN).map(i=>({role:i.role==="assistant"?"assistant":"user",text:typeof i.content=="string"?i.content:""}));return await r.ground({query:n,recentTurns:s,scope:t.knowledgeContext})}catch(o){f.warn("[KnowledgeGrounding] grounding hook failed open",{error:String(o)});return}}async validateStreamRequestOptions(t,r){if(await this.validateStreamInput(t),t.inputValidation&&t.input?.text){const n=t.inputValidation;if(n.trimWhitespace&&(t.input.text=t.input.text.trim()),n.requireContent&&!t.input.text.trim())throw new Error("Input content is required but was empty or whitespace");if(n.minLength&&t.input.text.length<n.minLength)throw new Error(`Input text is too short (${t.input.text.length} < ${n.minLength})`);if(n.maxLength&&t.input.text.length>n.maxLength)throw new Error(`Input text is too long (${t.input.text.length} > ${n.maxLength})`)}if(t.piiDetection?.enabled&&t.input?.text){const n=await Hne(t.input.text,{enabled:!0,action:t.piiDetection.action??"warn",detectTypes:t.piiDetection.detectTypes,customPatterns:t.piiDetection.customPatterns,allowList:t.piiDetection.allowList,redactionText:t.piiDetection.redactionText});if(n.action==="abort")throw new Error(n.feedback??"Request blocked: PII detected in input");t.input.text=n.text}this.enforceSessionBudget(t.maxBudgetUsd),await this.applyAuthenticatedRequestContext(t),this.emitStreamStartEvents(t,r),this.applyStreamLifecycleMiddleware(t)}async maybeHandleWorkflowStreamRequest(t){if(!t.options.workflow&&!t.options.workflowConfig)return null;const r=await this.streamWithWorkflow(t.options,t.startTime),n=r.stream,o=this;return r.stream=(async function*(){try{for await(const s of n)yield s;t.streamSpan.setStatus({code:qe.OK})}catch(s){throw t.streamSpan.setStatus({code:qe.ERROR,message:s instanceof Error?s.message:String(s)}),s}finally{o._disableToolCacheForCurrentRequest=!1,o._toolCacheKeysServedThisRequest=new Set,o._generationTurnActive=!1,t.streamSpan.setAttribute("neurolink.response_time_ms",Date.now()-t.spanStartTime),t.streamSpan.end()}})(),r}async runStandardStreamRequest(t){const{options:r,streamSpan:n,spanStartTime:o,startTime:s,hrTimeStart:i,streamId:a,originalPrompt:l,ttsResolver:c,ttsMetadataSink:u}=t;f.debug("[NeuroLink] Running standard stream request",{streamId:a,provider:r.provider,model:r.model,inputLength:r.input?.text?.length||0,disableTools:r.disableTools,enableAnalytics:r.enableAnalytics,enableEvaluation:r.enableEvaluation,contextKeys:r.context?Object.keys(r.context):[],optionKeys:Object.keys(r),sessionId:r.context?.sessionId});try{const{enhancedOptions:d,factoryResult:m}=await this.prepareStreamOptions(r,a,s,i);f.debug("[NeuroLink] Stream options prepared",{streamId:a,options:d,factoryResult:m,sessionId:d.context?.sessionId});const{stream:h,provider:g,usage:y,model:v,finishReason:_,toolCalls:b,toolResults:T,analytics:k,metadata:A}=await this.createMCPStream(d);let I;const{stream:M,ttsMetadata:R}=await this.createIncrementalTTSStream({stream:h,ttsOptions:d.tts,providerName:g,fallbackProvider:d.provider,onComplete:Y=>{I=Y}});u?.(R);const x={finishReason:_??"stop",toolCalls:b,toolResults:T};n.setAttribute(Pe.NL_PROVIDER,g||"unknown");let O="",N=0;const{eventSequence:P,cleanup:D}=this.setupStreamEventListeners(),L={fallbackAttempted:!1,guardrailsBlocked:!1,error:void 0,fallbackProvider:void 0,fallbackModel:void 0},$=this,U=Date.now(),j=d.context?.sessionId,B={providerEmitted:!1};d._streamDedupContext=B;const z=(async function*(){let Y,ie,ce=0;try{for await(const G of M){N++;const K=G!==null&&typeof G=="object"&&"metadata"in G&&G.metadata?.noOutput===!0,Ce=G&&"content"in G&&typeof G.content=="string"&&G.content.length>0,be=G!==null&&typeof G=="object"&&"type"in G&&(G.type==="audio"||G.type==="tts_audio"||G.type==="image");!K&&(Ce||be)&&ce++,G&&"content"in G&&typeof G.content=="string"&&(O+=G.content,$.emitter.emit("response:chunk",G.content),$.emitter.emit("stream:chunk",{type:"stream:chunk",content:G.content,metadata:{chunkIndex:N,totalLength:O.length,...K&&{noOutput:!0}},timestamp:Date.now()})),yield G}const re=d.fallbackOnMaxSteps===!1&&A?.stopReason==="step-cap";if(ce===0&&!re&&!L.fallbackAttempted&&!d.disableInternalFallback&&x.toolCalls.length===0&&x.toolResults.length===0){const G=$.handleStreamFallback(L,x,l,d,g,Ce=>{O+=Ce}),{stream:K}=await $.createIncrementalTTSStream({stream:G,ttsOptions:d.tts,providerName:g,fallbackProvider:d.provider,ttsMetadata:R,onComplete:Ce=>{I=Ce}});yield*K}if(c?.(I),ie=y,!ie&&k)try{const G=await Promise.resolve(k);G?.tokenUsage&&(ie=G.tokenUsage)}catch{}$.emitter.emit("stream:complete",{type:"stream:complete",content:O,provider:L.fallbackProvider??g,model:L.fallbackModel??v??d.model,finishReason:x.finishReason??"stop",prompt:d.input?.text||d.prompt,metadata:{chunkCount:N,totalLength:O.length,durationMs:Date.now()-U,sessionId:j,usage:ie,finishReason:x.finishReason??"stop",...L.fallbackAttempted&&{primaryProvider:g,primaryModel:d.model,fallback:!0}},timestamp:Date.now()})}catch(re){throw f.debug("[NeuroLink.stream] Stream error occurred",{error:re instanceof Error?re.message:String(re),name:re instanceof Error?re.name:"UnknownError",provider:g,model:d.model,chunkCount:N,totalLength:O.length,durationMs:Date.now()-U,sessionId:j}),Y=re,$.emitter.emit("stream:error",{type:"stream:error",content:re instanceof Error?re.message:String(re),provider:g,model:d.model,metadata:{chunkCount:N,totalLength:O.length,durationMs:Date.now()-U,errorName:re instanceof Error?re.name:"UnknownError",sessionId:j},timestamp:Date.now()}),re}finally{if(c?.(void 0),f.debug("[NeuroLink.stream] Stream finished, performing cleanup",{provider:g,model:d.model,totalChunks:N,totalLength:O.length,durationMs:Date.now()-U,fallbackAttempted:L.fallbackAttempted,guardrailsBlocked:L.guardrailsBlocked,error:L.error}),!B.providerEmitted)try{const G=L.fallbackProvider??g??"unknown",K=L.fallbackModel??v??d.model??"unknown",Ce=Y?"error":x.finishReason??"stop";$.emitter.emit("generation:end",{provider:G,model:K,responseTime:Date.now()-U,toolsUsed:x.toolCalls?.map(be=>be.toolName),timestamp:Date.now(),result:{content:O,usage:ie,model:K,provider:G,finishReason:Ce},prompt:d.input?.text||d.prompt,temperature:d.temperature,maxTokens:d.maxTokens,success:!Y,error:Y?Y instanceof Error?Y.message:String(Y):void 0,pipelineAHandled:!0})}catch(G){f.debug("[NeuroLink.stream] generation:end listener threw \u2014 ignored",{error:G instanceof Error?G.message:String(G)})}$._disableToolCacheForCurrentRequest=!1,$._toolCacheKeysServedThisRequest=new Set,$._generationTurnActive=!1,D(),n.setAttribute("neurolink.response_time_ms",Date.now()-o),n.setAttribute(Pe.NL_OUTPUT_LENGTH,O.length);const re=!!(L.error||Y);n.setAttribute(Pe.GEN_AI_FINISH_REASON,re?"error":"stop"),L.fallbackAttempted&&(n.setAttribute("neurolink.fallback_triggered",!0),L.fallbackProvider&&n.setAttribute("neurolink.fallback_provider",L.fallbackProvider)),re?n.setStatus({code:qe.ERROR,message:L.error||(Y instanceof Error?Y.message:String(Y))}):n.setStatus({code:qe.OK}),n.end(),O.trim()&&f.info("[NeuroLink.stream] stream() - COMPLETE SUCCESS",{provider:g,model:d.model,responseTimeMs:Date.now()-s,contentLength:O.length,fallback:L.fallbackAttempted}),await $.storeStreamConversationMemory({enhancedOptions:d,providerName:g,originalPrompt:l,accumulatedContent:O,startTime:s,eventSequence:P})}})(),J=await this.processStreamResult(z,d,m);return J.finishReason=x.finishReason||J.finishReason,J.toolCalls=x.toolCalls,J.toolResults=x.toolResults,J.usage||(J.usage=y),J.analytics||(J.analytics=k),Promise.resolve(J.analytics).then(Y=>{Y?.cost&&Y.cost>0&&(this._sessionCostUsd+=Y.cost)}).catch(()=>{}),this.emitStreamEndEvents(J),this.createStreamResponse(J,z,{providerName:g,options:r,startTime:s,responseTime:Date.now()-s,streamId:a,fallback:L.fallbackAttempted,guardrailsBlocked:L.guardrailsBlocked,error:L.error,events:P,providerMetadata:A})}catch(d){if(c?.(void 0),r.disableInternalFallback)throw d;return this.handleStreamError(d,r,s,a,void 0,void 0)}}async createIncrementalTTSStream(t){const{stream:r,ttsOptions:n,providerName:o,fallbackProvider:s,onComplete:i}=t;if(!n?.enabled)return i(void 0),{stream:r};const{TTSProcessor:a}=await Promise.resolve().then(()=>(dc(),hqe)),l=s==="auto"?void 0:s,c=n.provider??l??o,u=c&&a.supports(c)?c:void 0,d=t.ttsMetadata??{attempted:u!==void 0,success:!1};d.attempted=u!==void 0,d.success=!1,delete d.error,delete d.latency;const m=Date.now();let h=!1;const g=(y,v)=>{h||(h=!0,d.success=v===void 0&&y!==void 0,v?d.error=v:delete d.error,d.latency=Date.now()-m,i(y))};return u?{stream:Aqe({stream:r,provider:u,options:n,onComplete:g}),ttsMetadata:d}:(f.warn(`[NeuroLink.stream] No TTS provider resolved for incremental streaming (set tts.provider explicitly \u2014 chat provider "${c??"<unset>"}" is not a registered TTS handler)`),g(void 0),{stream:r,ttsMetadata:d})}deferProviderStreamTTS(t){return t.tts?.enabled?{...t,tts:void 0}:t}async prepareStreamOptions(t,r,n,o){if(await this.initializeConversationMemoryForGeneration(r,n,o),await this.initializeMCP(),this.shouldReadMemory(t.memory,t.context?.userId)&&t.context?.userId)try{t.input.text=await this.retrieveMemory(t.input.text??"",t.context.userId,t.memory?.additionalUsers),f.debug("Memory retrieval successful")}catch(a){f.warn("Memory retrieval failed:",a)}if(await this.applySkillsAugmentation(t),this.enableOrchestration&&!t.provider&&!t.model)try{const a=await this.applyStreamOrchestration(t);f.debug("Stream orchestration applied",{originalProvider:t.provider||"auto",orchestratedProvider:a.provider,orchestratedModel:a.model,prompt:t.input.text?.substring(0,100)}),t={...t,...a},a.model&&(t.model=rx(t.model,this.modelAliasConfig))}catch(a){f.warn("Stream orchestration failed, continuing with original options",{error:a instanceof Error?a.message:String(a),originalProvider:t.provider||"auto"})}if(await this.autoDisableOllamaStreamTools(t),t.rag?.files?.length)try{const{prepareRAGTool:a}=await Promise.resolve().then(()=>(noe(),roe)),l=await a(t.rag,t.provider);t.tools||(t.tools={}),t.tools[l.toolName]=l.tool;const c=[`
|
|
2160
2160
|
|
|
2161
|
-
IMPORTANT: You have a tool called "${l.toolName}" that searches through`,`${l.filesLoaded} loaded document(s) containing ${l.chunksIndexed} indexed chunks.`,`ALWAYS use the "${l.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+c,f.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){f.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const s=zGr(t),i=jGr(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(i.input.text=l)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Af(),nqe)),s=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=t.model;s.length>0&&i&&(s.some(l=>i.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,f.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,m)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{const m=d[0];n("response:chunk",{content:m})},s=(...d)=>{const m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{const m=d[0],h=m.toolName??m.tool,g=m.responseTime??m.duration,y=m.success??(m.error!==void 0?!1:void 0),v={...m,toolName:h,...g!==void 0?{responseTime:g}:{},...y!==void 0?{success:y}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",v),v.result&&v.result.uiComponent===!0&&n("ui-component",{toolName:h,componentData:v.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...g!==void 0?{responseTime:g}:{}})},a=(...d)=>{n("ui-component",d[0])},l=(...d)=>{n("hitl:confirmation-request",d[0])},c=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",l),this.emitter.on("hitl:confirmation-response",c),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",l),this.emitter.off("hitl:confirmation-response",c)}}}async*handleStreamFallback(t,r,n,o,s,i){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const g=this._metricsTraceContext;let y=Oe.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:g?.traceId,parentSpanId:g?.parentSpanId});y=Oe.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),dt().recordSpan(y)}catch{}const l=o.fallbackProvider?.trim()||void 0,c=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,m=qL.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),h={...m,provider:l??u??m.provider,model:c??d??m.model};f.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:h.provider,fallbackModel:h.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const g=await lo.createProvider(h.provider,h.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));g.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(A,I)=>this.executeTool(A,I,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const y=o.conversationMessages!==void 0?o.conversationMessages:await oh(this.conversationMemory,{prompt:o.input.text,context:o.context}),v=await g.stream({...this.deferProviderStreamTTS(o),model:h.model,conversationMessages:y}),_=v.toolCalls??[],b=v.toolResults??[];(_.length>0||b.length>0)&&(r.toolCalls=_,r.toolResults=b,r.finishReason=v.finishReason??r.finishReason);let T=0,k=0;for await(const A of v.stream){T++;const I=A!==null&&typeof A=="object"&&"metadata"in A&&A.metadata?.noOutput===!0,M=A&&"content"in A&&typeof A.content=="string"&&A.content.length>0,R=A!==null&&typeof A=="object"&&"type"in A&&(A.type==="audio"||A.type==="tts_audio"||A.type==="image");!I&&(M||R)&&k++,A&&"content"in A&&typeof A.content=="string"&&(i(A.content),this.emitter.emit("response:chunk",A.content)),yield A}if(k===0&&_.length===0&&b.length===0)throw new Error(`Fallback provider ${h.provider} also returned 0 real output chunks (chunkCount=${T}, sentinel-only or empty)`);t.fallbackProvider=h.provider,t.fallbackModel=h.model,t.guardrailsBlocked=!0}catch(g){const y=g instanceof Error?g.message:String(g);throw t.error=`${a}; Fallback failed: ${y}`,f.error("Fallback provider failed",{fallbackProvider:h.provider,error:y}),g}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=t;f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:B1(j1(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!s.trim()&&!l){f.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:B1(j1(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const c=r.context?.sessionId,u=r.context?.userId;let d;r.model&&(d={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),f.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),f.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}this.shouldWriteMemory(r.memory,r.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=await B_(t.provider),n=await lo.createProvider(r,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await n.ensureModelLimits?.(),n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),i=t.conversationMessages!==void 0,a=i?t.conversationMessages:await oh(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=a;let l=a;const c=ka({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o}),u=l?.length||0,d=this.getCompactionSessionId(t),m=u>0;if(!c.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:c.estimatedInputTokens,budget:c.availableInputTokens,provider:r,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Ya(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${c.estimatedInputTokens} tokens, budget: ${c.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:c.estimatedInputTokens,availableTokens:c.availableInputTokens,stagesUsed:[],breakdown:c.breakdown})}if(c.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){const y=await new m_({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(l,hQ(c),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId);y.compacted&&(l=d_(y.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(d,l.length));const v=ka({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){f.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=wQ(l,v.availableInputTokens,v.breakdown,r),t.conversationMessages=l;const _=ka({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!_.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:_.estimatedInputTokens,budget:_.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Ya(`Stream context exceeds model budget after all compaction stages. Estimated: ${_.estimatedInputTokens} tokens, Budget: ${_.availableInputTokens} tokens.`,{estimatedTokens:_.estimatedInputTokens,availableTokens:_.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:_.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let _=null;for(let b=0;b<y;b++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const T=g.selectNext(v);if(!T)break;v.add(g.memberKey(T));const k=T.provider,A=T.model??void 0,I=T.region??void 0;f.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:A,attempt:b});try{const M=await lo.createProvider(k,A,!t.disableTools,this,I,this.resolveCredentials(t.credentials));M.setTraceContext(this._metricsTraceContext),M.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(N,P)=>this.executeTool(N,P,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");const R=await M.stream({...this.deferProviderStreamTTS(t),provider:k,model:A,region:I,systemPrompt:s,conversationMessages:l});f.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const x=T;return{stream:(async function*(){try{yield*R.stream,g.recordSuccess(x)}catch(N){throw g.recordFailure(x,z_(N)),N}})(),provider:k,usage:R.usage,model:R.model||A,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics,metadata:R.metadata}}catch(M){if(qr(M))throw M;if(Goe(M)){const R=M instanceof Error?M.message:String(M);throw g.recordFailure(T,z_(M)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:M})}g.recordFailure(T,z_(M)),_=M instanceof Error?M:new Error(String(M)),f.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:_.message})}}throw new Error(`[ModelPool] all stream members failed: ${_?.message??"no stream members available"}`)}const h=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:l});return f.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:s.length}),{stream:h.stream,provider:r,usage:h.usage,model:h.model||t.model,finishReason:h.finishReason,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[],analytics:h.analytics,metadata:h.metadata}}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){return{stream:r,provider:n.providerName,model:n.options.model,usage:t.usage,finishReason:t.finishReason,toolCalls:t.toolCalls,toolResults:t.toolResults,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:Object.assign(n.providerMetadata??{},{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error})}}async handleStreamError(t,r,n,o,s,i){if(t instanceof Ya)throw t;f.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,l=Date.now()-n,c=await B_(r.provider),d=await(await lo.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials))).stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let m="";return{stream:(async function*(g){try{for await(const y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(m+=y.content,g.emitter.emit("response:chunk",y.content)),yield y}finally{if(m.trim()){f.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{const y=r.model||"unknown",v=Date.now()-n;g.emitter.emit("stream:complete",{content:m,provider:c,model:y,finishReason:"stop",metadata:{durationMs:v,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}}),g.emitter.emit("generation:end",{provider:c,model:y,responseTime:v,timestamp:Date.now(),result:{content:m,usage:{input:0,output:0,total:0},model:y,provider:c,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(g.conversationMemory&&s?.context?.sessionId&&m.trim()){const y=s?.context?.sessionId,v=s?.context?.userId;let _;r.model&&(_={provider:c,model:r.model});const b=Date.now();try{const T=y||r.context?.sessionId,k=g.drainPendingSkillMessages(T);await g.conversationMemory.storeConversationTurn({sessionId:T,userId:v||r.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:_,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||r.context?.requestId,...k.length>0?{skillMessages:k}:{}}),g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,1)}catch(T){g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,2,T instanceof Error?T.message:String(T)),f.warn("Failed to store fallback stream conversation turn",{error:T instanceof Error?T.message:String(T)})}}}})(this),provider:c,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:l,fallback:!0}}}getEventEmitter(){return this.emitter}getToolDedupConfig(){return this.toolDedupConfig}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(s){const i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof Ky?{provider:r,status:"denied",detail:i}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:i}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:i}:{provider:r,status:"unknown",detail:i}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",a0(t,{input:r,timestamp:n,executionId:o})),f.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,s=Date.now(),i){const a=o||s-1e3,l=s-a,c=!n;let u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(h=>h.tool===t&&!h.endTime);const d=i||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const m={tool:t,startTime:a,endTime:s,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",a0(t,{result:r,error:n,success:c,responseTime:l,timestamp:s,duration:l,executionId:d})),f.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:l,success:c,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(aV(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const i=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],m=d?.abortSignal,h=m?AbortSignal.any([m,u]):u,g={...d,abortSignal:h};return Promise.race([i(c[0],g),new Promise((y,v)=>{h.addEventListener("abort",()=>{u.aborted?v(xe.toolTimeout(l,a)):v(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const s=JBr(t,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw f.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},f.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,f.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),f.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),f.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new ml("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new ml("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ze(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0})),r=new Map;for(const o of t){const s=o.inputSchema||o.parameters;f.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{const l=this.toolExecutionContext||{},c=a&&ar(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return f.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(l),runtimeContextKeys:Object.keys(c),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=PMt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,s]of Object.entries(n))if(!r.has(o)){const i=s,a=i.inputSchema??i.parameters;r.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await s.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{de.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),de.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw de.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>xa({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return He.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(t,r,n,o,s))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),s=o?"mcp":this.getCustomTools().has(t)?"custom":"external",i=r?Dv(r):"",a=Date.now(),l=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:l,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,s){try{const i=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,i,o,s)}catch(i){if(!(i instanceof Ne)){const a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:qe.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(t,r,n,o){f.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:ar(r)?TGe(r):r,hasExternalManager:!!this.externalServerManager}),f.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",a0(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const s=this.toolRegistry.getToolInfo(t),i={timeout:n?.timeout??s?.tool?.timeoutMs??Yl.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??ls.DEFAULT,retryDelayMs:n?.retryDelayMs||bn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(ox(),q_)),l=a.getMemoryUsageMB(),u=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${t}`;let d=this.toolCircuitBreakers.get(u);d||(d=new c1(lI.FAILURE_THRESHOLD,r3),this.toolCircuitBreakers.set(u,d));let m=this.toolExecutionMetrics.get(t);return m||(m={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,m)),m.totalExecutions++,{finalOptions:i,startMemory:l,circuitBreaker:d,breakerKey:u,metrics:m}}async runPreparedToolExecution(t,r,n,o,s){let i=0;try{de.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=await n.circuitBreaker.execute(async()=>Vge(async()=>Ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),n.finalOptions.timeout,xe.toolTimeout(t,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:PB,onRetry:(l,c)=>{i=l,de.warn(`[${o.functionTag}] Retrying tool execution (attempt ${l})`,{toolName:t,error:c.message,attempt:l})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(t,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(t,r,a,n,o,s)}}async handleSuccessfulToolExecution(t,r,n,o,s){const i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(ox(),q_)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&de.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:i}),de.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:i,memoryDelta:c,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,h=d?m?.filter(g=>g.type==="text"&&g.text).map(g=>g.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}de.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const g=j7r(h??"Unknown error"),y=`[TOOL_ERROR: ${t} failed (${g})] `;if(u&&Array.isArray(m)){const b=m.map(T=>({...T}));for(const T of b)if(T.type==="text"&&T.text){T.text=y+T.text;break}u.content=b}s.setAttribute("tool.error.message",(h??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",g),s.setStatus({code:qe.ERROR,message:`MCP tool returned isError: ${(h??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const v=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=v>1?(n.metrics.averageExecutionTime*v-i)/(v-1):0;const _=q7r(g);n.metrics.errorCategories[_]=(n.metrics.errorCategories[_]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&h?new Error(h):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),r}async handleFailedToolExecution(t,r,n,o,s,i){o.metrics.failedExecutions++;const a=Date.now()-s.executionStartTime;if(n instanceof Xp)return de.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:qe.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let l;if(n instanceof Ne)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=xe.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=xe.toolNotFound(t,wIr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=xe.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=xe.networkError(t,n):l=xe.toolExecutionFailed(t,n);else l=xe.toolExecutionFailed(t,new Error(String(n)));const c=l.category||"execution";throw o.metrics.errorCategories[c]=(o.metrics.errorCategories[c]||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,l,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new Ne({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),Wge(l),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(l),i.setStatus({code:qe.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!i?.destructiveHint,l=this.mcpToolResultCache,c=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,c):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&l&&!d){const g=l.getCachedResult(t,c);if(g!==void 0)return f.debug(`[${s}] Cache HIT for tool: ${t}`),g}else d&&f.debug(`[${s}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const m=async g=>{if(this.mcpToolMiddlewares.length===0)return g();let y=0;const v=async()=>{if(y<this.mcpToolMiddlewares.length){const _=this.mcpToolMiddlewares[y++];return _({name:t,description:"",inputSchema:{},annotations:i,execute:async()=>({})},r,{toolMeta:{name:t,annotations:i}},v)}return g()};return await v()},h=async()=>{const g=this.externalServerManager.getAllTools(),y=g.filter(_=>_.name===t&&_.isAvailable);let v;if(y.length>1&&this.mcpToolRouter)try{const _={name:t,description:y[0].description??"",serverId:y[0].serverId,inputSchema:{}},b=this.mcpToolRouter.route(_);v=y.find(T=>T.serverId===b.serverId)||y[0],f.debug(`[${s}] Router selected server: ${b.serverId}`,{strategy:b.strategy,confidence:b.confidence})}catch(_){f.warn(`[${s}] Router failed, falling back to first match`,{error:_}),v=y[0]}else v=y[0];if(f.debug(`[${s}] External MCP tool search:`,{toolName:t,externalToolsCount:g.length,foundTool:!!v,isAvailable:v?.isAvailable,serverId:v?.serverId}),v&&v.isAvailable)try{de.debug(`[${s}] Executing external MCP tool: ${t} from ${v.serverId}`);const _=await this.externalServerManager.executeTool(v.serverId,t,r,{timeout:n.timeout});return f.debug(`[${s}] External MCP tool execution successful:`,{toolName:t,serverId:v.serverId,resultType:typeof _}),_}catch(_){throw f.error(`[${s}] External MCP tool execution failed:`,{toolName:t,serverId:v.serverId,error:_ instanceof Error?_.message:String(_)}),xe.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)),v.serverId)}try{const _=this.toolExecutionContext||{},b=n.authContext||{},T={..._,...b,hitlState:o};f.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(_),finalContextKeys:Object.keys(T)});const k=await this.toolRegistry.executeTool(t,r,T);if(k&&typeof k=="object"&&"success"in k&&k.success===!1){const A=k.error||"Tool execution failed",I=new Error(A);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",I)}return k}catch(_){const b=_ instanceof Error?_:new Error(String(_));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",b),_ instanceof Error&&_.message.includes("not found")){const T=await this.getAllAvailableTools();throw xe.toolNotFound(t,T.map(k=>k.name))}throw xe.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)))}};try{const g=await m(h);return a&&l&&g!==void 0&&(l.cacheResult(t,c,g),f.debug(`[${s}] Cached result for tool: ${t}`)),g}catch(g){const y=i?{name:t,description:"",annotations:i,execute:async()=>({})}:void 0;if(y&&GJ(y)&&g instanceof Error&&PB(g)){f.debug(`[${s}] Tool ${t} is safe to retry, attempting once more`);try{const v=await m(h);return a&&l&&v!==void 0&&l.cacheResult(t,c,v),v}catch{}}throw g}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return ap({name:t,description:""})}invalidateToolCache(){this.toolCache=null,f.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return f.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!lo,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(ox(),q_)),s=o.getMemoryUsageMB();try{const i=new Map,a=await this.toolRegistry.listTools();for(const y of a)if(!i.has(y.name)){const v=fP(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,v)}const l=this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0}));for(const y of l)if(!i.has(y.name)){const v=fP(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:xa({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const y of c)if(!i.has(y.name)){const v=fP(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,v)}const u=this.externalServerManager.getAllTools();for(const y of u)if(!i.has(y.name)){const v=fP(y,{category:xa({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const d=Array.from(i.values());de.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const h=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(h>em.LOW_USAGE_MB&&(de.debug(`\u{1F50D} Tool listing used ${h}MB memory (large tool registry detected)`),d.length>Hde.LARGE_TOOL_COLLECTION&&de.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const y of d)y.annotations||(y.annotations=ap({name:y.name,description:y.description||""}));const g=d.sort((y,v)=>y.name<v.name?-1:y.name>v.name?1:0);return this.toolCache={tools:g,timestamp:Date.now()},g}catch(i){return de.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(ox(),q_)),n=r.getMemoryUsageMB();t?.quiet||de.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||de.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Ul(),Mx)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(mh(),nx)),i=Ur.getAllDescriptors().map(m=>m.name),a=QS(qa.DEFAULT_CONCURRENCY_LIMIT),l=i.map(m=>a(async()=>{const h=Date.now();try{if(!await this.hasProviderEnvVars(m)&&m!=="ollama")return{provider:m,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-h};if(m==="ollama")try{const b=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(Zl.AUTH_MS)});if(!b.ok)throw new Error("Ollama service not responding");const T=await b.json(),k=T?.models;if(!Array.isArray(k))throw f.warn("Ollama API returned invalid models format in testProvider",{responseData:T,modelsType:typeof k}),new Error("Invalid models format from Ollama API");const A=k.filter(I=>I&&typeof I=="object"&&typeof I.name=="string");return A.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h,model:A[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-h}}catch(b){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:b instanceof Error?b.message:"Ollama service not running",responseTime:Date.now()-h}}const y=5e3,v=this.testProviderConnection(m),_=new Promise((b,T)=>{setTimeout(()=>T(new Error("Provider test timeout (5s)")),y)});return await Promise.race([v,_]),{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h}}catch(g){const y=g instanceof Error?g.message:String(g);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-h}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&de.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),c}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t){const{AIProviderFactory:r}=await Promise.resolve().then(()=>(Ul(),Mx));await(await r.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(mh(),nx));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(mh(),nx));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(mh(),nx));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,l=r.connectedServers+o.length+s.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:i.length,totalTools:c,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return de.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(ey(),F_));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return f.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(ey(),F_)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(ey(),F_));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(ey(),F_)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(ey(),F_));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,f.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new c1(lI.FAILURE_THRESHOLD,r3)),de.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),de.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(const i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(const i of o){const a=this.toolExecutionMetrics.get(i),l=`${s.get(i)||"unknown"}.${i}`,c=this.toolCircuitBreakers.get(l),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!c||c.getState()==="closed")&&u>=.8;d&&r++;const m=[],h=[];if(c&&c.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),h.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),h.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),h.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const g=a.errorCategories;g.timeout>0&&(m.push(`Timeout errors: ${g.timeout}`),h.push("Consider increasing the tool timeout configuration")),g.validation>0&&(m.push(`Validation errors: ${g.validation}`),h.push("Review input schemas and parameter validation")),g.network>0&&(m.push(`Network errors: ${g.network}`),h.push("Check network connectivity and endpoint availability"))}t[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:c?.getState()||"closed",failureCount:c?.getFailureCount()||0},issues:m,recommendations:h}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return f.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return f.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return f.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return f.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Ze(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return f.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return f.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const s=await Ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(s.length===0)return f.debug("No messages found for session export",{sessionId:t}),null;const i=this.conversationMemory.getSession(t),a=await Ze(i instanceof Promise?i:Promise.resolve(i),o,new Error("getSession operation timed out after 30s")),l=new Date().toISOString(),c={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():l,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():l,messages:s};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),f.debug("Exported conversation session",{sessionId:t,messageCount:s.length}),c}catch(s){return f.error("Failed to export conversation session",{sessionId:t,error:s instanceof Error?s.message:String(s)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,s=6e4;try{const i=await Ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of i){const c=await Ze(this.exportSession(l.id,r),s,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return f.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(i){return f.error("Failed to export all conversation sessions",{userId:t,error:i instanceof Error?i.message:String(i)}),[]}}async storeToolExecutions(t,r,n,o,s){const i=n&&n.length>0||o&&o.length>0;if(!i){f.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){f.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,s)}catch(l){f.warn("Failed to store tool executions",{sessionId:t,userId:r,error:l instanceof Error?l.message:String(l)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:r(o[s].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{de.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(de.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new mL({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const s of o)this.mcpToolRouter.registerServer(s.id||t);f.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else de.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?Xn(r.url):void 0});return n}catch(n){throw de.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{de.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(de.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?de.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):de.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw de.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){try{de.debug(`[NeuroLink] Executing external MCP tool: ${r} on ${t}`);const s=this.getToolAnnotationsForExecution(r),i=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,a={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},l=this._generationTurnActive?this.toolCacheRepeatKey(r,a):void 0,c=l!==void 0&&this._toolCacheKeysServedThisRequest.has(l);if(l!==void 0&&this._toolCacheKeysServedThisRequest.add(l),i&&this.mcpToolResultCache&&!c){const h=this.mcpToolResultCache.getCachedResult(r,a);if(h!==void 0)return de.debug(`[NeuroLink] Tool result cache HIT: ${r} on ${t}`),h}const u=await this.externalServerManager.executeTool(t,r,n,o),d=u&&typeof u=="object"?u:void 0,m=!!(d&&"isError"in d&&d.isError===!0||d&&"success"in d&&d.success===!1);return i&&this.mcpToolResultCache&&!m&&u!==void 0&&this.mcpToolResultCache.cacheResult(r,a,u),de.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${r}`),u}catch(s){throw de.error(`[NeuroLink] External MCP tool execution failed: ${r}`,s),s}}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Ze(Promise.resolve().then(()=>(cte(),bOt)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{de.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),de.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw de.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Ze(Promise.resolve().then(()=>(Y6t(),J6t)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Ze(Promise.resolve().then(()=>(aee(),zMt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Ze(Promise.resolve().then(()=>(lee(),jMt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ze(Promise.resolve().then(()=>(e5t(),Z6t)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Ioe(),xoe)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Ioe(),xoe)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Ze(Promise.resolve().then(()=>(a5t(),n5t)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Ze(Promise.resolve().then(()=>(g4(),HJ)),1e4),o=t.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Ze(Promise.resolve().then(()=>(g4(),HJ)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Ze(Promise.resolve().then(()=>(rC(),Owt)),1e4),s=this.toolRegistry.getToolInfo(t);if(!s)return null;const i=s.tool.annotations,a=r({name:s.tool.name,description:s.tool.description??""}),l=n(a,i);return{annotations:l,summary:o(l)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async s=>{try{de.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});const i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return de.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw de.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};r[n.name]=o,de.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return de.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await F7r().then(()=>u5t),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw f.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);de.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){de.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const s=new r(o);return await Ze(s.initialize(),3e4,xe.evaluationTimeout("pipeline initialization",3e4)),f.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));let s;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?s={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:s=o("quality"),r?.passThreshold!==void 0&&(s.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(s.executionMode=r.executionMode);const i=new n(s);await Ze(i.initialize(),3e4,xe.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await Ze(i.execute(t,{correlationId:r?.correlationId}),a,xe.evaluationTimeout("pipeline execution",a));return f.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:l.overallScore,passed:l.passed,scorerCount:l.scores.length}),l}async score(t,r,n){const{ScorerRegistry:o}=await Ze(Promise.resolve().then(()=>(f7(),h7)),1e4,xe.evaluationTimeout("scorer module load",1e4));await Ze(o.registerBuiltInScorers(),3e4,xe.evaluationTimeout("scorer bootstrap",3e4));const s=await Ze(o.getScorer(t,n),3e4,xe.evaluationTimeout(`scorer load: ${t}`,3e4));if(!s)throw xe.scorerNotFound(t);const i=s.validateInput(r);if(!i.valid)throw xe.evaluationValidationFailed(t,i.errors);const a=await Ze(s.score(r),6e4,xe.evaluationTimeout("scorer execution",6e4));return f.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Ze(Promise.resolve().then(()=>(f7(),h7)),1e4,xe.evaluationTimeout("scorer module load",1e4));await Ze(r.registerBuiltInScorers(),3e4,xe.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(Noe(),d5t));return f.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(m5t(),p5t));return f.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},s={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:{...this.observabilityConfig??{},langfuse:{...this.observabilityConfig?.langfuse??{},autoDetectExternalProvider:!0,skipLangfuseSpanProcessor:!0}},...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},i=new fF(s);if(t?.shareToolRegistry!==!1)for(const a of this.uncacheableTools)i.uncacheableTools.add(a);if(f.setEventEmitter(n),t?.onLog){const a=t.onLog,l=u=>{try{const d=u??{};a({tag:r,level:String(d.level??"info"),message:String(d.message??""),timestamp:typeof d.timestamp=="number"?d.timestamp:Date.now(),data:d.data})}catch{}};n.on("log-event",l);const c=i.dispose.bind(i);i.dispose=async()=>{n.off("log-event",l),await c()}}return f.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),i}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(Vk(),bL));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(Vk(),bL));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(Vk(),bL));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(Kk(),CL)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=bjr(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return yjr(t??ns(this))}clearTaskState(t){return vjr(t??ns(this))}registerDelegationTools(t){if(Bjr(this,t),this.hasBackgroundDelegationTools)return;const r=Yjr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return r2t(this,t)}async collectDelegates(t){return o2t(this,t)}async cancelDelegates(t){return Ure(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=new Tte,f.debug("[NeuroLink] Artifact store created on demand (local-temp) for banking")),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}async bankArtifact(t,r){return szr(this,t,r)}async readArtifact(t,r){return izr(this,t,r)}registerBackgroundCommandTools(t){if(p2t(this,t),this.hasBackgroundCommandTools)return;const r=aqr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){p2t(this,t)}async startBackgroundCommand(t,r){return w2t(this,t,r)}getBackgroundCommandStatus(t){return b2t(this,t)}async awaitBackgroundCommand(t,r){return Qre(this,t,r)}async killBackgroundCommand(t,r){return T2t(this,t,r)}async readBackgroundCommandOutput(t,r){return NL(this,t,r)}registerGitTools(t){if(lqr(this,t),this.hasGitTools)return;const r=fqr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return N2t(this,t,r)}async executeNetwork(t,r,n){return f.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){f.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(y5t(),g5t));return f.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(_5t(),v5t));return f.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(b5t(),w5t));return f.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){f.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await E2t(this),await Ure(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error stopping background work:",r)}try{f.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await qD(),await GD(),f.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{f.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),f.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.emitter)try{f.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),f.clearEventEmitter(this.emitter),f.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error removing event listeners:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{f.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),f.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{f.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],f.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{f.debug("[NeuroLink] Shutting down TaskManager..."),await Ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){f.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{f.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,f.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error resetting state:",r)}t.length===0?f.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):f.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw f.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new m_({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=ka({provider:r?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&d_(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const s=ka({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?ka({provider:r||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(E$(),T5t));r=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=r,f.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(Ik(),oL));r.set(t),f.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(Ik(),oL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(Ik(),oL)),r=t.get()?.user.id;t.clear(),r&&f.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(s=>typeof t[s]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(f.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async s=>{if(typeof t[s]=="function"){const i=await xte(t[s],o);t[s]=i.value,f.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof t.tools=="function"){const s=await xte(t.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);t.enabledToolNames=s.value,delete t.tools}}},Hoe=new fx,C5t=Hoe}}),k5t={};he(k5t,{VoyageProvider:()=>I5t});var x5t,Voe,A5t,C$,I5t,W7r=S({async"src/lib/providers/voyage.ts"(){"use strict";vc(),await dd(),no(),vt(),ct(),q(),Zo(),x5t="https://api.voyageai.com/v1",Voe=6e4,A5t=()=>Bi(Fcr()),C$=()=>zi("VOYAGE_MODEL","voyage-3.5"),I5t=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"voyage",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:A5t(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??x5t,this.proxyFetch=Bt(),f.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return C$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return C$()}getAISDKModel(){throw new yt("Voyage AI is an embedding-only provider; chat completions are not available. Use `embed()` or `embedMany()` instead, or pick a different provider for `generate()` / `stream()`.","voyage")}async executeStream(e,t){throw new yt("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new or("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new co(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new yt(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new yt("Voyage AI returned no embedding for the provided text","voyage");return r[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const s=e.slice(o,o+r),i=await this.callEmbeddings(s,t);n.push(...i)}return n}async callEmbeddings(e,t){const r=t??this.modelName;let n;try{n=await Ze(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:r})}),Voe,new yt(`Voyage embeddings request timed out after ${Voe/1e3}s`,"voyage"))}catch(i){throw i instanceof yt?i:this.formatProviderError(i)}if(!n.ok){const i=await n.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${n.status} \u2014 ${i}`))}const o=await n.json();if(!o.data||o.data.length===0)throw new yt("Voyage embeddings response missing data","voyage");if(o.data.length!==e.length)throw new yt(`Voyage embeddings response count mismatch: expected ${e.length}, got ${o.data.length}`,"voyage");const s=o.data.slice().sort((i,a)=>i.index-a.index);for(let i=0;i<s.length;i++)if(s[i].index!==i)throw new yt(`Voyage embeddings response has unexpected index ordering: position ${i} has index ${s[i].index}`,"voyage");return s.map(i=>i.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:C$(),baseURL:this.baseURL}}}}}),R5t={};he(R5t,{JinaProvider:()=>D5t});var M5t,gx,P5t,k$,D5t,K7r=S({async"src/lib/providers/jina.ts"(){"use strict";vc(),await dd(),no(),vt(),q(),Zo(),M5t="https://api.jina.ai/v1",gx=6e4,P5t=()=>Bi(Ucr()),k$=()=>zi("JINA_MODEL","jina-embeddings-v3"),D5t=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"jina",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:P5t(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??M5t,this.proxyFetch=Bt(),f.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return k$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return k$()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new or("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new co(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new yt(`Jina AI error: ${t}`,"jina")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new Error("Jina AI returned no embedding for the provided text");return r[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,r={}){if(t.length===0)return[];const n=r.model??"jina-reranker-v2-base-multilingual",o=r.credentials,s=o?.apiKey?.trim()||this.apiKey,i=o?.baseURL||this.baseURL,a=new AbortController,l=setTimeout(()=>a.abort(),gx);let c;try{c=await this.proxyFetch(`${i}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({model:n,query:e,documents:t,top_n:r.topN??t.length}),signal:a.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${gx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(l)}if(!c.ok){const d=await c.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${c.status} \u2014 ${d}`))}return((await c.json()).results??[]).map(d=>({index:d.index,score:d.relevance_score,document:t[d.index]??d.document?.text??""}))}async callEmbeddings(e,t,r){const n=t??this.modelName,o=r?.apiKey?.trim()||this.apiKey,s=r?.baseURL||this.baseURL,i=new AbortController,a=setTimeout(()=>i.abort(),gx);let l;try{l=await this.proxyFetch(`${s}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:i.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${gx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(a)}if(!l.ok){const d=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${d}`))}const c=await l.json();if(!c.data||c.data.length===0)throw new Error("Jina embeddings response missing data");if(c.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${c.data.length}`);const u=c.data.slice().sort((d,m)=>d.index-m.index);for(let d=0;d<u.length;d++)if(u[d].index!==d)throw new Error(`Jina embeddings response has unexpected index ordering: position ${d} has index ${u[d].index}`);return u.map(d=>d.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:k$(),baseURL:this.baseURL}}}}}),O5t={};he(O5t,{StabilityProvider:()=>Joe,default:()=>$5t});var N5t,Woe,L5t,Koe,Joe,$5t,J7r=S({async"src/lib/providers/stability.ts"(){"use strict";vc(),await dd(),no(),vt(),q(),Zo(),N5t="https://api.stability.ai",Woe=12e4,L5t=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,Koe=()=>zi("STABILITY_MODEL","stable-image-ultra"),Joe=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"stability",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:L5t(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??N5t,this.proxyFetch=Bt(),f.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Koe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new or("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new yt("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new co(`Stability AI model '${this.modelName}' not found. Use stable-image-ultra, stable-image-core, sd3.5-large, sd3.5-large-turbo, or sd3.5-medium.`,"stability"):new yt(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.stability,n=r?.apiKey?.trim()||this.apiKey;if(!n)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");const o=n,s=r?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");const a=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,c=new FormData;c.append("prompt",i),c.append("output_format","png"),l.aspectRatio&&c.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&c.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&c.append("model",this.modelName),l.seed!==void 0&&c.append("seed",String(l.seed));const u=new AbortController,d=setTimeout(()=>u.abort(),Woe);let m;try{m=await this.proxyFetch(`${s}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:c,signal:u.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${Woe/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(d)}if(!m.ok){const y=await m.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${m.status} \u2014 ${y}`))}const h=await m.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);const g=Date.now()-t;return f.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${g}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Koe(),baseURL:this.baseURL}}},$5t=Joe}}),F5t={};he(F5t,{IdeogramProvider:()=>Xoe,default:()=>z5t});var U5t,Yoe,B5t,Zoe,Xoe,z5t,Y7r=S({async"src/lib/providers/ideogram.ts"(){"use strict";vc(),await dd(),no(),vt(),q(),Zo(),U5t="https://api.ideogram.ai",Yoe=12e4,B5t=()=>Bi(Bcr()),Zoe=()=>zi("IDEOGRAM_MODEL","V_3"),Xoe=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"ideogram",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:B5t(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??U5t,this.proxyFetch=Bt(),f.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Zoe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new or("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new yt("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new yt(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.ideogram,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const i=e,a={prompt:s,model:this.modelName,magic_prompt:i.magicPrompt??"AUTO"};i.aspectRatio&&(a.aspect_ratio=i.aspectRatio),i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.seed!==void 0&&(a.seed=i.seed),i.style&&(a.style_type=i.style);const l=new AbortController,c=setTimeout(()=>l.abort(),Yoe);let u;try{u=await this.proxyFetch(`${o}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":n,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${Yoe/1e3}s`)):this.formatProviderError(T)}finally{clearTimeout(c)}if(!u.ok){const T=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${T}`))}const m=(await u.json()).data?.[0]?.url;if(!m)throw new Error("Ideogram returned no image URL");const h=new AbortController,g=setTimeout(()=>h.abort(),6e4);let y;try{y=await this.proxyFetch(m,{signal:h.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:T}):T}finally{clearTimeout(g)}if(!y.ok)throw new Error(`Failed to download Ideogram image: ${y.status}`);const v=Buffer.from(await y.arrayBuffer()),_=v.toString("base64"),b=Date.now()-t;return f.info(`[IdeogramProvider] Generated image (${v.length} bytes) in ${b}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:_}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Zoe(),baseURL:this.baseURL}}},z5t=Xoe}}),j5t={};he(j5t,{ReplicateProvider:()=>q5t});function Z7r(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
|
|
2161
|
+
IMPORTANT: You have a tool called "${l.toolName}" that searches through`,`${l.filesLoaded} loaded document(s) containing ${l.chunksIndexed} indexed chunks.`,`ALWAYS use the "${l.toolName}" tool FIRST to answer the user's question before using any other tools.`,"This tool searches your local knowledge base of pre-loaded documents and is the primary source of truth.","Do NOT use websearchGrounding or any web search tools when the answer can be found in the loaded documents."].join(" ");t.systemPrompt=(t.systemPrompt||"")+c,f.info("[RAG] Tool injected into stream()",{toolName:l.toolName,filesLoaded:l.filesLoaded,chunksIndexed:l.chunksIndexed})}catch(a){f.warn("[RAG] Failed to prepare RAG tool, continuing without RAG",{error:a instanceof Error?a.message:String(a)})}const s=zGr(t),i=jGr(t);if(t.input?.text){const{toolResults:a,enhancedPrompt:l}=await this.detectAndExecuteTools(t.input.text,void 0);l!==t.input.text&&(i.input.text=l)}return{enhancedOptions:i,factoryResult:s}}async autoDisableOllamaStreamTools(t){if((t.provider==="ollama"||t.provider?.toLowerCase().includes("ollama"))&&!t.disableTools){const{ModelConfigurationManager:r}=await Promise.resolve().then(()=>(Af(),nqe)),s=r.getInstance().getProviderConfiguration("ollama")?.modelBehavior?.toolCapableModels||[],i=t.model;s.length>0&&i&&(s.some(l=>i.toLowerCase().includes(l.toLowerCase()))||(t.disableTools=!0,f.debug("Auto-disabled tools for Ollama model that doesn't support them (stream)",{model:t.model,toolCapableModels:s.slice(0,3)})))}}setupStreamEventListeners(){const t=[];let r=0;const n=(d,m)=>{t.push({type:d,seq:r++,timestamp:Date.now(),...m&&typeof m=="object"?m:{data:m}})},o=(...d)=>{const m=d[0];n("response:chunk",{content:m})},s=(...d)=>{const m=d[0];n("tool:start",{...m,toolName:m.toolName??m.tool})},i=(...d)=>{const m=d[0],h=m.toolName??m.tool,g=m.responseTime??m.duration,y=m.success??(m.error!==void 0?!1:void 0),v={...m,toolName:h,...g!==void 0?{responseTime:g}:{},...y!==void 0?{success:y}:{},...m.error!==void 0?{error:m.error}:{}};n("tool:end",v),v.result&&v.result.uiComponent===!0&&n("ui-component",{toolName:h,componentData:v.result,timestamp:Date.now(),...y!==void 0?{success:y}:{},...g!==void 0?{responseTime:g}:{}})},a=(...d)=>{n("ui-component",d[0])},l=(...d)=>{n("hitl:confirmation-request",d[0])},c=(...d)=>{n("hitl:confirmation-response",d[0])};return this.emitter.on("response:chunk",o),this.emitter.on("tool:start",s),this.emitter.on("tool:end",i),this.emitter.on("ui-component",a),this.emitter.on("hitl:confirmation-request",l),this.emitter.on("hitl:confirmation-response",c),{eventSequence:t,cleanup:()=>{this.emitter.off("response:chunk",o),this.emitter.off("tool:start",s),this.emitter.off("tool:end",i),this.emitter.off("ui-component",a),this.emitter.off("hitl:confirmation-request",l),this.emitter.off("hitl:confirmation-response",c)}}}async*handleStreamFallback(t,r,n,o,s,i){t.fallbackAttempted=!0;const a="Stream completed with 0 chunks (possible guardrails block)";t.error=a;try{const g=this._metricsTraceContext;let y=Oe.createGenerationSpan({provider:s,model:o.model||"unknown",name:`gen_ai.${s}.stream.failed`,traceId:g?.traceId,parentSpanId:g?.parentSpanId});y=Oe.endSpan(y,2),y.statusMessage=a,y.durationMs=0,this.metricsAggregator.recordSpan(y),dt().recordSpan(y)}catch{}const l=o.fallbackProvider?.trim()||void 0,c=o.fallbackModel?.trim()||void 0,u=process.env.FALLBACK_PROVIDER?.trim()||void 0,d=process.env.FALLBACK_MODEL?.trim()||void 0,m=qL.getFallbackRoute(n||o.input.text||"",{provider:s,model:o.model||"gpt-4o",reasoning:"primary failed",confidence:.5},{fallbackStrategy:"auto"}),h={...m,provider:l??u??m.provider,model:c??d??m.model};f.warn("Retrying with fallback provider",{originalProvider:s,fallbackProvider:h.provider,fallbackModel:h.model,fallbackSource:l||c?"options":u||d?"env":"model_config",reason:a});try{const g=await lo.createProvider(h.provider,h.model,!0,void 0,void 0,this.resolveCredentials(o.credentials));g.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(A,I)=>this.executeTool(A,I,{disableToolCache:o.disableToolCache})},"NeuroLink.fallbackStream");const y=o.conversationMessages!==void 0?o.conversationMessages:await oh(this.conversationMemory,{prompt:o.input.text,context:o.context}),v=await g.stream({...this.deferProviderStreamTTS(o),model:h.model,conversationMessages:y}),_=v.toolCalls??[],b=v.toolResults??[];(_.length>0||b.length>0)&&(r.toolCalls=_,r.toolResults=b,r.finishReason=v.finishReason??r.finishReason);let T=0,k=0;for await(const A of v.stream){T++;const I=A!==null&&typeof A=="object"&&"metadata"in A&&A.metadata?.noOutput===!0,M=A&&"content"in A&&typeof A.content=="string"&&A.content.length>0,R=A!==null&&typeof A=="object"&&"type"in A&&(A.type==="audio"||A.type==="tts_audio"||A.type==="image");!I&&(M||R)&&k++,A&&"content"in A&&typeof A.content=="string"&&(i(A.content),this.emitter.emit("response:chunk",A.content)),yield A}if(k===0&&_.length===0&&b.length===0)throw new Error(`Fallback provider ${h.provider} also returned 0 real output chunks (chunkCount=${T}, sentinel-only or empty)`);t.fallbackProvider=h.provider,t.fallbackModel=h.model,t.guardrailsBlocked=!0}catch(g){const y=g instanceof Error?g.message:String(g);throw t.error=`${a}; Fallback failed: ${y}`,f.error("Fallback provider failed",{fallbackProvider:h.provider,error:y}),g}}async storeStreamConversationMemory(t){const{enhancedOptions:r,providerName:n,originalPrompt:o,accumulatedContent:s,startTime:i,eventSequence:a}=t;f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Preparing to store conversation turn in memory",{options:B1(j1(r)),sessionId:r.context?.sessionId});const l=a.some(c=>c.type==="tool:start"||c.type==="tool:end");if(!s.trim()&&!l){f.warn("[NeuroLink.stream] Skipping conversation turn storage \u2014 no text content or tool activity",{sessionId:r.context?.sessionId});return}if(f.shouldLog("debug")&&f.debug("[NeuroLink.stream] Storing conversation turn in memory",{options:B1(j1(r)),sessionId:r.context?.sessionId,conversationMemoryExists:!!this.conversationMemory}),this.conversationMemory&&r.context?.sessionId){const c=r.context?.sessionId,u=r.context?.userId;let d;r.model&&(d={provider:n,model:r.model});const m=Date.now();try{const h=this.drainPendingSkillMessages(c);await this.conversationMemory.storeConversationTurn({sessionId:c,userId:u,userMessage:o??"",aiResponse:s,startTimeStamp:new Date(i),providerDetails:d,enableSummarization:r.enableSummarization,events:a.length>0?a:void 0,requestId:r.context?.requestId,...h.length>0?{skillMessages:h}:{}}),this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,1),f.debug("[NeuroLink.stream] Stored conversation turn with events",{sessionId:c,eventCount:a.length,eventTypes:[...new Set(a.map(g=>g.type))]})}catch(h){this.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"stream"},Date.now()-m,2,h instanceof Error?h.message:String(h)),f.warn("Failed to store stream conversation turn",{error:h instanceof Error?h.message:String(h)})}}this.shouldWriteMemory(r.memory,r.context?.userId,s)&&this.storeMemoryInBackground(o??"",s.trim(),r.context?.userId,r.memory?.additionalUsers,r.context)}async validateStreamInput(t){const r=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F3AF} LOG_POINT_003_VALIDATION_START",{logPoint:"003_VALIDATION_START",validationStartTimeNs:r.toString(),message:"Starting comprehensive input validation process"});const n=typeof t?.input?.text=="string"&&t.input.text.trim().length>0,o=!!(t?.input?.audio&&t.input.audio.frames&&typeof t.input.audio.frames[Symbol.asyncIterator]=="function"),s=!!(t?.stt?.enabled&&t?.stt?.audio);if(!n&&!o&&!s)throw new Error("Stream options must include either input.text, input.audio, or stt.audio")}emitStreamStartEvents(t,r){this.emitter.emit("stream:start",{provider:t.provider||"auto",timestamp:r}),this.emitter.emit("response:start"),this.emitter.emit("message",`Starting ${t.provider||"auto"} stream...`)}async createMCPStream(t){const r=await B_(t.provider),n=await lo.createProvider(r,t.model,!t.disableTools,this,t.region,this.resolveCredentials(t.credentials));await n.ensureModelLimits?.(),n.setTraceContext(this._metricsTraceContext),n.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(g,y)=>this.executeTool(g,y,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");let o=await this.getAllAvailableTools();o=this.applyToolInfoFiltering(o,t);const s=t.skipToolPromptInjection?t.systemPrompt||"":this.createToolAwareSystemPrompt(t.systemPrompt,o,n.supportsTools?.()??!0),i=t.conversationMessages!==void 0,a=i?t.conversationMessages:await oh(this.conversationMemory,{...t,prompt:t.input.text,context:t.context});t.conversationMessages=a;let l=a;const c=ka({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o}),u=l?.length||0,d=this.getCompactionSessionId(t),m=u>0;if(!c.withinBudget&&!m){try{this.emitter.emit("compaction.insufficient",{stagesAttempted:["pre-dispatch hard cap"],finalTokens:c.estimatedInputTokens,budget:c.availableInputTokens,provider:r,model:t.model,phase:"pre-dispatch-no-recovery",timestamp:Date.now()})}catch{}throw new Ya(`Stream context exceeds model budget and no compaction is possible (no conversationMemory, no inline conversationMessages \u2014 only prompt + tools). Estimated: ${c.estimatedInputTokens} tokens, budget: ${c.availableInputTokens} tokens. Reduce prompt or tool-definition size, or trim the request.`,{estimatedTokens:c.estimatedInputTokens,availableTokens:c.availableInputTokens,stagesUsed:[],breakdown:c.breakdown})}if(c.shouldCompact&&(i||this.conversationMemory)&&u>(this.lastCompactionMessageCount.get(d)??0)){const y=await new m_({provider:r,summarizationProvider:this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:this.conversationMemoryConfig?.conversationMemory?.summarizationModel}).compact(l,hQ(c),this.conversationMemoryConfig?.conversationMemory,t.context?.requestId);y.compacted&&(l=d_(y.messages).messages,t.conversationMessages=l,this.lastCompactionMessageCount.set(d,l.length));const v=ka({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!v.withinBudget){f.warn("[NeuroLink] Stream: post-compaction still over budget, emergency truncation",{estimatedTokens:v.estimatedInputTokens,availableTokens:v.availableInputTokens,overagePercent:Math.round((v.usageRatio-1)*100)});try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:v.estimatedInputTokens,budget:v.availableInputTokens,provider:r,model:t.model,phase:"mid-compaction",willEmergencyTruncate:!0,timestamp:Date.now()})}catch{}l=wQ(l,v.availableInputTokens,v.breakdown,r),t.conversationMessages=l;const _=ka({provider:r,model:t.model,maxTokens:t.maxTokens,systemPrompt:s,conversationMessages:l,currentPrompt:t.input.text,toolDefinitions:o});if(!_.withinBudget){this.lastCompactionMessageCount.delete(d);try{this.emitter.emit("compaction.insufficient",{stagesAttempted:y.stagesUsed,finalTokens:_.estimatedInputTokens,budget:_.availableInputTokens,provider:r,model:t.model,phase:"post-emergency-truncation",timestamp:Date.now()})}catch{}throw new Ya(`Stream context exceeds model budget after all compaction stages. Estimated: ${_.estimatedInputTokens} tokens, Budget: ${_.availableInputTokens} tokens.`,{estimatedTokens:_.estimatedInputTokens,availableTokens:_.availableInputTokens,stagesUsed:y.stagesUsed,breakdown:_.breakdown})}}}if(this.modelPool){const g=this.modelPool,y=g.maxAttempts,v=new Set;let _=null;for(let b=0;b<y;b++){if(t.abortSignal?.aborted)throw new DOMException("The operation was aborted","AbortError");const T=g.selectNext(v);if(!T)break;v.add(g.memberKey(T));const k=T.provider,A=T.model??void 0,I=T.region??void 0;f.debug(`[createMCPStream] ModelPool: attempting member ${k}`,{model:A,attempt:b});try{const M=await lo.createProvider(k,A,!t.disableTools,this,I,this.resolveCredentials(t.credentials));M.setTraceContext(this._metricsTraceContext),M.setupToolExecutor({customTools:this.getCustomTools(),executeTool:(N,P)=>this.executeTool(N,P,{disableToolCache:t.disableToolCache})},"NeuroLink.createMCPStream");const R=await M.stream({...this.deferProviderStreamTTS(t),provider:k,model:A,region:I,systemPrompt:s,conversationMessages:l});f.debug("[createMCPStream] ModelPool stream handle obtained",{provider:k});const x=T;return{stream:(async function*(){try{yield*R.stream,g.recordSuccess(x)}catch(N){throw g.recordFailure(x,z_(N)),N}})(),provider:k,usage:R.usage,model:R.model||A,finishReason:R.finishReason,toolCalls:R.toolCalls??[],toolResults:R.toolResults??[],analytics:R.analytics,metadata:R.metadata}}catch(M){if(qr(M))throw M;if(Goe(M)){const R=M instanceof Error?M.message:String(M);throw g.recordFailure(T,z_(M)),new Error(`[ModelPool] non-retryable: ${R}`,{cause:M})}g.recordFailure(T,z_(M)),_=M instanceof Error?M:new Error(String(M)),f.warn(`[createMCPStream] ModelPool: member ${k} failed`,{error:_.message})}}throw new Error(`[ModelPool] all stream members failed: ${_?.message??"no stream members available"}`)}const h=await n.stream({...this.deferProviderStreamTTS(t),systemPrompt:s,conversationMessages:l});return f.debug("[createMCPStream] Stream created successfully",{provider:r,systemPromptPassedLength:s.length}),{stream:h.stream,provider:r,usage:h.usage,model:h.model||t.model,finishReason:h.finishReason,toolCalls:h.toolCalls??[],toolResults:h.toolResults??[],analytics:h.analytics,metadata:h.metadata}}async processStreamResult(t,r,n){return{content:"",usage:void 0,finishReason:"stop",toolCalls:[],toolResults:[],analytics:void 0,evaluation:void 0}}emitStreamEndEvents(t){this.emitter.emit("stream:end",{responseTime:Date.now(),timestamp:Date.now()}),this.emitter.emit("response:end",t.content||"")}createStreamResponse(t,r,n){return{stream:r,provider:n.providerName,model:n.options.model,usage:t.usage,finishReason:t.finishReason,toolCalls:t.toolCalls,toolResults:t.toolResults,analytics:t.analytics,evaluation:t.evaluation,events:n.events&&n.events.length>0?n.events:void 0,metadata:Object.assign(n.providerMetadata??{},{streamId:n.streamId,startTime:n.startTime,responseTime:n.responseTime,fallback:n.fallback||!1,guardrailsBlocked:n.guardrailsBlocked,error:n.error})}}async handleStreamError(t,r,n,o,s,i){if(t instanceof Ya)throw t;f.error("Stream generation failed, attempting fallback",{error:t instanceof Error?t.message:String(t)});try{this.emitter.emit("stream:error",{content:t instanceof Error?t.message:String(t),metadata:{errorName:t instanceof Error?t.name:"UnknownError",durationMs:Date.now()-n,chunkCount:0},provider:r.provider||"unknown",model:r.model||"unknown"})}catch{}const a=r.input.text,l=Date.now()-n,c=await B_(r.provider),d=await(await lo.createProvider(c,r.model,!0,void 0,void 0,this.resolveCredentials(r.credentials))).stream({input:{text:r.input.text},model:r.model,temperature:r.temperature,maxTokens:r.maxTokens,conversationMessages:r.conversationMessages});let m="";return{stream:(async function*(g){try{for await(const y of d.stream)y&&"content"in y&&typeof y.content=="string"&&(m+=y.content,g.emitter.emit("response:chunk",y.content)),yield y}finally{if(m.trim()){f.info("[NeuroLink.handleStreamError] stream() - COMPLETE SUCCESS (fallback)",{provider:c,model:r.model,responseTimeMs:Date.now()-n,contentLength:m.length});try{const y=r.model||"unknown",v=Date.now()-n;g.emitter.emit("stream:complete",{content:m,provider:c,model:y,finishReason:"stop",metadata:{durationMs:v,chunkCount:0,totalLength:m.length,isFallback:!0,finishReason:"stop"}}),g.emitter.emit("generation:end",{provider:c,model:y,responseTime:v,timestamp:Date.now(),result:{content:m,usage:{input:0,output:0,total:0},model:y,provider:c,finishReason:"stop"},success:!0,pipelineAHandled:!0})}catch{}}if(g.conversationMemory&&s?.context?.sessionId&&m.trim()){const y=s?.context?.sessionId,v=s?.context?.userId;let _;r.model&&(_={provider:c,model:r.model});const b=Date.now();try{const T=y||r.context?.sessionId,k=g.drainPendingSkillMessages(T);await g.conversationMemory.storeConversationTurn({sessionId:T,userId:v||r.context?.userId,userMessage:a??"",aiResponse:m,startTimeStamp:new Date(n),providerDetails:_,enableSummarization:s?.enableSummarization,requestId:s?.context?.requestId||r.context?.requestId,...k.length>0?{skillMessages:k}:{}}),g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,1)}catch(T){g.recordMemorySpan("memory.store",{"memory.operation":"store","memory.path":"fallback-stream"},Date.now()-b,2,T instanceof Error?T.message:String(T)),f.warn("Failed to store fallback stream conversation turn",{error:T instanceof Error?T.message:String(T)})}}}})(this),provider:c,model:r.model,usage:d.usage,finishReason:d.finishReason||"stop",toolCalls:d.toolCalls||[],toolResults:d.toolResults||[],analytics:d.analytics,evaluation:d.evaluation,metadata:{streamId:o,startTime:n,responseTime:l,fallback:!0}}}getEventEmitter(){return this.emitter}hasPendingHITLConfirmation(t){return this.hitlManager?.hasPendingConfirmation(t)??!1}getToolDedupConfig(){return this.toolDedupConfig}getToolsConfig(){return this.toolsConfig}getDiscoveryPins(t){const r=this.discoveryPins.get(t);return r?(this.discoveryPins.delete(t),this.discoveryPins.set(t,r),r):new Set}pinDiscoveredTools(t,r){let n=this.discoveryPins.get(t);n?this.discoveryPins.delete(t):n=new Set,this.discoveryPins.set(t,n);for(const o of r)n.add(o);if(this.discoveryPins.size>1e3){const o=this.discoveryPins.keys().next().value;o!==void 0&&this.discoveryPins.delete(o)}}async checkCredentials(t){const{provider:r,model:n}=t,o="ping";try{return await this.generate({provider:r,...n&&{model:n},input:{text:o},maxTokens:16,disableTools:!0}),{provider:r,status:"ok",detail:"credentials valid"}}catch(s){const i=s instanceof Error?s.message:String(s),a=i.toLowerCase();return s instanceof Ky?{provider:r,status:"denied",detail:i}:a.includes("authentication")||a.includes("401")||a.includes("invalid api key")||a.includes("incorrect api key")||a.includes("api_key_invalid")||a.includes("token has expired")||a.includes("expired credentials")?{provider:r,status:"expired",detail:i}:a.includes("not configured")||a.includes("missing api")||a.includes("api key is required")||a.includes("no api key")||a.includes("application default credentials")||a.includes("google_application_credentials")||a.includes("project_id")||a.includes("default credentials")||a.includes("service account")?{provider:r,status:"missing",detail:i}:a.includes("econnrefused")||a.includes("enotfound")||a.includes("could not resolve")||a.includes("timeout")||a.includes("network")||a.includes("cannot connect")?{provider:r,status:"network",detail:i}:{provider:r,status:"unknown",detail:i}}}emitToolStart(t,r,n=Date.now()){const o=`${t}-${n}-${Math.random().toString(36).substr(2,9)}`,s={executionId:o,tool:t,startTime:n,metadata:{inputType:typeof r,hasInput:r!=null}};return this.activeToolExecutions.set(o,s),this.currentStreamToolExecutions.push(s),this.emitter.emit("tool:start",a0(t,{input:r,timestamp:n,executionId:o})),f.debug(`tool:start emitted for ${t}`,{toolName:t,executionId:o,timestamp:n,inputProvided:r!==void 0}),o}emitToolEnd(t,r,n,o,s=Date.now(),i){const a=o||s-1e3,l=s-a,c=!n;let u;i?u=this.activeToolExecutions.get(i):u=Array.from(this.activeToolExecutions.values()).find(h=>h.tool===t&&!h.endTime);const d=i||u?.executionId||`${t}-${a}-fallback-${Math.random().toString(36).substr(2,9)}`;u&&(u.endTime=s,u.result=r,u.error=n,this.activeToolExecutions.delete(u.executionId));const m={tool:t,startTime:a,endTime:s,duration:l,success:c,result:r,error:n,executionId:d,metadata:{toolCategory:"custom"}};this.toolExecutionHistory.push(m),this.emitter.emit("tool:end",a0(t,{result:r,error:n,success:c,responseTime:l,timestamp:s,duration:l,executionId:d})),f.debug(`tool:end emitted for ${t}`,{toolName:t,executionId:d,duration:l,success:c,hasResult:r!==void 0,hasError:!!n})}getCurrentToolExecutions(){return[...this.currentStreamToolExecutions]}getToolExecutionHistory(){return[...this.toolExecutionHistory]}clearCurrentStreamExecutions(){this.currentStreamToolExecutions=[]}registerTool(t,r,n){this.invalidateToolCache(),this.emitter.emit("tools-register:start",{toolName:t,timestamp:Date.now()});try{if(!t||typeof t!="string")throw new Error("Invalid tool name");if(!r||typeof r!="object")throw new Error(`Invalid tool object provided for tool: ${t}`);if(typeof r.execute!="function")throw new Error(`Tool '${t}' must have an execute method.`);if(t.trim()==="")throw new Error("Tool name cannot be empty");if(t.length>100)throw new Error("Tool name is too long (maximum 100 characters)");if(/[\x00-\x1F\x7F]/.test(t))throw new Error("Tool name contains invalid control characters");const o={name:r.name||t,description:r.description||t,execute:r.execute,inputSchema:"parameters"in r&&r.parameters&&(aV(r.parameters)||typeof r.parameters=="object")?r.parameters:r.inputSchema||{}};if(n?.timeout!==void 0&&n.timeout>0&&Number.isFinite(n.timeout)&&typeof o.execute=="function"){const i=o.execute,a=n.timeout,l=t;o.execute=async(...c)=>{const u=AbortSignal.timeout(a),d=c[1],m=d?.abortSignal,h=m?AbortSignal.any([m,u]):u,g={...d,abortSignal:h};return Promise.race([i(c[0],g),new Promise((y,v)=>{h.addEventListener("abort",()=>{u.aborted?v(xe.toolTimeout(l,a)):v(new DOMException("The operation was aborted","AbortError"))},{once:!0})})])}}const s=JBr(t,o,n?.timeout,n?.maxRetries);this.toolRegistry.registerServer(s),n?.cacheable===!1?this.uncacheableTools.add(t):this.uncacheableTools.delete(t),this.emitter.emit("tools-register:end",{toolName:t,success:!0,timestamp:Date.now(),timeoutMs:n?.timeout})}catch(o){throw f.error(`Failed to register tool ${t}:`,o),o}}setToolContext(t){this.toolExecutionContext={...t},f.debug("Tool execution context updated",{sessionId:t.sessionId,contextKeys:Object.keys(t),hasJuspayToken:!!t.juspayToken,hasShopId:!!t.shopId})}getToolContext(){return this.toolExecutionContext?{...this.toolExecutionContext}:void 0}clearToolContext(){this.toolExecutionContext=void 0,f.debug("Tool execution context cleared")}registerTools(t){if(Array.isArray(t))for(const{name:r,tool:n}of t)this.registerTool(r,n);else for(const[r,n]of Object.entries(t))this.registerTool(r,n)}unregisterTool(t){this.invalidateToolCache();const r=`custom-tool-${t}`,n=this.toolRegistry.unregisterServer(r);return n&&(this.uncacheableTools.delete(t),f.info(`Unregistered custom tool: ${t}`)),n}useToolMiddleware(t){return this.mcpToolMiddlewares.push(t),f.debug(`[NeuroLink] Registered tool middleware (total: ${this.mcpToolMiddlewares.length})`),this}getToolMiddlewares(){return[...this.mcpToolMiddlewares]}async flushToolBatch(){this.mcpToolBatcher&&await this.mcpToolBatcher.flush()}getMCPEnhancementsConfig(){return this.mcpEnhancementsConfig}async updateAgenticLoopReport(t,r,n){if(!this.conversationMemory)throw new ml("Conversation memory is not initialized. Enable conversationMemory in NeuroLink options.","CONFIG_ERROR");if(!("updateAgenticLoopReport"in this.conversationMemory)||typeof this.conversationMemory.updateAgenticLoopReport!="function")throw new ml("updateAgenticLoopReport is only supported with Redis conversation memory.","CONFIG_ERROR");await Ze(this.conversationMemory.updateAgenticLoopReport(t,n,r),5e3)}getCustomTools(){const t=this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0})),r=new Map;for(const o of t){const s=o.inputSchema||o.parameters;f.debug("Processing tool schema for Claude",{toolName:o.name,hasDescription:!!o.description,description:o.description,hasParameters:!!o.parameters,parametersType:typeof o.parameters,parametersKeys:o.parameters&&typeof o.parameters=="object"?Object.keys(o.parameters):"NOT_OBJECT",hasInputSchema:!!o.inputSchema,inputSchemaType:typeof o.inputSchema,inputSchemaKeys:o.inputSchema&&typeof o.inputSchema=="object"?Object.keys(o.inputSchema):"NOT_OBJECT",hasEffectiveSchema:!!s,effectiveSchemaType:typeof s,effectiveSchemaHasProperties:!!s?.properties,effectiveSchemaHasRequired:!!s?.required,originalInputSchema:o.inputSchema,phase:"AFTER_SCHEMA_FIX",timestamp:Date.now()}),r.set(o.name,{name:o.name,description:o.description||"",inputSchema:typeof o.inputSchema=="object"&&o.inputSchema!==null?o.inputSchema:typeof o.parameters=="object"&&o.parameters!==null?o.parameters:{},execute:async(i,a)=>{const l=this.toolExecutionContext||{},c=a&&ar(a)?a:{},u={...l,...c,sessionId:c.sessionId||l.sessionId||`fallback-${Date.now()}`};return f.debug("Tool execution context merged",{toolName:o.name,storedContextKeys:Object.keys(l),runtimeContextKeys:Object.keys(c),finalContextKeys:Object.keys(u),hasJuspayToken:!!u.juspayToken,hasShopId:!!u.shopId,sessionId:u.sessionId}),await this.toolRegistry.executeTool(o.name,i,u)}})}this.cachedFileTools||(this.cachedFileTools=PMt(this.fileRegistry));const n=this.cachedFileTools;for(const[o,s]of Object.entries(n))if(!r.has(o)){const i=s,a=i.inputSchema??i.parameters;r.set(o,{name:o,description:s.description||`File tool: ${o}`,inputSchema:typeof a=="object"&&a!==null?a:{type:"object",properties:{}},execute:async l=>await s.execute(l,{toolCallId:`file-tool-${Date.now()}`,messages:[]})})}return r}async addInMemoryMCPServer(t,r){this.invalidateToolCache();try{de.debug(`[NeuroLink] Registering in-memory MCP server: ${t}`),r.tools||(r.tools=[]),await this.toolRegistry.registerServer(r),de.info(`[NeuroLink] Successfully registered in-memory server: ${t}`,{category:r.metadata?.category,provider:r.metadata?.provider,version:r.metadata?.version})}catch(n){throw de.error(`[NeuroLink] Failed to register in-memory server ${t}:`,n),n}}getInMemoryServers(){const t=this.getInMemoryServerInfos(),r=new Map;for(const n of t)r.set(n.id,n);return r}getInMemoryServerInfos(){return this.toolRegistry.getBuiltInServerInfos().filter(r=>xa({existingCategory:r.metadata?.category,serverId:r.id})==="in-memory")}getAutoDiscoveredServerInfos(){return this.autoDiscoveredServerInfos}async executeTool(t,r={},n){if(this.mcpToolBatcher&&!n?.bypassBatcher)return this.mcpToolBatcher.execute(t,r);const o=this.createToolExecutionContext(t,r,n);return He.mcp.startActiveSpan("neurolink.tool.execute",{attributes:{"tool.name":t,"tool.type":o.toolType,"tool.input_size":o.inputSize,"tool.input_preview":o.truncatedInput}},s=>this.executeToolWithSpan(t,r,n,o,s))}createToolExecutionContext(t,r,n){const o=this.externalServerManager.getAllTools().find(c=>c.name===t),s=o?"mcp":this.getCustomTools().has(t)?"custom":"external",i=r?Dv(r):"",a=Date.now(),l=`${t}-${a}-${Math.random().toString(36).slice(2,11)}`;return{functionTag:"NeuroLink.executeTool",executionStartTime:a,executionId:l,externalTool:o,toolType:s,inputSize:i.length,truncatedInput:i.length>2048?i.substring(0,2048):i,options:n,hitlState:{triggered:!1}}}async executeToolWithSpan(t,r,n,o,s){try{const i=await this.prepareToolExecutionState(t,r,n,o);return await this.runPreparedToolExecution(t,r,i,o,s)}catch(i){if(!(i instanceof Ne)){const a=i instanceof Error?i.message:String(i);s.recordException(i instanceof Error?i:new Error(a)),s.setStatus({code:qe.ERROR,message:a})}throw i}finally{s.end()}}async prepareToolExecutionState(t,r,n,o){f.debug(`[${o.functionTag}] Tool execution requested:`,{toolName:t,params:ar(r)?TGe(r):r,hasExternalManager:!!this.externalServerManager}),f.debug("Tool execution detailed analysis",{toolName:t,executionStartTime:o.executionStartTime,paramsAnalysis:{type:typeof r,isNull:r===null,isUndefined:r===void 0,isEmpty:r&&typeof r=="object"&&Object.keys(r).length===0,keys:r&&typeof r=="object"?Object.keys(r):"NOT_OBJECT",keysLength:r&&typeof r=="object"?Object.keys(r).length:0},isTargetTool:t==="juspay-analytics_SuccessRateSRByTime",options:n,hasExternalManager:!!this.externalServerManager}),this.emitter.emit("tool:start",a0(t,{timestamp:o.executionStartTime,input:r,executionId:o.executionId}));const s=this.toolRegistry.getToolInfo(t),i={timeout:n?.timeout??s?.tool?.timeoutMs??Yl.EXECUTION_BATCH_MS,maxRetries:n?.maxRetries??s?.tool?.maxRetries??ls.DEFAULT,retryDelayMs:n?.retryDelayMs||bn.BASE_MS,authContext:n?.authContext,disableToolCache:n?.disableToolCache},{MemoryManager:a}=await Promise.resolve().then(()=>(ox(),q_)),l=a.getMemoryUsageMB(),u=`${o.externalTool?.serverId||s?.tool?.serverId||"unknown"}.${t}`;let d=this.toolCircuitBreakers.get(u);d||(d=new c1(lI.FAILURE_THRESHOLD,r3),this.toolCircuitBreakers.set(u,d));let m=this.toolExecutionMetrics.get(t);return m||(m={totalExecutions:0,successfulExecutions:0,failedExecutions:0,averageExecutionTime:0,lastExecutionTime:0,errorCategories:{}},this.toolExecutionMetrics.set(t,m)),m.totalExecutions++,{finalOptions:i,startMemory:l,circuitBreaker:d,breakerKey:u,metrics:m}}async runPreparedToolExecution(t,r,n,o,s){let i=0;try{de.debug(`[${o.functionTag}] Executing tool: ${t}`,{toolName:t,params:r,options:n.finalOptions,circuitBreakerState:n.circuitBreaker.getState()});const a=await n.circuitBreaker.execute(async()=>Vge(async()=>Ze(this.executeToolInternal(t,r,n.finalOptions,o.hitlState),n.finalOptions.timeout,xe.toolTimeout(t,n.finalOptions.timeout)),{maxAttempts:n.finalOptions.maxRetries+1,delayMs:n.finalOptions.retryDelayMs,isRetriable:PB,onRetry:(l,c)=>{i=l,de.warn(`[${o.functionTag}] Retrying tool execution (attempt ${l})`,{toolName:t,error:c.message,attempt:l})}}));return s.setAttribute("tool.retry_count",i),await this.handleSuccessfulToolExecution(t,a,n,o,s)}catch(a){return s.setAttribute("tool.retry_count",i),this.handleFailedToolExecution(t,r,a,n,o,s)}}async handleSuccessfulToolExecution(t,r,n,o,s){const i=Date.now()-o.executionStartTime;n.metrics.successfulExecutions++,n.metrics.lastExecutionTime=i,n.metrics.averageExecutionTime=(n.metrics.averageExecutionTime*(n.metrics.successfulExecutions-1)+i)/n.metrics.successfulExecutions;const{MemoryManager:a}=await Promise.resolve().then(()=>(ox(),q_)),c=a.getMemoryUsageMB().heapUsed-n.startMemory.heapUsed;c>20&&de.warn(`Tool '${t}' used excessive memory: ${c}MB`,{toolName:t,memoryDelta:c,executionTime:i}),de.debug(`[${o.functionTag}] Tool executed successfully`,{toolName:t,executionTime:i,memoryDelta:c,circuitBreakerState:n.circuitBreaker.getState()});const u=r&&typeof r=="object"?r:void 0,d=u&&"isError"in u&&u.isError===!0||u&&"success"in u&&u.success===!1,m=d?u?.content:void 0,h=d?m?.filter(g=>g.type==="text"&&g.text).map(g=>g.text).join(" ")||(typeof u?.error=="string"?u.error:"Unknown error"):void 0;if(d){try{await n.circuitBreaker.execute(async()=>{throw new Error(`Tool ${t} returned isError:true`)})}catch{}de.debug(`[${o.functionTag}] Circuit breaker failure recorded for isError result`,{toolName:t,circuitBreakerState:n.circuitBreaker.getState(),circuitBreakerFailures:n.circuitBreaker.getFailureCount()});const g=j7r(h??"Unknown error"),y=`[TOOL_ERROR: ${t} failed (${g})] `;if(u&&Array.isArray(m)){const b=m.map(T=>({...T}));for(const T of b)if(T.type==="text"&&T.text){T.text=y+T.text;break}u.content=b}s.setAttribute("tool.error.message",(h??"Unknown error").substring(0,500)),s.setAttribute("tool.error.category",g),s.setStatus({code:qe.ERROR,message:`MCP tool returned isError: ${(h??"Unknown error").substring(0,200)}`}),n.metrics.failedExecutions++;const v=n.metrics.successfulExecutions;n.metrics.successfulExecutions=Math.max(0,n.metrics.successfulExecutions-1),n.metrics.averageExecutionTime=v>1?(n.metrics.averageExecutionTime*v-i)/(v-1):0;const _=q7r(g);n.metrics.errorCategories[_]=(n.metrics.errorCategories[_]||0)+1}return this.emitToolEndEvent(t,o.executionStartTime,!d,r,d&&h?new Error(h):void 0,o.executionId),s.setAttribute("tool.result.status",d?"error":"success"),s.setAttribute("tool.duration_ms",i),r}async handleFailedToolExecution(t,r,n,o,s,i){o.metrics.failedExecutions++;const a=Date.now()-s.executionStartTime;if(n instanceof Xp)return de.warn(`[${s.functionTag}] Tool blocked by circuit breaker: ${t}`,{toolName:t,breakerState:n.breakerState,retryAfter:n.retryAfter,retryAfterMs:n.retryAfterMs,failureCount:n.failureCount,executionTime:a}),o.metrics.errorCategories.execution=(o.metrics.errorCategories.execution||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,new Error(`Circuit breaker open for ${t} (state=${n.breakerState}, failures=${n.failureCount})`),s.executionId),i.setAttribute("tool.result.status","circuit_breaker_open"),i.setAttribute("tool.duration_ms",a),i.setAttribute("tool.circuit_breaker.state",n.breakerState),i.setAttribute("tool.circuit_breaker.retry_after_ms",n.retryAfterMs),i.setAttribute("tool.circuit_breaker.failure_count",n.failureCount),i.setStatus({code:qe.ERROR,message:`Circuit breaker open for ${t}: ${n.message}`}),{isError:!0,content:[{type:"text",text:`TOOL TEMPORARILY UNAVAILABLE: "${t}" has been disabled after ${n.failureCount} failures. This is a circuit breaker protection \u2014 do NOT retry this tool. It will become available again after ${Math.ceil(n.retryAfterMs/1e3)} seconds (at ${n.retryAfter}). Instead, inform the user that the operation failed and suggest trying again later.`}]};let l;if(n instanceof Ne)l=n;else if(n instanceof Error)if(n.message.includes("timeout"))l=xe.toolTimeout(t,o.finalOptions.timeout);else if(n.message.includes("not found")){const u=await this.getAllAvailableTools();l=xe.toolNotFound(t,wIr(u.map(d=>({name:d.name}))))}else n.message.includes("validation")||n.message.includes("parameter")?l=xe.invalidParameters(t,n,r):n.message.includes("network")||n.message.includes("connection")?l=xe.networkError(t,n):l=xe.toolExecutionFailed(t,n);else l=xe.toolExecutionFailed(t,new Error(String(n)));const c=l.category||"execution";throw o.metrics.errorCategories[c]=(o.metrics.errorCategories[c]||0)+1,this.emitToolEndEvent(t,s.executionStartTime,!1,void 0,l,s.executionId),this.emitter.listenerCount("error")>0&&this.emitter.emit("error",l),l=new Ne({...l,context:{...l.context,executionTime:a,params:r,options:o.finalOptions,circuitBreakerState:o.circuitBreaker.getState(),circuitBreakerFailures:o.circuitBreaker.getFailureCount(),metrics:{...o.metrics}}}),Wge(l),i.setAttribute("tool.result.status","error"),i.setAttribute("tool.duration_ms",a),i.recordException(l),i.setStatus({code:qe.ERROR,message:l.message}),l}toolCacheRepeatKey(t,r){try{return`${t}:${JSON.stringify(r)??""}`}catch{return}}async executeToolInternal(t,r,n,o){const s="NeuroLink.executeToolInternal",i=this.getToolAnnotationsForExecution(t),a=this.mcpToolResultCache&&!n.disableToolCache&&!this._disableToolCacheForCurrentRequest&&!this.uncacheableTools.has(t)&&!i?.destructiveHint,l=this.mcpToolResultCache,c=n.authContext||this.toolExecutionContext?{__args:r,__ctx:n.authContext??this.toolExecutionContext}:r,u=this._generationTurnActive?this.toolCacheRepeatKey(t,c):void 0,d=u!==void 0&&this._toolCacheKeysServedThisRequest.has(u);if(u!==void 0&&this._toolCacheKeysServedThisRequest.add(u),a&&l&&!d){const g=l.getCachedResult(t,c);if(g!==void 0)return f.debug(`[${s}] Cache HIT for tool: ${t}`),g}else d&&f.debug(`[${s}] Repeat call within this request \u2014 bypassing tool cache for: ${t}`);const m=async g=>{if(this.mcpToolMiddlewares.length===0)return g();let y=0;const v=async()=>{if(y<this.mcpToolMiddlewares.length){const _=this.mcpToolMiddlewares[y++];return _({name:t,description:"",inputSchema:{},annotations:i,execute:async()=>({})},r,{toolMeta:{name:t,annotations:i}},v)}return g()};return await v()},h=async()=>{const g=this.externalServerManager.getAllTools(),y=g.filter(_=>_.name===t&&_.isAvailable);let v;if(y.length>1&&this.mcpToolRouter)try{const _={name:t,description:y[0].description??"",serverId:y[0].serverId,inputSchema:{}},b=this.mcpToolRouter.route(_);v=y.find(T=>T.serverId===b.serverId)||y[0],f.debug(`[${s}] Router selected server: ${b.serverId}`,{strategy:b.strategy,confidence:b.confidence})}catch(_){f.warn(`[${s}] Router failed, falling back to first match`,{error:_}),v=y[0]}else v=y[0];if(f.debug(`[${s}] External MCP tool search:`,{toolName:t,externalToolsCount:g.length,foundTool:!!v,isAvailable:v?.isAvailable,serverId:v?.serverId}),v&&v.isAvailable)try{de.debug(`[${s}] Executing external MCP tool: ${t} from ${v.serverId}`);const _=await this.externalServerManager.executeTool(v.serverId,t,r,{timeout:n.timeout});return f.debug(`[${s}] External MCP tool execution successful:`,{toolName:t,serverId:v.serverId,resultType:typeof _}),_}catch(_){throw f.error(`[${s}] External MCP tool execution failed:`,{toolName:t,serverId:v.serverId,error:_ instanceof Error?_.message:String(_)}),xe.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)),v.serverId)}try{const _=this.toolExecutionContext||{},b=n.authContext||{},T={..._,...b,hitlState:o};f.debug("[Using merged context for unified registry tool:",{toolName:t,storedContextKeys:Object.keys(_),finalContextKeys:Object.keys(T)});const k=await this.toolRegistry.executeTool(t,r,T);if(k&&typeof k=="object"&&"success"in k&&k.success===!1){const A=k.error||"Tool execution failed",I=new Error(A);this.emitter.listenerCount("error")>0&&this.emitter.emit("error",I)}return k}catch(_){const b=_ instanceof Error?_:new Error(String(_));if(this.emitter.listenerCount("error")>0&&this.emitter.emit("error",b),_ instanceof Error&&_.message.includes("not found")){const T=await this.getAllAvailableTools();throw xe.toolNotFound(t,T.map(k=>k.name))}throw xe.toolExecutionFailed(t,_ instanceof Error?_:new Error(String(_)))}};try{const g=await m(h);return a&&l&&g!==void 0&&(l.cacheResult(t,c,g),f.debug(`[${s}] Cached result for tool: ${t}`)),g}catch(g){const y=i?{name:t,description:"",annotations:i,execute:async()=>({})}:void 0;if(y&&GJ(y)&&g instanceof Error&&PB(g)){f.debug(`[${s}] Tool ${t} is safe to retry, attempting once more`);try{const v=await m(h);return a&&l&&v!==void 0&&l.cacheResult(t,c,v),v}catch{}}throw g}}getToolAnnotationsForExecution(t){if(this.toolCache?.tools){const r=this.toolCache.tools.find(n=>n.name===t);if(r?.annotations)return r.annotations}if(this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)return ap({name:t,description:""})}invalidateToolCache(){this.toolCache=null,f.debug("Tool cache invalidated")}async getAllAvailableTools(){if(this.toolCache&&Date.now()-this.toolCache.timestamp<this.toolCacheDuration)return f.debug("Returning available tools from cache"),this.toolCache.tools;const t=`get-all-tools-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,r=Date.now(),n=process.hrtime.bigint();f.debug("[NeuroLink] \u{1F6E0}\uFE0F LOG_POINT_A001_GET_ALL_TOOLS_START",{logPoint:"A001_GET_ALL_TOOLS_START",getAllToolsId:t,timestamp:new Date().toISOString(),getAllToolsStartTime:r,getAllToolsHrTimeStart:n.toString(),toolRegistryState:{hasToolRegistry:!!this.toolRegistry,toolRegistrySize:0,toolRegistryType:this.toolRegistry?.constructor?.name||"NOT_SET",hasExternalServerManager:!!this.externalServerManager,externalServerManagerType:this.externalServerManager?.constructor?.name||"NOT_SET"},mcpState:{mcpInitialized:this.mcpInitialized,hasProviderRegistry:!!lo,providerRegistrySize:0},message:"Starting comprehensive tool discovery across all sources"});const{MemoryManager:o}=await Promise.resolve().then(()=>(ox(),q_)),s=o.getMemoryUsageMB();try{const i=new Map,a=await this.toolRegistry.listTools();for(const y of a)if(!i.has(y.name)){const v=fP(y,{serverId:y.serverId==="direct"?"neurolink-direct":y.serverId});i.set(y.name,v)}const l=this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0}));for(const y of l)if(!i.has(y.name)){const v=fP(y,{description:"Custom tool",serverId:`custom-tool-${y.name}`,category:xa({isCustomTool:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const c=this.toolRegistry.getToolsByCategory("in-memory");for(const y of c)if(!i.has(y.name)){const v=fP(y,{description:"In-memory MCP tool",serverId:"unknown",category:"in-memory",inputSchema:{}});i.set(y.name,v)}const u=this.externalServerManager.getAllTools();for(const y of u)if(!i.has(y.name)){const v=fP(y,{category:xa({existingCategory:typeof y.metadata?.category=="string"?y.metadata.category:void 0,isExternal:!0,serverId:y.serverId}),inputSchema:{}});i.set(y.name,v)}const d=Array.from(i.values());de.debug("Tool discovery results",{mcpTools:a.length,customTools:l.length,inMemoryTools:c.length,externalMCPTools:u.length,total:d.length});const h=o.getMemoryUsageMB().heapUsed-s.heapUsed;if(h>em.LOW_USAGE_MB&&(de.debug(`\u{1F50D} Tool listing used ${h}MB memory (large tool registry detected)`),d.length>Hde.LARGE_TOOL_COLLECTION&&de.debug("\u{1F4A1} Tool collection optimized for large sets. Memory usage reduced through efficient object reuse.")),this.mcpEnhancementsConfig?.annotations?.autoInfer!==!1)for(const y of d)y.annotations||(y.annotations=ap({name:y.name,description:y.description||""}));const g=d.sort((y,v)=>y.name<v.name?-1:y.name>v.name?1:0);return this.toolCache={tools:g,timestamp:Date.now()},g}catch(i){return de.error("Failed to list available tools",{error:i}),[]}}async getProviderStatus(t){const{MemoryManager:r}=await Promise.resolve().then(()=>(ox(),q_)),n=r.getMemoryUsageMB();t?.quiet||de.debug("\u{1F50D} DEBUG: Initializing MCP for provider status..."),await this.initializeMCP(),t?.quiet||de.debug("\u{1F50D} DEBUG: MCP initialized:",this.mcpInitialized);const{AIProviderFactory:o}=await Promise.resolve().then(()=>(Ul(),Mx)),{hasProviderEnvVars:s}=await Promise.resolve().then(()=>(mh(),nx)),i=Ur.getAllDescriptors().map(m=>m.name),a=QS(qa.DEFAULT_CONCURRENCY_LIMIT),l=i.map(m=>a(async()=>{const h=Date.now();try{if(!await this.hasProviderEnvVars(m)&&m!=="ollama")return{provider:m,status:"not-configured",configured:!1,authenticated:!1,error:"Missing required environment variables",responseTime:Date.now()-h};if(m==="ollama")try{const b=await fetch("http://localhost:11434/api/tags",{method:"GET",signal:AbortSignal.timeout(Zl.AUTH_MS)});if(!b.ok)throw new Error("Ollama service not responding");const T=await b.json(),k=T?.models;if(!Array.isArray(k))throw f.warn("Ollama API returned invalid models format in testProvider",{responseData:T,modelsType:typeof k}),new Error("Invalid models format from Ollama API");const A=k.filter(I=>I&&typeof I=="object"&&typeof I.name=="string");return A.length>0?{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h,model:A[0].name}:{provider:m,status:"failed",configured:!0,authenticated:!1,error:"Ollama service running but no models installed",responseTime:Date.now()-h}}catch(b){return{provider:m,status:"failed",configured:!1,authenticated:!1,error:b instanceof Error?b.message:"Ollama service not running",responseTime:Date.now()-h}}const y=5e3,v=this.testProviderConnection(m),_=new Promise((b,T)=>{setTimeout(()=>T(new Error("Provider test timeout (5s)")),y)});return await Promise.race([v,_]),{provider:m,status:"working",configured:!0,authenticated:!0,responseTime:Date.now()-h}}catch(g){const y=g instanceof Error?g.message:String(g);return{provider:m,status:"failed",configured:!0,authenticated:!1,error:y,responseTime:Date.now()-h}}})),c=await Promise.all(l),d=r.getMemoryUsageMB().heapUsed-n.heapUsed;return!t?.quiet&&d>20&&de.debug(`\u{1F50D} Memory usage: +${d}MB (consider cleanup for large operations)`),d>50&&r.forceGC(),c}async testProvider(t){try{return await this.testProviderConnection(t),!0}catch{return!1}}async testProviderConnection(t){const{AIProviderFactory:r}=await Promise.resolve().then(()=>(Ul(),Mx));await(await r.createProvider(t,null)).generate({prompt:"test",maxTokens:1,disableTools:!0})}async getBestProvider(t){const{getBestProvider:r}=await Promise.resolve().then(()=>(mh(),nx));return r(t)}async getAvailableProviders(){const{getAvailableProviders:t}=await Promise.resolve().then(()=>(mh(),nx));return t()}async isValidProvider(t){const{isValidProvider:r}=await Promise.resolve().then(()=>(mh(),nx));return r(t)}async getMCPStatus(){try{await this.initializeMCP();const t=await this.toolRegistry.listTools(),r=this.externalServerManager.getStatistics(),n=this.externalServerManager.listServers(),o=this.getInMemoryServerInfos(),s=this.toolRegistry.getBuiltInServerInfos(),i=this.getAutoDiscoveredServerInfos(),a=n.length+o.length+s.length+i.length,l=r.connectedServers+o.length+s.length,c=t.length+r.totalTools;return{mcpInitialized:this.mcpInitialized,totalServers:a,availableServers:l,autoDiscoveredCount:i.length,totalTools:c,autoDiscoveredServers:i,customToolsCount:this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0})).length,inMemoryServersCount:o.length,externalMCPServersCount:n.length,externalMCPConnectedCount:r.connectedServers,externalMCPFailedCount:r.failedServers,externalMCPServers:n}}catch(t){return{mcpInitialized:!1,totalServers:0,availableServers:0,autoDiscoveredCount:0,totalTools:0,autoDiscoveredServers:[],customToolsCount:this.toolRegistry.getToolsByCategory(xa({isCustomTool:!0})).length,inMemoryServersCount:0,externalMCPServersCount:0,externalMCPConnectedCount:0,externalMCPFailedCount:0,externalMCPServers:[],error:t instanceof Error?t.message:String(t)}}}async listMCPServers(){return[...this.externalServerManager.listServers(),...this.getInMemoryServerInfos(),...this.toolRegistry.getBuiltInServerInfos(),...this.getAutoDiscoveredServerInfos()]}async testMCPServer(t){try{if(t==="neurolink-direct")return(await this.toolRegistry.listTools()).length>0;const r=this.getInMemoryServers();if(r.has(t)){const o=r.get(t);return!!(o?.tools&&o.tools.length>0)}const n=this.externalServerManager.getServer(t);return n?n.status==="connected"&&n.client!==null:!1}catch(r){return de.error(`[NeuroLink] Error testing MCP server ${t}:`,r),!1}}async hasProviderEnvVars(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(ey(),F_));try{const n=await r.checkProviderHealth(t,{includeConnectivityTest:!1,cacheResults:!1});return n.isConfigured&&n.hasApiKey}catch(n){return f.warn(`Provider env var check failed for ${t}`,{error:n instanceof Error?n.message:String(n)}),!1}}async checkProviderHealth(t,r={}){const{ProviderHealthChecker:n}=await Promise.resolve().then(()=>(ey(),F_)),o=await n.checkProviderHealth(t,r);return{provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}}async checkAllProvidersHealth(t={}){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(ey(),F_));return(await r.checkAllProvidersHealth(t)).map(o=>({provider:o.provider,isHealthy:o.isHealthy,isConfigured:o.isConfigured,hasApiKey:o.hasApiKey,lastChecked:o.lastChecked,error:o.error,warning:o.warning,responseTime:o.responseTime,configurationIssues:o.configurationIssues,recommendations:o.recommendations}))}async getProviderHealthSummary(){const{ProviderHealthChecker:t}=await Promise.resolve().then(()=>(ey(),F_)),r=await t.checkAllProvidersHealth({cacheResults:!0,includeConnectivityTest:!1}),n=t.getHealthSummary(r),o=[];return n.healthy===0?o.push("No providers are healthy. Check your environment configuration."):n.healthy<2&&o.push("Consider configuring additional providers for better reliability."),n.hasIssues>0&&o.push("Some providers have configuration issues. Run checkAllProvidersHealth() for details."),{...n,recommendations:o}}async clearProviderHealthCache(t){const{ProviderHealthChecker:r}=await Promise.resolve().then(()=>(ey(),F_));r.clearHealthCache(t)}getToolExecutionMetrics(){const t={};for(const[r,n]of this.toolExecutionMetrics.entries())t[r]={...n,errorCategories:{...n.errorCategories},successRate:n.totalExecutions>0?n.successfulExecutions/n.totalExecutions:0};return t}setModelAliasConfig(t){this.modelAliasConfig=t,f.info(`[ModelAlias] Configured ${Object.keys(t.aliases).length} model aliases`)}getToolCircuitBreakerStatus(){const t={};for(const[r,n]of this.toolCircuitBreakers.entries())t[r]={state:n.getState(),failureCount:n.getFailureCount(),isHealthy:n.getState()==="closed"};return t}resetToolCircuitBreaker(t){this.toolCircuitBreakers.has(t)&&(this.toolCircuitBreakers.set(t,new c1(lI.FAILURE_THRESHOLD,r3)),de.info(`Circuit breaker reset for tool: ${t}`))}clearToolExecutionMetrics(){this.toolExecutionMetrics.clear(),de.info("All tool execution metrics cleared")}async getToolHealthReport(){const t={};let r=0;const n=await this.toolRegistry.listTools(),o=new Set(n.map(i=>i.name)),s=new Map;for(const i of n)s.has(i.name)||s.set(i.name,i.serverId||"unknown");for(const i of o){const a=this.toolExecutionMetrics.get(i),l=`${s.get(i)||"unknown"}.${i}`,c=this.toolCircuitBreakers.get(l),u=a&&a.totalExecutions>0?a.successfulExecutions/a.totalExecutions:0,d=(!c||c.getState()==="closed")&&u>=.8;d&&r++;const m=[],h=[];if(c&&c.getState()==="open"&&(m.push("Circuit breaker is open due to repeated failures"),h.push("Check tool implementation and fix underlying issues")),u<.8&&a&&a.totalExecutions>0&&(m.push(`Low success rate: ${(u*100).toFixed(1)}%`),h.push("Review error logs and improve tool reliability")),a&&a.averageExecutionTime>1e4&&(m.push("High average execution time"),h.push("Optimize tool performance or increase timeout")),a&&a.errorCategories){const g=a.errorCategories;g.timeout>0&&(m.push(`Timeout errors: ${g.timeout}`),h.push("Consider increasing the tool timeout configuration")),g.validation>0&&(m.push(`Validation errors: ${g.validation}`),h.push("Review input schemas and parameter validation")),g.network>0&&(m.push(`Network errors: ${g.network}`),h.push("Check network connectivity and endpoint availability"))}t[i]={name:i,isHealthy:d,metrics:{totalExecutions:a?.totalExecutions||0,successRate:u,averageExecutionTime:a?.averageExecutionTime||0,lastExecutionTime:a?.lastExecutionTime||0,errorCategories:a?.errorCategories?{...a.errorCategories}:{}},circuitBreaker:{state:c?.getState()||"closed",failureCount:c?.getFailureCount()||0},issues:m,recommendations:h}}return{totalTools:o.size,healthyTools:r,unhealthyTools:o.size-r,tools:t}}async ensureConversationMemoryInitialized(){try{const t=`manual-init-${Date.now()}`;return await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!!this.conversationMemory}catch(t){return f.error("Failed to initialize conversation memory",{error:t instanceof Error?t.message:String(t)}),!1}}async getConversationStats(){const t=`stats-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return await this.conversationMemory.getStats()}async getConversationHistory(t){const r=`history-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});try{const n=await this.conversationMemory.buildContextMessages(t);return f.debug("Retrieved conversation history",{sessionId:t,messageCount:n.length,turnCount:n.length/2}),n}catch(n){return f.error("Failed to retrieve conversation history",{sessionId:t,error:n instanceof Error?n.message:String(n)}),[]}}async clearConversationSession(t){const r=`clear-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});return this.lastCompactionMessageCount.delete(t),await this.conversationMemory.clearSession(t)}async clearAllConversations(){const t=`clear-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(t,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});this.lastCompactionMessageCount.clear(),await this.conversationMemory.clearAllSessions()}async listSessions(t){const r=`list-sessions-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(r,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!this.conversationMemory.listSessions)return f.warn("listSessions not available on current memory manager"),[];const n=3e4;try{const o=await Ze(this.conversationMemory.listSessions(t),n,new Error("listSessions operation timed out after 30s"));return f.debug("Listed conversation sessions",{userId:t,sessionCount:o.length}),o}catch(o){return f.error("Failed to list conversation sessions",{userId:t,error:o instanceof Error?o.message:String(o)}),[]}}async exportSession(t,r={}){const n=`export-session-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");if(!t||typeof t!="string")throw new Error("Session ID must be a non-empty string");const o=3e4;try{const s=await Ze(this.conversationMemory.buildContextMessages(t),o,new Error("buildContextMessages operation timed out after 30s"));if(s.length===0)return f.debug("No messages found for session export",{sessionId:t}),null;const i=this.conversationMemory.getSession(t),a=await Ze(i instanceof Promise?i:Promise.resolve(i),o,new Error("getSession operation timed out after 30s")),l=new Date().toISOString(),c={sessionId:t,title:t,userId:a?.userId,createdAt:a?.createdAt?new Date(a.createdAt).toISOString():l,updatedAt:a?.lastActivity?new Date(a.lastActivity).toISOString():l,messages:s};return r.includeMetadata&&(c.exportMetadata={exportedAt:l,exportFormat:r.format||"json"}),f.debug("Exported conversation session",{sessionId:t,messageCount:s.length}),c}catch(s){return f.error("Failed to export conversation session",{sessionId:t,error:s instanceof Error?s.message:String(s)}),null}}async exportAllSessions(t,r={}){const n=`export-all-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Error("Conversation memory is not enabled");const o=3e4,s=6e4;try{const i=await Ze(this.listSessions(t),o,new Error("listSessions operation timed out after 30s")),a=[];for(const l of i){const c=await Ze(this.exportSession(l.id,r),s,new Error(`exportSession operation timed out after 60s for session ${l.id}`));c&&a.push(c)}return f.debug("Exported all conversation sessions",{userId:t,sessionCount:a.length}),a}catch(i){return f.error("Failed to export all conversation sessions",{userId:t,error:i instanceof Error?i.message:String(i)}),[]}}async storeToolExecutions(t,r,n,o,s){const i=n&&n.length>0||o&&o.length>0;if(!i){f.debug("Tool execution storage skipped",{hasToolData:i,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});return}const a=this.conversationMemory;if(!a?.storeToolExecution){f.debug("Tool execution storage not supported by this memory backend");return}try{await a.storeToolExecution(t,r,n,o,s)}catch(l){f.warn("Failed to store tool executions",{sessionId:t,userId:r,error:l instanceof Error?l.message:String(l)})}}isToolExecutionStorageAvailable(){return typeof this.conversationMemory?.storeToolExecution=="function"}async getSessionMessages(t,r){const n=`get-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(n,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});return await this.conversationMemory.getSessionMessages(t,r)}async setSessionMessages(t,r,n){const o=`set-msgs-init-${Date.now()}`;if(await this.initializeConversationMemoryForGeneration(o,Date.now(),process.hrtime.bigint()),!this.conversationMemory)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Conversation memory is not enabled",category:"validation",severity:"high",retriable:!1});if(!t||typeof t!="string")throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Session ID must be a non-empty string",category:"validation",severity:"medium",retriable:!1,context:{sessionId:t}});await this.conversationMemory.setSessionMessages(t,r,n)}async modifyLastAssistantMessage(t,r,n){const o=await this.getSessionMessages(t,n);for(let s=o.length-1;s>=0;s--)if(o[s].role==="assistant")return o[s]={...o[s],content:r(o[s].content)},await this.setSessionMessages(t,o,n),!0;return!1}async addExternalMCPServer(t,r){this.invalidateToolCache();try{de.info(`[NeuroLink] Adding external MCP server: ${t}`,{command:r.command,transport:r.transport});const n=await this.externalServerManager.addServer(t,r);if(n.success){if(de.info(`[NeuroLink] External MCP server added successfully: ${t}`,{toolsDiscovered:n.metadata?.toolsDiscovered||0,duration:n.duration}),this.mcpEnhancementsConfig?.router?.enabled!==!1){const o=this.externalServerManager.listServers();if(o.length>=2&&!this.mcpToolRouter){this.mcpToolRouter=new mL({strategy:this.mcpEnhancementsConfig?.router?.strategy??"least-loaded",enableAffinity:this.mcpEnhancementsConfig?.router?.enableAffinity??!1});for(const s of o)this.mcpToolRouter.registerServer(s.id||t);f.debug("[NeuroLink] ToolRouter auto-initialized (2+ external servers)")}else this.mcpToolRouter&&this.mcpToolRouter.registerServer(t)}this.emitter.emit("externalMCP:serverAdded",{serverId:t,serverName:r.name||t,config:r,toolCount:n.metadata?.toolsDiscovered||0,timestamp:Date.now()})}else de.error(`[NeuroLink] Failed to add external MCP server: ${t}`,{error:n.error,transport:r.transport,command:r.command,url:r.url?Xn(r.url):void 0});return n}catch(n){throw de.error(`[NeuroLink] Error adding external MCP server: ${t}`,n),n}}async removeExternalMCPServer(t){this.invalidateToolCache();try{de.info(`[NeuroLink] Removing external MCP server: ${t}`);const r=this.externalServerManager.getServerName(t),n=await this.externalServerManager.removeServer(t);return n.success?(de.info(`[NeuroLink] External MCP server removed successfully: ${t}`),this.emitter.emit("externalMCP:serverRemoved",{serverId:t,serverName:r,timestamp:Date.now()})):n.error?.includes("not found")?de.debug(`[NeuroLink] Remove skipped \u2014 external MCP server not registered: ${t}`):de.error(`[NeuroLink] Failed to remove external MCP server: ${t}`,{error:n.error}),n}catch(r){throw de.error(`[NeuroLink] Error removing external MCP server: ${t}`,r),r}}listExternalMCPServers(){const t=this.externalServerManager.getServerStatuses(),r=this.externalServerManager.listServers();return t.map(n=>{const o=r.find(s=>s.id===n.serverId);return{serverId:n.serverId,status:n.status,toolCount:n.toolCount,uptime:n.performance.uptime,isHealthy:n.isHealthy,config:o||{}}})}getExternalMCPServer(t){return this.externalServerManager.getServer(t)}async executeExternalMCPTool(t,r,n,o){try{de.debug(`[NeuroLink] Executing external MCP tool: ${r} on ${t}`);const s=this.getToolAnnotationsForExecution(r),i=!!this.mcpToolResultCache&&!this._disableToolCacheForCurrentRequest&&!s?.destructiveHint,a={__serverId:t,__args:n,...this.toolExecutionContext?{__ctx:this.toolExecutionContext}:{}},l=this._generationTurnActive?this.toolCacheRepeatKey(r,a):void 0,c=l!==void 0&&this._toolCacheKeysServedThisRequest.has(l);if(l!==void 0&&this._toolCacheKeysServedThisRequest.add(l),i&&this.mcpToolResultCache&&!c){const h=this.mcpToolResultCache.getCachedResult(r,a);if(h!==void 0)return de.debug(`[NeuroLink] Tool result cache HIT: ${r} on ${t}`),h}const u=await this.externalServerManager.executeTool(t,r,n,o),d=u&&typeof u=="object"?u:void 0,m=!!(d&&"isError"in d&&d.isError===!0||d&&"success"in d&&d.success===!1);return i&&this.mcpToolResultCache&&!m&&u!==void 0&&this.mcpToolResultCache.cacheResult(r,a,u),de.debug(`[NeuroLink] External MCP tool ${m?"returned error":"executed successfully"}: ${r}`),u}catch(s){throw de.error(`[NeuroLink] External MCP tool execution failed: ${r}`,s),s}}getExternalMCPTools(){return this.externalServerManager.getAllTools()}getExternalMCPServerTools(t){return this.externalServerManager.getServerTools(t)}async testExternalMCPConnection(t){try{const{MCPClientFactory:r}=await Ze(Promise.resolve().then(()=>(cte(),bOt)),1e4),n=await r.testConnection(t,1e4);return{success:n.success,error:n.error,toolCount:n.capabilities?1:0}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}getExternalMCPStatistics(){return this.externalServerManager.getStatistics()}async shutdownExternalMCPServers(){try{de.info("[NeuroLink] Shutting down all external MCP servers..."),this.unregisterAllExternalMCPToolsFromRegistry(),await this.externalServerManager.shutdown(),de.info("[NeuroLink] All external MCP servers shut down successfully")}catch(t){throw de.error("[NeuroLink] Error shutting down external MCP servers:",t),t}}async getElicitationManager(){return(await Ze(Promise.resolve().then(()=>(Y6t(),J6t)),1e4)).globalElicitationManager}async registerElicitationHandler(t){(await this.getElicitationManager()).registerHandler(t)}async getMultiServerManager(){return(await Ze(Promise.resolve().then(()=>(aee(),zMt)),1e4)).globalMultiServerManager}async getEnhancedToolDiscovery(){const t=await Ze(Promise.resolve().then(()=>(lee(),jMt)),1e4);return new t.EnhancedToolDiscovery(this.toolRegistry)}async getMCPRegistryClient(){return(await Ze(Promise.resolve().then(()=>(e5t(),Z6t)),1e4)).globalMCPRegistryClient}async exposeAgentAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Ioe(),xoe)),1e4)).exposeAgentAsTool(t,r)}async exposeWorkflowAsTool(t,r){return(await Ze(Promise.resolve().then(()=>(Ioe(),xoe)),1e4)).exposeWorkflowAsTool(t,r)}async getToolIntegrationManager(){return(await Ze(Promise.resolve().then(()=>(a5t(),n5t)),1e4)).globalToolIntegrationManager}async convertToolsToMCPFormat(t,r={}){const n=await Ze(Promise.resolve().then(()=>(g4(),HJ)),1e4),o=t.map(s=>({...s,execute:s.execute??(async()=>({success:!1,error:"No execute function provided"}))}));return n.batchConvertToMCP(o,r)}async convertToolsFromMCPFormat(t,r={}){return(await Ze(Promise.resolve().then(()=>(g4(),HJ)),1e4)).batchConvertToNeuroLink(t,r)}async getToolAnnotations(t){const{inferAnnotations:r,mergeAnnotations:n,getAnnotationSummary:o}=await Ze(Promise.resolve().then(()=>(rC(),Owt)),1e4),s=this.toolRegistry.getToolInfo(t);if(!s)return null;const i=s.tool.annotations,a=r({name:s.tool.name,description:s.tool.description??""}),l=n(a,i);return{annotations:l,summary:o(l)}}convertExternalMCPToolsToAISDKFormat(){const t=this.externalServerManager.getAllTools(),r={};for(const n of t)if(n.isAvailable){const o={description:n.description,execute:async s=>{try{de.debug(`[NeuroLink] Executing external MCP tool via AI SDK: ${n.name}`,{params:s});const i=await this.externalServerManager.executeTool(n.serverId,n.name,s,{timeout:3e4});return de.debug(`[NeuroLink] External MCP tool execution result: ${n.name}`,{success:!!i,hasData:!!(i&&typeof i=="object"&&"content"in i)}),i}catch(i){throw de.error(`[NeuroLink] External MCP tool execution failed: ${n.name}`,i),i}}};r[n.name]=o,de.debug(`[NeuroLink] Converted external MCP tool to AI SDK format: ${n.name} from server ${n.serverId}`)}return de.info(`[NeuroLink] Converted ${Object.keys(r).length} external MCP tools to AI SDK format`),r}convertJSONSchemaToAISDKFormat(t){}unregisterExternalMCPToolsFromRegistry(t){try{const r=this.externalServerManager.getServerTools(t);for(const n of r)this.toolRegistry.removeTool(n.name),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${n.name}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tools from registry for server ${t}:`,r)}}unregisterExternalMCPToolFromRegistry(t){try{this.toolRegistry.removeTool(t),de.debug(`[NeuroLink] Unregistered external MCP tool from main registry: ${t}`)}catch(r){de.error(`[NeuroLink] Failed to unregister external MCP tool ${t} from registry:`,r)}}async lazyInitializeConversationMemory(t,r,n){try{const{initializeConversationMemory:o}=await F7r().then(()=>u5t),s=await o(this.conversationMemoryConfig);this.conversationMemory=s,this.conversationMemoryNeedsInit=!1}catch(o){throw f.error("[NeuroLink] \u274C LOG_POINT_G005_MEMORY_LAZY_INIT_ERROR",{logPoint:"G005_MEMORY_LAZY_INIT_ERROR",generateInternalId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-r,elapsedNs:(process.hrtime.bigint()-n).toString(),error:o instanceof Error?o.message:String(o),errorName:o instanceof Error?o.name:"UnknownError",errorStack:o instanceof Error?o.stack:void 0,message:"Lazy conversation memory initialization failed"}),o}}unregisterAllExternalMCPToolsFromRegistry(){try{const t=this.externalServerManager.getAllTools();for(const r of t)this.toolRegistry.removeTool(r.name);de.debug(`[NeuroLink] Unregistered ${t.length} external MCP tools from main registry`)}catch(t){de.error("[NeuroLink] Failed to unregister all external MCP tools from registry:",t)}}async createEvaluationPipeline(t){const{EvaluationPipeline:r,getPreset:n}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));let o;typeof t=="string"?o=n(t):o=t;const s=new r(o);return await Ze(s.initialize(),3e4,xe.evaluationTimeout("pipeline initialization",3e4)),f.debug(`[NeuroLink] Created evaluation pipeline: ${o.name??"custom"}`),s}async evaluate(t,r){const{EvaluationPipeline:n,getPreset:o}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));let s;if(r?.pipeline&&r?.scorers)throw new Error("Cannot specify both 'pipeline' and 'scorers' options. Use one or the other.");if(r?.scorers&&r.scorers.length===0)throw new Error("The 'scorers' array must not be empty. Provide at least one scorer ID or omit the option to use the default 'quality' preset.");r?.pipeline?s={...o(r.pipeline)}:r?.scorers&&r.scorers.length>0?s={name:"SDK Evaluation",description:"Evaluation from NeuroLink SDK",scorers:r.scorers.map(c=>({id:c})),executionMode:r.executionMode??"parallel",passThreshold:r.passThreshold??.7}:s=o("quality"),r?.passThreshold!==void 0&&(s.passThreshold=r.passThreshold),r?.executionMode!==void 0&&(s.executionMode=r.executionMode);const i=new n(s);await Ze(i.initialize(),3e4,xe.evaluationTimeout("pipeline initialization",3e4));const a=r?.timeoutMs??6e4,l=await Ze(i.execute(t,{correlationId:r?.correlationId}),a,xe.evaluationTimeout("pipeline execution",a));return f.debug("[NeuroLink] Evaluation completed",{pipeline:s.name,overallScore:l.overallScore,passed:l.passed,scorerCount:l.scores.length}),l}async score(t,r,n){const{ScorerRegistry:o}=await Ze(Promise.resolve().then(()=>(f7(),h7)),1e4,xe.evaluationTimeout("scorer module load",1e4));await Ze(o.registerBuiltInScorers(),3e4,xe.evaluationTimeout("scorer bootstrap",3e4));const s=await Ze(o.getScorer(t,n),3e4,xe.evaluationTimeout(`scorer load: ${t}`,3e4));if(!s)throw xe.scorerNotFound(t);const i=s.validateInput(r);if(!i.valid)throw xe.evaluationValidationFailed(t,i.errors);const a=await Ze(s.score(r),6e4,xe.evaluationTimeout("scorer execution",6e4));return f.debug("[NeuroLink] Scoring completed",{scorerId:t,score:a.score,passed:a.passed,computeTime:a.computeTime}),a}async getAvailableScorers(t){const{ScorerRegistry:r}=await Ze(Promise.resolve().then(()=>(f7(),h7)),1e4,xe.evaluationTimeout("scorer module load",1e4));await Ze(r.registerBuiltInScorers(),3e4,xe.evaluationTimeout("scorer bootstrap",3e4));let n=r.list();return t?.category&&(n=n.filter(o=>o.category===t.category)),t?.type&&(n=n.filter(o=>o.type===t.type)),n}async getEvaluationPresets(){const{getPresetNames:t}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));return t()}async getEvaluationPreset(t){const{getPreset:r}=await Ze(Promise.resolve().then(()=>($E(),LE)),1e4,xe.evaluationTimeout("evaluation module load",1e4));return r(t)}async createAgent(t){const{Agent:r}=await Promise.resolve().then(()=>(Noe(),d5t));return f.debug("[NeuroLink] Creating agent",{id:t.id,name:t.name,tools:t.tools?.length||0}),new r(t,this)}async createNetwork(t){const{AgentNetwork:r}=await Promise.resolve().then(()=>(m5t(),p5t));return f.debug("[NeuroLink] Creating agent network",{name:t.name,agentCount:t.agents.length,workflowCount:t.workflows?.length||0,toolCount:t.tools?.length||0}),new r(t,this)}createWorkerInstance(t){const r=t?.logTag??"worker",n=this.emitter,o=t?.config??{},s={...this.credentials?{credentials:this.credentials}:{},...o,conversationMemory:{enabled:!1},enableOrchestration:!1,observability:{...this.observabilityConfig??{},langfuse:{...this.observabilityConfig?.langfuse??{},autoDetectExternalProvider:!0,skipLangfuseSpanProcessor:!0}},...t?.shareToolRegistry!==!1&&{toolRegistry:this.toolRegistry}},i=new fF(s);if(t?.shareToolRegistry!==!1)for(const a of this.uncacheableTools)i.uncacheableTools.add(a);if(f.setEventEmitter(n),t?.onLog){const a=t.onLog,l=u=>{try{const d=u??{};a({tag:r,level:String(d.level??"info"),message:String(d.message??""),timestamp:typeof d.timestamp=="number"?d.timestamp:Date.now(),data:d.data})}catch{}};n.on("log-event",l);const c=i.dispose.bind(i);i.dispose=async()=>{n.off("log-event",l),await c()}}return f.debug("[NeuroLink] Created worker instance",{tag:r,sharedToolRegistry:t?.shareToolRegistry!==!1}),i}async runIsolatedAgent(t,r,n){const{runIsolatedAgent:o}=await Promise.resolve().then(()=>(Vk(),bL));return o(this,t,r,n)}async continueAgent(t,r){const{continueIsolatedAgent:n}=await Promise.resolve().then(()=>(Vk(),bL));return n(this,t,r)}async stopAgent(t){const{stopIsolatedAgent:r}=await Promise.resolve().then(()=>(Vk(),bL));return r(this,t)}async registerAgentTool(t,r){const{registerAgentTool:n}=await Promise.resolve().then(()=>(Kk(),CL)),o=n(this,t,r);return this.hasAgentTools=!0,o}registerTaskTools(){if(this.hasTaskChecklistTools)return;const t=bjr(this);for(const[r,n]of Object.entries(t))this.registerTool(r,n,{cacheable:!1});this.hasTaskChecklistTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(t).length} task checklist tools`)}getTaskState(t){return yjr(t??ns(this))}clearTaskState(t){return vjr(t??ns(this))}registerDelegationTools(t){if(Bjr(this,t),this.hasBackgroundDelegationTools)return;const r=Yjr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundDelegationTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background delegation tools`)}async spawnDelegate(t){return r2t(this,t)}async collectDelegates(t){return o2t(this,t)}async cancelDelegates(t){return Ure(this,t)}getArtifactStore(){return this.mcpArtifactStore||(this.mcpArtifactStore=new Tte,f.debug("[NeuroLink] Artifact store created on demand (local-temp) for banking")),this.registerMemoryRetrievalTools(),this.mcpArtifactStore}async bankArtifact(t,r){return szr(this,t,r)}async readArtifact(t,r){return izr(this,t,r)}registerBackgroundCommandTools(t){if(p2t(this,t),this.hasBackgroundCommandTools)return;const r=aqr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasBackgroundCommandTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} background command tools`)}setBackgroundCommandPolicy(t){p2t(this,t)}async startBackgroundCommand(t,r){return w2t(this,t,r)}getBackgroundCommandStatus(t){return b2t(this,t)}async awaitBackgroundCommand(t,r){return Qre(this,t,r)}async killBackgroundCommand(t,r){return T2t(this,t,r)}async readBackgroundCommandOutput(t,r){return NL(this,t,r)}registerGitTools(t){if(lqr(this,t),this.hasGitTools)return;const r=fqr(this);for(const[n,o]of Object.entries(r))this.registerTool(n,o,{cacheable:!1});this.hasGitTools=!0,f.info(`[NeuroLink] Registered ${Object.keys(r).length} read-only git tools`)}async runGitCommand(t,r){return N2t(this,t,r)}async executeNetwork(t,r,n){return f.debug("[NeuroLink] Executing agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),t.execute(r,n)}async*streamNetwork(t,r,n){f.debug("[NeuroLink] Streaming agent network",{networkId:t.id,networkName:t.name,hasContext:!!r.context}),yield*t.stream(r,n)}async createOrchestrator(t){const{NetworkOrchestrator:r}=await Promise.resolve().then(()=>(y5t(),g5t));return f.debug("[NeuroLink] Creating network orchestrator",{maxConcurrentExecutions:t?.maxConcurrentExecutions,defaultMode:t?.defaultMode}),new r(this,t)}async createCoordinator(t){const{AgentCoordinator:r}=await Promise.resolve().then(()=>(_5t(),v5t));return f.debug("[NeuroLink] Creating agent coordinator",{strategy:t?.strategy,maxConcurrency:t?.maxConcurrency}),new r(t)}async createMessageBus(t){const{MessageBus:r}=await Promise.resolve().then(()=>(b5t(),w5t));return f.debug("[NeuroLink] Creating message bus",{maxHistorySize:t?.maxHistorySize}),new r(t)}async dispose(){f.debug("[NeuroLink] Starting disposal of resources..."),this.lastCompactionMessageCount.clear();const t=[];try{try{await E2t(this),await Ure(this)}catch(r){const n=r instanceof Error?r:new Error(`Background work cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error stopping background work:",r)}try{f.debug("[NeuroLink] Flushing and shutting down OpenTelemetry..."),await qD(),await GD(),f.debug("[NeuroLink] OpenTelemetry shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`OpenTelemetry shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down OpenTelemetry:",r)}if(this.externalServerManager)try{f.debug("[NeuroLink] Shutting down external MCP servers..."),await this.externalServerManager.shutdown(),f.debug("[NeuroLink] External MCP servers shutdown successfully")}catch(r){const n=r instanceof Error?r:new Error(`External server shutdown error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error shutting down external MCP servers:",r)}if(this.emitter)try{f.debug("[NeuroLink] Removing all event listeners..."),this.emitter.removeAllListeners(),f.clearEventEmitter(this.emitter),f.debug("[NeuroLink] Event listeners removed successfully")}catch(r){const n=r instanceof Error?r:new Error(`Event emitter cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error removing event listeners:",r)}if(this.toolCircuitBreakers&&this.toolCircuitBreakers.size>0)try{f.debug(`[NeuroLink] Clearing ${this.toolCircuitBreakers.size} circuit breakers...`),this.toolCircuitBreakers.clear(),f.debug("[NeuroLink] Circuit breakers cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Circuit breaker cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing circuit breakers:",r)}try{f.debug("[NeuroLink] Clearing maps and caches..."),this.toolExecutionMetrics&&this.toolExecutionMetrics.clear(),this.activeToolExecutions&&this.activeToolExecutions.clear(),this.currentStreamToolExecutions&&(this.currentStreamToolExecutions.length=0),this.toolExecutionHistory&&(this.toolExecutionHistory.length=0),this.toolCache&&(this.toolCache.tools=[],this.toolCache.timestamp=0),this.mcpToolResultCache?.destroy(),this.mcpToolRouter?.destroy(),this.mcpToolBatcher?.destroy(),this.mcpToolResultCache=void 0,this.mcpToolRouter=void 0,this.mcpToolBatcher=void 0,this.mcpEnhancedDiscovery=void 0,this.mcpToolMiddlewares=[],f.debug("[NeuroLink] Maps and caches cleared successfully")}catch(r){const n=r instanceof Error?r:new Error(`Cache cleanup error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error clearing caches:",r)}if(this._taskManager)try{f.debug("[NeuroLink] Shutting down TaskManager..."),await Ze(this._taskManager.shutdown(),5e3,new Error("TaskManager shutdown timed out"))}catch(r){f.warn("[NeuroLink] TaskManager shutdown error:",r)}finally{this._taskManager=void 0}try{f.debug("[NeuroLink] Resetting initialization state..."),this.mcpInitialized=!1,this.mcpInitPromise=null,this.conversationMemoryNeedsInit=!1,this.credentials=void 0,f.debug("[NeuroLink] Initialization state reset successfully")}catch(r){const n=r instanceof Error?r:new Error(`State reset error: ${String(r)}`);t.push(n),f.warn("[NeuroLink] Error resetting state:",r)}t.length===0?f.debug("[NeuroLink] \u2705 Resource disposal completed successfully"):f.warn(`[NeuroLink] \u26A0\uFE0F Resource disposal completed with ${t.length} errors`,{errors:t.map(r=>r.message)})}catch(r){throw f.error("[NeuroLink] Critical error during disposal:",r),r}}getToolRegistry(){return this.toolRegistry}async compactSession(t,r){if(!this.conversationMemory)return null;const n=await this.conversationMemory.buildContextMessages(t);if(!n||n.length===0)return null;const o=new m_({...r,summarizationProvider:r?.summarizationProvider??this.conversationMemoryConfig?.conversationMemory?.summarizationProvider,summarizationModel:r?.summarizationModel??this.conversationMemoryConfig?.conversationMemory?.summarizationModel}),s=ka({provider:r?.provider||"openai",conversationMessages:n}),i=Math.floor(s.availableInputTokens*.6),a=await o.compact(n,i,this.conversationMemoryConfig?.conversationMemory);return a.compacted&&d_(a.messages),a}async getContextStats(t,r,n){if(!this.conversationMemory)return null;const o=await this.conversationMemory.buildContextMessages(t);if(!o||o.length===0)return null;const s=ka({provider:r||"openai",model:n,conversationMessages:o});return{estimatedInputTokens:s.estimatedInputTokens,availableInputTokens:s.availableInputTokens,usageRatio:s.usageRatio,shouldCompact:s.shouldCompact,messageCount:o.length}}needsCompaction(t,r,n){if(!this.conversationMemory)return!1;const o=this.conversationMemory.getSession?.(t);return o?ka({provider:r||"openai",model:n,conversationMessages:o.messages}).shouldCompact:!1}async setAuthProvider(t){this.authInitPromise=void 0,await this.initializeAuthProviderFromConfig(t)}async initializeAuthProviderFromConfig(t){let r,n;if("authenticateToken"in t&&typeof t.authenticateToken=="function")r=t,n=r.type;else if("provider"in t)r=t.provider,n=r.type;else{const o=t,{AuthProviderFactory:s}=await Promise.resolve().then(()=>(E$(),T5t));r=await s.createProvider(o.type,o.config),n=o.type}this.authProvider=r,f.info(`Auth provider set: ${n}`),this.emitter.emit("auth:provider:set",{type:r.type,timestamp:Date.now()})}getAuthProvider(){return this.authProvider}async ensureAuthProvider(){if(this.authProvider||!this.pendingAuthConfig)return;const t=this.pendingAuthConfig;this.authInitPromise??=(async()=>{try{await this.initializeAuthProviderFromConfig(t),this.pendingAuthConfig=void 0}finally{this.authInitPromise&&(this.pendingAuthConfig===void 0||this.pendingAuthConfig===t)&&(this.authInitPromise=void 0)}})(),await this.authInitPromise}async setAuthContext(t){const{globalAuthContext:r}=await Promise.resolve().then(()=>(Ik(),oL));r.set(t),f.debug("Auth context set",{userId:t.user.id,provider:t.provider,sessionId:t.session?.id})}async getAuthContext(){const{getAuthContext:t}=await Promise.resolve().then(()=>(Ik(),oL));return t()}async clearAuthContext(){const{globalAuthContext:t}=await Promise.resolve().then(()=>(Ik(),oL)),r=t.get()?.user.id;t.clear(),r&&f.debug(`Auth context cleared for user: ${r}`)}getExternalServerManager(){return this.externalServerManager}buildResolutionContext(t,r){return{requestContext:r||{},signal:t}}async resolveDynamicOptions(t){const r=["model","provider","temperature","maxTokens","systemPrompt","timeout","thinkingLevel","disableTools","enableAnalytics","enableEvaluation"];if(!(r.some(s=>typeof t[s]=="function")||typeof t.tools=="function"))return;const o=t.dynamicContext;await this.resolveDynamicFields(t,r,o)}async resolveDynamicFields(t,r,n){const o=this.buildResolutionContext(t.abortSignal,n);if(f.debug("[NeuroLink] Resolving dynamic arguments"),await Promise.all(r.map(async s=>{if(typeof t[s]=="function"){const i=await xte(t[s],o);t[s]=i.value,f.debug(`[NeuroLink] Resolved dynamic ${s}: ${i.resolutionType}`)}})),typeof t.tools=="function"){const s=await xte(t.tools,o);if(!Array.isArray(s.value))throw new TypeError(`Dynamic tools resolver must return string[] (tool names), got ${typeof s.value=="object"?"object":typeof s.value}`);t.enabledToolNames=s.value,delete t.tools}}},Hoe=new fx,C5t=Hoe}}),k5t={};he(k5t,{VoyageProvider:()=>I5t});var x5t,Voe,A5t,C$,I5t,W7r=S({async"src/lib/providers/voyage.ts"(){"use strict";vc(),await dd(),no(),vt(),ct(),q(),Zo(),x5t="https://api.voyageai.com/v1",Voe=6e4,A5t=()=>Bi(Fcr()),C$=()=>zi("VOYAGE_MODEL","voyage-3.5"),I5t=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"voyage",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:A5t(),this.baseURL=n?.baseURL??process.env.VOYAGE_BASE_URL??x5t,this.proxyFetch=Bt(),f.debug("Voyage Provider initialized (embeddings only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return C$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return C$()}getAISDKModel(){throw new yt("Voyage AI is an embedding-only provider; chat completions are not available. Use `embed()` or `embedMany()` instead, or pick a different provider for `generate()` / `stream()`.","voyage")}async executeStream(e,t){throw new yt("Voyage AI is an embedding-only provider; streaming chat is not available. Use `embed()` / `embedMany()`, or pick another provider for `stream()`.","voyage")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.includes("invalid_api_key")?new or("Invalid Voyage AI API key. Get one at https://dash.voyageai.com/api-keys","voyage"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Voyage AI rate limit exceeded. Back off and retry.","voyage"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new co(`Voyage AI model '${this.modelName}' not found. Browse https://docs.voyageai.com/docs/embeddings`,"voyage"):new yt(`Voyage AI error: ${t}`,"voyage")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new yt("Voyage AI returned no embedding for the provided text","voyage");return r[0]}async embedMany(e,t){if(e.length===0)return[];const r=128,n=[];for(let o=0;o<e.length;o+=r){const s=e.slice(o,o+r),i=await this.callEmbeddings(s,t);n.push(...i)}return n}async callEmbeddings(e,t){const r=t??this.modelName;let n;try{n=await Ze(this.proxyFetch(`${this.baseURL}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:r})}),Voe,new yt(`Voyage embeddings request timed out after ${Voe/1e3}s`,"voyage"))}catch(i){throw i instanceof yt?i:this.formatProviderError(i)}if(!n.ok){const i=await n.text();throw this.formatProviderError(new Error(`Voyage embeddings failed: ${n.status} \u2014 ${i}`))}const o=await n.json();if(!o.data||o.data.length===0)throw new yt("Voyage embeddings response missing data","voyage");if(o.data.length!==e.length)throw new yt(`Voyage embeddings response count mismatch: expected ${e.length}, got ${o.data.length}`,"voyage");const s=o.data.slice().sort((i,a)=>i.index-a.index);for(let i=0;i<s.length;i++)if(s[i].index!==i)throw new yt(`Voyage embeddings response has unexpected index ordering: position ${i} has index ${s[i].index}`,"voyage");return s.map(i=>i.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:C$(),baseURL:this.baseURL}}}}}),R5t={};he(R5t,{JinaProvider:()=>D5t});var M5t,gx,P5t,k$,D5t,K7r=S({async"src/lib/providers/jina.ts"(){"use strict";vc(),await dd(),no(),vt(),q(),Zo(),M5t="https://api.jina.ai/v1",gx=6e4,P5t=()=>Bi(Ucr()),k$=()=>zi("JINA_MODEL","jina-embeddings-v3"),D5t=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"jina",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:P5t(),this.baseURL=n?.baseURL??process.env.JINA_BASE_URL??M5t,this.proxyFetch=Bt(),f.debug("Jina Provider initialized (embeddings + reranking)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return k$()}supportsTools(){return!1}getDefaultEmbeddingModel(){return k$()}getAISDKModel(){throw new Error("Jina AI is an embeddings + reranking provider; chat completions are not available. Use `embed()` / `embedMany()` / `rerank()`.")}async executeStream(e,t){throw new Error("Jina AI is an embeddings + reranking provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new or("Invalid Jina AI API key. Get one at https://jina.ai/?sui=apikey","jina"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Jina AI rate limit exceeded. Back off and retry.","jina"):t.includes("404")||t.toLowerCase().includes("model_not_found")?new co(`Jina AI model '${this.modelName}' not found. See https://jina.ai/embeddings/`,"jina"):new yt(`Jina AI error: ${t}`,"jina")}async embed(e,t){const r=await this.callEmbeddings([e],t);if(!r[0])throw new Error("Jina AI returned no embedding for the provided text");return r[0]}async embedMany(e,t){return e.length===0?[]:this.callEmbeddings(e,t)}async rerank(e,t,r={}){if(t.length===0)return[];const n=r.model??"jina-reranker-v2-base-multilingual",o=r.credentials,s=o?.apiKey?.trim()||this.apiKey,i=o?.baseURL||this.baseURL,a=new AbortController,l=setTimeout(()=>a.abort(),gx);let c;try{c=await this.proxyFetch(`${i}/rerank`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify({model:n,query:e,documents:t,top_n:r.topN??t.length}),signal:a.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina rerank request timed out after ${gx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(l)}if(!c.ok){const d=await c.text();throw this.formatProviderError(new Error(`Jina rerank failed: ${c.status} \u2014 ${d}`))}return((await c.json()).results??[]).map(d=>({index:d.index,score:d.relevance_score,document:t[d.index]??d.document?.text??""}))}async callEmbeddings(e,t,r){const n=t??this.modelName,o=r?.apiKey?.trim()||this.apiKey,s=r?.baseURL||this.baseURL,i=new AbortController,a=setTimeout(()=>i.abort(),gx);let l;try{l=await this.proxyFetch(`${s}/embeddings`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:n}),signal:i.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?this.formatProviderError(new Error(`Jina embeddings request timed out after ${gx/1e3}s`)):this.formatProviderError(d)}finally{clearTimeout(a)}if(!l.ok){const d=await l.text();throw this.formatProviderError(new Error(`Jina embeddings failed: ${l.status} \u2014 ${d}`))}const c=await l.json();if(!c.data||c.data.length===0)throw new Error("Jina embeddings response missing data");if(c.data.length!==e.length)throw new Error(`Jina embeddings response count mismatch: expected ${e.length}, got ${c.data.length}`);const u=c.data.slice().sort((d,m)=>d.index-m.index);for(let d=0;d<u.length;d++)if(u[d].index!==d)throw new Error(`Jina embeddings response has unexpected index ordering: position ${d} has index ${u[d].index}`);return u.map(d=>d.embedding)}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:k$(),baseURL:this.baseURL}}}}}),O5t={};he(O5t,{StabilityProvider:()=>Joe,default:()=>$5t});var N5t,Woe,L5t,Koe,Joe,$5t,J7r=S({async"src/lib/providers/stability.ts"(){"use strict";vc(),await dd(),no(),vt(),q(),Zo(),N5t="https://api.stability.ai",Woe=12e4,L5t=()=>(process.env.STABILITY_API_KEY??process.env.STABILITY_AI_API_KEY??"").trim()||void 0,Koe=()=>zi("STABILITY_MODEL","stable-image-ultra"),Joe=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"stability",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:L5t(),this.baseURL=n?.baseURL??process.env.STABILITY_BASE_URL??N5t,this.proxyFetch=Bt(),f.debug("Stability AI Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Koe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Stability AI is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Stability AI is an image-generation-only provider; streaming chat is not available. Use generate({output:{format:'binary'}}) with a Stable Image / SD 3.5 model.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new or("Invalid Stability AI API key. Get one at https://platform.stability.ai/account/keys","stability"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Stability AI rate limit exceeded. Back off and retry.","stability"):t.includes("content_filtered")||t.includes("CONTENT_FILTERED")?new yt("Stability AI declined the request due to content policy. Adjust the prompt and retry.","stability"):t.includes("404")?new co(`Stability AI model '${this.modelName}' not found. Use stable-image-ultra, stable-image-core, sd3.5-large, sd3.5-large-turbo, or sd3.5-medium.`,"stability"):new yt(`Stability AI error: ${t}`,"stability")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.stability,n=r?.apiKey?.trim()||this.apiKey;if(!n)throw new Error("Stability AI API key is required. Set STABILITY_API_KEY or pass credentials.stability.apiKey per-call.");const o=n,s=r?.baseURL||this.baseURL,i=e.prompt??e.input?.text??"";if(!i.trim())throw new Error("Stability AI image generation requires a prompt (input.text or prompt)");const a=this.modelName.startsWith("sd3.5-")?"sd3":this.modelName==="stable-image-ultra"?"ultra":this.modelName==="stable-image-core"?"core":this.modelName,l=e,c=new FormData;c.append("prompt",i),c.append("output_format","png"),l.aspectRatio&&c.append("aspect_ratio",String(l.aspectRatio)),l.negativePrompt&&c.append("negative_prompt",l.negativePrompt),this.modelName.startsWith("sd3.5-")&&c.append("model",this.modelName),l.seed!==void 0&&c.append("seed",String(l.seed));const u=new AbortController,d=setTimeout(()=>u.abort(),Woe);let m;try{m=await this.proxyFetch(`${s}/v2beta/stable-image/generate/${a}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},body:c,signal:u.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Stability image-gen request timed out after ${Woe/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(d)}if(!m.ok){const y=await m.text();throw this.formatProviderError(new Error(`Stability image-gen failed: ${m.status} \u2014 ${y}`))}const h=await m.json();if(!h.image)throw new Error(`Stability AI returned no image (finish_reason: ${h.finish_reason??"unknown"})`);const g=Date.now()-t;return f.info(`[StabilityProvider] Generated image (${h.image.length} base64 chars) in ${g}ms \u2014 model ${this.modelName}`),{content:i,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h.image}}}async validateConfiguration(){return this.apiKey!==void 0&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Koe(),baseURL:this.baseURL}}},$5t=Joe}}),F5t={};he(F5t,{IdeogramProvider:()=>Xoe,default:()=>z5t});var U5t,Yoe,B5t,Zoe,Xoe,z5t,Y7r=S({async"src/lib/providers/ideogram.ts"(){"use strict";vc(),await dd(),no(),vt(),q(),Zo(),U5t="https://api.ideogram.ai",Yoe=12e4,B5t=()=>Bi(Bcr()),Zoe=()=>zi("IDEOGRAM_MODEL","V_3"),Xoe=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"ideogram",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:B5t(),this.baseURL=n?.baseURL??process.env.IDEOGRAM_BASE_URL??U5t,this.proxyFetch=Bt(),f.debug("Ideogram Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return Zoe()}supportsTools(){return!1}getAISDKModel(){throw new Error("Ideogram is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Ideogram is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new or("Invalid Ideogram API key. Get one at https://developer.ideogram.ai/","ideogram"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Ideogram rate limit exceeded. Back off and retry.","ideogram"):t.includes("safety")||t.includes("is_image_safe")?new yt("Ideogram declined the request due to safety filters. Adjust the prompt and retry.","ideogram"):new yt(`Ideogram error: ${t}`,"ideogram")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.ideogram,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Ideogram image generation requires a prompt (input.text or prompt)");const i=e,a={prompt:s,model:this.modelName,magic_prompt:i.magicPrompt??"AUTO"};i.aspectRatio&&(a.aspect_ratio=i.aspectRatio),i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.seed!==void 0&&(a.seed=i.seed),i.style&&(a.style_type=i.style);const l=new AbortController,c=setTimeout(()=>l.abort(),Yoe);let u;try{u=await this.proxyFetch(`${o}/v1/ideogram-v3/generate`,{method:"POST",headers:{"Api-Key":n,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?this.formatProviderError(new Error(`Ideogram image-gen request timed out after ${Yoe/1e3}s`)):this.formatProviderError(T)}finally{clearTimeout(c)}if(!u.ok){const T=await u.text();throw this.formatProviderError(new Error(`Ideogram image-gen failed: ${u.status} \u2014 ${T}`))}const m=(await u.json()).data?.[0]?.url;if(!m)throw new Error("Ideogram returned no image URL");const h=new AbortController,g=setTimeout(()=>h.abort(),6e4);let y;try{y=await this.proxyFetch(m,{signal:h.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error("Ideogram image download timed out after 60s",{cause:T}):T}finally{clearTimeout(g)}if(!y.ok)throw new Error(`Failed to download Ideogram image: ${y.status}`);const v=Buffer.from(await y.arrayBuffer()),_=v.toString("base64"),b=Date.now()-t;return f.info(`[IdeogramProvider] Generated image (${v.length} bytes) in ${b}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:_}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:Zoe(),baseURL:this.baseURL}}},z5t=Xoe}}),j5t={};he(j5t,{ReplicateProvider:()=>q5t});function Z7r(e){const t=e,r=t.prompt??t.input?.text??"",n=t.systemPrompt;return n?`${n}
|
|
2162
2162
|
|
|
2163
2163
|
${r}`:r}function X7r(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>typeof t=="string"?t:"").join(""):""}function Qoe(e){const t=e?.apiKey?.trim()||e?.apiToken?.trim(),r=e?.baseURL||e?.baseUrl;return{apiToken:t,baseUrl:r}}var ese,q5t,Q7r=S({async"src/lib/providers/replicate.ts"(){"use strict";vc(),rP(),s$(),c$(),Rl(),await dd(),q(),ct(),Zo(),ese=()=>zi("REPLICATE_MODEL","meta/meta-llama-3-70b-instruct"),q5t=class extends Il{apiToken;baseURL;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"replicate",o);const{apiToken:s,baseUrl:i}=Qoe(n);this.apiToken=s&&s.length>0?s:Bi(Ocr()),this.baseURL=i,f.debug("Replicate Provider initialized",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return ese()}supportsTools(){return!1}getAISDKModel(){throw new Error("Replicate routes through the predictions API, not the AI SDK chat models. Streaming uses the predict-then-stream path inside executeStream.")}async generate(e,t){const r=typeof e=="string"?{prompt:e}:e,n=e0(r,this.modelName);if(n==="video"||n==="avatar"||n==="music"||n==="image")return super.generate(r,t);if(r.output?.format==="json"||r.output?.format==="structured"||t!=null)throw new Ne({code:Xe.PROVIDER_NOT_AVAILABLE,message:"Replicate models do not support structured-output / JSON schema. Remove output.format or _analysisSchema, or use a provider that implements the OpenAI chat-completions contract (e.g. openai, anthropic).",category:"validation",severity:"medium",retriable:!1});const o=r.prompt??r.input?.text??"",s=Date.now(),i=await this.executeStream({input:{text:o},systemPrompt:r.systemPrompt,maxTokens:r.maxTokens,temperature:r.temperature,abortSignal:r.abortSignal,timeout:r.timeout});let a="";for await(const c of i.stream)"content"in c&&typeof c.content=="string"&&(a+=c.content);const l={content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0}};return f.info(`[ReplicateProvider] generate() complete in ${Date.now()-s}ms \u2014 ${a.length} chars`),l}async executeStream(e,t){const r=Date.now(),n=e.credentials?.replicate,o=Qoe(n),s=o.apiToken||this.apiToken,i=o.baseUrl||this.baseURL,a=gh({apiToken:s,baseUrl:i});if(!a)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const l=Z7r(e);if(!l.trim())throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Replicate predictions require a prompt (input.text or prompt)",category:"validation",severity:"medium",retriable:!1});const c={prompt:l,...e.maxTokens!==void 0&&{max_new_tokens:e.maxTokens},temperature:e.temperature,top_p:1};let u;try{u=await px(a,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(h){throw this.handleProviderError(h)}const d=X7r(u.output);if(!d)throw new Error(`Replicate prediction ${u.id} returned empty output`);const m={async*[Symbol.asyncIterator](){yield{content:d}}};return f.info(`[ReplicateProvider] Generated ${d.length} chars in ${Date.now()-r}ms \u2014 model ${this.modelName} (prediction ${u.id})`),{stream:m,provider:this.providerName,model:this.modelName,finishReason:"stop",metadata:{startTime:r,streamId:`replicate-${u.id}`}}}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.replicate,n=Qoe(r),o=n.apiToken||this.apiToken,s=n.baseUrl||this.baseURL,i=gh({apiToken:o,baseUrl:s});if(!i)throw new Ne({code:Xe.MISSING_CONFIGURATION,message:"Replicate auth could not be resolved (REPLICATE_API_TOKEN missing).",category:"configuration",severity:"high",retriable:!1});const a=e.prompt??e.input?.text??"";if(!a.trim())throw new Ne({code:Xe.INVALID_PARAMETERS,message:"Replicate image-gen requires a prompt",category:"validation",severity:"medium",retriable:!1});const l=e,c={prompt:a,output_format:"png"};l.aspectRatio&&(c.aspect_ratio=l.aspectRatio),l.negativePrompt&&(c.negative_prompt=l.negativePrompt),l.seed!==void 0&&(c.seed=l.seed);let u;try{u=await px(i,{model:this.modelName,input:c},{abortSignal:e.abortSignal})}catch(h){throw this.handleProviderError(h)}let d;try{d=await l$(u,cg)}catch(h){throw this.handleProviderError(h)}const m=d.toString("base64");return f.info(`[ReplicateProvider] Generated image (${d.length} bytes) in ${Date.now()-t}ms \u2014 model ${this.modelName}`),{content:a,provider:this.providerName,model:this.modelName,usage:{input:0,output:0,total:0},imageOutput:{base64:m}}}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error",r=e instanceof Error?e:void 0;return t.includes("401")||t.toLowerCase().includes("unauthorized")||t.toLowerCase().includes("invalid token")?new Ne({code:Xe.PROVIDER_AUTH_FAILED,message:"Invalid Replicate API token. Get one at https://replicate.com/account/api-tokens",category:"configuration",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:r}):t.includes("402")||t.toLowerCase().includes("insufficient credit")?new Ne({code:Xe.PROVIDER_QUOTA_EXCEEDED,message:"Replicate insufficient credit. Top up at https://replicate.com/account/billing \u2014 most image/music models require a paid balance.",category:"resource",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:r}):t.includes("429")||t.toLowerCase().includes("rate limit")?new Ne({code:Xe.PROVIDER_QUOTA_EXCEEDED,message:"Replicate rate limit exceeded. Back off and retry.",category:"resource",severity:"high",retriable:!0,context:{provider:"replicate"},originalError:r}):t.toLowerCase().includes("not found")||t.includes("404")?new Ne({code:Xe.PROVIDER_NOT_AVAILABLE,message:`Replicate model '${this.modelName}' not found. Use owner/name or owner/name:version format. Browse https://replicate.com/explore`,category:"validation",severity:"medium",retriable:!1,context:{provider:"replicate",model:this.modelName},originalError:r}):new Ne({code:Xe.PROVIDER_NOT_AVAILABLE,message:`Replicate error: ${t}`,category:"execution",severity:"high",retriable:!1,context:{provider:"replicate"},originalError:r})}async validateConfiguration(){return typeof this.apiToken=="string"&&this.apiToken.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:ese(),baseURL:this.baseURL}}}}}),G5t={};he(G5t,{RecraftProvider:()=>nse,default:()=>W5t});var H5t,tse,V5t,rse,nse,W5t,eVr=S({async"src/lib/providers/recraft.ts"(){"use strict";vc(),await dd(),no(),vt(),q(),Zo(),Rl(),dg(),H5t="https://external.api.recraft.ai/v1",tse=12e4,V5t=()=>Bi(zcr()),rse=()=>zi("RECRAFT_MODEL","recraftv3"),nse=class extends Il{apiKey;baseURL;proxyFetch;constructor(e,t,r,n){const o=sy(t)?t:void 0;super(e,"recraft",o);const s=n?.apiKey?.trim();this.apiKey=s&&s.length>0?s:V5t(),this.baseURL=n?.baseURL??process.env.RECRAFT_BASE_URL??H5t,this.proxyFetch=Bt(),f.debug("Recraft Provider initialized (image-gen only)",{modelName:this.modelName,baseURL:this.baseURL})}getProviderName(){return this.providerName}getDefaultModel(){return rse()}supportsTools(){return!1}getAISDKModel(){throw new Error("Recraft is an image-generation-only provider; chat completions are not available.")}async executeStream(e,t){throw new Error("Recraft is an image-generation-only provider; streaming chat is not available.")}formatProviderError(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";return t.includes("401")||t.toLowerCase().includes("unauthorized")?new or("Invalid Recraft API key. Get one at https://www.recraft.ai/api","recraft"):t.includes("429")||t.toLowerCase().includes("rate limit")?new Xs("Recraft rate limit exceeded. Back off and retry.","recraft"):t.includes("404")||t.includes("model_not_found")?new co(`Recraft model '${this.modelName}' not found. Use recraftv3, recraftv3-svg, or recraftv2.`,"recraft"):new yt(`Recraft error: ${t}`,"recraft")}async executeImageGeneration(e){const t=Date.now(),r=e.credentials?.recraft,n=r?.apiKey?.trim()||this.apiKey,o=r?.baseURL||this.baseURL,s=e.prompt??e.input?.text??"";if(!s.trim())throw new Error("Recraft image generation requires a prompt (input.text or prompt)");const i=e,a={model:e.model??this.modelName,prompt:s,n:1,response_format:"b64_json"};i.negativePrompt&&(a.negative_prompt=i.negativePrompt),i.style&&(a.style=i.style),i.styleId&&(a.style_id=i.styleId),i.size&&(a.size=i.size);const l=new AbortController,c=setTimeout(()=>l.abort(),tse);let u;try{u=await this.proxyFetch(`${o}/images/generations`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify(a),signal:l.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?this.formatProviderError(new Error(`Recraft image-gen request timed out after ${tse/1e3}s`)):this.formatProviderError(y)}finally{clearTimeout(c)}if(!u.ok){const y=await u.text();throw this.formatProviderError(new Error(`Recraft image-gen failed: ${u.status} \u2014 ${y}`))}const m=(await u.json()).data?.[0];if(!m)throw new Error("Recraft returned no image data");let h;if(m.b64_json)h=m.b64_json;else if(m.url){await ug(m.url);const y=new AbortController,v=setTimeout(()=>y.abort(),6e4);let _;try{_=await this.proxyFetch(m.url,{signal:y.signal})}catch(T){throw T instanceof Error&&T.name==="AbortError"?new Error("Recraft image download timed out after 60s",{cause:T}):T}finally{clearTimeout(v)}if(!_.ok)throw new Error(`Failed to download Recraft image: ${_.status}`);h=(await ip(_,cg,"Recraft image")).toString("base64")}else throw new Error("Recraft response missing both b64_json and url");const g=Date.now()-t;return f.info(`[RecraftProvider] Generated image (${h.length} base64 chars) in ${g}ms \u2014 model ${this.modelName}`),{content:s,provider:this.providerName,model:this.modelName,usage:{input:0,output:1e3,total:1e3},imageOutput:{base64:h}}}async validateConfiguration(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0}getConfiguration(){return{provider:this.providerName,model:this.modelName,defaultModel:rse(),baseURL:this.baseURL}}},W5t=nse}}),K5t={};he(K5t,{Agent:()=>$Bt,BedrockClient:()=>Y5t,BedrockRuntimeClient:()=>X5t,Blob:()=>LBt,Client:()=>UBt,ConverseCommand:()=>Q5t,ConverseStreamCommand:()=>eBt,Cron:()=>vBt,Dispatcher:()=>BBt,File:()=>NBt,FlowProducer:()=>yBt,FormData:()=>OBt,GoogleAuth:()=>iBt,HTTPException:()=>CBt,Headers:()=>DBt,Hippocampus:()=>uBt,HippocampusConfig:()=>dBt,Hono:()=>EBt,ImageFormat:()=>tBt,InvokeEndpointCommand:()=>oBt,InvokeEndpointWithResponseStreamCommand:()=>sBt,InvokeModelCommand:()=>rBt,Job:()=>fBt,ListFoundationModelsCommand:()=>Z5t,MockAgent:()=>qBt,Pool:()=>FBt,Queue:()=>mBt,QueueScheduler:()=>gBt,Request:()=>MBt,Response:()=>PBt,SageMakerRuntimeClient:()=>nBt,TextToSpeechClient:()=>lBt,VertexAI:()=>aBt,Webhook:()=>cBt,Worker:()=>hBt,convertToHtml:()=>TBt,cors:()=>SBt,createClient:()=>pBt,default:()=>J5t,extractRawText:()=>bBt,fetch:()=>RBt,getGlobalDispatcher:()=>jBt,interceptors:()=>GBt,logger:()=>kBt,parseBuffer:()=>_Bt,request:()=>HBt,secureHeaders:()=>xBt,selectCover:()=>wBt,setGlobalDispatcher:()=>zBt,streamSSE:()=>ABt,timeout:()=>IBt});var iy,xs,J5t,Y5t,Z5t,X5t,Q5t,eBt,tBt,rBt,nBt,oBt,sBt,iBt,aBt,lBt,cBt,uBt,dBt,pBt,mBt,hBt,fBt,gBt,yBt,vBt,_Bt,wBt,bBt,TBt,EBt,SBt,CBt,kBt,xBt,ABt,IBt,RBt,MBt,PBt,DBt,OBt,NBt,LBt,$Bt,FBt,UBt,BBt,zBt,jBt,qBt,GBt,HBt,tVr=S({"npm-stub:@google-cloud/text-to-speech"(){iy={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:iy.get}):new Proxy(function(...r){return new Proxy({},{get:iy.get})},{get:iy.get,apply(r,n,o){return new Proxy({},{get:iy.get})},construct(r,n){return new Proxy({},{get:iy.get})}})}},xs=new Proxy({},iy),J5t=xs,{BedrockClient:Y5t,ListFoundationModelsCommand:Z5t,BedrockRuntimeClient:X5t,ConverseCommand:Q5t,ConverseStreamCommand:eBt,ImageFormat:tBt,InvokeModelCommand:rBt}=xs,{SageMakerRuntimeClient:nBt,InvokeEndpointCommand:oBt,InvokeEndpointWithResponseStreamCommand:sBt}=xs,{GoogleAuth:iBt,VertexAI:aBt,TextToSpeechClient:lBt}=xs,{Webhook:cBt}=xs,{Hippocampus:uBt,HippocampusConfig:dBt}=xs,{createClient:pBt}=xs,{Queue:mBt,Worker:hBt,Job:fBt,QueueScheduler:gBt,FlowProducer:yBt}=xs,{Cron:vBt}=xs,{parseBuffer:_Bt,selectCover:wBt}=xs,{extractRawText:bBt,convertToHtml:TBt}=xs,{Hono:EBt}=xs,{cors:SBt,HTTPException:CBt,logger:kBt,secureHeaders:xBt,streamSSE:ABt,timeout:IBt}=xs,RBt=globalThis.fetch,MBt=globalThis.Request,PBt=globalThis.Response,DBt=globalThis.Headers,OBt=globalThis.FormData,NBt=globalThis.File,LBt=globalThis.Blob,$Bt=xs.Agent,FBt=xs.Pool,UBt=xs.Client,BBt=xs.Dispatcher,zBt=()=>{},jBt=()=>xs,qBt=xs.MockAgent,GBt={redirect:()=>e=>e,retry:()=>e=>e},HBt=async(e,t)=>{const r=await globalThis.fetch(e,t);return{statusCode:r.status,headers:Object.fromEntries(r.headers.entries()),body:{text:()=>r.text(),json:()=>r.json(),arrayBuffer:()=>r.arrayBuffer()}}}}}),x$,VBt=S({"src/lib/adapters/tts/googleTTSHandler.ts"(){"use strict";dc(),q(),Qn(),x$=class gF{client=null;voicesCache=null;static CACHE_TTL_MS=300*1e3;static DEFAULT_MAX_TEXT_LENGTH=5e3;static DEFAULT_API_TIMEOUT_MS=30*1e3;maxTextLength=gF.DEFAULT_MAX_TEXT_LENGTH;credentialsPath;constructor(t){this.credentialsPath=t??process.env.GOOGLE_APPLICATION_CREDENTIALS}isConfigured(){return this.credentialsPath!==void 0}async getClient(){if(!this.client){const{TextToSpeechClient:t}=await Promise.resolve().then(()=>(tVr(),K5t));this.client=new t({keyFilename:this.credentialsPath})}return this.client}async getVoices(t){if(!this.isConfigured())throw new Ut({code:Gt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});const r=await this.getClient(),n=Oe.createSpan("tts","tts.google.listVoices",{"tts.operation":"listVoices","tts.provider":"google"});try{if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<gF.CACHE_TTL_MS&&!t){const a=Oe.endSpan(n,1);return dt().recordSpan(a),this.voicesCache.voices}const[o]=await r.listVoices(t?{languageCode:t}:{});if(!o.voices||o.voices.length===0){f.warn("Google Cloud TTS returned no voices");const a=Oe.endSpan(n,1);return dt().recordSpan(a),[]}const s=[];for(const a of o.voices??[]){if(!a.name||!Array.isArray(a.languageCodes)||a.languageCodes.length===0){f.warn("Skipping voice with missing required fields",{name:a.name,languageCodesCount:a.languageCodes?.length});continue}const l=a.name,c=a.languageCodes,u=c[0],d=this.detectVoiceType(l),m=a.ssmlGender==="MALE"?"male":a.ssmlGender==="FEMALE"?"female":"neutral";s.push({id:l,name:l,languageCode:u,languageCodes:c,gender:m,type:d,naturalSampleRateHertz:a.naturalSampleRateHertz??void 0})}t||(this.voicesCache={voices:s,timestamp:Date.now()});const i=Oe.endSpan(n,1);return dt().recordSpan(i),s}catch(o){const s=Oe.endSpan(n,2,o instanceof Error?o.message:"Unknown error");dt().recordSpan(s);const i=o instanceof Error?o.message:"Unknown error";return f.error(`Failed to fetch Google TTS voices: ${i}`),[]}}async synthesize(t,r){if(!this.isConfigured())throw new Ut({code:Gt.PROVIDER_NOT_CONFIGURED,message:"Google Cloud TTS client not initialized. Set GOOGLE_APPLICATION_CREDENTIALS or pass credentials path.",category:"configuration",severity:"high",retriable:!1});const n=await this.getClient(),o=r.voice??"en-US-Neural2-C",s=Oe.createSpan("tts","tts.google.synthesize",{"tts.operation":"synthesize","tts.provider":"google","tts.voice":o,"tts.format":r.format??"mp3"}),i=Date.now();try{const a=t.startsWith("<speak>")&&t.endsWith("</speak>");if(t.startsWith("<speak>")&&!t.endsWith("</speak>")||!t.startsWith("<speak>")&&t.endsWith("</speak>"))throw new Ut({code:Gt.INVALID_INPUT,message:"Malformed SSML: missing opening <speak> or closing </speak> tag.",category:"validation",severity:"medium",retriable:!1});const l=this.extractLanguageCode(o),c=this.mapFormat(r.format??"mp3"),u={input:a?{ssml:t}:{text:t},voice:{name:o,languageCode:l},audioConfig:{audioEncoding:c,speakingRate:r.speed??1,pitch:r.pitch??0,volumeGainDb:r.volumeGainDb??0}},[d]=await n.synthesizeSpeech(u,{timeout:gF.DEFAULT_API_TIMEOUT_MS}),m=d.audioContent;if(!m)throw new Ut({code:Gt.SYNTHESIS_FAILED,message:"Google TTS returned empty audio content",category:"execution",severity:"high",retriable:!0});const h=m instanceof Uint8Array?Buffer.from(m):typeof m=="string"?Buffer.from(m,"base64"):(()=>{throw new Ut({code:Gt.SYNTHESIS_FAILED,message:"Unsupported audioContent type returned by Google TTS",category:"execution",severity:"high",retriable:!0,context:{type:typeof m}})})(),g=Date.now()-i,y=Oe.endSpan(s,1);return dt().recordSpan(y),{buffer:h,format:r.format??"mp3",size:h.length,voice:o,metadata:{latency:g,provider:"google-ai"}}}catch(a){const l=Oe.endSpan(s,2,a instanceof Error?a.message:String(a));if(dt().recordSpan(l),a instanceof Ut)throw a;const c=Date.now()-i,u=a instanceof Error?a.message:"Unknown error";throw new Ut({code:Gt.SYNTHESIS_FAILED,message:`Google TTS failed after ${c}ms: ${u}`,category:"execution",severity:"high",retriable:!0,context:{latency:c},originalError:a instanceof Error?a:void 0})}}extractLanguageCode(t){const r=t.split("-");if(r.length>=2)return`${r[0]}-${r[1]}`;throw new Ut({code:Gt.INVALID_INPUT,message:`Invalid Google TTS voiceId format: "${t}". Expected format like "en-US-Neural2-C".`,category:"validation",severity:"medium",retriable:!1,context:{voiceId:t}})}mapFormat(t){switch(t.toLowerCase()){case"mp3":return"MP3";case"wav":return"LINEAR16";case"ogg":case"opus":return"OGG_OPUS";default:throw new Ut({code:Gt.INVALID_INPUT,message:`Unsupported audio format: ${t}`,category:"validation",severity:"medium",retriable:!1,context:{format:t}})}}detectVoiceType(t){const r=t.toLowerCase().split("-");return r.some(n=>n.startsWith("chirp"))?"chirp":r.includes("neural2")?"neural":r.includes("wavenet")?"wavenet":r.includes("standard")?"standard":"unknown"}}}}),lw,yx,A$=S({"src/lib/voice/RealtimeVoiceAPI.ts"(){"use strict";q(),Sp(),vt(),n0(),lw=class{static registry=new If("RealtimeProcessor");static sessions=new Map;static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),f.debug(`[RealtimeProcessor] Registered Realtime handler for provider: ${r}`)}static getHandler(e){return this.registry.get(e)}static supports(e){return this.registry.supports(e)}static getProviders(){return this.registry.list()}static async connect(e,t,r){const n=this.getHandler(e);if(!n)throw sr.providerNotSupported(e,this.registry.list());if(!n.isConfigured())throw sr.providerNotConfigured(e);if(n.isConnected())throw sr.sessionAlreadyActive(e);const o={...n1,...t};r&&n.on(r);try{f.debug(`[RealtimeProcessor] Connecting to provider: ${e}`);const s=await n.connect(o);return this.sessions.set(e.toLowerCase(),s),f.info(`[RealtimeProcessor] Connected to ${e} session: ${s.id}`),s}catch(s){if(r&&n.off(),s instanceof sr)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw sr.connectionFailed(i,e,s instanceof Error?s:void 0)}}static async disconnect(e){const t=this.getHandler(e);if(!t)throw sr.providerNotSupported(e,this.registry.list());if(!t.isConnected()){f.warn(`[RealtimeProcessor] No active session for provider: ${e}`);return}try{await t.disconnect(),this.sessions.delete(e.toLowerCase()),t.off(),f.info(`[RealtimeProcessor] Disconnected from ${e}`)}catch(r){if(r instanceof sr)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw sr.protocolError(`Disconnect failed: ${n}`,e,r instanceof Error?r:void 0)}}static async sendAudio(e,t){const r=this.getHandler(e);if(!r)throw sr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw sr.sessionNotActive(e);try{await r.sendAudio(t)}catch(n){if(n instanceof sr)throw n;const o=n instanceof Error?n.message:String(n||"Unknown error");throw sr.audioStreamError(o,e)}}static async sendText(e,t){const r=this.getHandler(e);if(!r)throw sr.providerNotSupported(e,this.registry.list());if(!r.isConnected())throw sr.sessionNotActive(e);if(!r.sendText)throw new sr({code:Qs.PROTOCOL_ERROR,message:`Provider "${e}" does not support text input`,category:"validation",severity:"medium",context:{provider:e}});try{await r.sendText(t)}catch(n){throw n instanceof sr?n:new sr({code:Qs.PROTOCOL_ERROR,message:`sendText failed: ${n instanceof Error?n.message:String(n)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:n instanceof Error?n:void 0})}}static async triggerResponse(e){const t=this.getHandler(e);if(!t)throw sr.providerNotSupported(e,this.registry.list());if(!t.isConnected())throw sr.sessionNotActive(e);if(t.triggerResponse)try{await t.triggerResponse()}catch(r){throw r instanceof sr?r:new sr({code:Qs.PROTOCOL_ERROR,message:`triggerResponse failed: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:r instanceof Error?r:void 0})}}static async cancelResponse(e){const t=this.getHandler(e);if(!t)throw sr.providerNotSupported(e,this.registry.list());if(t.isConnected()&&t.cancelResponse)try{await t.cancelResponse()}catch(r){throw r instanceof sr?r:new sr({code:Qs.PROTOCOL_ERROR,message:`cancelResponse failed: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"medium",retriable:!0,context:{provider:e},originalError:r instanceof Error?r:void 0})}}static getSession(e){return this.getHandler(e)?.getSession()??null}static isConnected(e){return this.getHandler(e)?.isConnected()??!1}static getSupportedFormats(e){return this.getHandler(e)?.getSupportedFormats()??[]}static clearHandlers(){for(const[e]of this.sessions){const t=this.registry.get(e);t?.isConnected()&&t.disconnect().catch(()=>{})}this.sessions.clear(),this.registry.clear(),f.debug("[RealtimeProcessor] Cleared all handlers and sessions")}},yx=class{session=null;eventHandlers=null;state="disconnected";isConnected(){return this.state==="connected"}getSession(){return this.session}on(e){this.eventHandlers=e}off(){this.eventHandlers=null}emitStateChange(e){this.state=e,this.session&&(this.session.state=e,this.session.lastActivityAt=new Date),this.eventHandlers?.onStateChange?.(e)}emitAudio(e){this.eventHandlers?.onAudio?.(e)}emitTranscript(e,t){this.eventHandlers?.onTranscript?.(e,t)}emitText(e,t){this.eventHandlers?.onText?.(e,t)}async emitFunctionCall(e,t){if(this.eventHandlers?.onFunctionCall)return this.eventHandlers.onFunctionCall(e,t)}emitError(e){this.eventHandlers?.onError?.(e)}emitTurnStart(){this.eventHandlers?.onTurnStart?.()}emitTurnEnd(){this.eventHandlers?.onTurnEnd?.()}createSession(e,t){return{id:e,state:"connected",provider:this.name,model:t.model,createdAt:new Date,lastActivityAt:new Date,config:t}}}}});function WBt(e){if(e.length<12)return null;if(e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===65&&e[10]===86&&e[11]===69)return"wav";if(e[0]===73&&e[1]===68&&e[2]===51||e[0]===255&&(e[1]&224)===224)return"mp3";if(e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83){const t=e.indexOf("OpusHead");return t!==-1&&t<200?"opus":"ogg"}return null}function rVr(e){return wT[e]?.mimeType??"application/octet-stream"}function nVr(e){return wT[e]?.extension??".bin"}function oVr(e,t,r){const n=t??WBt(e);if(n)try{switch(n){case"wav":return sVr(e);case"mp3":return iVr(e);case"ogg":case"opus":return aVr(e);default:return r?e.length/(r*2):void 0}}catch(o){f.debug(`[audio-utils] Failed to calculate duration: ${o instanceof Error?o.message:String(o)}`);return}}function sVr(e){if(e.length<44)return;let t=12;for(;t<e.length-8;){const r=e.toString("ascii",t,t+4),n=e.readUInt32LE(t+4);if(r==="fmt "){const o=e.readUInt16LE(t+10),s=e.readUInt32LE(t+12),i=e.readUInt16LE(t+22);let a=t+8+n+n%2;for(;a<e.length-8;){const l=e.toString("ascii",a,a+4),c=e.readUInt32LE(a+4);if(l==="data"){const u=i/8*o;return c/u/s}a+=8+c+c%2}}t+=8+n+n%2}}function iVr(e){let t=0;for(e[0]===73&&e[1]===68&&e[2]===51&&(t=10+((e[6]&127)<<21|(e[7]&127)<<14|(e[8]&127)<<7|e[9]&127));t<e.length-4;){if(e[t]===255&&(e[t+1]&224)===224){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,o=e[t+2]>>4&15,s=e[t+2]>>2&3,a={3:[44100,48e3,32e3],2:[22050,24e3,16e3],0:[11025,12e3,8e3]}[r]?.[s],c=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0][o];if(a&&c)return(e.length-t)*8/(c*1e3);break}t++}return e.length*8/128e3}function aVr(e){return e.length*8/64e3}async function lVr(e,t,r,n={}){if(t===r)return e;throw f.warn(`[audio-utils] Audio format conversion from ${t} to ${r} is not implemented.`),new Error(`Audio format conversion from ${t} to ${r} is not implemented. Convert with ffmpeg before passing to NeuroLink.`)}function cVr(e,t=16e3,r=16){const n=r/8,o=Buffer.alloc(e.length*n);for(let s=0;s<e.length;s++){const i=Math.max(-1,Math.min(1,e[s])),a=s*n;switch(r){case 8:o.writeUInt8(Math.round((i+1)*127.5),a);break;case 16:o.writeInt16LE(Math.round(i*32767),a);break;case 24:{const l=Math.round(i*8388607);o.writeUInt8(l&255,a),o.writeUInt8(l>>8&255,a+1),o.writeUInt8(l>>16&255,a+2);break}case 32:o.writeInt32LE(Math.round(i*2147483647),a);break}}return o}function uVr(e,t=16){const r=t/8,n=Math.floor(e.length/r),o=[];for(let s=0;s<n;s++){const i=s*r;switch(t){case 8:o.push(e.readUInt8(i)/127.5-1);break;case 16:o.push(e.readInt16LE(i)/32767);break;case 24:{const a=e.readUInt8(i)|e.readUInt8(i+1)<<8|e.readUInt8(i+2)<<16;o.push((a>8388607?a-16777216:a)/8388607);break}case 32:o.push(e.readInt32LE(i)/2147483647);break}}return o}function dVr(e,t,r){if(t<=0||r<=0||t===r)return e;const n=t/r,o=Math.round(e.length/n),s=[];for(let i=0;i<o;i++){const a=i*n,l=Math.floor(a),c=Math.min(l+1,e.length-1),u=a-l,d=e[l]*(1-u)+e[c]*u;s.push(d)}return s}function pVr(e,t=.95){if(e.length===0)return e;let r=0;for(const o of e)r=Math.max(r,Math.abs(o));if(r===0)return e;const n=t/r;return e.map(o=>o*n)}function KBt(e,t=16e3,r=1,n=16){const o=Buffer.alloc(44),s=t*r*(n/8),i=r*(n/8);return o.write("RIFF",0),o.writeUInt32LE(36+e,4),o.write("WAVE",8),o.write("fmt ",12),o.writeUInt32LE(16,16),o.writeUInt16LE(1,20),o.writeUInt16LE(r,22),o.writeUInt32LE(t,24),o.writeUInt32LE(s,28),o.writeUInt16LE(i,32),o.writeUInt16LE(n,34),o.write("data",36),o.writeUInt32LE(e,40),o}function mVr(e,t=16e3,r=1,n=16){const o=KBt(e.length,t,r,n);return Buffer.concat([o,e])}function hVr(e,t,r=16e3,n=2){if(t<=0||r<=0||n<=0)return[e];const o=r*n/1e3,s=Math.round(t*o);if(s<=0)return[e];const i=[];for(let a=0;a<e.length;a+=s){const l=Math.min(a+s,e.length);i.push(e.subarray(a,l))}return i}var JBt,YBt,fVr=S({"src/lib/voice/audio-utils.ts"(){"use strict";vt(),q(),JBt={wav:Buffer.from([82,73,70,70]),mp3:{id3:Buffer.from([73,68,51]),frameSync:Buffer.from([255,224])},ogg:Buffer.from([79,103,103,83])},YBt={wav:"audio/wav",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus"}}});function gVr(e){return{[Symbol.asyncIterator](){const t=[];let r=null,n=null,o=!1,s=null;const i=u=>{r?(r({value:u,done:!1}),r=null,n=null):t.push(u)},a=()=>{o=!0,r&&(r({value:void 0,done:!0}),r=null,n=null)},l=u=>{s=u,n&&(n(u),r=null,n=null)};e.on("chunk",i),e.on("end",a),e.on("error",l);const c=()=>{e.off("chunk",i),e.off("end",a),e.off("error",l)};return{async next(){if(s)throw s;if(t.length>0){const u=t.shift();if(u!==void 0)return{value:u,done:!1}}return o?{value:void 0,done:!0}:new Promise((u,d)=>{r=u,n=d})},async return(){return c(),o=!0,{value:void 0,done:!0}}}}}}async function yVr(e,t={}){const r=new cw(t);return(async()=>{try{for await(const n of e)r.write(n)||await new Promise(s=>r.once("drain",s));r.end()}catch(n){r.emit("error",n instanceof Error?n:new Error(String(n)))}})(),r}var ose,cw,ZBt,XBt,vVr=S({"src/lib/voice/stream-handler.ts"(){"use strict";vn(),q(),ose={chunkDurationMs:100,sampleRate:16e3,bytesPerSample:2,format:"wav",highWaterMark:64*1024,bufferTimeoutMs:5e3},cw=class extends nn{config;chunkSize;buffer;chunkIndex;timestampMs;isPaused;isEnded;pendingData;bufferTimeout;constructor(e={}){if(super(),this.config={...ose,...e},this.config.sampleRate<=0)throw new Error("Invalid stream configuration: sampleRate must be positive");if(this.config.bytesPerSample<=0)throw new Error("Invalid stream configuration: bytesPerSample must be positive");const t=this.config.sampleRate*this.config.bytesPerSample/1e3;if(this.chunkSize=Math.round(this.config.chunkDurationMs*t),this.chunkSize<=0)throw new Error("Invalid stream configuration: chunkSize must be positive (check chunkDurationMs, sampleRate, bytesPerSample)");this.buffer=Buffer.alloc(0),this.chunkIndex=0,this.timestampMs=0,this.isPaused=!1,this.isEnded=!1,this.pendingData=[],this.bufferTimeout=null}write(e){if(this.isEnded)throw new Error("Cannot write to ended stream");return this.buffer.length+e.length>this.config.highWaterMark?(this.isPaused||(this.isPaused=!0,this.emit("pause")),this.pendingData.push(e),!1):(this.processData(e),!0)}processData(e){for(this.buffer=Buffer.concat([this.buffer,e]),this.resetBufferTimeout();this.buffer.length>=this.chunkSize;){const t=this.buffer.subarray(0,this.chunkSize);this.buffer=this.buffer.subarray(this.chunkSize);const r={data:t,index:this.chunkIndex++,isFinal:!1,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:this.config.chunkDurationMs};this.timestampMs+=this.config.chunkDurationMs,this.emit("chunk",r)}if(this.isPaused&&this.buffer.length<this.config.highWaterMark/2)for(this.isPaused=!1,this.emit("resume"),this.emit("drain");this.pendingData.length>0&&!this.isPaused;){const t=this.pendingData.shift();if(t===void 0||!this.write(t))break}}end(){if(!this.isEnded){this.isEnded=!0,this.clearBufferTimeout();for(const e of this.pendingData)this.buffer=Buffer.concat([this.buffer,e]);if(this.pendingData=[],this.buffer.length>0){const e=this.buffer.length/this.config.bytesPerSample/this.config.sampleRate*1e3,t={data:this.buffer,index:this.chunkIndex++,isFinal:!0,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:e};this.emit("chunk",t)}else{const e={data:Buffer.alloc(0),index:this.chunkIndex,isFinal:!0,format:this.config.format,sampleRate:this.config.sampleRate,timestampMs:this.timestampMs,durationMs:0};this.emit("chunk",e)}this.emit("end"),this.cleanup()}}resetBufferTimeout(){this.clearBufferTimeout(),this.bufferTimeout=setTimeout(()=>{this.buffer.length>0&&!this.isEnded&&(f.warn(`[ChunkedAudioStream] Buffer timeout, forcing flush of ${this.buffer.length} bytes`),this.end())},this.config.bufferTimeoutMs)}clearBufferTimeout(){this.bufferTimeout&&(clearTimeout(this.bufferTimeout),this.bufferTimeout=null)}cleanup(){this.clearBufferTimeout(),this.buffer=Buffer.alloc(0),this.pendingData=[]}getStats(){return{chunksEmitted:this.chunkIndex,bufferedBytes:this.buffer.length,pendingChunks:this.pendingData.length,totalDurationMs:this.timestampMs,isPaused:this.isPaused,isEnded:this.isEnded}}},ZBt=class extends nn{streams;config;constructor(e={}){super(),this.streams=new Map,this.config={...ose,...e}}addStream(e){if(this.streams.has(e))throw new Error(`Stream ${e} already exists`);const t=new cw(this.config);return t.on("chunk",r=>{this.emit("chunk",{id:e,chunk:r})}),t.on("end",()=>{this.emit("streamEnd",e),this.streams.delete(e),this.streams.size===0&&this.emit("end")}),t.on("error",r=>{this.emit("error",{id:e,error:r})}),this.streams.set(e,t),t}removeStream(e){const t=this.streams.get(e);t&&(t.end(),this.streams.delete(e))}write(e,t){const r=this.streams.get(e);if(!r)throw new Error(`Stream ${e} not found`);return r.write(t)}endAll(){for(const e of this.streams.values())e.end()}get activeStreams(){return this.streams.size}},XBt=class extends nn{consumers;input;constructor(e={}){super(),this.consumers=new Map,this.input=new cw(e),this.input.on("chunk",t=>{for(const[r,n]of this.consumers)try{n(t)}catch(o){this.emit("error",{consumerId:r,error:o instanceof Error?o:new Error(String(o))})}}),this.input.on("end",()=>{this.emit("end")}),this.input.on("error",t=>{this.emit("error",{error:t})})}write(e){return this.input.write(e)}end(){this.input.end()}addConsumer(e,t){if(this.consumers.has(e))throw new Error(`Consumer ${e} already exists`);this.consumers.set(e,t)}removeConsumer(e){this.consumers.delete(e)}get consumerCount(){return this.consumers.size}}}}),uw,QBt=S({"src/lib/voice/providers/AzureTTS.ts"(){"use strict";q(),dc(),uw=class acr{apiKey;region;voicesCache=null;static CACHE_TTL_MS=1800*1e3;maxTextLength=1e4;constructor(t,r){const n=(t??process.env.AZURE_SPEECH_KEY??"").trim();this.apiKey=n.length>0?n:null;const o=(r??process.env.AZURE_SPEECH_REGION??"").trim();this.region=o.length>0?o:"eastus"}isConfigured(){return this.apiKey!==null&&this.region.length>0}async getVoices(t){if(!this.apiKey)throw new Ut({code:Gt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});if(this.voicesCache&&Date.now()-this.voicesCache.timestamp<acr.CACHE_TTL_MS&&!t)return this.voicesCache.voices;try{const r=new AbortController,n=setTimeout(()=>r.abort(),3e4);let o;try{o=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/voices/list`,{method:"GET",headers:{"Ocp-Apim-Subscription-Key":this.apiKey},signal:r.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new Ut({code:Gt.SYNTHESIS_FAILED,message:"Azure TTS voices request timed out after 30 seconds",category:"network",severity:"medium",retriable:!0,originalError:a}):a}finally{clearTimeout(n)}if(!o.ok)throw new Error(`HTTP ${o.status}`);let i=(await o.json()).map(a=>({id:a.ShortName,name:a.DisplayName,languageCode:a.Locale,languageCodes:[a.Locale],gender:this.mapGender(a.Gender),type:a.VoiceType.toLowerCase().includes("neural")?"neural":"standard",description:a.LocaleName}));return t&&(i=i.filter(a=>a.languageCode.toLowerCase().startsWith(t.toLowerCase())||a.languageCode.toLowerCase()===t.toLowerCase())),t||(this.voicesCache={voices:i,timestamp:Date.now()}),i}catch(r){if(r instanceof Ut)throw r;const n=r instanceof Error?r.message:String(r||"Unknown error");throw f.error(`[AzureTTSHandler] Failed to get voices: ${n}`),new Ut({code:Gt.SYNTHESIS_FAILED,message:`Failed to get voices: ${n}`,category:"network",severity:"medium",retriable:!0,originalError:r instanceof Error?r:void 0})}}async synthesize(t,r={}){if(!this.apiKey)throw new Ut({code:Gt.PROVIDER_NOT_CONFIGURED,message:"Azure Speech key not configured",category:"configuration",severity:"high",retriable:!1});const n=Date.now(),o=r;try{const s=r.voice??"en-US-JennyNeural",i=o.outputFormat??this.mapFormat(r.format??"mp3"),a=this.buildSSML(t,s,r),l=new AbortController,c=setTimeout(()=>l.abort(),3e4);let u;try{u=await fetch(`https://${this.region}.tts.speech.microsoft.com/cognitiveservices/v1`,{method:"POST",headers:{"Ocp-Apim-Subscription-Key":this.apiKey,"Content-Type":"application/ssml+xml","X-Microsoft-OutputFormat":i},body:a,signal:l.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new Ut({code:Gt.SYNTHESIS_FAILED,message:"Azure TTS request timed out after 30 seconds",category:"network",severity:"high",retriable:!0,originalError:y}):y}finally{clearTimeout(c)}if(!u.ok){const y=await u.text();throw new Error(`HTTP ${u.status}: ${y}`)}const d=Date.now()-n,m=await u.arrayBuffer(),h=Buffer.from(m),g={buffer:h,format:this.effectiveFormat(i),size:h.length,voice:s,sampleRate:this.getSampleRate(i),metadata:{latency:d,provider:"azure-tts",requestedFormat:r.format,outputFormat:i,region:this.region}};return f.info(`[AzureTTSHandler] Synthesized ${h.length} bytes in ${d}ms`),g}catch(s){if(s instanceof Ut)throw s;const i=s instanceof Error?s.message:String(s||"Unknown error");throw f.error(`[AzureTTSHandler] Synthesis failed: ${i}`),new Ut({code:Gt.SYNTHESIS_FAILED,message:`Synthesis failed: ${i}`,category:"execution",severity:"high",retriable:!0,context:{textLength:t.length},originalError:s instanceof Error?s:void 0})}}buildSSML(t,r,n){const o=n;if(o.ssmlTemplate)return o.ssmlTemplate.replace("{text}",this.escapeXml(t)).replace("{voice}",this.escapeXml(r));if(o.allowRawSSML&&t.trim().startsWith("<speak"))return t;const s=n.speed?`${Math.round((n.speed-1)*100)}%`:"0%",i=n.pitch??0,a=i>=0?`+${Math.round(i)}st`:`${Math.round(i)}st`;return`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="${this.escapeXml(this.extractLanguage(r))}">
|
|
2164
2164
|
<voice name="${this.escapeXml(r)}">
|