blade-code 0.10.141 → 0.10.145

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 (129) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-erhaedch.js → chunk-06hkf59s.js} +1 -1
  3. package/dist/{chunk-cbgsjzdw.js → chunk-0kqrg1sv.js} +1 -1
  4. package/dist/{chunk-tya95jej.js → chunk-0tzecdv3.js} +1 -1
  5. package/dist/{chunk-4dtshx9v.js → chunk-1j24mgyp.js} +1 -1
  6. package/dist/chunk-1qcz0vdm.js +94 -0
  7. package/dist/{chunk-jsv3e4k6.js → chunk-2f8d0km4.js} +1 -1
  8. package/dist/{chunk-5q4z0sfr.js → chunk-2mk914vk.js} +2 -2
  9. package/dist/chunk-2t2hceyc.js +1 -0
  10. package/dist/{chunk-pzxg2sdv.js → chunk-3aprkwm1.js} +1 -1
  11. package/dist/{chunk-tqg9y2p6.js → chunk-3ar9yfmy.js} +1 -1
  12. package/dist/{chunk-6w8p6c0g.js → chunk-3kw9fwyc.js} +1 -1
  13. package/dist/{chunk-28tzj187.js → chunk-3y2x6fb6.js} +1 -1
  14. package/dist/{chunk-9kj19a8t.js → chunk-4cdk4mds.js} +1 -1
  15. package/dist/{chunk-7xtxvrh8.js → chunk-4wx5sya5.js} +1 -1
  16. package/dist/{chunk-f2jm4x5q.js → chunk-5p5pcdzj.js} +2 -2
  17. package/dist/chunk-5v0jcyea.js +2 -0
  18. package/dist/chunk-5y4btx3c.js +1 -0
  19. package/dist/chunk-66wk3exc.js +1 -0
  20. package/dist/{chunk-v67st2xb.js → chunk-6a16zba3.js} +1 -1
  21. package/dist/{chunk-yjbpfd3b.js → chunk-6vcqajdc.js} +1 -1
  22. package/dist/{chunk-4pexd8a7.js → chunk-6zh4327p.js} +1 -1
  23. package/dist/{chunk-3da7sqx6.js → chunk-8g4ybwbw.js} +1 -1
  24. package/dist/{chunk-be1fyzb3.js → chunk-9qm410b7.js} +5 -5
  25. package/dist/{chunk-7azws27d.js → chunk-a7skt1aw.js} +45 -45
  26. package/dist/{chunk-34fmx68h.js → chunk-b18242pd.js} +1 -1
  27. package/dist/{chunk-frvdjy8y.js → chunk-b7b1h83p.js} +1 -1
  28. package/dist/chunk-bpxva62c.js +1 -0
  29. package/dist/{chunk-tp4yy3a6.js → chunk-cydwzqec.js} +3 -3
  30. package/dist/{chunk-n34qsnks.js → chunk-ddvdc2p0.js} +1 -1
  31. package/dist/chunk-e12xrg41.js +2 -0
  32. package/dist/{chunk-j1pptwsq.js → chunk-e6p55b6q.js} +1 -1
  33. package/dist/{chunk-sdapqhj0.js → chunk-eg3ms291.js} +1 -1
  34. package/dist/chunk-ewrqfjcb.js +1 -0
  35. package/dist/{chunk-rv80nkve.js → chunk-fd7ez529.js} +1 -1
  36. package/dist/{chunk-83je3g6c.js → chunk-g25x285p.js} +3 -3
  37. package/dist/{chunk-ppp4gpy4.js → chunk-g3qmbwjp.js} +1 -1
  38. package/dist/{chunk-5v3eng7c.js → chunk-h1ny468k.js} +1 -1
  39. package/dist/{chunk-kf9j9z9k.js → chunk-h79tc5ms.js} +1 -1
  40. package/dist/{chunk-0b67y4j1.js → chunk-j8hbddjp.js} +2 -2
  41. package/dist/{chunk-9tk6wq70.js → chunk-jq5bhnrd.js} +1 -1
  42. package/dist/chunk-jrc1qd4n.js +1 -0
  43. package/dist/chunk-jwab80w1.js +1 -0
  44. package/dist/{chunk-sd9bze9x.js → chunk-kv458q06.js} +1 -1
  45. package/dist/{chunk-fx4xr1g6.js → chunk-m7dbggvr.js} +360 -357
  46. package/dist/{chunk-fx9vm1n5.js → chunk-mh9nqbwa.js} +1 -1
  47. package/dist/chunk-n14kcb52.js +1 -0
  48. package/dist/chunk-p07wgyps.js +1 -0
  49. package/dist/chunk-perarfr7.js +1 -0
  50. package/dist/{chunk-r5dmdsjb.js → chunk-phz87ec4.js} +1 -1
  51. package/dist/{chunk-ze1ra6f9.js → chunk-q7hkcmcd.js} +2 -2
  52. package/dist/{chunk-zrgfvc4k.js → chunk-qm0j4szw.js} +1 -1
  53. package/dist/chunk-qnkfm8bj.js +1 -0
  54. package/dist/{chunk-h5xad96g.js → chunk-qptj77rz.js} +1 -1
  55. package/dist/chunk-qwq8gt01.js +1 -0
  56. package/dist/{chunk-4w8v677q.js → chunk-rv3zap3q.js} +1 -1
  57. package/dist/{chunk-gm2yfq3r.js → chunk-rvs364rz.js} +2 -2
  58. package/dist/{chunk-0chvj0qt.js → chunk-sb3h9pbc.js} +1 -1
  59. package/dist/{chunk-k3ne93k8.js → chunk-shb7g2vr.js} +1 -1
  60. package/dist/{chunk-ae0fws1f.js → chunk-txq7gvbq.js} +2 -2
  61. package/dist/{chunk-zj32chp7.js → chunk-v1980qg4.js} +1 -1
  62. package/dist/{chunk-hv8nt7wj.js → chunk-vbjgcn49.js} +1 -1
  63. package/dist/{chunk-n9819k4p.js → chunk-vw9paban.js} +1 -1
  64. package/dist/chunk-w6eg8b87.js +1 -0
  65. package/dist/{chunk-f2y0gxyq.js → chunk-w6qfbea8.js} +1 -1
  66. package/dist/chunk-wcps5gjm.js +2 -0
  67. package/dist/{chunk-v1mamd1x.js → chunk-wzqcea6x.js} +1 -1
  68. package/dist/{chunk-jbpasjg9.js → chunk-xmymx75h.js} +1 -1
  69. package/dist/chunk-yfx9v808.js +6 -0
  70. package/dist/chunk-z2365g42.js +10 -0
  71. package/dist/{chunk-k1tfry97.js → chunk-z2k08r1h.js} +1 -1
  72. package/dist/{chunk-pv6cgfv1.js → chunk-zj1g4nbq.js} +1 -1
  73. package/dist/web/assets/ChatView-B6YVeOpl.js +63 -0
  74. package/dist/web/assets/{CodeBlockHighlighter-BC17_i4m.js → CodeBlockHighlighter-p-CwwjLJ.js} +1 -1
  75. package/dist/web/assets/{FilePreview-DuvfuHLi.js → FilePreview-C0zjFfLF.js} +1 -1
  76. package/dist/web/assets/{KanbanBoard-B-Z7lSaC.js → KanbanBoard-BTjc3GTe.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-DF-nYnJu.js → MarkdownRenderer-BQUL4vI_.js} +3 -3
  78. package/dist/web/assets/{ScrollArea-dipnxnqf.js → ScrollArea-UfoiaWDB.js} +1 -1
  79. package/dist/web/assets/{SessionHistorySurface-CnMBkiZW.js → SessionHistorySurface-B0WHnLst.js} +1 -1
  80. package/dist/web/assets/{SettingsModal-DLA1WQ6g.js → SettingsModal-CkF6k9qu.js} +1 -1
  81. package/dist/web/assets/{Sidebar-tu4OcImk.js → Sidebar-DmVMsipF.js} +1 -1
  82. package/dist/web/assets/{TaskSwitcher-D2TIUyr3.js → TaskSwitcher-DZELXs23.js} +1 -1
  83. package/dist/web/assets/{TerminalPanel-CcJVvSnz.js → TerminalPanel-kmWnkCMc.js} +1 -1
  84. package/dist/web/assets/{archive-EoUobrxu.js → archive-WXotGSXW.js} +1 -1
  85. package/dist/web/assets/{arrow-left-Y8E5lnQ1.js → arrow-left-Cb-SEc-l.js} +1 -1
  86. package/dist/web/assets/{calendar-clock-Cl0Spu99.js → calendar-clock-BRidlYhb.js} +1 -1
  87. package/dist/web/assets/{chevron-right-DmM1dl1s.js → chevron-right-CoRRZROd.js} +1 -1
  88. package/dist/web/assets/{chevrons-up-down-DFQNAYac.js → chevrons-up-down-Cv_JOz8A.js} +1 -1
  89. package/dist/web/assets/{clock-3-D3dzsSrc.js → clock-3-CMvLtvtl.js} +1 -1
  90. package/dist/web/assets/{copy-BwNmbccC.js → copy-DQqX0OQP.js} +1 -1
  91. package/dist/web/assets/{download-DHzGZhJT.js → download-FP4WtwG3.js} +1 -1
  92. package/dist/web/assets/{external-link-Dr_8T3Ah.js → external-link-BTBZEQYA.js} +1 -1
  93. package/dist/web/assets/{folder-DcgRdL_P.js → folder-Dd0PwX-t.js} +1 -1
  94. package/dist/web/assets/index-CXHca5Sw.js +203 -0
  95. package/dist/web/assets/index-RGoMvYl5.css +1 -0
  96. package/dist/web/assets/{pause-DXzNhd_w.js → pause-C4azsEtU.js} +1 -1
  97. package/dist/web/assets/{pencil-CYRCKPnu.js → pencil-BWrfxaIe.js} +1 -1
  98. package/dist/web/assets/{play-CfNxuNSd.js → play-DgOFsd17.js} +1 -1
  99. package/dist/web/assets/{plus-DBUPwsji.js → plus-KK_f8iC4.js} +1 -1
  100. package/dist/web/assets/session-events-CGQa6VXb.js +29 -0
  101. package/dist/web/assets/{settings-K2UJIIf_.js → settings-hrYiD_4G.js} +1 -1
  102. package/dist/web/assets/{team-BoulGGnJ.js → team-Yr9DBygX.js} +1 -1
  103. package/dist/web/assets/{teamService-Cfm0Cd6e.js → teamService-CPSMTxV-.js} +1 -1
  104. package/dist/web/assets/{terminal-C9ZyLrcq.js → terminal-CHxuQT2f.js} +1 -1
  105. package/dist/web/index.html +2 -2
  106. package/package.json +1 -1
  107. package/dist/chunk-0s0er9wr.js +0 -1
  108. package/dist/chunk-2b3j2egw.js +0 -1
  109. package/dist/chunk-44edbaa1.js +0 -1
  110. package/dist/chunk-514va7ce.js +0 -2
  111. package/dist/chunk-5vxhttdq.js +0 -10
  112. package/dist/chunk-7g76xzzg.js +0 -2
  113. package/dist/chunk-8tvf39jm.js +0 -1
  114. package/dist/chunk-enf0egke.js +0 -1
  115. package/dist/chunk-f5t7a64t.js +0 -1
  116. package/dist/chunk-h273dnvq.js +0 -1
  117. package/dist/chunk-j7784bxm.js +0 -1
  118. package/dist/chunk-jr402gf8.js +0 -1
  119. package/dist/chunk-ryyzbd76.js +0 -94
  120. package/dist/chunk-s56t6kzj.js +0 -2
  121. package/dist/chunk-se0q0p3v.js +0 -1
  122. package/dist/chunk-sz5g7eh5.js +0 -1
  123. package/dist/chunk-wemdt9n6.js +0 -6
  124. package/dist/chunk-znrafpad.js +0 -1
  125. package/dist/chunk-zqjm9yd8.js +0 -1
  126. package/dist/web/assets/ChatView-BBYsaZIk.js +0 -63
  127. package/dist/web/assets/index-BZZUIkal.js +0 -203
  128. package/dist/web/assets/index-DC2p1vGD.css +0 -1
  129. package/dist/web/assets/session-events-DTVYDdaH.js +0 -29
