blade-code 0.10.136 → 0.10.138

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 (139) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-03zfvfen.js +10 -0
  3. package/dist/{chunk-82x77b2p.js → chunk-14j2dbd6.js} +2 -2
  4. package/dist/{chunk-24rsvr6e.js → chunk-16648v5c.js} +1 -1
  5. package/dist/{chunk-77x1rrz9.js → chunk-1bqatrxs.js} +1 -1
  6. package/dist/chunk-23c4pys6.js +23 -0
  7. package/dist/{chunk-hx10bph0.js → chunk-2m79vd9p.js} +1 -1
  8. package/dist/{chunk-w2n1vwzg.js → chunk-2t0wp7gm.js} +2 -2
  9. package/dist/chunk-303b3x5q.js +1 -0
  10. package/dist/{chunk-wzkh3e6a.js → chunk-3eskgvpy.js} +1 -1
  11. package/dist/chunk-3g2z6hae.js +1 -0
  12. package/dist/chunk-3t5r41yh.js +1 -0
  13. package/dist/{chunk-ntd69c0k.js → chunk-516adpx6.js} +1 -1
  14. package/dist/{chunk-9z9v8v4j.js → chunk-56py3ryh.js} +1 -1
  15. package/dist/chunk-59980a8h.js +1 -0
  16. package/dist/{chunk-6rvrx275.js → chunk-5bfvdy62.js} +2 -2
  17. package/dist/chunk-5gy3x011.js +1 -0
  18. package/dist/{chunk-q0s3gcjm.js → chunk-5j68055h.js} +1 -1
  19. package/dist/{chunk-91pb41e7.js → chunk-5v1pjexj.js} +1 -1
  20. package/dist/chunk-5xgyx25z.js +2 -0
  21. package/dist/{chunk-bdtpq7j9.js → chunk-65c3vjwm.js} +1 -1
  22. package/dist/{chunk-wj16pvvn.js → chunk-6ezffjq1.js} +1 -1
  23. package/dist/{chunk-kbnxbb23.js → chunk-6qhbdcse.js} +2 -2
  24. package/dist/{chunk-nzwh9v6t.js → chunk-7j4s1nrc.js} +1 -1
  25. package/dist/chunk-7vdf66jp.js +171 -0
  26. package/dist/chunk-8cnxy251.js +1 -0
  27. package/dist/chunk-8cqm87j5.js +1 -0
  28. package/dist/chunk-8py443a5.js +1 -0
  29. package/dist/{chunk-yacv7f7h.js → chunk-8rccn1y2.js} +1 -1
  30. package/dist/{chunk-v2qxszks.js → chunk-92n2p24j.js} +2 -2
  31. package/dist/{chunk-r51afpkk.js → chunk-9m7d3ajv.js} +1 -1
  32. package/dist/{chunk-mq1mk3v5.js → chunk-a5hkv8er.js} +2 -2
  33. package/dist/chunk-ar85hxx2.js +5 -0
  34. package/dist/{chunk-mm1atkae.js → chunk-atdq9btn.js} +2 -2
  35. package/dist/{chunk-fnc97xg7.js → chunk-awheqy52.js} +2 -2
  36. package/dist/{chunk-sv5z5sna.js → chunk-az08pq83.js} +1 -1
  37. package/dist/chunk-bq6d0v5b.js +2 -0
  38. package/dist/{chunk-c85xvthj.js → chunk-byeq45rv.js} +1 -1
  39. package/dist/{chunk-g4vgnxh4.js → chunk-d11mqbqk.js} +1 -1
  40. package/dist/{chunk-vvawhvea.js → chunk-d64b7wta.js} +1 -1
  41. package/dist/chunk-ddcz0nwv.js +1 -0
  42. package/dist/{chunk-jc28ddt0.js → chunk-dv2m2xe5.js} +1 -1
  43. package/dist/chunk-e71y87zg.js +1 -0
  44. package/dist/{chunk-1p9sjb8d.js → chunk-earhezc8.js} +1 -1
  45. package/dist/{chunk-qm96k94k.js → chunk-ec7ykyqz.js} +3 -3
  46. package/dist/{chunk-ffh4c30x.js → chunk-egadh3e9.js} +1 -1
  47. package/dist/{chunk-jb8stg10.js → chunk-fbrdcveb.js} +1 -1
  48. package/dist/{chunk-1pmvyqed.js → chunk-fndqbf45.js} +1 -1
  49. package/dist/chunk-ft1bdqbs.js +3 -0
  50. package/dist/{chunk-hqwpnb0x.js → chunk-gcg56vaw.js} +2 -2
  51. package/dist/chunk-h2gp7smy.js +1 -0
  52. package/dist/{chunk-46jmq302.js → chunk-he0f6h5q.js} +1 -1
  53. package/dist/{chunk-tev70rzj.js → chunk-hrcz179j.js} +2 -2
  54. package/dist/{chunk-qjydadex.js → chunk-j21hez8g.js} +5 -5
  55. package/dist/{chunk-c5rfnzhf.js → chunk-j58wrt5n.js} +4 -4
  56. package/dist/{chunk-s3a017q7.js → chunk-jb4hmk56.js} +2 -2
  57. package/dist/{chunk-zy2etr3v.js → chunk-jy7k2dwm.js} +2 -2
  58. package/dist/{chunk-xtngc0th.js → chunk-k10d8t4f.js} +1 -1
  59. package/dist/chunk-mc2mr1kn.js +2 -0
  60. package/dist/{chunk-0qq64xqm.js → chunk-mjnkxem3.js} +4 -4
  61. package/dist/chunk-n2tfj82m.js +1 -0
  62. package/dist/{chunk-1cbaqh71.js → chunk-nnas8tdt.js} +2 -2
  63. package/dist/{chunk-gdnyt8a7.js → chunk-npc7jt96.js} +1 -1
  64. package/dist/{chunk-mxe4pr8t.js → chunk-nqts5by0.js} +2 -2
  65. package/dist/chunk-nyw686sf.js +6 -0
  66. package/dist/chunk-pty1ncam.js +6 -0
  67. package/dist/chunk-qdjqbgts.js +1 -0
  68. package/dist/{chunk-cgkbdh2m.js → chunk-r7bv1hmq.js} +1 -1
  69. package/dist/{chunk-f7hsagj6.js → chunk-rhwkvx96.js} +1 -1
  70. package/dist/{chunk-na3nregt.js → chunk-t88sfhjj.js} +1 -1
  71. package/dist/{chunk-13sdjfks.js → chunk-v2fewxvw.js} +2 -2
  72. package/dist/chunk-wv1mnf2m.js +1 -0
  73. package/dist/{chunk-sy0vxdc3.js → chunk-y66f1t18.js} +387 -387
  74. package/dist/{chunk-5sknjz9b.js → chunk-yvmexv2c.js} +1 -1
  75. package/dist/{chunk-g45camrd.js → chunk-z9qv0d6k.js} +1 -1
  76. package/dist/{chunk-z3hpstky.js → chunk-zx78c1an.js} +1 -1
  77. package/dist/web/assets/ChatView-CZLmEMBO.js +63 -0
  78. package/dist/web/assets/{CodeBlockHighlighter-41xRPXs2.js → CodeBlockHighlighter-6-iPmomS.js} +1 -1
  79. package/dist/web/assets/{FilePreview-lcc_hL7J.js → FilePreview-D0aSwNF3.js} +7 -7
  80. package/dist/web/assets/{KanbanBoard-BHgM338V.js → KanbanBoard-xPziptbY.js} +2 -2
  81. package/dist/web/assets/{MarkdownRenderer-BMAuTkc6.js → MarkdownRenderer-TWNqhwrr.js} +3 -3
  82. package/dist/web/assets/{ScrollArea-DJq2Kdpi.js → ScrollArea-CSQyGeWr.js} +1 -1
  83. package/dist/web/assets/{SessionHistorySurface-DSe8ePBJ.js → SessionHistorySurface-PRpOrUav.js} +1 -1
  84. package/dist/web/assets/{SettingsModal-Cih4bWul.js → SettingsModal-Ds-Uf-3r.js} +5 -10
  85. package/dist/web/assets/{Sidebar-DnWlUKmO.js → Sidebar-D6VyjkRY.js} +2 -2
  86. package/dist/web/assets/{TaskSwitcher-D3mrXv_i.js → TaskSwitcher-BEsAgt0k.js} +1 -1
  87. package/dist/web/assets/{TerminalPanel-BNKHhBVM.js → TerminalPanel-C_2lnmKH.js} +1 -1
  88. package/dist/web/assets/{archive-Dof4YpyT.js → archive-CPBIxP8f.js} +1 -1
  89. package/dist/web/assets/{arrow-left-DGFXaGox.js → arrow-left-z3DhPgf-.js} +1 -1
  90. package/dist/web/assets/{calendar-clock-BoxUNOvH.js → calendar-clock-tYt1E6zR.js} +1 -1
  91. package/dist/web/assets/{chevron-right-Brb1rhaA.js → chevron-right-BGTvSaVS.js} +1 -1
  92. package/dist/web/assets/{chevrons-up-down-N-VshXV_.js → chevrons-up-down-Jw3ElnjQ.js} +1 -1
  93. package/dist/web/assets/{clock-3-gdZEKe2U.js → clock-3-v0h4RrLK.js} +1 -1
  94. package/dist/web/assets/{copy-d9M8JUfQ.js → copy-CF3TUa0u.js} +1 -1
  95. package/dist/web/assets/{download-CQ-Pwfq0.js → download-ZG8PfhmH.js} +1 -1
  96. package/dist/web/assets/{external-link-GRAtjoO2.js → external-link-BKCjDDt-.js} +1 -1
  97. package/dist/web/assets/{folder-CqLD0IBh.js → folder-M-NM2bQG.js} +1 -1
  98. package/dist/web/assets/index-DC2p1vGD.css +1 -0
  99. package/dist/web/assets/index-VQVOzFZT.js +203 -0
  100. package/dist/web/assets/{pause-BqsFgQi0.js → pause-CP_wlUro.js} +1 -1
  101. package/dist/web/assets/{pencil-Ca9289F-.js → pencil-U3n9D8ed.js} +1 -1
  102. package/dist/web/assets/{play-DmEPnYDS.js → play-NBWnc2gU.js} +1 -1
  103. package/dist/web/assets/{plus-kIBLgk0p.js → plus-CmPqJgff.js} +1 -1
  104. package/dist/web/assets/session-events-DKjIMNKI.js +29 -0
  105. package/dist/web/assets/{settings-BuSrJl6s.js → settings-CVFpbh_y.js} +1 -1
  106. package/dist/web/assets/team-B9Na0Ocd.js +6 -0
  107. package/dist/web/assets/{teamService-B7Fp8Oyg.js → teamService-ZQZLqsjy.js} +1 -1
  108. package/dist/web/assets/{terminal-Qkr_gcNu.js → terminal-BdmigqIS.js} +1 -1
  109. package/dist/web/index.html +2 -2
  110. package/package.json +1 -1
  111. package/dist/chunk-1dscf8xj.js +0 -23
  112. package/dist/chunk-1n5d6b5k.js +0 -1
  113. package/dist/chunk-1qdemrkr.js +0 -1
  114. package/dist/chunk-83nxcfz3.js +0 -1
  115. package/dist/chunk-9y7j565j.js +0 -6
  116. package/dist/chunk-acsfh1cw.js +0 -5
  117. package/dist/chunk-as8stb2j.js +0 -10
  118. package/dist/chunk-azaqc1b6.js +0 -1
  119. package/dist/chunk-e1warjkn.js +0 -171
  120. package/dist/chunk-g13jmewd.js +0 -1
  121. package/dist/chunk-g7h0peka.js +0 -3
  122. package/dist/chunk-gq7fdc8c.js +0 -2
  123. package/dist/chunk-gwjah260.js +0 -1
  124. package/dist/chunk-n238rdz8.js +0 -1
  125. package/dist/chunk-nfzad4te.js +0 -2
  126. package/dist/chunk-pnanbvn3.js +0 -1
  127. package/dist/chunk-pz91qga3.js +0 -1
  128. package/dist/chunk-s4b1r3my.js +0 -1
  129. package/dist/chunk-t6cajkaj.js +0 -6
  130. package/dist/chunk-tah2002b.js +0 -1
  131. package/dist/chunk-tzfd2fza.js +0 -1
  132. package/dist/chunk-v3veeja5.js +0 -1
  133. package/dist/chunk-vptn8fhx.js +0 -2
  134. package/dist/chunk-wj813rcc.js +0 -1
  135. package/dist/web/assets/ChatView-Bc9twpWM.js +0 -63
  136. package/dist/web/assets/index-CPpIFWLG.css +0 -1
  137. package/dist/web/assets/index-DiRs2_w4.js +0 -203
  138. package/dist/web/assets/session-events-BqQQkbAN.js +0 -29
  139. package/dist/web/assets/team-QZ9byb3E.js +0 -1
