blade-code 0.10.206 → 0.11.2

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 (175) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-65wc1h38.js → chunk-04qhtx2w.js} +1 -1
  3. package/dist/{chunk-9kj19a8t.js → chunk-0eajnhrj.js} +1 -1
  4. package/dist/{chunk-pga8gxtf.js → chunk-0kxya4ye.js} +1 -1
  5. package/dist/{chunk-nj6kpdte.js → chunk-0wxnrjes.js} +2 -2
  6. package/dist/{chunk-hv8nt7wj.js → chunk-1cy4ab77.js} +1 -1
  7. package/dist/chunk-21qsfewd.js +1 -0
  8. package/dist/{chunk-e45r1a8r.js → chunk-290p3r7a.js} +2 -2
  9. package/dist/{chunk-av799ng5.js → chunk-2fdghgmf.js} +2 -2
  10. package/dist/chunk-3d4wgfkr.js +1 -0
  11. package/dist/{chunk-az3rehz9.js → chunk-3ee357pw.js} +399 -392
  12. package/dist/{chunk-09kqfdpa.js → chunk-4e4qtpca.js} +2 -2
  13. package/dist/{chunk-3crwyd2r.js → chunk-5s2x98rx.js} +2 -2
  14. package/dist/chunk-634ymwg5.js +1 -0
  15. package/dist/chunk-65v1vjvg.js +1 -0
  16. package/dist/{chunk-870szc6v.js → chunk-6v23hdt8.js} +1 -1
  17. package/dist/{chunk-fc1gz532.js → chunk-6x5f6she.js} +2 -2
  18. package/dist/{chunk-erhaedch.js → chunk-7ajvrtb3.js} +1 -1
  19. package/dist/chunk-7p8r4q6f.js +1 -0
  20. package/dist/chunk-7rz5dt79.js +94 -0
  21. package/dist/{chunk-5k8k56f2.js → chunk-8q6zsznc.js} +11 -9
  22. package/dist/{chunk-1n4v80hy.js → chunk-9qxch6sy.js} +1 -1
  23. package/dist/{chunk-9sf1t8gw.js → chunk-a3dz41pd.js} +1 -1
  24. package/dist/{chunk-ed2hdrwe.js → chunk-a95jmx2j.js} +1 -1
  25. package/dist/{chunk-n34qsnks.js → chunk-amabfzc8.js} +1 -1
  26. package/dist/{chunk-6xzk4hsg.js → chunk-b22ab7yw.js} +1 -1
  27. package/dist/{chunk-dnpkf5mv.js → chunk-crv3sghv.js} +2 -2
  28. package/dist/chunk-d4xsrx3z.js +357 -0
  29. package/dist/{chunk-n5jzmwhy.js → chunk-ebvzp8tn.js} +6 -6
  30. package/dist/chunk-eg0s155w.js +1 -0
  31. package/dist/chunk-enmn892r.js +10 -0
  32. package/dist/{chunk-p8vpvx07.js → chunk-er6zghgg.js} +1 -1
  33. package/dist/{chunk-h6ahwwpa.js → chunk-f9qrjd2f.js} +1 -1
  34. package/dist/chunk-fb2x1026.js +171 -0
  35. package/dist/chunk-g0xtk1yy.js +8 -0
  36. package/dist/{chunk-pdna2qvv.js → chunk-g2295k8s.js} +2 -2
  37. package/dist/{chunk-826xegd8.js → chunk-g7pjgspy.js} +2 -2
  38. package/dist/chunk-gff7a5q0.js +1 -0
  39. package/dist/chunk-gymecxcc.js +1 -0
  40. package/dist/{chunk-sqk8cnej.js → chunk-h4b4fn3t.js} +2 -2
  41. package/dist/{chunk-e0ft3vwg.js → chunk-jbpasjg9.js} +1 -1
  42. package/dist/{chunk-xcq0cehr.js → chunk-k2rgg45h.js} +3 -3
  43. package/dist/chunk-kaj8jaj5.js +6 -0
  44. package/dist/{chunk-ewwrss2w.js → chunk-kehgewqh.js} +1 -1
  45. package/dist/{chunk-53vh6vpt.js → chunk-kkzznz4w.js} +1 -1
  46. package/dist/chunk-m2x6pb4f.js +2 -0
  47. package/dist/{chunk-0ef47wgr.js → chunk-n30najxq.js} +2 -2
  48. package/dist/{chunk-h4k69z1b.js → chunk-p36k2e96.js} +1 -1
  49. package/dist/chunk-p665f6pn.js +1 -0
  50. package/dist/chunk-pjeks4cz.js +1 -0
  51. package/dist/{chunk-50vwafn5.js → chunk-pm163dfm.js} +1 -1
  52. package/dist/{chunk-asgmmaec.js → chunk-px45q235.js} +2 -2
  53. package/dist/{chunk-28n945me.js → chunk-q6sr4979.js} +2 -2
  54. package/dist/{chunk-67wy9mm7.js → chunk-qa86anwd.js} +2 -2
  55. package/dist/{chunk-tzvb0nd2.js → chunk-qhcd0ww0.js} +1 -1
  56. package/dist/chunk-qyfbeg5h.js +1 -0
  57. package/dist/{chunk-fnmqxhv1.js → chunk-re8p2y22.js} +1 -1
  58. package/dist/{chunk-9tpzmy8v.js → chunk-s7x4x6xw.js} +1 -1
  59. package/dist/{chunk-gmpsfkgg.js → chunk-sdapqhj0.js} +1 -1
  60. package/dist/{chunk-tsm8rhmd.js → chunk-skktstg8.js} +1 -1
  61. package/dist/chunk-sqsfztrv.js +1 -0
  62. package/dist/chunk-t3pkk95s.js +1 -0
  63. package/dist/{chunk-fd0a8h55.js → chunk-tx9tb485.js} +2 -2
  64. package/dist/{chunk-v4cxk10d.js → chunk-v0eanse2.js} +1 -1
  65. package/dist/chunk-vemyfx92.js +14 -0
  66. package/dist/{chunk-yjjxv7fn.js → chunk-wan9q99y.js} +2 -2
  67. package/dist/{chunk-ebpg1srd.js → chunk-wnzr9h84.js} +2 -2
  68. package/dist/{chunk-t0gm0pn1.js → chunk-x6k5ye1z.js} +1 -1
  69. package/dist/{chunk-gz84aewr.js → chunk-xnys4bgs.js} +1 -1
  70. package/dist/{chunk-v5vx6nz9.js → chunk-xrgeakpy.js} +1 -1
  71. package/dist/{chunk-vx2g1faw.js → chunk-yeandcre.js} +1 -1
  72. package/dist/chunk-yjcp8jk1.js +2 -0
  73. package/dist/{chunk-28tzj187.js → chunk-ys8gysg8.js} +1 -1
  74. package/dist/{chunk-1j39te3t.js → chunk-zf72e5w8.js} +14 -6
  75. package/dist/{chunk-p2y1zqsb.js → chunk-zwe1a7xe.js} +2 -2
  76. package/dist/web/assets/ChatView-DysPZPwF.js +17 -0
  77. package/dist/web/assets/CodeBlockHighlighter-OvLyFs9U.js +8 -0
  78. package/dist/web/assets/FilePreview-CkSPwPdW.js +8 -0
  79. package/dist/web/assets/KanbanBoard-DH1wApt6.js +1 -0
  80. package/dist/web/assets/MarkdownRenderer-BTxnqChi.js +30 -0
  81. package/dist/web/assets/ScrollArea-BdOqyQ3g.js +1 -0
  82. package/dist/web/assets/SessionHistorySurface-DaKE2oKU.js +1 -0
  83. package/dist/web/assets/SettingsModal-CWlSSO_E.js +5 -0
  84. package/dist/web/assets/Sidebar-Dirk-XAQ.js +1 -0
  85. package/dist/web/assets/TaskSwitcher-DKelLFZm.js +1 -0
  86. package/dist/web/assets/TerminalPanel-D5Rieq62.js +1 -0
  87. package/dist/web/assets/archive-CsFSEMp9.js +1 -0
  88. package/dist/web/assets/arrow-left-gaino9Tb.js +1 -0
  89. package/dist/web/assets/calendar-clock-DfHUrEw9.js +1 -0
  90. package/dist/web/assets/chevron-right-Bvu2j6hB.js +1 -0
  91. package/dist/web/assets/clock-3-dWIDc9IF.js +1 -0
  92. package/dist/web/assets/copy-BPfhyh47.js +1 -0
  93. package/dist/web/assets/dist-RGayDvc-.js +11 -0
  94. package/dist/web/assets/download-BR2L5Wme.js +1 -0
  95. package/dist/web/assets/folder-8dmZJ2a6.js +1 -0
  96. package/dist/web/assets/index-B7RyuO2x.css +1 -0
  97. package/dist/web/assets/index-DSa8Dzp7.js +11 -0
  98. package/dist/web/assets/message-square-plus-BgC981WF.js +1 -0
  99. package/dist/web/assets/pause-DLZIDFMB.js +1 -0
  100. package/dist/web/assets/pencil-DkC0bPYD.js +1 -0
  101. package/dist/web/assets/play-BVeNn6fv.js +1 -0
  102. package/dist/web/assets/plus-kzdwas-3.js +1 -0
  103. package/dist/web/assets/preload-helper-DvgLbiBV.js +1 -0
  104. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  105. package/dist/web/assets/session-events-BuMTbIwu.js +23 -0
  106. package/dist/web/assets/settings-msYyNDKx.js +1 -0
  107. package/dist/web/assets/team-D3XOVbxL.js +1 -0
  108. package/dist/web/assets/teamService-Bus5RDi1.js +1 -0
  109. package/dist/web/assets/terminal-Cp5WYo8w.js +1 -0
  110. package/dist/web/assets/triangle-alert-cGqHxFsZ.js +1 -0
  111. package/dist/web/assets/vendor-radix-L0yJCKJX.js +41 -0
  112. package/dist/web/assets/vendor-react-CHEIQMI-.js +9 -0
  113. package/dist/web/assets/vendor-xterm-CANZO_wP.js +16 -0
  114. package/dist/web/assets/vendor-xterm-CHOd7Rch.css +1 -0
  115. package/dist/web/index.html +6 -4
  116. package/package.json +11 -10
  117. package/dist/chunk-514va7ce.js +0 -2
  118. package/dist/chunk-6p0hkf4f.js +0 -1
  119. package/dist/chunk-793wjhvz.js +0 -332
  120. package/dist/chunk-867bpjzg.js +0 -1
  121. package/dist/chunk-983hqzat.js +0 -1
  122. package/dist/chunk-af0m5227.js +0 -1
  123. package/dist/chunk-dpg006xj.js +0 -1
  124. package/dist/chunk-g7tphxme.js +0 -6
  125. package/dist/chunk-gpnkxh4c.js +0 -1
  126. package/dist/chunk-hpge30p8.js +0 -8
  127. package/dist/chunk-mtvbm7xe.js +0 -1
  128. package/dist/chunk-mys9mmcp.js +0 -1
  129. package/dist/chunk-new78c3h.js +0 -1
  130. package/dist/chunk-nng1xbsm.js +0 -10
  131. package/dist/chunk-pt0y4zrg.js +0 -14
  132. package/dist/chunk-q6abav45.js +0 -171
  133. package/dist/chunk-r4em0ha7.js +0 -1
  134. package/dist/chunk-rdzbd5vk.js +0 -1
  135. package/dist/chunk-sbfe9vh3.js +0 -94
  136. package/dist/chunk-w6zat4v4.js +0 -1
  137. package/dist/chunk-wsd3rn0q.js +0 -1
  138. package/dist/chunk-yzf2jpam.js +0 -2
  139. package/dist/web/assets/ChatView-lUD-61n0.js +0 -70
  140. package/dist/web/assets/CodeBlockHighlighter--TbfcBxW.js +0 -8
  141. package/dist/web/assets/FilePreview-R6OKQPf2.js +0 -55
  142. package/dist/web/assets/KanbanBoard-BHOKtiv5.js +0 -16
  143. package/dist/web/assets/MarkdownRenderer-DqxNq8pa.js +0 -30
  144. package/dist/web/assets/ScrollArea-Dhu0B-zB.js +0 -1
  145. package/dist/web/assets/SessionHistorySurface-aZvoj3ma.js +0 -6
  146. package/dist/web/assets/SettingsModal-C7QBnIqa.js +0 -20
  147. package/dist/web/assets/Sidebar-Bznnq91x.js +0 -31
  148. package/dist/web/assets/TaskSwitcher-DJczhDRp.js +0 -26
  149. package/dist/web/assets/TerminalPanel-Vk4p0V3p.js +0 -6
  150. package/dist/web/assets/archive-0hLYBKQf.js +0 -6
  151. package/dist/web/assets/arrow-left-CXb6Gqf3.js +0 -6
  152. package/dist/web/assets/calendar-clock-DiaFI9Jk.js +0 -6
  153. package/dist/web/assets/chevron-right-CcPXH37D.js +0 -6
  154. package/dist/web/assets/clock-3-D6VR6gJc.js +0 -6
  155. package/dist/web/assets/copy-C3eUAQgp.js +0 -6
  156. package/dist/web/assets/download-DHvS9tI3.js +0 -6
  157. package/dist/web/assets/external-link-BDVaEuqY.js +0 -11
  158. package/dist/web/assets/folder-B80Ac6rr.js +0 -11
  159. package/dist/web/assets/index-B5mUEr6D.js +0 -11
  160. package/dist/web/assets/index-VwIiNjc8.css +0 -1
  161. package/dist/web/assets/index-YqughEZk.js +0 -211
  162. package/dist/web/assets/message-square-plus-D15quyPH.js +0 -21
  163. package/dist/web/assets/pause-BjMlj6Bx.js +0 -6
  164. package/dist/web/assets/pencil-BMoJvcB7.js +0 -6
  165. package/dist/web/assets/play-BHh4py3p.js +0 -6
  166. package/dist/web/assets/plus-DeFz_gQq.js +0 -6
  167. package/dist/web/assets/session-events-DCHBz9We.js +0 -25
  168. package/dist/web/assets/settings-CI8xbId2.js +0 -6
  169. package/dist/web/assets/team-zZ803hH9.js +0 -6
  170. package/dist/web/assets/teamService-CgLBXgmv.js +0 -1
  171. package/dist/web/assets/terminal-1WxSJ47E.js +0 -6
  172. package/dist/web/assets/vendor-radix-D6QrtXqd.js +0 -45
  173. package/dist/web/assets/vendor-react-DofNRwfy.js +0 -49
  174. package/dist/web/assets/vendor-xterm-9CEnUXvW.css +0 -32
  175. package/dist/web/assets/vendor-xterm-DuYZoU4T.js +0 -49
