blade-code 0.10.128 → 0.10.130

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.
Files changed (144) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-0z9nqbd0.js +2 -0
  3. package/dist/chunk-1bb4h5gf.js +1 -0
  4. package/dist/chunk-2bnpn8be.js +1 -0
  5. package/dist/{chunk-xzfc1s6k.js → chunk-2y1qngw7.js} +1 -1
  6. package/dist/{chunk-jy0vfp8a.js → chunk-42h7kj6p.js} +1 -1
  7. package/dist/{chunk-ted1hyvb.js → chunk-44jtpg8y.js} +1 -1
  8. package/dist/chunk-4sxxvtn4.js +1 -0
  9. package/dist/chunk-51qc7n8t.js +1 -0
  10. package/dist/{chunk-z3hpstky.js → chunk-53h87fmt.js} +1 -1
  11. package/dist/{chunk-y93nqyqd.js → chunk-55hq1ps4.js} +2 -2
  12. package/dist/{chunk-9n90djh7.js → chunk-5a17mdjd.js} +2 -2
  13. package/dist/{chunk-pq6g92cz.js → chunk-6p6ts4kv.js} +2 -2
  14. package/dist/{chunk-sca5q3tt.js → chunk-77efqpdc.js} +1 -1
  15. package/dist/chunk-7jj607dg.js +94 -0
  16. package/dist/{chunk-yqqeh12b.js → chunk-8a6nrqdc.js} +2 -2
  17. package/dist/{chunk-10w2pj3r.js → chunk-93x9xbew.js} +1 -1
  18. package/dist/{chunk-1aw643j2.js → chunk-9et78e3v.js} +2 -2
  19. package/dist/chunk-9gs4eqt8.js +1 -0
  20. package/dist/chunk-9s8saznq.js +1 -0
  21. package/dist/{chunk-fa0pyv9k.js → chunk-9yqadjea.js} +2 -2
  22. package/dist/{chunk-a7gghhvn.js → chunk-a4jetpj8.js} +18 -18
  23. package/dist/{chunk-yqpej45c.js → chunk-a60cmnmz.js} +2 -2
  24. package/dist/{chunk-8hd4vd20.js → chunk-aaxc81jc.js} +1 -1
  25. package/dist/{chunk-xejvs1fk.js → chunk-agda17kj.js} +1 -1
  26. package/dist/{chunk-c47db31j.js → chunk-ajsw4te2.js} +2 -2
  27. package/dist/{chunk-r04vwtej.js → chunk-ar5np5h5.js} +2 -2
  28. package/dist/chunk-b8m7zc7t.js +170 -0
  29. package/dist/chunk-bcre3557.js +1 -0
  30. package/dist/{chunk-atema2rc.js → chunk-dfjmvj3d.js} +2 -2
  31. package/dist/chunk-dkgaxmsp.js +10 -0
  32. package/dist/{chunk-mkvvyq49.js → chunk-e1d0e6t6.js} +2 -2
  33. package/dist/{chunk-s7axaw78.js → chunk-edtxcqxa.js} +1 -1
  34. package/dist/chunk-f8gb685p.js +2 -0
  35. package/dist/chunk-fjv2vede.js +1 -0
  36. package/dist/{chunk-zfyg3888.js → chunk-g4xny949.js} +1 -1
  37. package/dist/chunk-gfbkrk60.js +338 -0
  38. package/dist/{chunk-12hdakw4.js → chunk-gmqpfm52.js} +2 -2
  39. package/dist/{chunk-skv2gb99.js → chunk-grhsv55v.js} +2 -2
  40. package/dist/chunk-gzz0gnmv.js +1 -0
  41. package/dist/chunk-h1wphqkc.js +1 -0
  42. package/dist/{chunk-6v2hhgka.js → chunk-hhg1zcbq.js} +2 -2
  43. package/dist/{chunk-9hnfz9bx.js → chunk-hw1gbr11.js} +1 -1
  44. package/dist/{chunk-nx8xb7dm.js → chunk-jkfkyedn.js} +1 -1
  45. package/dist/chunk-kd3k1q9z.js +1 -0
  46. package/dist/{chunk-n8w1jxsh.js → chunk-kfkvdj49.js} +1 -1
  47. package/dist/chunk-m9mw8ppy.js +1 -0
  48. package/dist/{chunk-xshrj2nd.js → chunk-mdew58v9.js} +1 -1
  49. package/dist/{chunk-n4q6fvqe.js → chunk-mvm1rzc4.js} +2 -2
  50. package/dist/{chunk-qm632an7.js → chunk-p00f53yq.js} +1 -1
  51. package/dist/{chunk-p7349xay.js → chunk-p2sp2e0a.js} +2 -2
  52. package/dist/chunk-pj69j4zp.js +2 -0
  53. package/dist/{chunk-41byj2h8.js → chunk-pk11fexz.js} +2 -2
  54. package/dist/chunk-qahz5x5c.js +14 -0
  55. package/dist/{chunk-6m4sqwj0.js → chunk-qcvxff27.js} +2 -2
  56. package/dist/{chunk-p2rxrxct.js → chunk-r9tawy93.js} +3 -3
  57. package/dist/{chunk-rz2wc93t.js → chunk-s2atpv23.js} +4 -4
  58. package/dist/chunk-saedy6bj.js +1 -0
  59. package/dist/{chunk-fgbqm2jh.js → chunk-sfe4810k.js} +1 -1
  60. package/dist/{chunk-96w8ay2h.js → chunk-sj1dzeta.js} +1 -1
  61. package/dist/chunk-sn71fsm5.js +1 -0
  62. package/dist/{chunk-yysqw1cq.js → chunk-ss4sncn3.js} +2 -2
  63. package/dist/chunk-ss86eq2h.js +23 -0
  64. package/dist/{chunk-ektgnqmh.js → chunk-sx77dpxw.js} +1 -1
  65. package/dist/chunk-t4apxzp1.js +2 -0
  66. package/dist/chunk-te6203yf.js +1 -0
  67. package/dist/{chunk-gxwkwkhp.js → chunk-tkydv9k8.js} +1 -1
  68. package/dist/{chunk-60he05xs.js → chunk-tw5fr07c.js} +2 -2
  69. package/dist/{chunk-q3y3s16v.js → chunk-v52wc8yg.js} +2 -2
  70. package/dist/{chunk-b408cqg1.js → chunk-v5hzk7j2.js} +2 -2
  71. package/dist/{chunk-v4nqv1pr.js → chunk-v94ztjtp.js} +385 -385
  72. package/dist/{chunk-85jv1sr7.js → chunk-xa9k5pjt.js} +2 -2
  73. package/dist/{chunk-mvgmsjwq.js → chunk-z03dtyh6.js} +1 -1
  74. package/dist/{chunk-jxc67ydz.js → chunk-zc91c7b5.js} +2 -2
  75. package/dist/{chunk-mm05y2c5.js → chunk-zkzhm39s.js} +1 -1
  76. package/dist/{chunk-1xg7qx35.js → chunk-zwjrensv.js} +1 -1
  77. package/dist/web/assets/ChatView-Bg36FUaj.js +53 -0
  78. package/dist/web/assets/{CodeBlockHighlighter-0VOa5Mes.js → CodeBlockHighlighter-D5rB73Eo.js} +2 -2
  79. package/dist/web/assets/FilePreview-BxaBSmap.js +65 -0
  80. package/dist/web/assets/KanbanBoard-B4gx3JMo.js +16 -0
  81. package/dist/web/assets/{MarkdownRenderer-3g4TPTeI.js → MarkdownRenderer-BRH7LHhN.js} +3 -3
  82. package/dist/web/assets/ScrollArea-DikU3QeQ.js +1 -0
  83. package/dist/web/assets/SessionHistorySurface-DG80d6-F.js +6 -0
  84. package/dist/web/assets/{SettingsModal-3GMy6V-E.js → SettingsModal-Bxqkok81.js} +3 -3
  85. package/dist/web/assets/Sidebar-DGaHGcHx.js +31 -0
  86. package/dist/web/assets/TaskSwitcher-DOnLPurk.js +26 -0
  87. package/dist/web/assets/TerminalPanel-BzhCF9vw.js +6 -0
  88. package/dist/web/assets/archive-BiDGrqry.js +6 -0
  89. package/dist/web/assets/{arrow-left-03GxbYI7.js → arrow-left-BY-esOAP.js} +1 -1
  90. package/dist/web/assets/{calendar-clock-8W4ostX1.js → calendar-clock-BCyxvfVt.js} +1 -1
  91. package/dist/web/assets/chevron-right-Bg-10yuN.js +6 -0
  92. package/dist/web/assets/{chevrons-up-down-BboZzEAk.js → chevrons-up-down-M5SAJq7T.js} +1 -1
  93. package/dist/web/assets/{clock-3-aXgeptZP.js → clock-3-v-nHTA0A.js} +1 -1
  94. package/dist/web/assets/copy-p1zc_rjZ.js +6 -0
  95. package/dist/web/assets/download-D_-kbJXR.js +6 -0
  96. package/dist/web/assets/{external-link-UkIIC2ds.js → external-link-wSGTIqe3.js} +1 -1
  97. package/dist/web/assets/{folder-BOCc5dv2.js → folder-Ltm9jCS5.js} +1 -1
  98. package/dist/web/assets/index-B4186fIT.css +1 -0
  99. package/dist/web/assets/index-_xnlrekR.js +210 -0
  100. package/dist/web/assets/{pause-DVIT6IIr.js → pause-_LvCZkxM.js} +1 -1
  101. package/dist/web/assets/pencil-DB6ICr_h.js +6 -0
  102. package/dist/web/assets/{play-DsdF5dji.js → play-BRXP1rHJ.js} +1 -1
  103. package/dist/web/assets/plus-BqvjEpLw.js +6 -0
  104. package/dist/web/assets/session-events-AGMXvPey.js +22 -0
  105. package/dist/web/assets/settings-LfQbDvBA.js +6 -0
  106. package/dist/web/assets/teamService-B5FnUcet.js +1 -0
  107. package/dist/web/assets/terminal-By4sO9Gw.js +6 -0
  108. package/dist/web/assets/vendor-radix-D6QrtXqd.js +45 -0
  109. package/dist/web/index.html +3 -3
  110. package/package.json +1 -1
  111. package/dist/chunk-0ktte40x.js +0 -185
  112. package/dist/chunk-1acb8fwq.js +0 -120
  113. package/dist/chunk-3pwqqk7w.js +0 -1
  114. package/dist/chunk-3q7g9206.js +0 -1
  115. package/dist/chunk-562w5zc6.js +0 -2
  116. package/dist/chunk-5x56nka1.js +0 -1
  117. package/dist/chunk-7hajkvde.js +0 -1
  118. package/dist/chunk-9wptwfmg.js +0 -1
  119. package/dist/chunk-ap01rwg0.js +0 -169
  120. package/dist/chunk-cm8fy1jn.js +0 -1
  121. package/dist/chunk-dp4r5bay.js +0 -1
  122. package/dist/chunk-dtxza4zh.js +0 -1
  123. package/dist/chunk-hd7bxzvy.js +0 -1
  124. package/dist/chunk-hks48s9k.js +0 -1
  125. package/dist/chunk-hmncnf7p.js +0 -1
  126. package/dist/chunk-j6fj679p.js +0 -10
  127. package/dist/chunk-m8czdpyg.js +0 -1
  128. package/dist/chunk-p5awnndq.js +0 -8
  129. package/dist/chunk-s7peh6kf.js +0 -2
  130. package/dist/chunk-ws6gtw33.js +0 -1
  131. package/dist/chunk-wtmhqy5s.js +0 -1
  132. package/dist/chunk-xnstybjm.js +0 -2
  133. package/dist/chunk-xpdtg9h9.js +0 -23
  134. package/dist/chunk-z2jwm4s8.js +0 -1
  135. package/dist/web/assets/ChatView-DCHnicTP.js +0 -58
  136. package/dist/web/assets/FilePreview-C_3KHzzj.js +0 -65
  137. package/dist/web/assets/KanbanBoard-D_NTkUnD.js +0 -16
  138. package/dist/web/assets/TaskSwitcher-eCdxu5Eo.js +0 -26
  139. package/dist/web/assets/TerminalPanel-9q9Trmv9.js +0 -6
  140. package/dist/web/assets/index-DGf6Z2kM.css +0 -1
  141. package/dist/web/assets/index-DaiT-mmo.js +0 -275
  142. package/dist/web/assets/session-events-CWzF04l4.js +0 -22
  143. package/dist/web/assets/teamService-BliaDj1Z.js +0 -1
  144. package/dist/web/assets/vendor-radix-Bc1_Q9tz.js +0 -45
@@ -0,0 +1 @@
1
+ import{af as a,bf as b}from"./chunk-e1d0e6t6.js";import"./chunk-v5hzk7j2.js";import"./chunk-zkzhm39s.js";export{a as globalOptions,b as cliConfig};
@@ -1,3 +1,3 @@
1
- import{g as i}from"./chunk-skv2gb99.js";import{si as s}from"./chunk-ted1hyvb.js";import"./chunk-xnstybjm.js";import"./chunk-mm05y2c5.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{j as i}from"./chunk-grhsv55v.js";import{Ii as s}from"./chunk-44jtpg8y.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1,2 +1,2 @@
1
1
  import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
