blade-code 0.10.137 → 0.10.139

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 (132) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-5dwmhsrx.js → chunk-04t21rey.js} +1 -1
  3. package/dist/{chunk-w9z34f27.js → chunk-05cv54r8.js} +1 -1
  4. package/dist/{chunk-h74p51hg.js → chunk-16648v5c.js} +1 -1
  5. package/dist/{chunk-c2mx5zg0.js → chunk-1bqatrxs.js} +1 -1
  6. package/dist/{chunk-bx75fd0d.js → chunk-1h3736q2.js} +387 -387
  7. package/dist/{chunk-bzqbmz6t.js → chunk-25r1v5rn.js} +59 -59
  8. package/dist/chunk-2agbk8ef.js +1 -0
  9. package/dist/chunk-2bty4510.js +6 -0
  10. package/dist/chunk-2f7nr9hh.js +1 -0
  11. package/dist/{chunk-7ykqvsph.js → chunk-2jq9ed09.js} +1 -1
  12. package/dist/chunk-2t9vtt75.js +1 -0
  13. package/dist/chunk-3aaehgva.js +1 -0
  14. package/dist/{chunk-1evc05gr.js → chunk-3ekz3zms.js} +2 -2
  15. package/dist/{chunk-wzkh3e6a.js → chunk-3eskgvpy.js} +1 -1
  16. package/dist/chunk-3t5r41yh.js +1 -0
  17. package/dist/{chunk-ramana2t.js → chunk-40pd090k.js} +2 -2
  18. package/dist/{chunk-6e3mh79j.js → chunk-516adpx6.js} +1 -1
  19. package/dist/{chunk-q0s3gcjm.js → chunk-5j68055h.js} +1 -1
  20. package/dist/{chunk-ky9br0z8.js → chunk-5qwpdx3n.js} +1 -1
  21. package/dist/{chunk-e76gej4y.js → chunk-5w8pmsqe.js} +2 -2
  22. package/dist/chunk-5xgyx25z.js +2 -0
  23. package/dist/{chunk-wxtj6gqb.js → chunk-65c3vjwm.js} +1 -1
  24. package/dist/{chunk-69rjav47.js → chunk-6ezffjq1.js} +1 -1
  25. package/dist/{chunk-5btfnf2r.js → chunk-6j5v5emj.js} +4 -4
  26. package/dist/{chunk-9frd4fpk.js → chunk-6qhbdcse.js} +2 -2
  27. package/dist/{chunk-wa71vstt.js → chunk-7j4s1nrc.js} +1 -1
  28. package/dist/{chunk-affzv7f1.js → chunk-7pg5y3pg.js} +1 -1
  29. package/dist/{chunk-na4wzne8.js → chunk-8py443a5.js} +1 -1
  30. package/dist/{chunk-ybc5myz7.js → chunk-8rccn1y2.js} +1 -1
  31. package/dist/{chunk-0c82q1sz.js → chunk-9m7d3ajv.js} +1 -1
  32. package/dist/{chunk-p0gbxaqz.js → chunk-a5hkv8er.js} +2 -2
  33. package/dist/{chunk-xt0ktytp.js → chunk-awheqy52.js} +2 -2
  34. package/dist/{chunk-69nwa6bn.js → chunk-az08pq83.js} +1 -1
  35. package/dist/{chunk-y6jee9w7.js → chunk-bgzj85za.js} +1 -1
  36. package/dist/{chunk-0ccm29qy.js → chunk-bq6d0v5b.js} +2 -2
  37. package/dist/{chunk-zk9rf1d7.js → chunk-cefmcwyv.js} +2 -2
  38. package/dist/{chunk-4jqw75ce.js → chunk-d64b7wta.js} +1 -1
  39. package/dist/{chunk-g799czsy.js → chunk-dv2m2xe5.js} +1 -1
  40. package/dist/{chunk-h05qhgrb.js → chunk-dw0mewc2.js} +2 -2
  41. package/dist/{chunk-nxnmqk4s.js → chunk-earhezc8.js} +1 -1
  42. package/dist/{chunk-chspy9f8.js → chunk-esff371k.js} +7 -7
  43. package/dist/{chunk-f2b9cyj5.js → chunk-f4cn6v8t.js} +2 -2
  44. package/dist/{chunk-mzye1ah2.js → chunk-fbrdcveb.js} +1 -1
  45. package/dist/{chunk-vp6d1fqp.js → chunk-ft1bdqbs.js} +2 -2
  46. package/dist/{chunk-vg3zwv4g.js → chunk-gc4kj295.js} +1 -1
  47. package/dist/chunk-gjc1hhhv.js +1 -0
  48. package/dist/chunk-grx6fv9w.js +5 -0
  49. package/dist/chunk-gx4seq5c.js +10 -0
  50. package/dist/chunk-h2gp7smy.js +1 -0
  51. package/dist/{chunk-74bswv4z.js → chunk-hrcz179j.js} +2 -2
  52. package/dist/{chunk-xg9fyvw0.js → chunk-jb4hmk56.js} +2 -2
  53. package/dist/{chunk-wxypv01z.js → chunk-jy7k2dwm.js} +2 -2
  54. package/dist/chunk-mc2mr1kn.js +2 -0
  55. package/dist/{chunk-wc9wsyrc.js → chunk-mec8yedz.js} +1 -1
  56. package/dist/{chunk-gpj7k3er.js → chunk-mh3ne2sf.js} +2 -2
  57. package/dist/chunk-mkckss82.js +1 -0
  58. package/dist/{chunk-g9vdmvk2.js → chunk-mtfjwsn2.js} +2 -2
  59. package/dist/{chunk-6xvrrypm.js → chunk-npc7jt96.js} +1 -1
  60. package/dist/chunk-ntpwqfy3.js +1 -0
  61. package/dist/chunk-q82ntq7t.js +1 -0
  62. package/dist/{chunk-mthf5akx.js → chunk-qrv72yy6.js} +2 -2
  63. package/dist/{chunk-5sf2rc1z.js → chunk-recafw5r.js} +3 -3
  64. package/dist/{chunk-karq4wfd.js → chunk-rhwkvx96.js} +1 -1
  65. package/dist/{chunk-mavranwn.js → chunk-sdhdn0yx.js} +3 -3
  66. package/dist/{chunk-e8pfbb6c.js → chunk-sj4gz23a.js} +1 -1
  67. package/dist/chunk-smjfqtws.js +1 -0
  68. package/dist/{chunk-0k2x2ae6.js → chunk-t88sfhjj.js} +1 -1
  69. package/dist/{chunk-39de5k03.js → chunk-v2fewxvw.js} +2 -2
  70. package/dist/chunk-wazhd8bm.js +1 -0
  71. package/dist/chunk-wf4s1hp2.js +1 -0
  72. package/dist/{chunk-v5503t2t.js → chunk-x3c718v5.js} +4 -4
  73. package/dist/{chunk-etf3e9kt.js → chunk-yvmexv2c.js} +1 -1
  74. package/dist/{chunk-75yy9yre.js → chunk-z9qv0d6k.js} +1 -1
  75. package/dist/{chunk-z3hpstky.js → chunk-zx78c1an.js} +1 -1
  76. package/dist/{chunk-rgjr7jsd.js → chunk-zz5n2qxk.js} +1 -1
  77. package/dist/web/assets/ChatView-CQnuGDqk.js +63 -0
  78. package/dist/web/assets/{CodeBlockHighlighter-Czp4VZIg.js → CodeBlockHighlighter-CYhxXWvb.js} +1 -1
  79. package/dist/web/assets/{FilePreview-BJWuYfyF.js → FilePreview-ByTaE1GR.js} +1 -1
  80. package/dist/web/assets/{KanbanBoard-DrYzt5Kh.js → KanbanBoard-KMmGvNPc.js} +1 -1
  81. package/dist/web/assets/{MarkdownRenderer-DxkR5r7t.js → MarkdownRenderer-C6lKOJaG.js} +3 -3
  82. package/dist/web/assets/{ScrollArea-D71pJjgW.js → ScrollArea-Bo6cZ3PH.js} +1 -1
  83. package/dist/web/assets/{SessionHistorySurface-2y9bnndm.js → SessionHistorySurface-Cymc4xw0.js} +1 -1
  84. package/dist/web/assets/{SettingsModal-BbaTL5Rk.js → SettingsModal-D36xhHwa.js} +5 -10
  85. package/dist/web/assets/{Sidebar-COZltpL9.js → Sidebar-DEGQINYb.js} +1 -1
  86. package/dist/web/assets/{TaskSwitcher-3giB7l1P.js → TaskSwitcher-BEISb7-8.js} +1 -1
  87. package/dist/web/assets/{TerminalPanel-gvTTiTgX.js → TerminalPanel-B7PXaRGh.js} +1 -1
  88. package/dist/web/assets/{archive-DndqAA2q.js → archive-Dyn5Oz68.js} +1 -1
  89. package/dist/web/assets/{arrow-left-XNYfpUAb.js → arrow-left-mWU3P1zb.js} +1 -1
  90. package/dist/web/assets/{calendar-clock-BQOfNcCK.js → calendar-clock-B6b0Cb3d.js} +1 -1
  91. package/dist/web/assets/{chevron-right-Cvq3LzHK.js → chevron-right-Cl6g5_0e.js} +1 -1
  92. package/dist/web/assets/{chevrons-up-down-Dia1U9Sz.js → chevrons-up-down-FKryGzO4.js} +1 -1
  93. package/dist/web/assets/{clock-3-CnxLS8cv.js → clock-3-CfVjvMmA.js} +1 -1
  94. package/dist/web/assets/{copy-CWCS3Lql.js → copy-CIYuf7du.js} +1 -1
  95. package/dist/web/assets/{download-DXdsM18t.js → download-DecDFX8n.js} +1 -1
  96. package/dist/web/assets/{external-link-1IN2ZfaO.js → external-link-DaSwvjf7.js} +1 -1
  97. package/dist/web/assets/{folder-Bpq602dI.js → folder-DZtlKvFm.js} +1 -1
  98. package/dist/web/assets/{index-57UZsfTt.css → index-DC2p1vGD.css} +1 -1
  99. package/dist/web/assets/index-DQaqO-lw.js +203 -0
  100. package/dist/web/assets/{pause-BYhoGDZq.js → pause-Bd-STGLc.js} +1 -1
  101. package/dist/web/assets/{pencil-pRZQVHFU.js → pencil-BoTIqqxX.js} +1 -1
  102. package/dist/web/assets/{play-DGZdCyPk.js → play-C4ctis0t.js} +1 -1
  103. package/dist/web/assets/{plus-CAQ3qlUJ.js → plus-D08TlGJu.js} +1 -1
  104. package/dist/web/assets/session-events-DKjIMNKI.js +29 -0
  105. package/dist/web/assets/{settings-BPfzj_Vf.js → settings-BGRhMFaU.js} +1 -1
  106. package/dist/web/assets/team-CPme0l2K.js +6 -0
  107. package/dist/web/assets/{teamService-BScT9o9A.js → teamService-CVCtTVfY.js} +1 -1
  108. package/dist/web/assets/{terminal-CldJbdMr.js → terminal-D7GsyYki.js} +1 -1
  109. package/dist/web/index.html +2 -2
  110. package/package.json +1 -1
  111. package/dist/chunk-35668hyn.js +0 -1
  112. package/dist/chunk-3gmcvd0c.js +0 -1
  113. package/dist/chunk-5774a669.js +0 -1
  114. package/dist/chunk-7n035mhg.js +0 -1
  115. package/dist/chunk-9a7bppj7.js +0 -2
  116. package/dist/chunk-a26vtcv5.js +0 -5
  117. package/dist/chunk-b08thknq.js +0 -1
  118. package/dist/chunk-d6tbr25k.js +0 -1
  119. package/dist/chunk-dt9n4f4e.js +0 -1
  120. package/dist/chunk-ermypm1x.js +0 -2
  121. package/dist/chunk-esp69w6w.js +0 -1
  122. package/dist/chunk-g1y60ey9.js +0 -1
  123. package/dist/chunk-gf5v8aff.js +0 -1
  124. package/dist/chunk-m9kh7djg.js +0 -6
  125. package/dist/chunk-ntmkzrs8.js +0 -1
  126. package/dist/chunk-pj15kt5b.js +0 -10
  127. package/dist/chunk-pv1vwasz.js +0 -1
  128. package/dist/chunk-vda03kxj.js +0 -1
  129. package/dist/web/assets/ChatView-DpvPjAh7.js +0 -63
  130. package/dist/web/assets/index-DEOQizD2.js +0 -203
  131. package/dist/web/assets/session-events-C5_Q0kZV.js +0 -29
  132. package/dist/web/assets/team-QZ9byb3E.js +0 -1
