blade-code 0.10.206 → 0.11.1

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 (171) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-erhaedch.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/{chunk-dnpkf5mv.js → chunk-0b83mt1c.js} +2 -2
  4. package/dist/{chunk-3crwyd2r.js → chunk-0wcnkxe8.js} +2 -2
  5. package/dist/{chunk-gz84aewr.js → chunk-1beqtjsw.js} +1 -1
  6. package/dist/chunk-1kxpnt9q.js +1 -0
  7. package/dist/{chunk-az3rehz9.js → chunk-25s0c8km.js} +399 -392
  8. package/dist/{chunk-v5vx6nz9.js → chunk-27bjk35b.js} +1 -1
  9. package/dist/{chunk-65wc1h38.js → chunk-2ftyzk83.js} +1 -1
  10. package/dist/chunk-2g3v9qpz.js +1 -0
  11. package/dist/{chunk-q6abav45.js → chunk-2vrsfb8p.js} +59 -59
  12. package/dist/{chunk-h6ahwwpa.js → chunk-30p7aff1.js} +1 -1
  13. package/dist/{chunk-ewwrss2w.js → chunk-3kszepm6.js} +1 -1
  14. package/dist/{chunk-28tzj187.js → chunk-3y2x6fb6.js} +1 -1
  15. package/dist/chunk-43gg1wdc.js +1 -0
  16. package/dist/{chunk-67wy9mm7.js → chunk-447ps2te.js} +2 -2
  17. package/dist/{chunk-9kj19a8t.js → chunk-4cdk4mds.js} +1 -1
  18. package/dist/{chunk-nj6kpdte.js → chunk-5034apfz.js} +2 -2
  19. package/dist/{chunk-28n945me.js → chunk-5bc4hwt9.js} +2 -2
  20. package/dist/{chunk-t0gm0pn1.js → chunk-5yyp6njq.js} +1 -1
  21. package/dist/chunk-72wn385d.js +1 -0
  22. package/dist/{chunk-n5jzmwhy.js → chunk-7eset766.js} +2 -2
  23. package/dist/{chunk-793wjhvz.js → chunk-7vzz3rsx.js} +5 -5
  24. package/dist/{chunk-h4k69z1b.js → chunk-80946c9a.js} +1 -1
  25. package/dist/chunk-8emp6ysb.js +1 -0
  26. package/dist/chunk-8evyh5t0.js +1 -0
  27. package/dist/chunk-8hdtssvs.js +1 -0
  28. package/dist/{chunk-5k8k56f2.js → chunk-8n3jythp.js} +11 -9
  29. package/dist/{chunk-870szc6v.js → chunk-8sth12hd.js} +1 -1
  30. package/dist/{chunk-1n4v80hy.js → chunk-9qxch6sy.js} +1 -1
  31. package/dist/{chunk-09kqfdpa.js → chunk-9ydrwcpy.js} +2 -2
  32. package/dist/{chunk-p8vpvx07.js → chunk-9yn01a90.js} +1 -1
  33. package/dist/chunk-a1tt14a2.js +2 -0
  34. package/dist/{chunk-tsm8rhmd.js → chunk-a731hdwa.js} +1 -1
  35. package/dist/{chunk-pga8gxtf.js → chunk-a74ynw4t.js} +1 -1
  36. package/dist/chunk-b36egepz.js +1 -0
  37. package/dist/{chunk-yjjxv7fn.js → chunk-dxq7462e.js} +2 -2
  38. package/dist/{chunk-gmpsfkgg.js → chunk-f552hzcx.js} +1 -1
  39. package/dist/{chunk-ebpg1srd.js → chunk-f6hc7t65.js} +2 -2
  40. package/dist/{chunk-vx2g1faw.js → chunk-fqxzzsgr.js} +1 -1
  41. package/dist/{chunk-p2y1zqsb.js → chunk-g0hhqxpg.js} +2 -2
  42. package/dist/{chunk-ed2hdrwe.js → chunk-gzbb747a.js} +1 -1
  43. package/dist/{chunk-pdna2qvv.js → chunk-h8w3ahnk.js} +2 -2
  44. package/dist/{chunk-sbfe9vh3.js → chunk-hmw99nm1.js} +7 -7
  45. package/dist/chunk-hrtf7dba.js +2 -0
  46. package/dist/chunk-j7dx054r.js +1 -0
  47. package/dist/chunk-j9ppeg6v.js +1 -0
  48. package/dist/chunk-jemb0vwa.js +1 -0
  49. package/dist/{chunk-6xzk4hsg.js → chunk-m30qwpe9.js} +1 -1
  50. package/dist/{chunk-v4cxk10d.js → chunk-m70cnaeg.js} +1 -1
  51. package/dist/{chunk-826xegd8.js → chunk-m8te4s8f.js} +2 -2
  52. package/dist/chunk-ms0wve9g.js +14 -0
  53. package/dist/{chunk-n34qsnks.js → chunk-n8qg68y2.js} +1 -1
  54. package/dist/{chunk-e45r1a8r.js → chunk-pm5ssr7m.js} +2 -2
  55. package/dist/chunk-r9m3b170.js +1 -0
  56. package/dist/{chunk-1j39te3t.js → chunk-rt3f4xjz.js} +1 -1
  57. package/dist/{chunk-9sf1t8gw.js → chunk-s1cch8tt.js} +1 -1
  58. package/dist/{chunk-tzvb0nd2.js → chunk-sa9fxss4.js} +1 -1
  59. package/dist/{chunk-e0ft3vwg.js → chunk-ta99scbr.js} +1 -1
  60. package/dist/chunk-tf1qz4q6.js +1 -0
  61. package/dist/{chunk-0ef47wgr.js → chunk-tqt5c2f5.js} +2 -2
  62. package/dist/{chunk-fd0a8h55.js → chunk-ts5xzefm.js} +2 -2
  63. package/dist/{chunk-g7tphxme.js → chunk-v17q4bsd.js} +2 -2
  64. package/dist/{chunk-fnmqxhv1.js → chunk-v1k6nvth.js} +1 -1
  65. package/dist/{chunk-hv8nt7wj.js → chunk-vbjgcn49.js} +1 -1
  66. package/dist/{chunk-53vh6vpt.js → chunk-wcps5gjm.js} +1 -1
  67. package/dist/{chunk-av799ng5.js → chunk-xcj23spc.js} +2 -2
  68. package/dist/chunk-xcy45yxx.js +8 -0
  69. package/dist/{chunk-fc1gz532.js → chunk-xseh3f4m.js} +2 -2
  70. package/dist/{chunk-9tpzmy8v.js → chunk-xz7dddaj.js} +1 -1
  71. package/dist/{chunk-xcq0cehr.js → chunk-xzva8y4e.js} +3 -3
  72. package/dist/chunk-y0wc0hef.js +10 -0
  73. package/dist/{chunk-sqk8cnej.js → chunk-yrr9mdjn.js} +2 -2
  74. package/dist/{chunk-50vwafn5.js → chunk-zfxcef0z.js} +1 -1
  75. package/dist/{chunk-asgmmaec.js → chunk-zjezws85.js} +2 -2
  76. package/dist/web/assets/ChatView-BA3kB_z1.js +17 -0
  77. package/dist/web/assets/CodeBlockHighlighter-B5kcdVCA.js +8 -0
  78. package/dist/web/assets/FilePreview-BQid6G2-.js +8 -0
  79. package/dist/web/assets/KanbanBoard-CTR7bMLa.js +1 -0
  80. package/dist/web/assets/MarkdownRenderer-d7DdyYdx.js +30 -0
  81. package/dist/web/assets/ScrollArea-D1tPWHKZ.js +1 -0
  82. package/dist/web/assets/SessionHistorySurface-Cv_jRoJr.js +1 -0
  83. package/dist/web/assets/SettingsModal-CFa2uCzI.js +5 -0
  84. package/dist/web/assets/Sidebar-DrRNJOgU.js +1 -0
  85. package/dist/web/assets/TaskSwitcher-C9AKJrl-.js +1 -0
  86. package/dist/web/assets/TerminalPanel-BxBGcuB9.js +1 -0
  87. package/dist/web/assets/archive-DNa9b1YE.js +1 -0
  88. package/dist/web/assets/arrow-left-BQh8jlfT.js +1 -0
  89. package/dist/web/assets/calendar-clock-CC7FeYTg.js +1 -0
  90. package/dist/web/assets/chevron-right-6ZTOJE0p.js +1 -0
  91. package/dist/web/assets/clock-3-P2q6i6vm.js +1 -0
  92. package/dist/web/assets/copy-C-KvzjCC.js +1 -0
  93. package/dist/web/assets/dist-DiQNoDMg.js +11 -0
  94. package/dist/web/assets/download-CJHn20x1.js +1 -0
  95. package/dist/web/assets/folder-DmyFehXD.js +1 -0
  96. package/dist/web/assets/index-BVEiHNFk.css +1 -0
  97. package/dist/web/assets/index-D-oma3Je.js +11 -0
  98. package/dist/web/assets/message-square-plus-CKu9bFq3.js +1 -0
  99. package/dist/web/assets/pause-D2FxNG-w.js +1 -0
  100. package/dist/web/assets/pencil-D6HI7KC8.js +1 -0
  101. package/dist/web/assets/play-4jKCDYR-.js +1 -0
  102. package/dist/web/assets/plus-C4p8E1Nk.js +1 -0
  103. package/dist/web/assets/preload-helper-BC9Zf9qO.js +1 -0
  104. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  105. package/dist/web/assets/session-events-CvFfHkFA.js +23 -0
  106. package/dist/web/assets/settings-fWlqCZ-U.js +1 -0
  107. package/dist/web/assets/team-qGS2kixH.js +1 -0
  108. package/dist/web/assets/teamService-DfIvlI2_.js +1 -0
  109. package/dist/web/assets/terminal-DZkEoiSb.js +1 -0
  110. package/dist/web/assets/triangle-alert-Detl9fRQ.js +1 -0
  111. package/dist/web/assets/vendor-radix-CHeA_3Pt.js +41 -0
  112. package/dist/web/assets/vendor-react-hNfZDUf2.js +9 -0
  113. package/dist/web/assets/vendor-xterm-CANZO_wP.js +16 -0
  114. package/dist/web/assets/vendor-xterm-CHOd7Rch.css +1 -0
  115. package/dist/web/index.html +6 -4
  116. package/package.json +11 -10
  117. package/dist/chunk-514va7ce.js +0 -2
  118. package/dist/chunk-6p0hkf4f.js +0 -1
  119. package/dist/chunk-867bpjzg.js +0 -1
  120. package/dist/chunk-983hqzat.js +0 -1
  121. package/dist/chunk-af0m5227.js +0 -1
  122. package/dist/chunk-dpg006xj.js +0 -1
  123. package/dist/chunk-gpnkxh4c.js +0 -1
  124. package/dist/chunk-hpge30p8.js +0 -8
  125. package/dist/chunk-mtvbm7xe.js +0 -1
  126. package/dist/chunk-mys9mmcp.js +0 -1
  127. package/dist/chunk-new78c3h.js +0 -1
  128. package/dist/chunk-nng1xbsm.js +0 -10
  129. package/dist/chunk-pt0y4zrg.js +0 -14
  130. package/dist/chunk-r4em0ha7.js +0 -1
  131. package/dist/chunk-rdzbd5vk.js +0 -1
  132. package/dist/chunk-w6zat4v4.js +0 -1
  133. package/dist/chunk-wsd3rn0q.js +0 -1
  134. package/dist/chunk-yzf2jpam.js +0 -2
  135. package/dist/web/assets/ChatView-lUD-61n0.js +0 -70
  136. package/dist/web/assets/CodeBlockHighlighter--TbfcBxW.js +0 -8
  137. package/dist/web/assets/FilePreview-R6OKQPf2.js +0 -55
  138. package/dist/web/assets/KanbanBoard-BHOKtiv5.js +0 -16
  139. package/dist/web/assets/MarkdownRenderer-DqxNq8pa.js +0 -30
  140. package/dist/web/assets/ScrollArea-Dhu0B-zB.js +0 -1
  141. package/dist/web/assets/SessionHistorySurface-aZvoj3ma.js +0 -6
  142. package/dist/web/assets/SettingsModal-C7QBnIqa.js +0 -20
  143. package/dist/web/assets/Sidebar-Bznnq91x.js +0 -31
  144. package/dist/web/assets/TaskSwitcher-DJczhDRp.js +0 -26
  145. package/dist/web/assets/TerminalPanel-Vk4p0V3p.js +0 -6
  146. package/dist/web/assets/archive-0hLYBKQf.js +0 -6
  147. package/dist/web/assets/arrow-left-CXb6Gqf3.js +0 -6
  148. package/dist/web/assets/calendar-clock-DiaFI9Jk.js +0 -6
  149. package/dist/web/assets/chevron-right-CcPXH37D.js +0 -6
  150. package/dist/web/assets/clock-3-D6VR6gJc.js +0 -6
  151. package/dist/web/assets/copy-C3eUAQgp.js +0 -6
  152. package/dist/web/assets/download-DHvS9tI3.js +0 -6
  153. package/dist/web/assets/external-link-BDVaEuqY.js +0 -11
  154. package/dist/web/assets/folder-B80Ac6rr.js +0 -11
  155. package/dist/web/assets/index-B5mUEr6D.js +0 -11
  156. package/dist/web/assets/index-VwIiNjc8.css +0 -1
  157. package/dist/web/assets/index-YqughEZk.js +0 -211
  158. package/dist/web/assets/message-square-plus-D15quyPH.js +0 -21
  159. package/dist/web/assets/pause-BjMlj6Bx.js +0 -6
  160. package/dist/web/assets/pencil-BMoJvcB7.js +0 -6
  161. package/dist/web/assets/play-BHh4py3p.js +0 -6
  162. package/dist/web/assets/plus-DeFz_gQq.js +0 -6
  163. package/dist/web/assets/session-events-DCHBz9We.js +0 -25
  164. package/dist/web/assets/settings-CI8xbId2.js +0 -6
  165. package/dist/web/assets/team-zZ803hH9.js +0 -6
  166. package/dist/web/assets/teamService-CgLBXgmv.js +0 -1
  167. package/dist/web/assets/terminal-1WxSJ47E.js +0 -6
  168. package/dist/web/assets/vendor-radix-D6QrtXqd.js +0 -45
  169. package/dist/web/assets/vendor-react-DofNRwfy.js +0 -49
  170. package/dist/web/assets/vendor-xterm-9CEnUXvW.css +0 -32
  171. package/dist/web/assets/vendor-xterm-DuYZoU4T.js +0 -49
