blade-code 0.10.205 → 0.11.1
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-7ajvrtb3.js → chunk-06hkf59s.js} +1 -1
- package/dist/{chunk-p0wyhp5a.js → chunk-0b83mt1c.js} +2 -2
- package/dist/{chunk-qtwgm95z.js → chunk-0wcnkxe8.js} +3 -3
- package/dist/{chunk-b8ast0cp.js → chunk-1beqtjsw.js} +1 -1
- package/dist/chunk-1kxpnt9q.js +1 -0
- package/dist/chunk-25s0c8km.js +1726 -0
- package/dist/{chunk-ak5xvsxr.js → chunk-27bjk35b.js} +1 -1
- package/dist/{chunk-515yj7mt.js → chunk-2ftyzk83.js} +1 -1
- package/dist/chunk-2g3v9qpz.js +1 -0
- package/dist/{chunk-5zmp7p0n.js → chunk-2vrsfb8p.js} +59 -59
- package/dist/{chunk-17d4m89n.js → chunk-30p7aff1.js} +2 -2
- package/dist/{chunk-kehgewqh.js → chunk-3kszepm6.js} +1 -1
- package/dist/{chunk-ys8gysg8.js → chunk-3y2x6fb6.js} +1 -1
- package/dist/chunk-43gg1wdc.js +1 -0
- package/dist/{chunk-xbs91jd8.js → chunk-447ps2te.js} +2 -2
- package/dist/{chunk-0eajnhrj.js → chunk-4cdk4mds.js} +1 -1
- package/dist/{chunk-8pd1hp4r.js → chunk-5034apfz.js} +2 -2
- package/dist/{chunk-ynd1v33f.js → chunk-5bc4hwt9.js} +1 -1
- package/dist/chunk-72wn385d.js +1 -0
- package/dist/chunk-7eset766.js +25 -0
- package/dist/chunk-7vzz3rsx.js +332 -0
- package/dist/{chunk-xxbxc31z.js → chunk-80946c9a.js} +1 -1
- package/dist/chunk-8emp6ysb.js +1 -0
- package/dist/chunk-8evyh5t0.js +1 -0
- package/dist/chunk-8hdtssvs.js +1 -0
- package/dist/chunk-8n3jythp.js +733 -0
- package/dist/{chunk-zj1g4nbq.js → chunk-8sth12hd.js} +1 -1
- package/dist/{chunk-fdr4fcrf.js → chunk-9qxch6sy.js} +1 -1
- package/dist/chunk-9ydrwcpy.js +3 -0
- package/dist/chunk-9yn01a90.js +12 -0
- package/dist/chunk-a1tt14a2.js +2 -0
- package/dist/{chunk-egss0m1x.js → chunk-a731hdwa.js} +1 -1
- package/dist/{chunk-gn9er641.js → chunk-a74ynw4t.js} +1 -1
- package/dist/chunk-b36egepz.js +1 -0
- package/dist/chunk-dxq7462e.js +352 -0
- package/dist/{chunk-eg3ms291.js → chunk-f552hzcx.js} +1 -1
- package/dist/{chunk-g01mth5d.js → chunk-f6hc7t65.js} +2 -2
- package/dist/{chunk-qq5y7b2r.js → chunk-fqxzzsgr.js} +1 -1
- package/dist/{chunk-xyypxrad.js → chunk-g0hhqxpg.js} +1 -1
- package/dist/{chunk-4wx5sya5.js → chunk-gzbb747a.js} +1 -1
- package/dist/{chunk-w42j9p3t.js → chunk-h8w3ahnk.js} +1 -1
- package/dist/chunk-hmw99nm1.js +94 -0
- package/dist/chunk-hrtf7dba.js +2 -0
- package/dist/chunk-j7dx054r.js +1 -0
- package/dist/chunk-j9ppeg6v.js +1 -0
- package/dist/chunk-jemb0vwa.js +1 -0
- package/dist/{chunk-qdbbke8f.js → chunk-m30qwpe9.js} +1 -1
- package/dist/{chunk-kvp523gt.js → chunk-m70cnaeg.js} +1 -1
- package/dist/{chunk-rtwd35gd.js → chunk-m8te4s8f.js} +2 -2
- package/dist/chunk-ms0wve9g.js +14 -0
- package/dist/{chunk-wezr6wfq.js → chunk-n8qg68y2.js} +1 -1
- package/dist/chunk-pm5ssr7m.js +25 -0
- package/dist/chunk-r9m3b170.js +1 -0
- package/dist/chunk-rt3f4xjz.js +23 -0
- package/dist/{chunk-430b319j.js → chunk-s1cch8tt.js} +1 -1
- package/dist/chunk-sa9fxss4.js +2 -0
- package/dist/{chunk-xmymx75h.js → chunk-ta99scbr.js} +1 -1
- package/dist/chunk-tf1qz4q6.js +1 -0
- package/dist/{chunk-efjjkha8.js → chunk-tqt5c2f5.js} +2 -2
- package/dist/{chunk-9jz1q7bk.js → chunk-ts5xzefm.js} +2 -2
- package/dist/chunk-v17q4bsd.js +6 -0
- package/dist/{chunk-qp2qc4p2.js → chunk-v1k6nvth.js} +2 -2
- package/dist/{chunk-1cy4ab77.js → chunk-vbjgcn49.js} +1 -1
- package/dist/{chunk-kkzznz4w.js → chunk-wcps5gjm.js} +1 -1
- package/dist/{chunk-vz88tqtd.js → chunk-xcj23spc.js} +2 -2
- package/dist/chunk-xcy45yxx.js +8 -0
- package/dist/chunk-xseh3f4m.js +2 -0
- package/dist/chunk-xz7dddaj.js +4 -0
- package/dist/{chunk-c51wwnh2.js → chunk-xzva8y4e.js} +5 -6
- package/dist/chunk-y0wc0hef.js +10 -0
- package/dist/chunk-yrr9mdjn.js +44 -0
- package/dist/{chunk-f8kjdxz7.js → chunk-zjezws85.js} +2 -2
- package/dist/web/assets/ChatView-BA3kB_z1.js +17 -0
- package/dist/web/assets/CodeBlockHighlighter-B5kcdVCA.js +8 -0
- package/dist/web/assets/FilePreview-BQid6G2-.js +8 -0
- package/dist/web/assets/KanbanBoard-CTR7bMLa.js +1 -0
- package/dist/web/assets/MarkdownRenderer-d7DdyYdx.js +30 -0
- package/dist/web/assets/ScrollArea-D1tPWHKZ.js +1 -0
- package/dist/web/assets/SessionHistorySurface-Cv_jRoJr.js +1 -0
- package/dist/web/assets/SettingsModal-CFa2uCzI.js +5 -0
- package/dist/web/assets/Sidebar-DrRNJOgU.js +1 -0
- package/dist/web/assets/TaskSwitcher-C9AKJrl-.js +1 -0
- package/dist/web/assets/TerminalPanel-BxBGcuB9.js +1 -0
- package/dist/web/assets/archive-DNa9b1YE.js +1 -0
- package/dist/web/assets/arrow-left-BQh8jlfT.js +1 -0
- package/dist/web/assets/calendar-clock-CC7FeYTg.js +1 -0
- package/dist/web/assets/chevron-right-6ZTOJE0p.js +1 -0
- package/dist/web/assets/clock-3-P2q6i6vm.js +1 -0
- package/dist/web/assets/copy-C-KvzjCC.js +1 -0
- package/dist/web/assets/dist-DiQNoDMg.js +11 -0
- package/dist/web/assets/download-CJHn20x1.js +1 -0
- package/dist/web/assets/folder-DmyFehXD.js +1 -0
- package/dist/web/assets/index-BVEiHNFk.css +1 -0
- package/dist/web/assets/index-D-oma3Je.js +11 -0
- package/dist/web/assets/message-square-plus-CKu9bFq3.js +1 -0
- package/dist/web/assets/pause-D2FxNG-w.js +1 -0
- package/dist/web/assets/pencil-D6HI7KC8.js +1 -0
- package/dist/web/assets/play-4jKCDYR-.js +1 -0
- package/dist/web/assets/plus-C4p8E1Nk.js +1 -0
- package/dist/web/assets/preload-helper-BC9Zf9qO.js +1 -0
- package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/dist/web/assets/session-events-CvFfHkFA.js +23 -0
- package/dist/web/assets/settings-fWlqCZ-U.js +1 -0
- package/dist/web/assets/team-qGS2kixH.js +1 -0
- package/dist/web/assets/teamService-DfIvlI2_.js +1 -0
- package/dist/web/assets/terminal-DZkEoiSb.js +1 -0
- package/dist/web/assets/triangle-alert-Detl9fRQ.js +1 -0
- package/dist/web/assets/vendor-radix-CHeA_3Pt.js +41 -0
- package/dist/web/assets/vendor-react-hNfZDUf2.js +9 -0
- package/dist/web/assets/vendor-xterm-CANZO_wP.js +16 -0
- package/dist/web/assets/vendor-xterm-CHOd7Rch.css +1 -0
- package/dist/web/index.html +6 -4
- package/package.json +11 -10
- package/dist/chunk-18swytk4.js +0 -25
- package/dist/chunk-3297ghav.js +0 -1
- package/dist/chunk-33ck9ryb.js +0 -1
- package/dist/chunk-4fa11h6f.js +0 -94
- package/dist/chunk-535s1mm8.js +0 -1
- package/dist/chunk-57939tb3.js +0 -8
- package/dist/chunk-6169xxb4.js +0 -2
- package/dist/chunk-6v0cdqkw.js +0 -1
- package/dist/chunk-8kwj6px8.js +0 -1
- package/dist/chunk-a8z11yd2.js +0 -3
- package/dist/chunk-aatfjx15.js +0 -2
- package/dist/chunk-b2ek44t5.js +0 -12
- package/dist/chunk-b9d0ex8n.js +0 -4
- package/dist/chunk-bwe49m6n.js +0 -1719
- package/dist/chunk-ccgtbzrz.js +0 -14
- package/dist/chunk-jgxfhk9k.js +0 -733
- package/dist/chunk-jhpwwwjt.js +0 -1
- package/dist/chunk-jjj86dej.js +0 -1
- package/dist/chunk-kejvty9z.js +0 -23
- package/dist/chunk-kf9gj2gn.js +0 -2
- package/dist/chunk-mhe1zppc.js +0 -1
- package/dist/chunk-pb1q26gw.js +0 -181
- package/dist/chunk-pc5f77qh.js +0 -1
- package/dist/chunk-pkx6kfy6.js +0 -1
- package/dist/chunk-qjptyj18.js +0 -1
- package/dist/chunk-shgxzmdw.js +0 -1
- package/dist/chunk-thytjs86.js +0 -44
- package/dist/chunk-tm3789m3.js +0 -2
- package/dist/chunk-tnmcrvk2.js +0 -25
- package/dist/chunk-wejthch2.js +0 -1
- package/dist/chunk-xv6ejk2z.js +0 -353
- package/dist/chunk-yvgef7rp.js +0 -10
- package/dist/chunk-zj48897e.js +0 -6
- package/dist/web/assets/ChatView-BF6HUrBw.js +0 -70
- package/dist/web/assets/CodeBlockHighlighter-C4CgCiRf.js +0 -8
- package/dist/web/assets/FilePreview-BS4PgFKb.js +0 -55
- package/dist/web/assets/KanbanBoard-DDXB-yq1.js +0 -16
- package/dist/web/assets/MarkdownRenderer-DS7RznBE.js +0 -30
- package/dist/web/assets/ScrollArea-BM9NzGZM.js +0 -1
- package/dist/web/assets/SessionHistorySurface-DnRySeLE.js +0 -6
- package/dist/web/assets/SettingsModal-D5YLUtIo.js +0 -20
- package/dist/web/assets/Sidebar-BZC6OkDJ.js +0 -31
- package/dist/web/assets/TaskSwitcher-WewOkw5m.js +0 -26
- package/dist/web/assets/TerminalPanel-C5SGdRNr.js +0 -6
- package/dist/web/assets/archive-DkczUU08.js +0 -6
- package/dist/web/assets/arrow-left-9pBiQwu7.js +0 -6
- package/dist/web/assets/calendar-clock-BFnUlxrU.js +0 -6
- package/dist/web/assets/chevron-right-yCVkAEcj.js +0 -6
- package/dist/web/assets/clock-3-CcoWoRQs.js +0 -6
- package/dist/web/assets/copy-HJF0oQBS.js +0 -6
- package/dist/web/assets/download-DSBCIqk3.js +0 -6
- package/dist/web/assets/external-link-zIgEO0KB.js +0 -11
- package/dist/web/assets/folder-BdRo64o3.js +0 -11
- package/dist/web/assets/index-B5mUEr6D.js +0 -11
- package/dist/web/assets/index-BVDkKudh.js +0 -211
- package/dist/web/assets/index-CaCifsSK.css +0 -1
- package/dist/web/assets/message-square-plus-3klTXO0S.js +0 -21
- package/dist/web/assets/pause-B9Q5JWvH.js +0 -6
- package/dist/web/assets/pencil-CbYIz1b1.js +0 -6
- package/dist/web/assets/play-CZMTj43e.js +0 -6
- package/dist/web/assets/plus-Cc7I8fhb.js +0 -6
- package/dist/web/assets/session-events-NEjosinC.js +0 -31
- package/dist/web/assets/settings-DSF3exX2.js +0 -6
- package/dist/web/assets/team-qfeJHL9s.js +0 -6
- package/dist/web/assets/teamService-Bs9qBKI8.js +0 -1
- package/dist/web/assets/terminal-DQLqe-Ed.js +0 -6
- package/dist/web/assets/vendor-radix-D6QrtXqd.js +0 -45
- package/dist/web/assets/vendor-react-DofNRwfy.js +0 -49
- package/dist/web/assets/vendor-xterm-9CEnUXvW.css +0 -32
- package/dist/web/assets/vendor-xterm-DuYZoU4T.js +0 -49
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import{Ac as En,xc as Ut,yc as fn,zc as yn}from"./chunk-9qxch6sy.js";import{zh as xt}from"./chunk-xzva8y4e.js";import{Fh as Ot,Gh as vi,Ih as en,Jh as Bt,Kh as U,Lh as sn,Mh as St,Nh as gt,Ph as rn,Qh as Tn,Rh as B,Sh as on,Th as dn,Uh as pn,Vh as Lt,Wh as cn,Xh as un,Yh as Mn,_h as S,bi as wn,ci as Vt,di as lt,ei as h,fi as jt}from"./chunk-yrr9mdjn.js";import{Yi as Zt}from"./chunk-m30qwpe9.js";import{Fj as X,Hj as g}from"./chunk-9ydrwcpy.js";import{Xj as tn,Yj as nn}from"./chunk-a1tt14a2.js";import{Kk as ne}from"./chunk-f552hzcx.js";import{EventEmitter as be}from"events";import Un from"node:path";function hn(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 An(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||`验证失败:${hn(i)}`}}class Yt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Ft(t,i){let n=X(t,i);if(n.success)return n.data;let e=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),s=e.length===1?`参数验证失败 [${e[0].field}]: ${e[0].message}`:`参数验证失败 (${e.length} 个错误):
|
|
2
|
+
${e.map((r)=>` - ${r.field}: ${r.message}`).join(`
|
|
3
|
+
`)}`;throw new Yt(s,e)}function et(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 e of n)et(e);else et(n)}function st(t){let i=JSON.parse(JSON.stringify(t,(n,e)=>n.startsWith("~")?void 0:e));return et(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,e,s,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=e;this.affectedPathsFn=s;this.isRetrySafe=r}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 e={signal:t,updateOutput:i,...n};return this.executeFn(this.params,e)}}function Jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!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=st(t.schema),n=t.description.short;if(t.description.long)n+=`
|
|
4
|
+
|
|
5
|
+
${t.description.long}`;if(t.description.usageNotes&&t.description.usageNotes.length>0)n+=`
|
|
6
|
+
|
|
7
|
+
Usage Notes:
|
|
8
|
+
${t.description.usageNotes.map((e)=>`- ${e}`).join(`
|
|
9
|
+
`)}`;if(t.description.important&&t.description.important.length>0)n+=`
|
|
10
|
+
|
|
11
|
+
Important:
|
|
12
|
+
${t.description.important.map((e)=>`[WARN] ${e}`).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||[],isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),description:t.description,schema:st(t.schema)}},build(i){let n=Ft(t.schema,i);return new rt(t.name,n,t.execute,void 0,t.affectedPaths,t.isRetrySafe??!1)},async execute(i,n,e){return this.build(i).execute(n||new AbortController().signal,void 0,e)},extractSignatureContent:t.extractSignatureContent?(i)=>t.extractSignatureContent(i):void 0,abstractPermissionRule:t.abstractPermissionRule?(i)=>t.abstractPermissionRule(i):void 0}}import{randomUUID as an}from"node:crypto";import{EventEmitter as _n}from"node:events";import Pn from"node:path";class T extends _n{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 s=Vt(t.ttlMs,n),r=new AbortController,d=()=>r.abort(t.signal?.reason??"MCP task creation cancelled");t.signal?.addEventListener("abort",d,{once:!0});let c;try{c=await t.client.createToolTask(t.toolName,t.arguments,t.interactionContext,r.signal,s)}finally{t.signal?.removeEventListener("abort",d)}let o=Date.now(),p=`mcp_task_${an()}`,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:o,updatedAt:o,hasResult:!1,pollIntervalMs:c.pollIntervalMs,deadline:o+Math.min(s,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((e)=>ot(e.owner,n)&&(!i||e.serverName===i)).sort((e,s)=>e.createdAt-s.createdAt).map((e)=>this.snapshot(e))}hasActive(t){return this.ownedRecords(t).some((i)=>!h(i.status))}async wait(t,i,n,e){let s=this.getOwnedRecord(t,i);if(!s)return;if(!s.promise||h(s.status))return this.snapshot(s);let r,d,c=new Promise((o)=>{if(r=setTimeout(o,Math.max(0,n)),r.unref(),e){if(d=o,e.addEventListener("abort",d,{once:!0}),e.aborted)o()}});if(await Promise.race([s.promise,c]),r)clearTimeout(r);if(e&&d)e.removeEventListener("abort",d);return this.snapshot(s)}async cancel(t,i,n){let e=this.getOwnedRecord(t,i);if(!e)return;if(h(e.status))return this.snapshot(e);let s;try{await e.client.cancelToolTask(e.serverTaskId,n)}catch(r){s=dt(r,e.serverTaskId)}return e.controller.abort("MCP task cancelled"),this.update(e,{status:"cancelled",statusMessage:s?`Local cancellation completed; server acknowledgement failed: ${s}`:"Task cancelled",completedAt:Date.now()}),e.client.releaseTaskInteraction(e.serverTaskId),this.snapshot(e)}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(e){if(t.controller.signal.aborted)return;if(t.client.connectionStatus==="connected")throw e;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 e=t.deadline-Date.now();if(e<=0)continue;let s;try{s=await t.client.getToolTaskResult(t.serverTaskId,t.controller.signal,e)}catch(o){if(t.controller.signal.aborted)return;if(t.client.connectionStatus==="connected")throw o;this.update(t,{status:"interrupted",statusMessage:"Waiting for MCP connection recovery"}),await t.client.waitUntilConnected(t.controller.signal,e);continue}let r=await t.client.normalizeToolTaskResult(s),d=r.llmContent.replaceAll(t.serverTaskId,"[redacted-task-id]"),c=r.isError?{...r,llmContent:dt(d,t.serverTaskId)}:{...r,llmContent:d};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 Rn(t.pollIntervalMs,t.controller.signal)}}catch(i){if(!t.controller.signal.aborted)this.update(t,{status:"failed",statusMessage:"MCP task lifecycle failed",error:dt(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 e=JSON.stringify({status:t.status,statusMessage:t.statusMessage,serverUpdatedAt:t.serverUpdatedAt,hasResult:t.hasResult,error:t.error});if(n!==e||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&&ot(n.owner,z(i))?n:void 0}ownedRecords(t){let i=z(t);return[...this.tasks.values()].filter((n)=>ot(n.owner,i))}evictTerminalTasks(t,i){let n=this.ownedRecords(t).filter((e)=>h(e.status)).sort((e,s)=>e.updatedAt-s.updatedAt);while(this.list(t).length>=i&&n.length>0){let e=n.shift();if(e)this.tasks.delete(e.taskId)}if(this.tasks.size>=S){let e=[...this.tasks.values()].filter((s)=>h(s.status)).sort((s,r)=>s.updatedAt-r.updatedAt);while(this.tasks.size>=S&&e.length>0){let s=e.shift();if(s)this.tasks.delete(s.taskId)}}}}function z(t){if(!t.sessionId)throw Error("MCP task owner requires a Session ID");return{sessionId:t.sessionId,projectPath:Pn.resolve(t.projectPath)}}function ot(t,i){return t.sessionId===i.sessionId&&t.projectPath===i.projectPath}async function Rn(t,i){await new Promise((n,e)=>{let s=()=>i.removeEventListener("abort",d),r=setTimeout(()=>{s(),n()},t);r.unref();let d=()=>{clearTimeout(r),s(),e(new DOMException(String(i.reason||"MCP task cancelled"),"AbortError"))};if(i.addEventListener("abort",d,{once:!0}),i.aborted)d()})}function dt(t,i){let n=t instanceof Error?t.message:String(t);return jt(n.replaceAll(i,"[redacted-task-id]"))}import{createHash as Cn}from"node:crypto";var Nt=64,J=1048576,V=4194304,Gt=4194304,pt=8388608,D=16777216,qt=102400,$n=4096,Ht=8192,kn=256,mn=16384,ct=256,On=8192,Sn=2048;function Y(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 Ln(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 C(t,i,n){let e=F(t,i,n*4).trim();if(!e||e.length>n)throw Error(`MCP tool ${i} is invalid`);return e}function Kt(t,i,n){let e=Buffer.byteLength(i);if(e>J)throw Error(`MCP tool ${n} exceeds ${J} bytes`);if(t.textBytes+=e,t.textBytes>V)throw Error(`MCP tool text exceeds ${V} total bytes`)}function wt(t,i,n=!1){let e=Buffer.from(t);if(e.length<=i)return t;let r=(n?e.subarray(e.length-i):e.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 Wt(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 e=Buffer.from(t,"base64");if(e.length>pt)throw Error(`MCP tool ${i} exceeds ${pt} decoded bytes`);return e}async function ut(t,i){let n=Cn("sha256").update(t.bytes).digest("hex"),e={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 e;try{let s=await i.write(t);return{...e,...s,id:n,sha256:n,size:t.bytes.length}}catch{return e}}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(!Y(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>Gt)throw Error(`MCP tool structuredContent exceeds ${Gt} bytes`);return{text:i,bytes:n}}async function j(t,i){if(!Y(t)||!Array.isArray(t.content))throw Error("MCP tool result is malformed");if(t.content.length>Nt)throw Error(`MCP tool result exceeds ${Nt} content parts`);let n={textBytes:0,binaryBytes:0},e=[],s=[];for(let[o,p]of t.content.entries()){if(!Y(p))throw Error(`MCP tool content[${o}] is malformed`);if(p.type==="text"){let u=F(p.text,`content[${o}] text`,J);Kt(n,u,`content[${o}] text`),e.push(u);continue}if(p.type==="image"||p.type==="audio"){let u=C(p.mimeType,`content[${o}] MIME type`,ct),M=Wt(p.data,`content[${o}] ${p.type}`);if(n.binaryBytes+=M.length,n.binaryBytes>D)throw Error(`MCP tool binary content exceeds ${D} total bytes`);let w=await ut({kind:p.type,bytes:M,mimeType:u},i);s.push(w),e.push(Mt(w));continue}if(p.type==="resource_link"){let u=C(p.uri,`content[${o}] resource link URI`,Ht),M=C(p.name,`content[${o}] resource link name`,kn),w=p.description===void 0?void 0:F(p.description,`content[${o}] resource link description`,mn),y=p.mimeType===void 0?void 0:C(p.mimeType,`content[${o}] MIME type`,ct);e.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"&&Y(p.resource)){let u=p.resource,M=C(u.uri,`content[${o}] resource URI`,Ht),w=u.mimeType===void 0?void 0:C(u.mimeType,`content[${o}] resource MIME type`,ct);if(typeof u.text==="string"){let R=F(u.text,`content[${o}] resource text`,J);Kt(n,R,`content[${o}] resource text`),e.push(`[resource: uri=${JSON.stringify(M)}${w?` mime_type=${JSON.stringify(w)}`:""}]
|
|
14
|
+
${R}`);continue}let y=Wt(u.blob,`content[${o}] resource blob`);if(n.binaryBytes+=y.length,n.binaryBytes>D)throw Error(`MCP tool binary content exceeds ${D} total bytes`);let f=await ut({kind:"resource",bytes:y,mimeType:w,sourceUri:M},i);s.push(f),e.push(Mt(f));continue}throw Error(`Unsupported MCP tool content type: ${String(p.type)}`)}let r=ln(t.structuredContent);if(r)e.push(`[structuredContent]
|
|
15
|
+
${r.text}`);let d=e.join(`
|
|
16
|
+
|
|
17
|
+
`)||"MCP tool returned no content.";if(Buffer.byteLength(d)>V)throw Error(`MCP tool normalized result exceeds ${V} bytes`);let c=!1;if(Buffer.byteLength(d)>qt){let o=Buffer.from(d),p=await ut({kind:"text",bytes:o,mimeType:"text/plain"},i);s.push(p);let u=wt(d,On),M=wt(d,Sn,!0);d=`MCP tool result exceeded the ${qt}-byte inline budget.
|
|
18
|
+
${Mt(p)}
|
|
19
|
+
|
|
20
|
+
Preview (head):
|
|
21
|
+
${u}
|
|
22
|
+
|
|
23
|
+
Preview (tail):
|
|
24
|
+
${M}`,c=!0}return{isError:t.isError===!0,llmContent:d,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:s.length,truncated:c,binaryOmitted:n.binaryBytes>0,artifacts:s}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=Ln(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",$n)}function Qt(t,i,n,e,s){let r=n.inputSchema&&typeof n.inputSchema==="object"?g.Unsafe(n.inputSchema):g.Any(),d=e||n.name;return Jt({name:d,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,o){try{let p={...o.confirmationHandler?{confirmationHandler:o.confirmationHandler}:{},...o.mcpSamplingHandler?{samplingHandler:o.mcpSamplingHandler}:{},...o.onProgressUpdate?{progressHandler:o.onProgressUpdate}:{},...o.sessionId?{sessionId:o.sessionId}:{},...o.workspaceRoot?{workspaceRoot:o.workspaceRoot}:{},...o.permissionMode?{permissionMode:o.permissionMode}:{}};if(n.taskSupport==="required"){if(!o.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:o.sessionId,projectPath:Un.resolve(o.workspaceRoot||Zt())},interactionContext:p,signal:o.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,{...o.signal?{signal:o.signal}:{},...p}),M=await j(u,s),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 ee}from"node:fs";import Qi from"node:path";import{pathToFileURL as se}from"node:url";import{Client as re}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as oe}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as de}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolResultSchema as mt,CreateMessageRequestSchema as pe,ElicitationCompleteNotificationSchema as ce,ElicitRequestSchema as ue,ErrorCode as _,ListRootsRequestSchema as Me,LoggingMessageNotificationSchema as we,McpError as P,ResourceUpdatedNotificationSchema as ye,TaskStatusNotificationSchema as Te}from"@modelcontextprotocol/sdk/types.js";import{EventEmitter as fe}from"events";import Ee from"open";import{EventEmitter as Bn}from"events";function Tt(t,i,n,e,s){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t)||!Number.isInteger(t)||t<e||t>s)throw Error(`${n} must be an integer between ${e} and ${s}`);return t}class ft extends Bn{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:Tt(i.interval,30000,"MCP health check interval",10,300000),timeout:Tt(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:Tt(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 e={status:n,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:i};return this.emit("healthCheck",e),e}finally{this.isChecking=!1}}setStatus(t){if(this.currentStatus!==t){let i=this.currentStatus;this.currentStatus=t,this.emit("statusChanged",t,i)}}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}import{createHash as Xn}from"node:crypto";import{UriTemplate as zn}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";var vt=100,Dn=4096,Yn=65536,Et=1048576,ti=32,ii=65536,oi=4,bt=15000,ni=256,ei=16384,Fn=256,Jn=8192,Vn=/[\p{Cf}\p{Co}\p{Cn}]/u;function jn(t){return[...new Set(new zn(t).variableNames)]}function di(t,i){let n=N(t.argument.name,"completion argument name",ni),e=si(t.argument.value,"completion argument value",ei),s,r;if(t.reference.type==="prompt"){let p=N(t.reference.name,"completion prompt name",Fn),u=i.prompts.find((M)=>M.name===p);if(!u)throw Error(`MCP prompt "${p}" is not present in the current catalog`);s=new Set(u.arguments.map((M)=>M.name)),r={type:"ref/prompt",name:p}}else{let p=N(t.reference.uri,"completion resource template URI",Jn);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=jn(p)}catch{throw Error(`MCP resource template "${p}" is invalid`)}s=new Set(M),r={type:"ref/resource",uri:p}}if(!s.has(n))throw Error(`MCP ${t.reference.type} completion argument "${n}" is not declared`);let d=Object.entries(t.context??{});if(d.length>ti)throw Error(`MCP completion context exceeds ${ti} arguments`);let c=Object.create(null),o=0;for(let[p,u]of d){let M=N(p,"completion context argument name",ni);if(Mi(M))throw Error(`Unsafe MCP completion context argument "${M}"`);if(!s.has(M))throw Error(`Unknown MCP completion context argument "${M}"`);let w=si(u,`completion context argument "${M}"`,ei);if(o+=Buffer.byteLength(M)+Buffer.byteLength(w),o>ii)throw Error(`MCP completion context exceeds ${ii} bytes`);c[M]=w}return{ref:r,argument:{name:n,value:e},...d.length>0?{context:{arguments:c}}:{}}}function pi(t){let i=t.completion,n=JSON.stringify(i),e=Buffer.byteLength(n),s=Xn("sha256").update(n).digest("hex"),r=i.values.length,d=[],c=new Set,o=0,p=0,u=r>vt||e>Et;for(let w of i.values.slice(0,vt)){let y=Buffer.byteLength(w),f=Math.max(0,Et-p);if(f===0){u=!0;break}let R=ri(w,Math.min(Et,f));if(p+=Buffer.byteLength(R),y>Buffer.byteLength(R))u=!0;let zt=ci(R),O=ri(zt,Dn);if(Buffer.byteLength(O)<Buffer.byteLength(zt))u=!0;if(c.has(O))continue;let Dt=Buffer.byteLength(O);if(o+Dt>Yn){u=!0;break}c.add(O),d.push(O),o+=Dt}if(d.length<r)u=!0;let M=i.total!==void 0&&Number.isSafeInteger(i.total)&&i.total>=0?i.total:void 0;return{values:d,...M!==void 0?{total:M}:{},hasMore:i.hasMore===!0||u||M!==void 0&&M>d.length,sourceValueCount:r,sourceBytes:e,projectedBytes:o,sha256:s,truncated:u}}function ci(t){return[...t.normalize("NFKC")].filter((i)=>{let n=i.codePointAt(0)??0;if(n<32||n===127)return!1;return!Vn.test(i)}).join("")}function N(t,i,n){if(typeof t!=="string"||!t||Buffer.byteLength(t)>n)throw Error(`MCP ${i} is invalid`);if(ci(t)!==t||ui(t))throw Error(`MCP ${i} contains unsafe characters`);if(Mi(t))throw Error(`MCP ${i} is unsafe`);return t}function si(t,i,n){if(typeof t!=="string"||Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);if(ui(t))throw Error(`MCP ${i} contains control characters`);return t}function ui(t){return[...t].some((i)=>{let n=i.codePointAt(0)??0;return n<32||n===127})}function Mi(t){return["__proto__","constructor","prototype"].includes(t)}function ri(t,i){let n=Buffer.from(t);if(n.length<=i)return t;let e=n.subarray(0,Math.max(0,i)).toString("utf8");while(Buffer.byteLength(e)>i)e=e.slice(0,-1);return e}var ht=20,At=300000;function wi(t,i,n,e,s){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${n} must be a finite number`);if(t<e||t>s)throw Error(`${n} must be between ${e} and ${s}`);return t}function G(t,i,n,e,s){let r=wi(t,i,n,e,s);if(!Number.isInteger(r))throw Error(`${n} must be an integer`);return r}function yi(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 e=G(i?.maxAttempts,5,"MCP recovery maxAttempts",0,20),s=G(i?.initialDelayMs,1000,"MCP recovery initialDelayMs",10,300000),r=G(i?.maxDelayMs,30000,"MCP recovery maxDelayMs",s,300000),d=wi(i?.jitterRatio,0.2,"MCP recovery jitterRatio",0,1),c=G(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:e,initialDelayMs:s,maxDelayMs:r,jitterRatio:d,terminalErrorThreshold:c}}function Ti(t,i,n=Math.random){let e=Math.max(0,i-1),s=Math.min(t.initialDelayMs*2**e,t.maxDelayMs);if(t.jitterRatio===0)return s;let r=Math.min(1,Math.max(0,n())),d=1-t.jitterRatio+2*t.jitterRatio*r;return Math.max(0,Math.round(s*d))}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 e=Buffer.from(n).subarray(0,512).toString("utf8");while(Buffer.byteLength(e)>512)e=e.slice(0,-1);return e}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 Ei(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((e)=>n.includes(e))}function $(t){return new DOMException(String(t||"MCP connection recovery cancelled"),"AbortError")}async function at(t,i,n=!0){if(i.aborted)throw $(i.reason);await new Promise((e,s)=>{let d=setTimeout(()=>{i.removeEventListener("abort",c),e()},t);if(n)d.unref();let c=()=>{clearTimeout(d),i.removeEventListener("abort",c),s($(i.reason))};i.addEventListener("abort",c,{once:!0})})}import{createHash as Pi}from"node:crypto";var _t=100,q=1000,H=1000,K=1000,Pt=100,bi=64,W=1048576,a=4194304,A=256,Q=8192,L=256,l=16384,hi=64,Nn=4096,Ai=4194304,ai=128;function Ri(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}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 E(t,i,n){if(t===void 0)return;if(i==="description"?Gn(t):Ri(t))throw Error(`MCP ${i} contains control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);return t}function b(t,i,n){let e=t.trim();if(!e||e.length>n||Ri(e))throw Error(`MCP ${i} is invalid`);return e}function Rt(t){return Buffer.byteLength(JSON.stringify(t))}function Ct(t,i){if(Rt(t)>Ai)throw Error(`MCP ${i} catalog exceeds ${Ai} bytes`)}function Z(t,i){let n=new Set;for(let e of t){if(n.has(e))throw Error(`MCP ${i} catalog contains duplicate "${e}"`);n.add(e)}}function Ci(t){if(t.length>q)throw Error(`MCP resource catalog exceeds ${q} entries`);let i=t.map((n)=>({uri:b(n.uri,"resource URI",Q),name:b(n.name,"resource name",A),...E(n.title,"resource title",A)?{title:n.title}:{},...E(n.description,"description",l)?{description:n.description}:{},...E(n.mimeType,"resource MIME type",L)?{mimeType:n.mimeType}:{},...n.size!==void 0&&Number.isSafeInteger(n.size)&&n.size>=0?{size:n.size}:{}}));return Z(i.map((n)=>n.uri),"resource"),Ct(i,"resource"),i}function $i(t){if(t.length>H)throw Error(`MCP resource template catalog exceeds ${H} entries`);let i=t.map((n)=>({uriTemplate:b(n.uriTemplate,"resource template URI",Q),name:b(n.name,"resource template name",A),...E(n.title,"resource template title",A)?{title:n.title}:{},...E(n.description,"description",l)?{description:n.description}:{},...E(n.mimeType,"resource template MIME type",L)?{mimeType:n.mimeType}:{}}));return Z(i.map((n)=>n.uriTemplate),"resource template"),Ct(i,"resource template"),i}function ki(t){if(t.length>K)throw Error(`MCP prompt catalog exceeds ${K} entries`);let i=t.map((n)=>{if((n.arguments?.length??0)>hi)throw Error(`MCP prompt "${n.name}" exceeds ${hi} arguments`);let e=(n.arguments??[]).map((s)=>{let r=b(s.name,"prompt argument name",A);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...E(s.description,"description",Nn)?{description:s.description}:{},required:s.required===!0}});return Z(e.map((s)=>s.name),`prompt "${n.name}" argument`),{name:b(n.name,"prompt name",A),...E(n.title,"prompt title",A)?{title:n.title}:{},...E(n.description,"description",l)?{description:n.description}:{},arguments:e}});return Z(i.map((n)=>n.name),"prompt"),Ct(i,"prompt"),i}function _i(t){return Pi("sha256").update(JSON.stringify(t)).digest("hex")}function I(t,i,n){let e=new Map(t.map((r)=>[n(r),_i(r)])),s=new Map(i.map((r)=>[n(r),_i(r)]));return{added:[...s.keys()].filter((r)=>!e.has(r)).sort(),removed:[...e.keys()].filter((r)=>!s.has(r)).sort(),updated:[...s.keys()].filter((r)=>e.has(r)&&e.get(r)!==s.get(r)).sort()}}function mi(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function $t(t,i,n){if(t.bytes+=i,t.bytes>a)throw Error(`MCP ${n} exceeds ${a} total bytes`)}function Oi(t,i,n){if(t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP ${i} contains invalid base64`);let e=Buffer.from(t,"base64");if(e.length>a)throw Error(`MCP ${i} exceeds ${a} decoded bytes`);return $t(n,e.length,i),{size:e.length,sha256:Pi("sha256").update(e).digest("hex"),omitted:!0}}function Si(t,i){let n=b(typeof t.uri==="string"?t.uri:"","resource content URI",Q),e=typeof t.mimeType==="string"?E(t.mimeType,"resource MIME type",L):void 0;if(typeof t.text==="string"){let s=Buffer.byteLength(t.text);if(s>W)throw Error(`MCP resource text exceeds ${W} bytes`);return $t(i,s,"resource result"),{uri:n,...e?{mimeType:e}:{},text:t.text}}if(typeof t.blob==="string")return{uri:n,...e?{mimeType:e}:{},binary:Oi(t.blob,"resource blob",i)};throw Error("MCP resource content has neither text nor blob data")}function gi(t){let i=t&&typeof t==="object"&&Array.isArray(t.contents)?t.contents:[];if(i.length>bi)throw Error(`MCP resource result exceeds ${bi} contents`);let n={bytes:0},e=i.map((s)=>{if(!s||typeof s!=="object"||Array.isArray(s))throw Error("MCP resource content is malformed");return Si(s,n)});if(Rt(e)>a)throw Error(`MCP resource result exceeds ${a} bytes`);return{contents:e}}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>ai)throw Error(`MCP prompt exceeds ${ai} messages`);let e={bytes:0},s=n.map((r)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error("MCP prompt message is malformed");let d=r,c=d.role;if(c!=="user"&&c!=="assistant")throw Error("MCP prompt message has an invalid role");let o=d.content;if(!o||typeof o!=="object"||Array.isArray(o))throw Error("MCP prompt message content is malformed");let p=o;if(p.type==="text"&&typeof p.text==="string"){let u=Buffer.byteLength(p.text);if(u>W)throw Error(`MCP prompt text exceeds ${W} bytes`);return $t(e,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:b(p.mimeType,"prompt content MIME type",L),binary:Oi(p.data,`prompt ${p.type}`,e)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:c,content:{type:"resource",resource:Si(p.resource,e)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:c,content:{type:"resource_link",uri:b(p.uri,"prompt resource link URI",Q),name:b(p.name,"prompt resource link name",A),...typeof p.mimeType==="string"?{mimeType:b(p.mimeType,"prompt resource link MIME type",L)}:{},...typeof p.description==="string"?{description:E(p.description,"description",l)}:{}}};throw Error(`Unsupported MCP prompt content type: ${String(p.type)}`)});if(Rt(s)>a)throw Error(`MCP prompt result exceeds ${a} bytes`);return{...typeof i.description==="string"?{description:E(i.description,"description",l)}:{},messages:s}}var li=4000,xi=4096,Ui=32,qn=128,Bi=1000,Xi=100,zi=65536,Hn=new Set(["__proto__","constructor","prototype"]);function Di(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>li)throw Error(`MCP elicitation message exceeds ${li} characters`);if(i.mode==="url"){let s=Qn(i.url);if(!i.elicitationId.trim())throw Error("MCP URL elicitation ID is empty");return{serverName:t,mode:"url",message:i.message,url:s.toString(),domain:s.hostname,elicitationId:i.elicitationId}}let n=Object.entries(i.requestedSchema.properties);if(n.length>Ui)throw Error(`MCP elicitation exceeds the ${Ui} field limit`);let e=new Set(i.requestedSchema.required??[]);for(let s of e)if(!Object.hasOwn(i.requestedSchema.properties,s))throw Error(`MCP elicitation requires an unknown field: ${s}`);return{serverName:t,mode:"form",message:i.message,fields:n.map(([s,r])=>Kn(s,r,e.has(s))),requestedSchema:structuredClone(i.requestedSchema)}}function ve(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 ts(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 e=Number(n);if(!Number.isFinite(e))throw Error(`${t.title} must be a finite number`);if(t.type==="integer"&&!Number.isSafeInteger(e))throw Error(`${t.title} must be a safe integer`);return e}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 Yi(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")>zi)throw Error(`MCP elicitation response exceeds ${zi} bytes`);for(let r of Object.keys(n))Fi(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 e=g.Unsafe({...t.requestedSchema,additionalProperties:!1}),s=X(e,n);if(!s.success)throw Error(`Invalid MCP elicitation response: ${s.error.message}`);return{action:"accept",content:s.data}}function Kn(t,i,n){Fi(t);let e=tt(i.title?.trim()||t,"field title"),s=i.description?tt(i.description,"field description"):void 0,r={name:t,title:e,description:s,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=Zn(i);return{...r,type:"multi-select",options:c,...Array.isArray(i.default)&&i.default.every((o)=>typeof o==="string")?{defaultValue:[...i.default]}:{},...i.minItems!==void 0?{minItems:i.minItems}:{},...i.maxItems!==void 0?{maxItems:i.maxItems}:{}}}let d=Wn(i);if(d)return{...r,type:"select",options:d,...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 Wn(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 Zn(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>Xi)throw Error(`MCP elicitation options must contain 1-${Xi} 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 Fi(t){if(!t||t.length>qn||Hn.has(t))throw Error(`Unsafe MCP elicitation field name: ${t||"(empty)"}`)}function tt(t,i){if(t.length>Bi)throw Error(`MCP elicitation ${i} exceeds ${Bi} characters`);return t}function Qn(t){if(t.length>xi)throw Error(`MCP elicitation URL exceeds ${xi} 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 qi}from"node:crypto";var x=1000,it=100,In=256,Ji=16384,Vi=262144,ji=4194304,Ni=24;function vn(t,i=10){return qi("sha256").update(t).digest("hex").slice(0,i)}function kt(t){if(Array.isArray(t))return t.map(kt);if(!t||typeof t!=="object")return t;let i=t;return Object.fromEntries(Object.keys(i).sort().map((n)=>[n,kt(i[n])]))}function Hi(t){let i=t.normalize("NFKC"),n=i.replace(/[^A-Za-z0-9_-]/g,"_");if(n&&n===i&&n.length<=Ni)return n;return`${(n||"unnamed").slice(0,Ni-11)}_${vn(i)}`}function Ki(t,i){return`${te(t)}${Hi(i)}`}function te(t){return`mcp__${Hi(t)}__`}function Gi(t){return qi("sha256").update(JSON.stringify(kt({name:t.name,description:t.description,inputSchema:t.inputSchema,taskSupport:t.taskSupport}))).digest("hex")}function ie(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Wi(t){if(t.length>x)throw Error(`MCP tool catalog exceeds ${x} tools`);let i=new Set,n=[],e=0;for(let s of t){let r=s.name.trim();if(!r||r.length>In||ie(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 d=s.description??"";if(Buffer.byteLength(d)>Ji)throw Error(`MCP tool "${r}" description exceeds ${Ji} bytes`);let c=JSON.stringify(s.inputSchema),o=Buffer.byteLength(c);if(o>Vi)throw Error(`MCP tool "${r}" schema exceeds ${Vi} bytes`);if(e+=Buffer.byteLength(r)+Buffer.byteLength(d)+o,e>ji)throw Error(`MCP tool catalog exceeds ${ji} bytes`);n.push({name:r,description:d,inputSchema:JSON.parse(c),...s.execution?.taskSupport?{taskSupport:s.execution.taskSupport}:{}})}return n}function Zi(t,i){let n=new Map(t.map((s)=>[s.name,Gi(s)])),e=new Map(i.map((s)=>[s.name,Gi(s)]));return{added:[...e.keys()].filter((s)=>!n.has(s)).sort(),removed:[...n.keys()].filter((s)=>!e.has(s)).sort(),updated:[...e.keys()].filter((s)=>n.has(s)&&n.get(s)!==e.get(s)).sort()}}function nt(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function Ii(t){if(t instanceof Bt||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((s)=>i.includes(s)))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((s)=>i.includes(s)))return{type:"network_temporary",isRetryable:!0,originalError:t};return{type:"unknown",isRetryable:!0,originalError:t}}class Xt extends fe{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,e={}){super();this.config=t;this.runtimeOptions=e;this.serverName=i||"default",this.recoveryPolicy=yi(t),this.loggingPolicy=on(t),this.taskPolicy=wn(t.tasks),this.roots=(e.roots??[]).map((r)=>{let d=ee.native(Qi.resolve(r));return{uri:se(d).href,name:Qi.basename(d)||d}});let s=vi(t);if(this.config={...t,...s?{oauth:s}:{}},s?.enabled&&t.url&&e.oauthCredentialAccess!==!1)this.oauthProvider=new sn(this.serverName,t.url,s,e.oauthStorageRoot?{tokenStorage:new en(e.oauthStorageRoot)}:{});if(n?.enabled)this.healthMonitor=new ft(this,n),this.healthMonitor.on("unhealthy",(r,d)=>{this.emit("unhealthy",r,d)})}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 instructions(){return this.serverInstructions?structuredClone(this.serverInstructions):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>ht)throw Error(`MCP connection maxRetries must be an integer between 1 and ${ht}`);if(!Number.isFinite(i)||i<0||i>At)throw Error(`MCP connection initialDelay must be between 0 and ${At}`);if(this.status==="connected")return;if(this.recoveryPromise)return this.recoveryPromise;if(this.connectPromise)return this.connectPromise;this.desiredConnected=!0;let n=++this.connectionGeneration,e=new AbortController;this.connectAbortController=e;let s=this.runInitialConnection(Math.max(1,t),Math.max(0,i),n,e.signal).finally(()=>{if(this.connectPromise===s)this.connectPromise=void 0;if(this.connectAbortController===e)this.connectAbortController=void 0});return this.connectPromise=s,s}async runInitialConnection(t,i,n,e){let s;for(let d=1;d<=t;d++){this.assertConnectionGeneration(n,e);try{await this.doConnect(n,!1);return}catch(c){if(!this.isConnectionGenerationCurrent(n)||e.aborted)throw $(e.reason);if(s=c instanceof Error?c:Error(String(c)),!Ii(s).isRetryable||d===t)break;await at(i*2**Math.max(0,d-1),e,!1)}}let r=s??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 e=un(this.config.sampling),s={...e,enabled:e.enabled&&this.runtimeOptions.samplingAvailable===!0};n=new re({name:nn(),version:tn()},{capabilities:{roots:{listChanged:!1},elicitation:{form:{applyDefaults:!1},url:{}},...s.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),s.enabled)this.registerSamplingHandler(r,s);if(this.registerResourceNotificationHandler(r),this.registerLoggingHandler(r),this.taskPolicy.enabled)this.registerTaskStatusHandler(r);r.onclose=()=>{this.handleUnexpectedClose(r,t)},r.onerror=(o)=>{this.handleTransportError(r,t,o)};let d=await this.createTransport();this.assertConnectionGeneration(t),await r.connect(d),this.assertConnectionGeneration(t);let c=r.getServerVersion();this.serverInfo={name:c?.name||"Unknown",version:c?.version||"0.0.0"},this.serverInstructions=yn(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(e){if(n&&this.sdkClient===n)this.sdkClient=null;if(n)n.onclose=void 0,n.onerror=void 0,await n.close().catch(()=>{return});throw e}}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(!Ei(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 e=this.sdkClient;if(this.sdkClient=null,e)e.onclose=void 0,e.onerror=void 0;this.healthMonitor?.stop(),this.invalidateLiveConnection(!0);let s=++this.connectionGeneration,r=new AbortController;if(this.recoveryAbortController=r,this.setStatus("reconnecting"),n&&e)e.close().catch(()=>{return});let d=Promise.resolve().then(()=>this.runRecoveryLoop(t,i,s,r.signal)).finally(()=>{if(this.recoveryPromise===d)this.recoveryPromise=void 0;if(this.recoveryAbortController===r)this.recoveryAbortController=void 0});this.recoveryPromise=d,d.catch(()=>{return})}async runRecoveryLoop(t,i,n,e){let s=t;if(!this.recoveryPolicy.enabled||this.recoveryPolicy.maxAttempts===0){this.failRecovery(s,i,0,n);return}for(let r=1;r<=this.recoveryPolicy.maxAttempts;r++){this.assertConnectionGeneration(n,e);let d=Ti(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),c=Date.now()+d;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:c,error:k(s)}),await at(d,e),this.assertConnectionGeneration(n,e);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(o){if(!this.isConnectionGenerationCurrent(n)||e.aborted)throw $(e.reason);if(s=o instanceof Error?o:Error(String(o)),!Ii(s).isRetryable){this.failRecovery(s,i,r,n);return}}}this.failRecovery(s,i,this.recoveryPolicy.maxAttempts,n)}failRecovery(t,i,n,e){if(!this.isConnectionGenerationCurrent(e))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 $(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,e=setTimeout(()=>n.abort("MCP health check timeout"),t);e.unref();try{await i.ping({signal:n.signal,timeout:t,maxTotalTimeout:t})}catch(s){if(n.signal.aborted)throw Error(`MCP server "${this.serverName}" health check timed out after ${t}ms`);throw s}finally{clearTimeout(e)}}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 e=this.sdkClient;if(!e||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 s=St(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let d=new AbortController,c=setTimeout(()=>d.abort("mcp-tool-timeout"),s.totalTimeoutMs);c.unref();let o=n.signal?AbortSignal.any([n.signal,d.signal]):d.signal,p={count:0};try{return await e.callTool({name:t,arguments:i},mt,{signal:o,timeout:s.idleTimeoutMs,resetTimeoutOnProgress:!0,maxTotalTimeout:s.totalTimeoutMs,onprogress:(M)=>{let w=gt(M,p,s);if(w&&!o.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(d.signal.aborted&&!n.signal?.aborted)throw new P(_.RequestTimeout,`MCP server "${this.serverName}" tool "${t}" timed out after ${s.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,e,s){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 d=this.getToolTaskSupport(t);if(d!=="required"&&d!=="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=St(this.config),o=Symbol(t),p={token:o,context:{...n,signal:e},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let u={count:0},M=r.experimental.tasks.callToolStream({name:t,arguments:i},mt,{signal:e,task:{ttl:s??this.taskPolicy.defaultTtlMs,pollInterval:this.taskPolicy.pollIntervalMs},timeout:c.idleTimeoutMs,maxTotalTimeout:c.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let f=gt(y,u,c);if(f&&!e.aborted&&this.hasInteractionToken(o))n.progressHandler?.(f),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...f})}}),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 f=lt(y.value.task,this.taskPolicy);return this.taskInteractions.set(f.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:f}),f}finally{if(this.activeInteraction?.token===o)this.activeInteraction=void 0;if(!w){for(let[y,f]of this.taskInteractions)if(f.token===o)this.taskInteractions.delete(y)}}}async getToolTask(t,i,n){let e=this.requireTaskClient(),s=await e.experimental.tasks.getTask(t,{signal:n,timeout:this.taskPolicy.pollIntervalMs+1e4,maxTotalTimeout:this.taskPolicy.pollIntervalMs+1e4});if(this.sdkClient!==e)throw Error("MCP client changed while reading a task");return lt(s,this.taskPolicy,{taskId:t,createdAt:i})}async getToolTaskResult(t,i,n=this.taskPolicy.maxLifetimeMs){let e=this.requireTaskClient(),s=Math.max(1,Math.min(n,this.taskPolicy.maxLifetimeMs)),r=await e.experimental.tasks.getTaskResult(t,mt,{signal:i,timeout:s,maxTotalTimeout:s});if(this.sdkClient!==e)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,e)=>{let s=setTimeout(()=>{o(),e(Error(`MCP server "${this.serverName}" recovery timed out`))},i);s.unref();let r=()=>{o(),n()},d=()=>{if(this.desiredConnected)return;o(),e(Error(`MCP server "${this.serverName}" was disconnected`))},c=()=>{o(),e(new DOMException(String(t.reason||"MCP task recovery cancelled"),"AbortError"))},o=()=>{clearTimeout(s),this.off("connected",r),this.off("disconnected",d),t.removeEventListener("abort",c)};if(this.on("connected",r),this.on("disconnected",d),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(Me,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(Te,(i)=>{this.emit("taskStatus",i.params)})}registerSamplingHandler(t,i){t.setRequestHandler(pe,async(n,e)=>{let s=this.resolveInteraction(n.params);if(!s?.context.confirmationHandler||!s.context.samplingHandler)throw new P(_.InvalidRequest,"MCP sampling requires an active interactive Session");if(s.samplingInFlight)throw new P(_.InvalidRequest,"MCP server does not allow overlapping sampling requests");s.samplingInFlight=!0;try{if(s.samplingRequests++,s.samplingRequests>i.maxRequestsPerToolCall)throw new P(_.InvalidRequest,`MCP sampling exceeded ${i.maxRequestsPerToolCall} requests for one tool call`);let r=s.context.signal?AbortSignal.any([s.context.signal,e.signal]):e.signal;if(r.aborted)throw new P(_.InvalidRequest,"MCP sampling was cancelled");let d;try{d=Mn(n.params,i)}catch(p){throw new P(_.InvalidRequest,p instanceof Error?p.message:String(p))}let c=await s.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 ${d.maxTokens} output tokens.`,details:d.preview,risks:[`May consume up to ${d.maxTokens} output tokens`,"The model response will be returned to the MCP server"]},r);if(r.aborted||c.reason===Ut||c.reason==="timeout")throw new P(_.InvalidRequest,"MCP sampling was cancelled");if(!c.approved)throw new P(_.InvalidRequest,"MCP sampling was denied");let o=await s.context.samplingHandler(d,r);return this.emit("samplingCompleted",{serverName:this.serverName,model:o.model,maxTokens:d.maxTokens}),o}finally{s.samplingInFlight=!1}})}registerElicitationHandlers(t){t.setRequestHandler(ue,async(i,n)=>{let e=this.resolveInteraction(i.params)?.context;if(!e?.confirmationHandler)return this.emit("elicitationCancelled",{serverName:this.serverName,reason:"no-interaction-handler"}),{action:"cancel"};let s=e.signal?AbortSignal.any([e.signal,n.signal]):n.signal;if(s.aborted)return{action:"cancel"};let r;try{r=Di(this.serverName,i.params)}catch(d){return this.emit("elicitationRejected",{serverName:this.serverName,reason:d instanceof Error?d.message:String(d)}),{action:"decline"}}try{let d=e.sessionId&&e.workspaceRoot&&e.permissionMode?{projectDir:e.workspaceRoot,sessionId:e.sessionId,permissionMode:e.permissionMode,abortSignal:s}:void 0,c=d?await xt.getInstance().executeElicitationHooks(r,d):{},o;if(c.blockedReason)o={action:"decline"};else if(c.response)o=c.response;else{let M=await e.confirmationHandler.requestConfirmation({type:"mcpElicitation",message:r.message,title:`MCP input requested by ${this.serverName}`,mcpElicitation:r},s),w=this.resolveElicitationAction(M,s);if(o=M.elicitation??{action:w},w==="accept"&&r.mode==="url"&&M.openExternalUrl&&r.url)await Ee(r.url,{wait:!1})}let p=d?await xt.getInstance().executeElicitationResultHooks(r,o,d):{};if(p.blockedReason)o={action:"cancel"};else if(p.response)o=p.response;let u=Yi(r,o);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:u.action,elicitationId:r.elicitationId}),u}catch(d){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:d instanceof Error?d.message:String(d)}),{action:"cancel"}}}),t.setNotificationHandler(ce,(i)=>{this.emit("elicitationCompleted",{serverName:this.serverName,elicitationId:i.params.elicitationId})})}resolveElicitationAction(t,i){if(i.aborted||t.reason===Ut||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:e,cwd:s,url:r,headers:d,oauth:c}=this.config,o;if(c?.enabled){if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(!await this.oauthProvider.hasUsableCredentials())throw new Bt(this.serverName);o=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 de({command:i,args:n||[],env:{...p,...e},cwd:s,stderr:"ignore"})}else if(t==="sse"){if(!r)throw Error("sse 传输需要 url 参数");return new oe(new URL(r),{requestInit:{headers:d},...c?.enabled?{fetch:Ot}:{},...o?{authProvider:o}:{}})}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:d},...c?.enabled?{fetch:Ot}:{},...o?{authProvider:o}:{}})}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((e)=>{setTimeout(e,25).unref()}):Promise.resolve()).then(()=>this.runToolRefresh(t)).finally(()=>{if(i!==this.catalogGeneration||this.toolRefreshPromise!==n)return;let e=this.toolRefreshRequested;if(this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,e&&this.sdkClient)this.refreshTools("notification")});return this.toolRefreshPromise=n,n}async runToolRefresh(t){let i=t;for(let n=0;n<3&&this.toolRefreshRequested;n++){this.toolRefreshRequested=!1;try{await this.fetchAndPublishTools(i)}catch(e){if(this.emit("toolsRefreshFailed",{serverName:this.serverName,reason:i,error:e instanceof Error?e:Error(String(e))}),i!=="notification")throw e;return}i="notification"}}async fetchAndPublishTools(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=[],e=new Set,s;for(let p=0;p<it;p++){let u=await i.listTools(s?{cursor:s}:void 0);if(n.push(...u.tools),n.length>x)throw Error(`MCP tool catalog exceeds ${x} tools`);if(s=u.nextCursor,!s)break;if(e.has(s))throw Error("MCP tool catalog returned a repeated cursor");if(e.add(s),p===it-1)throw Error(`MCP tool catalog exceeds ${it} pages`)}let r=Wi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing tools");let d=this.availableTools,c=Zi(d,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(c))return;this.toolCatalogRevision++;let o={revision:this.toolCatalogRevision,reason:t,...c};this.emit("toolsUpdated",this.availableTools,o)}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 e=this.catalogGeneration,s=(t==="notification"?new Promise((r)=>{setTimeout(r,25).unref()}):Promise.resolve()).then(()=>this.runContentCatalogRefresh()).finally(()=>{if(e!==this.catalogGeneration||this.contentRefreshPromise!==s)return;let r=this.requestedContentCatalogs.size>0;if(this.contentRefreshPromise=void 0,this.contentRefreshReason="manual",r&&this.sdkClient)this.refreshContentCatalogs("notification")});return this.contentRefreshPromise=s,s}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 e=[];for(let s of i)try{if(s==="resources")await this.fetchAndPublishResourceCatalog(n);else await this.fetchAndPublishPromptCatalog(n)}catch(r){let d=r instanceof Error?r:Error(String(r));e.push(d),this.emit("contentCatalogRefreshFailed",{serverName:this.serverName,catalog:s,reason:n,error:d})}if(e.length>0&&n!=="notification")throw AggregateError(e,`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,(o)=>i.listResources(o?{cursor:o}:void 0),(o)=>o.resources),e=await this.fetchContentPages("resource template",H,(o)=>i.listResourceTemplates(o?{cursor:o}:void 0),(o)=>o.resourceTemplates),s=Ci(n),r=$i(e);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing resource catalogs");let d=I(this.resources,s,(o)=>o.uri),c=I(this.resourceTemplates,r,(o)=>o.uriTemplate);this.resources=s,this.resourceTemplates=r,await this.reconcileResourceSubscriptions(i),this.publishContentCatalogDelta("resources",t,d),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",K,(r)=>i.listPrompts(r?{cursor:r}:void 0),(r)=>r.prompts),e=ki(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing prompts");let s=I(this.prompts,e,(r)=>r.name);this.prompts=e,this.publishContentCatalogDelta("prompts",t,s)}async fetchContentPages(t,i,n,e){let s=[],r=new Set,d;for(let c=0;c<_t;c++){let o=await n(d);if(s.push(...e(o)),s.length>i)throw Error(`MCP ${t} catalog exceeds ${i} entries`);if(d=o.nextCursor,!d)return s;if(r.has(d))throw Error(`MCP ${t} catalog returned a repeated cursor`);r.add(d)}throw Error(`MCP ${t} catalog exceeds ${_t} pages`)}publishContentCatalogDelta(t,i,n){if(!mi(n))return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,kind:t,reason:i,...n};this.emit("contentCatalogUpdated",this.contentCatalog,e)}registerResourceNotificationHandler(t){t.setNotificationHandler(ye,(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(we,(i)=>{if(this.sdkClient!==t||!this.loggingPolicy.enabled||!pn(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>=rn){if(!this.logRateWarningEmitted)this.logRateWarningEmitted=!0,this.emit("log",cn(1,{now:n}));return}this.logEventsInWindow++;let e=Lt({level:i.params.level,logger:i.params.logger,data:i.params.data},{exposeDetails:this.runtimeOptions.exposeLogDetails,now:n});this.emit("log",e)})}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(!dn(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>=oi)throw Error(`MCP server "${this.serverName}" has too many completion requests`);let e=di(t,this.contentCatalog);this.completionCallsInFlight++;try{let s=await n.complete(e,{signal:i,timeout:bt,maxTotalTimeout:bt});if(this.sdkClient!==n)throw Error("MCP client changed while completing an argument");return pi(s)}catch(s){if(i?.aborted)throw new DOMException(String(i.reason||"MCP completion cancelled"),"AbortError");throw s}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 gi(await i.readResource({uri:t}))}async getPrompt(t,i={}){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");let e=this.prompts.find((r)=>r.name===t);if(!e)throw Error(`MCP prompt "${t}" is not present in server "${this.serverName}" catalog`);let s=new Set(e.arguments.map((r)=>r.name));for(let[r,d]of Object.entries(i)){if(["__proto__","constructor","prototype"].includes(r))throw Error(`Unsafe argument "${r}" for MCP prompt "${t}"`);if(!s.has(r))throw Error(`Unknown argument "${r}" for MCP prompt "${t}"`);if(Buffer.byteLength(d)>16384)throw Error(`Argument "${r}" for MCP prompt "${t}" is too large`)}for(let r of e.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((e)=>e.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>=Pt)throw Error(`MCP resource subscriptions exceed ${Pt}`);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(e){this.emit("resourceSubscriptionRestoreFailed",{serverName:this.serverName,uri:n,error:k(e)})}}}setStatus(t){let i=this.status;if(i===t)return;this.status=t,this.emit("statusChanged",t,i)}}class m extends be{runtimeOptions;static instance=null;servers=new Map;catalogRevision=0;contentCatalogRevision=0;connectionRevision=0;logRevision=0;instructionsRevision=0;logEntries=[];projectedTools=new Map;constructor(t={}){super();this.runtimeOptions=t}static getInstance(){if(!m.instance)m.instance=new m;return m.instance}static createIsolated(t={}){return new m(t)}async registerServer(t,i,n={}){if(this.servers.has(t))throw Error(`MCP服务器 "${t}" 已经注册`);let e=new Xt(i,t,i.healthCheck,this.runtimeOptions),s={config:i,client:e,status:"disconnected",tools:[],contentCatalog:{resources:[],resourceTemplates:[],prompts:[]},logging:e.logging};if(this.setupClientEventHandlers(e,s,t),this.servers.set(t,s),this.emit("serverRegistered",t,s),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}}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[e,s]of this.servers){if(s.status!=="connected")continue;t.push(...s.contentCatalog.resources.map((r)=>({server:e,...structuredClone(r)}))),i.push(...s.contentCatalog.resourceTemplates.map((r)=>({server:e,...structuredClone(r)}))),n.push(...s.contentCatalog.prompts.map((r)=>({server:e,...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,e=Number.isSafeInteger(i.limit)&&(i.limit??0)>=1&&(i.limit??0)<=B?i.limit??B:B,s=this.logEntries.filter((r)=>r.revision>n&&(!t||r.serverName===t)).slice(-e).map((r)=>structuredClone(r));return{revision:this.logRevision,entries:s}}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,e,s,r,d){let c=this.requireConnectedServer(t);if(!c.tools.some((o)=>o.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:e,interactionContext:s,signal:r,ttlMs:d})}listTasks(t,i){return T.getInstance().list(t,i)}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}getServerStatus(t){return this.servers.get(t)||null}getAllServers(){return new Map(this.servers)}async beginOAuthLogin(t,i={}){let n=this.servers.get(t);if(!n)throw Error(`MCP服务器 "${t}" 未注册`);let e=await n.client.beginOAuthLogin(i);this.emit("serverOAuthStatusChanged",t,"authorizing");let s=e.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 s.catch(()=>{return}),{...e,completion:s}}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")}setupClientEventHandlers(t,i,n){t.on("connected",(e)=>{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,e)}),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",(e)=>{i.status="error",i.lastError=e,this.invalidateServerProjection(n,i),this.emit("serverError",n,e)}),t.on("connectionLifecycleChanged",(e)=>{if(i.recovery=structuredClone(e),e.phase==="reconnecting")i.status="reconnecting",i.connectedAt=void 0,i.lastError=e.error?Error(e.error):i.lastError,this.invalidateServerProjection(n,i);else if(e.phase==="recovered")i.status="connected",i.lastError=void 0;else i.status="error",i.connectedAt=void 0,i.lastError=e.error?Error(e.error):i.lastError;this.publishConnectionLifecycle(n,e)}),t.on("toolsUpdated",(e,s)=>{let r=i.tools.length;if(i.tools=e,i.status==="connected"&&s)this.publishCatalog(n,s.reason);this.emit("toolsUpdated",n,e,r)}),t.on("toolsRefreshFailed",(e)=>{this.emit("catalogRefreshFailed",{serverName:n,...e})}),t.on("contentCatalogUpdated",(e,s)=>{if(i.contentCatalog=e,i.status!=="connected")return;this.publishContentCatalogChange(n,s.kind,s.reason,{added:s.added,removed:s.removed,updated:s.updated})}),t.on("contentCatalogRefreshFailed",(e)=>{this.emit("contentCatalogRefreshFailed",{serverName:n,...e})}),t.on("resourceUpdated",(e)=>{if(i.status!=="connected")return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,serverName:n,uri:e.uri};this.emit("resourceUpdated",s)}),t.on("statusChanged",(e,s)=>{if(i.status=e,e==="reconnecting"&&s==="connected")i.connectedAt=void 0,this.invalidateServerProjection(n,i);this.emit("serverStatusChanged",n,e,s)}),t.on("loggingLevelChanged",()=>{i.logging=t.logging,this.emit("serverLoggingLevelChanged",n,i.logging.level)}),t.on("log",(e)=>{this.publishLog(n,e)})}publishLog(t,i){this.logRevision++;let n={revision:this.logRevision,serverName:t,...structuredClone(i)};this.logEntries.push(n);let e=0;for(let s=this.logEntries.length-1;s>=0;s--){if(this.logEntries[s]?.serverName!==t)continue;if(e++,e>Tn)this.logEntries.splice(s,1)}while(this.logEntries.length>B)this.logEntries.shift();this.emit("log",structuredClone(n))}invalidateServerProjection(t,i){let n=i.contentCatalog,e=i.instructions!==void 0;if(i.tools=[],i.contentCatalog={resources:[],resourceTemplates:[],prompts:[]},i.instructions=void 0,this.publishCatalog(t,"disconnection"),this.publishRemovedContentCatalog(t,n),e)this.publishInstructions(t,"removed","disconnection")}fitInstructionBudget(t,i){if(!i)return;let n=0;for(let[e,s]of this.servers){if(e===t)continue;n+=s.instructions?.projectedBytes??0}return En(i,Math.max(0,fn-n))}publishInstructions(t,i,n,e){this.instructionsRevision++;let s={revision:this.instructionsRevision,serverName:t,action:i,reason:n,...e?{instruction:structuredClone(e)}:{}};this.emit("instructionsChanged",s)}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,o]of this.servers){if(o.status!=="connected")continue;for(let p of o.tools){let u=Ki(c,p.name);if(n.has(u))throw Error(`Duplicate projected MCP tool "${u}"`);n.set(u,Qt(o.client,c,p,u,this.runtimeOptions.artifactWriter))}}let e=new Map([...this.projectedTools].map(([c,o])=>[c,JSON.stringify(o.getFunctionDeclaration())])),s=new Map([...n].map(([c,o])=>[c,JSON.stringify(o.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)&&e.get(c)!==s.get(c)).sort()};if(this.projectedTools=n,!nt(r))return;this.catalogRevision++;let d={revision:this.catalogRevision,serverName:t,reason:i,tools:[...n.values()],...r};this.emit("catalogChanged",d)}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,e){if(e.added.length===0&&e.removed.length===0&&e.updated.length===0)return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,serverName:t,kind:i,reason:n,...e};this.emit("contentCatalogChanged",s)}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 disconnectAll(){let t=[];for(let[i,n]of this.servers)t.push(T.getInstance().cancelClient(n.client).then(()=>n.client.disconnect()).catch((e)=>{console.warn(`断开 MCP 服务器 "${i}" 时出错:`,e)}));await Promise.allSettled(t),this.servers.clear(),this.projectedTools.clear(),this.logEntries=[]}}
|
|
25
|
+
export{Jt as Na,T as Oa,jn as Pa,ve as Qa,ts as Ra,Yi as Sa,Ki as Ta,te as Ua,m as Va};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ag as c,Bg as d,yg as a,zg as b}from"./chunk-g0hhqxpg.js";import"./chunk-yrr9mdjn.js";import"./chunk-m30qwpe9.js";import"./chunk-n8qg68y2.js";import"./chunk-hrtf7dba.js";import"./chunk-9ydrwcpy.js";import"./chunk-0wcnkxe8.js";import"./chunk-4cdk4mds.js";import"./chunk-a1tt14a2.js";import"./chunk-zjezws85.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{w as JH,x as QH,z as r}from"./chunk-sa9fxss4.js";import{A as fz,B as uz,C as gz,D as S}from"./chunk-v1k6nvth.js";import{E as HH,F as bz,G as Rz,H as Sz,I as Mz,J as Iz}from"./chunk-30p7aff1.js";import{$ as Ez,Ea as hz,Fa as yz,Ga as kz,Ha as Cz,Q as R,_ as Oz,ha as qz,ka as Tz,la as Pz,oa as xz}from"./chunk-25s0c8km.js";import"./chunk-f6hc7t65.js";import{Va as zH}from"./chunk-pm5ssr7m.js";import{$a as i,Xa as Az,cb as a}from"./chunk-xseh3f4m.js";import{Rb as wz,bc as Nz,mc as l}from"./chunk-7vzz3rsx.js";import{xc as m}from"./chunk-9qxch6sy.js";import{$d as Fz,Hd as _z,Rd as I,Sd as d,Td as Vz,Yd as Dz,be as M,ee as Kz,je as jz,me as K}from"./chunk-hmw99nm1.js";import"./chunk-a731hdwa.js";import{Ke as Uz,Re as n,Se as Gz}from"./chunk-dxq7462e.js";import"./chunk-tqt5c2f5.js";import{Df as YH}from"./chunk-447ps2te.js";import"./chunk-0b83mt1c.js";import{Yf as oz,Zf as sz}from"./chunk-7eset766.js";import{eg as zz}from"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import{jg as Bz}from"./chunk-xcy45yxx.js";import{rg as p}from"./chunk-5bc4hwt9.js";import"./chunk-h8w3ahnk.js";import{wg as tz}from"./chunk-zfxcef0z.js";import"./chunk-g0hhqxpg.js";import"./chunk-8n3jythp.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import{rh as ez}from"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-xzva8y4e.js";import"./chunk-3y2x6fb6.js";import{wi as rz,zi as nz}from"./chunk-yrr9mdjn.js";import{Yi as e}from"./chunk-m30qwpe9.js";import"./chunk-n8qg68y2.js";import{vj as g,wj as Wz,yj as c,zj as v}from"./chunk-hrtf7dba.js";import{Dj as h}from"./chunk-9ydrwcpy.js";import"./chunk-0wcnkxe8.js";import{Qj as iz,Tj as az}from"./chunk-4cdk4mds.js";import"./chunk-a1tt14a2.js";import"./chunk-zjezws85.js";import{ek as Lz,fk as dz,jk as Hz,nk as Jz,ok as lz,pk as Qz}from"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";import{Readable as wH,Writable as NH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as VH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as cz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=h("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Xz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function XH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Xz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Xz("headers"in z?z.headers:void 0)};return null}function LH(z){let H={};for(let J of z){let Y=XH(J);if(Y)H[J.name]=Y}return H}function vz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function WH(z){let H=Gz(z.metadata);return H?[{type:"text",text:n(H)}]:vz(z.content)}function BH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}function _H(z){if(!Bz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function UH(z){if(!(z instanceof cz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Vz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function GH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,J,Y,X={}){this.id=z;this.roots=H;this.connection=J;this.clientCapabilities=Y;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Iz({maxPendingItems:bz,maxPendingBytes:Rz,writeTimeoutMs:Sz,signal:J.signal,sizeOf:(L)=>Buffer.byteLength(JSON.stringify(L)),write:async(L)=>{await J.sessionUpdate(L)},onFailure:(L)=>this.handleUpdateEgressFailure(L)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(J){if(!(J instanceof jz)&&J.code!=="ENOENT")throw J;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return xz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async($)=>{await this.sendUpdateAndWait($)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:($)=>this.requestPermission($)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?LH(this.options.mcpServers):void 0,Y=R.getTerminalService(this.id),X=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await qz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...X?{workspace:X}:{},permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,_)=>{let U=await Y.execute($,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=wz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.roots.hostStateRoot)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="follow_up.queue.changed"){let _=i.safeParse($.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if($.type==="provider.recovery"){let _=p.safeParse($.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if($.type==="turn.activity"){let _=a.safeParse($.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=$.properties,T=$.properties.metadata;if($.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Ez(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Oz(_,Lz()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!Uz(H))continue;let J=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of WH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],model:{getChatConfig:()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getChatService().getConfig()}},rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,$,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else $=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,$)_($);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),$=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:$.status,findings:$.findings.length,content:_z(_.start,$)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let $=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await kz(z,J),X=Y.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let L=Y.content||Y.message;if(L)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:L}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(H.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,J,Y=new Promise((X)=>{J=X});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch(X){if(H.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Cz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter((X)=>!H.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let L;if(X.usage){let Q=X.usage.replace(/^\/\w+\s*/,"").trim();if(Q)L=Q}if(X.aliases?.length){let Q=`Aliases: ${X.aliases.join(", ")}`;L=L?`${L} | ${Q}`:Q}return{name:X.name,description:X.description,input:L?{hint:L}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,X=J.displayText,L=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(L!==void 0)Q=Kz(L).schema;if(X.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let W=Az(X);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((D)=>D.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),this.sendFollowUpQueueSnapshot(D.queue??await this.runtime.getFollowUpQueueSnapshot()),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,$=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)$();else H.abortSignal?.addEventListener("abort",$,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((D)=>{T=D});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),hz(X)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,B.signal)}let D={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Z)=>{this.mode=this.mapPermissionModeToMode(Z),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Z)=>{return this.requestPermission(Z)}}},N=await Nz(this.agent.chatStream(Y,D,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(Z)=>{switch(Z.kind){case"content_delta":if(Q)break;if(Z.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z.delta}});break;case"thinking_delta":if(Z.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Z.delta}});break;case"tool_start":{V=!0;let F=Z.toolCall,A=F.function.name;if(A===M)break;let q=this.mapToolKind(Z.toolKind),j=`Executing ${A}`;if(A==="Task"&&"function"in F)try{let b=JSON.parse(F.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")j=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.id,status:"in_progress",title:j,content:[],kind:q});break}case"tool_progress":{V=!0;let F=Z.toolCall;if(F.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.update.message}}]});break}case"tool_result":{V=!0;let F=Z.toolCall;if(F.function.name===M)break;let A=Z.result,q=[],j=A.metadata;if(j?.kind==="patch"&&Array.isArray(j.changes))for(let w of j.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(j?.kind==="edit"&&typeof j.file_path==="string"&&typeof j.oldContent==="string"&&(typeof j.newContent==="string"||j.newContent===void 0))q.push({type:"diff",path:j.file_path,oldText:j.oldContent,newText:j.newContent??null});else{let w=F.function.name,ZH=Pz(Fz(Tz(w,A),Dz));q.push({type:"content",content:{type:"text",text:ZH}})}if(F.function.name==="Task"&&(j?.verificationVerdict==="pass"||j?.verificationVerdict==="fail"||j?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${j.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Z.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Z.revision} (${Z.serverName}): +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}
|
|
3
|
+
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Z.contentKind} r${Z.revision} (${Z.serverName}): +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}
|
|
4
|
+
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Z.revision} (${Z.serverName}): ${Z.uri}
|
|
5
|
+
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Z.revision} (${Z.serverName}): ${Z.phase} ${Z.attempt}/${Z.maxAttempts}
|
|
6
|
+
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${Z.revision} (${Z.serverName}) ${Z.level}${Z.logger?` logger=${Z.logger}`:""}: ${Z.message}
|
|
7
|
+
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Z.revision} (${Z.serverName}): ${Z.action}${Z.detailsOmitted?" details-omitted":""}
|
|
8
|
+
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Z.revision} ${Z.taskId} (${Z.serverName}/${Z.toolName}): ${Z.status}${Z.hasResult?" result-available":""}
|
|
9
|
+
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Z.files.length}${Z.blockedWrite?" (write retry required)":""}
|
|
10
|
+
`}});break;case"provider_admission":_=Z.phase!=="admitted",this.sendSessionMetadata("blade/providerAdmission",Z.phase==="admitted"?null:r(Z,{omitUndefined:!0})?.properties);break;case"provider_circuit":this.sendProjectedLoopMetadata("blade/providerCircuit",Z);break;case"provider_retry":this.sendProjectedLoopMetadata("blade/providerRetry",Z);break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z.assessment}});break;case"provider_stall":this.sendProjectedLoopMetadata("blade/providerStall",Z);break;case"provider_recovery":break;case"turn_activity":break;case"model_fallback":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/modelFallback":{from:Z.from,to:Z.to,candidate:Z.candidate,candidateCount:Z.candidateCount,trigger:Z.trigger}}});break;case"action_stationarity":this.sendProjectedLoopMetadata("blade/actionStationarity",Z);break;case"task_update":this.sendPlanUpdate(Z.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:Z.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:Z.goal.goalId,status:Z.goal.status,taskListId:Z.frontier.taskListId,total:Z.frontier.total,completed:Z.frontier.completed,inProgress:Z.frontier.inProgress,pending:Z.frontier.pending,blocked:Z.frontier.blocked,nextTask:Z.frontier.nextTask,digestSha256:Z.frontier.digestSha256,...Z.goal.frontierStall?{stall:{category:Z.goal.frontierStall.category,consecutiveCount:Z.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(Z.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(Z.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(Z.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(Z.queue);let F=0;for(let A of Z.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of vz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),F++}if(F>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${F} queued instruction${F===1?"":"s"} recovered after restart]
|
|
11
|
+
`}});break}case"goal_updated":if(Z.goal)this.sendUpdate(this.goalSessionUpdate(Z.goal));if(Z.goal&&Z.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Z.goal.status}: ${Z.goal.objective}]
|
|
12
|
+
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Z.goal.goalId,continuation:Z.continuation,...Z.prematureStopPattern?{prematureStopPattern:Z.prematureStopPattern}:{},...Z.prematureStopCount!==void 0?{prematureStopCount:Z.prematureStopCount}:{},...Z.goal.executionHostFailure?{executionHostFailure:{category:Z.goal.executionHostFailure.category,consecutiveCount:Z.goal.executionHostFailure.consecutiveCount}}:{},...Z.goal.turnLineage?{turnLineage:Z.goal.turnLineage}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Z.phase,...Z.reason?{reason:Z.reason}:{},...Z.strategy?{strategy:Z.strategy}:{},...Z.outcome?{outcome:Z.outcome}:{},...Z.preTokens!==void 0?{preTokens:Z.preTokens}:{},...Z.preTokenSource?{preTokenSource:Z.preTokenSource}:{},...Z.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Z.estimatedPendingTokens}:{},...Z.postTokens!==void 0?{postTokens:Z.postTokens}:{},...Z.sampleAttempts!==void 0?{sampleAttempts:Z.sampleAttempts}:{},...Z.inputReductions!==void 0?{inputReductions:Z.inputReductions}:{},...Z.messagesOmitted!==void 0?{messagesOmitted:Z.messagesOmitted}:{},...Z.filesOmitted!==void 0?{filesOmitted:Z.filesOmitted}:{},...Z.imagesOmitted!==void 0?{imagesOmitted:Z.imagesOmitted}:{},...Z.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Z.fallbackTargetTokens}:{},...Z.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Z.fallbackMessagesOmitted}:{},...Z.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Z.fallbackMessagesTruncated}:{},...Z.failureReason?{failureReason:Z.failureReason}:{},...Z.memory?{memory:Z.memory}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...D.messages];let Zz=await this.loadPersistedMessages();if(this.messages=Zz.length>0?Zz:[...D.messages],!N.success){let Z=N.error?.type??"unknown",F=N.error?.details??N.error?.message??"Agent execution failed",A=_H(F)??d(F);throw cz.internalError({failureType:Z,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Z})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let $z={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys($z).length>0?{_meta:$z}:{}}}catch(D){if(B.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(H.abortSignal?.removeEventListener("abort",$),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let J=new AbortController,Y,X=new Promise((W)=>{Y=W});this.pendingUserShell=J,this.pendingUserShellCompletion=X;let L,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:J.signal,onEvent:async($)=>{if(L=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){Q+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let _=n($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?BH($.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(L)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,J=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(J,z),this.pendingResumeTimer.unref?.();else queueMicrotask(J)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let J=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,J!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(J)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let J=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,J!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(J)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:fz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let J="preflight",Y=!1,X,L=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",$=this.runtime.getTurnRecoveryAssessment();if($.state!=="none"&&($.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if($.state==="requires_attention"){this.clearPendingResumeRequest();return}J=Q?"pending_input":"goal",Y=!0;let _=uz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:J,taskFailure:I("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}let U=new AbortController;L=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),L.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:J==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:J,taskFailure:I("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:J})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?UH(Q):{taskFailure:d(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=J==="preflight"||J==="pending_input"&&this.runtime.getPendingSteeringCount()>0,$=gz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if($.phase==="retry_scheduled")this.pendingResumeRequested=!0,X=$.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:J,taskFailure:W?.taskFailure,delayMs:$.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${$.delayMs}ms`);else{let _=$.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:J,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${$.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest()}}finally{if(L!==null)clearTimeout(L);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=X??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(J);await this.persistPermissionMode(Y),this.mode=J,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(J){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(J){throw await this.runtime.refresh({reasoningEffort:H.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(J){throw await this.runtime.refresh({serviceTier:H.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(J){throw await this.runtime.refresh({responseVerbosity:H.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Mz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,J=this.runtime,Y=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,L=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async($)=>{try{await $()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if(X)await B(()=>X);if(L)await B(()=>L);if(Q)await B(()=>Q);if(z&&Y&&J)await B(()=>J.discardPendingInput());if(H)await B(()=>H.destroy());if(J)await B(()=>J.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],J=[],Y=0,X=0,L=0,Q=($)=>{if(J.length>0)J.push({type:"text",text:`
|
|
13
|
+
`}),L+=1;if(J.push($),$.type==="text")L+=$.text.length};for(let $ of z)if($.type==="text")H.push($.text),Q({type:"text",text:$.text});else if($.type==="image"){let _=`data:${$.mimeType};base64,${$.data}`;Y+=1,X+=_.length,H.push(`[Image: ${$.mimeType}]`),Q({type:"image_url",image_url:{url:_}})}else if($.type==="resource"){let _=$.resource;if("text"in _){let U=`<file path="${_.uri}">
|
|
14
|
+
${_.text}
|
|
15
|
+
</file>`;H.push(U),Q({type:"text",text:U})}}else if($.type==="resource_link"){let _=`[Resource: ${$.uri}]`;H.push(_),Q({type:"text",text:_})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if(X>Wz)throw Error("ACP prompt images exceed the 5 MiB limit");if(L>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(H.join(`
|
|
16
|
+
`),"utf8")>v)throw Error(`ACP prompt text exceeds ${v} bytes`);let B=H.join(`
|
|
17
|
+
`);return{content:Y>0?J:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let H=this.updateEgress.offer({sessionId:this.id,update:z});if(!H.accepted)return!1;try{return await H.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount,...z.executionHostFailure?{executionHostFailure:{category:z.executionHostFailure.category,consecutiveCount:z.executionHostFailure.consecutiveCount}}:{},...z.turnLineage?{turnLineage:z.turnLineage}:{}}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendSessionMetadata("blade/followUpQueue",GH(H.data))}sendProviderRecoveryProjection(z){let H=p.safeParse(z);if(!H.success)return;this.sendSessionMetadata("blade/providerRecovery",H.data)}sendTurnActivityProjection(z){let H=a.safeParse(z);if(!H.success)return;if(H.data.generation===this.lastTurnActivityGeneration&&H.data.revision<=this.lastTurnActivityRevision)return;this.lastTurnActivityGeneration=H.data.generation,this.lastTurnActivityRevision=H.data.revision,this.sendSessionMetadata("blade/turnActivity",H.data)}sendProjectedLoopMetadata(z,H){let J=r(H,{omitUndefined:!0});if(J)this.sendSessionMetadata(z,J.properties)}sendSessionMetadata(z,H){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{[z]:H}})}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let H=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${H.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:H})}async requestPermission(z){let H=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,H);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,H);let J=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(J))return G.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.details)X.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
+
- ${z.risks.join(`
|
|
19
|
+
- `)}`}});let L=this.mapToolKind(J),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:z.title||"Permission Required",content:X,kind:L}},W=await this.waitForClientInteraction(this.connection.requestPermission(Q),H);if(!W)return{approved:!1,reason:m};let B=W.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let $=B.optionId;if($==="allow_always")return{approved:!0,scope:"project"};if($==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let _=$==="allow_once";return{approved:_,scope:"once",reason:_?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,H){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[X,L]of J.entries()){let Q=L.options.map((_,U)=>`answer:${X}:${U}`),W=`answer:${X}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...L.options.map((_,U)=>({optionId:Q[U],name:_.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:L.header,kind:"think",content:[{type:"content",content:{type:"text",text:[L.question,...L.options.map((_)=>`${_.label}: ${_.description}`)].join(`
|
|
20
|
+
`)}}]}}),H);if(!B)return{approved:!1,reason:m};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let $=Q.indexOf(B.outcome.optionId);if($<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[L.header]=L.options[$].label}return{approved:!0,answers:Y}}catch(X){return G.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,H){let J=z.mcpElicitation;if(!J)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(J.mode==="url"){let X=await this.requestElicitationChoice("MCP external authorization",[J.message,`Server: ${J.serverName}`,`Domain: ${J.domain??"unknown"}`,`URL: ${J.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
+
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],H);if(X==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:X==="decline"?"User declined URL":"User cancelled",elicitation:{action:X==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let X of J.fields??[]){let L=await this.collectAcpElicitationField(X,H);if(L.cancelled)return{approved:!1,reason:L.reason,elicitation:{action:"cancel"}};if(L.value!==void 0)Y[X.name]=L.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,H){if(z.type==="select"||z.type==="boolean"){let J=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((L,Q)=>({id:`option:${Q}`,label:L.label,value:L.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
+
`),[...J.map((L)=>({id:L.id,label:L.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(Y==="skip")return{cancelled:!1};let X=J.find((L)=>L.id===Y);if(!X)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:X.value}}if(z.defaultValue!==void 0){let J=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
+
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(J==="default")return{cancelled:!1,value:z.defaultValue};if(J==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,H,J,Y){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...J.map((L)=>({optionId:L.id,name:L.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:H}}]}}),Y);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((J,Y)=>{let X=!1,L=(W)=>{if(X)return;X=!0,H.removeEventListener("abort",Q),W()},Q=()=>L(()=>J(void 0));if(H.addEventListener("abort",Q,{once:!0}),H.aborted)Q();z.then((W)=>L(()=>J(W)),(W)=>L(()=>Y(W)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var O=h("Agent"),DH="remote task isolation is not supported";function y(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function FH(z){return C.invalidParams({code:z.code,reason:z.reason})}function KH(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:DH})}function pz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function mz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return Hz(z)}catch(H){if(H instanceof dz)throw FH(H);throw H}}function s(z,H){let J=Jz(z);return Object.freeze({kind:"acp-remote",hostStateRoot:Qz(J.collisionIdentity),executionRoot:J.wirePath,hostResourceRoot:H,profile:z,descriptor:J})}function t(z,H){let J=lz(z.remoteWorkspace),Y=Qz(J.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let X=Hz(J.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:J.wirePath,hostResourceRoot:H,profile:X,descriptor:J})}function jH(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Yz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=o.resolve(e())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=oz();this.runtimeResidencyValue=new QH({maxResident:z?.maxResidentSessionRuntimes??rz,idleMs:z?.sessionRuntimeIdleMs??nz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(H){if(H instanceof JH)throw C.internalError({resource:H.resource,limit:H.limit,retryable:H.retryable},H.message);throw H}}async initialize(z){return O.info("[BladeAgent] Initializing ACP connection"),O.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await sz(),{protocolVersion:VH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let H=zz("acp"),J=z.cwd||e(),Y=y(this.clientCapabilities),X=Y?k(J):void 0,L=z._meta?.["blade/taskIsolation"],Q=L==="local"||L==="worktree"?L:void 0;if(Y&&Q)throw KH();let W=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(H),$;try{let _,U;if(X){let T=s(X,this.hostResourceRoot);_=await K.createRemoteSessionMetadata(H,T.hostStateRoot,T.descriptor,{}),U=t(_,this.hostResourceRoot)}else U=P(J);let V=!Y&&Q?await HH.createSessionTask({sessionId:H,prompt:typeof W==="string"&&W.trim()?W:"ACP task session",sourceProjectPath:J,isolation:Q}):void 0;if(V)U=P(V.metadata.projectPath);return O.info(`[BladeAgent] Creating new session: ${H}`),O.debug(`[BladeAgent] Session kind: ${U.kind}`),$=new x(H,U,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...V?.taskWorktree?{taskWorktree:V.taskWorktree}:{},...V?.metadata.taskIsolation?{taskIsolation:V.metadata.taskIsolation}:{}}),await $.initialize(),this.assertNotDestroyed(),this.commitSession(H,$,B),O.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),$.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H,V?.metadata,$.getModelConfiguration())}catch(_){throw B.cancel(),await $?.destroy().catch(()=>{return}),_}}async listSessions(z){let H=y(this.clientCapabilities);if(!H&&z.cwd!=null&&!o.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=H?await K.listRemoteSessionPage({...z.cwd!=null?{descriptor:Jz(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await K.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:H?jH(Y):Y.projectPath,title:Y.title??null,updatedAt:Y.lastMessageTime,_meta:{"blade/taskStatus":Y.taskStatus,...Y.taskStatusReason?{"blade/taskStatusReason":Y.taskStatusReason}:{},...Y.taskFailure?{"blade/taskFailure":Y.taskFailure}:{},...Y.taskStartedAt?{"blade/taskStartedAt":Y.taskStartedAt}:{},...Y.taskCompletedAt?{"blade/taskCompletedAt":Y.taskCompletedAt}:{},...Y.taskModelId?{"blade/taskModelId":Y.taskModelId}:{},...Y.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Y.taskRetriedFrom?{"blade/taskRetriedFrom":Y.taskRetriedFrom}:{},...Y.taskDelivery?{"blade/taskDelivery":Y.taskDelivery}:{},...Y.taskIsolation?{"blade/taskIsolation":Y.taskIsolation}:{},...Y.taskSourceProjectPath?{"blade/taskSourceProjectPath":Y.taskSourceProjectPath}:{},...Y.taskWorktreeBranch?{"blade/taskWorktreeBranch":Y.taskWorktreeBranch}:{},...Y.taskBaseCommit?{"blade/taskBaseCommit":Y.taskBaseCommit}:{},...Y.taskDiffStat?{"blade/taskDiffStat":Y.taskDiffStat}:{},...Y.taskQueuePosition?{"blade/taskQueuePosition":Y.taskQueuePosition}:{},...Y.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Y.taskQueueDepth}:{},...Y.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Y.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let H=y(this.clientCapabilities),J=H?s(k(z.cwd),this.hostResourceRoot):void 0;if(!H&&!o.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=zz("fork"),X=await this.reserveSessionRuntime(Y),L;try{let Q;try{Q=await K.forkSession(z.sessionId,{sourceProjectPath:J?.hostStateRoot??z.cwd,targetProjectPath:J?.hostStateRoot??z.cwd,newSessionId:Y,...J?{remote:{expectedDescriptor:J.descriptor}}:{}})}catch(B){if(mz(B))throw pz();throw B}this.assertNotDestroyed();let W=H?t(Q.metadata,this.hostResourceRoot):P(Q.projectPath??z.cwd);return L=new x(Q.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await L.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,L,X),L.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,H?void 0:Q.metadata,L.getModelConfiguration())}catch(Q){throw X.cancel(),await L?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),O.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!y(this.clientCapabilities)){await K.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let W=await this.reserveSessionRuntime(z.sessionId),B;try{let[$,_]=await Promise.all([K.loadSession(z.sessionId,z.cwd),K.findSessionMetadata(z.sessionId,z.cwd)]);if(!_)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,P(z.cwd),this.connection,this.clientCapabilities,{initialMessages:$,permissionMode:_.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,W),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch($){throw W.cancel(),await B?.destroy().catch(()=>{return}),$}}let J=s(k(z.cwd),this.hostResourceRoot),Y;try{Y=await K.assertRemoteSessionWritable(z.sessionId,J.hostStateRoot,J.descriptor)}catch(W){if(mz(W))throw pz();throw W}let X=t(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let L=await this.reserveSessionRuntime(z.sessionId),Q;try{let W=await K.loadRemoteSession(z.sessionId,X.hostStateRoot,X.descriptor);return Q=new x(z.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,L),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(W){throw L.cancel(),await Q?.destroy().catch(()=>{return}),W}}commitSession(z,H,J){let Y=J.commit({key:z,surface:"acp",value:H,canEvict:()=>H.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===H)this.sessions.delete(z);await H.destroy()}});this.sessions.set(z,H),Y.release()}async closeResidentSession(z,H={}){let J=this.sessions.get(z);if(!J)return;let Y=this.runtimeResidency.owns(z,J),X;try{await J.destroy(H)}catch(Q){X=Q}let L=await this.runtimeResidency.forget(z,J);if(this.sessions.get(z)===J)this.sessions.delete(z);if(Y&&!L&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,H,J){return{sessionId:z,...this.buildSessionSetup(J,H?.permissionMode==="autoEdit"?"auto-edit":H?.permissionMode),...H?{_meta:{"blade/taskIsolation":H.taskIsolation,"blade/taskSourceProjectPath":H.taskSourceProjectPath,"blade/taskProjectPath":H.projectPath,...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,H="default"){let J=z?.models??[],Y=(z?.currentModelId&&J.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??J[0]?.id,X=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],L=[];if(J.length>0)L.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:J.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)L.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)L.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)L.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)L.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:X,currentModeId:H},configOptions:L.length>0?L:void 0}}async closeSession(z){this.assertNotDestroyed();let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{return await H.value.prompt(z)}finally{H.release()}}async cancel(z){O.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H){O.info("[BladeAgent] Found session, calling session.cancel()");try{H.value.cancel()}finally{H.release()}}else O.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){O.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H)try{await H.value.setMode(z.modeId)}finally{H.release()}return{}}async setSessionConfigOption(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{let J=H.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")O.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&tz(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&az(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&iz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&ez(z.value))O.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}finally{H.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let H of[...this.sessions.keys()])try{await this.closeResidentSession(H)}catch(J){z??=J}try{await this.runtimeResidency.disposeAll()}catch(H){z??=H}this.sessions.clear();try{await zH.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function OJ(){let z=NH.toWeb(process.stdout),H=wH.toWeb(process.stdin),J=f.ndJsonStream(z,H),Y,X=new f.AgentSideConnection((Q)=>{return Y=new Yz(Q),Y},J),L=YH(async()=>{await Y?.destroy()});try{await X.closed}finally{L(),await Y?.destroy()}}export{OJ as runAcpIntegration,P as createLocalAcpSessionRoots};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Va as H}from"./chunk-pm5ssr7m.js";import"./chunk-9qxch6sy.js";import"./chunk-a731hdwa.js";import{bg as $,dg as T}from"./chunk-7eset766.js";import"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import"./chunk-xzva8y4e.js";import"./chunk-3y2x6fb6.js";import"./chunk-yrr9mdjn.js";import{Yi as k}from"./chunk-m30qwpe9.js";import"./chunk-n8qg68y2.js";import"./chunk-hrtf7dba.js";import"./chunk-9ydrwcpy.js";import"./chunk-0wcnkxe8.js";import"./chunk-4cdk4mds.js";import"./chunk-a1tt14a2.js";import"./chunk-zjezws85.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
|
|
2
2
|
blade mcp
|
|
3
3
|
`),console.log(`管理 MCP 服务器
|
|
4
4
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{M as N,ka as _,la as z}from"./chunk-25s0c8km.js";import{$d as R,Xc as I,Zd as g,cd as x,dd as X,ed as B,fd as V,gd as b,wd as A}from"./chunk-hmw99nm1.js";import{Ci as M,Di as O}from"./chunk-yrr9mdjn.js";import{Mutex as j}from"async-mutex";class C extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(q){super("Session runtime capacity is full");this.limit=q;this.name="SessionRuntimeCapacityError"}}class W extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class Y extends Error{constructor(q){super(`Session runtime residency already owns key: ${q}`);this.name="SessionRuntimeResidencyConflictError"}}class k{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new j;nextGeneration=1;closed=!1;constructor(q){if(!M(q.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!O(q.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=q.maxResident,this.idleMs=q.idleMs,this.now=q.now??Date.now}acquire(q){let $=this.residents.get(q);if(!$||$.poisoned)return;return $.pins++,$.lastUsedAt=this.now(),this.createLease($)}owns(q,$){let Q=this.residents.get(q);return Boolean(Q&&($===void 0||Q.value===$))}async reserve(q,$){if(!q.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new W;if(this.residents.has(q)||this.reservations.has(q))throw new Y(q);while(this.retainedCount()>=this.maxResident){if(!$.allowEviction)throw new C(this.maxResident);let P=this.oldestEvictableWebResident();if(!P)throw new C(this.maxResident);await this.disposeResident(P,!0)}let Q={generation:this.allocateGeneration(),surface:$.surface};return this.reservations.set(q,Q),this.createReservation(q,Q)})}async remove(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$)return!1;if(Q.pins>0)return!1;return await this.disposeResident(Q,!0),!0})}async forget(q,$){return this.operations.runExclusive(async()=>{let Q=this.residents.get(q);if(!Q||$!==void 0&&Q.value!==$||Q.pins>0)return!1;return this.residents.delete(q),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let q=0;while(!0){let $=this.oldestIdleWebResident();if(!$)return q;await this.disposeResident($,!0),q++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let q;for(let $ of[...this.residents.values()])try{await this.disposeResident($,!1)}catch(Q){q??=Q}if(this.residents.clear(),q!==void 0)throw q})}getStats(){let q=0;for(let $ of this.residents.values())if($.pins>0)q++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:q,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let q=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,q}createReservation(q,$){let Q=!1;return{commit:(P)=>{if(Q)throw new Y(q);if(P.key!==q||P.surface!==$.surface||this.reservations.get(q)!==$||this.closed)throw this.reservations.delete(q),Q=!0,this.closed?new W:new Y(q);this.reservations.delete(q);let L={...P,generation:$.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(q,L),Q=!0,this.createLease(L)},cancel:()=>{if(Q)return;if(this.reservations.get(q)===$)this.reservations.delete(q);Q=!0}}}createLease(q){let $=!1;return{value:q.value,release:()=>{if($)return;$=!0;let Q=this.residents.get(q.key);if(Q!==q||Q.generation!==q.generation)return;Q.pins=Math.max(0,Q.pins-1),Q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((q)=>this.canEvict(q))}oldestIdleWebResident(){let q=this.now();return this.sortedWebResidents().find(($)=>q-$.lastUsedAt>=this.idleMs&&this.canEvict($))}sortedWebResidents(){return[...this.residents.values()].filter((q)=>q.surface==="web").sort((q,$)=>q.lastUsedAt-$.lastUsedAt||q.generation-$.generation)}canEvict(q){if(q.pins>0||q.poisoned)return!1;try{return q.canEvict()}catch{return!1}}async disposeResident(q,$){if(this.residents.get(q.key)!==q)return;this.residents.delete(q.key);try{await q.dispose()}catch(Q){if($&&!this.closed&&!this.residents.has(q.key))q.lastUsedAt=this.now(),q.poisoned=!0,this.residents.set(q.key,q);throw Q}}}function f(q){if(!q||typeof q!=="object"||Array.isArray(q))return;let $=q,{code:Q,kind:P,limit:L,reason:D,scope:J}=$;if(Q!=="tool_busy"&&Q!=="tool_batch_full"||D!=="queue_full"&&D!=="wait_timeout"&&D!=="turn_limit"||J!=="global"&&J!=="session"||typeof $.retryable!=="boolean"||!Number.isSafeInteger(L)||L<=0||P!==void 0&&P!=="readonly"&&P!=="write"&&P!=="execute")return;return{code:Q,reason:D,scope:J,retryable:$.retryable,...P===void 0?{}:{kind:P},limit:L}}function T(q,$){if(!$||typeof $!=="object")return $;let Q={...$},P=f(Q.tool_admission);if(P)Q.tool_admission=P;else delete Q.tool_admission;if(N(q)){let J=Q.browser&&typeof Q.browser==="object"&&!Array.isArray(Q.browser)?Q.browser:{},h={},G=(Z,F,K)=>{let H=J[Z];if(typeof H==="string"&&Buffer.byteLength(H)<=F&&(!K||K.test(H)))h[Z]=H};if(G("action",64),G("status",16,/^(?:ok|warning|error)$/),G("pageId",V,/^browser_page_[a-f0-9-]+$/),G("snapshotId",V,/^browser_snapshot_[a-f0-9-]+$/),G("origin",X),G("candidateOrigin",X),G("url",x),G("title",B),G("errorCode",64,/^browser_[a-z_]+$/),typeof J.truncated==="boolean")h.truncated=J.truncated;if(typeof J.actionApplied==="boolean"||J.actionApplied==="unknown")h.actionApplied=J.actionApplied;if(typeof J.sideEffectsUncertain==="boolean")h.sideEffectsUncertain=J.sideEffectsUncertain;if(typeof J.diagnosticCount==="number"&&Number.isSafeInteger(J.diagnosticCount)&&J.diagnosticCount>=0&&J.diagnosticCount<=I)h.diagnosticCount=J.diagnosticCount;if(J.interaction&&typeof J.interaction==="object"&&!Array.isArray(J.interaction)){let Z=J.interaction,F=new Set(["click","hover","fill","type","press","select","check","uncheck","scroll"]);if(typeof Z.action==="string"&&F.has(Z.action)){let K={action:Z.action};if(typeof Z.ref==="string"&&Buffer.byteLength(Z.ref)<=b&&/^[a-z][a-z0-9]*$/.test(Z.ref))K.ref=Z.ref;let H=(U,E,S)=>typeof U==="number"&&Number.isFinite(U)&&U>=E&&U<=S;if(Z.viewport&&typeof Z.viewport==="object"&&!Array.isArray(Z.viewport)){let U=Z.viewport;if(H(U.width,1,16384)&&H(U.height,1,16384))K.viewport={width:U.width,height:U.height}}if(Z.targetBox&&typeof Z.targetBox==="object"&&!Array.isArray(Z.targetBox)){let U=Z.targetBox;if(H(U.x,-16384,32768)&&H(U.y,-16384,32768)&&H(U.width,0,16384)&&H(U.height,0,16384))K.targetBox={x:U.x,y:U.y,width:U.width,height:U.height}}h.interaction=K}}if(J.artifact&&typeof J.artifact==="object"&&!Array.isArray(J.artifact)){let Z=J.artifact;if(typeof Z.id==="string"&&/^[a-f0-9]{64}$/.test(Z.id)&&Z.sha256===Z.id&&Z.kind==="image"&&Z.mimeType==="image/png"&&typeof Z.size==="number"&&Number.isSafeInteger(Z.size)&&Z.size>=0&&Z.size<=A&&Z.persisted===!0)h.artifact={id:Z.id,sha256:Z.sha256,kind:Z.kind,mimeType:Z.mimeType,size:Z.size,persisted:!0,...typeof Z.path==="string"&&Buffer.byteLength(Z.path)<=8192?{path:Z.path}:{}}}return{...typeof Q.summary==="string"?{summary:Q.summary.slice(0,512)}:{},browser:h,...P?{tool_admission:P}:{}}}if(q==="Bash"){let J={},h=["message","signal","status","summary"],G=["aborted","acp_mode","admission_failed","auto_backgrounded","background","capture_truncated","finalization_failed","has_stderr","output_accounting_complete","output_truncated","projection_truncated","sandbox_required","sandboxed","stderr_projection_truncated","stdout_projection_truncated","terminal_output_merged","timeout"],Z=["execution_time","foreground_budget_ms","pid","raw_output_bytes","stderr_length","stderr_omitted_bytes","stderr_retained_bytes","stderr_total_bytes","stdout_length","stdout_omitted_bytes","stdout_retained_bytes","stdout_total_bytes"];for(let K of h){let H=Q[K];if(typeof H==="string")J[K]=H.slice(0,8192)}for(let K of G){let H=Q[K];if(typeof H==="boolean")J[K]=H}for(let K of Z){let H=Q[K];if(typeof H==="number"&&Number.isSafeInteger(H)&&H>=0)J[K]=H}if(Q.exit_code===null||typeof Q.exit_code==="number"&&Number.isSafeInteger(Q.exit_code))J.exit_code=Q.exit_code;if(Q.terminal_transport==="local"||Q.terminal_transport==="acp"||Q.terminal_transport==="local_fallback")J.terminal_transport=Q.terminal_transport;if(Q.background_reason==="explicit"||Q.background_reason==="foreground_budget")J.background_reason=Q.background_reason;for(let K of["bash_id","shell_id"]){let H=Q[K];if(typeof H==="string"&&H.length<=128&&/^bash_[A-Za-z0-9-]+$/.test(H))J[K]=H}if(P)J.tool_admission=P;let F=Q.background_shell_admission;if(F&&typeof F==="object"&&!Array.isArray(F)){let K=F;if(K.code==="background_shell_busy"&&(K.scope==="session"||K.scope==="global")&&K.retryable===!0&&Number.isSafeInteger(K.limit)&&K.limit>0)J.background_shell_admission={code:K.code,scope:K.scope,retryable:K.retryable,limit:K.limit}}return J}let L=200000,D=(J,h)=>typeof J==="number"&&Number.isSafeInteger(J)&&J>=0&&J<=h?J:0;if(typeof Q.oldContent==="string"&&Q.oldContent.length>L)delete Q.oldContent;if(typeof Q.newContent==="string"&&Q.newContent.length>L)delete Q.newContent;if(Q.mcpResult&&typeof Q.mcpResult==="object"&&!Array.isArray(Q.mcpResult)){let J=Q.mcpResult,h=Array.isArray(J.artifacts)?J.artifacts.slice(0,64).flatMap((G)=>{if(!G||typeof G!=="object"||Array.isArray(G))return[];let Z=G,F=new Set(["text","image","audio","resource"]);if(typeof Z.id!=="string"||!/^[a-f0-9]{64}$/.test(Z.id)||typeof Z.sha256!=="string"||Z.sha256!==Z.id||typeof Z.kind!=="string"||!F.has(Z.kind)||D(Z.size,67108864)!==Z.size||typeof Z.persisted!=="boolean")return[];return[{id:Z.id.slice(0,128),sha256:Z.sha256.slice(0,128),kind:Z.kind,size:Z.size,persisted:Z.persisted,...typeof Z.mimeType==="string"?{mimeType:Z.mimeType.slice(0,256)}:{},...typeof Z.sourceUri==="string"?{sourceUri:Z.sourceUri.slice(0,8192)}:{},...typeof Z.path==="string"?{path:Z.path.slice(0,8192)}:{}}]}):[];Q.mcpResult={isError:J.isError===!0,contentCount:D(J.contentCount,64),textBytes:D(J.textBytes,4194304),structuredBytes:D(J.structuredBytes,4194304),artifactCount:D(J.artifactCount,64),truncated:J.truncated===!0,binaryOmitted:J.binaryOmitted===!0,artifacts:h}}else delete Q.mcpResult;return Q}var y=(q,$)=>Object.fromEntries($.map((Q)=>[String(Q),q[Q]])),w=(q,$,Q,P=!1)=>({type:$,messageScoped:P,properties:y(q,Q)});function m(q){switch(q.kind){case"tool_start":if(!("function"in q.toolCall))return;return{type:"tool.start",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,arguments:q.toolCall.function.arguments,toolKind:q.toolKind}};case"tool_progress":if(!("function"in q.toolCall))return;return{type:"tool.progress",messageScoped:!0,toolName:q.toolCall.function.name,properties:{toolName:q.toolCall.function.name,toolCallId:q.toolCall.id,...q.update}};case"tool_result":{if(!("function"in q.toolCall))return;let $=q.toolCall.function.name;return{type:"tool.result",messageScoped:!0,toolName:$,properties:{toolName:$,toolCallId:q.toolCall.id,success:q.result.success,summary:q.result.metadata?.summary,output:z(R(_($,q.result),g)),metadata:T($,q.result.metadata)}}}case"provider_admission":return w(q,"provider.admission",["phase","requestClass","resource","scope","reason","queuePosition","queueDepth","inFlight","limit","waitMs","maxWaitMs","recoveryRemainingMs"]);case"provider_circuit":return w(q,"provider.circuit",["phase","reason","statusCode","retryAfterMs","nextProbeAt","openDurationMs","sampleCount","failureCount","recoveryRemainingMs"]);case"provider_retry":return w(q,"provider.retry",["phase","attempt","maxRetries","reason","statusCode","delayMs","nextRetryAt","mode","recoveryBudgetMs","recoveryElapsedMs","recoveryRemainingMs","exhaustedBy"]);case"provider_stall":return w(q,"provider.stall",["phase","stallCount","durationMs","warningAfterMs","timeoutMs","outputStarted"]);case"action_stationarity":return w(q,"action.stationarity",["phase","toolName","runLength","nudgeThreshold","haltThreshold","progressAware"]);case"mcp_catalog_changed":return w(q,"mcp.catalog.changed",["revision","serverName","added","removed","updated"],!0);case"mcp_content_changed":return w(q,"mcp.content.changed",["revision","serverName","contentKind","added","removed","updated"],!0);case"mcp_resource_updated":return w(q,"mcp.resource.updated",["revision","serverName","uri"],!0);case"mcp_connection_changed":return w(q,"mcp.connection.changed",["revision","serverName","phase","reason","attempt","maxAttempts","nextRetryAt","error"],!0);case"mcp_log":return w(q,"mcp.log",["revision","serverName","level","logger","message","projectedBytes","dataSha256","truncated","detailsOmitted","timestamp","synthetic"],!0);case"mcp_instructions_changed":return w(q,"mcp.instructions.changed",["revision","serverName","action","reason","text","sourceBytes","projectedBytes","sha256","truncated","detailsOmitted"],!0);case"mcp_task_changed":return w(q,"mcp.task.changed",["revision","taskId","serverName","toolName","status","statusMessage","createdAt","updatedAt","completedAt","hasResult","error"],!0);case"project_rules_loaded":return w(q,"project.rules.loaded",["files","triggerPaths","blockedWrite"],!0);default:return}}function a(q,$={}){let Q=m(q);if(!Q||!$.omitUndefined)return Q;return{...Q,properties:Object.fromEntries(Object.entries(Q.properties).filter(([,P])=>P!==void 0))}}
|
|
2
|
+
export{C as w,k as x,T as y,a as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-f552hzcx.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bk as a,ck as b,dk as c}from"./chunk-zjezws85.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{A as
|
|
1
|
+
import{Hj as b,Ij as k,Kj as w}from"./chunk-9ydrwcpy.js";function g(j){return b.Object(j,{additionalProperties:!1})}var W=b.String({pattern:"^acp-remote-workspace:[A-Za-z0-9_-]{43}$"}),I=b.Optional(b.Integer({minimum:1,maximum:100})),x=b.String({minLength:1,maxLength:200,pattern:"^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$"}),A=k(b.Union([g({version:b.Literal(2),sessionId:x,workspace:g({kind:b.Literal("local"),projectPath:b.String({minLength:1})})}),g({version:b.Literal(2),sessionId:x,workspace:g({kind:b.Literal("acp-remote"),workspaceRef:W})})])),C=k(w(["history-only","owner-offline","owner-mismatch","archived","surface-not-supported","capability-not-advertised"])),X=k(g({connection:w(["local","online","offline"]),history:g({read:b.Boolean(),fork:b.Boolean()}),turn:g({start:b.Boolean(),reason:b.Optional(C)}),files:g({readText:b.Boolean(),writeText:b.Boolean(),browse:w(["none","known-files","tree"]),reason:b.Optional(C)}),terminal:g({mode:w(["none","command","interactive"]),owner:w(["none","local","acp-remote"]),reason:b.Optional(C)})})),Y=k(g({id:b.String({pattern:"^surface-message:[0-9]+:.+$"}),role:w(["user","assistant"]),content:b.String(),timestamp:b.String({minLength:1}),truncated:b.Optional(b.Boolean())})),Z=w(["queued","running","completed","failed","cancelled","interrupted"]),_=w(["posix","win32"]),$=w(["subagent","fork"]),D=b.String({minLength:1}),J=b.String({minLength:1}),z=40,H=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-](\d{2}):(\d{2}))$/,M="^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{3}Z$";function T(j){return j%4===0&&(j%100!==0||j%400===0)}function R(j,q){if(q===2)return T(j)?29:28;return[4,6,9,11].includes(q)?30:31}function d(j){if(j===void 0||j.length<20||j.length>z)return;let q=H.exec(j);if(!q)return;let L=Number(q[1]),B=Number(q[2]),E=Number(q[3]),N=Number(q[4]),O=Number(q[5]),P=Number(q[6]),Q=q[8],U=Number(q[9]),V=Number(q[10]);if(B<1||B>12||E<1||E>R(L,B)||N>23||O>59||P>59||Q!=="Z"&&(U>23||V>59))return;let F=Date.parse(j);if(!Number.isFinite(F))return;let G=new Date(F).toISOString();return G.length===24?G:void 0}var S=b.Refine(b.String({minLength:24,maxLength:24,pattern:M}),(j)=>d(j)===j,()=>"must be a canonical ISO instant"),K=k(g({locator:A,displayCwd:b.String({minLength:1}),pathStyle:b.Optional(_),title:b.Optional(b.String()),rootId:x,parentId:b.Optional(x),relationType:b.Optional($),taskStatus:Z,taskCompletedAt:b.Optional(S),messageCount:b.Integer({minimum:0}),firstMessageTime:b.String({minLength:1}),lastMessageTime:b.String({minLength:1}),hasErrors:b.Boolean(),archivedAt:b.Optional(b.String({minLength:1})),selectedModelId:b.Optional(b.String({minLength:1})),capabilities:X})),p=k(w(["invalid_session_surface_request","invalid_session_locator","session_surface_not_found","workspace_binding_mismatch","session_surface_cursor_invalid","session_surface_snapshot_changed","session_surface_read_only","session_surface_capability_unavailable","session_surface_capacity","session_surface_unavailable","session_surface_state_invalid"])),i=k(g({error:g({code:p,message:b.String({minLength:1}),retryable:b.Boolean()})})),s=k(g({sessions:b.Array(K),nextCursor:b.Optional(D)})),f=k(g({messages:b.Array(Y),olderCursor:b.Optional(D),snapshot:J,truncated:b.Boolean()})),v=k(g({locator:A,limit:I})),l=k(g({session:K,history:f})),r=k(g({locator:A,cursor:D,expectedSnapshot:J,limit:I})),n=k(g({locator:A}));
|
|
2
|
+
export{A as lf,Y as mf,d as nf,K as of,i as pf,s as qf,f as rf,v as sf,l as tf,r as uf,n as vf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{q as
|
|
1
|
+
import{Xj as d,Zj as h}from"./chunk-a1tt14a2.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
|
+
export{q as wf,w as xf};
|