@@ -1,4 +1,4 @@
1
- import{nc as m4}from"./chunk-wzkh3e6a.js";import{Ad as r4,Bd as n4,Cd as x1,Gd as A6,Pd as I0,Rd as w2,Sd as I1,Td as q2,_d as t$,kd as t6,md as e6,nd as $4,oc as U$,od as tJ,pd as eJ,qc as B$,rc as s6,sc as v1,uc as K$,vd as J4,wd as l4,xd as i4,yd as rJ,zd as d1}from"./chunk-mxe4pr8t.js";import{de as c4}from"./chunk-z3hpstky.js";import{ge as B0,je as I6,ke as k$,ve as j1}from"./chunk-mq1mk3v5.js";import{Wf as U4}from"./chunk-q0s3gcjm.js";import{Xf as p4,Yf as m0,Zf as h4,_f as L6,bg as R1,cg as D2,dg as O6,eg as f6,gg as y6}from"./chunk-acsfh1cw.js";import{$g as A4,Tg as $$,Ug as l0,Xg as d4}from"./chunk-5sknjz9b.js";import{mh as N$}from"./chunk-qm96k94k.js";import{Hi as h1}from"./chunk-gdnyt8a7.js";import{Qi as K0}from"./chunk-jc28ddt0.js";import{wj as k0}from"./chunk-g7h0peka.js";import{Kj as a6}from"./chunk-w2n1vwzg.js";import{Uj as i6,hk as p6,ik as d6,lk as $1,ok as Z6,pk as p1,rk as r6,wk as n6,xk as o6}from"./chunk-na3nregt.js";import{zk as v6}from"./chunk-ntd69c0k.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class _1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(y$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!y$(W))}get historyLength(){return this._history.length}get 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(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!A$(J)&&!y$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((J)=>!A$(J)&&!y$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function v2($){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 C2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function I2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var Y5=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"]),V5=/^(LD_.+|DYLD_.+|PATH)$/,u2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function n$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(u2);if(!V)break;let Q=V[1];if(!Y5.has(Q))break;J=Y}return J}function W3($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(u2);if(!V)break;let Q=V[1];if(V5.test(Q))break;J=Y}return J}var Q5=[/^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 fJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Q5){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function o$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){Z+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,Z+=K;continue}if(K==='"'&&!W){Y=!Y,Z+=K;continue}if(W||Y){Z+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}if(K==="&")return null;if(K===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=K}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function g2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(Z)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 V$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;Z+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(Z)J.push(Z),Z="";continue}Z+=K}if(Z)J.push(Z);return J}var K5=new Set(["npm","pnpm","yarn","bun"]),p2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),X5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),H5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function j5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function d2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function z5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!K$.isWithinWorkspace(Q,Z))return;return W[2]?.trim()||void 0}function B5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!Z){Y=!0;continue}if(Q==="'"&&!W){Z=!Z;continue}if(Q==='"'&&!Z){W=!W;continue}if(Q!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function U5($){let J=V$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function D5($){let J=d2($.replace(H5,"").trim()),Z=B5(J);if(!Z)return;if(Z.length===0)return c2(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=d2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!U5(V))return;return c2(Y)}function c2($){let Z=o$($)?.at(-1);if(!Z)return $;let W=V$(Z),[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 P$($,J){let Z=D5($);if(!Z)return!1;let W=n$(Z),Y=o$(W);if(!Y||g2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:z5(W,Y,J);if(!V)return!1;let Q=V$(V);if(Q.length===0||Q.some((z)=>[...X5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(K5.has(K??""))return j5(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&p2.has(X??""))return!0;if(p2.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 X3($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var yJ=k0("Agent"),w5=3;function AJ($,J,Z){if($!=="length")return{action:"none"};if(J>=w5)return{action:"truncated"};if(v2(Z)==="stop")return yJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var q5=[/:\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],G5=/```[\s\S]{50,}```/,m2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",F5=2;function PJ($,J,Z=!0){if(!$||J>=F5)return{action:"none"};if(!Z&&G5.test($))return{action:"retry",prompt:m2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(q5.some((Q)=>Q.test(W)))return{action:"retry",prompt:m2};return{action:"none"}}var L5=[/\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}(?:测试|单测|集成测试|检查|构建)/],l2={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},O5={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},f5="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.",y5="Required verification did not run successfully before the retry limit.",A5=3;function r2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&P$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&P$(V,W))$.add(V)}function NJ($,J,Z){if(!$||!L5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(l2).filter((X)=>l2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>O5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>P$(X)))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${f5}${K}`}}var P5=[/\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|子代理|子智能体)/],n2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function o2($){return typeof $==="string"&&n2.some((J)=>J.test($))}var N5=[/\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|子代理)/],_5=[/\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 b5($){if(typeof $!=="string")return;if(_5.some((J)=>J.test($)))return"multiple-allowed";return N5.some((J)=>J.test($))?"required":void 0}function a$($){for(let J of $){let Z=b5(J);if(Z!==void 0)return Z==="required"}return!1}var E5="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.",S5="Required delegation did not complete before the retry limit.",T5=3;function a2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=a$(W),V=!1;if(!Y)for(let Q of W){if(n2.some((K)=>K.test(Q)))break;if(P5.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",prompt:E5}}var M5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],R5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function s2($){return x5.reduce((J,Z)=>J.replace(Z," "),$)}function E1($){if(typeof $!=="string")return!1;let J=s2($);return M5.some((Z)=>Z.test(J))}var k5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",h5="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.",v5="Required worktree lifecycle did not complete before the retry limit.",C5=3;function t2($,J,Z){if(!$)return{action:"none"};let W=s2($);if(!E1(W))return{action:"none"};let Y=R5.some((Q)=>Q.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=C5)return{action:"fail",message:v5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?k5:h5}}var i2=30000;async function _J($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??K0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),i2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return yJ.warn(`[Loop] Stop hook 超时 (${i2}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return yJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function I5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var u5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function g5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function p5($){let J=$;for(let X of u5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;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 e2($){return p5(g5($))}import{EventEmitter as d5}from"events";import $6 from"node:path";function bJ($){if(Z6($.sessionId),!$6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:$6.resolve($.projectPath)}}function J6($){let J=bJ($);return JSON.stringify([J.projectPath,J.sessionId])}function f3($,J){return J6($)===J6(J)}class _$ extends d5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!_$.instance)_$.instance=new _$;return _$.instance}publish($,J,Z,W){let Y=bJ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var s$=_$.getInstance();var s0=k0("Agent"),S1=new Set;async function c5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(S1.has(Z))return;if(S1.size>=5000)S1.clear();S1.add(Z);try{let W=$.workspaceRoot,Y=await t$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=e2(J);if(!V)return;await t$.updateSessionMetadata(Z,Y.projectPath,{title:V}),s$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var EJ=`<turn_aborted>
1
+ import{qc as m4}from"./chunk-3eskgvpy.js";import{Ad as i4,Bd as rJ,Cd as d1,Dd as r4,Ed as n4,Fd as x1,Jd as A6,Sd as I0,Ud as w2,Vd as I1,Wd as q2,be as t$,nd as t6,pd as e6,qd as $4,rc as U$,rd as tJ,sd as eJ,tc as B$,uc as s6,vc as v1,xc as K$,yd as J4,zd as l4}from"./chunk-nqts5by0.js";import{ge as c4}from"./chunk-zx78c1an.js";import{je as B0,me as I6,ne as k$,ye as j1}from"./chunk-a5hkv8er.js";import{Zf as U4}from"./chunk-5j68055h.js";import{$f as m0,_f as p4,ag as h4,bg as L6,dg as R1,eg as D2,fg as O6,gg as f6,jg as y6}from"./chunk-ar85hxx2.js";import{Yg as $$,Zg as l0,ah as d4,eh as A4}from"./chunk-yvmexv2c.js";import{rh as N$}from"./chunk-ec7ykyqz.js";import{Mi as h1}from"./chunk-npc7jt96.js";import{Vi as K0}from"./chunk-dv2m2xe5.js";import{vj as k0}from"./chunk-ft1bdqbs.js";import{Pj as a6}from"./chunk-2t0wp7gm.js";import{Bk as n6,Ck as o6,Zj as i6,mk as p6,nk as d6,qk as $1,tk as Z6,uk as p1,wk as r6}from"./chunk-t88sfhjj.js";import{Ek as v6}from"./chunk-516adpx6.js";function A$($){return $.role==="system"&&Array.isArray($.content)}function y$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class _1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(A$);if(this._contextualSystemMessages=$.messages.filter(y$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!A$(W)&&!y$(W))}get historyLength(){return this._history.length}get 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(!y$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(A$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.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((J)=>!A$(J)&&!y$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(y$),this._history=$.filter((J)=>!A$(J)&&!y$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function v2($){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 C2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function I2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var Y5=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"]),V5=/^(LD_.+|DYLD_.+|PATH)$/,u2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function n$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(u2);if(!V)break;let Q=V[1];if(!Y5.has(Q))break;J=Y}return J}function W3($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(u2);if(!V)break;let Q=V[1];if(V5.test(Q))break;J=Y}return J}var Q5=[/^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 fJ($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Q5){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function o$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){Z+=K,V=!0;continue}if(K==="'"&&!Y){W=!W,Z+=K;continue}if(K==='"'&&!W){Y=!Y,Z+=K;continue}if(W||Y){Z+=K;continue}if(K==="|"){if(Q+1<$.length&&$[Q+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}return null}if(K===">"||K==="<")return null;if(K==="&"&&Q+1<$.length&&$[Q+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",Q++;continue}if(K==="&")return null;if(K===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=K}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function g2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let Q=$[Y+1];if(Q&&/[A-Za-z_@*#?!$0-9({]/.test(Q))return!0}if(V==="`")return!0;if(Z)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 V$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let Q=0;Q<$.length;Q++){let K=$[Q];if(V){Z+=K,V=!1;continue}if(K==="\\"&&!W){if(V=!0,Y){let X=$[Q+1];if(X&&'$`"\\'.includes(X))continue;Z+=K,V=!1}continue}if(K==="'"&&!Y){W=!W;continue}if(K==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(K)){if(Z)J.push(Z),Z="";continue}Z+=K}if(Z)J.push(Z);return J}var K5=new Set(["npm","pnpm","yarn","bun"]),p2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),X5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),H5=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function j5($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function d2($){return $.replace(/\s+2>&1\s*$/,"").trim()}function z5($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let Q=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!K$.isWithinWorkspace(Q,Z))return;return W[2]?.trim()||void 0}function B5($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let Q=$[V];if(Y){Y=!1;continue}if(Q==="\\"&&!Z){Y=!0;continue}if(Q==="'"&&!W){Z=!Z;continue}if(Q==='"'&&!Z){W=!W;continue}if(Q!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function U5($){let J=V$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(Q)=>Q!==void 0&&/^[1-9]\d{0,4}$/.test(Q);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function D5($){let J=d2($.replace(H5,"").trim()),Z=B5(J);if(!Z)return;if(Z.length===0)return c2(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=d2(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!U5(V))return;return c2(Y)}function c2($){let Z=o$($)?.at(-1);if(!Z)return $;let W=V$(Z),[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 P$($,J){let Z=D5($);if(!Z)return!1;let W=n$(Z),Y=o$(W);if(!Y||g2(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:z5(W,Y,J);if(!V)return!1;let Q=V$(V);if(Q.length===0||Q.some((z)=>[...X5].some((B)=>z===B||z.startsWith(`${B}=`))))return!1;let[K,X,H]=Q;if(K5.has(K??""))return j5(X==="run"?H:X)||X==="--test";if((K==="npx"||K==="bunx")&&p2.has(X??""))return!0;if(p2.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 X3($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return K$.isWithinWorkspace(Z,J)}var yJ=k0("Agent"),w5=3;function AJ($,J,Z){if($!=="length")return{action:"none"};if(J>=w5)return{action:"truncated"};if(v2(Z)==="stop")return yJ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var q5=[/:\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],G5=/```[\s\S]{50,}```/,m2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",F5=2;function PJ($,J,Z=!0){if(!$||J>=F5)return{action:"none"};if(!Z&&G5.test($))return{action:"retry",prompt:m2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(q5.some((Q)=>Q.test(W)))return{action:"retry",prompt:m2};return{action:"none"}}var L5=[/\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}(?:测试|单测|集成测试|检查|构建)/],l2={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},O5={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},f5="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.",y5="Required verification did not run successfully before the retry limit.",A5=3;function r2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&P$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&P$(V,W))$.add(V)}function NJ($,J,Z){if(!$||!L5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(l2).filter((X)=>l2[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>O5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>P$(X)))return{action:"none"};if(Z>=A5)return{action:"fail",message:y5};let K=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${f5}${K}`}}var P5=[/\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|子代理|子智能体)/],n2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function o2($){return typeof $==="string"&&n2.some((J)=>J.test($))}var N5=[/\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|子代理)/],_5=[/\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 b5($){if(typeof $!=="string")return;if(_5.some((J)=>J.test($)))return"multiple-allowed";return N5.some((J)=>J.test($))?"required":void 0}function a$($){for(let J of $){let Z=b5(J);if(Z!==void 0)return Z==="required"}return!1}var E5="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.",S5="Required delegation did not complete before the retry limit.",T5=3;function a2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((Q)=>Q.trim()).filter(Boolean),Y=a$(W),V=!1;if(!Y)for(let Q of W){if(n2.some((K)=>K.test(Q)))break;if(P5.some((K)=>K.test(Q))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=T5)return{action:"fail",message:S5};return{action:"retry",prompt:E5}}var M5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],R5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],x5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function s2($){return x5.reduce((J,Z)=>J.replace(Z," "),$)}function E1($){if(typeof $!=="string")return!1;let J=s2($);return M5.some((Z)=>Z.test(J))}var k5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",h5="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.",v5="Required worktree lifecycle did not complete before the retry limit.",C5=3;function t2($,J,Z){if(!$)return{action:"none"};let W=s2($);if(!E1(W))return{action:"none"};let Y=R5.some((Q)=>Q.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=C5)return{action:"fail",message:v5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?k5:h5}}var i2=30000;async function _J($){try{let Z=N$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??K0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),i2)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return yJ.warn(`[Loop] Stop hook 超时 (${i2}ms),按 shouldStop: true 处理`),{action:"stop"};let Q=V;if(!Q.shouldStop)return{action:"continue",reason:Q.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return yJ.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function I5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var u5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function g5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function p5($){let J=$;for(let X of u5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;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 e2($){return p5(g5($))}import{EventEmitter as d5}from"events";import $6 from"node:path";function bJ($){if(Z6($.sessionId),!$6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:$6.resolve($.projectPath)}}function J6($){let J=bJ($);return JSON.stringify([J.projectPath,J.sessionId])}function f3($,J){return J6($)===J6(J)}class _$ extends d5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!_$.instance)_$.instance=new _$;return _$.instance}publish($,J,Z,W){let Y=bJ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var s$=_$.getInstance();var s0=k0("Agent"),S1=new Set;async function c5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(S1.has(Z))return;if(S1.size>=5000)S1.clear();S1.add(Z);try{let W=$.workspaceRoot,Y=await t$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=e2(J);if(!V)return;await t$.updateSessionMetadata(Z,Y.projectPath,{title:V}),s$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){s0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var EJ=`<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>`,X$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",W6="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 b$ extends Error{phase;constructor($,J){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.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function H$($){return $.executionEngine?.getContextManager()}async function c0($,J,Z,W=null,Y,V={}){let Q=V.required??$.executionEngine!==void 0;try{let K=H$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(K&&J.sessionId&&X){let H=await K.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(Q&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)c5(J,Z);return H}if(Q&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(K){if(s0.warn("[Loop] 保存用户消息失败:",K),Q)throw new b$("user_message",{cause:K})}return null}async function h0($,J,Z,W,Y,V,Q={}){let K=Q.required??$.executionEngine!==void 0;try{let X=H$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let z=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(K&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(K&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(s0.warn("[Loop] 保存助手消息失败:",X),K)throw new b$("assistant_message",{cause:X})}return null}async function Y6($,J,Z){try{let W=H$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",EJ,Z,void 0,J.subagentInfo)}catch(W){s0.warn("[Loop] 保存中断边界失败:",W)}return null}async function V6($,J,Z,W,Y){try{let V=H$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((Q)=>({...Q})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){s0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function SJ($,J,Z,W,Y,V={}){try{let Q=H$($);if(Q&&J.sessionId){let K=await Q.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!K)throw Error("Durable tool-use commit returned no identity");return K}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(Q){if(s0.warn("[Loop] 保存工具调用失败:",Q),V.required)throw Q}return null}async function T1($,J,Z,W,Y,V,Q,K,X,H={}){try{let z=H$($);if(z&&J.sessionId){let B=await z.saveToolResult(J.sessionId,Z,W,Y,V,Q,J.subagentInfo,K,X);if(H.required&&!B)throw Error("Durable tool-result commit returned no identity");return B}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if(s0.warn("[Loop] 保存工具结果失败:",z),H.required)throw z}return null}async function e$($,J,Z,W,Y={}){try{let V=H$($);if(V&&J.sessionId){let Q=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!Q)throw Error("Compaction checkpoint commit returned no identity");return Q||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(s0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function G0($){let{deps:J,context:Z,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 h0(J,Z,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 c0(J,Z,B.content,H,X);if(j)H=j}return H}import{createHash as G2}from"node:crypto";import{promises as V8}from"node:fs";import Q8 from"node:path";import{nanoid as t0}from"nanoid";import*as Y0 from"node:fs/promises";import*as j$ from"node:path";var Q6={enabled:!0,maxIndexLines:200};var m5="memory",K6="MEMORY.md";class TJ{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=$1($);this.memoryDir=j$.join(W,m5)}this.config={...Q6,...J}}async initialize(){if(this.initialized)return;await Y0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=j$.join(this.memoryDir,K6);try{let J=await Y0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -83,7 +83,7 @@ Full output saved to: ${K}`}catch{return`${J}
83
83
 
84
84
  ${Y}`}}import n8 from"node:path";import{nanoid as o8}from"nanoid";import{randomUUID as Q1}from"node:crypto";import*as v0 from"node:fs/promises";import*as u6 from"node:path";import{Mutex as R8}from"async-mutex";import x8 from"write-file-atomic";var k6=120,cJ=128;function V1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function b8($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1&&J.version!==2&&J.version!==3||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if((J.version===2||J.version===3)&&(!("interruptedToolCallCount"in J)||!Number.isSafeInteger(J.interruptedToolCallCount)||J.interruptedToolCallCount<0))return[];if(J.version===3&&(!("allSuccessfulToolResultsSafeForResume"in J)||typeof J.allSuccessfulToolResultsSafeForResume!=="boolean"))return[];let Z=V1(J.inputMessageIds),W=V1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function k1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=b8(Z.data);if(W.length===0)return[];let Y=-1;for(let Q=J-1;Q>=0;Q--){let K=$[Q];if(K.type==="turn_started"){if(K.data.turnId!==Z.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<J;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 C1 from"node:fs/promises";import*as C6 from"node:path";var E8={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},S8=new h1,h6;async function R$($,J,Z,W=M8){let Y=B$($,J);return S8.runExclusive(Y,()=>v1($,J,async(V)=>{let Q=C6.dirname(V.inboxPath);await C1.mkdir(Q,{recursive:!0,mode:448}),await C1.chmod(Q,448);let K,X=await W(V.inboxPath,{...E8,onCompromised:(H)=>{K=H}});try{if(K)throw K;let H=await Z(V);if(K)throw K;return H}finally{await X()}}))}async function T8(){return h6??=await import("proper-lockfile"),h6}async function M8($,J){return(await T8()).lock($,J)}var iJ=2,x$=8388608;function mJ($,J,Z){let W={version:iJ,sessionId:$,generation:J,messages:Z.map(({recovered:Y,...V})=>V)};return`${JSON.stringify(W)}
85
85
  `}function lJ($,J){return $ instanceof Error&&"code"in $&&$.code===J}function k8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function h8($,J,Z){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==iJ||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!k8(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: ${J}`);let Q="outputSchema"in V&&V.outputSchema!==void 0?I1(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: ${J}`);if(W.version===1)return{version:1,sessionId:Z,messages:Y};if(!("generation"in W)||typeof W.generation!=="string"||!/^[a-f0-9-]{36}$/.test(W.generation))throw Error(`Invalid steering inbox generation: ${J}`);return{version:iJ,sessionId:Z,generation:W.generation,messages:Y}}function v8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return k1($,Z);return[]}))}function C8($){return new Set($.flatMap((J)=>{if(J.type!=="message_created"||J.data.role!=="user")return[];let Z=J.data.metadata,W=J.data.inboxMessageId!==void 0?J.data.inboxMessageId:Z!==null&&typeof Z==="object"&&!Array.isArray(Z)?Z.inboxMessageId:void 0;return typeof W==="string"?[W]:[]}))}class u1{sessionId;stateStorage;writeFile;lockFile;mutex=new R8;generation=Q1();messages=[];constructor($,J,Z,W){this.sessionId=$;this.stateStorage=J;this.writeFile=Z;this.lockFile=W}static async open($,J,Z=U$($),W={}){let Y=new u1(J,Z,W.writeFile??x8,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,J){return this.mutex.runExclusive(async()=>{let Z=await R$(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(J&&!J(Y.messages))return{accepted:!1,snapshot:Y};let V=[...Y.messages,{...$,recovered:!1}],Q=Q1(),K=mJ(this.sessionId,Q,V);if(Buffer.byteLength(K)>x$)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(Z.snapshot),Z.accepted})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=await R$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),V=Y.messages.filter((K)=>!J.has(K.id));if(V.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let Q=Q1();return await this.persistAtPath(V,Q,W),{generation:Q,messages:V}},this.lockFile);this.install(Z)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await R$(this.stateStorage,this.sessionId,(J)=>this.readAndReconcileAtPath(J),this.lockFile);return this.install($),this.snapshot()})}async replace($,J){return this.mutex.runExclusive(async()=>{let Z=await R$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let V=Q1(),Q=J.map((X)=>({...X})),K=mJ(this.sessionId,V,Q);if(Buffer.byteLength(K)>x$)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(Z.snapshot),{replaced:Z.replaced,snapshot:this.snapshot()}})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.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 R$(this.stateStorage,this.sessionId,async(J)=>{let Z=await this.readAndReconcileAtPath(J);if(Z.migrationRequired||Z.acknowledgedRemoved){let W=Q1();return await this.persistAtPath(Z.messages,W,J),{generation:W,messages:Z.messages}}return Z},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let J;try{let Q=await v0.open($.inboxPath,"r");try{if((await Q.stat()).size>x$)throw Error(`Steering inbox exceeds ${x$} bytes: ${$.inboxPath}`);J=h8(await Q.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await Q.close()}await v0.chmod($.inboxPath,384)}catch(Q){if(!lJ(Q,"ENOENT"))throw Q}let Z=new Set,W=new Set;try{let Q=I6(await v0.readFile($.transcriptPath,"utf8"),$.transcriptPath);Z=v8(Q),W=C8(Q)}catch(Q){if(!lJ(Q,"ENOENT"))throw Q}let Y=new Map(this.messages.map((Q)=>[Q.id,Q.recovered])),V=(J?.messages??[]).filter((Q)=>!Z.has(Q.id)).map((Q)=>({...Q,recovered:Y.get(Q.id)??!0,...Q.persisted===!0||W.has(Q.id)?{persisted:!0}:{}}));return{generation:J?.version===2?J.generation:this.generation,messages:V,...J?.version===1&&V.length>0?{migrationRequired:!0}:{},...J&&V.length!==J.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,J,Z,W){if(await v0.mkdir(u6.dirname(Z.inboxPath),{recursive:!0,mode:448}),$.length===0){await v0.unlink(Z.inboxPath).catch((V)=>{if(!lJ(V,"ENOENT"))throw V});return}let Y=W??mJ(this.sessionId,J,$);if(Buffer.byteLength(Y)>x$)throw Error(`Steering inbox exceeds ${x$} bytes: ${Z.inboxPath}`);await this.writeFile(Z.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as C0 from"node:fs/promises";import*as Z4 from"node:path";import{nanoid as j0}from"nanoid";var g6=256;class F0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,J,Z){this.sessionId=$;this.projectPath=J;this.storage=Z}static for($,J,Z=U$(J)){let W=B$(Z,$),Y=F0.instances.get(W);if(!Y)Y=new F0($,J,Z),F0.instances.set(W,Y),F0.pruneIdleInstances(W);else F0.instances.delete(W),F0.instances.set(W,Y);return Y}static release($,J,Z=U$(J)){F0.instances.delete(B$(Z,$))}static pruneIdleInstances($){if(F0.instances.size<=g6)return;for(let[J,Z]of F0.instances){if(J===$||Z.subscribers.size>0)continue;if(F0.instances.delete(J),F0.instances.size<=g6)return}}get lastSeq(){return this.highestSeq}async readAll(){return this.withStore(async($,J,Z)=>{let W=J?await $.readAllValidated(J):await $.readAll();return Z(W),W})}async commit($){let[J]=await this.commitEntries([$]);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.commitEntries($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.withStore((Z,W,Y)=>Z.appendValidated((V)=>{return Y(V),$(V)},W));return this.record(J),J}async commitValidatedBatch($){let J=await this.withStore((Z,W,Y)=>Z.appendValidatedBatch((V)=>{return Y(V),$(V)},W));for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);s$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),F0.pruneIdleInstances()}}async replay($,J){let Z=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)>=J)});for(let W of Z){if(rJ(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(rJ($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}s$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}commitEntries($){return this.withStore((J,Z,W)=>Z?J.appendValidatedBatch((Y)=>{return W(Y),$},Z):J.appendBatch($))}withStore($){return v1(this.storage,this.sessionId,async(J)=>{let Z=new k$(J.transcriptPath);if(!J.remoteScope)return $(Z,void 0,()=>{return});let W=J.remoteScope;return $(Z,{noFollow:!0,validateHandle:async(Q)=>{await p6(W,J.transcriptPath,Q)}},(Q)=>{d6(Q,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function D$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class N0 extends Error{}var I8="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 nJ($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+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 c6($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)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<=cJ)W.push(Q)}return[...new Set(W)]}function W4($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let J="inputMessageIds"in $?V1($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let Z=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(Z===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:Z,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function u8($,J){let Z=$.findLastIndex((K)=>K.type==="turn_started"&&K.data.turnId===J);if(Z<0)return 0;let W=$.findIndex((K,X)=>X>Z&&K.type==="turn_started"&&K.data.turnId!==J),Y=$.slice(Z+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 Y4($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return k1($,Z);return[]}))}function oJ($,J,Z=[]){let W=W4(J.data.recovery);if(!W)return;if($.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===J.data.turnId))return;let Y=Y4($);for(let K of Z)Y.add(K);let V=W.inputMessageIds.filter((K)=>!Y.has(K)),Q=W.version===1?u8($,J.data.turnId):W.interruptedToolCallCount;if(V.length===0&&!W.hadSuccessfulToolResult&&Q===0)return;return{turnId:J.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 K1($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=oJ($,Z);if(W)return W}return}function g1($,J){let Z=$.input,W=J?.metadata,Y=J?.subagentRef;if($.toolName!=="Task"||J?.toolCallId!==$.toolCallId||J.toolName!=="Task"||Z===null||typeof Z!=="object"||Array.isArray(Z)||W===null||typeof W!=="object"||Array.isArray(W)||!Y)return!1;let{subagent_session_id:V,subagent_type:Q,description:K}=Z,X=Y.subagentStatus==="completed"&&J.error===void 0&&typeof J.output==="string"||Y.subagentStatus==="failed"&&typeof J.error==="string"&&J.error.length>0&&J.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 g8=1e4,p8=1e5,d8=2592000000,m6=128,c8=1e6,m8=256;function l8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>m6||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>c8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>m6||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function V4($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.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<=cJ):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(Q)||Q.length>k6||z.length!==Q.length||typeof K!=="number"||!Number.isSafeInteger(K)||K<0||K>g8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>p8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>d8)return;let B;if("goalFinalization"in Y){if(B=l8(Y.goalFinalization),!B)return}return{turnId:V,inputMessageIds:[...new Set(z)],turnsCount:K,toolCallsCount:X,durationMs:H,...B?{goalFinalization:B}:{}}}function l6($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=V4(Y,J);if(V)return V}return}function i8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=V4(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function h$($,J){let Z=J?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,Q=new Set;for(let X of $.slice(Z+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 _0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=K0(),J=100,Z=a6(),W=U$($)){this.projectPath=$,this.maxSessions=J,this.version=Z,this.stateStorage=W}createEvent($,J,Z){return{id:j0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:n6(this.projectPath)}:{},version:this.version,data:Z}}log($){return F0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,J){let Z=B$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=_0.sessionInitializationRuns.get(Z);if(!W)W=this.initializeSessionFile($,Z,J),_0.sessionInitializationRuns.set(Z,W);try{await W,this.rememberInitializedSession($)}finally{if(_0.sessionInitializationRuns.get(Z)===W)_0.sessionInitializationRuns.delete(Z)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>m8){let J=this.initializedSessions.values().next().value;if(J===void 0)return;this.initializedSessions.delete(J)}}async initializeSessionFile($,J,Z){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),V={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},Q=this.createEvent("session_created",$,V);await this.log($).commit(Q)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.preTokenSource)J.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)J.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.sampleAttempts!==void 0)J.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)J.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)J.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)J.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)J.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)J.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)J.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)J.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)J.failureReason=$.failureReason;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=e6;return J}async initialize(){try{await s6(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await C0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,V,Q){try{await this.ensureSessionCreated($,V);let K=new Date().toISOString(),X=j0(),H={messageId:X,role:J,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=J==="assistant"&&Q?.trim()?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"reasoning",payload:{text:Q},createdAt:K})]:[],j=typeof Z==="string"?[this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:"text",payload:{text:Z},createdAt:K})]:Z.map((U)=>this.createEvent("part_created",$,{partId:j0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:r8(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($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async acknowledgeTurnRecovery($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=B0(Z);if(W.some((V)=>V.type==="turn_recovery_acknowledged"&&V.data.turnId===J))throw new N0;let Y=W.findLast((V)=>V.type==="turn_aborted"&&V.data.turnId===J);if(!Y||!oJ(W,Y))throw new N0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:J,acknowledgedAt:new Date().toISOString()})})}catch(Z){if(!(Z instanceof N0))throw Z}}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=Y.some((j)=>j.type==="inbox_acknowledged"&&j.data.messageIds.includes(J.inboxMessageId)),Q=Y.find((j)=>j.type==="message_created"&&j.data.inboxMessageId===J.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 P=U.input,_=P.resume_from??P.resume;return P.run_in_background===!0&&P.subagent_session_id===J.childSessionId&&P.description===J.subagentRef.subagentDescription&&(P.subagent_type===void 0||P.subagent_type===J.subagentRef.subagentType)&&(P.resume_from===void 0||P.resume===void 0||P.resume_from===P.resume)&&(_===void 0?J.subagentRef.subagentResumedFrom===void 0:_===J.subagentRef.subagentResumedFrom)});if(!K)return Z={eligible:!1,acknowledged:V,persisted:!1,...Q?{messageId:Q.data.messageId}:{}},[];if(V)return Z={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===J.childSessionId&&j.data.payload.status===J.subagentRef.subagentStatus);if(Q&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:Q.data.messageId},[];let H=new Date().toISOString(),z=Q?.data.messageId??j0(),B=[];if(!Q){let j={messageId:z,role:"user",inboxMessageId:J.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(J.metadata))};B.push(this.createEvent("message_created",$,j)),B.push(this.createEvent("part_created",$,{partId:j0(),messageId:z,partType:"text",payload:{text:J.content},createdAt:H}))}if(!X){let j=Y.findLast((P)=>P.type==="part_created"&&P.data.partType==="subtask_ref"&&P.data.messageId===K.data.messageId&&P.data.payload!==null&&typeof P.data.payload==="object"&&!Array.isArray(P.data.payload)&&P.data.payload.childSessionId===J.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:j0(),messageId:K.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return Z={eligible:!0,acknowledged:!1,persisted:B.length>0,messageId:z},B}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=B0(Z);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===J.turnId))throw new N0;let Y=D$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof N0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),Q=[...new Set(Z)].filter((H)=>!V.has(H)),K=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(K){if(K.type==="turn_aborted"||Q.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:J.completedAt})]}let X=D$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...Q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:Q,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof N0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=V1(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=B0(X),z=Y4(H),B=H.findLast((i)=>(i.type==="turn_completed"||i.type==="turn_aborted")&&i.data.turnId===J.turnId);if(B){if(B.type==="turn_completed")throw Q=void 0,K=[],new N0;let i=W4(B.data.recovery),L0=i?V.filter((y0)=>i.inputMessageIds.includes(y0)):[],S=L0.filter((y0)=>!z.has(y0));if(K=L0,Q=oJ(H,B,L0),S.length===0)throw new N0;return[this.createEvent("inbox_acknowledged",$,{messageIds:S,acknowledgedAt:J.abortedAt})]}let j=D$(H).active;if(!j||j.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=h$(H,j.turnId),P=c6(H,j.turnId),_=K1(H),k=new Set(J.recovery?.inputMessageIds??[]),R=_?_.inputMessageIds.filter((i)=>k.has(i)):[],h=[...new Set([...P,...R])],d=U.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,x={version:3,inputMessageIds:h,hadSuccessfulToolResult:d,interruptedToolCallCount:U.orphaned.length+(J.recovery?.version===2||J.recovery?.version===3?J.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:d&&!U.hadSuccessfulResult&&J.recovery?.version===3&&J.recovery.hadSuccessfulToolResult&&J.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:nJ(H,j.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};Q={turnId:J.turnId,outcome:"aborted",inputMessageIds:x.inputMessageIds,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent};let o=V.filter((i)=>h.includes(i)),G=o.filter((i)=>!z.has(i));K=o;let E=new Set(z);for(let i of o)E.add(i);let l=x.inputMessageIds.filter((i)=>!E.has(i)),g=x.hadSuccessfulToolResult||x.interruptedToolCallCount>0;Q=l.length>0||g?{turnId:J.turnId,outcome:"aborted",inputMessageIds:l,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:V0,...I}=J;return[this.createEvent("turn_aborted",$,{...I,...o.length>0?{acknowledgedInputMessageIds:o}:{},recovery:x}),...G.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:G,acknowledgedAt:J.abortedAt})]:[]]})}catch(X){if(!(X instanceof N0))throw X}return{...Q?{recovery:Q}:{},acknowledgedInputMessageIds:K}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=B0(J),W=D$(Z).active;return W?h$(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let J=await this.loadEvents($);if(!J)return!1;let Z=B0(J),W=D$(Z).active;if(W){let Y=h$(Z,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(l6(Z,W.turnId))return!0}return K1(Z)!==void 0}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=B0(J).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(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=B0(W),V=D$(Y).active,Q=h$(Y);if(!V&&Q.orphaned.length===0){if(Z=K1(Y),Z)return[];throw new N0}let K=V?l6(Y,V.turnId):void 0;if(V&&K&&Q.orphaned.length===0){let E=h$(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:K.inputMessageIds,hadSuccessfulToolResult:E.hadSuccessfulResult,emptyFinalCorrectionSpent:nJ(Y,V.turnId),finalization:K};let l=new Set(Y.flatMap((I)=>I.type==="inbox_acknowledged"?I.data.messageIds:[])),g=K.inputMessageIds.filter((I)=>!l.has(I)),V0=new Date().toISOString();return[...g.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:g,acknowledgedAt:V0})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:V0,turnsCount:K.turnsCount,toolCallsCount:K.toolCallsCount,durationMs:K.durationMs})]}let X=V?h$(Y,V.turnId):void 0,H=X?.orphaned.some((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return g1(E,l)&&l?.error===void 0})??!1,z=X?.orphaned.filter((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return l?.toolCallId===E.toolCallId&&l.toolName===E.toolName&&l.error===void 0}).every((E)=>g1(E,J.adoptedToolResults?.get(E.toolCallId)))??!0,B=new Set(V?.inputMessageIds??[]),j=V?K1(Y):void 0,U=j?j.inputMessageIds.filter((E)=>B.has(E)):[],P=U.length>0,_=V?c6(Y,V.turnId):[],k=X?X.orphaned.filter((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId);return!g1(E,l)}).length:0,R=P&&j?.hadSuccessfulToolResult===!0,h=(X?.hadSuccessfulResult??!1)||H||R;Z=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([..._,...U])],hadSuccessfulToolResult:h,...(()=>{let E=k+(P?j?.interruptedToolCallCount??0:0);return E>0?{interruptedToolCallCount:E}:{}})(),...h&&!(X?.hadSuccessfulResult??!1)&&z&&(!R||j?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:nJ(Y,V.turnId)||P&&j?.emptyFinalCorrectionSpent===!0}:K1(Y);let d=V?X?.all.length??0:0,x=new Date().toISOString(),o=V?Date.parse(V.startedAt):Number.NaN,G=Q.orphaned.flatMap((E)=>{let l=J.adoptedToolResults?.get(E.toolCallId),g=g1(E,l)?l:void 0,V0=this.createEvent("part_created",$,{partId:E.toolCallId,messageId:g?E.messageId:E.toolCallId,partType:"tool_result",payload:g?{toolCallId:E.toolCallId,toolName:E.toolName,output:g.output,error:g.error??null,...g.metadata===void 0?{}:{metadata:g.metadata}}:{toolCallId:E.toolCallId,toolName:E.toolName,output:null,error:I8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:x});if(!g?.subagentRef)return[V0];let I=g.subagentRef;return[V0,this.createEvent("part_created",$,{partId:j0(),messageId:E.messageId,partType:"subtask_ref",payload:{childSessionId:I.subagentSessionId,agentType:I.subagentType,description:I.subagentDescription??"",status:I.subagentStatus,summary:I.subagentSummary??"",resumedFrom:I.subagentResumedFrom??null,rootAgentId:I.subagentRootId??I.subagentSessionId,resumeDepth:I.subagentResumeDepth??0,verificationVerdict:I.verificationVerdict??null,startedAt:x,finishedAt:x},createdAt:x})]});return V?[...G,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:x,turnsCount:0,toolCallsCount:d,durationMs:Number.isFinite(o)?Math.max(0,Date.now()-o):0,recovery:Z?{version:3,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,interruptedToolCallCount:Z.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:Z.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:G})}catch(W){if(!(W instanceof N0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?i8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_requested"&&V.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_started"&&!Z.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",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_completed"&&V.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,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??j0(),X=[];if(!W){let B={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:Q};X.push(this.createEvent("message_created",$,B))}let H=V??j0(),z={partId:H,messageId:K,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:Q};if(X.push(this.createEvent("part_created",$,z)),J==="Task"&&Z&&typeof Z==="object"){let B=Z,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 P={partId:j0(),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",$,P))}}return await this.log($).commitBatch(X),H}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,J,Z,W,Y=null,V,Q,K,X){try{await this.ensureSessionCreated($,Q);let H=new Date().toISOString(),z=Y??j0();return await this.log($).commitValidatedBatch((B)=>{let j=K?.subagentStatus==="running"?B0(B).findLast((h)=>h.type==="part_created"&&h.data.partType==="subtask_ref"&&h.data.payload!==null&&typeof h.data.payload==="object"&&!Array.isArray(h.data.payload)&&h.data.payload.childSessionId===K.subagentSessionId&&(h.data.payload.status==="completed"||h.data.payload.status==="failed"||h.data.payload.status==="cancelled")):void 0,U=j?.data.payload,P=X&&typeof X==="object"&&!Array.isArray(X)?X:{},_=U?{...P,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,k=[];if(!Y){let h={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:H};k.push(this.createEvent("message_created",$,h))}let R={partId:J,messageId:z,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:V??null,..._===void 0?{}:{metadata:_}},createdAt:H};if(k.push(this.createEvent("part_created",$,R)),K&&!j){let h=K.subagentStatus==="running"?null:H,d={partId:j0(),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:h},createdAt:H};k.push(this.createEvent("part_created",$,d))}return k}),J}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=j0(),Q={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},K=this.buildCompactionMetadata(Z),X={partId:j0(),messageId:V,partType:"summary",payload:{text:J,metadata:K,...Z.replacementMessages?{replacementMessages:$4(Z.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($,J){await this.ensureSessionCreated($);let Z=d1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=d1(B0(V)),Z.kind!=="none")return[];let Q=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${J4}${j0()}`,createdAt:Q})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=d1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=await this.log($).readAll();return J.length>0?B0(J):null}catch{return null}}async loadSession($){try{let J=B0(await this.log($).readAll());if(J.length===0)return null;let Z=J.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Z?.timestamp??J[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=B0(await this.log($).readAll());if(J.length===0)return null;let Z=new Map;for(let Q of J){if(Q.type==="message_created")Z.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=Z.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=Z.get(Q.data.messageId);if(K)K.content=K.content?`${K.content}
86
- [Image]`:"[Image]"}}let W=Array.from(Z.values()),Y=J[J.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 $=$1(this.projectPath);return(await C0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let J=p1(this.projectPath,$),Z=new k$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(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 J=p1(this.projectPath,$);await new k$(J).delete(),await C0.unlink(r6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await t6(this.projectPath,$,i6());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-s4b1r3my.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}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(),J=0;for(let Z of $){let W=p1(this.projectPath,Z),V=await new k$(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,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 $=$1(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let J=Z4.join($,".health-check");return await C0.writeFile(J,"test","utf-8"),await C0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return o6()}}function r8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var Q4=131072,aJ=new h1;function sJ($,J){return`${n8.resolve($)}\x00${J}`}function $2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>Q4)throw Error(`${J} exceeds ${Q4} bytes`);return JSON.parse(Z)}function K4($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function a8($,J){return JSON.stringify($)===JSON.stringify(J)}function s8($,J){if($.request.interactionType!=="elicitation")return $2(J,"Interaction response");return $2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function X4($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function t8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function e8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
86
+ [Image]`:"[Image]"}}let W=Array.from(Z.values()),Y=J[J.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 $=$1(this.projectPath);return(await C0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let J=p1(this.projectPath,$),Z=new k$(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=B0(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 J=p1(this.projectPath,$);await new k$(J).delete(),await C0.unlink(r6(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await t6(this.projectPath,$,i6());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-8py443a5.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}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(),J=0;for(let Z of $){let W=p1(this.projectPath,Z),V=await new k$(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,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 $=$1(this.projectPath);await C0.mkdir($,{recursive:!0,mode:493});let J=Z4.join($,".health-check");return await C0.writeFile(J,"test","utf-8"),await C0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return o6()}}function r8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var Q4=131072,aJ=new h1;function sJ($,J){return`${n8.resolve($)}\x00${J}`}function $2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>Q4)throw Error(`${J} exceeds ${Q4} bytes`);return JSON.parse(Z)}function K4($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function a8($,J){return JSON.stringify($)===JSON.stringify(J)}function s8($,J){if($.request.interactionType!=="elicitation")return $2(J,"Interaction response");return $2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function X4($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function t8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function e8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
87
87
  `)}function $Z($,J){let{request:Z}=$;if(Z.interactionType==="question"){let Q=e8(J);return{toolOutput:`User answers:
88
88
  ${Q}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
89
89
  ${Q}
@@ -109,7 +109,7 @@ When facing complex multi-step tasks:
109
109
  3. If a step fails, diagnose the root cause rather than repeating the same approach.
110
110
  4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
111
111
  5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`}`}var w$=k0("Agent"),kZ=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","ReadPromptArtifact","GetSpecContext","ValidateSpec","TaskOutput"]);class a1{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;progressSink;requireDurableToolUse;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;hasExclusiveBarrier=!1;epoch=0;activeAborts=new Map;executeTool;admitTool;rollbackAdmission;turnAdmission=new X1;toolUsePersistenceTail=Promise.resolve();constructor($,J,Z,W,Y,V,Q,K,X=!1){this.pipeline=$;this.execContext=J;this.registry=Z;this.contextMgr=W;this.sessionId=Y;this.lastMessageUuid=V;this.subagentInfo=Q;this.progressSink=K;this.requireDurableToolUse=X}setExecutionPolicy($){this.executeTool=$}setAdmissionPolicy($){this.admitTool=$}setAdmissionRollback($){this.rollbackAdmission=$}addTool($,J){if(this.dispatched.has($.id))return w$.debug(`[StreamingToolExecutor] 跳过已分发工具: ${$.function.name} (${$.id})`),"rejected";this.dispatched.add($.id),this.order.push($.id);let Z=this.turnAdmission.admit();if(Z)return this.completed.set($.id,{toolCall:$,result:Z,toolUseUuid:null}),"rejected";H1($.function.name,J),$.function.arguments=JSON.stringify(J);let W=this.admitTool?.($.function.name,J);if(W)return this.completed.set($.id,{toolCall:$,result:W,toolUseUuid:null}),"rejected";let Y=this.registry.get($.function.name),V=Y?.isConcurrencySafe===!0,Q=Y?.parallelism==="shared"||Y?.parallelism===void 0&&V;if(kZ.has($.function.name)&&V&&!this.hasExclusiveBarrier){w$.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${$.function.name}`);let X=this.executeOne($,J);return this.pending.set($.id,X),"prelaunched"}else{if(w$.debug(`[StreamingToolExecutor] 排队非预启动工具: ${$.function.name}`),this.queued.push({toolCall:$,params:J}),!Q)this.hasExclusiveBarrier=!0;return"queued"}}getQueuedToolCalls(){return this.queued.map(($)=>$.toolCall)}async*getRemainingResults(){this.dispatchQueuedTools();for(let $ of this.order){if(this.completed.has($)){yield this.completed.get($),this.completed.delete($);continue}if(this.pending.has($)){let J=await this.pending.get($);this.pending.delete($),yield J;continue}}}getCompletedResults(){let $=Array.from(this.completed.values());return this.completed.clear(),$}discard(){for(let $ of this.queued)this.rollbackAdmission?.($.toolCall.function.name);this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,$]of this.activeAborts)$.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),this.hasExclusiveBarrier=!1,this.turnAdmission.reset(),this.toolUsePersistenceTail=Promise.resolve(),w$.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult($,J,Z=null){return{toolCall:$,result:{success:!1,llmContent:"",error:{type:"execution_error",message:J},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:Z}}dispatchQueuedTools(){let $=this.queued;this.queued=[],this.hasExclusiveBarrier=!1;let J=this.epoch;for(let{toolCall:Z,params:W}of $){if(this.execContext.signal?.aborted){this.completed.set(Z.id,this.makeAbortResult(Z,"Tool execution skipped: task aborted before launch"));continue}let Y=this.executeQueued(Z,W,J);this.pending.set(Z.id,Y)}}async executeQueued($,J,Z){if(Z!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)");if(this.execContext.signal?.aborted)return this.makeAbortResult($,"Tool execution skipped: task aborted before launch");return this.executeOne($,J)}async executeOne($,J){let Z=this.epoch,W=new AbortController;this.activeAborts.set($.id,W);let Y=null,V=this.abortController.signal;try{if(V.aborted||W.signal.aborted)return this.makeAbortResult($,"Tool execution aborted due to discard");try{if(this.contextMgr&&this.sessionId)Y=await this.persistToolUseInOrder($,J);else if(this.requireDurableToolUse&&this.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(j){if(w$.warn("[StreamingToolExecutor] 保存工具调用失败:",j),!this.requireDurableToolUse)Y=null;else return{toolCall:$,result:{success:!1,llmContent:X$,error:{type:"execution_error",message:X$},metadata:{durableToolUseFailed:!0,summary:"Blocked tool before execution"}},toolUseUuid:null,error:j instanceof Error?j:Error(String(j))}}let Q=[V,W.signal],K=this.execContext.signal;if(K)Q.push(K);let X=h4(...Q),H={...this.execContext,messageId:Y??$.id,signal:X,confirmationHandler:this.execContext.sessionId&&this.execContext.workspaceRoot&&this.execContext.workspaceKind!=="acp-remote"?U0.createConfirmationHandler(this.execContext.confirmationHandler,{sessionId:this.execContext.sessionId,projectPath:this.execContext.workspaceRoot,toolCallId:Y??$.id,toolName:$.function.name}):this.execContext.confirmationHandler,onProgress:(j)=>{this.execContext.onProgress?.(j),this.progressSink?.($,{message:j.slice(0,1000)})},onProgressUpdate:(j)=>{this.execContext.onProgressUpdate?.(j),this.progressSink?.($,j)}},z=this.executeTool?await this.executeTool($.function.name,J,H):await this.pipeline.execute($.function.name,J,H);if(Z!==this.epoch)return w$.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${$.function.name} (startEpoch=${Z}, currentEpoch=${this.epoch})`),this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);let B={toolCall:$,result:z,toolUseUuid:Y};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,B);return B}catch(Q){if(Z!==this.epoch)return this.makeAbortResult($,"Tool execution aborted due to epoch mismatch (discard)",Y);w$.error(`[StreamingToolExecutor] 工具执行失败: ${$.function.name}`,Q);let K={success:!1,llmContent:"",error:{type:"execution_error",message:Q instanceof Error?Q.message:"Unknown error"},metadata:void 0},X={toolCall:$,result:K,toolUseUuid:Y,error:Q instanceof Error?Q:Error("Unknown error")};if(this.pending.has($.id))this.pending.delete($.id),this.completed.set($.id,X);return X}finally{this.activeAborts.delete($.id)}}persistToolUseInOrder($,J){let Z=this.contextMgr,W=this.sessionId;if(!Z||!W)return Promise.resolve(null);let Y=this.toolUsePersistenceTail.then(()=>Z.saveToolUse(W,$.function.name,J,this.lastMessageUuid??null,this.subagentInfo,$.id));return this.toolUsePersistenceTail=Y.then(()=>{return},()=>{return}),Y}}class z2{pending=[];waiters=[];closed=!1;push($){if(this.closed)return;let J=this.waiters.shift();if(J){J($);return}if(this.pending.length>=256)this.pending.shift();this.pending.push($)}shift(){return this.pending.shift()}next(){let $=this.shift();if($)return Promise.resolve($);if(this.closed)return Promise.resolve(void 0);return new Promise((J)=>{this.waiters.push(J)})}get hasPending(){return this.pending.length>0}close(){if(this.closed)return;this.closed=!0;for(let $ of this.waiters.splice(0))$(void 0)}}function v4($,J){if(!["TaskCreate","TaskUpdate","TaskList"].includes($.function.name)||!J.success||!J.llmContent&&!J.metadata)return null;let Z=typeof J.llmContent==="object"?J.llmContent:{};return{kind:"task_update",tasks:J.metadata?.tasks||Z.tasks||[]}}function C4($,J,Z){if($.function.name!=="Skill"||!J.success||!J.metadata)return;let W=J.metadata;if(W.skillName)Z.onSkillActivated?.({skillName:W.skillName,allowedTools:W.allowedTools,basePath:W.basePath||""})}function I4($){let J=$.metadata;if(!J)return;return J.modelId?.toString().trim()||J.model?.toString().trim()||void 0||void 0}function hZ($,J,Z){if(!["EnterWorktree","ExitWorktree"].includes($.function.name)||!J.success)return;let W=J.metadata,Y=W?.workspaceRoot;if(!["enter","exit"].includes(String(W?.workspaceTransition))||typeof Y!=="string"||Y.trim()==="")return;return N$.getInstance().inheritProjectConfig(Z.workspaceRoot,Y,Z.sessionId),Z.workspaceRoot=Y,Z.worktreeActive=W?.workspaceTransition==="enter",Y}function vZ($,J){if($.function.name!=="Task")return null;let Z=J.metadata;if(!Z?.subagentSessionId)return null;let W=Z.subagentSessionId,Y=Z.subagentType||"Task",V=Z.subagentStatus,Q=typeof Z.subagentResumedFrom==="string"?Z.subagentResumedFrom:void 0,K=typeof Z.subagentRootId==="string"?Z.subagentRootId:void 0,X=typeof Z.subagentResumeDepth==="number"?Z.subagentResumeDepth:void 0;if(V==="completed"||V==="failed"||V==="cancelled")return{kind:"subagent_completed",sessionId:W,type:Y,success:V==="completed",summary:Z.subagentSummary,...Z.verificationVerdict==="pass"||Z.verificationVerdict==="fail"||Z.verificationVerdict==="partial"?{verificationVerdict:Z.verificationVerdict}:{},...Q?{resumedFrom:Q}:{},...K?{rootAgentId:K}:{},...X!==void 0?{resumeDepth:X}:{}};if(V==="running"){let H="";try{H=JSON.parse($.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:W,type:Y,prompt:H,resumedFrom:Q,rootAgentId:K,resumeDepth:X}}return null}async function B2($,J,Z,W){let Y=v4($,J),V=vZ($,J);C4($,J,Z);let Q=I4(J);if(Q)await Z.onModelSwitch?.(Q);if(W)hZ($,J,W);return V||Y}var r=k0("Agent");function s1($,J){return{inputTokens:$.promptTokens??0,outputTokens:$.completionTokens??0,totalTokens:CJ($)??0,maxContextTokens:J,cacheReadTokens:$.cacheReadInputTokens??0,cacheWriteTokens:$.cacheCreationInputTokens??0,...$.promptCacheBreak?{cacheBreak:$.promptCacheBreak}:{},costUsd:$.costUsd}}function J$($){return JSON.stringify($).replaceAll("<","\\u003c").replaceAll(">","\\u003e")}function u4($){let J=$.trim();if(J=J.replace(/,\s*([}\]])/g,"$1"),J.startsWith("{")&&!J.endsWith("}"))J+="}";J=J.replace(/,\s*([}\]])/g,"$1");try{let Z=JSON.parse(J);if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z))return Z;return null}catch{return null}}function z1($){let J=u4($);if(J)return J;try{let Z=JSON.parse($);return typeof Z==="string"?u4(Z):null}catch{return null}}function CZ($){let J=$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0;if(J?.contextualProjectRules!==!0)return[];if(!Array.isArray(J.ruleReferences))throw Error("Invalid contextual project rule provenance");return J.ruleReferences.map((Z)=>{if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid contextual project rule reference");let W=Z;if(typeof W.id!=="string"||typeof W.relativePath!=="string"||!["project","local"].includes(String(W.source))||typeof W.contentSha256!=="string"||!/^[a-f0-9]{64}$/u.test(W.contentSha256))throw Error("Invalid contextual project rule reference");return{id:W.id,relativePath:W.relativePath,source:W.source,contentSha256:W.contentSha256}})}function C$($){if(typeof $==="string")return $;try{return JSON.parse(JSON.stringify($))}catch{return String($)}}function IZ($){let J=new Set,Z=!1;for(let W of $){if(W.role==="assistant"){if(W.tool_calls&&W.tool_calls.length>0){for(let V of W.tool_calls)if("function"in V&&V.function.name==="Task")J.add(V.id)}else if(Z)Z=!1;continue}if(W.role!=="tool"||W.name!=="Task"||!W.tool_call_id||!J.has(W.tool_call_id)||typeof W.metadata!=="object"||W.metadata===null||Array.isArray(W.metadata))continue;let Y=W.metadata;if(Y.toolCallId===W.tool_call_id&&Y.toolName==="Task"&&Y.error===null)Z=!0}return Z}function uZ($){if(!($ instanceof Error))return"未知错误";let W=$.lastError??$;if(W.responseBody)try{let K=JSON.parse(W.responseBody)?.error?.message;if(K){let X=W.statusCode?` (HTTP ${W.statusCode})`:"";return`${K}${X}`}}catch{}let Y=$.message,V=Y.match(/Last error:\s*(.+)$/);if(V)return V[1];return Y}function gZ($){if(!($ instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some((Z)=>$.message.toLowerCase().includes(Z.toLowerCase()))}function pZ($,J){if(!J)return"Tool execution failed (no details).";let Z=[`Error: ${J.message||"Unknown error"}`];if(J.type==="validation_error")Z.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(J.type==="permission_denied")Z.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(J.type==="timeout_error")Z.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(J.type==="execution_error"){let W=J.message??"";if(W.includes("ENOENT")||W.includes("no such file"))Z.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(W.includes("EACCES")||W.includes("permission"))Z.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(W.includes("not found in file")||W.includes("old_string"))Z.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${$} with the exact text.`);else if(W.includes("ENOTDIR"))Z.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return Z.join(`
112
- `)}function U2($){if(!($ instanceof Error))return!1;return R1($)||$.status===413}function dZ($,J){let Z=J,W=Z.index??0;if(!$.has(W))$.set(W,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let Y=$.get(W);if(Z.id&&!Y.id)Y.id=Z.id;if(Z.function?.name&&!Y.name)Y.name=Z.function.name;if(Z.function?.arguments)Y.arguments+=Z.function.arguments}function cZ($){if($.size===0)return;return Array.from($.values()).filter((J)=>J.id&&J.name).map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:J.arguments}}))}async function*mZ($,J,Z,W,Y,V){let Q="",K="",X,H,z=new Map;try{let B=$.chatService.streamChat(J,Z,W,Y),j=0;for await(let U of B){if(W?.aborted)break;if(U.providerAdmission){yield{kind:"provider_admission",...U.providerAdmission};continue}if(U.providerCircuit){yield{kind:"provider_circuit",...U.providerCircuit};continue}if(U.providerRetry){yield{kind:"provider_retry",...U.providerRetry};continue}if(U.providerStall){yield{kind:"provider_stall",...U.providerStall};continue}if(j++,U.modelFallback){V?.discard(),Q="",K="",X=void 0,H=void 0,z.clear(),j=0,yield{kind:"model_fallback"};continue}if(U.content)Q+=U.content,yield{kind:"content_delta",delta:U.content};if(U.reasoningContent)K+=U.reasoningContent,yield{kind:"thinking_delta",delta:U.reasoningContent};if(U.usage)X=U.usage;if(U.toolCalls){for(let P of U.toolCalls)if(dZ(z,P),V){let k=P.index??0,R=z.get(k);if(R&&R.id&&R.name)try{let h=z1(R.arguments);if(h===null)continue;let d={id:R.id,type:"function",function:{name:R.name,arguments:R.arguments}},o=$.toolExecutor.getRegistry().get(R.name)?.kind,G=V.addTool(d,h);if(R.arguments=d.function.arguments,G==="prelaunched")yield{kind:"tool_start",toolCall:d,toolKind:o}}catch{}}}if(U.finishReason){H=U.finishReason;break}}if(j===0&&!W?.aborted&&Q.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};return{content:Q,reasoningContent:K||void 0,toolCalls:cZ(z),usage:X,finishReason:H}}catch(B){if(gZ(B))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};throw B}}function lZ($){return G2("sha256").update($).digest("hex").slice(0,16)}var iZ=new Set(["AbortError","Error","RangeError","TypeError"]),rZ=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function nZ($){if($ instanceof Error){let J=$,Z=iZ.has($.name)?$.name:"Error",W=typeof J.code==="string"&&rZ.has(J.code)?J.code:"unknown";return`${Z}:${W}`}return"UnknownError:unknown"}async function oZ($){let{deps:J,context:Z,state:W,snapshot:Y,attemptSpent:V}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((X)=>typeof X.id==="string"&&n4(X)))return{kind:"already_present"};if(V)return{kind:"failed"};let K=J.executionEngine?.getContextManager();if(!K)return{kind:"failed"};try{let X=await K.recordTokenBudgetHandoff(Z.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(X.outcome==="suppressed")return{kind:"suppressed"};let H=r4(X.event);if(!H)return{kind:"failed"};return W.appendDurableControl(H),{kind:"appended",message:H}}catch(X){let H=`token_budget_handoff_persist_failed session=${lZ(Z.sessionId)} error=${nZ(X)}`;return r.warn(H),{kind:"failed"}}}async function*o4($,J,Z,W,Y,V,Q,K){let X=W.contextTokens,H=S6(J.messages,V),z=H!==null;if(H)J.messages=H.messages,r.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${H.snippedCount} 轮旧工具结果(缓存已过期)`);let B=W1(J.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),z||j?{kind:"snipped"}:{kind:"none"}}let U=$.chatService.getConfig(),P=U.model,_=W.maxContextTokens??0,k=W.maxOutputTokens??0,R=W.availableForInput??0;if(_<=0||R<=0){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(模型上下文窗口未知)`),z||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{contextTokens:X,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:_,maxOutputTokens:k,availableForInput:R,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)J.messages=B.messages;return z||j?{kind:"snipped"}:{kind:"none"}}r.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);let h="failed",d,x,o,G,E,l,g,V0,I,D0,i,L0,S="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let y0=j?B.messages:J.messages,T=await S$.compact(y0,{trigger:"auto",modelName:P,modelProvider:U.provider,maxContextTokens:_,apiKey:U.apiKey,baseURL:U.baseUrl,actualPreTokens:X,signal:Y,activeTask:Q,workspaceRoot:J.workspaceRoot||K0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(T.usage)yield{kind:"token_usage",usage:s1(T.usage,_)};if(d=T.success?"llm":"fallback",x=T.preTokens,o=T.postTokens,G=T.sampleAttempts,E=T.inputReductions,l=T.messagesOmitted,g=T.filesOmitted,V0=T.imagesOmitted,I=T.fallbackTargetTokens,D0=T.fallbackMessagesOmitted,i=T.fallbackMessagesTruncated,L0=T.failureReason,T.success)r.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${T.preTokens} -> ${T.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${T.preTokens} -> ${T.postTokens} tokens`);if(S="checkpoint",await e$($,J,T.summary,{trigger:"auto",reason:"threshold",strategy:d,preTokens:T.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:T.postTokens,sampleAttempts:T.sampleAttempts,inputReductions:T.inputReductions,messagesOmitted:T.messagesOmitted,filesOmitted:T.filesOmitted,imagesOmitted:T.imagesOmitted,fallbackTargetTokens:T.fallbackTargetTokens,fallbackMessagesOmitted:T.fallbackMessagesOmitted,fallbackMessagesTruncated:T.fallbackMessagesTruncated,failureReason:T.failureReason,filesIncluded:T.filesIncluded,replacementMessages:T.compactedMessages},{required:$.executionEngine!==void 0}),J.messages=T.compactedMessages,K)K.lastCompactionTurn=Z;return h=T.success?"completed":"fallback",{kind:"compacted",postTokens:T.postTokens}}catch(y0){if(m0(y0))return r.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),{kind:"none"};return r.error(`[Loop] [轮次 ${Z}] 压缩失败,停止执行`,y0),{kind:"failed",phase:S}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:h,strategy:d,preTokens:x,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:o,sampleAttempts:G,inputReductions:E,messagesOmitted:l,filesOmitted:g,imagesOmitted:V0,fallbackTargetTokens:I,fallbackMessagesOmitted:D0,fallbackMessagesTruncated:i,failureReason:L0}}}function aZ($,J,Z,W){let Y=W?p4(W):"user-cancel";return{success:!1,error:{type:"aborted",message:(Y==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z,abortReason:Y}}}function g4($,J,Z){return{success:!1,error:{type:"tool_persistence_failed",message:W6},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}function sZ($,J,Z,W){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}async function*tZ($,J,Z,W,Y){let V=Date.now(),Q=0,K=[],X=null,H=!1,z=(B,j,U)=>{return H=!0,aZ(B,j,V,U)};try{let B=$.toolExecutor.getRegistry(),j=Z.permissionMode,U=W?.outputSchema?I1(W.outputSchema):void 0,P=()=>{let L=$.applySkillToolRestrictions(B.getFunctionDeclarationsByMode(j));if(!U)return L;return[...L.filter((F)=>F.name!==I0),U.declaration]},_=D4(),k=O4(),R=z4(),h=k4(Y,B);if(U)h=`${h??""}
112
+ `)}function U2($){if(!($ instanceof Error))return!1;return R1($)||$.status===413}function dZ($,J){let Z=J,W=Z.index??0;if(!$.has(W))$.set(W,{id:Z.id||"",name:Z.function?.name||"",arguments:""});let Y=$.get(W);if(Z.id&&!Y.id)Y.id=Z.id;if(Z.function?.name&&!Y.name)Y.name=Z.function.name;if(Z.function?.arguments)Y.arguments+=Z.function.arguments}function cZ($){if($.size===0)return;return Array.from($.values()).filter((J)=>J.id&&J.name).map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:J.arguments}}))}async function*mZ($,J,Z,W,Y,V){let Q="",K="",X,H,z=new Map;try{let B=$.chatService.streamChat(J,Z,W,Y),j=0;for await(let U of B){if(W?.aborted)break;if(U.providerAdmission){yield{kind:"provider_admission",...U.providerAdmission};continue}if(U.providerCircuit){yield{kind:"provider_circuit",...U.providerCircuit};continue}if(U.providerRetry){yield{kind:"provider_retry",...U.providerRetry};continue}if(U.providerStall){yield{kind:"provider_stall",...U.providerStall};continue}if(j++,U.modelFallback){V?.discard(),Q="",K="",X=void 0,H=void 0,z.clear(),j=0,yield{kind:"model_fallback",...U.modelFallback};continue}if(U.content)Q+=U.content,yield{kind:"content_delta",delta:U.content};if(U.reasoningContent)K+=U.reasoningContent,yield{kind:"thinking_delta",delta:U.reasoningContent};if(U.usage)X=U.usage;if(U.toolCalls){for(let P of U.toolCalls)if(dZ(z,P),V){let k=P.index??0,R=z.get(k);if(R&&R.id&&R.name)try{let h=z1(R.arguments);if(h===null)continue;let d={id:R.id,type:"function",function:{name:R.name,arguments:R.arguments}},o=$.toolExecutor.getRegistry().get(R.name)?.kind,G=V.addTool(d,h);if(R.arguments=d.function.arguments,G==="prelaunched")yield{kind:"tool_start",toolCall:d,toolKind:o}}catch{}}}if(U.finishReason){H=U.finishReason;break}}if(j===0&&!W?.aborted&&Q.length===0&&z.size===0)return r.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};return{content:Q,reasoningContent:K||void 0,toolCalls:cZ(z),usage:X,finishReason:H}}catch(B){if(gZ(B))return r.warn("[Loop] 流式请求失败,降级到非流式模式"),V?.discard(),{...await $.chatService.chat(J,Z,W,Y),_nonStreamingFallback:!0};throw B}}function lZ($){return G2("sha256").update($).digest("hex").slice(0,16)}var iZ=new Set(["AbortError","Error","RangeError","TypeError"]),rZ=new Set(["EACCES","EEXIST","EIO","EMFILE","ENFILE","ENOENT","ENOSPC","EPERM","EROFS"]);function nZ($){if($ instanceof Error){let J=$,Z=iZ.has($.name)?$.name:"Error",W=typeof J.code==="string"&&rZ.has(J.code)?J.code:"unknown";return`${Z}:${W}`}return"UnknownError:unknown"}async function oZ($){let{deps:J,context:Z,state:W,snapshot:Y,attemptSpent:V}=$;if(Y.phase!=="handoff_band")return{kind:"failed"};if(W.getHistory().find((X)=>typeof X.id==="string"&&n4(X)))return{kind:"already_present"};if(V)return{kind:"failed"};let K=J.executionEngine?.getContextManager();if(!K)return{kind:"failed"};try{let X=await K.recordTokenBudgetHandoff(Z.sessionId,{version:1,observedPromptTokens:Y.contextTokens??0,availableForInput:Y.availableForInput??0,handoffThreshold:Y.handoffThreshold??0,compactionThreshold:Y.compactionThreshold??0});if(X.outcome==="suppressed")return{kind:"suppressed"};let H=r4(X.event);if(!H)return{kind:"failed"};return W.appendDurableControl(H),{kind:"appended",message:H}}catch(X){let H=`token_budget_handoff_persist_failed session=${lZ(Z.sessionId)} error=${nZ(X)}`;return r.warn(H),{kind:"failed"}}}async function*o4($,J,Z,W,Y,V,Q,K){let X=W.contextTokens,H=S6(J.messages,V),z=H!==null;if(H)J.messages=H.messages,r.debug(`[Loop] [轮次 ${Z}] MicroCompact: 清理 ${H.snippedCount} 轮旧工具结果(缓存已过期)`);let B=W1(J.messages),j=!1;if(B.snippedCount>0)j=!0,r.debug(`[Loop] [轮次 ${Z}] Snip 压缩: 移除 ${B.snippedCount} 轮旧工具调用,释放约 ${B.estimatedTokensFreed} tokens`);if(W.phase==="unknown"){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),z||j?{kind:"snipped"}:{kind:"none"}}let U=$.chatService.getConfig(),P=U.model,_=W.maxContextTokens??0,k=W.maxOutputTokens??0,R=W.availableForInput??0;if(_<=0||R<=0){if(j)J.messages=B.messages;return r.debug(`[Loop] [轮次 ${Z}] 压缩检查: 跳过(模型上下文窗口未知)`),z||j?{kind:"snipped"}:{kind:"none"}}if(r.debug(`[Loop] [轮次 ${Z}] 压缩检查:`,{contextTokens:X,tokenSource:W.tokenSource,estimatedPendingTokens:W.estimatedPendingTokens,maxContextTokens:_,maxOutputTokens:k,availableForInput:R,threshold:W.compactionThreshold,shouldCompact:W.phase==="compaction_due"}),W.phase!=="compaction_due"){if(j)J.messages=B.messages;return z||j?{kind:"snipped"}:{kind:"none"}}r.debug(Z===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${Z}] 触发循环内自动压缩`);let h="failed",d,x,o,G,E,l,g,V0,I,D0,i,L0,S="compaction";yield{kind:"compaction",phase:"start",reason:"threshold"};try{let y0=j?B.messages:J.messages,T=await S$.compact(y0,{trigger:"auto",modelName:P,modelProvider:U.provider,maxContextTokens:_,apiKey:U.apiKey,baseURL:U.baseUrl,actualPreTokens:X,signal:Y,activeTask:Q,workspaceRoot:J.workspaceRoot||K0(),workspaceAccess:J.workspaceKind==="acp-remote"?"none":"full",sessionId:J.sessionId});if(T.usage)yield{kind:"token_usage",usage:s1(T.usage,_)};if(d=T.success?"llm":"fallback",x=T.preTokens,o=T.postTokens,G=T.sampleAttempts,E=T.inputReductions,l=T.messagesOmitted,g=T.filesOmitted,V0=T.imagesOmitted,I=T.fallbackTargetTokens,D0=T.fallbackMessagesOmitted,i=T.fallbackMessagesTruncated,L0=T.failureReason,T.success)r.debug(`[Loop] [轮次 ${Z}] 压缩完成: ${T.preTokens} -> ${T.postTokens} tokens`);else r.warn(`[Loop] [轮次 ${Z}] 压缩使用降级策略: ${T.preTokens} -> ${T.postTokens} tokens`);if(S="checkpoint",await e$($,J,T.summary,{trigger:"auto",reason:"threshold",strategy:d,preTokens:T.preTokens,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:T.postTokens,sampleAttempts:T.sampleAttempts,inputReductions:T.inputReductions,messagesOmitted:T.messagesOmitted,filesOmitted:T.filesOmitted,imagesOmitted:T.imagesOmitted,fallbackTargetTokens:T.fallbackTargetTokens,fallbackMessagesOmitted:T.fallbackMessagesOmitted,fallbackMessagesTruncated:T.fallbackMessagesTruncated,failureReason:T.failureReason,filesIncluded:T.filesIncluded,replacementMessages:T.compactedMessages},{required:$.executionEngine!==void 0}),J.messages=T.compactedMessages,K)K.lastCompactionTurn=Z;return h=T.success?"completed":"fallback",{kind:"compacted",postTokens:T.postTokens}}catch(y0){if(m0(y0))return r.debug(`[Loop] [轮次 ${Z}] 压缩被中止`),{kind:"none"};return r.error(`[Loop] [轮次 ${Z}] 压缩失败,停止执行`,y0),{kind:"failed",phase:S}}finally{yield{kind:"compaction",phase:"end",reason:"threshold",outcome:h,strategy:d,preTokens:x,...W.tokenSource?{preTokenSource:W.tokenSource}:{},...W.estimatedPendingTokens!==void 0?{estimatedPendingTokens:W.estimatedPendingTokens}:{},postTokens:o,sampleAttempts:G,inputReductions:E,messagesOmitted:l,filesOmitted:g,imagesOmitted:V0,fallbackTargetTokens:I,fallbackMessagesOmitted:D0,fallbackMessagesTruncated:i,failureReason:L0}}}function aZ($,J,Z,W){let Y=W?p4(W):"user-cancel";return{success:!1,error:{type:"aborted",message:(Y==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z,abortReason:Y}}}function g4($,J,Z){return{success:!1,error:{type:"tool_persistence_failed",message:W6},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}function sZ($,J,Z,W){return{success:!1,error:{type:"context_compaction_failed",message:"Context compaction could not cross the hard budget boundary.",details:{phase:W}},metadata:{turnsCount:$,toolCallsCount:J,duration:Date.now()-Z}}}async function*tZ($,J,Z,W,Y){let V=Date.now(),Q=0,K=[],X=null,H=!1,z=(B,j,U)=>{return H=!0,aZ(B,j,V,U)};try{let B=$.toolExecutor.getRegistry(),j=Z.permissionMode,U=W?.outputSchema?I1(W.outputSchema):void 0,P=()=>{let L=$.applySkillToolRestrictions(B.getFunctionDeclarationsByMode(j));if(!U)return L;return[...L.filter((F)=>F.name!==I0),U.declaration]},_=D4(),k=O4(),R=z4(),h=k4(Y,B);if(U)h=`${h??""}
113
113
 
114
114
  # Structured Final Output
115
115
  This turn has a required JSON Schema final-output contract. Complete the user's
@@ -168,4 +168,4 @@ ${A}`}if(typeof v==="object"&&v!==null)v=JSON.stringify(v,null,2);if(typeof v===
168
168
  ${B4(Y$)}
169
169
  </system-reminder>`,metadata:j1};G.appendControl("user",w);let D=await c0($,Z,w.content,X,j1);if(D)X=D}}if(W?.signal?.aborted)return z(Q,K.length,W.signal);if(Q>=L0&&(i||g)){if(r.info(`Warning: 达到轮次上限 ${L0} 轮`),W?.onTurnLimitReached){let w=await W.onTurnLimitReached({turnsCount:Q});if(w?.continue){G.writeback();let D="failed",N,y,m,b,f,p,v,A0,H0,C,A,e,s,q0;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let O=$.chatService.getConfig(),P0=P(),f0=L$&&a$(F$)?P0.filter((OJ)=>OJ.name!=="Task"):P0,z0=u0?f0.filter((OJ)=>OJ.name===u0):f0,M=IJ(G.systemMessages,z0,O.model),M0=O$.project({history:G.getHistory(),contextRevision:G.contextRevision,modelName:O.model,requestProfile:M});m=M0.source,b=M0.estimatedPendingTokens;let u=await S$.compact(Z.messages,{trigger:"auto",modelName:O.model,modelProvider:O.provider,maxContextTokens:O.maxContextTokens??0,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:M0.contextTokens,signal:W?.signal,activeTask:S0,workspaceRoot:Z.workspaceRoot||K0(),workspaceAccess:Z.workspaceKind==="acp-remote"?"none":"full",sessionId:Z.sessionId});if(u.usage)yield{kind:"token_usage",usage:s1(u.usage,O.maxContextTokens??0)};let W5={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
170
170
 
171
- 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.`},h2=[...u.compactedMessages,W5];N=u.success?"llm":"fallback",y=u.preTokens,f=u.postTokens,p=u.sampleAttempts,v=u.inputReductions,A0=u.messagesOmitted,H0=u.filesOmitted,C=u.imagesOmitted,A=u.fallbackTargetTokens,e=u.fallbackMessagesOmitted,s=u.fallbackMessagesTruncated,q0=u.failureReason,await e$($,Z,u.summary,{trigger:"auto",reason:"turn_limit",strategy:N,preTokens:u.preTokens,preTokenSource:M0.source,...M0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:M0.estimatedPendingTokens}:{},postTokens:u.postTokens,sampleAttempts:u.sampleAttempts,inputReductions:u.inputReductions,messagesOmitted:u.messagesOmitted,filesOmitted:u.filesOmitted,imagesOmitted:u.imagesOmitted,fallbackTargetTokens:u.fallbackTargetTokens,fallbackMessagesOmitted:u.fallbackMessagesOmitted,fallbackMessagesTruncated:u.fallbackMessagesTruncated,failureReason:u.failureReason,filesIncluded:u.filesIncluded,replacementMessages:h2},{required:$.executionEngine!==void 0}),Z.messages=h2,G.replaceHistory(Z.messages),O$.reset(),D=u.success?"completed":"fallback"}catch(O){throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:N,preTokens:y,preTokenSource:m,estimatedPendingTokens:b,postTokens:f,sampleAttempts:p,inputReductions:v,messagesOmitted:A0,filesOmitted:H0,imagesOmitted:C,fallbackTargetTokens:A,fallbackMessagesOmitted:e,fallbackMessagesTruncated:s,failureReason:q0}}Q=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:S}}}return{success:!1,error:{type:"max_turns_exceeded",message:g?`子代理已达到轮次上限 (${L0} 轮)。`:`已达到轮次上限 (${L0} 轮)。`},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:S}}}}}catch(L){if(L instanceof b$)try{let F=Z.sessionId?await t$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):o;G.restoreDurableHistory(F)}catch(F){r.error("[Loop] Failed to reload durable context after message commit failure:",F),G.restoreDurableHistory(o)}throw L}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});G.writeback()}}catch(B){if(m0(B))return z(Q,K.length,W?.signal);if(B instanceof b$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V}};let j=uZ(B);return r.error(`API 调用失败: ${j}`),{success:!1,error:{type:"api_error",message:j,details:B},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:EJ}),await Y6($,Z,X)}}export{TJ as sb,n$ as tb,W3 as ub,fJ as vb,o$ as wb,d2 as xb,D5 as yb,P$ as zb,X3 as Ab,D$ as Bb,bJ as Cb,J6 as Db,f3 as Eb,s$ as Fb,F0 as Gb,_0 as Hb,AJ as Ib,PJ as Jb,r2 as Kb,_J as Lb,E4 as Mb,S4 as Nb,M4 as Ob,A$ as Pb,_1 as Qb,I5 as Rb,c0 as Sb,h0 as Tb,SJ as Ub,T1 as Vb,e$ as Wb,n as Xb,S$ as Yb,u1 as Zb,U0 as _b,T9 as $b,k4 as ac,a1 as bc,v4 as cc,C4 as dc,I4 as ec,vZ as fc,B2 as gc,o4 as hc,tZ as ic};
171
+ 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.`},h2=[...u.compactedMessages,W5];N=u.success?"llm":"fallback",y=u.preTokens,f=u.postTokens,p=u.sampleAttempts,v=u.inputReductions,A0=u.messagesOmitted,H0=u.filesOmitted,C=u.imagesOmitted,A=u.fallbackTargetTokens,e=u.fallbackMessagesOmitted,s=u.fallbackMessagesTruncated,q0=u.failureReason,await e$($,Z,u.summary,{trigger:"auto",reason:"turn_limit",strategy:N,preTokens:u.preTokens,preTokenSource:M0.source,...M0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:M0.estimatedPendingTokens}:{},postTokens:u.postTokens,sampleAttempts:u.sampleAttempts,inputReductions:u.inputReductions,messagesOmitted:u.messagesOmitted,filesOmitted:u.filesOmitted,imagesOmitted:u.imagesOmitted,fallbackTargetTokens:u.fallbackTargetTokens,fallbackMessagesOmitted:u.fallbackMessagesOmitted,fallbackMessagesTruncated:u.fallbackMessagesTruncated,failureReason:u.failureReason,filesIncluded:u.filesIncluded,replacementMessages:h2},{required:$.executionEngine!==void 0}),Z.messages=h2,G.replaceHistory(Z.messages),O$.reset(),D=u.success?"completed":"fallback"}catch(O){throw r.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:N,preTokens:y,preTokenSource:m,estimatedPendingTokens:b,postTokens:f,sampleAttempts:p,inputReductions:v,messagesOmitted:A0,filesOmitted:H0,imagesOmitted:C,fallbackTargetTokens:A,fallbackMessagesOmitted:e,fallbackMessagesTruncated:s,failureReason:q0}}Q=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:S}}}return{success:!1,error:{type:"max_turns_exceeded",message:g?`子代理已达到轮次上限 (${L0} 轮)。`:`已达到轮次上限 (${L0} 轮)。`},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V,tokensUsed:S}}}}}catch(L){if(L instanceof b$)try{let F=Z.sessionId?await t$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):o;G.restoreDurableHistory(F)}catch(F){r.error("[Loop] Failed to reload durable context after message commit failure:",F),G.restoreDurableHistory(o)}throw L}finally{if(W?.transientInput==="goal_continuation")G.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});G.writeback()}}catch(B){if(m0(B))return z(Q,K.length,W?.signal);if(B instanceof b$)return{success:!1,error:{type:"message_persistence_failed",message:B.message},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V}};let j=uZ(B);return r.error(`API 调用失败: ${j}`),{success:!1,error:{type:"api_error",message:j,details:B},metadata:{turnsCount:Q,toolCallsCount:K.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:EJ}),await Y6($,Z,X)}}export{TJ as vb,n$ as wb,W3 as xb,fJ as yb,o$ as zb,d2 as Ab,D5 as Bb,P$ as Cb,X3 as Db,D$ as Eb,bJ as Fb,J6 as Gb,f3 as Hb,s$ as Ib,F0 as Jb,_0 as Kb,AJ as Lb,PJ as Mb,r2 as Nb,_J as Ob,E4 as Pb,S4 as Qb,M4 as Rb,A$ as Sb,_1 as Tb,I5 as Ub,c0 as Vb,h0 as Wb,SJ as Xb,T1 as Yb,e$ as Zb,n as _b,S$ as $b,u1 as ac,U0 as bc,T9 as cc,k4 as dc,a1 as ec,v4 as fc,C4 as gc,I4 as hc,vZ as ic,B2 as jc,o4 as kc,tZ as lc};
@@ -1,3 +1,3 @@
1
- import{Ej as N,Hj as M}from"./chunk-bdtpq7j9.js";import{Uj as H}from"./chunk-na3nregt.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
1
+ import{Jj as N,Mj as M}from"./chunk-65c3vjwm.js";import{Zj as H}from"./chunk-t88sfhjj.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
2
2
  `,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
3
- export{K as yj,X as zj,J as Aj,L as Bj,hu as Cj};
3
+ export{K as Dj,X as Ej,J as Fj,L as Gj,hu as Hj};
@@ -1,3 +1,3 @@
1
- import{Sj as C,Tj as I}from"./chunk-1p9sjb8d.js";import{Uj as _}from"./chunk-na3nregt.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
1
+ import{Xj as C,Yj as I}from"./chunk-earhezc8.js";import{Zj as _}from"./chunk-t88sfhjj.js";import{createHash as S}from"node:crypto";import{constants as A,promises as B}from"node:fs";import N from"node:os";import F from"node:path";import{Mutex as w}from"async-mutex";import{LRUCache as k}from"lru-cache";import E from"write-file-atomic";var X=1,j=65536,T=1048576,z=100,R=64;function t(q){return q.state==="trusted"||q.state==="not_required"}function K(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)}function V(q,Q=2048){return q.length<=Q?q:`${q.slice(0,Q-1)}…`}function M(q){if(typeof q!=="string"||!q.trim())return;try{let Q=new URL(q);return V(`${Q.origin}${Q.pathname}`)}catch{return V(q)}}function D(q){return Array.isArray(q)?q.filter((Q)=>typeof Q==="string"):[]}function m(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.type==="string"?$.type:"unknown",G=typeof $.command==="string"?$.command:void 0,J=D($.args),L=H==="stdio"?V([G,...J].filter(Boolean).join(" ")):M($.url);return{kind:"mcp",name:`${Q} (${H})`,...L?{target:L}:{}}})}function g(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.command==="string"?V($.command):void 0,G=K($.extensionToLanguage)?Object.keys($.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${Q} (${G})`,...H?{target:H}:{}}})}function P(q){if(!Array.isArray(q))return[];return q.slice(0,z).flatMap((Q)=>{if(!K(Q))return[];let Z=typeof Q.id==="string"?Q.id:"unnamed",$=typeof Q.provider==="string"?Q.provider:"unknown",H=typeof Q.model==="string"?Q.model:"unknown",G=K(Q.overrides)?Q.overrides:{},J=M(G.baseUrl);return[{kind:"model",name:`${Z}: ${$}/${H}`,...J?{target:J}:{}}]})}function y(q){if(!K(q))return[];return Object.entries(q).slice(0,z).map(([Q,Z])=>{let $=K(Z)?Z:{},H=typeof $.wireApi==="string"?$.wireApi:"unknown",G=M($.baseUrl);return{kind:"model",name:`${Q} (${H})`,...G?{target:G}:{}}})}function f(q){if(!K(q))return[];let Q=[];for(let Z of["allow","ask","deny"])for(let $ of D(q[Z]).slice(0,z))Q.push({kind:"permission",name:`${Z}: ${V($,512)}`});return Q}function h(q){let Q=[...m(q.mcpServers),...g(q.lspServers),...P(q.models),...y(q.modelProviders),...f(q.permissions)];if(K(q.env))for(let Z of Object.keys(q.env).slice(0,z))Q.push({kind:"environment",name:Z});if(typeof q.permissionMode==="string")Q.push({kind:"permission",name:`permissionMode: ${q.permissionMode}`});return Q}function v(q){return q!=="hooks"&&q!=="disableAllHooks"}function l(q){return S("sha256").update(q).digest("hex")}function p(q,Q){let Z=F.relative(q,Q);return Z===""||!Z.startsWith(`..${F.sep}`)&&Z!==".."&&!F.isAbsolute(Z)}class x{storeDir;static instance=null;mutex=new w;statusCache=new k({max:R});constructor(q=F.join(_(),"workspace-trust")){this.storeDir=q}static getInstance(){if(!x.instance)x.instance=new x;return x.instance}static resetInstance(){x.instance=null}async getStatus(q){let Q=await C(q),Z;try{Z=await this.discoverSensitiveSources(Q.projectPath)}catch(Y){let O={...Q,state:"error",sensitiveSources:0,sources:[],decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust review failed"};return this.cacheStatus(q,O),O}if(Z.length===0){let Y={...Q,state:"not_required",sensitiveSources:0,sources:Z,decision:"undecided"};return this.cacheStatus(q,Y),Y}let $;try{$=await this.readDecisions()}catch(Y){let O={...Q,state:"error",sensitiveSources:Z.length,sources:Z,decision:"undecided",error:Y instanceof Error?Y.message:"Workspace trust store is unavailable"};return this.cacheStatus(q,O),O}let H=$.filter((Y)=>p(Y.path,Q.trustRoot)),G=Math.max(-1,...H.map((Y)=>Y.path.split(F.sep).length)),J=H.filter((Y)=>Y.path.split(F.sep).length===G),L=J.length>0&&J.every((Y)=>Y.trusted),U=J[0],b=U?.path===Q.trustRoot,W={...Q,state:L?"trusted":"untrusted",sensitiveSources:Z.length,sources:Z,decision:U?b?U.trusted?"trusted":"untrusted":"inherited":"undecided",...U?.decidedAt?{decidedAt:U.decidedAt}:{},...!b&&U?.path?{inheritedFrom:U.path}:{}};return this.cacheStatus(q,W),W}cacheStatus(q,Q){this.statusCache.set(F.resolve(q),Q),this.statusCache.set(Q.projectPath,Q)}getCachedStatus(q){return this.statusCache.get(F.resolve(q))}isTrustedCached(q){return this.getCachedStatus(q)?.state==="trusted"}getCacheStats(){return{capacity:R,entries:this.statusCache.size}}async trust(q){return this.recordDecision(q,!0)}async revoke(q){return this.recordDecision(q,!1)}async recordDecision(q,Q){return this.mutex.runExclusive(async()=>{await I(q);let Z=await C(q);await this.assertSafeTrustRoot(Z);let $={version:X,path:Z.trustRoot,trusted:Q,decidedAt:new Date().toISOString()};return await this.writeDecision($),this.statusCache.clear(),this.getStatus(q)})}async assertSafeTrustRoot(q){let Q=F.parse(q.trustRoot).root,Z=await B.realpath(N.homedir()).catch(()=>F.resolve(N.homedir()));if(!F.isAbsolute(q.trustRoot)||q.trustRoot===Q||q.trustRoot===Z)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(q){let Q=[],Z=await this.reviewPackageScripts(q);if(Z)Q.push(Z);for(let[$,H]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let G=await this.reviewConfigFile(q,$,H);if(G)Q.push(G)}for(let $ of[".blade/plugins",".claude/plugins"]){let H=await this.reviewResourceDirectory(q,$,"plugins","plugin");if(H)Q.push(H)}for(let $ of[".blade/commands",".claude/commands"]){let H=await this.reviewResourceDirectory(q,$,"commands","command");if(H)Q.push(H)}for(let[$,H,G]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let J=await this.reviewResourceDirectory(q,$,H,G);if(J)Q.push(J)}for(let $ of["CLAUDE.md","AGENTS.md","BLADE.md"]){let H=await this.reviewInstructionFile(q,$);if(H)Q.push(H)}return Q}async reviewPackageScripts(q){let Q=F.join(q,"package.json"),Z;try{Z=await B.stat(Q)}catch(J){if(J.code==="ENOENT")return;throw J}if(!Z.isFile())return;if(Z.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let $;try{$=JSON.parse(await B.readFile(Q,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!K($)||!K($.scripts))return;let H=$.scripts,G=Object.keys(H).filter((J)=>typeof H[J]==="string").sort().slice(0,z);if(G.length===0)return;return{path:"package.json",kind:"package",keys:G,effects:G.map((J)=>({kind:"command",name:`package script: ${J}`}))}}async reviewInstructionFile(q,Q){try{if(!(await B.stat(F.join(q,Q))).isFile())return}catch(Z){if(Z.code==="ENOENT")return;throw Z}return{path:Q,kind:"instructions",keys:[Q],effects:[{kind:"instruction",name:Q}]}}async reviewConfigFile(q,Q,Z){let $=F.join(q,Q),H;try{H=await B.stat($)}catch(b){if(b.code==="ENOENT")return;throw b}if(!H.isFile())return;if(H.size>T)throw Error(`${Q} exceeds the 1 MiB workspace review limit`);let G;try{G=JSON.parse(await B.readFile($,"utf8"))}catch{return{path:Q,kind:Z,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!K(G))return{path:Q,kind:Z,keys:[],effects:[],warning:"Configuration root is not an object"};let J=Object.keys(G).filter(v).sort();if(J.length===0)return;let L=h(G),U=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let b of J)if(!U.has(b))L.push({kind:"configuration",name:b});return{path:Q,kind:Z,keys:J,effects:L}}async reviewResourceDirectory(q,Q,Z,$){let H=F.join(q,Q),G;try{G=await B.readdir(H,{withFileTypes:!0})}catch(L){if(L.code==="ENOENT")return;throw L}let J=G.filter((L)=>Z==="plugins"||Z==="skills"?L.isDirectory()||L.isSymbolicLink():L.isFile()||L.isDirectory()||L.isSymbolicLink()).slice(0,z);if(J.length===0)return;return{path:Q,kind:Z,keys:J.map((L)=>L.name),effects:J.map((L)=>({kind:$,name:L.name}))}}async readDecisions(){let q;try{q=await B.lstat(this.storeDir)}catch($){if($.code==="ENOENT")return[];throw $}if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let Q=await B.readdir(this.storeDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.name.endsWith(".json"))continue;if(!$.isFile())throw Error("Workspace trust store entries must be regular files");Z.push(await this.readDecision(F.join(this.storeDir,$.name)))}return Z}async readDecision(q){let Q;try{Q=await B.open(q,A.O_RDONLY|A.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let Z=await Q.stat();if(!Z.isFile()||Z.size>j)throw Error("Workspace trust decision is invalid");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let $=JSON.parse(await Q.readFile("utf8"));if(!K($)||$.version!==X||typeof $.path!=="string"||!F.isAbsolute($.path)||typeof $.trusted!=="boolean"||typeof $.decidedAt!=="string"||!Number.isFinite(Date.parse($.decidedAt))||Object.keys($).some((H)=>H!=="version"&&H!=="path"&&H!=="trusted"&&H!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:X,path:$.path,trusted:$.trusted,decidedAt:$.decidedAt}}finally{await Q.close()}}async writeDecision(q){await this.ensureStoreDirectoryForWrite();let Q=F.join(this.storeDir,`${l(q.path)}.json`);try{let Z=await B.lstat(Q);if(!Z.isFile()||Z.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&Z.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((Z.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(Z){if(Z.code!=="ENOENT")throw Z}await E(Q,`${JSON.stringify(q,null,2)}
2
2
  `,{mode:384}),await B.chmod(Q,384)}async ensureStoreDirectoryForWrite(){try{let q=await B.lstat(this.storeDir);if(!q.isDirectory()||q.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&q.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((q.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(q){if(q.code!=="ENOENT")throw q;await B.mkdir(this.storeDir,{recursive:!0,mode:448}),await B.chmod(this.storeDir,448)}}}
3
- export{R as Pj,t as Qj,x as Rj};
3
+ export{R as Uj,t as Vj,x as Wj};
@@ -1,4 +1,4 @@
1
- import{Ba as L,za as F}from"./chunk-sy0vxdc3.js";import{Qd as $,Sd as B,_d as Q}from"./chunk-mxe4pr8t.js";import{Ng as y}from"./chunk-1cbaqh71.js";import{Qi as V}from"./chunk-jc28ddt0.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{Ba as L,za as F}from"./chunk-y66f1t18.js";import{Td as $,Vd as B,be as Q}from"./chunk-nqts5by0.js";import{Sg as y}from"./chunk-nnas8tdt.js";import{Vi as V}from"./chunk-dv2m2xe5.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as p,I as q,M as r,R as s,_ as t,C as u};
@@ -0,0 +1,2 @@
1
+ var _=20,E=5242880,T=32768,A=1e6,S=4194304;
2
+ export{_ as Ni,E as Oi,T as Pi,A as Qi,S as Ri};