2
- export{a as ei,f as fi,l as gi,x as hi,b as ii,V as ji};
2
+ export{a as Ji,f as Ki,l as Li,x as Mi,b as Ni,V as Oi};
@@ -0,0 +1 @@
1
+ import{Ag as a,Bg as b,Cg as c,Dg as d,Eg as e,Fg as f,Gg as g,Hg as h,Ig as i,Jg as j,Kg as k}from"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,4 +1,4 @@
1
- import{ua as F,wa as L}from"./chunk-v4nqv1pr.js";import{Qd as $,Sd as B,_d as Q}from"./chunk-1acb8fwq.js";import{jg as y}from"./chunk-a7gghhvn.js";import{si as V}from"./chunk-ted1hyvb.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{xa as F,za as L}from"./chunk-v94ztjtp.js";import{Jd as $,Ld as B,Td as Q}from"./chunk-7jj607dg.js";import{Fg as y}from"./chunk-a4jetpj8.js";import{Ii as V}from"./chunk-44jtpg8y.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
- export{j as m,I as n,M as o,R as p,_ as q,C as r};
4
+ export{j as p,I as q,M as r,R as s,_ as t,C as u};
@@ -0,0 +1,23 @@
1
+ import{v as tz,w as ez}from"./chunk-xa9k5pjt.js";import{A as S,x as yz,y as Iz,z as kz}from"./chunk-5a17mdjd.js";import{B as sz,C as Pz,D as Ez,E as Tz,F as xz,G as bz}from"./chunk-9yqadjea.js";import{Aa as Mz,N as R,W as wz,X as Fz,aa as Oz,da as Nz,ea as Az,ha as qz,xa as Rz,ya as Sz,za as hz}from"./chunk-v94ztjtp.js";import"./chunk-6p6ts4kv.js";import{Oa as nz}from"./chunk-tw5fr07c.js";import{Qa as Dz}from"./chunk-v52wc8yg.js";import{Kb as Kz,Tb as d,yb as _z}from"./chunk-s2atpv23.js";import{cc as m}from"./chunk-77efqpdc.js";import{Dd as Uz,Gd as jz,Id as h,Ld as Gz,Qd as Vz,Td as K,md as Wz,wd as M,xd as v,yd as Bz}from"./chunk-7jj607dg.js";import"./chunk-53h87fmt.js";import{pe as Hz,we as l,xe as Xz}from"./chunk-gfbkrk60.js";import"./chunk-0z9nqbd0.js";import{hf as zJ}from"./chunk-9et78e3v.js";import"./chunk-a60cmnmz.js";import{Cf as iz,Df as az}from"./chunk-zc91c7b5.js";import"./chunk-v508x7cg.js";import{Of as n}from"./chunk-mdew58v9.js";import{Tf as Lz}from"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import{cg as rz}from"./chunk-edtxcqxa.js";import"./chunk-8a6nrqdc.js";import"./chunk-a4jetpj8.js";import"./chunk-sx77dpxw.js";import{Yg as oz}from"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r9tawy93.js";import"./chunk-g4xny949.js";import{$h as dz,ci as lz}from"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import{Ai as g,Bi as Yz,Di as c,Ei as p}from"./chunk-f8gb685p.js";import{Ii as o}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import{oj as y}from"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import{vj as mz,yj as vz}from"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import{Mj as Qz,Nj as cz,Rj as s,Vj as t,Wj as pz,Xj as e}from"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import{Readable as VJ,Writable as _J}from"node:stream";import*as f from"@agentclientprotocol/sdk";import i from"node:path";import{PROTOCOL_VERSION as XJ,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var V=y("Agent");function T(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function $z(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function $J(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:$z(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:$z("headers"in z?z.headers:void 0)};return null}function QJ(z){let J={};for(let Z of z){let Y=$J(Z);if(Y)J[Z.name]=Y}return J}function fz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function YJ(z){let J=Xz(z.metadata);return J?[{type:"text",text:l(J)}]:fz(z.content)}function LJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}function WJ(z){if(!Lz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...M("capacity"),resource:z.resource}}function HJ(z){if(!(z instanceof Cz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Bz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}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;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,J,Z,Y,W={}){this.id=z;this.roots=J;this.connection=Z;this.clientCapabilities=Y;this.options=W;this.messages=[...W.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(W.permissionMode),this.updateEgress=new bz({maxPendingItems:Pz,maxPendingBytes:Ez,writeTimeoutMs:Tz,signal:Z.signal,sizeOf:(H)=>Buffer.byteLength(JSON.stringify(H)),write:async(H)=>{await Z.sessionUpdate(H)},onFailure:(H)=>this.handleUpdateEgressFailure(H)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await this.loadPersistedModelContext();return J.length>0?J:[...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,J=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(Z){if(!(Z instanceof Vz)&&Z.code!=="ENOENT")throw Z;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...J})}}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 qz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){V.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(L)=>{await this.sendUpdateAndWait(L)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(V.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await d.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(L)=>this.requestPermission(L)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?QJ(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),W=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 Oz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...W?{workspace:W}:{},permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(L,U)=>{let j=await Y.execute(L,{cwd:U.cwd,env:U.env,timeout:U.timeoutMs,signal:U.signal,allowLocalFallback:!1,onOutput:(G)=>U.onOutput?.("stdout",G)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.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 Sz(this.roots.hostStateRoot);V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=_z.subscribe((L)=>{if(L.sessionId!==this.id||L.projectPath!==this.roots.hostStateRoot)return;if(L.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":L.properties}}),this.requestPendingResume();return}if(L.type==="task.delivery"){if(!L.properties.taskDelivery||typeof L.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":L.properties.taskDelivery,...L.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(L.type.startsWith("team.")){let{teamName:U,messageId:j,content:G}=L.properties,P=L.properties.metadata;if(L.type==="team.message.received"&&typeof U==="string"&&typeof j==="string"&&typeof G==="string"&&Fz(P,{messageId:j,teamName:U}))(async()=>{let E=await this.runtime?.enqueueSteering(G,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:P});if(!E?.accepted)return;if(await new wz(U,Qz()).markDelivered([j]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:L.type,...L.properties}}});return}if(L.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":L.properties.taskStatus,...typeof L.properties.taskStatusReason==="string"?{"blade/taskStatusReason":L.properties.taskStatusReason}:{},...L.properties.taskFailure&&typeof L.properties.taskFailure==="object"?{"blade/taskFailure":L.properties.taskFailure}:{},...typeof L.properties.taskStartedAt==="string"?{"blade/taskStartedAt":L.properties.taskStartedAt}:{},...typeof L.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":L.properties.taskCompletedAt}:{},...L.properties.taskDiffStat&&typeof L.properties.taskDiffStat==="object"?{"blade/taskDiffStat":L.properties.taskDiffStat}:{},...typeof L.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":L.properties.taskQueuePosition}:{},...typeof L.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":L.properties.taskQueueDepth}:{},...typeof L.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":L.properties.taskConcurrencyLimit}:{},...typeof L.properties.taskInFlight==="number"?{"blade/taskInFlight":L.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(X||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Hz(J))continue;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Y of YJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,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);V.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.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let Z={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],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 X=await this.runtime.rewindSession(Q);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},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,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,L,U=(G)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:G.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:G.result?.message||G.result?.error||`Subagent ${G.status}`}}]})},j=this.runtime.resumeSubagent({agentId:Q,prompt:X,onCompleted:(G)=>{if(B)U(G);else L=G}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.session.id,status:"in_progress",title:`Resuming ${j.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${j.source.id} at depth ${j.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,L)U(L);return j}}}:{},...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,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,X,B)},complete:async(Q,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,X,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,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,X)},getLogs:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,X)},setLoggingLevel:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:X})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,X)=>{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:X,onEvent:(j)=>{if(j.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.toolCall.id,status:"in_progress",title:`Review: ${j.toolCall.function.name}`,content:[],kind:this.mapToolKind(j.toolKind)});else if(j.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:j.toolCall.id,status:j.result.success?"completed":"failed",content:[]})}}),L=await B.completion,U=(await S.list(this.roots.hostStateRoot,this.id)).find((j)=>j.start.reviewId===B.reviewId);if(!U)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:L.status,findings:L.findings.length,content:Wz(U.start,L)}}}}:{},signal:J,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,X,B)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,U=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:U})},sendToolResult:(Q,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},Y=await hz(z,Z),W=Y.data?.action;if(W==="start_goal"||W==="resume_goal")this.requestPendingResume();if(W==="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 H=Y.content||Y.message;if(H)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:H}});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(Z){if(J.aborted||Z instanceof Error&&Z.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,Z),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,Z,Y=new Promise((W)=>{Z=W});this.pendingSideConversation=J,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,J.signal)}catch(W){if(J.signal.aborted||W instanceof Error&&W.name==="AbortError")return{stopReason:"cancelled"};throw W}finally{if(Z(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Mz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),J=["model","permissions","theme","config","exit","ide"],Y=z.filter((W)=>!J.includes(W.name)&&(W.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((W)=>{let H;if(W.usage){let Q=W.usage.replace(/^\/\w+\s*/,"").trim();if(Q)H=Q}if(W.aliases?.length){let Q=`Aliases: ${W.aliases.join(", ")}`;H=H?`${H} | ${Q}`:Q}return{name:W.name,description:W.description,input:H?{hint:H}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((W)=>W.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),V.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Z=this.resolvePrompt(z.prompt),Y=Z.content,W=Z.displayText,H=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(H!==void 0)Q=Gz(H).schema;if(W.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(W)}let X=Dz(W);if(X){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(X.question?`/btw ${X.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(W.trim()))return this.handleSlashCommand(W,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(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,L=()=>{B.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let U=!1,j=!1,G=!1,P,E=new Promise((D)=>{P=D});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${W.slice(0,100)}...`),Rz(W)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(W,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($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Kz(this.agent.chatStream(Y,D,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{G=!0;let _=$.toolCall,N=_.function.name;if(N===h)break;let q=this.mapToolKind($.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in _)try{let b=JSON.parse(_.function.arguments),F=b.resume_from??b.resume;if(typeof F==="string")w=`Resuming ${String(b.subagent_type||"subagent")} from ${F}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:_.id,status:"in_progress",title:w,content:[],kind:q});break}case"tool_progress":{G=!0;let _=$.toolCall;if(_.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{G=!0;let _=$.toolCall;if(_.function.name===h)break;let N=$.result,q=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let F of w.changes){if(!F||typeof F!=="object"||!("path"in F)||typeof F.path!=="string")continue;q.push({type:"diff",path:F.path,oldText:"oldContent"in F&&typeof F.oldContent==="string"?F.oldContent:null,newText:"newContent"in F&&typeof F.newContent==="string"?F.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))q.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let F=_.function.name,JJ=Az(jz(Nz(F,N),Uz));q.push({type:"content",content:{type:"text",text:JJ}})}if(_.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let b=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:b,content:q});break}case"structured_output":j=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
+ `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
+ `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
5
+ `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
6
+ `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
7
+ `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
8
+ `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
9
+ `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
10
+ `}});break;case"provider_admission":U=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:$.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:$.goal.goalId,status:$.goal.status,taskListId:$.frontier.taskListId,total:$.frontier.total,completed:$.frontier.completed,inProgress:$.frontier.inProgress,pending:$.frontier.pending,blocked:$.frontier.blocked,nextTask:$.frontier.nextTask,digestSha256:$.frontier.digestSha256,...$.goal.frontierStall?{stall:{category:$.goal.frontierStall.category,consecutiveCount:$.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":{let _=0;for(let N of $.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let q of fz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(N.id),_++}if(_>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${_} queued instruction${_===1?"":"s"} recovered after restart]
11
+ `}});break}case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
12
+ `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});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 Jz=await this.loadPersistedMessages();if(this.messages=Jz.length>0?Jz:[...D.messages],!O.success){let $=O.error?.type??"unknown",_=O.error?.details??O.error?.message??"Agent execution failed",N=WJ(_)??v(_);throw Cz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:N,outputStarted:j,toolExecutionStarted:G,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Zz={...O.metadata?.structuredOutput?{structuredOutput:O.metadata.structuredOutput,outputSchemaDigest:O.metadata.structuredOutputSchemaDigest}:{},...O.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:O.metadata.goalVerificationVerdict,...O.metadata.goalVerifierSessionId?{verifierSessionId:O.metadata.goalVerifierSessionId}:{},...O.metadata.goalVerificationEvidenceSha256?{evidenceSha256:O.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Zz).length>0?{_meta:Zz}:{}}}catch(D){if(B.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(J.abortSignal?.removeEventListener("abort",L),U&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(P(),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 J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let Z=new AbortController,Y,W=new Promise((X)=>{Y=X});this.pendingUserShell=Z,this.pendingUserShellCompletion=W;let H,Q="";try{let X=await this.runtime.executeUserShellCommand(J,{signal:Z.signal,onEvent:async(L)=>{if(H=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Q+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let U=l(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?LJ(L.record):U}}]})}}),B={role:"user",content:X.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(X.record))}};if(this.messages.push(B),this.contextMessages.push(B),X.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return Z.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:X.record.status==="aborted"?"cancelled":"end_turn"}}catch(X){if(H)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H,status:"failed",content:[{type:"content",content:{type:"text",text:X instanceof Error?X.message:String(X)}}]});if(Z.signal.aborted)return{stopReason:"cancelled"};throw X}finally{if(Y(),this.pendingUserShellCompletion===W)this.pendingUserShellCompletion=null;if(this.pendingUserShell===Z){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 J=this.pendingResumeGeneration,Z=()=>{if(J!==this.pendingResumeGeneration)return;this.startPendingResumeRun(J)};if(z>0)this.pendingResumeTimer=setTimeout(Z,z),this.pendingResumeTimer.unref?.();else queueMicrotask(Z)}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 J=this.resumePendingIfIdle();this.pendingResumeCompletion=J,J.then(()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}},()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}})}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,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:yz,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.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,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let Z="preflight",Y=!1,W,H=null;try{let Q=this.runtime.getPendingSteeringCount()>0,X=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=X?.status==="active"||X?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}Z=Q?"pending_input":"goal",Y=!0;let U=Iz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(U<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}let j=new AbortController;H=setTimeout(()=>{j.abort("acp-pending-resume-budget-exhausted")},U),H.unref?.();let G=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:Z==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:j.signal});if(z!==this.pendingResumeGeneration)return;if(j.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}if(G.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:Z})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let X=Y?HJ(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=Z==="preflight"||Z==="pending_input"&&this.runtime.getPendingSteeringCount()>0,L=kz({sessionIdentity:this.id,failedAttempt:J,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:X});if(L.phase==="retry_scheduled")this.pendingResumeRequested=!0,W=L.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:Z,taskFailure:X?.taskFailure,delayMs:L.delayMs})),V.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${L.delayMs}ms`);else{let U=L.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(U,{attempt:J,kind:Z,taskFailure:X?.taskFailure})),V.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L.retryable}, phase=${U})`,Q),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest()}}finally{if(H!==null)clearTimeout(H);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=W??0}}cancel(){V.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)V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let Z=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(Z);await this.persistPermissionMode(Y),this.mode=Z,V.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(V.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 J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(Z){if(J&&J!==z)await this.agent.switchModel(J).catch((Y)=>{V.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Z}}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 J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(Z){throw await this.runtime.refresh({reasoningEffort:J.selection}),Z}}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 J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(Z){throw await this.runtime.refresh({serviceTier:J.selection}),Z}}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 J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(Z){throw await this.runtime.refresh({responseVerbosity:J.selection}),Z}}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 J=this.runtime.getCommunicationStyleConfiguration(),Z=this.runtime.resolveCommunicationStyleConfiguration(z);if(Z.source!=="built-in"&&!Z.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:Z.source==="built-in"?null:Z.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...Z.source!=="built-in"&&Z.contentSha256?{communicationStyleDigest:Z.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:J.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),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 xz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime,Y=this.pendingPromptCompletion,W=this.pendingUserShellCompletion,H=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let X,B=async(L)=>{try{await L()}catch(U){X??=U}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if(W)await B(()=>W);if(H)await B(()=>H);if(Q)await B(()=>Q);if(z&&Y&&Z)await B(()=>Z.discardPendingInput());if(J)await B(()=>J.destroy());if(Z)await B(()=>Z.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,V.debug(`[AcpSession ${this.id}] Destroyed`),X!==void 0)throw X}resolvePrompt(z){let J=[],Z=[],Y=0,W=0,H=0,Q=(L)=>{if(Z.length>0)Z.push({type:"text",text:`
13
+ `}),H+=1;if(Z.push(L),L.type==="text")H+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Q({type:"text",text:L.text});else if(L.type==="image"){let U=`data:${L.mimeType};base64,${L.data}`;Y+=1,W+=U.length,J.push(`[Image: ${L.mimeType}]`),Q({type:"image_url",image_url:{url:U}})}else if(L.type==="resource"){let U=L.resource;if("text"in U){let j=`<file path="${U.uri}">
14
+ ${U.text}
15
+ </file>`;J.push(j),Q({type:"text",text:j})}}else if(L.type==="resource_link"){let U=`[Resource: ${L.uri}]`;J.push(U),Q({type:"text",text:U})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if(W>Yz)throw Error("ACP prompt images exceed the 5 MiB limit");if(H>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(J.join(`
16
+ `),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=J.join(`
17
+ `);return{content:Y>0?Z:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.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}}}}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;V.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 J=z.map((Z)=>({content:Z.subject,priority:Z.priority,status:Z.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let Z=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(Z))return V.debug(`[AcpSession ${this.id}] Auto-approving ${Z} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Z==="write"||Z==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${Z} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),W=[];if(z.message)W.push({type:"content",content:{type:"text",text:z.message}});if(z.details)W.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)W.push({type:"content",content:{type:"text",text:`Risks:
18
+ - ${z.risks.join(`
19
+ - `)}`}});let H=this.mapToolKind(Z),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:W,kind:H}},X=await this.waitForClientInteraction(this.connection.requestPermission(Q),J);if(!X)return{approved:!1,reason:m};let B=X.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=B.optionId;if(L==="allow_always")return{approved:!0,scope:"project"};if(L==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let U=L==="allow_once";return{approved:U,scope:"once",reason:U?void 0:"User denied the operation"}}catch(Y){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let Z=z.questions??[];if(Z.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Z.some((W)=>W.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[W,H]of Z.entries()){let Q=H.options.map((U,j)=>`answer:${W}:${j}`),X=`answer:${W}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.options.map((U,j)=>({optionId:Q[j],name:U.label,kind:"allow_once"})),{optionId:X,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:H.header,kind:"think",content:[{type:"content",content:{type:"text",text:[H.question,...H.options.map((U)=>`${U.label}: ${U.description}`)].join(`
20
+ `)}}]}}),J);if(!B)return{approved:!1,reason:m};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Q.indexOf(B.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[H.header]=H.options[L].label}return{approved:!0,answers:Y}}catch(W){return V.warn(`[AcpSession ${this.id}] Question request failed:`,W),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let Z=z.mcpElicitation;if(!Z)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Z.mode==="url"){let W=await this.requestElicitationChoice("MCP external authorization",[Z.message,`Server: ${Z.serverName}`,`Domain: ${Z.domain??"unknown"}`,`URL: ${Z.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"}],J);if(W==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:W==="decline"?"User declined URL":"User cancelled",elicitation:{action:W==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let W of Z.fields??[]){let H=await this.collectAcpElicitationField(W,J);if(H.cancelled)return{approved:!1,reason:H.reason,elicitation:{action:"cancel"}};if(H.value!==void 0)Y[W.name]=H.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return V.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let Z=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((H,Q)=>({id:`option:${Q}`,label:H.label,value:H.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
22
+ `),[...Z.map((H)=>({id:H.id,label:H.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Y==="skip")return{cancelled:!1};let W=Z.find((H)=>H.id===Y);if(!W)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:W.value}}if(z.defaultValue!==void 0){let Z=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"}]:[]],J);if(Z==="default")return{cancelled:!1,value:z.defaultValue};if(Z==="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,J,Z,Y){let W=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Z.map((H)=>({optionId:H.id,name:H.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:J}}]}}),Y);return W?.outcome.outcome==="selected"?W.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((Z,Y)=>{let W=!1,H=(X)=>{if(W)return;W=!0,J.removeEventListener("abort",Q),X()},Q=()=>H(()=>Z(void 0));if(J.addEventListener("abort",Q,{once:!0}),J.aborted)Q();z.then((X)=>H(()=>Z(X)),(X)=>H(()=>Y(X)))})}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 A=y("Agent"),BJ="remote task isolation is not supported";function I(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function UJ(z){return C.invalidParams({code:z.code,reason:z.reason})}function jJ(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:BJ})}function uz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function gz(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 s(z)}catch(J){if(J instanceof cz)throw UJ(J);throw J}}function a(z,J){let Z=t(z);return Object.freeze({kind:"acp-remote",hostStateRoot:e(Z.collisionIdentity),executionRoot:Z.wirePath,hostResourceRoot:J,profile:z,descriptor:Z})}function r(z,J){let Z=pz(z.remoteWorkspace),Y=e(Z.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let W=s(Z.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:Z.wirePath,hostResourceRoot:J,profile:W,descriptor:Z})}function GJ(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class zz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=i.resolve(o())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=iz();this.runtimeResidencyValue=new ez({maxResident:z?.maxResidentSessionRuntimes??dz,idleMs:z?.sessionRuntimeIdleMs??lz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof tz)throw C.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await az(),{protocolVersion:XJ,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 J=n("acp"),Z=z.cwd||o(),Y=I(this.clientCapabilities),W=Y?k(Z):void 0,H=z._meta?.["blade/taskIsolation"],Q=H==="local"||H==="worktree"?H:void 0;if(Y&&Q)throw jJ();let X=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(J),L;try{let U,j;if(W){let P=a(W,this.hostResourceRoot);U=await K.createRemoteSessionMetadata(J,P.hostStateRoot,P.descriptor,{}),j=r(U,this.hostResourceRoot)}else j=T(Z);let G=!Y&&Q?await sz.createSessionTask({sessionId:J,prompt:typeof X==="string"&&X.trim()?X:"ACP task session",sourceProjectPath:Z,isolation:Q}):void 0;if(G)j=T(G.metadata.projectPath);return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session kind: ${j.kind}`),L=new x(J,j,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...G?.taskWorktree?{taskWorktree:G.taskWorktree}:{},...G?.metadata.taskIsolation?{taskIsolation:G.metadata.taskIsolation}:{}}),await L.initialize(),this.assertNotDestroyed(),this.commitSession(J,L,B),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),L.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,G?.metadata,L.getModelConfiguration())}catch(U){throw B.cancel(),await L?.destroy().catch(()=>{return}),U}}async listSessions(z){let J=I(this.clientCapabilities);if(!J&&z.cwd!=null&&!i.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=J?await K.listRemoteSessionPage({...z.cwd!=null?{descriptor:t(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:Z.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:J?GJ(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:Z.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let J=I(this.clientCapabilities),Z=J?a(k(z.cwd),this.hostResourceRoot):void 0;if(!J&&!i.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=n("fork"),W=await this.reserveSessionRuntime(Y),H;try{let Q;try{Q=await K.forkSession(z.sessionId,{sourceProjectPath:Z?.hostStateRoot??z.cwd,targetProjectPath:Z?.hostStateRoot??z.cwd,newSessionId:Y,...Z?{remote:{expectedDescriptor:Z.descriptor}}:{}})}catch(B){if(gz(B))throw uz();throw B}this.assertNotDestroyed();let X=J?r(Q.metadata,this.hostResourceRoot):T(Q.projectPath??z.cwd);return H=new x(Q.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,H,W),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,J?void 0:Q.metadata,H.getModelConfiguration())}catch(Q){throw W.cancel(),await H?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!I(this.clientCapabilities)){await K.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),B;try{let[L,U]=await Promise.all([K.loadSession(z.sessionId,z.cwd),K.findSessionMetadata(z.sessionId,z.cwd)]);if(!U)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,T(z.cwd),this.connection,this.clientCapabilities,{initialMessages:L,permissionMode:U.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,X),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch(L){throw X.cancel(),await B?.destroy().catch(()=>{return}),L}}let Z=a(k(z.cwd),this.hostResourceRoot),Y;try{Y=await K.assertRemoteSessionWritable(z.sessionId,Z.hostStateRoot,Z.descriptor)}catch(X){if(gz(X))throw uz();throw X}let W=r(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let H=await this.reserveSessionRuntime(z.sessionId),Q;try{let X=await K.loadRemoteSession(z.sessionId,W.hostStateRoot,W.descriptor);return Q=new x(z.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:X,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,H),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(X){throw H.cancel(),await Q?.destroy().catch(()=>{return}),X}}commitSession(z,J,Z){let Y=Z.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),Y.release()}async closeResidentSession(z,J={}){let Z=this.sessions.get(z);if(!Z)return;let Y=this.runtimeResidency.owns(z,Z),W;try{await Z.destroy(J)}catch(Q){W=Q}let H=await this.runtimeResidency.forget(z,Z);if(this.sessions.get(z)===Z)this.sessions.delete(z);if(Y&&!H&&W===void 0)throw Error(`ACP Session is still active: ${z}`);if(W!==void 0)throw W}buildChildSessionResponse(z,J,Z){return{sessionId:z,...this.buildSessionSetup(Z,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let Z=z?.models??[],Y=(z?.currentModelId&&Z.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??Z[0]?.id,W=[{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"}],H=[];if(Z.length>0)H.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Z.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)H.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)H.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)H.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)H.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:W,currentModeId:J},configOptions:H.length>0?H:void 0}}async closeSession(z){this.assertNotDestroyed();let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let Z=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await Z.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&rz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await Z.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&vz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await Z.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&mz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await Z.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&oz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await Z.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}finally{J.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 J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(Z){z??=Z}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await nz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function GZ(){let z=_J.toWeb(process.stdout),J=VJ.toWeb(process.stdin),Z=f.ndJsonStream(z,J),Y,W=new f.AgentSideConnection((Q)=>{return Y=new zz(Q),Y},Z),H=zJ(async()=>{await Y?.destroy()});try{await W.closed}finally{H(),await Y?.destroy()}}export{GZ as runAcpIntegration,T as createLocalAcpSessionRoots};
@@ -1,2 +1,2 @@
1
1
  var n="verification",r="goal-verification",o="review";function e(t){return t==="verification"||t==="goal-verification"}function i(t){return e(t)||t==="review"}var s=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],c=["pending","pass","fail","partial"],l=4000,p=3,S=["unable_to_proceed","stopping_here","internal_wait","self_deferral","handoff"],u=3,_=["waiting_dependency","same_task_no_effect","repeated_deferral"],d=3;
2
- export{n as pg,r as qg,o as rg,e as sg,i as tg,s as ug,c as vg,l as wg,p as xg,S as yg,u as zg,_ as Ag,d as Bg};
2
+ export{n as Lg,r as Mg,o as Ng,e as Og,i as Pg,s as Qg,c as Rg,l as Sg,p as Tg,S as Ug,u as Vg,_ as Wg,d as Xg};
@@ -0,0 +1,2 @@
1
+ import{N as GP}from"./chunk-v94ztjtp.js";import{Td as N}from"./chunk-7jj607dg.js";import{Ce as L,Ee as PP,He as l,Je as d,Le as JP,Ne as QP,Oe as ZP,Pe as $P,Qe as w,ye as r,ze as e}from"./chunk-gfbkrk60.js";import{Se as t,Te as a,Ue as R,We as y,Xe as A,Ze as p}from"./chunk-0z9nqbd0.js";import{uj as q}from"./chunk-dfjmvj3d.js";import{Mj as o,ek as s,fk as n}from"./chunk-pj69j4zp.js";async function qP(){return q().listProviders()}async function EP(P){return q().listModels(P)}import{randomBytes as XP}from"node:crypto";var NP=600000,OP=2048,jP=64,MP=32,HP=67108864,WP=4,D={catalog:"session-surface-catalog:",history:"session-surface-history:",snapshot:"session-surface-snapshot:"},c={session_surface_cursor_invalid:{message:"session surface cursor is invalid",retryable:!1},session_surface_snapshot_changed:{message:"session surface snapshot changed",retryable:!1},session_surface_capacity:{message:"session surface cursor capacity exceeded",retryable:!0},session_surface_unavailable:{message:"session surface cursor registry is unavailable",retryable:!0}};class U extends Error{code;retryable;constructor(P){super(c[P].message);this.code=P;this.name="SessionSurfaceCursorRegistryError",this.retryable=c[P].retryable}}class g{now;tokenSource;tokenCollisionRetries;limitsValue;entries=new Map;chains=new Map;closed=!1;closePromise;totalIssues=0;activeLoads=0;frozenSnapshotBytes=0;retainedPayloadBytes=0;constructor(P={}){if(this.now=P.now??(()=>Date.now()),this.tokenSource=P.tokenSource??(()=>XP(32).toString("base64url")),this.tokenCollisionRetries=P.tokenCollisionRetries??WP,this.limitsValue=_P(P.limits??{}),!Number.isSafeInteger(this.tokenCollisionRetries)||this.tokenCollisionRetries<0)throw Error("tokenCollisionRetries must be a non-negative safe integer")}issueCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=m(P.boundary);if(J.value===void 0)throw new U("session_surface_cursor_invalid");let Q=T(P.request);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Z=this.createToken("catalog"),$=this.now(),G=this.ensureChain(P.chainId,$),Y={token:Z,chainId:P.chainId,kind:"catalog",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,scopeKey:P.scopeKey,epoch:P.epoch,revision:P.revision,boundary:J.value,boundaryBytes:J.bytes,requestHash:Q,cachedResultBytes:0};return this.storeEntry(G,Y),this.retainedPayloadBytes+=J.bytes,G.retainedPayloadBytes+=J.bytes,Z}issueHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=T(P.request),Q=this.assertSnapshotIssuableForHistory(P);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:0,chainId:P.chainId});let Z=this.createToken("history"),$=this.now(),G=this.ensureChain(P.chainId,$);this.touch(Q);let Y={token:Z,chainId:P.chainId,kind:"history",expiresAt:$+this.limitsValue.idleTtlMs,lastAccessAt:$,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,nextSequence:P.nextSequence,snapshotToken:P.snapshotToken,requestHash:J,cachedResultBytes:0};return this.storeEntry(G,Y),Z}issueSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=P.frozenSnapshot===void 0?{value:void 0,bytes:0}:m(P.frozenSnapshot);this.ensureCapacity({requestedEntries:1,requestedRetainedBytes:J.bytes,chainId:P.chainId});let Q=this.createToken("snapshot"),Z=this.now(),$=this.ensureChain(P.chainId,Z),G={token:Q,chainId:P.chainId,kind:"snapshot",expiresAt:Z+this.limitsValue.idleTtlMs,lastAccessAt:Z,locatorDigest:P.locatorDigest,transcriptFingerprint:P.transcriptFingerprint,frozenBytes:J.bytes,frozenSnapshot:J.value};return this.storeEntry($,G),this.frozenSnapshotBytes+=J.bytes,this.retainedPayloadBytes+=J.bytes,$.frozenSnapshotBytes+=J.bytes,$.retainedPayloadBytes+=J.bytes,Q}async redeemCatalogCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"catalog");if(J.scopeKey!==P.scopeKey)throw new U("session_surface_cursor_invalid");if(J.epoch!==P.epoch||J.revision!==P.revision)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");if(this.touch(J),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startCatalogLoad(J,P.loader)}async redeemHistoryCursor(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"history");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_snapshot_changed");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");if(J.requestHash!==T(P.request))throw new U("session_surface_cursor_invalid");let Q=this.resolveHistorySnapshot(J);if(this.touch(J),this.touch(Q),J.cachedResult!==void 0)return W(J.cachedResult);if(J.activeLoad)return this.cloneActiveLoadResult(J.activeLoad);return this.startHistoryLoad(J,Q,P.loader)}async assertSnapshotToken(P){this.assertAvailable(),this.cleanup();let J=this.getEntry(P.token,"snapshot");if(J.locatorDigest!==P.locatorDigest)throw new U("session_surface_cursor_invalid");if(J.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return this.touch(J),{chainId:J.chainId,locatorDigest:J.locatorDigest,transcriptFingerprint:J.transcriptFingerprint,frozenBytes:J.frozenBytes,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)}}completeChain(P){this.cleanup();let J=this.chains.get(P);if(!J)return;J.completed=!0,J.lastAccessAt=this.now()}stats(){this.cleanup();let P=0;for(let J of this.chains.values())if(J.completed)P+=1;return{closed:this.closed,chainCount:this.chains.size,activeChains:this.chains.size-P,completedChains:P,entryCount:this.entries.size,activeLoads:this.activeLoads,frozenSnapshotBytes:this.frozenSnapshotBytes,retainedPayloadBytes:this.retainedPayloadBytes,totalIssues:this.totalIssues,limits:{...this.limitsValue}}}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;let J=[];for(let Q of this.entries.values())if((Q.kind==="catalog"||Q.kind==="history")&&Q.activeLoad)J.push(Q.activeLoad.promise),Q.activeLoad.controller.abort(_());return this.closePromise=Promise.allSettled(J).then(()=>{this.entries.clear(),this.chains.clear(),this.activeLoads=0,this.frozenSnapshotBytes=0,this.retainedPayloadBytes=0}),this.closePromise}startCatalogLoad(P,J){let Q=this.requireChain(P.chainId),Z=new AbortController;this.activeLoads+=1,Q.activeLoads+=1;let $=Promise.resolve().then(()=>J({boundary:W(P.boundary)},Z.signal)).then((G)=>{return this.assertLoadAvailable(Z.signal),this.admitCachedResult(P,G)}).catch((G)=>{if(this.closed||Z.signal.aborted)throw _();throw G}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Q.activeLoads-=1});return P.activeLoad={controller:Z,promise:$},this.cloneActiveLoadResult(P.activeLoad)}startHistoryLoad(P,J,Q){let Z=this.requireChain(P.chainId),$=new AbortController;this.activeLoads+=1,Z.activeLoads+=1;let G=Promise.resolve().then(()=>Q({nextSequence:P.nextSequence,frozenSnapshot:J.frozenSnapshot===void 0?void 0:W(J.frozenSnapshot)},$.signal)).then((Y)=>{return this.assertLoadAvailable($.signal),this.admitCachedResult(P,Y)}).catch((Y)=>{if(this.closed||$.signal.aborted)throw _();throw Y}).finally(()=>{P.activeLoad=void 0,this.activeLoads-=1,Z.activeLoads-=1});return P.activeLoad={controller:$,promise:G},this.cloneActiveLoadResult(P.activeLoad)}resolveHistorySnapshot(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}assertSnapshotIssuableForHistory(P){let J=P.snapshotToken;if(E(J)!=="snapshot")throw new U("session_surface_snapshot_changed");let Q=this.entries.get(J);if(!Q||Q.kind!=="snapshot")throw new U("session_surface_snapshot_changed");if(Q.expiresAt<=this.now())throw this.removeEntry(Q),new U("session_surface_snapshot_changed");if(Q.chainId!==P.chainId||Q.locatorDigest!==P.locatorDigest||Q.transcriptFingerprint!==P.transcriptFingerprint)throw new U("session_surface_snapshot_changed");return Q}requireChain(P){let J=this.chains.get(P);if(!J)throw new U("session_surface_cursor_invalid");return J}assertLoadAvailable(P){if(this.closed||P.aborted)throw _()}getEntry(P,J){if(E(P)!==J)throw new U("session_surface_cursor_invalid");let Z=this.entries.get(P);if(!Z)throw new U("session_surface_cursor_invalid");if(Z.kind!==J)throw new U("session_surface_cursor_invalid");if(Z.expiresAt<=this.now()&&!f(Z))throw this.removeEntry(Z),new U("session_surface_cursor_invalid");return Z}touch(P){let J=this.now();P.lastAccessAt=J,P.expiresAt=J+this.limitsValue.idleTtlMs;let Q=this.chains.get(P.chainId);if(Q)Q.lastAccessAt=J}storeEntry(P,J){if(P.tokens.size>=this.limitsValue.maxEntriesPerChain)throw new U("session_surface_capacity");this.entries.set(J.token,J),P.tokens.add(J.token),P.completed=!1,P.lastAccessAt=J.lastAccessAt,P.issueCount+=1,this.totalIssues+=1}ensureChain(P,J){let Q=this.chains.get(P);if(Q)return Q.lastAccessAt=J,Q;let Z={chainId:P,tokens:new Set,completed:!1,lastAccessAt:J,issueCount:0,activeLoads:0,frozenSnapshotBytes:0,retainedPayloadBytes:0};return this.chains.set(P,Z),Z}cloneActiveLoadResult(P){return P.promise.then((J)=>W(J))}admitCachedResult(P,J){let Q=m(J),Z=this.requireChain(P.chainId),$=Q.bytes-P.cachedResultBytes;if(this.ensureCapacity({requestedEntries:0,requestedRetainedBytes:Math.max(0,$),chainId:P.chainId}),this.releaseCachedResult(P,Z),Q.value===void 0)throw new U("session_surface_cursor_invalid");return P.cachedResult=Q.value,P.cachedResultBytes=Q.bytes,this.retainedPayloadBytes+=Q.bytes,Z.retainedPayloadBytes+=Q.bytes,P.cachedResult}createToken(P){let J=D[P];for(let Q=0;Q<=this.tokenCollisionRetries;Q+=1){this.assertAvailable();let Z=`${J}${this.tokenSource()}`;if(!this.entries.has(Z))return Z}throw new U("session_surface_capacity")}ensureCapacity(P){this.reclaimCompletedChains(P);let J=this.entries.size+P.requestedEntries,Q=this.chains.size+(this.chains.has(P.chainId)?0:1),Z=this.retainedPayloadBytes+P.requestedRetainedBytes,$=(this.chains.get(P.chainId)?.tokens.size??0)+P.requestedEntries;if(J>this.limitsValue.maxEntries||Q>this.limitsValue.maxChains||$>this.limitsValue.maxEntriesPerChain||Z>this.limitsValue.maxFrozenSnapshotBytes)throw new U("session_surface_capacity")}reclaimCompletedChains(P){let J=[...this.chains.values()].filter((Q)=>Q.completed&&Q.activeLoads===0).sort((Q,Z)=>Q.lastAccessAt-Z.lastAccessAt);for(let Q of J){if(!(this.entries.size+P.requestedEntries>this.limitsValue.maxEntries||this.chains.size+(P.chainId!==""&&this.chains.has(P.chainId)?0:1)>this.limitsValue.maxChains||this.retainedPayloadBytes+P.requestedRetainedBytes>this.limitsValue.maxFrozenSnapshotBytes))break;this.removeChain(Q.chainId)}}cleanup(){let P=this.now();for(let J of[...this.entries.values()]){if(J.expiresAt>P||f(J))continue;this.removeEntry(J)}for(let J of[...this.chains.values()])if(J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}removeEntry(P){this.entries.delete(P.token);let J=this.chains.get(P.chainId);if(J){if(J.tokens.delete(P.token),this.releaseEntryRetainedPayload(P,J),J.tokens.size===0&&J.activeLoads===0)this.chains.delete(J.chainId)}else this.releaseEntryRetainedPayload(P)}removeChain(P){let J=this.chains.get(P);if(!J)return;for(let Q of J.tokens){let Z=this.entries.get(Q);if(!Z||f(Z))continue;this.entries.delete(Q),this.releaseEntryRetainedPayload(Z,J)}this.chains.delete(P)}releaseEntryRetainedPayload(P,J){if(P.kind==="snapshot"){if(this.frozenSnapshotBytes-=P.frozenBytes,this.retainedPayloadBytes-=P.frozenBytes,J)J.frozenSnapshotBytes-=P.frozenBytes,J.retainedPayloadBytes-=P.frozenBytes;return}if(P.kind==="catalog"){if(this.retainedPayloadBytes-=P.boundaryBytes,J)J.retainedPayloadBytes-=P.boundaryBytes}this.releaseCachedResult(P,J)}releaseCachedResult(P,J){if(P.cachedResultBytes===0){P.cachedResult=void 0;return}if(this.retainedPayloadBytes-=P.cachedResultBytes,J)J.retainedPayloadBytes-=P.cachedResultBytes;P.cachedResult=void 0,P.cachedResultBytes=0}assertAvailable(){if(this.closed)throw _()}}function E(P){if(P.startsWith(D.catalog))return"catalog";if(P.startsWith(D.history))return"history";if(P.startsWith(D.snapshot))return"snapshot";return}function f(P){return P.kind!=="snapshot"&&P.activeLoad!==void 0}function _P(P){let J={idleTtlMs:P.idleTtlMs??NP,maxEntries:P.maxEntries??OP,maxChains:P.maxChains??jP,maxEntriesPerChain:P.maxEntriesPerChain??MP,maxFrozenSnapshotBytes:P.maxFrozenSnapshotBytes??HP};for(let Q of Object.values(J))if(!Number.isSafeInteger(Q)||Q<=0)throw Error("session surface cursor registry limits must be positive safe integers");return J}function _(){return new U("session_surface_unavailable")}function T(P){return B(W(P))}function W(P){try{return S(P,new Set)}catch{throw new U("session_surface_cursor_invalid")}}function S(P,J){if(P===null)return null;if(typeof P==="string"||typeof P==="boolean")return P;if(typeof P==="number"){if(!Number.isFinite(P))throw Error("invalid number");return P}if(typeof P>"u"||typeof P==="function"||typeof P==="symbol"||typeof P==="bigint")throw Error("invalid JSON type");if(!P||typeof P!=="object")throw Error("invalid JSON value");if(J.has(P))throw Error("cycle");J.add(P);try{if(Array.isArray(P)){let $=[];for(let G=0;G<P.length;G+=1){if(!(G in P))throw Error("sparse array");$.push(S(P[G],J))}return $}if(Object.getOwnPropertySymbols(P).length>0)throw Error("symbol keys");let Q=Object.getPrototypeOf(P);if(Q!==Object.prototype&&Q!==null)throw Error("non-plain object");let Z={};for(let $ of Object.keys(P)){let G=Reflect.get(P,$);if(G===void 0)throw Error("undefined object value");Z[$]=S(G,J)}return Z}finally{J.delete(P)}}function B(P){if(P===null)return"null";if(typeof P==="string"||typeof P==="number")return JSON.stringify(P);if(typeof P==="boolean")return P?"true":"false";if(Array.isArray(P))return`[${P.map((Q)=>B(Q)).join(",")}]`;return`{${Object.keys(P).sort().map((Q)=>`${JSON.stringify(Q)}:${B(P[Q])}`).join(",")}}`}function m(P,J={}){if(P===void 0){if(J.allowUndefined)return{value:void 0,bytes:0};throw new U("session_surface_cursor_invalid")}let Q=W(P);return{value:Q,bytes:Buffer.byteLength(B(Q),"utf8")}}import{createHash as C,randomBytes as F}from"node:crypto";import FP from"node:path";var YP=50,zP=100,AP=16,TP=1e4,DP=16777216;class z extends Error{code;retryable;constructor(P){let J=CP(P);super(J.message);this.code=P;this.name="SessionSurfaceServiceError",this.retryable=J.retryable}}class BP{database;registry;epoch;maxConcurrentOperations;activeControllers=new Set;activeOperations=new Set;closed=!1;closePromise;concurrentOperations=0;constructor(P={}){if(this.database=P.database,this.registry=P.cursorRegistry??new g(P.cursorRegistryOptions),this.epoch=P.epochSource?.()??`session-surface-epoch:${F(32).toString("base64url")}`,this.maxConcurrentOperations=P.maxConcurrentOperations??AP,!Number.isSafeInteger(this.maxConcurrentOperations)||this.maxConcurrentOperations<1||this.maxConcurrentOperations>256)throw Error("maxConcurrentOperations must be an integer from 1 to 256")}async listPage(P={}){return this.runOperation(async(J)=>{let Q=K(P.limit),Z=P.archived??!1,$={archived:Z,limit:Q,workspaceKind:P.workspaceKind??null},G=JSON.stringify([Z,P.workspaceKind??null]),Y=await this.requireDatabase();if(J.throwIfAborted(),!Y)return this.listFallbackPage($,G,J,P.cursor);if(await this.syncAllSurfaces(Y,J),P.cursor){let V=String(ZP(Y));return this.registry.redeemCatalogCursor({token:P.cursor,scopeKey:G,epoch:this.epoch,revision:V,request:$,loader:async({boundary:X})=>{let O=KP(X);return this.loadCatalogPage(Y,$,G,V,O,O.chainId,J)}})}return this.loadCatalogPage(Y,$,G,void 0,void 0,void 0,J)})}async open(P,J={}){return this.runOperation((Q)=>this.openInternal(P,J,Q))}async historyPage(P,J){return this.runOperation(async(Q)=>{let Z=I(P),$=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.readFallbackHistoryPage(Z,J,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:1}),X=x(Z);await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint});let O={expectedSnapshot:J.expectedSnapshot,limit:$},j=await this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint,request:O,loader:async({nextSequence:M})=>{let H=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,beforeSequence:M,limit:$});return this.publicHistoryPage({history:H,snapshot:J.expectedSnapshot,chainId:(await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:X,transcriptFingerprint:V.transcriptFingerprint})).chainId,locatorDigest:X,limit:$})}});return A.parse(j)})}async fork(P){return this.runOperation(async(J)=>{let Q=I(P),Z=await this.requireDatabase(),$=Z?await this.resolveFromProjectionAfterSync(Z,Q,J):await this.resolveFallback(Q,J);if($.candidate.summary.archivedAt)throw new z("session_surface_read_only");J.throwIfAborted();let G=await N.forkSession(Q.sessionId,{sourceProjectPath:$.candidate.projectPath,targetProjectPath:$.candidate.projectPath,...$.remoteCandidate?{remote:{expectedDescriptor:$.remoteCandidate.descriptor}}:{}}),Y=$.remoteCandidate?{version:2,sessionId:G.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.candidate.publicWorkspaceRef}}:{version:2,sessionId:G.sessionId,workspace:{kind:"local",projectPath:$.candidate.projectPath}};return Z?this.openInternal(Y,{},J):this.openFallback(Y,YP,J)})}async resolveFromProjectionAfterSync(P,J,Q){return await this.syncForLocator(P,J,Q),this.resolveFromProjection(P,J,Q)}async close(P){if(this.closePromise)return this.closePromise;this.closed=!0;for(let J of this.activeControllers)J.abort(new z("session_surface_unavailable"));return this.closePromise=Promise.allSettled([...this.activeOperations,this.registry.close()]).then(()=>{return}),this.closePromise}async openInternal(P,J={},Q){let Z=I(P),$=K(J.limit);if(J.cursor!==void 0||J.expectedSnapshot!==void 0)throw new z("invalid_session_surface_request");let G=await this.requireDatabase();if(!G)return this.openFallback(Z,$,Q);await this.syncForLocator(G,Z,Q);let Y=await this.resolveFromProjection(G,Z,Q),V=w(G,{sourceKind:Y.candidate.sourceKind,projectPath:Y.candidate.projectPath,sessionId:Y.candidate.sessionId,limit:$}),X=`history-chain:${F(16).toString("base64url")}`,O=x(Z),j=this.registry.issueSnapshotToken({chainId:X,locatorDigest:O,transcriptFingerprint:V.transcriptFingerprint}),M={session:this.toSummary(Y),history:this.publicHistoryPage({history:V,snapshot:j,chainId:X,locatorDigest:O,limit:$})};return p.parse(M)}runOperation(P){if(this.assertAvailable(),this.concurrentOperations>=this.maxConcurrentOperations)throw new z("session_surface_capacity");let J=new AbortController;this.activeControllers.add(J),this.concurrentOperations+=1;let Q;return Q=Promise.resolve().then(()=>P(J.signal)).then((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");return Z}).catch((Z)=>{if(J.signal.aborted||this.closed)throw new z("session_surface_unavailable");throw kP(Z)}).finally(()=>{this.activeControllers.delete(J),this.activeOperations.delete(Q),this.concurrentOperations-=1}),this.activeOperations.add(Q),Q}async loadCatalogPage(P,J,Q,Z,$,G,Y){let V=$P(P,{archived:J.archived,limit:J.limit,...J.workspaceKind?{workspaceKind:J.workspaceKind}:{},...$?{boundary:$}:{}}),X=String(V.revision);if(Z!==void 0&&Z!==X)throw new z("session_surface_snapshot_changed");let O=G??`catalog-chain:${F(16).toString("base64url")}`,j={sessions:await Promise.all(V.sessions.map(async(M)=>this.toSummary(await this.resolveCandidate(M,Y)))),...V.nextBoundary?{nextCursor:this.registry.issueCatalogCursor({chainId:O,scopeKey:Q,epoch:this.epoch,revision:X,boundary:{...V.nextBoundary,chainId:O},request:J})}:{}};if(!V.nextBoundary)this.registry.completeChain(O);return y.parse(j)}publicHistoryPage(P){let J=h(P.history.messages,L()),Q={messages:J.messages,snapshot:P.snapshot,truncated:P.history.hasOlder||J.truncated||J.messages.some((Z)=>Z.truncated===!0),...P.history.hasOlder&&P.history.nextSequence!==void 0?{olderCursor:this.registry.issueHistoryCursor({chainId:P.chainId,locatorDigest:P.locatorDigest,transcriptFingerprint:P.history.transcriptFingerprint,nextSequence:P.history.nextSequence,snapshotToken:P.snapshot,request:{expectedSnapshot:P.snapshot,limit:P.limit}})}:{}};if(!P.history.hasOlder)this.registry.completeChain(P.chainId);return A.parse(Q)}async syncForLocator(P,J,Q){if(Q?.throwIfAborted(),J.workspace.kind==="local"){await l(P,J.sessionId,J.workspace.projectPath,N.projectionDeriverForSearch(),void 0,"local",Q);return}await d(P,N.projectionDeriverForSearch(),Q)}async syncAllSurfaces(P,J){let Q=N.projectionDeriverForSearch(),Z=await N.listValidatedLocalSurfaceCandidates(J),$=new Set(Z.map((Y)=>`${Y.projectPath}\x00${Y.sessionId}`)),G=P.prepare("SELECT project_path, session_id FROM sessions WHERE source_kind='local'").all();for(let Y of G)if(!$.has(`${Y.project_path}\x00${Y.session_id}`))JP(P,Y.session_id,Y.project_path,"local");for(let Y of Z)J?.throwIfAborted(),await l(P,Y.sessionId,Y.projectPath,Q,void 0,"local",J);await d(P,Q,J)}async listFallbackPage(P,J,Q,Z){if(Z)return this.registry.redeemCatalogCursor({token:Z,scopeKey:J,epoch:this.epoch,revision:"fallback",request:P,loader:async({boundary:G})=>{let Y=LP(G);return this.pageFallbackCatalog(Y.entries,P,J,Y.chainId)}});let $=await this.loadFallbackCatalog(P,Q);return this.pageFallbackCatalog($,P,J,`catalog-fallback:${F(16).toString("base64url")}`)}async loadFallbackCatalog(P,J){let Q=[];if(P.workspaceKind!=="acp-remote")for(let $ of await N.listValidatedLocalSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedLocalSurfaceSnapshot($.sessionId,$.projectPath,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"local",projectPath:$.projectPath}},summary:Y})}if(P.workspaceKind!=="local")for(let $ of await N.listValidatedRemoteSurfaceCandidates(J)){J?.throwIfAborted();let Y=(await N.readValidatedRemoteSurfaceSnapshot($,J)).summary;if(Boolean(Y.archivedAt)!==P.archived)continue;Q.push({locator:{version:2,sessionId:$.sessionId,workspace:{kind:"acp-remote",workspaceRef:$.workspaceRef}},summary:Y})}Q.sort(IP);let Z=Buffer.byteLength(JSON.stringify(Q));if(Q.length>TP||Z>DP)throw new z("session_surface_capacity");return Q}async pageFallbackCatalog(P,J,Q,Z){let $=P.slice(0,J.limit),G=P.slice($.length),V={sessions:$.map((X)=>R.parse({locator:X.locator,...X.summary,capabilities:X.locator.workspace.kind==="local"?UP(Boolean(X.summary.archivedAt)):RP(Boolean(X.summary.archivedAt))})),...G.length>0?{nextCursor:this.registry.issueCatalogCursor({chainId:Z,scopeKey:Q,epoch:this.epoch,revision:"fallback",boundary:{chainId:Z,entries:G},request:J})}:{}};if(G.length===0)this.registry.completeChain(Z);return y.parse(V)}async openFallback(P,J,Q){let Z=await this.resolveFallback(P,Q),$=Z.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(Z.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(Z.candidate.sessionId,Z.candidate.projectPath,Q),G=e($.entries,{...Z.remoteCandidate?r(Z.remoteCandidate.hostStateRoot,Z.remoteCandidate.descriptor):{privateRoots:[]},bladeStorageRoots:[o()]}),Y=h(G.slice(-J),L()),V=`history-fallback:${F(16).toString("base64url")}`,X=x(P),O=C("sha256").update(JSON.stringify($.entries)).digest("hex"),j=this.registry.issueSnapshotToken({chainId:V,locatorDigest:X,transcriptFingerprint:O,frozenSnapshot:G}),M={session:this.toSummary(Z),history:A.parse({messages:Y.messages,snapshot:j,truncated:Y.messages.length<G.length||Y.truncated||Y.messages.some((H)=>H.truncated===!0),...G.length>Y.messages.length&&Y.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:V,locatorDigest:X,transcriptFingerprint:O,nextSequence:v(Y.messages[0].id),snapshotToken:j,request:{expectedSnapshot:j,limit:J}})}:{}})};if(G.length<=Y.messages.length)this.registry.completeChain(V);return p.parse(M)}async readFallbackHistoryPage(P,J,Q){let Z=K(J.limit);if(!J.cursor||!J.expectedSnapshot)throw new z("invalid_session_surface_request");let $=x(P),G=await this.resolveFallback(P,Q),Y=G.remoteCandidate?await N.readValidatedRemoteSurfaceSnapshot(G.remoteCandidate,Q):await N.readValidatedLocalSurfaceSnapshot(G.candidate.sessionId,G.candidate.projectPath,Q),V=C("sha256").update(JSON.stringify(Y.entries)).digest("hex");await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V});let X={expectedSnapshot:J.expectedSnapshot,limit:Z};return this.registry.redeemHistoryCursor({token:J.cursor,locatorDigest:$,transcriptFingerprint:V,request:X,loader:async({nextSequence:O,frozenSnapshot:j})=>{let M=xP(j).filter((b)=>v(b.id)<O),H=h(M.slice(-Z),L()),u=await this.registry.assertSnapshotToken({token:J.expectedSnapshot,locatorDigest:$,transcriptFingerprint:V}),k=H.messages.length<M.length,VP={messages:H.messages,snapshot:J.expectedSnapshot,truncated:k||H.truncated||H.messages.some((b)=>b.truncated===!0),...k&&H.messages[0]?{olderCursor:this.registry.issueHistoryCursor({chainId:u.chainId,locatorDigest:$,transcriptFingerprint:V,nextSequence:v(H.messages[0].id),snapshotToken:J.expectedSnapshot,request:X})}:{}};if(!k)this.registry.completeChain(u.chainId);return A.parse(VP)}})}async resolveFallback(P,J){let Q=[];for(let G of[!1,!0]){let Y={archived:G,limit:zP,workspaceKind:P.workspace.kind};Q.push(...(await this.loadFallbackCatalog(Y,J)).filter((V)=>JSON.stringify(V.locator)===JSON.stringify(P)))}if(Q.length!==1)throw new z("session_surface_not_found");let Z=Q[0],$;if(P.workspace.kind==="acp-remote"){let G=P.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(J)).find((Y)=>Y.sessionId===P.sessionId&&Y.workspaceRef===G),!$)throw new z("workspace_binding_mismatch")}return{candidate:{sourceKind:P.workspace.kind,projectPath:P.workspace.kind==="local"?P.workspace.projectPath:$.hostStateRoot,sessionId:P.sessionId,...P.workspace.kind==="acp-remote"?{publicWorkspaceRef:P.workspace.workspaceRef}:{},publicWorkspaceSortKey:"",surfaceDigest:i(Z),transcriptFingerprint:i(Z),lastMessageTime:Z.summary.lastMessageTime,sessionSortKey:"",summary:Z.summary},...$?{remoteCandidate:$}:{}}}async resolveFromProjection(P,J,Q){let Z=QP(P,J.sessionId).filter((G)=>J.workspace.kind==="local"?G.sourceKind==="local"&&G.projectPath===FP.resolve(J.workspace.projectPath):G.sourceKind==="acp-remote"&&G.publicWorkspaceRef===J.workspace.workspaceRef);if(Z.length!==1)throw new z(Z.length===0?"session_surface_not_found":"workspace_binding_mismatch");let $;if(J.workspace.kind==="acp-remote"){let G=J.workspace.workspaceRef;if($=(await N.listValidatedRemoteSurfaceCandidates(Q)).filter((Y)=>Y.sessionId===J.sessionId&&Y.workspaceRef===G),$.length===0)throw new z("workspace_binding_mismatch");if($.length>1)throw new z("session_surface_state_invalid")}return $?{candidate:Z[0],remoteCandidate:$[0]}:{candidate:Z[0]}}async resolveCandidate(P,J){if(P.sourceKind==="local")return{candidate:P};let Q=(await N.listValidatedRemoteSurfaceCandidates(J)).filter((Z)=>Z.sessionId===P.sessionId&&Z.workspaceRef===P.publicWorkspaceRef);if(Q.length!==1)throw new z(Q.length===0?"workspace_binding_mismatch":"session_surface_state_invalid");return{candidate:P,remoteCandidate:Q[0]}}toSummary(P){let J=P.candidate,Q=J.sourceKind==="local"?{version:2,sessionId:J.sessionId,workspace:{kind:"local",projectPath:J.projectPath}}:{version:2,sessionId:J.sessionId,workspace:{kind:"acp-remote",workspaceRef:J.publicWorkspaceRef}};return R.parse({locator:Q,...J.summary,capabilities:this.capabilitiesFor(P)})}capabilitiesFor(P){let J=P.candidate.summary.archivedAt!==void 0;if(!P.remoteCandidate)return{connection:"local",history:{read:!0,fork:!J},turn:J?{start:!1,reason:"archived"}:{start:!0},files:J?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:J?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}};return{connection:GP.getRemoteSurfaceOwnerSnapshot(P.candidate.sessionId,P.remoteCandidate.descriptor).connection,history:{read:!0,fork:!J},turn:{start:!1,reason:J?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:J?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:J?"archived":"history-only"}}}async requireDatabase(){if(this.database===null)return null;return this.database??await PP()}assertAvailable(){if(this.closed)throw new z("session_surface_unavailable")}}function K(P){let J=P??YP;if(!Number.isSafeInteger(J)||J<1||J>zP)throw new z("invalid_session_surface_request");return J}function I(P){try{let J=t.parse(P);if(!n(J.sessionId))throw Error("invalid");if(J.workspace.kind==="local"){if(s(J.workspace.projectPath)!==J.workspace.projectPath)throw Error("invalid")}return J}catch{throw new z("invalid_session_locator")}}function x(P){return C("sha256").update("session-surface-locator-v2\x00").update(JSON.stringify(P)).digest("hex")}function KP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.lastMessageTime!=="string"||J.sourceKind!=="local"&&J.sourceKind!=="acp-remote"||typeof J.publicWorkspaceSortKey!=="string"||typeof J.sessionSortKey!=="string"||typeof J.chainId!=="string"||!J.chainId)throw new z("session_surface_cursor_invalid");return{lastMessageTime:J.lastMessageTime,sourceKind:J.sourceKind,publicWorkspaceSortKey:J.publicWorkspaceSortKey,sessionSortKey:J.sessionSortKey,chainId:J.chainId}}function h(P,J){let Q=[];for(let Z=P.length-1;Z>=0;Z-=1){let $=P[Z];if(!$)continue;let G=[$,...Q];if(Q.length>0&&Buffer.byteLength(JSON.stringify(G))>J)break;Q.unshift($)}return{messages:Q,truncated:Q.length<P.length}}function v(P){let J=/^surface-message:([0-9]+):/.exec(P),Q=J?Number(J[1]):Number.NaN;if(!Number.isSafeInteger(Q)||Q<=0)throw new z("session_surface_state_invalid");return Q}function xP(P){if(!Array.isArray(P))throw new z("session_surface_snapshot_changed");return P.map((J)=>{try{return a.parse(J)}catch{throw new z("session_surface_snapshot_changed")}})}function LP(P){if(!P||typeof P!=="object"||Array.isArray(P))throw new z("session_surface_cursor_invalid");let J=P;if(typeof J.chainId!=="string"||J.chainId.length===0||!Array.isArray(J.entries))throw new z("session_surface_cursor_invalid");let Q=J.entries.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new z("session_surface_cursor_invalid");let $=Z;return{locator:I($.locator),summary:wP($.summary)}});return{chainId:J.chainId,entries:Q}}function wP(P){let J={version:2,sessionId:"placeholder",workspace:{kind:"local",projectPath:"/"}},Q=R.parse({...P&&typeof P==="object"&&!Array.isArray(P)?P:{},locator:J,capabilities:UP(!1)}),{locator:Z,capabilities:$,...G}=Q;return G}function IP(P,J){if(P.summary.lastMessageTime>J.summary.lastMessageTime)return-1;if(P.summary.lastMessageTime<J.summary.lastMessageTime)return 1;if(P.locator.workspace.kind!==J.locator.workspace.kind)return P.locator.workspace.kind==="local"?-1:1;let Q=P.locator.workspace.kind==="local"?P.locator.workspace.projectPath:P.locator.workspace.workspaceRef,Z=J.locator.workspace.kind==="local"?J.locator.workspace.projectPath:J.locator.workspace.workspaceRef;if(Q<Z)return-1;if(Q>Z)return 1;return P.locator.sessionId<J.locator.sessionId?-1:P.locator.sessionId>J.locator.sessionId?1:0}function i(P){return C("sha256").update("session-surface-fallback-entry\x00").update(JSON.stringify(P)).digest("hex")}function UP(P){return{connection:"local",history:{read:!0,fork:!P},turn:P?{start:!1,reason:"archived"}:{start:!0},files:P?{readText:!1,writeText:!1,browse:"none",reason:"archived"}:{readText:!0,writeText:!0,browse:"tree"},terminal:P?{mode:"none",owner:"none",reason:"archived"}:{mode:"interactive",owner:"local"}}}function RP(P){return{connection:"offline",history:{read:!0,fork:!P},turn:{start:!1,reason:P?"archived":"history-only"},files:{readText:!1,writeText:!1,browse:"none",reason:P?"archived":"history-only"},terminal:{mode:"none",owner:"none",reason:P?"archived":"history-only"}}}function CP(P){if(P==="session_surface_cursor_invalid")return{message:"Session surface cursor is invalid",retryable:!1};if(P==="session_surface_snapshot_changed")return{message:"Session surface snapshot changed",retryable:!1};if(P==="session_surface_state_invalid")return{message:"Session surface state is invalid",retryable:!1};if(P==="session_surface_capability_unavailable")return{message:"Session surface capability is unavailable",retryable:!1};if(P==="session_surface_unavailable")return{message:"Session surface is unavailable",retryable:!0};if(P==="session_surface_not_found")return{message:"Session surface was not found",retryable:!1};if(P==="workspace_binding_mismatch")return{message:"Session workspace binding changed",retryable:!1};if(P==="session_surface_read_only")return{message:"Session surface is read only",retryable:!1};if(P==="session_surface_capacity")return{message:"Session surface capacity is exhausted",retryable:!0};if(P==="invalid_session_locator")return{message:"Session locator is invalid",retryable:!1};return{message:"Session surface request is invalid",retryable:!1}}function kP(P){if(P instanceof z)return P;if(P&&typeof P==="object"&&"code"in P&&typeof P.code==="string"){let J=P.code;if(J==="session_surface_cursor_invalid"||J==="session_surface_snapshot_changed"||J==="session_surface_capacity"||J==="session_surface_unavailable"||J==="session_surface_state_invalid")return new z(J);if(J==="acp_remote_workspace_state_invalid")return new z("session_surface_state_invalid")}return P instanceof Error?P:new z("session_surface_state_invalid")}
2
+ export{qP as e,EP as f,g,z as h,BP as i};
@@ -0,0 +1 @@
1
+ import{eg as a,fg as b,gg as c,hg as d}from"./chunk-8a6nrqdc.js";import"./chunk-hhg1zcbq.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import"./chunk-v5hzk7j2.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
@@ -1,2 +1,2 @@
1
1
  var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
2
- export{f as $i,p as aj,u as bj,S as cj,c as dj,l as ej};
2
+ export{f as vj,p as wj,u as xj,S as yj,c as zj,l as Aj};
@@ -1,4 +1,4 @@
1
- import{$b as Xt,ac as En,bc as yn,cc as bn}from"./chunk-sca5q3tt.js";import{Kg as Bt}from"./chunk-p2rxrxct.js";import{$g as dn,Pg as xt,Qg as vi,Rg as sn,Sg as zt,Tg as U,Ug as en,Vg as gt,Wg as mt,Yg as rn,Zg as Tn,_g as B,ah as on,bh as pn,ch as lt,dh as un,eh as cn,fh as Mn,hh as S,kh as wn,lh as Gt,mh as Ut,nh as h,oh as Ht}from"./chunk-6v2hhgka.js";import{ei as X,gi as x}from"./chunk-96w8ay2h.js";import{si as It}from"./chunk-ted1hyvb.js";import{gj as tn,hj as nn}from"./chunk-b408cqg1.js";import{Wj as ns}from"./chunk-mm05y2c5.js";import{EventEmitter as fs}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 Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{cc as Xt,dc as En,ec as yn,fc as bn}from"./chunk-77efqpdc.js";import{eh as Bt}from"./chunk-r9tawy93.js";import{Ah as cn,Bh as Mn,Dh as S,Gh as wn,Hh as Gt,Ih as Ut,Jh as h,Kh as Ht,jh as xt,kh as vi,lh as sn,mh as zt,nh as U,oh as en,ph as gt,qh as mt,sh as rn,th as Tn,uh as B,vh as dn,wh as on,xh as pn,yh as lt,zh as un}from"./chunk-hhg1zcbq.js";import{Ii as It}from"./chunk-44jtpg8y.js";import{Ji as X,Li as x}from"./chunk-sj1dzeta.js";import{Cj as tn,Dj as nn}from"./chunk-v5hzk7j2.js";import{rk as ns}from"./chunk-zkzhm39s.js";import{EventEmitter as fs}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 Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;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 s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}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=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -22,4 +22,4 @@ ${c}
22
22
 
23
23
  Preview (tail):
24
24
  ${M}`,u=!0}return{isError:t.isError===!0,llmContent:o,metadata:{contentCount:t.content.length,textBytes:n.textBytes,structuredBytes:r?.bytes??0,artifactCount:e.length,truncated:u,binaryOmitted:n.binaryBytes>0,artifacts:e}}}function yt(t){let i=t instanceof Error?t.message:String(t),n=gn(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",Cn)}function Tt(t,i,n,s,e){let r=n.inputSchema&&typeof n.inputSchema==="object"?x.Unsafe(n.inputSchema):x.Any(),o=s||n.name;return jt({name:o,displayName:`${i}: ${n.name}`,kind:"execute",schema:r,description:{short:n.description||`MCP Tool: ${n.name}`,important:[`From MCP server: ${i}`,"Executes external tools; user confirmation required",...n.taskSupport==="required"?["This tool requires MCP task execution and returns an opaque task ID.","Use TaskOutput to retrieve the eventual result."]:[]]},category:"MCP tool",tags:["mcp","external",i],async execute(u,d){try{let p={...d.confirmationHandler?{confirmationHandler:d.confirmationHandler}:{},...d.mcpSamplingHandler?{samplingHandler:d.mcpSamplingHandler}:{},...d.onProgressUpdate?{progressHandler:d.onProgressUpdate}:{},...d.sessionId?{sessionId:d.sessionId}:{},...d.workspaceRoot?{workspaceRoot:d.workspaceRoot}:{},...d.permissionMode?{permissionMode:d.permissionMode}:{}};if(n.taskSupport==="required"){if(!d.sessionId)throw Error("MCP tasks require an active Session");let y=await T.getInstance().start({client:t,serverName:i,toolName:n.name,arguments:u,owner:{sessionId:d.sessionId,projectPath:Un.resolve(d.workspaceRoot||It())},interactionContext:p,signal:d.signal});return{success:!0,llmContent:{task_id:y.taskId,type:"mcp",status:y.status,message:`MCP task started. Use TaskOutput(task_id: "${y.taskId}") to retrieve its result.`},metadata:{summary:`Started MCP task ${y.taskId}`,serverName:i,toolName:n.name,task_id:y.taskId,taskType:"mcp",taskStatus:y.status,background:!0}}}let c=await t.callTool(n.name,u,{...d.signal?{signal:d.signal}:{},...p}),M=await j(c,e),w={summary:`MCP ${n.name} 执行${M.isError?"失败":"成功"}`,serverName:i,toolName:n.name,mcpResult:{isError:M.isError,...M.metadata}};if(M.isError){let y=yt(M.llmContent);return{success:!1,llmContent:y,error:{type:"execution_error",message:y},metadata:w}}return{success:!0,llmContent:M.llmContent,metadata:w}}catch(p){let c=yt(p);return{success:!1,llmContent:`MCP tool execution failed: ${c}`,error:{type:"execution_error",message:c},metadata:{summary:`MCP ${n.name} 执行失败`,serverName:i,toolName:n.name}}}}})}import{realpathSync as ss}from"node:fs";import Ni from"node:path";import{pathToFileURL as es}from"node:url";import{Client as rs}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as ds}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as os}from"@modelcontextprotocol/sdk/client/stdio.js";import{CallToolResultSchema as St,CreateMessageRequestSchema as ps,ElicitationCompleteNotificationSchema as us,ElicitRequestSchema as cs,ErrorCode as R,ListRootsRequestSchema as Ms,LoggingMessageNotificationSchema as ws,McpError as P,ResourceUpdatedNotificationSchema as ys,TaskStatusNotificationSchema as Ts}from"@modelcontextprotocol/sdk/types.js";import{EventEmitter as Es}from"events";import bs from"open";import{EventEmitter as Bn}from"events";function Et(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t)||!Number.isInteger(t)||t<s||t>e)throw Error(`${n} must be an integer between ${s} and ${e}`);return t}class bt extends 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:Et(i.interval,30000,"MCP health check interval",10,300000),timeout:Et(i.timeout,1e4,"MCP health check timeout",10,60000),enabled:i.enabled??!1,failureThreshold:Et(i.failureThreshold,3,"MCP health check failureThreshold",1,10)}}start(){if(this.running||!this.config.enabled)return;this.running=!0,this.scheduleNextCheck()}stop(){if(this.running=!1,this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null}scheduleNextCheck(){if(!this.running)return;this.checkTimer=setTimeout(async()=>{this.checkTimer=null,await this.performHealthCheck().catch(()=>{return}),this.scheduleNextCheck()},this.config.interval),this.checkTimer.unref()}async performHealthCheck(){if(this.isChecking)return this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let t=this.client.connectionStatus;if(t==="connected"){await this.client.ping(this.config.timeout),this.consecutiveFailures=0,this.setStatus("healthy");let i={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",i),i}else throw Error(`连接状态异常: ${t}`)}catch(t){this.consecutiveFailures++;let i=t,n;if(this.consecutiveFailures>=this.config.failureThreshold)n="unhealthy",this.emit("unhealthy",this.consecutiveFailures,i),this.client.requestRecovery(i,"health_check");else n="degraded";this.setStatus(n);let s={status:n,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:i};return this.emit("healthCheck",s),s}finally{this.isChecking=!1}}setStatus(t){if(this.currentStatus!==t){let i=this.currentStatus;this.currentStatus=t,this.emit("statusChanged",t,i)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}import{createHash as Xn}from"node:crypto";import{UriTemplate as zn}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";var ti=100,Yn=4096,Dn=65536,ft=1048576,ii=32,ni=65536,oi=4,ht=15000,si=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 pi(t,i){let n=G(t.argument.name,"completion argument name",si),s=ri(t.argument.value,"completion argument value",ei),e,r;if(t.reference.type==="prompt"){let p=G(t.reference.name,"completion prompt name",Fn),c=i.prompts.find((M)=>M.name===p);if(!c)throw Error(`MCP prompt "${p}" is not present in the current catalog`);e=new Set(c.arguments.map((M)=>M.name)),r={type:"ref/prompt",name:p}}else{let p=G(t.reference.uri,"completion resource template URI",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`)}e=new Set(M),r={type:"ref/resource",uri:p}}if(!e.has(n))throw Error(`MCP ${t.reference.type} completion argument "${n}" is not declared`);let o=Object.entries(t.context??{});if(o.length>ii)throw Error(`MCP completion context exceeds ${ii} arguments`);let u=Object.create(null),d=0;for(let[p,c]of o){let M=G(p,"completion context argument name",si);if(wi(M))throw Error(`Unsafe MCP completion context argument "${M}"`);if(!e.has(M))throw Error(`Unknown MCP completion context argument "${M}"`);let w=ri(c,`completion context argument "${M}"`,ei);if(d+=Buffer.byteLength(M)+Buffer.byteLength(w),d>ni)throw Error(`MCP completion context exceeds ${ni} bytes`);u[M]=w}return{ref:r,argument:{name:n,value:s},...o.length>0?{context:{arguments:u}}:{}}}function ui(t){let i=t.completion,n=JSON.stringify(i),s=Buffer.byteLength(n),e=Xn("sha256").update(n).digest("hex"),r=i.values.length,o=[],u=new Set,d=0,p=0,c=r>ti||s>ft;for(let w of i.values.slice(0,ti)){let y=Buffer.byteLength(w),E=Math.max(0,ft-p);if(E===0){c=!0;break}let a=di(w,Math.min(ft,E));if(p+=Buffer.byteLength(a),y>Buffer.byteLength(a))c=!0;let Dt=ci(a),L=di(Dt,Yn);if(Buffer.byteLength(L)<Buffer.byteLength(Dt))c=!0;if(u.has(L))continue;let Ft=Buffer.byteLength(L);if(d+Ft>Dn){c=!0;break}u.add(L),o.push(L),d+=Ft}if(o.length<r)c=!0;let M=i.total!==void 0&&Number.isSafeInteger(i.total)&&i.total>=0?i.total:void 0;return{values:o,...M!==void 0?{total:M}:{},hasMore:i.hasMore===!0||c||M!==void 0&&M>o.length,sourceValueCount:r,sourceBytes:s,projectedBytes:d,sha256:e,truncated:c}}function 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 G(t,i,n){if(typeof t!=="string"||!t||Buffer.byteLength(t)>n)throw Error(`MCP ${i} is invalid`);if(ci(t)!==t||Mi(t))throw Error(`MCP ${i} contains unsafe characters`);if(wi(t))throw Error(`MCP ${i} is unsafe`);return t}function ri(t,i,n){if(typeof t!=="string"||Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);if(Mi(t))throw Error(`MCP ${i} contains control characters`);return t}function Mi(t){return[...t].some((i)=>{let n=i.codePointAt(0)??0;return n<32||n===127})}function wi(t){return["__proto__","constructor","prototype"].includes(t)}function di(t,i){let n=Buffer.from(t);if(n.length<=i)return t;let s=n.subarray(0,Math.max(0,i)).toString("utf8");while(Buffer.byteLength(s)>i)s=s.slice(0,-1);return s}var At=20,_t=300000;function yi(t,i,n,s,e){if(t===void 0)return i;if(typeof t!=="number"||!Number.isFinite(t))throw Error(`${n} must be a finite number`);if(t<s||t>e)throw Error(`${n} must be between ${s} and ${e}`);return t}function H(t,i,n,s,e){let r=yi(t,i,n,s,e);if(!Number.isInteger(r))throw Error(`${n} must be an integer`);return r}function Ti(t){let i=t.recovery;if(i!==void 0&&(i===null||typeof i!=="object"||Array.isArray(i)))throw Error("MCP recovery configuration must be an object");let n=i?.enabled??!0;if(typeof n!=="boolean")throw Error("MCP recovery enabled must be a boolean");let s=H(i?.maxAttempts,5,"MCP recovery maxAttempts",0,20),e=H(i?.initialDelayMs,1000,"MCP recovery initialDelayMs",10,300000),r=H(i?.maxDelayMs,30000,"MCP recovery maxDelayMs",e,300000),o=yi(i?.jitterRatio,0.2,"MCP recovery jitterRatio",0,1),u=H(i?.terminalErrorThreshold,3,"MCP recovery terminalErrorThreshold",1,10);return{enabled:n,maxAttempts:s,initialDelayMs:e,maxDelayMs:r,jitterRatio:o,terminalErrorThreshold:u}}function Ei(t,i,n=Math.random){let s=Math.max(0,i-1),e=Math.min(t.initialDelayMs*2**s,t.maxDelayMs);if(t.jitterRatio===0)return e;let r=Math.min(1,Math.max(0,n())),o=1-t.jitterRatio+2*t.jitterRatio*r;return Math.max(0,Math.round(e*o))}function k(t){let n=(t instanceof Error?t.message:String(t)).replace(/\bhttps?:\/\/[^\s"'`]+/gi,"[redacted-url]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted]").replace(/[\r\n\t]+/g," ").trim();if(Buffer.byteLength(n)<=512)return n;let s=Buffer.from(n).subarray(0,512).toString("utf8");while(Buffer.byteLength(s)>512)s=s.slice(0,-1);return s}function bi(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 fi(t){let n=(t instanceof Error?t.message:String(t)).toLowerCase();return["econnreset","etimedout","epipe","ehostunreach","econnrefused","body timeout error","socket hang up","connection closed","connection terminated","sse stream disconnected","failed to reconnect sse stream","maximum reconnection attempts"].some((s)=>n.includes(s))}function C(t){return new DOMException(String(t||"MCP connection recovery cancelled"),"AbortError")}async function Rt(t,i,n=!0){if(i.aborted)throw C(i.reason);await new Promise((s,e)=>{let o=setTimeout(()=>{i.removeEventListener("abort",u),s()},t);if(n)o.unref();let u=()=>{clearTimeout(o),i.removeEventListener("abort",u),e(C(i.reason))};i.addEventListener("abort",u,{once:!0})})}import{createHash as ai}from"node:crypto";var Pt=100,q=1000,K=1000,W=1000,at=100,hi=64,Z=1048576,_=4194304,A=256,N=8192,g=256,m=16384,Ai=64,Gn=4096,_i=4194304,Ri=128;function $i(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Hn(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n===0||n>=1&&n<=8||n===11||n===12||n>=14&&n<=31||n===127})}function b(t,i,n){if(t===void 0)return;if(i==="description"?Hn(t):$i(t))throw Error(`MCP ${i} contains control characters`);if(Buffer.byteLength(t)>n)throw Error(`MCP ${i} exceeds ${n} bytes`);return t}function f(t,i,n){let s=t.trim();if(!s||s.length>n||$i(s))throw Error(`MCP ${i} is invalid`);return s}function $t(t){return Buffer.byteLength(JSON.stringify(t))}function Ct(t,i){if($t(t)>_i)throw Error(`MCP ${i} catalog exceeds ${_i} bytes`)}function Q(t,i){let n=new Set;for(let s of t){if(n.has(s))throw Error(`MCP ${i} catalog contains duplicate "${s}"`);n.add(s)}}function Ci(t){if(t.length>q)throw Error(`MCP resource catalog exceeds ${q} entries`);let i=t.map((n)=>({uri:f(n.uri,"resource URI",N),name:f(n.name,"resource name",A),...b(n.title,"resource title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource MIME type",g)?{mimeType:n.mimeType}:{},...n.size!==void 0&&Number.isSafeInteger(n.size)&&n.size>=0?{size:n.size}:{}}));return Q(i.map((n)=>n.uri),"resource"),Ct(i,"resource"),i}function ki(t){if(t.length>K)throw Error(`MCP resource template catalog exceeds ${K} entries`);let i=t.map((n)=>({uriTemplate:f(n.uriTemplate,"resource template URI",N),name:f(n.name,"resource template name",A),...b(n.title,"resource template title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},...b(n.mimeType,"resource template MIME type",g)?{mimeType:n.mimeType}:{}}));return Q(i.map((n)=>n.uriTemplate),"resource template"),Ct(i,"resource template"),i}function Oi(t){if(t.length>W)throw Error(`MCP prompt catalog exceeds ${W} entries`);let i=t.map((n)=>{if((n.arguments?.length??0)>Ai)throw Error(`MCP prompt "${n.name}" exceeds ${Ai} arguments`);let s=(n.arguments??[]).map((e)=>{let r=f(e.name,"prompt argument name",A);if(["__proto__","constructor","prototype"].includes(r))throw Error(`MCP prompt argument name "${r}" is unsafe`);return{name:r,...b(e.description,"description",Gn)?{description:e.description}:{},required:e.required===!0}});return Q(s.map((e)=>e.name),`prompt "${n.name}" argument`),{name:f(n.name,"prompt name",A),...b(n.title,"prompt title",A)?{title:n.title}:{},...b(n.description,"description",m)?{description:n.description}:{},arguments:s}});return Q(i.map((n)=>n.name),"prompt"),Ct(i,"prompt"),i}function Pi(t){return ai("sha256").update(JSON.stringify(t)).digest("hex")}function I(t,i,n){let s=new Map(t.map((r)=>[n(r),Pi(r)])),e=new Map(i.map((r)=>[n(r),Pi(r)]));return{added:[...e.keys()].filter((r)=>!s.has(r)).sort(),removed:[...s.keys()].filter((r)=>!e.has(r)).sort(),updated:[...e.keys()].filter((r)=>s.has(r)&&s.get(r)!==e.get(r)).sort()}}function Li(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function kt(t,i,n){if(t.bytes+=i,t.bytes>_)throw Error(`MCP ${n} exceeds ${_} total bytes`)}function Si(t,i,n){if(t.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw Error(`MCP ${i} contains invalid base64`);let s=Buffer.from(t,"base64");if(s.length>_)throw Error(`MCP ${i} exceeds ${_} decoded bytes`);return kt(n,s.length,i),{size:s.length,sha256:ai("sha256").update(s).digest("hex"),omitted:!0}}function xi(t,i){let n=f(typeof t.uri==="string"?t.uri:"","resource content URI",N),s=typeof t.mimeType==="string"?b(t.mimeType,"resource MIME type",g):void 0;if(typeof t.text==="string"){let e=Buffer.byteLength(t.text);if(e>Z)throw Error(`MCP resource text exceeds ${Z} bytes`);return kt(i,e,"resource result"),{uri:n,...s?{mimeType:s}:{},text:t.text}}if(typeof t.blob==="string")return{uri:n,...s?{mimeType:s}:{},binary:Si(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>hi)throw Error(`MCP resource result exceeds ${hi} contents`);let n={bytes:0},s=i.map((e)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw Error("MCP resource content is malformed");return xi(e,n)});if($t(s)>_)throw Error(`MCP resource result exceeds ${_} bytes`);return{contents:s}}function mi(t){if(!t||typeof t!=="object"||Array.isArray(t))throw Error("MCP prompt result is malformed");let i=t,n=Array.isArray(i.messages)?i.messages:[];if(n.length>Ri)throw Error(`MCP prompt exceeds ${Ri} messages`);let s={bytes:0},e=n.map((r)=>{if(!r||typeof r!=="object"||Array.isArray(r))throw Error("MCP prompt message is malformed");let o=r,u=o.role;if(u!=="user"&&u!=="assistant")throw Error("MCP prompt message has an invalid role");let d=o.content;if(!d||typeof d!=="object"||Array.isArray(d))throw Error("MCP prompt message content is malformed");let p=d;if(p.type==="text"&&typeof p.text==="string"){let c=Buffer.byteLength(p.text);if(c>Z)throw Error(`MCP prompt text exceeds ${Z} bytes`);return kt(s,c,"prompt result"),{role:u,content:{type:"text",text:p.text}}}if((p.type==="image"||p.type==="audio")&&typeof p.data==="string"&&typeof p.mimeType==="string")return{role:u,content:{type:p.type,mimeType:f(p.mimeType,"prompt content MIME type",g),binary:Si(p.data,`prompt ${p.type}`,s)}};if(p.type==="resource"&&p.resource&&typeof p.resource==="object"&&!Array.isArray(p.resource))return{role:u,content:{type:"resource",resource:xi(p.resource,s)}};if(p.type==="resource_link"&&typeof p.uri==="string"&&typeof p.name==="string")return{role:u,content:{type:"resource_link",uri:f(p.uri,"prompt resource link URI",N),name:f(p.name,"prompt resource link name",A),...typeof p.mimeType==="string"?{mimeType:f(p.mimeType,"prompt resource link MIME type",g)}:{},...typeof p.description==="string"?{description:b(p.description,"description",m)}:{}}};throw Error(`Unsupported MCP prompt content type: ${String(p.type)}`)});if($t(e)>_)throw Error(`MCP prompt result exceeds ${_} bytes`);return{...typeof i.description==="string"?{description:b(i.description,"description",m)}:{},messages:e}}var li=4000,Ui=4096,Bi=32,qn=128,Xi=1000,zi=100,Yi=65536,Kn=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 e=Nn(i.url);if(!i.elicitationId.trim())throw Error("MCP URL elicitation ID is empty");return{serverName:t,mode:"url",message:i.message,url:e.toString(),domain:e.hostname,elicitationId:i.elicitationId}}let n=Object.entries(i.requestedSchema.properties);if(n.length>Bi)throw Error(`MCP elicitation exceeds the ${Bi} field limit`);let s=new Set(i.requestedSchema.required??[]);for(let e of s)if(!Object.hasOwn(i.requestedSchema.properties,e))throw Error(`MCP elicitation requires an unknown field: ${e}`);return{serverName:t,mode:"form",message:i.message,fields:n.map(([e,r])=>Wn(e,r,s.has(e))),requestedSchema:structuredClone(i.requestedSchema)}}function vs(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 te(t,i){let n=i.trim();if(!n){if(t.defaultValue!==void 0)return t.defaultValue;if(!t.required)return;throw Error(`${t.title} is required`)}if(t.type==="number"||t.type==="integer"){let s=Number(n);if(!Number.isFinite(s))throw Error(`${t.title} must be a finite number`);if(t.type==="integer"&&!Number.isSafeInteger(s))throw Error(`${t.title} must be a safe integer`);return s}if(t.type==="boolean"){if(["true","yes","y","1"].includes(n.toLowerCase()))return!0;if(["false","no","n","0"].includes(n.toLowerCase()))return!1;throw Error(`${t.title} must be true or false`)}return n}function Fi(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")>Yi)throw Error(`MCP elicitation response exceeds ${Yi} bytes`);for(let r of Object.keys(n))Ji(r);for(let r of Object.values(n))if(typeof r==="number"&&(!Number.isFinite(r)||Number.isInteger(r)&&!Number.isSafeInteger(r)))throw Error("MCP elicitation response contains an unsafe number");let s=x.Unsafe({...t.requestedSchema,additionalProperties:!1}),e=X(s,n);if(!e.success)throw Error(`Invalid MCP elicitation response: ${e.error.message}`);return{action:"accept",content:e.data}}function Wn(t,i,n){Ji(t);let s=tt(i.title?.trim()||t,"field title"),e=i.description?tt(i.description,"field description"):void 0,r={name:t,title:s,description:e,required:n};if(i.type==="boolean")return{...r,type:"boolean",...typeof i.default==="boolean"?{defaultValue:i.default}:{}};if(i.type==="number"||i.type==="integer")return{...r,type:i.type,...typeof i.default==="number"?{defaultValue:i.default}:{},...i.minimum!==void 0?{minimum:i.minimum}:{},...i.maximum!==void 0?{maximum:i.maximum}:{}};if(i.type==="array"){let u=Qn(i);return{...r,type:"multi-select",options:u,...Array.isArray(i.default)&&i.default.every((d)=>typeof d==="string")?{defaultValue:[...i.default]}:{},...i.minItems!==void 0?{minItems:i.minItems}:{},...i.maxItems!==void 0?{maxItems:i.maxItems}:{}}}let o=Zn(i);if(o)return{...r,type:"select",options:o,...typeof i.default==="string"?{defaultValue:i.default}:{}};return{...r,type:"string",...typeof i.default==="string"?{defaultValue:i.default}:{},...i.format?{format:i.format}:{},...i.minLength!==void 0?{minLength:i.minLength}:{},...i.maxLength!==void 0?{maxLength:i.maxLength}:{}}}function Zn(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 Qn(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>zi)throw Error(`MCP elicitation options must contain 1-${zi} 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 Ji(t){if(!t||t.length>qn||Kn.has(t))throw Error(`Unsafe MCP elicitation field name: ${t||"(empty)"}`)}function tt(t,i){if(t.length>Xi)throw Error(`MCP elicitation ${i} exceeds ${Xi} characters`);return t}function Nn(t){if(t.length>Ui)throw Error(`MCP elicitation URL exceeds ${Ui} 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 Ki}from"node:crypto";var l=1000,it=100,In=256,Vi=16384,ji=262144,Gi=4194304,Hi=24;function vn(t,i=10){return Ki("sha256").update(t).digest("hex").slice(0,i)}function Ot(t){if(Array.isArray(t))return t.map(Ot);if(!t||typeof t!=="object")return t;let i=t;return Object.fromEntries(Object.keys(i).sort().map((n)=>[n,Ot(i[n])]))}function Wi(t){let i=t.normalize("NFKC"),n=i.replace(/[^A-Za-z0-9_-]/g,"_");if(n&&n===i&&n.length<=Hi)return n;return`${(n||"unnamed").slice(0,Hi-11)}_${vn(i)}`}function Lt(t,i){return`${ts(t)}${Wi(i)}`}function ts(t){return`mcp__${Wi(t)}__`}function qi(t){return Ki("sha256").update(JSON.stringify(Ot({name:t.name,description:t.description,inputSchema:t.inputSchema,taskSupport:t.taskSupport}))).digest("hex")}function is(t){return[...t].some((i)=>{let n=i.charCodeAt(0);return n<=31||n===127})}function Zi(t){if(t.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);let i=new Set,n=[],s=0;for(let e of t){let r=e.name.trim();if(!r||r.length>In||is(r))throw Error("MCP tool catalog contains an invalid tool name");if(i.has(r))throw Error(`MCP tool catalog contains duplicate tool "${r}"`);i.add(r);let o=e.description??"";if(Buffer.byteLength(o)>Vi)throw Error(`MCP tool "${r}" description exceeds ${Vi} bytes`);let u=JSON.stringify(e.inputSchema),d=Buffer.byteLength(u);if(d>ji)throw Error(`MCP tool "${r}" schema exceeds ${ji} bytes`);if(s+=Buffer.byteLength(r)+Buffer.byteLength(o)+d,s>Gi)throw Error(`MCP tool catalog exceeds ${Gi} bytes`);n.push({name:r,description:o,inputSchema:JSON.parse(u),...e.execution?.taskSupport?{taskSupport:e.execution.taskSupport}:{}})}return n}function Qi(t,i){let n=new Map(t.map((e)=>[e.name,qi(e)])),s=new Map(i.map((e)=>[e.name,qi(e)]));return{added:[...s.keys()].filter((e)=>!n.has(e)).sort(),removed:[...n.keys()].filter((e)=>!s.has(e)).sort(),updated:[...s.keys()].filter((e)=>n.has(e)&&n.get(e)!==s.get(e)).sort()}}function nt(t){return t.added.length>0||t.removed.length>0||t.updated.length>0}function Ii(t){if(t instanceof zt||t instanceof U)return{type:"auth_error",isRetryable:!1,originalError:t};if(!(t instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(t))};let i=t.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((e)=>i.includes(e)))return{type:"config_error",isRetryable:!1,originalError:t};if(i.includes("unauthorized")||i.includes("401")||i.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:t};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((e)=>i.includes(e)))return{type:"network_temporary",isRetryable:!0,originalError:t};return{type:"unknown",isRetryable:!0,originalError:t}}class Yt extends Es{config;runtimeOptions;status="disconnected";sdkClient=null;tools=new Map;toolCatalogRevision=0;toolRefreshPromise;toolRefreshRequested=!1;resources=[];resourceTemplates=[];prompts=[];contentCatalogRevision=0;contentRefreshPromise;requestedContentCatalogs=new Set;contentRefreshReason="manual";catalogGeneration=0;desiredResourceSubscriptions=new Set;activeResourceSubscriptions=new Set;serverInfo=null;serverInstructions;completionCallsInFlight=0;loggingPolicy;logWindowStartedAt=0;logEventsInWindow=0;logRateWarningEmitted=!1;recoveryPolicy;desiredConnected=!1;connectionGeneration=0;connectPromise;connectAbortController;recoveryPromise;recoveryAbortController;recoveryState;consecutiveTerminalErrors=0;oauthProvider=null;serverName;healthMonitor=null;activeInteraction;taskInteractions=new Map;taskPolicy;roots;constructor(t,i,n,s={}){super();this.config=t;this.runtimeOptions=s;this.serverName=i||"default",this.recoveryPolicy=Ti(t),this.loggingPolicy=dn(t),this.taskPolicy=wn(t.tasks),this.roots=(s.roots??[]).map((r)=>{let o=ss.native(Ni.resolve(r));return{uri:es(o).href,name:Ni.basename(o)||o}});let e=vi(t);if(this.config={...t,...e?{oauth:e}:{}},e?.enabled&&t.url&&s.oauthCredentialAccess!==!1)this.oauthProvider=new en(this.serverName,t.url,e,s.oauthStorageRoot?{tokenStorage:new sn(s.oauthStorageRoot)}:{});if(n?.enabled)this.healthMonitor=new bt(this,n),this.healthMonitor.on("unhealthy",(r,o)=>{this.emit("unhealthy",r,o)})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get contentCatalog(){return{resources:structuredClone(this.resources),resourceTemplates:structuredClone(this.resourceTemplates),prompts:structuredClone(this.prompts)}}get completionSupported(){return Boolean(this.sdkClient?.getServerCapabilities()?.completions)}get tasks(){return{...this.taskPolicy}}get server(){return this.serverInfo}get instructions(){return this.serverInstructions?structuredClone(this.serverInstructions):void 0}get healthCheck(){return this.healthMonitor}get recovery(){return this.recoveryState?structuredClone(this.recoveryState):void 0}get logging(){return{...this.loggingPolicy}}get oauthEnabled(){return this.config.oauth?.enabled===!0}async getOAuthStatus(){if(!this.oauthEnabled)return"disabled";if(this.runtimeOptions.oauthCredentialAccess===!1)return"unavailable";return this.oauthProvider?.getStatus()??"error"}async beginOAuthLogin(t={}){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);return t.openBrowser?this.oauthProvider.openAuthorization():this.oauthProvider.beginAuthorization()}async logoutOAuth(){if(!this.oauthEnabled)throw Error(`MCP server "${this.serverName}" does not enable OAuth`);if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(this.status!=="disconnected")await this.disconnect();await this.oauthProvider.logout()}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(t=3,i=1000){if(!Number.isInteger(t)||t<1||t>At)throw Error(`MCP connection maxRetries must be an integer between 1 and ${At}`);if(!Number.isFinite(i)||i<0||i>_t)throw Error(`MCP connection initialDelay must be between 0 and ${_t}`);if(this.status==="connected")return;if(this.recoveryPromise)return this.recoveryPromise;if(this.connectPromise)return this.connectPromise;this.desiredConnected=!0;let n=++this.connectionGeneration,s=new AbortController;this.connectAbortController=s;let e=this.runInitialConnection(Math.max(1,t),Math.max(0,i),n,s.signal).finally(()=>{if(this.connectPromise===e)this.connectPromise=void 0;if(this.connectAbortController===s)this.connectAbortController=void 0});return this.connectPromise=e,e}async runInitialConnection(t,i,n,s){let e;for(let o=1;o<=t;o++){this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!1);return}catch(u){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=u instanceof Error?u:Error(String(u)),!Ii(e).isRetryable||o===t)break;await Rt(i*2**Math.max(0,o-1),s,!1)}}let r=e??Error("MCP connection failed");if(this.isConnectionGenerationCurrent(n))this.invalidateLiveConnection(!1),this.setStatus("error"),this.emitClientError(r);throw r}async doConnect(t,i){let n;try{this.assertConnectionGeneration(t),this.setStatus(i?"reconnecting":"connecting");let s=cn(this.config.sampling),e={...s,enabled:s.enabled&&this.runtimeOptions.samplingAvailable===!0};n=new rs({name:nn(),version:tn()},{capabilities:{roots:{listChanged:!1},elicitation:{form:{applyDefaults:!1},url:{}},...e.enabled?{sampling:{}}:{}},listChanged:{tools:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshTools("notification")}},resources:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["resources"])}},prompts:{autoRefresh:!1,debounceMs:0,onChanged:()=>{this.refreshContentCatalogs("notification",["prompts"])}}}});let r=n;if(this.sdkClient=r,this.resetCatalogRefreshState(),this.registerElicitationHandlers(r),this.registerRootHandler(r),e.enabled)this.registerSamplingHandler(r,e);if(this.registerResourceNotificationHandler(r),this.registerLoggingHandler(r),this.taskPolicy.enabled)this.registerTaskStatusHandler(r);r.onclose=()=>{this.handleUnexpectedClose(r,t)},r.onerror=(d)=>{this.handleTransportError(r,t,d)};let o=await this.createTransport();this.assertConnectionGeneration(t),await r.connect(o),this.assertConnectionGeneration(t);let u=r.getServerVersion();this.serverInfo={name:u?.name||"Unknown",version:u?.version||"0.0.0"},this.serverInstructions=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(s){if(n&&this.sdkClient===n)this.sdkClient=null;if(n)n.onclose=void 0,n.onerror=void 0,await n.close().catch(()=>{return});throw s}}handleUnexpectedClose(t,i){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;this.startRecovery(Error(`MCP server "${this.serverName}" connection closed`),"transport_closed",!1)}handleTransportError(t,i,n){if(this.sdkClient!==t||!this.isConnectionGenerationCurrent(i)||this.status!=="connected")return;if(this.emit("transportError",{serverName:this.serverName,error:k(n)}),bi(n)){this.startRecovery(n,"session_expired",!0);return}if(!fi(n)){this.consecutiveTerminalErrors=0;return}if(this.consecutiveTerminalErrors++,n.message.toLowerCase().includes("maximum reconnection attempts")||this.consecutiveTerminalErrors>=this.recoveryPolicy.terminalErrorThreshold)this.startRecovery(n,"transport_error",!0)}requestRecovery(t,i){if(!this.desiredConnected||this.status!=="connected"||this.recoveryPromise)return;this.startRecovery(t,i,!0)}startRecovery(t,i,n){if(!this.desiredConnected||this.recoveryPromise)return;let s=this.sdkClient;if(this.sdkClient=null,s)s.onclose=void 0,s.onerror=void 0;this.healthMonitor?.stop(),this.invalidateLiveConnection(!0);let e=++this.connectionGeneration,r=new AbortController;if(this.recoveryAbortController=r,this.setStatus("reconnecting"),n&&s)s.close().catch(()=>{return});let o=Promise.resolve().then(()=>this.runRecoveryLoop(t,i,e,r.signal)).finally(()=>{if(this.recoveryPromise===o)this.recoveryPromise=void 0;if(this.recoveryAbortController===r)this.recoveryAbortController=void 0});this.recoveryPromise=o,o.catch(()=>{return})}async runRecoveryLoop(t,i,n,s){let e=t;if(!this.recoveryPolicy.enabled||this.recoveryPolicy.maxAttempts===0){this.failRecovery(e,i,0,n);return}for(let r=1;r<=this.recoveryPolicy.maxAttempts;r++){this.assertConnectionGeneration(n,s);let o=Ei(this.recoveryPolicy,r,this.runtimeOptions.recoveryRandom),u=Date.now()+o;this.publishConnectionLifecycle({phase:"reconnecting",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts,nextRetryAt:u,error:k(e)}),await Rt(o,s),this.assertConnectionGeneration(n,s);try{await this.doConnect(n,!0),this.healthMonitor?.resetFailureCount(),this.publishConnectionLifecycle({phase:"recovered",reason:i,attempt:r,maxAttempts:this.recoveryPolicy.maxAttempts}),this.emit("reconnected");return}catch(d){if(!this.isConnectionGenerationCurrent(n)||s.aborted)throw C(s.reason);if(e=d instanceof Error?d:Error(String(d)),!Ii(e).isRetryable){this.failRecovery(e,i,r,n);return}}}this.failRecovery(e,i,this.recoveryPolicy.maxAttempts,n)}failRecovery(t,i,n,s){if(!this.isConnectionGenerationCurrent(s))return;this.setStatus("error"),this.publishConnectionLifecycle({phase:"failed",reason:i,attempt:n,maxAttempts:this.recoveryPolicy.maxAttempts,error:k(t)}),this.emit("reconnectFailed",t)}publishConnectionLifecycle(t){this.recoveryState=structuredClone(t),this.emit("connectionLifecycleChanged",structuredClone(t))}isConnectionGenerationCurrent(t){return this.desiredConnected&&this.connectionGeneration===t}assertConnectionGeneration(t,i){if(i?.aborted||!this.desiredConnected||this.connectionGeneration!==t)throw C(i?.reason)}invalidateLiveConnection(t){if(this.resetCatalogRefreshState(),this.tools.clear(),this.resources=[],this.resourceTemplates=[],this.prompts=[],this.activeResourceSubscriptions.clear(),!t)this.desiredResourceSubscriptions.clear();if(!t)this.taskInteractions.clear();this.serverInfo=null,this.serverInstructions=void 0,this.consecutiveTerminalErrors=0}resetCatalogRefreshState(){this.catalogGeneration++,this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,this.contentRefreshPromise=void 0,this.requestedContentCatalogs.clear(),this.contentRefreshReason="manual"}emitClientError(t){if(this.listenerCount("error")>0)this.emit("error",t)}async ping(t=1e4){let i=this.sdkClient;if(!i||this.status!=="connected")throw Error(`MCP server "${this.serverName}" is not connected`);let n=new AbortController,s=setTimeout(()=>n.abort("MCP health check timeout"),t);s.unref();try{await i.ping({signal:n.signal,timeout:t,maxTotalTimeout:t})}catch(e){if(n.signal.aborted)throw Error(`MCP server "${this.serverName}" health check timed out after ${t}ms`);throw e}finally{clearTimeout(s)}}async disconnect(){this.desiredConnected=!1,this.connectionGeneration++,this.connectAbortController?.abort("MCP client disconnected"),this.recoveryAbortController?.abort("MCP client disconnected"),this.healthMonitor?.stop();let t=this.sdkClient;if(this.sdkClient=null,t)t.onclose=void 0,t.onerror=void 0,await t.close().catch(()=>{return});await Promise.allSettled([this.connectPromise,this.recoveryPromise].filter((i)=>i!==void 0)),this.invalidateLiveConnection(!1),this.recoveryState=void 0,await this.oauthProvider?.dispose(),this.setStatus("disconnected"),this.emit("disconnected")}async callTool(t,i={},n={}){let s=this.sdkClient;if(!s||this.status!=="connected")throw Error("客户端未连接到服务器");if(!this.tools.has(t))throw Error(`工具 "${t}" 不存在`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive tool calls`);let e=gt(this.config),r=Symbol(t);this.activeInteraction={token:r,context:n,samplingRequests:0,samplingInFlight:!1};let o=new AbortController,u=setTimeout(()=>o.abort("mcp-tool-timeout"),e.totalTimeoutMs);u.unref();let d=n.signal?AbortSignal.any([n.signal,o.signal]):o.signal,p={count:0};try{return await s.callTool({name:t,arguments:i},St,{signal:d,timeout:e.idleTimeoutMs,resetTimeoutOnProgress:!0,maxTotalTimeout:e.totalTimeoutMs,onprogress:(M)=>{let w=mt(M,p,e);if(w&&!d.aborted&&this.activeInteraction?.token===r)n.progressHandler?.(w),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...w})}})}catch(c){if(n.signal?.aborted)throw new DOMException(String(n.signal.reason||"MCP tool call cancelled"),"AbortError");if(o.signal.aborted&&!n.signal?.aborted)throw new P(R.RequestTimeout,`MCP server "${this.serverName}" tool "${t}" timed out after ${e.totalTimeoutMs}ms`);throw console.error(`[McpClient] 调用工具 "${t}" 失败:`,c),c}finally{if(clearTimeout(u),this.activeInteraction?.token===r)this.activeInteraction=void 0}}getToolTaskSupport(t){return this.tools.get(t)?.taskSupport}async createToolTask(t,i,n,s,e){let r=this.sdkClient;if(!r||this.status!=="connected")throw Error("MCP client is not connected");if(!this.taskPolicy.enabled)throw Error(`MCP tasks are disabled for server "${this.serverName}"`);if(!r.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);let o=this.getToolTaskSupport(t);if(o!=="required"&&o!=="optional")throw Error(`MCP tool "${t}" does not support task execution`);if(this.activeInteraction)throw Error(`MCP server "${this.serverName}" does not allow overlapping interactive task creation`);let u=gt(this.config),d=Symbol(t),p={token:d,context:{...n,signal:s},samplingRequests:0,samplingInFlight:!1};this.activeInteraction=p;let c={count:0},M=r.experimental.tasks.callToolStream({name:t,arguments:i},St,{signal:s,task:{ttl:e??this.taskPolicy.defaultTtlMs,pollInterval:this.taskPolicy.pollIntervalMs},timeout:u.idleTimeoutMs,maxTotalTimeout:u.totalTimeoutMs,resetTimeoutOnProgress:!0,onprogress:(y)=>{let E=mt(y,c,u);if(E&&!s.aborted&&this.hasInteractionToken(d))n.progressHandler?.(E),this.emit("toolProgress",{serverName:this.serverName,toolName:t,...E})}}),w=!1;try{let y=await M.next();if(await M.return(void 0),y.done||y.value.type!=="taskCreated"){if(!y.done&&y.value.type==="error")throw y.value.error;throw Error(`MCP tool "${t}" did not create a task`)}if(this.sdkClient!==r)throw Error("MCP client changed while creating a task");let E=Ut(y.value.task,this.taskPolicy);return this.taskInteractions.set(E.taskId,p),w=!0,this.emit("taskCreated",{serverName:this.serverName,toolName:t,task:E}),E}finally{if(this.activeInteraction?.token===d)this.activeInteraction=void 0;if(!w){for(let[y,E]of this.taskInteractions)if(E.token===d)this.taskInteractions.delete(y)}}}async getToolTask(t,i,n){let s=this.requireTaskClient(),e=await s.experimental.tasks.getTask(t,{signal:n,timeout:this.taskPolicy.pollIntervalMs+1e4,maxTotalTimeout:this.taskPolicy.pollIntervalMs+1e4});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task");return Ut(e,this.taskPolicy,{taskId:t,createdAt:i})}async getToolTaskResult(t,i,n=this.taskPolicy.maxLifetimeMs){let s=this.requireTaskClient(),e=Math.max(1,Math.min(n,this.taskPolicy.maxLifetimeMs)),r=await s.experimental.tasks.getTaskResult(t,St,{signal:i,timeout:e,maxTotalTimeout:e});if(this.sdkClient!==s)throw Error("MCP client changed while reading a task result");return r}async cancelToolTask(t,i){let n=this.requireTaskClient();if(!n.getServerCapabilities()?.tasks?.cancel)throw Error(`MCP server "${this.serverName}" does not support task cancellation`);if(await n.experimental.tasks.cancelTask(t,{signal:i,timeout:15000,maxTotalTimeout:15000}),this.sdkClient!==n)throw Error("MCP client changed while cancelling a task")}async normalizeToolTaskResult(t){return j(t,this.runtimeOptions.artifactWriter)}releaseTaskInteraction(t){this.taskInteractions.delete(t)}async waitUntilConnected(t,i){if(this.status==="connected"&&this.sdkClient)return;if(!this.desiredConnected)throw Error(`MCP server "${this.serverName}" is disconnected`);await new Promise((n,s)=>{let e=setTimeout(()=>{d(),s(Error(`MCP server "${this.serverName}" recovery timed out`))},i);e.unref();let r=()=>{d(),n()},o=()=>{if(this.desiredConnected)return;d(),s(Error(`MCP server "${this.serverName}" was disconnected`))},u=()=>{d(),s(new DOMException(String(t.reason||"MCP task recovery cancelled"),"AbortError"))},d=()=>{clearTimeout(e),this.off("connected",r),this.off("disconnected",o),t.removeEventListener("abort",u)};if(this.on("connected",r),this.on("disconnected",o),t.addEventListener("abort",u,{once:!0}),t.aborted)u()})}requireTaskClient(){let t=this.sdkClient;if(!t||this.status!=="connected"||!this.taskPolicy.enabled)throw Error(`MCP server "${this.serverName}" task client is unavailable`);if(!t.getServerCapabilities()?.tasks?.requests?.tools?.call)throw Error(`MCP server "${this.serverName}" does not support task-augmented tools/call`);return t}hasInteractionToken(t){if(this.activeInteraction?.token===t)return!0;return[...this.taskInteractions.values()].some((i)=>i.token===t)}registerRootHandler(t){t.setRequestHandler(Ms,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(Ts,(i)=>{this.emit("taskStatus",i.params)})}registerSamplingHandler(t,i){t.setRequestHandler(ps,async(n,s)=>{let e=this.resolveInteraction(n.params);if(!e?.context.confirmationHandler||!e.context.samplingHandler)throw new P(R.InvalidRequest,"MCP sampling requires an active interactive Session");if(e.samplingInFlight)throw new P(R.InvalidRequest,"MCP server does not allow overlapping sampling requests");e.samplingInFlight=!0;try{if(e.samplingRequests++,e.samplingRequests>i.maxRequestsPerToolCall)throw new P(R.InvalidRequest,`MCP sampling exceeded ${i.maxRequestsPerToolCall} requests for one tool call`);let r=e.context.signal?AbortSignal.any([e.context.signal,s.signal]):s.signal;if(r.aborted)throw new P(R.InvalidRequest,"MCP sampling was cancelled");let o;try{o=Mn(n.params,i)}catch(p){throw new P(R.InvalidRequest,p instanceof Error?p.message:String(p))}let u=await e.context.confirmationHandler.requestConfirmation({type:"mcpSampling",kind:"execute",toolName:`MCP sampling: ${this.serverName}`,title:"MCP model sampling request",message:`MCP server "${this.serverName}" wants to call the current Session model with up to ${o.maxTokens} output tokens.`,details:o.preview,risks:[`May consume up to ${o.maxTokens} output tokens`,"The model response will be returned to the MCP server"]},r);if(r.aborted||u.reason===Xt||u.reason==="timeout")throw new P(R.InvalidRequest,"MCP sampling was cancelled");if(!u.approved)throw new P(R.InvalidRequest,"MCP sampling was denied");let d=await e.context.samplingHandler(o,r);return this.emit("samplingCompleted",{serverName:this.serverName,model:d.model,maxTokens:o.maxTokens}),d}finally{e.samplingInFlight=!1}})}registerElicitationHandlers(t){t.setRequestHandler(cs,async(i,n)=>{let s=this.resolveInteraction(i.params)?.context;if(!s?.confirmationHandler)return this.emit("elicitationCancelled",{serverName:this.serverName,reason:"no-interaction-handler"}),{action:"cancel"};let e=s.signal?AbortSignal.any([s.signal,n.signal]):n.signal;if(e.aborted)return{action:"cancel"};let r;try{r=Di(this.serverName,i.params)}catch(o){return this.emit("elicitationRejected",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"decline"}}try{let o=s.sessionId&&s.workspaceRoot&&s.permissionMode?{projectDir:s.workspaceRoot,sessionId:s.sessionId,permissionMode:s.permissionMode,abortSignal:e}:void 0,u=o?await Bt.getInstance().executeElicitationHooks(r,o):{},d;if(u.blockedReason)d={action:"decline"};else if(u.response)d=u.response;else{let M=await s.confirmationHandler.requestConfirmation({type:"mcpElicitation",message:r.message,title:`MCP input requested by ${this.serverName}`,mcpElicitation:r},e),w=this.resolveElicitationAction(M,e);if(d=M.elicitation??{action:w},w==="accept"&&r.mode==="url"&&M.openExternalUrl&&r.url)await bs(r.url,{wait:!1})}let p=o?await Bt.getInstance().executeElicitationResultHooks(r,d,o):{};if(p.blockedReason)d={action:"cancel"};else if(p.response)d=p.response;let c=Fi(r,d);return this.emit("elicitationResolved",{serverName:this.serverName,mode:r.mode,action:c.action,elicitationId:r.elicitationId}),c}catch(o){return this.emit("elicitationCancelled",{serverName:this.serverName,reason:o instanceof Error?o.message:String(o)}),{action:"cancel"}}}),t.setNotificationHandler(us,(i)=>{this.emit("elicitationCompleted",{serverName:this.serverName,elicitationId:i.params.elicitationId})})}resolveElicitationAction(t,i){if(i.aborted||t.reason===Xt||t.reason==="timeout")return"cancel";if(t.elicitation)return t.elicitation.action;return t.approved?"accept":"decline"}async createTransport(){let{type:t,command:i,args:n,env:s,cwd:e,url:r,headers:o,oauth:u}=this.config,d;if(u?.enabled){if(this.runtimeOptions.oauthCredentialAccess===!1||!this.oauthProvider)throw new U(this.serverName);if(!await this.oauthProvider.hasUsableCredentials())throw new zt(this.serverName);d=this.oauthProvider}if(t==="stdio"){if(!i)throw Error("stdio 传输需要 command 参数");let p={};for(let[c,M]of Object.entries(process.env))if(M!==void 0)p[c]=M;return new os({command:i,args:n||[],env:{...p,...s},cwd:e,stderr:"ignore"})}else if(t==="sse"){if(!r)throw Error("sse 传输需要 url 参数");return new ds(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}else if(t==="http"){if(!r)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:p}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new p(new URL(r),{requestInit:{headers:o},...u?.enabled?{fetch:xt}:{},...d?{authProvider:d}:{}})}throw Error(`不支持的传输类型: ${t}`)}async refreshTools(t="manual"){if(this.toolRefreshRequested=!0,this.toolRefreshPromise)return this.toolRefreshPromise;let i=this.catalogGeneration,n=(t==="notification"?new Promise((s)=>{setTimeout(s,25).unref()}):Promise.resolve()).then(()=>this.runToolRefresh(t)).finally(()=>{if(i!==this.catalogGeneration||this.toolRefreshPromise!==n)return;let s=this.toolRefreshRequested;if(this.toolRefreshPromise=void 0,this.toolRefreshRequested=!1,s&&this.sdkClient)this.refreshTools("notification")});return this.toolRefreshPromise=n,n}async waitForToolRefresh(){while(this.toolRefreshPromise)await this.toolRefreshPromise}async runToolRefresh(t){let i=t;for(let n=0;n<3&&this.toolRefreshRequested;n++){this.toolRefreshRequested=!1;try{await this.fetchAndPublishTools(i)}catch(s){if(this.emit("toolsRefreshFailed",{serverName:this.serverName,reason:i,error:s instanceof Error?s:Error(String(s))}),i!=="notification")throw s;return}i="notification"}}async fetchAndPublishTools(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=[],s=new Set,e;for(let p=0;p<it;p++){let c=await i.listTools(e?{cursor:e}:void 0);if(n.push(...c.tools),n.length>l)throw Error(`MCP tool catalog exceeds ${l} tools`);if(e=c.nextCursor,!e)break;if(s.has(e))throw Error("MCP tool catalog returned a repeated cursor");if(s.add(e),p===it-1)throw Error(`MCP tool catalog exceeds ${it} pages`)}let r=Zi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing tools");let o=this.availableTools,u=Qi(o,r);if(this.tools=new Map(r.map((p)=>[p.name,p])),!nt(u))return;this.toolCatalogRevision++;let d={revision:this.toolCatalogRevision,reason:t,...u};this.emit("toolsUpdated",this.availableTools,d)}async refreshContentCatalogs(t="manual",i=["resources","prompts"]){let n=this.sdkClient?.getServerCapabilities();for(let r of i){if(r==="resources"&&n?.resources)this.requestedContentCatalogs.add(r);if(r==="prompts"&&n?.prompts)this.requestedContentCatalogs.add(r)}if(this.requestedContentCatalogs.size===0)return;if(this.contentRefreshPromise){if(t!=="notification")this.contentRefreshReason=t;return this.contentRefreshPromise}this.contentRefreshReason=t;let s=this.catalogGeneration,e=(t==="notification"?new Promise((r)=>{setTimeout(r,25).unref()}):Promise.resolve()).then(()=>this.runContentCatalogRefresh()).finally(()=>{if(s!==this.catalogGeneration||this.contentRefreshPromise!==e)return;let r=this.requestedContentCatalogs.size>0;if(this.contentRefreshPromise=void 0,this.contentRefreshReason="manual",r&&this.sdkClient)this.refreshContentCatalogs("notification")});return this.contentRefreshPromise=e,e}async waitForCatalogRefresh(){while(this.toolRefreshPromise||this.contentRefreshPromise)await Promise.all([this.toolRefreshPromise??Promise.resolve(),this.contentRefreshPromise??Promise.resolve()])}async runContentCatalogRefresh(){for(let t=0;t<3&&this.requestedContentCatalogs.size>0;t++){let i=[...this.requestedContentCatalogs];this.requestedContentCatalogs.clear();let n=this.contentRefreshReason;this.contentRefreshReason="notification";let s=[];for(let e of i)try{if(e==="resources")await this.fetchAndPublishResourceCatalog(n);else await this.fetchAndPublishPromptCatalog(n)}catch(r){let o=r instanceof Error?r:Error(String(r));s.push(o),this.emit("contentCatalogRefreshFailed",{serverName:this.serverName,catalog:e,reason:n,error:o})}if(s.length>0&&n!=="notification")throw AggregateError(s,`Failed to refresh MCP content catalogs for "${this.serverName}"`)}}async fetchAndPublishResourceCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("resource",q,(d)=>i.listResources(d?{cursor:d}:void 0),(d)=>d.resources),s=await this.fetchContentPages("resource template",K,(d)=>i.listResourceTemplates(d?{cursor:d}:void 0),(d)=>d.resourceTemplates),e=Ci(n),r=ki(s);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing resource catalogs");let o=I(this.resources,e,(d)=>d.uri),u=I(this.resourceTemplates,r,(d)=>d.uriTemplate);this.resources=e,this.resourceTemplates=r,await this.reconcileResourceSubscriptions(i),this.publishContentCatalogDelta("resources",t,o),this.publishContentCatalogDelta("resourceTemplates",t,u)}async fetchAndPublishPromptCatalog(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");let n=await this.fetchContentPages("prompt",W,(r)=>i.listPrompts(r?{cursor:r}:void 0),(r)=>r.prompts),s=Oi(n);if(this.sdkClient!==i)throw Error("MCP client changed while refreshing prompts");let e=I(this.prompts,s,(r)=>r.name);this.prompts=s,this.publishContentCatalogDelta("prompts",t,e)}async fetchContentPages(t,i,n,s){let e=[],r=new Set,o;for(let u=0;u<Pt;u++){let d=await n(o);if(e.push(...s(d)),e.length>i)throw Error(`MCP ${t} catalog exceeds ${i} entries`);if(o=d.nextCursor,!o)return e;if(r.has(o))throw Error(`MCP ${t} catalog returned a repeated cursor`);r.add(o)}throw Error(`MCP ${t} catalog exceeds ${Pt} pages`)}publishContentCatalogDelta(t,i,n){if(!Li(n))return;this.contentCatalogRevision++;let s={revision:this.contentCatalogRevision,kind:t,reason:i,...n};this.emit("contentCatalogUpdated",this.contentCatalog,s)}registerResourceNotificationHandler(t){t.setNotificationHandler(ys,(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(ws,(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",un(1,{now:n}));return}this.logEventsInWindow++;let s=lt({level:i.params.level,logger:i.params.logger,data:i.params.data},{exposeDetails:this.runtimeOptions.exposeLogDetails,now:n});this.emit("log",s)})}async configureLogging(t){if(this.logWindowStartedAt=Date.now(),this.logEventsInWindow=0,this.logRateWarningEmitted=!1,!this.loggingPolicy.enabled||!t.getServerCapabilities()?.logging)return;try{await t.setLoggingLevel(this.loggingPolicy.level)}catch(i){if(this.sdkClient!==t)return;let n={serverName:this.serverName,level:this.loggingPolicy.level,error:k(i)};this.emit("loggingSetupFailed",n),this.emit("log",{...lt({level:"warning",logger:"blade.mcp.logging",data:`Failed to set MCP logging level: ${n.error}`},{exposeDetails:this.runtimeOptions.exposeLogDetails}),synthetic:!0})}}async setLoggingLevel(t){if(!on(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 s=pi(t,this.contentCatalog);this.completionCallsInFlight++;try{let e=await n.complete(s,{signal:i,timeout:ht,maxTotalTimeout:ht});if(this.sdkClient!==n)throw Error("MCP client changed while completing an argument");return ui(e)}catch(e){if(i?.aborted)throw new DOMException(String(i.reason||"MCP completion cancelled"),"AbortError");throw e}finally{this.completionCallsInFlight--}}async readResource(t){let i=this.sdkClient;if(!i)throw Error("MCP client is not connected");if(!this.resources.some((n)=>n.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);return gi(await i.readResource({uri:t}))}async getPrompt(t,i={}){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");let s=this.prompts.find((r)=>r.name===t);if(!s)throw Error(`MCP prompt "${t}" is not present in server "${this.serverName}" catalog`);let e=new Set(s.arguments.map((r)=>r.name));for(let[r,o]of Object.entries(i)){if(["__proto__","constructor","prototype"].includes(r))throw Error(`Unsafe argument "${r}" for MCP prompt "${t}"`);if(!e.has(r))throw Error(`Unknown argument "${r}" for MCP prompt "${t}"`);if(Buffer.byteLength(o)>16384)throw Error(`Argument "${r}" for MCP prompt "${t}" is too large`)}for(let r of s.arguments)if(r.required&&i[r.name]===void 0)throw Error(`Required argument "${r.name}" is missing for MCP prompt "${t}"`);return mi(await n.getPrompt({name:t,arguments:i}))}async setResourceSubscription(t,i){let n=this.sdkClient;if(!n)throw Error("MCP client is not connected");if(i){if(!this.resources.some((s)=>s.uri===t))throw Error(`MCP resource "${t}" is not present in server "${this.serverName}" catalog`);if(this.desiredResourceSubscriptions.has(t)&&this.activeResourceSubscriptions.has(t))return;if(!this.desiredResourceSubscriptions.has(t)&&this.desiredResourceSubscriptions.size>=at)throw Error(`MCP resource subscriptions exceed ${at}`);if(!n.getServerCapabilities()?.resources?.subscribe)throw Error(`MCP server "${this.serverName}" does not support resource subscriptions`);if(await n.subscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while subscribing to resource");this.desiredResourceSubscriptions.add(t),this.activeResourceSubscriptions.add(t);return}if(!this.desiredResourceSubscriptions.has(t))return;if(this.activeResourceSubscriptions.has(t)){if(await n.unsubscribeResource({uri:t}),this.sdkClient!==n)throw Error("MCP client changed while unsubscribing from resource")}this.activeResourceSubscriptions.delete(t),this.desiredResourceSubscriptions.delete(t)}async reconcileResourceSubscriptions(t){if(this.sdkClient!==t)return;let i=new Set(this.resources.map((n)=>n.uri));for(let n of this.activeResourceSubscriptions)if(!i.has(n))this.activeResourceSubscriptions.delete(n);if(!t.getServerCapabilities()?.resources?.subscribe){this.activeResourceSubscriptions.clear();return}for(let n of this.desiredResourceSubscriptions){if(!i.has(n)||this.activeResourceSubscriptions.has(n))continue;try{if(await t.subscribeResource({uri:n}),this.sdkClient!==t)return;this.activeResourceSubscriptions.add(n)}catch(s){this.emit("resourceSubscriptionRestoreFailed",{serverName:this.serverName,uri:n,error:k(s)})}}}setStatus(t){let i=this.status;if(i===t)return;this.status=t,this.emit("statusChanged",t,i)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(t){return this.connect()}async disconnectFromServer(t){return this.disconnect()}async listResources(t){return structuredClone(this.resources)}async listResourceTemplates(){return structuredClone(this.resourceTemplates)}async listPrompts(){return structuredClone(this.prompts)}async listTools(t){return this.availableTools}}class O extends fs{runtimeOptions;static instance=null;servers=new Map;isDiscovering=!1;catalogRevision=0;contentCatalogRevision=0;connectionRevision=0;logRevision=0;instructionsRevision=0;logEntries=[];projectedTools=new Map;constructor(t={}){super();this.runtimeOptions=t}static getInstance(){if(!O.instance)O.instance=new O;return O.instance}static createIsolated(t={}){return new O(t)}async registerServer(t,i,n={}){if(this.servers.has(t))throw Error(`MCP服务器 "${t}" 已经注册`);let s=new Yt(i,t,i.healthCheck,this.runtimeOptions),e={config:i,client:s,status:"disconnected",tools:[],contentCatalog:{resources:[],resourceTemplates:[],prompts:[]},logging:s.logging};if(this.setupClientEventHandlers(s,e,t),this.servers.set(t,e),this.emit("serverRegistered",t,e),n.connect===!1)return;try{await this.connectServer(t)}catch(r){console.warn(`MCP服务器 "${t}" 连接失败:`,r)}}async unregisterServer(t){let i=this.servers.get(t);if(!i)return;try{await T.getInstance().cancelClient(i.client),await i.client.disconnect()}catch(n){console.warn(`断开MCP服务器 "${t}" 时出错:`,n)}this.servers.delete(t),this.logEntries=this.logEntries.filter((n)=>n.serverName!==t),this.emit("serverUnregistered",t)}async connectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status==="connected")return;try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async disconnectServer(t){let i=this.servers.get(t);if(!i)return;await T.getInstance().cancelClient(i.client),await i.client.disconnect(),i.connectedAt=void 0}async reconnectServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await T.getInstance().cancelClient(i.client),await i.client.disconnect();try{i.status="connecting",await i.client.connect(),i.connectedAt=new Date,i.lastError=void 0,i.tools=i.client.availableTools}catch(n){throw i.lastError=n,i.status="error",n}}async getAvailableTools(){return[...this.projectedTools.values()]}getCatalogSnapshot(){return{revision:this.catalogRevision,tools:[...this.projectedTools.values()]}}async waitForCatalogIdle(){await Promise.all([...this.servers.values()].map((t)=>t.client.waitForCatalogRefresh()))}getContentCatalogSnapshot(){let t=[],i=[],n=[];for(let[s,e]of this.servers){if(e.status!=="connected")continue;t.push(...e.contentCatalog.resources.map((r)=>({server:s,...structuredClone(r)}))),i.push(...e.contentCatalog.resourceTemplates.map((r)=>({server:s,...structuredClone(r)}))),n.push(...e.contentCatalog.prompts.map((r)=>({server:s,...structuredClone(r)})))}return{revision:this.contentCatalogRevision,resources:t,resourceTemplates:i,prompts:n}}getLogSnapshot(t,i={}){let n=Number.isSafeInteger(i.afterRevision)&&(i.afterRevision??0)>=0?i.afterRevision??0:0,s=Number.isSafeInteger(i.limit)&&(i.limit??0)>=1&&(i.limit??0)<=B?i.limit??B:B,e=this.logEntries.filter((r)=>r.revision>n&&(!t||r.serverName===t)).slice(-s).map((r)=>structuredClone(r));return{revision:this.logRevision,entries:e}}getInstructionsSnapshot(){let t=[];for(let[i,n]of this.servers){if(n.status!=="connected"||!n.instructions)continue;t.push({serverName:i,...structuredClone(n.instructions)})}return t.sort((i,n)=>i.serverName.localeCompare(n.serverName)),{revision:this.instructionsRevision,instructions:t}}async refreshContentCatalogs(t){if(t){await this.requireConnectedServer(t).client.refreshContentCatalogs("manual");return}await Promise.all([...this.servers.values()].filter((i)=>i.status==="connected").map((i)=>i.client.refreshContentCatalogs("manual")))}async readResource(t,i){return this.requireConnectedServer(t).client.readResource(i)}async getPrompt(t,i,n={}){return this.requireConnectedServer(t).client.getPrompt(i,n)}async complete(t,i,n){return this.requireConnectedServer(t).client.complete(i,n)}async startTask(t,i,n,s,e,r,o){let u=this.requireConnectedServer(t);if(!u.tools.some((d)=>d.name===i))throw Error(`MCP tool "${i}" is not present in server "${t}" catalog`);return T.getInstance().start({client:u.client,serverName:t,toolName:i,arguments:n,owner:s,interactionContext:e,signal:r,ttlMs:o})}listTasks(t,i){return T.getInstance().list(t,i)}getTask(t,i){return T.getInstance().get(t,i)}waitForTask(t,i,n,s){return T.getInstance().wait(t,i,n,s)}cancelTask(t,i,n){return T.getInstance().cancel(t,i,n)}async setResourceSubscription(t,i,n){await this.requireConnectedServer(t).client.setResourceSubscription(i,n)}async setServerLoggingLevel(t,i){let n=this.requireConnectedServer(t);await n.client.setLoggingLevel(i),n.logging=n.client.logging}async findTool(t){return this.projectedTools.get(t)??null}getToolsByServer(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return[];return i.tools.map((n)=>Tt(i.client,t,n,Lt(t,n.name),this.runtimeOptions.artifactWriter))}getServerStatus(t){return this.servers.get(t)||null}getAllServers(){return new Map(this.servers)}async getServerOAuthStatus(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);return i.client.getOAuthStatus()}async beginOAuthLogin(t,i={}){let n=this.servers.get(t);if(!n)throw Error(`MCP服务器 "${t}" 未注册`);let s=await n.client.beginOAuthLogin(i);this.emit("serverOAuthStatusChanged",t,"authorizing");let e=s.completion.then(async()=>{this.emit("serverOAuthCompleted",t),this.emit("serverOAuthStatusChanged",t,"authenticated");try{await this.reconnectServer(t)}catch(r){n.lastError=r instanceof Error?r:Error(String(r)),n.status="error",this.emit("serverError",t,n.lastError)}},(r)=>{throw n.lastError=r instanceof Error?r:Error(String(r)),this.emit("serverOAuthError",t,n.lastError),this.emit("serverOAuthStatusChanged",t,"error"),n.lastError});return e.catch(()=>{return}),{...s,completion:e}}async logoutOAuth(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);await i.client.logoutOAuth(),i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.tools=[],this.emit("serverOAuthStatusChanged",t,"unauthenticated")}async refreshAllTools(){let t=[];for(let[i,n]of this.servers)if(n.status==="connected")t.push(this.refreshServerTools(i));await Promise.allSettled(t)}async refreshServerTools(t){let i=this.servers.get(t);if(!i||i.status!=="connected")return;try{await i.client.refreshTools("manual")}catch(n){throw console.warn(`刷新服务器 "${t}" 工具列表失败:`,n),n}}setupClientEventHandlers(t,i,n){t.on("connected",(s)=>{if(i.status="connected",i.connectedAt=new Date,i.lastError=void 0,i.tools=t.availableTools,i.contentCatalog=t.contentCatalog,i.logging=t.logging,i.instructions=this.fitInstructionBudget(n,t.instructions),this.publishCatalog(n,"connection"),this.publishInitialContentCatalog(n,i.contentCatalog),i.instructions)this.publishInstructions(n,"added","connection",i.instructions);this.emit("serverConnected",n,s)}),t.on("disconnected",()=>{i.status="disconnected",i.connectedAt=void 0,i.lastError=void 0,i.recovery=void 0,this.invalidateServerProjection(n,i),this.emit("serverDisconnected",n)}),t.on("error",(s)=>{i.status="error",i.lastError=s,this.invalidateServerProjection(n,i),this.emit("serverError",n,s)}),t.on("connectionLifecycleChanged",(s)=>{if(i.recovery=structuredClone(s),s.phase==="reconnecting")i.status="reconnecting",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError,this.invalidateServerProjection(n,i);else if(s.phase==="recovered")i.status="connected",i.lastError=void 0;else i.status="error",i.connectedAt=void 0,i.lastError=s.error?Error(s.error):i.lastError;this.publishConnectionLifecycle(n,s)}),t.on("toolsUpdated",(s,e)=>{let r=i.tools.length;if(i.tools=s,i.status==="connected"&&e)this.publishCatalog(n,e.reason);this.emit("toolsUpdated",n,s,r)}),t.on("toolsRefreshFailed",(s)=>{this.emit("catalogRefreshFailed",{serverName:n,...s})}),t.on("contentCatalogUpdated",(s,e)=>{if(i.contentCatalog=s,i.status!=="connected")return;this.publishContentCatalogChange(n,e.kind,e.reason,{added:e.added,removed:e.removed,updated:e.updated})}),t.on("contentCatalogRefreshFailed",(s)=>{this.emit("contentCatalogRefreshFailed",{serverName:n,...s})}),t.on("resourceUpdated",(s)=>{if(i.status!=="connected")return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:n,uri:s.uri};this.emit("resourceUpdated",e)}),t.on("statusChanged",(s,e)=>{if(i.status=s,s==="reconnecting"&&e==="connected")i.connectedAt=void 0,this.invalidateServerProjection(n,i);this.emit("serverStatusChanged",n,s,e)}),t.on("loggingLevelChanged",()=>{i.logging=t.logging,this.emit("serverLoggingLevelChanged",n,i.logging.level)}),t.on("log",(s)=>{this.publishLog(n,s)})}publishLog(t,i){this.logRevision++;let n={revision:this.logRevision,serverName:t,...structuredClone(i)};this.logEntries.push(n);let s=0;for(let e=this.logEntries.length-1;e>=0;e--){if(this.logEntries[e]?.serverName!==t)continue;if(s++,s>Tn)this.logEntries.splice(e,1)}while(this.logEntries.length>B)this.logEntries.shift();this.emit("log",structuredClone(n))}invalidateServerProjection(t,i){let n=i.contentCatalog,s=i.instructions!==void 0;if(i.tools=[],i.contentCatalog={resources:[],resourceTemplates:[],prompts:[]},i.instructions=void 0,this.publishCatalog(t,"disconnection"),this.publishRemovedContentCatalog(t,n),s)this.publishInstructions(t,"removed","disconnection")}fitInstructionBudget(t,i){if(!i)return;let n=0;for(let[s,e]of this.servers){if(s===t)continue;n+=e.instructions?.projectedBytes??0}return bn(i,Math.max(0,En-n))}publishInstructions(t,i,n,s){this.instructionsRevision++;let e={revision:this.instructionsRevision,serverName:t,action:i,reason:n,...s?{instruction:structuredClone(s)}:{}};this.emit("instructionsChanged",e)}publishConnectionLifecycle(t,i){this.connectionRevision++;let n={revision:this.connectionRevision,serverName:t,...structuredClone(i)};this.emit("connectionLifecycleChanged",n)}publishCatalog(t,i){let n=new Map;for(let[u,d]of this.servers){if(d.status!=="connected")continue;for(let p of d.tools){let c=Lt(u,p.name);if(n.has(c))throw Error(`Duplicate projected MCP tool "${c}"`);n.set(c,Tt(d.client,u,p,c,this.runtimeOptions.artifactWriter))}}let s=new Map([...this.projectedTools].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),e=new Map([...n].map(([u,d])=>[u,JSON.stringify(d.getFunctionDeclaration())])),r={added:[...n.keys()].filter((u)=>!this.projectedTools.has(u)).sort(),removed:[...this.projectedTools.keys()].filter((u)=>!n.has(u)).sort(),updated:[...n.keys()].filter((u)=>this.projectedTools.has(u)&&s.get(u)!==e.get(u)).sort()};if(this.projectedTools=n,!nt(r))return;this.catalogRevision++;let o={revision:this.catalogRevision,serverName:t,reason:i,tools:[...n.values()],...r};this.emit("catalogChanged",o)}publishInitialContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","connection",{added:i.resources.map((n)=>n.uri).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","connection",{added:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),removed:[],updated:[]}),this.publishContentCatalogChange(t,"prompts","connection",{added:i.prompts.map((n)=>n.name).sort(),removed:[],updated:[]})}publishRemovedContentCatalog(t,i){this.publishContentCatalogChange(t,"resources","disconnection",{added:[],removed:i.resources.map((n)=>n.uri).sort(),updated:[]}),this.publishContentCatalogChange(t,"resourceTemplates","disconnection",{added:[],removed:i.resourceTemplates.map((n)=>n.uriTemplate).sort(),updated:[]}),this.publishContentCatalogChange(t,"prompts","disconnection",{added:[],removed:i.prompts.map((n)=>n.name).sort(),updated:[]})}publishContentCatalogChange(t,i,n,s){if(s.added.length===0&&s.removed.length===0&&s.updated.length===0)return;this.contentCatalogRevision++;let e={revision:this.contentCatalogRevision,serverName:t,kind:i,reason:n,...s};this.emit("contentCatalogChanged",e)}requireConnectedServer(t){let i=this.servers.get(t);if(!i)throw Error(`MCP服务器 "${t}" 未注册`);if(i.status!=="connected")throw Error(`MCP服务器 "${t}" 未连接`);return i}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(t){let i=Object.entries(t).map(([n,s])=>this.registerServer(n,s).catch((e)=>{return console.warn(`注册MCP服务器 "${n}" 失败:`,e),e}));await Promise.allSettled(i)}getStatistics(){let t=0,i=0,n=0;for(let s of this.servers.values())if(s.status==="connected")t++,i+=s.tools.length;else if(s.status==="error")n++;return{totalServers:this.servers.size,connectedServers:t,errorServers:n,totalTools:i,isDiscovering:this.isDiscovering}}async disconnectAll(){let t=[];for(let[i,n]of this.servers)t.push(T.getInstance().cancelClient(n.client).then(()=>n.client.disconnect()).catch((s)=>{console.warn(`断开 MCP 服务器 "${i}" 时出错:`,s)}));await Promise.allSettled(t),this.servers.clear(),this.projectedTools.clear(),this.logEntries=[]}}
25
- export{jt as Da,T as Ea,jn as Fa,vs as Ga,te as Ha,Fi as Ia,Lt as Ja,ts as Ka,O as La};
25
+ export{jt as Ga,T as Ha,jn as Ia,vs as Ja,te as Ka,Fi as La,Lt as Ma,ts as Na,O as Oa};