@@ -1,5 +1,13 @@
1
- import{w as JH,x as QH,z as r}from"./chunk-tzvb0nd2.js";import{A as fz,B as uz,C as gz,D as S}from"./chunk-fnmqxhv1.js";import{E as HH,F as bz,G as Rz,H as Sz,I as Mz,J as Iz}from"./chunk-h6ahwwpa.js";import{Da as hz,Ea as yz,Fa as kz,Ga as Cz,Q as R,Z as Oz,_ as Ez,ga as qz,ja as Tz,ka as Pz,na as xz}from"./chunk-az3rehz9.js";import"./chunk-ebpg1srd.js";import{Ua as zH}from"./chunk-e45r1a8r.js";import{Wa as Az,_a as i,bb as a}from"./chunk-fc1gz532.js";import{Qb as wz,ac as Nz,lc as l}from"./chunk-793wjhvz.js";import{wc as m}from"./chunk-1n4v80hy.js";import{Gd as _z,Qd as I,Rd as d,Sd as Vz,Xd as Dz,_d as Fz,ae as M,de as Kz,ie as jz,le as K}from"./chunk-sbfe9vh3.js";import"./chunk-tsm8rhmd.js";import{Je as Uz,Qe as n,Re as Gz}from"./chunk-yjjxv7fn.js";import"./chunk-0ef47wgr.js";import{Cf as YH}from"./chunk-67wy9mm7.js";import"./chunk-dnpkf5mv.js";import{Xf as oz,Yf as sz}from"./chunk-n5jzmwhy.js";import{dg as zz}from"./chunk-t0gm0pn1.js";import"./chunk-v508x7cg.js";import{ig as Bz}from"./chunk-hpge30p8.js";import{qg as p}from"./chunk-28n945me.js";import"./chunk-pdna2qvv.js";import{vg as tz}from"./chunk-50vwafn5.js";import"./chunk-p2y1zqsb.js";import"./chunk-5k8k56f2.js";import"./chunk-ewwrss2w.js";import"./chunk-53vh6vpt.js";import{qh as ez}from"./chunk-hv8nt7wj.js";import"./chunk-erhaedch.js";import"./chunk-xcq0cehr.js";import"./chunk-28tzj187.js";import{vi as rz,yi as nz}from"./chunk-sqk8cnej.js";import{Ui as g,Vi as Wz,Xi as c,Yi as v}from"./chunk-514va7ce.js";import{aj as e}from"./chunk-6xzk4hsg.js";import"./chunk-n34qsnks.js";import{Cj as h}from"./chunk-09kqfdpa.js";import"./chunk-3crwyd2r.js";import{Pj as iz,Sj as az}from"./chunk-9kj19a8t.js";import"./chunk-yzf2jpam.js";import"./chunk-asgmmaec.js";import{dk as Lz,ek as dz,ik as Hz,mk as Jz,nk as lz,ok as Qz}from"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.js";import{Readable as wH,Writable as NH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as VH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as cz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=h("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Xz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function XH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Xz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Xz("headers"in z?z.headers:void 0)};return null}function LH(z){let H={};for(let J of z){let Y=XH(J);if(Y)H[J.name]=Y}return H}function vz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function WH(z){let H=Gz(z.metadata);return H?[{type:"text",text:n(H)}]:vz(z.content)}function BH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}function _H(z){if(!Bz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function UH(z){if(!(z instanceof cz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Vz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function GH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,J,Y,X={}){this.id=z;this.roots=H;this.connection=J;this.clientCapabilities=Y;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Iz({maxPendingItems:bz,maxPendingBytes:Rz,writeTimeoutMs:Sz,signal:J.signal,sizeOf:(L)=>Buffer.byteLength(JSON.stringify(L)),write:async(L)=>{await J.sessionUpdate(L)},onFailure:(L)=>this.handleUpdateEgressFailure(L)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(J){if(!(J instanceof jz)&&J.code!=="ENOENT")throw J;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return xz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async($)=>{await this.sendUpdateAndWait($)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:($)=>this.requestPermission($)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?LH(this.options.mcpServers):void 0,Y=R.getTerminalService(this.id),X=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await qz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...X?{workspace:X}:{},permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,_)=>{let U=await Y.execute($,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=wz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.roots.hostStateRoot)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="follow_up.queue.changed"){let _=i.safeParse($.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if($.type==="provider.recovery"){let _=p.safeParse($.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if($.type==="turn.activity"){let _=a.safeParse($.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=$.properties,T=$.properties.metadata;if($.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Ez(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Oz(_,Lz()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!Uz(H))continue;let J=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of WH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],model:{getChatConfig:()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getChatService().getConfig()}},rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,$,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else $=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,$)_($);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),$=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:$.status,findings:$.findings.length,content:_z(_.start,$)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let $=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await kz(z,J),X=Y.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let L=Y.content||Y.message;if(L)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:L}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(H.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,J,Y=new Promise((X)=>{J=X});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch(X){if(H.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Cz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter((X)=>!H.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let L;if(X.usage){let Q=X.usage.replace(/^\/\w+\s*/,"").trim();if(Q)L=Q}if(X.aliases?.length){let Q=`Aliases: ${X.aliases.join(", ")}`;L=L?`${L} | ${Q}`:Q}return{name:X.name,description:X.description,input:L?{hint:L}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,X=J.displayText,L=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(L!==void 0)Q=Kz(L).schema;if(X.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let W=Az(X);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((D)=>D.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),this.sendFollowUpQueueSnapshot(D.queue??await this.runtime.getFollowUpQueueSnapshot()),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,$=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)$();else H.abortSignal?.addEventListener("abort",$,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((D)=>{T=D});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),hz(X)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,B.signal)}let D={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Z)=>{this.mode=this.mapPermissionModeToMode(Z),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Z)=>{return this.requestPermission(Z)}}},N=await Nz(this.agent.chatStream(Y,D,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(Z)=>{switch(Z.kind){case"content_delta":if(Q)break;if(Z.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z.delta}});break;case"thinking_delta":if(Z.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Z.delta}});break;case"tool_start":{V=!0;let F=Z.toolCall,A=F.function.name;if(A===M)break;let q=this.mapToolKind(Z.toolKind),j=`Executing ${A}`;if(A==="Task"&&"function"in F)try{let b=JSON.parse(F.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")j=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.id,status:"in_progress",title:j,content:[],kind:q});break}case"tool_progress":{V=!0;let F=Z.toolCall;if(F.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.update.message}}]});break}case"tool_result":{V=!0;let F=Z.toolCall;if(F.function.name===M)break;let A=Z.result,q=[],j=A.metadata;if(j?.kind==="patch"&&Array.isArray(j.changes))for(let w of j.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(j?.kind==="edit"&&typeof j.file_path==="string"&&typeof j.oldContent==="string"&&(typeof j.newContent==="string"||j.newContent===void 0))q.push({type:"diff",path:j.file_path,oldText:j.oldContent,newText:j.newContent??null});else{let w=F.function.name,ZH=Pz(Fz(Tz(w,A),Dz));q.push({type:"content",content:{type:"text",text:ZH}})}if(F.function.name==="Task"&&(j?.verificationVerdict==="pass"||j?.verificationVerdict==="fail"||j?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${j.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Z.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Z.revision} (${Z.serverName}): +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}
1
+ import{w as QH,x as YH,z as a}from"./chunk-qhcd0ww0.js";import{A as uz,B as gz,C as cz,D as S}from"./chunk-re8p2y22.js";import{E as JH,F as Rz,G as Sz,H as Mz,I as Iz,J as hz}from"./chunk-f9qrjd2f.js";import{$ as qz,Ea as yz,Fa as kz,Ga as Cz,Ha as fz,Q as R,_ as Ez,ha as Tz,ka as Pz,la as xz,oa as bz}from"./chunk-3ee357pw.js";import"./chunk-wnzr9h84.js";import{Va as HH}from"./chunk-290p3r7a.js";import{$a as i,Xa as Oz,cb as r}from"./chunk-6x5f6she.js";import{Rb as Nz,bc as Az,mc as l}from"./chunk-d4xsrx3z.js";import{xc as m}from"./chunk-9qxch6sy.js";import{$d as Fz,Hd as _z,Rd as I,Sd as d,Td as Vz,Yd as Dz,ae as Kz,ce as M,fe as jz,ke as wz,ne as K}from"./chunk-7rz5dt79.js";import"./chunk-skktstg8.js";import{Le as Uz,Se as n,Te as Gz}from"./chunk-wan9q99y.js";import"./chunk-n30najxq.js";import{Ef as ZH}from"./chunk-qa86anwd.js";import"./chunk-crv3sghv.js";import{Zf as sz,_f as tz}from"./chunk-ebvzp8tn.js";import{fg as zz}from"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import{kg as Bz}from"./chunk-g0xtk1yy.js";import{sg as p}from"./chunk-q6sr4979.js";import"./chunk-g2295k8s.js";import{xg as ez}from"./chunk-pm163dfm.js";import"./chunk-zwe1a7xe.js";import"./chunk-8q6zsznc.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import{sh as zH}from"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-k2rgg45h.js";import"./chunk-ys8gysg8.js";import{Ai as oz,xi as nz}from"./chunk-h4b4fn3t.js";import{Zi as e}from"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import{Aj as v,wj as g,xj as Wz,zj as c}from"./chunk-m2x6pb4f.js";import{Ej as h}from"./chunk-4e4qtpca.js";import"./chunk-5s2x98rx.js";import{Rj as rz,Uj as az}from"./chunk-0eajnhrj.js";import"./chunk-yjcp8jk1.js";import"./chunk-px45q235.js";import{fk as Lz,gk as lz,kk as Hz,ok as Jz,pk as iz,qk as Qz}from"./chunk-a95jmx2j.js";import"./chunk-sdapqhj0.js";import{Readable as NH,Writable as AH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as DH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as vz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=h("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Xz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function LH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Xz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Xz("headers"in z?z.headers:void 0)};return null}function WH(z){let H={};for(let J of z){let Y=LH(J);if(Y)H[J.name]=Y}return H}function pz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function BH(z){let H=Gz(z.metadata);return H?[{type:"text",text:n(H)}]:pz(z.content)}function _H(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}function UH(z){if(!Bz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function GH(z){if(!(z instanceof vz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Vz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function VH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,J,Y,X={}){this.id=z;this.roots=H;this.connection=J;this.clientCapabilities=Y;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new hz({maxPendingItems:Rz,maxPendingBytes:Sz,writeTimeoutMs:Mz,signal:J.signal,sizeOf:(L)=>Buffer.byteLength(JSON.stringify(L)),write:async(L)=>{await J.sessionUpdate(L)},onFailure:(L)=>this.handleUpdateEgressFailure(L)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(J){if(!(J instanceof wz)&&J.code!=="ENOENT")throw J;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return bz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async($)=>{await this.sendUpdateAndWait($)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:($)=>this.requestPermission($)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?WH(this.options.mcpServers):void 0,Y=R.getTerminalService(this.id),X=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Tz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...X?{workspace:X}:{},permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,_)=>{let U=await Y.execute($,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await kz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Nz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.roots.hostStateRoot)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="follow_up.queue.changed"){let _=i.safeParse($.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if($.type==="provider.recovery"){let _=p.safeParse($.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if($.type==="turn.activity"){let _=r.safeParse($.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=$.properties,T=$.properties.metadata;if($.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&qz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Ez(_,Lz()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!Uz(H))continue;if(Kz(H)&&typeof H.content==="string"){if(!await this.sendUpdateAndWait({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
3
+
4
+ recap: ${H.content}
5
+
6
+ `},_meta:{"blade/conversationRecap":!0}}))return;continue}let J=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of BH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],model:{getChatConfig:()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getChatService().getConfig()}},rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,$,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else $=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,$)_($);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),$=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:$.status,findings:$.findings.length,content:_z(_.start,$)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let $=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await Cz(z,J),X=Y.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let L=Y.content||Y.message;if(L)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:L}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(H.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,J,Y=new Promise((X)=>{J=X});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch(X){if(H.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=fz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter((X)=>!H.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let L;if(X.usage){let Q=X.usage.replace(/^\/\w+\s*/,"").trim();if(Q)L=Q}if(X.aliases?.length){let Q=`Aliases: ${X.aliases.join(", ")}`;L=L?`${L} | ${Q}`:Q}return{name:X.name,description:X.description,input:L?{hint:L}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,X=J.displayText,L=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(L!==void 0)Q=jz(L).schema;if(X.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let W=Oz(X);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((D)=>D.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),this.sendFollowUpQueueSnapshot(D.queue??await this.runtime.getFollowUpQueueSnapshot()),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,$=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)$();else H.abortSignal?.addEventListener("abort",$,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((D)=>{T=D});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),yz(X)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,B.signal)}let D={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Z)=>{this.mode=this.mapPermissionModeToMode(Z),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Z)=>{return this.requestPermission(Z)}}},N=await Az(this.agent.chatStream(Y,D,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(Z)=>{switch(Z.kind){case"conversation_recap":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
7
+
8
+ recap: ${Z.text}
9
+
10
+ `},_meta:{"blade/conversationRecap":!0}});break;case"content_delta":if(Q)break;if(Z.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z.delta}});break;case"thinking_delta":if(Z.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Z.delta}});break;case"tool_start":{V=!0;let F=Z.toolCall,A=F.function.name;if(A===M)break;let q=this.mapToolKind(Z.toolKind),j=`Executing ${A}`;if(A==="Task"&&"function"in F)try{let b=JSON.parse(F.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")j=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.id,status:"in_progress",title:j,content:[],kind:q});break}case"tool_progress":{V=!0;let F=Z.toolCall;if(F.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.update.message}}]});break}case"tool_result":{V=!0;let F=Z.toolCall;if(F.function.name===M)break;let A=Z.result,q=[],j=A.metadata;if(j?.kind==="patch"&&Array.isArray(j.changes))for(let w of j.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(j?.kind==="edit"&&typeof j.file_path==="string"&&typeof j.oldContent==="string"&&(typeof j.newContent==="string"||j.newContent===void 0))q.push({type:"diff",path:j.file_path,oldText:j.oldContent,newText:j.newContent??null});else{let w=F.function.name,$H=xz(Fz(Pz(w,A),Dz));q.push({type:"content",content:{type:"text",text:$H}})}if(F.function.name==="Task"&&(j?.verificationVerdict==="pass"||j?.verificationVerdict==="fail"||j?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${j.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Z.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Z.revision} (${Z.serverName}): +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}
3
11
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Z.contentKind} r${Z.revision} (${Z.serverName}): +${Z.added.length} -${Z.removed.length} ~${Z.updated.length}
4
12
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Z.revision} (${Z.serverName}): ${Z.uri}
5
13
  `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Z.revision} (${Z.serverName}): ${Z.phase} ${Z.attempt}/${Z.maxAttempts}
@@ -7,17 +15,17 @@ import{w as JH,x as QH,z as r}from"./chunk-tzvb0nd2.js";import{A as fz,B as uz,C
7
15
  `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Z.revision} (${Z.serverName}): ${Z.action}${Z.detailsOmitted?" details-omitted":""}
8
16
  `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Z.revision} ${Z.taskId} (${Z.serverName}/${Z.toolName}): ${Z.status}${Z.hasResult?" result-available":""}
9
17
  `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Z.files.length}${Z.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_admission":_=Z.phase!=="admitted",this.sendSessionMetadata("blade/providerAdmission",Z.phase==="admitted"?null:r(Z,{omitUndefined:!0})?.properties);break;case"provider_circuit":this.sendProjectedLoopMetadata("blade/providerCircuit",Z);break;case"provider_retry":this.sendProjectedLoopMetadata("blade/providerRetry",Z);break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z.assessment}});break;case"provider_stall":this.sendProjectedLoopMetadata("blade/providerStall",Z);break;case"provider_recovery":break;case"turn_activity":break;case"model_fallback":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/modelFallback":{from:Z.from,to:Z.to,candidate:Z.candidate,candidateCount:Z.candidateCount,trigger:Z.trigger}}});break;case"action_stationarity":this.sendProjectedLoopMetadata("blade/actionStationarity",Z);break;case"task_update":this.sendPlanUpdate(Z.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:Z.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:Z.goal.goalId,status:Z.goal.status,taskListId:Z.frontier.taskListId,total:Z.frontier.total,completed:Z.frontier.completed,inProgress:Z.frontier.inProgress,pending:Z.frontier.pending,blocked:Z.frontier.blocked,nextTask:Z.frontier.nextTask,digestSha256:Z.frontier.digestSha256,...Z.goal.frontierStall?{stall:{category:Z.goal.frontierStall.category,consecutiveCount:Z.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(Z.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(Z.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(Z.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(Z.queue);let F=0;for(let A of Z.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of vz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),F++}if(F>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${F} queued instruction${F===1?"":"s"} recovered after restart]
18
+ `}});break;case"provider_admission":_=Z.phase!=="admitted",this.sendSessionMetadata("blade/providerAdmission",Z.phase==="admitted"?null:a(Z,{omitUndefined:!0})?.properties);break;case"provider_circuit":this.sendProjectedLoopMetadata("blade/providerCircuit",Z);break;case"provider_retry":this.sendProjectedLoopMetadata("blade/providerRetry",Z);break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z.assessment}});break;case"provider_stall":this.sendProjectedLoopMetadata("blade/providerStall",Z);break;case"provider_recovery":break;case"turn_activity":break;case"model_fallback":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/modelFallback":{from:Z.from,to:Z.to,candidate:Z.candidate,candidateCount:Z.candidateCount,trigger:Z.trigger}}});break;case"action_stationarity":this.sendProjectedLoopMetadata("blade/actionStationarity",Z);break;case"task_update":this.sendPlanUpdate(Z.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:Z.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:Z.goal.goalId,status:Z.goal.status,taskListId:Z.frontier.taskListId,total:Z.frontier.total,completed:Z.frontier.completed,inProgress:Z.frontier.inProgress,pending:Z.frontier.pending,blocked:Z.frontier.blocked,nextTask:Z.frontier.nextTask,digestSha256:Z.frontier.digestSha256,...Z.goal.frontierStall?{stall:{category:Z.goal.frontierStall.category,consecutiveCount:Z.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(Z.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(Z.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(Z.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(Z.queue);let F=0;for(let A of Z.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of pz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),F++}if(F>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${F} queued instruction${F===1?"":"s"} recovered after restart]
11
19
  `}});break}case"goal_updated":if(Z.goal)this.sendUpdate(this.goalSessionUpdate(Z.goal));if(Z.goal&&Z.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Z.goal.status}: ${Z.goal.objective}]
12
- `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Z.goal.goalId,continuation:Z.continuation,...Z.prematureStopPattern?{prematureStopPattern:Z.prematureStopPattern}:{},...Z.prematureStopCount!==void 0?{prematureStopCount:Z.prematureStopCount}:{},...Z.goal.executionHostFailure?{executionHostFailure:{category:Z.goal.executionHostFailure.category,consecutiveCount:Z.goal.executionHostFailure.consecutiveCount}}:{},...Z.goal.turnLineage?{turnLineage:Z.goal.turnLineage}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Z.phase,...Z.reason?{reason:Z.reason}:{},...Z.strategy?{strategy:Z.strategy}:{},...Z.outcome?{outcome:Z.outcome}:{},...Z.preTokens!==void 0?{preTokens:Z.preTokens}:{},...Z.preTokenSource?{preTokenSource:Z.preTokenSource}:{},...Z.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Z.estimatedPendingTokens}:{},...Z.postTokens!==void 0?{postTokens:Z.postTokens}:{},...Z.sampleAttempts!==void 0?{sampleAttempts:Z.sampleAttempts}:{},...Z.inputReductions!==void 0?{inputReductions:Z.inputReductions}:{},...Z.messagesOmitted!==void 0?{messagesOmitted:Z.messagesOmitted}:{},...Z.filesOmitted!==void 0?{filesOmitted:Z.filesOmitted}:{},...Z.imagesOmitted!==void 0?{imagesOmitted:Z.imagesOmitted}:{},...Z.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Z.fallbackTargetTokens}:{},...Z.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Z.fallbackMessagesOmitted}:{},...Z.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Z.fallbackMessagesTruncated}:{},...Z.failureReason?{failureReason:Z.failureReason}:{},...Z.memory?{memory:Z.memory}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...D.messages];let Zz=await this.loadPersistedMessages();if(this.messages=Zz.length>0?Zz:[...D.messages],!N.success){let Z=N.error?.type??"unknown",F=N.error?.details??N.error?.message??"Agent execution failed",A=_H(F)??d(F);throw cz.internalError({failureType:Z,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Z})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let $z={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys($z).length>0?{_meta:$z}:{}}}catch(D){if(B.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(H.abortSignal?.removeEventListener("abort",$),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let J=new AbortController,Y,X=new Promise((W)=>{Y=W});this.pendingUserShell=J,this.pendingUserShellCompletion=X;let L,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:J.signal,onEvent:async($)=>{if(L=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){Q+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let _=n($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?BH($.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(L)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,J=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(J,z),this.pendingResumeTimer.unref?.();else queueMicrotask(J)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let J=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,J!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(J)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let J=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,J!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(J)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:fz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let J="preflight",Y=!1,X,L=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",$=this.runtime.getTurnRecoveryAssessment();if($.state!=="none"&&($.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if($.state==="requires_attention"){this.clearPendingResumeRequest();return}J=Q?"pending_input":"goal",Y=!0;let _=uz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:J,taskFailure:I("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}let U=new AbortController;L=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),L.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:J==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:J,taskFailure:I("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:J})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?UH(Q):{taskFailure:d(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=J==="preflight"||J==="pending_input"&&this.runtime.getPendingSteeringCount()>0,$=gz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if($.phase==="retry_scheduled")this.pendingResumeRequested=!0,X=$.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:J,taskFailure:W?.taskFailure,delayMs:$.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${$.delayMs}ms`);else{let _=$.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:J,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${$.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest()}}finally{if(L!==null)clearTimeout(L);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=X??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(J);await this.persistPermissionMode(Y),this.mode=J,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(J){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(J){throw await this.runtime.refresh({reasoningEffort:H.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(J){throw await this.runtime.refresh({serviceTier:H.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(J){throw await this.runtime.refresh({responseVerbosity:H.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Mz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,J=this.runtime,Y=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,L=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async($)=>{try{await $()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if(X)await B(()=>X);if(L)await B(()=>L);if(Q)await B(()=>Q);if(z&&Y&&J)await B(()=>J.discardPendingInput());if(H)await B(()=>H.destroy());if(J)await B(()=>J.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],J=[],Y=0,X=0,L=0,Q=($)=>{if(J.length>0)J.push({type:"text",text:`
20
+ `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Z.goal.goalId,continuation:Z.continuation,...Z.prematureStopPattern?{prematureStopPattern:Z.prematureStopPattern}:{},...Z.prematureStopCount!==void 0?{prematureStopCount:Z.prematureStopCount}:{},...Z.goal.executionHostFailure?{executionHostFailure:{category:Z.goal.executionHostFailure.category,consecutiveCount:Z.goal.executionHostFailure.consecutiveCount}}:{},...Z.goal.turnLineage?{turnLineage:Z.goal.turnLineage}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Z.phase,...Z.reason?{reason:Z.reason}:{},...Z.strategy?{strategy:Z.strategy}:{},...Z.outcome?{outcome:Z.outcome}:{},...Z.preTokens!==void 0?{preTokens:Z.preTokens}:{},...Z.preTokenSource?{preTokenSource:Z.preTokenSource}:{},...Z.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Z.estimatedPendingTokens}:{},...Z.postTokens!==void 0?{postTokens:Z.postTokens}:{},...Z.sampleAttempts!==void 0?{sampleAttempts:Z.sampleAttempts}:{},...Z.inputReductions!==void 0?{inputReductions:Z.inputReductions}:{},...Z.messagesOmitted!==void 0?{messagesOmitted:Z.messagesOmitted}:{},...Z.filesOmitted!==void 0?{filesOmitted:Z.filesOmitted}:{},...Z.imagesOmitted!==void 0?{imagesOmitted:Z.imagesOmitted}:{},...Z.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Z.fallbackTargetTokens}:{},...Z.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Z.fallbackMessagesOmitted}:{},...Z.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Z.fallbackMessagesTruncated}:{},...Z.failureReason?{failureReason:Z.failureReason}:{},...Z.memory?{memory:Z.memory}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...D.messages];let Zz=await this.loadPersistedMessages();if(this.messages=Zz.length>0?Zz:[...D.messages],!N.success){let Z=N.error?.type??"unknown",F=N.error?.details??N.error?.message??"Agent execution failed",A=UH(F)??d(F);throw vz.internalError({failureType:Z,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Z})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let $z={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys($z).length>0?{_meta:$z}:{}}}catch(D){if(B.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(H.abortSignal?.removeEventListener("abort",$),_&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(T(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let H=z.trimStart().slice(1).trim();if(!H)throw Error("User shell command cannot be empty");let J=new AbortController,Y,X=new Promise((W)=>{Y=W});this.pendingUserShell=J,this.pendingUserShellCompletion=X;let L,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:J.signal,onEvent:async($)=>{if(L=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){Q+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let _=n($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?_H($.record):_}}]})}}),B={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(B),this.contextMessages.push(B),W.queue)this.sendFollowUpQueueSnapshot(W.queue);if(W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(L)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let H=this.pendingResumeGeneration,J=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(J,z),this.pendingResumeTimer.unref?.();else queueMicrotask(J)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let H=this.resumePendingIfIdle();this.pendingResumeCompletion=H,H.then(()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let J=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,J!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(J)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let J=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,J!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(J)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,H){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:H.kind,attempt:H.attempt,maxAttempts:uz,...H.delayMs!==void 0?{delayMs:H.delayMs,nextRetryAt:Date.now()+H.delayMs}:{},...H.taskFailure?{failure:{code:H.taskFailure.code,retryable:H.taskFailure.retryable,...H.taskFailure.resource?{resource:H.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,H=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=H,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let J="preflight",Y=!1,X,L=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=W?.status==="active"||W?.status==="verifying",$=this.runtime.getTurnRecoveryAssessment();if($.state!=="none"&&($.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if($.state==="requires_attention"){this.clearPendingResumeRequest();return}J=Q?"pending_input":"goal",Y=!0;let _=gz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:J,taskFailure:I("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}let U=new AbortController;L=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),L.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:J==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:U.signal});if(z!==this.pendingResumeGeneration)return;if(U.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:J,taskFailure:I("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:J})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=Y?GH(Q):{taskFailure:d(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=J==="preflight"||J==="pending_input"&&this.runtime.getPendingSteeringCount()>0,$=cz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if($.phase==="retry_scheduled")this.pendingResumeRequested=!0,X=$.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:J,taskFailure:W?.taskFailure,delayMs:$.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${$.delayMs}ms`);else{let _=$.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:J,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${$.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest()}}finally{if(L!==null)clearTimeout(L);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=X??0}}cancel(){G.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(J);await this.persistPermissionMode(Y),this.mode=J,G.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(G.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(J){if(H&&H!==z)await this.agent.switchModel(H).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw J}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(H.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(J){throw await this.runtime.refresh({reasoningEffort:H.selection}),J}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(H.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(J){throw await this.runtime.refresh({serviceTier:H.selection}),J}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(H.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(J){throw await this.runtime.refresh({responseVerbosity:H.selection}),J}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let H=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(H.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:H.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((H)=>structuredClone(H)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new Iz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,J=this.runtime,Y=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,L=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async($)=>{try{await $()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if(X)await B(()=>X);if(L)await B(()=>L);if(Q)await B(()=>Q);if(z&&Y&&J)await B(()=>J.discardPendingInput());if(H)await B(()=>H.destroy());if(J)await B(()=>J.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,G.debug(`[AcpSession ${this.id}] Destroyed`),W!==void 0)throw W}resolvePrompt(z){let H=[],J=[],Y=0,X=0,L=0,Q=($)=>{if(J.length>0)J.push({type:"text",text:`
13
21
  `}),L+=1;if(J.push($),$.type==="text")L+=$.text.length};for(let $ of z)if($.type==="text")H.push($.text),Q({type:"text",text:$.text});else if($.type==="image"){let _=`data:${$.mimeType};base64,${$.data}`;Y+=1,X+=_.length,H.push(`[Image: ${$.mimeType}]`),Q({type:"image_url",image_url:{url:_}})}else if($.type==="resource"){let _=$.resource;if("text"in _){let U=`<file path="${_.uri}">
14
22
  ${_.text}
15
23
  </file>`;H.push(U),Q({type:"text",text:U})}}else if($.type==="resource_link"){let _=`[Resource: ${$.uri}]`;H.push(_),Q({type:"text",text:_})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if(X>Wz)throw Error("ACP prompt images exceed the 5 MiB limit");if(L>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(H.join(`
16
24
  `),"utf8")>v)throw Error(`ACP prompt text exceeds ${v} bytes`);let B=H.join(`
17
- `);return{content:Y>0?J:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let H=this.updateEgress.offer({sessionId:this.id,update:z});if(!H.accepted)return!1;try{return await H.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount,...z.executionHostFailure?{executionHostFailure:{category:z.executionHostFailure.category,consecutiveCount:z.executionHostFailure.consecutiveCount}}:{},...z.turnLineage?{turnLineage:z.turnLineage}:{}}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendSessionMetadata("blade/followUpQueue",GH(H.data))}sendProviderRecoveryProjection(z){let H=p.safeParse(z);if(!H.success)return;this.sendSessionMetadata("blade/providerRecovery",H.data)}sendTurnActivityProjection(z){let H=a.safeParse(z);if(!H.success)return;if(H.data.generation===this.lastTurnActivityGeneration&&H.data.revision<=this.lastTurnActivityRevision)return;this.lastTurnActivityGeneration=H.data.generation,this.lastTurnActivityRevision=H.data.revision,this.sendSessionMetadata("blade/turnActivity",H.data)}sendProjectedLoopMetadata(z,H){let J=r(H,{omitUndefined:!0});if(J)this.sendSessionMetadata(z,J.properties)}sendSessionMetadata(z,H){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{[z]:H}})}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let H=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${H.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:H})}async requestPermission(z){let H=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,H);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,H);let J=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(J))return G.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.details)X.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
25
+ `);return{content:Y>0?J:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let H=this.updateEgress.offer({sessionId:this.id,update:z});if(!H.accepted)return!1;try{return await H.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount,...z.executionHostFailure?{executionHostFailure:{category:z.executionHostFailure.category,consecutiveCount:z.executionHostFailure.consecutiveCount}}:{},...z.turnLineage?{turnLineage:z.turnLineage}:{}}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendSessionMetadata("blade/followUpQueue",VH(H.data))}sendProviderRecoveryProjection(z){let H=p.safeParse(z);if(!H.success)return;this.sendSessionMetadata("blade/providerRecovery",H.data)}sendTurnActivityProjection(z){let H=r.safeParse(z);if(!H.success)return;if(H.data.generation===this.lastTurnActivityGeneration&&H.data.revision<=this.lastTurnActivityRevision)return;this.lastTurnActivityGeneration=H.data.generation,this.lastTurnActivityRevision=H.data.revision,this.sendSessionMetadata("blade/turnActivity",H.data)}sendProjectedLoopMetadata(z,H){let J=a(H,{omitUndefined:!0});if(J)this.sendSessionMetadata(z,J.properties)}sendSessionMetadata(z,H){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{[z]:H}})}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;G.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let H=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));G.debug(`[AcpSession ${this.id}] Sending plan update with ${H.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:H})}async requestPermission(z){let H=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,H);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,H);let J=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(J))return G.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.details)X.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
18
26
  - ${z.risks.join(`
19
27
  - `)}`}});let L=this.mapToolKind(J),Q={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:z.title||"Permission Required",content:X,kind:L}},W=await this.waitForClientInteraction(this.connection.requestPermission(Q),H);if(!W)return{approved:!1,reason:m};let B=W.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let $=B.optionId;if($==="allow_always")return{approved:!0,scope:"project"};if($==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let _=$==="allow_once";return{approved:_,scope:"once",reason:_?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,H){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[X,L]of J.entries()){let Q=L.options.map((_,U)=>`answer:${X}:${U}`),W=`answer:${X}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...L.options.map((_,U)=>({optionId:Q[U],name:_.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:L.header,kind:"think",content:[{type:"content",content:{type:"text",text:[L.question,...L.options.map((_)=>`${_.label}: ${_.description}`)].join(`
20
28
  `)}}]}}),H);if(!B)return{approved:!1,reason:m};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let $=Q.indexOf(B.outcome.optionId);if($<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[L.header]=L.options[$].label}return{approved:!0,answers:Y}}catch(X){return G.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,H){let J=z.mcpElicitation;if(!J)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(J.mode==="url"){let X=await this.requestElicitationChoice("MCP external authorization",[J.message,`Server: ${J.serverName}`,`Domain: ${J.domain??"unknown"}`,`URL: ${J.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
21
29
  `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],H);if(X==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:X==="decline"?"User declined URL":"User cancelled",elicitation:{action:X==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let X of J.fields??[]){let L=await this.collectAcpElicitationField(X,H);if(L.cancelled)return{approved:!1,reason:L.reason,elicitation:{action:"cancel"}};if(L.value!==void 0)Y[X.name]=L.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,H){if(z.type==="select"||z.type==="boolean"){let J=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((L,Q)=>({id:`option:${Q}`,label:L.label,value:L.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
22
30
  `),[...J.map((L)=>({id:L.id,label:L.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(Y==="skip")return{cancelled:!1};let X=J.find((L)=>L.id===Y);if(!X)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:X.value}}if(z.defaultValue!==void 0){let J=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
23
- `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(J==="default")return{cancelled:!1,value:z.defaultValue};if(J==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,H,J,Y){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...J.map((L)=>({optionId:L.id,name:L.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:H}}]}}),Y);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((J,Y)=>{let X=!1,L=(W)=>{if(X)return;X=!0,H.removeEventListener("abort",Q),W()},Q=()=>L(()=>J(void 0));if(H.addEventListener("abort",Q,{once:!0}),H.aborted)Q();z.then((W)=>L(()=>J(W)),(W)=>L(()=>Y(W)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var O=h("Agent"),DH="remote task isolation is not supported";function y(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function FH(z){return C.invalidParams({code:z.code,reason:z.reason})}function KH(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:DH})}function pz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function mz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return Hz(z)}catch(H){if(H instanceof dz)throw FH(H);throw H}}function s(z,H){let J=Jz(z);return Object.freeze({kind:"acp-remote",hostStateRoot:Qz(J.collisionIdentity),executionRoot:J.wirePath,hostResourceRoot:H,profile:z,descriptor:J})}function t(z,H){let J=lz(z.remoteWorkspace),Y=Qz(J.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let X=Hz(J.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:J.wirePath,hostResourceRoot:H,profile:X,descriptor:J})}function jH(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Yz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=o.resolve(e())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=oz();this.runtimeResidencyValue=new QH({maxResident:z?.maxResidentSessionRuntimes??rz,idleMs:z?.sessionRuntimeIdleMs??nz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(H){if(H instanceof JH)throw C.internalError({resource:H.resource,limit:H.limit,retryable:H.retryable},H.message);throw H}}async initialize(z){return O.info("[BladeAgent] Initializing ACP connection"),O.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await sz(),{protocolVersion:VH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let H=zz("acp"),J=z.cwd||e(),Y=y(this.clientCapabilities),X=Y?k(J):void 0,L=z._meta?.["blade/taskIsolation"],Q=L==="local"||L==="worktree"?L:void 0;if(Y&&Q)throw KH();let W=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(H),$;try{let _,U;if(X){let T=s(X,this.hostResourceRoot);_=await K.createRemoteSessionMetadata(H,T.hostStateRoot,T.descriptor,{}),U=t(_,this.hostResourceRoot)}else U=P(J);let V=!Y&&Q?await HH.createSessionTask({sessionId:H,prompt:typeof W==="string"&&W.trim()?W:"ACP task session",sourceProjectPath:J,isolation:Q}):void 0;if(V)U=P(V.metadata.projectPath);return O.info(`[BladeAgent] Creating new session: ${H}`),O.debug(`[BladeAgent] Session kind: ${U.kind}`),$=new x(H,U,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...V?.taskWorktree?{taskWorktree:V.taskWorktree}:{},...V?.metadata.taskIsolation?{taskIsolation:V.metadata.taskIsolation}:{}}),await $.initialize(),this.assertNotDestroyed(),this.commitSession(H,$,B),O.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),$.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H,V?.metadata,$.getModelConfiguration())}catch(_){throw B.cancel(),await $?.destroy().catch(()=>{return}),_}}async listSessions(z){let H=y(this.clientCapabilities);if(!H&&z.cwd!=null&&!o.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=H?await K.listRemoteSessionPage({...z.cwd!=null?{descriptor:Jz(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await K.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:H?jH(Y):Y.projectPath,title:Y.title??null,updatedAt:Y.lastMessageTime,_meta:{"blade/taskStatus":Y.taskStatus,...Y.taskStatusReason?{"blade/taskStatusReason":Y.taskStatusReason}:{},...Y.taskFailure?{"blade/taskFailure":Y.taskFailure}:{},...Y.taskStartedAt?{"blade/taskStartedAt":Y.taskStartedAt}:{},...Y.taskCompletedAt?{"blade/taskCompletedAt":Y.taskCompletedAt}:{},...Y.taskModelId?{"blade/taskModelId":Y.taskModelId}:{},...Y.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Y.taskRetriedFrom?{"blade/taskRetriedFrom":Y.taskRetriedFrom}:{},...Y.taskDelivery?{"blade/taskDelivery":Y.taskDelivery}:{},...Y.taskIsolation?{"blade/taskIsolation":Y.taskIsolation}:{},...Y.taskSourceProjectPath?{"blade/taskSourceProjectPath":Y.taskSourceProjectPath}:{},...Y.taskWorktreeBranch?{"blade/taskWorktreeBranch":Y.taskWorktreeBranch}:{},...Y.taskBaseCommit?{"blade/taskBaseCommit":Y.taskBaseCommit}:{},...Y.taskDiffStat?{"blade/taskDiffStat":Y.taskDiffStat}:{},...Y.taskQueuePosition?{"blade/taskQueuePosition":Y.taskQueuePosition}:{},...Y.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Y.taskQueueDepth}:{},...Y.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Y.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let H=y(this.clientCapabilities),J=H?s(k(z.cwd),this.hostResourceRoot):void 0;if(!H&&!o.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=zz("fork"),X=await this.reserveSessionRuntime(Y),L;try{let Q;try{Q=await K.forkSession(z.sessionId,{sourceProjectPath:J?.hostStateRoot??z.cwd,targetProjectPath:J?.hostStateRoot??z.cwd,newSessionId:Y,...J?{remote:{expectedDescriptor:J.descriptor}}:{}})}catch(B){if(mz(B))throw pz();throw B}this.assertNotDestroyed();let W=H?t(Q.metadata,this.hostResourceRoot):P(Q.projectPath??z.cwd);return L=new x(Q.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await L.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,L,X),L.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,H?void 0:Q.metadata,L.getModelConfiguration())}catch(Q){throw X.cancel(),await L?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),O.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!y(this.clientCapabilities)){await K.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let W=await this.reserveSessionRuntime(z.sessionId),B;try{let[$,_]=await Promise.all([K.loadSession(z.sessionId,z.cwd),K.findSessionMetadata(z.sessionId,z.cwd)]);if(!_)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,P(z.cwd),this.connection,this.clientCapabilities,{initialMessages:$,permissionMode:_.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,W),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch($){throw W.cancel(),await B?.destroy().catch(()=>{return}),$}}let J=s(k(z.cwd),this.hostResourceRoot),Y;try{Y=await K.assertRemoteSessionWritable(z.sessionId,J.hostStateRoot,J.descriptor)}catch(W){if(mz(W))throw pz();throw W}let X=t(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let L=await this.reserveSessionRuntime(z.sessionId),Q;try{let W=await K.loadRemoteSession(z.sessionId,X.hostStateRoot,X.descriptor);return Q=new x(z.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,L),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(W){throw L.cancel(),await Q?.destroy().catch(()=>{return}),W}}commitSession(z,H,J){let Y=J.commit({key:z,surface:"acp",value:H,canEvict:()=>H.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===H)this.sessions.delete(z);await H.destroy()}});this.sessions.set(z,H),Y.release()}async closeResidentSession(z,H={}){let J=this.sessions.get(z);if(!J)return;let Y=this.runtimeResidency.owns(z,J),X;try{await J.destroy(H)}catch(Q){X=Q}let L=await this.runtimeResidency.forget(z,J);if(this.sessions.get(z)===J)this.sessions.delete(z);if(Y&&!L&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,H,J){return{sessionId:z,...this.buildSessionSetup(J,H?.permissionMode==="autoEdit"?"auto-edit":H?.permissionMode),...H?{_meta:{"blade/taskIsolation":H.taskIsolation,"blade/taskSourceProjectPath":H.taskSourceProjectPath,"blade/taskProjectPath":H.projectPath,...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,H="default"){let J=z?.models??[],Y=(z?.currentModelId&&J.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??J[0]?.id,X=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],L=[];if(J.length>0)L.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:J.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)L.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)L.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)L.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)L.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:X,currentModeId:H},configOptions:L.length>0?L:void 0}}async closeSession(z){this.assertNotDestroyed();let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{return await H.value.prompt(z)}finally{H.release()}}async cancel(z){O.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H){O.info("[BladeAgent] Found session, calling session.cancel()");try{H.value.cancel()}finally{H.release()}}else O.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){O.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H)try{await H.value.setMode(z.modeId)}finally{H.release()}return{}}async setSessionConfigOption(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{let J=H.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")O.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&tz(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&az(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&iz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&ez(z.value))O.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}finally{H.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let H of[...this.sessions.keys()])try{await this.closeResidentSession(H)}catch(J){z??=J}try{await this.runtimeResidency.disposeAll()}catch(H){z??=H}this.sessions.clear();try{await zH.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function OJ(){let z=NH.toWeb(process.stdout),H=wH.toWeb(process.stdin),J=f.ndJsonStream(z,H),Y,X=new f.AgentSideConnection((Q)=>{return Y=new Yz(Q),Y},J),L=YH(async()=>{await Y?.destroy()});try{await X.closed}finally{L(),await Y?.destroy()}}export{OJ as runAcpIntegration,P as createLocalAcpSessionRoots};
31
+ `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(J==="default")return{cancelled:!1,value:z.defaultValue};if(J==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,H,J,Y){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...J.map((L)=>({optionId:L.id,name:L.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:H}}]}}),Y);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((J,Y)=>{let X=!1,L=(W)=>{if(X)return;X=!0,H.removeEventListener("abort",Q),W()},Q=()=>L(()=>J(void 0));if(H.addEventListener("abort",Q,{once:!0}),H.aborted)Q();z.then((W)=>L(()=>J(W)),(W)=>L(()=>Y(W)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var O=h("Agent"),FH="remote task isolation is not supported";function y(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function KH(z){return C.invalidParams({code:z.code,reason:z.reason})}function jH(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:FH})}function mz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function dz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return Hz(z)}catch(H){if(H instanceof lz)throw KH(H);throw H}}function s(z,H){let J=Jz(z);return Object.freeze({kind:"acp-remote",hostStateRoot:Qz(J.collisionIdentity),executionRoot:J.wirePath,hostResourceRoot:H,profile:z,descriptor:J})}function t(z,H){let J=iz(z.remoteWorkspace),Y=Qz(J.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let X=Hz(J.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:J.wirePath,hostResourceRoot:H,profile:X,descriptor:J})}function wH(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Yz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=o.resolve(e())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=sz();this.runtimeResidencyValue=new YH({maxResident:z?.maxResidentSessionRuntimes??nz,idleMs:z?.sessionRuntimeIdleMs??oz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(H){if(H instanceof QH)throw C.internalError({resource:H.resource,limit:H.limit,retryable:H.retryable},H.message);throw H}}async initialize(z){return O.info("[BladeAgent] Initializing ACP connection"),O.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await tz(),{protocolVersion:DH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let H=zz("acp"),J=z.cwd||e(),Y=y(this.clientCapabilities),X=Y?k(J):void 0,L=z._meta?.["blade/taskIsolation"],Q=L==="local"||L==="worktree"?L:void 0;if(Y&&Q)throw jH();let W=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(H),$;try{let _,U;if(X){let T=s(X,this.hostResourceRoot);_=await K.createRemoteSessionMetadata(H,T.hostStateRoot,T.descriptor,{}),U=t(_,this.hostResourceRoot)}else U=P(J);let V=!Y&&Q?await JH.createSessionTask({sessionId:H,prompt:typeof W==="string"&&W.trim()?W:"ACP task session",sourceProjectPath:J,isolation:Q}):void 0;if(V)U=P(V.metadata.projectPath);return O.info(`[BladeAgent] Creating new session: ${H}`),O.debug(`[BladeAgent] Session kind: ${U.kind}`),$=new x(H,U,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...V?.taskWorktree?{taskWorktree:V.taskWorktree}:{},...V?.metadata.taskIsolation?{taskIsolation:V.metadata.taskIsolation}:{}}),await $.initialize(),this.assertNotDestroyed(),this.commitSession(H,$,B),O.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),$.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H,V?.metadata,$.getModelConfiguration())}catch(_){throw B.cancel(),await $?.destroy().catch(()=>{return}),_}}async listSessions(z){let H=y(this.clientCapabilities);if(!H&&z.cwd!=null&&!o.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=H?await K.listRemoteSessionPage({...z.cwd!=null?{descriptor:Jz(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await K.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:H?wH(Y):Y.projectPath,title:Y.title??null,updatedAt:Y.lastMessageTime,_meta:{"blade/taskStatus":Y.taskStatus,...Y.taskStatusReason?{"blade/taskStatusReason":Y.taskStatusReason}:{},...Y.taskFailure?{"blade/taskFailure":Y.taskFailure}:{},...Y.taskStartedAt?{"blade/taskStartedAt":Y.taskStartedAt}:{},...Y.taskCompletedAt?{"blade/taskCompletedAt":Y.taskCompletedAt}:{},...Y.taskModelId?{"blade/taskModelId":Y.taskModelId}:{},...Y.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Y.taskRetriedFrom?{"blade/taskRetriedFrom":Y.taskRetriedFrom}:{},...Y.taskDelivery?{"blade/taskDelivery":Y.taskDelivery}:{},...Y.taskIsolation?{"blade/taskIsolation":Y.taskIsolation}:{},...Y.taskSourceProjectPath?{"blade/taskSourceProjectPath":Y.taskSourceProjectPath}:{},...Y.taskWorktreeBranch?{"blade/taskWorktreeBranch":Y.taskWorktreeBranch}:{},...Y.taskBaseCommit?{"blade/taskBaseCommit":Y.taskBaseCommit}:{},...Y.taskDiffStat?{"blade/taskDiffStat":Y.taskDiffStat}:{},...Y.taskQueuePosition?{"blade/taskQueuePosition":Y.taskQueuePosition}:{},...Y.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Y.taskQueueDepth}:{},...Y.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Y.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let H=y(this.clientCapabilities),J=H?s(k(z.cwd),this.hostResourceRoot):void 0;if(!H&&!o.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=zz("fork"),X=await this.reserveSessionRuntime(Y),L;try{let Q;try{Q=await K.forkSession(z.sessionId,{sourceProjectPath:J?.hostStateRoot??z.cwd,targetProjectPath:J?.hostStateRoot??z.cwd,newSessionId:Y,...J?{remote:{expectedDescriptor:J.descriptor}}:{}})}catch(B){if(dz(B))throw mz();throw B}this.assertNotDestroyed();let W=H?t(Q.metadata,this.hostResourceRoot):P(Q.projectPath??z.cwd);return L=new x(Q.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await L.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,L,X),L.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,H?void 0:Q.metadata,L.getModelConfiguration())}catch(Q){throw X.cancel(),await L?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),O.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!y(this.clientCapabilities)){await K.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let W=await this.reserveSessionRuntime(z.sessionId),B;try{let[$,_]=await Promise.all([K.loadSession(z.sessionId,z.cwd),K.findSessionMetadata(z.sessionId,z.cwd)]);if(!_)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,P(z.cwd),this.connection,this.clientCapabilities,{initialMessages:$,permissionMode:_.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,W),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch($){throw W.cancel(),await B?.destroy().catch(()=>{return}),$}}let J=s(k(z.cwd),this.hostResourceRoot),Y;try{Y=await K.assertRemoteSessionWritable(z.sessionId,J.hostStateRoot,J.descriptor)}catch(W){if(dz(W))throw mz();throw W}let X=t(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let L=await this.reserveSessionRuntime(z.sessionId),Q;try{let W=await K.loadRemoteSession(z.sessionId,X.hostStateRoot,X.descriptor);return Q=new x(z.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,L),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(W){throw L.cancel(),await Q?.destroy().catch(()=>{return}),W}}commitSession(z,H,J){let Y=J.commit({key:z,surface:"acp",value:H,canEvict:()=>H.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===H)this.sessions.delete(z);await H.destroy()}});this.sessions.set(z,H),Y.release()}async closeResidentSession(z,H={}){let J=this.sessions.get(z);if(!J)return;let Y=this.runtimeResidency.owns(z,J),X;try{await J.destroy(H)}catch(Q){X=Q}let L=await this.runtimeResidency.forget(z,J);if(this.sessions.get(z)===J)this.sessions.delete(z);if(Y&&!L&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,H,J){return{sessionId:z,...this.buildSessionSetup(J,H?.permissionMode==="autoEdit"?"auto-edit":H?.permissionMode),...H?{_meta:{"blade/taskIsolation":H.taskIsolation,"blade/taskSourceProjectPath":H.taskSourceProjectPath,"blade/taskProjectPath":H.projectPath,...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,H="default"){let J=z?.models??[],Y=(z?.currentModelId&&J.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??J[0]?.id,X=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],L=[];if(J.length>0)L.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:J.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)L.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)L.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)L.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)L.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:X,currentModeId:H},configOptions:L.length>0?L:void 0}}async closeSession(z){this.assertNotDestroyed();let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{return await H.value.prompt(z)}finally{H.release()}}async cancel(z){O.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H){O.info("[BladeAgent] Found session, calling session.cancel()");try{H.value.cancel()}finally{H.release()}}else O.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){O.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let H=this.runtimeResidency.acquire(z.sessionId);if(H)try{await H.value.setMode(z.modeId)}finally{H.release()}return{}}async setSessionConfigOption(z){let H=this.runtimeResidency.acquire(z.sessionId);if(!H)throw Error(`Session not found: ${z.sessionId}`);try{let J=H.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")O.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&ez(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&az(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&rz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&zH(z.value))O.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}finally{H.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let H of[...this.sessions.keys()])try{await this.closeResidentSession(H)}catch(J){z??=J}try{await this.runtimeResidency.disposeAll()}catch(H){z??=H}this.sessions.clear();try{await HH.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function qJ(){let z=AH.toWeb(process.stdout),H=NH.toWeb(process.stdin),J=f.ndJsonStream(z,H),Y,X=new f.AgentSideConnection((Q)=>{return Y=new Yz(Q),Y},J),L=ZH(async()=>{await Y?.destroy()});try{await X.closed}finally{L(),await Y?.destroy()}}export{qJ as runAcpIntegration,P as createLocalAcpSessionRoots};
@@ -1,2 +1,2 @@
1
- import{Si as I}from"./chunk-sqk8cnej.js";import{Nj as G,Oj as H}from"./chunk-3crwyd2r.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
2
- export{D as xg,Q as yg,T as zg,U as Ag};
1
+ import{Ui as I}from"./chunk-h4b4fn3t.js";import{Pj as G,Qj as H}from"./chunk-5s2x98rx.js";import B from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function D(b){return A(b)}function E(b,q){let w=new G(q?.credentials??H().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=B.resolve(b),x=I.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...D(q),...J,...K},F=E(z);return x.validateConfig(z,F),{projectRoot:w,config:z,catalog:F}}function T(b){let q=D(b.config);return{projectRoot:B.resolve(b.projectRoot),config:q,catalog:E(q,b.catalog)}}function U(b,q){let w=D(q);return{projectRoot:B.resolve(b),config:w,catalog:E(w)}}
2
+ export{D as zg,Q as Ag,T as Bg,U as Cg};