@@ -1,4 +1,4 @@
1
- import{Ac as w4}from"./chunk-1n4v80hy.js";import{Ad as A2,Bc as B$,Bd as V6,Cd as z6,Dc as z$,Ec as _2,Fc as d1,Hc as K$,Id as b2,Jd as U4,Kd as q4,Ld as Y6,Md as o1,Nd as G4,Od as L4,Pd as g1,Td as lJ,ae as I0,ce as b6,de as i1,ee as E6,le as Z1,xd as N2,zd as y2}from"./chunk-sbfe9vh3.js";import{qe as D4}from"./chunk-tsm8rhmd.js";import{Ie as G0,te as L0,we as V2,xe as r1}from"./chunk-yjjxv7fn.js";import{dg as v2}from"./chunk-t0gm0pn1.js";import{eg as B4,fg as k0,gg as X4,hg as uJ,jg as p1,kg as A6,lg as dJ,mg as cJ,pg as iJ}from"./chunk-hpge30p8.js";import{ah as $$,bh as d0,eh as j4}from"./chunk-ewwrss2w.js";import{jh as r2,nh as J2}from"./chunk-53vh6vpt.js";import{yh as E$}from"./chunk-xcq0cehr.js";import{Gh as T$}from"./chunk-sqk8cnej.js";import{aj as H0}from"./chunk-6xzk4hsg.js";import{Cj as P0}from"./chunk-09kqfdpa.js";import{Wj as P2}from"./chunk-yzf2jpam.js";import{Ak as L2,Ck as O2,Hk as F2,dk as G2,sk as j2,tk as D2,wk as AJ,zk as GJ}from"./chunk-ed2hdrwe.js";import{Jk as gZ}from"./chunk-gmpsfkgg.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class M1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(y$),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)=>!A$(W)&&!y$(W))}get historyLength(){return this._history.length}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getHistory(){return this._history}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);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:{},...G0}})}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)=>!A$(Z)&&!y$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((Z)=>!A$(Z)&&!y$(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]}}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 X$ from"node:path";var S4=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"]),f4=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function a$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],X=W.match($J);if(!X)break;let K=X[1];if(!S4.has(K))break;Z=Y}return Z}function c9($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],X=W.match($J);if(!X)break;let K=X[1];if(f4.test(K))break;Z=Y}return Z}var T4=[/^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 fZ($){let Z=$,J=!0;while(J){J=!1;for(let W of T4){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 s$($){let Z=[],J="",W=!1,Y=!1,X=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(X){J+=Q,X=!1;continue}if(Q==="\\"&&!W){J+=Q,X=!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(K+1<$.length&&$[K+1]==="|"){if(J.trim())Z.push(J.trim());J="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(J.trim())Z.push(J.trim());J="",K++;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 X=$[Y];if(W){W=!1;continue}if(X==="\\"&&!Z){W=!0;continue}if(X==="'"&&!J){Z=!Z;continue}if(X==='"'&&!Z){J=!J;continue}if(Z)continue;if(X==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(X==="`")return!0;if(J)continue;if(X==="|")return!0;if(X===">"||X==="<")return!0;if(X==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function Y$($){let Z=[],J="",W=!1,Y=!1,X=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(X){J+=Q,X=!1;continue}if(Q==="\\"&&!W){if(X=!0,Y){let H=$[K+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,X=!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 M4=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),R4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),k4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function x4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function I4($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Y$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let X=Y[1];if(!X||X==="-")return;let K=X$.isAbsolute(X)?X$.resolve(X):X$.resolve(J,X);if(!K$.isWithinWorkspace(K,J))return;return W[2]?.trim()||void 0}function h4($){let Z=[],J=!1,W=!1,Y=!1;for(let X=0;X<$.length;X++){let K=$[X];if(Y){Y=!1;continue}if(K==="\\"&&!J){Y=!0;continue}if(K==="'"&&!W){J=!J;continue}if(K==='"'&&!J){W=!W;continue}if(K!=="|"||J||W)continue;if($[X+1]==="|")return;Z.push(X)}return Z}function v4($){let Z=Y$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let X=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(Z.length===2)return W?.startsWith("--lines=")&&X(W.slice(8))||W?.startsWith("-")&&X(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&X(Y)}function C4($){let Z=WJ($.replace(k4,"").trim()),J=h4(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()),X=Z.slice(W+1).trim();if(!Y||!v4(X))return;return YJ(Y)}function YJ($){let J=s$($)?.at(-1);if(!J)return $;let W=Y$(J),[Y,X]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&X==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function b$($,Z){let J=C4($);if(!J)return!1;let W=a$(J),Y=s$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let X=Y.length===1?Y[0]:I4(W,Y,Z);if(!X)return!1;let K=Y$(X);if(K.length===0||K.some((z)=>[...R4].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=K;if(M4.has(Q??""))return x4(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 o9($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!X$.isAbsolute($);let J=X$.isAbsolute($)?X$.resolve($):X$.resolve(Z,$);return K$.isWithinWorkspace(J,Z)}var TZ=P0("Agent"),p4=3;function MZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=p4)return{action:"truncated"};if(s6(J)==="stop")return TZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var g4=[/:\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],m4=/```[\s\S]{50,}```/,XJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",u4=2;function RZ($,Z,J=!0){if(!$||Z>=u4)return{action:"none"};if(!J&&m4.test($))return{action:"retry",prompt:XJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(g4.some((K)=>K.test(W)))return{action:"retry",prompt:XJ};return{action:"none"}}var R1=2,d4="The model returned tool-call JSON as text instead of completing the requested tool workflow.",c4="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 kZ($,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 X;try{X=JSON.parse($)}catch{return{action:"none"}}if(!X||typeof X!=="object"||Array.isArray(X)||Object.keys(X).length!==1||!("tool_calls"in X)||!Array.isArray(X.tool_calls)||X.tool_calls.length===0||X.tool_calls.length>32)return{action:"none"};let K=new Set;for(let Q of X.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))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((G)=>G!=="name"&&G!=="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 w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),B=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!j.test(Y)||B.test(Y))return{action:"none"};K.add(V.name)}return W<R1?{action:"retry",prompt:c4,...K.size===1?{toolName:[...K][0]}:{}}:{action:"fail",message:d4}}var i4=[/\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}(?:测试|单测|集成测试|检查|构建)/],KJ={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},l4={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},r4="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.",n4="Required verification did not run successfully before the retry limit.",o4=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&&b$(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 X of Y)if(typeof X==="string"&&b$(X,W))$.add(X)}function xZ($,Z,J){if(!$||!i4.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(KJ).filter((H)=>KJ[H].test($)),Y=[...Z],X=W.filter((H)=>!Y.some((V)=>l4[H].test(V)));if(W.length>0?X.length===0:Y.some((H)=>b$(H)))return{action:"none"};if(J>=o4)return{action:"fail",message:n4};let Q=W.length>1&&X.length>0?` Missing successful verification categories: ${X.join(", ")}.`:"";return{action:"retry",prompt:`${r4}${Q}`}}var a4=[/\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 s4=[/\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|子代理)/],t4=[/\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 e4($){if(typeof $!=="string")return;if(t4.some((Z)=>Z.test($)))return"multiple-allowed";return s4.some((Z)=>Z.test($))?"required":void 0}function e$($){for(let Z of $){let J=e4(Z);if(J!==void 0)return J==="required"}return!1}var $5="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.",Z5="Required delegation did not complete before the retry limit.",J5=3;function BJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),X=!1;if(!Y)for(let K of W){if(VJ.some((Q)=>Q.test(K)))break;if(a4.some((Q)=>Q.test(K))){X=!0;break}}if(W.length===0||!Y&&!X||Z.has("Task"))return{action:"none"};if(J>=J5)return{action:"fail",message:Z5};return{action:"retry",prompt:$5}}var W5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Y5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],X5=[/\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 jJ($){return X5.reduce((Z,J)=>Z.replace(J," "),$)}function k1($){if(typeof $!=="string")return!1;let Z=jJ($);return W5.some((J)=>J.test(Z))}var K5="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.",Q5="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.",H5="Required worktree lifecycle did not complete before the retry limit.",V5=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=jJ($);if(!k1(W))return{action:"none"};let Y=Y5.some((K)=>K.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let X=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!X)return{action:"none"};if(J>=V5)return{action:"fail",message:H5};return{action:"retry",tool:X,prompt:X==="EnterWorktree"?K5:Q5}}var QJ=30000;async function IZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((X)=>{W=setTimeout(()=>X("timeout"),QJ)});try{let X=await Promise.race([J,Y]);if(X==="timeout")return TZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let K=X;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return TZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function z5($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var B5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function j5($){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 D5($){let Z=$;for(let H of B5)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 X=Y.slice(0,60),K=X.lastIndexOf(" ");return`${(K>36?X.slice(0,K):X).trimEnd()}…`}function wJ($){return D5(j5($))}import{EventEmitter as w5}from"events";import UJ from"node:path";function hZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=hZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function H3($,Z){return qJ($)===qJ(Z)}class S$ extends w5{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=hZ($);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 $1=S$.getInstance();var o0=P0("Agent"),x1=new Set;async function U5($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(x1.has(J))return;if(x1.size>=5000)x1.clear();x1.add(J);try{let W=$.workspaceRoot,Y=await Z1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let X=wJ(Z);if(!X)return;await Z1.updateSessionMetadata(J,Y.projectPath,{title:X}),$1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:X})}catch(W){o0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var vZ=`<turn_aborted>
1
+ import{Bc as w4}from"./chunk-9qxch6sy.js";import{Ad as y2,Bd as A2,Cc as B$,Cd as V6,Dd as z6,Ec as z$,Fc as _2,Gc as d1,Ic as K$,Jd as b2,Kd as U4,Ld as q4,Md as Y6,Nd as o1,Od as G4,Pd as L4,Qd as g1,Ud as lJ,be as I0,de as b6,ee as i1,fe as E6,me as Z1,yd as N2}from"./chunk-hmw99nm1.js";import{re as D4}from"./chunk-a731hdwa.js";import{Je as G0,ue as L0,xe as V2,ye as r1}from"./chunk-dxq7462e.js";import{eg as v2}from"./chunk-5yyp6njq.js";import{fg as B4,gg as k0,hg as X4,ig as uJ,kg as p1,lg as A6,mg as dJ,ng as cJ,qg as iJ}from"./chunk-xcy45yxx.js";import{bh as $$,ch as d0,fh as j4}from"./chunk-3kszepm6.js";import{kh as r2,oh as J2}from"./chunk-wcps5gjm.js";import{zh as E$}from"./chunk-xzva8y4e.js";import{Hh as T$}from"./chunk-yrr9mdjn.js";import{Yi as H0}from"./chunk-m30qwpe9.js";import{Dj as P0}from"./chunk-9ydrwcpy.js";import{Xj as P2}from"./chunk-a1tt14a2.js";import{Ak as GJ,Bk as L2,Dk as O2,Ik as F2,ek as G2,tk as j2,uk as D2,xk as AJ}from"./chunk-gzbb747a.js";import{Kk as gZ}from"./chunk-f552hzcx.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class M1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(y$),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)=>!A$(W)&&!y$(W))}get historyLength(){return this._history.length}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getHistory(){return this._history}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);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:{},...G0}})}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)=>!A$(Z)&&!y$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((Z)=>!A$(Z)&&!y$(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]}}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 X$ from"node:path";var S4=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"]),f4=/^(LD_.+|DYLD_.+|PATH)$/,$J=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function a$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],X=W.match($J);if(!X)break;let K=X[1];if(!S4.has(K))break;Z=Y}return Z}function c9($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],X=W.match($J);if(!X)break;let K=X[1];if(f4.test(K))break;Z=Y}return Z}var T4=[/^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 fZ($){let Z=$,J=!0;while(J){J=!1;for(let W of T4){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 s$($){let Z=[],J="",W=!1,Y=!1,X=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(X){J+=Q,X=!1;continue}if(Q==="\\"&&!W){J+=Q,X=!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(K+1<$.length&&$[K+1]==="|"){if(J.trim())Z.push(J.trim());J="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(J.trim())Z.push(J.trim());J="",K++;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 X=$[Y];if(W){W=!1;continue}if(X==="\\"&&!Z){W=!0;continue}if(X==="'"&&!J){Z=!Z;continue}if(X==='"'&&!Z){J=!J;continue}if(Z)continue;if(X==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(X==="`")return!0;if(J)continue;if(X==="|")return!0;if(X===">"||X==="<")return!0;if(X==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function Y$($){let Z=[],J="",W=!1,Y=!1,X=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(X){J+=Q,X=!1;continue}if(Q==="\\"&&!W){if(X=!0,Y){let H=$[K+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,X=!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 M4=new Set(["npm","pnpm","yarn","bun"]),JJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),R4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),k4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function x4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function WJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function I4($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Y$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let X=Y[1];if(!X||X==="-")return;let K=X$.isAbsolute(X)?X$.resolve(X):X$.resolve(J,X);if(!K$.isWithinWorkspace(K,J))return;return W[2]?.trim()||void 0}function h4($){let Z=[],J=!1,W=!1,Y=!1;for(let X=0;X<$.length;X++){let K=$[X];if(Y){Y=!1;continue}if(K==="\\"&&!J){Y=!0;continue}if(K==="'"&&!W){J=!J;continue}if(K==='"'&&!J){W=!W;continue}if(K!=="|"||J||W)continue;if($[X+1]==="|")return;Z.push(X)}return Z}function v4($){let Z=Y$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let X=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(Z.length===2)return W?.startsWith("--lines=")&&X(W.slice(8))||W?.startsWith("-")&&X(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&X(Y)}function C4($){let Z=WJ($.replace(k4,"").trim()),J=h4(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()),X=Z.slice(W+1).trim();if(!Y||!v4(X))return;return YJ(Y)}function YJ($){let J=s$($)?.at(-1);if(!J)return $;let W=Y$(J),[Y,X]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&X==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function b$($,Z){let J=C4($);if(!J)return!1;let W=a$(J),Y=s$(W);if(!Y||ZJ(W)||/[\r\n]/.test(W))return!1;let X=Y.length===1?Y[0]:I4(W,Y,Z);if(!X)return!1;let K=Y$(X);if(K.length===0||K.some((z)=>[...R4].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=K;if(M4.has(Q??""))return x4(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 o9($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!X$.isAbsolute($);let J=X$.isAbsolute($)?X$.resolve($):X$.resolve(Z,$);return K$.isWithinWorkspace(J,Z)}var TZ=P0("Agent"),p4=3;function MZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=p4)return{action:"truncated"};if(s6(J)==="stop")return TZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var g4=[/:\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],m4=/```[\s\S]{50,}```/,XJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",u4=2;function RZ($,Z,J=!0){if(!$||Z>=u4)return{action:"none"};if(!J&&m4.test($))return{action:"retry",prompt:XJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(g4.some((K)=>K.test(W)))return{action:"retry",prompt:XJ};return{action:"none"}}var R1=2,d4="The model returned tool-call JSON as text instead of completing the requested tool workflow.",c4="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 kZ($,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 X;try{X=JSON.parse($)}catch{return{action:"none"}}if(!X||typeof X!=="object"||Array.isArray(X)||Object.keys(X).length!==1||!("tool_calls"in X)||!Array.isArray(X.tool_calls)||X.tool_calls.length===0||X.tool_calls.length>32)return{action:"none"};let K=new Set;for(let Q of X.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))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((G)=>G!=="name"&&G!=="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 w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),j=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),B=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!j.test(Y)||B.test(Y))return{action:"none"};K.add(V.name)}return W<R1?{action:"retry",prompt:c4,...K.size===1?{toolName:[...K][0]}:{}}:{action:"fail",message:d4}}var i4=[/\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}(?:测试|单测|集成测试|检查|构建)/],KJ={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},l4={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},r4="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.",n4="Required verification did not run successfully before the retry limit.",o4=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&&b$(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 X of Y)if(typeof X==="string"&&b$(X,W))$.add(X)}function xZ($,Z,J){if(!$||!i4.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(KJ).filter((H)=>KJ[H].test($)),Y=[...Z],X=W.filter((H)=>!Y.some((V)=>l4[H].test(V)));if(W.length>0?X.length===0:Y.some((H)=>b$(H)))return{action:"none"};if(J>=o4)return{action:"fail",message:n4};let Q=W.length>1&&X.length>0?` Missing successful verification categories: ${X.join(", ")}.`:"";return{action:"retry",prompt:`${r4}${Q}`}}var a4=[/\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 s4=[/\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|子代理)/],t4=[/\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 e4($){if(typeof $!=="string")return;if(t4.some((Z)=>Z.test($)))return"multiple-allowed";return s4.some((Z)=>Z.test($))?"required":void 0}function e$($){for(let Z of $){let J=e4(Z);if(J!==void 0)return J==="required"}return!1}var $5="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.",Z5="Required delegation did not complete before the retry limit.",J5=3;function BJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=e$(W),X=!1;if(!Y)for(let K of W){if(VJ.some((Q)=>Q.test(K)))break;if(a4.some((Q)=>Q.test(K))){X=!0;break}}if(W.length===0||!Y&&!X||Z.has("Task"))return{action:"none"};if(J>=J5)return{action:"fail",message:Z5};return{action:"retry",prompt:$5}}var W5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Y5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],X5=[/\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 jJ($){return X5.reduce((Z,J)=>Z.replace(J," "),$)}function k1($){if(typeof $!=="string")return!1;let Z=jJ($);return W5.some((J)=>J.test(Z))}var K5="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.",Q5="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.",H5="Required worktree lifecycle did not complete before the retry limit.",V5=3;function DJ($,Z,J){if(!$)return{action:"none"};let W=jJ($);if(!k1(W))return{action:"none"};let Y=Y5.some((K)=>K.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let X=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!X)return{action:"none"};if(J>=V5)return{action:"fail",message:H5};return{action:"retry",tool:X,prompt:X==="EnterWorktree"?K5:Q5}}var QJ=30000;async function IZ($){try{let J=E$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((X)=>{W=setTimeout(()=>X("timeout"),QJ)});try{let X=await Promise.race([J,Y]);if(X==="timeout")return TZ.warn(`[Loop] Stop hook 超时 (${QJ}ms),按 shouldStop: true 处理`),{action:"stop"};let K=X;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return TZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function z5($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var B5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function j5($){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 D5($){let Z=$;for(let H of B5)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 X=Y.slice(0,60),K=X.lastIndexOf(" ");return`${(K>36?X.slice(0,K):X).trimEnd()}…`}function wJ($){return D5(j5($))}import{EventEmitter as w5}from"events";import UJ from"node:path";function hZ($){if(GJ($.sessionId),!UJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:UJ.resolve($.projectPath)}}function qJ($){let Z=hZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function H3($,Z){return qJ($)===qJ(Z)}class S$ extends w5{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=hZ($);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 $1=S$.getInstance();var o0=P0("Agent"),x1=new Set;async function U5($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(x1.has(J))return;if(x1.size>=5000)x1.clear();x1.add(J);try{let W=$.workspaceRoot,Y=await Z1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let X=wJ(Z);if(!X)return;await Z1.updateSessionMetadata(J,Y.projectPath,{title:X}),$1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:X})}catch(W){o0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var vZ=`<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>`,Q$="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 f$ 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 H$($){return $.executionEngine?.getContextManager()}async function u0($,Z,J,W=null,Y,X={}){let K=X.required??$.executionEngine!==void 0;try{let Q=H$($),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(K&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)U5(Z,J);return V}if(K&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if(o0.warn("[Loop] 保存用户消息失败:",Q),K)throw new f$("user_message",{cause:Q})}return null}async function R0($,Z,J,W,Y,X,K={}){let Q=K.required??$.executionEngine!==void 0;try{let H=H$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,X,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(o0.warn("[Loop] 保存助手消息失败:",H),Q)throw new f$("assistant_message",{cause:H})}return null}async function OJ($,Z,J){try{let W=H$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",vZ,J,void 0,Z.subagentInfo)}catch(W){o0.warn("[Loop] 保存中断边界失败:",W)}return null}async function FJ($,Z,J,W,Y){try{let X=H$($);if(!X||!Z.sessionId||J.length===0)return null;return await X.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((K)=>({...K})))),triggerPaths:[...W]},Z.subagentInfo)}catch(X){o0.warn("[Loop] 保存 contextual project rules provenance 失败:",X)}return null}async function CZ($,Z,J,W,Y,X={}){try{let K=H$($);if(K&&Z.sessionId){let Q=await K.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,X.providerToolCallId);if(X.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(X.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(o0.warn("[Loop] 保存工具调用失败:",K),X.required)throw K}return null}async function I1($,Z,J,W,Y,X,K,Q,H,V={}){try{let z=H$($);if(z&&Z.sessionId){let w=await z.saveToolResult(Z.sessionId,J,W,Y,X,K,Z.subagentInfo,Q,H);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if(o0.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function J1($,Z,J,W,Y={}){try{let X=H$($);if(X&&Z.sessionId){let K=await X.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(X){if(o0.warn("[Loop] 保存压缩数据失败:",X),Y.required)throw X}return null}async function K0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:X,lastMessageUuid:K,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:X});let H=K,V=await R0(Z,J,Y,H,X);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:G0};W.appendControl("user",z);let w=await u0(Z,J,Q,H,G0);if(w)H=w}return H}import{createHash as S6}from"node:crypto";import{promises as c5}from"node:fs";import i5 from"node:path";import{nanoid as s0}from"nanoid";import*as a from"node:fs/promises";import*as a0 from"node:path";import _J from"write-file-atomic";var PJ={enabled:!0,maxIndexLines:200};var q5="memory",pZ="MEMORY.md",mZ="<!-- blade:auto-memory-topics:start -->",h1="<!-- blade:auto-memory-topics:end -->",G5={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},L5=new T$,NJ;function bJ($){return $.trim().replace(/\s+/g," ")}function O5($){return bJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function F5($){return[mZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),h1].join(`
4
4
  `)}function P5($,Z){let J=F5(Z),W=$.indexOf(mZ),Y=$.indexOf(h1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+h1.length);if(!$)return`${J}
@@ -78,7 +78,7 @@ ${H}${V}
78
78
  `),metadata:{isPostCompactActiveTask:!0}}}static fallbackCompact($,Z,J,W,Y,X,K,Q,H,V,z){let w=s0(),j=this.createBoundaryMessage(w,Z.trigger,J),B=W instanceof Error?W.message:String(W),G=s0(),_=gJ(`[Automatic compaction failed; using bounded fallback]
79
79
 
80
80
  The exact continuation records and retained tail are authoritative for execution status. Do not repeat actions marked complete, applied, or passed. Treat failed actions as historical evidence and execute only the pending exact next action, which may require a corrected retry, before claiming completion. After pending work succeeds, obey exact final-response constraints from the preserved request literally.`,$),b=this.createSummaryMessage(G,_),T=this.buildActiveTaskMessage(Z.activeTask),M=[b,...T?[T]:[]],g=pJ($,M,{maxContextTokens:Z.maxContextTokens,modelName:Z.modelName,preservedActiveTask:Z.activeTask&&Z.activeTask.length<=this.ACTIVE_TASK_MAX_CHARS?Z.activeTask:void 0}),I=[b,...g.messages,...T?[T]:[]],m=r.countTokens(I,Z.modelName);if(m>g.targetTokens)throw Error(`Fallback compaction retained ${m} estimated tokens; target is ${g.targetTokens}`);return{success:!1,summary:typeof b.content==="string"?b.content:b.content.filter((x)=>x.type==="text").map((x)=>x.text).join(`
81
- `),preTokens:J,postTokens:m,filesIncluded:[],compactedMessages:I,boundaryMessage:j,summaryMessage:b,error:B,usage:z,sampleAttempts:Y,inputReductions:K,messagesOmitted:Q,filesOmitted:H,imagesOmitted:V,fallbackTargetTokens:g.targetTokens,fallbackMessagesOmitted:g.messagesOmitted,fallbackMessagesTruncated:g.messagesTruncated,failureReason:X,memoryPlan:Z.workspaceAccess==="none"?uZ:dZ(g.omittedSourceIndexes.map((x)=>$[x]))}}}import{createHash as W8}from"node:crypto";function Y1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function k$($,Z){if($>=Number.MAX_SAFE_INTEGER-Z)return Number.MAX_SAFE_INTEGER;return $+Z}function sJ($){let Z=JSON.stringify($);if(Z===void 0)throw Error("Context token request profile is not serializable");return Z}function m1($){let Z=Y1($.promptTokens)?$.promptTokens:void 0,J=Y1($.completionTokens)?$.completionTokens:void 0,W=Y1($.totalTokens)?$.totalTokens:void 0,Y=Z!==void 0&&J!==void 0?k$(Z,J):void 0;if(W===void 0)return Y;if(Y===void 0)return W;return Math.max(W,Y)}function oZ($,Z,J){let W=sJ(Z),Y=W8("sha256").update(J).update("\x00").update(sJ($)).update("\x00").update(W).digest("hex"),X=Z.length===0?0:k$(r.countTextTokens(W,J),Z.length*8);return{fingerprint:Y,estimatedFixedTokens:k$(r.countTokens($,J),X)}}class aZ{baseline;recordProviderUsage($){let Z=$.usage?m1($.usage):void 0;if(Z===void 0||!Y1($.contextRevision)||!Y1($.historyLength)){this.baseline=void 0;return}this.baseline={contextTokens:Z,contextRevision:$.contextRevision,estimatedFixedTokens:$.requestProfile.estimatedFixedTokens,historyLength:$.historyLength,modelName:$.modelName,requestFingerprint:$.requestProfile.fingerprint}}reset(){this.baseline=void 0}project($){let Z=$.pendingMessages??[],J=this.baseline;if(!J||J.contextRevision!==$.contextRevision||$.history.length<J.historyLength)return this.projectLocally($.history,Z,$);let W=$.history.slice(J.historyLength);if(W.length>0&&W[0]?.role!=="assistant")return this.projectLocally($.history,Z,$);let Y=[...W.length>0?W.slice(1):[],...Z],X=r.countTokens(Y,$.modelName),K=Math.max(0,$.requestProfile.estimatedFixedTokens-J.estimatedFixedTokens),Q=k$(X,K),H=J.modelName!==$.modelName||J.requestFingerprint!==$.requestProfile.fingerprint;return{contextTokens:k$(J.contextTokens,Q),source:Q>0||H?"provider_plus_estimate":"provider",estimatedPendingTokens:Q}}projectLocally($,Z,J){let W=r.countTokens([...$,...Z],J.modelName);return{contextTokens:k$(J.requestProfile.estimatedFixedTokens,W),source:"local_estimate"}}}var Y8=new Set(["Read","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function X8($,Z){let Y=($[Z.assistantIdx].tool_calls??[]).filter((K)=>K.type==="function").map((K)=>K.function.name).some((K)=>!Y8.has(K));if(Z.toolResultIdxs.some((K)=>{let Q=$[K]?.content;if(typeof Q!=="string")return!1;return Q.startsWith("Error:")||Q.includes("failed")||Q.includes("ENOENT")}))return 3;if(Y)return 2;return 1}function X1($,Z){let J=Z?.keepRecentTurns??10,W=Z?.minMessagesForSnip??30;if($.length<W)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let Y=[];for(let j=0;j<$.length;j++){let B=$[j];if(B.role==="assistant"&&B.tool_calls&&B.tool_calls.length>0){let G=new Set(B.tool_calls.map((b)=>b.id)),_=[];for(let b=j+1;b<$.length;b++){let T=$[b];if(T.role==="tool"&&T.tool_call_id&&G.has(T.tool_call_id))_.push(b);if(T.role==="assistant"||T.role==="user")break}Y.push({assistantIdx:j,toolResultIdxs:_,priority:0})}}for(let j of Y)j.priority=X8($,j);let Q=[...Y.slice(0,Math.max(0,Y.length-J))].sort((j,B)=>j.priority-B.priority);if(Q.length===0)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let H=new Set,V=0;for(let j of Q){H.add(j.assistantIdx);for(let B of j.toolResultIdxs)H.add(B)}for(let j of H){let B=$[j],G=typeof B.content==="string"?B.content:JSON.stringify(B.content);if(V+=G.length,B.tool_calls)V+=JSON.stringify(B.tool_calls).length}let z=[],w=!1;for(let j=0;j<$.length;j++){if(H.has(j)){if(!w)z.push({role:"system",content:`[${Q.length} earlier tool interaction${Q.length===1?"":"s"} snipped for brevity]`}),w=!0;continue}z.push($[j])}return{messages:z,snippedCount:Q.length,estimatedTokensFreed:Math.floor(V/4)}}var K8=60000,Q8=3;function tJ($,Z){if(!Z)return null;if(Date.now()-Z<K8)return null;let W=X1($,{keepRecentTurns:Q8,minMessagesForSnip:15});if(W.snippedCount===0)return null;return W}var H8="[Reactive context recovery applied deterministic tool-output snipping.]";class sZ{hasAttempted=!1;canAttempt(){return!this.hasAttempted}async tryReactiveCompact($,Z){if(this.hasAttempted)return{success:!1,messages:$};this.hasAttempted=!0;let J=g1($),W=X1(J,{keepRecentTurns:3,minMessagesForSnip:10}),Y=W.messages;try{let X=await R$.compact(Y,{trigger:"auto",modelName:Z.modelName,modelProvider:Z.modelProvider,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,chatConfig:Z.chatConfig,signal:Z.signal,activeTask:Z.activeTask,workspaceRoot:Z.workspaceRoot,workspaceAccess:Z.workspaceAccess,sessionId:Z.sessionId});if(X.success||X.summary.trim())return{success:!0,messages:X.compactedMessages,strategy:X.success?"llm":"fallback",summary:X.summary,preTokens:X.preTokens,postTokens:X.postTokens,sampleAttempts:X.sampleAttempts,inputReductions:X.inputReductions,messagesOmitted:X.messagesOmitted,filesOmitted:X.filesOmitted,imagesOmitted:X.imagesOmitted,fallbackTargetTokens:X.fallbackTargetTokens,fallbackMessagesOmitted:X.fallbackMessagesOmitted,fallbackMessagesTruncated:X.fallbackMessagesTruncated,failureReason:X.failureReason,filesIncluded:X.filesIncluded,usage:X.usage,memoryPlan:X.memoryPlan};if(W.snippedCount>0)return this.snipRecovery(J,Y,Z.modelName);return{success:!1,messages:$}}catch(X){if(k0(X))throw X;if(rJ(X))return{success:!1,messages:$};if(W.snippedCount>0)return this.snipRecovery(J,Y,Z.modelName);return{success:!1,messages:$}}}snipRecovery($,Z,J){return{success:!0,messages:Z,strategy:"snip",summary:H8,preTokens:r.countTokens($,J),postTokens:r.countTokens(Z,J),filesIncluded:[]}}reset(){this.hasAttempted=!1}}import*as x$ from"fs";import{nanoid as $2}from"nanoid";import*as tZ from"os";import*as K1 from"path";var V8=1e5,z8=2000,B8=200000;class eZ{currentChars=0;track($){this.currentChars+=$}remaining(){return Math.max(0,B8-this.currentChars)}}function Z2($,Z,J){let W=J?.maxCharsPerResult??V8,Y=J?.previewChars??z8,X=J?.messageBudget,K=typeof $==="string"?$:JSON.stringify($,null,2);if(K.length<=W)return j8($,K,Z,Y,X,J);let Q=J?.outputDir??K1.join(tZ.homedir(),".blade","tool-results"),H=`${Z}-${$2(8)}.txt`,V=K1.join(Q,H);try{x$.mkdirSync(Q,{recursive:!0}),x$.writeFileSync(V,K,"utf-8")}catch{let j=K.slice(0,W)+`
81
+ `),preTokens:J,postTokens:m,filesIncluded:[],compactedMessages:I,boundaryMessage:j,summaryMessage:b,error:B,usage:z,sampleAttempts:Y,inputReductions:K,messagesOmitted:Q,filesOmitted:H,imagesOmitted:V,fallbackTargetTokens:g.targetTokens,fallbackMessagesOmitted:g.messagesOmitted,fallbackMessagesTruncated:g.messagesTruncated,failureReason:X,memoryPlan:Z.workspaceAccess==="none"?uZ:dZ(g.omittedSourceIndexes.map((x)=>$[x]))}}}import{createHash as W8}from"node:crypto";function Y1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function k$($,Z){if($>=Number.MAX_SAFE_INTEGER-Z)return Number.MAX_SAFE_INTEGER;return $+Z}function sJ($){let Z=JSON.stringify($);if(Z===void 0)throw Error("Context token request profile is not serializable");return Z}function m1($){let Z=Y1($.promptTokens)?$.promptTokens:void 0,J=Y1($.completionTokens)?$.completionTokens:void 0,W=Y1($.totalTokens)?$.totalTokens:void 0,Y=Z!==void 0&&J!==void 0?k$(Z,J):void 0;if(W===void 0)return Y;if(Y===void 0)return W;return Math.max(W,Y)}function oZ($,Z,J){let W=sJ(Z),Y=W8("sha256").update(J).update("\x00").update(sJ($)).update("\x00").update(W).digest("hex"),X=Z.length===0?0:k$(r.countTextTokens(W,J),Z.length*8);return{fingerprint:Y,estimatedFixedTokens:k$(r.countTokens($,J),X)}}class aZ{baseline;recordProviderUsage($){let Z=$.usage?m1($.usage):void 0;if(Z===void 0||!Y1($.contextRevision)||!Y1($.historyLength)){this.baseline=void 0;return}this.baseline={contextTokens:Z,contextRevision:$.contextRevision,estimatedFixedTokens:$.requestProfile.estimatedFixedTokens,historyLength:$.historyLength,modelName:$.modelName,requestFingerprint:$.requestProfile.fingerprint}}reset(){this.baseline=void 0}project($){let Z=$.pendingMessages??[],J=this.baseline;if(!J||J.contextRevision!==$.contextRevision||$.history.length<J.historyLength)return this.projectLocally($.history,Z,$);let W=$.history.slice(J.historyLength);if(W.length>0&&W[0]?.role!=="assistant")return this.projectLocally($.history,Z,$);let Y=[...W.length>0?W.slice(1):[],...Z],X=r.countTokens(Y,$.modelName),K=Math.max(0,$.requestProfile.estimatedFixedTokens-J.estimatedFixedTokens),Q=k$(X,K),H=J.modelName!==$.modelName||J.requestFingerprint!==$.requestProfile.fingerprint;return{contextTokens:k$(J.contextTokens,Q),source:Q>0||H?"provider_plus_estimate":"provider",estimatedPendingTokens:Q}}projectLocally($,Z,J){let W=r.countTokens([...$,...Z],J.modelName);return{contextTokens:k$(J.requestProfile.estimatedFixedTokens,W),source:"local_estimate"}}}var Y8=new Set(["Read","FindFiles","Grep","Glob","Search","WebSearch","WebFetch","ToolSearch"]);function X8($,Z){let Y=($[Z.assistantIdx].tool_calls??[]).filter((K)=>K.type==="function").map((K)=>K.function.name).some((K)=>!Y8.has(K));if(Z.toolResultIdxs.some((K)=>{let Q=$[K]?.content;if(typeof Q!=="string")return!1;return Q.startsWith("Error:")||Q.includes("failed")||Q.includes("ENOENT")}))return 3;if(Y)return 2;return 1}function X1($,Z){let J=Z?.keepRecentTurns??10,W=Z?.minMessagesForSnip??30;if($.length<W)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let Y=[];for(let j=0;j<$.length;j++){let B=$[j];if(B.role==="assistant"&&B.tool_calls&&B.tool_calls.length>0){let G=new Set(B.tool_calls.map((b)=>b.id)),_=[];for(let b=j+1;b<$.length;b++){let T=$[b];if(T.role==="tool"&&T.tool_call_id&&G.has(T.tool_call_id))_.push(b);if(T.role==="assistant"||T.role==="user")break}Y.push({assistantIdx:j,toolResultIdxs:_,priority:0})}}for(let j of Y)j.priority=X8($,j);let Q=[...Y.slice(0,Math.max(0,Y.length-J))].sort((j,B)=>j.priority-B.priority);if(Q.length===0)return{messages:$,snippedCount:0,estimatedTokensFreed:0};let H=new Set,V=0;for(let j of Q){H.add(j.assistantIdx);for(let B of j.toolResultIdxs)H.add(B)}for(let j of H){let B=$[j],G=typeof B.content==="string"?B.content:JSON.stringify(B.content);if(V+=G.length,B.tool_calls)V+=JSON.stringify(B.tool_calls).length}let z=[],w=!1;for(let j=0;j<$.length;j++){if(H.has(j)){if(!w)z.push({role:"system",content:`[${Q.length} earlier tool interaction${Q.length===1?"":"s"} snipped for brevity]`}),w=!0;continue}z.push($[j])}return{messages:z,snippedCount:Q.length,estimatedTokensFreed:Math.floor(V/4)}}var K8=60000,Q8=3;function tJ($,Z){if(!Z)return null;if(Date.now()-Z<K8)return null;let W=X1($,{keepRecentTurns:Q8,minMessagesForSnip:15});if(W.snippedCount===0)return null;return W}var H8="[Reactive context recovery applied deterministic tool-output snipping.]";class sZ{hasAttempted=!1;canAttempt(){return!this.hasAttempted}async tryReactiveCompact($,Z){if(this.hasAttempted)return{success:!1,messages:$};this.hasAttempted=!0;let J=g1($),W=X1(J,{keepRecentTurns:3,minMessagesForSnip:10}),Y=W.messages;try{let X=await R$.compact(Y,{trigger:"auto",modelName:Z.modelName,modelProvider:Z.modelProvider,maxContextTokens:Z.maxContextTokens,apiKey:Z.apiKey,baseURL:Z.baseURL,chatConfig:Z.chatConfig,signal:Z.signal,activeTask:Z.activeTask,workspaceRoot:Z.workspaceRoot,workspaceAccess:Z.workspaceAccess,sessionId:Z.sessionId});if(X.success||X.summary.trim())return{success:!0,messages:X.compactedMessages,strategy:X.success?"llm":"fallback",summary:X.summary,preTokens:X.preTokens,postTokens:X.postTokens,sampleAttempts:X.sampleAttempts,inputReductions:X.inputReductions,messagesOmitted:X.messagesOmitted,filesOmitted:X.filesOmitted,imagesOmitted:X.imagesOmitted,fallbackTargetTokens:X.fallbackTargetTokens,fallbackMessagesOmitted:X.fallbackMessagesOmitted,fallbackMessagesTruncated:X.fallbackMessagesTruncated,failureReason:X.failureReason,filesIncluded:X.filesIncluded,usage:X.usage,memoryPlan:X.memoryPlan};if(W.snippedCount>0)return this.snipRecovery(J,Y,Z.modelName);return{success:!1,messages:$}}catch(X){if(k0(X))throw X;if(rJ(X))return{success:!1,messages:$};if(W.snippedCount>0)return this.snipRecovery(J,Y,Z.modelName);return{success:!1,messages:$}}}snipRecovery($,Z,J){return{success:!0,messages:Z,strategy:"snip",summary:H8,preTokens:r.countTokens($,J),postTokens:r.countTokens(Z,J),filesIncluded:[]}}reset(){this.hasAttempted=!1}}import*as x$ from"fs";import{nanoid as $2}from"nanoid";import*as tZ from"os";import*as K1 from"path";var V8=1e5,z8=2000,B8=200000;class eZ{currentChars=0;track($){this.currentChars+=$}remaining(){return Math.max(0,B8-this.currentChars)}}function Z2($,Z,J){let W=J?.maxCharsPerResult??V8,Y=J?.previewChars??z8,X=J?.messageBudget,K=typeof $==="string"?$:JSON.stringify($,null,2);if(K.length<=W)return j8($,K,Z,Y,X,J);let Q=J?.outputDir??K1.join(tZ.homedir(),".blade","tool-results"),H=`${Z}-${$2(8)}.txt`,V=K1.join(Q,H);try{x$.mkdirSync(Q,{recursive:!0}),x$.writeFileSync(V,K,"utf-8")}catch{let j=K.slice(0,W)+`
82
82
 
83
83
  ... (truncated, ${K.length} total chars)`;if(X)X.track(j.length);return j}let z=K.slice(0,Y),w=`Result too large (${K.length} chars). Full output saved to: ${V}
84
84
 
@@ -92,7 +92,7 @@ Full output saved to: ${Q}`}catch{return`${Z}
92
92
 
93
93
  ${Y}`}}function W2(){return{successfulBash:!1}}function D8($){return typeof $==="string"&&J2.some((Z)=>Z===$)}function L7($){switch($){case"timeout":case"admission":case"spawn":case"finalization":return $;case"unavailable":return"terminal";default:return}}function O7($){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(D8(W))$.category=W}function X2($){return $.successfulBash?void 0:$.category}import I8 from"node:path";import{nanoid as h8}from"nanoid";import{randomUUID as H1}from"node:crypto";import*as x0 from"node:fs/promises";import*as z2 from"node:path";import{Mutex as O8}from"async-mutex";import F8 from"write-file-atomic";var K2=120,$6=128;function Q1($){if(!Array.isArray($)||$.length>120||!$.every((Z)=>typeof Z==="string"&&Z.length>0&&Z.length<=128))return;return[...new Set($)]}function w8($){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=Q1(Z.inputMessageIds),W=Q1($.acknowledgedInputMessageIds);if(!J||!W)return[];let Y=new Set(J);return W.filter((X)=>Y.has(X))}function u1($,Z){let J=$[Z];if(J?.type!=="turn_aborted")return[];let W=w8(J.data);if(W.length===0)return[];let Y=-1;for(let K=Z-1;K>=0;K--){let Q=$[K];if(Q.type==="turn_started"){if(Q.data.turnId!==J.data.turnId)return[];Y=K;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let X=new Set;for(let K=Y+1;K<Z;K++){let Q=$[K];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)X.add(V)}return W.filter((K)=>X.has(K))}import*as c1 from"node:fs/promises";import*as H2 from"node:path";var U8={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},q8=new T$,Q2;async function I$($,Z,J,W=L8){let Y=z$($,Z);return q8.runExclusive(Y,()=>d1($,Z,async(X)=>{let K=H2.dirname(X.inboxPath);await c1.mkdir(K,{recursive:!0,mode:448}),await c1.chmod(K,448);let Q,H=await W(X.inboxPath,{...U8,onCompromised:(V)=>{Q=V}});try{if(Q)throw Q;let V=await J(X);if(Q)throw Q;return V}finally{await H()}}))}async function G8(){return Q2??=await import("proper-lockfile"),Q2}async function L8($,Z){return(await G8()).lock($,Z)}var W6=2,h$=8388608;function Z6($,Z,J){let W={version:W6,sessionId:$,generation:Z,messages:J.map(({recovered:Y,...X})=>X)};return`${JSON.stringify(W)}
95
- `}function J6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function P8($){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 _8($,Z,J){let W;try{W=JSON.parse($)}catch(X){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:X})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==W6||!("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((X)=>{if(!X||typeof X!=="object"||!("id"in X)||typeof X.id!=="string"||!("content"in X)||!P8(X.content)||!("queuedAt"in X)||typeof X.queuedAt!=="number"||"persisted"in X&&typeof X.persisted!=="boolean"||"origin"in X&&X.origin!=="user"&&X.origin!=="background_subagent"&&X.origin!=="team_message"&&X.origin!=="interaction_recovery"&&X.origin!=="user_shell"||"metadata"in X&&(X.metadata===null||typeof X.metadata!=="object"||Array.isArray(X.metadata))||"outputSchema"in X&&X.outputSchema!==void 0&&(!X.outputSchema||typeof X.outputSchema!=="object"||Array.isArray(X.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let K="outputSchema"in X&&X.outputSchema!==void 0?i1(X.outputSchema).schema:void 0;return{id:X.id,content:X.content,queuedAt:X.queuedAt,..."persisted"in X&&X.persisted===!0?{persisted:!0}:{},..."origin"in X&&X.origin?{origin:X.origin}:{},..."metadata"in X&&X.metadata?{metadata:JSON.parse(JSON.stringify(X.metadata))}:{},...K?{outputSchema:K}:{}}});if(new Set(Y.map((X)=>X.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:W6,sessionId:J,generation:W.generation,messages:Y}}function N8($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return u1($,J);return[]}))}function y8($){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 l1{sessionId;stateStorage;writeFile;lockFile;mutex=new O8;generation=H1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=B$($),W={}){let Y=new l1(Z,J,W.writeFile??F8,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await I$(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 X=[...Y.messages,{...$,recovered:!1}],K=H1(),Q=Z6(this.sessionId,K,X);if(Buffer.byteLength(Q)>h$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(X,K,W,Q),{accepted:!0,snapshot:{generation:K,messages:X}}},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 I$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),X=Y.messages.filter((Q)=>!Z.has(Q.id));if(X.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let K=H1();return await this.persistAtPath(X,K,W),{generation:K,messages:X}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await I$(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 I$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let X=H1(),K=Z.map((H)=>({...H})),Q=Z6(this.sessionId,X,K);if(Buffer.byteLength(Q)>h$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(K,X,W,Q),{replaced:!0,snapshot:{generation:X,messages:K}}},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 I$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=H1();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 K=await x0.open($.inboxPath,"r");try{if((await K.stat()).size>h$)throw Error(`Steering inbox exceeds ${h$} bytes: ${$.inboxPath}`);Z=_8(await K.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await K.close()}await x0.chmod($.inboxPath,384)}catch(K){if(!J6(K,"ENOENT"))throw K}let J=new Set,W=new Set;try{let K=V2(await x0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=N8(K),W=y8(K)}catch(K){if(!J6(K,"ENOENT"))throw K}let Y=new Map(this.messages.map((K)=>[K.id,K.recovered])),X=(Z?.messages??[]).filter((K)=>!J.has(K.id)).map((K)=>({...K,recovered:Y.get(K.id)??!0,...K.persisted===!0||W.has(K.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:X,...Z?.version===1&&X.length>0?{migrationRequired:!0}:{},...Z&&X.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await x0.mkdir(z2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await x0.unlink(J.inboxPath).catch((X)=>{if(!J6(X,"ENOENT"))throw X});return}let Y=W??Z6(this.sessionId,Z,$);if(Buffer.byteLength(Y)>h$)throw Error(`Steering inbox exceeds ${h$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as a1 from"node:fs/promises";import{nanoid as V0}from"nanoid";var B2=256;class D0{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=B$(Z)){let W=z$(J,$),Y=D0.instances.get(W);if(!Y)Y=new D0($,Z,J),D0.instances.set(W,Y),D0.pruneIdleInstances(W);else D0.instances.delete(W),D0.instances.set(W,Y);return Y}static release($,Z,J=B$(Z)){D0.instances.delete(z$(J,$))}static pruneIdleInstances($){if(D0.instances.size<=B2)return;for(let[Z,J]of D0.instances){if(Z===$||J.subscribers.size>0)continue;if(D0.instances.delete(Z),D0.instances.size<=B2)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((X)=>{return Y(X),$(X)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((X)=>{return Y(X),$(X)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);$1.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($),D0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,X)=>{let K=Y?await W.readAllValidated(Y):await W.readAll();return X(K),K.filter((Q)=>(Q.seq??0)>=Z)});for(let W of J){if(Y6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(Y6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}$1.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 d1(this.storage,this.sessionId,async(Z)=>{let J=new r1(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(K)=>{await j2(W,Z.transcriptPath,K)}},(K)=>{D2(K,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function j$($){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 O0 extends Error{}var A8="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 X6($,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 X=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=$6)W.push(K)}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 $?Q1($.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 b8($,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),X=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]})),K=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(X.has(V)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)K.add(V)}return K.size}function S2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return u1($,J);return[]}))}function K6($,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 X=W.inputMessageIds.filter((Q)=>!Y.has(Q)),K=W.version===1?b8($,Z.data.turnId):W.interruptedToolCallCount;if(X.length===0&&!W.hadSuccessfulToolResult&&K===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:X,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...K>0?{interruptedToolCallCount:K}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function V1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=K6($,J);if(W)return W}return}function n1($,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:X,subagent_type:K,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 X==="string"&&X===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof Q==="string"&&Y.subagentDescription===Q&&W.description===Q&&(K===void 0||typeof K==="string"&&K===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&H&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var E8=1e4,S8=1e5,f8=2592000000,U2=128,T8=1e6,M8=256;function R8($){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>T8||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 f2($,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,X=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,H=Y.toolCallsCount,V=Y.durationMs,z=Array.isArray(K)?K.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=$6):[];if(typeof X!=="string"||X.length===0||X.length>128||Z!==void 0&&X!==Z||!Array.isArray(K)||K.length>K2||z.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>E8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>S8||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>f8)return;let w;if("goalFinalization"in Y){if(w=R8(Y.goalFinalization),!w)return}return{turnId:X,inputMessageIds:[...new Set(z)],turnsCount:Q,toolCallsCount:H,durationMs:V,...w?{goalFinalization:w}:{}}}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 X=f2(Y,Z);if(X)return X}return}function k8($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=f2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((X)=>X.type==="turn_started"&&X.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function v$($,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,X=new Set,K=new Set;for(let H of $.slice(J+1)){if(H.type==="interaction_requested"){K.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)X.add(z)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((H)=>!Y.has(H.toolCallId)&&!K.has(H.toolCallId)),hadSuccessfulResult:Q.some((H)=>X.has(H.toolCallId))}}class N0{static sessionInitializationRuns=new Map;projectPath;version;stateStorage;initializedSessions=new Set;constructor($=H0(),Z=P2(),J=B$($)){this.projectPath=$,this.version=Z,this.stateStorage=J}createEvent($,Z,J){return{id:V0(),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 D0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=z$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=N0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,Z),N0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(N0.sessionInitializationRuns.get(J)===W)N0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>M8){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z){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 W=new Date().toISOString(),Y={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:W,updatedAt:W},X=this.createEvent("session_created",$,Y);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=y2;return Z}async initialize(){try{await _2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await a1.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,X,K){try{await this.ensureSessionCreated($,X);let Q=new Date().toISOString(),H=V0(),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),w=Z==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],j=typeof J==="string"?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"text",payload:{text:J},createdAt:Q})]:J.map((B)=>this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:B.type==="text"?"text":"image",payload:B.type==="text"?{text:B.text}:{mimeType:x8(B.image_url.url)??"image/png",dataUrl:B.image_url.url},createdAt:Q}));return await this.log($).commitBatch([z,...w,...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=L0(J);if(W.some((X)=>X.type==="turn_recovery_acknowledged"&&X.data.turnId===Z))throw new O0;let Y=W.findLast((X)=>X.type==="turn_aborted"&&X.data.turnId===Z);if(!Y||!K6(W,Y))throw new O0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof O0))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=L0(W),X=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(Z.inboxMessageId)),K=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 B=j.data.payload;if(B.toolName!=="Task"||!B.input||typeof B.input!=="object"||Array.isArray(B.input))return!1;let G=B.input,_=G.resume_from??G.resume;return G.run_in_background===!0&&G.subagent_session_id===Z.childSessionId&&G.description===Z.subagentRef.subagentDescription&&(G.subagent_type===void 0||G.subagent_type===Z.subagentRef.subagentType)&&(G.resume_from===void 0||G.resume===void 0||G.resume_from===G.resume)&&(_===void 0?Z.subagentRef.subagentResumedFrom===void 0:_===Z.subagentRef.subagentResumedFrom)});if(!Q)return J={eligible:!1,acknowledged:X,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(X)return J={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.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(K&&H)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let V=new Date().toISOString(),z=K?.data.messageId??V0(),w=[];if(!K){let j={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:V,metadata:JSON.parse(JSON.stringify(Z.metadata))};w.push(this.createEvent("message_created",$,j)),w.push(this.createEvent("part_created",$,{partId:V0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:V}))}if(!H){let j=Y.findLast((G)=>G.type==="part_created"&&G.data.partType==="subtask_ref"&&G.data.messageId===Q.data.messageId&&G.data.payload!==null&&typeof G.data.payload==="object"&&!Array.isArray(G.data.payload)&&G.data.payload.childSessionId===Z.childSessionId),B=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;w.push(this.createEvent("part_created",$,{partId:V0(),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 B?.startedAt==="string"?B.startedAt:V,finishedAt:V},createdAt:V}))}return J={eligible:!0,acknowledged:!1,persisted:w.length>0,messageId:z},w}),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=L0(J);if(W.some((X)=>X.type==="turn_started"&&X.data.turnId===Z.turnId))throw new O0;let Y=j$(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 O0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=L0(W),X=new Set(Y.flatMap((V)=>V.type==="inbox_acknowledged"?V.data.messageIds:[])),K=[...new Set(J)].filter((V)=>!X.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"||K.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:Z.completedAt})]}let H=j$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof O0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=Q1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let X=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((H)=>{let V=L0(H),z=S2(V),w=V.findLast((v)=>(v.type==="turn_completed"||v.type==="turn_aborted")&&v.data.turnId===Z.turnId);if(w){if(w.type==="turn_completed")throw K=void 0,Q=[],new O0;let v=E2(w.data.recovery),U0=v?X.filter((n)=>v.inputMessageIds.includes(n)):[],f0=U0.filter((n)=>!z.has(n));if(Q=U0,K=K6(V,w,U0),f0.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:f0,acknowledgedAt:Z.abortedAt})]}let j=j$(V).active;if(!j||j.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let B=v$(V,j.turnId),G=w2(V,j.turnId),_=V1(V),b=new Set(Z.recovery?.inputMessageIds??[]),T=_?_.inputMessageIds.filter((v)=>b.has(v)):[],M=[...new Set([...G,...T])],g=B.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,I={version:3,inputMessageIds:M,hadSuccessfulToolResult:g,interruptedToolCallCount:B.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:g&&!B.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:X6(V,j.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:Z.turnId,outcome:"aborted",inputMessageIds:I.inputMessageIds,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent};let m=X.filter((v)=>M.includes(v)),x=m.filter((v)=>!z.has(v));Q=m;let k=new Set(z);for(let v of m)k.add(v);let i=I.inputMessageIds.filter((v)=>!k.has(v)),Z0=I.hadSuccessfulToolResult||I.interruptedToolCallCount>0;K=i.length>0||Z0?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:i,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:L,...l}=Z;return[this.createEvent("turn_aborted",$,{...l,...m.length>0?{acknowledgedInputMessageIds:m}:{},recovery:I}),...x.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:x,acknowledgedAt:Z.abortedAt})]:[]]})}catch(H){if(!(H instanceof O0))throw H}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=L0(Z),W=j$(J).active;return W?v$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=L0(Z),W=j$(J).active;if(W){let Y=v$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(q2(J,W.turnId))return!0}return V1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=L0(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 X=Y.input;return X.run_in_background===!0&&typeof X.subagent_session_id==="string"?[X.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=L0(W),X=j$(Y).active,K=v$(Y);if(!X&&K.orphaned.length===0){if(J=V1(Y),J)return[];throw new O0}let Q=X?q2(Y,X.turnId):void 0;if(X&&Q&&K.orphaned.length===0){let k=v$(Y,X.turnId);J={turnId:X.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:k.hadSuccessfulResult,emptyFinalCorrectionSpent:X6(Y,X.turnId),finalization:Q};let i=new Set(Y.flatMap((l)=>l.type==="inbox_acknowledged"?l.data.messageIds:[])),Z0=Q.inputMessageIds.filter((l)=>!i.has(l)),L=new Date().toISOString();return[...Z0.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Z0,acknowledgedAt:L})]:[],this.createEvent("turn_completed",$,{turnId:X.turnId,completedAt:L,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let H=X?v$(Y,X.turnId):void 0,V=H?.orphaned.some((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId);return n1(k,i)&&i?.error===void 0})??!1,z=H?.orphaned.filter((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId);return i?.toolCallId===k.toolCallId&&i.toolName===k.toolName&&i.error===void 0}).every((k)=>n1(k,Z.adoptedToolResults?.get(k.toolCallId)))??!0,w=new Set(X?.inputMessageIds??[]),j=X?V1(Y):void 0,B=j?j.inputMessageIds.filter((k)=>w.has(k)):[],G=B.length>0,_=X?w2(Y,X.turnId):[],b=H?H.orphaned.filter((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId);return!n1(k,i)}).length:0,T=G&&j?.hadSuccessfulToolResult===!0,M=(H?.hadSuccessfulResult??!1)||V||T;J=X?{turnId:X.turnId,outcome:"aborted",inputMessageIds:[...new Set([..._,...B])],hadSuccessfulToolResult:M,...(()=>{let k=b+(G?j?.interruptedToolCallCount??0:0);return k>0?{interruptedToolCallCount:k}:{}})(),...M&&!(H?.hadSuccessfulResult??!1)&&z&&(!T||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:X6(Y,X.turnId)||G&&j?.emptyFinalCorrectionSpent===!0}:V1(Y);let g=X?H?.all.length??0:0,I=new Date().toISOString(),m=X?Date.parse(X.startedAt):Number.NaN,x=K.orphaned.flatMap((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId),Z0=n1(k,i)?i:void 0,L=this.createEvent("part_created",$,{partId:k.toolCallId,messageId:Z0?k.messageId:k.toolCallId,partType:"tool_result",payload:Z0?{toolCallId:k.toolCallId,toolName:k.toolName,output:Z0.output,error:Z0.error??null,...Z0.metadata===void 0?{}:{metadata:Z0.metadata}}:{toolCallId:k.toolCallId,toolName:k.toolName,output:null,error:A8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:I});if(!Z0?.subagentRef)return[L];let l=Z0.subagentRef;return[L,this.createEvent("part_created",$,{partId:V0(),messageId:k.messageId,partType:"subtask_ref",payload:{childSessionId:l.subagentSessionId,agentType:l.subagentType,description:l.subagentDescription??"",status:l.subagentStatus,summary:l.subagentSummary??"",resumedFrom:l.subagentResumedFrom??null,rootAgentId:l.subagentRootId??l.subagentSessionId,resumeDepth:l.subagentResumeDepth??0,verificationVerdict:l.verificationVerdict??null,startedAt:I,finishedAt:I},createdAt:I})]});return X?[...x,this.createEvent("turn_aborted",$,{turnId:X.turnId,cause:"process_restart",abortedAt:I,turnsCount:0,toolCallsCount:g,durationMs:Number.isFinite(m)?Math.max(0,Date.now()-m):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:x})}catch(W){if(!(W instanceof O0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?k8(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((X)=>X.type==="interaction_requested"&&X.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((X)=>X.type==="interaction_responded"&&X.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((X)=>X.type==="interaction_responded"&&X.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((X)=>X.type==="interaction_recovered"&&X.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((X)=>X.type==="review_started"&&X.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((X)=>X.type==="review_started"&&!J.some((K)=>K.type==="review_completed"&&K.data.reviewId===X.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((X)=>X.type==="review_started"&&X.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((X)=>X.type==="review_completed"&&X.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,X){try{if(X!==void 0&&(X.length===0||X.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=W??V0(),H=[];if(!W){let w={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};H.push(this.createEvent("message_created",$,w))}let V=X??V0(),z={partId:V,messageId:Q,partType:"tool_call",payload:{toolCallId:V,toolName:Z,input:J},createdAt:K};if(H.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let w=J,j=typeof w.subagent_session_id==="string"?w.subagent_session_id:void 0,B=typeof w.subagent_type==="string"?w.subagent_type:void 0;if(j&&B){let G={partId:V0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:j,agentType:B,status:"running",summary:typeof w.description==="string"?w.description:"",startedAt:K},createdAt:K};H.push(this.createEvent("part_created",$,G))}}return await this.log($).commitBatch(H),V}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,Z,J,W,Y=null,X,K,Q,H){try{await this.ensureSessionCreated($,K);let V=new Date().toISOString(),z=Y??V0();return await this.log($).commitValidatedBatch((w)=>{let j=Q?.subagentStatus==="running"?L0(w).findLast((M)=>M.type==="part_created"&&M.data.partType==="subtask_ref"&&M.data.payload!==null&&typeof M.data.payload==="object"&&!Array.isArray(M.data.payload)&&M.data.payload.childSessionId===Q.subagentSessionId&&(M.data.payload.status==="completed"||M.data.payload.status==="failed"||M.data.payload.status==="cancelled")):void 0,B=j?.data.payload,G=H&&typeof H==="object"&&!Array.isArray(H)?H:{},_=B?{...G,subagentSessionId:B.childSessionId,subagentType:B.agentType,description:B.description,subagentStatus:B.status,subagentSummary:B.summary,subagentResumedFrom:B.resumedFrom,subagentRootId:B.rootAgentId,subagentResumeDepth:B.resumeDepth,verificationVerdict:B.verificationVerdict}:H,b=[];if(!Y){let M={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:V};b.push(this.createEvent("message_created",$,M))}let T={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:X??null,..._===void 0?{}:{metadata:_}},createdAt:V};if(b.push(this.createEvent("part_created",$,T)),Q&&!j){let M=Q.subagentStatus==="running"?null:V,g={partId:V0(),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:M},createdAt:V};b.push(this.createEvent("part_created",$,g))}return b}),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(),X=V0(),K={messageId:X,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(J),H={partId:V0(),messageId:X,partType:"summary",payload:{text:Z,metadata:Q,...J.replacementMessages?{replacementMessages:A2(J.replacementMessages)}:{}},createdAt:Y},V=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,H)];return await this.log($).commitBatch(V),X}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=o1([]),W=await this.log($).commitValidatedBatch((X)=>{if(J=o1(L0(X)),J.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${b2}${V0()}`,createdAt:K})]});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=o1(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?L0(Z):null}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=L2(this.projectPath,$);await new r1(Z).delete(),await a1.unlink(O2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await N2(this.projectPath,$,G2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-h4k69z1b.js"),X=await W();if(X)Y(X,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}}function x8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var T2=131072,Q6=new T$;function H6($,Z){return`${I8.resolve($)}\x00${Z}`}function B6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>T2)throw Error(`${Z} exceeds ${T2} 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 v8($,Z){return JSON.stringify($)===JSON.stringify(Z)}function C8($,Z){if($.request.interactionType!=="elicitation")return B6(Z,"Interaction response");return B6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function R2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function p8($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function g8($){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(`
95
+ `}function J6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function P8($){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 _8($,Z,J){let W;try{W=JSON.parse($)}catch(X){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:X})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==W6||!("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((X)=>{if(!X||typeof X!=="object"||!("id"in X)||typeof X.id!=="string"||!("content"in X)||!P8(X.content)||!("queuedAt"in X)||typeof X.queuedAt!=="number"||"persisted"in X&&typeof X.persisted!=="boolean"||"origin"in X&&X.origin!=="user"&&X.origin!=="background_subagent"&&X.origin!=="team_message"&&X.origin!=="interaction_recovery"&&X.origin!=="user_shell"||"metadata"in X&&(X.metadata===null||typeof X.metadata!=="object"||Array.isArray(X.metadata))||"outputSchema"in X&&X.outputSchema!==void 0&&(!X.outputSchema||typeof X.outputSchema!=="object"||Array.isArray(X.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let K="outputSchema"in X&&X.outputSchema!==void 0?i1(X.outputSchema).schema:void 0;return{id:X.id,content:X.content,queuedAt:X.queuedAt,..."persisted"in X&&X.persisted===!0?{persisted:!0}:{},..."origin"in X&&X.origin?{origin:X.origin}:{},..."metadata"in X&&X.metadata?{metadata:JSON.parse(JSON.stringify(X.metadata))}:{},...K?{outputSchema:K}:{}}});if(new Set(Y.map((X)=>X.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:W6,sessionId:J,generation:W.generation,messages:Y}}function N8($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return u1($,J);return[]}))}function y8($){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 l1{sessionId;stateStorage;writeFile;lockFile;mutex=new O8;generation=H1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=B$($),W={}){let Y=new l1(Z,J,W.writeFile??F8,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await I$(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 X=[...Y.messages,{...$,recovered:!1}],K=H1(),Q=Z6(this.sessionId,K,X);if(Buffer.byteLength(Q)>h$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(X,K,W,Q),{accepted:!0,snapshot:{generation:K,messages:X}}},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 I$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),X=Y.messages.filter((Q)=>!Z.has(Q.id));if(X.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let K=H1();return await this.persistAtPath(X,K,W),{generation:K,messages:X}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await I$(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 I$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let X=H1(),K=Z.map((H)=>({...H})),Q=Z6(this.sessionId,X,K);if(Buffer.byteLength(Q)>h$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(K,X,W,Q),{replaced:!0,snapshot:{generation:X,messages:K}}},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 I$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=H1();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 K=await x0.open($.inboxPath,"r");try{if((await K.stat()).size>h$)throw Error(`Steering inbox exceeds ${h$} bytes: ${$.inboxPath}`);Z=_8(await K.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await K.close()}await x0.chmod($.inboxPath,384)}catch(K){if(!J6(K,"ENOENT"))throw K}let J=new Set,W=new Set;try{let K=V2(await x0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=N8(K),W=y8(K)}catch(K){if(!J6(K,"ENOENT"))throw K}let Y=new Map(this.messages.map((K)=>[K.id,K.recovered])),X=(Z?.messages??[]).filter((K)=>!J.has(K.id)).map((K)=>({...K,recovered:Y.get(K.id)??!0,...K.persisted===!0||W.has(K.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:X,...Z?.version===1&&X.length>0?{migrationRequired:!0}:{},...Z&&X.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await x0.mkdir(z2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await x0.unlink(J.inboxPath).catch((X)=>{if(!J6(X,"ENOENT"))throw X});return}let Y=W??Z6(this.sessionId,Z,$);if(Buffer.byteLength(Y)>h$)throw Error(`Steering inbox exceeds ${h$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as a1 from"node:fs/promises";import{nanoid as V0}from"nanoid";var B2=256;class D0{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=B$(Z)){let W=z$(J,$),Y=D0.instances.get(W);if(!Y)Y=new D0($,Z,J),D0.instances.set(W,Y),D0.pruneIdleInstances(W);else D0.instances.delete(W),D0.instances.set(W,Y);return Y}static release($,Z,J=B$(Z)){D0.instances.delete(z$(J,$))}static pruneIdleInstances($){if(D0.instances.size<=B2)return;for(let[Z,J]of D0.instances){if(Z===$||J.subscribers.size>0)continue;if(D0.instances.delete(Z),D0.instances.size<=B2)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((X)=>{return Y(X),$(X)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((X)=>{return Y(X),$(X)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);$1.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($),D0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,X)=>{let K=Y?await W.readAllValidated(Y):await W.readAll();return X(K),K.filter((Q)=>(Q.seq??0)>=Z)});for(let W of J){if(Y6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(Y6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}$1.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 d1(this.storage,this.sessionId,async(Z)=>{let J=new r1(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(K)=>{await j2(W,Z.transcriptPath,K)}},(K)=>{D2(K,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function j$($){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 O0 extends Error{}var A8="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 X6($,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 X=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=$6)W.push(K)}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 $?Q1($.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 b8($,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),X=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]})),K=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(X.has(V)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)K.add(V)}return K.size}function S2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return u1($,J);return[]}))}function K6($,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 X=W.inputMessageIds.filter((Q)=>!Y.has(Q)),K=W.version===1?b8($,Z.data.turnId):W.interruptedToolCallCount;if(X.length===0&&!W.hadSuccessfulToolResult&&K===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:X,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...K>0?{interruptedToolCallCount:K}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function V1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=K6($,J);if(W)return W}return}function n1($,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:X,subagent_type:K,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 X==="string"&&X===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof Q==="string"&&Y.subagentDescription===Q&&W.description===Q&&(K===void 0||typeof K==="string"&&K===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&H&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var E8=1e4,S8=1e5,f8=2592000000,U2=128,T8=1e6,M8=256;function R8($){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>T8||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 f2($,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,X=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,H=Y.toolCallsCount,V=Y.durationMs,z=Array.isArray(K)?K.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=$6):[];if(typeof X!=="string"||X.length===0||X.length>128||Z!==void 0&&X!==Z||!Array.isArray(K)||K.length>K2||z.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>E8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>S8||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>f8)return;let w;if("goalFinalization"in Y){if(w=R8(Y.goalFinalization),!w)return}return{turnId:X,inputMessageIds:[...new Set(z)],turnsCount:Q,toolCallsCount:H,durationMs:V,...w?{goalFinalization:w}:{}}}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 X=f2(Y,Z);if(X)return X}return}function k8($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=f2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((X)=>X.type==="turn_started"&&X.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function v$($,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,X=new Set,K=new Set;for(let H of $.slice(J+1)){if(H.type==="interaction_requested"){K.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)X.add(z)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((H)=>!Y.has(H.toolCallId)&&!K.has(H.toolCallId)),hadSuccessfulResult:Q.some((H)=>X.has(H.toolCallId))}}class N0{static sessionInitializationRuns=new Map;projectPath;version;stateStorage;initializedSessions=new Set;constructor($=H0(),Z=P2(),J=B$($)){this.projectPath=$,this.version=Z,this.stateStorage=J}createEvent($,Z,J){return{id:V0(),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 D0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=z$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=N0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,Z),N0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(N0.sessionInitializationRuns.get(J)===W)N0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>M8){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z){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 W=new Date().toISOString(),Y={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:W,updatedAt:W},X=this.createEvent("session_created",$,Y);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=y2;return Z}async initialize(){try{await _2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await a1.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,X,K){try{await this.ensureSessionCreated($,X);let Q=new Date().toISOString(),H=V0(),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),w=Z==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],j=typeof J==="string"?[this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:"text",payload:{text:J},createdAt:Q})]:J.map((B)=>this.createEvent("part_created",$,{partId:V0(),messageId:H,partType:B.type==="text"?"text":"image",payload:B.type==="text"?{text:B.text}:{mimeType:x8(B.image_url.url)??"image/png",dataUrl:B.image_url.url},createdAt:Q}));return await this.log($).commitBatch([z,...w,...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=L0(J);if(W.some((X)=>X.type==="turn_recovery_acknowledged"&&X.data.turnId===Z))throw new O0;let Y=W.findLast((X)=>X.type==="turn_aborted"&&X.data.turnId===Z);if(!Y||!K6(W,Y))throw new O0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof O0))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=L0(W),X=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(Z.inboxMessageId)),K=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 B=j.data.payload;if(B.toolName!=="Task"||!B.input||typeof B.input!=="object"||Array.isArray(B.input))return!1;let G=B.input,_=G.resume_from??G.resume;return G.run_in_background===!0&&G.subagent_session_id===Z.childSessionId&&G.description===Z.subagentRef.subagentDescription&&(G.subagent_type===void 0||G.subagent_type===Z.subagentRef.subagentType)&&(G.resume_from===void 0||G.resume===void 0||G.resume_from===G.resume)&&(_===void 0?Z.subagentRef.subagentResumedFrom===void 0:_===Z.subagentRef.subagentResumedFrom)});if(!Q)return J={eligible:!1,acknowledged:X,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(X)return J={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.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(K&&H)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let V=new Date().toISOString(),z=K?.data.messageId??V0(),w=[];if(!K){let j={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:V,metadata:JSON.parse(JSON.stringify(Z.metadata))};w.push(this.createEvent("message_created",$,j)),w.push(this.createEvent("part_created",$,{partId:V0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:V}))}if(!H){let j=Y.findLast((G)=>G.type==="part_created"&&G.data.partType==="subtask_ref"&&G.data.messageId===Q.data.messageId&&G.data.payload!==null&&typeof G.data.payload==="object"&&!Array.isArray(G.data.payload)&&G.data.payload.childSessionId===Z.childSessionId),B=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;w.push(this.createEvent("part_created",$,{partId:V0(),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 B?.startedAt==="string"?B.startedAt:V,finishedAt:V},createdAt:V}))}return J={eligible:!0,acknowledged:!1,persisted:w.length>0,messageId:z},w}),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=L0(J);if(W.some((X)=>X.type==="turn_started"&&X.data.turnId===Z.turnId))throw new O0;let Y=j$(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 O0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=L0(W),X=new Set(Y.flatMap((V)=>V.type==="inbox_acknowledged"?V.data.messageIds:[])),K=[...new Set(J)].filter((V)=>!X.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"||K.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:Z.completedAt})]}let H=j$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof O0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=Q1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let X=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((H)=>{let V=L0(H),z=S2(V),w=V.findLast((v)=>(v.type==="turn_completed"||v.type==="turn_aborted")&&v.data.turnId===Z.turnId);if(w){if(w.type==="turn_completed")throw K=void 0,Q=[],new O0;let v=E2(w.data.recovery),U0=v?X.filter((n)=>v.inputMessageIds.includes(n)):[],f0=U0.filter((n)=>!z.has(n));if(Q=U0,K=K6(V,w,U0),f0.length===0)throw new O0;return[this.createEvent("inbox_acknowledged",$,{messageIds:f0,acknowledgedAt:Z.abortedAt})]}let j=j$(V).active;if(!j||j.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let B=v$(V,j.turnId),G=w2(V,j.turnId),_=V1(V),b=new Set(Z.recovery?.inputMessageIds??[]),T=_?_.inputMessageIds.filter((v)=>b.has(v)):[],M=[...new Set([...G,...T])],g=B.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,I={version:3,inputMessageIds:M,hadSuccessfulToolResult:g,interruptedToolCallCount:B.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:g&&!B.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:X6(V,j.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:Z.turnId,outcome:"aborted",inputMessageIds:I.inputMessageIds,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent};let m=X.filter((v)=>M.includes(v)),x=m.filter((v)=>!z.has(v));Q=m;let k=new Set(z);for(let v of m)k.add(v);let i=I.inputMessageIds.filter((v)=>!k.has(v)),Z0=I.hadSuccessfulToolResult||I.interruptedToolCallCount>0;K=i.length>0||Z0?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:i,hadSuccessfulToolResult:I.hadSuccessfulToolResult,...I.interruptedToolCallCount>0?{interruptedToolCallCount:I.interruptedToolCallCount}:{},...I.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:I.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:L,...l}=Z;return[this.createEvent("turn_aborted",$,{...l,...m.length>0?{acknowledgedInputMessageIds:m}:{},recovery:I}),...x.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:x,acknowledgedAt:Z.abortedAt})]:[]]})}catch(H){if(!(H instanceof O0))throw H}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=L0(Z),W=j$(J).active;return W?v$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=L0(Z),W=j$(J).active;if(W){let Y=v$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(q2(J,W.turnId))return!0}return V1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=L0(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 X=Y.input;return X.run_in_background===!0&&typeof X.subagent_session_id==="string"?[X.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=L0(W),X=j$(Y).active,K=v$(Y);if(!X&&K.orphaned.length===0){if(J=V1(Y),J)return[];throw new O0}let Q=X?q2(Y,X.turnId):void 0;if(X&&Q&&K.orphaned.length===0){let k=v$(Y,X.turnId);J={turnId:X.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:k.hadSuccessfulResult,emptyFinalCorrectionSpent:X6(Y,X.turnId),finalization:Q};let i=new Set(Y.flatMap((l)=>l.type==="inbox_acknowledged"?l.data.messageIds:[])),Z0=Q.inputMessageIds.filter((l)=>!i.has(l)),L=new Date().toISOString();return[...Z0.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Z0,acknowledgedAt:L})]:[],this.createEvent("turn_completed",$,{turnId:X.turnId,completedAt:L,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let H=X?v$(Y,X.turnId):void 0,V=H?.orphaned.some((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId);return n1(k,i)&&i?.error===void 0})??!1,z=H?.orphaned.filter((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId);return i?.toolCallId===k.toolCallId&&i.toolName===k.toolName&&i.error===void 0}).every((k)=>n1(k,Z.adoptedToolResults?.get(k.toolCallId)))??!0,w=new Set(X?.inputMessageIds??[]),j=X?V1(Y):void 0,B=j?j.inputMessageIds.filter((k)=>w.has(k)):[],G=B.length>0,_=X?w2(Y,X.turnId):[],b=H?H.orphaned.filter((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId);return!n1(k,i)}).length:0,T=G&&j?.hadSuccessfulToolResult===!0,M=(H?.hadSuccessfulResult??!1)||V||T;J=X?{turnId:X.turnId,outcome:"aborted",inputMessageIds:[...new Set([..._,...B])],hadSuccessfulToolResult:M,...(()=>{let k=b+(G?j?.interruptedToolCallCount??0:0);return k>0?{interruptedToolCallCount:k}:{}})(),...M&&!(H?.hadSuccessfulResult??!1)&&z&&(!T||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:X6(Y,X.turnId)||G&&j?.emptyFinalCorrectionSpent===!0}:V1(Y);let g=X?H?.all.length??0:0,I=new Date().toISOString(),m=X?Date.parse(X.startedAt):Number.NaN,x=K.orphaned.flatMap((k)=>{let i=Z.adoptedToolResults?.get(k.toolCallId),Z0=n1(k,i)?i:void 0,L=this.createEvent("part_created",$,{partId:k.toolCallId,messageId:Z0?k.messageId:k.toolCallId,partType:"tool_result",payload:Z0?{toolCallId:k.toolCallId,toolName:k.toolName,output:Z0.output,error:Z0.error??null,...Z0.metadata===void 0?{}:{metadata:Z0.metadata}}:{toolCallId:k.toolCallId,toolName:k.toolName,output:null,error:A8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:I});if(!Z0?.subagentRef)return[L];let l=Z0.subagentRef;return[L,this.createEvent("part_created",$,{partId:V0(),messageId:k.messageId,partType:"subtask_ref",payload:{childSessionId:l.subagentSessionId,agentType:l.subagentType,description:l.subagentDescription??"",status:l.subagentStatus,summary:l.subagentSummary??"",resumedFrom:l.subagentResumedFrom??null,rootAgentId:l.subagentRootId??l.subagentSessionId,resumeDepth:l.subagentResumeDepth??0,verificationVerdict:l.verificationVerdict??null,startedAt:I,finishedAt:I},createdAt:I})]});return X?[...x,this.createEvent("turn_aborted",$,{turnId:X.turnId,cause:"process_restart",abortedAt:I,turnsCount:0,toolCallsCount:g,durationMs:Number.isFinite(m)?Math.max(0,Date.now()-m):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:x})}catch(W){if(!(W instanceof O0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?k8(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((X)=>X.type==="interaction_requested"&&X.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((X)=>X.type==="interaction_responded"&&X.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((X)=>X.type==="interaction_responded"&&X.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((X)=>X.type==="interaction_recovered"&&X.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((X)=>X.type==="review_started"&&X.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((X)=>X.type==="review_started"&&!J.some((K)=>K.type==="review_completed"&&K.data.reviewId===X.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((X)=>X.type==="review_started"&&X.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((X)=>X.type==="review_completed"&&X.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,X){try{if(X!==void 0&&(X.length===0||X.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=W??V0(),H=[];if(!W){let w={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};H.push(this.createEvent("message_created",$,w))}let V=X??V0(),z={partId:V,messageId:Q,partType:"tool_call",payload:{toolCallId:V,toolName:Z,input:J},createdAt:K};if(H.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let w=J,j=typeof w.subagent_session_id==="string"?w.subagent_session_id:void 0,B=typeof w.subagent_type==="string"?w.subagent_type:void 0;if(j&&B){let G={partId:V0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:j,agentType:B,status:"running",summary:typeof w.description==="string"?w.description:"",startedAt:K},createdAt:K};H.push(this.createEvent("part_created",$,G))}}return await this.log($).commitBatch(H),V}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,Z,J,W,Y=null,X,K,Q,H){try{await this.ensureSessionCreated($,K);let V=new Date().toISOString(),z=Y??V0();return await this.log($).commitValidatedBatch((w)=>{let j=Q?.subagentStatus==="running"?L0(w).findLast((M)=>M.type==="part_created"&&M.data.partType==="subtask_ref"&&M.data.payload!==null&&typeof M.data.payload==="object"&&!Array.isArray(M.data.payload)&&M.data.payload.childSessionId===Q.subagentSessionId&&(M.data.payload.status==="completed"||M.data.payload.status==="failed"||M.data.payload.status==="cancelled")):void 0,B=j?.data.payload,G=H&&typeof H==="object"&&!Array.isArray(H)?H:{},_=B?{...G,subagentSessionId:B.childSessionId,subagentType:B.agentType,description:B.description,subagentStatus:B.status,subagentSummary:B.summary,subagentResumedFrom:B.resumedFrom,subagentRootId:B.rootAgentId,subagentResumeDepth:B.resumeDepth,verificationVerdict:B.verificationVerdict}:H,b=[];if(!Y){let M={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:V};b.push(this.createEvent("message_created",$,M))}let T={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:X??null,..._===void 0?{}:{metadata:_}},createdAt:V};if(b.push(this.createEvent("part_created",$,T)),Q&&!j){let M=Q.subagentStatus==="running"?null:V,g={partId:V0(),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:M},createdAt:V};b.push(this.createEvent("part_created",$,g))}return b}),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(),X=V0(),K={messageId:X,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(J),H={partId:V0(),messageId:X,partType:"summary",payload:{text:Z,metadata:Q,...J.replacementMessages?{replacementMessages:A2(J.replacementMessages)}:{}},createdAt:Y},V=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,H)];return await this.log($).commitBatch(V),X}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=o1([]),W=await this.log($).commitValidatedBatch((X)=>{if(J=o1(L0(X)),J.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${b2}${V0()}`,createdAt:K})]});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=o1(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?L0(Z):null}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=L2(this.projectPath,$);await new r1(Z).delete(),await a1.unlink(O2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await N2(this.projectPath,$,G2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-80946c9a.js"),X=await W();if(X)Y(X,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}}function x8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var T2=131072,Q6=new T$;function H6($,Z){return`${I8.resolve($)}\x00${Z}`}function B6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>T2)throw Error(`${Z} exceeds ${T2} 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 v8($,Z){return JSON.stringify($)===JSON.stringify(Z)}function C8($,Z){if($.request.interactionType!=="elicitation")return B6(Z,"Interaction response");return B6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function R2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function p8($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function g8($){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
96
  `)}function m8($,Z){let{request:J}=$;if(J.interactionType==="question"){let K=g8(Z);return{toolOutput:`User answers:
97
97
  ${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
98
98
  ${K}
@@ -269,7 +269,7 @@ When facing complex multi-step tasks:
269
269
  2. Execute one step at a time — verify each step succeeded before moving to the next.
270
270
  3. If a step fails, diagnose the root cause rather than repeating the same approach.
271
271
  4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
272
- 5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var D$=P0("Agent"),P9=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class YZ{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;progressSink;requireDurableToolUse;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;hasExclusiveBarrier=!1;epoch=0;activeAborts=new Map;executeTool;admitTool;rollbackAdmission;turnAdmission=new z1;toolUsePersistenceTail=Promise.resolve();constructor($,Z,J,W,Y,X,K,Q,H=!1){this.pipeline=$;this.execContext=Z;this.registry=J;this.contextMgr=W;this.sessionId=Y;this.lastMessageUuid=X;this.subagentInfo=K;this.progressSink=Q;this.requireDurableToolUse=H}setExecutionPolicy($){this.executeTool=$}setAdmissionPolicy($){this.admitTool=$}setAdmissionRollback($){this.rollbackAdmission=$}addTool($,Z){if(this.dispatched.has($.id))return D$.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`),"rejected";this.dispatched.add($.id),this.order.push($.id);let J=this.turnAdmission.admit();if(J)return this.completed.set($.id,{toolCall:$,result:J,toolUseUuid:null}),"rejected";B1($.function.name,Z),$.function.arguments=JSON.stringify(Z);let W=this.admitTool?.($.function.name,Z);if(W)return this.completed.set($.id,{toolCall:$,result:W,toolUseUuid:null}),"rejected";let Y=this.registry.get($.function.name),X=Y?.isConcurrencySafe===!0,K=Y?.parallelism==="shared"||Y?.parallelism===void 0&&X;if(P9.has($.function.name)&&X&&!this.hasExclusiveBarrier){D$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let H=this.executeOne($,Z);return this.pending.set($.id,H),"prelaunched"}else{if(D$.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:Z}),!K)this.hasExclusiveBarrier=!0;return"queued"}}getQueuedToolCalls(){return this.queued.map(($)=>$.toolCall)}async*getRemainingResults(){this.dispatchQueuedTools();for(let $ of this.order){if(this.completed.has($)){yield this.completed.get($),this.completed.delete($);continue}if(this.pending.has($)){let Z=await this.pending.get($);this.pending.delete($),yield Z;continue}}}getCompletedResults(){let $=Array.from(this.completed.values());return this.completed.clear(),$}discard(){for(let $ of this.queued)this.rollbackAdmission?.($.toolCall.function.name);this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,$]of this.activeAborts)$.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),this.hasExclusiveBarrier=!1,this.turnAdmission.reset(),this.toolUsePersistenceTail=Promise.resolve(),D$.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,Z,J=null){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:J}}dispatchQueuedTools(){let $=this.queued;this.queued=[],this.hasExclusiveBarrier=!1;let Z=this.epoch;for(let{toolCall:J,params:W}of $){if(this.execContext.signal?.aborted){this.completed.set(J.id,this.makeAbortResult(J,"Tool execution skipped: task aborted before launch"));continue}let Y=this.executeQueued(J,W,Z);this.pending.set(J.id,Y)}}async executeQueued($,Z,J){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");if(this.execContext.signal?.aborted)return this.makeAbortResult($,"Tool execution skipped: task aborted before launch");return this.executeOne($,Z)}async executeOne($,Z){let J=this.epoch,W=new AbortController;this.activeAborts.set($.id,W);let Y=null,X=this.abortController.signal;try{if(X.aborted||W.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");try{if(this.contextMgr&&this.sessionId)Y=await this.persistToolUseInOrder($,Z);else if(this.requireDurableToolUse&&this.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(j){if(D$.warn("[StreamingToolExecutor] 保存工具调用失败:",j),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:Q$,error:{type:"execution_error",message:Q$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:j instanceof Error?j:Error(String(j))}}let K=[X,W.signal],Q=this.execContext.signal;if(Q)K.push(Q);let H=X4(...K),V={...this.execContext,messageId:Y??$.id,signal:H,confirmationHandler:this.execContext.sessionId&&this.execContext.workspaceRoot&&this.execContext.workspaceKind!=="acp-remote"?B0.createConfirmationHandler(this.execContext.confirmationHandler,{sessionId:this.execContext.sessionId,projectPath:this.execContext.workspaceRoot,toolCallId:Y??$.id,toolName:$.function.name}):this.execContext.confirmationHandler,onProgress:(j)=>{this.execContext.onProgress?.(j),this.progressSink?.($,{message:j.slice(0,1000)})},onProgressUpdate:(j)=>{this.execContext.onProgressUpdate?.(j),this.progressSink?.($,j)}},z=this.executeTool?await this.executeTool($.function.name,Z,V):await this.pipeline.execute($.function.name,Z,V);if(J!==this.epoch)return D$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${J}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let w={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,w);return w}catch(K){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);D$.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,K);let Q={success:!1,llmContent:"",error:{type:"execution_error",message:K instanceof Error?K.message:"Unknown error"},metadata:void 0},H={toolCall:$,result:Q,toolUseUuid:Y,error:K instanceof Error?K:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,H);return H}finally{this.activeAborts.delete($.id)}}persistToolUseInOrder($,Z){let J=this.contextMgr,W=this.sessionId;if(!J||!W)return Promise.resolve(null);let Y=this.toolUsePersistenceTail.then(()=>J.saveToolUse(W,$.function.name,Z,this.lastMessageUuid??null,this.subagentInfo,$.id));return this.toolUsePersistenceTail=Y.then(()=>{return},()=>{return}),Y}}class _6{pending=[];waiters=[];closed=!1;push($){if(this.closed)return;let Z=this.waiters.shift();if(Z){Z($);return}if(this.pending.length>=256)this.pending.shift();this.pending.push($)}shift(){return this.pending.shift()}next(){let $=this.shift();if($)return Promise.resolve($);if(this.closed)return Promise.resolve(void 0);return new Promise((Z)=>{this.waiters.push(Z)})}get hasPending(){return this.pending.length>0}close(){if(this.closed)return;this.closed=!0;for(let $ of this.waiters.splice(0))$(void 0)}}function K4($,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let J=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||J.tasks||[]}}function Q4($,Z,J){if($.function.name!=="Skill"||!Z.success||!Z.metadata)return;let W=Z.metadata;if(W.skillName)J.onSkillActivated?.({skillName:W.skillName,allowedTools:W.allowedTools,basePath:W.basePath||""})}function H4($){let Z=$.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function _9($,Z,J){if(!["EnterWorktree","ExitWorktree"].includes($.function.name)||!Z.success)return;let W=Z.metadata,Y=W?.workspaceRoot;if(!["enter","exit"].includes(String(W?.workspaceTransition))||typeof Y!=="string"||Y.trim()==="")return;return E$.getInstance().inheritProjectConfig(J.workspaceRoot,Y,J.sessionId),J.workspaceRoot=Y,J.worktreeActive=W?.workspaceTransition==="enter",Y}function N9($,Z){if($.function.name!=="Task")return null;let J=Z.metadata;if(!J?.subagentSessionId)return null;let W=J.subagentSessionId,Y=J.subagentType||"Task",X=J.subagentStatus,K=typeof J.subagentResumedFrom==="string"?J.subagentResumedFrom:void 0,Q=typeof J.subagentRootId==="string"?J.subagentRootId:void 0,H=typeof J.subagentResumeDepth==="number"?J.subagentResumeDepth:void 0;if(X==="completed"||X==="failed"||X==="cancelled")return{kind:"subagent_completed",sessionId:W,type:Y,success:X==="completed",summary:J.subagentSummary,...J.verificationVerdict==="pass"||J.verificationVerdict==="fail"||J.verificationVerdict==="partial"?{verificationVerdict:J.verificationVerdict}:{},...K?{resumedFrom:K}:{},...Q?{rootAgentId:Q}:{},...H!==void 0?{resumeDepth:H}:{}};if(X==="running"){let V="";try{V=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:W,type:Y,prompt:V,resumedFrom:K,rootAgentId:Q,resumeDepth:H}}return null}async function N6($,Z,J,W){let Y=K4($,Z),X=N9($,Z);Q4($,Z,J);let K=H4(Z);if(K)await J.onModelSwitch?.(K);if(W)_9($,Z,W);return X||Y}var c=P0("Agent");function w$($,Z,J){return{...J?{scope:J}:{},inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:m1($)??0,maxContextTokens:Z,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function Z$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function V4($){let Z=$.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let J=JSON.parse(Z);if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return null}catch{return null}}function j1($){let Z=V4($);if(Z)return Z;try{let J=JSON.parse($);return typeof J==="string"?V4(J):null}catch{return null}}function y9($){let Z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(Z?.contextualProjectRules!==!0)return[];if(!Array.isArray(Z.ruleReferences))throw Error("Invalid contextual project rule provenance");return Z.ruleReferences.map((J)=>{if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Invalid contextual project rule reference");let W=J;if(typeof W.id!=="string"||typeof W.relativePath!=="string"||!["project","local"].includes(String(W.source))||typeof W.contentSha256!=="string"||!/^[a-f0-9]{64}$/u.test(W.contentSha256))throw Error("Invalid contextual project rule reference");return{id:W.id,relativePath:W.relativePath,source:W.source,contentSha256:W.contentSha256}})}function p$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function A9($){let Z=new Set,J=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let X of W.tool_calls)if("function"in X&&X.function.name==="Task")Z.add(X.id)}else if(J)J=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!Z.has(W.tool_call_id)||typeof W.metadata!=="object"||W.metadata===null||Array.isArray(W.metadata))continue;let Y=W.metadata;if(Y.toolCallId===W.tool_call_id&&Y.toolName==="Task"&&Y.error===null)J=!0}return J}function b9($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let Q=JSON.parse(W.responseBody)?.error?.message;if(Q){let H=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${Q}${H}`}}catch{}let Y=$.message,X=Y.match(/Last error:\s*(.+)$/);if(X)return X[1];return Y}function E9($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((J)=>$.message.toLowerCase().includes(J.toLowerCase()))}function S9($,Z){if(!Z)return"Tool execution failed (no details).";let J=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")J.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")J.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")J.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let W=Z.message??"";if(W.includes("ENOENT")||W.includes("no such file"))J.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(W.includes("EACCES")||W.includes("permission"))J.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(W.includes("not found in file")||W.includes("old_string"))J.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(W.includes("ENOTDIR"))J.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return J.join(`
272
+ 5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var D$=P0("Agent"),P9=new Set(["Read","FindFiles","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class YZ{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;progressSink;requireDurableToolUse;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;hasExclusiveBarrier=!1;epoch=0;activeAborts=new Map;executeTool;admitTool;rollbackAdmission;turnAdmission=new z1;toolUsePersistenceTail=Promise.resolve();constructor($,Z,J,W,Y,X,K,Q,H=!1){this.pipeline=$;this.execContext=Z;this.registry=J;this.contextMgr=W;this.sessionId=Y;this.lastMessageUuid=X;this.subagentInfo=K;this.progressSink=Q;this.requireDurableToolUse=H}setExecutionPolicy($){this.executeTool=$}setAdmissionPolicy($){this.admitTool=$}setAdmissionRollback($){this.rollbackAdmission=$}addTool($,Z){if(this.dispatched.has($.id))return D$.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`),"rejected";this.dispatched.add($.id),this.order.push($.id);let J=this.turnAdmission.admit();if(J)return this.completed.set($.id,{toolCall:$,result:J,toolUseUuid:null}),"rejected";B1($.function.name,Z),$.function.arguments=JSON.stringify(Z);let W=this.admitTool?.($.function.name,Z);if(W)return this.completed.set($.id,{toolCall:$,result:W,toolUseUuid:null}),"rejected";let Y=this.registry.get($.function.name),X=Y?.isConcurrencySafe===!0,K=Y?.parallelism==="shared"||Y?.parallelism===void 0&&X;if(P9.has($.function.name)&&X&&!this.hasExclusiveBarrier){D$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let H=this.executeOne($,Z);return this.pending.set($.id,H),"prelaunched"}else{if(D$.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:Z}),!K)this.hasExclusiveBarrier=!0;return"queued"}}getQueuedToolCalls(){return this.queued.map(($)=>$.toolCall)}async*getRemainingResults(){this.dispatchQueuedTools();for(let $ of this.order){if(this.completed.has($)){yield this.completed.get($),this.completed.delete($);continue}if(this.pending.has($)){let Z=await this.pending.get($);this.pending.delete($),yield Z;continue}}}getCompletedResults(){let $=Array.from(this.completed.values());return this.completed.clear(),$}discard(){for(let $ of this.queued)this.rollbackAdmission?.($.toolCall.function.name);this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,$]of this.activeAborts)$.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),this.hasExclusiveBarrier=!1,this.turnAdmission.reset(),this.toolUsePersistenceTail=Promise.resolve(),D$.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,Z,J=null){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:J}}dispatchQueuedTools(){let $=this.queued;this.queued=[],this.hasExclusiveBarrier=!1;let Z=this.epoch;for(let{toolCall:J,params:W}of $){if(this.execContext.signal?.aborted){this.completed.set(J.id,this.makeAbortResult(J,"Tool execution skipped: task aborted before launch"));continue}let Y=this.executeQueued(J,W,Z);this.pending.set(J.id,Y)}}async executeQueued($,Z,J){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");if(this.execContext.signal?.aborted)return this.makeAbortResult($,"Tool execution skipped: task aborted before launch");return this.executeOne($,Z)}async executeOne($,Z){let J=this.epoch,W=new AbortController;this.activeAborts.set($.id,W);let Y=null,X=this.abortController.signal;try{if(X.aborted||W.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");try{if(this.contextMgr&&this.sessionId)Y=await this.persistToolUseInOrder($,Z);else if(this.requireDurableToolUse&&this.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(j){if(D$.warn("[StreamingToolExecutor] 保存工具调用失败:",j),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:Q$,error:{type:"execution_error",message:Q$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:j instanceof Error?j:Error(String(j))}}let K=[X,W.signal],Q=this.execContext.signal;if(Q)K.push(Q);let H=X4(...K),V={...this.execContext,messageId:Y??$.id,signal:H,confirmationHandler:this.execContext.sessionId&&this.execContext.workspaceRoot&&this.execContext.workspaceKind!=="acp-remote"?B0.createConfirmationHandler(this.execContext.confirmationHandler,{sessionId:this.execContext.sessionId,projectPath:this.execContext.workspaceRoot,toolCallId:Y??$.id,toolName:$.function.name}):this.execContext.confirmationHandler,onProgress:(j)=>{this.execContext.onProgress?.(j),this.progressSink?.($,{message:j.slice(0,1000)})},onProgressUpdate:(j)=>{this.execContext.onProgressUpdate?.(j),this.progressSink?.($,j)}},z=this.executeTool?await this.executeTool($.function.name,Z,V):await this.pipeline.execute($.function.name,Z,V);if(J!==this.epoch)return D$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${J}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let w={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,w);return w}catch(K){if(J!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);D$.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,K);let Q={success:!1,llmContent:"",error:{type:"execution_error",message:K instanceof Error?K.message:"Unknown error"},metadata:void 0},H={toolCall:$,result:Q,toolUseUuid:Y,error:K instanceof Error?K:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,H);return H}finally{this.activeAborts.delete($.id)}}persistToolUseInOrder($,Z){let J=this.contextMgr,W=this.sessionId;if(!J||!W)return Promise.resolve(null);let Y=this.toolUsePersistenceTail.then(()=>J.saveToolUse(W,$.function.name,Z,this.lastMessageUuid??null,this.subagentInfo,$.id));return this.toolUsePersistenceTail=Y.then(()=>{return},()=>{return}),Y}}class _6{pending=[];waiters=[];closed=!1;push($){if(this.closed)return;let Z=this.waiters.shift();if(Z){Z($);return}if(this.pending.length>=256)this.pending.shift();this.pending.push($)}shift(){return this.pending.shift()}next(){let $=this.shift();if($)return Promise.resolve($);if(this.closed)return Promise.resolve(void 0);return new Promise((Z)=>{this.waiters.push(Z)})}get hasPending(){return this.pending.length>0}close(){if(this.closed)return;this.closed=!0;for(let $ of this.waiters.splice(0))$(void 0)}}function K4($,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let J=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||J.tasks||[]}}function Q4($,Z,J){if($.function.name!=="Skill"||!Z.success||!Z.metadata)return;let W=Z.metadata;if(W.skillName)J.onSkillActivated?.({skillName:W.skillName,allowedTools:W.allowedTools,basePath:W.basePath||""})}function H4($){let Z=$.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function _9($,Z,J){if(!["EnterWorktree","ExitWorktree"].includes($.function.name)||!Z.success)return;let W=Z.metadata,Y=W?.workspaceRoot;if(!["enter","exit"].includes(String(W?.workspaceTransition))||typeof Y!=="string"||Y.trim()==="")return;return E$.getInstance().inheritProjectConfig(J.workspaceRoot,Y,J.sessionId),J.workspaceRoot=Y,J.worktreeActive=W?.workspaceTransition==="enter",Y}function N9($,Z){if($.function.name!=="Task")return null;let J=Z.metadata;if(!J?.subagentSessionId)return null;let W=J.subagentSessionId,Y=J.subagentType||"Task",X=J.subagentStatus,K=typeof J.subagentResumedFrom==="string"?J.subagentResumedFrom:void 0,Q=typeof J.subagentRootId==="string"?J.subagentRootId:void 0,H=typeof J.subagentResumeDepth==="number"?J.subagentResumeDepth:void 0;if(X==="completed"||X==="failed"||X==="cancelled")return{kind:"subagent_completed",sessionId:W,type:Y,success:X==="completed",summary:J.subagentSummary,...J.verificationVerdict==="pass"||J.verificationVerdict==="fail"||J.verificationVerdict==="partial"?{verificationVerdict:J.verificationVerdict}:{},...K?{resumedFrom:K}:{},...Q?{rootAgentId:Q}:{},...H!==void 0?{resumeDepth:H}:{}};if(X==="running"){let V="";try{V=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:W,type:Y,prompt:V,resumedFrom:K,rootAgentId:Q,resumeDepth:H}}return null}async function N6($,Z,J,W){let Y=K4($,Z),X=N9($,Z);Q4($,Z,J);let K=H4(Z);if(K)await J.onModelSwitch?.(K);if(W)_9($,Z,W);return X||Y}var c=P0("Agent");function w$($,Z,J){return{...J?{scope:J}:{},inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:m1($)??0,maxContextTokens:Z,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function Z$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function V4($){let Z=$.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let J=JSON.parse(Z);if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return null}catch{return null}}function j1($){let Z=V4($);if(Z)return Z;try{let J=JSON.parse($);return typeof J==="string"?V4(J):null}catch{return null}}function y9($){let Z=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(Z?.contextualProjectRules!==!0)return[];if(!Array.isArray(Z.ruleReferences))throw Error("Invalid contextual project rule provenance");return Z.ruleReferences.map((J)=>{if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Invalid contextual project rule reference");let W=J;if(typeof W.id!=="string"||typeof W.relativePath!=="string"||!["project","local"].includes(String(W.source))||typeof W.contentSha256!=="string"||!/^[a-f0-9]{64}$/u.test(W.contentSha256))throw Error("Invalid contextual project rule reference");return{id:W.id,relativePath:W.relativePath,source:W.source,contentSha256:W.contentSha256}})}function p$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function A9($){let Z=new Set,J=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let X of W.tool_calls)if("function"in X&&X.function.name==="Task")Z.add(X.id)}else if(J)J=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!Z.has(W.tool_call_id)||typeof W.metadata!=="object"||W.metadata===null||Array.isArray(W.metadata))continue;let Y=W.metadata;if(Y.toolCallId===W.tool_call_id&&Y.toolName==="Task"&&Y.error===null)J=!0}return J}function b9($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let Q=JSON.parse(W.responseBody)?.error?.message;if(Q){let H=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${Q}${H}`}}catch{}let Y=$.message,X=Y.match(/Last error:\s*(.+)$/);if(X)return X[1];return Y}function E9($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((J)=>$.message.toLowerCase().includes(J.toLowerCase()))}function S9($,Z){if(!Z)return"Tool execution failed (no details).";let J=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")J.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")J.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")J.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let W=Z.message??"";if(W.includes("ENOENT")||W.includes("no such file"))J.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(W.includes("EACCES")||W.includes("permission"))J.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(W.includes("not found in file")||W.includes("old_string"))J.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(W.includes("ENOTDIR"))J.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return J.join(`
273
273
  `)}function y6($){if(!($ instanceof Error))return!1;return p1($)||$.status===413}function f9($,Z){let J=Z,W=J.index??0;if(!$.has(W))$.set(W,{id:J.id||"",name:J.function?.name||"",arguments:""});let Y=$.get(W);if(J.id&&!Y.id)Y.id=J.id;if(J.function?.name&&!Y.name)Y.name=J.function.name;if(J.function?.arguments)Y.arguments+=J.function.arguments}function T9($){if($.size===0)return;return Array.from($.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*M9($,Z,J,W,Y,X){let K="",Q="",H,V,z=new Map;try{let w=$.chatService.streamChat(Z,J,W,Y),j=0;for await(let B of w){if(W?.aborted)break;if(B.providerAdmission){yield{kind:"provider_admission",...B.providerAdmission};continue}if(B.providerCircuit){yield{kind:"provider_circuit",...B.providerCircuit};continue}if(B.providerRetry){yield{kind:"provider_retry",...B.providerRetry};continue}if(B.providerStall){yield{kind:"provider_stall",...B.providerStall};continue}if(j++,B.modelFallback){X?.discard(),K="",Q="",H=void 0,V=void 0,z.clear(),j=0,yield{kind:"model_fallback",...B.modelFallback};continue}if(B.content)K+=B.content,yield{kind:"content_delta",delta:B.content};if(B.reasoningContent)Q+=B.reasoningContent,yield{kind:"thinking_delta",delta:B.reasoningContent};if(B.usage)H=B.usage;if(B.toolCalls){for(let G of B.toolCalls)if(f9(z,G),X){let b=G.index??0,T=z.get(b);if(T&&T.id&&T.name)try{let M=j1(T.arguments);if(M===null)continue;let g={id:T.id,type:"function",function:{name:T.name,arguments:T.arguments}},m=$.toolExecutor.getRegistry().get(T.name)?.kind,x=X.addTool(g,M);if(T.arguments=g.function.arguments,x==="prelaunched")yield{kind:"tool_start",toolCall:g,toolKind:m}}catch{}}}if(B.finishReason){V=B.finishReason;break}}if(j===0&&!W?.aborted&&K.length===0&&z.size===0)return c.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),X?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};return{content:K,reasoningContent:Q||void 0,toolCalls:T9(z),usage:H,finishReason:V}}catch(w){if(E9(w))return c.warn("[Loop] 流式请求失败,降级到非流式模式"),X?.discard(),{...await $.chatService.chat(Z,J,W,Y),_nonStreamingFallback:!0};throw w}}function XZ($){return{postTokens:$.postTokens,sampleAttempts:$.sampleAttempts,inputReductions:$.inputReductions,messagesOmitted:$.messagesOmitted,filesOmitted:$.filesOmitted,imagesOmitted:$.imagesOmitted,fallbackTargetTokens:$.fallbackTargetTokens,fallbackMessagesOmitted:$.fallbackMessagesOmitted,fallbackMessagesTruncated:$.fallbackMessagesTruncated,failureReason:$.failureReason}}function f6($,Z,J,W={}){return{outcome:J,strategy:Z,preTokens:$.preTokens,...XZ($),...W}}async function T6($,Z,J){if(!$)return;if(!J)return{outcome:"disabled",entries:0,topics:[]};try{return await TJ($,{workspaceRoot:Z.workspaceRoot||H0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full"})}catch{return{outcome:"failed",entries:0,topics:[]}}}function R9($){return S6("sha256").update($).digest("hex").slice(0,16)}var k9=new Set(["AbortError","Error","RangeError","TypeError"]),x9=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function I9($){if($ instanceof Error){let Z=$,J=k9.has($.name)?$.name:"Error",W=typeof Z.code==="string"&&x9.has(Z.code)?Z.code:"unknown";return`${J}:${W}`}return"UnknownError:unknown"}async function h9($){let{deps:Z,context:J,state:W,snapshot:Y,attemptSpent:X}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((H)=>typeof H.id==="string"&&L4(H)))return{kind:"already_present"};if(X)return{kind:"failed"};let Q=Z.executionEngine?.getContextManager();if(!Q)return{kind:"failed"};try{let H=await Q.recordTokenBudgetHandoff(J.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(H.outcome==="suppressed")return{kind:"suppressed"};let V=G4(H.event);if(!V)return{kind:"failed"};return W.appendDurableControl(V),{kind:"appended",message:V}}catch(H){let V=`token_budget_handoff_persist_failed session=${R9(J.sessionId)} error=${I9(H)}`;return c.warn(V),{kind:"failed"}}}async function*O4($,Z,J,W,Y,X,K,Q,H){let V=W.contextTokens,z=tJ(Z.messages,X),w=z!==null;if(z)Z.messages=z.messages,c.debug(`[Loop] [轮次 ${J}] MicroCompact: 清理 ${z.snippedCount} 轮旧工具结果(缓存已过期)`);let j=X1(Z.messages),B=!1;if(j.snippedCount>0)B=!0,c.debug(`[Loop] [轮次 ${J}] Snip 压缩: 移除 ${j.snippedCount} 轮旧工具调用,释放约 ${j.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(B)Z.messages=j.messages;return c.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(无历史 usage 数据)`),w||B?{kind:"snipped"}:{kind:"none"}}let G=$.chatService.getConfig(),_=G.model,b=W.maxContextTokens??0,T=W.maxOutputTokens??0,M=W.availableForInput??0;if(b<=0||M<=0){if(B)Z.messages=j.messages;return c.debug(`[Loop] [轮次 ${J}] 压缩检查: 跳过(模型上下文窗口未知)`),w||B?{kind:"snipped"}:{kind:"none"}}if(c.debug(`[Loop] [轮次 ${J}] 压缩检查:`,{contextTokens:V,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:b,maxOutputTokens:T,availableForInput:M,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(B)Z.messages=j.messages;return w||B?{kind:"snipped"}:{kind:"none"}}c.debug(J===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${J}] 触发循环内自动压缩`);let g={outcome:"failed"},I="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let m=B?j.messages:Z.messages,x=await R$.compact(m,{trigger:"auto",modelName:_,modelProvider:G.provider,maxContextTokens:b,apiKey:G.apiKey,baseURL:G.baseUrl,chatConfig:G,actualPreTokens:V,signal:Y,activeTask:K,workspaceRoot:Z.workspaceRoot||H0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(x.usage)H?.(x.usage),yield{kind:"token_usage",usage:w$(x.usage,b,"auxiliary")};let k=x.success?"llm":"fallback";if(g=f6(x,k,"failed",{preTokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens}),x.success)c.debug(`[Loop] [轮次 ${J}] 压缩完成: ${x.preTokens} -> ${x.postTokens} tokens`);else c.warn(`[Loop] [轮次 ${J}] 压缩使用降级策略: ${x.preTokens} -> ${x.postTokens} tokens`);I="checkpoint";let i=await J1($,Z,x.summary,{trigger:"auto",reason:"threshold",strategy:k,preTokens:x.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},...XZ(x),filesIncluded:x.filesIncluded,replacementMessages:x.compactedMessages},{required:$.executionEngine!==void 0});if(g.memory=await T6(x.memoryPlan,Z,i),g.outcome=x.success?"completed":"fallback",Z.messages=x.compactedMessages,Q)Q.lastCompactionTurn=J;return{kind:"compacted",postTokens:x.postTokens}}catch(m){if(k0(m)){if(m instanceof e0)H?.(m.usage),yield{kind:"token_usage",usage:w$(m.usage,b,"auxiliary")};return c.debug(`[Loop] [轮次 ${J}] 压缩被中止`),{kind:"none"}}return c.error(`[Loop] [轮次 ${J}] 压缩失败,停止执行`,m),{kind:"failed",phase:I}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",...g}}}function v9($,Z,J,W,Y){let X=Y?B4(Y):"user-cancel";return{success:!1,error:{type:"aborted",message:(X==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W,abortReason:X}}}function z4($,Z,J,W){return{success:!1,error:{type:"tool_persistence_failed",message:LJ},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:W}}}function C9($,Z,J,W,Y){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:Z,duration:Date.now()-J,tokensUsed:Y}}}async function*p9($,Z,J,W,Y){let X=Date.now(),K=0,Q=(B)=>{K=Math.min(Number.MAX_SAFE_INTEGER,K+(m1(B)??0))},H=0,V=[],z=null,w=!1,j=(B,G,_)=>{return w=!0,v9(B,G,X,K,_)};try{let B=$.toolExecutor.getRegistry(),G=J.permissionMode,_=W?.outputSchema?i1(W.outputSchema):void 0,b=()=>{let F=B.getFunctionDeclarationsByMode(G),O=$.applySkillToolRestrictions(F);if(F.some((u)=>u.name==="ToolSearch")&&!O.some((u)=>u.name==="ToolSearch")){let u=G==="plan"?B.getReadOnlyTools():B.getAll();O=$.applySkillToolRestrictions(u.map((J0)=>J0.getFunctionDeclaration()))}if(!_)return O;return[...O.filter((u)=>u.name!==I0),_.declaration]},T=C2(),M=W2(),g=()=>{let F=X2(M);return F?{executionHostFailureCategory:F}:{}},I=c2(),m=I2(),x=Y4(Y,B);if(_)x=`${x??""}
274
274
 
275
275
  # Structured Final Output
@@ -329,4 +329,4 @@ ${E}`}if(typeof R==="object"&&R!==null)R=JSON.stringify(R,null,2);if(typeof R===
329
329
 
330
330
  <system-reminder>
331
331
  ${h2(W$)}
332
- </system-reminder>`,metadata:G0};L.appendControl("user",U);let D=await u0($,J,U.content,z,G0);if(D)z=D}}if(W?.signal?.aborted)return j(H,V.length,W.signal)}}catch(F){if(F instanceof f$)try{let O=J.sessionId?await Z1.loadSessionModelContext(J.sessionId,J.workspaceRoot):Z0;L.restoreDurableHistory(O)}catch(O){c.error("[Loop] Failed to reload durable context after message commit failure:",O),L.restoreDurableHistory(Z0)}throw F}finally{if(W?.transientInput==="goal_continuation")L.removeMessages((F)=>{let O=F.metadata;return O!==null&&typeof O==="object"&&!Array.isArray(O)&&O.transientGoalContinuation===!0});L.writeback()}}catch(B){if(k0(B))return j(H,V.length,W?.signal);if(B instanceof f$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-X,tokensUsed:K}};let G=b9(B);return c.error(`API 调用失败: ${G}`),{success:!1,error:{type:"api_error",message:G,details:B},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-X,tokensUsed:K}}}finally{if(w)J.messages.push({role:"system",content:vZ}),await OJ($,J,z)}}export{L7 as Ab,O7 as Bb,v1 as Cb,EJ as Db,a$ as Eb,c9 as Fb,fZ as Gb,s$ as Hb,WJ as Ib,C4 as Jb,b$ as Kb,o9 as Lb,j$ as Mb,hZ as Nb,qJ as Ob,H3 as Pb,$1 as Qb,D0 as Rb,N0 as Sb,MZ as Tb,RZ as Ub,HJ as Vb,IZ as Wb,t2 as Xb,e2 as Yb,Z4 as Zb,A$ as _b,M1 as $b,z5 as ac,u0 as bc,R0 as cc,CZ as dc,I1 as ec,J1 as fc,TJ as gc,r as hc,e0 as ic,R$ as jc,l1 as kc,B0 as lc,yW as mc,Y4 as nc,YZ as oc,K4 as pc,Q4 as qc,H4 as rc,N9 as sc,N6 as tc,O4 as uc,p9 as vc};
332
+ </system-reminder>`,metadata:G0};L.appendControl("user",U);let D=await u0($,J,U.content,z,G0);if(D)z=D}}if(W?.signal?.aborted)return j(H,V.length,W.signal)}}catch(F){if(F instanceof f$)try{let O=J.sessionId?await Z1.loadSessionModelContext(J.sessionId,J.workspaceRoot):Z0;L.restoreDurableHistory(O)}catch(O){c.error("[Loop] Failed to reload durable context after message commit failure:",O),L.restoreDurableHistory(Z0)}throw F}finally{if(W?.transientInput==="goal_continuation")L.removeMessages((F)=>{let O=F.metadata;return O!==null&&typeof O==="object"&&!Array.isArray(O)&&O.transientGoalContinuation===!0});L.writeback()}}catch(B){if(k0(B))return j(H,V.length,W?.signal);if(B instanceof f$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-X,tokensUsed:K}};let G=b9(B);return c.error(`API 调用失败: ${G}`),{success:!1,error:{type:"api_error",message:G,details:B},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-X,tokensUsed:K}}}finally{if(w)J.messages.push({role:"system",content:vZ}),await OJ($,J,z)}}export{L7 as Bb,O7 as Cb,v1 as Db,EJ as Eb,a$ as Fb,c9 as Gb,fZ as Hb,s$ as Ib,WJ as Jb,C4 as Kb,b$ as Lb,o9 as Mb,j$ as Nb,hZ as Ob,qJ as Pb,H3 as Qb,$1 as Rb,D0 as Sb,N0 as Tb,MZ as Ub,RZ as Vb,HJ as Wb,IZ as Xb,t2 as Yb,e2 as Zb,Z4 as _b,A$ as $b,M1 as ac,z5 as bc,u0 as cc,R0 as dc,CZ as ec,I1 as fc,J1 as gc,TJ as hc,r as ic,e0 as jc,R$ as kc,l1 as lc,B0 as mc,yW as nc,Y4 as oc,YZ as pc,K4 as qc,Q4 as rc,H4 as sc,N9 as tc,N6 as uc,O4 as vc,p9 as wc};
@@ -1 +1 @@
1
- import{$e as h,Ue as a,Ve as b,We as c,Xe as d,Ye as e,Ze as f,_e as g,af as i,bf as j,cf as k,df as l,ef as m,ff as n,gf as o,hf as p,if as q,jf as r}from"./chunk-yjjxv7fn.js";import"./chunk-0ef47wgr.js";import"./chunk-28tzj187.js";import"./chunk-09kqfdpa.js";import"./chunk-ed2hdrwe.js";import"./chunk-gmpsfkgg.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 g,Ve as a,We as b,Xe as c,Ye as d,Ze as e,_e as f,af as h,bf as i,cf as j,df as k,ef as l,ff as m,gf as n,hf as o,if as p,jf as q,kf as r}from"./chunk-dxq7462e.js";import"./chunk-tqt5c2f5.js";import"./chunk-3y2x6fb6.js";import"./chunk-9ydrwcpy.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.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};
@@ -0,0 +1 @@
1
+ import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-8n3jythp.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-xzva8y4e.js";import"./chunk-3y2x6fb6.js";import"./chunk-yrr9mdjn.js";import"./chunk-m30qwpe9.js";import"./chunk-n8qg68y2.js";import"./chunk-hrtf7dba.js";import"./chunk-9ydrwcpy.js";import"./chunk-0wcnkxe8.js";import"./chunk-4cdk4mds.js";import"./chunk-a1tt14a2.js";import"./chunk-zjezws85.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -0,0 +1 @@
1
+ import{Af as c,yf as a,zf as b}from"./chunk-m8te4s8f.js";import"./chunk-5034apfz.js";import"./chunk-7eset766.js";import"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import"./chunk-06hkf59s.js";import"./chunk-yrr9mdjn.js";import"./chunk-m30qwpe9.js";import"./chunk-n8qg68y2.js";import"./chunk-hrtf7dba.js";import"./chunk-9ydrwcpy.js";import"./chunk-0wcnkxe8.js";import"./chunk-4cdk4mds.js";import"./chunk-a1tt14a2.js";import"./chunk-zjezws85.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -0,0 +1 @@
1
+ import{a,b as i,c as l,d as m}from"./chunk-ms0wve9g.js";import"./chunk-1beqtjsw.js";import"./chunk-8sth12hd.js";import"./chunk-sa9fxss4.js";import"./chunk-v1k6nvth.js";import"./chunk-30p7aff1.js";import"./chunk-25s0c8km.js";import"./chunk-f6hc7t65.js";import"./chunk-pm5ssr7m.js";import"./chunk-xseh3f4m.js";import"./chunk-7vzz3rsx.js";import"./chunk-9qxch6sy.js";import"./chunk-hmw99nm1.js";import"./chunk-a731hdwa.js";import"./chunk-dxq7462e.js";import"./chunk-tqt5c2f5.js";import{Df as n}from"./chunk-447ps2te.js";import"./chunk-0b83mt1c.js";import{Zf as s}from"./chunk-7eset766.js";import"./chunk-5yyp6njq.js";import"./chunk-v508x7cg.js";import"./chunk-xcy45yxx.js";import"./chunk-5bc4hwt9.js";import"./chunk-h8w3ahnk.js";import"./chunk-zfxcef0z.js";import"./chunk-g0hhqxpg.js";import"./chunk-8n3jythp.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-xzva8y4e.js";import"./chunk-3y2x6fb6.js";import"./chunk-yrr9mdjn.js";import"./chunk-m30qwpe9.js";import"./chunk-n8qg68y2.js";import"./chunk-hrtf7dba.js";import"./chunk-9ydrwcpy.js";import"./chunk-0wcnkxe8.js";import"./chunk-4cdk4mds.js";import"./chunk-a1tt14a2.js";import"./chunk-zjezws85.js";import"./chunk-gzbb747a.js";import"./chunk-f552hzcx.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};