blade-code 0.10.101 → 0.10.103

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 (113) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-03qymy9e.js +1 -0
  3. package/dist/{chunk-2191220r.js → chunk-07w0qapm.js} +1 -1
  4. package/dist/{chunk-qjv5kz7q.js → chunk-0aa40zbs.js} +15 -15
  5. package/dist/{chunk-9sx3vsyj.js → chunk-0hr050ck.js} +1 -1
  6. package/dist/chunk-0kdrgmyy.js +1 -0
  7. package/dist/{chunk-8z9d0zd0.js → chunk-14bs89sm.js} +2 -2
  8. package/dist/{chunk-b4d43ap3.js → chunk-181ef74x.js} +1 -1
  9. package/dist/{chunk-c6tq09mt.js → chunk-41cg66y0.js} +1 -1
  10. package/dist/{chunk-p0rvgzpx.js → chunk-41ympwz1.js} +1 -1
  11. package/dist/chunk-42bcht8b.js +169 -0
  12. package/dist/{chunk-39qzk9nm.js → chunk-47e6tdbb.js} +1 -1
  13. package/dist/{chunk-cjgpas7y.js → chunk-4qfke0gd.js} +5 -5
  14. package/dist/chunk-5sk7q6pw.js +1 -0
  15. package/dist/chunk-6v10cs0h.js +1 -0
  16. package/dist/{chunk-4fmtv329.js → chunk-6wsvgk20.js} +1 -1
  17. package/dist/chunk-7ab7jcvn.js +1 -0
  18. package/dist/{chunk-j00px1es.js → chunk-7fz3w4rk.js} +1 -1
  19. package/dist/chunk-8zjn51fr.js +1 -0
  20. package/dist/{chunk-ykkqywtq.js → chunk-946wkbmw.js} +1 -1
  21. package/dist/{chunk-k7vv9vne.js → chunk-9p20hhs0.js} +1 -1
  22. package/dist/{chunk-j22d84s7.js → chunk-a7ejfmtc.js} +1 -1
  23. package/dist/chunk-a8x3xygs.js +1 -0
  24. package/dist/{chunk-dcjh1cj6.js → chunk-aa5zmwd9.js} +3 -3
  25. package/dist/{chunk-0zhdjaen.js → chunk-abd57h72.js} +1 -1
  26. package/dist/{chunk-fqbc1ppx.js → chunk-afa35v3f.js} +1 -1
  27. package/dist/{chunk-2f5kkhan.js → chunk-b0j9v359.js} +407 -403
  28. package/dist/{chunk-qjeadpj2.js → chunk-bt18xsc6.js} +1 -1
  29. package/dist/chunk-bx82y5ce.js +1 -0
  30. package/dist/chunk-c475tfqf.js +2 -0
  31. package/dist/{chunk-9ajkzcqj.js → chunk-c479s9v2.js} +1 -1
  32. package/dist/{chunk-jvxskq6a.js → chunk-cpex23zk.js} +1 -1
  33. package/dist/{chunk-wbf4qcws.js → chunk-e1tt6b1w.js} +2 -2
  34. package/dist/{chunk-czcxx8tb.js → chunk-f3426b1c.js} +1 -1
  35. package/dist/{chunk-z5a8ay9s.js → chunk-f945dzj6.js} +2 -2
  36. package/dist/{chunk-w9xfks7f.js → chunk-fhfzdyba.js} +1 -1
  37. package/dist/{chunk-qcy79mva.js → chunk-fva7jnjy.js} +1 -1
  38. package/dist/chunk-fw2x9p4c.js +6 -0
  39. package/dist/{chunk-8yt4nmyb.js → chunk-gr80w0vh.js} +1 -1
  40. package/dist/{chunk-3c01jje5.js → chunk-gxgq70gm.js} +1 -1
  41. package/dist/{chunk-10taec1j.js → chunk-j2dyprdy.js} +1 -1
  42. package/dist/{chunk-f8z5v101.js → chunk-jaswqpe7.js} +1 -1
  43. package/dist/{chunk-kdatgrjy.js → chunk-k9fveqq6.js} +1 -1
  44. package/dist/chunk-kdjtxpxw.js +1 -0
  45. package/dist/chunk-kf7whgr7.js +2 -0
  46. package/dist/{chunk-tp5bep1y.js → chunk-khtxprbv.js} +1 -1
  47. package/dist/{chunk-ykf4cqpg.js → chunk-mgsvn9v4.js} +4 -4
  48. package/dist/{chunk-d8wzc602.js → chunk-n7mzxa8h.js} +2 -2
  49. package/dist/chunk-nz7kjzc0.js +1 -0
  50. package/dist/{chunk-70hwyc2w.js → chunk-q69fzq4y.js} +1 -1
  51. package/dist/{chunk-z0dmm227.js → chunk-q6eb20fz.js} +1 -1
  52. package/dist/{chunk-3an3vxzt.js → chunk-rahch228.js} +1 -1
  53. package/dist/{chunk-3awjdsef.js → chunk-rchz6j90.js} +1 -1
  54. package/dist/{chunk-2va6ex5v.js → chunk-rvk9r2cm.js} +1 -1
  55. package/dist/{chunk-425p4nwx.js → chunk-s10pmnrd.js} +2 -2
  56. package/dist/{chunk-twhf09qs.js → chunk-s66fwx1p.js} +1 -1
  57. package/dist/chunk-s6vzjear.js +10 -0
  58. package/dist/{chunk-f9asjkfz.js → chunk-sdbbyagy.js} +1 -1
  59. package/dist/{chunk-9hsbjy6a.js → chunk-szxajr6e.js} +1 -1
  60. package/dist/{chunk-q3vza5gt.js → chunk-tgdhsm5t.js} +2 -2
  61. package/dist/chunk-v4w5b2cq.js +1 -0
  62. package/dist/chunk-vk4xbek0.js +1 -0
  63. package/dist/{chunk-53xtssbf.js → chunk-w7hy5wh1.js} +1 -1
  64. package/dist/{chunk-cp7xsjj2.js → chunk-wyhyw9rq.js} +2 -2
  65. package/dist/{chunk-zydvg30x.js → chunk-wzmqkam9.js} +1 -1
  66. package/dist/{chunk-hpjnk87v.js → chunk-x3cxmwnz.js} +1 -1
  67. package/dist/chunk-xm8nyj5z.js +2 -0
  68. package/dist/{chunk-2cg8f38t.js → chunk-xtb84adp.js} +1 -1
  69. package/dist/chunk-yr56ttgw.js +1 -0
  70. package/dist/{chunk-nh4jy5cs.js → chunk-ywarj5j9.js} +1 -1
  71. package/dist/{chunk-rej5bbbs.js → chunk-z9gd9spf.js} +1 -1
  72. package/dist/web/assets/ChatView-_4ut_-Jh.js +58 -0
  73. package/dist/web/assets/{CodeBlockHighlighter-DZcVFtJE.js → CodeBlockHighlighter-DkDr6wE9.js} +1 -1
  74. package/dist/web/assets/{FilePreview-CzNS6kfM.js → FilePreview-DCI-oqhJ.js} +1 -1
  75. package/dist/web/assets/{KanbanBoard-cdh2g0r0.js → KanbanBoard-CB5C4tJC.js} +1 -1
  76. package/dist/web/assets/{MarkdownRenderer-BqBOUlXa.js → MarkdownRenderer-ychfmIQK.js} +3 -3
  77. package/dist/web/assets/{SettingsModal-meSWhCOP.js → SettingsModal-SSdk0Bjr.js} +1 -1
  78. package/dist/web/assets/{TaskSwitcher-CiQi64Yl.js → TaskSwitcher-EnaUhn3o.js} +1 -1
  79. package/dist/web/assets/{TerminalPanel-Bze9t5mz.js → TerminalPanel-BcWxLSV3.js} +1 -1
  80. package/dist/web/assets/{arrow-left-DpTnLOBT.js → arrow-left-Ob5r20g7.js} +1 -1
  81. package/dist/web/assets/{calendar-clock-DlAXXpl_.js → calendar-clock-eOALT8DB.js} +1 -1
  82. package/dist/web/assets/{chevrons-up-down-CmAktdaR.js → chevrons-up-down-BkZBwmbt.js} +1 -1
  83. package/dist/web/assets/{clock-3-_w8nIuEK.js → clock-3-DQp9SzYc.js} +1 -1
  84. package/dist/web/assets/{external-link-AlymrIfc.js → external-link-BuGUowPD.js} +1 -1
  85. package/dist/web/assets/{folder-CrxO-9Rc.js → folder-c92kw1oI.js} +1 -1
  86. package/dist/web/assets/index-CS8jtO_A.js +275 -0
  87. package/dist/web/assets/{pause-GQZaG_P3.js → pause-DP_CXoH7.js} +1 -1
  88. package/dist/web/assets/{play-BPhmPVpi.js → play-DcRwtohz.js} +1 -1
  89. package/dist/web/assets/{session-events-CO2pRY9U.js → session-events-CrAgnaj2.js} +19 -19
  90. package/dist/web/assets/{teamService-BqS4iOx0.js → teamService-JyVbGQhi.js} +1 -1
  91. package/dist/web/index.html +2 -2
  92. package/package.json +1 -1
  93. package/dist/chunk-2r0f3b4t.js +0 -1
  94. package/dist/chunk-as2ezx8p.js +0 -1
  95. package/dist/chunk-bswjne5v.js +0 -1
  96. package/dist/chunk-c663rajb.js +0 -1
  97. package/dist/chunk-fvfc95g3.js +0 -2
  98. package/dist/chunk-hz5rsfxv.js +0 -2
  99. package/dist/chunk-kfcs62nw.js +0 -1
  100. package/dist/chunk-kvdk0pfk.js +0 -1
  101. package/dist/chunk-maebpz1j.js +0 -2
  102. package/dist/chunk-mzab7qak.js +0 -1
  103. package/dist/chunk-n4cw6vt1.js +0 -1
  104. package/dist/chunk-n5jfmzp2.js +0 -1
  105. package/dist/chunk-p7t010gq.js +0 -1
  106. package/dist/chunk-qgjgjzbx.js +0 -10
  107. package/dist/chunk-sa7t9kht.js +0 -6
  108. package/dist/chunk-tazb5tze.js +0 -1
  109. package/dist/chunk-tc9rq0st.js +0 -160
  110. package/dist/chunk-vc7gh3wc.js +0 -1
  111. package/dist/chunk-zjpph3ys.js +0 -1
  112. package/dist/web/assets/ChatView-Cc4bXZ6x.js +0 -58
  113. package/dist/web/assets/index-JJH0FKfo.js +0 -275
