blade-code 0.10.41 → 0.10.43
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/dist/blade.js +2 -2
- package/dist/{chunk-qgez5vw6.js → chunk-0qsssahq.js} +1 -1
- package/dist/{chunk-5ygv33qe.js → chunk-26wse17p.js} +2 -2
- package/dist/{chunk-eg5sz4bw.js → chunk-2eddqgnh.js} +1 -1
- package/dist/{chunk-01jt0mpr.js → chunk-2yvte5a7.js} +1 -1
- package/dist/chunk-32g59k4p.js +8 -0
- package/dist/{chunk-q87nwpsb.js → chunk-372mmzj3.js} +1 -1
- package/dist/{chunk-2bm55evt.js → chunk-3bpxvanm.js} +2 -2
- package/dist/chunk-3y784b9c.js +1 -0
- package/dist/{chunk-bdxaz350.js → chunk-56qew7w0.js} +2 -2
- package/dist/chunk-5wzjdfde.js +1 -0
- package/dist/chunk-6ch7a6xf.js +44 -0
- package/dist/chunk-6cx4t8r6.js +1 -0
- package/dist/chunk-6skymhz5.js +1 -0
- package/dist/{chunk-4ekrbk2w.js → chunk-7fqsgdee.js} +2 -2
- package/dist/{chunk-wvc6bx0t.js → chunk-7s5hw0gr.js} +7 -7
- package/dist/{chunk-gbbnjzy8.js → chunk-7sna3js9.js} +1 -1
- package/dist/chunk-8vsx6m43.js +10 -0
- package/dist/{chunk-t80e2bms.js → chunk-8vtyatd6.js} +1 -1
- package/dist/{chunk-0hqsdbkr.js → chunk-9rrced3b.js} +1 -1
- package/dist/chunk-ag5ea7ce.js +111 -0
- package/dist/{chunk-4mdy9d43.js → chunk-bct3s5vs.js} +1 -1
- package/dist/{chunk-5sbewyjn.js → chunk-bvf9syb2.js} +2 -2
- package/dist/chunk-c3020yav.js +22 -0
- package/dist/{chunk-wk0vpgwk.js → chunk-c8ddch38.js} +395 -395
- package/dist/{chunk-dp9xzsja.js → chunk-c9s4n31b.js} +1 -1
- package/dist/{chunk-tsskar00.js → chunk-cxzx7j0p.js} +1 -1
- package/dist/{chunk-sfbprf9r.js → chunk-d5x5wknc.js} +1 -1
- package/dist/{chunk-adgx9vd7.js → chunk-dcp5gg6q.js} +3 -3
- package/dist/{chunk-f4bx2n1y.js → chunk-e1vyznkn.js} +3 -3
- package/dist/chunk-egczvfsv.js +5 -0
- package/dist/{chunk-5zf8204m.js → chunk-f4sp074f.js} +1 -1
- package/dist/chunk-fer18bbe.js +1 -0
- package/dist/{chunk-fz55cnws.js → chunk-fhnkyqfb.js} +2 -2
- package/dist/{chunk-y30kw6gj.js → chunk-fk4wbmv6.js} +2 -2
- package/dist/chunk-fzqsea19.js +1 -0
- package/dist/{chunk-x04xb9g3.js → chunk-hcm55r3d.js} +1 -1
- package/dist/{chunk-22h5kh4z.js → chunk-hfrcwkc8.js} +1 -1
- package/dist/chunk-j7edwwg1.js +2 -0
- package/dist/{chunk-yhw0pvyt.js → chunk-jpz805fs.js} +2 -2
- package/dist/chunk-k87p7x1e.js +1 -0
- package/dist/{chunk-g9re8v25.js → chunk-kfpzrmq7.js} +1 -1
- package/dist/chunk-m8a2qj5c.js +1 -0
- package/dist/{chunk-b5b8fb9y.js → chunk-m8ss9rmx.js} +1 -1
- package/dist/{chunk-5cgyevqj.js → chunk-mrsc4a55.js} +1 -1
- package/dist/{chunk-xs7w13na.js → chunk-n7dvqbrc.js} +1 -1
- package/dist/{chunk-w07gb3h0.js → chunk-nsrghqdx.js} +1 -1
- package/dist/chunk-nwzjmcxq.js +1 -0
- package/dist/chunk-nynfqgsj.js +6 -0
- package/dist/chunk-pyk2ey7y.js +1 -0
- package/dist/{chunk-npgt73cg.js → chunk-q78s028m.js} +1 -1
- package/dist/{chunk-9neq5xrb.js → chunk-qb0sqh29.js} +2 -2
- package/dist/chunk-qmcj20g2.js +1 -0
- package/dist/chunk-qnxgzyyx.js +2 -0
- package/dist/{chunk-fxw1q5j5.js → chunk-qp2z1r7y.js} +1 -1
- package/dist/{chunk-djr17h80.js → chunk-rwjm6p0f.js} +1 -1
- package/dist/chunk-s9s9daak.js +1 -0
- package/dist/{chunk-8xfzbv9v.js → chunk-skb4h36j.js} +1 -1
- package/dist/{chunk-ens8nsge.js → chunk-sqd5ge5s.js} +1 -1
- package/dist/chunk-t2r7tqn0.js +2 -0
- package/dist/{chunk-n0ebpwxd.js → chunk-tpa75y39.js} +1 -1
- package/dist/chunk-txkrtgcd.js +2 -0
- package/dist/{chunk-3p32k12g.js → chunk-v9tzhe90.js} +2 -2
- package/dist/{chunk-358zaryv.js → chunk-vbpykrxd.js} +2 -2
- package/dist/{chunk-27w2k6t7.js → chunk-w5ayh9b8.js} +2 -2
- package/dist/{chunk-atsw605q.js → chunk-wwvb6znp.js} +1 -1
- package/dist/{chunk-yxwargqc.js → chunk-x2vqgssm.js} +2 -2
- package/dist/chunk-y6tkxqjx.js +2 -0
- package/dist/{chunk-nhzdkxnx.js → chunk-yk9pxkc1.js} +1 -1
- package/dist/{chunk-hjkdc185.js → chunk-yqy000kg.js} +2 -2
- package/dist/chunk-yt9qer14.js +1 -0
- package/dist/{chunk-6dma8han.js → chunk-yypnfmed.js} +2 -2
- package/dist/chunk-z1aqe7ms.js +1 -0
- package/dist/web/assets/{ChatView-BP89vdT_.js → ChatView-CyxiCTbL.js} +3 -3
- package/dist/web/assets/{CodeBlockHighlighter-UnjC3KVk.js → CodeBlockHighlighter-Bb3gIeQv.js} +1 -1
- package/dist/web/assets/{FilePreview-D0BiZowf.js → FilePreview-BXg9VaTv.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-CPu_rkPT.js → MarkdownRenderer-vxpqGt4L.js} +3 -3
- package/dist/web/assets/{SettingsModal-CM9pcJas.js → SettingsModal-4L1nPkh0.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-BOCm7kPO.js → TaskSwitcher-DKSqTLK1.js} +1 -1
- package/dist/web/assets/{TerminalPanel-CUZ4slSS.js → TerminalPanel-Bv9PDclr.js} +1 -1
- package/dist/web/assets/index-Bz4W1-8a.js +11 -0
- package/dist/web/assets/{session-events-109FkhOM.js → session-events-DJh6SZcl.js} +5 -5
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1j2sf8mc.js +0 -1
- package/dist/chunk-1kwm2m6t.js +0 -1
- package/dist/chunk-5w8edqbt.js +0 -1
- package/dist/chunk-62jaf7ej.js +0 -22
- package/dist/chunk-6a3c496e.js +0 -1
- package/dist/chunk-6fe9kq17.js +0 -1
- package/dist/chunk-asnzpfzh.js +0 -10
- package/dist/chunk-atdeg922.js +0 -2
- package/dist/chunk-bw7fgs2n.js +0 -1
- package/dist/chunk-ck8sw2zp.js +0 -2
- package/dist/chunk-d61673v7.js +0 -5
- package/dist/chunk-f7y4m3y0.js +0 -1
- package/dist/chunk-fnz5g9ac.js +0 -1
- package/dist/chunk-kjn0yaqw.js +0 -1
- package/dist/chunk-m883e8d4.js +0 -1
- package/dist/chunk-mx5s93np.js +0 -6
- package/dist/chunk-nsawkccy.js +0 -2
- package/dist/chunk-p54vmne8.js +0 -1
- package/dist/chunk-qy9qkvwe.js +0 -1
- package/dist/chunk-s8f8amvg.js +0 -1
- package/dist/chunk-v80xem15.js +0 -2
- package/dist/chunk-w1vcjwbx.js +0 -8
- package/dist/chunk-x5s68axq.js +0 -44
- package/dist/chunk-z15h0370.js +0 -1
- package/dist/chunk-zracmha2.js +0 -111
- package/dist/web/assets/index-CthLsVgC.js +0 -11
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Db as Xt,Eb as bn,Fb as Tn,Gb as fn}from"./chunk-mrsc4a55.js";import{Ec as jt}from"./chunk-0qsssahq.js";import{Je as Bt}from"./chunk-e1vyznkn.js";import{$e as pn,Oe as xt,Pe as tn,Qe as en,Re as zt,Se as U,Te as rn,Ue as gt,Ve as mt,Xe as dn,Ye as En,Ze as B,_e as on,af as cn,bf as lt,cf as un,df as Mn,ef as wn,gf as S,jf as yn,kf as Ht,lf as Ut,mf as h,nf as qt}from"./chunk-6ch7a6xf.js";import{Tf as X,Vf as x}from"./chunk-m8ss9rmx.js";import{dg as vt}from"./chunk-kfpzrmq7.js";import{Sg as nn,Tg as sn}from"./chunk-vbpykrxd.js";import{hh as ss}from"./chunk-hfrcwkc8.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
|
|
2
2
|
${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
3
|
`)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
4
|
|
|
@@ -10,16 +10,16 @@ ${t.description.usageNotes.map((s)=>`- ${s}`).join(`
|
|
|
10
10
|
|
|
11
11
|
Important:
|
|
12
12
|
${t.description.important.map((s)=>`[WARN] ${s}`).join(`
|
|
13
|
-
`)}`;return{name:t.name,description:n,parameters:i}},getMetadata(){return{name:t.name,displayName:t.displayName,kind:t.kind,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),description:t.description,schema:et(t.schema)}},build(i){let n=Vt(t.schema,i);return new rt(t.name,n,t.execute,void 0,t.affectedPaths)},async execute(i,n,s){return this.build(i).execute(n||new AbortController().signal,void 0,s)},extractSignatureContent:t.extractSignatureContent?(i)=>t.extractSignatureContent(i):void 0,abstractPermissionRule:t.abstractPermissionRule?(i)=>t.abstractPermissionRule(i):void 0}}import{randomUUID as Pn}from"node:crypto";import{EventEmitter as Rn}from"node:events";import an from"node:path";class T extends Rn{static instance;tasks=new Map;revision=0;static getInstance(){if(!T.instance)T.instance=new T;return T.instance}static resetForTests(){T.instance?.removeAllListeners(),T.instance=void 0}async start(t){let i=z(t.owner),n=t.client.tasks;if(!n.enabled)throw Error(`MCP tasks are disabled for server "${t.serverName}"`);if(this.evictTerminalTasks(i,n.maxTasksPerSession),this.list(i).length>=n.maxTasksPerSession)throw Error(`MCP task limit reached for Session (${n.maxTasksPerSession})`);if(this.tasks.size>=S)throw Error(`Global MCP task limit reached (${S})`);let e=Ht(t.ttlMs,n),r=new AbortController,o=()=>r.abort(t.signal?.reason??"MCP task creation cancelled");t.signal?.addEventListener("abort",o,{once:!0});let u;try{u=await t.client.createToolTask(t.toolName,t.arguments,t.interactionContext,r.signal,e)}finally{t.signal?.removeEventListener("abort",o)}let d=Date.now(),p=`mcp_task_${Pn()}`,c={taskId:p,serverName:t.serverName,toolName:t.toolName,owner:i,client:t.client,serverTaskId:u.taskId,serverCreatedAt:u.createdAt,serverUpdatedAt:u.lastUpdatedAt,status:u.status,statusMessage:u.statusMessage,createdAt:d,updatedAt:d,hasResult:!1,pollIntervalMs:u.pollIntervalMs,deadline:d+Math.min(e,n.maxLifetimeMs),controller:r};return this.tasks.set(p,c),this.publish(c),c.promise=this.poll(c),c.promise.catch(()=>{return}),this.snapshot(c)}get(t,i){let n=this.getOwnedRecord(t,i);return n?this.snapshot(n):void 0}list(t,i){let n=z(t);return[...this.tasks.values()].filter((s)=>dt(s.owner,n)&&(!i||s.serverName===i)).sort((s,e)=>s.createdAt-e.createdAt).map((s)=>this.snapshot(s))}async wait(t,i,n,s){let e=this.getOwnedRecord(t,i);if(!e)return;if(!e.promise||R(e.status))return this.snapshot(e);let r,o,u=new Promise((d)=>{if(r=setTimeout(d,Math.max(0,n)),r.unref(),s){if(o=d,s.addEventListener("abort",o,{once:!0}),s.aborted)d()}});if(await Promise.race([e.promise,u]),r)clearTimeout(r);if(s&&o)s.removeEventListener("abort",o);return this.snapshot(e)}async cancel(t,i,n){let s=this.getOwnedRecord(t,i);if(!s)return;if(R(s.status))return this.snapshot(s);let e;try{await s.client.cancelToolTask(s.serverTaskId,n)}catch(r){e=ot(r,s.serverTaskId)}return s.controller.abort("MCP task cancelled"),this.update(s,{status:"cancelled",statusMessage:e?`Local cancellation completed; server acknowledgement failed: ${e}`:"Task cancelled",completedAt:Date.now()}),s.client.releaseTaskInteraction(s.serverTaskId),this.snapshot(s)}async cancelSession(t){let i=this.ownedRecords(t);await Promise.all(i.filter((n)=>!R(n.status)).map((n)=>this.cancel(n.taskId,t))),await Promise.allSettled(i.map((n)=>n.promise).filter((n)=>n!==void 0));for(let n of i)n.client.releaseTaskInteraction(n.serverTaskId),this.tasks.delete(n.taskId)}async cancelClient(t){let i=[...this.tasks.values()].filter((n)=>n.client===t&&!R(n.status));await Promise.all(i.map((n)=>this.cancel(n.taskId,n.owner)))}async poll(t){try{while(!t.controller.signal.aborted){let i=t.deadline-Date.now();if(i<=0){if(await this.cancel(t.taskId,t.owner),t.status==="cancelled")this.update(t,{status:"failed",statusMessage:"MCP task exceeded its local lifetime budget",error:"MCP task timed out",completedAt:Date.now()});return}let n;try{n=await t.client.getToolTask(t.serverTaskId,t.serverCreatedAt,t.controller.signal)}catch(s){if(t.controller.signal.aborted)return;if(t.client.connectionStatus==="connected")throw s;this.update(t,{status:"interrupted",statusMessage:"Waiting for MCP connection recovery"}),await t.client.waitUntilConnected(t.controller.signal,i);continue}if(this.applyServerState(t,n),n.status==="completed"||n.status==="input_required"){let s=t.deadline-Date.now();if(s<=0)continue;let e;try{e=await t.client.getToolTaskResult(t.serverTaskId,t.controller.signal,s)}catch(d){if(t.controller.signal.aborted)return;if(t.client.connectionStatus==="connected")throw d;this.update(t,{status:"interrupted",statusMessage:"Waiting for MCP connection recovery"}),await t.client.waitUntilConnected(t.controller.signal,s);continue}let r=await t.client.normalizeToolTaskResult(e),o=r.llmContent.replaceAll(t.serverTaskId,"[redacted-task-id]"),u=r.isError?{...r,llmContent:ot(o,t.serverTaskId)}:{...r,llmContent:o};this.update(t,{status:r.isError?"failed":"completed",hasResult:!0,result:u,...r.isError?{error:u.llmContent,statusMessage:"MCP task returned an error result"}:{},completedAt:Date.now()});return}if(n.status==="failed"||n.status==="cancelled"){this.update(t,{status:n.status,error:n.status==="failed"?n.statusMessage??"MCP task failed":void 0,completedAt:Date.now()});return}await $n(t.pollIntervalMs,t.controller.signal)}}catch(i){if(!t.controller.signal.aborted)this.update(t,{status:"failed",statusMessage:"MCP task lifecycle failed",error:ot(i,t.serverTaskId),completedAt:Date.now()})}finally{t.client.releaseTaskInteraction(t.serverTaskId)}}applyServerState(t,i){t.pollIntervalMs=i.pollIntervalMs,this.update(t,{status:i.status,statusMessage:i.statusMessage,serverUpdatedAt:i.lastUpdatedAt})}update(t,i){let n=JSON.stringify({status:t.status,statusMessage:t.statusMessage,serverUpdatedAt:t.serverUpdatedAt,hasResult:t.hasResult,error:t.error});Object.assign(t,i);let s=JSON.stringify({status:t.status,statusMessage:t.statusMessage,serverUpdatedAt:t.serverUpdatedAt,hasResult:t.hasResult,error:t.error});if(n!==s||i.completedAt!==void 0)t.updatedAt=Date.now(),this.publish(t)}publish(t){let i={revision:++this.revision,owner:{...t.owner},...this.snapshot(t)};this.emit("taskChanged",i)}snapshot(t){return structuredClone({taskId:t.taskId,serverName:t.serverName,toolName:t.toolName,status:t.status,...t.statusMessage?{statusMessage:t.statusMessage}:{},createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt?{completedAt:t.completedAt}:{},hasResult:t.hasResult,...t.result?{result:t.result}:{},...t.error?{error:t.error}:{}})}getOwnedRecord(t,i){let n=this.tasks.get(t);return n&&dt(n.owner,z(i))?n:void 0}ownedRecords(t){let i=z(t);return[...this.tasks.values()].filter((n)=>dt(n.owner,i))}evictTerminalTasks(t,i){let n=this.ownedRecords(t).filter((s)=>R(s.status)).sort((s,e)=>s.updatedAt-e.updatedAt);while(this.list(t).length>=i&&n.length>0){let s=n.shift();if(s)this.tasks.delete(s.taskId)}if(this.tasks.size>=S){let s=[...this.tasks.values()].filter((e)=>R(e.status)).sort((e,r)=>e.updatedAt-r.updatedAt);while(this.tasks.size>=S&&s.length>0){let e=s.shift();if(e)this.tasks.delete(e.taskId)}}}}function z(t){if(!t.sessionId)throw Error("MCP task owner requires a Session ID");return{sessionId:t.sessionId,projectPath:an.resolve(t.projectPath)}}function dt(t,i){return t.sessionId===i.sessionId&&t.projectPath===i.projectPath}async function $n(t,i){await new Promise((n,s)=>{let e=()=>i.removeEventListener("abort",o),r=setTimeout(()=>{e(),n()},t);r.unref();let o=()=>{clearTimeout(r),e(),s(new DOMException(String(i.reason||"MCP task cancelled"),"AbortError"))};if(i.addEventListener("abort",o,{once:!0}),i.aborted)o()})}function ot(t,i){let n=t instanceof Error?t.message:String(t);return qt(n.replaceAll(i,"[redacted-task-id]"))}import{createHash as Cn}from"node:crypto";var Kt=64,J=1048576,V=4194304,Wt=4194304,pt=8388608,Y=16777216,Zt=102400,kn=4096,Qt=8192,On=256,Ln=16384,ut=256,Sn=8192,xn=2048;function D(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function gn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function mn(t){return[...t].filter((i)=>{let n=i.charCodeAt(0);return!(n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127)}).join("")}function F(t,i,n){if(typeof t!=="string")throw Error(`MCP tool ${i} must be a string`);if(gn(t))throw Error(`MCP tool ${i} contains unsafe control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP tool ${i} exceeds ${n} bytes`);return t}function $(t,i,n){let s=F(t,i,n*4).trim();if(!s||s.length>n)throw Error(`MCP tool ${i} is invalid`);return s}function Nt(t,i,n){let s=Buffer.byteLength(i);if(s>J)throw Error(`MCP tool ${n} exceeds ${J} bytes`);if(t.textBytes+=s,t.textBytes>V)throw Error(`MCP tool text exceeds ${V} total bytes`)}function wt(t,i,n=!1){let s=Buffer.from(t);if(s.length<=i)return t;let r=(n?s.subarray(s.length-i):s.subarray(0,i)).toString("utf8");while(Buffer.byteLength(r)>i)r=n?r.slice(1):r.slice(0,-1);return r.replace(n?/^\uFFFD/:/\uFFFD$/,"")}function It(t,i){if(typeof t!=="string")throw Error(`MCP tool ${i} must contain base64 data`);let n=Math.ceil(pt*4/3)+4;if(t.length>n||t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP tool ${i} contains invalid or oversized base64`);let s=Buffer.from(t,"base64");if(s.length>pt)throw Error(`MCP tool ${i} exceeds ${pt} decoded bytes`);return s}async function ct(t,i){let n=Cn("sha256").update(t.bytes).digest("hex"),s={id:n,kind:t.kind,size:t.bytes.length,sha256:n,persisted:!1,...t.mimeType?{mimeType:t.mimeType}:{},...t.sourceUri?{sourceUri:t.sourceUri}:{}};if(!i)return s;try{let e=await i.write(t);return{...s,...e,id:n,sha256:n,size:t.bytes.length}}catch{return s}}function Mt(t){let i=t.path?` path=${JSON.stringify(t.path)}`:t.persisted?` artifact_id=${t.id}`:" content_omitted=true";return`[${t.kind} artifact: size=${t.size} sha256=${t.sha256}${t.mimeType?` mime_type=${JSON.stringify(t.mimeType)}`:""}${t.sourceUri?` uri=${JSON.stringify(t.sourceUri)}`:""}${i}]`}function ln(t){if(t===void 0)return;if(!D(t))throw Error("MCP tool structuredContent must be an object");let i;try{i=JSON.stringify(t,null,2)}catch{throw Error("MCP tool structuredContent is not serializable")}let n=Buffer.byteLength(i);if(n>Wt)throw Error(`MCP tool structuredContent exceeds ${Wt} bytes`);return{text:i,bytes:n}}async function j(t,i){if(!D(t)||!Array.isArray(t.content))throw Error("MCP tool result is malformed");if(t.content.length>Kt)throw Error(`MCP tool result exceeds ${Kt} content parts`);let n={textBytes:0,binaryBytes:0},s=[],e=[];for(let[d,p]of t.content.entries()){if(!D(p))throw Error(`MCP tool content[${d}] is malformed`);if(p.type==="text"){let c=F(p.text,`content[${d}] text`,J);Nt(n,c,`content[${d}] text`),s.push(c);continue}if(p.type==="image"||p.type==="audio"){let c=$(p.mimeType,`content[${d}] MIME type`,ut),M=It(p.data,`content[${d}] ${p.type}`);if(n.binaryBytes+=M.length,n.binaryBytes>Y)throw Error(`MCP tool binary content exceeds ${Y} total bytes`);let w=await ct({kind:p.type,bytes:M,mimeType:c},i);e.push(w),s.push(Mt(w));continue}if(p.type==="resource_link"){let c=$(p.uri,`content[${d}] resource link URI`,Qt),M=$(p.name,`content[${d}] resource link name`,On),w=p.description===void 0?void 0:F(p.description,`content[${d}] resource link description`,Ln),y=p.mimeType===void 0?void 0:$(p.mimeType,`content[${d}] MIME type`,ut);s.push(`[resource link: name=${JSON.stringify(M)} uri=${JSON.stringify(c)}${y?` mime_type=${JSON.stringify(y)}`:""}${w?` description=${JSON.stringify(w)}`:""}]`);continue}if(p.type==="resource"&&D(p.resource)){let c=p.resource,M=$(c.uri,`content[${d}] resource URI`,Qt),w=c.mimeType===void 0?void 0:$(c.mimeType,`content[${d}] resource MIME type`,ut);if(typeof c.text==="string"){let a=F(c.text,`content[${d}] resource text`,J);Nt(n,a,`content[${d}] resource text`),s.push(`[resource: uri=${JSON.stringify(M)}${w?` mime_type=${JSON.stringify(w)}`:""}]
|
|
14
|
-
${a}`);continue}let y=It(
|
|
13
|
+
`)}`;return{name:t.name,description:n,parameters:i}},getMetadata(){return{name:t.name,displayName:t.displayName,kind:t.kind,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),description:t.description,schema:et(t.schema)}},build(i){let n=Vt(t.schema,i);return new rt(t.name,n,t.execute,void 0,t.affectedPaths)},async execute(i,n,s){return this.build(i).execute(n||new AbortController().signal,void 0,s)},extractSignatureContent:t.extractSignatureContent?(i)=>t.extractSignatureContent(i):void 0,abstractPermissionRule:t.abstractPermissionRule?(i)=>t.abstractPermissionRule(i):void 0}}import{randomUUID as Pn}from"node:crypto";import{EventEmitter as Rn}from"node:events";import an from"node:path";class T extends Rn{static instance;tasks=new Map;revision=0;static getInstance(){if(!T.instance)T.instance=new T;return T.instance}static resetForTests(){T.instance?.removeAllListeners(),T.instance=void 0}async start(t){let i=z(t.owner),n=t.client.tasks;if(!n.enabled)throw Error(`MCP tasks are disabled for server "${t.serverName}"`);if(this.evictTerminalTasks(i,n.maxTasksPerSession),this.list(i).length>=n.maxTasksPerSession)throw Error(`MCP task limit reached for Session (${n.maxTasksPerSession})`);if(this.tasks.size>=S)throw Error(`Global MCP task limit reached (${S})`);let e=Ht(t.ttlMs,n),r=new AbortController,o=()=>r.abort(t.signal?.reason??"MCP task creation cancelled");t.signal?.addEventListener("abort",o,{once:!0});let c;try{c=await t.client.createToolTask(t.toolName,t.arguments,t.interactionContext,r.signal,e)}finally{t.signal?.removeEventListener("abort",o)}let d=Date.now(),p=`mcp_task_${Pn()}`,u={taskId:p,serverName:t.serverName,toolName:t.toolName,owner:i,client:t.client,serverTaskId:c.taskId,serverCreatedAt:c.createdAt,serverUpdatedAt:c.lastUpdatedAt,status:c.status,statusMessage:c.statusMessage,createdAt:d,updatedAt:d,hasResult:!1,pollIntervalMs:c.pollIntervalMs,deadline:d+Math.min(e,n.maxLifetimeMs),controller:r};return this.tasks.set(p,u),this.publish(u),u.promise=this.poll(u),u.promise.catch(()=>{return}),this.snapshot(u)}get(t,i){let n=this.getOwnedRecord(t,i);return n?this.snapshot(n):void 0}list(t,i){let n=z(t);return[...this.tasks.values()].filter((s)=>dt(s.owner,n)&&(!i||s.serverName===i)).sort((s,e)=>s.createdAt-e.createdAt).map((s)=>this.snapshot(s))}hasActive(t){return this.ownedRecords(t).some((i)=>!h(i.status))}async wait(t,i,n,s){let e=this.getOwnedRecord(t,i);if(!e)return;if(!e.promise||h(e.status))return this.snapshot(e);let r,o,c=new Promise((d)=>{if(r=setTimeout(d,Math.max(0,n)),r.unref(),s){if(o=d,s.addEventListener("abort",o,{once:!0}),s.aborted)d()}});if(await Promise.race([e.promise,c]),r)clearTimeout(r);if(s&&o)s.removeEventListener("abort",o);return this.snapshot(e)}async cancel(t,i,n){let s=this.getOwnedRecord(t,i);if(!s)return;if(h(s.status))return this.snapshot(s);let e;try{await s.client.cancelToolTask(s.serverTaskId,n)}catch(r){e=ot(r,s.serverTaskId)}return s.controller.abort("MCP task cancelled"),this.update(s,{status:"cancelled",statusMessage:e?`Local cancellation completed; server acknowledgement failed: ${e}`:"Task cancelled",completedAt:Date.now()}),s.client.releaseTaskInteraction(s.serverTaskId),this.snapshot(s)}async cancelSession(t){let i=this.ownedRecords(t);await Promise.all(i.filter((n)=>!h(n.status)).map((n)=>this.cancel(n.taskId,t))),await Promise.allSettled(i.map((n)=>n.promise).filter((n)=>n!==void 0));for(let n of i)n.client.releaseTaskInteraction(n.serverTaskId),this.tasks.delete(n.taskId)}async cancelClient(t){let i=[...this.tasks.values()].filter((n)=>n.client===t&&!h(n.status));await Promise.all(i.map((n)=>this.cancel(n.taskId,n.owner)))}async poll(t){try{while(!t.controller.signal.aborted){let i=t.deadline-Date.now();if(i<=0){if(await this.cancel(t.taskId,t.owner),t.status==="cancelled")this.update(t,{status:"failed",statusMessage:"MCP task exceeded its local lifetime budget",error:"MCP task timed out",completedAt:Date.now()});return}let n;try{n=await t.client.getToolTask(t.serverTaskId,t.serverCreatedAt,t.controller.signal)}catch(s){if(t.controller.signal.aborted)return;if(t.client.connectionStatus==="connected")throw s;this.update(t,{status:"interrupted",statusMessage:"Waiting for MCP connection recovery"}),await t.client.waitUntilConnected(t.controller.signal,i);continue}if(this.applyServerState(t,n),n.status==="completed"||n.status==="input_required"){let s=t.deadline-Date.now();if(s<=0)continue;let e;try{e=await t.client.getToolTaskResult(t.serverTaskId,t.controller.signal,s)}catch(d){if(t.controller.signal.aborted)return;if(t.client.connectionStatus==="connected")throw d;this.update(t,{status:"interrupted",statusMessage:"Waiting for MCP connection recovery"}),await t.client.waitUntilConnected(t.controller.signal,s);continue}let r=await t.client.normalizeToolTaskResult(e),o=r.llmContent.replaceAll(t.serverTaskId,"[redacted-task-id]"),c=r.isError?{...r,llmContent:ot(o,t.serverTaskId)}:{...r,llmContent:o};this.update(t,{status:r.isError?"failed":"completed",hasResult:!0,result:c,...r.isError?{error:c.llmContent,statusMessage:"MCP task returned an error result"}:{},completedAt:Date.now()});return}if(n.status==="failed"||n.status==="cancelled"){this.update(t,{status:n.status,error:n.status==="failed"?n.statusMessage??"MCP task failed":void 0,completedAt:Date.now()});return}await $n(t.pollIntervalMs,t.controller.signal)}}catch(i){if(!t.controller.signal.aborted)this.update(t,{status:"failed",statusMessage:"MCP task lifecycle failed",error:ot(i,t.serverTaskId),completedAt:Date.now()})}finally{t.client.releaseTaskInteraction(t.serverTaskId)}}applyServerState(t,i){t.pollIntervalMs=i.pollIntervalMs,this.update(t,{status:i.status,statusMessage:i.statusMessage,serverUpdatedAt:i.lastUpdatedAt})}update(t,i){let n=JSON.stringify({status:t.status,statusMessage:t.statusMessage,serverUpdatedAt:t.serverUpdatedAt,hasResult:t.hasResult,error:t.error});Object.assign(t,i);let s=JSON.stringify({status:t.status,statusMessage:t.statusMessage,serverUpdatedAt:t.serverUpdatedAt,hasResult:t.hasResult,error:t.error});if(n!==s||i.completedAt!==void 0)t.updatedAt=Date.now(),this.publish(t)}publish(t){let i={revision:++this.revision,owner:{...t.owner},...this.snapshot(t)};this.emit("taskChanged",i)}snapshot(t){return structuredClone({taskId:t.taskId,serverName:t.serverName,toolName:t.toolName,status:t.status,...t.statusMessage?{statusMessage:t.statusMessage}:{},createdAt:t.createdAt,updatedAt:t.updatedAt,...t.completedAt?{completedAt:t.completedAt}:{},hasResult:t.hasResult,...t.result?{result:t.result}:{},...t.error?{error:t.error}:{}})}getOwnedRecord(t,i){let n=this.tasks.get(t);return n&&dt(n.owner,z(i))?n:void 0}ownedRecords(t){let i=z(t);return[...this.tasks.values()].filter((n)=>dt(n.owner,i))}evictTerminalTasks(t,i){let n=this.ownedRecords(t).filter((s)=>h(s.status)).sort((s,e)=>s.updatedAt-e.updatedAt);while(this.list(t).length>=i&&n.length>0){let s=n.shift();if(s)this.tasks.delete(s.taskId)}if(this.tasks.size>=S){let s=[...this.tasks.values()].filter((e)=>h(e.status)).sort((e,r)=>e.updatedAt-r.updatedAt);while(this.tasks.size>=S&&s.length>0){let e=s.shift();if(e)this.tasks.delete(e.taskId)}}}}function z(t){if(!t.sessionId)throw Error("MCP task owner requires a Session ID");return{sessionId:t.sessionId,projectPath:an.resolve(t.projectPath)}}function dt(t,i){return t.sessionId===i.sessionId&&t.projectPath===i.projectPath}async function $n(t,i){await new Promise((n,s)=>{let e=()=>i.removeEventListener("abort",o),r=setTimeout(()=>{e(),n()},t);r.unref();let o=()=>{clearTimeout(r),e(),s(new DOMException(String(i.reason||"MCP task cancelled"),"AbortError"))};if(i.addEventListener("abort",o,{once:!0}),i.aborted)o()})}function ot(t,i){let n=t instanceof Error?t.message:String(t);return qt(n.replaceAll(i,"[redacted-task-id]"))}import{createHash as Cn}from"node:crypto";var Kt=64,J=1048576,V=4194304,Wt=4194304,pt=8388608,Y=16777216,Zt=102400,kn=4096,Qt=8192,On=256,Ln=16384,ct=256,Sn=8192,xn=2048;function D(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function gn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function mn(t){return[...t].filter((i)=>{let n=i.charCodeAt(0);return!(n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127)}).join("")}function F(t,i,n){if(typeof t!=="string")throw Error(`MCP tool ${i} must be a string`);if(gn(t))throw Error(`MCP tool ${i} contains unsafe control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP tool ${i} exceeds ${n} bytes`);return t}function $(t,i,n){let s=F(t,i,n*4).trim();if(!s||s.length>n)throw Error(`MCP tool ${i} is invalid`);return s}function Nt(t,i,n){let s=Buffer.byteLength(i);if(s>J)throw Error(`MCP tool ${n} exceeds ${J} bytes`);if(t.textBytes+=s,t.textBytes>V)throw Error(`MCP tool text exceeds ${V} total bytes`)}function wt(t,i,n=!1){let s=Buffer.from(t);if(s.length<=i)return t;let r=(n?s.subarray(s.length-i):s.subarray(0,i)).toString("utf8");while(Buffer.byteLength(r)>i)r=n?r.slice(1):r.slice(0,-1);return r.replace(n?/^\uFFFD/:/\uFFFD$/,"")}function It(t,i){if(typeof t!=="string")throw Error(`MCP tool ${i} must contain base64 data`);let n=Math.ceil(pt*4/3)+4;if(t.length>n||t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP tool ${i} contains invalid or oversized base64`);let s=Buffer.from(t,"base64");if(s.length>pt)throw Error(`MCP tool ${i} exceeds ${pt} decoded bytes`);return s}async function ut(t,i){let n=Cn("sha256").update(t.bytes).digest("hex"),s={id:n,kind:t.kind,size:t.bytes.length,sha256:n,persisted:!1,...t.mimeType?{mimeType:t.mimeType}:{},...t.sourceUri?{sourceUri:t.sourceUri}:{}};if(!i)return s;try{let e=await i.write(t);return{...s,...e,id:n,sha256:n,size:t.bytes.length}}catch{return s}}function Mt(t){let i=t.path?` path=${JSON.stringify(t.path)}`:t.persisted?` artifact_id=${t.id}`:" content_omitted=true";return`[${t.kind} artifact: size=${t.size} sha256=${t.sha256}${t.mimeType?` mime_type=${JSON.stringify(t.mimeType)}`:""}${t.sourceUri?` uri=${JSON.stringify(t.sourceUri)}`:""}${i}]`}function ln(t){if(t===void 0)return;if(!D(t))throw Error("MCP tool structuredContent must be an object");let i;try{i=JSON.stringify(t,null,2)}catch{throw Error("MCP tool structuredContent is not serializable")}let n=Buffer.byteLength(i);if(n>Wt)throw Error(`MCP tool structuredContent exceeds ${Wt} bytes`);return{text:i,bytes:n}}async function j(t,i){if(!D(t)||!Array.isArray(t.content))throw Error("MCP tool result is malformed");if(t.content.length>Kt)throw Error(`MCP tool result exceeds ${Kt} content parts`);let n={textBytes:0,binaryBytes:0},s=[],e=[];for(let[d,p]of t.content.entries()){if(!D(p))throw Error(`MCP tool content[${d}] is malformed`);if(p.type==="text"){let u=F(p.text,`content[${d}] text`,J);Nt(n,u,`content[${d}] text`),s.push(u);continue}if(p.type==="image"||p.type==="audio"){let u=$(p.mimeType,`content[${d}] MIME type`,ct),M=It(p.data,`content[${d}] ${p.type}`);if(n.binaryBytes+=M.length,n.binaryBytes>Y)throw Error(`MCP tool binary content exceeds ${Y} total bytes`);let w=await ut({kind:p.type,bytes:M,mimeType:u},i);e.push(w),s.push(Mt(w));continue}if(p.type==="resource_link"){let u=$(p.uri,`content[${d}] resource link URI`,Qt),M=$(p.name,`content[${d}] resource link name`,On),w=p.description===void 0?void 0:F(p.description,`content[${d}] resource link description`,Ln),y=p.mimeType===void 0?void 0:$(p.mimeType,`content[${d}] MIME type`,ct);s.push(`[resource link: name=${JSON.stringify(M)} uri=${JSON.stringify(u)}${y?` mime_type=${JSON.stringify(y)}`:""}${w?` description=${JSON.stringify(w)}`:""}]`);continue}if(p.type==="resource"&&D(p.resource)){let u=p.resource,M=$(u.uri,`content[${d}] resource URI`,Qt),w=u.mimeType===void 0?void 0:$(u.mimeType,`content[${d}] resource MIME type`,ct);if(typeof u.text==="string"){let a=F(u.text,`content[${d}] resource text`,J);Nt(n,a,`content[${d}] resource text`),s.push(`[resource: uri=${JSON.stringify(M)}${w?` mime_type=${JSON.stringify(w)}`:""}]
|
|
14
|
+
${a}`);continue}let y=It(u.blob,`content[${d}] resource blob`);if(n.binaryBytes+=y.length,n.binaryBytes>Y)throw Error(`MCP tool binary content exceeds ${Y} total bytes`);let E=await ut({kind:"resource",bytes:y,mimeType:w,sourceUri:M},i);e.push(E),s.push(Mt(E));continue}throw Error(`Unsupported MCP tool content type: ${String(p.type)}`)}let r=ln(t.structuredContent);if(r)s.push(`[structuredContent]
|
|
15
15
|
${r.text}`);let o=s.join(`
|
|
16
16
|
|
|
17
|
-
`)||"MCP tool returned no content.";if(Buffer.byteLength(o)>V)throw Error(`MCP tool normalized result exceeds ${V} bytes`);let
|
|
17
|
+
`)||"MCP tool returned no content.";if(Buffer.byteLength(o)>V)throw Error(`MCP tool normalized result exceeds ${V} bytes`);let c=!1;if(Buffer.byteLength(o)>Zt){let d=Buffer.from(o),p=await ut({kind:"text",bytes:d,mimeType:"text/plain"},i);e.push(p);let u=wt(o,Sn),M=wt(o,xn,!0);o=`MCP tool result exceeded the ${Zt}-byte inline budget.
|
|
18
18
|
${Mt(p)}
|
|
19
19
|
|
|
20
20
|
Preview (head):
|
|
21
|
-
${
|
|
21
|
+
${u}
|
|
22
22
|
|
|
23
23
|
Preview (tail):
|
|
24
|
-
${M}`,u=!0}return{isError:t.isError===!0,llmContent:o,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:e.length,truncated:u,binaryOmitted:n.binaryBytes>0,artifacts:e}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=mn(i.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")).trim();return wt(n||"MCP tool execution failed",kn)}function Tt(t,i,n,s,e){let r=n.inputSchema&&typeof n.inputSchema==="object"?x.Unsafe(n.inputSchema):x.Any(),o=s||n.name;return Gt({name:o,displayName:`${i}: ${n.name}`,kind:"execute",schema:r,description:{short:n.description||`MCP Tool: ${n.name}`,important:[`From MCP server: ${i}`,"Executes external tools; user confirmation required",...n.taskSupport==="required"?["This tool requires MCP task execution and returns an opaque task ID.","Use TaskOutput to retrieve the eventual result."]:[]]},category:"MCP tool",tags:["mcp","external",i],async execute(u,d){try{let p={...d.confirmationHandler?{confirmationHandler:d.confirmationHandler}:{},...d.mcpSamplingHandler?{samplingHandler:d.mcpSamplingHandler}:{},...d.onProgressUpdate?{progressHandler:d.onProgressUpdate}:{},...d.sessionId?{sessionId:d.sessionId}:{},...d.workspaceRoot?{workspaceRoot:d.workspaceRoot}:{},...d.permissionMode?{permissionMode:d.permissionMode}:{}};if(n.taskSupport==="required"){if(!d.sessionId)throw Error("MCP tasks require an active Session");let y=await T.getInstance().start({client:t,serverName:i,toolName:n.name,arguments:u,owner:{sessionId:d.sessionId,projectPath:Bn.resolve(d.workspaceRoot||vt())},interactionContext:p,signal:d.signal});return{success:!0,llmContent:{task_id:y.taskId,type:"mcp",status:y.status,message:`MCP task started. Use TaskOutput(task_id: "${y.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${y.taskId}`,serverName:i,toolName:n.name,task_id:y.taskId,taskType:"mcp",taskStatus:y.status,background:!0}}}let c=await t.callTool(n.name,u,{...d.signal?{signal:d.signal}:{},...p}),M=await j(c,e),w={summary:`MCP ${n.name} 执行${M.isError?"失败":"成功"}`,serverName:i,toolName:n.name,mcpResult:{isError:M.isError,...M.metadata}};if(M.isError){let y=yt(M.llmContent);return{success:!1,llmContent:y,error:{type:"execution_error",message:y},metadata:w}}return{success:!0,llmContent:M.llmContent,metadata:w}}catch(p){let c=yt(p);return{success:!1,llmContent:`MCP tool execution failed: ${c}`,error:{type:"execution_error",message:c},metadata:{summary:`MCP ${n.name} 执行失败`,serverName:i,toolName:n.name}}}}})}import{realpathSync as es}from"node:fs";import Ii from"node:path";import{pathToFileURL as rs}from"node:url";import{Client as ds}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as os}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as ps}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolResultSchema as St,CreateMessageRequestSchema as us,ElicitationCompleteNotificationSchema as cs,ElicitRequestSchema as Ms,ErrorCode as _,ListRootsRequestSchema as ws,LoggingMessageNotificationSchema as ys,McpError as P,ResourceUpdatedNotificationSchema as Ts,TaskStatusNotificationSchema as Es}from"@modelcontextprotocol/sdk/types.js";import{EventEmitter as bs}from"events";import fs from"open";import{EventEmitter as Xn}from"events";function Et(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t)||!Number.isInteger(t)||t<s||t>e)throw Error(`${n} must be an integer between ${s} and ${e}`);return t}class bt extends Xn{client;config;checkTimer=null;isChecking=!1;running=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(t,i={}){super();if(this.client=t,i.enabled!==void 0&&typeof i.enabled!=="boolean")throw Error("MCP health check enabled must be a boolean");this.config={interval:Et(i.interval,30000,"MCP health check interval",10,300000),timeout:Et(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:Et(i.failureThreshold,3,"MCP health check failureThreshold",1,10)}}start(){if(this.running||!this.config.enabled)return;this.running=!0,this.scheduleNextCheck()}stop(){if(this.running=!1,this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null}scheduleNextCheck(){if(!this.running)return;this.checkTimer=setTimeout(async()=>{this.checkTimer=null,await this.performHealthCheck().catch(()=>{return}),this.scheduleNextCheck()},this.config.interval),this.checkTimer.unref()}async performHealthCheck(){if(this.isChecking)return this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let t=this.client.connectionStatus;if(t==="connected"){await this.client.ping(this.config.timeout),this.consecutiveFailures=0,this.setStatus("healthy");let i={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",i),i}else throw Error(`连接状态异常: ${t}`)}catch(t){this.consecutiveFailures++;let i=t,n;if(this.consecutiveFailures>=this.config.failureThreshold)n="unhealthy",this.emit("unhealthy",this.consecutiveFailures,i),this.client.requestRecovery(i,"health_check");else n="degraded";this.setStatus(n);let s={status:n,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:i};return this.emit("healthCheck",s),s}finally{this.isChecking=!1}}setStatus(t){if(this.currentStatus!==t){let i=this.currentStatus;this.currentStatus=t,this.emit("statusChanged",t,i)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}import{createHash as zn}from"node:crypto";import{UriTemplate as Yn}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";var ii=100,Dn=4096,Fn=65536,ft=1048576,ni=32,si=65536,pi=4,ht=15000,ei=256,ri=16384,Jn=256,Vn=8192,jn=/[\p{Cf}\p{Co}\p{Cn}]/u;function Gn(t){return[...new Set(new Yn(t).variableNames)]}function ui(t,i){let n=G(t.argument.name,"completion argument name",ei),s=di(t.argument.value,"completion argument value",ri),e,r;if(t.reference.type==="prompt"){let p=G(t.reference.name,"completion prompt name",Jn),c=i.prompts.find((M)=>M.name===p);if(!c)throw Error(`MCP prompt "${p}" is not present in the current catalog`);e=new Set(c.arguments.map((M)=>M.name)),r={type:"ref/prompt",name:p}}else{let p=G(t.reference.uri,"completion resource template URI",Vn);if(!i.resourceTemplates.find((w)=>w.uriTemplate===p))throw Error(`MCP resource template "${p}" is not present in the current catalog`);let M;try{M=Gn(p)}catch{throw Error(`MCP resource template "${p}" is invalid`)}e=new Set(M),r={type:"ref/resource",uri:p}}if(!e.has(n))throw Error(`MCP ${t.reference.type} completion argument "${n}" is not declared`);let o=Object.entries(t.context??{});if(o.length>ni)throw Error(`MCP completion context exceeds ${ni} arguments`);let u=Object.create(null),d=0;for(let[p,c]of o){let M=G(p,"completion context argument name",ei);if(yi(M))throw Error(`Unsafe MCP completion context argument "${M}"`);if(!e.has(M))throw Error(`Unknown MCP completion context argument "${M}"`);let w=di(c,`completion context argument "${M}"`,ri);if(d+=Buffer.byteLength(M)+Buffer.byteLength(w),d>si)throw Error(`MCP completion context exceeds ${si} bytes`);u[M]=w}return{ref:r,argument:{name:n,value:s},...o.length>0?{context:{arguments:u}}:{}}}function ci(t){let i=t.completion,n=JSON.stringify(i),s=Buffer.byteLength(n),e=zn("sha256").update(n).digest("hex"),r=i.values.length,o=[],u=new Set,d=0,p=0,c=r>ii||s>ft;for(let w of i.values.slice(0,ii)){let y=Buffer.byteLength(w),E=Math.max(0,ft-p);if(E===0){c=!0;break}let a=oi(w,Math.min(ft,E));if(p+=Buffer.byteLength(a),y>Buffer.byteLength(a))c=!0;let Dt=Mi(a),L=oi(Dt,Dn);if(Buffer.byteLength(L)<Buffer.byteLength(Dt))c=!0;if(u.has(L))continue;let Ft=Buffer.byteLength(L);if(d+Ft>Fn){c=!0;break}u.add(L),o.push(L),d+=Ft}if(o.length<r)c=!0;let M=i.total!==void 0&&Number.isSafeInteger(i.total)&&i.total>=0?i.total:void 0;return{values:o,...M!==void 0?{total:M}:{},hasMore:i.hasMore===!0||c||M!==void 0&&M>o.length,sourceValueCount:r,sourceBytes:s,projectedBytes:d,sha256:e,truncated:c}}function Mi(t){return[...t.normalize("NFKC")].filter((i)=>{let n=i.codePointAt(0)??0;if(n<32||n===127)return!1;return!jn.test(i)}).join("")}function G(t,i,n){if(typeof t!=="string"||!t||Buffer.byteLength(t)>n)throw Error(`MCP ${i} is invalid`);if(Mi(t)!==t||wi(t))throw Error(`MCP ${i} contains unsafe characters`);if(yi(t))throw Error(`MCP ${i} is unsafe`);return t}function di(t,i,n){if(typeof t!=="string"||Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);if(wi(t))throw Error(`MCP ${i} contains control characters`);return t}function wi(t){return[...t].some((i)=>{let n=i.codePointAt(0)??0;return n<32||n===127})}function yi(t){return["__proto__","constructor","prototype"].includes(t)}function oi(t,i){let n=Buffer.from(t);if(n.length<=i)return t;let s=n.subarray(0,Math.max(0,i)).toString("utf8");while(Buffer.byteLength(s)>i)s=s.slice(0,-1);return s}var At=20,_t=300000;function Ti(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${n} must be a finite number`);if(t<s||t>e)throw Error(`${n} must be between ${s} and ${e}`);return t}function H(t,i,n,s,e){let r=Ti(t,i,n,s,e);if(!Number.isInteger(r))throw Error(`${n} must be an integer`);return r}function Ei(t){let i=t.recovery;if(i!==void 0&&(i===null||typeof i!=="object"||Array.isArray(i)))throw Error("MCP recovery configuration must be an object");let n=i?.enabled??!0;if(typeof n!=="boolean")throw Error("MCP recovery enabled must be a boolean");let s=H(i?.maxAttempts,5,"MCP recovery maxAttempts",0,20),e=H(i?.initialDelayMs,1000,"MCP recovery initialDelayMs",10,300000),r=H(i?.maxDelayMs,30000,"MCP recovery maxDelayMs",e,300000),o=Ti(i?.jitterRatio,0.2,"MCP recovery jitterRatio",0,1),u=H(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:s,initialDelayMs:e,maxDelayMs:r,jitterRatio:o,terminalErrorThreshold:u}}function bi(t,i,n=Math.random){let s=Math.max(0,i-1),e=Math.min(t.initialDelayMs*2**s,t.maxDelayMs);if(t.jitterRatio===0)return e;let r=Math.min(1,Math.max(0,n())),o=1-t.jitterRatio+2*t.jitterRatio*r;return Math.max(0,Math.round(e*o))}function k(t){let n=(t instanceof Error?t.message:String(t)).replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/[\r\n\t]+/g," ").trim();if(Buffer.byteLength(n)<=512)return n;let s=Buffer.from(n).subarray(0,512).toString("utf8");while(Buffer.byteLength(s)>512)s=s.slice(0,-1);return s}function fi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return(n.includes("404")||n.includes("-32001"))&&(n.includes("session")||n.includes("not found"))}function hi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return["econnreset","etimedout","epipe","ehostunreach","econnrefused","body timeout error","socket hang up","connection closed","connection terminated","sse stream disconnected","failed to reconnect sse stream","maximum reconnection attempts"].some((s)=>n.includes(s))}function C(t){return new DOMException(String(t||"MCP connection recovery cancelled"),"AbortError")}async function Pt(t,i,n=!0){if(i.aborted)throw C(i.reason);await new Promise((s,e)=>{let o=setTimeout(()=>{i.removeEventListener("abort",u),s()},t);if(n)o.unref();let u=()=>{clearTimeout(o),i.removeEventListener("abort",u),e(C(i.reason))};i.addEventListener("abort",u,{once:!0})})}import{createHash as $i}from"node:crypto";var Rt=100,q=1000,K=1000,W=1000,at=100,Ai=64,Z=1048576,A=4194304,h=256,N=8192,g=256,m=16384,_i=64,Hn=4096,Pi=4194304,Ri=128;function Ci(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function qn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function b(t,i,n){if(t===void 0)return;if(i==="description"?qn(t):Ci(t))throw Error(`MCP ${i} contains control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);return t}function f(t,i,n){let s=t.trim();if(!s||s.length>n||Ci(s))throw Error(`MCP ${i} is invalid`);return s}function $t(t){return Buffer.byteLength(JSON.stringify(t))}function Ct(t,i){if($t(t)>Pi)throw Error(`MCP ${i} catalog exceeds ${Pi} bytes`)}function Q(t,i){let n=new Set;for(let s of t){if(n.has(s))throw Error(`MCP ${i} catalog contains duplicate "${s}"`);n.add(s)}}function ki(t){if(t.length>q)throw Error(`MCP resource catalog exceeds ${q} entries`);let i=t.map((n)=>({uri:f(n.uri,"resource URI",N),name:f(n.name,"resource name",h),...b(n.title,"resource title",h)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource MIME type",g)?{mimeType:n.mimeType}:{},...n.size!==void 0&&Number.isSafeInteger(n.size)&&n.size>=0?{size:n.size}:{}}));return Q(i.map((n)=>n.uri),"resource"),Ct(i,"resource"),i}function Oi(t){if(t.length>K)throw Error(`MCP resource template catalog exceeds ${K} entries`);let i=t.map((n)=>({uriTemplate:f(n.uriTemplate,"resource template URI",N),name:f(n.name,"resource template name",h),...b(n.title,"resource template title",h)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource template MIME type",g)?{mimeType:n.mimeType}:{}}));return Q(i.map((n)=>n.uriTemplate),"resource template"),Ct(i,"resource template"),i}function Li(t){if(t.length>W)throw Error(`MCP prompt catalog exceeds ${W} entries`);let i=t.map((n)=>{if((n.arguments?.length??0)>_i)throw Error(`MCP prompt "${n.name}" exceeds ${_i} arguments`);let s=(n.arguments??[]).map((e)=>{let r=f(e.name,"prompt argument name",h);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...b(e.description,"description",Hn)?{description:e.description}:{},required:e.required===!0}});return Q(s.map((e)=>e.name),`prompt "${n.name}" argument`),{name:f(n.name,"prompt name",h),...b(n.title,"prompt title",h)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},arguments:s}});return Q(i.map((n)=>n.name),"prompt"),Ct(i,"prompt"),i}function ai(t){return $i("sha256").update(JSON.stringify(t)).digest("hex")}function I(t,i,n){let s=new Map(t.map((r)=>[n(r),ai(r)])),e=new Map(i.map((r)=>[n(r),ai(r)]));return{added:[...e.keys()].filter((r)=>!s.has(r)).sort(),removed:[...s.keys()].filter((r)=>!e.has(r)).sort(),updated:[...e.keys()].filter((r)=>s.has(r)&&s.get(r)!==e.get(r)).sort()}}function Si(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function kt(t,i,n){if(t.bytes+=i,t.bytes>A)throw Error(`MCP ${n} exceeds ${A} total bytes`)}function xi(t,i,n){if(t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP ${i} contains invalid base64`);let s=Buffer.from(t,"base64");if(s.length>A)throw Error(`MCP ${i} exceeds ${A} decoded bytes`);return kt(n,s.length,i),{size:s.length,sha256:$i("sha256").update(s).digest("hex"),omitted:!0}}function gi(t,i){let n=f(typeof t.uri==="string"?t.uri:"","resource content URI",N),s=typeof t.mimeType==="string"?b(t.mimeType,"resource MIME type",g):void 0;if(typeof t.text==="string"){let e=Buffer.byteLength(t.text);if(e>Z)throw Error(`MCP resource text exceeds ${Z} bytes`);return kt(i,e,"resource result"),{uri:n,...s?{mimeType:s}:{},text:t.text}}if(typeof t.blob==="string")return{uri:n,...s?{mimeType:s}:{},binary:xi(t.blob,"resource blob",i)};throw Error("MCP resource content has neither text nor blob data")}function mi(t){let i=t&&typeof t==="object"&&Array.isArray(t.contents)?t.contents:[];if(i.length>Ai)throw Error(`MCP resource result exceeds ${Ai} contents`);let n={bytes:0},s=i.map((e)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw Error("MCP resource content is malformed");return gi(e,n)});if($t(s)>A)throw Error(`MCP resource result exceeds ${A} bytes`);return{contents:s}}function li(t){if(!t||typeof t!=="object"||Array.isArray(t))throw Error("MCP prompt result is malformed");let i=t,n=Array.isArray(i.messages)?i.messages:[];if(n.length>Ri)throw Error(`MCP prompt exceeds ${Ri} messages`);let s={bytes:0},e=n.map((r)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error("MCP prompt message is malformed");let o=r,u=o.role;if(u!=="user"&&u!=="assistant")throw Error("MCP prompt message has an invalid role");let d=o.content;if(!d||typeof d!=="object"||Array.isArray(d))throw Error("MCP prompt message content is malformed");let p=d;if(p.type==="text"&&typeof p.text==="string"){let c=Buffer.byteLength(p.text);if(c>Z)throw Error(`MCP prompt text exceeds ${Z} bytes`);return kt(s,c,"prompt result"),{role:u,content:{type:"text",text:p.text}}}if((p.type==="image"||p.type==="audio")&&typeof p.data==="string"&&typeof p.mimeType==="string")return{role:u,content:{type:p.type,mimeType:f(p.mimeType,"prompt content MIME type",g),binary:xi(p.data,`prompt ${p.type}`,s)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:u,content:{type:"resource",resource:gi(p.resource,s)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:u,content:{type:"resource_link",uri:f(p.uri,"prompt resource link URI",N),name:f(p.name,"prompt resource link name",h),...typeof p.mimeType==="string"?{mimeType:f(p.mimeType,"prompt resource link MIME type",g)}:{},...typeof p.description==="string"?{description:b(p.description,"description",m)}:{}}};throw Error(`Unsupported MCP prompt content type: ${String(p.type)}`)});if($t(e)>A)throw Error(`MCP prompt result exceeds ${A} bytes`);return{...typeof i.description==="string"?{description:b(i.description,"description",m)}:{},messages:e}}var Ui=4000,Bi=4096,Xi=32,Kn=128,zi=1000,Yi=100,Di=65536,Wn=new Set(["__proto__","constructor","prototype"]);function Fi(t,i){if(!t.trim())throw Error("MCP elicitation server name is empty");if(!i.message.trim())throw Error("MCP elicitation message is empty");if(i.message.length>Ui)throw Error(`MCP elicitation message exceeds ${Ui} characters`);if(i.mode==="url"){let e=In(i.url);if(!i.elicitationId.trim())throw Error("MCP URL elicitation ID is empty");return{serverName:t,mode:"url",message:i.message,url:e.toString(),domain:e.hostname,elicitationId:i.elicitationId}}let n=Object.entries(i.requestedSchema.properties);if(n.length>Xi)throw Error(`MCP elicitation exceeds the ${Xi} field limit`);let s=new Set(i.requestedSchema.required??[]);for(let e of s)if(!Object.hasOwn(i.requestedSchema.properties,e))throw Error(`MCP elicitation requires an unknown field: ${e}`);return{serverName:t,mode:"form",message:i.message,fields:n.map(([e,r])=>Zn(e,r,s.has(e))),requestedSchema:structuredClone(i.requestedSchema)}}function ie(t){let i=Object.create(null);for(let n of t.fields??[])if(n.defaultValue!==void 0)i[n.name]=Array.isArray(n.defaultValue)?[...n.defaultValue]:n.defaultValue;return i}function ne(t,i){let n=i.trim();if(!n){if(t.defaultValue!==void 0)return t.defaultValue;if(!t.required)return;throw Error(`${t.title} is required`)}if(t.type==="number"||t.type==="integer"){let s=Number(n);if(!Number.isFinite(s))throw Error(`${t.title} must be a finite number`);if(t.type==="integer"&&!Number.isSafeInteger(s))throw Error(`${t.title} must be a safe integer`);return s}if(t.type==="boolean"){if(["true","yes","y","1"].includes(n.toLowerCase()))return!0;if(["false","no","n","0"].includes(n.toLowerCase()))return!1;throw Error(`${t.title} must be true or false`)}return n}function Ji(t,i){if(i.action!=="accept")return{action:i.action};if(t.mode==="url")return{action:"accept"};if(!t.requestedSchema)throw Error("MCP form elicitation schema is unavailable");let n=i.content??{};if(Buffer.byteLength(JSON.stringify(n),"utf8")>Di)throw Error(`MCP elicitation response exceeds ${Di} bytes`);for(let r of Object.keys(n))Vi(r);for(let r of Object.values(n))if(typeof r==="number"&&(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r)))throw Error("MCP elicitation response contains an unsafe number");let s=x.Unsafe({...t.requestedSchema,additionalProperties:!1}),e=X(s,n);if(!e.success)throw Error(`Invalid MCP elicitation response: ${e.error.message}`);return{action:"accept",content:e.data}}function Zn(t,i,n){Vi(t);let s=tt(i.title?.trim()||t,"field title"),e=i.description?tt(i.description,"field description"):void 0,r={name:t,title:s,description:e,required:n};if(i.type==="boolean")return{...r,type:"boolean",...typeof i.default==="boolean"?{defaultValue:i.default}:{}};if(i.type==="number"||i.type==="integer")return{...r,type:i.type,...typeof i.default==="number"?{defaultValue:i.default}:{},...i.minimum!==void 0?{minimum:i.minimum}:{},...i.maximum!==void 0?{maximum:i.maximum}:{}};if(i.type==="array"){let u=Nn(i);return{...r,type:"multi-select",options:u,...Array.isArray(i.default)&&i.default.every((d)=>typeof d==="string")?{defaultValue:[...i.default]}:{},...i.minItems!==void 0?{minItems:i.minItems}:{},...i.maxItems!==void 0?{maxItems:i.maxItems}:{}}}let o=Qn(i);if(o)return{...r,type:"select",options:o,...typeof i.default==="string"?{defaultValue:i.default}:{}};return{...r,type:"string",...typeof i.default==="string"?{defaultValue:i.default}:{},...i.format?{format:i.format}:{},...i.minLength!==void 0?{minLength:i.minLength}:{},...i.maxLength!==void 0?{maxLength:i.maxLength}:{}}}function Qn(t){if(t.oneOf)return v(t.oneOf.map((i)=>({value:i.const,label:i.title})));if(!t.enum)return;return v(t.enum.map((i,n)=>({value:i,label:t.enumNames?.[n]??i})))}function Nn(t){if(t.items?.anyOf)return v(t.items.anyOf.map((i)=>({value:i.const,label:i.title})));if(t.items?.enum)return v(t.items.enum.map((i)=>({value:i,label:i})));throw Error("MCP multi-select elicitation is missing enum options")}function v(t){if(t.length===0||t.length>Yi)throw Error(`MCP elicitation options must contain 1-${Yi} items`);let i=new Set;return t.map((n)=>{if(i.has(n.value))throw Error(`MCP elicitation contains duplicate option: ${n.value}`);return i.add(n.value),{value:tt(n.value,"option value"),label:tt(n.label,"option label")}})}function Vi(t){if(!t||t.length>Kn||Wn.has(t))throw Error(`Unsafe MCP elicitation field name: ${t||"(empty)"}`)}function tt(t,i){if(t.length>zi)throw Error(`MCP elicitation ${i} exceeds ${zi} characters`);return t}function In(t){if(t.length>Bi)throw Error(`MCP elicitation URL exceeds ${Bi} characters`);let i;try{i=new URL(t)}catch{throw Error("MCP elicitation URL is invalid")}if(!["http:","https:"].includes(i.protocol))throw Error(`MCP elicitation URL protocol is not allowed: ${i.protocol}`);if(i.username||i.password)throw Error("MCP elicitation URL must not contain credentials");return i}import{createHash as Wi}from"node:crypto";var l=1000,it=100,vn=256,ji=16384,Gi=262144,Hi=4194304,qi=24;function ts(t,i=10){return Wi("sha256").update(t).digest("hex").slice(0,i)}function Ot(t){if(Array.isArray(t))return t.map(Ot);if(!t||typeof t!=="object")return t;let i=t;return Object.fromEntries(Object.keys(i).sort().map((n)=>[n,Ot(i[n])]))}function Zi(t){let i=t.normalize("NFKC"),n=i.replace(/[^A-Za-z0-9_-]/g,"_");if(n&&n===i&&n.length<=qi)return n;return`${(n||"unnamed").slice(0,qi-11)}_${ts(i)}`}function Lt(t,i){return`${is(t)}${Zi(i)}`}function is(t){return`mcp__${Zi(t)}__`}function Ki(t){return Wi("sha256").update(JSON.stringify(Ot({name:t.name,description:t.description,inputSchema:t.inputSchema,taskSupport:t.taskSupport}))).digest("hex")}function ns(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Qi(t){if(t.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);let i=new Set,n=[],s=0;for(let e of t){let r=e.name.trim();if(!r||r.length>vn||ns(r))throw Error("MCP tool catalog contains an invalid tool name");if(i.has(r))throw Error(`MCP tool catalog contains duplicate tool "${r}"`);i.add(r);let o=e.description??"";if(Buffer.byteLength(o)>ji)throw Error(`MCP tool "${r}" description exceeds ${ji} bytes`);let u=JSON.stringify(e.inputSchema),d=Buffer.byteLength(u);if(d>Gi)throw Error(`MCP tool "${r}" schema exceeds ${Gi} bytes`);if(s+=Buffer.byteLength(r)+Buffer.byteLength(o)+d,s>Hi)throw Error(`MCP tool catalog exceeds ${Hi} bytes`);n.push({name:r,description:o,inputSchema:JSON.parse(u),...e.execution?.taskSupport?{taskSupport:e.execution.taskSupport}:{}})}return n}function Ni(t,i){let n=new Map(t.map((e)=>[e.name,Ki(e)])),s=new Map(i.map((e)=>[e.name,Ki(e)]));return{added:[...s.keys()].filter((e)=>!n.has(e)).sort(),removed:[...n.keys()].filter((e)=>!s.has(e)).sort(),updated:[...s.keys()].filter((e)=>n.has(e)&&n.get(e)!==s.get(e)).sort()}}function nt(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function vi(t){if(t instanceof zt||t instanceof U)return{type:"auth_error",isRetryable:!1,originalError:t};if(!(t instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(t))};let i=t.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((e)=>i.includes(e)))return{type:"config_error",isRetryable:!1,originalError:t};if(i.includes("unauthorized")||i.includes("401")||i.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:t};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((e)=>i.includes(e)))return{type:"network_temporary",isRetryable:!0,originalError:t};return{type:"unknown",isRetryable:!0,originalError:t}}class Yt extends bs{config;runtimeOptions;status="disconnected";sdkClient=null;tools=new Map;toolCatalogRevision=0;toolRefreshPromise;toolRefreshRequested=!1;resources=[];resourceTemplates=[];prompts=[];contentCatalogRevision=0;contentRefreshPromise;requestedContentCatalogs=new Set;contentRefreshReason="manual";catalogGeneration=0;desiredResourceSubscriptions=new Set;activeResourceSubscriptions=new Set;serverInfo=null;serverInstructions;completionCallsInFlight=0;loggingPolicy;logWindowStartedAt=0;logEventsInWindow=0;logRateWarningEmitted=!1;recoveryPolicy;desiredConnected=!1;connectionGeneration=0;connectPromise;connectAbortController;recoveryPromise;recoveryAbortController;recoveryState;consecutiveTerminalErrors=0;oauthProvider=null;serverName;healthMonitor=null;activeInteraction;taskInteractions=new Map;taskPolicy;roots;constructor(t,i,n,s={}){super();this.config=t;this.runtimeOptions=s;this.serverName=i||"default",this.recoveryPolicy=Ei(t),this.loggingPolicy=on(t),this.taskPolicy=yn(t.tasks),this.roots=(s.roots??[]).map((r)=>{let o=es.native(Ii.resolve(r));return{uri:rs(o).href,name:Ii.basename(o)||o}});let e=tn(t);if(this.config={...t,...e?{oauth:e}:{}},e?.enabled&&t.url&&s.oauthCredentialAccess!==!1)this.oauthProvider=new rn(this.serverName,t.url,e,s.oauthStorageRoot?{tokenStorage:new en(s.oauthStorageRoot)}:{});if(n?.enabled)this.healthMonitor=new bt(this,n),this.healthMonitor.on("unhealthy",(r,o)=>{this.emit("unhealthy",r,o)})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get contentCatalog(){return{resources:structuredClone(this.resources),resourceTemplates:structuredClone(this.resourceTemplates),prompts:structuredClone(this.prompts)}}get completionSupported(){return Boolean(this.sdkClient?.getServerCapabilities()?.completions)}get tasks(){return{...this.taskPolicy}}get server(){return this.serverInfo}get instructions(){return this.serverInstructions?structuredClone(this.serverInstructions):void 0}get healthCheck(){return this.healthMonitor}get recovery(){return this.recoveryState?structuredClone(this.recoveryState):void 0}get logging(){return{...this.loggingPolicy}}get oauthEnabled(){return this.config.oauth?.enabled===!0}async getOAuthStatus(){if(!this.oauthEnabled)return"disabled";if(this.runtimeOptions.oauthCredentialAccess===!1)return"unavailable";return this.oauthProvider?.getStatus()??"error"}async beginOAuthLogin(t={}){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);return t.openBrowser?this.oauthProvider.openAuthorization():this.oauthProvider.beginAuthorization()}async logoutOAuth(){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(this.status!=="disconnected")await this.disconnect();await this.oauthProvider.logout()}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(t=3,i=1000){if(!Number.isInteger(t)||t<1||t>At)throw Error(`MCP connection maxRetries must be an integer between 1 and ${At}`);if(!Number.isFinite(i)||i<0||i>_t)throw Error(`MCP connection initialDelay must be between 0 and ${_t}`);if(this.status==="connected")return;if(this.recoveryPromise)return this.recoveryPromise;if(this.connectPromise)return this.connectPromise;this.desiredConnected=!0;let n=++this.connectionGeneration,s=new AbortController;this.connectAbortController=s;let e=this.runInitialConnection(Math.max(1,t),Math.max(0,i),n,s.signal).finally(()=>{if(this.connectPromise===e)this.connectPromise=void 0;if(this.connectAbortController===s)this.connectAbortController=void 0});return this.connectPromise=e,e}async runInitialConnection(t,i,n,s){let e;for(let o=1;o<=t;o++){this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!1);return}catch(u){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=u instanceof Error?u:Error(String(u)),!vi(e).isRetryable||o===t)break;await Pt(i*2**Math.max(0,o-1),s,!1)}}let r=e??Error("MCP connection failed");if(this.isConnectionGenerationCurrent(n))this.invalidateLiveConnection(!1),this.setStatus("error"),this.emitClientError(r);throw r}async doConnect(t,i){let n;try{this.assertConnectionGeneration(t),this.setStatus(i?"reconnecting":"connecting");let s=Mn(this.config.sampling),e={...s,enabled:s.enabled&&this.runtimeOptions.samplingAvailable===!0};n=new ds({name:sn(),version:nn()},{capabilities:{roots:{listChanged:!1},elicitation:{form:{applyDefaults:!1},url:{}},...e.enabled?{sampling:{}}:{}},listChanged:{tools:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshTools("notification")}},resources:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["resources"])}},prompts:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["prompts"])}}}});let r=n;if(this.sdkClient=r,this.resetCatalogRefreshState(),this.registerElicitationHandlers(r),this.registerRootHandler(r),e.enabled)this.registerSamplingHandler(r,e);if(this.registerResourceNotificationHandler(r),this.registerLoggingHandler(r),this.taskPolicy.enabled)this.registerTaskStatusHandler(r);r.onclose=()=>{this.handleUnexpectedClose(r,t)},r.onerror=(d)=>{this.handleTransportError(r,t,d)};let o=await this.createTransport();this.assertConnectionGeneration(t),await r.connect(o),this.assertConnectionGeneration(t);let u=r.getServerVersion();this.serverInfo={name:u?.name||"Unknown",version:u?.version||"0.0.0"},this.serverInstructions=Tn(r.getInstructions(),{exposeDetails:this.runtimeOptions.exposeInstructions}),await this.configureLogging(r),await this.refreshTools("initial"),await this.refreshContentCatalogs("initial").catch(()=>{return}),await this.reconcileResourceSubscriptions(r),this.assertConnectionGeneration(t),this.consecutiveTerminalErrors=0,this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor?.resetFailureCount(),this.healthMonitor?.start()}catch(s){if(n&&this.sdkClient===n)this.sdkClient=null;if(n)n.onclose=void 0,n.onerror=void 0,await n.close().catch(()=>{return});throw s}}handleUnexpectedClose(t,i){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;this.startRecovery(Error(`MCP server "${this.serverName}" connection closed`),"transport_closed",!1)}handleTransportError(t,i,n){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;if(this.emit("transportError",{serverName:this.serverName,error:k(n)}),fi(n)){this.startRecovery(n,"session_expired",!0);return}if(!hi(n)){this.consecutiveTerminalErrors=0;return}if(this.consecutiveTerminalErrors++,n.message.toLowerCase().includes("maximum reconnection attempts")||this.consecutiveTerminalErrors>=this.recoveryPolicy.terminalErrorThreshold)this.startRecovery(n,"transport_error",!0)}requestRecovery(t,i){if(!this.desiredConnected||this.status!=="connected"||this.recoveryPromise)return;this.startRecovery(t,i,!0)}startRecovery(t,i,n){if(!this.desiredConnected||this.recoveryPromise)return;let s=this.sdkClient;if(this.sdkClient=null,s)s.onclose=void 0,s.onerror=void 0;this.healthMonitor?.stop(),this.invalidateLiveConnection(!0);let e=++this.connectionGeneration,r=new AbortController;if(this.recoveryAbortController=r,this.setStatus("reconnecting"),n&&s)s.close().catch(()=>{return});let o=Promise.resolve().then(()=>this.runRecoveryLoop(t,i,e,r.signal)).finally(()=>{if(this.recoveryPromise===o)this.recoveryPromise=void 0;if(this.recoveryAbortController===r)this.recoveryAbortController=void 0});this.recoveryPromise=o,o.catch(()=>{return})}async runRecoveryLoop(t,i,n,s){let e=t;if(!this.recoveryPolicy.enabled||this.recoveryPolicy.maxAttempts===0){this.failRecovery(e,i,0,n);return}for(let r=1;r<=this.recoveryPolicy.maxAttempts;r++){this.assertConnectionGeneration(n,s);let o=bi(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),u=Date.now()+o;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:u,error:k(e)}),await Pt(o,s),this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!0),this.healthMonitor?.resetFailureCount(),this.publishConnectionLifecycle({phase:"recovered",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts}),this.emit("reconnected");return}catch(d){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=d instanceof Error?d:Error(String(d)),!vi(e).isRetryable){this.failRecovery(e,i,r,n);return}}}this.failRecovery(e,i,this.recoveryPolicy.maxAttempts,n)}failRecovery(t,i,n,s){if(!this.isConnectionGenerationCurrent(s))return;this.setStatus("error"),this.publishConnectionLifecycle({phase:"failed",reason:i,attempt:n,maxAttempts:this.recoveryPolicy.maxAttempts,error:k(t)}),this.emit("reconnectFailed",t)}publishConnectionLifecycle(t){this.recoveryState=structuredClone(t),this.emit("connectionLifecycleChanged",structuredClone(t))}isConnectionGenerationCurrent(t){return this.desiredConnected&&this.connectionGeneration===t}assertConnectionGeneration(t,i){if(i?.aborted||!this.desiredConnected||this.connectionGeneration!==t)throw C(i?.reason)}invalidateLiveConnection(t){if(this.resetCatalogRefreshState(),this.tools.clear(),this.resources=[],this.resourceTemplates=[],this.prompts=[],this.activeResourceSubscriptions.clear(),!t)this.desiredResourceSubscriptions.clear();if(!t)this.taskInteractions.clear();this.serverInfo=null,this.serverInstructions=void 0,this.consecutiveTerminalErrors=0}resetCatalogRefreshState(){this.catalogGeneration++,this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,this.contentRefreshPromise=void 0,this.requestedContentCatalogs.clear(),this.contentRefreshReason="manual"}emitClientError(t){if(this.listenerCount("error")>0)this.emit("error",t)}async ping(t=1e4){let i=this.sdkClient;if(!i||this.status!=="connected")throw Error(`MCP server "${this.serverName}" is not connected`);let n=new AbortController,s=setTimeout(()=>n.abort("MCP health check timeout"),t);s.unref();try{await i.ping({signal:n.signal,timeout:t,maxTotalTimeout:t})}catch(e){if(n.signal.aborted)throw Error(`MCP server "${this.serverName}" health check timed out after ${t}ms`);throw e}finally{clearTimeout(s)}}async disconnect(){this.desiredConnected=!1,this.connectionGeneration++,this.connectAbortController?.abort("MCP client disconnected"),this.recoveryAbortController?.abort("MCP client disconnected"),this.healthMonitor?.stop();let t=this.sdkClient;if(this.sdkClient=null,t)t.onclose=void 0,t.onerror=void 0,await t.close().catch(()=>{return});await Promise.allSettled([this.connectPromise,this.recoveryPromise].filter((i)=>i!==void 0)),this.invalidateLiveConnection(!1),this.recoveryState=void 0,await this.oauthProvider?.dispose(),this.setStatus("disconnected"),this.emit("disconnected")}async callTool(t,i={},n={}){let s=this.sdkClient;if(!s||this.status!=="connected")throw Error("客户端未连接到服务器");if(!this.tools.has(t))throw Error(`工具 "${t}" 不存在`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive tool calls`);let e=gt(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let o=new AbortController,u=setTimeout(()=>o.abort("mcp-tool-timeout"),e.totalTimeoutMs);u.unref();let d=n.signal?AbortSignal.any([n.signal,o.signal]):o.signal,p={count:0};try{return await s.callTool({name:t,arguments:i},St,{signal:d,timeout:e.idleTimeoutMs,resetTimeoutOnProgress:!0,maxTotalTimeout:e.totalTimeoutMs,onprogress:(M)=>{let w=mt(M,p,e);if(w&&!d.aborted&&this.activeInteraction?.token===r)n.progressHandler?.(w),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...w})}})}catch(c){if(n.signal?.aborted)throw new DOMException(String(n.signal.reason||"MCP tool call cancelled"),"AbortError");if(o.signal.aborted&&!n.signal?.aborted)throw new P(_.RequestTimeout,`MCP server "${this.serverName}" tool "${t}" timed out after ${e.totalTimeoutMs}ms`);throw console.error(`[McpClient] 调用工具 "${t}" 失败:`,c),c}finally{if(clearTimeout(u),this.activeInteraction?.token===r)this.activeInteraction=void 0}}getToolTaskSupport(t){return this.tools.get(t)?.taskSupport}async createToolTask(t,i,n,s,e){let r=this.sdkClient;if(!r||this.status!=="connected")throw Error("MCP client is not connected");if(!this.taskPolicy.enabled)throw Error(`MCP tasks are disabled for server "${this.serverName}"`);if(!r.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);let o=this.getToolTaskSupport(t);if(o!=="required"&&o!=="optional")throw Error(`MCP tool "${t}" does not support task execution`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive task creation`);let u=gt(this.config),d=Symbol(t),p={token:d,context:{...n,signal:s},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let c={count:0},M=r.experimental.tasks.callToolStream({name:t,arguments:i},St,{signal:s,task:{ttl:e??this.taskPolicy.defaultTtlMs,pollInterval:this.taskPolicy.pollIntervalMs},timeout:u.idleTimeoutMs,maxTotalTimeout:u.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let E=mt(y,c,u);if(E&&!s.aborted&&this.hasInteractionToken(d))n.progressHandler?.(E),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...E})}}),w=!1;try{let y=await M.next();if(await M.return(void 0),y.done||y.value.type!=="taskCreated"){if(!y.done&&y.value.type==="error")throw y.value.error;throw Error(`MCP tool "${t}" did not create a task`)}if(this.sdkClient!==r)throw Error("MCP client changed while creating a task");let E=Ut(y.value.task,this.taskPolicy);return this.taskInteractions.set(E.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:E}),E}finally{if(this.activeInteraction?.token===d)this.activeInteraction=void 0;if(!w){for(let[y,E]of this.taskInteractions)if(E.token===d)this.taskInteractions.delete(y)}}}async getToolTask(t,i,n){let s=this.requireTaskClient(),e=await s.experimental.tasks.getTask(t,{signal:n,timeout:this.taskPolicy.pollIntervalMs+1e4,maxTotalTimeout:this.taskPolicy.pollIntervalMs+1e4});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task");return Ut(e,this.taskPolicy,{taskId:t,createdAt:i})}async getToolTaskResult(t,i,n=this.taskPolicy.maxLifetimeMs){let s=this.requireTaskClient(),e=Math.max(1,Math.min(n,this.taskPolicy.maxLifetimeMs)),r=await s.experimental.tasks.getTaskResult(t,St,{signal:i,timeout:e,maxTotalTimeout:e});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task result");return r}async cancelToolTask(t,i){let n=this.requireTaskClient();if(!n.getServerCapabilities()?.tasks?.cancel)throw Error(`MCP server "${this.serverName}" does not support task cancellation`);if(await n.experimental.tasks.cancelTask(t,{signal:i,timeout:15000,maxTotalTimeout:15000}),this.sdkClient!==n)throw Error("MCP client changed while cancelling a task")}async normalizeToolTaskResult(t){return j(t,this.runtimeOptions.artifactWriter)}releaseTaskInteraction(t){this.taskInteractions.delete(t)}async waitUntilConnected(t,i){if(this.status==="connected"&&this.sdkClient)return;if(!this.desiredConnected)throw Error(`MCP server "${this.serverName}" is disconnected`);await new Promise((n,s)=>{let e=setTimeout(()=>{d(),s(Error(`MCP server "${this.serverName}" recovery timed out`))},i);e.unref();let r=()=>{d(),n()},o=()=>{if(this.desiredConnected)return;d(),s(Error(`MCP server "${this.serverName}" was disconnected`))},u=()=>{d(),s(new DOMException(String(t.reason||"MCP task recovery cancelled"),"AbortError"))},d=()=>{clearTimeout(e),this.off("connected",r),this.off("disconnected",o),t.removeEventListener("abort",u)};if(this.on("connected",r),this.on("disconnected",o),t.addEventListener("abort",u,{once:!0}),t.aborted)u()})}requireTaskClient(){let t=this.sdkClient;if(!t||this.status!=="connected"||!this.taskPolicy.enabled)throw Error(`MCP server "${this.serverName}" task client is unavailable`);if(!t.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);return t}hasInteractionToken(t){if(this.activeInteraction?.token===t)return!0;return[...this.taskInteractions.values()].some((i)=>i.token===t)}registerRootHandler(t){t.setRequestHandler(ws,async()=>({roots:this.roots.map((i)=>({...i}))}))}resolveInteraction(t){let i=t._meta?.["io.modelcontextprotocol/related-task"]?.taskId;return i?this.taskInteractions.get(i):this.activeInteraction}registerTaskStatusHandler(t){t.setNotificationHandler(Es,(i)=>{this.emit("taskStatus",i.params)})}registerSamplingHandler(t,i){t.setRequestHandler(us,async(n,s)=>{let e=this.resolveInteraction(n.params);if(!e?.context.confirmationHandler||!e.context.samplingHandler)throw new P(_.InvalidRequest,"MCP sampling requires an active interactive Session");if(e.samplingInFlight)throw new P(_.InvalidRequest,"MCP server does not allow overlapping sampling requests");e.samplingInFlight=!0;try{if(e.samplingRequests++,e.samplingRequests>i.maxRequestsPerToolCall)throw new P(_.InvalidRequest,`MCP sampling exceeded ${i.maxRequestsPerToolCall} requests for one tool call`);let r=e.context.signal?AbortSignal.any([e.context.signal,s.signal]):s.signal;if(r.aborted)throw new P(_.InvalidRequest,"MCP sampling was cancelled");let o;try{o=wn(n.params,i)}catch(p){throw new P(_.InvalidRequest,p instanceof Error?p.message:String(p))}let u=await e.context.confirmationHandler.requestConfirmation({type:"mcpSampling",kind:"execute",toolName:`MCP sampling: ${this.serverName}`,title:"MCP model sampling request",message:`MCP server "${this.serverName}" wants to call the current Session model with up to ${o.maxTokens} output tokens.`,details:o.preview,risks:[`May consume up to ${o.maxTokens} output tokens`,"The model response will be returned to the MCP server"]},r);if(r.aborted||u.reason===Xt||u.reason==="timeout")throw new P(_.InvalidRequest,"MCP sampling was cancelled");if(!u.approved)throw new P(_.InvalidRequest,"MCP sampling was denied");let d=await e.context.samplingHandler(o,r);return this.emit("samplingCompleted",{serverName:this.serverName,model:d.model,maxTokens:o.maxTokens}),d}finally{e.samplingInFlight=!1}})}registerElicitationHandlers(t){t.setRequestHandler(Ms,async(i,n)=>{let s=this.resolveInteraction(i.params)?.context;if(!s?.confirmationHandler)return this.emit("elicitationCancelled",{serverName:this.serverName,reason:"no-interaction-handler"}),{action:"cancel"};let e=s.signal?AbortSignal.any([s.signal,n.signal]):n.signal;if(e.aborted)return{action:"cancel"};let r;try{r=Fi(this.serverName,i.params)}catch(o){return this.emit("elicitationRejected",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"decline"}}try{let o=s.sessionId&&s.workspaceRoot&&s.permissionMode?{projectDir:s.workspaceRoot,sessionId:s.sessionId,permissionMode:s.permissionMode,abortSignal:e}:void 0,u=o?await Bt.getInstance().executeElicitationHooks(r,o):{},d;if(u.blockedReason)d={action:"decline"};else if(u.response)d=u.response;else{let M=await s.confirmationHandler.requestConfirmation({type:"mcpElicitation",message:r.message,title:`MCP input requested by ${this.serverName}`,mcpElicitation:r},e),w=this.resolveElicitationAction(M,e);if(d=M.elicitation??{action:w},w==="accept"&&r.mode==="url"&&M.openExternalUrl&&r.url)await fs(r.url,{wait:!1})}let p=o?await Bt.getInstance().executeElicitationResultHooks(r,d,o):{};if(p.blockedReason)d={action:"cancel"};else if(p.response)d=p.response;let c=Ji(r,d);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:c.action,elicitationId:r.elicitationId}),c}catch(o){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"cancel"}}}),t.setNotificationHandler(cs,(i)=>{this.emit("elicitationCompleted",{serverName:this.serverName,elicitationId:i.params.elicitationId})})}resolveElicitationAction(t,i){if(i.aborted||t.reason===Xt||t.reason==="timeout")return"cancel";if(t.elicitation)return t.elicitation.action;return t.approved?"accept":"decline"}async createTransport(){let{type:t,command:i,args:n,env:s,cwd:e,url:r,headers:o,oauth:u}=this.config,d;if(u?.enabled){if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(!await this.oauthProvider.hasUsableCredentials())throw new zt(this.serverName);d=this.oauthProvider}if(t==="stdio"){if(!i)throw Error("stdio 传输需要 command 参数");let p={};for(let[c,M]of Object.entries(process.env))if(M!==void 0)p[c]=M;return new ps({command:i,args:n||[],env:{...p,...s},cwd:e,stderr:"ignore"})}else if(t==="sse"){if(!r)throw Error("sse 传输需要 url 参数");return new os(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}else if(t==="http"){if(!r)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:p}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new p(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}throw Error(`不支持的传输类型: ${t}`)}async refreshTools(t="manual"){if(this.toolRefreshRequested=!0,this.toolRefreshPromise)return this.toolRefreshPromise;let i=this.catalogGeneration,n=(t==="notification"?new Promise((s)=>{setTimeout(s,25).unref()}):Promise.resolve()).then(()=>this.runToolRefresh(t)).finally(()=>{if(i!==this.catalogGeneration||this.toolRefreshPromise!==n)return;let s=this.toolRefreshRequested;if(this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,s&&this.sdkClient)this.refreshTools("notification")});return this.toolRefreshPromise=n,n}async waitForToolRefresh(){while(this.toolRefreshPromise)await this.toolRefreshPromise}async runToolRefresh(t){let i=t;for(let n=0;n<3&&this.toolRefreshRequested;n++){this.toolRefreshRequested=!1;try{await this.fetchAndPublishTools(i)}catch(s){if(this.emit("toolsRefreshFailed",{serverName:this.serverName,reason:i,error:s instanceof Error?s:Error(String(s))}),i!=="notification")throw s;return}i="notification"}}async fetchAndPublishTools(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=[],s=new Set,e;for(let p=0;p<it;p++){let c=await i.listTools(e?{cursor:e}:void 0);if(n.push(...c.tools),n.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);if(e=c.nextCursor,!e)break;if(s.has(e))throw Error("MCP tool catalog returned a repeated cursor");if(s.add(e),p===it-1)throw Error(`MCP tool catalog exceeds ${it} pages`)}let r=Qi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing tools");let o=this.availableTools,u=Ni(o,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(u))return;this.toolCatalogRevision++;let d={revision:this.toolCatalogRevision,reason:t,...u};this.emit("toolsUpdated",this.availableTools,d)}async refreshContentCatalogs(t="manual",i=["resources","prompts"]){let n=this.sdkClient?.getServerCapabilities();for(let r of i){if(r==="resources"&&n?.resources)this.requestedContentCatalogs.add(r);if(r==="prompts"&&n?.prompts)this.requestedContentCatalogs.add(r)}if(this.requestedContentCatalogs.size===0)return;if(this.contentRefreshPromise){if(t!=="notification")this.contentRefreshReason=t;return this.contentRefreshPromise}this.contentRefreshReason=t;let s=this.catalogGeneration,e=(t==="notification"?new Promise((r)=>{setTimeout(r,25).unref()}):Promise.resolve()).then(()=>this.runContentCatalogRefresh()).finally(()=>{if(s!==this.catalogGeneration||this.contentRefreshPromise!==e)return;let r=this.requestedContentCatalogs.size>0;if(this.contentRefreshPromise=void 0,this.contentRefreshReason="manual",r&&this.sdkClient)this.refreshContentCatalogs("notification")});return this.contentRefreshPromise=e,e}async waitForCatalogRefresh(){while(this.toolRefreshPromise||this.contentRefreshPromise)await Promise.all([this.toolRefreshPromise??Promise.resolve(),this.contentRefreshPromise??Promise.resolve()])}async runContentCatalogRefresh(){for(let t=0;t<3&&this.requestedContentCatalogs.size>0;t++){let i=[...this.requestedContentCatalogs];this.requestedContentCatalogs.clear();let n=this.contentRefreshReason;this.contentRefreshReason="notification";let s=[];for(let e of i)try{if(e==="resources")await this.fetchAndPublishResourceCatalog(n);else await this.fetchAndPublishPromptCatalog(n)}catch(r){let o=r instanceof Error?r:Error(String(r));s.push(o),this.emit("contentCatalogRefreshFailed",{serverName:this.serverName,catalog:e,reason:n,error:o})}if(s.length>0&&n!=="notification")throw AggregateError(s,`Failed to refresh MCP content catalogs for "${this.serverName}"`)}}async fetchAndPublishResourceCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("resource",q,(d)=>i.listResources(d?{cursor:d}:void 0),(d)=>d.resources),s=await this.fetchContentPages("resource template",K,(d)=>i.listResourceTemplates(d?{cursor:d}:void 0),(d)=>d.resourceTemplates),e=ki(n),r=Oi(s);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing resource catalogs");let o=I(this.resources,e,(d)=>d.uri),u=I(this.resourceTemplates,r,(d)=>d.uriTemplate);this.resources=e,this.resourceTemplates=r,await this.reconcileResourceSubscriptions(i),this.publishContentCatalogDelta("resources",t,o),this.publishContentCatalogDelta("resourceTemplates",t,u)}async fetchAndPublishPromptCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("prompt",W,(r)=>i.listPrompts(r?{cursor:r}:void 0),(r)=>r.prompts),s=Li(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing prompts");let e=I(this.prompts,s,(r)=>r.name);this.prompts=s,this.publishContentCatalogDelta("prompts",t,e)}async fetchContentPages(t,i,n,s){let e=[],r=new Set,o;for(let u=0;u<Rt;u++){let d=await n(o);if(e.push(...s(d)),e.length>i)throw Error(`MCP ${t} catalog exceeds ${i} entries`);if(o=d.nextCursor,!o)return e;if(r.has(o))throw Error(`MCP ${t} catalog returned a repeated cursor`);r.add(o)}throw Error(`MCP ${t} catalog exceeds ${Rt} pages`)}publishContentCatalogDelta(t,i,n){if(!Si(n))return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,kind:t,reason:i,...n};this.emit("contentCatalogUpdated",this.contentCatalog,s)}registerResourceNotificationHandler(t){t.setNotificationHandler(Ts,(i)=>{let n=i.params.uri;if(this.sdkClient!==t||!this.activeResourceSubscriptions.has(n))return;this.contentCatalogRevision++,this.emit("resourceUpdated",{revision:this.contentCatalogRevision,serverName:this.serverName,uri:n})})}registerLoggingHandler(t){t.setNotificationHandler(ys,(i)=>{if(this.sdkClient!==t||!this.loggingPolicy.enabled||!un(i.params.level,this.loggingPolicy.level))return;let n=Date.now();if(n-this.logWindowStartedAt>=1000)this.logWindowStartedAt=n,this.logEventsInWindow=0,this.logRateWarningEmitted=!1;if(this.logEventsInWindow>=dn){if(!this.logRateWarningEmitted)this.logRateWarningEmitted=!0,this.emit("log",cn(1,{now:n}));return}this.logEventsInWindow++;let s=lt({level:i.params.level,logger:i.params.logger,data:i.params.data},{exposeDetails:this.runtimeOptions.exposeLogDetails,now:n});this.emit("log",s)})}async configureLogging(t){if(this.logWindowStartedAt=Date.now(),this.logEventsInWindow=0,this.logRateWarningEmitted=!1,!this.loggingPolicy.enabled||!t.getServerCapabilities()?.logging)return;try{await t.setLoggingLevel(this.loggingPolicy.level)}catch(i){if(this.sdkClient!==t)return;let n={serverName:this.serverName,level:this.loggingPolicy.level,error:k(i)};this.emit("loggingSetupFailed",n),this.emit("log",{...lt({level:"warning",logger:"blade.mcp.logging",data:`Failed to set MCP logging level: ${n.error}`},{exposeDetails:this.runtimeOptions.exposeLogDetails}),synthetic:!0})}}async setLoggingLevel(t){if(!pn(t))throw Error("Invalid MCP logging level");let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!i.getServerCapabilities()?.logging)throw Error(`MCP server "${this.serverName}" does not support logging`);if(await i.setLoggingLevel(t),this.sdkClient!==i)throw Error("MCP client changed while setting logging level");this.loggingPolicy={enabled:!0,level:t},this.emit("loggingLevelChanged",{serverName:this.serverName,level:t})}async complete(t,i){let n=this.sdkClient;if(!n||this.status!=="connected")throw Error("MCP client is not connected");if(!n.getServerCapabilities()?.completions)throw Error(`MCP server "${this.serverName}" does not support completions`);if(this.completionCallsInFlight>=pi)throw Error(`MCP server "${this.serverName}" has too many completion requests`);let s=ui(t,this.contentCatalog);this.completionCallsInFlight++;try{let e=await n.complete(s,{signal:i,timeout:ht,maxTotalTimeout:ht});if(this.sdkClient!==n)throw Error("MCP client changed while completing an argument");return ci(e)}catch(e){if(i?.aborted)throw new DOMException(String(i.reason||"MCP completion cancelled"),"AbortError");throw e}finally{this.completionCallsInFlight--}}async readResource(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!this.resources.some((n)=>n.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);return mi(await i.readResource({uri:t}))}async getPrompt(t,i={}){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");let s=this.prompts.find((r)=>r.name===t);if(!s)throw Error(`MCP prompt "${t}" is not present in server "${this.serverName}" catalog`);let e=new Set(s.arguments.map((r)=>r.name));for(let[r,o]of Object.entries(i)){if(["__proto__","constructor","prototype"].includes(r))throw Error(`Unsafe argument "${r}" for MCP prompt "${t}"`);if(!e.has(r))throw Error(`Unknown argument "${r}" for MCP prompt "${t}"`);if(Buffer.byteLength(o)>16384)throw Error(`Argument "${r}" for MCP prompt "${t}" is too large`)}for(let r of s.arguments)if(r.required&&i[r.name]===void 0)throw Error(`Required argument "${r.name}" is missing for MCP prompt "${t}"`);return li(await n.getPrompt({name:t,arguments:i}))}async setResourceSubscription(t,i){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");if(i){if(!this.resources.some((s)=>s.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);if(this.desiredResourceSubscriptions.has(t)&&this.activeResourceSubscriptions.has(t))return;if(!this.desiredResourceSubscriptions.has(t)&&this.desiredResourceSubscriptions.size>=at)throw Error(`MCP resource subscriptions exceed ${at}`);if(!n.getServerCapabilities()?.resources?.subscribe)throw Error(`MCP server "${this.serverName}" does not support resource subscriptions`);if(await n.subscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while subscribing to resource");this.desiredResourceSubscriptions.add(t),this.activeResourceSubscriptions.add(t);return}if(!this.desiredResourceSubscriptions.has(t))return;if(this.activeResourceSubscriptions.has(t)){if(await n.unsubscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while unsubscribing from resource")}this.activeResourceSubscriptions.delete(t),this.desiredResourceSubscriptions.delete(t)}async reconcileResourceSubscriptions(t){if(this.sdkClient!==t)return;let i=new Set(this.resources.map((n)=>n.uri));for(let n of this.activeResourceSubscriptions)if(!i.has(n))this.activeResourceSubscriptions.delete(n);if(!t.getServerCapabilities()?.resources?.subscribe){this.activeResourceSubscriptions.clear();return}for(let n of this.desiredResourceSubscriptions){if(!i.has(n)||this.activeResourceSubscriptions.has(n))continue;try{if(await t.subscribeResource({uri:n}),this.sdkClient!==t)return;this.activeResourceSubscriptions.add(n)}catch(s){this.emit("resourceSubscriptionRestoreFailed",{serverName:this.serverName,uri:n,error:k(s)})}}}setStatus(t){let i=this.status;if(i===t)return;this.status=t,this.emit("statusChanged",t,i)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(t){return this.connect()}async disconnectFromServer(t){return this.disconnect()}async listResources(t){return structuredClone(this.resources)}async listResourceTemplates(){return structuredClone(this.resourceTemplates)}async listPrompts(){return structuredClone(this.prompts)}async listTools(t){return this.availableTools}}class O extends hs{runtimeOptions;static instance=null;servers=new Map;isDiscovering=!1;catalogRevision=0;contentCatalogRevision=0;connectionRevision=0;logRevision=0;instructionsRevision=0;logEntries=[];projectedTools=new Map;constructor(t={}){super();this.runtimeOptions=t}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static createIsolated(t={}){return new O(t)}async registerServer(t,i,n={}){if(this.servers.has(t))throw Error(`MCP服务器 "${t}" 已经注册`);let s=new Yt(i,t,i.healthCheck,this.runtimeOptions),e={config:i,client:s,status:"disconnected",tools:[],contentCatalog:{resources:[],resourceTemplates:[],prompts:[]},logging:s.logging};if(this.setupClientEventHandlers(s,e,t),this.servers.set(t,e),this.emit("serverRegistered",t,e),n.connect===!1)return;try{await this.connectServer(t)}catch(r){console.warn(`MCP服务器 "${t}" 连接失败:`,r)}}async unregisterServer(t){let i=this.servers.get(t);if(!i)return;try{await T.getInstance().cancelClient(i.client),await i.client.disconnect()}catch(n){console.warn(`断开MCP服务器 "${t}" 时出错:`,n)}this.servers.delete(t),this.logEntries=this.logEntries.filter((n)=>n.serverName!==t),this.emit("serverUnregistered",t)}async connectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status==="connected")return;try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async disconnectServer(t){let i=this.servers.get(t);if(!i)return;await T.getInstance().cancelClient(i.client),await i.client.disconnect(),i.connectedAt=void 0}async reconnectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await T.getInstance().cancelClient(i.client),await i.client.disconnect();try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async getAvailableTools(){return[...this.projectedTools.values()]}getCatalogSnapshot(){return{revision:this.catalogRevision,tools:[...this.projectedTools.values()]}}async waitForCatalogIdle(){await Promise.all([...this.servers.values()].map((t)=>t.client.waitForCatalogRefresh()))}getContentCatalogSnapshot(){let t=[],i=[],n=[];for(let[s,e]of this.servers){if(e.status!=="connected")continue;t.push(...e.contentCatalog.resources.map((r)=>({server:s,...structuredClone(r)}))),i.push(...e.contentCatalog.resourceTemplates.map((r)=>({server:s,...structuredClone(r)}))),n.push(...e.contentCatalog.prompts.map((r)=>({server:s,...structuredClone(r)})))}return{revision:this.contentCatalogRevision,resources:t,resourceTemplates:i,prompts:n}}getLogSnapshot(t,i={}){let n=Number.isSafeInteger(i.afterRevision)&&(i.afterRevision??0)>=0?i.afterRevision??0:0,s=Number.isSafeInteger(i.limit)&&(i.limit??0)>=1&&(i.limit??0)<=B?i.limit??B:B,e=this.logEntries.filter((r)=>r.revision>n&&(!t||r.serverName===t)).slice(-s).map((r)=>structuredClone(r));return{revision:this.logRevision,entries:e}}getInstructionsSnapshot(){let t=[];for(let[i,n]of this.servers){if(n.status!=="connected"||!n.instructions)continue;t.push({serverName:i,...structuredClone(n.instructions)})}return t.sort((i,n)=>i.serverName.localeCompare(n.serverName)),{revision:this.instructionsRevision,instructions:t}}async refreshContentCatalogs(t){if(t){await this.requireConnectedServer(t).client.refreshContentCatalogs("manual");return}await Promise.all([...this.servers.values()].filter((i)=>i.status==="connected").map((i)=>i.client.refreshContentCatalogs("manual")))}async readResource(t,i){return this.requireConnectedServer(t).client.readResource(i)}async getPrompt(t,i,n={}){return this.requireConnectedServer(t).client.getPrompt(i,n)}async complete(t,i,n){return this.requireConnectedServer(t).client.complete(i,n)}async startTask(t,i,n,s,e,r,o){let u=this.requireConnectedServer(t);if(!u.tools.some((d)=>d.name===i))throw Error(`MCP tool "${i}" is not present in server "${t}" catalog`);return T.getInstance().start({client:u.client,serverName:t,toolName:i,arguments:n,owner:s,interactionContext:e,signal:r,ttlMs:o})}listTasks(t,i){return T.getInstance().list(t,i)}getTask(t,i){return T.getInstance().get(t,i)}waitForTask(t,i,n,s){return T.getInstance().wait(t,i,n,s)}cancelTask(t,i,n){return T.getInstance().cancel(t,i,n)}async setResourceSubscription(t,i,n){await this.requireConnectedServer(t).client.setResourceSubscription(i,n)}async setServerLoggingLevel(t,i){let n=this.requireConnectedServer(t);await n.client.setLoggingLevel(i),n.logging=n.client.logging}async findTool(t){return this.projectedTools.get(t)??null}getToolsByServer(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return[];return i.tools.map((n)=>Tt(i.client,t,n,Lt(t,n.name),this.runtimeOptions.artifactWriter))}getServerStatus(t){return this.servers.get(t)||null}getAllServers(){return new Map(this.servers)}async getServerOAuthStatus(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);return i.client.getOAuthStatus()}async beginOAuthLogin(t,i={}){let n=this.servers.get(t);if(!n)throw Error(`MCP服务器 "${t}" 未注册`);let s=await n.client.beginOAuthLogin(i);this.emit("serverOAuthStatusChanged",t,"authorizing");let e=s.completion.then(async()=>{this.emit("serverOAuthCompleted",t),this.emit("serverOAuthStatusChanged",t,"authenticated");try{await this.reconnectServer(t)}catch(r){n.lastError=r instanceof Error?r:Error(String(r)),n.status="error",this.emit("serverError",t,n.lastError)}},(r)=>{throw n.lastError=r instanceof Error?r:Error(String(r)),this.emit("serverOAuthError",t,n.lastError),this.emit("serverOAuthStatusChanged",t,"error"),n.lastError});return e.catch(()=>{return}),{...s,completion:e}}async logoutOAuth(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await i.client.logoutOAuth(),i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.tools=[],this.emit("serverOAuthStatusChanged",t,"unauthenticated")}async refreshAllTools(){let t=[];for(let[i,n]of this.servers)if(n.status==="connected")t.push(this.refreshServerTools(i));await Promise.allSettled(t)}async refreshServerTools(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return;try{await i.client.refreshTools("manual")}catch(n){throw console.warn(`刷新服务器 "${t}" 工具列表失败:`,n),n}}setupClientEventHandlers(t,i,n){t.on("connected",(s)=>{if(i.status="connected",i.connectedAt=new Date,i.lastError=void 0,i.tools=t.availableTools,i.contentCatalog=t.contentCatalog,i.logging=t.logging,i.instructions=this.fitInstructionBudget(n,t.instructions),this.publishCatalog(n,"connection"),this.publishInitialContentCatalog(n,i.contentCatalog),i.instructions)this.publishInstructions(n,"added","connection",i.instructions);this.emit("serverConnected",n,s)}),t.on("disconnected",()=>{i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.recovery=void 0,this.invalidateServerProjection(n,i),this.emit("serverDisconnected",n)}),t.on("error",(s)=>{i.status="error",i.lastError=s,this.invalidateServerProjection(n,i),this.emit("serverError",n,s)}),t.on("connectionLifecycleChanged",(s)=>{if(i.recovery=structuredClone(s),s.phase==="reconnecting")i.status="reconnecting",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError,this.invalidateServerProjection(n,i);else if(s.phase==="recovered")i.status="connected",i.lastError=void 0;else i.status="error",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError;this.publishConnectionLifecycle(n,s)}),t.on("toolsUpdated",(s,e)=>{let r=i.tools.length;if(i.tools=s,i.status==="connected"&&e)this.publishCatalog(n,e.reason);this.emit("toolsUpdated",n,s,r)}),t.on("toolsRefreshFailed",(s)=>{this.emit("catalogRefreshFailed",{serverName:n,...s})}),t.on("contentCatalogUpdated",(s,e)=>{if(i.contentCatalog=s,i.status!=="connected")return;this.publishContentCatalogChange(n,e.kind,e.reason,{added:e.added,removed:e.removed,updated:e.updated})}),t.on("contentCatalogRefreshFailed",(s)=>{this.emit("contentCatalogRefreshFailed",{serverName:n,...s})}),t.on("resourceUpdated",(s)=>{if(i.status!=="connected")return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:n,uri:s.uri};this.emit("resourceUpdated",e)}),t.on("statusChanged",(s,e)=>{if(i.status=s,s==="reconnecting"&&e==="connected")i.connectedAt=void 0,this.invalidateServerProjection(n,i);this.emit("serverStatusChanged",n,s,e)}),t.on("loggingLevelChanged",()=>{i.logging=t.logging,this.emit("serverLoggingLevelChanged",n,i.logging.level)}),t.on("log",(s)=>{this.publishLog(n,s)})}publishLog(t,i){this.logRevision++;let n={revision:this.logRevision,serverName:t,...structuredClone(i)};this.logEntries.push(n);let s=0;for(let e=this.logEntries.length-1;e>=0;e--){if(this.logEntries[e]?.serverName!==t)continue;if(s++,s>En)this.logEntries.splice(e,1)}while(this.logEntries.length>B)this.logEntries.shift();this.emit("log",structuredClone(n))}invalidateServerProjection(t,i){let n=i.contentCatalog,s=i.instructions!==void 0;if(i.tools=[],i.contentCatalog={resources:[],resourceTemplates:[],prompts:[]},i.instructions=void 0,this.publishCatalog(t,"disconnection"),this.publishRemovedContentCatalog(t,n),s)this.publishInstructions(t,"removed","disconnection")}fitInstructionBudget(t,i){if(!i)return;let n=0;for(let[s,e]of this.servers){if(s===t)continue;n+=e.instructions?.projectedBytes??0}return fn(i,Math.max(0,bn-n))}publishInstructions(t,i,n,s){this.instructionsRevision++;let e={revision:this.instructionsRevision,serverName:t,action:i,reason:n,...s?{instruction:structuredClone(s)}:{}};this.emit("instructionsChanged",e)}publishConnectionLifecycle(t,i){this.connectionRevision++;let n={revision:this.connectionRevision,serverName:t,...structuredClone(i)};this.emit("connectionLifecycleChanged",n)}publishCatalog(t,i){let n=new Map;for(let[u,d]of this.servers){if(d.status!=="connected")continue;for(let p of d.tools){let c=Lt(u,p.name);if(n.has(c))throw Error(`Duplicate projected MCP tool "${c}"`);n.set(c,Tt(d.client,u,p,c,this.runtimeOptions.artifactWriter))}}let s=new Map([...this.projectedTools].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),e=new Map([...n].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),r={added:[...n.keys()].filter((u)=>!this.projectedTools.has(u)).sort(),removed:[...this.projectedTools.keys()].filter((u)=>!n.has(u)).sort(),updated:[...n.keys()].filter((u)=>this.projectedTools.has(u)&&s.get(u)!==e.get(u)).sort()};if(this.projectedTools=n,!nt(r))return;this.catalogRevision++;let o={revision:this.catalogRevision,serverName:t,reason:i,tools:[...n.values()],...r};this.emit("catalogChanged",o)}publishInitialContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","connection",{added:i.resources.map((n)=>n.uri).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","connection",{added:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"prompts","connection",{added:i.prompts.map((n)=>n.name).sort(),removed:[],updated:[]})}publishRemovedContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","disconnection",{added:[],removed:i.resources.map((n)=>n.uri).sort(),updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","disconnection",{added:[],removed:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),updated:[]}),this.publishContentCatalogChange(t,"prompts","disconnection",{added:[],removed:i.prompts.map((n)=>n.name).sort(),updated:[]})}publishContentCatalogChange(t,i,n,s){if(s.added.length===0&&s.removed.length===0&&s.updated.length===0)return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:t,kind:i,reason:n,...s};this.emit("contentCatalogChanged",e)}requireConnectedServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status!=="connected")throw Error(`MCP服务器 "${t}" 未连接`);return i}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(t){let i=Object.entries(t).map(([n,s])=>this.registerServer(n,s).catch((e)=>{return console.warn(`注册MCP服务器 "${n}" 失败:`,e),e}));await Promise.allSettled(i)}getStatistics(){let t=0,i=0,n=0;for(let s of this.servers.values())if(s.status==="connected")t++,i+=s.tools.length;else if(s.status==="error")n++;return{totalServers:this.servers.size,connectedServers:t,errorServers:n,totalTools:i,isDiscovering:this.isDiscovering}}async disconnectAll(){let t=[];for(let[i,n]of this.servers)t.push(T.getInstance().cancelClient(n.client).then(()=>n.client.disconnect()).catch((s)=>{console.warn(`断开 MCP 服务器 "${i}" 时出错:`,s)}));await Promise.allSettled(t),this.servers.clear(),this.projectedTools.clear(),this.logEntries=[]}}
|
|
25
|
-
export{Gt as
|
|
24
|
+
${M}`,c=!0}return{isError:t.isError===!0,llmContent:o,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:e.length,truncated:c,binaryOmitted:n.binaryBytes>0,artifacts:e}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=mn(i.replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]")).trim();return wt(n||"MCP tool execution failed",kn)}function Tt(t,i,n,s,e){let r=n.inputSchema&&typeof n.inputSchema==="object"?x.Unsafe(n.inputSchema):x.Any(),o=s||n.name;return Gt({name:o,displayName:`${i}: ${n.name}`,kind:"execute",schema:r,description:{short:n.description||`MCP Tool: ${n.name}`,important:[`From MCP server: ${i}`,"Executes external tools; user confirmation required",...n.taskSupport==="required"?["This tool requires MCP task execution and returns an opaque task ID.","Use TaskOutput to retrieve the eventual result."]:[]]},category:"MCP tool",tags:["mcp","external",i],async execute(c,d){try{let p={...d.confirmationHandler?{confirmationHandler:d.confirmationHandler}:{},...d.mcpSamplingHandler?{samplingHandler:d.mcpSamplingHandler}:{},...d.onProgressUpdate?{progressHandler:d.onProgressUpdate}:{},...d.sessionId?{sessionId:d.sessionId}:{},...d.workspaceRoot?{workspaceRoot:d.workspaceRoot}:{},...d.permissionMode?{permissionMode:d.permissionMode}:{}};if(n.taskSupport==="required"){if(!d.sessionId)throw Error("MCP tasks require an active Session");let y=await T.getInstance().start({client:t,serverName:i,toolName:n.name,arguments:c,owner:{sessionId:d.sessionId,projectPath:Bn.resolve(d.workspaceRoot||vt())},interactionContext:p,signal:d.signal});return{success:!0,llmContent:{task_id:y.taskId,type:"mcp",status:y.status,message:`MCP task started. Use TaskOutput(task_id: "${y.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${y.taskId}`,serverName:i,toolName:n.name,task_id:y.taskId,taskType:"mcp",taskStatus:y.status,background:!0}}}let u=await t.callTool(n.name,c,{...d.signal?{signal:d.signal}:{},...p}),M=await j(u,e),w={summary:`MCP ${n.name} 执行${M.isError?"失败":"成功"}`,serverName:i,toolName:n.name,mcpResult:{isError:M.isError,...M.metadata}};if(M.isError){let y=yt(M.llmContent);return{success:!1,llmContent:y,error:{type:"execution_error",message:y},metadata:w}}return{success:!0,llmContent:M.llmContent,metadata:w}}catch(p){let u=yt(p);return{success:!1,llmContent:`MCP tool execution failed: ${u}`,error:{type:"execution_error",message:u},metadata:{summary:`MCP ${n.name} 执行失败`,serverName:i,toolName:n.name}}}}})}import{realpathSync as es}from"node:fs";import Ii from"node:path";import{pathToFileURL as rs}from"node:url";import{Client as ds}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as os}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as ps}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolResultSchema as St,CreateMessageRequestSchema as cs,ElicitationCompleteNotificationSchema as us,ElicitRequestSchema as Ms,ErrorCode as P,ListRootsRequestSchema as ws,LoggingMessageNotificationSchema as ys,McpError as R,ResourceUpdatedNotificationSchema as Ts,TaskStatusNotificationSchema as Es}from"@modelcontextprotocol/sdk/types.js";import{EventEmitter as bs}from"events";import fs from"open";import{EventEmitter as Xn}from"events";function Et(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t)||!Number.isInteger(t)||t<s||t>e)throw Error(`${n} must be an integer between ${s} and ${e}`);return t}class bt extends Xn{client;config;checkTimer=null;isChecking=!1;running=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(t,i={}){super();if(this.client=t,i.enabled!==void 0&&typeof i.enabled!=="boolean")throw Error("MCP health check enabled must be a boolean");this.config={interval:Et(i.interval,30000,"MCP health check interval",10,300000),timeout:Et(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:Et(i.failureThreshold,3,"MCP health check failureThreshold",1,10)}}start(){if(this.running||!this.config.enabled)return;this.running=!0,this.scheduleNextCheck()}stop(){if(this.running=!1,this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null}scheduleNextCheck(){if(!this.running)return;this.checkTimer=setTimeout(async()=>{this.checkTimer=null,await this.performHealthCheck().catch(()=>{return}),this.scheduleNextCheck()},this.config.interval),this.checkTimer.unref()}async performHealthCheck(){if(this.isChecking)return this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let t=this.client.connectionStatus;if(t==="connected"){await this.client.ping(this.config.timeout),this.consecutiveFailures=0,this.setStatus("healthy");let i={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",i),i}else throw Error(`连接状态异常: ${t}`)}catch(t){this.consecutiveFailures++;let i=t,n;if(this.consecutiveFailures>=this.config.failureThreshold)n="unhealthy",this.emit("unhealthy",this.consecutiveFailures,i),this.client.requestRecovery(i,"health_check");else n="degraded";this.setStatus(n);let s={status:n,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:i};return this.emit("healthCheck",s),s}finally{this.isChecking=!1}}setStatus(t){if(this.currentStatus!==t){let i=this.currentStatus;this.currentStatus=t,this.emit("statusChanged",t,i)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}import{createHash as zn}from"node:crypto";import{UriTemplate as Yn}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";var ii=100,Dn=4096,Fn=65536,ft=1048576,ni=32,si=65536,pi=4,ht=15000,ei=256,ri=16384,Jn=256,Vn=8192,jn=/[\p{Cf}\p{Co}\p{Cn}]/u;function Gn(t){return[...new Set(new Yn(t).variableNames)]}function ci(t,i){let n=G(t.argument.name,"completion argument name",ei),s=di(t.argument.value,"completion argument value",ri),e,r;if(t.reference.type==="prompt"){let p=G(t.reference.name,"completion prompt name",Jn),u=i.prompts.find((M)=>M.name===p);if(!u)throw Error(`MCP prompt "${p}" is not present in the current catalog`);e=new Set(u.arguments.map((M)=>M.name)),r={type:"ref/prompt",name:p}}else{let p=G(t.reference.uri,"completion resource template URI",Vn);if(!i.resourceTemplates.find((w)=>w.uriTemplate===p))throw Error(`MCP resource template "${p}" is not present in the current catalog`);let M;try{M=Gn(p)}catch{throw Error(`MCP resource template "${p}" is invalid`)}e=new Set(M),r={type:"ref/resource",uri:p}}if(!e.has(n))throw Error(`MCP ${t.reference.type} completion argument "${n}" is not declared`);let o=Object.entries(t.context??{});if(o.length>ni)throw Error(`MCP completion context exceeds ${ni} arguments`);let c=Object.create(null),d=0;for(let[p,u]of o){let M=G(p,"completion context argument name",ei);if(yi(M))throw Error(`Unsafe MCP completion context argument "${M}"`);if(!e.has(M))throw Error(`Unknown MCP completion context argument "${M}"`);let w=di(u,`completion context argument "${M}"`,ri);if(d+=Buffer.byteLength(M)+Buffer.byteLength(w),d>si)throw Error(`MCP completion context exceeds ${si} bytes`);c[M]=w}return{ref:r,argument:{name:n,value:s},...o.length>0?{context:{arguments:c}}:{}}}function ui(t){let i=t.completion,n=JSON.stringify(i),s=Buffer.byteLength(n),e=zn("sha256").update(n).digest("hex"),r=i.values.length,o=[],c=new Set,d=0,p=0,u=r>ii||s>ft;for(let w of i.values.slice(0,ii)){let y=Buffer.byteLength(w),E=Math.max(0,ft-p);if(E===0){u=!0;break}let a=oi(w,Math.min(ft,E));if(p+=Buffer.byteLength(a),y>Buffer.byteLength(a))u=!0;let Dt=Mi(a),L=oi(Dt,Dn);if(Buffer.byteLength(L)<Buffer.byteLength(Dt))u=!0;if(c.has(L))continue;let Ft=Buffer.byteLength(L);if(d+Ft>Fn){u=!0;break}c.add(L),o.push(L),d+=Ft}if(o.length<r)u=!0;let M=i.total!==void 0&&Number.isSafeInteger(i.total)&&i.total>=0?i.total:void 0;return{values:o,...M!==void 0?{total:M}:{},hasMore:i.hasMore===!0||u||M!==void 0&&M>o.length,sourceValueCount:r,sourceBytes:s,projectedBytes:d,sha256:e,truncated:u}}function Mi(t){return[...t.normalize("NFKC")].filter((i)=>{let n=i.codePointAt(0)??0;if(n<32||n===127)return!1;return!jn.test(i)}).join("")}function G(t,i,n){if(typeof t!=="string"||!t||Buffer.byteLength(t)>n)throw Error(`MCP ${i} is invalid`);if(Mi(t)!==t||wi(t))throw Error(`MCP ${i} contains unsafe characters`);if(yi(t))throw Error(`MCP ${i} is unsafe`);return t}function di(t,i,n){if(typeof t!=="string"||Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);if(wi(t))throw Error(`MCP ${i} contains control characters`);return t}function wi(t){return[...t].some((i)=>{let n=i.codePointAt(0)??0;return n<32||n===127})}function yi(t){return["__proto__","constructor","prototype"].includes(t)}function oi(t,i){let n=Buffer.from(t);if(n.length<=i)return t;let s=n.subarray(0,Math.max(0,i)).toString("utf8");while(Buffer.byteLength(s)>i)s=s.slice(0,-1);return s}var At=20,_t=300000;function Ti(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${n} must be a finite number`);if(t<s||t>e)throw Error(`${n} must be between ${s} and ${e}`);return t}function H(t,i,n,s,e){let r=Ti(t,i,n,s,e);if(!Number.isInteger(r))throw Error(`${n} must be an integer`);return r}function Ei(t){let i=t.recovery;if(i!==void 0&&(i===null||typeof i!=="object"||Array.isArray(i)))throw Error("MCP recovery configuration must be an object");let n=i?.enabled??!0;if(typeof n!=="boolean")throw Error("MCP recovery enabled must be a boolean");let s=H(i?.maxAttempts,5,"MCP recovery maxAttempts",0,20),e=H(i?.initialDelayMs,1000,"MCP recovery initialDelayMs",10,300000),r=H(i?.maxDelayMs,30000,"MCP recovery maxDelayMs",e,300000),o=Ti(i?.jitterRatio,0.2,"MCP recovery jitterRatio",0,1),c=H(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:s,initialDelayMs:e,maxDelayMs:r,jitterRatio:o,terminalErrorThreshold:c}}function bi(t,i,n=Math.random){let s=Math.max(0,i-1),e=Math.min(t.initialDelayMs*2**s,t.maxDelayMs);if(t.jitterRatio===0)return e;let r=Math.min(1,Math.max(0,n())),o=1-t.jitterRatio+2*t.jitterRatio*r;return Math.max(0,Math.round(e*o))}function k(t){let n=(t instanceof Error?t.message:String(t)).replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/[\r\n\t]+/g," ").trim();if(Buffer.byteLength(n)<=512)return n;let s=Buffer.from(n).subarray(0,512).toString("utf8");while(Buffer.byteLength(s)>512)s=s.slice(0,-1);return s}function fi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return(n.includes("404")||n.includes("-32001"))&&(n.includes("session")||n.includes("not found"))}function hi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return["econnreset","etimedout","epipe","ehostunreach","econnrefused","body timeout error","socket hang up","connection closed","connection terminated","sse stream disconnected","failed to reconnect sse stream","maximum reconnection attempts"].some((s)=>n.includes(s))}function C(t){return new DOMException(String(t||"MCP connection recovery cancelled"),"AbortError")}async function Pt(t,i,n=!0){if(i.aborted)throw C(i.reason);await new Promise((s,e)=>{let o=setTimeout(()=>{i.removeEventListener("abort",c),s()},t);if(n)o.unref();let c=()=>{clearTimeout(o),i.removeEventListener("abort",c),e(C(i.reason))};i.addEventListener("abort",c,{once:!0})})}import{createHash as $i}from"node:crypto";var Rt=100,q=1000,K=1000,W=1000,at=100,Ai=64,Z=1048576,_=4194304,A=256,N=8192,g=256,m=16384,_i=64,Hn=4096,Pi=4194304,Ri=128;function Ci(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function qn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function b(t,i,n){if(t===void 0)return;if(i==="description"?qn(t):Ci(t))throw Error(`MCP ${i} contains control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);return t}function f(t,i,n){let s=t.trim();if(!s||s.length>n||Ci(s))throw Error(`MCP ${i} is invalid`);return s}function $t(t){return Buffer.byteLength(JSON.stringify(t))}function Ct(t,i){if($t(t)>Pi)throw Error(`MCP ${i} catalog exceeds ${Pi} bytes`)}function Q(t,i){let n=new Set;for(let s of t){if(n.has(s))throw Error(`MCP ${i} catalog contains duplicate "${s}"`);n.add(s)}}function ki(t){if(t.length>q)throw Error(`MCP resource catalog exceeds ${q} entries`);let i=t.map((n)=>({uri:f(n.uri,"resource URI",N),name:f(n.name,"resource name",A),...b(n.title,"resource title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource MIME type",g)?{mimeType:n.mimeType}:{},...n.size!==void 0&&Number.isSafeInteger(n.size)&&n.size>=0?{size:n.size}:{}}));return Q(i.map((n)=>n.uri),"resource"),Ct(i,"resource"),i}function Oi(t){if(t.length>K)throw Error(`MCP resource template catalog exceeds ${K} entries`);let i=t.map((n)=>({uriTemplate:f(n.uriTemplate,"resource template URI",N),name:f(n.name,"resource template name",A),...b(n.title,"resource template title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource template MIME type",g)?{mimeType:n.mimeType}:{}}));return Q(i.map((n)=>n.uriTemplate),"resource template"),Ct(i,"resource template"),i}function Li(t){if(t.length>W)throw Error(`MCP prompt catalog exceeds ${W} entries`);let i=t.map((n)=>{if((n.arguments?.length??0)>_i)throw Error(`MCP prompt "${n.name}" exceeds ${_i} arguments`);let s=(n.arguments??[]).map((e)=>{let r=f(e.name,"prompt argument name",A);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...b(e.description,"description",Hn)?{description:e.description}:{},required:e.required===!0}});return Q(s.map((e)=>e.name),`prompt "${n.name}" argument`),{name:f(n.name,"prompt name",A),...b(n.title,"prompt title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},arguments:s}});return Q(i.map((n)=>n.name),"prompt"),Ct(i,"prompt"),i}function ai(t){return $i("sha256").update(JSON.stringify(t)).digest("hex")}function I(t,i,n){let s=new Map(t.map((r)=>[n(r),ai(r)])),e=new Map(i.map((r)=>[n(r),ai(r)]));return{added:[...e.keys()].filter((r)=>!s.has(r)).sort(),removed:[...s.keys()].filter((r)=>!e.has(r)).sort(),updated:[...e.keys()].filter((r)=>s.has(r)&&s.get(r)!==e.get(r)).sort()}}function Si(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function kt(t,i,n){if(t.bytes+=i,t.bytes>_)throw Error(`MCP ${n} exceeds ${_} total bytes`)}function xi(t,i,n){if(t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP ${i} contains invalid base64`);let s=Buffer.from(t,"base64");if(s.length>_)throw Error(`MCP ${i} exceeds ${_} decoded bytes`);return kt(n,s.length,i),{size:s.length,sha256:$i("sha256").update(s).digest("hex"),omitted:!0}}function gi(t,i){let n=f(typeof t.uri==="string"?t.uri:"","resource content URI",N),s=typeof t.mimeType==="string"?b(t.mimeType,"resource MIME type",g):void 0;if(typeof t.text==="string"){let e=Buffer.byteLength(t.text);if(e>Z)throw Error(`MCP resource text exceeds ${Z} bytes`);return kt(i,e,"resource result"),{uri:n,...s?{mimeType:s}:{},text:t.text}}if(typeof t.blob==="string")return{uri:n,...s?{mimeType:s}:{},binary:xi(t.blob,"resource blob",i)};throw Error("MCP resource content has neither text nor blob data")}function mi(t){let i=t&&typeof t==="object"&&Array.isArray(t.contents)?t.contents:[];if(i.length>Ai)throw Error(`MCP resource result exceeds ${Ai} contents`);let n={bytes:0},s=i.map((e)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw Error("MCP resource content is malformed");return gi(e,n)});if($t(s)>_)throw Error(`MCP resource result exceeds ${_} bytes`);return{contents:s}}function li(t){if(!t||typeof t!=="object"||Array.isArray(t))throw Error("MCP prompt result is malformed");let i=t,n=Array.isArray(i.messages)?i.messages:[];if(n.length>Ri)throw Error(`MCP prompt exceeds ${Ri} messages`);let s={bytes:0},e=n.map((r)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error("MCP prompt message is malformed");let o=r,c=o.role;if(c!=="user"&&c!=="assistant")throw Error("MCP prompt message has an invalid role");let d=o.content;if(!d||typeof d!=="object"||Array.isArray(d))throw Error("MCP prompt message content is malformed");let p=d;if(p.type==="text"&&typeof p.text==="string"){let u=Buffer.byteLength(p.text);if(u>Z)throw Error(`MCP prompt text exceeds ${Z} bytes`);return kt(s,u,"prompt result"),{role:c,content:{type:"text",text:p.text}}}if((p.type==="image"||p.type==="audio")&&typeof p.data==="string"&&typeof p.mimeType==="string")return{role:c,content:{type:p.type,mimeType:f(p.mimeType,"prompt content MIME type",g),binary:xi(p.data,`prompt ${p.type}`,s)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:c,content:{type:"resource",resource:gi(p.resource,s)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:c,content:{type:"resource_link",uri:f(p.uri,"prompt resource link URI",N),name:f(p.name,"prompt resource link name",A),...typeof p.mimeType==="string"?{mimeType:f(p.mimeType,"prompt resource link MIME type",g)}:{},...typeof p.description==="string"?{description:b(p.description,"description",m)}:{}}};throw Error(`Unsupported MCP prompt content type: ${String(p.type)}`)});if($t(e)>_)throw Error(`MCP prompt result exceeds ${_} bytes`);return{...typeof i.description==="string"?{description:b(i.description,"description",m)}:{},messages:e}}var Ui=4000,Bi=4096,Xi=32,Kn=128,zi=1000,Yi=100,Di=65536,Wn=new Set(["__proto__","constructor","prototype"]);function Fi(t,i){if(!t.trim())throw Error("MCP elicitation server name is empty");if(!i.message.trim())throw Error("MCP elicitation message is empty");if(i.message.length>Ui)throw Error(`MCP elicitation message exceeds ${Ui} characters`);if(i.mode==="url"){let e=In(i.url);if(!i.elicitationId.trim())throw Error("MCP URL elicitation ID is empty");return{serverName:t,mode:"url",message:i.message,url:e.toString(),domain:e.hostname,elicitationId:i.elicitationId}}let n=Object.entries(i.requestedSchema.properties);if(n.length>Xi)throw Error(`MCP elicitation exceeds the ${Xi} field limit`);let s=new Set(i.requestedSchema.required??[]);for(let e of s)if(!Object.hasOwn(i.requestedSchema.properties,e))throw Error(`MCP elicitation requires an unknown field: ${e}`);return{serverName:t,mode:"form",message:i.message,fields:n.map(([e,r])=>Zn(e,r,s.has(e))),requestedSchema:structuredClone(i.requestedSchema)}}function ie(t){let i=Object.create(null);for(let n of t.fields??[])if(n.defaultValue!==void 0)i[n.name]=Array.isArray(n.defaultValue)?[...n.defaultValue]:n.defaultValue;return i}function ne(t,i){let n=i.trim();if(!n){if(t.defaultValue!==void 0)return t.defaultValue;if(!t.required)return;throw Error(`${t.title} is required`)}if(t.type==="number"||t.type==="integer"){let s=Number(n);if(!Number.isFinite(s))throw Error(`${t.title} must be a finite number`);if(t.type==="integer"&&!Number.isSafeInteger(s))throw Error(`${t.title} must be a safe integer`);return s}if(t.type==="boolean"){if(["true","yes","y","1"].includes(n.toLowerCase()))return!0;if(["false","no","n","0"].includes(n.toLowerCase()))return!1;throw Error(`${t.title} must be true or false`)}return n}function Ji(t,i){if(i.action!=="accept")return{action:i.action};if(t.mode==="url")return{action:"accept"};if(!t.requestedSchema)throw Error("MCP form elicitation schema is unavailable");let n=i.content??{};if(Buffer.byteLength(JSON.stringify(n),"utf8")>Di)throw Error(`MCP elicitation response exceeds ${Di} bytes`);for(let r of Object.keys(n))Vi(r);for(let r of Object.values(n))if(typeof r==="number"&&(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r)))throw Error("MCP elicitation response contains an unsafe number");let s=x.Unsafe({...t.requestedSchema,additionalProperties:!1}),e=X(s,n);if(!e.success)throw Error(`Invalid MCP elicitation response: ${e.error.message}`);return{action:"accept",content:e.data}}function Zn(t,i,n){Vi(t);let s=tt(i.title?.trim()||t,"field title"),e=i.description?tt(i.description,"field description"):void 0,r={name:t,title:s,description:e,required:n};if(i.type==="boolean")return{...r,type:"boolean",...typeof i.default==="boolean"?{defaultValue:i.default}:{}};if(i.type==="number"||i.type==="integer")return{...r,type:i.type,...typeof i.default==="number"?{defaultValue:i.default}:{},...i.minimum!==void 0?{minimum:i.minimum}:{},...i.maximum!==void 0?{maximum:i.maximum}:{}};if(i.type==="array"){let c=Nn(i);return{...r,type:"multi-select",options:c,...Array.isArray(i.default)&&i.default.every((d)=>typeof d==="string")?{defaultValue:[...i.default]}:{},...i.minItems!==void 0?{minItems:i.minItems}:{},...i.maxItems!==void 0?{maxItems:i.maxItems}:{}}}let o=Qn(i);if(o)return{...r,type:"select",options:o,...typeof i.default==="string"?{defaultValue:i.default}:{}};return{...r,type:"string",...typeof i.default==="string"?{defaultValue:i.default}:{},...i.format?{format:i.format}:{},...i.minLength!==void 0?{minLength:i.minLength}:{},...i.maxLength!==void 0?{maxLength:i.maxLength}:{}}}function Qn(t){if(t.oneOf)return v(t.oneOf.map((i)=>({value:i.const,label:i.title})));if(!t.enum)return;return v(t.enum.map((i,n)=>({value:i,label:t.enumNames?.[n]??i})))}function Nn(t){if(t.items?.anyOf)return v(t.items.anyOf.map((i)=>({value:i.const,label:i.title})));if(t.items?.enum)return v(t.items.enum.map((i)=>({value:i,label:i})));throw Error("MCP multi-select elicitation is missing enum options")}function v(t){if(t.length===0||t.length>Yi)throw Error(`MCP elicitation options must contain 1-${Yi} items`);let i=new Set;return t.map((n)=>{if(i.has(n.value))throw Error(`MCP elicitation contains duplicate option: ${n.value}`);return i.add(n.value),{value:tt(n.value,"option value"),label:tt(n.label,"option label")}})}function Vi(t){if(!t||t.length>Kn||Wn.has(t))throw Error(`Unsafe MCP elicitation field name: ${t||"(empty)"}`)}function tt(t,i){if(t.length>zi)throw Error(`MCP elicitation ${i} exceeds ${zi} characters`);return t}function In(t){if(t.length>Bi)throw Error(`MCP elicitation URL exceeds ${Bi} characters`);let i;try{i=new URL(t)}catch{throw Error("MCP elicitation URL is invalid")}if(!["http:","https:"].includes(i.protocol))throw Error(`MCP elicitation URL protocol is not allowed: ${i.protocol}`);if(i.username||i.password)throw Error("MCP elicitation URL must not contain credentials");return i}import{createHash as Wi}from"node:crypto";var l=1000,it=100,vn=256,ji=16384,Gi=262144,Hi=4194304,qi=24;function ts(t,i=10){return Wi("sha256").update(t).digest("hex").slice(0,i)}function Ot(t){if(Array.isArray(t))return t.map(Ot);if(!t||typeof t!=="object")return t;let i=t;return Object.fromEntries(Object.keys(i).sort().map((n)=>[n,Ot(i[n])]))}function Zi(t){let i=t.normalize("NFKC"),n=i.replace(/[^A-Za-z0-9_-]/g,"_");if(n&&n===i&&n.length<=qi)return n;return`${(n||"unnamed").slice(0,qi-11)}_${ts(i)}`}function Lt(t,i){return`${is(t)}${Zi(i)}`}function is(t){return`mcp__${Zi(t)}__`}function Ki(t){return Wi("sha256").update(JSON.stringify(Ot({name:t.name,description:t.description,inputSchema:t.inputSchema,taskSupport:t.taskSupport}))).digest("hex")}function ns(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Qi(t){if(t.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);let i=new Set,n=[],s=0;for(let e of t){let r=e.name.trim();if(!r||r.length>vn||ns(r))throw Error("MCP tool catalog contains an invalid tool name");if(i.has(r))throw Error(`MCP tool catalog contains duplicate tool "${r}"`);i.add(r);let o=e.description??"";if(Buffer.byteLength(o)>ji)throw Error(`MCP tool "${r}" description exceeds ${ji} bytes`);let c=JSON.stringify(e.inputSchema),d=Buffer.byteLength(c);if(d>Gi)throw Error(`MCP tool "${r}" schema exceeds ${Gi} bytes`);if(s+=Buffer.byteLength(r)+Buffer.byteLength(o)+d,s>Hi)throw Error(`MCP tool catalog exceeds ${Hi} bytes`);n.push({name:r,description:o,inputSchema:JSON.parse(c),...e.execution?.taskSupport?{taskSupport:e.execution.taskSupport}:{}})}return n}function Ni(t,i){let n=new Map(t.map((e)=>[e.name,Ki(e)])),s=new Map(i.map((e)=>[e.name,Ki(e)]));return{added:[...s.keys()].filter((e)=>!n.has(e)).sort(),removed:[...n.keys()].filter((e)=>!s.has(e)).sort(),updated:[...s.keys()].filter((e)=>n.has(e)&&n.get(e)!==s.get(e)).sort()}}function nt(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function vi(t){if(t instanceof zt||t instanceof U)return{type:"auth_error",isRetryable:!1,originalError:t};if(!(t instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(t))};let i=t.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((e)=>i.includes(e)))return{type:"config_error",isRetryable:!1,originalError:t};if(i.includes("unauthorized")||i.includes("401")||i.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:t};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((e)=>i.includes(e)))return{type:"network_temporary",isRetryable:!0,originalError:t};return{type:"unknown",isRetryable:!0,originalError:t}}class Yt extends bs{config;runtimeOptions;status="disconnected";sdkClient=null;tools=new Map;toolCatalogRevision=0;toolRefreshPromise;toolRefreshRequested=!1;resources=[];resourceTemplates=[];prompts=[];contentCatalogRevision=0;contentRefreshPromise;requestedContentCatalogs=new Set;contentRefreshReason="manual";catalogGeneration=0;desiredResourceSubscriptions=new Set;activeResourceSubscriptions=new Set;serverInfo=null;serverInstructions;completionCallsInFlight=0;loggingPolicy;logWindowStartedAt=0;logEventsInWindow=0;logRateWarningEmitted=!1;recoveryPolicy;desiredConnected=!1;connectionGeneration=0;connectPromise;connectAbortController;recoveryPromise;recoveryAbortController;recoveryState;consecutiveTerminalErrors=0;oauthProvider=null;serverName;healthMonitor=null;activeInteraction;taskInteractions=new Map;taskPolicy;roots;constructor(t,i,n,s={}){super();this.config=t;this.runtimeOptions=s;this.serverName=i||"default",this.recoveryPolicy=Ei(t),this.loggingPolicy=on(t),this.taskPolicy=yn(t.tasks),this.roots=(s.roots??[]).map((r)=>{let o=es.native(Ii.resolve(r));return{uri:rs(o).href,name:Ii.basename(o)||o}});let e=tn(t);if(this.config={...t,...e?{oauth:e}:{}},e?.enabled&&t.url&&s.oauthCredentialAccess!==!1)this.oauthProvider=new rn(this.serverName,t.url,e,s.oauthStorageRoot?{tokenStorage:new en(s.oauthStorageRoot)}:{});if(n?.enabled)this.healthMonitor=new bt(this,n),this.healthMonitor.on("unhealthy",(r,o)=>{this.emit("unhealthy",r,o)})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get contentCatalog(){return{resources:structuredClone(this.resources),resourceTemplates:structuredClone(this.resourceTemplates),prompts:structuredClone(this.prompts)}}get completionSupported(){return Boolean(this.sdkClient?.getServerCapabilities()?.completions)}get tasks(){return{...this.taskPolicy}}get server(){return this.serverInfo}get instructions(){return this.serverInstructions?structuredClone(this.serverInstructions):void 0}get healthCheck(){return this.healthMonitor}get recovery(){return this.recoveryState?structuredClone(this.recoveryState):void 0}get logging(){return{...this.loggingPolicy}}get oauthEnabled(){return this.config.oauth?.enabled===!0}async getOAuthStatus(){if(!this.oauthEnabled)return"disabled";if(this.runtimeOptions.oauthCredentialAccess===!1)return"unavailable";return this.oauthProvider?.getStatus()??"error"}async beginOAuthLogin(t={}){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);return t.openBrowser?this.oauthProvider.openAuthorization():this.oauthProvider.beginAuthorization()}async logoutOAuth(){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(this.status!=="disconnected")await this.disconnect();await this.oauthProvider.logout()}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(t=3,i=1000){if(!Number.isInteger(t)||t<1||t>At)throw Error(`MCP connection maxRetries must be an integer between 1 and ${At}`);if(!Number.isFinite(i)||i<0||i>_t)throw Error(`MCP connection initialDelay must be between 0 and ${_t}`);if(this.status==="connected")return;if(this.recoveryPromise)return this.recoveryPromise;if(this.connectPromise)return this.connectPromise;this.desiredConnected=!0;let n=++this.connectionGeneration,s=new AbortController;this.connectAbortController=s;let e=this.runInitialConnection(Math.max(1,t),Math.max(0,i),n,s.signal).finally(()=>{if(this.connectPromise===e)this.connectPromise=void 0;if(this.connectAbortController===s)this.connectAbortController=void 0});return this.connectPromise=e,e}async runInitialConnection(t,i,n,s){let e;for(let o=1;o<=t;o++){this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!1);return}catch(c){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=c instanceof Error?c:Error(String(c)),!vi(e).isRetryable||o===t)break;await Pt(i*2**Math.max(0,o-1),s,!1)}}let r=e??Error("MCP connection failed");if(this.isConnectionGenerationCurrent(n))this.invalidateLiveConnection(!1),this.setStatus("error"),this.emitClientError(r);throw r}async doConnect(t,i){let n;try{this.assertConnectionGeneration(t),this.setStatus(i?"reconnecting":"connecting");let s=Mn(this.config.sampling),e={...s,enabled:s.enabled&&this.runtimeOptions.samplingAvailable===!0};n=new ds({name:sn(),version:nn()},{capabilities:{roots:{listChanged:!1},elicitation:{form:{applyDefaults:!1},url:{}},...e.enabled?{sampling:{}}:{}},listChanged:{tools:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshTools("notification")}},resources:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["resources"])}},prompts:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["prompts"])}}}});let r=n;if(this.sdkClient=r,this.resetCatalogRefreshState(),this.registerElicitationHandlers(r),this.registerRootHandler(r),e.enabled)this.registerSamplingHandler(r,e);if(this.registerResourceNotificationHandler(r),this.registerLoggingHandler(r),this.taskPolicy.enabled)this.registerTaskStatusHandler(r);r.onclose=()=>{this.handleUnexpectedClose(r,t)},r.onerror=(d)=>{this.handleTransportError(r,t,d)};let o=await this.createTransport();this.assertConnectionGeneration(t),await r.connect(o),this.assertConnectionGeneration(t);let c=r.getServerVersion();this.serverInfo={name:c?.name||"Unknown",version:c?.version||"0.0.0"},this.serverInstructions=Tn(r.getInstructions(),{exposeDetails:this.runtimeOptions.exposeInstructions}),await this.configureLogging(r),await this.refreshTools("initial"),await this.refreshContentCatalogs("initial").catch(()=>{return}),await this.reconcileResourceSubscriptions(r),this.assertConnectionGeneration(t),this.consecutiveTerminalErrors=0,this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor?.resetFailureCount(),this.healthMonitor?.start()}catch(s){if(n&&this.sdkClient===n)this.sdkClient=null;if(n)n.onclose=void 0,n.onerror=void 0,await n.close().catch(()=>{return});throw s}}handleUnexpectedClose(t,i){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;this.startRecovery(Error(`MCP server "${this.serverName}" connection closed`),"transport_closed",!1)}handleTransportError(t,i,n){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;if(this.emit("transportError",{serverName:this.serverName,error:k(n)}),fi(n)){this.startRecovery(n,"session_expired",!0);return}if(!hi(n)){this.consecutiveTerminalErrors=0;return}if(this.consecutiveTerminalErrors++,n.message.toLowerCase().includes("maximum reconnection attempts")||this.consecutiveTerminalErrors>=this.recoveryPolicy.terminalErrorThreshold)this.startRecovery(n,"transport_error",!0)}requestRecovery(t,i){if(!this.desiredConnected||this.status!=="connected"||this.recoveryPromise)return;this.startRecovery(t,i,!0)}startRecovery(t,i,n){if(!this.desiredConnected||this.recoveryPromise)return;let s=this.sdkClient;if(this.sdkClient=null,s)s.onclose=void 0,s.onerror=void 0;this.healthMonitor?.stop(),this.invalidateLiveConnection(!0);let e=++this.connectionGeneration,r=new AbortController;if(this.recoveryAbortController=r,this.setStatus("reconnecting"),n&&s)s.close().catch(()=>{return});let o=Promise.resolve().then(()=>this.runRecoveryLoop(t,i,e,r.signal)).finally(()=>{if(this.recoveryPromise===o)this.recoveryPromise=void 0;if(this.recoveryAbortController===r)this.recoveryAbortController=void 0});this.recoveryPromise=o,o.catch(()=>{return})}async runRecoveryLoop(t,i,n,s){let e=t;if(!this.recoveryPolicy.enabled||this.recoveryPolicy.maxAttempts===0){this.failRecovery(e,i,0,n);return}for(let r=1;r<=this.recoveryPolicy.maxAttempts;r++){this.assertConnectionGeneration(n,s);let o=bi(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),c=Date.now()+o;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:c,error:k(e)}),await Pt(o,s),this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!0),this.healthMonitor?.resetFailureCount(),this.publishConnectionLifecycle({phase:"recovered",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts}),this.emit("reconnected");return}catch(d){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=d instanceof Error?d:Error(String(d)),!vi(e).isRetryable){this.failRecovery(e,i,r,n);return}}}this.failRecovery(e,i,this.recoveryPolicy.maxAttempts,n)}failRecovery(t,i,n,s){if(!this.isConnectionGenerationCurrent(s))return;this.setStatus("error"),this.publishConnectionLifecycle({phase:"failed",reason:i,attempt:n,maxAttempts:this.recoveryPolicy.maxAttempts,error:k(t)}),this.emit("reconnectFailed",t)}publishConnectionLifecycle(t){this.recoveryState=structuredClone(t),this.emit("connectionLifecycleChanged",structuredClone(t))}isConnectionGenerationCurrent(t){return this.desiredConnected&&this.connectionGeneration===t}assertConnectionGeneration(t,i){if(i?.aborted||!this.desiredConnected||this.connectionGeneration!==t)throw C(i?.reason)}invalidateLiveConnection(t){if(this.resetCatalogRefreshState(),this.tools.clear(),this.resources=[],this.resourceTemplates=[],this.prompts=[],this.activeResourceSubscriptions.clear(),!t)this.desiredResourceSubscriptions.clear();if(!t)this.taskInteractions.clear();this.serverInfo=null,this.serverInstructions=void 0,this.consecutiveTerminalErrors=0}resetCatalogRefreshState(){this.catalogGeneration++,this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,this.contentRefreshPromise=void 0,this.requestedContentCatalogs.clear(),this.contentRefreshReason="manual"}emitClientError(t){if(this.listenerCount("error")>0)this.emit("error",t)}async ping(t=1e4){let i=this.sdkClient;if(!i||this.status!=="connected")throw Error(`MCP server "${this.serverName}" is not connected`);let n=new AbortController,s=setTimeout(()=>n.abort("MCP health check timeout"),t);s.unref();try{await i.ping({signal:n.signal,timeout:t,maxTotalTimeout:t})}catch(e){if(n.signal.aborted)throw Error(`MCP server "${this.serverName}" health check timed out after ${t}ms`);throw e}finally{clearTimeout(s)}}async disconnect(){this.desiredConnected=!1,this.connectionGeneration++,this.connectAbortController?.abort("MCP client disconnected"),this.recoveryAbortController?.abort("MCP client disconnected"),this.healthMonitor?.stop();let t=this.sdkClient;if(this.sdkClient=null,t)t.onclose=void 0,t.onerror=void 0,await t.close().catch(()=>{return});await Promise.allSettled([this.connectPromise,this.recoveryPromise].filter((i)=>i!==void 0)),this.invalidateLiveConnection(!1),this.recoveryState=void 0,await this.oauthProvider?.dispose(),this.setStatus("disconnected"),this.emit("disconnected")}async callTool(t,i={},n={}){let s=this.sdkClient;if(!s||this.status!=="connected")throw Error("客户端未连接到服务器");if(!this.tools.has(t))throw Error(`工具 "${t}" 不存在`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive tool calls`);let e=gt(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let o=new AbortController,c=setTimeout(()=>o.abort("mcp-tool-timeout"),e.totalTimeoutMs);c.unref();let d=n.signal?AbortSignal.any([n.signal,o.signal]):o.signal,p={count:0};try{return await s.callTool({name:t,arguments:i},St,{signal:d,timeout:e.idleTimeoutMs,resetTimeoutOnProgress:!0,maxTotalTimeout:e.totalTimeoutMs,onprogress:(M)=>{let w=mt(M,p,e);if(w&&!d.aborted&&this.activeInteraction?.token===r)n.progressHandler?.(w),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...w})}})}catch(u){if(n.signal?.aborted)throw new DOMException(String(n.signal.reason||"MCP tool call cancelled"),"AbortError");if(o.signal.aborted&&!n.signal?.aborted)throw new R(P.RequestTimeout,`MCP server "${this.serverName}" tool "${t}" timed out after ${e.totalTimeoutMs}ms`);throw console.error(`[McpClient] 调用工具 "${t}" 失败:`,u),u}finally{if(clearTimeout(c),this.activeInteraction?.token===r)this.activeInteraction=void 0}}getToolTaskSupport(t){return this.tools.get(t)?.taskSupport}async createToolTask(t,i,n,s,e){let r=this.sdkClient;if(!r||this.status!=="connected")throw Error("MCP client is not connected");if(!this.taskPolicy.enabled)throw Error(`MCP tasks are disabled for server "${this.serverName}"`);if(!r.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);let o=this.getToolTaskSupport(t);if(o!=="required"&&o!=="optional")throw Error(`MCP tool "${t}" does not support task execution`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive task creation`);let c=gt(this.config),d=Symbol(t),p={token:d,context:{...n,signal:s},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let u={count:0},M=r.experimental.tasks.callToolStream({name:t,arguments:i},St,{signal:s,task:{ttl:e??this.taskPolicy.defaultTtlMs,pollInterval:this.taskPolicy.pollIntervalMs},timeout:c.idleTimeoutMs,maxTotalTimeout:c.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let E=mt(y,u,c);if(E&&!s.aborted&&this.hasInteractionToken(d))n.progressHandler?.(E),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...E})}}),w=!1;try{let y=await M.next();if(await M.return(void 0),y.done||y.value.type!=="taskCreated"){if(!y.done&&y.value.type==="error")throw y.value.error;throw Error(`MCP tool "${t}" did not create a task`)}if(this.sdkClient!==r)throw Error("MCP client changed while creating a task");let E=Ut(y.value.task,this.taskPolicy);return this.taskInteractions.set(E.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:E}),E}finally{if(this.activeInteraction?.token===d)this.activeInteraction=void 0;if(!w){for(let[y,E]of this.taskInteractions)if(E.token===d)this.taskInteractions.delete(y)}}}async getToolTask(t,i,n){let s=this.requireTaskClient(),e=await s.experimental.tasks.getTask(t,{signal:n,timeout:this.taskPolicy.pollIntervalMs+1e4,maxTotalTimeout:this.taskPolicy.pollIntervalMs+1e4});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task");return Ut(e,this.taskPolicy,{taskId:t,createdAt:i})}async getToolTaskResult(t,i,n=this.taskPolicy.maxLifetimeMs){let s=this.requireTaskClient(),e=Math.max(1,Math.min(n,this.taskPolicy.maxLifetimeMs)),r=await s.experimental.tasks.getTaskResult(t,St,{signal:i,timeout:e,maxTotalTimeout:e});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task result");return r}async cancelToolTask(t,i){let n=this.requireTaskClient();if(!n.getServerCapabilities()?.tasks?.cancel)throw Error(`MCP server "${this.serverName}" does not support task cancellation`);if(await n.experimental.tasks.cancelTask(t,{signal:i,timeout:15000,maxTotalTimeout:15000}),this.sdkClient!==n)throw Error("MCP client changed while cancelling a task")}async normalizeToolTaskResult(t){return j(t,this.runtimeOptions.artifactWriter)}releaseTaskInteraction(t){this.taskInteractions.delete(t)}async waitUntilConnected(t,i){if(this.status==="connected"&&this.sdkClient)return;if(!this.desiredConnected)throw Error(`MCP server "${this.serverName}" is disconnected`);await new Promise((n,s)=>{let e=setTimeout(()=>{d(),s(Error(`MCP server "${this.serverName}" recovery timed out`))},i);e.unref();let r=()=>{d(),n()},o=()=>{if(this.desiredConnected)return;d(),s(Error(`MCP server "${this.serverName}" was disconnected`))},c=()=>{d(),s(new DOMException(String(t.reason||"MCP task recovery cancelled"),"AbortError"))},d=()=>{clearTimeout(e),this.off("connected",r),this.off("disconnected",o),t.removeEventListener("abort",c)};if(this.on("connected",r),this.on("disconnected",o),t.addEventListener("abort",c,{once:!0}),t.aborted)c()})}requireTaskClient(){let t=this.sdkClient;if(!t||this.status!=="connected"||!this.taskPolicy.enabled)throw Error(`MCP server "${this.serverName}" task client is unavailable`);if(!t.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);return t}hasInteractionToken(t){if(this.activeInteraction?.token===t)return!0;return[...this.taskInteractions.values()].some((i)=>i.token===t)}registerRootHandler(t){t.setRequestHandler(ws,async()=>({roots:this.roots.map((i)=>({...i}))}))}resolveInteraction(t){let i=t._meta?.["io.modelcontextprotocol/related-task"]?.taskId;return i?this.taskInteractions.get(i):this.activeInteraction}registerTaskStatusHandler(t){t.setNotificationHandler(Es,(i)=>{this.emit("taskStatus",i.params)})}registerSamplingHandler(t,i){t.setRequestHandler(cs,async(n,s)=>{let e=this.resolveInteraction(n.params);if(!e?.context.confirmationHandler||!e.context.samplingHandler)throw new R(P.InvalidRequest,"MCP sampling requires an active interactive Session");if(e.samplingInFlight)throw new R(P.InvalidRequest,"MCP server does not allow overlapping sampling requests");e.samplingInFlight=!0;try{if(e.samplingRequests++,e.samplingRequests>i.maxRequestsPerToolCall)throw new R(P.InvalidRequest,`MCP sampling exceeded ${i.maxRequestsPerToolCall} requests for one tool call`);let r=e.context.signal?AbortSignal.any([e.context.signal,s.signal]):s.signal;if(r.aborted)throw new R(P.InvalidRequest,"MCP sampling was cancelled");let o;try{o=wn(n.params,i)}catch(p){throw new R(P.InvalidRequest,p instanceof Error?p.message:String(p))}let c=await e.context.confirmationHandler.requestConfirmation({type:"mcpSampling",kind:"execute",toolName:`MCP sampling: ${this.serverName}`,title:"MCP model sampling request",message:`MCP server "${this.serverName}" wants to call the current Session model with up to ${o.maxTokens} output tokens.`,details:o.preview,risks:[`May consume up to ${o.maxTokens} output tokens`,"The model response will be returned to the MCP server"]},r);if(r.aborted||c.reason===Xt||c.reason==="timeout")throw new R(P.InvalidRequest,"MCP sampling was cancelled");if(!c.approved)throw new R(P.InvalidRequest,"MCP sampling was denied");let d=await e.context.samplingHandler(o,r);return this.emit("samplingCompleted",{serverName:this.serverName,model:d.model,maxTokens:o.maxTokens}),d}finally{e.samplingInFlight=!1}})}registerElicitationHandlers(t){t.setRequestHandler(Ms,async(i,n)=>{let s=this.resolveInteraction(i.params)?.context;if(!s?.confirmationHandler)return this.emit("elicitationCancelled",{serverName:this.serverName,reason:"no-interaction-handler"}),{action:"cancel"};let e=s.signal?AbortSignal.any([s.signal,n.signal]):n.signal;if(e.aborted)return{action:"cancel"};let r;try{r=Fi(this.serverName,i.params)}catch(o){return this.emit("elicitationRejected",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"decline"}}try{let o=s.sessionId&&s.workspaceRoot&&s.permissionMode?{projectDir:s.workspaceRoot,sessionId:s.sessionId,permissionMode:s.permissionMode,abortSignal:e}:void 0,c=o?await Bt.getInstance().executeElicitationHooks(r,o):{},d;if(c.blockedReason)d={action:"decline"};else if(c.response)d=c.response;else{let M=await s.confirmationHandler.requestConfirmation({type:"mcpElicitation",message:r.message,title:`MCP input requested by ${this.serverName}`,mcpElicitation:r},e),w=this.resolveElicitationAction(M,e);if(d=M.elicitation??{action:w},w==="accept"&&r.mode==="url"&&M.openExternalUrl&&r.url)await fs(r.url,{wait:!1})}let p=o?await Bt.getInstance().executeElicitationResultHooks(r,d,o):{};if(p.blockedReason)d={action:"cancel"};else if(p.response)d=p.response;let u=Ji(r,d);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:u.action,elicitationId:r.elicitationId}),u}catch(o){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"cancel"}}}),t.setNotificationHandler(us,(i)=>{this.emit("elicitationCompleted",{serverName:this.serverName,elicitationId:i.params.elicitationId})})}resolveElicitationAction(t,i){if(i.aborted||t.reason===Xt||t.reason==="timeout")return"cancel";if(t.elicitation)return t.elicitation.action;return t.approved?"accept":"decline"}async createTransport(){let{type:t,command:i,args:n,env:s,cwd:e,url:r,headers:o,oauth:c}=this.config,d;if(c?.enabled){if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(!await this.oauthProvider.hasUsableCredentials())throw new zt(this.serverName);d=this.oauthProvider}if(t==="stdio"){if(!i)throw Error("stdio 传输需要 command 参数");let p={};for(let[u,M]of Object.entries(process.env))if(M!==void 0)p[u]=M;return new ps({command:i,args:n||[],env:{...p,...s},cwd:e,stderr:"ignore"})}else if(t==="sse"){if(!r)throw Error("sse 传输需要 url 参数");return new os(new URL(r),{requestInit:{headers:o},...c?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}else if(t==="http"){if(!r)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:p}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new p(new URL(r),{requestInit:{headers:o},...c?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}throw Error(`不支持的传输类型: ${t}`)}async refreshTools(t="manual"){if(this.toolRefreshRequested=!0,this.toolRefreshPromise)return this.toolRefreshPromise;let i=this.catalogGeneration,n=(t==="notification"?new Promise((s)=>{setTimeout(s,25).unref()}):Promise.resolve()).then(()=>this.runToolRefresh(t)).finally(()=>{if(i!==this.catalogGeneration||this.toolRefreshPromise!==n)return;let s=this.toolRefreshRequested;if(this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,s&&this.sdkClient)this.refreshTools("notification")});return this.toolRefreshPromise=n,n}async waitForToolRefresh(){while(this.toolRefreshPromise)await this.toolRefreshPromise}async runToolRefresh(t){let i=t;for(let n=0;n<3&&this.toolRefreshRequested;n++){this.toolRefreshRequested=!1;try{await this.fetchAndPublishTools(i)}catch(s){if(this.emit("toolsRefreshFailed",{serverName:this.serverName,reason:i,error:s instanceof Error?s:Error(String(s))}),i!=="notification")throw s;return}i="notification"}}async fetchAndPublishTools(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=[],s=new Set,e;for(let p=0;p<it;p++){let u=await i.listTools(e?{cursor:e}:void 0);if(n.push(...u.tools),n.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);if(e=u.nextCursor,!e)break;if(s.has(e))throw Error("MCP tool catalog returned a repeated cursor");if(s.add(e),p===it-1)throw Error(`MCP tool catalog exceeds ${it} pages`)}let r=Qi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing tools");let o=this.availableTools,c=Ni(o,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(c))return;this.toolCatalogRevision++;let d={revision:this.toolCatalogRevision,reason:t,...c};this.emit("toolsUpdated",this.availableTools,d)}async refreshContentCatalogs(t="manual",i=["resources","prompts"]){let n=this.sdkClient?.getServerCapabilities();for(let r of i){if(r==="resources"&&n?.resources)this.requestedContentCatalogs.add(r);if(r==="prompts"&&n?.prompts)this.requestedContentCatalogs.add(r)}if(this.requestedContentCatalogs.size===0)return;if(this.contentRefreshPromise){if(t!=="notification")this.contentRefreshReason=t;return this.contentRefreshPromise}this.contentRefreshReason=t;let s=this.catalogGeneration,e=(t==="notification"?new Promise((r)=>{setTimeout(r,25).unref()}):Promise.resolve()).then(()=>this.runContentCatalogRefresh()).finally(()=>{if(s!==this.catalogGeneration||this.contentRefreshPromise!==e)return;let r=this.requestedContentCatalogs.size>0;if(this.contentRefreshPromise=void 0,this.contentRefreshReason="manual",r&&this.sdkClient)this.refreshContentCatalogs("notification")});return this.contentRefreshPromise=e,e}async waitForCatalogRefresh(){while(this.toolRefreshPromise||this.contentRefreshPromise)await Promise.all([this.toolRefreshPromise??Promise.resolve(),this.contentRefreshPromise??Promise.resolve()])}async runContentCatalogRefresh(){for(let t=0;t<3&&this.requestedContentCatalogs.size>0;t++){let i=[...this.requestedContentCatalogs];this.requestedContentCatalogs.clear();let n=this.contentRefreshReason;this.contentRefreshReason="notification";let s=[];for(let e of i)try{if(e==="resources")await this.fetchAndPublishResourceCatalog(n);else await this.fetchAndPublishPromptCatalog(n)}catch(r){let o=r instanceof Error?r:Error(String(r));s.push(o),this.emit("contentCatalogRefreshFailed",{serverName:this.serverName,catalog:e,reason:n,error:o})}if(s.length>0&&n!=="notification")throw AggregateError(s,`Failed to refresh MCP content catalogs for "${this.serverName}"`)}}async fetchAndPublishResourceCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("resource",q,(d)=>i.listResources(d?{cursor:d}:void 0),(d)=>d.resources),s=await this.fetchContentPages("resource template",K,(d)=>i.listResourceTemplates(d?{cursor:d}:void 0),(d)=>d.resourceTemplates),e=ki(n),r=Oi(s);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing resource catalogs");let o=I(this.resources,e,(d)=>d.uri),c=I(this.resourceTemplates,r,(d)=>d.uriTemplate);this.resources=e,this.resourceTemplates=r,await this.reconcileResourceSubscriptions(i),this.publishContentCatalogDelta("resources",t,o),this.publishContentCatalogDelta("resourceTemplates",t,c)}async fetchAndPublishPromptCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("prompt",W,(r)=>i.listPrompts(r?{cursor:r}:void 0),(r)=>r.prompts),s=Li(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing prompts");let e=I(this.prompts,s,(r)=>r.name);this.prompts=s,this.publishContentCatalogDelta("prompts",t,e)}async fetchContentPages(t,i,n,s){let e=[],r=new Set,o;for(let c=0;c<Rt;c++){let d=await n(o);if(e.push(...s(d)),e.length>i)throw Error(`MCP ${t} catalog exceeds ${i} entries`);if(o=d.nextCursor,!o)return e;if(r.has(o))throw Error(`MCP ${t} catalog returned a repeated cursor`);r.add(o)}throw Error(`MCP ${t} catalog exceeds ${Rt} pages`)}publishContentCatalogDelta(t,i,n){if(!Si(n))return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,kind:t,reason:i,...n};this.emit("contentCatalogUpdated",this.contentCatalog,s)}registerResourceNotificationHandler(t){t.setNotificationHandler(Ts,(i)=>{let n=i.params.uri;if(this.sdkClient!==t||!this.activeResourceSubscriptions.has(n))return;this.contentCatalogRevision++,this.emit("resourceUpdated",{revision:this.contentCatalogRevision,serverName:this.serverName,uri:n})})}registerLoggingHandler(t){t.setNotificationHandler(ys,(i)=>{if(this.sdkClient!==t||!this.loggingPolicy.enabled||!cn(i.params.level,this.loggingPolicy.level))return;let n=Date.now();if(n-this.logWindowStartedAt>=1000)this.logWindowStartedAt=n,this.logEventsInWindow=0,this.logRateWarningEmitted=!1;if(this.logEventsInWindow>=dn){if(!this.logRateWarningEmitted)this.logRateWarningEmitted=!0,this.emit("log",un(1,{now:n}));return}this.logEventsInWindow++;let s=lt({level:i.params.level,logger:i.params.logger,data:i.params.data},{exposeDetails:this.runtimeOptions.exposeLogDetails,now:n});this.emit("log",s)})}async configureLogging(t){if(this.logWindowStartedAt=Date.now(),this.logEventsInWindow=0,this.logRateWarningEmitted=!1,!this.loggingPolicy.enabled||!t.getServerCapabilities()?.logging)return;try{await t.setLoggingLevel(this.loggingPolicy.level)}catch(i){if(this.sdkClient!==t)return;let n={serverName:this.serverName,level:this.loggingPolicy.level,error:k(i)};this.emit("loggingSetupFailed",n),this.emit("log",{...lt({level:"warning",logger:"blade.mcp.logging",data:`Failed to set MCP logging level: ${n.error}`},{exposeDetails:this.runtimeOptions.exposeLogDetails}),synthetic:!0})}}async setLoggingLevel(t){if(!pn(t))throw Error("Invalid MCP logging level");let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!i.getServerCapabilities()?.logging)throw Error(`MCP server "${this.serverName}" does not support logging`);if(await i.setLoggingLevel(t),this.sdkClient!==i)throw Error("MCP client changed while setting logging level");this.loggingPolicy={enabled:!0,level:t},this.emit("loggingLevelChanged",{serverName:this.serverName,level:t})}async complete(t,i){let n=this.sdkClient;if(!n||this.status!=="connected")throw Error("MCP client is not connected");if(!n.getServerCapabilities()?.completions)throw Error(`MCP server "${this.serverName}" does not support completions`);if(this.completionCallsInFlight>=pi)throw Error(`MCP server "${this.serverName}" has too many completion requests`);let s=ci(t,this.contentCatalog);this.completionCallsInFlight++;try{let e=await n.complete(s,{signal:i,timeout:ht,maxTotalTimeout:ht});if(this.sdkClient!==n)throw Error("MCP client changed while completing an argument");return ui(e)}catch(e){if(i?.aborted)throw new DOMException(String(i.reason||"MCP completion cancelled"),"AbortError");throw e}finally{this.completionCallsInFlight--}}async readResource(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!this.resources.some((n)=>n.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);return mi(await i.readResource({uri:t}))}async getPrompt(t,i={}){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");let s=this.prompts.find((r)=>r.name===t);if(!s)throw Error(`MCP prompt "${t}" is not present in server "${this.serverName}" catalog`);let e=new Set(s.arguments.map((r)=>r.name));for(let[r,o]of Object.entries(i)){if(["__proto__","constructor","prototype"].includes(r))throw Error(`Unsafe argument "${r}" for MCP prompt "${t}"`);if(!e.has(r))throw Error(`Unknown argument "${r}" for MCP prompt "${t}"`);if(Buffer.byteLength(o)>16384)throw Error(`Argument "${r}" for MCP prompt "${t}" is too large`)}for(let r of s.arguments)if(r.required&&i[r.name]===void 0)throw Error(`Required argument "${r.name}" is missing for MCP prompt "${t}"`);return li(await n.getPrompt({name:t,arguments:i}))}async setResourceSubscription(t,i){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");if(i){if(!this.resources.some((s)=>s.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);if(this.desiredResourceSubscriptions.has(t)&&this.activeResourceSubscriptions.has(t))return;if(!this.desiredResourceSubscriptions.has(t)&&this.desiredResourceSubscriptions.size>=at)throw Error(`MCP resource subscriptions exceed ${at}`);if(!n.getServerCapabilities()?.resources?.subscribe)throw Error(`MCP server "${this.serverName}" does not support resource subscriptions`);if(await n.subscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while subscribing to resource");this.desiredResourceSubscriptions.add(t),this.activeResourceSubscriptions.add(t);return}if(!this.desiredResourceSubscriptions.has(t))return;if(this.activeResourceSubscriptions.has(t)){if(await n.unsubscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while unsubscribing from resource")}this.activeResourceSubscriptions.delete(t),this.desiredResourceSubscriptions.delete(t)}async reconcileResourceSubscriptions(t){if(this.sdkClient!==t)return;let i=new Set(this.resources.map((n)=>n.uri));for(let n of this.activeResourceSubscriptions)if(!i.has(n))this.activeResourceSubscriptions.delete(n);if(!t.getServerCapabilities()?.resources?.subscribe){this.activeResourceSubscriptions.clear();return}for(let n of this.desiredResourceSubscriptions){if(!i.has(n)||this.activeResourceSubscriptions.has(n))continue;try{if(await t.subscribeResource({uri:n}),this.sdkClient!==t)return;this.activeResourceSubscriptions.add(n)}catch(s){this.emit("resourceSubscriptionRestoreFailed",{serverName:this.serverName,uri:n,error:k(s)})}}}setStatus(t){let i=this.status;if(i===t)return;this.status=t,this.emit("statusChanged",t,i)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(t){return this.connect()}async disconnectFromServer(t){return this.disconnect()}async listResources(t){return structuredClone(this.resources)}async listResourceTemplates(){return structuredClone(this.resourceTemplates)}async listPrompts(){return structuredClone(this.prompts)}async listTools(t){return this.availableTools}}class O extends hs{runtimeOptions;static instance=null;servers=new Map;isDiscovering=!1;catalogRevision=0;contentCatalogRevision=0;connectionRevision=0;logRevision=0;instructionsRevision=0;logEntries=[];projectedTools=new Map;constructor(t={}){super();this.runtimeOptions=t}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static createIsolated(t={}){return new O(t)}async registerServer(t,i,n={}){if(this.servers.has(t))throw Error(`MCP服务器 "${t}" 已经注册`);let s=new Yt(i,t,i.healthCheck,this.runtimeOptions),e={config:i,client:s,status:"disconnected",tools:[],contentCatalog:{resources:[],resourceTemplates:[],prompts:[]},logging:s.logging};if(this.setupClientEventHandlers(s,e,t),this.servers.set(t,e),this.emit("serverRegistered",t,e),n.connect===!1)return;try{await this.connectServer(t)}catch(r){console.warn(`MCP服务器 "${t}" 连接失败:`,r)}}async unregisterServer(t){let i=this.servers.get(t);if(!i)return;try{await T.getInstance().cancelClient(i.client),await i.client.disconnect()}catch(n){console.warn(`断开MCP服务器 "${t}" 时出错:`,n)}this.servers.delete(t),this.logEntries=this.logEntries.filter((n)=>n.serverName!==t),this.emit("serverUnregistered",t)}async connectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status==="connected")return;try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async disconnectServer(t){let i=this.servers.get(t);if(!i)return;await T.getInstance().cancelClient(i.client),await i.client.disconnect(),i.connectedAt=void 0}async reconnectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await T.getInstance().cancelClient(i.client),await i.client.disconnect();try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async getAvailableTools(){return[...this.projectedTools.values()]}getCatalogSnapshot(){return{revision:this.catalogRevision,tools:[...this.projectedTools.values()]}}async waitForCatalogIdle(){await Promise.all([...this.servers.values()].map((t)=>t.client.waitForCatalogRefresh()))}getContentCatalogSnapshot(){let t=[],i=[],n=[];for(let[s,e]of this.servers){if(e.status!=="connected")continue;t.push(...e.contentCatalog.resources.map((r)=>({server:s,...structuredClone(r)}))),i.push(...e.contentCatalog.resourceTemplates.map((r)=>({server:s,...structuredClone(r)}))),n.push(...e.contentCatalog.prompts.map((r)=>({server:s,...structuredClone(r)})))}return{revision:this.contentCatalogRevision,resources:t,resourceTemplates:i,prompts:n}}getLogSnapshot(t,i={}){let n=Number.isSafeInteger(i.afterRevision)&&(i.afterRevision??0)>=0?i.afterRevision??0:0,s=Number.isSafeInteger(i.limit)&&(i.limit??0)>=1&&(i.limit??0)<=B?i.limit??B:B,e=this.logEntries.filter((r)=>r.revision>n&&(!t||r.serverName===t)).slice(-s).map((r)=>structuredClone(r));return{revision:this.logRevision,entries:e}}getInstructionsSnapshot(){let t=[];for(let[i,n]of this.servers){if(n.status!=="connected"||!n.instructions)continue;t.push({serverName:i,...structuredClone(n.instructions)})}return t.sort((i,n)=>i.serverName.localeCompare(n.serverName)),{revision:this.instructionsRevision,instructions:t}}async refreshContentCatalogs(t){if(t){await this.requireConnectedServer(t).client.refreshContentCatalogs("manual");return}await Promise.all([...this.servers.values()].filter((i)=>i.status==="connected").map((i)=>i.client.refreshContentCatalogs("manual")))}async readResource(t,i){return this.requireConnectedServer(t).client.readResource(i)}async getPrompt(t,i,n={}){return this.requireConnectedServer(t).client.getPrompt(i,n)}async complete(t,i,n){return this.requireConnectedServer(t).client.complete(i,n)}async startTask(t,i,n,s,e,r,o){let c=this.requireConnectedServer(t);if(!c.tools.some((d)=>d.name===i))throw Error(`MCP tool "${i}" is not present in server "${t}" catalog`);return T.getInstance().start({client:c.client,serverName:t,toolName:i,arguments:n,owner:s,interactionContext:e,signal:r,ttlMs:o})}listTasks(t,i){return T.getInstance().list(t,i)}getTask(t,i){return T.getInstance().get(t,i)}waitForTask(t,i,n,s){return T.getInstance().wait(t,i,n,s)}cancelTask(t,i,n){return T.getInstance().cancel(t,i,n)}async setResourceSubscription(t,i,n){await this.requireConnectedServer(t).client.setResourceSubscription(i,n)}async setServerLoggingLevel(t,i){let n=this.requireConnectedServer(t);await n.client.setLoggingLevel(i),n.logging=n.client.logging}async findTool(t){return this.projectedTools.get(t)??null}getToolsByServer(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return[];return i.tools.map((n)=>Tt(i.client,t,n,Lt(t,n.name),this.runtimeOptions.artifactWriter))}getServerStatus(t){return this.servers.get(t)||null}getAllServers(){return new Map(this.servers)}async getServerOAuthStatus(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);return i.client.getOAuthStatus()}async beginOAuthLogin(t,i={}){let n=this.servers.get(t);if(!n)throw Error(`MCP服务器 "${t}" 未注册`);let s=await n.client.beginOAuthLogin(i);this.emit("serverOAuthStatusChanged",t,"authorizing");let e=s.completion.then(async()=>{this.emit("serverOAuthCompleted",t),this.emit("serverOAuthStatusChanged",t,"authenticated");try{await this.reconnectServer(t)}catch(r){n.lastError=r instanceof Error?r:Error(String(r)),n.status="error",this.emit("serverError",t,n.lastError)}},(r)=>{throw n.lastError=r instanceof Error?r:Error(String(r)),this.emit("serverOAuthError",t,n.lastError),this.emit("serverOAuthStatusChanged",t,"error"),n.lastError});return e.catch(()=>{return}),{...s,completion:e}}async logoutOAuth(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await i.client.logoutOAuth(),i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.tools=[],this.emit("serverOAuthStatusChanged",t,"unauthenticated")}async refreshAllTools(){let t=[];for(let[i,n]of this.servers)if(n.status==="connected")t.push(this.refreshServerTools(i));await Promise.allSettled(t)}async refreshServerTools(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return;try{await i.client.refreshTools("manual")}catch(n){throw console.warn(`刷新服务器 "${t}" 工具列表失败:`,n),n}}setupClientEventHandlers(t,i,n){t.on("connected",(s)=>{if(i.status="connected",i.connectedAt=new Date,i.lastError=void 0,i.tools=t.availableTools,i.contentCatalog=t.contentCatalog,i.logging=t.logging,i.instructions=this.fitInstructionBudget(n,t.instructions),this.publishCatalog(n,"connection"),this.publishInitialContentCatalog(n,i.contentCatalog),i.instructions)this.publishInstructions(n,"added","connection",i.instructions);this.emit("serverConnected",n,s)}),t.on("disconnected",()=>{i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.recovery=void 0,this.invalidateServerProjection(n,i),this.emit("serverDisconnected",n)}),t.on("error",(s)=>{i.status="error",i.lastError=s,this.invalidateServerProjection(n,i),this.emit("serverError",n,s)}),t.on("connectionLifecycleChanged",(s)=>{if(i.recovery=structuredClone(s),s.phase==="reconnecting")i.status="reconnecting",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError,this.invalidateServerProjection(n,i);else if(s.phase==="recovered")i.status="connected",i.lastError=void 0;else i.status="error",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError;this.publishConnectionLifecycle(n,s)}),t.on("toolsUpdated",(s,e)=>{let r=i.tools.length;if(i.tools=s,i.status==="connected"&&e)this.publishCatalog(n,e.reason);this.emit("toolsUpdated",n,s,r)}),t.on("toolsRefreshFailed",(s)=>{this.emit("catalogRefreshFailed",{serverName:n,...s})}),t.on("contentCatalogUpdated",(s,e)=>{if(i.contentCatalog=s,i.status!=="connected")return;this.publishContentCatalogChange(n,e.kind,e.reason,{added:e.added,removed:e.removed,updated:e.updated})}),t.on("contentCatalogRefreshFailed",(s)=>{this.emit("contentCatalogRefreshFailed",{serverName:n,...s})}),t.on("resourceUpdated",(s)=>{if(i.status!=="connected")return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:n,uri:s.uri};this.emit("resourceUpdated",e)}),t.on("statusChanged",(s,e)=>{if(i.status=s,s==="reconnecting"&&e==="connected")i.connectedAt=void 0,this.invalidateServerProjection(n,i);this.emit("serverStatusChanged",n,s,e)}),t.on("loggingLevelChanged",()=>{i.logging=t.logging,this.emit("serverLoggingLevelChanged",n,i.logging.level)}),t.on("log",(s)=>{this.publishLog(n,s)})}publishLog(t,i){this.logRevision++;let n={revision:this.logRevision,serverName:t,...structuredClone(i)};this.logEntries.push(n);let s=0;for(let e=this.logEntries.length-1;e>=0;e--){if(this.logEntries[e]?.serverName!==t)continue;if(s++,s>En)this.logEntries.splice(e,1)}while(this.logEntries.length>B)this.logEntries.shift();this.emit("log",structuredClone(n))}invalidateServerProjection(t,i){let n=i.contentCatalog,s=i.instructions!==void 0;if(i.tools=[],i.contentCatalog={resources:[],resourceTemplates:[],prompts:[]},i.instructions=void 0,this.publishCatalog(t,"disconnection"),this.publishRemovedContentCatalog(t,n),s)this.publishInstructions(t,"removed","disconnection")}fitInstructionBudget(t,i){if(!i)return;let n=0;for(let[s,e]of this.servers){if(s===t)continue;n+=e.instructions?.projectedBytes??0}return fn(i,Math.max(0,bn-n))}publishInstructions(t,i,n,s){this.instructionsRevision++;let e={revision:this.instructionsRevision,serverName:t,action:i,reason:n,...s?{instruction:structuredClone(s)}:{}};this.emit("instructionsChanged",e)}publishConnectionLifecycle(t,i){this.connectionRevision++;let n={revision:this.connectionRevision,serverName:t,...structuredClone(i)};this.emit("connectionLifecycleChanged",n)}publishCatalog(t,i){let n=new Map;for(let[c,d]of this.servers){if(d.status!=="connected")continue;for(let p of d.tools){let u=Lt(c,p.name);if(n.has(u))throw Error(`Duplicate projected MCP tool "${u}"`);n.set(u,Tt(d.client,c,p,u,this.runtimeOptions.artifactWriter))}}let s=new Map([...this.projectedTools].map(([c,d])=>[c,JSON.stringify(d.getFunctionDeclaration())])),e=new Map([...n].map(([c,d])=>[c,JSON.stringify(d.getFunctionDeclaration())])),r={added:[...n.keys()].filter((c)=>!this.projectedTools.has(c)).sort(),removed:[...this.projectedTools.keys()].filter((c)=>!n.has(c)).sort(),updated:[...n.keys()].filter((c)=>this.projectedTools.has(c)&&s.get(c)!==e.get(c)).sort()};if(this.projectedTools=n,!nt(r))return;this.catalogRevision++;let o={revision:this.catalogRevision,serverName:t,reason:i,tools:[...n.values()],...r};this.emit("catalogChanged",o)}publishInitialContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","connection",{added:i.resources.map((n)=>n.uri).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","connection",{added:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"prompts","connection",{added:i.prompts.map((n)=>n.name).sort(),removed:[],updated:[]})}publishRemovedContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","disconnection",{added:[],removed:i.resources.map((n)=>n.uri).sort(),updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","disconnection",{added:[],removed:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),updated:[]}),this.publishContentCatalogChange(t,"prompts","disconnection",{added:[],removed:i.prompts.map((n)=>n.name).sort(),updated:[]})}publishContentCatalogChange(t,i,n,s){if(s.added.length===0&&s.removed.length===0&&s.updated.length===0)return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:t,kind:i,reason:n,...s};this.emit("contentCatalogChanged",e)}requireConnectedServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status!=="connected")throw Error(`MCP服务器 "${t}" 未连接`);return i}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(t){let i=Object.entries(t).map(([n,s])=>this.registerServer(n,s).catch((e)=>{return console.warn(`注册MCP服务器 "${n}" 失败:`,e),e}));await Promise.allSettled(i)}getStatistics(){let t=0,i=0,n=0;for(let s of this.servers.values())if(s.status==="connected")t++,i+=s.tools.length;else if(s.status==="error")n++;return{totalServers:this.servers.size,connectedServers:t,errorServers:n,totalTools:i,isDiscovering:this.isDiscovering}}async disconnectAll(){let t=[];for(let[i,n]of this.servers)t.push(T.getInstance().cancelClient(n.client).then(()=>n.client.disconnect()).catch((s)=>{console.warn(`断开 MCP 服务器 "${i}" 时出错:`,s)}));await Promise.allSettled(t),this.servers.clear(),this.projectedTools.clear(),this.logEntries=[]}}
|
|
25
|
+
export{Gt as ma,T as na,Gn as oa,ie as pa,ne as qa,Ji as ra,Lt as sa,is as ta,O as ua};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var f;((b)=>{b.DEFAULT="default";b.AUTO_EDIT="autoEdit";b.YOLO="yolo";b.PLAN="plan"})(f||={});
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as Sf};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{f as T,g as W,h as X,i as Y}from"./chunk-32g59k4p.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-qnxgzyyx.js";import"./chunk-x2vqgssm.js";import"./chunk-txkrtgcd.js";import"./chunk-c8ddch38.js";import"./chunk-7s5hw0gr.js";import"./chunk-y6tkxqjx.js";import"./chunk-dcp5gg6q.js";import"./chunk-mrsc4a55.js";import"./chunk-ag5ea7ce.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as R}from"./chunk-yqy000kg.js";import"./chunk-fk4wbmv6.js";import{yd as Q}from"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-jpz805fs.js";import"./chunk-yypnfmed.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import{Sg as M}from"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
+
____ _ _
|
|
3
|
+
| __ )| | __ _ __| | ___
|
|
4
|
+
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
+
| |_) | | (_| | (_| | __/
|
|
6
|
+
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
+
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
+
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
+
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
+
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Kg as o}from"./chunk-26wse17p.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
|
|
2
2
|
export{e as j,i as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Oa as J,va as V,xa as W,ya as O}from"./chunk-y6tkxqjx.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as Q}from"./chunk-kfpzrmq7.js";import"./chunk-fhnkyqfb.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
|