@@ -1,4 +1,4 @@
1
- import{vc as H8}from"./chunk-wm896gnx.js";import{$d as P6,Ac as p1,Cc as X$,Dd as f2,Ed as j8,Fd as z8,Gd as Z6,Hd as r1,Id as B8,Jd as U8,Kd as u1,Od as uJ,Xd as I0,Zd as N6,_d as m1,ge as J1,sd as G2,ud as F2,vd as L2,wc as U$,wd as Q6,xd as K6,yc as B$,zc as q2}from"./chunk-ryyzbd76.js";import{le as X8}from"./chunk-9xbwtjac.js";import{De as w1,oe as D0,re as W2,se as C$}from"./chunk-rv80nkve.js";import{cg as M2}from"./chunk-7xhw74hk.js";import{dg as Q8,eg as c0,fg as $8,gg as xJ,ig as I1,jg as A6,kg as vJ,lg as CJ,og as IJ}from"./chunk-k1tfry97.js";import{bh as Z$,ch as l0,fh as K8}from"./chunk-3kszepm6.js";import{jh as d2,nh as aJ}from"./chunk-s56t6kzj.js";import{yh as b$}from"./chunk-tp4yy3a6.js";import{Ti as R$}from"./chunk-sd9bze9x.js";import{aj as z0}from"./chunk-jsv3e4k6.js";import{Cj as b0}from"./chunk-5q4z0sfr.js";import{Wj as D2}from"./chunk-f2jm4x5q.js";import{Ak as zJ,Bk as i1,Dk as B2,Ik as U2,Jk as w2,ek as z2,tk as Q2,uk as K2,xk as Y1}from"./chunk-7xtxvrh8.js";import{Lk as vZ}from"./chunk-sdapqhj0.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function P$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class T1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(P$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!P$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!P$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(P$),this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function l6($){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 i6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function r6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import K$ from"node:path";var P8=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"]),y8=/^(LD_.+|DYLD_.+|PATH)$/,n6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function s$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(!P8.has(Q))break;Z=Y}return Z}function v5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(y8.test(Q))break;Z=Y}return Z}var _8=[/^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 _Z($){let Z=$,J=!0;while(J){J=!1;for(let W of _8){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 t$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){J+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,J+=K;continue}if(K==='"'&&!W){Y=!Y,J+=K;continue}if(W||Y){J+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(K==="&")return null;if(K===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=K}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function o6($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!Z){W=!0;continue}if(V==="'"&&!J){Z=!Z;continue}if(V==='"'&&!Z){J=!J;continue}if(Z)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(J)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;J+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(J)Z.push(J),J="";continue}J+=K}if(J)Z.push(J);return Z}var b8=new Set(["npm","pnpm","yarn","bun"]),a6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),E8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),S8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function R8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function s6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function T8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=K$.isAbsolute(V)?K$.resolve(V):K$.resolve(J,V);if(!X$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function M8($){let Z=[],J=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[V+1]==="|")return;Z.push(V)}return Z}function k8($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function h8($){let Z=s6($.replace(S8,"").trim()),J=M8(Z);if(!J)return;if(J.length===0)return t6(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=s6(Z.slice(0,W).trim()),V=Z.slice(W+1).trim();if(!Y||!k8(V))return;return t6(Y)}function t6($){let J=t$($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function _$($,Z){let J=h8($);if(!J)return!1;let W=s$(J),Y=t$(W);if(!Y||o6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:T8(W,Y,Z);if(!V)return!1;let Q=Q$(V);if(Q.length===0||Q.some((z)=>[...E8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(b8.has(K??""))return R8(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&a6.has(X??""))return!0;if(a6.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function p5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!K$.isAbsolute($);let J=K$.isAbsolute($)?K$.resolve($):K$.resolve(Z,$);return X$.isWithinWorkspace(J,Z)}var bZ=b0("Agent"),x8=3;function EZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=x8)return{action:"truncated"};if(l6(J)==="stop")return bZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var v8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],C8=/```[\s\S]{50,}```/,e6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",I8=2;function SZ($,Z,J=!0){if(!$||Z>=I8)return{action:"none"};if(!J&&C8.test($))return{action:"retry",prompt:e6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(v8.some((Q)=>Q.test(W)))return{action:"retry",prompt:e6};return{action:"none"}}var u8=[/\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}(?:测试|单测|集成测试|检查|构建)/],$J={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},g8={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},p8="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.",d8="Required verification did not run successfully before the retry limit.",m8=3;function JJ($,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&&_$(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 V of Y)if(typeof V==="string"&&_$(V,W))$.add(V)}function RZ($,Z,J){if(!$||!u8.some((X)=>X.test($)))return{action:"none"};let W=Object.keys($J).filter((X)=>$J[X].test($)),Y=[...Z],V=W.filter((X)=>!Y.some((H)=>g8[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>_$(X)))return{action:"none"};if(J>=m8)return{action:"fail",message:d8};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${p8}${K}`}}var c8=[/\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|子代理|子智能体)/],WJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function YJ($){return typeof $==="string"&&WJ.some((Z)=>Z.test($))}var l8=[/\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|子代理)/],i8=[/\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 r8($){if(typeof $!=="string")return;if(i8.some((Z)=>Z.test($)))return"multiple-allowed";return l8.some((Z)=>Z.test($))?"required":void 0}function $1($){for(let Z of $){let J=r8(Z);if(J!==void 0)return J==="required"}return!1}var n8="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.",o8="Required delegation did not complete before the retry limit.",a8=3;function VJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=$1(W),V=!1;if(!Y)for(let Q of W){if(WJ.some((K)=>K.test(Q)))break;if(c8.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||Z.has("Task"))return{action:"none"};if(J>=a8)return{action:"fail",message:o8};return{action:"retry",prompt:n8}}var s8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],t8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],e8=[/\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 QJ($){return e8.reduce((Z,J)=>Z.replace(J," "),$)}function M1($){if(typeof $!=="string")return!1;let Z=QJ($);return s8.some((J)=>J.test(Z))}var $9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",Z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",J9="Required worktree lifecycle did not complete before the retry limit.",W9=3;function KJ($,Z,J){if(!$)return{action:"none"};let W=QJ($);if(!M1(W))return{action:"none"};let Y=t8.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let V=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(J>=W9)return{action:"fail",message:J9};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?$9:Z9}}var ZJ=30000;async function TZ($){try{let J=b$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??z0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),ZJ)});try{let V=await Promise.race([J,Y]);if(V==="timeout")return bZ.warn(`[Loop] Stop hook 超时 (${ZJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return bZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function Y9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var V9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function Q9($){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 K9($){let Z=$;for(let X of V9)Z=Z.replace(X," ");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 V=Y.slice(0,60),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function XJ($){return K9(Q9($))}import{EventEmitter as X9}from"events";import HJ from"node:path";function MZ($){if(zJ($.sessionId),!HJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:HJ.resolve($.projectPath)}}function jJ($){let Z=MZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function $3($,Z){return jJ($)===jJ(Z)}class E$ extends X9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!E$.instance)E$.instance=new E$;return E$.instance}publish($,Z,J,W){let Y=MZ($);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 Z1=E$.getInstance();var s0=b0("Agent"),k1=new Set;async function H9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(k1.has(J))return;if(k1.size>=5000)k1.clear();k1.add(J);try{let W=$.workspaceRoot,Y=await J1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=XJ(Z);if(!V)return;await J1.updateSessionMetadata(J,Y.projectPath,{title:V}),Z1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var kZ=`<turn_aborted>
1
+ import{vc as H8}from"./chunk-wm896gnx.js";import{$d as P6,Ac as p1,Cc as X$,Dd as f2,Ed as j8,Fd as z8,Gd as Z6,Hd as r1,Id as B8,Jd as U8,Kd as u1,Od as uJ,Xd as I0,Zd as N6,_d as m1,ge as J1,sd as G2,ud as F2,vd as L2,wc as U$,wd as Q6,xd as K6,yc as B$,zc as q2}from"./chunk-1qcz0vdm.js";import{le as X8}from"./chunk-9xbwtjac.js";import{De as w1,oe as D0,re as W2,se as C$}from"./chunk-fd7ez529.js";import{cg as M2}from"./chunk-7xhw74hk.js";import{dg as Q8,eg as c0,fg as $8,gg as xJ,ig as I1,jg as A6,kg as vJ,lg as CJ,og as IJ}from"./chunk-z2k08r1h.js";import{bh as Z$,ch as l0,fh as K8}from"./chunk-3kszepm6.js";import{kh as d2,oh as aJ}from"./chunk-wcps5gjm.js";import{zh as b$}from"./chunk-cydwzqec.js";import{Ui as R$}from"./chunk-kv458q06.js";import{bj as z0}from"./chunk-2f8d0km4.js";import{Dj as b0}from"./chunk-2mk914vk.js";import{Xj as D2}from"./chunk-5p5pcdzj.js";import{Bk as zJ,Ck as i1,Ek as B2,Jk as U2,Kk as w2,fk as z2,uk as Q2,vk as K2,yk as Y1}from"./chunk-4wx5sya5.js";import{Mk as vZ}from"./chunk-eg3ms291.js";function y$($){return $.role==="system"&&Array.isArray($.content)}function P$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class T1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(y$);if(this._contextualSystemMessages=$.messages.filter(P$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!y$(W)&&!P$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!P$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(y$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(P$),this._history=$.filter((Z)=>!y$(Z)&&!P$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function l6($){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 i6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function r6($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import K$ from"node:path";var P8=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"]),y8=/^(LD_.+|DYLD_.+|PATH)$/,n6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function s$($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(!P8.has(Q))break;Z=Y}return Z}function v5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],V=W.match(n6);if(!V)break;let Q=V[1];if(y8.test(Q))break;Z=Y}return Z}var _8=[/^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 _Z($){let Z=$,J=!0;while(J){J=!1;for(let W of _8){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 t$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){J+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,J+=K;continue}if(K==='"'&&!W){Y=!Y,J+=K;continue}if(W||Y){J+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(J.trim())Z.push(J.trim());J="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(J.trim())Z.push(J.trim());J="",Q++;continue}if(K==="&")return null;if(K===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=K}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function o6($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!Z){W=!0;continue}if(V==="'"&&!J){Z=!Z;continue}if(V==='"'&&!Z){J=!J;continue}if(Z)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(J)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let Q=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(Q)||/^\{[^}]*\.\.[^}]*\}/.test(Q))return!0}}return!1}function Q$($){let Z=[],J="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){J+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;J+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(J)Z.push(J),J="";continue}J+=K}if(J)Z.push(J);return Z}var b8=new Set(["npm","pnpm","yarn","bun"]),a6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),E8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),S8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function R8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function s6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function T8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=Q$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=K$.isAbsolute(V)?K$.resolve(V):K$.resolve(J,V);if(!X$.isWithinWorkspace(Q,J))return;return W[2]?.trim()||void 0}function M8($){let Z=[],J=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!J){Y=!0;continue}if(Q==="'"&&!W){J=!J;continue}if(Q==='"'&&!J){W=!W;continue}if(Q!=="|"||J||W)continue;if($[V+1]==="|")return;Z.push(V)}return Z}function k8($){let Z=Q$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(Z.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function h8($){let Z=s6($.replace(S8,"").trim()),J=M8(Z);if(!J)return;if(J.length===0)return t6(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=s6(Z.slice(0,W).trim()),V=Z.slice(W+1).trim();if(!Y||!k8(V))return;return t6(Y)}function t6($){let J=t$($)?.at(-1);if(!J)return $;let W=Q$(J),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((K)=>K==="--configLoader"||K.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function _$($,Z){let J=h8($);if(!J)return!1;let W=s$(J),Y=t$(W);if(!Y||o6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:T8(W,Y,Z);if(!V)return!1;let Q=Q$(V);if(Q.length===0||Q.some((z)=>[...E8].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(b8.has(K??""))return R8(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&a6.has(X??""))return!0;if(a6.has(K??""))return!0;if(K==="node"&&X==="--test")return!0;if(K==="go"&&["build","test","vet"].includes(X??""))return!0;return K==="cargo"&&["build","check","clippy","test"].includes(X??"")}function p5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!K$.isAbsolute($);let J=K$.isAbsolute($)?K$.resolve($):K$.resolve(Z,$);return X$.isWithinWorkspace(J,Z)}var bZ=b0("Agent"),x8=3;function EZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=x8)return{action:"truncated"};if(l6(J)==="stop")return bZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var v8=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],C8=/```[\s\S]{50,}```/,e6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",I8=2;function SZ($,Z,J=!0){if(!$||Z>=I8)return{action:"none"};if(!J&&C8.test($))return{action:"retry",prompt:e6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(v8.some((Q)=>Q.test(W)))return{action:"retry",prompt:e6};return{action:"none"}}var u8=[/\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}(?:测试|单测|集成测试|检查|构建)/],$J={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},g8={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},p8="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.",d8="Required verification did not run successfully before the retry limit.",m8=3;function JJ($,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&&_$(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 V of Y)if(typeof V==="string"&&_$(V,W))$.add(V)}function RZ($,Z,J){if(!$||!u8.some((X)=>X.test($)))return{action:"none"};let W=Object.keys($J).filter((X)=>$J[X].test($)),Y=[...Z],V=W.filter((X)=>!Y.some((H)=>g8[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>_$(X)))return{action:"none"};if(J>=m8)return{action:"fail",message:d8};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${p8}${K}`}}var c8=[/\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|子代理|子智能体)/],WJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function YJ($){return typeof $==="string"&&WJ.some((Z)=>Z.test($))}var l8=[/\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|子代理)/],i8=[/\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 r8($){if(typeof $!=="string")return;if(i8.some((Z)=>Z.test($)))return"multiple-allowed";return l8.some((Z)=>Z.test($))?"required":void 0}function $1($){for(let Z of $){let J=r8(Z);if(J!==void 0)return J==="required"}return!1}var n8="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.",o8="Required delegation did not complete before the retry limit.",a8=3;function VJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=$1(W),V=!1;if(!Y)for(let Q of W){if(WJ.some((K)=>K.test(Q)))break;if(c8.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||Z.has("Task"))return{action:"none"};if(J>=a8)return{action:"fail",message:o8};return{action:"retry",prompt:n8}}var s8=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],t8=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],e8=[/\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 QJ($){return e8.reduce((Z,J)=>Z.replace(J," "),$)}function M1($){if(typeof $!=="string")return!1;let Z=QJ($);return s8.some((J)=>J.test(Z))}var $9="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",Z9="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",J9="Required worktree lifecycle did not complete before the retry limit.",W9=3;function KJ($,Z,J){if(!$)return{action:"none"};let W=QJ($);if(!M1(W))return{action:"none"};let Y=t8.some((Q)=>Q.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let V=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(J>=W9)return{action:"fail",message:J9};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?$9:Z9}}var ZJ=30000;async function TZ($){try{let J=b$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??z0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),ZJ)});try{let V=await Promise.race([J,Y]);if(V==="timeout")return bZ.warn(`[Loop] Stop hook 超时 (${ZJ}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return bZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function Y9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var V9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function Q9($){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 K9($){let Z=$;for(let X of V9)Z=Z.replace(X," ");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 V=Y.slice(0,60),Q=V.lastIndexOf(" ");return`${(Q>36?V.slice(0,Q):V).trimEnd()}…`}function XJ($){return K9(Q9($))}import{EventEmitter as X9}from"events";import HJ from"node:path";function MZ($){if(zJ($.sessionId),!HJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:HJ.resolve($.projectPath)}}function jJ($){let Z=MZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function $3($,Z){return jJ($)===jJ(Z)}class E$ extends X9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!E$.instance)E$.instance=new E$;return E$.instance}publish($,Z,J,W){let Y=MZ($);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 Z1=E$.getInstance();var s0=b0("Agent"),k1=new Set;async function H9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(k1.has(J))return;if(k1.size>=5000)k1.clear();k1.add(J);try{let W=$.workspaceRoot,Y=await J1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=XJ(Z);if(!V)return;await J1.updateSessionMetadata(J,Y.projectPath,{title:V}),Z1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var kZ=`<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>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",BJ="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 S$ 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 j$($){return $.executionEngine?.getContextManager()}async function m0($,Z,J,W=null,Y,V={}){let Q=V.required??$.executionEngine!==void 0;try{let K=j$($),X=typeof J==="string"?J.trim()!=="":J.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(K&&Z.sessionId&&X){let H=await K.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(Q&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)H9(Z,J);return H}if(Q&&Z.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(K){if(s0.warn("[Loop] 保存用户消息失败:",K),Q)throw new S$("user_message",{cause:K})}return null}async function x0($,Z,J,W,Y,V,Q={}){let K=Q.required??$.executionEngine!==void 0;try{let X=j$($),H=Boolean(J.trim()||Y?.trim());if(X&&Z.sessionId&&H){let z=await X.saveMessage(Z.sessionId,"assistant",J,W,V,Z.subagentInfo,Y);if(K&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(K&&Z.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(s0.warn("[Loop] 保存助手消息失败:",X),K)throw new S$("assistant_message",{cause:X})}return null}async function UJ($,Z,J){try{let W=j$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",kZ,J,void 0,Z.subagentInfo)}catch(W){s0.warn("[Loop] 保存中断边界失败:",W)}return null}async function wJ($,Z,J,W,Y){try{let V=j$($);if(!V||!Z.sessionId||J.length===0)return null;return await V.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((Q)=>({...Q})))),triggerPaths:[...W]},Z.subagentInfo)}catch(V){s0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function hZ($,Z,J,W,Y,V={}){try{let Q=j$($);if(Q&&Z.sessionId){let K=await Q.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,V.providerToolCallId);if(V.required&&!K)throw Error("Durable tool-use commit returned no identity");return K}if(V.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(Q){if(s0.warn("[Loop] 保存工具调用失败:",Q),V.required)throw Q}return null}async function h1($,Z,J,W,Y,V,Q,K,X,H={}){try{let z=j$($);if(z&&Z.sessionId){let B=await z.saveToolResult(Z.sessionId,J,W,Y,V,Q,Z.subagentInfo,K,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if(s0.warn("[Loop] 保存工具结果失败:",z),H.required)throw z}return null}async function W1($,Z,J,W,Y={}){try{let V=j$($);if(V&&Z.sessionId){let Q=await V.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!Q)throw Error("Compaction checkpoint commit returned no identity");return Q||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(s0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function f0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:Q,controlPrompt:K,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=Q,z=await x0(Z,J,Y,H,V);if(z)H=z;if(K!==void 0){let B={role:"user",content:K};if(X)B.metadata=X;W.appendControl("user",B);let j=await m0(Z,J,B.content,H,X);if(j)H=j}return H}import{createHash as y6}from"node:crypto";import{promises as C9}from"node:fs";import I9 from"node:path";import{nanoid as e0}from"nanoid";import*as t from"node:fs/promises";import*as t0 from"node:path";import qJ from"write-file-atomic";var DJ={enabled:!0,maxIndexLines:200};var j9="memory",xZ="MEMORY.md",CZ="<!-- blade:auto-memory-topics:start -->",x1="<!-- blade:auto-memory-topics:end -->",z9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},B9=new R$,GJ;function LJ($){return $.trim().replace(/\s+/g," ")}function U9($){return LJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function w9($){return[CZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),x1].join(`
4
4
  `)}function D9($,Z){let J=w9(Z),W=$.indexOf(CZ),Y=$.indexOf(x1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+x1.length);if(!$)return`${J}
@@ -92,8 +92,8 @@ Full output saved to: ${K}`}catch{return`${Z}
92
92
 
93
93
  ${Y}`}}function sJ(){return{successfulBash:!1}}function V4($){return typeof $==="string"&&aJ.some((Z)=>Z===$)}function j7($){switch($){case"timeout":case"admission":case"spawn":case"finalization":return $;case"unavailable":return"terminal";default:return}}function z7($){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 tJ($,Z,J){if(Z!=="Bash")return;if(J.success){$.successfulBash=!0;return}let W=J.metadata?.execution_host_failure;if(V4(W))$.category=W}function eJ($){return $.successfulBash?void 0:$.category}import b4 from"node:path";import{nanoid as E4}from"nanoid";import{randomUUID as j1}from"node:crypto";import*as v0 from"node:fs/promises";import*as Y2 from"node:path";import{Mutex as z4}from"async-mutex";import B4 from"write-file-atomic";var $2=120,sZ=128;function H1($){if(!Array.isArray($)||$.length>120||!$.every((Z)=>typeof Z==="string"&&Z.length>0&&Z.length<=128))return;return[...new Set($)]}function Q4($){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=H1(Z.inputMessageIds),W=H1($.acknowledgedInputMessageIds);if(!J||!W)return[];let Y=new Set(J);return W.filter((V)=>Y.has(V))}function g1($,Z){let J=$[Z];if(J?.type!=="turn_aborted")return[];let W=Q4(J.data);if(W.length===0)return[];let Y=-1;for(let Q=Z-1;Q>=0;Q--){let K=$[Q];if(K.type==="turn_started"){if(K.data.turnId!==J.data.turnId)return[];Y=Q;break}if(K.type==="turn_completed"||K.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let Q=Y+1;Q<Z;Q++){let K=$[Q];if(K.type!=="message_created"||K.data.role!=="user")continue;let X=K.data.metadata,H=K.data.inboxMessageId!==void 0?K.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=128)V.add(H)}return W.filter((Q)=>V.has(Q))}import*as d1 from"node:fs/promises";import*as J2 from"node:path";var K4={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},X4=new R$,Z2;async function x$($,Z,J,W=j4){let Y=B$($,Z);return X4.runExclusive(Y,()=>p1($,Z,async(V)=>{let Q=J2.dirname(V.inboxPath);await d1.mkdir(Q,{recursive:!0,mode:448}),await d1.chmod(Q,448);let K,X=await W(V.inboxPath,{...K4,onCompromised:(H)=>{K=H}});try{if(K)throw K;let H=await J(V);if(K)throw K;return H}finally{await X()}}))}async function H4(){return Z2??=await import("proper-lockfile"),Z2}async function j4($,Z){return(await H4()).lock($,Z)}var $6=2,v$=8388608;function tZ($,Z,J){let W={version:$6,sessionId:$,generation:Z,messages:J.map(({recovered:Y,...V})=>V)};return`${JSON.stringify(W)}
95
- `}function eZ($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function U4($){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 w4($,Z,J){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==$6||!("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((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!U4(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"&&V.origin!=="interaction_recovery"&&V.origin!=="user_shell"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let Q="outputSchema"in V&&V.outputSchema!==void 0?m1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...Q?{outputSchema:Q}:{}}});if(new Set(Y.map((V)=>V.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:$6,sessionId:J,generation:W.generation,messages:Y}}function D4($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return g1($,J);return[]}))}function q4($){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 c1{sessionId;stateStorage;writeFile;lockFile;mutex=new z4;generation=j1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=U$($),W={}){let Y=new c1(Z,J,W.writeFile??B4,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.messages.some((X)=>X.id===$.id))return{accepted:!0,snapshot:Y};if(Z&&!Z(Y.messages))return{accepted:!1,snapshot:Y};let V=[...Y.messages,{...$,recovered:!1}],Q=j1(),K=tZ(this.sessionId,Q,V);if(Buffer.byteLength(K)>v$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(V,Q,W,K),{accepted:!0,snapshot:{generation:Q,messages:V}}},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 x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),V=Y.messages.filter((K)=>!Z.has(K.id));if(V.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let Q=j1();return await this.persistAtPath(V,Q,W),{generation:Q,messages:V}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await x$(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 x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let V=j1(),Q=Z.map((X)=>({...X})),K=tZ(this.sessionId,V,Q);if(Buffer.byteLength(K)>v$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(Q,V,W,K),{replaced:!0,snapshot:{generation:V,messages:Q}}},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 x$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=j1();return await this.persistAtPath(J.messages,W,Z),{generation:W,messages:J.messages}}return J},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let Z;try{let Q=await v0.open($.inboxPath,"r");try{if((await Q.stat()).size>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${$.inboxPath}`);Z=w4(await Q.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await Q.close()}await v0.chmod($.inboxPath,384)}catch(Q){if(!eZ(Q,"ENOENT"))throw Q}let J=new Set,W=new Set;try{let Q=W2(await v0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=D4(Q),W=q4(Q)}catch(Q){if(!eZ(Q,"ENOENT"))throw Q}let Y=new Map(this.messages.map((Q)=>[Q.id,Q.recovered])),V=(Z?.messages??[]).filter((Q)=>!J.has(Q.id)).map((Q)=>({...Q,recovered:Y.get(Q.id)??!0,...Q.persisted===!0||W.has(Q.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:V,...Z?.version===1&&V.length>0?{migrationRequired:!0}:{},...Z&&V.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await v0.mkdir(Y2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await v0.unlink(J.inboxPath).catch((V)=>{if(!eZ(V,"ENOENT"))throw V});return}let Y=W??tZ(this.sessionId,Z,$);if(Buffer.byteLength(Y)>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as C0 from"node:fs/promises";import*as O2 from"node:path";import{nanoid as B0}from"nanoid";var V2=256;class O0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,Z,J){this.sessionId=$;this.projectPath=Z;this.storage=J}static for($,Z,J=U$(Z)){let W=B$(J,$),Y=O0.instances.get(W);if(!Y)Y=new O0($,Z,J),O0.instances.set(W,Y),O0.pruneIdleInstances(W);else O0.instances.delete(W),O0.instances.set(W,Y);return Y}static release($,Z,J=U$(Z)){O0.instances.delete(B$(J,$))}static pruneIdleInstances($){if(O0.instances.size<=V2)return;for(let[Z,J]of O0.instances){if(Z===$||J.subscribers.size>0)continue;if(O0.instances.delete(Z),O0.instances.size<=V2)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((V)=>{return Y(V),$(V)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((V)=>{return Y(V),$(V)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);Z1.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($),O0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,V)=>{let Q=Y?await W.readAllValidated(Y):await W.readAll();return V(Q),Q.filter((K)=>(K.seq??0)>=Z)});for(let W of J){if(Z6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(Z6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}Z1.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 p1(this.storage,this.sessionId,async(Z)=>{let J=new C$(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(Q)=>{await Q2(W,Z.transcriptPath,Q)}},(Q)=>{K2(Q,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function w$($){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 _0 extends Error{}var G4="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 J6($,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 X2($,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 V=Y.data.metadata,Q=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof Q==="string"&&Q.length>0&&Q.length<=sZ)W.push(Q)}return[...new Set(W)]}function A2($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let Z="inputMessageIds"in $?H1($.inputMessageIds):void 0;if(!Z||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let J=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(J===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:Z,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:J,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function F4($,Z){let J=$.findLastIndex((K)=>K.type==="turn_started"&&K.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((K,X)=>X>J&&K.type==="turn_started"&&K.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),V=new Set(Y.flatMap((K)=>{if(K.type!=="part_created"||K.data.partType!=="tool_call")return[];let X=K.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:K.data.partId]:[K.data.partId]})),Q=new Set;for(let K of Y){if(K.type!=="part_created"||K.data.partType!=="tool_result")continue;let X=K.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:K.data.partId,z=X.metadata;if(V.has(H)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)Q.add(H)}return Q.size}function N2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return g1($,J);return[]}))}function W6($,Z,J=[]){let W=A2(Z.data.recovery);if(!W)return;if($.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z.data.turnId))return;let Y=N2($);for(let K of J)Y.add(K);let V=W.inputMessageIds.filter((K)=>!Y.has(K)),Q=W.version===1?F4($,Z.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&Q===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...Q>0?{interruptedToolCallCount:Q}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function z1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=W6($,J);if(W)return W}return}function l1($,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:V,subagent_type:Q,description:K}=J,X=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 V==="string"&&V===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof K==="string"&&Y.subagentDescription===K&&W.description===K&&(Q===void 0||typeof Q==="string"&&Q===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&X&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var L4=1e4,f4=1e5,O4=2592000000,H2=128,A4=1e6,N4=256;function P4($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>H2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>A4||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>H2||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 P2($,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,V=Y.turnId,Q=Y.inputMessageIds,K=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,z=Array.isArray(Q)?Q.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=sZ):[];if(typeof V!=="string"||V.length===0||V.length>128||Z!==void 0&&V!==Z||!Array.isArray(Q)||Q.length>$2||z.length!==Q.length||typeof K!=="number"||!Number.isSafeInteger(K)||K<0||K>L4||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>f4||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>O4)return;let B;if("goalFinalization"in Y){if(B=P4(Y.goalFinalization),!B)return}return{turnId:V,inputMessageIds:[...new Set(z)],turnsCount:K,toolCallsCount:X,durationMs:H,...B?{goalFinalization:B}:{}}}function j2($,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 V=P2(Y,Z);if(V)return V}return}function y4($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=P2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function I$($,Z){let J=Z?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===Z):-1;if(Z&&J<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,Q=new Set;for(let X of $.slice(J+1)){if(X.type==="interaction_requested"){Q.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},z=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(z,{toolCallId:z,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(z),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(z)&&H.error===null)V.add(z)}}let K=[...W.values()];return{all:K,orphaned:K.filter((X)=>!Y.has(X.toolCallId)&&!Q.has(X.toolCallId)),hadSuccessfulResult:K.some((X)=>V.has(X.toolCallId))}}class E0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=z0(),Z=100,J=D2(),W=U$($)){this.projectPath=$,this.maxSessions=Z,this.version=J,this.stateStorage=W}createEvent($,Z,J){return{id:B0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:U2(this.projectPath)}:{},version:this.version,data:J}}log($){return O0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=B$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=E0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,J,Z),E0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(E0.sessionInitializationRuns.get(J)===W)E0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>N4){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z,J){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),V={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},Q=this.createEvent("session_created",$,V);await this.log($).commit(Q)}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=F2;return Z}async initialize(){try{await q2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await C0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,V,Q){try{await this.ensureSessionCreated($,V);let K=new Date().toISOString(),X=B0(),H={messageId:X,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:K,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,H),B=Z==="assistant"&&Q?.trim()?[this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:"reasoning",payload:{text:Q},createdAt:K})]:[],j=typeof J==="string"?[this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:"text",payload:{text:J},createdAt:K})]:J.map((U)=>this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:_4(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:K}));return await this.log($).commitBatch([z,...B,...j]),X}catch(K){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,K),K}}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=D0(J);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===Z))throw new _0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===Z);if(!Y||!W6(W,Y))throw new _0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof _0))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=D0(W),V=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(Z.inboxMessageId)),Q=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===Z.inboxMessageId),K=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 U=j.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let f=U.input,N=f.resume_from??f.resume;return f.run_in_background===!0&&f.subagent_session_id===Z.childSessionId&&f.description===Z.subagentRef.subagentDescription&&(f.subagent_type===void 0||f.subagent_type===Z.subagentRef.subagentType)&&(f.resume_from===void 0||f.resume===void 0||f.resume_from===f.resume)&&(N===void 0?Z.subagentRef.subagentResumedFrom===void 0:N===Z.subagentRef.subagentResumedFrom)});if(!K)return J={eligible:!1,acknowledged:V,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];if(V)return J={eligible:!0,acknowledged:!0,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];let X=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(Q&&X)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:Q.data.messageId},[];let H=new Date().toISOString(),z=Q?.data.messageId??B0(),B=[];if(!Q){let j={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(Z.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:B0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:H}))}if(!X){let j=Y.findLast((f)=>f.type==="part_created"&&f.data.partType==="subtask_ref"&&f.data.messageId===K.data.messageId&&f.data.payload!==null&&typeof f.data.payload==="object"&&!Array.isArray(f.data.payload)&&f.data.payload.childSessionId===Z.childSessionId),U=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;B.push(this.createEvent("part_created",$,{partId:B0(),messageId:K.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 U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return J={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),J}async saveTurnStart($,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=D0(J);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===Z.turnId))throw new _0;let Y=w$(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 _0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=D0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),Q=[...new Set(J)].filter((H)=>!V.has(H)),K=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===Z.turnId);if(K){if(K.type==="turn_aborted"||Q.length===0)throw new _0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]}let X=w$(Y).active;if(!X||X.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...Q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof _0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=H1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let Q,K=[];try{await this.log($).commitValidatedBatch((X)=>{let H=D0(X),z=N2(H),B=H.findLast((u)=>(u.type==="turn_completed"||u.type==="turn_aborted")&&u.data.turnId===Z.turnId);if(B){if(B.type==="turn_completed")throw Q=void 0,K=[],new _0;let u=A2(B.data.recovery),P0=u?V.filter((A0)=>u.inputMessageIds.includes(A0)):[],Z0=P0.filter((A0)=>!z.has(A0));if(K=P0,Q=W6(H,B,P0),Z0.length===0)throw new _0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Z0,acknowledgedAt:Z.abortedAt})]}let j=w$(H).active;if(!j||j.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let U=I$(H,j.turnId),f=X2(H,j.turnId),N=z1(H),b=new Set(Z.recovery?.inputMessageIds??[]),S=N?N.inputMessageIds.filter((u)=>b.has(u)):[],R=[...new Set([...f,...S])],g=U.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,h={version:3,inputMessageIds:R,hadSuccessfulToolResult:g,interruptedToolCallCount:U.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:g&&!U.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:J6(H,j.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};Q={turnId:Z.turnId,outcome:"aborted",inputMessageIds:h.inputMessageIds,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},...h.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent};let $0=V.filter((u)=>R.includes(u)),o=$0.filter((u)=>!z.has(u));K=$0;let T=new Set(z);for(let u of $0)T.add(u);let q=h.inputMessageIds.filter((u)=>!T.has(u)),l=h.hadSuccessfulToolResult||h.interruptedToolCallCount>0;Q=q.length>0||l?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:q,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},...h.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:G0,...v}=Z;return[this.createEvent("turn_aborted",$,{...v,...$0.length>0?{acknowledgedInputMessageIds:$0}:{},recovery:h}),...o.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:o,acknowledgedAt:Z.abortedAt})]:[]]})}catch(X){if(!(X instanceof _0))throw X}return{...Q?{recovery:Q}:{},acknowledgedInputMessageIds:K}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=D0(Z),W=w$(J).active;return W?I$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=D0(Z),W=w$(J).active;if(W){let Y=I$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(j2(J,W.turnId))return!0}return z1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=D0(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 V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=D0(W),V=w$(Y).active,Q=I$(Y);if(!V&&Q.orphaned.length===0){if(J=z1(Y),J)return[];throw new _0}let K=V?j2(Y,V.turnId):void 0;if(V&&K&&Q.orphaned.length===0){let T=I$(Y,V.turnId);J={turnId:V.turnId,outcome:"completed",inputMessageIds:K.inputMessageIds,hadSuccessfulToolResult:T.hadSuccessfulResult,emptyFinalCorrectionSpent:J6(Y,V.turnId),finalization:K};let q=new Set(Y.flatMap((v)=>v.type==="inbox_acknowledged"?v.data.messageIds:[])),l=K.inputMessageIds.filter((v)=>!q.has(v)),G0=new Date().toISOString();return[...l.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:l,acknowledgedAt:G0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:G0,turnsCount:K.turnsCount,toolCallsCount:K.toolCallsCount,durationMs:K.durationMs})]}let X=V?I$(Y,V.turnId):void 0,H=X?.orphaned.some((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return l1(T,q)&&q?.error===void 0})??!1,z=X?.orphaned.filter((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return q?.toolCallId===T.toolCallId&&q.toolName===T.toolName&&q.error===void 0}).every((T)=>l1(T,Z.adoptedToolResults?.get(T.toolCallId)))??!0,B=new Set(V?.inputMessageIds??[]),j=V?z1(Y):void 0,U=j?j.inputMessageIds.filter((T)=>B.has(T)):[],f=U.length>0,N=V?X2(Y,V.turnId):[],b=X?X.orphaned.filter((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return!l1(T,q)}).length:0,S=f&&j?.hadSuccessfulToolResult===!0,R=(X?.hadSuccessfulResult??!1)||H||S;J=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([...N,...U])],hadSuccessfulToolResult:R,...(()=>{let T=b+(f?j?.interruptedToolCallCount??0:0);return T>0?{interruptedToolCallCount:T}:{}})(),...R&&!(X?.hadSuccessfulResult??!1)&&z&&(!S||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:J6(Y,V.turnId)||f&&j?.emptyFinalCorrectionSpent===!0}:z1(Y);let g=V?X?.all.length??0:0,h=new Date().toISOString(),$0=V?Date.parse(V.startedAt):Number.NaN,o=Q.orphaned.flatMap((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId),l=l1(T,q)?q:void 0,G0=this.createEvent("part_created",$,{partId:T.toolCallId,messageId:l?T.messageId:T.toolCallId,partType:"tool_result",payload:l?{toolCallId:T.toolCallId,toolName:T.toolName,output:l.output,error:l.error??null,...l.metadata===void 0?{}:{metadata:l.metadata}}:{toolCallId:T.toolCallId,toolName:T.toolName,output:null,error:G4,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:h});if(!l?.subagentRef)return[G0];let v=l.subagentRef;return[G0,this.createEvent("part_created",$,{partId:B0(),messageId:T.messageId,partType:"subtask_ref",payload:{childSessionId:v.subagentSessionId,agentType:v.subagentType,description:v.subagentDescription??"",status:v.subagentStatus,summary:v.subagentSummary??"",resumedFrom:v.subagentResumedFrom??null,rootAgentId:v.subagentRootId??v.subagentSessionId,resumeDepth:v.subagentResumeDepth??0,verificationVerdict:v.verificationVerdict??null,startedAt:h,finishedAt:h},createdAt:h})]});return V?[...o,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:h,turnsCount:0,toolCallsCount:g,durationMs:Number.isFinite($0)?Math.max(0,Date.now()-$0):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:o})}catch(W){if(!(W instanceof _0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?y4(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((V)=>V.type==="interaction_requested"&&V.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((V)=>V.type==="interaction_responded"&&V.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((V)=>V.type==="interaction_responded"&&V.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((V)=>V.type==="interaction_recovered"&&V.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((V)=>V.type==="review_started"&&V.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((V)=>V.type==="review_started"&&!J.some((Q)=>Q.type==="review_completed"&&Q.data.reviewId===V.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((V)=>V.type==="review_started"&&V.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((V)=>V.type==="review_completed"&&V.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let Q=new Date().toISOString(),K=W??B0(),X=[];if(!W){let B={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:Q};X.push(this.createEvent("message_created",$,B))}let H=V??B0(),z={partId:H,messageId:K,partType:"tool_call",payload:{toolCallId:H,toolName:Z,input:J},createdAt:Q};if(X.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let B=J,j=typeof B.subagent_session_id==="string"?B.subagent_session_id:void 0,U=typeof B.subagent_type==="string"?B.subagent_type:void 0;if(j&&U){let f={partId:B0(),messageId:K,partType:"subtask_ref",payload:{childSessionId:j,agentType:U,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:Q},createdAt:Q};X.push(this.createEvent("part_created",$,f))}}return await this.log($).commitBatch(X),H}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Z,J,W,Y=null,V,Q,K,X){try{await this.ensureSessionCreated($,Q);let H=new Date().toISOString(),z=Y??B0();return await this.log($).commitValidatedBatch((B)=>{let j=K?.subagentStatus==="running"?D0(B).findLast((R)=>R.type==="part_created"&&R.data.partType==="subtask_ref"&&R.data.payload!==null&&typeof R.data.payload==="object"&&!Array.isArray(R.data.payload)&&R.data.payload.childSessionId===K.subagentSessionId&&(R.data.payload.status==="completed"||R.data.payload.status==="failed"||R.data.payload.status==="cancelled")):void 0,U=j?.data.payload,f=X&&typeof X==="object"&&!Array.isArray(X)?X:{},N=U?{...f,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,b=[];if(!Y){let R={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:H};b.push(this.createEvent("message_created",$,R))}let S={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:V??null,...N===void 0?{}:{metadata:N}},createdAt:H};if(b.push(this.createEvent("part_created",$,S)),K&&!j){let R=K.subagentStatus==="running"?null:H,g={partId:B0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:K.subagentSessionId,agentType:K.subagentType,description:K.subagentDescription??"",status:K.subagentStatus,summary:K.subagentSummary??"",resumedFrom:K.subagentResumedFrom??null,rootAgentId:K.subagentRootId??K.subagentSessionId,resumeDepth:K.subagentResumeDepth??0,verificationVerdict:K.verificationVerdict??null,startedAt:H,finishedAt:R},createdAt:H};b.push(this.createEvent("part_created",$,g))}return b}),Z}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=B0(),Q={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},K=this.buildCompactionMetadata(J),X={partId:B0(),messageId:V,partType:"summary",payload:{text:Z,metadata:K,...J.replacementMessages?{replacementMessages:L2(J.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,Q),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=r1([]),W=await this.log($).commitValidatedBatch((V)=>{if(J=r1(D0(V)),J.kind!=="none")return[];let Q=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${f2}${B0()}`,createdAt:Q})]});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=r1(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?D0(Z):null}catch{return null}}async loadSession($){try{let Z=D0(await this.log($).readAll());if(Z.length===0)return null;let J=Z.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Z[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=D0(await this.log($).readAll());if(Z.length===0)return null;let J=new Map;for(let Q of Z){if(Q.type==="message_created")J.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let K=J.get(Q.data.messageId);if(K){let X=Q.data.payload;K.content=X.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let K=J.get(Q.data.messageId);if(K)K.content=K.content?`${K.content}
96
- [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],V=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:V}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=Y1(this.projectPath);return(await C0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=i1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let V=D0(Y),Q=Y[Y.length-1],K=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(Q.timestamp).getTime(),messageCount:K,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=i1(this.projectPath,$);await new C$(Z).delete(),await C0.unlink(B2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await G2(this.projectPath,$,z2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-frvdjy8y.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=i1(this.projectPath,J),V=await new C$(W).getStats();Z+=V.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=Y1(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let Z=O2.join($,".health-check");return await C0.writeFile(Z,"test","utf-8"),await C0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return w2()}}function _4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var y2=131072,Y6=new R$;function V6($,Z){return`${b4.resolve($)}\x00${Z}`}function X6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>y2)throw Error(`${Z} exceeds ${y2} bytes`);return JSON.parse(J)}function _2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function S4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function R4($,Z){if($.request.interactionType!=="elicitation")return X6(Z,"Interaction response");return X6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function b2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function T4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function M4($){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 eZ($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function U4($){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 w4($,Z,J){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==$6||!("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((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!U4(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"&&V.origin!=="interaction_recovery"&&V.origin!=="user_shell"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let Q="outputSchema"in V&&V.outputSchema!==void 0?m1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...Q?{outputSchema:Q}:{}}});if(new Set(Y.map((V)=>V.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:$6,sessionId:J,generation:W.generation,messages:Y}}function D4($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return g1($,J);return[]}))}function q4($){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 c1{sessionId;stateStorage;writeFile;lockFile;mutex=new z4;generation=j1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=U$($),W={}){let Y=new c1(Z,J,W.writeFile??B4,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.messages.some((X)=>X.id===$.id))return{accepted:!0,snapshot:Y};if(Z&&!Z(Y.messages))return{accepted:!1,snapshot:Y};let V=[...Y.messages,{...$,recovered:!1}],Q=j1(),K=tZ(this.sessionId,Q,V);if(Buffer.byteLength(K)>v$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(V,Q,W,K),{accepted:!0,snapshot:{generation:Q,messages:V}}},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 x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),V=Y.messages.filter((K)=>!Z.has(K.id));if(V.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let Q=j1();return await this.persistAtPath(V,Q,W),{generation:Q,messages:V}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await x$(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 x$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let V=j1(),Q=Z.map((X)=>({...X})),K=tZ(this.sessionId,V,Q);if(Buffer.byteLength(K)>v$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(Q,V,W,K),{replaced:!0,snapshot:{generation:V,messages:Q}}},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 x$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=j1();return await this.persistAtPath(J.messages,W,Z),{generation:W,messages:J.messages}}return J},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let Z;try{let Q=await v0.open($.inboxPath,"r");try{if((await Q.stat()).size>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${$.inboxPath}`);Z=w4(await Q.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await Q.close()}await v0.chmod($.inboxPath,384)}catch(Q){if(!eZ(Q,"ENOENT"))throw Q}let J=new Set,W=new Set;try{let Q=W2(await v0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=D4(Q),W=q4(Q)}catch(Q){if(!eZ(Q,"ENOENT"))throw Q}let Y=new Map(this.messages.map((Q)=>[Q.id,Q.recovered])),V=(Z?.messages??[]).filter((Q)=>!J.has(Q.id)).map((Q)=>({...Q,recovered:Y.get(Q.id)??!0,...Q.persisted===!0||W.has(Q.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:V,...Z?.version===1&&V.length>0?{migrationRequired:!0}:{},...Z&&V.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await v0.mkdir(Y2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await v0.unlink(J.inboxPath).catch((V)=>{if(!eZ(V,"ENOENT"))throw V});return}let Y=W??tZ(this.sessionId,Z,$);if(Buffer.byteLength(Y)>v$)throw Error(`Steering inbox exceeds ${v$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as C0 from"node:fs/promises";import*as O2 from"node:path";import{nanoid as B0}from"nanoid";var V2=256;class O0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,Z,J){this.sessionId=$;this.projectPath=Z;this.storage=J}static for($,Z,J=U$(Z)){let W=B$(J,$),Y=O0.instances.get(W);if(!Y)Y=new O0($,Z,J),O0.instances.set(W,Y),O0.pruneIdleInstances(W);else O0.instances.delete(W),O0.instances.set(W,Y);return Y}static release($,Z,J=U$(Z)){O0.instances.delete(B$(J,$))}static pruneIdleInstances($){if(O0.instances.size<=V2)return;for(let[Z,J]of O0.instances){if(Z===$||J.subscribers.size>0)continue;if(O0.instances.delete(Z),O0.instances.size<=V2)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((V)=>{return Y(V),$(V)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((V)=>{return Y(V),$(V)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);Z1.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($),O0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,V)=>{let Q=Y?await W.readAllValidated(Y):await W.readAll();return V(Q),Q.filter((K)=>(K.seq??0)>=Z)});for(let W of J){if(Z6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(Z6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}Z1.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 p1(this.storage,this.sessionId,async(Z)=>{let J=new C$(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(Q)=>{await Q2(W,Z.transcriptPath,Q)}},(Q)=>{K2(Q,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function w$($){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 _0 extends Error{}var G4="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 J6($,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 X2($,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 V=Y.data.metadata,Q=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof Q==="string"&&Q.length>0&&Q.length<=sZ)W.push(Q)}return[...new Set(W)]}function A2($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let Z="inputMessageIds"in $?H1($.inputMessageIds):void 0;if(!Z||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let J=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(J===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:Z,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:J,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function F4($,Z){let J=$.findLastIndex((K)=>K.type==="turn_started"&&K.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((K,X)=>X>J&&K.type==="turn_started"&&K.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),V=new Set(Y.flatMap((K)=>{if(K.type!=="part_created"||K.data.partType!=="tool_call")return[];let X=K.data.payload;return X&&typeof X==="object"&&!Array.isArray(X)?[typeof X.toolCallId==="string"?X.toolCallId:K.data.partId]:[K.data.partId]})),Q=new Set;for(let K of Y){if(K.type!=="part_created"||K.data.partType!=="tool_result")continue;let X=K.data.payload;if(!X||typeof X!=="object"||Array.isArray(X))continue;let H=typeof X.toolCallId==="string"?X.toolCallId:K.data.partId,z=X.metadata;if(V.has(H)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)Q.add(H)}return Q.size}function N2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return g1($,J);return[]}))}function W6($,Z,J=[]){let W=A2(Z.data.recovery);if(!W)return;if($.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z.data.turnId))return;let Y=N2($);for(let K of J)Y.add(K);let V=W.inputMessageIds.filter((K)=>!Y.has(K)),Q=W.version===1?F4($,Z.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&Q===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...Q>0?{interruptedToolCallCount:Q}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function z1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=W6($,J);if(W)return W}return}function l1($,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:V,subagent_type:Q,description:K}=J,X=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 V==="string"&&V===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof K==="string"&&Y.subagentDescription===K&&W.description===K&&(Q===void 0||typeof Q==="string"&&Q===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&X&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var L4=1e4,f4=1e5,O4=2592000000,H2=128,A4=1e6,N4=256;function P4($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>H2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>A4||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>H2||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 P2($,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,V=Y.turnId,Q=Y.inputMessageIds,K=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,z=Array.isArray(Q)?Q.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=sZ):[];if(typeof V!=="string"||V.length===0||V.length>128||Z!==void 0&&V!==Z||!Array.isArray(Q)||Q.length>$2||z.length!==Q.length||typeof K!=="number"||!Number.isSafeInteger(K)||K<0||K>L4||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>f4||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>O4)return;let B;if("goalFinalization"in Y){if(B=P4(Y.goalFinalization),!B)return}return{turnId:V,inputMessageIds:[...new Set(z)],turnsCount:K,toolCallsCount:X,durationMs:H,...B?{goalFinalization:B}:{}}}function j2($,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 V=P2(Y,Z);if(V)return V}return}function y4($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=P2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function I$($,Z){let J=Z?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===Z):-1;if(Z&&J<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,Q=new Set;for(let X of $.slice(J+1)){if(X.type==="interaction_requested"){Q.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},z=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(z,{toolCallId:z,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(z),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(z)&&H.error===null)V.add(z)}}let K=[...W.values()];return{all:K,orphaned:K.filter((X)=>!Y.has(X.toolCallId)&&!Q.has(X.toolCallId)),hadSuccessfulResult:K.some((X)=>V.has(X.toolCallId))}}class E0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=z0(),Z=100,J=D2(),W=U$($)){this.projectPath=$,this.maxSessions=Z,this.version=J,this.stateStorage=W}createEvent($,Z,J){return{id:B0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:U2(this.projectPath)}:{},version:this.version,data:J}}log($){return O0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=B$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=E0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,J,Z),E0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(E0.sessionInitializationRuns.get(J)===W)E0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>N4){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z,J){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),V={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},Q=this.createEvent("session_created",$,V);await this.log($).commit(Q)}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=F2;return Z}async initialize(){try{await q2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await C0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,V,Q){try{await this.ensureSessionCreated($,V);let K=new Date().toISOString(),X=B0(),H={messageId:X,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:K,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,H),B=Z==="assistant"&&Q?.trim()?[this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:"reasoning",payload:{text:Q},createdAt:K})]:[],j=typeof J==="string"?[this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:"text",payload:{text:J},createdAt:K})]:J.map((U)=>this.createEvent("part_created",$,{partId:B0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:_4(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:K}));return await this.log($).commitBatch([z,...B,...j]),X}catch(K){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,K),K}}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=D0(J);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===Z))throw new _0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===Z);if(!Y||!W6(W,Y))throw new _0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof _0))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=D0(W),V=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(Z.inboxMessageId)),Q=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===Z.inboxMessageId),K=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 U=j.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let f=U.input,N=f.resume_from??f.resume;return f.run_in_background===!0&&f.subagent_session_id===Z.childSessionId&&f.description===Z.subagentRef.subagentDescription&&(f.subagent_type===void 0||f.subagent_type===Z.subagentRef.subagentType)&&(f.resume_from===void 0||f.resume===void 0||f.resume_from===f.resume)&&(N===void 0?Z.subagentRef.subagentResumedFrom===void 0:N===Z.subagentRef.subagentResumedFrom)});if(!K)return J={eligible:!1,acknowledged:V,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];if(V)return J={eligible:!0,acknowledged:!0,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];let X=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(Q&&X)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:Q.data.messageId},[];let H=new Date().toISOString(),z=Q?.data.messageId??B0(),B=[];if(!Q){let j={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(Z.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:B0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:H}))}if(!X){let j=Y.findLast((f)=>f.type==="part_created"&&f.data.partType==="subtask_ref"&&f.data.messageId===K.data.messageId&&f.data.payload!==null&&typeof f.data.payload==="object"&&!Array.isArray(f.data.payload)&&f.data.payload.childSessionId===Z.childSessionId),U=j?.data.payload&&typeof j.data.payload==="object"&&!Array.isArray(j.data.payload)?j.data.payload:void 0;B.push(this.createEvent("part_created",$,{partId:B0(),messageId:K.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 U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return J={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),J}async saveTurnStart($,Z){if(Z.goalLineage&&Z.goalLineage.currentTurnId!==Z.turnId)throw Error("Goal lineage current turn must match turn start");await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=D0(J);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===Z.turnId))throw new _0;let Y=w$(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 _0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=D0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),Q=[...new Set(J)].filter((H)=>!V.has(H)),K=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===Z.turnId);if(K){if(K.type==="turn_aborted"||Q.length===0)throw new _0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]}let X=w$(Y).active;if(!X||X.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...Q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof _0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=H1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let Q,K=[];try{await this.log($).commitValidatedBatch((X)=>{let H=D0(X),z=N2(H),B=H.findLast((u)=>(u.type==="turn_completed"||u.type==="turn_aborted")&&u.data.turnId===Z.turnId);if(B){if(B.type==="turn_completed")throw Q=void 0,K=[],new _0;let u=A2(B.data.recovery),P0=u?V.filter((A0)=>u.inputMessageIds.includes(A0)):[],Z0=P0.filter((A0)=>!z.has(A0));if(K=P0,Q=W6(H,B,P0),Z0.length===0)throw new _0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Z0,acknowledgedAt:Z.abortedAt})]}let j=w$(H).active;if(!j||j.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let U=I$(H,j.turnId),f=X2(H,j.turnId),N=z1(H),b=new Set(Z.recovery?.inputMessageIds??[]),S=N?N.inputMessageIds.filter((u)=>b.has(u)):[],R=[...new Set([...f,...S])],g=U.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,h={version:3,inputMessageIds:R,hadSuccessfulToolResult:g,interruptedToolCallCount:U.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:g&&!U.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:J6(H,j.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};Q={turnId:Z.turnId,outcome:"aborted",inputMessageIds:h.inputMessageIds,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},...h.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent};let $0=V.filter((u)=>R.includes(u)),o=$0.filter((u)=>!z.has(u));K=$0;let T=new Set(z);for(let u of $0)T.add(u);let q=h.inputMessageIds.filter((u)=>!T.has(u)),l=h.hadSuccessfulToolResult||h.interruptedToolCallCount>0;Q=q.length>0||l?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:q,hadSuccessfulToolResult:h.hadSuccessfulToolResult,...h.interruptedToolCallCount>0?{interruptedToolCallCount:h.interruptedToolCallCount}:{},...h.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:h.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:G0,...v}=Z;return[this.createEvent("turn_aborted",$,{...v,...$0.length>0?{acknowledgedInputMessageIds:$0}:{},recovery:h}),...o.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:o,acknowledgedAt:Z.abortedAt})]:[]]})}catch(X){if(!(X instanceof _0))throw X}return{...Q?{recovery:Q}:{},acknowledgedInputMessageIds:K}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=D0(Z),W=w$(J).active;return W?I$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=D0(Z),W=w$(J).active;if(W){let Y=I$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(j2(J,W.turnId))return!0}return z1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=D0(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 V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=D0(W),V=w$(Y).active,Q=I$(Y);if(!V&&Q.orphaned.length===0){if(J=z1(Y),J)return[];throw new _0}let K=V?j2(Y,V.turnId):void 0;if(V&&K&&Q.orphaned.length===0){let T=I$(Y,V.turnId);J={turnId:V.turnId,outcome:"completed",inputMessageIds:K.inputMessageIds,hadSuccessfulToolResult:T.hadSuccessfulResult,emptyFinalCorrectionSpent:J6(Y,V.turnId),finalization:K};let q=new Set(Y.flatMap((v)=>v.type==="inbox_acknowledged"?v.data.messageIds:[])),l=K.inputMessageIds.filter((v)=>!q.has(v)),G0=new Date().toISOString();return[...l.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:l,acknowledgedAt:G0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:G0,turnsCount:K.turnsCount,toolCallsCount:K.toolCallsCount,durationMs:K.durationMs})]}let X=V?I$(Y,V.turnId):void 0,H=X?.orphaned.some((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return l1(T,q)&&q?.error===void 0})??!1,z=X?.orphaned.filter((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return q?.toolCallId===T.toolCallId&&q.toolName===T.toolName&&q.error===void 0}).every((T)=>l1(T,Z.adoptedToolResults?.get(T.toolCallId)))??!0,B=new Set(V?.inputMessageIds??[]),j=V?z1(Y):void 0,U=j?j.inputMessageIds.filter((T)=>B.has(T)):[],f=U.length>0,N=V?X2(Y,V.turnId):[],b=X?X.orphaned.filter((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId);return!l1(T,q)}).length:0,S=f&&j?.hadSuccessfulToolResult===!0,R=(X?.hadSuccessfulResult??!1)||H||S;J=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([...N,...U])],hadSuccessfulToolResult:R,...(()=>{let T=b+(f?j?.interruptedToolCallCount??0:0);return T>0?{interruptedToolCallCount:T}:{}})(),...R&&!(X?.hadSuccessfulResult??!1)&&z&&(!S||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:J6(Y,V.turnId)||f&&j?.emptyFinalCorrectionSpent===!0}:z1(Y);let g=V?X?.all.length??0:0,h=new Date().toISOString(),$0=V?Date.parse(V.startedAt):Number.NaN,o=Q.orphaned.flatMap((T)=>{let q=Z.adoptedToolResults?.get(T.toolCallId),l=l1(T,q)?q:void 0,G0=this.createEvent("part_created",$,{partId:T.toolCallId,messageId:l?T.messageId:T.toolCallId,partType:"tool_result",payload:l?{toolCallId:T.toolCallId,toolName:T.toolName,output:l.output,error:l.error??null,...l.metadata===void 0?{}:{metadata:l.metadata}}:{toolCallId:T.toolCallId,toolName:T.toolName,output:null,error:G4,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:h});if(!l?.subagentRef)return[G0];let v=l.subagentRef;return[G0,this.createEvent("part_created",$,{partId:B0(),messageId:T.messageId,partType:"subtask_ref",payload:{childSessionId:v.subagentSessionId,agentType:v.subagentType,description:v.subagentDescription??"",status:v.subagentStatus,summary:v.subagentSummary??"",resumedFrom:v.subagentResumedFrom??null,rootAgentId:v.subagentRootId??v.subagentSessionId,resumeDepth:v.subagentResumeDepth??0,verificationVerdict:v.verificationVerdict??null,startedAt:h,finishedAt:h},createdAt:h})]});return V?[...o,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:h,turnsCount:0,toolCallsCount:g,durationMs:Number.isFinite($0)?Math.max(0,Date.now()-$0):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:o})}catch(W){if(!(W instanceof _0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?y4(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((V)=>V.type==="interaction_requested"&&V.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((V)=>V.type==="interaction_responded"&&V.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((V)=>V.type==="interaction_responded"&&V.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((V)=>V.type==="interaction_recovered"&&V.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((V)=>V.type==="review_started"&&V.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((V)=>V.type==="review_started"&&!J.some((Q)=>Q.type==="review_completed"&&Q.data.reviewId===V.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((V)=>V.type==="review_started"&&V.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((V)=>V.type==="review_completed"&&V.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let Q=new Date().toISOString(),K=W??B0(),X=[];if(!W){let B={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:Q};X.push(this.createEvent("message_created",$,B))}let H=V??B0(),z={partId:H,messageId:K,partType:"tool_call",payload:{toolCallId:H,toolName:Z,input:J},createdAt:Q};if(X.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let B=J,j=typeof B.subagent_session_id==="string"?B.subagent_session_id:void 0,U=typeof B.subagent_type==="string"?B.subagent_type:void 0;if(j&&U){let f={partId:B0(),messageId:K,partType:"subtask_ref",payload:{childSessionId:j,agentType:U,status:"running",summary:typeof B.description==="string"?B.description:"",startedAt:Q},createdAt:Q};X.push(this.createEvent("part_created",$,f))}}return await this.log($).commitBatch(X),H}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Z,J,W,Y=null,V,Q,K,X){try{await this.ensureSessionCreated($,Q);let H=new Date().toISOString(),z=Y??B0();return await this.log($).commitValidatedBatch((B)=>{let j=K?.subagentStatus==="running"?D0(B).findLast((R)=>R.type==="part_created"&&R.data.partType==="subtask_ref"&&R.data.payload!==null&&typeof R.data.payload==="object"&&!Array.isArray(R.data.payload)&&R.data.payload.childSessionId===K.subagentSessionId&&(R.data.payload.status==="completed"||R.data.payload.status==="failed"||R.data.payload.status==="cancelled")):void 0,U=j?.data.payload,f=X&&typeof X==="object"&&!Array.isArray(X)?X:{},N=U?{...f,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,b=[];if(!Y){let R={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:H};b.push(this.createEvent("message_created",$,R))}let S={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:V??null,...N===void 0?{}:{metadata:N}},createdAt:H};if(b.push(this.createEvent("part_created",$,S)),K&&!j){let R=K.subagentStatus==="running"?null:H,g={partId:B0(),messageId:z,partType:"subtask_ref",payload:{childSessionId:K.subagentSessionId,agentType:K.subagentType,description:K.subagentDescription??"",status:K.subagentStatus,summary:K.subagentSummary??"",resumedFrom:K.subagentResumedFrom??null,rootAgentId:K.subagentRootId??K.subagentSessionId,resumeDepth:K.subagentResumeDepth??0,verificationVerdict:K.verificationVerdict??null,startedAt:H,finishedAt:R},createdAt:H};b.push(this.createEvent("part_created",$,g))}return b}),Z}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=B0(),Q={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},K=this.buildCompactionMetadata(J),X={partId:B0(),messageId:V,partType:"summary",payload:{text:Z,metadata:K,...J.replacementMessages?{replacementMessages:L2(J.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,Q),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=r1([]),W=await this.log($).commitValidatedBatch((V)=>{if(J=r1(D0(V)),J.kind!=="none")return[];let Q=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${f2}${B0()}`,createdAt:Q})]});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=r1(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?D0(Z):null}catch{return null}}async loadSession($){try{let Z=D0(await this.log($).readAll());if(Z.length===0)return null;let J=Z.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Z[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=D0(await this.log($).readAll());if(Z.length===0)return null;let J=new Map;for(let Q of Z){if(Q.type==="message_created")J.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let K=J.get(Q.data.messageId);if(K){let X=Q.data.payload;K.content=X.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let K=J.get(Q.data.messageId);if(K)K.content=K.content?`${K.content}
96
+ [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],V=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:V}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=Y1(this.projectPath);return(await C0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=i1(this.projectPath,$),J=new C$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let V=D0(Y),Q=Y[Y.length-1],K=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(Q.timestamp).getTime(),messageCount:K,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=i1(this.projectPath,$);await new C$(Z).delete(),await C0.unlink(B2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await G2(this.projectPath,$,z2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-b7b1h83p.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=i1(this.projectPath,J),V=await new C$(W).getStats();Z+=V.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=Y1(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let Z=O2.join($,".health-check");return await C0.writeFile(Z,"test","utf-8"),await C0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return w2()}}function _4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var y2=131072,Y6=new R$;function V6($,Z){return`${b4.resolve($)}\x00${Z}`}function X6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>y2)throw Error(`${Z} exceeds ${y2} bytes`);return JSON.parse(J)}function _2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function S4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function R4($,Z){if($.request.interactionType!=="elicitation")return X6(Z,"Interaction response");return X6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function b2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function T4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function M4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
97
97
  `)}function k4($,Z){let{request:J}=$;if(J.interactionType==="question"){let Q=M4(Z);return{toolOutput:`User answers:
98
98
  ${Q}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
99
99
  ${Q}
@@ -158,7 +158,7 @@ MCP task ${J$(D.taskId)} for ${J$(D.serverName)}/${J$(D.toolName)} is ${D.status
158
158
 
159
159
  <system-reminder>
160
160
  ${I2(W$,N.totalFailures)}
161
- </system-reminder>`}:void 0,v6=f(),C6=L$&&$1(F$)?v6.filter((D)=>D.name!=="Task"):v6,a$=u0,FZ=a$?C6.filter((D)=>D.name===a$):C6;q.writeback();let O$=$.chatService.getConfig(),I6=iZ(q.systemMessages,FZ,O$.model),LZ=f$.project({history:q.getHistory(),pendingMessages:_1?[_1]:[],contextRevision:q.contextRevision,modelName:O$.model,requestProfile:I6}),fZ=z8({contextTokens:LZ.contextTokens,tokenSource:LZ.source,estimatedPendingTokens:LZ.estimatedPendingTokens,maxContextTokens:O$.maxContextTokens,maxOutputTokens:j8({maxContextTokens:O$.maxContextTokens,maxOutputTokens:O$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),b1=yield*w8($,J,Q,fZ,W?.signal,M,T0,G8);if(b1.kind==="failed")return R5(Q,K.length,V,b1.phase);if(b1.kind==="snipped"||b1.kind==="compacted")q.replaceHistory(J.messages),f$.reset();if(fZ.phase==="handoff_band"){let D=await E5({deps:$,context:J,state:q,snapshot:fZ,attemptSpent:q1});if(D.kind==="failed"||D.kind==="suppressed")q1=!0}if(q.writeback(),Q=W$,yield{kind:"turn_start",turn:Q,maxTurns:A0},W?.signal?.aborted)return z(Q-1,K.length,W.signal);if(_1)q.appendControl("user",_1);let u6=W?.stream!==!1;u0=void 0;let F8=q.historyLength+q.pending.length,g6=!v&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,OZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,p6={providerSessionId:J.sessionId,...a$?{toolChoice:{type:"tool",toolName:a$}}:{},...g6?{providerRecovery:g6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:OZ,requestClass:v?"background":"foreground"}},G,a0,Y$=new L6;try{if(u6)a0=new ZZ($.toolExecutor,{sessionId:J.sessionId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:OZ,workspaceRoot:J.workspaceRoot||z0(),executionRoot:J.executionRoot??J.workspaceRoot??z0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:P1,worktreeActive:F0.has("EnterWorktree")&&!F0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,X,J.subagentInfo,(D,w)=>{Y$.push({toolCall:D,update:w})},$.executionEngine!==void 0),a0.setAdmissionPolicy(k6),a0.setAdmissionRollback(q8),a0.setExecutionPolicy(x6),G=yield*N5($,q.toLLMMessages(),FZ,W?.signal,p6,a0);else G=await $.chatService.chat(q.toLLMMessages(),FZ,W?.signal,p6)}catch(D){if(O6(D)&&!A6(D)&&GZ.canAttempt()){c.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let w=$.chatService.getConfig(),_=!1,P="failed",m,E,O,p,x,y0,H0,C,y,J0,s,L0,r;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{a0?.discard();let A=await GZ.tryReactiveCompact(J.messages,{modelName:w.model,modelProvider:w.provider,maxContextTokens:w.maxContextTokens??0,apiKey:w.apiKey,baseURL:w.baseUrl,signal:W?.signal,activeTask:T0,workspaceRoot:J.workspaceRoot||z0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(m=A.strategy,E=A.preTokens,O=A.postTokens,p=A.sampleAttempts,x=A.inputReductions,y0=A.messagesOmitted,H0=A.filesOmitted,C=A.imagesOmitted,y=A.fallbackTargetTokens,J0=A.fallbackMessagesOmitted,s=A.fallbackMessagesTruncated,L0=A.failureReason,A.success&&A.strategy&&A.summary!==void 0&&A.preTokens!==void 0){if(A.usage)yield{kind:"token_usage",usage:JZ(A.usage,w.maxContextTokens??0)};let w0=await W1($,J,A.summary,{trigger:"auto",reason:"context_limit",strategy:A.strategy,preTokens:A.preTokens,postTokens:A.postTokens,sampleAttempts:A.sampleAttempts,inputReductions:A.inputReductions,messagesOmitted:A.messagesOmitted,filesOmitted:A.filesOmitted,imagesOmitted:A.imagesOmitted,fallbackTargetTokens:A.fallbackTargetTokens,fallbackMessagesOmitted:A.fallbackMessagesOmitted,fallbackMessagesTruncated:A.fallbackMessagesTruncated,failureReason:A.failureReason,filesIncluded:A.filesIncluded,replacementMessages:A.messages},{required:$.executionEngine!==void 0});r=await _6(A.memoryPlan,J,w0),J.messages=A.messages,q.replaceHistory(J.messages),f$.reset(),u0=a$,P=A.strategy==="llm"?"completed":"fallback",_=!0,c.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(A){if(c0(A))throw A;c.error("[Loop] 反应式压缩失败,不重放 Provider 请求",A)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:P,strategy:m,preTokens:E,postTokens:O,sampleAttempts:p,inputReductions:x,messagesOmitted:y0,filesOmitted:H0,imagesOmitted:C,fallbackTargetTokens:y,fallbackMessagesOmitted:J0,fallbackMessagesTruncated:s,failureReason:L0,memory:r}}if(_){Q--;continue}}else if(O6(D)&&A6(D))c.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(O6(D))c.warn("[Loop] reactive context recovery already attempted; refusing another replay");throw D}for(let D of G.toolCalls??[]){if(D.type!=="function")continue;let w=D1(D.function.arguments);if(w===null)continue;U1(D.function.name,w),D.function.arguments=JSON.stringify(w)}if(GZ.reset(),M=Date.now(),G.usage){if(G.usage.totalTokens)i+=G.usage.totalTokens;yield{kind:"token_usage",usage:JZ(G.usage,$.currentModelMaxContextTokens)}}f$.recordProviderUsage({usage:G.usage,contextRevision:q.contextRevision,historyLength:F8,modelName:O$.model,requestProfile:I6});let L8=G.usage?.completionTokens??0;if(qZ=r6(qZ,L8,i0>0),W?.signal?.aborted)return z(Q-1,K.length,W.signal);if(!u6||!!G._nonStreamingFallback){if(G.reasoningContent&&G.reasoningContent.trim())yield{kind:"thinking_delta",delta:G.reasoningContent};if(G.content&&G.content.trim())yield{kind:"content_delta",delta:G.content}}yield{kind:"stream_end"};let E1=EZ(G.finishReason,i0,qZ),AZ=E1.action!=="none"&&K0!==void 0&&U!==void 0&&(G.toolCalls?.length??0)===0;if(AZ){let D=await o0?.drainOrSeal();if(D&&D.messages.length>0){K0=void 0,r0=!1,d0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let w=await x0($,J,G.content||"",X,G.reasoningContent);if(w)X=w;yield{kind:"steering_applied",...await y1(D.messages),delivery:"current_turn",queue:await o0.getSnapshot()};continue}S6=!0}if(E1.action==="recover"&&!AZ){let D=await T6(G);if(D.action==="continue")continue;if(D.action==="fail")return D.result;i0++,c.warn(`[Loop] Max output tokens hit (recovery ${i0}/3)`);let w={role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls};q.appendToHistory(w);let _=await x0($,J,G.content||"",X,G.reasoningContent);if(_)X=_;let P={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};q.appendToHistory(P);let m=await m0($,J,P.content,X);if(m)X=m;continue}if(!AZ&&(E1.action==="truncated"||E1.action==="budget_stop")){if(!G.content?.trim()&&!K0)return{success:!1,error:{type:"intent_fulfillment_failed",message:"The model exhausted its output budget without a non-empty final response."},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,outputTruncated:!0}};let D=R6(),w=D?.finalMessage??G.content??"",_=await l(),P=D||_?{...D?.persistenceMetadata,..._?{turnFinalization:_}:{}}:void 0;q.appendAssistant({role:"assistant",content:w,reasoningContent:D?void 0:G.reasoningContent,tool_calls:D?void 0:G.toolCalls,...P?{metadata:g$(P)}:{}});let m=await x0($,J,w,X,D?void 0:G.reasoningContent,P);if(m)X=m;if(U&&!D)return{success:!1,error:{type:"structured_output_failed",message:"The model reached its output budget before submitting a schema-valid structured response."},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,outputTruncated:!0,structuredOutputSchemaDigest:U.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:w,metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,outputTruncated:!0,...D?.resultMetadata}}}if(!G.toolCalls||G.toolCalls.length===0){let D=z6(g,[],[]);if(D)yield{kind:"action_stationarity",...D};let w=await o0?.drain()??[];if(w.length>0){if(G.finishReason!=="length")i0=0;K0=void 0,r0=!1,d0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let k=await x0($,J,G.content||"",X,G.reasoningContent);if(k)X=k;yield{kind:"steering_applied",...await y1(w),delivery:"current_turn",queue:await o0.getSnapshot()};continue}if(U&&!K0){if(G.finishReason!=="length")i0=0;if(X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),d0>=N6)return{success:!1,error:{type:"structured_output_failed",message:`The model did not call ${I0} with a schema-valid object before the corrective retry budget was exhausted.`},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,structuredOutputSchemaDigest:U.schemaDigest}};d0++;let k=`The final response is invalid because this turn requires the ${I0} tool. Complete any remaining work, then call ${I0} exactly once with an object matching its schema. Do not return JSON as prose.`;q.appendControl("user",{role:"user",content:k});let A$=await m0($,J,k,X);if(A$)X=A$;continue}let _=await T6(G);if(_.action==="continue")continue;if(_.action==="fail")return _.result;if(G.finishReason!=="length")i0=0;if(G.content&&g2(R,G.content)){X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:`
161
+ </system-reminder>`}:void 0,v6=f(),C6=L$&&$1(F$)?v6.filter((D)=>D.name!=="Task"):v6,a$=u0,FZ=a$?C6.filter((D)=>D.name===a$):C6;q.writeback();let O$=$.chatService.getConfig(),I6=iZ(q.systemMessages,FZ,O$.model),LZ=f$.project({history:q.getHistory(),pendingMessages:_1?[_1]:[],contextRevision:q.contextRevision,modelName:O$.model,requestProfile:I6}),fZ=z8({contextTokens:LZ.contextTokens,tokenSource:LZ.source,estimatedPendingTokens:LZ.estimatedPendingTokens,maxContextTokens:O$.maxContextTokens,maxOutputTokens:j8({maxContextTokens:O$.maxContextTokens,maxOutputTokens:O$.maxOutputTokens,configuredMaxOutputTokens:$.config.maxOutputTokens})}),b1=yield*w8($,J,Q,fZ,W?.signal,M,T0,G8);if(b1.kind==="failed")return R5(Q,K.length,V,b1.phase);if(b1.kind==="snipped"||b1.kind==="compacted")q.replaceHistory(J.messages),f$.reset();if(fZ.phase==="handoff_band"){let D=await E5({deps:$,context:J,state:q,snapshot:fZ,attemptSpent:q1});if(D.kind==="failed"||D.kind==="suppressed")q1=!0}if(q.writeback(),Q=W$,yield{kind:"turn_start",turn:Q,maxTurns:A0},W?.signal?.aborted)return z(Q-1,K.length,W.signal);if(_1)q.appendControl("user",_1);let u6=W?.stream!==!1;u0=void 0;let F8=q.historyLength+q.pending.length,g6=!v&&($.config.providerForegroundRecoveryMs??0)>0?{mode:"bounded_foreground",budgetMs:$.config.providerForegroundRecoveryMs}:void 0,OZ=J.subagentInfo?.providerAdmissionOwnerId??J.subagentInfo?.parentSessionId??J.sessionId,p6={providerSessionId:J.sessionId,...a$?{toolChoice:{type:"tool",toolName:a$}}:{},...g6?{providerRecovery:g6}:{},providerAdmission:{sessionId:J.sessionId,ownerId:OZ,requestClass:v?"background":"foreground"}},G,a0,Y$=new L6;try{if(u6)a0=new ZZ($.toolExecutor,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:OZ,workspaceRoot:J.workspaceRoot||z0(),executionRoot:J.executionRoot??J.workspaceRoot??z0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:P1,worktreeActive:F0.has("EnterWorktree")&&!F0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager},$.toolExecutor.getRegistry(),$.executionEngine?.getContextManager(),J.sessionId,X,J.subagentInfo,(D,w)=>{Y$.push({toolCall:D,update:w})},$.executionEngine!==void 0),a0.setAdmissionPolicy(k6),a0.setAdmissionRollback(q8),a0.setExecutionPolicy(x6),G=yield*N5($,q.toLLMMessages(),FZ,W?.signal,p6,a0);else G=await $.chatService.chat(q.toLLMMessages(),FZ,W?.signal,p6)}catch(D){if(O6(D)&&!A6(D)&&GZ.canAttempt()){c.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let w=$.chatService.getConfig(),_=!1,P="failed",m,E,O,p,x,y0,H0,C,y,J0,s,L0,r;yield{kind:"compaction",phase:"start",reason:"context_limit"};try{a0?.discard();let A=await GZ.tryReactiveCompact(J.messages,{modelName:w.model,modelProvider:w.provider,maxContextTokens:w.maxContextTokens??0,apiKey:w.apiKey,baseURL:w.baseUrl,signal:W?.signal,activeTask:T0,workspaceRoot:J.workspaceRoot||z0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(m=A.strategy,E=A.preTokens,O=A.postTokens,p=A.sampleAttempts,x=A.inputReductions,y0=A.messagesOmitted,H0=A.filesOmitted,C=A.imagesOmitted,y=A.fallbackTargetTokens,J0=A.fallbackMessagesOmitted,s=A.fallbackMessagesTruncated,L0=A.failureReason,A.success&&A.strategy&&A.summary!==void 0&&A.preTokens!==void 0){if(A.usage)yield{kind:"token_usage",usage:JZ(A.usage,w.maxContextTokens??0)};let w0=await W1($,J,A.summary,{trigger:"auto",reason:"context_limit",strategy:A.strategy,preTokens:A.preTokens,postTokens:A.postTokens,sampleAttempts:A.sampleAttempts,inputReductions:A.inputReductions,messagesOmitted:A.messagesOmitted,filesOmitted:A.filesOmitted,imagesOmitted:A.imagesOmitted,fallbackTargetTokens:A.fallbackTargetTokens,fallbackMessagesOmitted:A.fallbackMessagesOmitted,fallbackMessagesTruncated:A.fallbackMessagesTruncated,failureReason:A.failureReason,filesIncluded:A.filesIncluded,replacementMessages:A.messages},{required:$.executionEngine!==void 0});r=await _6(A.memoryPlan,J,w0),J.messages=A.messages,q.replaceHistory(J.messages),f$.reset(),u0=a$,P=A.strategy==="llm"?"completed":"fallback",_=!0,c.info("[Loop] 反应式压缩成功,重试 LLM 调用")}}catch(A){if(c0(A))throw A;c.error("[Loop] 反应式压缩失败,不重放 Provider 请求",A)}finally{yield{kind:"compaction",phase:"end",reason:"context_limit",outcome:P,strategy:m,preTokens:E,postTokens:O,sampleAttempts:p,inputReductions:x,messagesOmitted:y0,filesOmitted:H0,imagesOmitted:C,fallbackTargetTokens:y,fallbackMessagesOmitted:J0,fallbackMessagesTruncated:s,failureReason:L0,memory:r}}if(_){Q--;continue}}else if(O6(D)&&A6(D))c.warn("[Loop] prompt_too_long arrived after Provider output; refusing replay");else if(O6(D))c.warn("[Loop] reactive context recovery already attempted; refusing another replay");throw D}for(let D of G.toolCalls??[]){if(D.type!=="function")continue;let w=D1(D.function.arguments);if(w===null)continue;U1(D.function.name,w),D.function.arguments=JSON.stringify(w)}if(GZ.reset(),M=Date.now(),G.usage){if(G.usage.totalTokens)i+=G.usage.totalTokens;yield{kind:"token_usage",usage:JZ(G.usage,$.currentModelMaxContextTokens)}}f$.recordProviderUsage({usage:G.usage,contextRevision:q.contextRevision,historyLength:F8,modelName:O$.model,requestProfile:I6});let L8=G.usage?.completionTokens??0;if(qZ=r6(qZ,L8,i0>0),W?.signal?.aborted)return z(Q-1,K.length,W.signal);if(!u6||!!G._nonStreamingFallback){if(G.reasoningContent&&G.reasoningContent.trim())yield{kind:"thinking_delta",delta:G.reasoningContent};if(G.content&&G.content.trim())yield{kind:"content_delta",delta:G.content}}yield{kind:"stream_end"};let E1=EZ(G.finishReason,i0,qZ),AZ=E1.action!=="none"&&K0!==void 0&&U!==void 0&&(G.toolCalls?.length??0)===0;if(AZ){let D=await o0?.drainOrSeal();if(D&&D.messages.length>0){K0=void 0,r0=!1,d0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let w=await x0($,J,G.content||"",X,G.reasoningContent);if(w)X=w;yield{kind:"steering_applied",...await y1(D.messages),delivery:"current_turn",queue:await o0.getSnapshot()};continue}S6=!0}if(E1.action==="recover"&&!AZ){let D=await T6(G);if(D.action==="continue")continue;if(D.action==="fail")return D.result;i0++,c.warn(`[Loop] Max output tokens hit (recovery ${i0}/3)`);let w={role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls};q.appendToHistory(w);let _=await x0($,J,G.content||"",X,G.reasoningContent);if(_)X=_;let P={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};q.appendToHistory(P);let m=await m0($,J,P.content,X);if(m)X=m;continue}if(!AZ&&(E1.action==="truncated"||E1.action==="budget_stop")){if(!G.content?.trim()&&!K0)return{success:!1,error:{type:"intent_fulfillment_failed",message:"The model exhausted its output budget without a non-empty final response."},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,outputTruncated:!0}};let D=R6(),w=D?.finalMessage??G.content??"",_=await l(),P=D||_?{...D?.persistenceMetadata,..._?{turnFinalization:_}:{}}:void 0;q.appendAssistant({role:"assistant",content:w,reasoningContent:D?void 0:G.reasoningContent,tool_calls:D?void 0:G.toolCalls,...P?{metadata:g$(P)}:{}});let m=await x0($,J,w,X,D?void 0:G.reasoningContent,P);if(m)X=m;if(U&&!D)return{success:!1,error:{type:"structured_output_failed",message:"The model reached its output budget before submitting a schema-valid structured response."},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,outputTruncated:!0,structuredOutputSchemaDigest:U.schemaDigest}};if(D)yield D.event;return{success:!0,finalMessage:w,metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,outputTruncated:!0,...D?.resultMetadata}}}if(!G.toolCalls||G.toolCalls.length===0){let D=z6(g,[],[]);if(D)yield{kind:"action_stationarity",...D};let w=await o0?.drain()??[];if(w.length>0){if(G.finishReason!=="length")i0=0;K0=void 0,r0=!1,d0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let k=await x0($,J,G.content||"",X,G.reasoningContent);if(k)X=k;yield{kind:"steering_applied",...await y1(w),delivery:"current_turn",queue:await o0.getSnapshot()};continue}if(U&&!K0){if(G.finishReason!=="length")i0=0;if(X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),d0>=N6)return{success:!1,error:{type:"structured_output_failed",message:`The model did not call ${I0} with a schema-valid object before the corrective retry budget was exhausted.`},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,structuredOutputSchemaDigest:U.schemaDigest}};d0++;let k=`The final response is invalid because this turn requires the ${I0} tool. Complete any remaining work, then call ${I0} exactly once with an object matching its schema. Do not return JSON as prose.`;q.appendControl("user",{role:"user",content:k});let A$=await m0($,J,k,X);if(A$)X=A$;continue}let _=await T6(G);if(_.action==="continue")continue;if(_.action==="fail")return _.result;if(G.finishReason!=="length")i0=0;if(G.content&&g2(R,G.content)){X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:`
162
162
 
163
163
  <system-reminder>
164
164
  ${p2()}
@@ -170,7 +170,7 @@ ${x.reason}
170
170
 
171
171
  <system-reminder>
172
172
  Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
173
- </system-reminder>`;X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:k});continue}let y0=await o0?.drainOrSeal();if(y0&&y0.messages.length>0){await o$("Goal completion evidence invalidated by new user steering"),K0=void 0,r0=!1,d0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let k=await x0($,J,G.content||"",X,G.reasoningContent);if(k)X=k;yield{kind:"steering_applied",...await y1(y0.messages),delivery:"current_turn",queue:await o0.getSnapshot()};continue}let H0=c2({requested:S0,taskAvailable:f().some((k)=>k.name==="Task"),mutationRevision:G$,verificationRevision:m$,verificationVerdict:N0,verificationFeedback:q$,verificationStallCount:l$,retryCount:F1});if(H0.action==="retry"){if(F1++,g0=H0.requireVerificationTask,g0)u0="Task";X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:H0.prompt});continue}if(H0.action==="fail")return X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:H0.message},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,goalVerificationVerdict:N0,goalVerifierSessionId:R0,goalVerificationEvidenceSha256:h0}};let C=!1,y=!1;if(S0){if(!W?.goalLifecycle||N0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,goalVerificationVerdict:N0,goalVerifierSessionId:R0,goalVerificationEvidenceSha256:h0}};y=!0}let J0=R6(),s=J0?.finalMessage??G.content??"",L0=J0?.persistenceMetadata,r;if(y){let k=p0?.completionVerification;if(p0?.status!=="verifying"||p0.goalId!==c$||k?.status!=="pass"||k.attempt!==f1||typeof k.verifierSessionId!=="string"||k.verifierSessionId!==R0||typeof k.evidenceSha256!=="string"||k.evidenceSha256!==h0)throw Error("Goal completion lost its persisted verification receipt before finalization");r={goalId:p0.goalId,verificationAttempt:k.attempt,verifierSessionId:k.verifierSessionId,evidenceSha256:k.evidenceSha256,goalUpdatedAt:p0.updatedAt}}let A=await l(r),w0=L0||A?{...L0,...A?{turnFinalization:A}:{}}:void 0;q.appendAssistant({role:"assistant",content:s,...w0?{metadata:g$(w0)}:{}});let j0=await x0($,J,s,X,L0?void 0:G.reasoningContent,w0);if(j0)X=j0;if(y&&W?.goalLifecycle){let k=await W.goalLifecycle.finalizeCompletion();S0=!1,C=!0,yield{kind:"goal_updated",goal:k}}if(J0)yield J0.event;return{success:!0,finalMessage:s,metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,toolSuccessRate:K.length>0?K.filter((k)=>k.success).length/K.length:void 0,totalToolFailures:N.totalFailures||void 0,...S(),...C?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...R0?{goalVerifierSessionId:R0}:{},...h0?{goalVerificationEvidenceSha256:h0}:{}}:{},...S6?{outputTruncated:!0}:{},...J0?.resultMetadata}}}if(G.finishReason!=="length")i0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let D=await x0($,J,G.content||"",X,G.reasoningContent);if(D)X=D}if(W?.signal?.aborted)return z(Q,K.length,W.signal);let S1=G.toolCalls.filter((D)=>D.type==="function"),NZ;if(a0?.hasTools()){c.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${S1.length} 个工具结果`);let D=a0;for(let w of D.getQueuedToolCalls()){let P=B.get(w.function.name)?.kind;yield{kind:"tool_start",toolCall:w,toolKind:P}}NZ=(async()=>{let w=[];for await(let _ of D.getRemainingResults())w.push(_);return w})()}else{let D=new Map,w=new B1;for(let E of S1){let O=w.admit();if(O){D.set(E.id,O);continue}let p=D1(E.function.arguments),x=p===null?void 0:k6(E.function.name,p);if(x){D.set(E.id,x);continue}let H0=B.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:H0}}let _=Promise.resolve(),P=(E,O,p)=>{let x=_.then(()=>hZ($,J,E,O,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return _=x.then(()=>{return},()=>{return}),x},m=async(E)=>{let O=null;try{let p=D.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let x=D1(E.function.arguments);if(x===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};U1(E.function.name,x);try{O=await P(E.function.name,x,E.id)}catch(C){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:C instanceof Error?C:Error(String(C))}}if(E.function.name==="ExitWorktree"&&F0.has("EnterWorktree")&&!F0.has("ExitWorktree")&&RZ(BZ,jZ,0).action!=="none"){let C="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:C,error:{type:"validation_error",message:C},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:O}}let H0=await x6(E.function.name,x,{sessionId:J.sessionId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:OZ,workspaceRoot:J.workspaceRoot||z0(),executionRoot:J.executionRoot??J.workspaceRoot??z0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:P1,worktreeActive:F0.has("EnterWorktree")&&!F0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.sessionId&&J.workspaceKind!=="acp-remote"?q0.createConfirmationHandler(J.confirmationHandler,{sessionId:J.sessionId,projectPath:J.workspaceRoot||z0(),toolCallId:O??E.id,toolName:E.function.name}):J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager,onProgress:(C)=>{Y$.push({toolCall:E,update:{message:C.slice(0,1000)}})},onProgressUpdate:(C)=>{Y$.push({toolCall:E,update:C})}});return{toolCall:E,result:H0,toolUseUuid:O}}catch(p){return c.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:O,error:p instanceof Error?p:Error("Unknown error")}}};NZ=Promise.all(S1.map(m))}let R1,d6,m6=!1,PZ=!1,f8=NZ.then((D)=>{R1=D},(D)=>{m6=!0,d6=D}).finally(()=>{PZ=!0,Y$.close()});while(!PZ||Y$.hasPending){let D=Y$.shift()??(PZ?void 0:await Y$.next());if(D)yield{kind:"tool_progress",toolCall:D.toolCall,update:D.update}}if(await f8,m6)throw d6;if(!R1)throw Error("Tool execution completed without results");let O8=new aZ;for(let{toolCall:D,result:w,toolUseUuid:_}of R1){let P=D;if(K.push(w),w.metadata?.abortedBeforeLaunch){let y=w.error?.message??"任务已被用户中止";if(_)try{let J0=await h1($,J,_,P.function.name,null,_,y,void 0,void 0,{required:$.executionEngine!==void 0});if(J0)X=J0}catch{return V8(Q,K.length,V)}return q.appendToolResult({role:"tool",tool_call_id:P.id,name:P.function.name,content:`Error: ${y}`}),z(Q,K.length,W?.signal)}{let y=w.metadata&&typeof w.metadata==="object"?w.metadata:void 0,s=((j0)=>j0==="running"||j0==="completed"||j0==="failed"||j0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",L0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,r=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:P.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:s,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:L0}:void 0,A=y?(()=>{let{oldContent:j0,newContent:k,...A$}=y;return g$(A$)})():void 0;if(y?.durableToolUseFailed!==!0&&(_!==null||$.executionEngine===void 0))try{let j0=await h1($,J,_??P.id,P.function.name,w.success?g$(w.llmContent):null,_,w.success?void 0:w.error?.message,r,A,{required:$.executionEngine!==void 0});if(j0)X=j0}catch{return V8(Q,K.length,V)}}yield{kind:"tool_result",toolCall:P,result:w};let m=await f6(P,w,$,J);if(m){if(yield m,!J.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i}}}}}let E,O=w.metadata&&typeof w.metadata==="object"?w.metadata:void 0,p=P.function.name==="Task"&&O?{subagentSessionId:O.subagentSessionId,subagentType:O.subagentType,subagentStatus:O.subagentStatus,subagentSummary:O.subagentSummary,subagentResumedFrom:O.subagentResumedFrom,subagentRootId:O.subagentRootId,subagentResumeDepth:O.subagentResumeDepth,verificationVerdict:O.verificationVerdict,verificationFeedback:O.verificationFeedback}:void 0;if(w.success){if(h2(N,P.function.name),O?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");S0=!0;let r=typeof O.goalCompletionAttempt==="number"?O.goalCompletionAttempt:void 0,A=typeof O.goalCompletionRequestedAt==="string"?O.goalCompletionRequestedAt:void 0,w0=typeof O.goalId==="string"?O.goalId:void 0;if(m2({goalId:c$,attempt:f1,requestedAt:HZ},{goalId:w0,attempt:r,requestedAt:A}))F1=0,m$=-1,N0=void 0,R0=void 0,q$=void 0,A1=void 0,h0=void 0,p0=void 0;f1=r??f1,HZ=A??HZ,c$=w0??c$,O1=typeof O.goalObjective==="string"?O.goalObjective:O1;let k=await W?.goalLifecycle?.getSnapshot();if(k)l$=k.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:k}}else if(P.function.name==="UpdateGoal"&&O?.goalStatus==="blocked"){S0=!1,g0=!1,d$=!1,L1=!1,N0=void 0,m$=-1,R0=void 0,q$=void 0,A1=void 0,l$=void 0,h0=void 0,p0=void 0;let r=await W?.goalLifecycle?.getSnapshot();if(r)yield{kind:"goal_updated",goal:r}}let y=a2(n$,P.function.name,w,J.workspaceRoot);if(y.length>0){if(K0=void 0,r0=!1,d0=0,G$++,r$=-1,n0=void 0,G1=0,S0){F1=0,await o$("Goal completion evidence invalidated by a workspace mutation");let r=await W?.goalLifecycle?.getSnapshot();if(r)l$=r.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:r}}if(W?.goalLifecycle?.clearFrontierStall){let r=await W.goalLifecycle.clearFrontierStall();if(r)yield{kind:"goal_updated",goal:r}}}let J0=typeof O?.subagentType==="string"?O.subagentType:typeof O?.subagent_type==="string"?O.subagent_type:void 0,s=J0===l0,L0=P.function.name==="Task"&&O?.verificationAgentBuiltin===!0&&(J0===Z$||s)&&(O?.subagentStatus==="completed"||O?.status==="completed");if(L0){if(n0=(O?.verificationVerdict==="pass"||O?.verificationVerdict==="fail"||O?.verificationVerdict==="partial"?O.verificationVerdict:void 0)??n2(typeof w.llmContent==="string"?w.llmContent:O?.subagentSummary&&typeof O.subagentSummary==="string"?O.subagentSummary:void 0),r$=G$,L1&&s){L1=!1,N0=n0,m$=G$,R0=typeof O?.subagentSessionId==="string"?O.subagentSessionId:void 0;let A=typeof w.llmContent==="string"?w.llmContent.slice(0,4000):typeof O?.subagentSummary==="string"?O.subagentSummary:void 0,w0=typeof O?.verificationFeedback==="string"&&O.verificationFeedback.trim()?O.verificationFeedback.trim():void 0;if(q$=N0?w0??`Independent verifier returned ${N0.toUpperCase()}.`:void 0,A1=N0!=="pass"&&w0?y6("sha256").update(w0,"utf8").digest("hex"):void 0,N0&&W?.goalLifecycle){let j0=JSON.stringify({goalId:c$,objective:O1,mutationRevision:G$,verdict:N0,verifierSessionId:R0,evidence:A});h0=y6("sha256").update(j0).digest("hex");let k=await W.goalLifecycle.recordVerification({verdict:N0,verifierSessionId:R0,summary:q$,evidenceSha256:h0,feedbackSha256:A1});p0=k,l$=k.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:k}}}}if(y.length>0||L0)E={...y.length>0?{modifiedFiles:y}:{},...L0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...n0?{verificationVerdict:n0}:{}}:{}};if(P.function.name==="EnterWorktree"&&w.metadata?.workspaceTransition==="enter")F0.add("EnterWorktree"),F0.delete("ExitWorktree");else if(P.function.name==="ExitWorktree"&&w.metadata?.workspaceTransition==="exit"&&F0.has("EnterWorktree"))F0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(P.function.name))F0.add(P.function.name);if(P.function.name==="Task"&&w.metadata?.isolation==="worktree")F0.add("TaskWorktree");JJ(jZ,P.function.name,w,J.workspaceRoot)}else x2(N,P.function.name);tJ(b,P.function.name,w);let x=w.success?w.llmContent||"":f5(P.function.name,w.error);if(!w.success){let y=v2(N,P.function.name);if(y&&typeof x==="string")x=`${x}
173
+ </system-reminder>`;X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:k});continue}let y0=await o0?.drainOrSeal();if(y0&&y0.messages.length>0){await o$("Goal completion evidence invalidated by new user steering"),K0=void 0,r0=!1,d0=0,q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent});let k=await x0($,J,G.content||"",X,G.reasoningContent);if(k)X=k;yield{kind:"steering_applied",...await y1(y0.messages),delivery:"current_turn",queue:await o0.getSnapshot()};continue}let H0=c2({requested:S0,taskAvailable:f().some((k)=>k.name==="Task"),mutationRevision:G$,verificationRevision:m$,verificationVerdict:N0,verificationFeedback:q$,verificationStallCount:l$,retryCount:F1});if(H0.action==="retry"){if(F1++,g0=H0.requireVerificationTask,g0)u0="Task";X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X,controlPrompt:H0.prompt});continue}if(H0.action==="fail")return X=await f0({deps:$,context:J,state:q,assistantContent:G.content||"",assistantReasoningContent:G.reasoningContent,lastMessageUuid:X}),{success:!1,error:{type:"goal_verification_failed",message:H0.message},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,goalVerificationVerdict:N0,goalVerifierSessionId:R0,goalVerificationEvidenceSha256:h0}};let C=!1,y=!1;if(S0){if(!W?.goalLifecycle||N0!=="pass")return{success:!1,error:{type:"goal_verification_failed",message:"Goal completion reached the final boundary without host-owned verification authority and a fresh PASS."},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,goalVerificationVerdict:N0,goalVerifierSessionId:R0,goalVerificationEvidenceSha256:h0}};y=!0}let J0=R6(),s=J0?.finalMessage??G.content??"",L0=J0?.persistenceMetadata,r;if(y){let k=p0?.completionVerification;if(p0?.status!=="verifying"||p0.goalId!==c$||k?.status!=="pass"||k.attempt!==f1||typeof k.verifierSessionId!=="string"||k.verifierSessionId!==R0||typeof k.evidenceSha256!=="string"||k.evidenceSha256!==h0)throw Error("Goal completion lost its persisted verification receipt before finalization");r={goalId:p0.goalId,verificationAttempt:k.attempt,verifierSessionId:k.verifierSessionId,evidenceSha256:k.evidenceSha256,goalUpdatedAt:p0.updatedAt}}let A=await l(r),w0=L0||A?{...L0,...A?{turnFinalization:A}:{}}:void 0;q.appendAssistant({role:"assistant",content:s,...w0?{metadata:g$(w0)}:{}});let j0=await x0($,J,s,X,L0?void 0:G.reasoningContent,w0);if(j0)X=j0;if(y&&W?.goalLifecycle){let k=await W.goalLifecycle.finalizeCompletion();S0=!1,C=!0,yield{kind:"goal_updated",goal:k}}if(J0)yield J0.event;return{success:!0,finalMessage:s,metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,toolSuccessRate:K.length>0?K.filter((k)=>k.success).length/K.length:void 0,totalToolFailures:N.totalFailures||void 0,...S(),...C?{goalCompletionVerified:!0,goalVerificationVerdict:"pass",...R0?{goalVerifierSessionId:R0}:{},...h0?{goalVerificationEvidenceSha256:h0}:{}}:{},...S6?{outputTruncated:!0}:{},...J0?.resultMetadata}}}if(G.finishReason!=="length")i0=0;q.appendAssistant({role:"assistant",content:G.content||"",reasoningContent:G.reasoningContent,tool_calls:G.toolCalls});{let D=await x0($,J,G.content||"",X,G.reasoningContent);if(D)X=D}if(W?.signal?.aborted)return z(Q,K.length,W.signal);let S1=G.toolCalls.filter((D)=>D.type==="function"),NZ;if(a0?.hasTools()){c.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${S1.length} 个工具结果`);let D=a0;for(let w of D.getQueuedToolCalls()){let P=B.get(w.function.name)?.kind;yield{kind:"tool_start",toolCall:w,toolKind:P}}NZ=(async()=>{let w=[];for await(let _ of D.getRemainingResults())w.push(_);return w})()}else{let D=new Map,w=new B1;for(let E of S1){let O=w.admit();if(O){D.set(E.id,O);continue}let p=D1(E.function.arguments),x=p===null?void 0:k6(E.function.name,p);if(x){D.set(E.id,x);continue}let H0=B.get(E.function.name)?.kind;yield{kind:"tool_start",toolCall:E,toolKind:H0}}let _=Promise.resolve(),P=(E,O,p)=>{let x=_.then(()=>hZ($,J,E,O,X,{required:$.executionEngine!==void 0,providerToolCallId:p}));return _=x.then(()=>{return},()=>{return}),x},m=async(E)=>{let O=null;try{let p=D.get(E.id);if(p)return{toolCall:E,result:p,toolUseUuid:null};let x=D1(E.function.arguments);if(x===null)return{toolCall:E,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${E.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};U1(E.function.name,x);try{O=await P(E.function.name,x,E.id)}catch(C){return{toolCall:E,result:{success:!1,llmContent:H$,error:{type:"execution_error",message:H$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:C instanceof Error?C:Error(String(C))}}if(E.function.name==="ExitWorktree"&&F0.has("EnterWorktree")&&!F0.has("ExitWorktree")&&RZ(BZ,jZ,0).action!=="none"){let C="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:E,result:{success:!1,llmContent:C,error:{type:"validation_error",message:C},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:O}}let H0=await x6(E.function.name,x,{sessionId:J.sessionId,turnId:W?.turnFinalization?.turnId,taskListId:J.taskListId,goalTaskListId:J.goalTaskListId,userId:J.userId||"default",modelId:$.config.currentModelId,providerAdmissionOwnerId:OZ,workspaceRoot:J.workspaceRoot||z0(),executionRoot:J.executionRoot??J.workspaceRoot??z0(),workspaceKind:J.workspaceKind??"local",environment:$.config.env,worktreeIsolationRequired:P1,worktreeActive:F0.has("EnterWorktree")&&!F0.has("ExitWorktree"),subagentType:J.subagentInfo?.subagentType,signal:W?.signal,confirmationHandler:J.sessionId&&J.workspaceKind!=="acp-remote"?q0.createConfirmationHandler(J.confirmationHandler,{sessionId:J.sessionId,projectPath:J.workspaceRoot||z0(),toolCallId:O??E.id,toolName:E.function.name}):J.confirmationHandler,permissionMode:J.permissionMode,toolRegistry:B,deferredToolManager:B.deferredToolManager,onProgress:(C)=>{Y$.push({toolCall:E,update:{message:C.slice(0,1000)}})},onProgressUpdate:(C)=>{Y$.push({toolCall:E,update:C})}});return{toolCall:E,result:H0,toolUseUuid:O}}catch(p){return c.error(`Tool execution failed for ${E.function.name}:`,p),{toolCall:E,result:{success:!1,llmContent:"",error:{type:"execution_error",message:p instanceof Error?p.message:"Unknown error"},metadata:void 0},toolUseUuid:O,error:p instanceof Error?p:Error("Unknown error")}}};NZ=Promise.all(S1.map(m))}let R1,d6,m6=!1,PZ=!1,f8=NZ.then((D)=>{R1=D},(D)=>{m6=!0,d6=D}).finally(()=>{PZ=!0,Y$.close()});while(!PZ||Y$.hasPending){let D=Y$.shift()??(PZ?void 0:await Y$.next());if(D)yield{kind:"tool_progress",toolCall:D.toolCall,update:D.update}}if(await f8,m6)throw d6;if(!R1)throw Error("Tool execution completed without results");let O8=new aZ;for(let{toolCall:D,result:w,toolUseUuid:_}of R1){let P=D;if(K.push(w),w.metadata?.abortedBeforeLaunch){let y=w.error?.message??"任务已被用户中止";if(_)try{let J0=await h1($,J,_,P.function.name,null,_,y,void 0,void 0,{required:$.executionEngine!==void 0});if(J0)X=J0}catch{return V8(Q,K.length,V)}return q.appendToolResult({role:"tool",tool_call_id:P.id,name:P.function.name,content:`Error: ${y}`}),z(Q,K.length,W?.signal)}{let y=w.metadata&&typeof w.metadata==="object"?w.metadata:void 0,s=((j0)=>j0==="running"||j0==="completed"||j0==="failed"||j0==="cancelled")(y?.subagentStatus)?y.subagentStatus:"completed",L0=y?.verificationVerdict==="pass"||y?.verificationVerdict==="fail"||y?.verificationVerdict==="partial"?y.verificationVerdict:void 0,r=y&&typeof y.subagentSessionId==="string"?{subagentSessionId:y.subagentSessionId,subagentType:typeof y.subagentType==="string"?y.subagentType:P.function.name,subagentDescription:typeof y.description==="string"?y.description:void 0,subagentStatus:s,subagentSummary:typeof y.subagentSummary==="string"?y.subagentSummary:void 0,subagentResumedFrom:typeof y.subagentResumedFrom==="string"?y.subagentResumedFrom:void 0,subagentRootId:typeof y.subagentRootId==="string"?y.subagentRootId:void 0,subagentResumeDepth:typeof y.subagentResumeDepth==="number"?y.subagentResumeDepth:void 0,verificationVerdict:L0}:void 0,A=y?(()=>{let{oldContent:j0,newContent:k,...A$}=y;return g$(A$)})():void 0;if(y?.durableToolUseFailed!==!0&&(_!==null||$.executionEngine===void 0))try{let j0=await h1($,J,_??P.id,P.function.name,w.success?g$(w.llmContent):null,_,w.success?void 0:w.error?.message,r,A,{required:$.executionEngine!==void 0});if(j0)X=j0}catch{return V8(Q,K.length,V)}}yield{kind:"tool_result",toolCall:P,result:w};let m=await f6(P,w,$,J);if(m){if(yield m,!J.taskListId&&W?.goalLifecycle?.refreshFrontier){let y=await W.goalLifecycle.refreshFrontier();if(y?.ok)yield{kind:"goal_frontier_updated",goal:y.goal,frontier:y.frontier,tasks:y.tasks};else if(y){if(y.goal)yield{kind:"goal_updated",goal:y.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:y.error.message},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i}}}}}let E,O=w.metadata&&typeof w.metadata==="object"?w.metadata:void 0,p=P.function.name==="Task"&&O?{subagentSessionId:O.subagentSessionId,subagentType:O.subagentType,subagentStatus:O.subagentStatus,subagentSummary:O.subagentSummary,subagentResumedFrom:O.subagentResumedFrom,subagentRootId:O.subagentRootId,subagentResumeDepth:O.subagentResumeDepth,verificationVerdict:O.verificationVerdict,verificationFeedback:O.verificationFeedback}:void 0;if(w.success){if(h2(N,P.function.name),O?.goalCompletionRequested===!0){if(!W?.goalLifecycle)throw Error("Goal completion candidate has no host lifecycle authority");S0=!0;let r=typeof O.goalCompletionAttempt==="number"?O.goalCompletionAttempt:void 0,A=typeof O.goalCompletionRequestedAt==="string"?O.goalCompletionRequestedAt:void 0,w0=typeof O.goalId==="string"?O.goalId:void 0;if(m2({goalId:c$,attempt:f1,requestedAt:HZ},{goalId:w0,attempt:r,requestedAt:A}))F1=0,m$=-1,N0=void 0,R0=void 0,q$=void 0,A1=void 0,h0=void 0,p0=void 0;f1=r??f1,HZ=A??HZ,c$=w0??c$,O1=typeof O.goalObjective==="string"?O.goalObjective:O1;let k=await W?.goalLifecycle?.getSnapshot();if(k)l$=k.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:k}}else if(P.function.name==="UpdateGoal"&&O?.goalStatus==="blocked"){S0=!1,g0=!1,d$=!1,L1=!1,N0=void 0,m$=-1,R0=void 0,q$=void 0,A1=void 0,l$=void 0,h0=void 0,p0=void 0;let r=await W?.goalLifecycle?.getSnapshot();if(r)yield{kind:"goal_updated",goal:r}}let y=a2(n$,P.function.name,w,J.workspaceRoot);if(y.length>0){if(K0=void 0,r0=!1,d0=0,G$++,r$=-1,n0=void 0,G1=0,S0){F1=0,await o$("Goal completion evidence invalidated by a workspace mutation");let r=await W?.goalLifecycle?.getSnapshot();if(r)l$=r.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:r}}if(W?.goalLifecycle?.clearFrontierStall){let r=await W.goalLifecycle.clearFrontierStall();if(r)yield{kind:"goal_updated",goal:r}}}let J0=typeof O?.subagentType==="string"?O.subagentType:typeof O?.subagent_type==="string"?O.subagent_type:void 0,s=J0===l0,L0=P.function.name==="Task"&&O?.verificationAgentBuiltin===!0&&(J0===Z$||s)&&(O?.subagentStatus==="completed"||O?.status==="completed");if(L0){if(n0=(O?.verificationVerdict==="pass"||O?.verificationVerdict==="fail"||O?.verificationVerdict==="partial"?O.verificationVerdict:void 0)??n2(typeof w.llmContent==="string"?w.llmContent:O?.subagentSummary&&typeof O.subagentSummary==="string"?O.subagentSummary:void 0),r$=G$,L1&&s){L1=!1,N0=n0,m$=G$,R0=typeof O?.subagentSessionId==="string"?O.subagentSessionId:void 0;let A=typeof w.llmContent==="string"?w.llmContent.slice(0,4000):typeof O?.subagentSummary==="string"?O.subagentSummary:void 0,w0=typeof O?.verificationFeedback==="string"&&O.verificationFeedback.trim()?O.verificationFeedback.trim():void 0;if(q$=N0?w0??`Independent verifier returned ${N0.toUpperCase()}.`:void 0,A1=N0!=="pass"&&w0?y6("sha256").update(w0,"utf8").digest("hex"):void 0,N0&&W?.goalLifecycle){let j0=JSON.stringify({goalId:c$,objective:O1,mutationRevision:G$,verdict:N0,verifierSessionId:R0,evidence:A});h0=y6("sha256").update(j0).digest("hex");let k=await W.goalLifecycle.recordVerification({verdict:N0,verifierSessionId:R0,summary:q$,evidenceSha256:h0,feedbackSha256:A1});p0=k,l$=k.verificationStall?.consecutiveCount,yield{kind:"goal_updated",goal:k}}}}if(y.length>0||L0)E={...y.length>0?{modifiedFiles:y}:{},...L0?{verificationAttempted:!0,verificationAgentBuiltin:!0,...n0?{verificationVerdict:n0}:{}}:{}};if(P.function.name==="EnterWorktree"&&w.metadata?.workspaceTransition==="enter")F0.add("EnterWorktree"),F0.delete("ExitWorktree");else if(P.function.name==="ExitWorktree"&&w.metadata?.workspaceTransition==="exit"&&F0.has("EnterWorktree"))F0.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(P.function.name))F0.add(P.function.name);if(P.function.name==="Task"&&w.metadata?.isolation==="worktree")F0.add("TaskWorktree");JJ(jZ,P.function.name,w,J.workspaceRoot)}else x2(N,P.function.name);tJ(b,P.function.name,w);let x=w.success?w.llmContent||"":f5(P.function.name,w.error);if(!w.success){let y=v2(N,P.function.name);if(y&&typeof x==="string")x=`${x}
174
174
 
175
175
  ${y}`}if(typeof x==="object"&&x!==null)x=JSON.stringify(x,null,2);if(typeof x==="string")x=oJ(x,P.function.name,{messageBudget:O8});let y0=typeof x==="string"?x:JSON.stringify(x);if(q.appendToolResult({role:"tool",tool_call_id:P.id,name:P.function.name,content:X8(w,y0),...P.function.name==="Task"||E?{metadata:g$({toolCallId:P.id,toolName:P.function.name,error:w.success?null:w.error?.message??null,...p?{metadata:p}:{},...E?{independentVerification:E}:{}})}:{}}),O?.durableToolUseFailed===!0)return{success:!1,error:{type:"tool_persistence_failed",message:H$,details:w.error},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V}};let H0=D1(P.function.arguments)??{},C=h6(P.function.name,H0,w);if(C&&C.files.length>0){for(let s of C.references)o.add(s.id);let y={role:"system",content:C.content,metadata:g$({contextualProjectRules:!0,ruleReferences:C.references,triggerPaths:C.triggerPaths})};q.appendContextualProjectInstructions(y);let J0=await wJ($,J,C.references,C.triggerPaths,X);if(J0)X=J0;yield{kind:"project_rules_loaded",files:C.files.map((s)=>({id:s.id,relativePath:s.relativePath,source:s.source,conditional:s.conditional,contentSha256:s.contentSha256})),triggerPaths:C.triggerPaths,blockedWrite:w.metadata?.contextualProjectRulesRequired===!0}}if(P.function.name===I0&&w.metadata?.structuredOutputRetryExhausted===!0)return{success:!1,error:{type:"structured_output_failed",message:w.error?.message??"Structured output validation retry budget was exhausted."},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i,structuredOutputSchemaDigest:U?.schemaDigest}};if(W?.signal?.aborted)return z(Q,K.length,W.signal);if(w.metadata?.shouldExitLoop){let y=typeof w.llmContent==="string"?w.llmContent:"循环已退出";return{success:w.success,finalMessage:y,metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,shouldExitLoop:!0,targetMode:w.metadata?.targetMode,planContent:typeof w.metadata?.planContent==="string"?w.metadata.planContent:void 0}}}}let V$=z6(g,S1,R1.map(({result:D})=>D));if(V$){if(yield{kind:"action_stationarity",...V$},V$.phase==="halted")return{success:!1,error:{type:"loop_detected",message:`Stopped after ${V$.runLength} repeated ${V$.toolName} calls without observable progress.`},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:i}};if(V$.phase==="detected"){let D={role:"user",content:`
176
176