@@ -1,3 +1,3 @@
1
- import{Si as $,Ti as F}from"./chunk-q3vza5gt.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{Ui as $,Vi as F}from"./chunk-tgdhsm5t.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as g};
@@ -1,5 +1,5 @@
1
- import{s as cz,t as pz}from"./chunk-fqbc1ppx.js";import{u as S}from"./chunk-tp5bep1y.js";import{A as Oz,v as gz,w as wz,x as Dz,y as _z,z as Nz}from"./chunk-kdatgrjy.js";import{G as E,P as Bz,Q as Gz,U as Uz,X as jz,Y as Vz,aa as Kz,qa as Az,ra as qz,sa as Pz,ta as Rz}from"./chunk-2f5kkhan.js";import"./chunk-0zhdjaen.js";import{Ha as uz}from"./chunk-2cg8f38t.js";import{Ja as Fz}from"./chunk-hz5rsfxv.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-qjv5kz7q.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{Cd as p,Dd as $z,Fd as h,Id as Wz,Nd as P,Qd as j,ad as zz,kd as y,ld as c,md as Hz,rd as Jz,ud as Qz,wd as Zz}from"./chunk-zydvg30x.js";import"./chunk-s0tq8gyx.js";import"./chunk-hpjnk87v.js";import{ve as mz}from"./chunk-8yt4nmyb.js";import"./chunk-rej5bbbs.js";import{Qe as kz,Re as Iz}from"./chunk-z0dmm227.js";import"./chunk-v508x7cg.js";import{af as m}from"./chunk-dg0d3303.js";import{ff as e}from"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import{qf as Cz}from"./chunk-2hb222re.js";import"./chunk-2191220r.js";import"./chunk-nh4jy5cs.js";import"./chunk-fvfc95g3.js";import{gg as fz}from"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-dcjh1cj6.js";import"./chunk-c6tq09mt.js";import{_g as yz,bh as Mz}from"./chunk-z5a8ay9s.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import{Fh as C,Gh as t,Ih as f,Jh as u}from"./chunk-maebpz1j.js";import{Nh as bz}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import{ni as M}from"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import{ui as hz,xi as Sz}from"./chunk-k7vv9vne.js";import"./chunk-8z9d0zd0.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import{Ti as s}from"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import{Readable as JH,Writable as QH}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as zH,RequestError as HH}from"@agentclientprotocol/sdk";import{createHash as lz}from"node:crypto";import{RequestError as Tz}from"@agentclientprotocol/sdk";import{nanoid as I}from"nanoid";var U=M("Agent"),i=4,iz=1000,a=4000,r=120000,o=0.2;function n(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function az(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:n(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:n("headers"in z?z.headers:void 0)};return null}function rz(z){let J={};for(let H of z){let W=az(H);if(W)J[H.name]=W}return J}function xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function oz(z){let J=$z(z.metadata);return J?[{type:"text",text:p(J)}]:xz(z.content)}function nz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}function sz(z){if(!e(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...y("capacity"),resource:z.resource}}function tz(z,J){let H=Math.max(0,J-1),W=Math.min(iz*2**H,a),Y=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*Y;return Math.min(a,Math.max(0,Math.round(W*Z)))}function ez(z){if(!(z instanceof Tz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class b{id;cwd;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;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Oz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:(Y)=>Buffer.byteLength(JSON.stringify(Y)),write:async(Y)=>{await H.sessionUpdate(Y)},onFailure:(Y)=>this.handleUpdateEgressFailure(Y)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([j.loadSession(this.id,this.cwd),j.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await j.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...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 Kz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await j.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),E.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Lz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?rz(this.options.mcpServers):void 0,H=E.getInstance().getTerminalService(this.id);if(this.runtime=await Uz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,F)=>{let L=await H.execute($,{cwd:F.cwd,env:F.env,timeout:F.timeoutMs,signal:F.signal,allowLocalFallback:!1,onOutput:(B)=>F.onOutput?.("stdout",B)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await S.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:F,messageId:L,content:B}=$.properties,G=$.properties.metadata;if($.type==="team.message.received"&&typeof F==="string"&&typeof L==="string"&&typeof B==="string"&&Gz(G,{messageId:L,teamName:F}))(async()=>{let V=await this.runtime?.enqueueSteering(B,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:G});if(!V?.accepted)return;if(await new Bz(F,s()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let X=await this.runtime.getGoal(),Y=this.runtime.getPendingSteeringCount()>0,Z=X?.status==="active"||X?.status==="verifying";if(Y||Z)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Zz(J))continue;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of oz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))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);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],this.contextMessages=await this.loadModelContextOr($.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),$}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!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(Z)=>{if(await this.setServiceTier(Z),!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(Z)=>{if(await this.setResponseVerbosity(Z),!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(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(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}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(V)=>{if(F)B(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,L)B(L);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,$,F)},complete:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,$,F)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,$)},getLogs:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,$)},setLoggingLevel:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,$)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:$})}},codeReview:{run:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await S.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:$,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),L=await F.completion,B=(await S.list(this.cwd,this.id)).find((G)=>G.start.reviewId===F.reviewId);if(!B)throw Error(`Review not found: ${F.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:F.reviewId,status:L.status,findings:L.findings.length,content:zz(B.start,L)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,F)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:B})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},W=await Pz(z,H),X=W.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await j.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let Y=W.content||W.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){if(J.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,H,W=new Promise((X)=>{H=X});this.pendingSideConversation=J,this.pendingSideConversationCompletion=W;try{return await this.handleSlashCommand(z,J.signal)}catch(X){if(J.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(H(),this.pendingSideConversationCompletion===W)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Rz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((X)=>!J.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),U.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(E.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,X=H.displayText,Y=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((w)=>w.outputSchema)?.outputSchema:void 0),Z;if(Y!==void 0)Z=Wz(Y).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let $=Fz(X);if($){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((w)=>w.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand($.question?`/btw ${$.question}`:"/btw")}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let w=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${w.queued})`),w.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let F=new AbortController,L=()=>{F.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let B=!1,G=!1,V=!1,R,T=new Promise((w)=>{R=w});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Az(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let w={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},N=await Yz(this.agent.chatStream(W,w,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{V=!0;let K=Q.toolCall,O=K.function.name;if(O===h)break;let q=this.mapToolKind(Q.toolKind),D=`Executing ${O}`;if(O==="Task"&&"function"in K)try{let x=JSON.parse(K.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")D=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K.id,status:"in_progress",title:D,content:[],kind:q});break}case"tool_progress":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;let O=Q.result,q=[],D=O.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;q.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))q.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=K.function.name,vz=Vz(Qz(jz(_,O),Jz));q.push({type:"content",content:{type:"text",text:vz}})}if(K.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let x=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:x,content:q});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
1
+ import{s as cz,t as pz}from"./chunk-afa35v3f.js";import{u as S}from"./chunk-khtxprbv.js";import{A as Oz,v as gz,w as wz,x as Dz,y as _z,z as Nz}from"./chunk-k9fveqq6.js";import{H as E,Q as Bz,R as Gz,V as Uz,Y as jz,Z as Vz,aa as Kz,qa as Az,ra as qz,sa as Pz,ta as Rz}from"./chunk-b0j9v359.js";import"./chunk-abd57h72.js";import{Ha as uz}from"./chunk-xtb84adp.js";import{Ja as Fz}from"./chunk-xm8nyj5z.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-0aa40zbs.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{Cd as p,Dd as $z,Fd as h,Id as Wz,Nd as P,Qd as j,ad as zz,kd as y,ld as c,md as Hz,rd as Jz,ud as Qz,wd as Zz}from"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{ve as mz}from"./chunk-gr80w0vh.js";import"./chunk-z9gd9spf.js";import{Qe as kz,Re as Iz}from"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import{af as m}from"./chunk-dg0d3303.js";import{ff as e}from"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import{qf as Cz}from"./chunk-2hb222re.js";import"./chunk-07w0qapm.js";import"./chunk-ywarj5j9.js";import"./chunk-kf7whgr7.js";import{ig as fz}from"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import{ah as yz,dh as Mz}from"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import{Hh as C,Ih as t,Kh as f,Lh as u}from"./chunk-c475tfqf.js";import{Ph as bz}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{pi as M}from"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import{wi as hz,zi as Sz}from"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import{Vi as s}from"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import{Readable as JH,Writable as QH}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as zH,RequestError as HH}from"@agentclientprotocol/sdk";import{createHash as lz}from"node:crypto";import{RequestError as Tz}from"@agentclientprotocol/sdk";import{nanoid as I}from"nanoid";var U=M("Agent"),i=4,iz=1000,a=4000,r=120000,o=0.2;function n(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function az(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:n(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:n("headers"in z?z.headers:void 0)};return null}function rz(z){let J={};for(let H of z){let W=az(H);if(W)J[H.name]=W}return J}function xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function oz(z){let J=$z(z.metadata);return J?[{type:"text",text:p(J)}]:xz(z.content)}function nz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}function sz(z){if(!e(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...y("capacity"),resource:z.resource}}function tz(z,J){let H=Math.max(0,J-1),W=Math.min(iz*2**H,a),Y=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*Y;return Math.min(a,Math.max(0,Math.round(W*Z)))}function ez(z){if(!(z instanceof Tz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class b{id;cwd;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;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Oz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:(Y)=>Buffer.byteLength(JSON.stringify(Y)),write:async(Y)=>{await H.sessionUpdate(Y)},onFailure:(Y)=>this.handleUpdateEgressFailure(Y)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([j.loadSession(this.id,this.cwd),j.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await j.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...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 Kz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await j.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),E.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Lz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?rz(this.options.mcpServers):void 0,H=E.getInstance().getTerminalService(this.id);if(this.runtime=await Uz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,F)=>{let L=await H.execute($,{cwd:F.cwd,env:F.env,timeout:F.timeoutMs,signal:F.signal,allowLocalFallback:!1,onOutput:(B)=>F.onOutput?.("stdout",B)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await S.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:F,messageId:L,content:B}=$.properties,G=$.properties.metadata;if($.type==="team.message.received"&&typeof F==="string"&&typeof L==="string"&&typeof B==="string"&&Gz(G,{messageId:L,teamName:F}))(async()=>{let V=await this.runtime?.enqueueSteering(B,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:G});if(!V?.accepted)return;if(await new Bz(F,s()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let X=await this.runtime.getGoal(),Y=this.runtime.getPendingSteeringCount()>0,Z=X?.status==="active"||X?.status==="verifying";if(Y||Z)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Zz(J))continue;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of oz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))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);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],this.contextMessages=await this.loadModelContextOr($.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),$}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!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(Z)=>{if(await this.setServiceTier(Z),!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(Z)=>{if(await this.setResponseVerbosity(Z),!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(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(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}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(V)=>{if(F)B(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,L)B(L);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,$,F)},complete:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,$,F)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,$)},getLogs:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,$)},setLoggingLevel:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,$)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:$})}},codeReview:{run:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await S.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:$,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),L=await F.completion,B=(await S.list(this.cwd,this.id)).find((G)=>G.start.reviewId===F.reviewId);if(!B)throw Error(`Review not found: ${F.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:F.reviewId,status:L.status,findings:L.findings.length,content:zz(B.start,L)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,F)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:B})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},W=await Pz(z,H),X=W.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await j.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let Y=W.content||W.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){if(J.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,H,W=new Promise((X)=>{H=X});this.pendingSideConversation=J,this.pendingSideConversationCompletion=W;try{return await this.handleSlashCommand(z,J.signal)}catch(X){if(J.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(H(),this.pendingSideConversationCompletion===W)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Rz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((X)=>!J.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),U.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(E.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,X=H.displayText,Y=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((w)=>w.outputSchema)?.outputSchema:void 0),Z;if(Y!==void 0)Z=Wz(Y).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let $=Fz(X);if($){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((w)=>w.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand($.question?`/btw ${$.question}`:"/btw")}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let w=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${w.queued})`),w.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let F=new AbortController,L=()=>{F.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let B=!1,G=!1,V=!1,R,T=new Promise((w)=>{R=w});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Az(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let w={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},N=await Yz(this.agent.chatStream(W,w,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{V=!0;let K=Q.toolCall,O=K.function.name;if(O===h)break;let q=this.mapToolKind(Q.toolKind),D=`Executing ${O}`;if(O==="Task"&&"function"in K)try{let x=JSON.parse(K.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")D=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K.id,status:"in_progress",title:D,content:[],kind:q});break}case"tool_progress":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;let O=Q.result,q=[],D=O.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;q.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))q.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=K.function.name,dz=Vz(Qz(jz(_,O),Jz));q.push({type:"content",content:{type:"text",text:dz}})}if(K.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let x=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:x,content:q});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
5
5
  `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Q.revision} (${Q.serverName}): ${Q.phase} ${Q.attempt}/${Q.maxAttempts}
@@ -7,9 +7,9 @@ import{s as cz,t as pz}from"./chunk-fqbc1ppx.js";import{u as S}from"./chunk-tp5b
7
7
  `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Q.revision} (${Q.serverName}): ${Q.action}${Q.detailsOmitted?" details-omitted":""}
