blade-code 0.10.159 → 0.10.161

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 (135) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-05d9ff3r.js +14 -0
  3. package/dist/{chunk-erhaedch.js → chunk-06hkf59s.js} +1 -1
  4. package/dist/{chunk-k3ne93k8.js → chunk-0mr8nexh.js} +2 -2
  5. package/dist/{chunk-tya95jej.js → chunk-0tzecdv3.js} +1 -1
  6. package/dist/{chunk-w1x8d19a.js → chunk-1017ck9e.js} +1 -1
  7. package/dist/{chunk-74yxkkne.js → chunk-1excdv7t.js} +2 -2
  8. package/dist/chunk-1yq72zb7.js +8 -0
  9. package/dist/{chunk-jsv3e4k6.js → chunk-2f8d0km4.js} +1 -1
  10. package/dist/{chunk-5q4z0sfr.js → chunk-2mk914vk.js} +2 -2
  11. package/dist/{chunk-ht8epjz2.js → chunk-30x3mcsb.js} +2 -2
  12. package/dist/{chunk-ewwrss2w.js → chunk-3kszepm6.js} +1 -1
  13. package/dist/chunk-3tm59hw3.js +1 -0
  14. package/dist/{chunk-28tzj187.js → chunk-3y2x6fb6.js} +1 -1
  15. package/dist/{chunk-9kj19a8t.js → chunk-4cdk4mds.js} +1 -1
  16. package/dist/{chunk-7xtxvrh8.js → chunk-4wx5sya5.js} +1 -1
  17. package/dist/{chunk-7wcxjbyg.js → chunk-50vwafn5.js} +1 -1
  18. package/dist/{chunk-9xbwtjac.js → chunk-53fc0yrq.js} +1 -1
  19. package/dist/chunk-5d7sxpvh.js +1 -0
  20. package/dist/chunk-5v0jcyea.js +2 -0
  21. package/dist/chunk-66wk3exc.js +1 -0
  22. package/dist/{chunk-g6v3ff0v.js → chunk-7veb9t8x.js} +2 -2
  23. package/dist/{chunk-9c0yfd4s.js → chunk-9q2ftpdv.js} +3 -3
  24. package/dist/{chunk-z7m4yh1n.js → chunk-9yjbzeep.js} +1 -1
  25. package/dist/{chunk-mt26v0vg.js → chunk-a6wkam4s.js} +1 -1
  26. package/dist/{chunk-spyyvqq4.js → chunk-bp45c17b.js} +1 -1
  27. package/dist/chunk-cmrtbnhs.js +1 -0
  28. package/dist/{chunk-42y6ks44.js → chunk-d420fs8m.js} +1 -1
  29. package/dist/{chunk-n34qsnks.js → chunk-ddvdc2p0.js} +1 -1
  30. package/dist/{chunk-sdapqhj0.js → chunk-eg3ms291.js} +1 -1
  31. package/dist/chunk-f8g9wwa5.js +1 -0
  32. package/dist/chunk-fdt6w600.js +1 -0
  33. package/dist/{chunk-67pa42n8.js → chunk-fws2cnbp.js} +2 -2
  34. package/dist/{chunk-zrgfvc4k.js → chunk-g01mth5d.js} +2 -2
  35. package/dist/{chunk-dd4gev98.js → chunk-hxyf4erv.js} +3 -3
  36. package/dist/{chunk-0b67y4j1.js → chunk-j8hbddjp.js} +2 -2
  37. package/dist/{chunk-v1mamd1x.js → chunk-jj4ggb04.js} +2 -2
  38. package/dist/{chunk-kp77mfmv.js → chunk-jw75y9sy.js} +1 -1
  39. package/dist/{chunk-b17d67gc.js → chunk-jz8355xa.js} +2 -2
  40. package/dist/{chunk-yb72nbfx.js → chunk-k0bcdhww.js} +1 -1
  41. package/dist/chunk-k48xg585.js +1 -0
  42. package/dist/{chunk-qq308eks.js → chunk-k67yh6be.js} +2 -2
  43. package/dist/{chunk-f2y0gxyq.js → chunk-kqvzmnja.js} +2 -2
  44. package/dist/{chunk-sd9bze9x.js → chunk-kv458q06.js} +1 -1
  45. package/dist/{chunk-9tk6wq70.js → chunk-kvp523gt.js} +1 -1
  46. package/dist/{chunk-kzrd648a.js → chunk-m0ztysws.js} +2 -2
  47. package/dist/{chunk-5w1bzrx1.js → chunk-mcnptqmc.js} +2 -2
  48. package/dist/{chunk-2z9hxxw9.js → chunk-mpk5qqnv.js} +1 -1
  49. package/dist/{chunk-t8w6s1te.js → chunk-n2qhccts.js} +2 -2
  50. package/dist/chunk-n6mv8p83.js +1 -0
  51. package/dist/{chunk-f97vk8pq.js → chunk-nb6h0709.js} +1 -1
  52. package/dist/{chunk-v67st2xb.js → chunk-nheny8xp.js} +2 -2
  53. package/dist/{chunk-w1h35604.js → chunk-pe3nhf71.js} +2 -2
  54. package/dist/chunk-pzqy0x7r.js +1 -0
  55. package/dist/{chunk-asjbhtpk.js → chunk-q1c70ep2.js} +1 -1
  56. package/dist/chunk-q47gn49w.js +1 -0
  57. package/dist/chunk-q8gmxcj2.js +1 -0
  58. package/dist/{chunk-gm2yfq3r.js → chunk-rvs364rz.js} +2 -2
  59. package/dist/{chunk-xxktawex.js → chunk-sqtt43cv.js} +2 -2
  60. package/dist/{chunk-7xhw74hk.js → chunk-t0gm0pn1.js} +1 -1
  61. package/dist/chunk-tntnsg2z.js +1 -0
  62. package/dist/{chunk-gfr6qac3.js → chunk-tv8wq9ze.js} +5 -5
  63. package/dist/chunk-vaj59nf7.js +1 -0
  64. package/dist/{chunk-hv8nt7wj.js → chunk-vbjgcn49.js} +1 -1
  65. package/dist/{chunk-0bqt0wgm.js → chunk-vt4a2j8d.js} +1 -1
  66. package/dist/{chunk-n9819k4p.js → chunk-vw9paban.js} +1 -1
  67. package/dist/{chunk-y72z40kh.js → chunk-vz147wy3.js} +1 -1
  68. package/dist/{chunk-fx9vm1n5.js → chunk-w33zjw8m.js} +2 -2
  69. package/dist/{chunk-53vh6vpt.js → chunk-wcps5gjm.js} +1 -1
  70. package/dist/chunk-wgykr4we.js +10 -0
  71. package/dist/{chunk-wxtb8n1j.js → chunk-wqzwq701.js} +2 -2
  72. package/dist/chunk-xm9cmg6m.js +171 -0
  73. package/dist/{chunk-jbpasjg9.js → chunk-xmymx75h.js} +1 -1
  74. package/dist/{chunk-vz13c7fr.js → chunk-y5wngtz0.js} +2 -2
  75. package/dist/{chunk-age2q38q.js → chunk-z9ebxd1x.js} +1 -1
  76. package/dist/{chunk-pv6cgfv1.js → chunk-zj1g4nbq.js} +1 -1
  77. package/dist/{chunk-wm896gnx.js → chunk-zzvs471p.js} +1 -1
  78. package/dist/web/assets/ChatView-er_sxPPR.js +70 -0
  79. package/dist/web/assets/{CodeBlockHighlighter-BpPOUcO7.js → CodeBlockHighlighter-y0h2qpHE.js} +1 -1
  80. package/dist/web/assets/{FilePreview-DXGkgNrQ.js → FilePreview-D3mhQ088.js} +14 -19
  81. package/dist/web/assets/{KanbanBoard-MYvqGgQH.js → KanbanBoard-CVg8k1mE.js} +2 -2
  82. package/dist/web/assets/{MarkdownRenderer-CXDrI3kX.js → MarkdownRenderer-CNBuegIp.js} +3 -3
  83. package/dist/web/assets/{ScrollArea-DocDa_rN.js → ScrollArea-nKClMHtv.js} +1 -1
  84. package/dist/web/assets/{SessionHistorySurface-D4Hxlpnr.js → SessionHistorySurface-DxS7TPaS.js} +1 -1
  85. package/dist/web/assets/{SettingsModal-ROSA92Eo.js → SettingsModal-CUn7pWF9.js} +1 -1
  86. package/dist/web/assets/{Sidebar-ByhqdRdj.js → Sidebar-CfxwNI2v.js} +1 -1
  87. package/dist/web/assets/TaskSwitcher-CSoJ4y5B.js +26 -0
  88. package/dist/web/assets/{TerminalPanel-czvVuMgl.js → TerminalPanel-BQuhnBca.js} +2 -2
  89. package/dist/web/assets/{archive-BwNnCDDQ.js → archive-BboAmbOv.js} +1 -1
  90. package/dist/web/assets/{arrow-left-Dc9lvaeD.js → arrow-left-DAUtSPbk.js} +1 -1
  91. package/dist/web/assets/{calendar-clock-o0GyQ0Np.js → calendar-clock-Vl0t-Nd3.js} +1 -1
  92. package/dist/web/assets/{chevron-right-CgHjrrmB.js → chevron-right-CF4tZJv_.js} +1 -1
  93. package/dist/web/assets/{clock-3-BB58ITKo.js → clock-3-UujBmwyg.js} +1 -1
  94. package/dist/web/assets/{copy-o_KiXkAh.js → copy-DqhAOOxU.js} +1 -1
  95. package/dist/web/assets/{download-BBtK3WHk.js → download-9K17cUAi.js} +1 -1
  96. package/dist/web/assets/{external-link-smSBd9oE.js → external-link-ZWYy4pMB.js} +1 -1
  97. package/dist/web/assets/{folder-BJP6kIlC.js → folder-CWkv_E0L.js} +1 -1
  98. package/dist/web/assets/index-C6zClU0B.js +211 -0
  99. package/dist/web/assets/index-CaCifsSK.css +1 -0
  100. package/dist/web/assets/message-square-plus-DOcUaurY.js +21 -0
  101. package/dist/web/assets/{pause-yqaK1hvk.js → pause-CvRQWY37.js} +1 -1
  102. package/dist/web/assets/{pencil-BZbDnyg2.js → pencil-CrKIc9az.js} +1 -1
  103. package/dist/web/assets/{play-WQ7288Ky.js → play-DN4KhXKM.js} +1 -1
  104. package/dist/web/assets/{plus-veQ2IAZx.js → plus-jGKGKGzn.js} +1 -1
  105. package/dist/web/assets/{session-events-Dwyp0AVI.js → session-events-aq2qdB3u.js} +25 -25
  106. package/dist/web/assets/{settings-B8xvrdSb.js → settings-DkVTw2qw.js} +1 -1
  107. package/dist/web/assets/{team-BrF46S7E.js → team-BBLJq3rO.js} +1 -1
  108. package/dist/web/assets/teamService-B6W5r_Z_.js +1 -0
  109. package/dist/web/assets/{terminal-BrqsCKf2.js → terminal-C30CbzhP.js} +1 -1
  110. package/dist/web/index.html +2 -2
  111. package/package.json +1 -1
  112. package/dist/chunk-1ms4x6yd.js +0 -1
  113. package/dist/chunk-514va7ce.js +0 -2
  114. package/dist/chunk-aka7w2bf.js +0 -1
  115. package/dist/chunk-cwk0r8wh.js +0 -1
  116. package/dist/chunk-dc2p24y5.js +0 -1
  117. package/dist/chunk-enf0egke.js +0 -1
  118. package/dist/chunk-es4aaeqw.js +0 -14
  119. package/dist/chunk-fszezcm7.js +0 -1
  120. package/dist/chunk-gjd5f281.js +0 -1
  121. package/dist/chunk-j7784bxm.js +0 -1
  122. package/dist/chunk-k1tfry97.js +0 -5
  123. package/dist/chunk-kvgxt3sw.js +0 -1
  124. package/dist/chunk-n42cnhzv.js +0 -1
  125. package/dist/chunk-smkxpfnk.js +0 -1
  126. package/dist/chunk-vbb7tn8t.js +0 -1
  127. package/dist/chunk-vbgb5j6x.js +0 -10
  128. package/dist/chunk-yd2qz6ts.js +0 -171
  129. package/dist/chunk-zqjm9yd8.js +0 -1
  130. package/dist/web/assets/ChatView-DYpMrwtA.js +0 -63
  131. package/dist/web/assets/TaskSwitcher-Dbo20Tim.js +0 -26
  132. package/dist/web/assets/chevrons-up-down-zQ_UZWV9.js +0 -16
  133. package/dist/web/assets/index-RGoMvYl5.css +0 -1
  134. package/dist/web/assets/index-pqMcowCZ.js +0 -203
  135. package/dist/web/assets/teamService-fDnXqw4L.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Ae as A0,Be as B1,Ce as H1,Ee as d2,Le as i2,Me as C0,Te as p_,Ve as N1,Xe as r2,Ye as o2,Ze as q1,_e as a2,ne as u2,oe as e,pe as h2,qe as Z1,re as l2,se as v,te as G1,ue as c2,ve as p2,we as V1,xe as L1,ye as n2,ze as U1}from"./chunk-vz13c7fr.js";import{ug as o_}from"./chunk-7wcxjbyg.js";import{qh as a_}from"./chunk-hv8nt7wj.js";import{Ui as v2,Vi as P2,Wi as x_,Xi as Q0,Yi as w_}from"./chunk-514va7ce.js";import{aj as f1}from"./chunk-jsv3e4k6.js";import{Cj as H0}from"./chunk-5q4z0sfr.js";import{Pj as i_,Sj as r_}from"./chunk-9kj19a8t.js";import{Wj as __}from"./chunk-5w1bzrx1.js";import{Ak as A,Bk as P,Ck as I,Dk as E1,Ek as F1,Fk as M_,Gk as z1,Hk as b1,Ik as q_,ek as h,ok as o,pk as p,qk as S2,rk as n,sk as d,tk as I2,uk as K0,vk as Y1,wk as m2,xk as K_,yk as M0,zk as c_}from"./chunk-7xtxvrh8.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
1
+ import{$e as a2,Ae as U1,Be as A0,Ce as B1,De as H1,Fe as d2,Me as i2,Ne as C0,Ue as p_,We as N1,Ye as r2,Ze as o2,_e as q1,oe as u2,pe as e,qe as h2,re as Z1,se as l2,te as v,ue as G1,ve as c2,we as p2,xe as V1,ye as L1,ze as n2}from"./chunk-y5wngtz0.js";import{vg as o_}from"./chunk-50vwafn5.js";import{rh as a_}from"./chunk-vbjgcn49.js";import{Vi as v2,Wi as P2,Xi as x_,Yi as Q0,Zi as w_}from"./chunk-5v0jcyea.js";import{bj as f1}from"./chunk-2f8d0km4.js";import{Dj as H0}from"./chunk-2mk914vk.js";import{Qj as i_,Tj as r_}from"./chunk-4cdk4mds.js";import{Xj as __}from"./chunk-mcnptqmc.js";import{Ak as c_,Bk as A,Ck as P,Dk as I,Ek as E1,Fk as F1,Gk as M_,Hk as z1,Ik as b1,Jk as q_,fk as h,pk as o,qk as p,rk as S2,sk as n,tk as d,uk as I2,vk as K0,wk as Y1,xk as m2,yk as K_,zk as M0}from"./chunk-4wx5sya5.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
2
2
  `,"utf8"),!0}catch(W){if(R_(W,"EEXIST"))return!1;if($)await W_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class $_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function k1(_,X,$=!1){let W,J;try{J=await D4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(R_(Q,"ELOCKED"))throw new $_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class u{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return u.acquire(_,X.root);return H_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return u.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return u.acquireAtPath(_,R4(X,_))}static async acquireRemote(_,X,$){let W=b1(X,_);try{await d(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await u.acquireAtPath(_,W);try{return await d(X,W),new u(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await W_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),k1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:z4(),pid:process.pid,processIdentity:m_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new u(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new $_;if(w4(J.pid)){let O=J.processIdentity?m_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new $_(J.pid)}if($(),await W_.unlink(X).catch((O)=>{if(!R_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new u(X,W);throw new $_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>k1(this.filePath,async(X)=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await W_.unlink(this.filePath).catch((W)=>{if(!R_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await H_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as O_}from"node:fs";import G_ from"node:path";import{Mutex as x4}from"async-mutex";var y1=128,g1=67108864,k4=24576,S1=65536,f0=1,h1=/^[a-f0-9]{64}$/,b4=/^[a-f0-9]{64}\.txt$/,l1=64,f4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),Y0=`
3
3
 
4
4
  ...[middle omitted; read the private prompt artifact for the complete request]...
