@juspay/neurolink 12.14.3 → 12.14.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,8 +1,8 @@
1
- ## [12.14.3](https://github.com/juspay/neurolink/compare/v12.14.2...v12.14.3) (2026-09-12)
1
+ ## [12.14.4](https://github.com/juspay/neurolink/compare/v12.14.3...v12.14.4) (2026-09-13)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(openai):** stop rejecting schemas that carry an optional field ([1dc7040](https://github.com/juspay/neurolink/commit/1dc704049e6c86f769cea5cd8a90d7e87965a7cc))
5
+ - **(mcp):** return isolated copies from the tool result cache so callers cannot mutate later hits ([f17c05f](https://github.com/juspay/neurolink/commit/f17c05fbe90c27e6c19d319a6fff70ed6683ff7d)), closes [#1618](https://github.com/juspay/neurolink/issues/1618)
6
6
 
7
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
8
8
 
@@ -1429,7 +1429,7 @@ Audio processing failed. Error: ${n instanceof Error?n.message:String(n)}`}}asyn
1429
1429
  - ARCHIVE (zip): Use entry_path to extract a specific file from the archive
1430
1430
  - TEXT/CODE: Use page_range as line range for targeted reading
1431
1431
 
1432
- 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:O.object({file_id:O.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:O.number().optional().describe("Start timestamp in seconds (video only)"),end_time:O.number().optional().describe("End timestamp in seconds (video only)"),frame_count:O.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:O.array(O.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:O.object({start:O.number().int().min(1),end:O.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:O.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:O.object({start:O.number().int().min(1),end:O.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:O.array(O.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:O.string().optional().describe("File path within archive to extract (archive only)"),format:O.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 mbt(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 pPr=S({"src/lib/files/fileTools.ts"(){"use strict";Jr(),pc()}}),Z0,lY,uY,pbt=S({"src/lib/hitl/hitlManager.ts"(){"use strict";An(),Dt(),BI(),U(),Z0=3e4,lY=!1,uY=class extends qr{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??Z0,confirmationMethod:e.confirmationMethod??"event",allowArgumentModification:e.allowArgumentModification??lY,autoApproveOnTimeout:e.autoApproveOnTimeout??!1,auditLogging:e.auditLogging??!1,customRules:e.customRules??[]};if(!t.enabled)return t;if(!Array.isArray(t.dangerousActions))throw new mE("dangerousActions must be an array of strings");if(typeof t.timeout!="number"||t.timeout<=0)throw new mE("timeout must be a positive number (milliseconds)");if(t.confirmationMethod!=="event")throw new mE("confirmationMethod must be 'event' (only supported method)");if(typeof t.allowArgumentModification!="boolean")throw new mE("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),c={confirmationId:n,toolName:e,arguments:t,timestamp:o,timeoutHandle:a,resolve:s,reject:i};this.pendingConfirmations.set(n,c);const l={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??Z0,allowModification:this.config.allowArgumentModification??lY}};this.emit("hitl:confirmation-request",l),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){p.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??Z0,arguments:t.arguments,autoApproved:n});const o={type:"hitl:timeout",payload:{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??Z0}};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 dE(`Confirmation timeout for tool: ${t.toolName}`,e,this.config.timeout??Z0))}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()}-${Qe()}`}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};p.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)}}}}),gD,hbt,dY,yD,fbt,hPr=S({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";An(),U(),tt(),Mr(),cr(),gD=class extends qr{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 ue.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw ue.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 ue.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(ue.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=>{p.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=>{p.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 ct({name:"neurolink.mcp.batch.execute",tracer:Fe.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 ue.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 c;const l=new Promise((m,h)=>{c=setTimeout(()=>h(ue.toolTimeout("batchExecution",a)),a)});i.catch(m=>{});const u=await Promise.race([i,l]).finally(()=>{c&&clearTimeout(c)}),d=[];for(let m=0;m<e.length;m++){const h=e[m],f=u[m],g=Date.now()-r;if(!f){const y=ue.toolExecutionFailed(h.tool,new Error(`Batch executor returned no result for request ${m}`));h.reject(y),d.push({id:h.id,success:!1,error:y,executionTime:g}),s++;continue}if(f.success)h.resolve(f.result),d.push({id:h.id,success:!0,result:f.result,executionTime:g}),o++;else{const y=f.error??ue.toolExecutionFailed(h.tool,new Error("Unknown batch execution error"));h.reject(y),d.push({id:h.id,success:!1,error:y,executionTime:g}),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:ue.toolExecutionFailed("batch",new Error(String(i)));for(const c of e)c.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{p.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{p.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}},hbt=e=>new gD(e),dY={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},yD=class{batcher;toolExecutor;constructor(e){this.batcher=new gD({...dY,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw ue.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:ue.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()}},fbt=e=>new yD(e)}}),gbt=S({"src/lib/mcp/batching/index.ts"(){"use strict";hPr()}}),Tf,ybt,mY,vD,vbt,fPr=S({"src/lib/mcp/caching/toolCache.ts"(){"use strict";Dt(),An(),Gr(),Tf=class extends qr{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 xt(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 c="["+o.map(l=>r(l,s)).join(",")+"]";return s.delete(o),c}const a=Object.keys(o).sort().map(c=>JSON.stringify(c)+":"+r(o[c],s));return s.delete(o),"{"+a.join(",")+"}"},n=zl("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}},ybt=e=>new Tf(e),mY={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},vD=class{cache;constructor(e){this.cache=new Tf({...mY,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=Tf.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=Tf.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=Tf.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()}},vbt=e=>new vD(e)}}),wbt=S({"src/lib/mcp/caching/index.ts"(){"use strict";fPr()}}),Tbt={};ne(Tbt,{MultiServerManager:()=>zb,globalMultiServerManager:()=>pY});var zb,pY,hY=S({"src/lib/mcp/multiServerManager.ts"(){"use strict";An(),U(),tt(),zb=class extends qr{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}),p.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}),p.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw ue.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 ue.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}),p.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 ue.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw ue.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 ue.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 c=this.servers.get(r),l=this.metrics.get(r);if(c&&(!this.config.healthAwareRouting||l?.isHealthy)&&c.tools?.some(u=>u.name===e))return{serverId:r,server:c}}let n;if(t){const c=this.groups.get(t);if(!c)return p.warn(`[MultiServerManager] Group '${t}' not found`),null;n=c.servers.filter(l=>this.servers.get(l)?.tools?.some(d=>d.name===e))}else{n=[];for(const[c,l]of this.servers)l.tools?.some(u=>u.name===e)&&n.push(c)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(c=>this.metrics.get(c)?.isHealthy??!0),n.length===0))return p.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 c=Math.floor(Math.random()*t.length);return t[c]}const n=this.groups.get(r);if(!n?.weights){const c=Math.floor(Math.random()*t.length);return t[c]}const o=1,s=t.map(c=>{const u=(n.weights??[]).find(d=>d.serverId===c);return{serverId:c,weight:u?.weight??o}}),i=s.reduce((c,l)=>c+l.weight,0);if(i===0){const c=Math.floor(Math.random()*t.length);return t[c]}let a=Math.random()*i;for(const c of s)if(a-=c.weight,a<=0)return c.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}}},pY=new zb}}),Ebt={};ne(Ebt,{EnhancedToolDiscovery:()=>wD});var wD,fY=S({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";An(),U(),Gr(),tt(),O_(),hY(),wD=class extends qr{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new zb}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{p.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await xt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw ue.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),c=this.createToolKey(e,i.name);this.toolRegistry.set(c,a);let l=this.serverToolsMap.get(e);l||(l=new Set,this.serverToolsMap.set(e,l)),l.add(i.name),s.push(a),this.emit("toolDiscovered",{serverId:e,toolName:i.name,annotations:a.annotations,timestamp:new Date})}return p.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 p.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=md({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 c=i;if(s.annotations[c]!==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 c=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0,l=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0;a=c-l;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 c=o.version.split(".").map(Number),l=r.split(".").map(Number);c.some(isNaN)||l.some(isNaN)?i.push(`Non-standard version format: tool=${o.version}, target=${r}`):c[0]!==l[0]?s.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):c[1]<l[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}}}}}),Sbt={};ne(Sbt,{Agent:()=>dCt,BedrockClient:()=>bbt,BedrockRuntimeClient:()=>kbt,Blob:()=>uCt,Client:()=>pCt,ConverseCommand:()=>Abt,ConverseStreamCommand:()=>xbt,Cron:()=>Vbt,Dispatcher:()=>hCt,File:()=>lCt,FlowProducer:()=>Hbt,FormData:()=>cCt,GoogleAuth:()=>Obt,HTTPException:()=>Qbt,Headers:()=>aCt,Hippocampus:()=>$bt,HippocampusConfig:()=>Ubt,Hono:()=>Zbt,ImageFormat:()=>Ibt,InvokeEndpointCommand:()=>Pbt,InvokeEndpointWithResponseStreamCommand:()=>Dbt,InvokeModelCommand:()=>Rbt,Job:()=>qbt,ListFoundationModelsCommand:()=>Cbt,MockAgent:()=>yCt,Pool:()=>mCt,Queue:()=>zbt,QueueScheduler:()=>jbt,Request:()=>sCt,Response:()=>iCt,SageMakerRuntimeClient:()=>Mbt,TextToSpeechClient:()=>Lbt,VertexAI:()=>Nbt,Webhook:()=>Fbt,Worker:()=>Gbt,convertToHtml:()=>Ybt,cors:()=>Xbt,createClient:()=>Bbt,default:()=>_bt,extractRawText:()=>Jbt,fetch:()=>oCt,getGlobalDispatcher:()=>gCt,interceptors:()=>vCt,logger:()=>eCt,parseBuffer:()=>Wbt,request:()=>wCt,secureHeaders:()=>tCt,selectCover:()=>Kbt,setGlobalDispatcher:()=>fCt,streamSSE:()=>rCt,timeout:()=>nCt});var Ef,ns,_bt,bbt,Cbt,kbt,Abt,xbt,Ibt,Rbt,Mbt,Pbt,Dbt,Obt,Nbt,Lbt,Fbt,$bt,Ubt,Bbt,zbt,Gbt,qbt,jbt,Hbt,Vbt,Wbt,Kbt,Jbt,Ybt,Zbt,Xbt,Qbt,eCt,tCt,rCt,nCt,oCt,sCt,iCt,aCt,cCt,lCt,uCt,dCt,mCt,pCt,hCt,fCt,gCt,yCt,vCt,wCt,gPr=S({"npm-stub:which"(){Ef={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Ef.get}):new Proxy(function(...r){return new Proxy({},{get:Ef.get})},{get:Ef.get,apply(r,n,o){return new Proxy({},{get:Ef.get})},construct(r,n){return new Proxy({},{get:Ef.get})}})}},ns=new Proxy({},Ef),_bt=ns,{BedrockClient:bbt,ListFoundationModelsCommand:Cbt,BedrockRuntimeClient:kbt,ConverseCommand:Abt,ConverseStreamCommand:xbt,ImageFormat:Ibt,InvokeModelCommand:Rbt}=ns,{SageMakerRuntimeClient:Mbt,InvokeEndpointCommand:Pbt,InvokeEndpointWithResponseStreamCommand:Dbt}=ns,{GoogleAuth:Obt,VertexAI:Nbt,TextToSpeechClient:Lbt}=ns,{Webhook:Fbt}=ns,{Hippocampus:$bt,HippocampusConfig:Ubt}=ns,{createClient:Bbt}=ns,{Queue:zbt,Worker:Gbt,Job:qbt,QueueScheduler:jbt,FlowProducer:Hbt}=ns,{Cron:Vbt}=ns,{parseBuffer:Wbt,selectCover:Kbt}=ns,{extractRawText:Jbt,convertToHtml:Ybt}=ns,{Hono:Zbt}=ns,{cors:Xbt,HTTPException:Qbt,logger:eCt,secureHeaders:tCt,streamSSE:rCt,timeout:nCt}=ns,oCt=globalThis.fetch,sCt=globalThis.Request,iCt=globalThis.Response,aCt=globalThis.Headers,cCt=globalThis.FormData,lCt=globalThis.File,uCt=globalThis.Blob,dCt=ns.Agent,mCt=ns.Pool,pCt=ns.Client,hCt=ns.Dispatcher,fCt=()=>{},gCt=()=>ns,yCt=ns.MockAgent,vCt={redirect:()=>e=>e,retry:()=>e=>e},wCt=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()}}}}}),yPr=Or({"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}}),vPr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(pr(),Nr(pm)),n=(gPr(),Nr(Sbt)),o=yPr();function s(a,c){const l=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:l[o({env:l})],pathExt:c?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}}),wPr=Or({"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}}),TPr=Or({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),EPr=Or({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=TPr();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}}}),SPr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(kn(),Nr(ql)),n=EPr();function o(s){const a=Buffer.alloc(150);let c;try{c=r.openSync(s,"r"),r.readSync(c,a,0,150,0),r.closeSync(c)}catch{}return n(a.toString())}t.exports=o}}),_Pr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(pr(),Nr(pm)),n=vPr(),o=wPr(),s=SPr(),i=process.platform==="win32",a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(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=l(m),f=!a.test(h);if(m.options.forceShell||f){const g=c.test(h);m.command=r.normalize(m.command),m.command=o.command(m.command),m.args=m.args.map(w=>o.argument(w,g));const y=[m.command].concat(m.args).join(" ");m.args=["/d","/s","/c",`"${y}"`],m.command=process.env.comspec||"cmd.exe",m.options.windowsVerbatimArguments=!0}return m}function d(m,h,f){h&&!Array.isArray(h)&&(f=h,h=null),h=h?h.slice(0):[],f=Object.assign({},f);const g={command:m,args:h,options:f,file:void 0,original:{command:m,args:h}};return f.shell?g:u(g)}t.exports=d}}),bPr=Or({"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,c){return Object.assign(new Error(`${c} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${c} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,c){if(!r)return;const l=a.emit;a.emit=function(u,d){if(u==="exit"){const m=s(d,c);if(m)return l.call(a,"error",m)}return l.apply(a,arguments)}}function s(a,c){return r&&a===1&&!c.file?n(c.original,"spawn"):null}function i(a,c){return r&&a===1&&!c.file?n(c.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:s,verifyENOENTSync:i,notFoundError:n}}}),CPr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(HSe(),Nr(gTe)),n=_Pr(),o=bPr();function s(a,c,l){const u=n(a,c,l),d=r.spawn(u.command,u.args,u.options);return o.hookChildProcess(d,u),d}function i(a,c,l){const u=n(a,c,l),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}}),Gb,kPr,APr,xPr,IPr,TD,TCt,gY,RPr,MPr,PPr,DPr,OPr=S({"node-stub:node:process"(){Gb={},kPr=globalThis.crypto,APr=globalThis.ReadableStream||class{},xPr=globalThis.URL,IPr=globalThis.URLSearchParams,TD=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},TD.custom=Symbol.for("nodejs.util.inspect.custom"),TD.colors={},TD.styles={},TCt=globalThis.TextDecoder,gY=globalThis.TextEncoder,RPr=globalThis.performance||{now:()=>Date.now()},MPr=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 gY().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 gY().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 TCt().decode(this)}},PPr=globalThis.clearTimeout,DPr=globalThis.clearInterval}}),ECt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js"(){DI(),DI()}}),SCt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/index.js"(){ECt(),ECt()}}),qb,_Ct,rp,jb,Fs,yY,vY,NPr,bCt,CCt,ED,ga,X0,kCt,$s,Wa,Ka,Us,Hb,wY,SD,TY,ACt,_D,Q0,zt,bD,xCt,Sf,LPr,_f,ICt,CD,RCt,ev,bf,EY,MCt,PCt,DCt,OCt,NCt,LCt,FCt,$Ct,SY,_Y,UCt,kD,BCt,zCt,AD,GCt,tv,rv,qCt,nv,ov,jCt,Vb,xD,ID,RD,FPr,MD,PD,DD,HCt,bY,CY,OD,kY,sv,Cf,AY,VCt,WCt,xY,KCt,IY,ND,JCt,YCt,RY,MY,ZCt,XCt,QCt,ekt,tkt,rkt,nkt,okt,skt,PY,ikt,akt,LD,FD,$D,ckt,lkt,ukt,UD,dkt,DY,OY,mkt,pkt,NY,hkt,LY,Wb,$Pr,fkt,gkt,FY,ykt,$Y,vkt,wkt,Tkt,Ekt,Skt,_kt,bkt,Ckt,kkt,Kb,Akt,xkt,UY,BY,zY,Ikt,Rkt,Mkt,Pkt,Dkt,Okt,Nkt,Lkt,Fkt,$kt,Ukt,Bkt,zkt,Gkt,qkt,GY,jkt,Hkt,qY,Vkt,Wkt,Kkt,Jkt,jY,Ykt,Zkt,Xkt,Qkt,UPr,BPr,zPr,GPr,qPr,jPr,It,eAt,np=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"(){SCt(),qb="2025-11-25",_Ct=[qb,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],rp="io.modelcontextprotocol/related-task",jb="2.0",Fs=T6(e=>e!==null&&(typeof e=="object"||typeof e=="function")),yY=Br([X(),vr().int()]),vY=X(),NPr=us({ttl:Br([vr(),NT()]).optional(),pollInterval:vr().optional()}),bCt=Xe({ttl:vr().optional()}),CCt=Xe({taskId:X()}),ED=us({progressToken:yY.optional(),[rp]:CCt.optional()}),ga=Xe({_meta:ED.optional()}),X0=ga.extend({task:bCt.optional()}),kCt=e=>X0.safeParse(e).success,$s=Xe({method:X(),params:ga.loose().optional()}),Wa=Xe({_meta:ED.optional()}),Ka=Xe({method:X(),params:Wa.loose().optional()}),Us=us({_meta:ED.optional()}),Hb=Br([X(),vr().int()]),wY=Xe({jsonrpc:pt(jb),id:Hb,...$s.shape}).strict(),SD=e=>wY.safeParse(e).success,TY=Xe({jsonrpc:pt(jb),...Ka.shape}).strict(),ACt=e=>TY.safeParse(e).success,_D=Xe({jsonrpc:pt(jb),id:Hb,result:Us}).strict(),Q0=e=>_D.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"})(zt||(zt={})),bD=Xe({jsonrpc:pt(jb),id:Hb.optional(),error:Xe({code:vr().int(),message:X(),data:Kr().optional()})}).strict(),xCt=e=>bD.safeParse(e).success,Sf=Br([wY,TY,_D,bD]),LPr=Br([_D,bD]),_f=Us.strict(),ICt=Wa.extend({requestId:Hb.optional(),reason:X().optional()}),CD=Ka.extend({method:pt("notifications/cancelled"),params:ICt}),RCt=Xe({src:X(),mimeType:X().optional(),sizes:Je(X()).optional(),theme:mi(["light","dark"]).optional()}),ev=Xe({icons:Je(RCt).optional()}),bf=Xe({name:X(),title:X().optional()}),EY=bf.extend({...bf.shape,...ev.shape,version:X(),websiteUrl:X().optional(),description:X().optional()}),MCt=LT(Xe({applyDefaults:Ur().optional()}),Cn(X(),Kr())),PCt=tI(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,LT(Xe({form:MCt.optional(),url:Fs.optional()}),Cn(X(),Kr()).optional())),DCt=us({list:Fs.optional(),cancel:Fs.optional(),requests:us({sampling:us({createMessage:Fs.optional()}).optional(),elicitation:us({create:Fs.optional()}).optional()}).optional()}),OCt=us({list:Fs.optional(),cancel:Fs.optional(),requests:us({tools:us({call:Fs.optional()}).optional()}).optional()}),NCt=Xe({experimental:Cn(X(),Fs).optional(),sampling:Xe({context:Fs.optional(),tools:Fs.optional()}).optional(),elicitation:PCt.optional(),roots:Xe({listChanged:Ur().optional()}).optional(),tasks:DCt.optional()}),LCt=ga.extend({protocolVersion:X(),capabilities:NCt,clientInfo:EY}),FCt=$s.extend({method:pt("initialize"),params:LCt}),$Ct=Xe({experimental:Cn(X(),Fs).optional(),logging:Fs.optional(),completions:Fs.optional(),prompts:Xe({listChanged:Ur().optional()}).optional(),resources:Xe({subscribe:Ur().optional(),listChanged:Ur().optional()}).optional(),tools:Xe({listChanged:Ur().optional()}).optional(),tasks:OCt.optional()}),SY=Us.extend({protocolVersion:X(),capabilities:$Ct,serverInfo:EY,instructions:X().optional()}),_Y=Ka.extend({method:pt("notifications/initialized"),params:Wa.optional()}),UCt=e=>_Y.safeParse(e).success,kD=$s.extend({method:pt("ping"),params:ga.optional()}),BCt=Xe({progress:vr(),total:Pn(vr()),message:Pn(X())}),zCt=Xe({...Wa.shape,...BCt.shape,progressToken:yY}),AD=Ka.extend({method:pt("notifications/progress"),params:zCt}),GCt=ga.extend({cursor:vY.optional()}),tv=$s.extend({params:GCt.optional()}),rv=Us.extend({nextCursor:vY.optional()}),qCt=mi(["working","input_required","completed","failed","cancelled"]),nv=Xe({taskId:X(),status:qCt,ttl:Br([vr(),NT()]),createdAt:X(),lastUpdatedAt:X(),pollInterval:Pn(vr()),statusMessage:Pn(X())}),ov=Us.extend({task:nv}),jCt=Wa.merge(nv),Vb=Ka.extend({method:pt("notifications/tasks/status"),params:jCt}),xD=$s.extend({method:pt("tasks/get"),params:ga.extend({taskId:X()})}),ID=Us.merge(nv),RD=$s.extend({method:pt("tasks/result"),params:ga.extend({taskId:X()})}),FPr=Us.loose(),MD=tv.extend({method:pt("tasks/list")}),PD=rv.extend({tasks:Je(nv)}),DD=$s.extend({method:pt("tasks/cancel"),params:ga.extend({taskId:X()})}),HCt=Us.merge(nv),bY=Xe({uri:X(),mimeType:Pn(X()),_meta:Cn(X(),Kr()).optional()}),CY=bY.extend({text:X()}),OD=X().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),kY=bY.extend({blob:OD}),sv=mi(["user","assistant"]),Cf=Xe({audience:Je(sv).optional(),priority:vr().min(0).max(1).optional(),lastModified:jx.datetime({offset:!0}).optional()}),AY=Xe({...bf.shape,...ev.shape,uri:X(),description:Pn(X()),mimeType:Pn(X()),annotations:Cf.optional(),_meta:Pn(us({}))}),VCt=Xe({...bf.shape,...ev.shape,uriTemplate:X(),description:Pn(X()),mimeType:Pn(X()),annotations:Cf.optional(),_meta:Pn(us({}))}),WCt=tv.extend({method:pt("resources/list")}),xY=rv.extend({resources:Je(AY)}),KCt=tv.extend({method:pt("resources/templates/list")}),IY=rv.extend({resourceTemplates:Je(VCt)}),ND=ga.extend({uri:X()}),JCt=ND,YCt=$s.extend({method:pt("resources/read"),params:JCt}),RY=Us.extend({contents:Je(Br([CY,kY]))}),MY=Ka.extend({method:pt("notifications/resources/list_changed"),params:Wa.optional()}),ZCt=ND,XCt=$s.extend({method:pt("resources/subscribe"),params:ZCt}),QCt=ND,ekt=$s.extend({method:pt("resources/unsubscribe"),params:QCt}),tkt=Wa.extend({uri:X()}),rkt=Ka.extend({method:pt("notifications/resources/updated"),params:tkt}),nkt=Xe({name:X(),description:Pn(X()),required:Pn(Ur())}),okt=Xe({...bf.shape,...ev.shape,description:Pn(X()),arguments:Pn(Je(nkt)),_meta:Pn(us({}))}),skt=tv.extend({method:pt("prompts/list")}),PY=rv.extend({prompts:Je(okt)}),ikt=ga.extend({name:X(),arguments:Cn(X(),X()).optional()}),akt=$s.extend({method:pt("prompts/get"),params:ikt}),LD=Xe({type:pt("text"),text:X(),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),FD=Xe({type:pt("image"),data:OD,mimeType:X(),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),$D=Xe({type:pt("audio"),data:OD,mimeType:X(),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),ckt=Xe({type:pt("tool_use"),name:X(),id:X(),input:Cn(X(),Kr()),_meta:Cn(X(),Kr()).optional()}),lkt=Xe({type:pt("resource"),resource:Br([CY,kY]),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),ukt=AY.extend({type:pt("resource_link")}),UD=Br([LD,FD,$D,ukt,lkt]),dkt=Xe({role:sv,content:UD}),DY=Us.extend({description:X().optional(),messages:Je(dkt)}),OY=Ka.extend({method:pt("notifications/prompts/list_changed"),params:Wa.optional()}),mkt=Xe({title:X().optional(),readOnlyHint:Ur().optional(),destructiveHint:Ur().optional(),idempotentHint:Ur().optional(),openWorldHint:Ur().optional()}),pkt=Xe({taskSupport:mi(["required","optional","forbidden"]).optional()}),NY=Xe({...bf.shape,...ev.shape,description:X().optional(),inputSchema:Xe({type:pt("object"),properties:Cn(X(),Fs).optional(),required:Je(X()).optional()}).catchall(Kr()),outputSchema:Xe({type:pt("object"),properties:Cn(X(),Fs).optional(),required:Je(X()).optional()}).catchall(Kr()).optional(),annotations:mkt.optional(),execution:pkt.optional(),_meta:Cn(X(),Kr()).optional()}),hkt=tv.extend({method:pt("tools/list")}),LY=rv.extend({tools:Je(NY)}),Wb=Us.extend({content:Je(UD).default([]),structuredContent:Cn(X(),Kr()).optional(),isError:Ur().optional()}),$Pr=Wb.or(Us.extend({toolResult:Kr()})),fkt=X0.extend({name:X(),arguments:Cn(X(),Kr()).optional()}),gkt=$s.extend({method:pt("tools/call"),params:fkt}),FY=Ka.extend({method:pt("notifications/tools/list_changed"),params:Wa.optional()}),ykt=Xe({autoRefresh:Ur().default(!0),debounceMs:vr().int().nonnegative().default(300)}),$Y=mi(["debug","info","notice","warning","error","critical","alert","emergency"]),vkt=ga.extend({level:$Y}),wkt=$s.extend({method:pt("logging/setLevel"),params:vkt}),Tkt=Wa.extend({level:$Y,logger:X().optional(),data:Kr()}),Ekt=Ka.extend({method:pt("notifications/message"),params:Tkt}),Skt=Xe({name:X().optional()}),_kt=Xe({hints:Je(Skt).optional(),costPriority:vr().min(0).max(1).optional(),speedPriority:vr().min(0).max(1).optional(),intelligencePriority:vr().min(0).max(1).optional()}),bkt=Xe({mode:mi(["auto","required","none"]).optional()}),Ckt=Xe({type:pt("tool_result"),toolUseId:X().describe("The unique identifier for the corresponding tool call."),content:Je(UD).default([]),structuredContent:Xe({}).loose().optional(),isError:Ur().optional(),_meta:Cn(X(),Kr()).optional()}),kkt=Xx("type",[LD,FD,$D]),Kb=Xx("type",[LD,FD,$D,ckt,Ckt]),Akt=Xe({role:sv,content:Br([Kb,Je(Kb)]),_meta:Cn(X(),Kr()).optional()}),xkt=X0.extend({messages:Je(Akt),modelPreferences:_kt.optional(),systemPrompt:X().optional(),includeContext:mi(["none","thisServer","allServers"]).optional(),temperature:vr().optional(),maxTokens:vr().int(),stopSequences:Je(X()).optional(),metadata:Fs.optional(),tools:Je(NY).optional(),toolChoice:bkt.optional()}),UY=$s.extend({method:pt("sampling/createMessage"),params:xkt}),BY=Us.extend({model:X(),stopReason:Pn(mi(["endTurn","stopSequence","maxTokens"]).or(X())),role:sv,content:kkt}),zY=Us.extend({model:X(),stopReason:Pn(mi(["endTurn","stopSequence","maxTokens","toolUse"]).or(X())),role:sv,content:Br([Kb,Je(Kb)])}),Ikt=Xe({type:pt("boolean"),title:X().optional(),description:X().optional(),default:Ur().optional()}),Rkt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),minLength:vr().optional(),maxLength:vr().optional(),format:mi(["email","uri","date","date-time"]).optional(),default:X().optional()}),Mkt=Xe({type:mi(["number","integer"]),title:X().optional(),description:X().optional(),minimum:vr().optional(),maximum:vr().optional(),default:vr().optional()}),Pkt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),enum:Je(X()),default:X().optional()}),Dkt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),oneOf:Je(Xe({const:X(),title:X()})),default:X().optional()}),Okt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),enum:Je(X()),enumNames:Je(X()).optional(),default:X().optional()}),Nkt=Br([Pkt,Dkt]),Lkt=Xe({type:pt("array"),title:X().optional(),description:X().optional(),minItems:vr().optional(),maxItems:vr().optional(),items:Xe({type:pt("string"),enum:Je(X())}),default:Je(X()).optional()}),Fkt=Xe({type:pt("array"),title:X().optional(),description:X().optional(),minItems:vr().optional(),maxItems:vr().optional(),items:Xe({anyOf:Je(Xe({const:X(),title:X()}))}),default:Je(X()).optional()}),$kt=Br([Lkt,Fkt]),Ukt=Br([Okt,Nkt,$kt]),Bkt=Br([Ukt,Ikt,Rkt,Mkt]),zkt=X0.extend({mode:pt("form").optional(),message:X(),requestedSchema:Xe({type:pt("object"),properties:Cn(X(),Bkt),required:Je(X()).optional()})}),Gkt=X0.extend({mode:pt("url"),message:X(),elicitationId:X(),url:X().url()}),qkt=Br([zkt,Gkt]),GY=$s.extend({method:pt("elicitation/create"),params:qkt}),jkt=Wa.extend({elicitationId:X()}),Hkt=Ka.extend({method:pt("notifications/elicitation/complete"),params:jkt}),qY=Us.extend({action:mi(["accept","decline","cancel"]),content:tI(e=>e===null?void 0:e,Cn(X(),Br([X(),vr(),Ur(),Je(X())])).optional())}),Vkt=Xe({type:pt("ref/resource"),uri:X()}),Wkt=Xe({type:pt("ref/prompt"),name:X()}),Kkt=ga.extend({ref:Br([Wkt,Vkt]),argument:Xe({name:X(),value:X()}),context:Xe({arguments:Cn(X(),X()).optional()}).optional()}),Jkt=$s.extend({method:pt("completion/complete"),params:Kkt}),jY=Us.extend({completion:us({values:Je(X()).max(100),total:Pn(vr().int()),hasMore:Pn(Ur())})}),Ykt=Xe({uri:X().startsWith("file://"),name:X().optional(),_meta:Cn(X(),Kr()).optional()}),Zkt=$s.extend({method:pt("roots/list"),params:ga.optional()}),Xkt=Us.extend({roots:Je(Ykt)}),Qkt=Ka.extend({method:pt("notifications/roots/list_changed"),params:Wa.optional()}),UPr=Br([kD,FCt,Jkt,wkt,akt,skt,WCt,KCt,YCt,XCt,ekt,gkt,hkt,xD,RD,MD,DD]),BPr=Br([CD,AD,_Y,Qkt,Vb]),zPr=Br([_f,BY,zY,qY,Xkt,ID,PD,ov]),GPr=Br([kD,UY,GY,Zkt,xD,RD,MD,DD]),qPr=Br([CD,AD,Ekt,rkt,MY,FY,OY,Vb,Hkt]),jPr=Br([_f,SY,jY,DY,PY,xY,IY,RY,Wb,LY,ID,PD,ov]),It=class Btr 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===zt.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new eAt(o.elicitations,r)}return new Btr(t,r,n)}},eAt=class extends It{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(zt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function HPr(e){return Sf.parse(JSON.parse(e))}function VPr(e){return JSON.stringify(e)+`
1432
+ 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:O.object({file_id:O.string().describe("File ID (UUID) or exact filename from list_attached_files"),start_time:O.number().optional().describe("Start timestamp in seconds (video only)"),end_time:O.number().optional().describe("End timestamp in seconds (video only)"),frame_count:O.number().int().min(1).max(20).optional().describe("Number of frames to extract in time range (video only, default: 5, max: 20)"),pages:O.array(O.number().int().min(1)).optional().describe("Specific page/slide numbers to extract (1-indexed)"),page_range:O.object({start:O.number().int().min(1),end:O.number().int().min(1)}).optional().describe("Page/slide range to extract (1-indexed, inclusive)"),sheet:O.string().optional().describe("Sheet name or 0-based index as string e.g. '0', '1' (spreadsheet only, default: first sheet)"),row_range:O.object({start:O.number().int().min(1),end:O.number().int().min(1)}).optional().describe("Row range (1-indexed, spreadsheet only)"),columns:O.array(O.string()).optional().describe("Specific column letters to include (e.g., ['A', 'B', 'D'], spreadsheet only)"),entry_path:O.string().optional().describe("File path within archive to extract (archive only)"),format:O.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 mbt(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 pPr=S({"src/lib/files/fileTools.ts"(){"use strict";Jr(),pc()}}),Z0,lY,uY,pbt=S({"src/lib/hitl/hitlManager.ts"(){"use strict";An(),Dt(),BI(),U(),Z0=3e4,lY=!1,uY=class extends qr{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??Z0,confirmationMethod:e.confirmationMethod??"event",allowArgumentModification:e.allowArgumentModification??lY,autoApproveOnTimeout:e.autoApproveOnTimeout??!1,auditLogging:e.auditLogging??!1,customRules:e.customRules??[]};if(!t.enabled)return t;if(!Array.isArray(t.dangerousActions))throw new mE("dangerousActions must be an array of strings");if(typeof t.timeout!="number"||t.timeout<=0)throw new mE("timeout must be a positive number (milliseconds)");if(t.confirmationMethod!=="event")throw new mE("confirmationMethod must be 'event' (only supported method)");if(typeof t.allowArgumentModification!="boolean")throw new mE("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),c={confirmationId:n,toolName:e,arguments:t,timestamp:o,timeoutHandle:a,resolve:s,reject:i};this.pendingConfirmations.set(n,c);const l={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??Z0,allowModification:this.config.allowArgumentModification??lY}};this.emit("hitl:confirmation-request",l),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){p.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??Z0,arguments:t.arguments,autoApproved:n});const o={type:"hitl:timeout",payload:{confirmationId:e,toolName:t.toolName,timeout:this.config.timeout??Z0}};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 dE(`Confirmation timeout for tool: ${t.toolName}`,e,this.config.timeout??Z0))}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()}-${Qe()}`}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};p.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)}}}}),gD,hbt,dY,yD,fbt,hPr=S({"src/lib/mcp/batching/requestBatcher.ts"(){"use strict";An(),U(),tt(),Mr(),cr(),gD=class extends qr{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 ue.invalidConfiguration("batcher","Batcher has been destroyed");if(!this.executor)throw ue.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 ue.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(ue.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=>{p.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=>{p.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 ct({name:"neurolink.mcp.batch.execute",tracer:Fe.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 ue.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 c;const l=new Promise((m,h)=>{c=setTimeout(()=>h(ue.toolTimeout("batchExecution",a)),a)});i.catch(m=>{});const u=await Promise.race([i,l]).finally(()=>{c&&clearTimeout(c)}),d=[];for(let m=0;m<e.length;m++){const h=e[m],f=u[m],g=Date.now()-r;if(!f){const y=ue.toolExecutionFailed(h.tool,new Error(`Batch executor returned no result for request ${m}`));h.reject(y),d.push({id:h.id,success:!1,error:y,executionTime:g}),s++;continue}if(f.success)h.resolve(f.result),d.push({id:h.id,success:!0,result:f.result,executionTime:g}),o++;else{const y=f.error??ue.toolExecutionFailed(h.tool,new Error("Unknown batch execution error"));h.reject(y),d.push({id:h.id,success:!1,error:y,executionTime:g}),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:ue.toolExecutionFailed("batch",new Error(String(i)));for(const c of e)c.reject(a);throw this.emit("batchFailed",{batchId:t,error:a}),a}finally{this.activeBatches--}}).catch(n=>{p.error("Batch span execution failed:",n)}),this.pending.size>0&&(this.clearFlushTimer(),this.flushTimer=setTimeout(()=>{this.executeBatch().catch(n=>{p.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}},hbt=e=>new gD(e),dY={maxBatchSize:10,maxWaitMs:100,enableParallel:!0,maxConcurrentBatches:5,groupByServer:!0},yD=class{batcher;toolExecutor;constructor(e){this.batcher=new gD({...dY,...e}),this.batcher.setExecutor(async t=>{if(!this.toolExecutor)throw ue.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:ue.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()}},fbt=e=>new yD(e)}}),gbt=S({"src/lib/mcp/batching/index.ts"(){"use strict";hPr()}}),Tf,ybt,mY,vD,vbt,fPr=S({"src/lib/mcp/caching/toolCache.ts"(){"use strict";Dt(),An(),Gr(),Tf=class extends qr{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}r.accessedAt=Date.now(),r.accessCount++,this.stats.hits++,this.updateHitRate();const n=this.cloneCachedValue(r.value);return this.listenerCount("hit")>0&&this.emit("hit",{key:t,value:this.cloneCachedValue(r.value)}),n}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:this.cloneCachedValue(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 xt(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 c="["+o.map(l=>r(l,s)).join(",")+"]";return s.delete(o),c}const a=Object.keys(o).sort().map(c=>JSON.stringify(c)+":"+r(o[c],s));return s.delete(o),"{"+a.join(",")+"}"},n=zl("sha256").update(r(t)).digest("hex").substring(0,16);return`${e}:${n}`}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.clear()}cloneCachedValue(e){if(e===null||typeof e!="object")return e;try{return structuredClone(e)}catch{return JSON.parse(JSON.stringify(e))}}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}},ybt=e=>new Tf(e),mY={ttl:300*1e3,maxSize:500,strategy:"lru",enableAutoCleanup:!0,cleanupInterval:6e4},vD=class{cache;constructor(e){this.cache=new Tf({...mY,...e,namespace:e?.namespace??"tool-results"})}cacheResult(e,t,r,n){const o=Tf.generateKey(e,t);this.cache.set(o,r,n)}getCachedResult(e,t){const r=Tf.generateKey(e,t);return this.cache.get(r)}hasCachedResult(e,t){const r=Tf.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()}},vbt=e=>new vD(e)}}),wbt=S({"src/lib/mcp/caching/index.ts"(){"use strict";fPr()}}),Tbt={};ne(Tbt,{MultiServerManager:()=>zb,globalMultiServerManager:()=>pY});var zb,pY,hY=S({"src/lib/mcp/multiServerManager.ts"(){"use strict";An(),U(),tt(),zb=class extends qr{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}),p.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}),p.debug(`[MultiServerManager] Removed server: ${e}`),!0}updateServer(e,t){const r=this.servers.get(e);if(!r)throw ue.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 ue.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}),p.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 ue.invalidConfiguration("groupId",`Group '${t}' not found`,{groupId:t});if(!this.servers.has(e))throw ue.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 ue.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 c=this.servers.get(r),l=this.metrics.get(r);if(c&&(!this.config.healthAwareRouting||l?.isHealthy)&&c.tools?.some(u=>u.name===e))return{serverId:r,server:c}}let n;if(t){const c=this.groups.get(t);if(!c)return p.warn(`[MultiServerManager] Group '${t}' not found`),null;n=c.servers.filter(l=>this.servers.get(l)?.tools?.some(d=>d.name===e))}else{n=[];for(const[c,l]of this.servers)l.tools?.some(u=>u.name===e)&&n.push(c)}if(n.length===0)return null;if((t?this.groups.get(t)?.healthAware??this.config.healthAwareRouting:this.config.healthAwareRouting)&&(n=n.filter(c=>this.metrics.get(c)?.isHealthy??!0),n.length===0))return p.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 c=Math.floor(Math.random()*t.length);return t[c]}const n=this.groups.get(r);if(!n?.weights){const c=Math.floor(Math.random()*t.length);return t[c]}const o=1,s=t.map(c=>{const u=(n.weights??[]).find(d=>d.serverId===c);return{serverId:c,weight:u?.weight??o}}),i=s.reduce((c,l)=>c+l.weight,0);if(i===0){const c=Math.floor(Math.random()*t.length);return t[c]}let a=Math.random()*i;for(const c of s)if(a-=c.weight,a<=0)return c.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}}},pY=new zb}}),Ebt={};ne(Ebt,{EnhancedToolDiscovery:()=>wD});var wD,fY=S({"src/lib/mcp/enhancedToolDiscovery.ts"(){"use strict";An(),U(),Gr(),tt(),O_(),hY(),wD=class extends qr{toolRegistry=new Map;serverToolsMap=new Map;multiServerManager;discoveryInProgress=new Set;constructor(e){super(),this.multiServerManager=e??new zb}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{p.info(`[EnhancedToolDiscovery] Starting discovery with annotations for: ${e}`);const o=await xt(t.listTools(),r,"Discovery timeout");if(!o?.tools)throw ue.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),c=this.createToolKey(e,i.name);this.toolRegistry.set(c,a);let l=this.serverToolsMap.get(e);l||(l=new Set,this.serverToolsMap.set(e,l)),l.add(i.name),s.push(a),this.emit("toolDiscovered",{serverId:e,toolName:i.name,annotations:a.annotations,timestamp:new Date})}return p.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 p.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=md({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 c=i;if(s.annotations[c]!==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 c=s.stats.totalCalls>0?s.stats.successfulCalls/s.stats.totalCalls:0,l=i.stats.totalCalls>0?i.stats.successfulCalls/i.stats.totalCalls:0;a=c-l;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 c=o.version.split(".").map(Number),l=r.split(".").map(Number);c.some(isNaN)||l.some(isNaN)?i.push(`Non-standard version format: tool=${o.version}, target=${r}`):c[0]!==l[0]?s.push(`Major version mismatch: tool is v${o.version}, target is v${r}`):c[1]<l[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}}}}}),Sbt={};ne(Sbt,{Agent:()=>dCt,BedrockClient:()=>bbt,BedrockRuntimeClient:()=>kbt,Blob:()=>uCt,Client:()=>pCt,ConverseCommand:()=>Abt,ConverseStreamCommand:()=>xbt,Cron:()=>Vbt,Dispatcher:()=>hCt,File:()=>lCt,FlowProducer:()=>Hbt,FormData:()=>cCt,GoogleAuth:()=>Obt,HTTPException:()=>Qbt,Headers:()=>aCt,Hippocampus:()=>$bt,HippocampusConfig:()=>Ubt,Hono:()=>Zbt,ImageFormat:()=>Ibt,InvokeEndpointCommand:()=>Pbt,InvokeEndpointWithResponseStreamCommand:()=>Dbt,InvokeModelCommand:()=>Rbt,Job:()=>qbt,ListFoundationModelsCommand:()=>Cbt,MockAgent:()=>yCt,Pool:()=>mCt,Queue:()=>zbt,QueueScheduler:()=>jbt,Request:()=>sCt,Response:()=>iCt,SageMakerRuntimeClient:()=>Mbt,TextToSpeechClient:()=>Lbt,VertexAI:()=>Nbt,Webhook:()=>Fbt,Worker:()=>Gbt,convertToHtml:()=>Ybt,cors:()=>Xbt,createClient:()=>Bbt,default:()=>_bt,extractRawText:()=>Jbt,fetch:()=>oCt,getGlobalDispatcher:()=>gCt,interceptors:()=>vCt,logger:()=>eCt,parseBuffer:()=>Wbt,request:()=>wCt,secureHeaders:()=>tCt,selectCover:()=>Kbt,setGlobalDispatcher:()=>fCt,streamSSE:()=>rCt,timeout:()=>nCt});var Ef,ns,_bt,bbt,Cbt,kbt,Abt,xbt,Ibt,Rbt,Mbt,Pbt,Dbt,Obt,Nbt,Lbt,Fbt,$bt,Ubt,Bbt,zbt,Gbt,qbt,jbt,Hbt,Vbt,Wbt,Kbt,Jbt,Ybt,Zbt,Xbt,Qbt,eCt,tCt,rCt,nCt,oCt,sCt,iCt,aCt,cCt,lCt,uCt,dCt,mCt,pCt,hCt,fCt,gCt,yCt,vCt,wCt,gPr=S({"npm-stub:which"(){Ef={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Ef.get}):new Proxy(function(...r){return new Proxy({},{get:Ef.get})},{get:Ef.get,apply(r,n,o){return new Proxy({},{get:Ef.get})},construct(r,n){return new Proxy({},{get:Ef.get})}})}},ns=new Proxy({},Ef),_bt=ns,{BedrockClient:bbt,ListFoundationModelsCommand:Cbt,BedrockRuntimeClient:kbt,ConverseCommand:Abt,ConverseStreamCommand:xbt,ImageFormat:Ibt,InvokeModelCommand:Rbt}=ns,{SageMakerRuntimeClient:Mbt,InvokeEndpointCommand:Pbt,InvokeEndpointWithResponseStreamCommand:Dbt}=ns,{GoogleAuth:Obt,VertexAI:Nbt,TextToSpeechClient:Lbt}=ns,{Webhook:Fbt}=ns,{Hippocampus:$bt,HippocampusConfig:Ubt}=ns,{createClient:Bbt}=ns,{Queue:zbt,Worker:Gbt,Job:qbt,QueueScheduler:jbt,FlowProducer:Hbt}=ns,{Cron:Vbt}=ns,{parseBuffer:Wbt,selectCover:Kbt}=ns,{extractRawText:Jbt,convertToHtml:Ybt}=ns,{Hono:Zbt}=ns,{cors:Xbt,HTTPException:Qbt,logger:eCt,secureHeaders:tCt,streamSSE:rCt,timeout:nCt}=ns,oCt=globalThis.fetch,sCt=globalThis.Request,iCt=globalThis.Response,aCt=globalThis.Headers,cCt=globalThis.FormData,lCt=globalThis.File,uCt=globalThis.Blob,dCt=ns.Agent,mCt=ns.Pool,pCt=ns.Client,hCt=ns.Dispatcher,fCt=()=>{},gCt=()=>ns,yCt=ns.MockAgent,vCt={redirect:()=>e=>e,retry:()=>e=>e},wCt=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()}}}}}),yPr=Or({"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}}),vPr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(e,t){"use strict";var r=(pr(),Nr(pm)),n=(gPr(),Nr(Sbt)),o=yPr();function s(a,c){const l=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:l[o({env:l})],pathExt:c?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}}),wPr=Or({"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}}),TPr=Or({"node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js"(e,t){"use strict";t.exports=/^#!(.*)/}}),EPr=Or({"node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js"(e,t){"use strict";var r=TPr();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}}}),SPr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(e,t){"use strict";var r=(kn(),Nr(ql)),n=EPr();function o(s){const a=Buffer.alloc(150);let c;try{c=r.openSync(s,"r"),r.readSync(c,a,0,150,0),r.closeSync(c)}catch{}return n(a.toString())}t.exports=o}}),_Pr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(e,t){"use strict";var r=(pr(),Nr(pm)),n=vPr(),o=wPr(),s=SPr(),i=process.platform==="win32",a=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function l(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=l(m),f=!a.test(h);if(m.options.forceShell||f){const g=c.test(h);m.command=r.normalize(m.command),m.command=o.command(m.command),m.args=m.args.map(w=>o.argument(w,g));const y=[m.command].concat(m.args).join(" ");m.args=["/d","/s","/c",`"${y}"`],m.command=process.env.comspec||"cmd.exe",m.options.windowsVerbatimArguments=!0}return m}function d(m,h,f){h&&!Array.isArray(h)&&(f=h,h=null),h=h?h.slice(0):[],f=Object.assign({},f);const g={command:m,args:h,options:f,file:void 0,original:{command:m,args:h}};return f.shell?g:u(g)}t.exports=d}}),bPr=Or({"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,c){return Object.assign(new Error(`${c} ${a.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${c} ${a.command}`,path:a.command,spawnargs:a.args})}function o(a,c){if(!r)return;const l=a.emit;a.emit=function(u,d){if(u==="exit"){const m=s(d,c);if(m)return l.call(a,"error",m)}return l.apply(a,arguments)}}function s(a,c){return r&&a===1&&!c.file?n(c.original,"spawn"):null}function i(a,c){return r&&a===1&&!c.file?n(c.original,"spawnSync"):null}t.exports={hookChildProcess:o,verifyENOENT:s,verifyENOENTSync:i,notFoundError:n}}}),CPr=Or({"node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/index.js"(e,t){"use strict";var r=(HSe(),Nr(gTe)),n=_Pr(),o=bPr();function s(a,c,l){const u=n(a,c,l),d=r.spawn(u.command,u.args,u.options);return o.hookChildProcess(d,u),d}function i(a,c,l){const u=n(a,c,l),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}}),Gb,kPr,APr,xPr,IPr,TD,TCt,gY,RPr,MPr,PPr,DPr,OPr=S({"node-stub:node:process"(){Gb={},kPr=globalThis.crypto,APr=globalThis.ReadableStream||class{},xPr=globalThis.URL,IPr=globalThis.URLSearchParams,TD=e=>{try{return JSON.stringify(e,null,2)}catch{return String(e)}},TD.custom=Symbol.for("nodejs.util.inspect.custom"),TD.colors={},TD.styles={},TCt=globalThis.TextDecoder,gY=globalThis.TextEncoder,RPr=globalThis.performance||{now:()=>Date.now()},MPr=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 gY().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 gY().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 TCt().decode(this)}},PPr=globalThis.clearTimeout,DPr=globalThis.clearInterval}}),ECt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js"(){DI(),DI()}}),SCt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/index.js"(){ECt(),ECt()}}),qb,_Ct,rp,jb,Fs,yY,vY,NPr,bCt,CCt,ED,ga,X0,kCt,$s,Wa,Ka,Us,Hb,wY,SD,TY,ACt,_D,Q0,zt,bD,xCt,Sf,LPr,_f,ICt,CD,RCt,ev,bf,EY,MCt,PCt,DCt,OCt,NCt,LCt,FCt,$Ct,SY,_Y,UCt,kD,BCt,zCt,AD,GCt,tv,rv,qCt,nv,ov,jCt,Vb,xD,ID,RD,FPr,MD,PD,DD,HCt,bY,CY,OD,kY,sv,Cf,AY,VCt,WCt,xY,KCt,IY,ND,JCt,YCt,RY,MY,ZCt,XCt,QCt,ekt,tkt,rkt,nkt,okt,skt,PY,ikt,akt,LD,FD,$D,ckt,lkt,ukt,UD,dkt,DY,OY,mkt,pkt,NY,hkt,LY,Wb,$Pr,fkt,gkt,FY,ykt,$Y,vkt,wkt,Tkt,Ekt,Skt,_kt,bkt,Ckt,kkt,Kb,Akt,xkt,UY,BY,zY,Ikt,Rkt,Mkt,Pkt,Dkt,Okt,Nkt,Lkt,Fkt,$kt,Ukt,Bkt,zkt,Gkt,qkt,GY,jkt,Hkt,qY,Vkt,Wkt,Kkt,Jkt,jY,Ykt,Zkt,Xkt,Qkt,UPr,BPr,zPr,GPr,qPr,jPr,It,eAt,np=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"(){SCt(),qb="2025-11-25",_Ct=[qb,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],rp="io.modelcontextprotocol/related-task",jb="2.0",Fs=T6(e=>e!==null&&(typeof e=="object"||typeof e=="function")),yY=Br([X(),vr().int()]),vY=X(),NPr=us({ttl:Br([vr(),NT()]).optional(),pollInterval:vr().optional()}),bCt=Xe({ttl:vr().optional()}),CCt=Xe({taskId:X()}),ED=us({progressToken:yY.optional(),[rp]:CCt.optional()}),ga=Xe({_meta:ED.optional()}),X0=ga.extend({task:bCt.optional()}),kCt=e=>X0.safeParse(e).success,$s=Xe({method:X(),params:ga.loose().optional()}),Wa=Xe({_meta:ED.optional()}),Ka=Xe({method:X(),params:Wa.loose().optional()}),Us=us({_meta:ED.optional()}),Hb=Br([X(),vr().int()]),wY=Xe({jsonrpc:pt(jb),id:Hb,...$s.shape}).strict(),SD=e=>wY.safeParse(e).success,TY=Xe({jsonrpc:pt(jb),...Ka.shape}).strict(),ACt=e=>TY.safeParse(e).success,_D=Xe({jsonrpc:pt(jb),id:Hb,result:Us}).strict(),Q0=e=>_D.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"})(zt||(zt={})),bD=Xe({jsonrpc:pt(jb),id:Hb.optional(),error:Xe({code:vr().int(),message:X(),data:Kr().optional()})}).strict(),xCt=e=>bD.safeParse(e).success,Sf=Br([wY,TY,_D,bD]),LPr=Br([_D,bD]),_f=Us.strict(),ICt=Wa.extend({requestId:Hb.optional(),reason:X().optional()}),CD=Ka.extend({method:pt("notifications/cancelled"),params:ICt}),RCt=Xe({src:X(),mimeType:X().optional(),sizes:Je(X()).optional(),theme:mi(["light","dark"]).optional()}),ev=Xe({icons:Je(RCt).optional()}),bf=Xe({name:X(),title:X().optional()}),EY=bf.extend({...bf.shape,...ev.shape,version:X(),websiteUrl:X().optional(),description:X().optional()}),MCt=LT(Xe({applyDefaults:Ur().optional()}),Cn(X(),Kr())),PCt=tI(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,LT(Xe({form:MCt.optional(),url:Fs.optional()}),Cn(X(),Kr()).optional())),DCt=us({list:Fs.optional(),cancel:Fs.optional(),requests:us({sampling:us({createMessage:Fs.optional()}).optional(),elicitation:us({create:Fs.optional()}).optional()}).optional()}),OCt=us({list:Fs.optional(),cancel:Fs.optional(),requests:us({tools:us({call:Fs.optional()}).optional()}).optional()}),NCt=Xe({experimental:Cn(X(),Fs).optional(),sampling:Xe({context:Fs.optional(),tools:Fs.optional()}).optional(),elicitation:PCt.optional(),roots:Xe({listChanged:Ur().optional()}).optional(),tasks:DCt.optional()}),LCt=ga.extend({protocolVersion:X(),capabilities:NCt,clientInfo:EY}),FCt=$s.extend({method:pt("initialize"),params:LCt}),$Ct=Xe({experimental:Cn(X(),Fs).optional(),logging:Fs.optional(),completions:Fs.optional(),prompts:Xe({listChanged:Ur().optional()}).optional(),resources:Xe({subscribe:Ur().optional(),listChanged:Ur().optional()}).optional(),tools:Xe({listChanged:Ur().optional()}).optional(),tasks:OCt.optional()}),SY=Us.extend({protocolVersion:X(),capabilities:$Ct,serverInfo:EY,instructions:X().optional()}),_Y=Ka.extend({method:pt("notifications/initialized"),params:Wa.optional()}),UCt=e=>_Y.safeParse(e).success,kD=$s.extend({method:pt("ping"),params:ga.optional()}),BCt=Xe({progress:vr(),total:Pn(vr()),message:Pn(X())}),zCt=Xe({...Wa.shape,...BCt.shape,progressToken:yY}),AD=Ka.extend({method:pt("notifications/progress"),params:zCt}),GCt=ga.extend({cursor:vY.optional()}),tv=$s.extend({params:GCt.optional()}),rv=Us.extend({nextCursor:vY.optional()}),qCt=mi(["working","input_required","completed","failed","cancelled"]),nv=Xe({taskId:X(),status:qCt,ttl:Br([vr(),NT()]),createdAt:X(),lastUpdatedAt:X(),pollInterval:Pn(vr()),statusMessage:Pn(X())}),ov=Us.extend({task:nv}),jCt=Wa.merge(nv),Vb=Ka.extend({method:pt("notifications/tasks/status"),params:jCt}),xD=$s.extend({method:pt("tasks/get"),params:ga.extend({taskId:X()})}),ID=Us.merge(nv),RD=$s.extend({method:pt("tasks/result"),params:ga.extend({taskId:X()})}),FPr=Us.loose(),MD=tv.extend({method:pt("tasks/list")}),PD=rv.extend({tasks:Je(nv)}),DD=$s.extend({method:pt("tasks/cancel"),params:ga.extend({taskId:X()})}),HCt=Us.merge(nv),bY=Xe({uri:X(),mimeType:Pn(X()),_meta:Cn(X(),Kr()).optional()}),CY=bY.extend({text:X()}),OD=X().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),kY=bY.extend({blob:OD}),sv=mi(["user","assistant"]),Cf=Xe({audience:Je(sv).optional(),priority:vr().min(0).max(1).optional(),lastModified:jx.datetime({offset:!0}).optional()}),AY=Xe({...bf.shape,...ev.shape,uri:X(),description:Pn(X()),mimeType:Pn(X()),annotations:Cf.optional(),_meta:Pn(us({}))}),VCt=Xe({...bf.shape,...ev.shape,uriTemplate:X(),description:Pn(X()),mimeType:Pn(X()),annotations:Cf.optional(),_meta:Pn(us({}))}),WCt=tv.extend({method:pt("resources/list")}),xY=rv.extend({resources:Je(AY)}),KCt=tv.extend({method:pt("resources/templates/list")}),IY=rv.extend({resourceTemplates:Je(VCt)}),ND=ga.extend({uri:X()}),JCt=ND,YCt=$s.extend({method:pt("resources/read"),params:JCt}),RY=Us.extend({contents:Je(Br([CY,kY]))}),MY=Ka.extend({method:pt("notifications/resources/list_changed"),params:Wa.optional()}),ZCt=ND,XCt=$s.extend({method:pt("resources/subscribe"),params:ZCt}),QCt=ND,ekt=$s.extend({method:pt("resources/unsubscribe"),params:QCt}),tkt=Wa.extend({uri:X()}),rkt=Ka.extend({method:pt("notifications/resources/updated"),params:tkt}),nkt=Xe({name:X(),description:Pn(X()),required:Pn(Ur())}),okt=Xe({...bf.shape,...ev.shape,description:Pn(X()),arguments:Pn(Je(nkt)),_meta:Pn(us({}))}),skt=tv.extend({method:pt("prompts/list")}),PY=rv.extend({prompts:Je(okt)}),ikt=ga.extend({name:X(),arguments:Cn(X(),X()).optional()}),akt=$s.extend({method:pt("prompts/get"),params:ikt}),LD=Xe({type:pt("text"),text:X(),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),FD=Xe({type:pt("image"),data:OD,mimeType:X(),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),$D=Xe({type:pt("audio"),data:OD,mimeType:X(),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),ckt=Xe({type:pt("tool_use"),name:X(),id:X(),input:Cn(X(),Kr()),_meta:Cn(X(),Kr()).optional()}),lkt=Xe({type:pt("resource"),resource:Br([CY,kY]),annotations:Cf.optional(),_meta:Cn(X(),Kr()).optional()}),ukt=AY.extend({type:pt("resource_link")}),UD=Br([LD,FD,$D,ukt,lkt]),dkt=Xe({role:sv,content:UD}),DY=Us.extend({description:X().optional(),messages:Je(dkt)}),OY=Ka.extend({method:pt("notifications/prompts/list_changed"),params:Wa.optional()}),mkt=Xe({title:X().optional(),readOnlyHint:Ur().optional(),destructiveHint:Ur().optional(),idempotentHint:Ur().optional(),openWorldHint:Ur().optional()}),pkt=Xe({taskSupport:mi(["required","optional","forbidden"]).optional()}),NY=Xe({...bf.shape,...ev.shape,description:X().optional(),inputSchema:Xe({type:pt("object"),properties:Cn(X(),Fs).optional(),required:Je(X()).optional()}).catchall(Kr()),outputSchema:Xe({type:pt("object"),properties:Cn(X(),Fs).optional(),required:Je(X()).optional()}).catchall(Kr()).optional(),annotations:mkt.optional(),execution:pkt.optional(),_meta:Cn(X(),Kr()).optional()}),hkt=tv.extend({method:pt("tools/list")}),LY=rv.extend({tools:Je(NY)}),Wb=Us.extend({content:Je(UD).default([]),structuredContent:Cn(X(),Kr()).optional(),isError:Ur().optional()}),$Pr=Wb.or(Us.extend({toolResult:Kr()})),fkt=X0.extend({name:X(),arguments:Cn(X(),Kr()).optional()}),gkt=$s.extend({method:pt("tools/call"),params:fkt}),FY=Ka.extend({method:pt("notifications/tools/list_changed"),params:Wa.optional()}),ykt=Xe({autoRefresh:Ur().default(!0),debounceMs:vr().int().nonnegative().default(300)}),$Y=mi(["debug","info","notice","warning","error","critical","alert","emergency"]),vkt=ga.extend({level:$Y}),wkt=$s.extend({method:pt("logging/setLevel"),params:vkt}),Tkt=Wa.extend({level:$Y,logger:X().optional(),data:Kr()}),Ekt=Ka.extend({method:pt("notifications/message"),params:Tkt}),Skt=Xe({name:X().optional()}),_kt=Xe({hints:Je(Skt).optional(),costPriority:vr().min(0).max(1).optional(),speedPriority:vr().min(0).max(1).optional(),intelligencePriority:vr().min(0).max(1).optional()}),bkt=Xe({mode:mi(["auto","required","none"]).optional()}),Ckt=Xe({type:pt("tool_result"),toolUseId:X().describe("The unique identifier for the corresponding tool call."),content:Je(UD).default([]),structuredContent:Xe({}).loose().optional(),isError:Ur().optional(),_meta:Cn(X(),Kr()).optional()}),kkt=Xx("type",[LD,FD,$D]),Kb=Xx("type",[LD,FD,$D,ckt,Ckt]),Akt=Xe({role:sv,content:Br([Kb,Je(Kb)]),_meta:Cn(X(),Kr()).optional()}),xkt=X0.extend({messages:Je(Akt),modelPreferences:_kt.optional(),systemPrompt:X().optional(),includeContext:mi(["none","thisServer","allServers"]).optional(),temperature:vr().optional(),maxTokens:vr().int(),stopSequences:Je(X()).optional(),metadata:Fs.optional(),tools:Je(NY).optional(),toolChoice:bkt.optional()}),UY=$s.extend({method:pt("sampling/createMessage"),params:xkt}),BY=Us.extend({model:X(),stopReason:Pn(mi(["endTurn","stopSequence","maxTokens"]).or(X())),role:sv,content:kkt}),zY=Us.extend({model:X(),stopReason:Pn(mi(["endTurn","stopSequence","maxTokens","toolUse"]).or(X())),role:sv,content:Br([Kb,Je(Kb)])}),Ikt=Xe({type:pt("boolean"),title:X().optional(),description:X().optional(),default:Ur().optional()}),Rkt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),minLength:vr().optional(),maxLength:vr().optional(),format:mi(["email","uri","date","date-time"]).optional(),default:X().optional()}),Mkt=Xe({type:mi(["number","integer"]),title:X().optional(),description:X().optional(),minimum:vr().optional(),maximum:vr().optional(),default:vr().optional()}),Pkt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),enum:Je(X()),default:X().optional()}),Dkt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),oneOf:Je(Xe({const:X(),title:X()})),default:X().optional()}),Okt=Xe({type:pt("string"),title:X().optional(),description:X().optional(),enum:Je(X()),enumNames:Je(X()).optional(),default:X().optional()}),Nkt=Br([Pkt,Dkt]),Lkt=Xe({type:pt("array"),title:X().optional(),description:X().optional(),minItems:vr().optional(),maxItems:vr().optional(),items:Xe({type:pt("string"),enum:Je(X())}),default:Je(X()).optional()}),Fkt=Xe({type:pt("array"),title:X().optional(),description:X().optional(),minItems:vr().optional(),maxItems:vr().optional(),items:Xe({anyOf:Je(Xe({const:X(),title:X()}))}),default:Je(X()).optional()}),$kt=Br([Lkt,Fkt]),Ukt=Br([Okt,Nkt,$kt]),Bkt=Br([Ukt,Ikt,Rkt,Mkt]),zkt=X0.extend({mode:pt("form").optional(),message:X(),requestedSchema:Xe({type:pt("object"),properties:Cn(X(),Bkt),required:Je(X()).optional()})}),Gkt=X0.extend({mode:pt("url"),message:X(),elicitationId:X(),url:X().url()}),qkt=Br([zkt,Gkt]),GY=$s.extend({method:pt("elicitation/create"),params:qkt}),jkt=Wa.extend({elicitationId:X()}),Hkt=Ka.extend({method:pt("notifications/elicitation/complete"),params:jkt}),qY=Us.extend({action:mi(["accept","decline","cancel"]),content:tI(e=>e===null?void 0:e,Cn(X(),Br([X(),vr(),Ur(),Je(X())])).optional())}),Vkt=Xe({type:pt("ref/resource"),uri:X()}),Wkt=Xe({type:pt("ref/prompt"),name:X()}),Kkt=ga.extend({ref:Br([Wkt,Vkt]),argument:Xe({name:X(),value:X()}),context:Xe({arguments:Cn(X(),X()).optional()}).optional()}),Jkt=$s.extend({method:pt("completion/complete"),params:Kkt}),jY=Us.extend({completion:us({values:Je(X()).max(100),total:Pn(vr().int()),hasMore:Pn(Ur())})}),Ykt=Xe({uri:X().startsWith("file://"),name:X().optional(),_meta:Cn(X(),Kr()).optional()}),Zkt=$s.extend({method:pt("roots/list"),params:ga.optional()}),Xkt=Us.extend({roots:Je(Ykt)}),Qkt=Ka.extend({method:pt("notifications/roots/list_changed"),params:Wa.optional()}),UPr=Br([kD,FCt,Jkt,wkt,akt,skt,WCt,KCt,YCt,XCt,ekt,gkt,hkt,xD,RD,MD,DD]),BPr=Br([CD,AD,_Y,Qkt,Vb]),zPr=Br([_f,BY,zY,qY,Xkt,ID,PD,ov]),GPr=Br([kD,UY,GY,Zkt,xD,RD,MD,DD]),qPr=Br([CD,AD,Ekt,rkt,MY,FY,OY,Vb,Hkt]),jPr=Br([_f,SY,jY,DY,PY,xY,IY,RY,Wb,LY,ID,PD,ov]),It=class Btr 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===zt.UrlElicitationRequired&&n){const o=n;if(o.elicitations)return new eAt(o.elicitations,r)}return new Btr(t,r,n)}},eAt=class extends It{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(zt.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}}});function HPr(e){return Sf.parse(JSON.parse(e))}function VPr(e){return JSON.stringify(e)+`
1433
1433
  `}var tAt,WPr=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"(){np(),tAt=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