8
8
  `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Q.revision} ${Q.taskId} (${Q.serverName}/${Q.toolName}): ${Q.status}${Q.hasResult?" result-available":""}
9
9
  `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Q.files.length}${Q.blockedWrite?" (write retry required)":""}
10
- `}});break;case"provider_admission":B=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Q.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":{let K=0;for(let O of Q.messages){if(!O.recovered||O.persisted)continue;if(J.projectedRecoveredInputIds?.has(O.id))continue;for(let q of xz(O.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(O.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
10
+ `}});break;case"provider_admission":B=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Q.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:Q.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:Q.goal.goalId,status:Q.goal.status,taskListId:Q.frontier.taskListId,total:Q.frontier.total,completed:Q.frontier.completed,inProgress:Q.frontier.inProgress,pending:Q.frontier.pending,blocked:Q.frontier.blocked,nextTask:Q.frontier.nextTask,digestSha256:Q.frontier.digestSha256,...Q.goal.frontierStall?{stall:{category:Q.goal.frontierStall.category,consecutiveCount:Q.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":{let K=0;for(let O of Q.messages){if(!O.recovered||O.persisted)continue;if(J.projectedRecoveredInputIds?.has(O.id))continue;for(let q of xz(O.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(O.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
11
11
  `}});break}case"goal_updated":if(Q.goal)this.sendUpdate(this.goalSessionUpdate(Q.goal));if(Q.goal&&Q.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Q.goal.status}: ${Q.goal.objective}]
12
- `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Q.goal.goalId,continuation:Q.continuation,...Q.prematureStopPattern?{prematureStopPattern:Q.prematureStopPattern}:{},...Q.prematureStopCount!==void 0?{prematureStopCount:Q.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Q.phase,...Q.reason?{reason:Q.reason}:{},...Q.strategy?{strategy:Q.strategy}:{},...Q.outcome?{outcome:Q.outcome}:{},...Q.preTokens!==void 0?{preTokens:Q.preTokens}:{},...Q.preTokenSource?{preTokenSource:Q.preTokenSource}:{},...Q.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Q.estimatedPendingTokens}:{},...Q.postTokens!==void 0?{postTokens:Q.postTokens}:{},...Q.sampleAttempts!==void 0?{sampleAttempts:Q.sampleAttempts}:{},...Q.inputReductions!==void 0?{inputReductions:Q.inputReductions}:{},...Q.messagesOmitted!==void 0?{messagesOmitted:Q.messagesOmitted}:{},...Q.filesOmitted!==void 0?{filesOmitted:Q.filesOmitted}:{},...Q.imagesOmitted!==void 0?{imagesOmitted:Q.imagesOmitted}:{},...Q.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Q.fallbackTargetTokens}:{},...Q.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Q.fallbackMessagesOmitted}:{},...Q.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Q.fallbackMessagesTruncated}:{},...Q.failureReason?{failureReason:Q.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())F.abort("acp-egress-failed")});if(!await this.flushUpdates())F.abort("acp-egress-failed");this.contextMessages=[...w.messages];let d=await j.loadSession(this.id,this.cwd);if(this.messages=d.length>0?d:[...w.messages],!N.success){let Q=N.error?.type??"unknown",K=N.error?.details??N.error?.message??"Agent execution failed",O=sz(K)??c(K);throw Tz.internalError({failureType:Q,modelId:this.runtime.getCurrentModelId(),taskFailure:O,outputStarted:G,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Q})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let l={...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(l).length>0?{_meta:l}:{}}}catch(w){if(F.signal.aborted||w instanceof Error&&w.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,w),w}finally{if(J.abortSignal?.removeEventListener("abort",L),B&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(R(),this.pendingPromptCompletion===T)this.pendingPromptCompletion=null;if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,W,X=new Promise(($)=>{W=$});this.pendingUserShell=H,this.pendingUserShellCompletion=X;let Y,Z="";try{let $=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(L)=>{if(Y=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Z+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let B=p(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Z?nz(L.record):B}}]})}}),F={role:"user",content:$.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify($.record))}};if(this.messages.push(F),this.contextMessages.push(F),$.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:$.record.status==="aborted"?"cancelled":"end_turn"}}catch($){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:$ instanceof Error?$.message:String($)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw $}finally{if(W(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H){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)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,H=()=>{if(J!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(H,z),this.pendingResumeTimer.unref?.();else queueMicrotask(H)}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:i,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let H="preflight",W=!1,X,Y=null;try{let Z=this.runtime.getPendingSteeringCount()>0,$=Z?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let F=$?.status==="active"||$?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Z&&!F))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Z&&!F){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}H=Z?"pending_input":"goal",W=!0;let B=r-(Date.now()-this.pendingResumeRecoveryStartedAt);if(B<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}let G=new AbortController;Y=setTimeout(()=>{G.abort("acp-pending-resume-budget-exhausted")},B),Y.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Z,goalContinuationOnly:F,projectedRecoveredInputIds:H==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:G.signal});if(z!==this.pendingResumeGeneration)return;if(G.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:H}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Z){if(z!==this.pendingResumeGeneration)return;let $=W?ez(Z):{taskFailure:c(Z),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=(H==="preflight"||H==="pending_input"&&this.runtime.getPendingSteeringCount()>0)&&$?.taskFailure.retryable===!0&&!$.toolExecutionStarted&&$.toolCallsCount===0&&!$.outputStarted,B=tz(this.id,J),G=Date.now()-this.pendingResumeRecoveryStartedAt,V=J<i,R=G+B<=r;if(L&&V&&R)this.pendingResumeRequested=!0,X=B,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:H,taskFailure:$.taskFailure,delayMs:B})),U.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${B}ms`);else{let T=L&&(!V||!R)?"exhausted":"failed";if(this.sendUpdate(this.pendingResumeSessionUpdate(T,{attempt:J,kind:H,taskFailure:$?.taskFailure})),U.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L}, phase=${T})`,Z),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest()}}finally{if(Y!==null)clearTimeout(Y);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(X)}}cancel(){U.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)U.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",W=this.mapModeIdToPermissionMode(H);await j.setSessionPermissionMode(this.id,this.cwd,W),this.mode=H,U.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(U.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await j.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((W)=>{U.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(W){if(!(W instanceof P)&&W.code!=="ENOENT")throw W;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:J.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.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 Nz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,H=this.runtime,W=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,Y=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Z,$=async(F)=>{try{await F()}catch(L){Z??=L}};if(await $(()=>this.cancel()),W)await $(()=>W);if(X)await $(()=>X);if(Y)await $(()=>Y);if(z&&W&&H)await $(()=>H.discardPendingInput());if(J)await $(()=>J.destroy());if(H)await $(()=>H.dispose());if(await $(()=>E.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),Z!==void 0)throw Z}resolvePrompt(z){let J=[],H=[],W=0,X=0,Y=0,Z=(L)=>{if(H.length>0)H.push({type:"text",text:`
12
+ `}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Q.goal.goalId,continuation:Q.continuation,...Q.prematureStopPattern?{prematureStopPattern:Q.prematureStopPattern}:{},...Q.prematureStopCount!==void 0?{prematureStopCount:Q.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Q.phase,...Q.reason?{reason:Q.reason}:{},...Q.strategy?{strategy:Q.strategy}:{},...Q.outcome?{outcome:Q.outcome}:{},...Q.preTokens!==void 0?{preTokens:Q.preTokens}:{},...Q.preTokenSource?{preTokenSource:Q.preTokenSource}:{},...Q.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Q.estimatedPendingTokens}:{},...Q.postTokens!==void 0?{postTokens:Q.postTokens}:{},...Q.sampleAttempts!==void 0?{sampleAttempts:Q.sampleAttempts}:{},...Q.inputReductions!==void 0?{inputReductions:Q.inputReductions}:{},...Q.messagesOmitted!==void 0?{messagesOmitted:Q.messagesOmitted}:{},...Q.filesOmitted!==void 0?{filesOmitted:Q.filesOmitted}:{},...Q.imagesOmitted!==void 0?{imagesOmitted:Q.imagesOmitted}:{},...Q.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Q.fallbackTargetTokens}:{},...Q.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Q.fallbackMessagesOmitted}:{},...Q.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Q.fallbackMessagesTruncated}:{},...Q.failureReason?{failureReason:Q.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())F.abort("acp-egress-failed")});if(!await this.flushUpdates())F.abort("acp-egress-failed");this.contextMessages=[...w.messages];let v=await j.loadSession(this.id,this.cwd);if(this.messages=v.length>0?v:[...w.messages],!N.success){let Q=N.error?.type??"unknown",K=N.error?.details??N.error?.message??"Agent execution failed",O=sz(K)??c(K);throw Tz.internalError({failureType:Q,modelId:this.runtime.getCurrentModelId(),taskFailure:O,outputStarted:G,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Q})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let l={...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(l).length>0?{_meta:l}:{}}}catch(w){if(F.signal.aborted||w instanceof Error&&w.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,w),w}finally{if(J.abortSignal?.removeEventListener("abort",L),B&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(R(),this.pendingPromptCompletion===T)this.pendingPromptCompletion=null;if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,W,X=new Promise(($)=>{W=$});this.pendingUserShell=H,this.pendingUserShellCompletion=X;let Y,Z="";try{let $=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(L)=>{if(Y=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Z+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let B=p(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Z?nz(L.record):B}}]})}}),F={role:"user",content:$.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify($.record))}};if(this.messages.push(F),this.contextMessages.push(F),$.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:$.record.status==="aborted"?"cancelled":"end_turn"}}catch($){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:$ instanceof Error?$.message:String($)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw $}finally{if(W(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H){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)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,H=()=>{if(J!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(H,z),this.pendingResumeTimer.unref?.();else queueMicrotask(H)}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:i,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let H="preflight",W=!1,X,Y=null;try{let Z=this.runtime.getPendingSteeringCount()>0,$=Z?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let F=$?.status==="active"||$?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Z&&!F))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Z&&!F){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}H=Z?"pending_input":"goal",W=!0;let B=r-(Date.now()-this.pendingResumeRecoveryStartedAt);if(B<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}let G=new AbortController;Y=setTimeout(()=>{G.abort("acp-pending-resume-budget-exhausted")},B),Y.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Z,goalContinuationOnly:F,projectedRecoveredInputIds:H==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:G.signal});if(z!==this.pendingResumeGeneration)return;if(G.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:H}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Z){if(z!==this.pendingResumeGeneration)return;let $=W?ez(Z):{taskFailure:c(Z),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=(H==="preflight"||H==="pending_input"&&this.runtime.getPendingSteeringCount()>0)&&$?.taskFailure.retryable===!0&&!$.toolExecutionStarted&&$.toolCallsCount===0&&!$.outputStarted,B=tz(this.id,J),G=Date.now()-this.pendingResumeRecoveryStartedAt,V=J<i,R=G+B<=r;if(L&&V&&R)this.pendingResumeRequested=!0,X=B,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:H,taskFailure:$.taskFailure,delayMs:B})),U.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${B}ms`);else{let T=L&&(!V||!R)?"exhausted":"failed";if(this.sendUpdate(this.pendingResumeSessionUpdate(T,{attempt:J,kind:H,taskFailure:$?.taskFailure})),U.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L}, phase=${T})`,Z),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest()}}finally{if(Y!==null)clearTimeout(Y);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(X)}}cancel(){U.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)U.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",W=this.mapModeIdToPermissionMode(H);await j.setSessionPermissionMode(this.id,this.cwd,W),this.mode=H,U.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(U.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await j.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((W)=>{U.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(W){if(!(W instanceof P)&&W.code!=="ENOENT")throw W;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:J.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.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 Nz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,H=this.runtime,W=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,Y=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Z,$=async(F)=>{try{await F()}catch(L){Z??=L}};if(await $(()=>this.cancel()),W)await $(()=>W);if(X)await $(()=>X);if(Y)await $(()=>Y);if(z&&W&&H)await $(()=>H.discardPendingInput());if(J)await $(()=>J.destroy());if(H)await $(()=>H.dispose());if(await $(()=>E.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),Z!==void 0)throw Z}resolvePrompt(z){let J=[],H=[],W=0,X=0,Y=0,Z=(L)=>{if(H.length>0)H.push({type:"text",text:`
13
13
  `}),Y+=1;if(H.push(L),L.type==="text")Y+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Z({type:"text",text:L.text});else if(L.type==="image"){let B=`data:${L.mimeType};base64,${L.data}`;W+=1,X+=B.length,J.push(`[Image: ${L.mimeType}]`),Z({type:"image_url",image_url:{url:B}})}else if(L.type==="resource"){let B=L.resource;if("text"in B){let G=`<file path="${B.uri}">