@@ -91,4 +91,4 @@ ${[...X_,...Z_].join(`
91
91
  s.project_sort_key ASC,
92
92
  s.session_sort_key ASC
93
93
  LIMIT ?`).all(...J,_.limit+1),Q=await Promise.all(O.map(async(Z)=>{let V=JSON.parse(Z.metadata_json);if(V.remoteWorkspace)throw Error("Local projection contains remote session metadata");if(Z.archive_root_id&&Z.effective_archived_at)return this.reconcileInterruptedTask({...V,archivedAt:Z.effective_archived_at,archivedBySessionId:Z.archive_root_id});let{archivedAt:U,archivedBySessionId:G,...L}=V;return this.reconcileInterruptedTask(L)})),Y=B1(Q,_);return{sessions:Y.sessions.map((Z)=>this.toPublicMetadata(Z)),nextCursor:Y.nextCursor}}catch{return null}}static async listRemoteSessionPageFromProjection(_){p2(_);try{let X=await this.scanRemoteStoredSessionsFromProjection(_,0);if(!X)return null;let $=H1(this.toRemoteCatalogEntries(X).sort(A0),_);return{sessions:$.sessions.map((W)=>this.toPublicMetadata(W)),nextCursor:$.nextCursor}}catch(X){throw z(X)}}static async listSessions(_={}){let X=V1(_),$=n2(_),W=await this.scanStoredSessions(X.cwd??void 0,X.includeSubagents,0,X.archived,$),J=new Set;return W.sort(U1).flatMap((O)=>{let Q=`${O.projectPath}\x00${O.sessionId}`;if(J.has(Q))return[];return J.add(Q),[this.toPublicMetadata(O)]})}static async listRemoteSessions(_={}){let X=L1(_.descriptor!==void 0?{..._,descriptor:f2(_.descriptor)}:_),$=await this.scanRemoteStoredSessions(X,0),W=new Set;return this.toRemoteCatalogEntries($).sort(A0).flatMap((J)=>{let O=`${J.projectPath}\x00${J.sessionId}`;if(W.has(O))return[];return W.add(O),[this.toPublicMetadata(J)]})}static async collectStaleEmptySessions(_={}){let X=_.now??Date.now(),$=_.olderThanMs??gX;if(!Number.isFinite($)||$<0)throw Error("Stale empty session age must be a non-negative number");let W=_.projectPath?[{storagePath:K_(this.resolveCatalogWorkspace(_.projectPath)),projectPath:this.resolveCatalogWorkspace(_.projectPath)}]:await this.listAllProjectStorageDirectories(),J=0;for(let O of W){let Q;try{Q=await b_(O.storagePath)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}for(let Y of Q){if(!Y.endsWith(".jsonl"))continue;let Z=Y.slice(0,-6);if(!c_(Z))continue;let V=N.join(O.storagePath,Y);try{let G=await E0(V);if(X-G.mtimeMs<$)continue;if(await Promise.all([E0(N.join(O.storagePath,`${Z}.inbox.json`)).then(()=>!0).catch(()=>!1),E0(M_(O.projectPath,Z)).then(()=>!0).catch(()=>!1)]).then((B)=>B.some(Boolean)))continue}catch(G){if(G.code==="ENOENT")continue;throw G}let U;try{U=await u.acquire(Z,O.projectPath)}catch(G){if(G instanceof $_)continue;throw G}try{if(!await new v(V).deleteValidated((L)=>L.length===1&&L[0]?.type==="session_created"&&L[0].data.relationType!=="subagent"))continue;J++,await f_(N.join(O.storagePath,`${Z}.inbox.json`),{force:!0}),await f_(M_(O.projectPath,Z),{force:!0}),await this.removeFromProjection(Z,O.projectPath)}catch(G){l_.warn(`[SessionService] Skipping stale empty session cleanup: ${Z}`,G)}finally{await U.release()}}}return J}static async findSessionMetadata(_,X){if(A(_),X!==void 0){let W=this.resolveCatalogWorkspace(X),J=this.getSessionFilePath(W,_);try{let O=await this.readStoredSessionMetadata(J,_,W);if(O.projectPath!==W)return;if(!O.parentId||O.archivedAt)return this.toPublicMetadata(Q1([O],null)[0]??O);let Q=await this.scanStoredSessions(W,!0,0,null);return this.toPublicMetadata(Q.find((Y)=>Y.sessionId===_)??O)}catch(O){if(O.code==="ENOENT")return;throw O}}let $=(await this.scanStoredSessions(void 0,!0,0,null)).filter((W)=>W.sessionId===_);if($.length===0)return;if($.length>1)throw Error(`Ambiguous session ID: ${_}`);return this.toPublicMetadata($[0])}static async loadSession(_,X){try{if(X){let W=this.resolveCatalogWorkspace(X),J=this.getSessionFilePath(W,_);try{return await this.loadSessionFromFile(J,_,W)}catch(O){if(O.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw O}}let $=(await this.scanStoredSessions(void 0,!0,0,null)).find((W)=>W.sessionId===_);if(!$)throw Error(`未找到会话: ${_}`);return await this.loadSessionFromFile($.filePath,_)}catch($){throw l_.error(`[SessionService] 加载会话失败 (${_}):`,$),$}}static async loadSessionModelContext(_,X){try{if(X){let W=this.resolveCatalogWorkspace(X),J=this.getSessionFilePath(W,_);try{return await this.loadSessionModelContextFromFile(J,_,W)}catch(O){if(O.code==="ENOENT")throw Error(`未找到会话: ${_}`);throw O}}let $=(await this.scanStoredSessions(void 0,!0,0,null)).find((W)=>W.sessionId===_);if(!$)throw Error(`未找到会话: ${_}`);return await this.loadSessionModelContextFromFile($.filePath,_)}catch($){throw l_.error(`[SessionService] 加载模型上下文失败 (${_}):`,$),$}}static async loadRemoteSession(_,X,$){let W=await this.readValidatedRemoteSessionSnapshot(_,X,$);return this.convertJSONLToMessages(W)}static async loadRemoteSessionModelContext(_,X,$){let W=await this.readValidatedRemoteSessionSnapshot(_,X,$);return this.convertJSONLToModelContext(W)}static async readValidatedLocalSurfaceSnapshot(_,X,$){A(_);let W=this.resolveCatalogWorkspace(X),J=P(W,_),O=await this.readStableSessionSnapshot(J,_,3,$);this.validateSessionWorkspace(O,_,W);let Q=this.projectMetadataFromEntries(O,_,W,J);if(Q.remoteWorkspace)throw new R;return{entries:O,summary:N1(Q)}}static async readValidatedRemoteSurfaceSnapshot(_,X){let $=await this.readValidatedRemoteSessionSnapshot(_.sessionId,_.hostStateRoot,_.descriptor,X);return n(_.hostStateRoot,async(W)=>{X?.throwIfAborted();let J=I(W,_.sessionId),O=g(this.projectMetadataFromEntries($,_.sessionId,_.hostStateRoot,J),_.descriptor);return{entries:$,summary:N1(O,_.workspaceRef)}})}static async listValidatedRemoteSurfaceCandidates(_){let X=[];for(let $ of await Y1())_?.throwIfAborted(),await n(String($),async(W)=>{for(let J of await b_(String(W))){if(_?.throwIfAborted(),!J.endsWith(".jsonl"))continue;let O=J.slice(0,-6);if(!c_(O))continue;let Q=I(W,O);await d(W,Q);let Y=await this.readStableSessionSnapshot(Q,O,3,_),Z=g(this.projectMetadataFromEntries(Y,O,String(W),Q));await this.reconcileInterruptedTask(Z,"acp-remote",W);let V=await u2(W,Z.remoteWorkspace);_?.throwIfAborted(),X.push({descriptor:Z.remoteWorkspace,hostStateRoot:String(W),sessionId:O,workspaceRef:V})}});return X}static async listValidatedLocalSurfaceCandidates(_){let X=new Map;for(let $ of await this.listAllProjectStorageDirectories()){_?.throwIfAborted();let W;try{W=await b_($.storagePath)}catch(J){if(J.code==="ENOENT")continue;throw J}for(let J of W){if(_?.throwIfAborted(),!J.endsWith(".jsonl"))continue;let O=J.slice(0,-6);if(!c_(O))continue;let Q=N.join($.storagePath,J);try{let Y=await this.readStableSessionSnapshot(Q,O,3,_),Z=this.getSessionCreatedEntry(Y,O);if(Z.data.sessionId!==O||!N.isAbsolute(Z.cwd)||Object.hasOwn(Z.data,"remoteWorkspace"))continue;let V;try{V=M0(Z.cwd)}catch{continue}if(P(V,O)!==Q)continue;await this.reconcileInterruptedTask(this.projectMetadataFromEntries(Y,O,V,Q)),X.set(`${V}\x00${O}`,{projectPath:V,sessionId:O})}catch(Y){if(_?.aborted)throw Y;if(Y.code==="ENOENT")continue;if(Y instanceof R)throw Y}}}return[...X.values()]}static async exportSessionMarkdown(_,X,$={}){A(_);let W=this.resolveCatalogWorkspace(X),J=P(W,_),O;try{O=await this.readStableSessionSnapshot(J,_)}catch(Z){throw this.sanitizeStoredSessionError(Z,_)}let Q=this.projectMetadataFromEntries(O,_,W,J);if(Q.projectPath!==W)throw Error(`Session export workspace mismatch: ${_}`);let Y=Q.archivedAt;if(!Y&&Q.parentId)Y=(await this.findArchivedAncestor(Q.parentId,W))?.archivedAt;return N2(O,{...Q,archivedAt:Y},$)}static async listRewindCheckpoints(_,X){A(_);let $=this.resolveCatalogWorkspace(X),W=P($,_),J=await this.readStableSessionSnapshot(W,_);this.validateSessionWorkspace(J,_,$);let O=new N0({sessionId:_,workspaceRoot:$});await O.initialize();let Q=h2(J),Y=[];for(let Z of Q){let V=Z1(J,Z.messageId),U=await O.previewRewind(V.snapshotMessageIds);Y.push({...Z,fileCount:U.files.length})}return Y}static async rewindSession(_,X,$){A(_);let W=this.resolveCatalogWorkspace(X);await this.assertSessionWritable(_,W);let J=P(W,_),O=new v(J),Q;try{await O.appendValidatedAsync(async(Y)=>{this.validateSessionWorkspace(Y,_,W);let Z=Z1(Y,$.targetMessageId),V=new N0({sessionId:_,workspaceRoot:W});await V.initialize();let U=await V.previewRewind(Z.snapshotMessageIds),G=$.mode==="conversation"?await V.commitSnapshots(Z.snapshotMessageIds):await V.rewindSnapshots(Z.snapshotMessageIds),L=new Date().toISOString(),B={id:m(),sessionId:_,timestamp:L,type:"session_rewound",cwd:W,gitBranch:q_(W),version:__(),data:{rewindId:m(),targetMessageId:$.targetMessageId,mode:$.mode,restoredFiles:$.mode==="conversation"?[]:G.files,createdAt:L}},H=e([...Y,B]);return Q={checkpoint:{...Z.checkpoint,fileCount:U.files.length},mode:$.mode,removedTurns:Z.removedTurns,restoredFiles:B.data.restoredFiles,messages:this.convertJSONLToMessages(H)},B})}catch(Y){throw this.sanitizeStoredSessionError(Y,_)}if(!Q)throw Error(`Session rewind did not produce a result: ${_}`);for(let Y of Q.restoredFiles)N_.getInstance().clearFileRecord(Y);return Q}static async forkSession(_,X){A(_);let $=X.newSessionId??`fork-${Date.now()}-${m(8)}`;A($);let W=X.remote;if(W)return this.forkRemoteSession(_,$,X.sourceProjectPath,X.targetProjectPath,W.expectedDescriptor);let J=this.resolveForkWorkspace(X.sourceProjectPath),O=this.resolveForkWorkspace(X.targetProjectPath);if(J!==O)throw Error("Session forks must stay in the source workspace");let Q=P(J,_),Y=await this.readStableSessionSnapshot(Q,_),Z=this.getSessionCreatedEntry(Y,_);if(Z.data.sessionId!==_)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!N.isAbsolute(Z.cwd)||N.resolve(Z.cwd)!==J)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let V=this.projectMetadataFromEntries(Y,_,J,Q);if(V.archivedAt)throw new t(_,_);if(V.parentId){let K=await this.findArchivedAncestor(V.parentId,J);if(K)throw new t(_,K.sessionId)}let U=e(Y),G=new Date().toISOString(),L=Z.data.rootId||_,B=q_(O),H=__(),{status:k,taskStatus:b,taskStatusReason:w,taskFailure:X_,taskStartedAt:Z_,taskCompletedAt:l,taskOwnerPid:c,taskPromptSummary:D,taskPriority:x,taskKind:f,taskDueAt:T,taskDispatch:L_,taskModelId:j,taskRetriedFrom:S,taskDelivery:U_,taskIsolation:y_,taskSourceProjectPath:t_,taskWorktree:R0,taskDiffStat:w0,taskQueuePosition:s_,taskQueueDepth:e_,taskConcurrencyLimit:_0,pendingInteraction:g_,...y}=Z.data,X0={id:m(),sessionId:$,timestamp:G,type:"session_created",cwd:O,gitBranch:B,version:H,data:{...y,sessionId:$,rootId:L,parentId:_,relationType:"fork",taskStatus:"completed",taskCompletedAt:G,taskIsolation:"local",taskSourceProjectPath:O,createdAt:G,updatedAt:G}},S_=U.filter((K)=>K.type!=="session_created"&&K.type!=="token_budget_handoff_recorded"&&K.type!=="inbox_acknowledged"&&K.type!=="interaction_requested"&&K.type!=="interaction_responded"&&K.type!=="interaction_recovered"&&K.type!=="review_started"&&K.type!=="review_completed").map((K)=>{let r={...K,id:m(),sessionId:$,cwd:O,gitBranch:B,version:H};if(K.type==="session_updated"){let{status:E,taskStatus:D_,taskStatusReason:_4,taskFailure:X4,taskStartedAt:$4,taskCompletedAt:W4,taskOwnerPid:O4,taskPromptSummary:J4,taskPriority:Q4,taskKind:Y4,taskDueAt:Z4,taskDispatch:G4,taskModelId:V4,taskRetriedFrom:L4,taskDelivery:U4,taskIsolation:B4,taskSourceProjectPath:H4,taskWorktree:N4,taskDiffStat:A1,taskQueuePosition:mX,taskQueueDepth:vX,taskConcurrencyLimit:PX,pendingInteraction:uX,...q4}=K.data;return{...r,type:"session_updated",data:{...q4,sessionId:$,rootId:L,parentId:_,relationType:"fork"}}}if(K.type==="message_created"){let{inboxMessageId:E,...D_}=K.data;return{...r,type:"message_created",data:D_}}return r}),T_={id:m(),sessionId:$,timestamp:G,type:"session_updated",cwd:O,gitBranch:B,version:H,data:{sessionId:$,rootId:L,parentId:_,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:G,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:O,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:G}},C_=[X0,...S_,T_],B_=P(O,$),I_=!1;try{await new v(B_).createExclusive(C_),I_=!0;let K=g0(U.flatMap((r)=>r.type==="message_created"?[r.data.metadata]:[]));if(K.length>0){let r=new J_(J,_,{storageRoot:h()}),E=new J_(O,$,{storageRoot:h()});await r.copyReferencedTo(K,E)}}catch(K){if(I_)await new v(B_).delete().catch(()=>{return}),await new J_(O,$,{storageRoot:h()}).removeAll().catch(()=>{return});if(K.code==="EEXIST")throw Error(`Fork session already exists: ${$}`,{cause:K});throw K}let $0=this.projectMetadataFromEntries(C_,$,O,B_);return{sessionId:$,parentSessionId:_,projectPath:O,messages:this.convertJSONLToMessages(C_),metadata:this.toPublicMetadata($0)}}static async forkRemoteSession(_,X,$,W,J){let O;try{O=o(J)}catch(Y){throw z(Y)}let Q=p(O.collisionIdentity);if($!==Q||W!==Q)throw new R;return n(Q,async(Y)=>{let Z=I(Y,_);try{await d(Y,Z)}catch(S){throw z(S)}let V;try{V=await this.readStableSessionSnapshot(Z,_)}catch(S){throw b2(S)}let U=K0(V,_,Q),G=g(this.projectMetadataFromEntries(V,_,Q,Z),O);if(G.archivedAt)throw new t(_,_);if(G.parentId){let S=await this.findRemoteArchivedAncestor(G.parentId,Y,G.remoteWorkspace);if(S)throw new t(_,S.sessionId)}let L=e(V),B=new Date().toISOString(),H=__(),k=G.rootId||_,b=this.buildForkChildEntries({sourceEntries:L,sourceCreated:U,sourceSessionId:_,targetSessionId:X,targetProjectPath:Q,rootId:k,version:H,now:B,remoteDescriptor:G.remoteWorkspace}),w=I(Y,X),X_=!1;try{await new v(w).createExclusive(b),X_=!0,await d(Y,w);let S=g0(L.flatMap((U_)=>U_.type==="message_created"?[U_.data.metadata]:[]));if(S.length>0){let U_=new J_(Q,_,{storageRoot:Q}),y_=new J_(Q,X,{storageRoot:Q});await U_.copyReferencedTo(S,y_)}}catch(S){if(X_)await new v(w).delete().catch(()=>{return}),await new J_(Q,X,{storageRoot:Q}).removeAll().catch(()=>{return});if(S.code==="EEXIST")throw Error(`Fork session already exists: ${X}`,{cause:S});throw z(S)}let Z_=g(this.projectMetadataFromEntries(b,X,Q,w),G.remoteWorkspace),{gitBranch:l,taskIsolation:c,taskSourceProjectPath:D,taskWorktreePath:x,taskWorktreeBranch:f,taskBaseCommit:T,taskDiffStat:L_,...j}=this.toPublicMetadata(Z_);return{sessionId:X,parentSessionId:_,projectPath:Q,messages:this.convertJSONLToMessages(b),metadata:j}})}static async findRemoteArchivedAncestor(_,X,$){let W=new Set,J=_;while(J){if(W.has(J))throw new R;W.add(J),A(J);let O=I(X,J);try{await d(X,O)}catch(Z){if(Z.code==="ENOENT")return;throw z(Z)}let Q;try{Q=await this.readStableSessionSnapshot(O,J)}catch(Z){throw b2(Z)}K0(Q,J,String(X));let Y=g(this.projectMetadataFromEntries(Q,J,String(X),O));if(!j_(Y.remoteWorkspace,$))return;if(Y.archivedAt)return{sessionId:Y.sessionId,archivedAt:Y.archivedAt};J=Y.parentId}return}static buildForkChildEntries(_){let{sourceEntries:X,sourceCreated:$,sourceSessionId:W,targetSessionId:J,targetProjectPath:O,rootId:Q,version:Y,now:Z,remoteDescriptor:V}=_,{status:U,taskStatus:G,taskStatusReason:L,taskFailure:B,taskStartedAt:H,taskCompletedAt:k,taskOwnerPid:b,taskPromptSummary:w,taskPriority:X_,taskKind:Z_,taskDueAt:l,taskDispatch:c,taskModelId:D,taskRetriedFrom:x,taskDelivery:f,taskIsolation:T,taskSourceProjectPath:L_,taskWorktree:j,taskDiffStat:S,taskQueuePosition:U_,taskQueueDepth:y_,taskConcurrencyLimit:t_,pendingInteraction:R0,remoteWorkspace:w0,...s_}=$.data,e_={id:m(),sessionId:J,projectPath:O,timestamp:Z,type:"session_created",cwd:O,version:Y,data:{...s_,sessionId:J,rootId:Q,parentId:W,relationType:"fork",taskStatus:"completed",taskCompletedAt:Z,remoteWorkspace:V,createdAt:Z,updatedAt:Z}},_0=X.filter((y)=>y.type!=="session_created"&&y.type!=="token_budget_handoff_recorded"&&y.type!=="inbox_acknowledged"&&y.type!=="interaction_requested"&&y.type!=="interaction_responded"&&y.type!=="interaction_recovered"&&y.type!=="review_started"&&y.type!=="review_completed").map((y)=>{let{gitBranch:X0,...S_}=y,T_={...S_,id:m(),sessionId:J,projectPath:O,cwd:O,version:Y};if(y.type==="session_updated"){let{status:C_,taskStatus:B_,taskStatusReason:I_,taskFailure:$0,taskStartedAt:K,taskCompletedAt:r,taskOwnerPid:E,taskPromptSummary:D_,taskPriority:_4,taskKind:X4,taskDueAt:$4,taskDispatch:W4,taskModelId:O4,taskRetriedFrom:J4,taskDelivery:Q4,taskIsolation:Y4,taskSourceProjectPath:Z4,taskWorktree:G4,taskDiffStat:V4,taskQueuePosition:L4,taskQueueDepth:U4,taskConcurrencyLimit:B4,pendingInteraction:H4,remoteWorkspace:N4,...A1}=y.data;return{...T_,type:"session_updated",data:{...A1,sessionId:J,rootId:Q,parentId:W,relationType:"fork"}}}if(y.type==="message_created"){let{inboxMessageId:C_,...B_}=y.data;return{...T_,type:"message_created",data:B_}}return T_}),g_={id:m(),sessionId:J,projectPath:O,timestamp:Z,type:"session_updated",cwd:O,version:Y,data:{sessionId:J,rootId:Q,parentId:W,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:Z,taskOwnerPid:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:Z}};return[e_,..._0,g_]}static async deleteSession(_,X){if(A(_),X){if(!N.isAbsolute(X))throw Error("Session catalog cwd must be absolute");let W=N.resolve(X),J=this.getSessionFilePath(W,_),O=new v(J),Q;try{Q=await O.deleteValidated((Y)=>{return this.projectMetadataFromEntries(Y,_,W,J).projectPath===W})}catch(Y){if(!this.isCorruptSessionJSONLError(Y))throw Y;Q=await O.delete()}if(!Q)return 0;return await f_(N.join(N.dirname(J),`${_}.inbox.json`),{force:!0}),await f_(M_(W,_),{force:!0}),await new J_(W,_,{storageRoot:h()}).removeAll(),await P0(W,_,h()),await this.removeFromProjection(_,W),1}let $=(await this.scanStoredSessions(void 0,!0)).filter((W)=>W.sessionId===_);if($.length===0)return 0;return await Promise.all($.map(async(W)=>{await new v(W.filePath).delete(),await f_(N.join(N.dirname(W.filePath),`${W.sessionId}.inbox.json`),{force:!0}),await f_(M_(W.projectPath,W.sessionId),{force:!0}),await new J_(W.projectPath,W.sessionId,{storageRoot:h()}).removeAll(),await P0(W.projectPath,W.sessionId,h()),await this.removeFromProjection(W.sessionId,W.projectPath)})),$.length}static async removeFromProjection(_,X){try{let $=await p_();if($)a2($,_,X)}catch{}}static validateTaskMetadataUpdate(_,X){if(_.taskPromptSummary!==void 0&&_.taskPromptSummary!==null&&(!_.taskPromptSummary.trim()||_.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if(_.taskPriority!==void 0&&_.taskPriority!==null&&!z0.has(_.taskPriority))throw Error("Invalid session task priority");if(_.taskKind!==void 0&&_.taskKind!==null&&!D0.has(_.taskKind))throw Error("Invalid session task kind");if(_.taskDueAt!==void 0&&_.taskDueAt!==null&&!Number.isFinite(Date.parse(_.taskDueAt)))throw Error("Invalid session task due date");if(_.taskFailure!==void 0&&_.taskFailure!==null&&!o0(_.taskFailure))throw Error("Invalid session task failure");if(_.taskDispatch!==void 0&&_.taskDispatch!==null&&!x2(_.taskDispatch))throw Error("Invalid durable task dispatch");if(_.taskModelId!==void 0&&_.taskModelId!==null&&(!_.taskModelId.trim()||_.taskModelId.length>500))throw Error("Invalid session task model ID");if(_.selectedModelId!==void 0&&_.selectedModelId!==null&&(!_.selectedModelId.trim()||_.selectedModelId.length>500))throw Error("Invalid selected session model ID");if(_.permissionMode!==void 0&&_.permissionMode!==null&&!F0(_.permissionMode))throw Error("Invalid session permission mode");if(_.reasoningEffort!==void 0&&_.reasoningEffort!==null&&!o_(_.reasoningEffort))throw Error("Invalid session reasoning effort");if(_.serviceTier!==void 0&&_.serviceTier!==null&&!r_(_.serviceTier))throw Error("Invalid session service tier");if(_.responseVerbosity!==void 0&&_.responseVerbosity!==null&&!i_(_.responseVerbosity))throw Error("Invalid session response verbosity");if(_.communicationStyle!==void 0&&_.communicationStyle!==null&&!a_(_.communicationStyle))throw Error("Invalid session communication style");if(_.communicationStyleDigest!==void 0&&_.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test(_.communicationStyleDigest))throw Error("Invalid session communication style digest");if(_.projectInstructionsDigest!==void 0&&_.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test(_.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if(_.taskRetriedFrom!==void 0&&_.taskRetriedFrom!==null&&!k2(_.taskRetriedFrom))throw Error("Invalid session task retry source");if(_.taskDelivery!==void 0&&_.taskDelivery!==null&&!R2(_.taskDelivery))throw Error("Invalid session task delivery");if(_.taskIsolation!==void 0&&_.taskIsolation!==null&&!T1.has(_.taskIsolation))throw Error(`Invalid session task isolation: ${String(_.taskIsolation)}`);if(_.taskSourceProjectPath!==void 0&&_.taskSourceProjectPath!==null&&!N.isAbsolute(_.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if(_.taskWorktree!==void 0&&_.taskWorktree!==null){let $=D2(_.taskWorktree);if(!$||$.sessionId!==X||![$.repositoryRoot,$.originalWorkspaceRoot,$.worktreeRoot,$.workspaceRoot].every((W)=>N.isAbsolute(W)))throw Error("Invalid session task worktree metadata")}if(_.taskDiffStat!==void 0&&_.taskDiffStat!==null&&!w2(_.taskDiffStat))throw Error("Invalid session task diff stat");if(_.taskQueuePosition!==void 0&&_.taskQueuePosition!==null&&(!Number.isInteger(_.taskQueuePosition)||_.taskQueuePosition<1))throw Error("Invalid session task queue position");if(_.taskQueueDepth!==void 0&&_.taskQueueDepth!==null&&(!Number.isInteger(_.taskQueueDepth)||_.taskQueueDepth<0))throw Error("Invalid session task queue depth");if(_.taskConcurrencyLimit!==void 0&&_.taskConcurrencyLimit!==null&&(!Number.isInteger(_.taskConcurrencyLimit)||_.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof _.taskQueuePosition==="number"&&typeof _.taskQueueDepth==="number"&&_.taskQueuePosition>_.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata(_,X,$={}){A(_),q.validateTaskMetadataUpdate($,_);let W=q.resolveCatalogWorkspace(X);if($.taskWorktree&&N.resolve($.taskWorktree.workspaceRoot)!==W)throw Error("Session task worktree must match the catalog workspace");let J=new Date().toISOString(),O={id:m(),sessionId:_,timestamp:J,type:"session_created",cwd:W,gitBranch:q_(W),version:__(),data:{sessionId:_,rootId:_,...$.title!==void 0?{title:$.title}:{},taskStatus:$.taskStatus??"queued",...$.taskPromptSummary!==void 0?{taskPromptSummary:$.taskPromptSummary}:{},...$.taskPriority!==void 0?{taskPriority:$.taskPriority}:{},...$.taskKind!==void 0?{taskKind:$.taskKind}:{},...typeof $.taskDueAt==="string"?{taskDueAt:new Date($.taskDueAt).toISOString()}:{},...$.taskDispatch!==void 0?{taskDispatch:$.taskDispatch}:{},...$.taskModelId!==void 0?{taskModelId:$.taskModelId}:{},...$.taskRetriedFrom!==void 0?{taskRetriedFrom:$.taskRetriedFrom}:{},...$.taskIsolation!==void 0?{taskIsolation:$.taskIsolation}:{},...$.taskSourceProjectPath!==void 0?{taskSourceProjectPath:$.taskSourceProjectPath}:{},...$.taskWorktree!==void 0?{taskWorktree:$.taskWorktree}:{},...$.selectedModelId!==void 0?{selectedModelId:$.selectedModelId}:{},...$.permissionMode!==void 0?{permissionMode:$.permissionMode}:{},...$.reasoningEffort!==void 0?{reasoningEffort:$.reasoningEffort}:{},...$.serviceTier!==void 0?{serviceTier:$.serviceTier}:{},...$.responseVerbosity!==void 0?{responseVerbosity:$.responseVerbosity}:{},...$.communicationStyle!==void 0?{communicationStyle:$.communicationStyle}:{},...$.communicationStyleDigest!==void 0?{communicationStyleDigest:$.communicationStyleDigest}:{},...$.projectInstructionsDigest!==void 0?{projectInstructionsDigest:$.projectInstructionsDigest}:{},createdAt:J,updatedAt:J}},Q=q.getSessionFilePath(W,_);return await new v(Q).createExclusive([O]),q.toPublicMetadata(q.projectMetadataFromEntries([O],_,W,Q))}static async createRemoteSessionMetadata(_,X,$,W={}){A(_),q.validateTaskMetadataUpdate(W,_);let J;try{J=o($)}catch(Y){throw z(Y)}if(p(J.collisionIdentity)!==X)throw new R;await S2(X);let Q=new Date().toISOString();return n(X,async(Y)=>{let Z=I(Y,_),V={id:m(),sessionId:_,projectPath:X,timestamp:Q,type:"session_created",cwd:X,version:__(),data:{sessionId:_,rootId:_,remoteWorkspace:J,...W.title!==void 0?{title:W.title}:{},taskStatus:W.taskStatus??"queued",...W.taskPromptSummary!==void 0?{taskPromptSummary:W.taskPromptSummary}:{},...W.taskPriority!==void 0?{taskPriority:W.taskPriority}:{},...W.taskKind!==void 0?{taskKind:W.taskKind}:{},...typeof W.taskDueAt==="string"?{taskDueAt:new Date(W.taskDueAt).toISOString()}:{},...W.taskModelId!==void 0?{taskModelId:W.taskModelId}:{},...W.selectedModelId!==void 0?{selectedModelId:W.selectedModelId}:{},...W.permissionMode!==void 0?{permissionMode:W.permissionMode}:{},...W.reasoningEffort!==void 0?{reasoningEffort:W.reasoningEffort}:{},...W.serviceTier!==void 0?{serviceTier:W.serviceTier}:{},...W.responseVerbosity!==void 0?{responseVerbosity:W.responseVerbosity}:{},...W.communicationStyle!==void 0?{communicationStyle:W.communicationStyle}:{},...W.communicationStyleDigest!==void 0?{communicationStyleDigest:W.communicationStyleDigest}:{},...W.projectInstructionsDigest!==void 0?{projectInstructionsDigest:W.projectInstructionsDigest}:{},createdAt:Q,updatedAt:Q}};try{await new v(Z).createExclusive([V])}catch(U){if(U.code!=="EEXIST")throw U;return this.assertRemoteSessionWritableInScope(_,X,J,Y)}return q.toPublicMetadata(q.projectMetadataFromEntries([V],_,X,Z))})}static async assertSessionWritable(_,X){let $=await this.findSessionMetadata(_,X);if(!$)throw Error(`Session not found: ${_}`);if($.archivedAt)throw new t(_,$.archivedBySessionId??_);return $}static async assertRemoteSessionWritable(_,X,$){A(_);let W;try{W=o($)}catch(O){throw z(O)}if(p(W.collisionIdentity)!==X)throw new R;return n(X,async(O)=>{return this.assertRemoteSessionWritableInScope(_,X,W,O)})}static async findArchivedAncestor(_,X){let $=new Set,W=_;while(W){if($.has(W))throw Error("Session lineage contains a cycle");$.add(W),A(W);let J=P(X,W),O;try{O=await V_(J,"utf8")}catch(Y){if(Y.code==="ENOENT")return;throw Y}let Q=this.projectMetadataFromEntries(this.parseStoredSession(O,W),W,X,J);if(Q.projectPath!==X)throw Error("Session lineage escapes the requested workspace");if(Q.archivedAt)return{sessionId:Q.sessionId,archivedAt:Q.archivedAt};W=Q.parentId}return}static async listSessionArchiveMembers(_,X){A(_);let $=this.resolveCatalogWorkspace(X),W=await this.scanStoredSessions($,!0,0,null);if(!W.some((Q)=>Q.sessionId===_))throw Error(`Session not found: ${_}`);let J=new Set([_]),O=!0;while(O){O=!1;for(let Q of W)if(Q.parentId&&J.has(Q.parentId)&&!J.has(Q.sessionId))J.add(Q.sessionId),O=!0}return W.filter((Q)=>J.has(Q.sessionId)).sort((Q,Y)=>Q.sessionId.localeCompare(Y.sessionId)).map((Q)=>this.toPublicMetadata(Q))}static async archiveSession(_,X){A(_);let $=this.resolveCatalogWorkspace(X),W=await this.findSessionMetadata(_,$);if(!W)throw Error(`Session not found: ${_}`);if(W.archivedAt)return W;let J=await this.listSessionArchiveMembers(_,$),O=J.find((Y)=>Y.taskStatus==="queued"||Y.taskStatus==="running");if(O)throw new Y_(`Stop session ${O.sessionId} before archiving this session tree`);let Q=[];try{for(let U of J)Q.push(await u.acquire(U.sessionId,$));let Y=P($,_),Z=new v(Y),V=[];return await Z.appendValidated((U)=>{let G=this.projectMetadataFromEntries(U,_,$,Y);if(G.archivedAt)throw new Y_(`Session archive state changed concurrently: ${_}`);if(G.taskStatus==="queued"||G.taskStatus==="running")throw new Y_(`Stop session ${_} before archiving it`);let L=new Date().toISOString(),B={id:m(),sessionId:_,timestamp:L,type:"session_updated",cwd:$,gitBranch:q_($),version:__(),data:{sessionId:_,archivedAt:L,updatedAt:L}};return V=[...U,B],B}),this.toPublicMetadata({...this.projectMetadataFromEntries(V,_,$,Y),archivedBySessionId:_})}catch(Y){if(Y instanceof Y_)throw Y;if(Y instanceof $_)throw new Y_(Y.message);throw this.sanitizeStoredSessionError(Y,_)}finally{for(let Y of Q.reverse())await Y.release()}}static async unarchiveSession(_,X){A(_);let $=this.resolveCatalogWorkspace(X),W=await this.findSessionMetadata(_,$);if(!W)throw Error(`Session not found: ${_}`);if(!W.archivedAt)return W;if(W.archivedBySessionId&&W.archivedBySessionId!==_)throw new Y_(`Unarchive ancestor ${W.archivedBySessionId} to restore session ${_}`);let J;try{J=await u.acquire(_,$);let O=P($,_),Q=new v(O),Y=[];return await Q.appendValidated((Z)=>{if(!this.projectMetadataFromEntries(Z,_,$,O).archivedAt)throw new Y_(`Session archive state changed concurrently: ${_}`);let U=new Date().toISOString(),G={id:m(),sessionId:_,timestamp:U,type:"session_updated",cwd:$,gitBranch:q_($),version:__(),data:{sessionId:_,archivedAt:null,updatedAt:U}};return Y=[...Z,G],G}),this.toPublicMetadata(this.projectMetadataFromEntries(Y,_,$,O))}catch(O){if(O instanceof Y_)throw O;if(O instanceof $_)throw new Y_(O.message);throw this.sanitizeStoredSessionError(O,_)}finally{await J?.release()}}static async updateSessionMetadata(_,X,$){if(A(_),q.validateTaskMetadataUpdate($,_),$.taskStatus!==void 0&&!O1.has($.taskStatus))throw Error(`Invalid session task status: ${String($.taskStatus)}`);if($.taskOwnerPid!==void 0&&$.taskOwnerPid!==null&&(!Number.isInteger($.taskOwnerPid)||$.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let W=q.resolveCatalogWorkspace(X);if($.taskWorktree&&N.resolve($.taskWorktree.workspaceRoot)!==W)throw Error("Session task worktree must match the catalog workspace");let J=q.getSessionFilePath(W,_),O=new v(J),Q=[];try{await O.appendValidatedAsync(async(Y)=>{let Z=q.getSessionCreatedEntry(Y,_);if(Z.data.sessionId!==_)throw Error(`Session metadata creation record sessionId mismatch: ${_}`);if(!N.isAbsolute(Z.cwd)||N.resolve(Z.cwd)!==W)throw Error(`Session metadata creation record cwd mismatch: ${_}`);let V=q.projectMetadataFromEntries(Y,_,W,J);if(V.archivedAt)throw new t(_,_);if(V.parentId){let L=await q.findArchivedAncestor(V.parentId,W);if(L)throw new t(_,L.sessionId)}let U=new Date().toISOString(),G={id:m(),sessionId:_,timestamp:U,type:"session_updated",cwd:W,gitBranch:q_(W),version:__(),data:{sessionId:_,...$.title!==void 0?{title:$.title}:{},...$.taskStatus!==void 0?{taskStatus:$.taskStatus}:{},...$.taskStatusReason!==void 0?{taskStatusReason:$.taskStatusReason}:{},...$.taskFailure!==void 0?{taskFailure:$.taskFailure}:{},...$.taskStartedAt!==void 0?{taskStartedAt:$.taskStartedAt}:{},...$.taskCompletedAt!==void 0?{taskCompletedAt:$.taskCompletedAt}:{},...$.taskOwnerPid!==void 0?{taskOwnerPid:$.taskOwnerPid}:{},...$.taskPromptSummary!==void 0?{taskPromptSummary:$.taskPromptSummary}:{},...$.taskPriority!==void 0?{taskPriority:$.taskPriority}:{},...$.taskKind!==void 0?{taskKind:$.taskKind}:{},...$.taskDueAt!==void 0?{taskDueAt:$.taskDueAt===null?null:new Date($.taskDueAt).toISOString()}:{},...$.taskDispatch!==void 0?{taskDispatch:$.taskDispatch}:{},...$.taskModelId!==void 0?{taskModelId:$.taskModelId}:{},...$.taskRetriedFrom!==void 0?{taskRetriedFrom:$.taskRetriedFrom}:{},...$.taskDelivery!==void 0?{taskDelivery:$.taskDelivery}:{},...$.taskIsolation!==void 0?{taskIsolation:$.taskIsolation}:{},...$.taskSourceProjectPath!==void 0?{taskSourceProjectPath:$.taskSourceProjectPath}:{},...$.taskWorktree!==void 0?{taskWorktree:$.taskWorktree}:{},...$.taskDiffStat!==void 0?{taskDiffStat:$.taskDiffStat}:{},...$.taskQueuePosition!==void 0?{taskQueuePosition:$.taskQueuePosition}:{},...$.taskQueueDepth!==void 0?{taskQueueDepth:$.taskQueueDepth}:{},...$.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:$.taskConcurrencyLimit}:{},...$.selectedModelId!==void 0?{selectedModelId:$.selectedModelId}:{},...$.permissionMode!==void 0?{permissionMode:$.permissionMode}:{},...$.reasoningEffort!==void 0?{reasoningEffort:$.reasoningEffort}:{},...$.serviceTier!==void 0?{serviceTier:$.serviceTier}:{},...$.responseVerbosity!==void 0?{responseVerbosity:$.responseVerbosity}:{},...$.communicationStyle!==void 0?{communicationStyle:$.communicationStyle}:{},...$.communicationStyleDigest!==void 0?{communicationStyleDigest:$.communicationStyleDigest}:{},...$.projectInstructionsDigest!==void 0?{projectInstructionsDigest:$.projectInstructionsDigest}:{},updatedAt:U}};return Q=[...Y,G],G})}catch(Y){throw q.sanitizeStoredSessionError(Y,_)}return q.toPublicMetadata(q.projectMetadataFromEntries(Q,_,W,J))}static async updateRemoteSessionMetadata(_,X,$,W){if(A(_),q.validateTaskMetadataUpdate(W,_),W.taskStatus!==void 0&&!O1.has(W.taskStatus))throw Error(`Invalid session task status: ${String(W.taskStatus)}`);if(W.taskOwnerPid!==void 0&&W.taskOwnerPid!==null&&(!Number.isInteger(W.taskOwnerPid)||W.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let J;try{if(J=o($),p(J.collisionIdentity)!==X)throw new R}catch(O){throw z(O)}try{return await n(X,async(O)=>{let Q=I(O,_);await d(O,Q);let Y=new v(Q),Z=[];return await Y.appendValidatedAsync(async(V)=>{let U=g(q.projectMetadataFromEntries(V,_,X,Q),J);if(U.archivedAt)throw new t(_,_);if(U.parentId){let B=await q.findRemoteArchivedAncestor(U.parentId,O,U.remoteWorkspace);if(B)throw new t(_,B.sessionId)}let G=new Date().toISOString(),L={id:m(),sessionId:_,projectPath:X,timestamp:G,type:"session_updated",cwd:X,version:__(),data:{sessionId:_,...W.title!==void 0?{title:W.title}:{},...W.taskStatus!==void 0?{taskStatus:W.taskStatus}:{},...W.taskStatusReason!==void 0?{taskStatusReason:W.taskStatusReason}:{},...W.taskFailure!==void 0?{taskFailure:W.taskFailure}:{},...W.taskStartedAt!==void 0?{taskStartedAt:W.taskStartedAt}:{},...W.taskCompletedAt!==void 0?{taskCompletedAt:W.taskCompletedAt}:{},...W.taskOwnerPid!==void 0?{taskOwnerPid:W.taskOwnerPid}:{},...W.taskPromptSummary!==void 0?{taskPromptSummary:W.taskPromptSummary}:{},...W.taskPriority!==void 0?{taskPriority:W.taskPriority}:{},...W.taskKind!==void 0?{taskKind:W.taskKind}:{},...W.taskDueAt!==void 0?{taskDueAt:W.taskDueAt===null?null:new Date(W.taskDueAt).toISOString()}:{},...W.taskModelId!==void 0?{taskModelId:W.taskModelId}:{},...W.taskQueuePosition!==void 0?{taskQueuePosition:W.taskQueuePosition}:{},...W.taskQueueDepth!==void 0?{taskQueueDepth:W.taskQueueDepth}:{},...W.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:W.taskConcurrencyLimit}:{},...W.selectedModelId!==void 0?{selectedModelId:W.selectedModelId}:{},...W.permissionMode!==void 0?{permissionMode:W.permissionMode}:{},...W.reasoningEffort!==void 0?{reasoningEffort:W.reasoningEffort}:{},...W.serviceTier!==void 0?{serviceTier:W.serviceTier}:{},...W.responseVerbosity!==void 0?{responseVerbosity:W.responseVerbosity}:{},...W.communicationStyle!==void 0?{communicationStyle:W.communicationStyle}:{},...W.communicationStyleDigest!==void 0?{communicationStyleDigest:W.communicationStyleDigest}:{},...W.projectInstructionsDigest!==void 0?{projectInstructionsDigest:W.projectInstructionsDigest}:{},updatedAt:G}};return Z=[...V,L],L},{noFollow:!0,validateHandle:(V)=>I2(O,Q,V)}),q.toPublicMetadata(g(q.projectMetadataFromEntries(Z,_,X,Q),J))})}catch(O){if(O instanceof d_||O instanceof t)throw O;throw z(O)}}static async setSessionPermissionMode(_,X,$){if(A(_),!F0($))throw Error("Invalid session permission mode");let W=q.resolveCatalogWorkspace(X),J=await q.findSessionMetadata(_,W);if(J?.permissionMode===$)return J;if(J)return q.updateSessionMetadata(_,W,{permissionMode:$});try{return await q.createSessionMetadata(_,W,{taskStatus:"completed",permissionMode:$})}catch(O){if(O.code!=="EEXIST")throw O;return q.updateSessionMetadata(_,W,{permissionMode:$})}}static async findSessionTaskWorktree(_,X){A(_);let $=q.resolveCatalogWorkspace(X),W=q.getSessionFilePath($,_);try{return(await q.readStoredSessionMetadata(W,_,$)).taskWorktree}catch(J){if(J.code==="ENOENT")return;throw q.sanitizeStoredSessionError(J,_)}}static async findSessionTaskDispatch(_,X){A(_);let $=q.resolveCatalogWorkspace(X),W=q.getSessionFilePath($,_);try{return(await q.readStoredSessionMetadata(W,_,$)).taskDispatch}catch(J){if(J.code==="ENOENT")return;throw q.sanitizeStoredSessionError(J,_)}}static async loadSessionFromFile(_,X,$){let W=await V_(_,"utf-8"),J=this.parseStoredSession(W,X);if($!==void 0){if(this.projectMetadataFromEntries(J,X,$,_).projectPath!==$)throw Error(`未找到会话: ${X}`)}return this.convertJSONLToMessages(J)}static async loadSessionModelContextFromFile(_,X,$){let W=await V_(_,"utf-8"),J=this.parseStoredSession(W,X);if($!==void 0){if(this.projectMetadataFromEntries(J,X,$,_).projectPath!==$)throw Error(`未找到会话: ${X}`)}return this.convertJSONLToModelContext(J)}static convertJSONLToModelContext(_){let X=e(_),$=-1,W;for(let O=0;O<X.length;O++){let Q=X[O];if(Q?.type!=="part_created"||Q.data.partType!=="summary")continue;let Y=Q.data.payload;if($=O,W=V0(Y.replacementMessages),!W)W=[{role:"user",content:Y.text??"",metadata:Q.data.payload}]}if($<0||!W)return this.convertJSONLToMessages(X,{includeTokenBudgetHandoffs:!0});let J=this.convertJSONLToMessages(X.slice($+1),{includeTokenBudgetHandoffs:!0});return[...W,...J]}static convertJSONLToMessages(_,X={}){let $=[],W=new Map,J=new Map,O=new Map,Q=new Map,Y=new Map,Z=e(_),V=X.includeTokenBudgetHandoffs?O2(Z):{kind:"none"},U=new Set;for(let G of Z){if(G.type==="token_budget_handoff_recorded"){if(V.kind==="valid"&&V.event.id===G.id){let L=J2(G);if(L)$.push(L)}continue}if(G.type==="message_created"){let L=G.data.metadata&&typeof G.data.metadata==="object"&&!Array.isArray(G.data.metadata)?G.data.metadata:void 0,B=L?.codeReview&&typeof L.codeReview==="object"&&!Array.isArray(L.codeReview)?L.codeReview:void 0;if(B?.phase==="completed"&&typeof B.reviewId==="string")U.add(B.reviewId);let H=G.data.role==="assistant"&&G.data.parentMessageId?O.get(G.data.parentMessageId):void 0,k=H??{role:G.data.role,content:"",...G.data.metadata||G.data.inboxMessageId?{metadata:{...G.data.metadata&&typeof G.data.metadata==="object"&&!Array.isArray(G.data.metadata)?G.data.metadata:{},...G.data.inboxMessageId?{inboxMessageId:G.data.inboxMessageId}:{}}}:{}};if(W.set(G.data.messageId,k),J.set(G.data.messageId,[]),!H)$.push(k)}if(G.type==="part_created"){if(G.data.partType==="reasoning"){let L=W.get(G.data.messageId);if(L){let B=G.data.payload;L.reasoningContent=(L.reasoningContent??"")+(B.text??"")}}if(G.data.partType==="text"){let L=W.get(G.data.messageId);if(L){let B=G.data.payload,H=J.get(G.data.messageId);if(H)H.push({type:"text",text:B.text??""}),L.content=g2(H);else L.content=B.text??""}}if(G.data.partType==="image"){let L=W.get(G.data.messageId);if(L){let B=G.data.payload,H=J.get(G.data.messageId);if(H&&B.dataUrl)H.push({type:"image_url",image_url:{url:B.dataUrl}}),L.content=g2(H)}}if(G.data.partType==="tool_call"){let L=W.get(G.data.messageId);if(L?.role!=="assistant"){if(L=O.get(G.data.messageId),!L)L={role:"assistant",content:"",tool_calls:[]},O.set(G.data.messageId,L),$.push(L)}if(L.role==="assistant"){let B=G.data.payload,H=B.toolCallId??G.data.partId;Q.set(G.data.partId,H),Y.set(H,L),L.tool_calls??=[],L.tool_calls.push({id:H,type:"function",function:{name:B.toolName??"unknown",arguments:JSON.stringify(B.input??{})}})}}if(G.data.partType==="tool_result"){let L=G.data.payload,B=L2(L),H=B.error?`Error: ${B.error.message}`:typeof B.llmContent==="string"?B.llmContent:JSON.stringify(B.llmContent),k=L;$.push({role:"tool",content:H,tool_call_id:Q.get(G.data.messageId)??L.toolCallId,name:L.toolName,metadata:k})}if(G.data.partType==="summary"){let L=G.data.payload,B=G.data.payload;$.push({role:"system",content:L.text??"",metadata:B})}if(G.data.partType==="subtask_ref"){let L=W.get(G.data.messageId)??Y.get(G.data.messageId);if(L){let B=G.data.payload,H=L.metadata??{};L.metadata={...H,subtaskRef:B}}}}}for(let G of L0(Z)){if(G.completion===void 0||U.has(G.start.reviewId))continue;$.push({role:"assistant",content:e1(G.start,G.completion),metadata:{codeReview:{..._2(G.start,G.completion),synthetic:!0}}})}return $}static projectionDeriver(){return(_,X,$,W,J)=>{try{let O=J??P($,X),Q=this.projectMetadataFromEntries(_,X,$,O);if(W==="acp-remote")return g(Q);return Q}catch(O){if(W==="acp-remote")throw z(O);return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection(_,X,$=0,W=!1,J={}){try{let O=await p_();if(!O)return null;await q1(O,this.projectionDeriver(),$);let Q=[];Q.push("source_kind = 'local'");let Y=[];if(_!==void 0)Q.push("project_path=?"),Y.push(_);bX(J,"",Q,Y);let Z=Q.length>0?` WHERE ${Q.join(" AND ")}`:"",V=O.prepare(`SELECT metadata_json, is_subagent FROM sessions${Z}`).all(...Y),U=[];for(let L of V){if(!X&&L.is_subagent===1)continue;try{let B=JSON.parse(L.metadata_json);if(B.remoteWorkspace)continue;if(_!==void 0&&B.projectPath!==_)continue;U.push(B)}catch{}}let G=await Promise.all(U.map((L)=>this.reconcileInterruptedTask(L)));return Q1(G.filter((L)=>t2(L,J)),W)}catch{return null}}static async scanStoredSessions(_,X=!1,$=0,W=!1,J={}){let O=_?N.resolve(_):void 0,Q=await this.scanStoredSessionsFromProjection(O,X,0,W,J);if(Q)return Q;let Y=O?[{storagePath:K_(O),projectPath:O}]:await this.listAllProjectStorageDirectories(),Z=[];for(let V of Y){let U;try{U=await b_(V.storagePath)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of U){if(!G.endsWith(".jsonl"))continue;let L=G.slice(0,-6),B=N.join(V.storagePath,G);try{let H=await this.readLocalCatalogSessionMetadata(B,L,V.projectPath);if(!H)continue;if(O!==void 0&&H.projectPath!==O){l_.warn(`[SessionService] Skipping out-of-scope session transcript: ${L}`);continue}if(!X&&H.relationType==="subagent")continue;if(!fX(H,J))continue;Z.push(await this.reconcileInterruptedTask(H))}catch(H){let k=H.code;if(k==="ENOENT")continue;if(k)throw H;if(H instanceof R)throw H;l_.warn(`[SessionService] Skipping invalid session transcript: ${L}`)}}}return Q1(Z,W)}static async listAllProjectStorageDirectories(){let _=N.join(h(),"projects"),X;try{X=await b_(_,{withFileTypes:!0,encoding:"utf8"})}catch($){if($.code==="ENOENT")return[];throw $}return X.filter(($)=>$.isDirectory()).map(($)=>({storagePath:N.join(_,$.name),projectPath:m2($.name)}))}static async listRemoteSessionScopes(_){if(_.descriptor){let $=p(_.descriptor.collisionIdentity);try{return await n($,async()=>[{hostStateRoot:$,descriptor:_.descriptor}])}catch(W){if(W.code==="ENOENT")return[];throw z(W)}}return(await Y1()).map(($)=>({hostStateRoot:String($)}))}static async scanRemoteStoredSessions(_,X=0){let $=await this.scanRemoteStoredSessionsFromProjection(_,X);if($)return $;let W=await this.listRemoteSessionScopes(_),J=[];for(let O of W)await n(O.hostStateRoot,async(Q)=>{let Y;try{Y=await b_(String(Q))}catch(Z){if(Z.code==="ENOENT")return;throw z(Z)}for(let Z of Y){if(!Z.endsWith(".jsonl"))continue;let V=Z.slice(0,-6);if(!c_(V))continue;let U=I(Q,V),G;try{G=await this.readRemoteStoredSessionMetadata(U,V,O.hostStateRoot,Q,_.descriptor)}catch(L){if(L.code==="ENOENT")continue;if(L instanceof Error&&L.message)throw z(L);throw L}if(!G)continue;if(!_.includeSubagents&&G.relationType==="subagent")continue;J.push(G)}});return y2(J,_.archived)}static async scanRemoteStoredSessionsFromProjection(_,X=0){try{let $=await p_();if(!$)return null;if(_.descriptor)await r2($,this.projectionDeriver(),p(_.descriptor.collisionIdentity));else await o2($,this.projectionDeriver());let W=["source_kind = 'acp-remote'"],J=[];if(_.descriptor)W.push("project_path=?"),J.push(p(_.descriptor.collisionIdentity));let O=W.length>0?` WHERE ${W.join(" AND ")}`:"",Q=$.prepare(`SELECT metadata_json, is_subagent FROM sessions${O}`).all(...J),Y=[];for(let G of Q){if(!_.includeSubagents&&G.is_subagent===1)continue;let L=g(JSON.parse(G.metadata_json),void 0);if(_.descriptor&&!j_(L.remoteWorkspace,_.descriptor))continue;Y.push(L)}let Z=_.descriptor,V=Z?Y.filter((G)=>j_(G.remoteWorkspace,Z)):Y,U=await Promise.all(V.map((G)=>this.reconcileInterruptedTask(G,"acp-remote")));return y2(U.map((G)=>g(G)),_.archived)}catch($){throw z($)}}static toRemoteCatalogEntries(_){return _.flatMap((X)=>{if(!X.remoteWorkspace)return[];return[{...X,workspaceIdentity:X.remoteWorkspace.exactIdentity}]})}static async readStoredSessionMetadata(_,X,$,W="local",J){if(W==="acp-remote"){if(!J||String(J)!==$)throw new R;let Q=I(J,X);if(_!==Q)throw new R}let O=await this.readStoredSessionMetadataWithoutReconciliation(_,X,$);if(W==="acp-remote")g(O);else if(O.projectPath!==$||O.remoteWorkspace)return O;return this.reconcileInterruptedTask(O,W,J)}static async readStoredSessionMetadataWithoutReconciliation(_,X,$){let W=await V_(_,"utf-8"),J=this.parseStoredSession(W,X);return this.projectMetadataFromEntries(J,X,$,_)}static async readLocalCatalogSessionMetadata(_,X,$){let W=await V_(_,"utf-8"),J=this.parseStoredSession(W,X),O=this.getSessionCreatedEntry(J,X);if(Object.hasOwn(O.data,"remoteWorkspace")){try{o(O.data.remoteWorkspace)}catch(Q){throw z(Q)}return}return this.projectMetadataFromEntries(J,X,$,_)}static async readRemoteStoredSessionMetadata(_,X,$,W,J){if(String(W)!==$||_!==I(W,X))throw new R;await d(W,_);let O=await V_(_,"utf-8"),Q=this.parseStoredSession(O,X);this.validateSessionWorkspace(Q,X,$);let Y=g(this.projectMetadataFromEntries(Q,X,$,_));if(J&&!j_(Y.remoteWorkspace,J))return;return g(await this.reconcileInterruptedTask(Y,"acp-remote",W),Y.remoteWorkspace)}static async reconcileInterruptedTask(_,X="local",$){let W=_.taskOwnerPid;if(_.taskStatus!=="running"||W===void 0)return _;if(X==="acp-remote"){if($)return this.reconcileInterruptedTaskInScope(_,W,$);return n(_.projectPath,async(J)=>this.reconcileInterruptedTaskInScope(_,W,J))}return this.reconcileInterruptedTaskInScope(_,W)}static async reconcileInterruptedTaskInScope(_,X,$){let W=$?g(_).remoteWorkspace:void 0;if($){let Y=I($,_.sessionId);if(_.projectPath!==String($)||_.filePath!==Y)throw new R;await d($,_.filePath)}let J;try{J=$?await u.acquireRemote(_.sessionId,$):await u.acquire(_.sessionId,_.projectPath)}catch(Y){if(!(Y instanceof $_))throw Y;let Z=await V_(_.filePath,"utf-8"),V=this.projectMetadataFromEntries(this.parseStoredSession(Z,_.sessionId),_.sessionId,_.projectPath,_.filePath);return W?g(V,W):V}let O=new v(_.filePath),Q;try{try{await O.appendValidated((Z)=>{let V=this.projectMetadataFromEntries(Z,_.sessionId,_.projectPath,_.filePath);if(W)g(V,W);if(V.taskStatus!=="running"||V.taskOwnerPid!==X)throw new C1;let U=new Date().toISOString(),G={id:m(),sessionId:_.sessionId,timestamp:U,type:"session_updated",cwd:_.projectPath,...$?{projectPath:_.projectPath}:{},...$?{}:{gitBranch:q_(_.projectPath)},version:__(),data:{sessionId:_.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:U,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:U}};return Q=[...Z,G],G})}catch(Z){if(!(Z instanceof C1))throw Z}if(!Q){let Z=await V_(_.filePath,"utf-8");Q=this.parseStoredSession(Z,_.sessionId)}let Y=this.projectMetadataFromEntries(Q,_.sessionId,_.projectPath,_.filePath);return W?g(Y,W):Y}finally{await J.release()}}static projectMetadataFromEntries(_,X,$,W){if(_.length===0)throw Error(`Empty session transcript: ${X}`);let J=this.getSessionCreatedEntry(_,X);if(Object.hasOwn(J.data,"remoteWorkspace"))this.validateRemoteSessionCreationRecord(_,J,X,$);let O=_.reduce((E,D_)=>D_.type==="session_updated"?{...E,...D_.data}:E,{...J.data}),Q=e(_),Y=s1(t1(Q)),V=L0(Q).at(-1),U=Q.findLastIndex((E)=>E.type==="review_started"&&E.data.reviewId===V?.start.reviewId||E.type==="review_completed"&&E.data.reviewId===V?.start.reviewId),G=Q.findLastIndex((E)=>(E.type==="session_created"||E.type==="session_updated")&&Object.hasOwn(E.data,"taskStatus")),L=V!==void 0&&U>G,B=L?V.completion===void 0?"running":V.completion.status==="completed"||V.completion.status==="stale"?"completed":V.completion.status==="aborted"?"cancelled":V.completion.status==="interrupted"?"interrupted":"failed":void 0,H=Q.filter((E)=>E.type==="message_created"&&["user","assistant"].includes(E.data.role)).length,k=Q.some((E)=>E.type==="part_created"&&E.data.partType==="tool_result"&&typeof E.data.payload.error==="string"),b=O1.has(O.taskStatus)?O.taskStatus:void 0,w=B??b??(k?"failed":"completed"),X_=typeof O.taskOwnerPid==="number"&&Number.isInteger(O.taskOwnerPid)&&O.taskOwnerPid>0?O.taskOwnerPid:void 0,Z_=T1.has(O.taskIsolation)?O.taskIsolation:void 0,l=typeof O.taskSourceProjectPath==="string"&&N.isAbsolute(O.taskSourceProjectPath)?N.resolve(O.taskSourceProjectPath):void 0,c=J.cwd;if(c!==void 0&&!N.isAbsolute(c))throw Error(`Session catalog cwd must be absolute: ${X}`);let D=c===void 0?$:N.resolve(c),x=this.parseRemoteWorkspaceFromCreated(J,X,D),f=D2(O.taskWorktree),T=f?.sessionId===X&&N.resolve(f.workspaceRoot)===D?f:void 0,L_=w2(O.taskDiffStat),j=x2(O.taskDispatch),S=z0.has(O.taskPriority)?O.taskPriority:j?.taskPriority,U_=D0.has(O.taskKind)?O.taskKind:j?.taskKind,y_=typeof O.taskDueAt==="string"&&Number.isFinite(Date.parse(O.taskDueAt))?new Date(O.taskDueAt).toISOString():j?.taskDueAt,t_=typeof O.taskModelId==="string"&&O.taskModelId.trim()?O.taskModelId:j?.modelId,R0=typeof O.selectedModelId==="string"&&O.selectedModelId.trim()?O.selectedModelId:t_,w0=F0(O.permissionMode)?O.permissionMode:j?.permissionMode,s_=o_(O.reasoningEffort)?O.reasoningEffort:j?.reasoningEffort,e_=r_(O.serviceTier)?O.serviceTier:j?.serviceTier,_0=i_(O.responseVerbosity)?O.responseVerbosity:j?.responseVerbosity,g_=a_(O.communicationStyle)?O.communicationStyle:j?.communicationStyle,y=Object.hasOwn(O,"communicationStyleDigest")?typeof O.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(O.communicationStyleDigest)?O.communicationStyleDigest:void 0:g_===j?.communicationStyle?j?.communicationStyleDigest:void 0,X0=Object.hasOwn(O,"projectInstructionsDigest")?typeof O.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(O.projectInstructionsDigest)?O.projectInstructionsDigest:void 0:j?.projectInstructionsDigest,S_=M1(O.archivedAt)?O.archivedAt:void 0,T_=k2(O.taskRetriedFrom),C_=R2(O.taskDelivery),B_=typeof O.taskQueuePosition==="number"&&Number.isInteger(O.taskQueuePosition)&&O.taskQueuePosition>0?O.taskQueuePosition:void 0,I_=typeof O.taskQueueDepth==="number"&&Number.isInteger(O.taskQueueDepth)&&O.taskQueueDepth>=0?O.taskQueueDepth:void 0,$0=typeof O.taskConcurrencyLimit==="number"&&Number.isInteger(O.taskConcurrencyLimit)&&O.taskConcurrencyLimit>0?O.taskConcurrencyLimit:void 0,K=L?V?.completion?V.completion.status==="completed"?void 0:`Code review ${h0(V.completion.status)}`:`Reviewing ${V?.start.target.label??"changes"}`:void 0,r=L?w==="failed"&&K?r0(K):void 0:o0(O.taskFailure)?O.taskFailure:w==="failed"&&typeof O.taskStatusReason==="string"?r0(O.taskStatusReason):void 0;return{sessionId:X,projectPath:D,remoteWorkspace:x,...J.gitBranch!==void 0?{gitBranch:J.gitBranch}:{},rootId:O.rootId||X,parentId:O.parentId,relationType:O.relationType,resumedFrom:O.resumedFrom,rootAgentId:O.rootAgentId,resumeDepth:O.resumeDepth,title:O.title,agentType:O.agentType,model:O.model,selectedModelId:R0,permissionMode:w0,reasoningEffort:s_,serviceTier:e_,responseVerbosity:_0,communicationStyle:g_,communicationStyleDigest:y,projectInstructionsDigest:X0,pendingInteraction:Y,taskStatus:w,taskStatusReason:r?.message??K??(typeof O.taskStatusReason==="string"?O.taskStatusReason:void 0),taskFailure:r,taskStartedAt:L?V?.start.startedAt:typeof O.taskStartedAt==="string"?O.taskStartedAt:void 0,taskCompletedAt:L?V?.completion?.completedAt:typeof O.taskCompletedAt==="string"?O.taskCompletedAt:void 0,taskPromptSummary:L?V?SX(V.start.target):"/review uncommitted":typeof O.taskPromptSummary==="string"?O.taskPromptSummary:void 0,taskPriority:S,taskKind:U_,taskDueAt:y_,taskModelId:t_,taskRetryAvailable:j!==void 0,taskRetriedFrom:T_,taskDelivery:C_,taskIsolation:Z_,taskSourceProjectPath:l,taskWorktreePath:T?.worktreeRoot,taskWorktreeBranch:T?.branch,taskBaseCommit:T?.baseCommit,taskDiffStat:L_,taskQueuePosition:B_,taskQueueDepth:I_,taskConcurrencyLimit:$0,archivedAt:S_,taskOwnerPid:L?void 0:X_,taskWorktree:T,taskDispatch:j,messageCount:H,firstMessageTime:_[0].timestamp,lastMessageTime:_.at(-1).timestamp,hasErrors:k||w==="failed",filePath:W}}static parseRemoteWorkspaceFromCreated(_,X,$){if(!Object.hasOwn(_.data,"remoteWorkspace"))return;let W;try{W=o(_.data.remoteWorkspace)}catch(O){throw z(O)}if(p(W.collisionIdentity)!==$)throw new R;return W}static async assertRemoteSessionWritableInScope(_,X,$,W){let J=I(W,_),O;try{await d(W,J),O=await this.readStableSessionSnapshot(J,_)}catch(Y){throw z(Y)}let Q;try{Q=this.projectMetadataFromEntries(O,_,X,J)}catch(Y){throw z(Y)}if(Q.archivedAt)throw new t(_,Q.archivedBySessionId??_);if(!Q.remoteWorkspace)throw new R;if(!j_(Q.remoteWorkspace,$))throw new d_;return this.toPublicMetadata(Q)}static async readValidatedRemoteSessionSnapshot(_,X,$,W){W?.throwIfAborted();let J;try{if(A(_),J=o($),p(J.collisionIdentity)!==X)throw new R}catch(O){throw z(O)}try{return await n(X,async(O)=>{W?.throwIfAborted();let Q=I(O,_);await d(O,Q);let Y=await this.readStableSessionSnapshot(Q,_,3,W),Z=this.projectMetadataFromEntries(Y,_,X,Q);return g(Z,J),Y})}catch(O){if(W?.aborted)throw O;if(O instanceof d_)throw O;throw z(O)}}static toPublicMetadata(_){let{filePath:X,taskOwnerPid:$,taskWorktree:W,taskDispatch:J,...O}=_;return O}static getSessionFilePath(_,X){return P(_,X)}static getSessionCreatedEntry(_,X){let $=_.find((W)=>W.type==="session_created");if(!$)throw new e2(X);return $}static validateRemoteSessionCreationRecord(_,X,$,W){if(K0(_,$,W)!==X)throw new R}static resolveCatalogWorkspace(_){if(!N.isAbsolute(_))throw Error("Session catalog cwd must be absolute");return M0(_)}static validateSessionWorkspace(_,X,$){let W=this.getSessionCreatedEntry(_,X);if(W.data.sessionId!==X)throw Error(`Session creation record sessionId mismatch: ${X}`);if(!N.isAbsolute(W.cwd)||N.resolve(W.cwd)!==$)throw Error(`Session creation record cwd mismatch: ${X}`)}static resolveForkWorkspace(_){if(!N.isAbsolute(_))throw Error("Fork workspace paths must be absolute");return M0(_)}static parseStoredSession(_,X){return l2(_,`session ${X}`)}static isCorruptSessionJSONLError(_){return _ instanceof Error&&_.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError(_,X){if(!this.isCorruptSessionJSONLError(_)||!(_ instanceof Error))return _;let $=_.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${X}${$?` at line ${$}`:""}`,{cause:_.cause})}static async readStableSessionSnapshot(_,X,$=3,W){for(let J=0;J<$;J+=1){W?.throwIfAborted();let O=await n_.stat(_,W),Q=await n_.readFile(_,W),Y=this.parseStoredSession(Q,X),Z=await n_.stat(_,W);if(W?.throwIfAborted(),O.size===Z.size&&O.mtimeNs===Z.mtimeNs&&O.dev===Z.dev&&O.ino===Z.ino)return Y}throw new K1}}function g2(_){if(_.length===1&&_[0]?.type==="text")return _[0].text;return[..._]}
94
- export{cX as wc,pX as xc,nX as yc,H_ as zc,dX as Ac,m0 as Bc,a0 as Cc,D1 as Dc,m_ as Ec,tX as Fc,sX as Gc,$_ as Hc,u as Ic,k4 as Jc,S1 as Kc,J_ as Lc,E$ as Mc,F$ as Nc,z$ as Oc,D$ as Pc,R$ as Qc,w$ as Rc,x$ as Sc,k$ as Tc,b$ as Uc,f$ as Vc,j$ as Wc,y$ as Xc,g$ as Yc,S$ as Zc,I$ as _c,m$ as $c,v$ as ad,P$ as bd,u$ as cd,h$ as dd,l$ as ed,c$ as fd,p$ as gd,n$ as hd,d$ as id,i$ as jd,r$ as kd,o$ as ld,a$ as md,t$ as nd,s$ as od,e$ as pd,n1 as qd,h4 as rd,P0 as sd,r1 as td,JW as ud,QW as vd,t1 as wd,GW as xd,L0 as yd,LW as zd,h0 as Ad,e1 as Bd,_2 as Cd,HW as Dd,NW as Ed,qW as Fd,e4 as Gd,O2 as Hd,J2 as Id,_X as Jd,TW as Kd,k_ as Ld,r0 as Md,o0 as Nd,N_ as Od,N0 as Pd,jW as Qd,yW as Rd,gW as Sd,SW as Td,L2 as Ud,IW as Vd,lW as Wd,F2 as Xd,q2 as Yd,dW as Zd,z2 as _d,iW as $d,gX as ae,RO as be,wO as ce,e2 as de,t as ee,Y_ as fe,q as ge};
94
+ export{cX as xc,pX as yc,nX as zc,H_ as Ac,dX as Bc,m0 as Cc,a0 as Dc,D1 as Ec,m_ as Fc,tX as Gc,sX as Hc,$_ as Ic,u as Jc,k4 as Kc,S1 as Lc,J_ as Mc,E$ as Nc,F$ as Oc,z$ as Pc,D$ as Qc,R$ as Rc,w$ as Sc,x$ as Tc,k$ as Uc,b$ as Vc,f$ as Wc,j$ as Xc,y$ as Yc,g$ as Zc,S$ as _c,I$ as $c,m$ as ad,v$ as bd,P$ as cd,u$ as dd,h$ as ed,l$ as fd,c$ as gd,p$ as hd,n$ as id,d$ as jd,i$ as kd,r$ as ld,o$ as md,a$ as nd,t$ as od,s$ as pd,e$ as qd,n1 as rd,h4 as sd,P0 as td,r1 as ud,JW as vd,QW as wd,t1 as xd,GW as yd,L0 as zd,LW as Ad,h0 as Bd,e1 as Cd,_2 as Dd,HW as Ed,NW as Fd,qW as Gd,e4 as Hd,O2 as Id,J2 as Jd,_X as Kd,TW as Ld,k_ as Md,r0 as Nd,o0 as Od,N_ as Pd,N0 as Qd,jW as Rd,yW as Sd,gW as Td,SW as Ud,L2 as Vd,IW as Wd,lW as Xd,F2 as Yd,q2 as Zd,dW as _d,z2 as $d,iW as ae,gX as be,RO as ce,wO as de,e2 as ee,t as fe,Y_ as ge,q as he};
@@ -1,4 +1,4 @@
1
- import{vc as U8}from"./chunk-wm896gnx.js";import{$d as T6,Ac as i1,Cc as z$,Dd as y2,Ed as q8,Fd as G8,Gd as Q6,Hd as t1,Id as L8,Jd as F8,Kd as c1,Od as lJ,Xd as u0,Zd as S6,_d as n1,ge as W1,sd as _2,ud as A2,vd as b2,wc as U$,wd as B6,xd as D6,yc as w$,zc as N2}from"./chunk-g6v3ff0v.js";import{le as w8}from"./chunk-9xbwtjac.js";import{De as E0,oe as q0,re as V2,se as C$}from"./chunk-vz13c7fr.js";import{cg as C2}from"./chunk-7xhw74hk.js";import{dg as B8,eg as r0,fg as X8,gg as uJ,ig as d1,jg as E6,kg as mJ,lg as dJ,og as cJ}from"./chunk-k1tfry97.js";import{ah as Y$,bh as n0,eh as D8}from"./chunk-ewwrss2w.js";import{jh as n2,nh as J2}from"./chunk-53vh6vpt.js";import{yh as E$}from"./chunk-dd4gev98.js";import{Ti as R$}from"./chunk-sd9bze9x.js";import{aj as j0}from"./chunk-jsv3e4k6.js";import{Cj as T0}from"./chunk-5q4z0sfr.js";import{Wj as P2}from"./chunk-5w1bzrx1.js";import{Ak as GJ,Bk as s1,Dk as L2,Ik as F2,Jk as O2,ek as G2,tk as B2,uk as D2,xk as K1}from"./chunk-7xtxvrh8.js";import{Lk as mZ}from"./chunk-sdapqhj0.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],XJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},o8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},a8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],Z9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
1
+ import{wc as U8}from"./chunk-zzvs471p.js";import{$d as n1,Ac as N2,Bc as i1,Dc as z$,Ed as y2,Fd as q8,Gd as G8,Hd as Q6,Id as t1,Jd as L8,Kd as F8,Ld as c1,Pd as lJ,Yd as u0,_d as S6,ae as T6,he as W1,td as _2,vd as A2,wd as b2,xc as U$,xd as B6,yd as D6,zc as w$}from"./chunk-7veb9t8x.js";import{me as w8}from"./chunk-53fc0yrq.js";import{Ee as E0,pe as q0,se as V2,te as C$}from"./chunk-y5wngtz0.js";import{dg as C2}from"./chunk-t0gm0pn1.js";import{eg as B8,fg as r0,gg as X8,hg as uJ,jg as d1,kg as E6,lg as mJ,mg as dJ,pg as cJ}from"./chunk-1yq72zb7.js";import{bh as Y$,ch as n0,fh as D8}from"./chunk-3kszepm6.js";import{kh as n2,oh as J2}from"./chunk-wcps5gjm.js";import{zh as E$}from"./chunk-hxyf4erv.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as T0}from"./chunk-2mk914vk.js";import{Xj as P2}from"./chunk-mcnptqmc.js";import{Bk as GJ,Ck as s1,Ek as L2,Jk as F2,Kk as O2,fk as G2,uk as B2,vk as D2,yk as K1}from"./chunk-4wx5sya5.js";import{Mk as mZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function b$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class I1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(b$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!b$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!b$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...E0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(b$),this._history=$.filter((Z)=>!y$(Z)&&!b$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function s6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function t6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function e6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import V$ from"node:path";var R8=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),M8=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function t$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(!R8.has(X))break;Z=Y}return Z}function l5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match($J);if(!K)break;let X=K[1];if(M8.test(X))break;Z=Y}return Z}var k8=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function RZ($){let Z=$,J=!0;while(J){J=!1;for(let W of k8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function e$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function ZJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function H$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var x8=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),I8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),h8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function v8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function C8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=H$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=V$.isAbsolute(K)?V$.resolve(K):V$.resolve(J,K);if(!z$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function g8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function p8($){let Z=H$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function u8($){let Z=WJ($.replace(h8,"").trim()),J=g8(Z);if(!J)return;if(J.length===0)return YJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=WJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!p8(K))return;return YJ(Y)}function YJ($){let J=e$($)?.at(-1);if(!J)return $;let W=H$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function f$($,Z){let J=u8($);if(!J)return!1;let W=t$(J),Y=e$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:C8(W,Y,Z);if(!K)return!1;let X=H$(K);if(X.length===0||X.some((z)=>[...I8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[Q,H,V]=X;if(x8.has(Q??""))return v8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&JJ.has(H??""))return!0;if(JJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function a5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!V$.isAbsolute($);let J=V$.isAbsolute($)?V$.resolve($):V$.resolve(Z,$);return z$.isWithinWorkspace(J,Z)}var MZ=T0("Agent"),m8=3;function kZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=m8)return{action:"truncated"};if(s6(J)==="stop")return MZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var d8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],c8=/```[\s\S]{50,}```/,KJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",l8=2;function xZ($,Z,J=!0){if(!$||Z>=l8)return{action:"none"};if(!J&&c8.test($))return{action:"retry",prompt:KJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(d8.some((X)=>X.test(W)))return{action:"retry",prompt:KJ};return{action:"none"}}var h1=2,i8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",r8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function IZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((L)=>!["id","type",...H?["function"]:["name","arguments"]].includes(L)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((L)=>L!=="name"&&L!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let B=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i"),w=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${B}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${B}(?![\\w:-])`,"i");if(!j.test(Y)||w.test(Y))return{action:"none"};X.add(V.name)}return W<h1?{action:"retry",prompt:r8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:i8}}var n8=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],XJ={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},o8={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},a8="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",s8="Required verification did not run successfully before the retry limit.",t8=3;function HJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&f$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&f$(K,W))$.add(K)}function hZ($,Z,J){if(!$||!n8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(XJ).filter((H)=>XJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>o8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>f$(H)))return{action:"none"};if(J>=t8)return{action:"fail",message:s8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${a8}${Q}`}}var e8=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],VJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function zJ($){return typeof $==="string"&&VJ.some((Z)=>Z.test($))}var $9=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],Z9=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function J9($){if(typeof $!=="string")return;if(Z9.some((Z)=>Z.test($)))return"multiple-allowed";return $9.some((Z)=>Z.test($))?"required":void 0}function Z1($){for(let Z of $){let J=J9(Z);if(J!==void 0)return J==="required"}return!1}var W9="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",Y9="Required delegation did not complete before the retry limit.",K9=3;function jJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Z1(W),K=!1;if(!Y)for(let X of W){if(VJ.some((Q)=>Q.test(X)))break;if(e8.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=K9)return{action:"fail",message:Y9};return{action:"retry",prompt:W9}}var X9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H9=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function BJ($){return H9.reduce((Z,J)=>Z.replace(J," "),$)}function v1($){if(typeof $!=="string")return!1;let Z=BJ($);return X9.some((J)=>J.test(Z))}var V9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",j9="Required worktree lifecycle did not complete before the retry limit.",B9=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=BJ($);if(!v1(W))return{action:"none"};let Y=Q9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=B9)return{action:"fail",message:j9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?V9:z9}}var QJ=30000;async function vZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),QJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return MZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return MZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function D9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var w9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function U9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function q9($){let Z=$;for(let H of w9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function wJ($){return q9(U9($))}import{EventEmitter as G9}from"events";import UJ from"node:path";function CZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=CZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function V3($,Z){return qJ($)===qJ(Z)}class S$ extends G9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!S$.instance)S$.instance=new S$;return S$.instance}publish($,Z,J,W){let Y=CZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var J1=S$.getInstance();var $$=T0("Agent"),C1=new Set;async function L9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(C1.has(J))return;if(C1.size>=5000)C1.clear();C1.add(J);try{let W=$.workspaceRoot,Y=await W1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=wJ(Z);if(!K)return;await W1.updateSessionMetadata(J,Y.projectPath,{title:K}),J1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var gZ=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,j$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",LJ="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class T$ extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function B$($){return $.executionEngine?.getContextManager()}async function i0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=B$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)L9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new T$("user_message",{cause:Q})}return null}async function C0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=B$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new T$("assistant_message",{cause:H})}return null}async function FJ($,Z,J){try{let W=B$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",gZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function OJ($,Z,J,W,Y){try{let K=B$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function pZ($,Z,J,W,Y,K={}){try{let X=B$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function g1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=B$($);if(z&&Z.sessionId){let B=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function Y1($,Z,J,W,Y={}){try{let K=B$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await C0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:E0};W.appendControl("user",z);let B=await i0(Z,J,Q,H,E0);if(B)H=B}return H}import{createHash as R6}from"node:crypto";import{promises as i9}from"node:fs";import r9 from"node:path";import{nanoid as J$}from"nanoid";import*as t from"node:fs/promises";import*as Z$ from"node:path";import NJ from"write-file-atomic";var PJ={enabled:!0,maxIndexLines:200};var F9="memory",uZ="MEMORY.md",dZ="<!-- blade:auto-memory-topics:start -->",p1="<!-- blade:auto-memory-topics:end -->",O9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},P9=new R$,_J;function bJ($){return $.trim().replace(/\s+/g," ")}function N9($){return bJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function _9($){return[dZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),p1].join(`
4
4
  `)}function A9($,Z){let J=_9(Z),W=$.indexOf(dZ),Y=$.indexOf(p1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+p1.length);if(!$)return`${J}
@@ -93,7 +93,7 @@ Full output saved to: ${Q}`}catch{return`${Z}
93
93
  ${Y}`}}function W2(){return{successfulBash:!1}}function w4($){return typeof $==="string"&&J2.some((Z)=>Z===$)}function O7($){switch($){case"timeout":case"admission":case"spawn":case"finalization":return $;case"unavailable":return"terminal";default:return}}function P7($){return["<goal-execution-host-failure>",`Category: ${$.category}`,`Consecutive turns: ${$.consecutiveCount}/3`,"</goal-execution-host-failure>","","The execution host has failed in consecutive Goal turns. Do not blindly","repeat the same command path. Validate shell, sandbox, and terminal","availability, then switch to a different executable strategy or call","UpdateGoal blocked with concrete evidence if external intervention is required."].join(`
94
94
  `)}function Y2($,Z,J){if(Z!=="Bash")return;if(J.success){$.successfulBash=!0;return}let W=J.metadata?.execution_host_failure;if(w4(W))$.category=W}function K2($){return $.successfulBash?void 0:$.category}import h4 from"node:path";import{nanoid as v4}from"nanoid";import{randomUUID as j1}from"node:crypto";import*as g0 from"node:fs/promises";import*as z2 from"node:path";import{Mutex as O4}from"async-mutex";import P4 from"write-file-atomic";var X2=120,W6=128;function z1($){if(!Array.isArray($)||$.length>120||!$.every((Z)=>typeof Z==="string"&&Z.length>0&&Z.length<=128))return;return[...new Set($)]}function U4($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let Z=$.recovery;if(typeof Z!=="object"||Array.isArray(Z))return[];if(!("version"in Z)||Z.version!==1&&Z.version!==2&&Z.version!==3||!("inputMessageIds"in Z)||!("hadSuccessfulToolResult"in Z)||typeof Z.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in Z)||typeof Z.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if((Z.version===2||Z.version===3)&&(!("interruptedToolCallCount"in Z)||!Number.isSafeInteger(Z.interruptedToolCallCount)||Z.interruptedToolCallCount<0))return[];if(Z.version===3&&(!("allSuccessfulToolResultsSafeForResume"in Z)||typeof Z.allSuccessfulToolResultsSafeForResume!=="boolean"))return[];let J=z1(Z.inputMessageIds),W=z1($.acknowledgedInputMessageIds);if(!J||!W)return[];let Y=new Set(J);return W.filter((K)=>Y.has(K))}function l1($,Z){let J=$[Z];if(J?.type!=="turn_aborted")return[];let W=U4(J.data);if(W.length===0)return[];let Y=-1;for(let X=Z-1;X>=0;X--){let Q=$[X];if(Q.type==="turn_started"){if(Q.data.turnId!==J.data.turnId)return[];Y=X;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let K=new Set;for(let X=Y+1;X<Z;X++){let Q=$[X];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let H=Q.data.metadata,V=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:H!==null&&typeof H==="object"&&!Array.isArray(H)?H.inboxMessageId:void 0;if(typeof V==="string"&&V.length>0&&V.length<=128)K.add(V)}return W.filter((X)=>K.has(X))}import*as r1 from"node:fs/promises";import*as H2 from"node:path";var q4={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},G4=new R$,Q2;async function h$($,Z,J,W=F4){let Y=w$($,Z);return G4.runExclusive(Y,()=>i1($,Z,async(K)=>{let X=H2.dirname(K.inboxPath);await r1.mkdir(X,{recursive:!0,mode:448}),await r1.chmod(X,448);let Q,H=await W(K.inboxPath,{...q4,onCompromised:(V)=>{Q=V}});try{if(Q)throw Q;let V=await J(K);if(Q)throw Q;return V}finally{await H()}}))}async function L4(){return Q2??=await import("proper-lockfile"),Q2}async function F4($,Z){return(await L4()).lock($,Z)}var X6=2,v$=8388608;function Y6($,Z,J){let W={version:X6,sessionId:$,generation:Z,messages:J.map(({recovered:Y,...K})=>K)};return`${JSON.stringify(W)}
95
95
  `}function K6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function N4($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((Z)=>{if(!Z||typeof Z!=="object"||!("type"in Z))return!1;if(Z.type==="text")return"text"in Z&&typeof Z.text==="string";return Z.type==="image_url"&&"image_url"in Z&&typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string"})}function _4($,Z,J){let W;try{W=JSON.parse($)}catch(K){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:K})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==X6||!("sessionId"in W)||W.sessionId!==J||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${Z}`);let Y=W.messages.map((K)=>{if(!K||typeof K!=="object"||!("id"in K)||typeof K.id!=="string"||!("content"in K)||!N4(K.content)||!("queuedAt"in K)||typeof K.queuedAt!=="number"||"persisted"in K&&typeof K.persisted!=="boolean"||"origin"in K&&K.origin!=="user"&&K.origin!=="background_subagent"&&K.origin!=="team_message"&&K.origin!=="interaction_recovery"&&K.origin!=="user_shell"||"metadata"in K&&(K.metadata===null||typeof K.metadata!=="object"||Array.isArray(K.metadata))||"outputSchema"in K&&K.outputSchema!==void 0&&(!K.outputSchema||typeof K.outputSchema!=="object"||Array.isArray(K.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let X="outputSchema"in K&&K.outputSchema!==void 0?n1(K.outputSchema).schema:void 0;return{id:K.id,content:K.content,queuedAt:K.queuedAt,..."persisted"in K&&K.persisted===!0?{persisted:!0}:{},..."origin"in K&&K.origin?{origin:K.origin}:{},..."metadata"in K&&K.metadata?{metadata:JSON.parse(JSON.stringify(K.metadata))}:{},...X?{outputSchema:X}:{}}});if(new Set(Y.map((K)=>K.id)).size!==Y.length)throw Error(`Duplicate steering inbox message: ${Z}`);if(W.version===1)return{version:1,sessionId:J,messages:Y};if(!("generation"in W)||typeof W.generation!=="string"||!/^[a-f0-9-]{36}$/.test(W.generation))throw Error(`Invalid steering inbox generation: ${Z}`);return{version:X6,sessionId:J,generation:W.generation,messages:Y}}function A4($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return l1($,J);return[]}))}function b4($){return new Set($.flatMap((Z)=>{if(Z.type!=="message_created"||Z.data.role!=="user")return[];let J=Z.data.metadata,W=Z.data.inboxMessageId!==void 0?Z.data.inboxMessageId:J!==null&&typeof J==="object"&&!Array.isArray(J)?J.inboxMessageId:void 0;return typeof W==="string"?[W]:[]}))}class o1{sessionId;stateStorage;writeFile;lockFile;mutex=new O4;generation=j1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=U$($),W={}){let Y=new o1(Z,J,W.writeFile??P4,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await h$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.messages.some((H)=>H.id===$.id))return{accepted:!0,snapshot:Y};if(Z&&!Z(Y.messages))return{accepted:!1,snapshot:Y};let K=[...Y.messages,{...$,recovered:!1}],X=j1(),Q=Y6(this.sessionId,X,K);if(Buffer.byteLength(Q)>v$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(K,X,W,Q),{accepted:!0,snapshot:{generation:X,messages:K}}},this.lockFile);return this.install(J.snapshot),J.accepted})}async acknowledge($){if($.length===0)return;let Z=new Set($);await this.mutex.runExclusive(async()=>{let J=await h$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),K=Y.messages.filter((Q)=>!Z.has(Q.id));if(K.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let X=j1();return await this.persistAtPath(K,X,W),{generation:X,messages:K}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await h$(this.stateStorage,this.sessionId,(Z)=>this.readAndReconcileAtPath(Z),this.lockFile);return this.install($),this.snapshot()})}async replace($,Z){return this.mutex.runExclusive(async()=>{let J=await h$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let K=j1(),X=Z.map((H)=>({...H})),Q=Y6(this.sessionId,K,X);if(Buffer.byteLength(Q)>v$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(X,K,W,Q),{replaced:!0,snapshot:{generation:K,messages:X}}},this.lockFile);return this.install(J.snapshot),{replaced:J.replaced,snapshot:this.snapshot()}})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((Z)=>Z.type==="text"?{...Z}:{...Z,image_url:{...Z.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $=await h$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=j1();return await this.persistAtPath(J.messages,W,Z),{generation:W,messages:J.messages}}return J},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let Z;try{let X=await g0.open($.inboxPath,"r");try{if((await X.stat()).size>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${$.inboxPath}`);Z=_4(await X.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await X.close()}await g0.chmod($.inboxPath,384)}catch(X){if(!K6(X,"ENOENT"))throw X}let J=new Set,W=new Set;try{let X=V2(await g0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=A4(X),W=b4(X)}catch(X){if(!K6(X,"ENOENT"))throw X}let Y=new Map(this.messages.map((X)=>[X.id,X.recovered])),K=(Z?.messages??[]).filter((X)=>!J.has(X.id)).map((X)=>({...X,recovered:Y.get(X.id)??!0,...X.persisted===!0||W.has(X.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:K,...Z?.version===1&&K.length>0?{migrationRequired:!0}:{},...Z&&K.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await g0.mkdir(z2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await g0.unlink(J.inboxPath).catch((K)=>{if(!K6(K,"ENOENT"))throw K});return}let Y=W??Y6(this.sessionId,Z,$);if(Buffer.byteLength(Y)>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as p0 from"node:fs/promises";import*as f2 from"node:path";import{nanoid as B0}from"nanoid";var j2=256;class N0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,Z,J){this.sessionId=$;this.projectPath=Z;this.storage=J}static for($,Z,J=U$(Z)){let W=w$(J,$),Y=N0.instances.get(W);if(!Y)Y=new N0($,Z,J),N0.instances.set(W,Y),N0.pruneIdleInstances(W);else N0.instances.delete(W),N0.instances.set(W,Y);return Y}static release($,Z,J=U$(Z)){N0.instances.delete(w$(J,$))}static pruneIdleInstances($){if(N0.instances.size<=j2)return;for(let[Z,J]of N0.instances){if(Z===$||J.subscribers.size>0)continue;if(N0.instances.delete(Z),N0.instances.size<=j2)return}}get lastSeq(){return this.highestSeq}async readAll(){return this.withStore(async($,Z,J)=>{let W=Z?await $.readAllValidated(Z):await $.readAll();return J(W),W})}async commit($){let[Z]=await this.commitEntries([$]);return this.record(Z),Z}async commitBatch($){if($.length===0)return[];let Z=await this.commitEntries($);for(let J of Z)this.record(J);return Z}async commitValidated($){let Z=await this.withStore((J,W,Y)=>J.appendValidated((K)=>{return Y(K),$(K)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((K)=>{return Y(K),$(K)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);J1.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,Z){if(this.subscribers.add($),Z?.fromSeq!==void 0)this.replay($,Z.fromSeq);return()=>{this.subscribers.delete($),N0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,K)=>{let X=Y?await W.readAllValidated(Y):await W.readAll();return K(X),X.filter((Q)=>(Q.seq??0)>=Z)});for(let W of J){if(Q6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(Q6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}J1.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}commitEntries($){return this.withStore((Z,J,W)=>J?Z.appendValidatedBatch((Y)=>{return W(Y),$},J):Z.appendBatch($))}withStore($){return i1(this.storage,this.sessionId,async(Z)=>{let J=new C$(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(X)=>{await B2(W,Z.transcriptPath,X)}},(X)=>{D2(X,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function q$($){let Z=null,J=null;for(let W of $){if(W.type==="turn_started"){Z=W.data;continue}if(W.type==="turn_completed")J={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")J={type:"turn_aborted",data:W.data};else continue;if(Z?.turnId===J.data.turnId)Z=null}return{active:Z,lastTerminal:J}}class S0 extends Error{}var y4="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function H6($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return!1;return $.slice(J+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function w2($,Z){let J=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===Z);if(J<0)return[];let W=[];for(let Y of $.slice(J+1)){if(Y.type==="turn_started"&&Y.data.turnId!==Z||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===Z)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let K=Y.data.metadata,X=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:K!==null&&typeof K==="object"&&!Array.isArray(K)?K.inboxMessageId:void 0;if(typeof X==="string"&&X.length>0&&X.length<=W6)W.push(X)}return[...new Set(W)]}function E2($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let Z="inputMessageIds"in $?z1($.inputMessageIds):void 0;if(!Z||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let J=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(J===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:Z,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:J,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function f4($,Z){let J=$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((Q,H)=>H>J&&Q.type==="turn_started"&&Q.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),K=new Set(Y.flatMap((Q)=>{if(Q.type!=="part_created"||Q.data.partType!=="tool_call")return[];let H=Q.data.payload;return H&&typeof H==="object"&&!Array.isArray(H)?[typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId]:[Q.data.partId]})),X=new Set;for(let Q of Y){if(Q.type!=="part_created"||Q.data.partType!=="tool_result")continue;let H=Q.data.payload;if(!H||typeof H!=="object"||Array.isArray(H))continue;let V=typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId,z=H.metadata;if(K.has(V)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)X.add(V)}return X.size}function S2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return l1($,J);return[]}))}function V6($,Z,J=[]){let W=E2(Z.data.recovery);if(!W)return;if($.some((Q)=>Q.type==="turn_recovery_acknowledged"&&Q.data.turnId===Z.data.turnId))return;let Y=S2($);for(let Q of J)Y.add(Q);let K=W.inputMessageIds.filter((Q)=>!Y.has(Q)),X=W.version===1?f4($,Z.data.turnId):W.interruptedToolCallCount;if(K.length===0&&!W.hadSuccessfulToolResult&&X===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:K,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...X>0?{interruptedToolCallCount:X}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function B1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=V6($,J);if(W)return W}return}function a1($,Z){let J=$.input,W=Z?.metadata,Y=Z?.subagentRef;if($.toolName!=="Task"||Z?.toolCallId!==$.toolCallId||Z.toolName!=="Task"||J===null||typeof J!=="object"||Array.isArray(J)||W===null||typeof W!=="object"||Array.isArray(W)||!Y)return!1;let{subagent_session_id:K,subagent_type:X,description:Q}=J,H=Y.subagentStatus==="completed"&&Z.error===void 0&&typeof Z.output==="string"||Y.subagentStatus==="failed"&&typeof Z.error==="string"&&Z.error.length>0&&Z.output===null;return typeof K==="string"&&K===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof Q==="string"&&Y.subagentDescription===Q&&W.description===Q&&(X===void 0||typeof X==="string"&&X===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&H&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var E4=1e4,S4=1e5,T4=2592000000,U2=128,R4=1e6,M4=256;function k4($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>U2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>R4||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>U2||typeof Z.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(Z.evidenceSha256)||typeof Z.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(Z.goalUpdatedAt)))return;return{goalId:Z.goalId,verificationAttempt:Z.verificationAttempt,verifierSessionId:Z.verifierSessionId,evidenceSha256:Z.evidenceSha256,goalUpdatedAt:Z.goalUpdatedAt}}function T2($,Z){let J=$.data.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let W=J.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,K=Y.turnId,X=Y.inputMessageIds,Q=Y.turnsCount,H=Y.toolCallsCount,V=Y.durationMs,z=Array.isArray(X)?X.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=W6):[];if(typeof K!=="string"||K.length===0||K.length>128||Z!==void 0&&K!==Z||!Array.isArray(X)||X.length>X2||z.length!==X.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>E4||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>S4||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>T4)return;let B;if("goalFinalization"in Y){if(B=k4(Y.goalFinalization),!B)return}return{turnId:K,inputMessageIds:[...new Set(z)],turnsCount:Q,toolCallsCount:H,durationMs:V,...B?{goalFinalization:B}:{}}}function q2($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return;for(let W=$.length-1;W>J;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let K=T2(Y,Z);if(K)return K}return}function x4($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=T2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((K)=>K.type==="turn_started"&&K.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function g$($,Z){let J=Z?$.findLastIndex((H)=>H.type==="turn_started"&&H.data.turnId===Z):-1;if(Z&&J<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,K=new Set,X=new Set;for(let H of $.slice(J+1)){if(H.type==="interaction_requested"){X.add(H.data.toolCallId);continue}if(H.type!=="part_created")continue;let V=H.data.payload&&typeof H.data.payload==="object"&&!Array.isArray(H.data.payload)?H.data.payload:{},z=typeof V.toolCallId==="string"?V.toolCallId:H.data.partId;if(H.data.partType==="tool_call")W.set(z,{toolCallId:z,messageId:H.data.messageId,toolName:typeof V.toolName==="string"?V.toolName:"unknown",input:V.input??null});else if(H.data.partType==="tool_result"){if(Y.add(z),Y.add(H.data.partId),Y.add(H.data.messageId),W.has(z)&&V.error===null)K.add(z)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((H)=>!Y.has(H.toolCallId)&&!X.has(H.toolCallId)),hadSuccessfulResult:Q.some((H)=>K.has(H.toolCallId))}}class R0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=j0(),Z=100,J=P2(),W=U$($)){this.projectPath=$,this.maxSessions=Z,this.version=J,this.stateStorage=W}createEvent($,Z,J){return{id:B0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:F2(this.projectPath)}:{},version:this.version,data:J}}log($){return N0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=w$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=R0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,J,Z),R0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(R0.sessionInitializationRuns.get(J)===W)R0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>M4){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z,J){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),K={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},X=this.createEvent("session_created",$,K);await this.log($).commit(X)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.reason)Z.reason=$.reason;if($.strategy)Z.strategy=$.strategy;if($.preTokenSource)Z.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)Z.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.sampleAttempts!==void 0)Z.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)Z.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)Z.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)Z.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)Z.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)Z.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)Z.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)Z.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)Z.failureReason=$.failureReason;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;if($.replacementMessages)Z.checkpointVersion=A2;return Z}async initialize(){try{await N2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await p0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,K,X){try{await this.ensureSessionCreated($,K);let Q=new Date().toISOString(),H=B0(),V={messageId:H,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,V),B=Z==="assistant"&&X?.trim()?[this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:"reasoning",payload:{text:X},createdAt:Q})]:[],j=typeof J==="string"?[this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:"text",payload:{text:J},createdAt:Q})]:J.map((w)=>this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:I4(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:Q}));return await this.log($).commitBatch([z,...B,...j]),H}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,Z){if(Z.length===0)return;await this.ensureSessionCreated($);let J=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...Z],acknowledgedAt:J}))}async acknowledgeTurnRecovery($,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=q0(J);if(W.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z))throw new S0;let Y=W.findLast((K)=>K.type==="turn_aborted"&&K.data.turnId===Z);if(!Y||!V6(W,Y))throw new S0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof S0))throw J}}async persistBackgroundSubagentCompletion($,Z){if(Z.inboxMessageId!==`background-subagent-completion:${Z.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let J={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(Z.inboxMessageId)),X=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===Z.inboxMessageId),Q=Y.findLast((j)=>{if(j.type!=="part_created"||j.data.partType!=="tool_call"||!j.data.payload||typeof j.data.payload!=="object"||Array.isArray(j.data.payload))return!1;let w=j.data.payload;if(w.toolName!=="Task"||!w.input||typeof w.input!=="object"||Array.isArray(w.input))return!1;let L=w.input,A=L.resume_from??L.resume;return L.run_in_background===!0&&L.subagent_session_id===Z.childSessionId&&L.description===Z.subagentRef.subagentDescription&&(L.subagent_type===void 0||L.subagent_type===Z.subagentRef.subagentType)&&(L.resume_from===void 0||L.resume===void 0||L.resume_from===L.resume)&&(A===void 0?Z.subagentRef.subagentResumedFrom===void 0:A===Z.subagentRef.subagentResumedFrom)});if(!Q)return J={eligible:!1,acknowledged:K,persisted:!1,...X?{messageId:X.data.messageId}:{}},[];if(K)return J={eligible:!0,acknowledged:!0,persisted:!1,...X?{messageId:X.data.messageId}:{}},[];let H=Y.find((j)=>j.type==="part_created"&&j.data.partType==="subtask_ref"&&j.data.payload!==null&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)&&j.data.payload.childSessionId===Z.childSessionId&&j.data.payload.status===Z.subagentRef.subagentStatus);if(X&&H)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:X.data.messageId},[];let V=new Date().toISOString(),z=X?.data.messageId??B0(),B=[];if(!X){let j={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:V,metadata:JSON.parse(JSON.stringify(Z.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:B0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:V}))}if(!H){let j=Y.findLast((L)=>L.type==="part_created"&&L.data.partType==="subtask_ref"&&L.data.messageId===Q.data.messageId&&L.data.payload!==null&&typeof L.data.payload==="object"&&!Array.isArray(L.data.payload)&&L.data.payload.childSessionId===Z.childSessionId),w=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;B.push(this.createEvent("part_created",$,{partId:B0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:Z.subagentRef.subagentSessionId,agentType:Z.subagentRef.subagentType,description:Z.subagentRef.subagentDescription??"",status:Z.subagentRef.subagentStatus,summary:Z.subagentRef.subagentSummary??"",resumedFrom:Z.subagentRef.subagentResumedFrom??null,rootAgentId:Z.subagentRef.subagentRootId??Z.subagentRef.subagentSessionId,resumeDepth:Z.subagentRef.subagentResumeDepth??0,verificationVerdict:Z.subagentRef.verificationVerdict??null,startedAt:typeof w?.startedAt==="string"?w.startedAt:V,finishedAt:V},createdAt:V}))}return J={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),J}async saveTurnStart($,Z){if(Z.goalLineage&&Z.goalLineage.currentTurnId!==Z.turnId)throw Error("Goal lineage current turn must match turn start");await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=q0(J);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===Z.turnId))throw new S0;let Y=q$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,Z)})}catch(J){if(!(J instanceof S0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=new Set(Y.flatMap((V)=>V.type==="inbox_acknowledged"?V.data.messageIds:[])),X=[...new Set(J)].filter((V)=>!K.has(V)),Q=Y.findLast((V)=>(V.type==="turn_completed"||V.type==="turn_aborted")&&V.data.turnId===Z.turnId);if(Q){if(Q.type==="turn_aborted"||X.length===0)throw new S0;return[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]}let H=q$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...X.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof S0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=z1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let K=Y;await this.ensureSessionCreated($);let X,Q=[];try{await this.log($).commitValidatedBatch((H)=>{let V=q0(H),z=S2(V),B=V.findLast((g)=>(g.type==="turn_completed"||g.type==="turn_aborted")&&g.data.turnId===Z.turnId);if(B){if(B.type==="turn_completed")throw X=void 0,Q=[],new S0;let g=E2(B.data.recovery),A0=g?K.filter((F0)=>g.inputMessageIds.includes(F0)):[],Z0=A0.filter((F0)=>!z.has(F0));if(Q=A0,X=V6(V,B,A0),Z0.length===0)throw new S0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Z0,acknowledgedAt:Z.abortedAt})]}let j=q$(V).active;if(!j||j.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let w=g$(V,j.turnId),L=w2(V,j.turnId),A=B1(V),E=new Set(Z.recovery?.inputMessageIds??[]),S=A?A.inputMessageIds.filter((g)=>E.has(g)):[],T=[...new Set([...L,...S])],p=w.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,k={version:3,inputMessageIds:T,hadSuccessfulToolResult:p,interruptedToolCallCount:w.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:p&&!w.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:H6(V,j.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};X={turnId:Z.turnId,outcome:"aborted",inputMessageIds:k.inputMessageIds,hadSuccessfulToolResult:k.hadSuccessfulToolResult,...k.interruptedToolCallCount>0?{interruptedToolCallCount:k.interruptedToolCallCount}:{},...k.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:k.emptyFinalCorrectionSpent};let $0=K.filter((g)=>T.includes(g)),a=$0.filter((g)=>!z.has(g));Q=$0;let R=new Set(z);for(let g of $0)R.add(g);let G=k.inputMessageIds.filter((g)=>!R.has(g)),r=k.hadSuccessfulToolResult||k.interruptedToolCallCount>0;X=G.length>0||r?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:G,hadSuccessfulToolResult:k.hadSuccessfulToolResult,...k.interruptedToolCallCount>0?{interruptedToolCallCount:k.interruptedToolCallCount}:{},...k.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:k.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:L0,...v}=Z;return[this.createEvent("turn_aborted",$,{...v,...$0.length>0?{acknowledgedInputMessageIds:$0}:{},recovery:k}),...a.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:a,acknowledgedAt:Z.abortedAt})]:[]]})}catch(H){if(!(H instanceof S0))throw H}return{...X?{recovery:X}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=q0(Z),W=q$(J).active;return W?g$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=q0(Z),W=q$(J).active;if(W){let Y=g$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(q2(J,W.turnId))return!0}return B1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=q0(Z).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let K=Y.input;return K.run_in_background===!0&&typeof K.subagent_session_id==="string"?[K.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=q$(Y).active,X=g$(Y);if(!K&&X.orphaned.length===0){if(J=B1(Y),J)return[];throw new S0}let Q=K?q2(Y,K.turnId):void 0;if(K&&Q&&X.orphaned.length===0){let R=g$(Y,K.turnId);J={turnId:K.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:R.hadSuccessfulResult,emptyFinalCorrectionSpent:H6(Y,K.turnId),finalization:Q};let G=new Set(Y.flatMap((v)=>v.type==="inbox_acknowledged"?v.data.messageIds:[])),r=Q.inputMessageIds.filter((v)=>!G.has(v)),L0=new Date().toISOString();return[...r.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:r,acknowledgedAt:L0})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:L0,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let H=K?g$(Y,K.turnId):void 0,V=H?.orphaned.some((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId);return a1(R,G)&&G?.error===void 0})??!1,z=H?.orphaned.filter((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId);return G?.toolCallId===R.toolCallId&&G.toolName===R.toolName&&G.error===void 0}).every((R)=>a1(R,Z.adoptedToolResults?.get(R.toolCallId)))??!0,B=new Set(K?.inputMessageIds??[]),j=K?B1(Y):void 0,w=j?j.inputMessageIds.filter((R)=>B.has(R)):[],L=w.length>0,A=K?w2(Y,K.turnId):[],E=H?H.orphaned.filter((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId);return!a1(R,G)}).length:0,S=L&&j?.hadSuccessfulToolResult===!0,T=(H?.hadSuccessfulResult??!1)||V||S;J=K?{turnId:K.turnId,outcome:"aborted",inputMessageIds:[...new Set([...A,...w])],hadSuccessfulToolResult:T,...(()=>{let R=E+(L?j?.interruptedToolCallCount??0:0);return R>0?{interruptedToolCallCount:R}:{}})(),...T&&!(H?.hadSuccessfulResult??!1)&&z&&(!S||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:H6(Y,K.turnId)||L&&j?.emptyFinalCorrectionSpent===!0}:B1(Y);let p=K?H?.all.length??0:0,k=new Date().toISOString(),$0=K?Date.parse(K.startedAt):Number.NaN,a=X.orphaned.flatMap((R)=>{let G=Z.adoptedToolResults?.get(R.toolCallId),r=a1(R,G)?G:void 0,L0=this.createEvent("part_created",$,{partId:R.toolCallId,messageId:r?R.messageId:R.toolCallId,partType:"tool_result",payload:r?{toolCallId:R.toolCallId,toolName:R.toolName,output:r.output,error:r.error??null,...r.metadata===void 0?{}:{metadata:r.metadata}}:{toolCallId:R.toolCallId,toolName:R.toolName,output:null,error:y4,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:k});if(!r?.subagentRef)return[L0];let v=r.subagentRef;return[L0,this.createEvent("part_created",$,{partId:B0(),messageId:R.messageId,partType:"subtask_ref",payload:{childSessionId:v.subagentSessionId,agentType:v.subagentType,description:v.subagentDescription??"",status:v.subagentStatus,summary:v.subagentSummary??"",resumedFrom:v.subagentResumedFrom??null,rootAgentId:v.subagentRootId??v.subagentSessionId,resumeDepth:v.subagentResumeDepth??0,verificationVerdict:v.verificationVerdict??null,startedAt:k,finishedAt:k},createdAt:k})]});return K?[...a,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:k,turnsCount:0,toolCallsCount:p,durationMs:Number.isFinite($0)?Math.max(0,Date.now()-$0):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:a})}catch(W){if(!(W instanceof S0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?x4(Z):void 0}async saveInteractionRequest($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===Z.requestId))throw Error(`Interaction request already exists: ${Z.requestId}`);return this.createEvent("interaction_requested",$,Z)})}async saveInteractionResponse($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="interaction_requested"&&K.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((K)=>K.type==="interaction_responded"&&K.data.requestId===Z.requestId))throw Error(`Interaction already responded: ${Z.requestId}`);return this.createEvent("interaction_responded",$,Z)})}async saveInteractionRecovery($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="interaction_responded"&&K.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((K)=>K.type==="interaction_recovered"&&K.data.requestId===Z.requestId))throw Error(`Interaction already recovered: ${Z.requestId}`);return this.createEvent("interaction_recovered",$,Z)})}async saveReviewStart($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((K)=>K.type==="review_started"&&K.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((K)=>K.type==="review_started"&&!J.some((X)=>X.type==="review_completed"&&X.data.reviewId===K.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,Z)})}async saveReviewCompletion($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="review_started"&&K.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((K)=>K.type==="review_completed"&&K.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,K){try{if(K!==void 0&&(K.length===0||K.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let X=new Date().toISOString(),Q=W??B0(),H=[];if(!W){let B={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:X};H.push(this.createEvent("message_created",$,B))}let V=K??B0(),z={partId:V,messageId:Q,partType:"tool_call",payload:{toolCallId:V,toolName:Z,input:J},createdAt:X};if(H.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let B=J,j=typeof B.subagent_session_id==="string"?B.subagent_session_id:void 0,w=typeof B.subagent_type==="string"?B.subagent_type:void 0;if(j&&w){let L={partId:B0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:j,agentType:w,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:X},createdAt:X};H.push(this.createEvent("part_created",$,L))}}return await this.log($).commitBatch(H),V}catch(X){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,X),X}}async saveToolResult($,Z,J,W,Y=null,K,X,Q,H){try{await this.ensureSessionCreated($,X);let V=new Date().toISOString(),z=Y??B0();return await this.log($).commitValidatedBatch((B)=>{let j=Q?.subagentStatus==="running"?q0(B).findLast((T)=>T.type==="part_created"&&T.data.partType==="subtask_ref"&&T.data.payload!==null&&typeof T.data.payload==="object"&&!Array.isArray(T.data.payload)&&T.data.payload.childSessionId===Q.subagentSessionId&&(T.data.payload.status==="completed"||T.data.payload.status==="failed"||T.data.payload.status==="cancelled")):void 0,w=j?.data.payload,L=H&&typeof H==="object"&&!Array.isArray(H)?H:{},A=w?{...L,subagentSessionId:w.childSessionId,subagentType:w.agentType,description:w.description,subagentStatus:w.status,subagentSummary:w.summary,subagentResumedFrom:w.resumedFrom,subagentRootId:w.rootAgentId,subagentResumeDepth:w.resumeDepth,verificationVerdict:w.verificationVerdict}:H,E=[];if(!Y){let T={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:V};E.push(this.createEvent("message_created",$,T))}let S={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:K??null,...A===void 0?{}:{metadata:A}},createdAt:V};if(E.push(this.createEvent("part_created",$,S)),Q&&!j){let T=Q.subagentStatus==="running"?null:V,p={partId:B0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:V,finishedAt:T},createdAt:V};E.push(this.createEvent("part_created",$,p))}return E}),Z}catch(V){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,V),V}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=B0(),X={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(J),H={partId:B0(),messageId:K,partType:"summary",payload:{text:Z,metadata:Q,...J.replacementMessages?{replacementMessages:b2(J.replacementMessages)}:{}},createdAt:Y},V=[this.createEvent("message_created",$,X),this.createEvent("part_created",$,H)];return await this.log($).commitBatch(V),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=t1([]),W=await this.log($).commitValidatedBatch((K)=>{if(J=t1(q0(K)),J.kind!=="none")return[];let X=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${y2}${B0()}`,createdAt:X})]});if(J.kind==="valid")return{outcome:"existing",event:J.event};if(J.kind==="suppressed")return{outcome:"suppressed",recordId:J.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=t1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,Z){await this.ensureSessionCreated($,Z)}async loadEvents($){try{let Z=await this.log($).readAll();return Z.length>0?q0(Z):null}catch{return null}}async loadSession($){try{let Z=q0(await this.log($).readAll());if(Z.length===0)return null;let J=Z.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Z[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=q0(await this.log($).readAll());if(Z.length===0)return null;let J=new Map;for(let X of Z){if(X.type==="message_created")J.set(X.data.messageId,{id:X.data.messageId,role:X.data.role,content:"",timestamp:new Date(X.timestamp).getTime()});if(X.type==="part_created"&&X.data.partType==="text"){let Q=J.get(X.data.messageId);if(Q){let H=X.data.payload;Q.content=H.text??""}}if(X.type==="part_created"&&X.data.partType==="image"){let Q=J.get(X.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
96
- [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],K=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:K}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=K1(this.projectPath);return(await p0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=s1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let K=q0(Y),X=Y[Y.length-1],Q=K.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=s1(this.projectPath,$);await new C$(Z).delete(),await p0.unlink(L2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await _2(this.projectPath,$,G2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-42y6ks44.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=s1(this.projectPath,J),K=await new C$(W).getStats();Z+=K.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=K1(this.projectPath);await p0.mkdir($,{recursive:!0,mode:493});let Z=f2.join($,".health-check");return await p0.writeFile(Z,"test","utf-8"),await p0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return O2()}}function I4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var R2=131072,z6=new R$;function j6($,Z){return`${h4.resolve($)}\x00${Z}`}function w6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>R2)throw Error(`${Z} exceeds ${R2} bytes`);return JSON.parse(J)}function M2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function C4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function g4($,Z){if($.request.interactionType!=="elicitation")return w6(Z,"Interaction response");return w6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function k2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function p4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function u4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
96
+ [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],K=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:K}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=K1(this.projectPath);return(await p0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=s1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let K=q0(Y),X=Y[Y.length-1],Q=K.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=s1(this.projectPath,$);await new C$(Z).delete(),await p0.unlink(L2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await _2(this.projectPath,$,G2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-d420fs8m.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=s1(this.projectPath,J),K=await new C$(W).getStats();Z+=K.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=K1(this.projectPath);await p0.mkdir($,{recursive:!0,mode:493});let Z=f2.join($,".health-check");return await p0.writeFile(Z,"test","utf-8"),await p0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return O2()}}function I4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var R2=131072,z6=new R$;function j6($,Z){return`${h4.resolve($)}\x00${Z}`}function w6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>R2)throw Error(`${Z} exceeds ${R2} bytes`);return JSON.parse(J)}function M2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function C4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function g4($,Z){if($.request.interactionType!=="elicitation")return w6(Z,"Interaction response");return w6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function k2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function p4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function u4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
97
97
  `)}function m4($,Z){let{request:J}=$;if(J.interactionType==="question"){let X=u4(Z);return{toolOutput:`User answers:
98
98
  ${X}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
99
99
  ${X}
@@ -178,4 +178,4 @@ ${b}`}if(typeof x==="object"&&x!==null)x=JSON.stringify(x,null,2);if(typeof x===
178
178
 
179
179
  <system-reminder>
180
180
  ${v2(Q$)}
181
- </system-reminder>`,metadata:E0};G.appendControl("user",U);let D=await i0($,J,U.content,H,E0);if(D)H=D}}if(W?.signal?.aborted)return z(X,Q.length,W.signal)}}catch(F){if(F instanceof T$)try{let O=J.sessionId?await W1.loadSessionModelContext(J.sessionId,J.workspaceRoot):R;G.restoreDurableHistory(O)}catch(O){i.error("[Loop] Failed to reload durable context after message commit failure:",O),G.restoreDurableHistory(R)}throw F}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((F)=>{let O=F.metadata;return O!==null&&typeof O==="object"&&!Array.isArray(O)&&O.transientGoalContinuation===!0});G.writeback()}}catch(B){if(r0(B))return z(X,Q.length,W?.signal);if(B instanceof T$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K}};let j=f5(B);return i.error(`API 调用失败: ${j}`),{success:!1,error:{type:"api_error",message:j,details:B},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K}}}finally{if(V)J.messages.push({role:"system",content:gZ}),await FJ($,J,H)}}export{O7 as wb,P7 as xb,u1 as yb,yJ as zb,t$ as Ab,l5 as Bb,RZ as Cb,e$ as Db,WJ as Eb,u8 as Fb,f$ as Gb,a5 as Hb,q$ as Ib,CZ as Jb,qJ as Kb,V3 as Lb,J1 as Mb,N0 as Nb,R0 as Ob,kZ as Pb,xZ as Qb,HJ as Rb,vZ as Sb,e2 as Tb,$8 as Ub,J8 as Vb,y$ as Wb,I1 as Xb,D9 as Yb,i0 as Zb,C0 as _b,pZ as $b,g1 as ac,Y1 as bc,SJ as cc,o as dc,k$ as ec,o1 as fc,G0 as gc,fW as hc,K8 as ic,XZ as jc,Q8 as kc,H8 as lc,V8 as mc,A5 as nc,y6 as oc,O8 as pc,p5 as qc};
181
+ </system-reminder>`,metadata:E0};G.appendControl("user",U);let D=await i0($,J,U.content,H,E0);if(D)H=D}}if(W?.signal?.aborted)return z(X,Q.length,W.signal)}}catch(F){if(F instanceof T$)try{let O=J.sessionId?await W1.loadSessionModelContext(J.sessionId,J.workspaceRoot):R;G.restoreDurableHistory(O)}catch(O){i.error("[Loop] Failed to reload durable context after message commit failure:",O),G.restoreDurableHistory(R)}throw F}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((F)=>{let O=F.metadata;return O!==null&&typeof O==="object"&&!Array.isArray(O)&&O.transientGoalContinuation===!0});G.writeback()}}catch(B){if(r0(B))return z(X,Q.length,W?.signal);if(B instanceof T$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K}};let j=f5(B);return i.error(`API 调用失败: ${j}`),{success:!1,error:{type:"api_error",message:j,details:B},metadata:{turnsCount:X,toolCallsCount:Q.length,duration:Date.now()-K}}}finally{if(V)J.messages.push({role:"system",content:gZ}),await FJ($,J,H)}}export{O7 as xb,P7 as yb,u1 as zb,yJ as Ab,t$ as Bb,l5 as Cb,RZ as Db,e$ as Eb,WJ as Fb,u8 as Gb,f$ as Hb,a5 as Ib,q$ as Jb,CZ as Kb,qJ as Lb,V3 as Mb,J1 as Nb,N0 as Ob,R0 as Pb,kZ as Qb,xZ as Rb,HJ as Sb,vZ as Tb,e2 as Ub,$8 as Vb,J8 as Wb,y$ as Xb,I1 as Yb,D9 as Zb,i0 as _b,C0 as $b,pZ as ac,g1 as bc,Y1 as cc,SJ as dc,o as ec,k$ as fc,o1 as gc,G0 as hc,fW as ic,K8 as jc,XZ as kc,Q8 as lc,H8 as mc,V8 as nc,A5 as oc,y6 as pc,O8 as qc,p5 as rc};
@@ -1,2 +1,2 @@
1
- import{Wj as I}from"./chunk-5w1bzrx1.js";import{Lk as f}from"./chunk-sdapqhj0.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
1
+ import{Xj as I}from"./chunk-mcnptqmc.js";import{Mk as f}from"./chunk-eg3ms291.js";import*as j from"fs/promises";import*as S from"path";import X from"semver";import{ProxyAgent as R,fetch as k}from"undici";function x(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function L(){let z=x();if(z)try{return new R(z)}catch(q){console.warn(`[proxyFetch] Invalid proxy URL: ${z}`)}return}async function F(z,q,Z){let{timeout:W=30000,signal:J,...Q}=q;if(J?.aborted)throw new DOMException("The operation was aborted.","AbortError");let Y=L(),$=new AbortController,w=!1,y=setTimeout(()=>{w=!0,$.abort()},W),T=()=>$.abort();J?.addEventListener("abort",T);let D;try{let B={method:Q.method,headers:Q.headers,body:Q.body,signal:$.signal,dispatcher:Y};return D=await k(z.toString(),B),await Z(D)}catch(B){if(B instanceof Error&&B.name==="AbortError"){if(w)throw Error(`Request timeout after ${W}ms`);throw B}throw B}finally{if(clearTimeout(y),J?.removeEventListener("abort",T),$.abort(),D?.body&&!D.body.locked)await D.body.cancel().catch(()=>{return});await Y?.destroy?.().catch(()=>{return})}}var O="blade-code",G="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",H=S.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),N=S.join(H,"version-cache.json"),_=3600000,g=`https://registry.npmjs.org/${O}/latest`,M=null;async function P(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return I()}catch{return"unknown"}}async function b(){try{let z=await j.readFile(N,"utf-8"),q=JSON.parse(z);if(Date.now()-q.checkedAt<_)return q;return{...q,checkedAt:0}}catch{return null}}async function K(z){try{await j.mkdir(H,{recursive:!0,mode:493}),await j.writeFile(N,JSON.stringify(z,null,2))}catch{}}async function E(){try{return await F(g,{timeout:5000,headers:{Accept:"application/json"}},async(z)=>{if(!z.ok)return null;let q=await z.json();if(!q||typeof q!=="object"||!("version"in q))return null;return typeof q.version==="string"&&X.valid(q.version)?q.version:null})}catch{return null}}async function A(z=!1){let q=await P(),Z=G;if(q==="unknown")return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to determine current version"};let W=await b(),J=W?.skipUntilVersion,Q=null;if(!z&&W?.latestVersion&&W.checkedAt>0)Q=W.latestVersion;else if(Q=await E(),J=(await b())?.skipUntilVersion??J,Q)await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});else if(W?.latestVersion)await K({checkedAt:0,skipUntilVersion:J});if(!Q||!X.valid(Q))return{currentVersion:q,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:Z,error:"Unable to check for updates"};if(X.lt(Q,q))Q=q,await K({latestVersion:Q,checkedAt:Date.now(),skipUntilVersion:J});let Y=X.gt(Q,q),$=Y;if(Y&&J)$=X.gt(Q,J);return{currentVersion:q,latestVersion:Q,hasUpdate:Y,shouldPrompt:$,releaseNotesUrl:Z}}async function V(z){let q=await b();await K({latestVersion:q?.latestVersion??z,checkedAt:q?.checkedAt||Date.now(),skipUntilVersion:z})}function v(){return`npm install -g ${O}@latest --registry https://registry.npmjs.org`}async function p(){let{spawn:z}=await import("child_process");return new Promise((q)=>{let Z=v(),W=z(Z,{stdio:"inherit",shell:!0});W.on("close",(J)=>{if(J===0)q({success:!0,message:"Upgrade successful! Please restart blade."});else q({success:!1,message:`Upgrade failed (exit code: ${J})`})}),W.on("error",(J)=>{q({success:!1,message:`Upgrade failed: ${J.message}`})})})}async function h(){try{let z=await b();if(!z?.latestVersion||!X.valid(z.latestVersion)||!z.checkedAt){if(!M)M=A(!0).then(()=>{return},()=>{return}).finally(()=>{M=null});return null}let q=await P();if(!X.valid(q)||!X.gt(z.latestVersion,q)||z.skipUntilVersion&&X.valid(z.skipUntilVersion)&&!X.gt(z.latestVersion,z.skipUntilVersion))return null;return{currentVersion:q,latestVersion:z.latestVersion,hasUpdate:!0,shouldPrompt:!0,releaseNotesUrl:G}}catch{return null}}
2
2
  export{A as k,V as l,v as m,p as n,h as o};
@@ -1 +1 @@
1
- import{ab as V,cb as W,db as O,vb as J}from"./chunk-ht8epjz2.js";import"./chunk-fx9vm1n5.js";import"./chunk-f2y0gxyq.js";import"./chunk-53vh6vpt.js";import"./chunk-514va7ce.js";import{aj as Q}from"./chunk-jsv3e4k6.js";import"./chunk-5q4z0sfr.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{bb as V,db as W,eb as O,wb as J}from"./chunk-30x3mcsb.js";import"./chunk-w33zjw8m.js";import"./chunk-kqvzmnja.js";import"./chunk-wcps5gjm.js";import"./chunk-5v0jcyea.js";import{bj as Q}from"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -1,4 +1,4 @@
1
- import{Qa as H}from"./chunk-67pa42n8.js";import"./chunk-wm896gnx.js";import"./chunk-9xbwtjac.js";import{Xf as $,bg as T}from"./chunk-t8w6s1te.js";import"./chunk-v508x7cg.js";import"./chunk-7xhw74hk.js";import"./chunk-dd4gev98.js";import"./chunk-28tzj187.js";import"./chunk-xxktawex.js";import"./chunk-sd9bze9x.js";import"./chunk-514va7ce.js";import{aj as k}from"./chunk-jsv3e4k6.js";import"./chunk-n34qsnks.js";import"./chunk-5q4z0sfr.js";import"./chunk-0b67y4j1.js";import"./chunk-9kj19a8t.js";import"./chunk-5w1bzrx1.js";import"./chunk-gm2yfq3r.js";import"./chunk-n9819k4p.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{Ra as H}from"./chunk-fws2cnbp.js";import"./chunk-zzvs471p.js";import"./chunk-53fc0yrq.js";import{Yf as $,cg as T}from"./chunk-n2qhccts.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-hxyf4erv.js";import"./chunk-3y2x6fb6.js";import"./chunk-sqtt43cv.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as k}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-mcnptqmc.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -0,0 +1 @@
1
+ import{Ag as d,xg as a,yg as b,zg as c}from"./chunk-m0ztysws.js";import"./chunk-sqtt43cv.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-mcnptqmc.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +1 @@
1
- import{$e as m,Pe as a,Qe as b,Re as c,Se as d,Te as e,Ue as f,Ve as g,We as h,Xe as i,Ye as j,Ze as k,_e as l,af as n,bf as o,cf as p,df as q,ef as r}from"./chunk-vz13c7fr.js";import"./chunk-fx9vm1n5.js";import"./chunk-28tzj187.js";import"./chunk-5q4z0sfr.js";import"./chunk-7xtxvrh8.js";import"./chunk-sdapqhj0.js";export{h as syncSession,j as syncAllAcpRemoteScopes,k as syncAll,i as syncAcpRemoteScope,r as searchProjectionText,f as resetProjectionDbCache,l as removeSessionFromProjection,m as rebuildProjectionIndex,q as readSessionSurfaceHistoryPage,o as readSessionSurfaceCatalogRevision,p as readSessionSurfaceCatalogPage,n as readSessionSurfaceCandidates,g as projectSessionSurfaceSummaryFields,c as getSessionSurfaceHistoryByteLimit,e as getProjectionDb,d as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};
1
+ import{$e as l,Qe as a,Re as b,Se as c,Te as d,Ue as e,Ve as f,We as g,Xe as h,Ye as i,Ze as j,_e as k,af as m,bf as n,cf as o,df as p,ef as q,ff as r}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-3y2x6fb6.js";import"./chunk-2mk914vk.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{h as syncSession,j as syncAllAcpRemoteScopes,k as syncAll,i as syncAcpRemoteScope,r as searchProjectionText,f as resetProjectionDbCache,l as removeSessionFromProjection,m as rebuildProjectionIndex,q as readSessionSurfaceHistoryPage,o as readSessionSurfaceCatalogRevision,p as readSessionSurfaceCatalogPage,n as readSessionSurfaceCandidates,g as projectSessionSurfaceSummaryFields,c as getSessionSurfaceHistoryByteLimit,e as getProjectionDb,d as getIndexDbPath,a as __setProjectionIOForTesting,b as __resetProjectionIOForTesting};
@@ -1,2 +1,2 @@
1
1
  var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
2
- export{I as bj,r as cj,t as dj,o as ej,O as fj,P as gj,R as hj,C as ij,M as jj,p as kj,E as lj,T as mj,s as nj,n as oj,D as pj,m as qj,x as rj,S as sj,U as tj,V as uj,A as vj,w as wj,z as xj,F as yj};
2
+ export{I as cj,r as dj,t as ej,o as fj,O as gj,P as hj,R as ij,C as jj,M as kj,p as lj,E as mj,T as nj,s as oj,n as pj,D as qj,m as rj,x as sj,S as tj,U as uj,V as vj,A as wj,w as xj,z as yj,F as zj};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as Lk};
2
+ export{c as Mk};