1434
1434
  `);if(e===-1)return null;const t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),HPr(t)}clear(){this._buffer=void 0}}}});function KPr(){const e={};for(const t of nAt){const r=Gb.env[t];r!==void 0&&(r.startsWith("()")||(e[t]=r))}return e}function JPr(){return"type"in Gb}var rAt,nAt,HY,oAt=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"(){rAt=Bc(CPr(),1),OPr(),Ift(),WPr(),nAt=Gb.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],HY=class{constructor(e){this._readBuffer=new tAt,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Aft)}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,rAt.default)(this._serverParams.command,this._serverParams.args??[],{env:{...KPr(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:Gb.platform==="win32"&&JPr(),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=VPr(e);this._process.stdin.write(r)?t():this._process.stdin.once("drain",t)})}}}}),sAt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/parse.js"(){qo()}}),VY=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/schemas.js"(){qo(),gt(),sAt()}}),YPr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/checks.js"(){qo()}}),iAt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/iso.js"(){qo(),VY()}}),ZPr=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/coerce.js"(){qo(),VY()}}),aAt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/mini/external.js"(){qo(),sAt(),VY(),YPr(),qo(),OT(),N3(),iAt(),iAt(),ZPr()}}),cAt=S({"node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4-mini/index.js"(){aAt(),aAt()}});function BD(e){return!!e._zod}function op(e,t){return BD(e)?ex(e,t):e.safeParse(t)}function lAt(e){if(!e)return;let t;if(BD(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function XPr(e){if(BD(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 WY=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"(){UA(),cAt()}});function kf(e){return e==="completed"||e==="failed"||e==="cancelled"}var QPr=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 uAt(e){const r=lAt(e)?.method;if(!r)throw new Error("Schema is missing a method literal");const n=XPr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function dAt(e,t){const r=op(e,t);if(!r.success)throw r.error;return r.data}var e4r=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"(){cAt(),WY(),a$()}});function mAt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function t4r(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];mAt(i)&&mAt(s)?r[o]={...i,...s}:r[o]=s}return r}var pAt,hAt,r4r=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"(){WY(),np(),QPr(),e4r(),pAt=6e4,hAt=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(CD,t=>{this._oncancel(t)}),this.setNotificationHandler(AD,t=>{this._onprogress(t)}),this.setRequestHandler(kD,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xD,async(t,r)=>{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new It(zt.InvalidParams,"Failed to retrieve task: Task not found");return{...n}}),this.setRequestHandler(RD,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,c=a.id,l=this._requestResolvers.get(c);if(l)if(this._requestResolvers.delete(c),i.type==="response")l(a);else{const u=a,d=new It(u.error.code,u.error.message,u.error.data);l(d)}else{const u=i.type==="response"?"Response":"Error";this._onerror(new Error(`${u} handler missing for request ${c}`))}continue}await this._transport?.send(i.message,{relatedRequestId:r.requestId})}}const s=await this._taskStore.getTask(o,r.sessionId);if(!s)throw new It(zt.InvalidParams,`Task not found: ${o}`);if(!kf(s.status))return await this._waitForTaskUpdate(o,r.signal),await n();if(kf(s.status)){const i=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[rp]:{taskId:o}}}}return await n()};return await n()}),this.setRequestHandler(MD,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 It(zt.InvalidParams,`Failed to list tasks: ${n instanceof Error?n.message:String(n)}`)}}),this.setRequestHandler(DD,async(t,r)=>{try{const n=await this._taskStore.getTask(t.params.taskId,r.sessionId);if(!n)throw new It(zt.InvalidParams,`Task not found: ${t.params.taskId}`);if(kf(n.status))throw new It(zt.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 It(zt.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(n){throw n instanceof It?n:new It(zt.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),It.fromError(zt.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),Q0(o)||xCt(o)?this._onresponse(o):SD(o)?this._onrequest(o,s):ACt(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=It.fromError(zt.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?.[rp]?.taskId;if(r===void 0){const l={jsonrpc:"2.0",id:e.id,error:{code:zt.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},n?.sessionId).catch(u=>this._onerror(new Error(`Failed to enqueue error response: ${u}`))):n?.send(l).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=kCt(e.params)?e.params.task:void 0,a=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,c={signal:s.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;const u={relatedRequestId:e.id};o&&(u.relatedTask={taskId:o}),await this.notification(l,u)},sendRequest:async(l,u,d)=>{if(s.signal.aborted)throw new It(zt.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(l,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,c)).then(async l=>{if(s.signal.aborted)return;const u={result:l,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 l=>{if(s.signal.aborted)return;const u={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:zt.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},n?.sessionId):await n?.send(u)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).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),Q0(e))r(e);else{const s=new It(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(Q0(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),Q0(e))n(e);else{const s=It.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 It?s:new It(zt.InternalError,String(s))}}return}let o;try{const s=await this.request(e,ov,r);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new It(zt.InternalError,"Task creation did not return a task");for(;;){const i=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:i},kf(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,r)}:i.status==="failed"?yield{type:"error",error:new It(zt.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new It(zt.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(c=>setTimeout(c,a)),r?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof It?s:new It(zt.InternalError,String(s))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s,task:i,relatedTask:a}=r??{};return new Promise((c,l)=>{const u=w=>{l(w)};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(w){u(w);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||{},[rp]:a}});const h=w=>{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(w)}},{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`)));const E=w instanceof It?w:new It(zt.RequestTimeout,String(w));l(E)};this._responseHandlers.set(d,w=>{if(!r?.signal?.aborted){if(w instanceof Error)return l(w);try{const E=op(t,w.result);E.success?c(E.data):l(E.error)}catch(E){l(E)}}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});const f=r?.timeout??pAt,g=()=>h(It.fromError(zt.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(d,f,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);const y=a?.taskId;if(y){const w=E=>{const _=this._responseHandlers.get(d);_?_(E):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,w),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(E=>{this._cleanupTimeout(d),l(E)})}else this._transport.send(m,{relatedRequestId:n,resumptionToken:o,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(d),l(w)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},ID,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},PD,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},HCt,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||{},[rp]: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||{},[rp]: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||{},[rp]:t.relatedTask}}}),await this._transport.send(s,t)}setRequestHandler(e,t){const r=uAt(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(n,o)=>{const s=dAt(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=uAt(e);this._notificationHandlers.set(r,n=>{const o=dAt(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"&&SD(n.message)){const o=n.message.id,s=this._requestResolvers.get(o);s?(s(new It(zt.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 It(zt.InvalidRequest,"Request cancelled"));return}const s=setTimeout(n,r);t.addEventListener("abort",()=>{clearTimeout(s),o(new It(zt.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 It(zt.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=Vb.parse({method:"notifications/tasks/status",params:i});await this.notification(a),kf(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 It(zt.InvalidParams,`Task "${n}" not found - it may have been cleaned up`);if(kf(i.status))throw new It(zt.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 c=Vb.parse({method:"notifications/tasks/status",params:a});await this.notification(c),kf(a.status)&&this._cleanupTaskProgressHandler(n)}},listTasks:n=>r.listTasks(n,t)}}}}}),Af,_s,fAt,n4r,o4r,s4r,i4r,a4r,c4r,l4r,u4r,d4r,m4r,p4r,h4r,f4r,g4r,y4r,v4r,w4r,T4r,E4r,S4r,_4r,b4r,C4r,k4r,A4r,x4r,I4r,R4r,M4r,P4r,D4r,O4r,N4r,L4r,F4r,$4r,U4r,B4r,z4r,G4r,q4r,j4r,H4r,V4r,W4r,K4r,J4r=S({"npm-stub:ajv"(){Af={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Af.get}):new Proxy(function(...r){return new Proxy({},{get:Af.get})},{get:Af.get,apply(r,n,o){return new Proxy({},{get:Af.get})},construct(r,n){return new Proxy({},{get:Af.get})}})}},_s=new Proxy({},Af),fAt=_s,{BedrockClient:n4r,ListFoundationModelsCommand:o4r,BedrockRuntimeClient:s4r,ConverseCommand:i4r,ConverseStreamCommand:a4r,ImageFormat:c4r,InvokeModelCommand:l4r}=_s,{SageMakerRuntimeClient:u4r,InvokeEndpointCommand:d4r,InvokeEndpointWithResponseStreamCommand:m4r}=_s,{GoogleAuth:p4r,VertexAI:h4r,TextToSpeechClient:f4r}=_s,{Webhook:g4r}=_s,{Hippocampus:y4r,HippocampusConfig:v4r}=_s,{createClient:w4r}=_s,{Queue:T4r,Worker:E4r,Job:S4r,QueueScheduler:_4r,FlowProducer:b4r}=_s,{Cron:C4r}=_s,{parseBuffer:k4r,selectCover:A4r}=_s,{extractRawText:x4r,convertToHtml:I4r}=_s,{Hono:R4r}=_s,{cors:M4r,HTTPException:P4r,logger:D4r,secureHeaders:O4r,streamSSE:N4r,timeout:L4r}=_s,F4r=globalThis.fetch,$4r=globalThis.Request,U4r=globalThis.Response,B4r=globalThis.Headers,z4r=globalThis.FormData,G4r=globalThis.File,q4r=globalThis.Blob,j4r=_s.Agent,H4r=_s.Pool,V4r=_s.Client,W4r=_s.Dispatcher,K4r=_s.MockAgent}}),xf,bs,gAt,Y4r,Z4r,X4r,Q4r,eDr,tDr,rDr,nDr,oDr,sDr,iDr,aDr,cDr,lDr,uDr,dDr,mDr,pDr,hDr,fDr,gDr,yDr,vDr,wDr,TDr,EDr,SDr,_Dr,bDr,CDr,kDr,ADr,xDr,IDr,RDr,MDr,PDr,DDr,ODr,NDr,LDr,FDr,$Dr,UDr,BDr,zDr,GDr=S({"npm-stub:ajv-formats"(){xf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:xf.get}):new Proxy(function(...r){return new Proxy({},{get:xf.get})},{get:xf.get,apply(r,n,o){return new Proxy({},{get:xf.get})},construct(r,n){return new Proxy({},{get:xf.get})}})}},bs=new Proxy({},xf),gAt=bs,{BedrockClient:Y4r,ListFoundationModelsCommand:Z4r,BedrockRuntimeClient:X4r,ConverseCommand:Q4r,ConverseStreamCommand:eDr,ImageFormat:tDr,InvokeModelCommand:rDr}=bs,{SageMakerRuntimeClient:nDr,InvokeEndpointCommand:oDr,InvokeEndpointWithResponseStreamCommand:sDr}=bs,{GoogleAuth:iDr,VertexAI:aDr,TextToSpeechClient:cDr}=bs,{Webhook:lDr}=bs,{Hippocampus:uDr,HippocampusConfig:dDr}=bs,{createClient:mDr}=bs,{Queue:pDr,Worker:hDr,Job:fDr,QueueScheduler:gDr,FlowProducer:yDr}=bs,{Cron:vDr}=bs,{parseBuffer:wDr,selectCover:TDr}=bs,{extractRawText:EDr,convertToHtml:SDr}=bs,{Hono:_Dr}=bs,{cors:bDr,HTTPException:CDr,logger:kDr,secureHeaders:ADr,streamSSE:xDr,timeout:IDr}=bs,RDr=globalThis.fetch,MDr=globalThis.Request,PDr=globalThis.Response,DDr=globalThis.Headers,ODr=globalThis.FormData,NDr=globalThis.File,LDr=globalThis.Blob,FDr=bs.Agent,$Dr=bs.Pool,UDr=bs.Client,BDr=bs.Dispatcher,zDr=bs.MockAgent}});function qDr(){const e=new fAt({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return gAt(e),e}var yAt,jDr=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"(){J4r(),GDr(),yAt=class{constructor(e){this._ajv=e??qDr()}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)}}}}}),vAt,HDr=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"(){np(),vAt=class{constructor(e){this._client=e}async*callToolStream(e,t=Wb,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 c=a.result;if(!c.structuredContent&&!c.isError){yield{type:"error",error:new It(zt.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(c.structuredContent)try{const l=i(c.structuredContent);if(!l.valid){yield{type:"error",error:new It(zt.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof It){yield{type:"error",error:l};return}yield{type:"error",error:new It(zt.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};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 VDr(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 WDr(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 KDr=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 zD(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&&zD(s,r[o])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)typeof r!="boolean"&&zD(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)typeof r!="boolean"&&zD(r,t)}}function JDr(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 wAt,YDr=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"(){r4r(),np(),jDr(),WY(),HDr(),KDr(),wAt=class extends hAt{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 yAt,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",FY,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",OY,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",MY,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new vAt(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=t4r(this._capabilities,e)}setRequestHandler(e,t){const n=lAt(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let o;if(BD(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,c)=>{const l=op(GY,a);if(!l.success){const w=l.error instanceof Error?l.error.message:String(l.error);throw new It(zt.InvalidParams,`Invalid elicitation request: ${w}`)}const{params:u}=l.data;u.mode=u.mode??"form";const{supportsFormMode:d,supportsUrlMode:m}=JDr(this._capabilities.elicitation);if(u.mode==="form"&&!d)throw new It(zt.InvalidParams,"Client does not support form-mode elicitation requests");if(u.mode==="url"&&!m)throw new It(zt.InvalidParams,"Client does not support URL-mode elicitation requests");const h=await Promise.resolve(t(a,c));if(u.task){const w=op(ov,h);if(!w.success){const E=w.error instanceof Error?w.error.message:String(w.error);throw new It(zt.InvalidParams,`Invalid task creation result: ${E}`)}return w.data}const f=op(qY,h);if(!f.success){const w=f.error instanceof Error?f.error.message:String(f.error);throw new It(zt.InvalidParams,`Invalid elicitation result: ${w}`)}const g=f.data,y=u.mode==="form"?u.requestedSchema:void 0;if(u.mode==="form"&&g.action==="accept"&&g.content&&y&&this._capabilities.elicitation?.form?.applyDefaults)try{zD(y,g.content)}catch{}return g};return super.setRequestHandler(e,i)}if(s==="sampling/createMessage"){const i=async(a,c)=>{const l=op(UY,a);if(!l.success){const g=l.error instanceof Error?l.error.message:String(l.error);throw new It(zt.InvalidParams,`Invalid sampling request: ${g}`)}const{params:u}=l.data,d=await Promise.resolve(t(a,c));if(u.task){const g=op(ov,d);if(!g.success){const y=g.error instanceof Error?g.error.message:String(g.error);throw new It(zt.InvalidParams,`Invalid task creation result: ${y}`)}return g.data}const h=u.tools||u.toolChoice?zY:BY,f=op(h,d);if(!f.success){const g=f.error instanceof Error?f.error.message:String(f.error);throw new It(zt.InvalidParams,`Invalid sampling result: ${g}`)}return f.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:qb,capabilities:this._capabilities,clientInfo:this._clientInfo}},SY,t);if(r===void 0)throw new Error(`Server sent invalid initialize result: ${r}`);if(!_Ct.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){VDr(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&WDr(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},_f,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},jY,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},_f,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},DY,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},PY,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},xY,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},IY,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},RY,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},_f,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},_f,t)}async callTool(e,t=Wb,r){if(this.isToolTaskRequired(e.name))throw new It(zt.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 It(zt.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 It(zt.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof It?s:new It(zt.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},LY,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const o=ykt.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,c=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)}},l=()=>{if(i){const u=this._listChangedDebounceTimers.get(e);u&&clearTimeout(u);const d=setTimeout(c,i);this._listChangedDebounceTimers.set(e,d)}else c()};this.setNotificationHandler(t,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}}});function ZDr(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function KY(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(KY).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${KY(e.cause)}`:e.message:`${e}`}function TAt(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}function XDr(){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 JY,YY,GD,ir,os,Nn,cu,ya,If,iv,qD,jD,Jb,av,Yb,sp,cv,lv,uv,Zb,ul,ZY,XY,QY,EAt,eZ,tZ,Xb,rZ,nZ,Qb,QDr=S({"node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js"(){D9(),JY=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(TAt(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(TAt(this),t)}},YY=e=>{throw TypeError(e)},GD=(e,t,r)=>t.has(e)||YY("Cannot "+r),ir=(e,t,r)=>(GD(e,t,"read from private field"),r?r.call(e):t.get(e)),os=(e,t,r)=>t.has(e)?YY("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Nn=(e,t,r,n)=>(GD(e,t,"write to private field"),t.set(e,r),r),cu=(e,t,r)=>(GD(e,t,"access private method"),r),Qb=class extends EventTarget{constructor(e,t){var r,n;super(),os(this,ul),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,os(this,ya),os(this,If),os(this,iv),os(this,qD),os(this,jD),os(this,Jb),os(this,av),os(this,Yb,null),os(this,sp),os(this,cv),os(this,lv,null),os(this,uv,null),os(this,Zb,null),os(this,XY,async o=>{var s;ir(this,cv).reset();const{body:i,redirected:a,status:c,headers:l}=o;if(c===204){cu(this,ul,Xb).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(a?Nn(this,iv,new URL(o.url)):Nn(this,iv,void 0),c!==200){cu(this,ul,Xb).call(this,`Non-200 status code (${c})`,c);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){cu(this,ul,Xb).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(ir(this,ya)===this.CLOSED)return;Nn(this,ya,this.OPEN);const u=new Event("open");if((s=ir(this,Zb))==null||s.call(this,u),this.dispatchEvent(u),typeof i!="object"||!i||!("getReader"in i)){cu(this,ul,Xb).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const d=new TextDecoder,m=i.getReader();let h=!0;do{const{done:f,value:g}=await m.read();g&&ir(this,cv).feed(d.decode(g,{stream:!f})),f&&(h=!1,ir(this,cv).reset(),cu(this,ul,rZ).call(this))}while(h)}),os(this,QY,o=>{Nn(this,sp,void 0),!(o.name==="AbortError"||o.type==="aborted")&&cu(this,ul,rZ).call(this,KY(o))}),os(this,eZ,o=>{typeof o.id=="string"&&Nn(this,Yb,o.id);const s=new MessageEvent(o.event||"message",{data:o.data,origin:ir(this,iv)?ir(this,iv).origin:ir(this,If).origin,lastEventId:o.id||""});ir(this,uv)&&(!o.event||o.event==="message")&&ir(this,uv).call(this,s),this.dispatchEvent(s)}),os(this,tZ,o=>{Nn(this,Jb,o)}),os(this,nZ,()=>{Nn(this,av,void 0),ir(this,ya)===this.CONNECTING&&cu(this,ul,ZY).call(this)});try{if(e instanceof URL)Nn(this,If,e);else if(typeof e=="string")Nn(this,If,new URL(e,XDr()));else throw new Error("Invalid URL")}catch{throw ZDr("An invalid or illegal string was specified")}Nn(this,cv,R9({onEvent:ir(this,eZ),onRetry:ir(this,tZ)})),Nn(this,ya,this.CONNECTING),Nn(this,Jb,3e3),Nn(this,jD,(r=t?.fetch)!=null?r:globalThis.fetch),Nn(this,qD,(n=t?.withCredentials)!=null?n:!1),cu(this,ul,ZY).call(this)}get readyState(){return ir(this,ya)}get url(){return ir(this,If).href}get withCredentials(){return ir(this,qD)}get onerror(){return ir(this,lv)}set onerror(e){Nn(this,lv,e)}get onmessage(){return ir(this,uv)}set onmessage(e){Nn(this,uv,e)}get onopen(){return ir(this,Zb)}set onopen(e){Nn(this,Zb,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(){ir(this,av)&&clearTimeout(ir(this,av)),ir(this,ya)!==this.CLOSED&&(ir(this,sp)&&ir(this,sp).abort(),Nn(this,ya,this.CLOSED),Nn(this,sp,void 0))}},ya=new WeakMap,If=new WeakMap,iv=new WeakMap,qD=new WeakMap,jD=new WeakMap,Jb=new WeakMap,av=new WeakMap,Yb=new WeakMap,sp=new WeakMap,cv=new WeakMap,lv=new WeakMap,uv=new WeakMap,Zb=new WeakMap,ul=new WeakSet,ZY=function(){Nn(this,ya,this.CONNECTING),Nn(this,sp,new AbortController),ir(this,jD)(ir(this,If),cu(this,ul,EAt).call(this)).then(ir(this,XY)).catch(ir(this,QY))},XY=new WeakMap,QY=new WeakMap,EAt=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...ir(this,Yb)?{"Last-Event-ID":ir(this,Yb)}:void 0},cache:"no-store",signal:(e=ir(this,sp))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},eZ=new WeakMap,tZ=new WeakMap,Xb=function(e,t){var r;ir(this,ya)!==this.CLOSED&&Nn(this,ya,this.CLOSED);const n=new JY("error",{code:t,message:e});(r=ir(this,lv))==null||r.call(this,n),this.dispatchEvent(n)},rZ=function(e,t){var r;if(ir(this,ya)===this.CLOSED)return;Nn(this,ya,this.CONNECTING);const n=new JY("error",{code:t,message:e});(r=ir(this,lv))==null||r.call(this,n),this.dispatchEvent(n),Nn(this,av,setTimeout(ir(this,nZ),ir(this,Jb)))},nZ=new WeakMap,Qb.CONNECTING=0,Qb.OPEN=1,Qb.CLOSED=2}});function HD(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function SAt(e=fetch,t){return t?async(r,n)=>{const o={...t,...n,headers:n?.headers?{...HD(t.headers),...HD(n.headers)}:t.headers};return e(r,o)}:e}var _At=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"(){}}),Rf,Cs,bAt,eOr,tOr,rOr,nOr,oOr,sOr,iOr,aOr,cOr,lOr,uOr,dOr,mOr,pOr,hOr,fOr,gOr,yOr,vOr,wOr,TOr,EOr,SOr,_Or,bOr,COr,kOr,AOr,xOr,IOr,ROr,MOr,POr,DOr,OOr,NOr,LOr,FOr,$Or,UOr,BOr,zOr,GOr,qOr,jOr,HOr,VOr=S({"npm-stub:pkce-challenge"(){Rf={get(e,t){return t==="__esModule"?!0:t==="default"?new Proxy({},{get:Rf.get}):new Proxy(function(...r){return new Proxy({},{get:Rf.get})},{get:Rf.get,apply(r,n,o){return new Proxy({},{get:Rf.get})},construct(r,n){return new Proxy({},{get:Rf.get})}})}},Cs=new Proxy({},Rf),bAt=Cs,{BedrockClient:eOr,ListFoundationModelsCommand:tOr,BedrockRuntimeClient:rOr,ConverseCommand:nOr,ConverseStreamCommand:oOr,ImageFormat:sOr,InvokeModelCommand:iOr}=Cs,{SageMakerRuntimeClient:aOr,InvokeEndpointCommand:cOr,InvokeEndpointWithResponseStreamCommand:lOr}=Cs,{GoogleAuth:uOr,VertexAI:dOr,TextToSpeechClient:mOr}=Cs,{Webhook:pOr}=Cs,{Hippocampus:hOr,HippocampusConfig:fOr}=Cs,{createClient:gOr}=Cs,{Queue:yOr,Worker:vOr,Job:wOr,QueueScheduler:TOr,FlowProducer:EOr}=Cs,{Cron:SOr}=Cs,{parseBuffer:_Or,selectCover:bOr}=Cs,{extractRawText:COr,convertToHtml:kOr}=Cs,{Hono:AOr}=Cs,{cors:xOr,HTTPException:IOr,logger:ROr,secureHeaders:MOr,streamSSE:POr,timeout:DOr}=Cs,OOr=globalThis.fetch,NOr=globalThis.Request,LOr=globalThis.Response,FOr=globalThis.Headers,$Or=globalThis.FormData,UOr=globalThis.File,BOr=globalThis.Blob,zOr=Cs.Agent,GOr=Cs.Pool,qOr=Cs.Client,jOr=Cs.Dispatcher,HOr=Cs.MockAgent}}),Bs,CAt,oZ,kAt,AAt,xAt,IAt,sZ,RAt,MAt,PAt,WOr,KOr,DAt=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"(){SCt(),Bs=u6().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:k6.custom,message:"URL must be parseable",fatal:!0}),jA}).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"}),CAt=us({resource:X().url(),authorization_servers:Je(Bs).optional(),jwks_uri:X().url().optional(),scopes_supported:Je(X()).optional(),bearer_methods_supported:Je(X()).optional(),resource_signing_alg_values_supported:Je(X()).optional(),resource_name:X().optional(),resource_documentation:X().optional(),resource_policy_uri:X().url().optional(),resource_tos_uri:X().url().optional(),tls_client_certificate_bound_access_tokens:Ur().optional(),authorization_details_types_supported:Je(X()).optional(),dpop_signing_alg_values_supported:Je(X()).optional(),dpop_bound_access_tokens_required:Ur().optional()}),oZ=us({issuer:X(),authorization_endpoint:Bs,token_endpoint:Bs,registration_endpoint:Bs.optional(),scopes_supported:Je(X()).optional(),response_types_supported:Je(X()),response_modes_supported:Je(X()).optional(),grant_types_supported:Je(X()).optional(),token_endpoint_auth_methods_supported:Je(X()).optional(),token_endpoint_auth_signing_alg_values_supported:Je(X()).optional(),service_documentation:Bs.optional(),revocation_endpoint:Bs.optional(),revocation_endpoint_auth_methods_supported:Je(X()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Je(X()).optional(),introspection_endpoint:X().optional(),introspection_endpoint_auth_methods_supported:Je(X()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Je(X()).optional(),code_challenge_methods_supported:Je(X()).optional(),client_id_metadata_document_supported:Ur().optional()}),kAt=us({issuer:X(),authorization_endpoint:Bs,token_endpoint:Bs,userinfo_endpoint:Bs.optional(),jwks_uri:Bs,registration_endpoint:Bs.optional(),scopes_supported:Je(X()).optional(),response_types_supported:Je(X()),response_modes_supported:Je(X()).optional(),grant_types_supported:Je(X()).optional(),acr_values_supported:Je(X()).optional(),subject_types_supported:Je(X()),id_token_signing_alg_values_supported:Je(X()),id_token_encryption_alg_values_supported:Je(X()).optional(),id_token_encryption_enc_values_supported:Je(X()).optional(),userinfo_signing_alg_values_supported:Je(X()).optional(),userinfo_encryption_alg_values_supported:Je(X()).optional(),userinfo_encryption_enc_values_supported:Je(X()).optional(),request_object_signing_alg_values_supported:Je(X()).optional(),request_object_encryption_alg_values_supported:Je(X()).optional(),request_object_encryption_enc_values_supported:Je(X()).optional(),token_endpoint_auth_methods_supported:Je(X()).optional(),token_endpoint_auth_signing_alg_values_supported:Je(X()).optional(),display_values_supported:Je(X()).optional(),claim_types_supported:Je(X()).optional(),claims_supported:Je(X()).optional(),service_documentation:X().optional(),claims_locales_supported:Je(X()).optional(),ui_locales_supported:Je(X()).optional(),claims_parameter_supported:Ur().optional(),request_parameter_supported:Ur().optional(),request_uri_parameter_supported:Ur().optional(),require_request_uri_registration:Ur().optional(),op_policy_uri:Bs.optional(),op_tos_uri:Bs.optional(),client_id_metadata_document_supported:Ur().optional()}),AAt=Xe({...kAt.shape,...oZ.pick({code_challenge_methods_supported:!0}).shape}),xAt=Xe({access_token:X(),id_token:X().optional(),token_type:X(),expires_in:x6.number().optional(),scope:X().optional(),refresh_token:X().optional()}).strip(),IAt=Xe({error:X(),error_description:X().optional(),error_uri:X().optional()}),sZ=Bs.optional().or(pt("").transform(()=>{})),RAt=Xe({redirect_uris:Je(Bs),token_endpoint_auth_method:X().optional(),grant_types:Je(X()).optional(),response_types:Je(X()).optional(),client_name:X().optional(),client_uri:Bs.optional(),logo_uri:sZ,scope:X().optional(),contacts:Je(X()).optional(),tos_uri:sZ,policy_uri:X().optional(),jwks_uri:Bs.optional(),jwks:d6().optional(),software_id:X().optional(),software_version:X().optional(),software_statement:X().optional()}).strip(),MAt=Xe({client_id:X(),client_secret:X().optional(),client_id_issued_at:vr().optional(),client_secret_expires_at:vr().optional()}).strip(),PAt=RAt.merge(MAt),WOr=Xe({error:X(),error_description:X().optional()}).strip(),KOr=Xe({token:X(),token_type_hint:X().optional()}).strip()}});function JOr(e){const t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function YOr({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 ZOr=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"(){}}),ks,VD,eC,tC,rC,WD,KD,JD,Mf,YD,ZD,XD,QD,eO,tO,nC,rO,nO,OAt,XOr=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"(){ks=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}},VD=class extends ks{},VD.errorCode="invalid_request",eC=class extends ks{},eC.errorCode="invalid_client",tC=class extends ks{},tC.errorCode="invalid_grant",rC=class extends ks{},rC.errorCode="unauthorized_client",WD=class extends ks{},WD.errorCode="unsupported_grant_type",KD=class extends ks{},KD.errorCode="invalid_scope",JD=class extends ks{},JD.errorCode="access_denied",Mf=class extends ks{},Mf.errorCode="server_error",YD=class extends ks{},YD.errorCode="temporarily_unavailable",ZD=class extends ks{},ZD.errorCode="unsupported_response_type",XD=class extends ks{},XD.errorCode="unsupported_token_type",QD=class extends ks{},QD.errorCode="invalid_token",eO=class extends ks{},eO.errorCode="method_not_allowed",tO=class extends ks{},tO.errorCode="too_many_requests",nC=class extends ks{},nC.errorCode="invalid_client_metadata",rO=class extends ks{},rO.errorCode="insufficient_scope",nO=class extends ks{},nO.errorCode="invalid_target",OAt={[VD.errorCode]:VD,[eC.errorCode]:eC,[tC.errorCode]:tC,[rC.errorCode]:rC,[WD.errorCode]:WD,[KD.errorCode]:KD,[JD.errorCode]:JD,[Mf.errorCode]:Mf,[YD.errorCode]:YD,[ZD.errorCode]:ZD,[XD.errorCode]:XD,[QD.errorCode]:QD,[eO.errorCode]:eO,[tO.errorCode]:tO,[nC.errorCode]:nC,[rO.errorCode]:rO,[nO.errorCode]:nO}}});function QOr(e){return["client_secret_basic","client_secret_post","none"].includes(e)}function eNr(e,t){const r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&QOr(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 tNr(e,t,r,n){const{client_id:o,client_secret:s}=t;switch(e){case"client_secret_basic":rNr(o,s,r);return;case"client_secret_post":nNr(o,s,n);return;case"none":oNr(o,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function rNr(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 nNr(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}function oNr(e,t){t.set("client_id",e)}async function NAt(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const n=IAt.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=OAt[o]||Mf;return new a(s||"",i)}catch(n){const o=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Mf(o)}}async function Pf(e,t){try{return await iZ(e,t)}catch(r){if(r instanceof eC||r instanceof rC)return await e.invalidateCredentials?.("all"),await iZ(e,t);if(r instanceof tC)return await e.invalidateCredentials?.("tokens"),await iZ(e,t);throw r}}async function iZ(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){const i=await e.discoveryState?.();let a,c,l,u=o;if(!u&&i?.resourceMetadataUrl&&(u=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,l=i.authorizationServerMetadata??await $At(c,{fetchFn:s}),!a)try{a=await LAt(t,{resourceMetadataUrl:u},s)}catch{}(l!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}else{const _=await dNr(t,{resourceMetadataUrl:u,fetchFn:s});c=_.authorizationServerUrl,l=_.authorizationServerMetadata,a=_.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:a,authorizationServerMetadata:l})}const d=await iNr(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 _=l?.client_id_metadata_document_supported===!0,C=e.clientMetadataUrl;if(C&&!sNr(C))throw new nC(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${C}`);if(_&&C)h={client_id:C},await e.saveClientInformation?.(h);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const b=await gNr(c,{metadata:l,clientMetadata:e.clientMetadata,scope:m,fetchFn:s});await e.saveClientInformation(b),h=b}}const f=!e.redirectUrl;if(r!==void 0||f){const _=await fNr(e,c,{metadata:l,resource:d,authorizationCode:r,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}const g=await e.tokens();if(g?.refresh_token)try{const _=await hNr(c,{metadata:l,clientInformation:h,refreshToken:g.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(_),"AUTHORIZED"}catch(_){if(!(!(_ instanceof ks)||_ instanceof Mf))throw _}const y=e.state?await e.state():void 0,{authorizationUrl:w,codeVerifier:E}=await mNr(c,{metadata:l,clientInformation:h,state:y,redirectUrl:e.redirectUrl,scope:m,resource:d});return await e.saveCodeVerifier(E),await e.redirectToAuthorization(w),"REDIRECT"}function sNr(e){if(!e)return!1;try{const t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function iNr(e,t,r){const n=JOr(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!YOr({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 oO(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};const o=aZ(e,"resource_metadata")||void 0;let s;if(o)try{s=new URL(o)}catch{}const i=aZ(e,"scope")||void 0,a=aZ(e,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function aZ(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 LAt(e,t,r=fetch){const n=await lNr(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 CAt.parse(await n.json())}async function cZ(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?cZ(e,void 0,r):void 0;throw n}}function aNr(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function FAt(e,t,r=fetch){return await cZ(e,{"MCP-Protocol-Version":t},r)}function cNr(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function lNr(e,t,r,n){const o=new URL(e),s=n?.protocolVersion??qb;let i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{const c=aNr(t,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await FAt(i,s,r);if(!n?.metadataUrl&&cNr(a,o.pathname)){const c=new URL(`/.well-known/${t}`,o);a=await FAt(c,s,r)}return a}function uNr(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 $At(e,{fetchFn:t=fetch,protocolVersion:r=qb}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},o=uNr(e);for(const{url:s,type:i}of o){const a=await cZ(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"?oZ.parse(await a.json()):AAt.parse(await a.json())}}}async function dNr(e,t){let r,n;try{r=await LAt(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 $At(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function mNr(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(sO))throw new Error(`Incompatible auth server: does not support response type ${sO}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(iO))throw new Error(`Incompatible auth server: does not support code challenge method ${iO}`)}else a=new URL("/authorize",e);const c=await bAt(),l=c.code_verifier,u=c.code_challenge;return a.searchParams.set("response_type",sO),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",u),a.searchParams.set("code_challenge_method",iO),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:l}}function pNr(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function UAt(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),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,a,t);else if(n){const u=t?.token_endpoint_auth_methods_supported??[],d=eNr(n,u);tNr(d,n,c,r)}const l=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!l.ok)throw await NAt(l);return xAt.parse(await l.json())}async function hNr(e,{metadata:t,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await UAt(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function fNr(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 l=await e.codeVerifier();a=pNr(o,l,e.redirectUrl)}const c=await e.clientInformation();return UAt(t,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:s})}async function gNr(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 NAt(i);return PAt.parse(await i.json())}var xc,sO,iO,BAt=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"(){VOr(),np(),DAt(),DAt(),ZOr(),XOr(),xc=class extends Error{constructor(e){super(e??"Unauthorized")}},sO="code",iO="S256"}}),zAt,GAt,yNr=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"(){QDr(),_At(),np(),BAt(),zAt=class extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}},GAt=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=SAt(t?.fetch,t?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new xc("No auth provider");let e;try{e=await Pf(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 xc;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=HD(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 Qb(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:c}=oO(i);this._resourceMetadataUrl=a,this._scope=c}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 zAt(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=Sf.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 xc("No auth provider");if(await Pf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new xc("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}=oO(n);if(this._resourceMetadataUrl=s,this._scope=i,await Pf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new xc;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}}}}),qAt,jAt,vNr=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"(){np(),qAt="mcp",jAt=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,qAt),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=Sf.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()})}}}}),HAt,wNr=S({"node_modules/.pnpm/eventsource-parser@3.0.8/node_modules/eventsource-parser/dist/stream.js"(){D9(),HAt=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:r}={}){let n;super({start(o){n=R9({onEvent:s=>{o.enqueue(s)},onError(s){e==="terminate"?o.error(s):typeof e=="function"&&e(s)},onRetry:t,onComment:r})},transform(o){n.feed(o)}})}}}}),VAt,Df,WAt,TNr=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"(){_At(),np(),BAt(),wNr(),VAt={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Df=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},WAt=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=SAt(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??VAt}async _authThenStart(){if(!this._authProvider)throw new xc("No auth provider");let e;try{e=await Pf(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 xc;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=HD(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 Df(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 l=e.pipeThrough(new TextDecoderStream).pipeThrough(new HAt({onRetry:m=>{this._serverRetryMs=m}})).getReader();for(;;){const{value:m,done:h}=await l.read();if(h)break;if(m.id&&(s=m.id,i=!0,n?.(m.id)),!!m.data&&(!m.event||m.event==="message"))try{const f=Sf.parse(JSON.parse(m.data));Q0(f)&&(a=!0,o!==void 0&&(f.id=o)),this.onmessage?.(f)}catch(f){this.onerror?.(f)}}(r||i)&&!a&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:n,replayMessageId:o},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(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 xc("No auth provider");if(await Pf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new xc("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:SD(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 Df(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:m,scope:h}=oO(i);if(this._resourceMetadataUrl=m,this._scope=h,await Pf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new xc;return this._hasCompletedAuthFlow=!0,this.send(e)}if(i.status===403&&this._authProvider){const{resourceMetadataUrl:m,scope:h,error:f}=oO(i);if(f==="insufficient_scope"){const g=i.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===g)throw new Df(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),m&&(this._resourceMetadataUrl=m),this._lastUpscopingHeader=g??void 0,await Pf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new xc;return this.send(e)}}throw new Df(i.status,`Error POSTing to endpoint: ${d}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,i.status===202){await i.body?.cancel(),UCt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(d=>this.onerror?.(d));return}const l=(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(l)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=>Sf.parse(h)):[Sf.parse(d)];for(const h of m)this.onmessage?.(h)}else throw await i.body?.cancel(),new Df(-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 Df(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})}}}}),KAt,lZ,uZ,oC,dZ=S({"src/lib/mcp/mcpCircuitBreaker.ts"(){"use strict";An(),Zt(),U(),lt(),lt(),KAt=Math.max(1e4,Number(process.env.MCP_OPERATION_TIMEOUT)||6e4),lZ=class extends qr{constructor(e,t={}){super(),this.name=e,this.config={failureThreshold:t.failureThreshold??5,resetTimeout:t.resetTimeout??6e4,halfOpenMaxCalls:t.halfOpenMaxCalls??3,operationTimeout:t.operationTimeout??KAt,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 tm({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 tm({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=ut.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;te.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=ut.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})),te.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&&te.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,te.debug(`[CircuitBreaker:${this.name}] Cleanup timer cleared`)),this.removeAllListeners(),this.callHistory=[],te.debug(`[CircuitBreaker:${this.name}] Destroyed and cleaned up`)}},uZ=class{breakers=new Map;getBreaker(e,t){if(!this.breakers.has(e)){const n=new lZ(e,t);this.breakers.set(e,n),te.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),te.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();te.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(),te.info("[CircuitBreakerManager] Destroyed all circuit breakers")}},oC=new uZ}});function ENr(e){return new Promise(t=>setTimeout(t,e))}function aO(e,t=lu){return t.retryableStatusCodes.includes(e)}function JAt(e,t=lu){if(!e||typeof e!="object")return!1;const r=e;if(nr(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"?aO(r.status,t):r.response&&typeof r.response=="object"&&typeof r.response.status=="number"?aO(r.response.status,t):typeof r.statusCode=="number"?aO(r.statusCode,t):!1}async function YAt(e,t={}){const r={...lu,...t},{traceId:n,parentSpanId:o}=xy(),s=Se.createSpan("mcp.transport","mcp.retry",{"mcp.transport":"http","mcp.operation":"retry","mcp.maxAttempts":r.maxAttempts},o,n),i=Date.now();let a,c=0;for(let u=1;u<=r.maxAttempts;u++){c=u;try{const d=await e();s.durationMs=Date.now()-i,s.attributes["mcp.retryAttempt"]=u;const m=Se.endSpan(s,1);return ot().recordSpan(m),d}catch(d){if(a=d,u===r.maxAttempts){p.debug(`HTTP retry: All ${r.maxAttempts} attempts exhausted`);break}if(!JAt(d,r)){p.debug("HTTP retry: Non-retryable error encountered",d instanceof Error?d.message:String(d));break}const m=tKe(u,r.initialDelay,r.backoffMultiplier,r.maxDelay,!0),h=d instanceof Error?d.message:String(d);p.warn(`HTTP retry: Attempt ${u}/${r.maxAttempts} failed: ${h}. Retrying in ${Math.round(m)}ms...`),await ENr(m)}}s.durationMs=Date.now()-i,s.attributes["mcp.retryAttempt"]=c;const l=Se.endSpan(s,2);throw l.statusMessage=a instanceof Error?a.message:String(a),ot().recordSpan(l),a}var lu,ZAt=S({"src/lib/mcp/httpRetryHandler.ts"(){"use strict";tt(),iKe(),U(),zn(),Iy(),lu={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:[408,429,500,502,503,504]}}}),mZ,pZ,hZ,fZ,XAt=S({"src/lib/mcp/httpRateLimiter.ts"(){"use strict";U(),K6(),zn(),Iy(),mZ={requestsPerWindow:60,windowMs:6e4,useTokenBucket:!0,refillRate:1,maxBurst:10},pZ=class{tokens;lastRefill;config;waitQueue=[];processingQueue=!1;constructor(e={}){this.config={...mZ,...e},this.tokens=this.config.maxBurst,this.lastRefill=Date.now(),te.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&&te.debug(`[HTTPRateLimiter] Refilled tokens: ${o.toFixed(2)} -> ${this.tokens.toFixed(2)} (+${n.toFixed(2)})`)}}async acquire(){const{traceId:e,parentSpanId:t}=xy(),r=Se.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=Se.endSpan(r,1);ot().recordSpan(s);return}await new Promise((s,i)=>{this.waitQueue.push({resolve:s,reject:i}),te.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=Se.endSpan(r,1);ot().recordSpan(o)}catch(o){r.durationMs=Date.now()-n;const s=Se.endSpan(r,2);throw s.statusMessage=o instanceof Error?o.message:String(o),ot().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,te.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));te.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,te.debug(`[HTTPRateLimiter] Token acquired, remaining: ${this.tokens.toFixed(2)}`),!0):(te.debug(`[HTTPRateLimiter] No tokens available, current: ${this.tokens.toFixed(2)}`),!1)}handleRateLimitResponse(e){const t=fE(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 te.info(`[HTTPRateLimiter] Server requested retry at ${i.toISOString()} (${t}ms)`),t}else return te.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 te.info(`[HTTPRateLimiter] Rate limit resets at ${new Date(i).toISOString()} (${t}ms)`),t}}return e.get("X-RateLimit-Remaining")==="0"&&t!==void 0?(te.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"))}te.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),te.info("[HTTPRateLimiter] Configuration updated:",e)}getConfig(){return{...this.config}}},hZ=class{limiters=new Map;getLimiter(e,t){let r=this.limiters.get(e);return r?t&&r.updateConfig(t):(r=new pZ(t),this.limiters.set(e,r),te.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),te.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();te.info("[RateLimiterManager] Reset all rate limiters")}destroyAll(){for(const e of this.limiters.values())e.reset();this.limiters.clear(),te.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}}},fZ=new hZ}});function QAt(e,t=60){if(!e.expiresAt)return!1;const r=t*1e3,n=Date.now();return e.expiresAt-r<=n}function gZ(e){return Date.now()+e*1e3}var cO,ext,txt=S({"src/lib/mcp/auth/tokenStorage.ts"(){"use strict";U(),cO=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())}},ext=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(()=>(Fo(),_h))).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"&&p.warn(`[FileTokenStorage] Error loading tokens: ${e.message}`),this.tokens=new Map,this.loaded=!0}}async saveToFile(){try{const e=await Promise.resolve().then(()=>(Fo(),_h)),r=(await Promise.resolve().then(()=>(pr(),pm))).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 p.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 SNr(e,t){return new lO({clientId:e.clientId,clientSecret:e.clientSecret,authorizationUrl:e.authorizationUrl,tokenUrl:e.tokenUrl,redirectUrl:e.redirectUrl,scope:e.scope,usePKCE:e.usePKCE??!0},t)}var Of,lO,_Nr=S({"src/lib/mcp/auth/oauthClientProvider.ts"(){"use strict";Dt(),txt(),U(),tt(),Of=3e4,lO=class{config;storage;pendingChallenges=new Map;pendingStates=new Set;constructor(e,t){this.config={...e,usePKCE:e.usePKCE??!0},this.storage=t??new cO}async tokens(e){const t=await this.storage.getTokens(e);if(!t)return null;if(QAt(t)){if(t.refreshToken)try{return await this.refreshTokens(e,t.refreshToken)}catch(r){return p.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 Be(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:n.toString()}),Of,new Error(`OAuth token exchange timed out after ${Of}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?gZ(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 Be(fetch(this.config.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:r.toString()}),Of,new Error(`OAuth token refresh timed out after ${Of}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?gZ(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 Be(fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n.toString()}),Of,new Error(`OAuth token revocation timed out after ${Of}ms`))}catch(o){p.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 Hp(32).toString("base64url")}generatePKCE(){const e=Hp(32).toString("base64url"),t=zl("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()}}}}),rxt=S({"src/lib/mcp/auth/index.ts"(){"use strict";txt(),_Nr()}}),nxt={};ne(nxt,{MCPClientFactory:()=>dv});var oxt,yZ,sxt,vZ,dv,wZ=S({"src/lib/mcp/mcpClientFactory.ts"(){"use strict";YDr(),oAt(),yNr(),vNr(),TNr(),U(),dZ(),lt(),ZAt(),XAt(),rxt(),zn(),Iy(),oxt=Math.max(5e3,Number(process.env.MCP_CLIENT_TIMEOUT)||6e4),yZ=20,sxt=class{lines=[];partial="";append(e){this.partial+=e.toString();const t=this.partial.split(/\r?\n/);this.partial=t.pop()??"";for(const r of t)r.trim().length!==0&&(this.lines.push(r),this.lines.length>yZ&&this.lines.shift())}snapshot(){const e=[...this.lines];return this.partial.trim().length>0&&e.push(this.partial),e.slice(-yZ)}},vZ=new WeakMap,dv=class{static NEUROLINK_IMPLEMENTATION={name:"neurolink-sdk",version:"1.0.0"};static DEFAULT_CAPABILITIES={sampling:{},roots:{listChanged:!1}};static async createClient(e,t=oxt){const r=Date.now(),{traceId:n,parentSpanId:o}=xy(),s=Se.createSpan("mcp.transport","mcp.connect",{"mcp.transport":e.transport,"mcp.operation":"connect","mcp.server_id":e.id},o,n);try{te.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 fZ.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(),te.debug(`[MCPClientFactory] Rate limit token acquired for ${e.id}`));const i=oC.getBreaker(`mcp-client-${e.id}`,{failureThreshold:3,resetTimeout:3e4,operationTimeout:t}),a=async()=>await i.execute(async()=>await this.createClientInternal(e,t));let c;(e.transport==="http"||e.transport==="sse")&&e.retryConfig?(te.debug(`[MCPClientFactory] Using retry logic for ${e.id}`,{maxAttempts:e.retryConfig.maxAttempts??lu.maxAttempts}),c=await YAt(a,{maxAttempts:e.retryConfig.maxAttempts??lu.maxAttempts,initialDelay:e.retryConfig.initialDelay??lu.initialDelay,maxDelay:e.retryConfig.maxDelay??lu.maxDelay,backoffMultiplier:e.retryConfig.backoffMultiplier??lu.backoffMultiplier})):c=await a(),te.info(`[MCPClientFactory] Client created successfully for ${e.id}`,{duration:Date.now()-r,capabilities:c.capabilities}),s.durationMs=Date.now()-r;const l=Se.endSpan(s,1);return ot().recordSpan(l),{...c,success:!0,duration:Date.now()-r}}catch(i){const a=i instanceof Error?i.message:String(i);if(i instanceof tm){te.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 l=Se.endSpan(s,2);return l.statusMessage=`Circuit breaker open: ${a}`,ot().recordSpan(l),{success:!1,error:a,duration:Date.now()-r}}te.debug(`[MCPClientFactory] Failed to create client for ${e.id}:`,i),s.durationMs=Date.now()-r;const c=Se.endSpan(s,2);return c.statusMessage=a,ot().recordSpan(c),{success:!1,error:a,duration:Date.now()-r}}}static async createClientInternal(e,t){const n=(await this.createTransport(e)).transport;try{const o=new wAt(this.NEUROLINK_IMPLEMENTATION,{capabilities:this.DEFAULT_CAPABILITIES});await Promise.race([o.connect(n),this.createTimeoutPromise(t,`Client connection timeout for ${e.id}`)]);const s=await this.performHandshake(o,t);return te.debug(`[MCPClientFactory] Handshake completed for ${e.id}`,{capabilities:s}),{client:o,transport:n,capabilities:s}}catch(o){try{await n.close()}catch(i){te.debug("[MCPClientFactory] Error closing transport during cleanup:",i)}const s=this.getStderrTail(n);throw o instanceof Error&&s.length>0?new Error(`${o.message}
1435
1435
  Server stderr (last ${s.length} lines):
@@ -38,10 +38,18 @@ export declare class ToolCache<T = unknown> extends EventEmitter {
38
38
  constructor(config: McpCacheConfig);
39
39
  /**
40
40
  * Get a value from the cache
41
+ *
42
+ * Returns an isolated copy of the stored value (see `cloneCachedValue`), so
43
+ * a caller mutating what it gets back cannot corrupt the entry for later
44
+ * hits or for other concurrent callers of the same key.
41
45
  */
42
46
  get(key: string): T | undefined;
43
47
  /**
44
48
  * Set a value in the cache
49
+ *
50
+ * Stores an isolated copy of `value` (see `cloneCachedValue`), so mutating
51
+ * the caller's original object after this call cannot reach into the
52
+ * cache entry.
45
53
  */
46
54
  set(key: string, value: T, ttl?: number): void;
47
55
  /**
@@ -89,6 +97,28 @@ export declare class ToolCache<T = unknown> extends EventEmitter {
89
97
  * Stop the auto-cleanup timer
90
98
  */
91
99
  destroy(): void;
100
+ /**
101
+ * Isolate a value crossing the cache boundary (on write into the entry,
102
+ * and on read back out of it) so no two callers — nor a caller and the
103
+ * stored entry itself — ever share object identity.
104
+ *
105
+ * Without this, `set()` stored the caller's object by reference and
106
+ * `get()` returned `entry.value` by the same reference on every hit: one
107
+ * caller mutating a result it got back (e.g. an in-place truncation or
108
+ * normalization pass) silently corrupted the entry for every later
109
+ * caller of the same key for the rest of the TTL.
110
+ *
111
+ * `structuredClone` is the primary path — it is a deep copy, has no
112
+ * caller-visible side effects, and (unlike a JSON round-trip) tolerates
113
+ * circular references, which a sufficiently deep or recursive tool
114
+ * result could contain. It throws on values it cannot clone (functions,
115
+ * some non-plain class instances); the JSON round-trip fallback covers
116
+ * that case for the plain-data shapes MCP tool results actually have
117
+ * (text/JSON content arrays), at the cost of silently dropping
118
+ * `undefined`, functions and symbol keys — acceptable for a cache that
119
+ * only ever holds serializable tool results.
120
+ */
121
+ private cloneCachedValue;
92
122
  private getFullKey;
93
123
  private isExpired;
94
124
  /**
@@ -60,6 +60,10 @@ export class ToolCache extends EventEmitter {
60
60
  }
61
61
  /**
62
62
  * Get a value from the cache
63
+ *
64
+ * Returns an isolated copy of the stored value (see `cloneCachedValue`), so
65
+ * a caller mutating what it gets back cannot corrupt the entry for later
66
+ * hits or for other concurrent callers of the same key.
63
67
  */
64
68
  get(key) {
65
69
  const fullKey = this.getFullKey(key);
@@ -83,11 +87,24 @@ export class ToolCache extends EventEmitter {
83
87
  entry.accessCount++;
84
88
  this.stats.hits++;
85
89
  this.updateHitRate();
86
- this.emit("hit", { key: fullKey, value: entry.value });
87
- return entry.value;
90
+ const returnedValue = this.cloneCachedValue(entry.value);
91
+ if (this.listenerCount("hit") > 0) {
92
+ // Listeners get their own copy. `emit` is synchronous, so a listener
93
+ // that mutates `event.value` would otherwise be mutating the very object
94
+ // the caller is about to receive.
95
+ this.emit("hit", {
96
+ key: fullKey,
97
+ value: this.cloneCachedValue(entry.value),
98
+ });
99
+ }
100
+ return returnedValue;
88
101
  }
89
102
  /**
90
103
  * Set a value in the cache
104
+ *
105
+ * Stores an isolated copy of `value` (see `cloneCachedValue`), so mutating
106
+ * the caller's original object after this call cannot reach into the
107
+ * cache entry.
91
108
  */
92
109
  set(key, value, ttl) {
93
110
  const fullKey = this.getFullKey(key);
@@ -98,7 +115,7 @@ export class ToolCache extends EventEmitter {
98
115
  this.evictOne();
99
116
  }
100
117
  const entry = {
101
- value,
118
+ value: this.cloneCachedValue(value),
102
119
  expires: now + effectiveTtl,
103
120
  createdAt: now,
104
121
  accessedAt: now,
@@ -250,6 +267,38 @@ export class ToolCache extends EventEmitter {
250
267
  this.clear();
251
268
  }
252
269
  // ==================== Private Methods ====================
270
+ /**
271
+ * Isolate a value crossing the cache boundary (on write into the entry,
272
+ * and on read back out of it) so no two callers — nor a caller and the
273
+ * stored entry itself — ever share object identity.
274
+ *
275
+ * Without this, `set()` stored the caller's object by reference and
276
+ * `get()` returned `entry.value` by the same reference on every hit: one
277
+ * caller mutating a result it got back (e.g. an in-place truncation or
278
+ * normalization pass) silently corrupted the entry for every later
279
+ * caller of the same key for the rest of the TTL.
280
+ *
281
+ * `structuredClone` is the primary path — it is a deep copy, has no
282
+ * caller-visible side effects, and (unlike a JSON round-trip) tolerates
283
+ * circular references, which a sufficiently deep or recursive tool
284
+ * result could contain. It throws on values it cannot clone (functions,
285
+ * some non-plain class instances); the JSON round-trip fallback covers
286
+ * that case for the plain-data shapes MCP tool results actually have
287
+ * (text/JSON content arrays), at the cost of silently dropping
288
+ * `undefined`, functions and symbol keys — acceptable for a cache that
289
+ * only ever holds serializable tool results.
290
+ */
291
+ cloneCachedValue(value) {
292
+ if (value === null || typeof value !== "object") {
293
+ return value;
294
+ }
295
+ try {
296
+ return structuredClone(value);
297
+ }
298
+ catch {
299
+ return JSON.parse(JSON.stringify(value));
300
+ }
301
+ }
253
302
  getFullKey(key) {
254
303
  return this.config.namespace ? `${this.config.namespace}:${key}` : key;
255
304
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "12.14.3",
3
+ "version": "12.14.4",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "TypeScript AI SDK with 24+ LLM providers behind one consistent API. MCP-native (connect any MCP server), voice TTS/STT/realtime, RAG, agents, memory, context compaction. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · DeepSeek · NVIDIA NIM and more.",
6
6
  "author": {