@@ -1,5 +1,5 @@
1
- import{v as zH,w as HH}from"./chunk-ky9br0z8.js";import{A as S,x as kz,y as Cz,z as fz}from"./chunk-y6jee9w7.js";import{B as ez,C as Pz,D as xz,E as bz,F as Rz,G as Sz}from"./chunk-e8pfbb6c.js";import{Aa as Iz,Ba as yz,Ca as hz,N as R,W as Nz,X as Az,ca as Oz,fa as Ez,ga as qz,ja as Tz,za as Mz}from"./chunk-bx75fd0d.js";import"./chunk-h74p51hg.js";import{Qa as tz}from"./chunk-7ykqvsph.js";import{Sa as wz,Wa as i}from"./chunk-ermypm1x.js";import{Fb as Fz,Rb as Kz,_b as l}from"./chunk-5sf2rc1z.js";import{jc as d}from"./chunk-wzkh3e6a.js";import{Dd as I,Ed as v,Fd as Uz,Kd as Gz,Nd as Vz,Pd as M,Sd as jz,Xd as Dz,_d as F,td as Wz}from"./chunk-zk9rf1d7.js";import"./chunk-z3hpstky.js";import{De as a,Ee as _z,we as Bz}from"./chunk-p0gbxaqz.js";import"./chunk-xt0ktytp.js";import{pf as JH}from"./chunk-1evc05gr.js";import"./chunk-9frd4fpk.js";import{Kf as rz,Lf as oz}from"./chunk-v5503t2t.js";import"./chunk-v508x7cg.js";import{Wf as t}from"./chunk-q0s3gcjm.js";import{$f as Xz}from"./chunk-a26vtcv5.js";import{hg as m}from"./chunk-0ccm29qy.js";import"./chunk-74bswv4z.js";import{mg as nz}from"./chunk-4jqw75ce.js";import"./chunk-e76gej4y.js";import"./chunk-f2b9cyj5.js";import"./chunk-etf3e9kt.js";import{gh as sz}from"./chunk-karq4wfd.js";import"./chunk-69nwa6bn.js";import"./chunk-mavranwn.js";import"./chunk-c2mx5zg0.js";import{ji as iz,mi as az}from"./chunk-ramana2t.js";import"./chunk-6xvrrypm.js";import{Ki as g,Li as $z,Ni as c,Oi as p}from"./chunk-9a7bppj7.js";import{Si as s}from"./chunk-g799czsy.js";import"./chunk-mzye1ah2.js";import{sj as y}from"./chunk-vp6d1fqp.js";import"./chunk-xg9fyvw0.js";import{Fj as vz,Ij as lz}from"./chunk-wxtj6gqb.js";import"./chunk-g9vdmvk2.js";import"./chunk-wxypv01z.js";import"./chunk-nxnmqk4s.js";import{$j as e,Wj as Zz,Xj as mz,dk as zz,ek as dz,fk as Hz}from"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";import{Readable as FH,Writable as KH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import r from"node:path";import{PROTOCOL_VERSION as UH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as uz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Yz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function YH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Yz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Yz("headers"in z?z.headers:void 0)};return null}function ZH(z){let H={};for(let L of z){let Y=YH(L);if(Y)H[L.name]=Y}return H}function gz(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 L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function $H(z){let H=_z(z.metadata);return H?[{type:"text",text:a(H)}]:gz(z.content)}function XH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}function WH(z){if(!Xz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function BH(z){if(!(z instanceof uz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Uz(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 _H(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;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Sz({maxPendingItems:Pz,maxPendingBytes:xz,writeTimeoutMs:bz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}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"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Dz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.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 Tz.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(Z)=>{await this.sendUpdateAndWait(Z)},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:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?ZH(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Oz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{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 Iz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Fz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Az(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 Nz(_,Zz()).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:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.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 Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!Bz(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of $H(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,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())}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 L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let 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,Z,_=(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 Z=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,Z)_(Z);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:[]})}}),Z=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:Z.status,findings:Z.findings.length,content:Wz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,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 yz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="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 X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});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(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),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=hz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.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 L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=jz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=wz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.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($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.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 (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Mz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={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(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await Kz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.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(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,LH=qz(Vz(Ez(w,A),Gz));q.push({type:"content",content:{type:"text",text:LH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
1
+ import{v as HH,w as JH}from"./chunk-5qwpdx3n.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-bgzj85za.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-sj4gz23a.js";import{Aa as yz,Ba as hz,Ca as kz,N as R,W as Az,X as Oz,ca as Ez,fa as qz,ga as Tz,ja as Pz,za as Iz}from"./chunk-1h3736q2.js";import"./chunk-16648v5c.js";import{Qa as ez}from"./chunk-2jq9ed09.js";import{Sa as Nz,Wa as i,Za as a}from"./chunk-5xgyx25z.js";import{Ib as Kz,Ub as wz,bc as l}from"./chunk-recafw5r.js";import{mc as d}from"./chunk-3eskgvpy.js";import{Gd as I,Hd as v,Id as Gz,Nd as Vz,Qd as jz,Sd as M,Vd as Dz,_d as Fz,be as F,wd as Bz}from"./chunk-cefmcwyv.js";import"./chunk-zx78c1an.js";import{Ge as r,He as Uz,ze as _z}from"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{sf as LH}from"./chunk-3ekz3zms.js";import"./chunk-6qhbdcse.js";import{Nf as oz,Of as nz}from"./chunk-x3c718v5.js";import"./chunk-v508x7cg.js";import{Zf as e}from"./chunk-5j68055h.js";import{cg as Wz}from"./chunk-grx6fv9w.js";import{kg as m}from"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import{pg as sz}from"./chunk-d64b7wta.js";import"./chunk-5w8pmsqe.js";import"./chunk-f4cn6v8t.js";import"./chunk-yvmexv2c.js";import{jh as tz}from"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-sdhdn0yx.js";import"./chunk-1bqatrxs.js";import{mi as az,pi as rz}from"./chunk-40pd090k.js";import"./chunk-npc7jt96.js";import{Ni as g,Oi as Xz,Qi as c,Ri as p}from"./chunk-mc2mr1kn.js";import{Vi as t}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import{vj as y}from"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import{Ij as lz,Lj as iz}from"./chunk-65c3vjwm.js";import"./chunk-mtfjwsn2.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import{Zj as $z,_j as dz,ck as zz,gk as Hz,hk as vz,ik as Jz}from"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(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 L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(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 UH(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,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}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"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.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 Pz.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(Z)=>{await this.sendUpdateAndWait(Z)},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:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=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 Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{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=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(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 Az(_,$z()).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:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.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 Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,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 L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let 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,Z,_=(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 Z=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,Z)_(Z);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:[]})}}),Z=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:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,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 hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="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 X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});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(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),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=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.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 L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.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($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.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 (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={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(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.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(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
5
5
  `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${J.revision} (${J.serverName}): ${J.phase} ${J.attempt}/${J.maxAttempts}
@@ -7,17 +7,17 @@ import{v as zH,w as HH}from"./chunk-ky9br0z8.js";import{A as S,x as kz,y as Cz,z
7
7
  `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${J.revision} (${J.serverName}): ${J.action}${J.detailsOmitted?" details-omitted":""}
8
8
  `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${J.revision} ${J.taskId} (${J.serverName}/${J.toolName}): ${J.status}${J.hasResult?" result-available":""}
9
9
  `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${J.files.length}${J.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_admission":_=J.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":J.phase!=="admitted"?{phase:J.phase,requestClass:J.requestClass,resource:J.resource,scope:J.scope,...J.reason!==void 0?{reason:J.reason}:{},queuePosition:J.queuePosition,queueDepth:J.queueDepth,inFlight:J.inFlight,limit:J.limit,waitMs:J.waitMs,maxWaitMs:J.maxWaitMs,...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:J.phase,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.retryAfterMs!==void 0?{retryAfterMs:J.retryAfterMs}:{},...J.nextProbeAt!==void 0?{nextProbeAt:J.nextProbeAt}:{},openDurationMs:J.openDurationMs,...J.sampleCount!==void 0?{sampleCount:J.sampleCount}:{},...J.failureCount!==void 0?{failureCount:J.failureCount}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.delayMs!==void 0?{delayMs:J.delayMs}:{},...J.nextRetryAt!==void 0?{nextRetryAt:J.nextRetryAt}:{},...J.mode!==void 0?{mode:J.mode}:{},...J.recoveryBudgetMs!==void 0?{recoveryBudgetMs:J.recoveryBudgetMs}:{},...J.recoveryElapsedMs!==void 0?{recoveryElapsedMs:J.recoveryElapsedMs}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{},...J.exhaustedBy!==void 0?{exhaustedBy:J.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":J.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted}}});break;case"provider_recovery":break;case"model_fallback":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/modelFallback":{from:J.from,to:J.to,candidate:J.candidate,candidateCount:J.candidateCount,trigger:J.trigger}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware}}});break;case"task_update":this.sendPlanUpdate(J.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:J.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:J.goal.goalId,status:J.goal.status,taskListId:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,inProgress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,nextTask:J.frontier.nextTask,digestSha256:J.frontier.digestSha256,...J.goal.frontierStall?{stall:{category:J.goal.frontierStall.category,consecutiveCount:J.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(J.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(J.queue);let D=0;for(let A of J.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of gz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),D++}if(D>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${D} queued instruction${D===1?"":"s"} recovered after restart]
10
+ `}});break;case"provider_admission":_=J.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":J.phase!=="admitted"?{phase:J.phase,requestClass:J.requestClass,resource:J.resource,scope:J.scope,...J.reason!==void 0?{reason:J.reason}:{},queuePosition:J.queuePosition,queueDepth:J.queueDepth,inFlight:J.inFlight,limit:J.limit,waitMs:J.waitMs,maxWaitMs:J.maxWaitMs,...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:J.phase,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.retryAfterMs!==void 0?{retryAfterMs:J.retryAfterMs}:{},...J.nextProbeAt!==void 0?{nextProbeAt:J.nextProbeAt}:{},openDurationMs:J.openDurationMs,...J.sampleCount!==void 0?{sampleCount:J.sampleCount}:{},...J.failureCount!==void 0?{failureCount:J.failureCount}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:J.phase,attempt:J.attempt,maxRetries:J.maxRetries,reason:J.reason,...J.statusCode!==void 0?{statusCode:J.statusCode}:{},...J.delayMs!==void 0?{delayMs:J.delayMs}:{},...J.nextRetryAt!==void 0?{nextRetryAt:J.nextRetryAt}:{},...J.mode!==void 0?{mode:J.mode}:{},...J.recoveryBudgetMs!==void 0?{recoveryBudgetMs:J.recoveryBudgetMs}:{},...J.recoveryElapsedMs!==void 0?{recoveryElapsedMs:J.recoveryElapsedMs}:{},...J.recoveryRemainingMs!==void 0?{recoveryRemainingMs:J.recoveryRemainingMs}:{},...J.exhaustedBy!==void 0?{exhaustedBy:J.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":J.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:J.phase,stallCount:J.stallCount,durationMs:J.durationMs,warningAfterMs:J.warningAfterMs,timeoutMs:J.timeoutMs,outputStarted:J.outputStarted}}});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:J.from,to:J.to,candidate:J.candidate,candidateCount:J.candidateCount,trigger:J.trigger}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:J.phase,toolName:J.toolName,runLength:J.runLength,nudgeThreshold:J.nudgeThreshold,haltThreshold:J.haltThreshold,progressAware:J.progressAware}}});break;case"task_update":this.sendPlanUpdate(J.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:J.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:J.goal.goalId,status:J.goal.status,taskListId:J.frontier.taskListId,total:J.frontier.total,completed:J.frontier.completed,inProgress:J.frontier.inProgress,pending:J.frontier.pending,blocked:J.frontier.blocked,nextTask:J.frontier.nextTask,digestSha256:J.frontier.digestSha256,...J.goal.frontierStall?{stall:{category:J.goal.frontierStall.category,consecutiveCount:J.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(J.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot(J.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot(J.queue);let D=0;for(let A of J.messages){if(!A.recovered||A.persisted)continue;if(H.projectedRecoveredInputIds?.has(A.id))continue;for(let q of cz(A.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});H.projectedRecoveredInputIds?.add(A.id),D++}if(D>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${D} queued instruction${D===1?"":"s"} recovered after restart]
11
11
  `}});break}case"goal_updated":if(J.goal)this.sendUpdate(this.goalSessionUpdate(J.goal));if(J.goal&&J.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${J.goal.status}: ${J.goal.objective}]
12
- `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:J.goal.goalId,continuation:J.continuation,...J.prematureStopPattern?{prematureStopPattern:J.prematureStopPattern}:{},...J.prematureStopCount!==void 0?{prematureStopCount:J.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:J.phase,...J.reason?{reason:J.reason}:{},...J.strategy?{strategy:J.strategy}:{},...J.outcome?{outcome:J.outcome}:{},...J.preTokens!==void 0?{preTokens:J.preTokens}:{},...J.preTokenSource?{preTokenSource:J.preTokenSource}:{},...J.estimatedPendingTokens!==void 0?{estimatedPendingTokens:J.estimatedPendingTokens}:{},...J.postTokens!==void 0?{postTokens:J.postTokens}:{},...J.sampleAttempts!==void 0?{sampleAttempts:J.sampleAttempts}:{},...J.inputReductions!==void 0?{inputReductions:J.inputReductions}:{},...J.messagesOmitted!==void 0?{messagesOmitted:J.messagesOmitted}:{},...J.filesOmitted!==void 0?{filesOmitted:J.filesOmitted}:{},...J.imagesOmitted!==void 0?{imagesOmitted:J.imagesOmitted}:{},...J.fallbackTargetTokens!==void 0?{fallbackTargetTokens:J.fallbackTargetTokens}:{},...J.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:J.fallbackMessagesOmitted}:{},...J.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:J.fallbackMessagesTruncated}:{},...J.failureReason?{failureReason:J.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...j.messages];let Lz=await this.loadPersistedMessages();if(this.messages=Lz.length>0?Lz:[...j.messages],!N.success){let J=N.error?.type??"unknown",D=N.error?.details??N.error?.message??"Agent execution failed",A=WH(D)??v(D);throw uz.internalError({failureType:J,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${J})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Qz={...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(Qz).length>0?{_meta:Qz}:{}}}catch(j){if(B.signal.aborted||j instanceof Error&&j.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,j),j}finally{if(H.abortSignal?.removeEventListener("abort",Z),_&&!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 L=new AbortController,Y,$=new Promise((W)=>{Y=W});this.pendingUserShell=L,this.pendingUserShellCompletion=$;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:L.signal,onEvent:async(Z)=>{if(X=Z.executionId,Z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.executionId,status:"in_progress",title:`! ${Z.command}`,content:[],kind:"execute"});return}if(Z.type==="output"){Q+=Z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.chunk}}]});return}let _=a(Z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:Z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?XH(Z.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 L.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(L.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===$)this.pendingUserShellCompletion=null;if(this.pendingUserShell===L){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,L=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(L,z),this.pendingResumeTimer.unref?.();else queueMicrotask(L)}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 L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}})}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:kz,...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 L="preflight",Y=!1,$,X=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",Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none"&&(Z.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(Z.state==="requires_attention"){this.clearPendingResumeRequest();return}L=Q?"pending_input":"goal",Y=!0;let _=Cz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}let U=new AbortController;X=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),X.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:L==="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:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:L})))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?BH(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=L==="preflight"||L==="pending_input"&&this.runtime.getPendingSteeringCount()>0,Z=fz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if(Z.phase==="retry_scheduled")this.pendingResumeRequested=!0,$=Z.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:L,taskFailure:W?.taskFailure,delayMs:Z.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${Z.delayMs}ms`);else{let _=Z.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:L,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${Z.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=$??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 L=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(L);await this.persistPermissionMode(Y),this.mode=L,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(L){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 L}}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(L){throw Error(L instanceof Error?L.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(L){throw await this.runtime.refresh({reasoningEffort:H.selection}),L}}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(L){throw Error(L instanceof Error?L.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(L){throw await this.runtime.refresh({serviceTier:H.selection}),L}}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(L){throw Error(L instanceof Error?L.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(L){throw await this.runtime.refresh({responseVerbosity:H.selection}),L}}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(),L=this.runtime.resolveCommunicationStyleConfiguration(z);if(L.source!=="built-in"&&!L.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:L.source==="built-in"?null:L.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...L.source!=="built-in"&&L.contentSha256?{communicationStyleDigest:L.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 Rz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,L=this.runtime,Y=this.pendingPromptCompletion,$=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async(Z)=>{try{await Z()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if($)await B(()=>$);if(X)await B(()=>X);if(Q)await B(()=>Q);if(z&&Y&&L)await B(()=>L.discardPendingInput());if(H)await B(()=>H.destroy());if(L)await B(()=>L.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=[],L=[],Y=0,$=0,X=0,Q=(Z)=>{if(L.length>0)L.push({type:"text",text:`
12
+ `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:J.goal.goalId,continuation:J.continuation,...J.prematureStopPattern?{prematureStopPattern:J.prematureStopPattern}:{},...J.prematureStopCount!==void 0?{prematureStopCount:J.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:J.phase,...J.reason?{reason:J.reason}:{},...J.strategy?{strategy:J.strategy}:{},...J.outcome?{outcome:J.outcome}:{},...J.preTokens!==void 0?{preTokens:J.preTokens}:{},...J.preTokenSource?{preTokenSource:J.preTokenSource}:{},...J.estimatedPendingTokens!==void 0?{estimatedPendingTokens:J.estimatedPendingTokens}:{},...J.postTokens!==void 0?{postTokens:J.postTokens}:{},...J.sampleAttempts!==void 0?{sampleAttempts:J.sampleAttempts}:{},...J.inputReductions!==void 0?{inputReductions:J.inputReductions}:{},...J.messagesOmitted!==void 0?{messagesOmitted:J.messagesOmitted}:{},...J.filesOmitted!==void 0?{filesOmitted:J.filesOmitted}:{},...J.imagesOmitted!==void 0?{imagesOmitted:J.imagesOmitted}:{},...J.fallbackTargetTokens!==void 0?{fallbackTargetTokens:J.fallbackTargetTokens}:{},...J.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:J.fallbackMessagesOmitted}:{},...J.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:J.fallbackMessagesTruncated}:{},...J.failureReason?{failureReason:J.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...j.messages];let Qz=await this.loadPersistedMessages();if(this.messages=Qz.length>0?Qz:[...j.messages],!N.success){let J=N.error?.type??"unknown",D=N.error?.details??N.error?.message??"Agent execution failed",A=BH(D)??v(D);throw gz.internalError({failureType:J,modelId:this.runtime.getCurrentModelId(),taskFailure:A,outputStarted:U,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${J})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Yz={...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(Yz).length>0?{_meta:Yz}:{}}}catch(j){if(B.signal.aborted||j instanceof Error&&j.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,j),j}finally{if(H.abortSignal?.removeEventListener("abort",Z),_&&!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 L=new AbortController,Y,$=new Promise((W)=>{Y=W});this.pendingUserShell=L,this.pendingUserShellCompletion=$;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(H,{signal:L.signal,onEvent:async(Z)=>{if(X=Z.executionId,Z.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z.executionId,status:"in_progress",title:`! ${Z.command}`,content:[],kind:"execute"});return}if(Z.type==="output"){Q+=Z.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:Z.chunk}}]});return}let _=r(Z.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Z.executionId,status:Z.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?WH(Z.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 L.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(L.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(Y(),this.pendingUserShellCompletion===$)this.pendingUserShellCompletion=null;if(this.pendingUserShell===L){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,L=()=>{if(H!==this.pendingResumeGeneration)return;this.startPendingResumeRun(H)};if(z>0)this.pendingResumeTimer=setTimeout(L,z),this.pendingResumeTimer.unref?.();else queueMicrotask(L)}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 L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}},()=>{if(this.pendingResumeCompletion===H){this.pendingResumeCompletion=null;let L=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,L!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(L)}})}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:Cz,...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 L="preflight",Y=!1,$,X=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",Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none"&&(Z.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(Z.state==="requires_attention"){this.clearPendingResumeRequest();return}L=Q?"pending_input":"goal",Y=!0;let _=fz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(_<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:H,kind:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}let U=new AbortController;X=setTimeout(()=>{U.abort("acp-pending-resume-budget-exhausted")},_),X.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:L==="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:L,taskFailure:I("timeout")})),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(H>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:H,kind:L})))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?_H(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=L==="preflight"||L==="pending_input"&&this.runtime.getPendingSteeringCount()>0,Z=uz({sessionIdentity:this.id,failedAttempt:H,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:W});if(Z.phase==="retry_scheduled")this.pendingResumeRequested=!0,$=Z.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:H+1,kind:L,taskFailure:W?.taskFailure,delayMs:Z.delayMs})),G.warn(`[AcpSession ${this.id}] Pending resume attempt ${H} failed; retrying in ${Z.delayMs}ms`);else{let _=Z.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(_,{attempt:H,kind:L,taskFailure:W?.taskFailure})),G.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${H}, retryable=${Z.retryable}, phase=${_})`,Q),!this.preserveNewPendingInput(L))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=$??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 L=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(L);await this.persistPermissionMode(Y),this.mode=L,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(L){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 L}}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(L){throw Error(L instanceof Error?L.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(L){throw await this.runtime.refresh({reasoningEffort:H.selection}),L}}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(L){throw Error(L instanceof Error?L.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(L){throw await this.runtime.refresh({serviceTier:H.selection}),L}}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(L){throw Error(L instanceof Error?L.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(L){throw await this.runtime.refresh({responseVerbosity:H.selection}),L}}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(),L=this.runtime.resolveCommunicationStyleConfiguration(z);if(L.source!=="built-in"&&!L.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:L.source==="built-in"?null:L.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...L.source!=="built-in"&&L.contentSha256?{communicationStyleDigest:L.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 Sz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let H=this.agent,L=this.runtime,Y=this.pendingPromptCompletion,$=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let W,B=async(Z)=>{try{await Z()}catch(_){W??=_}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if($)await B(()=>$);if(X)await B(()=>X);if(Q)await B(()=>Q);if(z&&Y&&L)await B(()=>L.discardPendingInput());if(H)await B(()=>H.destroy());if(L)await B(()=>L.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=[],L=[],Y=0,$=0,X=0,Q=(Z)=>{if(L.length>0)L.push({type:"text",text:`
13
13
  `}),X+=1;if(L.push(Z),Z.type==="text")X+=Z.text.length};for(let Z of z)if(Z.type==="text")H.push(Z.text),Q({type:"text",text:Z.text});else if(Z.type==="image"){let _=`data:${Z.mimeType};base64,${Z.data}`;Y+=1,$+=_.length,H.push(`[Image: ${Z.mimeType}]`),Q({type:"image_url",image_url:{url:_}})}else if(Z.type==="resource"){let _=Z.resource;if("text"in _){let U=`<file path="${_.uri}">
14
14
  ${_.text}
15
- </file>`;H.push(U),Q({type:"text",text:U})}}else if(Z.type==="resource_link"){let _=`[Resource: ${Z.uri}]`;H.push(_),Q({type:"text",text:_})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if($>$z)throw Error("ACP prompt images exceed the 5 MiB limit");if(X>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(H.join(`
15
+ </file>`;H.push(U),Q({type:"text",text:U})}}else if(Z.type==="resource_link"){let _=`[Resource: ${Z.uri}]`;H.push(_),Q({type:"text",text:_})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if($>Xz)throw Error("ACP prompt images exceed the 5 MiB limit");if(X>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(H.join(`
16
16
  `),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=H.join(`
17
- `);return{content:Y>0?L: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}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/followUpQueue":_H(H.data)}})}sendProviderRecoveryProjection(z){let H=m.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRecovery":H.data}})}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((L)=>({content:L.subject,priority:L.priority,status:L.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 L=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(L))return G.debug(`[AcpSession ${this.id}] Auto-approving ${L} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(L==="write"||L==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${L} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),$=[];if(z.message)$.push({type:"content",content:{type:"text",text:z.message}});if(z.details)$.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)$.push({type:"content",content:{type:"text",text:`Risks:
17
+ `);return{content:Y>0?L: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}}}}sendFollowUpQueueSnapshot(z){let H=i.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/followUpQueue":UH(H.data)}})}sendProviderRecoveryProjection(z){let H=m.safeParse(z);if(!H.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"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.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnActivity":H.data}})}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((L)=>({content:L.subject,priority:L.priority,status:L.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 L=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(L))return G.debug(`[AcpSession ${this.id}] Auto-approving ${L} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(L==="write"||L==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${L} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),$=[];if(z.message)$.push({type:"content",content:{type:"text",text:z.message}});if(z.details)$.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)$.push({type:"content",content:{type:"text",text:`Risks:
18
18
  - ${z.risks.join(`
19
19
  - `)}`}});let X=this.mapToolKind(L),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:$,kind:X}},W=await this.waitForClientInteraction(this.connection.requestPermission(Q),H);if(!W)return{approved:!1,reason:d};let B=W.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let Z=B.optionId;if(Z==="allow_always")return{approved:!0,scope:"project"};if(Z==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let _=Z==="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 L=z.questions??[];if(L.length===0)return{approved:!1,reason:"No structured questions were provided"};if(L.some(($)=>$.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[$,X]of L.entries()){let Q=X.options.map((_,U)=>`answer:${$}:${U}`),W=`answer:${$}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...X.options.map((_,U)=>({optionId:Q[U],name:_.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:X.header,kind:"think",content:[{type:"content",content:{type:"text",text:[X.question,...X.options.map((_)=>`${_.label}: ${_.description}`)].join(`
20
20
  `)}}]}}),H);if(!B)return{approved:!1,reason:d};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let Z=Q.indexOf(B.outcome.optionId);if(Z<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[X.header]=X.options[Z].label}return{approved:!0,answers:Y}}catch($){return G.warn(`[AcpSession ${this.id}] Question request failed:`,$),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,H){let L=z.mcpElicitation;if(!L)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(L.mode==="url"){let $=await this.requestElicitationChoice("MCP external authorization",[L.message,`Server: ${L.serverName}`,`Domain: ${L.domain??"unknown"}`,`URL: ${L.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
21
21
  `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],H);if($==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:$==="decline"?"User declined URL":"User cancelled",elicitation:{action:$==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let $ of L.fields??[]){let X=await this.collectAcpElicitationField($,H);if(X.cancelled)return{approved:!1,reason:X.reason,elicitation:{action:"cancel"}};if(X.value!==void 0)Y[$.name]=X.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 L=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((X,Q)=>({id:`option:${Q}`,label:X.label,value:X.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
22
22
  `),[...L.map((X)=>({id:X.id,label:X.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(Y==="skip")return{cancelled:!1};let $=L.find((X)=>X.id===Y);if(!$)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:$.value}}if(z.defaultValue!==void 0){let L=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(L==="default")return{cancelled:!1,value:z.defaultValue};if(L==="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,L,Y){let $=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...L.map((X)=>({optionId:X.id,name:X.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 $?.outcome.outcome==="selected"?$.outcome.optionId:void 0}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((L,Y)=>{let $=!1,X=(W)=>{if($)return;$=!0,H.removeEventListener("abort",Q),W()},Q=()=>X(()=>L(void 0));if(H.addEventListener("abort",Q,{once:!0}),H.aborted)Q();z.then((W)=>X(()=>L(W)),(W)=>X(()=>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=y("Agent"),GH="remote task isolation is not supported";function h(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function VH(z){return C.invalidParams({code:z.code,reason:z.reason})}function jH(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:GH})}function cz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function pz(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 e(z)}catch(H){if(H instanceof mz)throw VH(H);throw H}}function o(z,H){let L=zz(z);return Object.freeze({kind:"acp-remote",hostStateRoot:Hz(L.collisionIdentity),executionRoot:L.wirePath,hostResourceRoot:H,profile:z,descriptor:L})}function n(z,H){let L=dz(z.remoteWorkspace),Y=Hz(L.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let $=e(L.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:L.wirePath,hostResourceRoot:H,profile:$,descriptor:L})}function DH(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Jz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=r.resolve(s())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=rz();this.runtimeResidencyValue=new HH({maxResident:z?.maxResidentSessionRuntimes??iz,idleMs:z?.sessionRuntimeIdleMs??az})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(H){if(H instanceof zH)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 oz(),{protocolVersion:UH,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=t("acp"),L=z.cwd||s(),Y=h(this.clientCapabilities),$=Y?k(L):void 0,X=z._meta?.["blade/taskIsolation"],Q=X==="local"||X==="worktree"?X:void 0;if(Y&&Q)throw jH();let W=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(H),Z;try{let _,U;if($){let T=o($,this.hostResourceRoot);_=await F.createRemoteSessionMetadata(H,T.hostStateRoot,T.descriptor,{}),U=n(_,this.hostResourceRoot)}else U=P(L);let V=!Y&&Q?await ez.createSessionTask({sessionId:H,prompt:typeof W==="string"&&W.trim()?W:"ACP task session",sourceProjectPath:L,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}`),Z=new x(H,U,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...V?.taskWorktree?{taskWorktree:V.taskWorktree}:{},...V?.metadata.taskIsolation?{taskIsolation:V.metadata.taskIsolation}:{}}),await Z.initialize(),this.assertNotDestroyed(),this.commitSession(H,Z,B),O.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),Z.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H,V?.metadata,Z.getModelConfiguration())}catch(_){throw B.cancel(),await Z?.destroy().catch(()=>{return}),_}}async listSessions(z){let H=h(this.clientCapabilities);if(!H&&z.cwd!=null&&!r.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let L=H?await F.listRemoteSessionPage({...z.cwd!=null?{descriptor:zz(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await F.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:L.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:H?DH(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:L.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let H=h(this.clientCapabilities),L=H?o(k(z.cwd),this.hostResourceRoot):void 0;if(!H&&!r.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=t("fork"),$=await this.reserveSessionRuntime(Y),X;try{let Q;try{Q=await F.forkSession(z.sessionId,{sourceProjectPath:L?.hostStateRoot??z.cwd,targetProjectPath:L?.hostStateRoot??z.cwd,newSessionId:Y,...L?{remote:{expectedDescriptor:L.descriptor}}:{}})}catch(B){if(pz(B))throw cz();throw B}this.assertNotDestroyed();let W=H?n(Q.metadata,this.hostResourceRoot):P(Q.projectPath??z.cwd);return X=new x(Q.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await X.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,X,$),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,H?void 0:Q.metadata,X.getModelConfiguration())}catch(Q){throw $.cancel(),await X?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),O.info(`[BladeAgent] Loading session: ${z.sessionId}`);let L=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=L.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await L}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!h(this.clientCapabilities)){await F.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let W=await this.reserveSessionRuntime(z.sessionId),B;try{let[Z,_]=await Promise.all([F.loadSession(z.sessionId,z.cwd),F.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:Z,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(Z){throw W.cancel(),await B?.destroy().catch(()=>{return}),Z}}let L=o(k(z.cwd),this.hostResourceRoot),Y;try{Y=await F.assertRemoteSessionWritable(z.sessionId,L.hostStateRoot,L.descriptor)}catch(W){if(pz(W))throw cz();throw W}let $=n(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),Q;try{let W=await F.loadRemoteSession(z.sessionId,$.hostStateRoot,$.descriptor);return Q=new x(z.sessionId,$,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,X),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(W){throw X.cancel(),await Q?.destroy().catch(()=>{return}),W}}commitSession(z,H,L){let Y=L.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 L=this.sessions.get(z);if(!L)return;let Y=this.runtimeResidency.owns(z,L),$;try{await L.destroy(H)}catch(Q){$=Q}let X=await this.runtimeResidency.forget(z,L);if(this.sessions.get(z)===L)this.sessions.delete(z);if(Y&&!X&&$===void 0)throw Error(`ACP Session is still active: ${z}`);if($!==void 0)throw $}buildChildSessionResponse(z,H,L){return{sessionId:z,...this.buildSessionSetup(L,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 L=z?.models??[],Y=(z?.currentModelId&&L.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??L[0]?.id,$=[{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"}],X=[];if(L.length>0)X.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:L.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)X.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)X.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)X.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)X.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:$,currentModeId:H},configOptions:X.length>0?X:void 0}}async closeSession(z){this.assertNotDestroyed();let L=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=L.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await L}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 L=H.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")O.info(`[BladeAgent] Setting session model: ${z.value}`),await L.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&nz(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await L.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&lz(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await L.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&vz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await L.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&sz(z.value))O.info(`[BladeAgent] Setting communication style: ${z.value}`),await L.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(L.getModelConfiguration(),L.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(L){z??=L}try{await this.runtimeResidency.disposeAll()}catch(H){z??=H}this.sessions.clear();try{await tz.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function KJ(){let z=KH.toWeb(process.stdout),H=FH.toWeb(process.stdin),L=f.ndJsonStream(z,H),Y,$=new f.AgentSideConnection((Q)=>{return Y=new Jz(Q),Y},L),X=JH(async()=>{await Y?.destroy()});try{await $.closed}finally{X(),await Y?.destroy()}}export{KJ as runAcpIntegration,P as createLocalAcpSessionRoots};
23
+ `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],H);if(L==="default")return{cancelled:!1,value:z.defaultValue};if(L==="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,L,Y){let $=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...L.map((X)=>({optionId:X.id,name:X.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 $?.outcome.outcome==="selected"?$.outcome.optionId:void 0}async waitForClientInteraction(z,H){if(!H)return z;if(H.aborted)return;return new Promise((L,Y)=>{let $=!1,X=(W)=>{if($)return;$=!0,H.removeEventListener("abort",Q),W()},Q=()=>X(()=>L(void 0));if(H.addEventListener("abort",Q,{once:!0}),H.aborted)Q();z.then((W)=>X(()=>L(W)),(W)=>X(()=>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=y("Agent"),VH="remote task isolation is not supported";function h(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function jH(z){return C.invalidParams({code:z.code,reason:z.reason})}function DH(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:VH})}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 zz(z)}catch(H){if(H instanceof dz)throw jH(H);throw H}}function n(z,H){let L=Hz(z);return Object.freeze({kind:"acp-remote",hostStateRoot:Jz(L.collisionIdentity),executionRoot:L.wirePath,hostResourceRoot:H,profile:z,descriptor:L})}function s(z,H){let L=vz(z.remoteWorkspace),Y=Jz(L.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let $=zz(L.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:L.wirePath,hostResourceRoot:H,profile:$,descriptor:L})}function FH(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Lz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=o.resolve(t())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=oz();this.runtimeResidencyValue=new JH({maxResident:z?.maxResidentSessionRuntimes??az,idleMs:z?.sessionRuntimeIdleMs??rz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(H){if(H instanceof HH)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 nz(),{protocolVersion:GH,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=e("acp"),L=z.cwd||t(),Y=h(this.clientCapabilities),$=Y?k(L):void 0,X=z._meta?.["blade/taskIsolation"],Q=X==="local"||X==="worktree"?X:void 0;if(Y&&Q)throw DH();let W=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(H),Z;try{let _,U;if($){let T=n($,this.hostResourceRoot);_=await F.createRemoteSessionMetadata(H,T.hostStateRoot,T.descriptor,{}),U=s(_,this.hostResourceRoot)}else U=P(L);let V=!Y&&Q?await zH.createSessionTask({sessionId:H,prompt:typeof W==="string"&&W.trim()?W:"ACP task session",sourceProjectPath:L,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}`),Z=new x(H,U,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...V?.taskWorktree?{taskWorktree:V.taskWorktree}:{},...V?.metadata.taskIsolation?{taskIsolation:V.metadata.taskIsolation}:{}}),await Z.initialize(),this.assertNotDestroyed(),this.commitSession(H,Z,B),O.info(`[BladeAgent] Session ${H} created, scheduling available commands update`),Z.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(H,V?.metadata,Z.getModelConfiguration())}catch(_){throw B.cancel(),await Z?.destroy().catch(()=>{return}),_}}async listSessions(z){let H=h(this.clientCapabilities);if(!H&&z.cwd!=null&&!o.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let L=H?await F.listRemoteSessionPage({...z.cwd!=null?{descriptor:Hz(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await F.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:L.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:H?FH(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:L.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let H=h(this.clientCapabilities),L=H?n(k(z.cwd),this.hostResourceRoot):void 0;if(!H&&!o.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=e("fork"),$=await this.reserveSessionRuntime(Y),X;try{let Q;try{Q=await F.forkSession(z.sessionId,{sourceProjectPath:L?.hostStateRoot??z.cwd,targetProjectPath:L?.hostStateRoot??z.cwd,newSessionId:Y,...L?{remote:{expectedDescriptor:L.descriptor}}:{}})}catch(B){if(mz(B))throw pz();throw B}this.assertNotDestroyed();let W=H?s(Q.metadata,this.hostResourceRoot):P(Q.projectPath??z.cwd);return X=new x(Q.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await X.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,X,$),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,H?void 0:Q.metadata,X.getModelConfiguration())}catch(Q){throw $.cancel(),await X?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),O.info(`[BladeAgent] Loading session: ${z.sessionId}`);let L=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=L.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await L}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!h(this.clientCapabilities)){await F.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let W=await this.reserveSessionRuntime(z.sessionId),B;try{let[Z,_]=await Promise.all([F.loadSession(z.sessionId,z.cwd),F.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:Z,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(Z){throw W.cancel(),await B?.destroy().catch(()=>{return}),Z}}let L=n(k(z.cwd),this.hostResourceRoot),Y;try{Y=await F.assertRemoteSessionWritable(z.sessionId,L.hostStateRoot,L.descriptor)}catch(W){if(mz(W))throw pz();throw W}let $=s(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),Q;try{let W=await F.loadRemoteSession(z.sessionId,$.hostStateRoot,$.descriptor);return Q=new x(z.sessionId,$,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,X),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(W){throw X.cancel(),await Q?.destroy().catch(()=>{return}),W}}commitSession(z,H,L){let Y=L.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 L=this.sessions.get(z);if(!L)return;let Y=this.runtimeResidency.owns(z,L),$;try{await L.destroy(H)}catch(Q){$=Q}let X=await this.runtimeResidency.forget(z,L);if(this.sessions.get(z)===L)this.sessions.delete(z);if(Y&&!X&&$===void 0)throw Error(`ACP Session is still active: ${z}`);if($!==void 0)throw $}buildChildSessionResponse(z,H,L){return{sessionId:z,...this.buildSessionSetup(L,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 L=z?.models??[],Y=(z?.currentModelId&&L.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??L[0]?.id,$=[{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"}],X=[];if(L.length>0)X.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:L.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)X.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)X.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)X.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)X.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:$,currentModeId:H},configOptions:X.length>0?X:void 0}}async closeSession(z){this.assertNotDestroyed();let L=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=L.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await L}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 L=H.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")O.info(`[BladeAgent] Setting session model: ${z.value}`),await L.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&sz(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await L.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&iz(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await L.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&lz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await L.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&tz(z.value))O.info(`[BladeAgent] Setting communication style: ${z.value}`),await L.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(L.getModelConfiguration(),L.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(L){z??=L}try{await this.runtimeResidency.disposeAll()}catch(H){z??=H}this.sessions.clear();try{await ez.getInstance().disconnectAll()}catch(H){z??=H}if(z!==void 0)throw z}}async function NJ(){let z=wH.toWeb(process.stdout),H=KH.toWeb(process.stdin),L=f.ndJsonStream(z,H),Y,$=new f.AgentSideConnection((Q)=>{return Y=new Lz(Q),Y},L),X=LH(async()=>{await Y?.destroy()});try{await $.closed}finally{X(),await Y?.destroy()}}export{NJ as runAcpIntegration,P as createLocalAcpSessionRoots};
@@ -1,4 +1,4 @@
1
- import{Vg as A1,Wg as L0,Xg as M1,ah as v0}from"./chunk-etf3e9kt.js";import{hh as SO,ih as F1}from"./chunk-karq4wfd.js";import{lh as x1}from"./chunk-69nwa6bn.js";import{mh as A0,oh as J0}from"./chunk-mavranwn.js";import{Bi as z0,Ci as WO,Gi as b0}from"./chunk-ramana2t.js";import{Si as M}from"./chunk-g799czsy.js";import{sj as P,tj as S,uj as u,wj as L,zj as l1}from"./chunk-vp6d1fqp.js";import{Mj as c0}from"./chunk-g9vdmvk2.js";import{Tj as N}from"./chunk-wxypv01z.js";import{ok as qO}from"./chunk-0k2x2ae6.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
1
+ import{Yg as A1,Zg as L0,_g as M1,dh as v0}from"./chunk-yvmexv2c.js";import{kh as SO,lh as F1}from"./chunk-rhwkvx96.js";import{oh as x1}from"./chunk-az08pq83.js";import{ph as A0,rh as J0}from"./chunk-sdhdn0yx.js";import{Ei as z0,Fi as WO,Ji as b0}from"./chunk-40pd090k.js";import{Vi as M}from"./chunk-dv2m2xe5.js";import{Cj as l1,vj as P,wj as S,xj as u,zj as L}from"./chunk-ft1bdqbs.js";import{Pj as c0}from"./chunk-mtfjwsn2.js";import{Wj as N}from"./chunk-jy7k2dwm.js";import{rk as qO}from"./chunk-t88sfhjj.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
2
2
  ${J.map((K)=>`- ${K}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4
 
@@ -730,4 +730,4 @@ ${Z.join(`
730
730
  </${Q}>`:"";return{content:K,files:[...O],references:O.map($4),triggerPaths:[...$],contentBytes:Buffer.byteLength(K,"utf8"),provenanceSha256:D0(O.map((q)=>`${q.id}:${q.contentSha256}`).join(`
731
731
  `))}}function TO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let K=O[J];if(!K)continue;let q=Buffer.byteLength(K.content,"utf8");if(q>Q)continue;Z.push(K),Q-=q}return Z.reverse()}class m{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=G1(O),this.definitions=Object.freeze([...$].sort(W1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=D0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
732
732
  `))}static empty(O){return new m(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new m(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=l$){if(this.definitions.length===0)return q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&L1(J.scopeDirectory,Q));return q0(TO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=s$){if(this.definitions.length===0)return q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),K=[...new Set($.map((G)=>Y1(z.relative(this.projectRoot,G1(G)))).filter(X1))].sort(),q=new Map;for(let G of K)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!L1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=z.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((U)=>_O(U,{dot:!0})(X)))continue}else if(L1(Y.scopeDirectory,J))continue;q.set(Y.id,Y)}let W=TO([...q.values()].sort(W1),Z);return q0(W,K,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(W1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=Y1(z.relative(this.projectRoot,G1(O)));if($&&!X1($))throw Error("Project instruction source is outside the catalog root");return $}}async function Q4(O,$){let Q=await d.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>IO)throw Error(`Project rule exceeds ${IO} bytes`);let Z=await d.realpath($),J=Y1(z.relative(O,Z));if(!X1(J))throw Error("Project rule escapes its repository root");let K=await d.readFile(Z,"utf8");if(wO(K))throw Error("Project rule contains hidden control characters");let q=c$(K),W=q.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=e$(q.data.paths),Y=O4(J),X=D0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${D0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function DO(O,$){let Q=r$(O);if(!$.projectTrusted)return m.empty(Q);let Z=await d.realpath(Q),J=u$.stream([...a$],{cwd:Z,absolute:!0,dot:!0,deep:n$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...t$]}),K=[];for await(let Y of J)if(K.push(Y.toString()),K.length>MO)throw Error(`Project rule catalog exceeds ${MO} files`);K.sort();let q=new Set(K.filter((Y)=>z.basename(Y)==="AGENTS.override.md").map((Y)=>z.dirname(Y))),W=[],G=0;for(let Y of K){if(z.basename(Y)==="AGENTS.md"&&q.has(z.dirname(Y)))continue;try{let X=await Q4(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>bO)throw Error(`Project rule catalog exceeds ${bO} bytes`);W.push(X)}catch(X){o$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new m(Z,W)}var CO=32,C0=64;class NO extends Error{capacity=C0;constructor(){super(`Workspace agent resource capacity is full (${C0})`);this.name="WorkspaceAgentResourceCapacityError"}}var T=new Map,H1=0,EO=[];async function Z4(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await K1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function J4(O){let $={...O};for(let Q of Object.values(A0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function K5(O){EO=[...new Set(O.map(($)=>N0.resolve($)))]}function vO(O,$){HO(O,$.plugins),w.releaseInstance(O,$.subagents),h.releaseInstance({cwd:O},$.skills),x.releaseInstance(O,$.commands),C.releaseInstance(O,$.plugins)}function RO(O){vO(O.workspaceRoot,O)}function K0(){while(T.size>CO){let O=!1;for(let[$,Q]of T){if(!Q.resources||Q.users>0)continue;if(T.get($)!==Q)continue;T.delete($),RO(Q.resources),O=!0;break}if(!O)return}}function q4(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),K0()}).unref?.()}async function K4(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),K=x.getInstance(O),q=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),K.isInitialized()?void 0:K.initialize(O),q.isInitialized()?void 0:q.initialize(O,[...$.cliPluginDirs??EO])]),x0(O),await J1(O);let W=await K1(O,{projectTrusted:Q.state==="trusted",plugins:q.getActive()}),G=await DO(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:K,plugins:q,communicationStyles:W,projectRules:G}}catch(W){throw vO(O,{subagents:Z,skills:J,commands:K,plugins:q}),W}}function G4(O,$){let Q={generation:H1,users:0};return Q.promise=K4(O,$).then((Z)=>{if(Q.generation!==H1||T.get(O)!==Q)return RO(Z),Z;return Q.resources=Z,K0(),Z},(Z)=>{if(T.get(O)===Q)T.delete(O);throw Z}),T.set(O,Q),Q}async function yO(O,$){let Q=N0.resolve(O),Z=T.get(Q);if(!Z){if(K0(),T.size>=C0)throw new NO;Z=G4(Q,$)}else T.delete(Q),T.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(K){throw Z.users=Math.max(0,Z.users-1),K0(),K}return{entry:Z,resources:J}}async function fO(O,$){if(!$)return;x0(O.workspaceRoot),await J1(O.workspaceRoot),await Z4(O)}async function G5(O,$={}){let Q=await yO(O,$);try{return await fO(Q.resources,$.reconcilePlugins),Q.resources}finally{q4(Q.entry)}}async function L5(O,$,Q={}){let Z=await yO(O,Q);try{return await fO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),K0()}}function W5(){let O=0,$=0;for(let Q of T.values()){if(Q.resources)O++;$+=Q.users}return{capacity:CO,activeCapacity:C0,entries:T.size,initialized:O,inFlight:T.size-O,activeUsers:$}}function Y5(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:N0.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??F1.snapshot(),projectRules:O.projectRules?.snapshot()??m.empty($),hooks:J4("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function X5(O){let $=N0.resolve(O);return{projectRoot:$,subagents:new w,skills:new h,commands:x.empty($),hooks:{enabled:!1},communicationStyles:F1.snapshot(),projectRules:m.empty($)}}function H5(){H1++;for(let[O,$]of T)if($.resources)x0(O);T.clear(),w.resetInstances(),h.resetInstance(),x.resetInstance(),C.resetInstance()}
733
- export{X4 as sg,H4 as tg,F4 as ug,I1 as vg,S4 as wg,z4 as xg,o as yg,f4 as zg,D1 as Ag,g as Bg,x as Cg,e0 as Dg,I0 as Eg,C as Fg,Q0 as Gg,J1 as Hg,x0 as Ig,m as Jg,CO as Kg,C0 as Lg,NO as Mg,Z4 as Ng,K5 as Og,G5 as Pg,L5 as Qg,W5 as Rg,Y5 as Sg,X5 as Tg,H5 as Ug};
733
+ export{X4 as vg,H4 as wg,F4 as xg,I1 as yg,S4 as zg,z4 as Ag,o as Bg,f4 as Cg,D1 as Dg,g as Eg,x as Fg,e0 as Gg,I0 as Hg,C as Ig,Q0 as Jg,J1 as Kg,x0 as Lg,m as Mg,CO as Ng,C0 as Og,NO as Pg,Z4 as Qg,K5 as Rg,G5 as Sg,L5 as Tg,W5 as Ug,Y5 as Vg,X5 as Wg,H5 as Xg};
@@ -1,2 +1,2 @@
1
1
  var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
2
- export{I as Ti,r as Ui,t as Vi,o as Wi,O as Xi,P as Yi,R as Zi,C as _i,M as $i,p as aj,E as bj,T as cj,s as dj,n as ej,D as fj,m as gj,x as hj,S as ij,U as jj,V as kj,A as lj,w as mj,z as nj,F as oj};
2
+ export{I as Wi,r as Xi,t as Yi,o as Zi,O as _i,P as $i,R as aj,C as bj,M as cj,p as dj,E as ej,T as fj,s as gj,n as hj,D as ij,m as jj,x as kj,S as lj,U as mj,V as nj,A as oj,w as pj,z as qj,F as rj};
@@ -1,3 +1,3 @@
1
- import{Wj as K}from"./chunk-0k2x2ae6.js";import{appendFileSync as Y,existsSync as Z,mkdirSync as _,readdirSync as f,statSync as M,unlinkSync as p}from"node:fs";import x from"node:path";var E;((T)=>{T[T.DEBUG=0]="DEBUG";T[T.INFO=1]="INFO";T[T.WARN=2]="WARN";T[T.ERROR=3]="ERROR"})(E||={});var t=null,G=null,H=!1;function S(n){if(t!==n)t=n}async function b(){}function z(){if(H)return G;H=!0;try{let n=x.join(K(),"logs");if(!Z(n))_(n,{recursive:!0,mode:493});if(M(n).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return B(n,30),G=n,n}catch(n){return console.error("[Logger] 无法创建日志目录:",n),null}}function B(n,u){try{let c=f(n),w=Date.now(),T=u*24*60*60*1000;for(let $ of c){if(!$.startsWith("blade-")||!$.endsWith(".log")&&!$.endsWith(".jsonl"))continue;let m=x.join(n,$);try{let q=M(m);if(w-q.mtimeMs>T)p(m)}catch(q){}}}catch(c){}}function J(){let n=z();if(!n)return null;let u=t||"default";return x.join(n,`blade-${u}.jsonl`)}function U(n,u,c){let w=J();if(!w)return;try{let T={timestamp:new Date().toISOString(),level:E[u],category:n,message:c};Y(w,JSON.stringify(T)+`
1
+ import{Zj as K}from"./chunk-t88sfhjj.js";import{appendFileSync as Y,existsSync as Z,mkdirSync as _,readdirSync as f,statSync as M,unlinkSync as p}from"node:fs";import x from"node:path";var E;((T)=>{T[T.DEBUG=0]="DEBUG";T[T.INFO=1]="INFO";T[T.WARN=2]="WARN";T[T.ERROR=3]="ERROR"})(E||={});var t=null,G=null,H=!1;function S(n){if(t!==n)t=n}async function b(){}function z(){if(H)return G;H=!0;try{let n=x.join(K(),"logs");if(!Z(n))_(n,{recursive:!0,mode:493});if(M(n).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return B(n,30),G=n,n}catch(n){return console.error("[Logger] 无法创建日志目录:",n),null}}function B(n,u){try{let c=f(n),w=Date.now(),T=u*24*60*60*1000;for(let $ of c){if(!$.startsWith("blade-")||!$.endsWith(".log")&&!$.endsWith(".jsonl"))continue;let m=x.join(n,$);try{let q=M(m);if(w-q.mtimeMs>T)p(m)}catch(q){}}}catch(c){}}function J(){let n=z();if(!n)return null;let u=t||"default";return x.join(n,`blade-${u}.jsonl`)}function U(n,u,c){let w=J();if(!w)return;try{let T={timestamp:new Date().toISOString(),level:E[u],category:n,message:c};Y(w,JSON.stringify(T)+`
2
2
  `)}catch(T){}}class k{static globalDebugConfig=null;enabled;minLevel;category;constructor(n={}){if(n.enabled!==void 0)this.enabled=n.enabled;else if(k.globalDebugConfig!==null)this.enabled=Boolean(k.globalDebugConfig);else this.enabled=!1;this.minLevel=n.minLevel??0,this.category=n.category??"General"}static setGlobalDebug(n){k.globalDebugConfig=n}static clearGlobalDebug(){k.globalDebugConfig=null}setEnabled(n){this.enabled=n}parseDebugFilter(n){if(!n)return{enabled:!1};if(n===!0||n==="true"||n==="1")return{enabled:!0};let u=String(n).trim();if(!u)return{enabled:!0};if(u.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:u.split(",").map((T)=>T.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:u.split(",").map((w)=>w.trim()).filter(Boolean)}}}shouldLogCategory(n){if(!n)return!0;let u=this.category.toLowerCase();if(n.mode==="include")return n.categories.some((c)=>u.includes(c.toLowerCase()));return!n.categories.some((c)=>u.includes(c.toLowerCase()))}shouldLogToConsole(n){if(k.globalDebugConfig!==null){let{enabled:u,filter:c}=this.parseDebugFilter(k.globalDebugConfig);if(!u)return!1;if(n<this.minLevel)return!1;return this.shouldLogCategory(c)}return this.enabled&&n>=this.minLevel}log(n,...u){let c=u.map((w)=>typeof w==="object"?JSON.stringify(w):String(w)).join(" ");if(U(this.category,n,c),this.shouldLogToConsole(n)){let w=E[n],T=`[${this.category}] [${w}]`;console.error(T,...u)}}debug(...n){this.log(0,...n)}info(...n){this.log(1,...n)}warn(...n){this.log(2,...n)}error(...n){this.log(3,...n)}}function h(n,u){return new k({...u,category:n})}var s=new k({category:"General"});import F from"typebox/schema";import R from"typebox/value";class A extends Error{issues;constructor(n){super(n.map((u)=>{return`${u.path.length>0?u.path.join("."):"root"}: ${u.message}`}).join("; "));this.issues=n;this.name="SchemaValidationError"}}function O(n){if(!n)return[];return n.split("/").slice(1).map((u)=>u.replace(/~1/g,"/").replace(/~0/g,"~")).map((u)=>/^(0|[1-9]\d*)$/.test(u)?Number(u):u)}function P(n,u){let c=n;for(let w of u){if(c===null||typeof c!=="object")return;c=c[w]}return c}function Q(n,u){let[,c]=F.Errors(n,u);return c.map((w)=>{let T=O(w.instancePath);return{code:w.keyword,path:T,message:w.message,value:P(u,T)}})}function j(n,u){let c=R.Default(n,R.Clone(u)),w=Q(n,c);if(w.length>0)return{success:!1,error:new A(w)};let T=R.Clean(n,c),$=Q(n,T);if($.length>0)return{success:!1,error:new A($)};return{success:!0,data:T}}function W(n,u){let c=j(n,u);if(!c.success)throw c.error;return c.data}import X from"typebox";function i(n){return Object.defineProperties(n,{parse:{value:(u)=>W(n,u),enumerable:!1},safeParse:{value:(u)=>j(n,u),enumerable:!1}}),n}function a(n,u){return X.Optional({...n,default:u})}function L(n,u={}){return X.Unsafe({type:"string",enum:[...n],...u})}
3
- export{S as pj,b as qj,k as rj,h as sj,s as tj,j as uj,W as vj,X as wj,i as xj,a as yj,L as zj};
3
+ export{S as sj,b as tj,k as uj,h as vj,s as wj,j as xj,W as yj,X as zj,i as Aj,a as Bj,L as Cj};
@@ -1,4 +1,4 @@
1
- import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-w9z34f27.js";import{ca as O,ja as S}from"./chunk-bx75fd0d.js";import"./chunk-h74p51hg.js";import"./chunk-7ykqvsph.js";import"./chunk-ermypm1x.js";import{Rb as M,_b as E}from"./chunk-5sf2rc1z.js";import"./chunk-wzkh3e6a.js";import{_d as f}from"./chunk-zk9rf1d7.js";import"./chunk-z3hpstky.js";import{De as h}from"./chunk-p0gbxaqz.js";import"./chunk-xt0ktytp.js";import{if as I}from"./chunk-h05qhgrb.js";import{kf as y,lf as R,mf as g}from"./chunk-gpj7k3er.js";import{nf as C}from"./chunk-39de5k03.js";import"./chunk-9frd4fpk.js";import{Kf as w}from"./chunk-v5503t2t.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-a26vtcv5.js";import"./chunk-0ccm29qy.js";import"./chunk-74bswv4z.js";import"./chunk-4jqw75ce.js";import"./chunk-e76gej4y.js";import"./chunk-f2b9cyj5.js";import"./chunk-etf3e9kt.js";import"./chunk-karq4wfd.js";import"./chunk-69nwa6bn.js";import"./chunk-mavranwn.js";import"./chunk-c2mx5zg0.js";import"./chunk-ramana2t.js";import{Ii as A}from"./chunk-6xvrrypm.js";import"./chunk-9a7bppj7.js";import{Si as P}from"./chunk-g799czsy.js";import"./chunk-mzye1ah2.js";import"./chunk-vp6d1fqp.js";import"./chunk-xg9fyvw0.js";import"./chunk-wxtj6gqb.js";import"./chunk-g9vdmvk2.js";import"./chunk-wxypv01z.js";import"./chunk-nxnmqk4s.js";import"./chunk-0k2x2ae6.js";import"./chunk-6e3mh79j.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-05cv54r8.js";import{ca as O,ja as S}from"./chunk-1h3736q2.js";import"./chunk-16648v5c.js";import"./chunk-2jq9ed09.js";import"./chunk-5xgyx25z.js";import{Ub as M,bc as E}from"./chunk-recafw5r.js";import"./chunk-3eskgvpy.js";import{be as f}from"./chunk-cefmcwyv.js";import"./chunk-zx78c1an.js";import{Ge as h}from"./chunk-a5hkv8er.js";import"./chunk-awheqy52.js";import{lf as I}from"./chunk-dw0mewc2.js";import{nf as y,of as R,pf as g}from"./chunk-mh3ne2sf.js";import{qf as C}from"./chunk-v2fewxvw.js";import"./chunk-6qhbdcse.js";import{Nf as w}from"./chunk-x3c718v5.js";import"./chunk-v508x7cg.js";import"./chunk-5j68055h.js";import"./chunk-grx6fv9w.js";import"./chunk-bq6d0v5b.js";import"./chunk-hrcz179j.js";import"./chunk-d64b7wta.js";import"./chunk-5w8pmsqe.js";import"./chunk-f4cn6v8t.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-sdhdn0yx.js";import"./chunk-1bqatrxs.js";import"./chunk-40pd090k.js";import{Li as A}from"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import{Vi as P}from"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-mtfjwsn2.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -0,0 +1 @@
1
+ import{Ng as a,Og as b,Pg as c,Qg as d,Rg as e,Sg as f,Tg as g,Ug as h,Vg as i,Wg as j,Xg as k}from"./chunk-f4cn6v8t.js";import"./chunk-yvmexv2c.js";import"./chunk-rhwkvx96.js";import"./chunk-az08pq83.js";import"./chunk-sdhdn0yx.js";import"./chunk-1bqatrxs.js";import"./chunk-40pd090k.js";import"./chunk-npc7jt96.js";import"./chunk-mc2mr1kn.js";import"./chunk-dv2m2xe5.js";import"./chunk-fbrdcveb.js";import"./chunk-ft1bdqbs.js";import"./chunk-jb4hmk56.js";import"./chunk-65c3vjwm.js";import"./chunk-mtfjwsn2.js";import"./chunk-jy7k2dwm.js";import"./chunk-earhezc8.js";import"./chunk-t88sfhjj.js";import"./chunk-516adpx6.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};