14
14
  ${B.text}
15
15
  </file>`;J.push(G),Z({type:"text",text:G})}}else if(L.type==="resource_link"){let B=`[Resource: ${L.uri}]`;J.push(B),Z({type:"text",text:B})}if(W>C)throw Error(`ACP prompt contains more than ${C} images`);if(X>t)throw Error("ACP prompt images exceed the 5 MiB limit");if(Y>f)throw Error(`ACP prompt text exceeds ${f} characters`);if(Buffer.byteLength(J.join(`
@@ -20,4 +20,4 @@ ${B.text}
20
20
  `)}}]}}),J);if(!F)return{approved:!1,reason:g};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Z.indexOf(F.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};W[Y.header]=Y.options[L].label}return{approved:!0,answers:W}}catch(X){return U.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let H=z.mcpElicitation;if(!H)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(H.mode==="url"){let X=await this.requestElicitationChoice("MCP external authorization",[H.message,`Server: ${H.serverName}`,`Domain: ${H.domain??"unknown"}`,`URL: ${H.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"}],J);if(X==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:X==="decline"?"User declined URL":"User cancelled",elicitation:{action:X==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let X of H.fields??[]){let Y=await this.collectAcpElicitationField(X,J);if(Y.cancelled)return{approved:!1,reason:Y.reason,elicitation:{action:"cancel"}};if(Y.value!==void 0)W[X.name]=Y.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return U.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let H=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((Y,Z)=>({id:`option:${Z}`,label:Y.label,value:Y.value})),W=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
22
22
  `),[...H.map((Y)=>({id:Y.id,label:Y.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(W==="skip")return{cancelled:!1};let X=H.find((Y)=>Y.id===W);if(!X)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:X.value}}if(z.defaultValue!==void 0){let H=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
23
- `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(H==="default")return{cancelled:!1,value:z.defaultValue};if(H==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,H,W){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.map((Y)=>({optionId:Y.id,name:Y.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),W);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,W)=>{let X=!1,Y=($)=>{if(X)return;X=!0,J.removeEventListener("abort",Z),$()},Z=()=>Y(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then(($)=>Y(()=>H($)),($)=>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 A=M("Agent");class v{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=kz();this.runtimeResidencyValue=new pz({maxResident:z?.maxResidentSessionRuntimes??yz,idleMs:z?.sessionRuntimeIdleMs??Mz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof cz)throw HH.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Iz(),{protocolVersion:zH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=m("acp"),H=await this.reserveSessionRuntime(J),W=z.cwd||bz(),X=z._meta?.["blade/taskIsolation"],Y=X==="local"||X==="worktree"?X:void 0,Z=z._meta?.["blade/taskPrompt"],$;try{let F=Y?await gz.createSessionTask({sessionId:J,prompt:typeof Z==="string"&&Z.trim()?Z:"ACP task session",sourceProjectPath:W,isolation:Y}):void 0,L=F?.metadata.projectPath??W;return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session cwd: ${L}`),$=new b(J,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...F?.taskWorktree?{taskWorktree:F.taskWorktree}:{},...F?.metadata.taskIsolation?{taskIsolation:F.metadata.taskIsolation}:{}}),await $.initialize(),this.assertNotDestroyed(),this.commitSession(J,$,H),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),$.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,F?.metadata,$.getModelConfiguration())}catch(F){throw H.cancel(),await $?.destroy().catch(()=>{return}),F}}async listSessions(z){if(z.cwd!=null&&!Ez.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskFailure?{"blade/taskFailure":H.taskFailure}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Ez.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=m("fork"),H=await this.reserveSessionRuntime(J),W;try{let X=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:J});return this.assertNotDestroyed(),W=new b(X.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:X.messages,permissionMode:X.metadata.permissionMode,mcpServers:z.mcpServers}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(X.sessionId,W,H),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(X.sessionId,X.metadata,W.getModelConfiguration())}catch(X){throw H.cancel(),await W?.destroy().catch(()=>{return}),X}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await j.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let J=await this.reserveSessionRuntime(z.sessionId),H;try{let[W,X]=await Promise.all([j.loadSession(z.sessionId,z.cwd),j.findSessionMetadata(z.sessionId,z.cwd)]);if(!X)throw Error(`Session not found: ${z.sessionId}`);return H=new b(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:X.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),await H.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}catch(W){throw J.cancel(),await H?.destroy().catch(()=>{return}),W}}commitSession(z,J,H){let W=H.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),W.release()}async closeResidentSession(z,J={}){let H=this.sessions.get(z);if(!H)return;let W=this.runtimeResidency.owns(z,H),X;try{await H.destroy(J)}catch(Z){X=Z}let Y=await this.runtimeResidency.forget(z,H);if(this.sessions.get(z)===H)this.sessions.delete(z);if(W&&!Y&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,J,H){return{sessionId:z,...this.buildSessionSetup(H,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let H=z?.models??[],W=(z?.currentModelId&&H.some((Z)=>Z.id===z.currentModelId)?z.currentModelId:void 0)??H[0]?.id,X=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],Y=[];if(H.length>0)Y.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:H.map((Z)=>({value:Z.id,name:Z.displayName??Z.model,description:`${z?.modelProviders[Z.provider]?.name??Z.provider} · ${Z.model}`}))});if(z?.reasoning)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="off"?"Disable model reasoning":`Use ${Z} reasoning effort`}))]});if(z?.serviceTier)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="fast"?"Use the provider priority tier":Z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:`Use ${Z} response verbosity`}))]});if(z?.communicationStyle)Y.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((Z)=>({value:Z.id,name:Z.name,description:`${Z.description} · ${Z.source}`}))});return{modes:{availableModes:X,currentModeId:J},configOptions:Y.length>0?Y:void 0}}async closeSession(z){this.assertNotDestroyed();let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let H=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await H.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Cz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await H.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Sz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await H.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&hz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await H.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&fz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await H.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(H.getModelConfiguration(),H.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(H){z??=H}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await uz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function eH(){let z=QH.toWeb(process.stdout),J=JH.toWeb(process.stdin),H=k.ndJsonStream(z,J),W,X=new k.AgentSideConnection((Z)=>{return W=new v(Z),W},H),Y=mz(async()=>{await W?.destroy()});try{await X.closed}finally{Y(),await W?.destroy()}}export{eH as runAcpIntegration};
23
+ `),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(H==="default")return{cancelled:!1,value:z.defaultValue};if(H==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,H,W){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.map((Y)=>({optionId:Y.id,name:Y.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),W);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,W)=>{let X=!1,Y=($)=>{if(X)return;X=!0,J.removeEventListener("abort",Z),$()},Z=()=>Y(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then(($)=>Y(()=>H($)),($)=>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 A=M("Agent");class d{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=kz();this.runtimeResidencyValue=new pz({maxResident:z?.maxResidentSessionRuntimes??yz,idleMs:z?.sessionRuntimeIdleMs??Mz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof cz)throw HH.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Iz(),{protocolVersion:zH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=m("acp"),H=await this.reserveSessionRuntime(J),W=z.cwd||bz(),X=z._meta?.["blade/taskIsolation"],Y=X==="local"||X==="worktree"?X:void 0,Z=z._meta?.["blade/taskPrompt"],$;try{let F=Y?await gz.createSessionTask({sessionId:J,prompt:typeof Z==="string"&&Z.trim()?Z:"ACP task session",sourceProjectPath:W,isolation:Y}):void 0,L=F?.metadata.projectPath??W;return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session cwd: ${L}`),$=new b(J,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...F?.taskWorktree?{taskWorktree:F.taskWorktree}:{},...F?.metadata.taskIsolation?{taskIsolation:F.metadata.taskIsolation}:{}}),await $.initialize(),this.assertNotDestroyed(),this.commitSession(J,$,H),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),$.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,F?.metadata,$.getModelConfiguration())}catch(F){throw H.cancel(),await $?.destroy().catch(()=>{return}),F}}async listSessions(z){if(z.cwd!=null&&!Ez.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskFailure?{"blade/taskFailure":H.taskFailure}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Ez.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=m("fork"),H=await this.reserveSessionRuntime(J),W;try{let X=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:J});return this.assertNotDestroyed(),W=new b(X.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:X.messages,permissionMode:X.metadata.permissionMode,mcpServers:z.mcpServers}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(X.sessionId,W,H),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(X.sessionId,X.metadata,W.getModelConfiguration())}catch(X){throw H.cancel(),await W?.destroy().catch(()=>{return}),X}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await j.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let J=await this.reserveSessionRuntime(z.sessionId),H;try{let[W,X]=await Promise.all([j.loadSession(z.sessionId,z.cwd),j.findSessionMetadata(z.sessionId,z.cwd)]);if(!X)throw Error(`Session not found: ${z.sessionId}`);return H=new b(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:X.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),await H.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}catch(W){throw J.cancel(),await H?.destroy().catch(()=>{return}),W}}commitSession(z,J,H){let W=H.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),W.release()}async closeResidentSession(z,J={}){let H=this.sessions.get(z);if(!H)return;let W=this.runtimeResidency.owns(z,H),X;try{await H.destroy(J)}catch(Z){X=Z}let Y=await this.runtimeResidency.forget(z,H);if(this.sessions.get(z)===H)this.sessions.delete(z);if(W&&!Y&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,J,H){return{sessionId:z,...this.buildSessionSetup(H,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let H=z?.models??[],W=(z?.currentModelId&&H.some((Z)=>Z.id===z.currentModelId)?z.currentModelId:void 0)??H[0]?.id,X=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],Y=[];if(H.length>0)Y.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:H.map((Z)=>({value:Z.id,name:Z.displayName??Z.model,description:`${z?.modelProviders[Z.provider]?.name??Z.provider} · ${Z.model}`}))});if(z?.reasoning)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="off"?"Disable model reasoning":`Use ${Z} reasoning effort`}))]});if(z?.serviceTier)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="fast"?"Use the provider priority tier":Z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:`Use ${Z} response verbosity`}))]});if(z?.communicationStyle)Y.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((Z)=>({value:Z.id,name:Z.name,description:`${Z.description} · ${Z.source}`}))});return{modes:{availableModes:X,currentModeId:J},configOptions:Y.length>0?Y:void 0}}async closeSession(z){this.assertNotDestroyed();let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let H=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await H.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Cz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await H.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Sz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await H.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&hz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await H.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&fz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await H.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(H.getModelConfiguration(),H.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(H){z??=H}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await uz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function eH(){let z=QH.toWeb(process.stdout),J=JH.toWeb(process.stdin),H=k.ndJsonStream(z,J),W,X=new k.AgentSideConnection((Z)=>{return W=new d(Z),W},H),Y=mz(async()=>{await W?.destroy()});try{await X.closed}finally{Y(),await W?.destroy()}}export{eH as runAcpIntegration};
@@ -0,0 +1 @@
1
+ import{$e as q,Le as a,Me as b,Ne as c,Oe as d,Pe as e,Qe as f,Re as g,Se as h,Te as i,Ue as j,Ve as k,We as l,Xe as m,Ye as n,Ze as o,_e as p}from"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -0,0 +1 @@
1
+ import{Bb as d,Cb as e,Db as f,Eb as g,Fb as h,Gb as i,Hb as j,Ib as k,Pb as l,Qb as m,Rb as n,Sb as o,Ub as p,Vb as q,Wb as r,ub as a,vb as b,xb as c}from"./chunk-0aa40zbs.js";import"./chunk-8hprmrd5.js";import"./chunk-wzmqkam9.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import"./chunk-dg0d3303.js";import"./chunk-rchz6j90.js";import"./chunk-2hb222re.js";import"./chunk-kf7whgr7.js";import"./chunk-fva7jnjy.js";import"./chunk-aa5zmwd9.js";import"./chunk-41cg66y0.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,3 +1,3 @@
1
- import{g as i}from"./chunk-39qzk9nm.js";import{Nh as s}from"./chunk-9sx3vsyj.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{g as i}from"./chunk-47e6tdbb.js";import{Ph as s}from"./chunk-0hr050ck.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -0,0 +1 @@
1
+ import{h as a,i as b,j as c,k as d,l as e}from"./chunk-jaswqpe7.js";import"./chunk-14bs89sm.js";import"./chunk-fhfzdyba.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,2 +1,2 @@
1
- import{ti as o}from"./chunk-425p4nwx.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
1
+ import{vi as o}from"./chunk-s10pmnrd.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
2
  export{e,i as f};
@@ -0,0 +1 @@
1
+ import{Ci as a,Di as b,Ei as c,Fi as d,Gi as e,Hi as f}from"./chunk-14bs89sm.js";import"./chunk-fhfzdyba.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{va as h,xa as f,ya as k}from"./chunk-0zhdjaen.js";import"./chunk-w9xfks7f.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
1
+ import{va as h,xa as f,ya as k}from"./chunk-abd57h72.js";import"./chunk-fhfzdyba.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
@@ -1,2 +1,2 @@
1
1
  var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
2
- export{f as ui,p as vi,u as wi,S as xi,c as yi,l as zi};
2
+ export{f as wi,p as xi,u as yi,S as zi,c as Ai,l as Bi};
@@ -1,2 +1,2 @@
1
- import{Bi as d,Di as h}from"./chunk-8z9d0zd0.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{Di as d,Fi as h}from"./chunk-14bs89sm.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as oe,w as pe};
@@ -0,0 +1 @@
1
+ import{qe as a,re as b,se as c}from"./chunk-gxgq70gm.js";import"./chunk-j2dyprdy.js";import"./chunk-q6eb20fz.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-41ympwz1.js";import"./chunk-f945dzj6.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-14bs89sm.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};