@qwen-code/qwen-code 0.21.12-preview.3 → 0.21.12

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 (348) hide show
  1. package/bundled/qc-helper/docs/configuration/settings.md +10 -0
  2. package/bundled/qc-helper/docs/features/channels/overview.md +1 -1
  3. package/bundled/qc-helper/docs/features/channels/plugins.md +11 -11
  4. package/bundled/qc-helper/docs/features/code-review.md +1 -1
  5. package/bundled/qc-helper/docs/qwen-serve.md +99 -34
  6. package/bundled/review/SKILL.md +55 -36
  7. package/chunks/{MaxSizedBox-EIK4BHBQ.js → MaxSizedBox-ZSJJ2D5S.js} +46 -46
  8. package/chunks/{StandaloneSessionPicker-NHVJDRYD.js → StandaloneSessionPicker-WHUHQXSA.js} +65 -66
  9. package/chunks/{acp-startup-profiler-JMJBZDVO.js → acp-startup-profiler-SVPUHLXV.js} +2 -2
  10. package/chunks/{acpAgent-37UDZP64.js → acpAgent-7JOAESF5.js} +960 -539
  11. package/chunks/{agent-FAWBG7PP.js → agent-E6V3VXQR.js} +42 -42
  12. package/chunks/{agent-headless-SHK4PCCH.js → agent-headless-OEQNFOMH.js} +42 -42
  13. package/chunks/{anthropicContentGenerator-4JSC3ZFL.js → anthropicContentGenerator-YDT4EOKO.js} +25 -25
  14. package/chunks/{artifact-tool-FRMBPDPB.js → artifact-tool-4GCQQDZI.js} +5 -5
  15. package/chunks/{askUserQuestion-7G3LI3IZ.js → askUserQuestion-HZJJLR3Z.js} +2 -2
  16. package/chunks/{bridge-DEAYNDCI.js → bridge-NPBV53UA.js} +49 -49
  17. package/chunks/{build-RZS65IIX.js → build-GDBLPA24.js} +1 -1
  18. package/chunks/{channel-management-service-SKAN6NOB.js → channel-management-service-OADNGQM3.js} +4 -4
  19. package/chunks/{channel-settings-store-UIGYER6R.js → channel-settings-store-4ODLJ4X2.js} +49 -49
  20. package/chunks/{channel-worker-group-YPTB5ASD.js → channel-worker-group-IHBIHQ45.js} +7 -7
  21. package/chunks/{channel-worker-manager-4EHJSPRH.js → channel-worker-manager-GEHYJ5AE.js} +7 -7
  22. package/chunks/{channel-worker-supervisor-DZKHYFHV.js → channel-worker-supervisor-ZJIIWM4I.js} +5 -5
  23. package/chunks/{chunk-LHOG4E6Y.js → chunk-22C7BQ6D.js} +3 -3
  24. package/chunks/{chunk-DP3IHZGG.js → chunk-2AUM35J5.js} +59 -7
  25. package/chunks/{chunk-2SB4SLKC.js → chunk-2IIJTXYF.js} +1 -3
  26. package/chunks/{chunk-DYVCDQW2.js → chunk-2IVYL3IF.js} +1 -1
  27. package/chunks/{chunk-EYW54TBD.js → chunk-2ZWH53I4.js} +3 -3
  28. package/chunks/{chunk-5I5NMQCU.js → chunk-36XKGB7E.js} +3 -3
  29. package/chunks/{chunk-AQHNAA7E.js → chunk-3AEKDXKT.js} +1 -1
  30. package/chunks/{chunk-M6SXIXBV.js → chunk-3GDBZJD6.js} +6 -6
  31. package/chunks/{chunk-6XZERB6P.js → chunk-3GM5DLBI.js} +5 -5
  32. package/chunks/{chunk-4M2F7OG7.js → chunk-3LDGOQXZ.js} +6 -6
  33. package/chunks/{chunk-BKHCW2BI.js → chunk-3VUENPWF.js} +10 -0
  34. package/chunks/{chunk-ENEEQMGM.js → chunk-45NQKMYB.js} +1 -1
  35. package/chunks/{chunk-MDFUBQAQ.js → chunk-47BGDLJG.js} +119 -27
  36. package/chunks/{chunk-EFIMD5VA.js → chunk-4AOVQPJU.js} +1 -1
  37. package/chunks/{chunk-HB6QW4LM.js → chunk-4KM2SYK5.js} +19 -16
  38. package/chunks/{chunk-UNCIELQJ.js → chunk-4XA4QIUA.js} +1 -1
  39. package/chunks/{chunk-2J53A6MV.js → chunk-56HVDG3M.js} +4 -4
  40. package/chunks/{chunk-N3FJOQX7.js → chunk-5AFGJNY6.js} +4 -4
  41. package/chunks/{chunk-2AZMF6G5.js → chunk-5RUCD4ED.js} +2 -2
  42. package/chunks/{chunk-32VOOMEF.js → chunk-62X3CM7Q.js} +7 -7
  43. package/chunks/{chunk-6LYDH7VT.js → chunk-63FNZTWG.js} +2 -2
  44. package/chunks/{chunk-P64FPV3G.js → chunk-6JEIRPLN.js} +47 -4
  45. package/chunks/{chunk-O5G7IQGM.js → chunk-6P5EXEBL.js} +499 -112
  46. package/chunks/{chunk-3ZYX7AUR.js → chunk-6SPD4Z7F.js} +1 -1
  47. package/chunks/{chunk-YZJVVQD3.js → chunk-6ZKSO6K7.js} +7 -7
  48. package/chunks/{chunk-N5ULBHP3.js → chunk-7KJPO7YH.js} +2 -2
  49. package/chunks/{chunk-MZSJ43WV.js → chunk-7U5G6JXI.js} +24 -2
  50. package/chunks/{chunk-K7JW6V5O.js → chunk-A6NRNRKE.js} +1 -1
  51. package/chunks/{chunk-XLQS3VI6.js → chunk-AKBFSOC5.js} +2 -2
  52. package/chunks/{chunk-LT532KF4.js → chunk-AW27A43Y.js} +10 -12
  53. package/chunks/{chunk-M4NWDIFU.js → chunk-AZQ3DT76.js} +1 -1
  54. package/chunks/{chunk-4GLFFNP3.js → chunk-B4VN3VDH.js} +5 -5
  55. package/chunks/{chunk-YTYPRVIZ.js → chunk-BSR5AXZR.js} +4 -3
  56. package/chunks/{chunk-AJX4ITUG.js → chunk-BSSLSQEW.js} +3 -3
  57. package/chunks/{chunk-EYY4IBPV.js → chunk-CGM3E75C.js} +3 -3
  58. package/chunks/{chunk-V4MJ56RS.js → chunk-CIDQISGM.js} +5 -5
  59. package/chunks/{chunk-T6W4KACQ.js → chunk-CPFFU46D.js} +1 -1
  60. package/chunks/{chunk-TYCXSMZU.js → chunk-CQ6IPDQW.js} +3 -3
  61. package/chunks/{chunk-KIFRFCCB.js → chunk-CZ4OWGQQ.js} +67 -22
  62. package/chunks/{chunk-N7NBMAMW.js → chunk-D2RNVVH6.js} +2 -2
  63. package/chunks/{chunk-KPVVWKF3.js → chunk-D7QGE3RT.js} +1 -1
  64. package/chunks/{chunk-TYGKUOEG.js → chunk-DAV4QFD5.js} +3 -11
  65. package/chunks/{chunk-QUESTNOP.js → chunk-DD6O3ZRD.js} +1 -1
  66. package/chunks/{chunk-NWPO6I7V.js → chunk-DEDESZDL.js} +1 -1
  67. package/chunks/{chunk-7LZ7DK4D.js → chunk-DFVXU5YM.js} +1 -1
  68. package/chunks/{chunk-TBVNYG5B.js → chunk-DG4IQ6JG.js} +5 -5
  69. package/chunks/{chunk-SAQHDAUJ.js → chunk-DPTMKFIH.js} +452 -57
  70. package/chunks/{chunk-M6HXP2SG.js → chunk-EBPLKY6U.js} +2192 -849
  71. package/chunks/{chunk-3XZYK76R.js → chunk-EJOGLSNJ.js} +2 -2
  72. package/chunks/{chunk-L7T742G2.js → chunk-FA5K6YI2.js} +47 -3
  73. package/chunks/{chunk-M2NMFAFR.js → chunk-FMIH5KMQ.js} +1 -1
  74. package/chunks/{chunk-HHGQGTJQ.js → chunk-FQDCO3CJ.js} +10 -1
  75. package/chunks/{chunk-V3LXMASR.js → chunk-FRHQQC2Z.js} +1 -1
  76. package/chunks/{chunk-732MOPEM.js → chunk-G6MUFRNI.js} +1 -1
  77. package/chunks/{chunk-KNXA5XXK.js → chunk-GXTMEATA.js} +15 -34
  78. package/chunks/{chunk-7SUQZ7QH.js → chunk-GZDWTBT3.js} +2 -2
  79. package/chunks/{chunk-IQFYO5BF.js → chunk-H7TMVHKE.js} +1 -1
  80. package/chunks/{chunk-KNQZXSLW.js → chunk-HG3UBTJ4.js} +23 -9
  81. package/chunks/{chunk-MPBRV3UU.js → chunk-HOSVOUDK.js} +71 -0
  82. package/chunks/{chunk-OPBATTFQ.js → chunk-HTYND72J.js} +1 -1
  83. package/chunks/{chunk-I4XSOFH2.js → chunk-I7BT2MME.js} +1 -1
  84. package/chunks/{chunk-LHY6HBRA.js → chunk-IH4Z54RJ.js} +7 -5
  85. package/chunks/{chunk-GYBDYWMV.js → chunk-IRSLAS4M.js} +2 -2
  86. package/chunks/{chunk-UZPWH6SP.js → chunk-IX4PWUDU.js} +401 -173
  87. package/chunks/{chunk-KT4OWAAZ.js → chunk-JRIVMPD2.js} +3 -3
  88. package/chunks/{chunk-Q7YDKOGY.js → chunk-JVEGA3MM.js} +1 -1
  89. package/chunks/{chunk-O5AZPHYZ.js → chunk-K34GJQOZ.js} +138 -16
  90. package/chunks/{chunk-L2GTEEEU.js → chunk-K5IDV3PC.js} +44 -1
  91. package/chunks/{chunk-5HBFERG5.js → chunk-KEC5FHLM.js} +3 -3
  92. package/chunks/{chunk-5PWLQ7SK.js → chunk-KLOMACIR.js} +15 -8
  93. package/chunks/{chunk-XWUQ4IH5.js → chunk-KWX56CHZ.js} +7 -7
  94. package/chunks/{chunk-VQZXRLEX.js → chunk-LCX5B364.js} +3 -3
  95. package/chunks/{chunk-CTQE2NB2.js → chunk-LSRI3ND3.js} +1 -1
  96. package/chunks/{chunk-5TXOGH4I.js → chunk-LUISTZXI.js} +3 -3
  97. package/chunks/{chunk-6AECVSVX.js → chunk-MAKIANMX.js} +3 -3
  98. package/chunks/{chunk-M4OYAR6J.js → chunk-MDNUCDKZ.js} +2 -2
  99. package/chunks/{chunk-CZXQ4UZA.js → chunk-MELQSJOU.js} +1 -1
  100. package/chunks/{chunk-6ZIIHBNV.js → chunk-MUNA4QDC.js} +4 -4
  101. package/chunks/{chunk-E5BWLU5J.js → chunk-N4SVADAV.js} +305 -143
  102. package/chunks/{chunk-URK542T4.js → chunk-NF5J2WFA.js} +15 -2
  103. package/chunks/{chunk-GJJQV4PY.js → chunk-NLFLYSS4.js} +1 -1
  104. package/chunks/{chunk-FRH4SSGX.js → chunk-NW2GIPG3.js} +2 -4
  105. package/chunks/{chunk-JS4Q5NG5.js → chunk-NX4A23LY.js} +3 -3
  106. package/chunks/{chunk-DEG7R6Z6.js → chunk-OK47XBYH.js} +79 -36
  107. package/chunks/{chunk-7D4KEFOT.js → chunk-OPVF453Q.js} +3 -3
  108. package/chunks/{chunk-J7DNMZFO.js → chunk-OR64CU46.js} +1 -1
  109. package/chunks/{chunk-DAX3G67A.js → chunk-OWGRUU7F.js} +1 -1
  110. package/chunks/{chunk-M2PY7CNK.js → chunk-OWXFBIB6.js} +2 -2
  111. package/chunks/{chunk-NELCY6JT.js → chunk-OYWVIXHT.js} +1 -3
  112. package/chunks/{chunk-V7RNNPGC.js → chunk-P5Y23G2L.js} +18 -1
  113. package/chunks/{chunk-QZ5G26ZE.js → chunk-PTSEETCO.js} +27 -27
  114. package/chunks/{chunk-IEP44U2R.js → chunk-PVXEJB66.js} +1 -1
  115. package/chunks/{chunk-NC4O6UE6.js → chunk-PZW46OTB.js} +2 -2
  116. package/chunks/{chunk-RQVVXDHS.js → chunk-Q4ZPYNIZ.js} +4 -4
  117. package/chunks/{chunk-QSWDGAIC.js → chunk-QILD6R27.js} +1 -1
  118. package/chunks/{chunk-GLWWPFTW.js → chunk-QLTATTPS.js} +1 -1
  119. package/chunks/{chunk-QTI7SRXI.js → chunk-QPBFRWCP.js} +3 -3
  120. package/chunks/{chunk-3TT6MZHJ.js → chunk-QSD4UH74.js} +842 -62
  121. package/chunks/{chunk-TEKFBSMY.js → chunk-RDVNSJQU.js} +3 -3
  122. package/chunks/{chunk-NPE3STIW.js → chunk-ROIJYS5K.js} +6 -6
  123. package/chunks/{chunk-JEMR2FTD.js → chunk-RQJA2YYO.js} +4 -4
  124. package/chunks/{chunk-YI6UGZF5.js → chunk-S6TCTH4Z.js} +13 -13
  125. package/chunks/{chunk-ZGWY4YUB.js → chunk-SYHXR6WM.js} +5 -5
  126. package/chunks/{chunk-O4BBDP2G.js → chunk-TB4YFWXG.js} +2 -2
  127. package/chunks/{chunk-ILVATFYJ.js → chunk-TDESMS7M.js} +22 -18
  128. package/chunks/{chunk-47FQVRCO.js → chunk-TMFWI4RC.js} +1 -1
  129. package/chunks/{chunk-T4FTABSW.js → chunk-TQDFSQQF.js} +1 -1
  130. package/chunks/{chunk-ZV4XVYL3.js → chunk-TTRH3RTQ.js} +4 -4
  131. package/chunks/{chunk-ZWPWQEF5.js → chunk-TXP5NGG3.js} +1 -1
  132. package/chunks/{chunk-E3GLDLYB.js → chunk-TYAMGABM.js} +0 -6
  133. package/chunks/{chunk-VWD7SNNN.js → chunk-UI5UGEF4.js} +1082 -926
  134. package/chunks/{chunk-MWZYNOCG.js → chunk-ULNWG62W.js} +3 -3
  135. package/chunks/{chunk-HGCQ5SE7.js → chunk-UXEO7E3V.js} +21 -0
  136. package/chunks/{chunk-U6PTKAOW.js → chunk-V6OBVAST.js} +1 -1
  137. package/chunks/{chunk-5UPJ774B.js → chunk-VIFA5VJD.js} +1 -1
  138. package/chunks/{chunk-Y66OOMKS.js → chunk-VLHR7F4E.js} +595 -58
  139. package/chunks/{chunk-EYS3GGM3.js → chunk-VPV7WBVT.js} +1 -1
  140. package/chunks/{chunk-XCGIMOLN.js → chunk-WCCLLK7X.js} +14 -1
  141. package/chunks/{chunk-JL3LC3CQ.js → chunk-WCEI6J56.js} +1 -1
  142. package/chunks/{chunk-JXK3WAP7.js → chunk-WDVDVWJ3.js} +6 -6
  143. package/chunks/{chunk-ZQSNP4TG.js → chunk-WI6GIM2M.js} +2 -2
  144. package/chunks/{chunk-TRYJ3BVE.js → chunk-WM3LUQLO.js} +7 -7
  145. package/chunks/{chunk-VJNBRRZG.js → chunk-WZMH7II3.js} +1 -1
  146. package/chunks/{chunk-HBZUU4AE.js → chunk-X5SLJOMF.js} +9 -7
  147. package/chunks/{chunk-FDWH6CBK.js → chunk-XAFIL4BD.js} +7 -7
  148. package/chunks/{chunk-P2UCMHDT.js → chunk-XDRXOSAD.js} +3 -3
  149. package/chunks/{chunk-RRQJPCRQ.js → chunk-XH3KAV2G.js} +2 -2
  150. package/chunks/{chunk-F6AOBFUN.js → chunk-YBHUXEC6.js} +1 -1
  151. package/chunks/{chunk-GZGDJ4E6.js → chunk-YBVVOSOH.js} +1 -1
  152. package/chunks/{chunk-EXG2R5UR.js → chunk-YCHNAKC5.js} +16 -14
  153. package/chunks/{chunk-XTH2OMDS.js → chunk-YIGGWOJE.js} +1 -1
  154. package/chunks/{chunk-IX7CFQGA.js → chunk-YILJKX2T.js} +3 -3
  155. package/chunks/{chunk-SSAOTDK7.js → chunk-YX2RDGAL.js} +1 -1
  156. package/chunks/{chunk-6S52N6PG.js → chunk-ZBB5EZZV.js} +2 -2
  157. package/chunks/{chunk-3GCU5O2E.js → chunk-ZLCT4C5A.js} +1 -1
  158. package/chunks/{chunk-4ETA3KRC.js → chunk-ZMY2P4L3.js} +3 -3
  159. package/chunks/{chunk-575MI5K3.js → chunk-ZQUY3ZJU.js} +4 -4
  160. package/chunks/{computer-use-S4JEU5P7.js → computer-use-F4URV4TU.js} +45 -45
  161. package/chunks/{config-utils-TXVKR27S.js → config-utils-Z3OW3IQG.js} +4 -4
  162. package/chunks/{contextCommand-2H5OH2HW.js → contextCommand-IGSS2U5J.js} +44 -44
  163. package/chunks/{core-runtime-IAQ4DD4Y.js → core-runtime-H5CZDN3A.js} +42 -42
  164. package/chunks/{create-sub-session-EKHKXJAA.js → create-sub-session-PA7MFTHK.js} +42 -42
  165. package/chunks/{create-sub-session-Y4WYDZGC.js → create-sub-session-XT6DLYOE.js} +2 -2
  166. package/chunks/{cron-create-ZOVA3CC2.js → cron-create-2JZ2TWTF.js} +4 -4
  167. package/chunks/{cron-delete-7Z3H4LJY.js → cron-delete-CTPD2P26.js} +4 -4
  168. package/chunks/{cron-list-UHGX3IQG.js → cron-list-V44KHAF6.js} +4 -4
  169. package/chunks/{daemon-PXIC4ZDK.js → daemon-GED37WOX.js} +30 -2
  170. package/chunks/daemon-git-worktree-guard-LZDCNJGV.js +2062 -0
  171. package/chunks/daemon-status-provider-QYM57Z44.js +102 -0
  172. package/chunks/{daemon-trust-policy-7JOBVFH3.js → daemon-trust-policy-TSRVEYZR.js} +48 -48
  173. package/chunks/{daemon-trust-policy-monitor-OU3NRHAR.js → daemon-trust-policy-monitor-2K2YETMT.js} +48 -48
  174. package/chunks/{deferred-core-runtime-SFT3KI2C.js → deferred-core-runtime-FKJ3OYE7.js} +44 -44
  175. package/chunks/{devtools-X6ROTKHE.js → devtools-4QFYJT6U.js} +1 -1
  176. package/chunks/{display-image-ZE3GZNIK.js → display-image-M2ELAVN4.js} +4 -4
  177. package/chunks/{dist-KTYDJNYM.js → dist-4ZPG4BY6.js} +2 -2
  178. package/chunks/{dist-NPS52B2V.js → dist-BROOP2EG.js} +1 -1
  179. package/chunks/{dist-BW2LDPV3.js → dist-IYYN3RUT.js} +2 -2
  180. package/chunks/{dist-EFJILGIS.js → dist-JWMKPWT5.js} +3 -1
  181. package/chunks/{dist-AVUYBK7L.js → dist-K7IQB53U.js} +1 -1
  182. package/chunks/{dist-PKSRQAR2.js → dist-MAQXAQ2Y.js} +1 -1
  183. package/chunks/{dist-BNWP6IZL.js → dist-WJ4BHIEW.js} +2 -2
  184. package/chunks/{dist-ZWDH5HLS.js → dist-YEPL4RAW.js} +1 -1
  185. package/chunks/{earlyInputCapture-27RPWE2D.js → earlyInputCapture-WJBSJQUF.js} +43 -43
  186. package/chunks/{edit-WXVZ7FHS.js → edit-X73LA4YO.js} +50 -49
  187. package/chunks/{enter-worktree-TYMVXFLA.js → enter-worktree-CLRQTIVN.js} +47 -47
  188. package/chunks/{enterPlanMode-FT4MRU5N.js → enterPlanMode-6BDYUQ5T.js} +48 -48
  189. package/chunks/{environment-Z6OMA34I.js → environment-WOAJXJDJ.js} +44 -44
  190. package/chunks/{errors-YMXK2GG3.js → errors-7OY5MXYY.js} +44 -44
  191. package/chunks/{exit-worktree-ODZUQLGJ.js → exit-worktree-TFFJXCRT.js} +47 -47
  192. package/chunks/{exitPlanMode-MBPAPBBV.js → exitPlanMode-WDURQMIU.js} +42 -42
  193. package/chunks/{external-tool-guard-provider-5HTGOPGU.js → external-tool-guard-provider-TE4DRY36.js} +1 -1
  194. package/chunks/{fast-path-ZU5T6XSN.js → fast-path-QQLGC37M.js} +5 -5
  195. package/chunks/{gemini-OZK6AIMC.js → gemini-VHE62IJL.js} +110 -105
  196. package/chunks/{geminiContentGenerator-MC6ZKWZG.js → geminiContentGenerator-VSHIEGAQ.js} +11 -11
  197. package/chunks/{glob-KJ4A4ZOM.js → glob-VMEEDDLO.js} +49 -49
  198. package/chunks/{goal-tools-JDK2SNMV.js → goal-tools-M4UDAZXP.js} +4 -4
  199. package/chunks/{grep-QWBLG564.js → grep-F4UAR7KX.js} +47 -47
  200. package/chunks/{handleAutoUpdate-M3ACKDKF.js → handleAutoUpdate-GN7Z6QAC.js} +46 -46
  201. package/chunks/{i18n-FPW7XZL5.js → i18n-ETW24DHW.js} +43 -43
  202. package/chunks/{image-gen-OTFC2S7L.js → image-gen-YPK2AZT4.js} +11 -11
  203. package/chunks/{initializer-5HKUXXBT.js → initializer-UA6KQ7MS.js} +49 -49
  204. package/chunks/{installationInfo-4OA6UW7V.js → installationInfo-P7OTIR4P.js} +43 -43
  205. package/chunks/{keychain-token-storage-JTWUYFU7.js → keychain-token-storage-NKKCUHI2.js} +2 -2
  206. package/chunks/{list-3TKZ264A.js → list-GRAMIQOT.js} +51 -51
  207. package/chunks/{list-agents-4GQ2XNEU.js → list-agents-O6WSY4CT.js} +2 -2
  208. package/chunks/{loadedSettingsAdapter-IRUANLS2.js → loadedSettingsAdapter-5O2TDS3I.js} +48 -48
  209. package/chunks/{loggingContentGenerator-D4URLH2A.js → loggingContentGenerator-J2J2AANS.js} +151 -120
  210. package/chunks/{loop-wakeup-HOQI3K5D.js → loop-wakeup-GVQRMUKS.js} +5 -5
  211. package/chunks/{ls-FSHISLLA.js → ls-6W2D7TKU.js} +6 -6
  212. package/chunks/{lsp-APQJ5ZEZ.js → lsp-NJ4KFBI2.js} +2 -2
  213. package/chunks/{managed-npm-update-2O7XSAWJ.js → managed-npm-update-WMV5ITKU.js} +45 -45
  214. package/chunks/{mcp-AFVHCHKT.js → mcp-XLP33CAI.js} +48 -48
  215. package/chunks/{monitor-PY4WDSX3.js → monitor-2MM23VDV.js} +47 -47
  216. package/chunks/{node-YSOU44FX.js → node-UUDY34IG.js} +3 -3
  217. package/chunks/nonInteractiveCli-KTA5K6FS.js +163 -0
  218. package/chunks/{notebook-edit-GEPL33NO.js → notebook-edit-QD4TRKLY.js} +47 -47
  219. package/chunks/{openaiContentGenerator-ACYSXQ6R.js → openaiContentGenerator-KLHSPVN2.js} +31 -31
  220. package/chunks/{pidfile-SUNYCAA4.js → pidfile-RQGZBNXT.js} +43 -43
  221. package/chunks/{processUtils-F7LP7YUV.js → processUtils-HZZDA2VV.js} +2 -2
  222. package/chunks/{qwenContentGenerator-BB6IPELF.js → qwenContentGenerator-T75M2Z3B.js} +50 -50
  223. package/chunks/{qwenOAuth2-OU3WGDOI.js → qwenOAuth2-5QZU444W.js} +10 -10
  224. package/chunks/{read-file-GORBXJTS.js → read-file-LOVUSBJC.js} +12 -12
  225. package/chunks/{read-mcp-resource-TJSJRH4F.js → read-mcp-resource-GWCP23WG.js} +2 -2
  226. package/chunks/{read-package-up-TCM6I7S2.js → read-package-up-K6RKTL5D.js} +1 -1
  227. package/chunks/{record-artifact-FXF5LHPE.js → record-artifact-IYQDEYMV.js} +3 -3
  228. package/chunks/{resumeHistoryUtils-FOAJJJWK.js → resumeHistoryUtils-LVKSSQII.js} +50 -50
  229. package/chunks/{ripGrep-RNLIZGCY.js → ripGrep-ZJSHKB6H.js} +42 -42
  230. package/chunks/{run-qwen-serve-GVMMX3IU.js → run-qwen-serve-GZW7B4WK.js} +186 -90
  231. package/chunks/{runtime-RNBZ5FDD.js → runtime-MYRXEO2E.js} +53 -53
  232. package/chunks/{scheduler-NTRFSPIP.js → scheduler-DPTPI6FW.js} +44 -44
  233. package/chunks/{sdk-exporters-grpc-4QKV6MCX.js → sdk-exporters-grpc-54L4LS5L.js} +2 -2
  234. package/chunks/{sdk-exporters-http-2VPMAPFI.js → sdk-exporters-http-NHBYB5FZ.js} +21 -17
  235. package/chunks/{sdk-impl-5W3JUCWF.js → sdk-impl-SK4P5WON.js} +17 -14
  236. package/chunks/{send-message-RBYLV5NY.js → send-message-O7FO63UK.js} +6 -6
  237. package/chunks/{serve-H3PGA26U.js → serve-XCG4XCDA.js} +52 -52
  238. package/chunks/{server-SUXD2F3C.js → server-AWQHKXLG.js} +310 -200
  239. package/chunks/{session-MTFVUWWM.js → session-P5FKNCNR.js} +94 -97
  240. package/chunks/{settings-GUJ3TN2J.js → settings-CSYVIP2R.js} +47 -47
  241. package/chunks/{shell-C2UP5FF2.js → shell-EGTSUO2P.js} +42 -42
  242. package/chunks/{skill-4XCNK55E.js → skill-IFUD72GF.js} +22 -22
  243. package/chunks/{skill-settings-Y2BU27XM.js → skill-settings-YOE7LBHE.js} +47 -47
  244. package/chunks/{spawnChannel-UUUUK734.js → spawnChannel-PQSZIOLY.js} +45 -47
  245. package/chunks/{standalone-update-MJ722XZ4.js → standalone-update-RB2EGUSF.js} +44 -44
  246. package/chunks/{startInteractiveUI-TCPIPNGN.js → startInteractiveUI-KMYUJ2MU.js} +3040 -2399
  247. package/chunks/{syntheticOutput-D3Z64LJC.js → syntheticOutput-DVHJMUGV.js} +3 -3
  248. package/chunks/{task-create-URFZ5EUX.js → task-create-4NC7PDI4.js} +11 -11
  249. package/chunks/{task-list-6JDFMPUW.js → task-list-LBSRMOC7.js} +5 -5
  250. package/chunks/{task-stop-HHUGCD25.js → task-stop-YFNATTIM.js} +2 -2
  251. package/chunks/{task-update-DVV6CUGI.js → task-update-BPLM52GD.js} +12 -12
  252. package/chunks/{team-create-WZWH2NJI.js → team-create-B6A6MJBT.js} +47 -47
  253. package/chunks/{team-delete-PZGGBQLM.js → team-delete-MKYMYBFM.js} +5 -5
  254. package/chunks/{team-plan-approval-SUZQJCWJ.js → team-plan-approval-5WO3CXXU.js} +48 -48
  255. package/chunks/{terminal-image-renderer-BCUN3Z3W.js → terminal-image-renderer-BTRE2GEU.js} +44 -44
  256. package/chunks/{theme-manager-UGMFDREN.js → theme-manager-XL2N5SBY.js} +43 -43
  257. package/chunks/{todoWrite-WINAZSZI.js → todoWrite-K5K7NRE5.js} +4 -4
  258. package/chunks/{tool-search-B6F3MPUZ.js → tool-search-QNBLXUGR.js} +18 -18
  259. package/chunks/{total-session-admission-MQLBJ5WL.js → total-session-admission-N4E5SFBO.js} +49 -49
  260. package/chunks/{trustedFolders-2XST7U5C.js → trustedFolders-MQS46LIU.js} +43 -43
  261. package/chunks/{update-relaunch-OVC7YNGD.js → update-relaunch-536KRL33.js} +5 -5
  262. package/chunks/{updateCheck-YAKM36WQ.js → updateCheck-QJI2SYWF.js} +48 -48
  263. package/chunks/{useAutoAcceptIndicator-RF6FVX3S.js → useAutoAcceptIndicator-7QASHD46.js} +51 -51
  264. package/chunks/{validateNonInterActiveAuth-IPPXFNQH.js → validateNonInterActiveAuth-ZNRGWBLV.js} +86 -88
  265. package/chunks/{version-4IDFEXOU.js → version-DBEQAFRW.js} +2 -2
  266. package/chunks/{web-fetch-NUOLHXPN.js → web-fetch-MBIVXKPE.js} +21 -21
  267. package/chunks/{web-search-LVOOV4XZ.js → web-search-4LBIN6VF.js} +16 -16
  268. package/chunks/{workflow-JSTYTG3K.js → workflow-LNMA55HY.js} +127 -61
  269. package/chunks/{workspace-providers-status-U4EYXA4K.js → workspace-providers-status-PDDMI6ST.js} +51 -51
  270. package/chunks/{workspace-registration-store-OG66U3CB.js → workspace-registration-store-BGRKKIYR.js} +1 -1
  271. package/chunks/{workspace-registry-WSHWQRQQ.js → workspace-registry-L4NCJ34K.js} +49 -49
  272. package/chunks/{workspace-service-QZXQHX2F.js → workspace-service-LOXYKYTR.js} +54 -54
  273. package/chunks/{workspace-skills-status-VRBHEX5O.js → workspace-skills-status-IJ5FOQI6.js} +49 -49
  274. package/chunks/{workspace-trust-reconciler-FCRIUIOF.js → workspace-trust-reconciler-H36TCR2S.js} +57 -57
  275. package/chunks/{write-file-PYL3JCCD.js → write-file-JJAY7JSP.js} +42 -42
  276. package/chunks/{zoom-image-RS6MU26F.js → zoom-image-4MVVVM7E.js} +12 -12
  277. package/cli.js +18 -17
  278. package/package.json +4 -4
  279. package/web-shell/assets/{arc-CgGUyHWd.js → arc-B-89zHN4.js} +1 -1
  280. package/web-shell/assets/{architectureDiagram-3BPJPVTR-BR0Qv-1Y.js → architectureDiagram-3BPJPVTR-BkcOncHk.js} +1 -1
  281. package/web-shell/assets/{blockDiagram-GPEHLZMM-DIoaceaI.js → blockDiagram-GPEHLZMM-DQ4yboaF.js} +1 -1
  282. package/web-shell/assets/{c4Diagram-AAUBKEIU-Bc5k6BbI.js → c4Diagram-AAUBKEIU-C_8ZjPDI.js} +1 -1
  283. package/web-shell/assets/channel-Du2WFns8.js +1 -0
  284. package/web-shell/assets/{chunk-2J33WTMH-DtPEz2WX.js → chunk-2J33WTMH-naKVe1Bm.js} +1 -1
  285. package/web-shell/assets/{chunk-4BX2VUAB-Dydo6ydE.js → chunk-4BX2VUAB-DdoViKT2.js} +1 -1
  286. package/web-shell/assets/{chunk-55IACEB6-DD9_VWXm.js → chunk-55IACEB6-DUDQZEwU.js} +1 -1
  287. package/web-shell/assets/{chunk-727SXJPM-DVI2m59k.js → chunk-727SXJPM-BqpDTR5s.js} +1 -1
  288. package/web-shell/assets/{chunk-AQP2D5EJ-luatmaTN.js → chunk-AQP2D5EJ-CdmEknkT.js} +1 -1
  289. package/web-shell/assets/{chunk-FMBD7UC4-Duy8NTIi.js → chunk-FMBD7UC4-CH7fFTLB.js} +1 -1
  290. package/web-shell/assets/{chunk-ND2GUHAM-CrL1yhms.js → chunk-ND2GUHAM-ObgSuFKF.js} +1 -1
  291. package/web-shell/assets/{chunk-QZHKN3VN-C7BX6bu1.js → chunk-QZHKN3VN-D9fKdv_s.js} +1 -1
  292. package/web-shell/assets/classDiagram-4FO5ZUOK-Zw0HafH6.js +1 -0
  293. package/web-shell/assets/classDiagram-v2-Q7XG4LA2-Zw0HafH6.js +1 -0
  294. package/web-shell/assets/{cose-bilkent-S5V4N54A-BTzs7mIi.js → cose-bilkent-S5V4N54A-CvzATMx9.js} +1 -1
  295. package/web-shell/assets/{dagre-BM42HDAG-3VTUmWts.js → dagre-BM42HDAG-M_xU21QW.js} +1 -1
  296. package/web-shell/assets/{diagram-2AECGRRQ-Ehdp75GN.js → diagram-2AECGRRQ-CNrl9sW1.js} +1 -1
  297. package/web-shell/assets/{diagram-5GNKFQAL-B3wu3teE.js → diagram-5GNKFQAL-CUweVT6T.js} +1 -1
  298. package/web-shell/assets/{diagram-KO2AKTUF-DjgTSf2S.js → diagram-KO2AKTUF-D3n6Lxjo.js} +1 -1
  299. package/web-shell/assets/{diagram-LMA3HP47-Br9mwjY3.js → diagram-LMA3HP47-0SeFPK4t.js} +1 -1
  300. package/web-shell/assets/{diagram-OG6HWLK6-D4xz5M-z.js → diagram-OG6HWLK6-DAgyEwge.js} +1 -1
  301. package/web-shell/assets/{erDiagram-TEJ5UH35-CXayWlG_.js → erDiagram-TEJ5UH35-CzxBBDIK.js} +1 -1
  302. package/web-shell/assets/{flowDiagram-I6XJVG4X-CLonjQTi.js → flowDiagram-I6XJVG4X-B0uj0jyo.js} +1 -1
  303. package/web-shell/assets/{ganttDiagram-6RSMTGT7-BTySFT-1.js → ganttDiagram-6RSMTGT7-DFzcj5km.js} +1 -1
  304. package/web-shell/assets/{gitGraphDiagram-PVQCEYII--2WcUjOe.js → gitGraphDiagram-PVQCEYII-DylJ_Fc9.js} +1 -1
  305. package/web-shell/assets/index-BIGQygTL.css +5 -0
  306. package/web-shell/assets/{index-DPJHkFOG.js → index-BKSAnXU9.js} +1 -1
  307. package/web-shell/assets/index-J7OMTqAN.js +1789 -0
  308. package/web-shell/assets/{infoDiagram-5YYISTIA-9vpgAf1m.js → infoDiagram-5YYISTIA-BYMcJVMI.js} +1 -1
  309. package/web-shell/assets/{ishikawaDiagram-YF4QCWOH-DcRpHnAW.js → ishikawaDiagram-YF4QCWOH-t1quI1S3.js} +1 -1
  310. package/web-shell/assets/{journeyDiagram-JHISSGLW-C2TKorRm.js → journeyDiagram-JHISSGLW-YM_QVUJm.js} +1 -1
  311. package/web-shell/assets/{kanban-definition-UN3LZRKU-DdsFwB8b.js → kanban-definition-UN3LZRKU-jw8OddK1.js} +1 -1
  312. package/web-shell/assets/{linear-7PjRvJrf.js → linear-Dlr3RVuP.js} +1 -1
  313. package/web-shell/assets/{mermaid.core-raDXa11C.js → mermaid.core-CqGKzNzd.js} +5 -5
  314. package/web-shell/assets/{mindmap-definition-RKZ34NQL-DLHc-PRN.js → mindmap-definition-RKZ34NQL-BqureoOS.js} +1 -1
  315. package/web-shell/assets/{pieDiagram-4H26LBE5-BftYpeTW.js → pieDiagram-4H26LBE5-Da20HkK1.js} +1 -1
  316. package/web-shell/assets/{quadrantDiagram-W4KKPZXB-O-6ygOYn.js → quadrantDiagram-W4KKPZXB-BsNlMvJy.js} +1 -1
  317. package/web-shell/assets/{requirementDiagram-4Y6WPE33-BmZWVufJ.js → requirementDiagram-4Y6WPE33-DzVCQCse.js} +1 -1
  318. package/web-shell/assets/{sankeyDiagram-5OEKKPKP-2x5beiWt.js → sankeyDiagram-5OEKKPKP-BMo16voT.js} +1 -1
  319. package/web-shell/assets/{sequenceDiagram-3UESZ5HK-BH8uKokQ.js → sequenceDiagram-3UESZ5HK-Bgi-pdHk.js} +1 -1
  320. package/web-shell/assets/{stateDiagram-AJRCARHV-Dq1MFgX_.js → stateDiagram-AJRCARHV-xaPQXwGk.js} +1 -1
  321. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-D5RqimXD.js +1 -0
  322. package/web-shell/assets/{timeline-definition-PNZ67QCA-Cl2WKbv9.js → timeline-definition-PNZ67QCA-C_9RuvKG.js} +1 -1
  323. package/web-shell/assets/{vennDiagram-CIIHVFJN-BqoRo_Q-.js → vennDiagram-CIIHVFJN-Bgu6vdla.js} +1 -1
  324. package/web-shell/assets/{wardley-L42UT6IY-BTxp-Yot.js → wardley-L42UT6IY-CFTZ8IrX.js} +1 -1
  325. package/web-shell/assets/{wardleyDiagram-YWT4CUSO-DFXVCSH2.js → wardleyDiagram-YWT4CUSO-BASW9Vmt.js} +1 -1
  326. package/web-shell/assets/{xychartDiagram-2RQKCTM6-qQhWx0aE.js → xychartDiagram-2RQKCTM6--Nh-CD3F.js} +1 -1
  327. package/web-shell/index.html +2 -2
  328. package/chunks/chunk-CG3OQDNY.js +0 -649
  329. package/chunks/chunk-L34XSHIZ.js +0 -28
  330. package/chunks/chunk-N2TNM3QB.js +0 -9
  331. package/chunks/chunk-UOMZKPI5.js +0 -830
  332. package/chunks/chunk-WFRHWDBT.js +0 -622
  333. package/chunks/chunk-WLML6VIA.js +0 -18
  334. package/chunks/chunk-ZBBVBZBR.js +0 -137
  335. package/chunks/chunk-bdqvmfwv-OHYAFAAO.js +0 -17446
  336. package/chunks/daemon-status-provider-LPYR2GXY.js +0 -103
  337. package/chunks/dispatch-B53LNEO4.js +0 -37
  338. package/chunks/nonInteractiveCli-ZHW6F76F.js +0 -166
  339. package/chunks/opentui-entry-SBAOWW7M.js +0 -52325
  340. package/chunks/runtime-gate-T4ICWGQJ.js +0 -89
  341. package/chunks/wrapper-46Z24CTM.js +0 -35
  342. package/web-shell/assets/channel-D2b9IYpS.js +0 -1
  343. package/web-shell/assets/classDiagram-4FO5ZUOK-DHatTCmD.js +0 -1
  344. package/web-shell/assets/classDiagram-v2-Q7XG4LA2-DHatTCmD.js +0 -1
  345. package/web-shell/assets/index-CIFO52Wx.css +0 -5
  346. package/web-shell/assets/index-bhq3CUUF.js +0 -1789
  347. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-spuAYji6.js +0 -1
  348. /package/chunks/{chunk-44CTCCLY.js → chunk-NWNEANAT.js} +0 -0
@@ -40,7 +40,7 @@ import {
40
40
  CronScheduler,
41
41
  DEFAULT_RECURRING_MAX_AGE_DAYS,
42
42
  normalizeRecurringMaxAge
43
- } from "./chunk-QTI7SRXI.js";
43
+ } from "./chunk-QPBFRWCP.js";
44
44
  import {
45
45
  consumeUnread,
46
46
  forwardApproval,
@@ -49,13 +49,13 @@ import {
49
49
  sendStructuredMessage,
50
50
  wrapConfirmWithBadge,
51
51
  writeMessage
52
- } from "./chunk-KT4OWAAZ.js";
52
+ } from "./chunk-JRIVMPD2.js";
53
53
  import {
54
54
  claimTask,
55
55
  listTasks,
56
56
  onTasksUpdated,
57
57
  unassignTeammateTasks
58
- } from "./chunk-IX7CFQGA.js";
58
+ } from "./chunk-YILJKX2T.js";
59
59
  import {
60
60
  assignTeammateColor,
61
61
  classifyShutdownResponse,
@@ -63,7 +63,7 @@ import {
63
63
  formatAgentId,
64
64
  generateUniqueTeammateName,
65
65
  writeTeamFile
66
- } from "./chunk-N7NBMAMW.js";
66
+ } from "./chunk-D2RNVVH6.js";
67
67
  import {
68
68
  parsePositiveIntegerEnv
69
69
  } from "./chunk-6PVPNMXU.js";
@@ -71,13 +71,13 @@ import {
71
71
  RUNTIME_SNAPSHOT_PREFIX,
72
72
  buildModelIdContext,
73
73
  resolveModelId
74
- } from "./chunk-I4XSOFH2.js";
74
+ } from "./chunk-I7BT2MME.js";
75
75
  import {
76
76
  ARTIFACT_TITLE_MAX_LENGTH,
77
77
  ARTIFACT_WORKSPACE_PATH_MAX_LENGTH,
78
78
  hasControlCharacter,
79
79
  hasUnsafeDisplayPayload
80
- } from "./chunk-NWPO6I7V.js";
80
+ } from "./chunk-DEDESZDL.js";
81
81
  import {
82
82
  promptIdContext,
83
83
  todoWorkChainContext
@@ -86,22 +86,6 @@ import {
86
86
  LEADER_NAME,
87
87
  MAX_TEAMMATES
88
88
  } from "./chunk-CPBF7KYF.js";
89
- import {
90
- APPROVAL_MODES,
91
- READ_ONLY_INSPECTION_TOOLS,
92
- SUBAGENT_PLAN_LIFECYCLE_TOOLS,
93
- buildSubagentPlanToolBlockedResult,
94
- getLeaderOnlyToolUnavailableMessage,
95
- getPlanRequiredTeammatePreApprovalMessage,
96
- getSubagentPlanToolUnavailableMessage,
97
- isLeaderOnlyToolUnavailableInSubagent,
98
- isPlanLifecycleToolUnavailableInSubagent,
99
- isPlanRequiredTeammateAwaitingApproval,
100
- isPlanRequiredTeammateContext,
101
- isPlanRequiredTeammatePreApprovalAllowedTool,
102
- isSubagentLikeExecutionContext,
103
- shouldUsePlanOnlyReminderInSubagentContext
104
- } from "./chunk-6LYDH7VT.js";
105
89
  import {
106
90
  SKILL_FILE_NAME,
107
91
  SKILL_NAME_PATTERN,
@@ -121,7 +105,7 @@ import {
121
105
  require_dist as require_dist2,
122
106
  stringify,
123
107
  validateSkillName
124
- } from "./chunk-2AZMF6G5.js";
108
+ } from "./chunk-5RUCD4ED.js";
125
109
  import {
126
110
  require_proper_lockfile
127
111
  } from "./chunk-KRXPRVGL.js";
@@ -139,48 +123,74 @@ import {
139
123
  createHookOutput,
140
124
  getHookKey,
141
125
  isToolArtifactLike
142
- } from "./chunk-GZGDJ4E6.js";
126
+ } from "./chunk-YBVVOSOH.js";
143
127
  import {
144
128
  BaseTokenStorage,
145
129
  KeychainTokenStorage
146
- } from "./chunk-T6W4KACQ.js";
130
+ } from "./chunk-CPFFU46D.js";
147
131
  import {
148
132
  normalizeImageGenerationBaseUrl,
149
133
  resolveNetworkTarget
150
- } from "./chunk-MWZYNOCG.js";
134
+ } from "./chunk-ULNWG62W.js";
151
135
  import {
136
+ EvidenceSourceUnavailableError,
137
+ GoalEvidenceCheckpointAccumulator,
138
+ GoalEvidenceRecordIndexAccumulator,
152
139
  GoalPersistenceUnavailableError,
140
+ InvalidGoalEvidenceReferenceError,
153
141
  PAUSED_GOAL_SYSTEM_REMINDER,
154
142
  aggregateTranscriptRecordFragments,
155
143
  createGoalCheckpointVerifier,
156
144
  createGoalRuntime,
157
145
  goalRequiresExactPermit,
158
146
  goalTurnContext,
147
+ isGoalRecoveryCandidate,
159
148
  isTranscriptArtifactRecord,
160
149
  isTranscriptConversationRecord,
161
150
  isUserPromptSubmitContextPartText,
151
+ normalizeGoalRecoveryRecord,
162
152
  parseGoalStateRecordPayloadV2,
163
153
  prepareTranscriptRecords,
164
154
  projectUserTranscriptForDisplay,
155
+ selectGoalRecoveryFromRecords,
165
156
  selectTranscriptLeaf,
166
157
  validateTranscriptRecord,
167
158
  walkTranscriptUuidChain,
168
159
  wrapUserPromptSubmitContext
169
- } from "./chunk-SAQHDAUJ.js";
160
+ } from "./chunk-DPTMKFIH.js";
161
+ import {
162
+ APPROVAL_MODES,
163
+ READ_ONLY_INSPECTION_TOOLS,
164
+ SUBAGENT_PLAN_LIFECYCLE_TOOLS,
165
+ buildSubagentPlanToolBlockedResult,
166
+ getLeaderOnlyToolUnavailableMessage,
167
+ getPlanRequiredTeammatePreApprovalMessage,
168
+ getSubagentPlanToolUnavailableMessage,
169
+ isLeaderOnlyToolUnavailableInSubagent,
170
+ isPlanLifecycleToolUnavailableInSubagent,
171
+ isPlanRequiredTeammateAwaitingApproval,
172
+ isPlanRequiredTeammateContext,
173
+ isPlanRequiredTeammatePreApprovalAllowedTool,
174
+ isSubagentLikeExecutionContext,
175
+ shouldUsePlanOnlyReminderInSubagentContext
176
+ } from "./chunk-63FNZTWG.js";
170
177
  import {
178
+ AgentOutputMessageCapture,
171
179
  DEFAULT_OTLP_ENDPOINT,
172
180
  DEFAULT_TELEMETRY_TARGET,
181
+ addAgentInputMessageAttributes,
182
+ addDaemonRequestAttribute,
173
183
  addToolArgumentsAttributes,
174
184
  addToolCallResultAttributes,
175
185
  addUserPromptAttributes
176
- } from "./chunk-O5AZPHYZ.js";
186
+ } from "./chunk-K34GJQOZ.js";
177
187
  import {
178
188
  supportsOpenAIPrefixCaching
179
189
  } from "./chunk-SAH4BD2J.js";
180
190
  import {
181
191
  DashScopeOpenAICompatibleProvider,
182
192
  selectDashScopeThinkingKnob
183
- } from "./chunk-5PWLQ7SK.js";
193
+ } from "./chunk-KLOMACIR.js";
184
194
  import {
185
195
  childLaunchDepth,
186
196
  getCurrentAgentDepth,
@@ -191,7 +201,7 @@ import {
191
201
  runWithAgentContext,
192
202
  runWithRuntimeContentGenerator,
193
203
  spawnBlockReason
194
- } from "./chunk-EYS3GGM3.js";
204
+ } from "./chunk-VPV7WBVT.js";
195
205
  import {
196
206
  getTeammateContext,
197
207
  isTeammate,
@@ -201,6 +211,92 @@ import {
201
211
  InvalidStreamError,
202
212
  getThoughtSummary
203
213
  } from "./chunk-2J3OJGTL.js";
214
+ import {
215
+ BUBBLE_APPROVAL_MODE,
216
+ FORK_AGENT,
217
+ FORK_DEFAULT_MAX_TURNS,
218
+ FORK_PLACEHOLDER_RESULT,
219
+ FORK_SUBAGENT_TYPE,
220
+ SubagentError,
221
+ SubagentErrorCode,
222
+ buildAvailableSkillsReminder,
223
+ buildChangedAgentsReminder,
224
+ buildChangedMcpToolsReminder,
225
+ buildChangedSkillsReminder,
226
+ buildChildMessage,
227
+ buildDeferredToolsReminder,
228
+ buildForkExecutionAllowlist,
229
+ buildForkedMessages,
230
+ buildFunctionResponseParts,
231
+ buildMcpServerInstructionsReminder,
232
+ buildPinnedWorktreeNotice,
233
+ buildWorktreeNotice,
234
+ formatDateForContext,
235
+ getDirectoryContextString,
236
+ getFolderStructure,
237
+ getInitialChatHistory,
238
+ getStartupContextLength,
239
+ isSystemReminderContent,
240
+ normalizeForkTurns,
241
+ registerForkDisplayImageForCache,
242
+ resolveForkExecutionAllowedTools,
243
+ runInForkContext,
244
+ selectForkHistory,
245
+ stripSystemReminderBlocks,
246
+ validateForkToolList
247
+ } from "./chunk-TTRH3RTQ.js";
248
+ import {
249
+ collectAvailableSkillEntries,
250
+ renderAvailableSkillsBlock
251
+ } from "./chunk-K623ENWT.js";
252
+ import {
253
+ escapeSystemReminderTags,
254
+ escapeXml
255
+ } from "./chunk-AQ37AY7B.js";
256
+ import {
257
+ DEFAULT_FILE_FILTERING_OPTIONS,
258
+ DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES,
259
+ QwenIgnoreParser,
260
+ WorkspaceContext,
261
+ formatQwenIgnoreFileNames,
262
+ getQwenIgnoreFileNames,
263
+ isPathWithinRoot,
264
+ require_ignore
265
+ } from "./chunk-FRHQQC2Z.js";
266
+ import {
267
+ openBrowserSecurely,
268
+ shouldAttemptBrowserLaunch
269
+ } from "./chunk-NAVJD2PQ.js";
270
+ import {
271
+ isUnattendedMode,
272
+ retryWithBackoff
273
+ } from "./chunk-2ZWH53I4.js";
274
+ import {
275
+ classifyRetryError,
276
+ isFallbackEligible
277
+ } from "./chunk-TB4YFWXG.js";
278
+ import {
279
+ QUOTA_EXHAUSTED_PREFIX,
280
+ formatQuotaExhaustedMessage,
281
+ getRateLimitErrorDetails,
282
+ getRateLimitRetryDelayMs,
283
+ isApiError,
284
+ isQuotaExhaustedError,
285
+ isRateLimitError,
286
+ isStructuredError
287
+ } from "./chunk-D7QGE3RT.js";
288
+ import {
289
+ DEFAULT_OPENAI_BASE_URL
290
+ } from "./chunk-AXMWHKXA.js";
291
+ import {
292
+ getToolCallPreparations,
293
+ setToolCallPreparations
294
+ } from "./chunk-GLCZKT5V.js";
295
+ import {
296
+ combineAbortSignals,
297
+ createAbortController,
298
+ createChildAbortController
299
+ } from "./chunk-DJ2GSRLV.js";
204
300
  import {
205
301
  ApiRetryEvent,
206
302
  COMBINED_PASS_TOLERANCE_FACTOR,
@@ -318,7 +414,7 @@ import {
318
414
  updateMCPServerStatus,
319
415
  writeLine,
320
416
  writeLineSync
321
- } from "./chunk-HB6QW4LM.js";
417
+ } from "./chunk-4KM2SYK5.js";
322
418
  import {
323
419
  defaultModalities,
324
420
  isTieredEffortWireModel
@@ -347,65 +443,13 @@ import {
347
443
  isManagedMemoryPath,
348
444
  isTeamAutoMemPath,
349
445
  isUserAutoMemPath
350
- } from "./chunk-732MOPEM.js";
446
+ } from "./chunk-G6MUFRNI.js";
351
447
  import {
352
448
  runSideQuery
353
- } from "./chunk-CTQE2NB2.js";
449
+ } from "./chunk-LSRI3ND3.js";
354
450
  import {
355
451
  STRUCTURED_OUTPUT_REDACTED_ARGS
356
- } from "./chunk-IEP44U2R.js";
357
- import {
358
- BUBBLE_APPROVAL_MODE,
359
- FORK_AGENT,
360
- FORK_DEFAULT_MAX_TURNS,
361
- FORK_PLACEHOLDER_RESULT,
362
- FORK_SUBAGENT_TYPE,
363
- SubagentError,
364
- SubagentErrorCode,
365
- buildAvailableSkillsReminder,
366
- buildChangedAgentsReminder,
367
- buildChangedMcpToolsReminder,
368
- buildChangedSkillsReminder,
369
- buildChildMessage,
370
- buildDeferredToolsReminder,
371
- buildForkExecutionAllowlist,
372
- buildForkedMessages,
373
- buildFunctionResponseParts,
374
- buildMcpServerInstructionsReminder,
375
- buildPinnedWorktreeNotice,
376
- buildWorktreeNotice,
377
- formatDateForContext,
378
- getDirectoryContextString,
379
- getFolderStructure,
380
- getInitialChatHistory,
381
- getStartupContextLength,
382
- isSystemReminderContent,
383
- normalizeForkTurns,
384
- registerForkDisplayImageForCache,
385
- resolveForkExecutionAllowedTools,
386
- runInForkContext,
387
- selectForkHistory,
388
- stripSystemReminderBlocks,
389
- validateForkToolList
390
- } from "./chunk-ZV4XVYL3.js";
391
- import {
392
- collectAvailableSkillEntries,
393
- renderAvailableSkillsBlock
394
- } from "./chunk-K623ENWT.js";
395
- import {
396
- escapeSystemReminderTags,
397
- escapeXml
398
- } from "./chunk-AQ37AY7B.js";
399
- import {
400
- DEFAULT_FILE_FILTERING_OPTIONS,
401
- DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES,
402
- QwenIgnoreParser,
403
- WorkspaceContext,
404
- formatQwenIgnoreFileNames,
405
- getQwenIgnoreFileNames,
406
- isPathWithinRoot,
407
- require_ignore
408
- } from "./chunk-V3LXMASR.js";
452
+ } from "./chunk-PVXEJB66.js";
409
453
  import {
410
454
  AgentStatistics,
411
455
  BaseDeclarativeTool,
@@ -424,29 +468,7 @@ import {
424
468
  require_dist,
425
469
  require_fast_deep_equal,
426
470
  require_fast_uri
427
- } from "./chunk-XTH2OMDS.js";
428
- import {
429
- openBrowserSecurely,
430
- shouldAttemptBrowserLaunch
431
- } from "./chunk-NAVJD2PQ.js";
432
- import {
433
- isUnattendedMode,
434
- retryWithBackoff
435
- } from "./chunk-EYW54TBD.js";
436
- import {
437
- classifyRetryError,
438
- isFallbackEligible
439
- } from "./chunk-O4BBDP2G.js";
440
- import {
441
- QUOTA_EXHAUSTED_PREFIX,
442
- formatQuotaExhaustedMessage,
443
- getRateLimitErrorDetails,
444
- getRateLimitRetryDelayMs,
445
- isApiError,
446
- isQuotaExhaustedError,
447
- isRateLimitError,
448
- isStructuredError
449
- } from "./chunk-KPVVWKF3.js";
471
+ } from "./chunk-YIGGWOJE.js";
450
472
  import {
451
473
  AUTH_ENV_MAPPINGS,
452
474
  AuthType,
@@ -458,24 +480,11 @@ import {
458
480
  createContentGenerator,
459
481
  resetPreloadedContentGenerator,
460
482
  resolveContentGeneratorConfigWithSources
461
- } from "./chunk-XWUQ4IH5.js";
483
+ } from "./chunk-KWX56CHZ.js";
462
484
  import {
463
485
  DEFAULT_QWEN_EMBEDDING_MODEL,
464
486
  DEFAULT_QWEN_MODEL
465
487
  } from "./chunk-F6WFNA7U.js";
466
- import {
467
- atomicWriteFile,
468
- atomicWriteFileSync,
469
- atomicWriteJSON,
470
- renameWithRetry
471
- } from "./chunk-F6AOBFUN.js";
472
- import {
473
- DEFAULT_OPENAI_BASE_URL
474
- } from "./chunk-AXMWHKXA.js";
475
- import {
476
- getToolCallPreparations,
477
- setToolCallPreparations
478
- } from "./chunk-GLCZKT5V.js";
479
488
  import {
480
489
  normalizeMcpToolName,
481
490
  sanitizeToolNameForProvider
@@ -489,18 +498,19 @@ import {
489
498
  parsePositiveIntegerEnvValue,
490
499
  tokenLimit
491
500
  } from "./chunk-FPGTNKCP.js";
492
- import {
493
- combineAbortSignals,
494
- createAbortController,
495
- createChildAbortController
496
- } from "./chunk-DJ2GSRLV.js";
497
501
  import {
498
502
  getOrCreateMcpDispatcher,
499
503
  loadUndici,
500
504
  preloadRuntimeFetchModule,
501
505
  redactProxyError,
502
506
  setResolvedProxyUrlForRuntimeFetch
503
- } from "./chunk-EFIMD5VA.js";
507
+ } from "./chunk-4AOVQPJU.js";
508
+ import {
509
+ atomicWriteFile,
510
+ atomicWriteFileSync,
511
+ atomicWriteJSON,
512
+ renameWithRetry
513
+ } from "./chunk-YBHUXEC6.js";
504
514
  import {
505
515
  endHookSpan,
506
516
  endInteractionSpan,
@@ -510,10 +520,14 @@ import {
510
520
  endToolSpan,
511
521
  getActiveInteractionSpan,
512
522
  initializeTelemetry,
523
+ isBinary,
513
524
  isPerformanceMonitoringActive,
514
525
  isTelemetrySdkInitialized,
526
+ normalizeContent,
515
527
  recordCpuUsage,
528
+ recordInteractionActivity,
516
529
  recordMemoryUsage,
530
+ redactUrlCredentials,
517
531
  refreshSessionContext,
518
532
  runInSubagentSpanContext,
519
533
  runInToolSpanContext,
@@ -525,8 +539,9 @@ import {
525
539
  startToolBlockedOnUserSpan,
526
540
  startToolExecutionSpan,
527
541
  startToolSpan,
542
+ stripAnsiAndControl,
528
543
  truncateSpanError
529
- } from "./chunk-E5BWLU5J.js";
544
+ } from "./chunk-N4SVADAV.js";
530
545
  import {
531
546
  safeJsonStringify
532
547
  } from "./chunk-HHJLM3WQ.js";
@@ -546,8 +561,15 @@ import {
546
561
  TOOL_FAILURE_KIND_TIMEOUT,
547
562
  TOOL_FAILURE_KIND_TOOL_ERROR,
548
563
  TOOL_FAILURE_KIND_TOOL_EXCEPTION,
549
- isValidSensitiveSpanAttributeMaxLength
550
- } from "./chunk-L2GTEEEU.js";
564
+ getSessionModel,
565
+ getSessionProjectDir,
566
+ isValidSensitiveSpanAttributeMaxLength,
567
+ registerSessionModel,
568
+ registerSessionProjectDir,
569
+ sessionIdContext,
570
+ unregisterSessionModel,
571
+ unregisterSessionProjectDir
572
+ } from "./chunk-K5IDV3PC.js";
551
573
  import {
552
574
  FatalConfigError,
553
575
  PATH_ARG_KEYS,
@@ -561,6 +583,7 @@ import {
561
583
  formatTraceparent,
562
584
  getErrorMessage,
563
585
  getErrorStatus,
586
+ getErrorType,
564
587
  getProjectHash,
565
588
  getTraceContext,
566
589
  isAbortError,
@@ -576,7 +599,7 @@ import {
576
599
  tildeifyPath,
577
600
  toFriendlyError,
578
601
  unescapePath
579
- } from "./chunk-MPBRV3UU.js";
602
+ } from "./chunk-HOSVOUDK.js";
580
603
  import {
581
604
  require_src
582
605
  } from "./chunk-AMDSOFFV.js";
@@ -21328,6 +21351,13 @@ var getGitBranch = /* @__PURE__ */ __name((cwd) => {
21328
21351
  return void 0;
21329
21352
  }
21330
21353
  }, "getGitBranch");
21354
+ var gitBranchCache = /* @__PURE__ */ new Map();
21355
+ var getCachedGitBranch = /* @__PURE__ */ __name((cwd) => {
21356
+ if (gitBranchCache.has(cwd)) return gitBranchCache.get(cwd);
21357
+ const branch = getGitBranch(cwd);
21358
+ gitBranchCache.set(cwd, branch);
21359
+ return branch;
21360
+ }, "getCachedGitBranch");
21331
21361
  var getGitRepoName = /* @__PURE__ */ __name((cwd) => {
21332
21362
  try {
21333
21363
  const remoteUrl = execSync("git remote get-url origin", {
@@ -26558,6 +26588,46 @@ var FileHistoryService = class {
26558
26588
  }
26559
26589
  };
26560
26590
 
26591
+ // packages/core/src/services/session-file-history-state.ts
26592
+ init_esbuild_shims();
26593
+ var SessionFileHistoryAccumulator = class {
26594
+ static {
26595
+ __name(this, "SessionFileHistoryAccumulator");
26596
+ }
26597
+ seenPromptIds = /* @__PURE__ */ new Set();
26598
+ retainedPromptIds = [];
26599
+ snapshotsByPromptId = /* @__PURE__ */ new Map();
26600
+ add(record2) {
26601
+ if (record2.type !== "system" || record2.subtype !== "file_history_snapshot" || !record2.systemPayload) {
26602
+ return;
26603
+ }
26604
+ const payload = record2.systemPayload;
26605
+ if (!Array.isArray(payload.snapshots)) return;
26606
+ const deserialized = deserializeSnapshots(payload.snapshots);
26607
+ for (const snapshot of deserialized) {
26608
+ if (this.seenPromptIds.has(snapshot.promptId)) {
26609
+ if (this.snapshotsByPromptId.has(snapshot.promptId)) {
26610
+ this.snapshotsByPromptId.set(snapshot.promptId, snapshot);
26611
+ }
26612
+ continue;
26613
+ }
26614
+ this.seenPromptIds.add(snapshot.promptId);
26615
+ this.retainedPromptIds.push(snapshot.promptId);
26616
+ this.snapshotsByPromptId.set(snapshot.promptId, snapshot);
26617
+ if (this.retainedPromptIds.length > MAX_SNAPSHOTS) {
26618
+ const evictedPromptId = this.retainedPromptIds.shift();
26619
+ this.snapshotsByPromptId.delete(evictedPromptId);
26620
+ }
26621
+ }
26622
+ }
26623
+ finish() {
26624
+ const snapshots = this.retainedPromptIds.map(
26625
+ (promptId) => this.snapshotsByPromptId.get(promptId)
26626
+ );
26627
+ return snapshots.length > 0 ? snapshots : void 0;
26628
+ }
26629
+ };
26630
+
26561
26631
  // packages/core/src/utils/runtimeStatus.ts
26562
26632
  init_esbuild_shims();
26563
26633
  import * as fs7 from "node:fs/promises";
@@ -26910,42 +26980,21 @@ function readLastJsonStringFieldsSync(filePath, primaryKey, otherKeys, lineConta
26910
26980
  }
26911
26981
  }
26912
26982
  __name(readLastJsonStringFieldsSync, "readLastJsonStringFieldsSync");
26913
-
26914
- // packages/core/src/services/tokenEstimation.ts
26915
- init_esbuild_shims();
26916
- var CHARS_PER_TOKEN = TOKEN_TO_CHAR_RATIO;
26917
- function estimateContentTokens(contents, imageTokenEstimate = DEFAULT_IMAGE_TOKEN_ESTIMATE) {
26918
- let totalChars = 0;
26919
- for (const content of contents) {
26920
- totalChars += estimateContentChars(content, imageTokenEstimate);
26921
- }
26922
- return Math.ceil(totalChars / CHARS_PER_TOKEN);
26923
- }
26924
- __name(estimateContentTokens, "estimateContentTokens");
26925
- var CONSERVATIVE_NEW_CONTENT_SAFETY_FACTOR = 1.5;
26926
- function estimatePromptTokens(history, userMessage, lastPromptTokenCount, lastOutputTokenCount = 0, imageTokenEstimate = DEFAULT_IMAGE_TOKEN_ESTIMATE, conservative = false) {
26927
- if (lastPromptTokenCount > 0) {
26928
- const newContentTokens = estimateContentTokens(
26929
- [userMessage],
26930
- imageTokenEstimate
26931
- );
26932
- return lastPromptTokenCount + lastOutputTokenCount + (conservative ? Math.ceil(newContentTokens * CONSERVATIVE_NEW_CONTENT_SAFETY_FACTOR) : newContentTokens);
26933
- }
26934
- return estimateContentTokens([...history, userMessage], imageTokenEstimate);
26935
- }
26936
- __name(estimatePromptTokens, "estimatePromptTokens");
26937
- function getUsageOutputTokenCountForPromptEstimate(usage) {
26938
- if (usage?.promptTokenCount === void 0) {
26939
- return 0;
26940
- }
26941
- if (usage.totalTokenCount !== void 0) {
26942
- return Math.max(0, usage.totalTokenCount - usage.promptTokenCount);
26943
- }
26944
- const candidates = Math.max(0, usage.candidatesTokenCount ?? 0);
26945
- const thoughts = Math.max(0, usage.thoughtsTokenCount ?? 0);
26946
- return candidates > thoughts ? candidates : candidates + thoughts;
26983
+ function readSessionTitleInfoFromFileSync(filePath, scratchBuffer) {
26984
+ const hit = readLastJsonStringFieldsSync(
26985
+ filePath,
26986
+ "customTitle",
26987
+ ["titleSource"],
26988
+ '"subtype":"custom_title"',
26989
+ scratchBuffer
26990
+ );
26991
+ const title = hit["customTitle"];
26992
+ if (!title) return {};
26993
+ const rawSource = hit["titleSource"];
26994
+ const source = rawSource === "auto" || rawSource === "manual" ? rawSource : void 0;
26995
+ return { title, source };
26947
26996
  }
26948
- __name(getUsageOutputTokenCountForPromptEstimate, "getUsageOutputTokenCountForPromptEstimate");
26997
+ __name(readSessionTitleInfoFromFileSync, "readSessionTitleInfoFromFileSync");
26949
26998
 
26950
26999
  // packages/core/src/services/session-artifact-persistence.ts
26951
27000
  init_esbuild_shims();
@@ -26971,6 +27020,52 @@ function isSessionArtifactRecord(record2) {
26971
27020
  return isTranscriptArtifactRecord(record2);
26972
27021
  }
26973
27022
  __name(isSessionArtifactRecord, "isSessionArtifactRecord");
27023
+ function selectActiveSideArtifactRecordUuids(records, activeRecordUuids) {
27024
+ const activeUuids = new Set(activeRecordUuids);
27025
+ const firstActiveUuid = activeRecordUuids[0];
27026
+ const firstActiveIndex = firstActiveUuid === void 0 ? -1 : records.findIndex((record2) => record2.uuid === firstActiveUuid);
27027
+ const nextActiveUuidByIndex = /* @__PURE__ */ new Map();
27028
+ const nextBlockingUuidByIndex = /* @__PURE__ */ new Map();
27029
+ let nextActiveUuid;
27030
+ let nextBlockingUuid;
27031
+ for (let index = records.length - 1; index >= 0; index--) {
27032
+ if (nextActiveUuid !== void 0) {
27033
+ nextActiveUuidByIndex.set(index, nextActiveUuid);
27034
+ }
27035
+ if (nextBlockingUuid !== void 0) {
27036
+ nextBlockingUuidByIndex.set(index, nextBlockingUuid);
27037
+ }
27038
+ const record2 = records[index];
27039
+ if (activeUuids.has(record2.uuid)) {
27040
+ nextActiveUuid = record2.uuid;
27041
+ nextBlockingUuid = void 0;
27042
+ } else if (!isSessionArtifactRecord(record2) && !(record2.type === "system" && record2.subtype === "custom_title")) {
27043
+ nextBlockingUuid = record2.uuid;
27044
+ }
27045
+ }
27046
+ const selected = [];
27047
+ const includedSideArtifactUuids = /* @__PURE__ */ new Set();
27048
+ let previousActiveUuid;
27049
+ for (let index = 0; index < records.length; index++) {
27050
+ const record2 = records[index];
27051
+ if (activeUuids.has(record2.uuid)) {
27052
+ previousActiveUuid = record2.uuid;
27053
+ continue;
27054
+ }
27055
+ if (!isSessionArtifactRecord(record2)) continue;
27056
+ const nextUuid = nextActiveUuidByIndex.get(index);
27057
+ const isInActiveSegment = !nextBlockingUuidByIndex.has(index) && (nextUuid !== void 0 ? activeUuids.has(nextUuid) : previousActiveUuid !== void 0 && activeUuids.has(previousActiveUuid));
27058
+ if (record2.parentUuid !== null && (activeUuids.has(record2.parentUuid) || includedSideArtifactUuids.has(record2.parentUuid)) && isInActiveSegment && (record2.parentUuid === previousActiveUuid || includedSideArtifactUuids.has(record2.parentUuid))) {
27059
+ selected.push(record2.uuid);
27060
+ includedSideArtifactUuids.add(record2.uuid);
27061
+ } else if (record2.parentUuid === null && index < firstActiveIndex && isInActiveSegment) {
27062
+ selected.push(record2.uuid);
27063
+ includedSideArtifactUuids.add(record2.uuid);
27064
+ }
27065
+ }
27066
+ return selected;
27067
+ }
27068
+ __name(selectActiveSideArtifactRecordUuids, "selectActiveSideArtifactRecordUuids");
26974
27069
  function stableSessionArtifactId(sessionId, identityKey) {
26975
27070
  return createHash2("sha256").update(`${sessionId}:${identityKey}`).digest("hex").slice(0, 16);
26976
27071
  }
@@ -26982,75 +27077,87 @@ function sessionArtifactIdentityKey(artifact) {
26982
27077
  return void 0;
26983
27078
  }
26984
27079
  __name(sessionArtifactIdentityKey, "sessionArtifactIdentityKey");
26985
- function rebuildSessionArtifactSnapshot(records, fallbackSessionId) {
26986
- const artifacts = /* @__PURE__ */ new Map();
26987
- const tombstonedIds = /* @__PURE__ */ new Set();
26988
- const stickyEphemeralIds = /* @__PURE__ */ new Set();
26989
- const markerArtifacts = /* @__PURE__ */ new Map();
26990
- const warnings = [];
26991
- let sequence = 0;
26992
- let lastSnapshotSequence = 0;
26993
- let sessionId = fallbackSessionId;
26994
- let sawRecord = false;
26995
- for (const record2 of records) {
26996
- if (!isSessionArtifactRecord(record2)) continue;
27080
+ var SessionArtifactSnapshotAccumulator = class {
27081
+ static {
27082
+ __name(this, "SessionArtifactSnapshotAccumulator");
27083
+ }
27084
+ artifacts = /* @__PURE__ */ new Map();
27085
+ tombstonedIds = /* @__PURE__ */ new Set();
27086
+ stickyEphemeralIds = /* @__PURE__ */ new Set();
27087
+ markerArtifacts = /* @__PURE__ */ new Map();
27088
+ warnings = [];
27089
+ sequence = 0;
27090
+ lastSnapshotSequence = 0;
27091
+ sessionId;
27092
+ sawRecord = false;
27093
+ constructor(fallbackSessionId) {
27094
+ this.sessionId = fallbackSessionId;
27095
+ }
27096
+ add(record2) {
27097
+ if (!isSessionArtifactRecord(record2)) return;
26997
27098
  if (record2.subtype === "session_artifact_snapshot") {
26998
- const payload2 = normalizeSnapshotPayload(record2.systemPayload, warnings);
26999
- if (!payload2) continue;
27000
- sawRecord = true;
27001
- sessionId = payload2.sessionId;
27002
- sequence = Math.max(sequence, payload2.sequence);
27003
- lastSnapshotSequence = payload2.sequence;
27004
- artifacts.clear();
27005
- tombstonedIds.clear();
27006
- stickyEphemeralIds.clear();
27007
- markerArtifacts.clear();
27008
- for (const id of payload2.tombstonedIds ?? []) tombstonedIds.add(id);
27099
+ const payload2 = normalizeSnapshotPayload(
27100
+ record2.systemPayload,
27101
+ this.warnings
27102
+ );
27103
+ if (!payload2) return;
27104
+ this.sawRecord = true;
27105
+ this.sessionId = payload2.sessionId;
27106
+ this.sequence = Math.max(this.sequence, payload2.sequence);
27107
+ this.lastSnapshotSequence = payload2.sequence;
27108
+ this.artifacts.clear();
27109
+ this.tombstonedIds.clear();
27110
+ this.stickyEphemeralIds.clear();
27111
+ this.markerArtifacts.clear();
27112
+ for (const id of payload2.tombstonedIds ?? []) this.tombstonedIds.add(id);
27009
27113
  for (const id of payload2.stickyEphemeralIds ?? []) {
27010
- stickyEphemeralIds.add(id);
27114
+ this.stickyEphemeralIds.add(id);
27011
27115
  }
27012
- const markerIds = /* @__PURE__ */ new Set([...tombstonedIds, ...stickyEphemeralIds]);
27116
+ const markerIds = /* @__PURE__ */ new Set([
27117
+ ...this.tombstonedIds,
27118
+ ...this.stickyEphemeralIds
27119
+ ]);
27013
27120
  for (const artifact of payload2.markerArtifacts ?? []) {
27014
27121
  if (markerIds.has(artifact.id)) {
27015
- markerArtifacts.set(artifact.id, artifact);
27122
+ this.markerArtifacts.set(artifact.id, artifact);
27016
27123
  }
27017
27124
  }
27018
27125
  for (const artifact of payload2.artifacts) {
27019
27126
  if (artifact.retention === "ephemeral") continue;
27020
- artifacts.set(artifact.id, artifact);
27021
- markerArtifacts.delete(artifact.id);
27127
+ this.artifacts.set(artifact.id, artifact);
27128
+ this.markerArtifacts.delete(artifact.id);
27022
27129
  }
27023
- continue;
27130
+ return;
27024
27131
  }
27025
- const payload = normalizeEventPayload(record2.systemPayload, warnings);
27026
- if (!payload) continue;
27027
- sawRecord = true;
27028
- sessionId = payload.sessionId;
27029
- if (payload.sequence <= lastSnapshotSequence) {
27030
- warnings.push(
27031
- `skipped stale event sequence ${payload.sequence} at or before snapshot sequence ${lastSnapshotSequence}`
27132
+ const payload = normalizeEventPayload(record2.systemPayload, this.warnings);
27133
+ if (!payload) return;
27134
+ this.sawRecord = true;
27135
+ this.sessionId = payload.sessionId;
27136
+ if (payload.sequence <= this.lastSnapshotSequence) {
27137
+ this.warnings.push(
27138
+ `skipped stale event sequence ${payload.sequence} at or before snapshot sequence ${this.lastSnapshotSequence}`
27032
27139
  );
27033
- continue;
27140
+ return;
27034
27141
  }
27035
- sequence = Math.max(sequence, payload.sequence);
27142
+ this.sequence = Math.max(this.sequence, payload.sequence);
27036
27143
  for (const change of payload.changes) {
27037
27144
  if (change.action === "removed") {
27038
- artifacts.delete(change.artifactId);
27145
+ this.artifacts.delete(change.artifactId);
27039
27146
  if (change.reason === "explicit") {
27040
- tombstonedIds.add(change.artifactId);
27041
- stickyEphemeralIds.delete(change.artifactId);
27147
+ this.tombstonedIds.add(change.artifactId);
27148
+ this.stickyEphemeralIds.delete(change.artifactId);
27042
27149
  if (change.artifact) {
27043
- markerArtifacts.set(change.artifactId, change.artifact);
27150
+ this.markerArtifacts.set(change.artifactId, change.artifact);
27044
27151
  }
27045
27152
  }
27046
27153
  if (change.reason === "eviction") {
27047
- stickyEphemeralIds.delete(change.artifactId);
27048
- markerArtifacts.delete(change.artifactId);
27154
+ this.stickyEphemeralIds.delete(change.artifactId);
27155
+ this.markerArtifacts.delete(change.artifactId);
27049
27156
  }
27050
27157
  if (change.reason === "unpin_to_ephemeral") {
27051
- stickyEphemeralIds.add(change.artifactId);
27158
+ this.stickyEphemeralIds.add(change.artifactId);
27052
27159
  if (change.artifact) {
27053
- markerArtifacts.set(change.artifactId, change.artifact);
27160
+ this.markerArtifacts.set(change.artifactId, change.artifact);
27054
27161
  }
27055
27162
  }
27056
27163
  continue;
@@ -27058,25 +27165,30 @@ function rebuildSessionArtifactSnapshot(records, fallbackSessionId) {
27058
27165
  if (!change.artifact || change.artifact.retention === "ephemeral") {
27059
27166
  continue;
27060
27167
  }
27061
- artifacts.set(change.artifact.id, change.artifact);
27062
- tombstonedIds.delete(change.artifact.id);
27063
- stickyEphemeralIds.delete(change.artifact.id);
27064
- markerArtifacts.delete(change.artifact.id);
27168
+ this.artifacts.set(change.artifact.id, change.artifact);
27169
+ this.tombstonedIds.delete(change.artifact.id);
27170
+ this.stickyEphemeralIds.delete(change.artifact.id);
27171
+ this.markerArtifacts.delete(change.artifact.id);
27065
27172
  }
27066
27173
  }
27067
- if (!sawRecord || !sessionId) {
27068
- return void 0;
27174
+ finish() {
27175
+ if (!this.sawRecord || !this.sessionId) return void 0;
27176
+ return {
27177
+ v: SESSION_ARTIFACT_PERSISTENCE_VERSION,
27178
+ sessionId: this.sessionId,
27179
+ sequence: this.sequence,
27180
+ artifacts: Array.from(this.artifacts.values()),
27181
+ tombstonedIds: Array.from(this.tombstonedIds),
27182
+ stickyEphemeralIds: Array.from(this.stickyEphemeralIds),
27183
+ ...this.markerArtifacts.size > 0 ? { markerArtifacts: Array.from(this.markerArtifacts.values()) } : {},
27184
+ warnings: this.warnings
27185
+ };
27069
27186
  }
27070
- return {
27071
- v: SESSION_ARTIFACT_PERSISTENCE_VERSION,
27072
- sessionId,
27073
- sequence,
27074
- artifacts: Array.from(artifacts.values()),
27075
- tombstonedIds: Array.from(tombstonedIds),
27076
- stickyEphemeralIds: Array.from(stickyEphemeralIds),
27077
- ...markerArtifacts.size > 0 ? { markerArtifacts: Array.from(markerArtifacts.values()) } : {},
27078
- warnings
27079
- };
27187
+ };
27188
+ function rebuildSessionArtifactSnapshot(records, fallbackSessionId) {
27189
+ const accumulator = new SessionArtifactSnapshotAccumulator(fallbackSessionId);
27190
+ for (const record2 of records) accumulator.add(record2);
27191
+ return accumulator.finish();
27080
27192
  }
27081
27193
  __name(rebuildSessionArtifactSnapshot, "rebuildSessionArtifactSnapshot");
27082
27194
  function remapSessionArtifactPayloadForFork(payload, sourceSessionId, newSessionId, remappedArtifactIds = /* @__PURE__ */ new Map()) {
@@ -28177,6 +28289,291 @@ import * as crypto from "node:crypto";
28177
28289
  import * as fs10 from "node:fs";
28178
28290
  import * as fsp from "node:fs/promises";
28179
28291
  import * as path10 from "node:path";
28292
+ import { performance as performance3 } from "node:perf_hooks";
28293
+
28294
+ // packages/core/src/services/session-api-history.ts
28295
+ init_esbuild_shims();
28296
+ function stripThoughtsFromContent(content) {
28297
+ if (!content.parts) return content;
28298
+ const filteredParts = content.parts.filter((part) => !part.thought);
28299
+ if (filteredParts.length === 0) return null;
28300
+ return { ...content, parts: filteredParts };
28301
+ }
28302
+ __name(stripThoughtsFromContent, "stripThoughtsFromContent");
28303
+ function copyContentForApiHistory(content) {
28304
+ return {
28305
+ ...content,
28306
+ parts: content.parts?.map((part) => {
28307
+ if ("functionCall" in part && part.functionCall) {
28308
+ return {
28309
+ ...part,
28310
+ functionCall: {
28311
+ ...part.functionCall,
28312
+ args: part.functionCall.args ? { ...part.functionCall.args } : part.functionCall.args
28313
+ }
28314
+ };
28315
+ }
28316
+ if ("functionResponse" in part && part.functionResponse) {
28317
+ return {
28318
+ ...part,
28319
+ functionResponse: { ...part.functionResponse }
28320
+ };
28321
+ }
28322
+ return { ...part };
28323
+ })
28324
+ };
28325
+ }
28326
+ __name(copyContentForApiHistory, "copyContentForApiHistory");
28327
+ function appendApiHistoryRecord(history, record2) {
28328
+ if (!record2.message || record2.subtype === "realtime_message") return;
28329
+ const message = copyContentForApiHistory(record2.message);
28330
+ if (record2.subtype === "mid_turn_user_message") {
28331
+ const previous = history.at(-1);
28332
+ if (previous?.role === "user") {
28333
+ previous.parts = [...previous.parts ?? [], ...message.parts ?? []];
28334
+ return;
28335
+ }
28336
+ }
28337
+ history.push(message);
28338
+ }
28339
+ __name(appendApiHistoryRecord, "appendApiHistoryRecord");
28340
+ var SessionApiHistoryAccumulator = class {
28341
+ static {
28342
+ __name(this, "SessionApiHistoryAccumulator");
28343
+ }
28344
+ history = [];
28345
+ compressionCandidate;
28346
+ add(record2) {
28347
+ if (record2.type === "system") {
28348
+ if (!isApiHistoryCompressionCandidate(record2)) return;
28349
+ const payload = record2.systemPayload;
28350
+ this.compressionCandidate = payload.compressedHistory;
28351
+ this.history = Array.isArray(payload.compressedHistory) ? payload.compressedHistory.map(copyContentForApiHistory) : [];
28352
+ return;
28353
+ }
28354
+ if (this.compressionCandidate !== void 0 && !Array.isArray(this.compressionCandidate)) {
28355
+ return;
28356
+ }
28357
+ appendApiHistoryRecord(this.history, record2);
28358
+ }
28359
+ finish(options2 = {}) {
28360
+ if (this.compressionCandidate !== void 0 && !Array.isArray(this.compressionCandidate)) {
28361
+ return this.compressionCandidate.map(
28362
+ copyContentForApiHistory
28363
+ );
28364
+ }
28365
+ if (!options2.stripThoughtsFromHistory) return this.history;
28366
+ return this.history.map(stripThoughtsFromContent).filter((content) => content !== null);
28367
+ }
28368
+ };
28369
+ function isApiHistoryCompressionCandidate(record2) {
28370
+ if (record2.type !== "system" || record2.subtype !== "chat_compression") {
28371
+ return false;
28372
+ }
28373
+ const payload = record2.systemPayload;
28374
+ return Boolean(payload?.compressedHistory);
28375
+ }
28376
+ __name(isApiHistoryCompressionCandidate, "isApiHistoryCompressionCandidate");
28377
+ function buildApiHistoryFromConversation(conversation, options2 = {}) {
28378
+ const accumulator = new SessionApiHistoryAccumulator();
28379
+ for (const record2 of conversation.messages) accumulator.add(record2);
28380
+ return accumulator.finish(options2);
28381
+ }
28382
+ __name(buildApiHistoryFromConversation, "buildApiHistoryFromConversation");
28383
+
28384
+ // packages/core/src/services/session-resume-token-counts.ts
28385
+ init_esbuild_shims();
28386
+
28387
+ // packages/core/src/services/tokenEstimation.ts
28388
+ init_esbuild_shims();
28389
+ var CHARS_PER_TOKEN = TOKEN_TO_CHAR_RATIO;
28390
+ function estimateContentTokens(contents, imageTokenEstimate = DEFAULT_IMAGE_TOKEN_ESTIMATE) {
28391
+ let totalChars = 0;
28392
+ for (const content of contents) {
28393
+ totalChars += estimateContentChars(content, imageTokenEstimate);
28394
+ }
28395
+ return Math.ceil(totalChars / CHARS_PER_TOKEN);
28396
+ }
28397
+ __name(estimateContentTokens, "estimateContentTokens");
28398
+ var CONSERVATIVE_NEW_CONTENT_SAFETY_FACTOR = 1.5;
28399
+ function estimatePromptTokens(history, userMessage, lastPromptTokenCount, lastOutputTokenCount = 0, imageTokenEstimate = DEFAULT_IMAGE_TOKEN_ESTIMATE, conservative = false) {
28400
+ if (lastPromptTokenCount > 0) {
28401
+ const newContentTokens = estimateContentTokens(
28402
+ [userMessage],
28403
+ imageTokenEstimate
28404
+ );
28405
+ return lastPromptTokenCount + lastOutputTokenCount + (conservative ? Math.ceil(newContentTokens * CONSERVATIVE_NEW_CONTENT_SAFETY_FACTOR) : newContentTokens);
28406
+ }
28407
+ return estimateContentTokens([...history, userMessage], imageTokenEstimate);
28408
+ }
28409
+ __name(estimatePromptTokens, "estimatePromptTokens");
28410
+ function getUsageOutputTokenCountForPromptEstimate(usage) {
28411
+ if (usage?.promptTokenCount === void 0) {
28412
+ return 0;
28413
+ }
28414
+ if (usage.totalTokenCount !== void 0) {
28415
+ return Math.max(0, usage.totalTokenCount - usage.promptTokenCount);
28416
+ }
28417
+ const candidates = Math.max(0, usage.candidatesTokenCount ?? 0);
28418
+ const thoughts = Math.max(0, usage.thoughtsTokenCount ?? 0);
28419
+ return candidates > thoughts ? candidates : candidates + thoughts;
28420
+ }
28421
+ __name(getUsageOutputTokenCountForPromptEstimate, "getUsageOutputTokenCountForPromptEstimate");
28422
+
28423
+ // packages/core/src/services/session-resume-token-counts.ts
28424
+ var ResumeTokenCountsAccumulator = class {
28425
+ static {
28426
+ __name(this, "ResumeTokenCountsAccumulator");
28427
+ }
28428
+ value;
28429
+ add(record2) {
28430
+ if (record2.type === "assistant") {
28431
+ const usage = record2.usageMetadata;
28432
+ const candidate = usage?.promptTokenCount ?? usage?.totalTokenCount;
28433
+ if (candidate) {
28434
+ this.value = {
28435
+ promptTokenCount: candidate,
28436
+ outputTokenCount: getUsageOutputTokenCountForPromptEstimate(usage),
28437
+ isEstimated: false
28438
+ };
28439
+ }
28440
+ return;
28441
+ }
28442
+ if (record2.type === "system" && record2.subtype === "chat_compression") {
28443
+ const payload = record2.systemPayload;
28444
+ if (payload?.info) {
28445
+ this.value = {
28446
+ promptTokenCount: payload.info.newTokenCount,
28447
+ outputTokenCount: 0,
28448
+ isEstimated: payload.info.newTokenCountIsEstimated ?? true
28449
+ };
28450
+ }
28451
+ }
28452
+ }
28453
+ finish() {
28454
+ return this.value;
28455
+ }
28456
+ };
28457
+ function isResumeTokenCountsCandidate(record2) {
28458
+ if (record2.type === "assistant") {
28459
+ const usage = record2.usageMetadata;
28460
+ return Boolean(usage?.promptTokenCount ?? usage?.totalTokenCount);
28461
+ }
28462
+ if (record2.type !== "system" || record2.subtype !== "chat_compression") {
28463
+ return false;
28464
+ }
28465
+ const payload = record2.systemPayload;
28466
+ return payload?.info !== void 0;
28467
+ }
28468
+ __name(isResumeTokenCountsCandidate, "isResumeTokenCountsCandidate");
28469
+ function getResumeTokenCounts(conversation) {
28470
+ const accumulator = new ResumeTokenCountsAccumulator();
28471
+ for (const record2 of conversation.messages) accumulator.add(record2);
28472
+ return accumulator.finish();
28473
+ }
28474
+ __name(getResumeTokenCounts, "getResumeTokenCounts");
28475
+
28476
+ // packages/core/src/services/session-turn-state.ts
28477
+ init_esbuild_shims();
28478
+ var SessionTurnStateAccumulator = class {
28479
+ constructor(sessionId) {
28480
+ this.sessionId = sessionId;
28481
+ }
28482
+ static {
28483
+ __name(this, "SessionTurnStateAccumulator");
28484
+ }
28485
+ maxPromptTurn = 0;
28486
+ userMessageCount = 0;
28487
+ turnParentUuids = [];
28488
+ backgroundNotificationTaskIds = /* @__PURE__ */ new Set();
28489
+ add(record2) {
28490
+ this.addHint(getSessionTurnRecordHint(record2, this.sessionId));
28491
+ }
28492
+ addHint(hint) {
28493
+ if (hint.countsAsUserPrompt) {
28494
+ this.userMessageCount += 1;
28495
+ }
28496
+ if (hint.promptTurn !== void 0) {
28497
+ this.maxPromptTurn = Math.max(this.maxPromptTurn, hint.promptTurn);
28498
+ }
28499
+ if (hint.turnParentUuid !== void 0) {
28500
+ this.turnParentUuids.push(hint.turnParentUuid);
28501
+ }
28502
+ if (hint.backgroundNotificationTaskId !== void 0) {
28503
+ this.backgroundNotificationTaskIds.add(hint.backgroundNotificationTaskId);
28504
+ }
28505
+ }
28506
+ finish() {
28507
+ return {
28508
+ initialTurn: this.maxPromptTurn > 0 ? this.maxPromptTurn : this.userMessageCount,
28509
+ turnParentUuids: [...this.turnParentUuids],
28510
+ backgroundNotificationTaskIds: [...this.backgroundNotificationTaskIds]
28511
+ };
28512
+ }
28513
+ };
28514
+ function getSessionTurnRecordHint(record2, sessionId) {
28515
+ let promptTurn;
28516
+ for (const promptId of getRecordPromptIds(record2)) {
28517
+ const candidate = parseSessionPromptTurn(promptId, sessionId);
28518
+ if (candidate !== void 0) {
28519
+ promptTurn = Math.max(promptTurn ?? 0, candidate);
28520
+ }
28521
+ }
28522
+ const turnParentUuid = record2.type === "user" && record2.subtype !== "goal_runtime" && record2.subtype !== "notification" && record2.subtype !== "cron" && record2.subtype !== "mid_turn_user_message" && record2.subtype !== "realtime_message" ? record2.parentUuid ?? null : void 0;
28523
+ const backgroundTask = record2.subtype === "notification" ? record2.systemPayload?.backgroundTask : void 0;
28524
+ return {
28525
+ ...promptTurn !== void 0 ? { promptTurn } : {},
28526
+ countsAsUserPrompt: record2.sessionId === sessionId && isUserPromptRecord(record2),
28527
+ ...turnParentUuid !== void 0 ? { turnParentUuid } : {},
28528
+ ...typeof backgroundTask?.taskId === "string" ? { backgroundNotificationTaskId: backgroundTask.taskId } : {}
28529
+ };
28530
+ }
28531
+ __name(getSessionTurnRecordHint, "getSessionTurnRecordHint");
28532
+ function collectSessionTurnState(records, sessionId) {
28533
+ const accumulator = new SessionTurnStateAccumulator(sessionId);
28534
+ for (const record2 of records) accumulator.add(record2);
28535
+ return accumulator.finish();
28536
+ }
28537
+ __name(collectSessionTurnState, "collectSessionTurnState");
28538
+ function getRecordPromptIds(record2) {
28539
+ const promptIds = [];
28540
+ const recordPromptId = record2.promptId;
28541
+ if (typeof recordPromptId === "string") promptIds.push(recordPromptId);
28542
+ const telemetryPromptId = readTelemetryPromptId(record2.systemPayload);
28543
+ if (telemetryPromptId) promptIds.push(telemetryPromptId);
28544
+ return promptIds;
28545
+ }
28546
+ __name(getRecordPromptIds, "getRecordPromptIds");
28547
+ function readTelemetryPromptId(payload) {
28548
+ if (!payload || typeof payload !== "object" || !("uiEvent" in payload)) {
28549
+ return void 0;
28550
+ }
28551
+ const uiEvent = payload.uiEvent;
28552
+ if (!uiEvent || typeof uiEvent !== "object" || !("prompt_id" in uiEvent)) {
28553
+ return void 0;
28554
+ }
28555
+ const promptId = uiEvent.prompt_id;
28556
+ return typeof promptId === "string" ? promptId : void 0;
28557
+ }
28558
+ __name(readTelemetryPromptId, "readTelemetryPromptId");
28559
+ function parseSessionPromptTurn(promptId, sessionId) {
28560
+ const promptIdPrefix = `${sessionId}########`;
28561
+ if (!promptId.startsWith(promptIdPrefix)) return void 0;
28562
+ const suffix = promptId.slice(promptIdPrefix.length);
28563
+ return /^\d+$/.test(suffix) ? Number(suffix) : void 0;
28564
+ }
28565
+ __name(parseSessionPromptTurn, "parseSessionPromptTurn");
28566
+ function isUserPromptRecord(record2) {
28567
+ if (record2.type !== "user" || record2.subtype === "realtime_message") {
28568
+ return false;
28569
+ }
28570
+ return record2.message?.parts?.some(
28571
+ (part) => typeof part.text === "string" && part.text.trim().length > 0
28572
+ ) ?? false;
28573
+ }
28574
+ __name(isUserPromptRecord, "isUserPromptRecord");
28575
+
28576
+ // packages/core/src/services/session-transcript-reader.ts
28180
28577
  var SESSION_TRANSCRIPT_DEFAULT_LIMIT = 100;
28181
28578
  var SESSION_TRANSCRIPT_MAX_LIMIT = 500;
28182
28579
  var SESSION_TRANSCRIPT_CURSOR_VERSION = 1;
@@ -28201,6 +28598,11 @@ var SessionTranscriptSnapshotUnavailableError = class extends Error {
28201
28598
  this.name = "SessionTranscriptSnapshotUnavailableError";
28202
28599
  }
28203
28600
  };
28601
+ var EmptySessionTranscriptError = class extends SessionTranscriptSnapshotUnavailableError {
28602
+ static {
28603
+ __name(this, "EmptySessionTranscriptError");
28604
+ }
28605
+ };
28204
28606
  var SessionTranscriptTooLargeError = class extends Error {
28205
28607
  constructor(sessionId, snapshotSize, maxBytes) {
28206
28608
  super(
@@ -28235,15 +28637,104 @@ var INDEX_CACHE_TTL_MS = 5 * 60 * 1e3;
28235
28637
  var INDEX_ENTRY_BASE_BYTES = 256;
28236
28638
  var INDEX_SEGMENT_BYTES = 64;
28237
28639
  var INDEX_STRING_BYTES = 2;
28640
+ var INDEX_HINT_BASE_BYTES = 64;
28641
+ var INDEX_CONTAINER_BASE_BYTES = 64;
28642
+ var INDEX_CONTAINER_SLOT_BYTES = 8;
28643
+ var INDEX_MAP_ENTRY_BYTES = 48;
28238
28644
  var READ_CHUNK_SIZE = 64 * 1024;
28645
+ var COOPERATIVE_READ_BYTE_BUDGET = 2 * 1024 * 1024;
28646
+ var COOPERATIVE_READ_TIME_BUDGET_MS = 8;
28239
28647
  var CURSOR_HMAC_KEY_BYTES = 32;
28240
28648
  var CURSOR_HMAC_KEY_FILENAME = "session-transcript-cursor-key";
28241
28649
  var SESSION_TRANSCRIPT_SESSION_ID_PATTERN = /^[0-9a-fA-F-]{32,36}$/;
28242
28650
  var debugLogger14 = createDebugLogger("SESSION_TRANSCRIPT");
28651
+ function recordRestoreStage(stage, startedAt) {
28652
+ const durationMs = Math.round((performance3.now() - startedAt) * 100) / 100;
28653
+ if (Number.isFinite(durationMs) && durationMs >= 0) {
28654
+ addDaemonRequestAttribute(
28655
+ `qwen-code.daemon.session_restore.${stage}_ms`,
28656
+ durationMs
28657
+ );
28658
+ }
28659
+ }
28660
+ __name(recordRestoreStage, "recordRestoreStage");
28661
+ function recordRestoreIndexAttributes(index) {
28662
+ addDaemonRequestAttribute(
28663
+ "qwen-code.daemon.session_restore.transcript_bytes",
28664
+ index.snapshotSize
28665
+ );
28666
+ addDaemonRequestAttribute(
28667
+ "qwen-code.daemon.session_restore.records_indexed",
28668
+ index.byUuid.size
28669
+ );
28670
+ addDaemonRequestAttribute(
28671
+ "qwen-code.daemon.session_restore.active_records",
28672
+ index.runtimeUuids.length
28673
+ );
28674
+ }
28675
+ __name(recordRestoreIndexAttributes, "recordRestoreIndexAttributes");
28676
+ function selectedRecordBytes(index, uuids) {
28677
+ const offsets = /* @__PURE__ */ new Set();
28678
+ let bytes = 0;
28679
+ for (const uuid of uuids) {
28680
+ const entry = index.byUuid.get(uuid);
28681
+ if (!entry) continue;
28682
+ for (const segment of entry.segments) {
28683
+ if (offsets.has(segment.offset)) continue;
28684
+ offsets.add(segment.offset);
28685
+ bytes += segment.length;
28686
+ }
28687
+ }
28688
+ return bytes;
28689
+ }
28690
+ __name(selectedRecordBytes, "selectedRecordBytes");
28691
+ function recordRestoreSelectionAttributes(index, selectedUuids, replayUuids) {
28692
+ addDaemonRequestAttribute(
28693
+ "qwen-code.daemon.session_restore.selected_records",
28694
+ selectedUuids.size
28695
+ );
28696
+ addDaemonRequestAttribute(
28697
+ "qwen-code.daemon.session_restore.selected_bytes",
28698
+ selectedRecordBytes(index, selectedUuids)
28699
+ );
28700
+ addDaemonRequestAttribute(
28701
+ "qwen-code.daemon.session_restore.replay_records",
28702
+ replayUuids.size
28703
+ );
28704
+ addDaemonRequestAttribute(
28705
+ "qwen-code.daemon.session_restore.replay_bytes",
28706
+ selectedRecordBytes(index, replayUuids)
28707
+ );
28708
+ }
28709
+ __name(recordRestoreSelectionAttributes, "recordRestoreSelectionAttributes");
28243
28710
  var indexCache = /* @__PURE__ */ new Map();
28244
28711
  var cursorHmacKeys = /* @__PURE__ */ new Map();
28245
28712
  var indexCacheMaxBytesForTest;
28246
28713
  var expandedPageBytesForTest;
28714
+ var cooperativeReadByteBudgetForTest;
28715
+ var cooperativeReadTimeBudgetMsForTest;
28716
+ var cooperativeYieldHookForTest;
28717
+ var selectedLineReadHookForTest;
28718
+ var indexBuildCompleteHookForTest;
28719
+ var CooperativeReadScheduler = class {
28720
+ static {
28721
+ __name(this, "CooperativeReadScheduler");
28722
+ }
28723
+ processedBytes = 0;
28724
+ startedAt = performance3.now();
28725
+ async afterUnit(sourceBytes) {
28726
+ this.processedBytes += sourceBytes;
28727
+ const byteBudget = cooperativeReadByteBudgetForTest ?? COOPERATIVE_READ_BYTE_BUDGET;
28728
+ const timeBudgetMs = cooperativeReadTimeBudgetMsForTest ?? COOPERATIVE_READ_TIME_BUDGET_MS;
28729
+ if (this.processedBytes < byteBudget && performance3.now() - this.startedAt < timeBudgetMs) {
28730
+ return;
28731
+ }
28732
+ cooperativeYieldHookForTest?.();
28733
+ await new Promise((resolve41) => setImmediate(resolve41));
28734
+ this.processedBytes = 0;
28735
+ this.startedAt = performance3.now();
28736
+ }
28737
+ };
28247
28738
  function getExpandedPageBytes() {
28248
28739
  return expandedPageBytesForTest ?? SESSION_TRANSCRIPT_MAX_EXPANDED_PAGE_BYTES;
28249
28740
  }
@@ -28262,6 +28753,14 @@ function isObjectRecord(value) {
28262
28753
  return typeof value === "object" && value !== null && !Array.isArray(value);
28263
28754
  }
28264
28755
  __name(isObjectRecord, "isObjectRecord");
28756
+ function isFileMissingError(error) {
28757
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
28758
+ }
28759
+ __name(isFileMissingError, "isFileMissingError");
28760
+ function isAttributionSnapshotCandidate(record2) {
28761
+ return record2.subtype === "attribution_snapshot" && isObjectRecord(record2.systemPayload) && "snapshot" in record2.systemPayload;
28762
+ }
28763
+ __name(isAttributionSnapshotCandidate, "isAttributionSnapshotCandidate");
28265
28764
  function isFiniteNonNegativeInteger(value) {
28266
28765
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
28267
28766
  }
@@ -28473,7 +28972,7 @@ function recordSegmentBytes(index, uuid) {
28473
28972
  }
28474
28973
  __name(recordSegmentBytes, "recordSegmentBytes");
28475
28974
  function selectPageUuids(index, position, limit, maxBytes) {
28476
- const candidates = index.activeUuids.slice(position, position + limit);
28975
+ const candidates = index.replayUuids.slice(position, position + limit);
28477
28976
  if (maxBytes === void 0) return candidates;
28478
28977
  const selected = [];
28479
28978
  let selectedBytes = 0;
@@ -28516,7 +29015,7 @@ function findBoundaryAtOrBefore(items, from, floor, isBoundary) {
28516
29015
  __name(findBoundaryAtOrBefore, "findBoundaryAtOrBefore");
28517
29016
  function findReplayBoundaryAtOrBefore(index, from, floor, isBoundary) {
28518
29017
  return findBoundaryAtOrBefore(
28519
- index.activeUuids,
29018
+ index.replayUuids,
28520
29019
  from,
28521
29020
  floor,
28522
29021
  (uuid) => isBoundary(index, uuid)
@@ -28526,7 +29025,7 @@ __name(findReplayBoundaryAtOrBefore, "findReplayBoundaryAtOrBefore");
28526
29025
  function backwardPageBytesFit(index, start, end, budget) {
28527
29026
  let total = 0;
28528
29027
  for (let i = start; i < end; i++) {
28529
- total += recordSegmentBytes(index, index.activeUuids[i]);
29028
+ total += recordSegmentBytes(index, index.replayUuids[i]);
28530
29029
  if (total > budget) return false;
28531
29030
  }
28532
29031
  return true;
@@ -28534,11 +29033,11 @@ function backwardPageBytesFit(index, start, end, budget) {
28534
29033
  __name(backwardPageBytesFit, "backwardPageBytesFit");
28535
29034
  function selectionOrphansToolResult(index, start, end) {
28536
29035
  for (let i = start; i < end; i++) {
28537
- if (index.byUuid.get(index.activeUuids[i])?.type !== "tool_result") {
29036
+ if (index.byUuid.get(index.replayUuids[i])?.type !== "tool_result") {
28538
29037
  continue;
28539
29038
  }
28540
29039
  for (let owner = i - 1; owner >= start; owner--) {
28541
- if (isReplayPageStart(index, index.activeUuids[owner])) return false;
29040
+ if (isReplayPageStart(index, index.replayUuids[owner])) return false;
28542
29041
  }
28543
29042
  return true;
28544
29043
  }
@@ -28550,7 +29049,7 @@ function selectBackwardPageUuids(index, sessionId, position, limit, maxBytes) {
28550
29049
  const expansionByteBudget = maxBytes === void 0 ? getExpandedPageBytes() : Math.min(2 * maxBytes, getExpandedPageBytes());
28551
29050
  let start = Math.max(0, position - limit);
28552
29051
  for (let i = start; i < position; i++) {
28553
- if (isReplayTurnStart(index, index.activeUuids[i])) {
29052
+ if (isReplayTurnStart(index, index.replayUuids[i])) {
28554
29053
  start = i;
28555
29054
  break;
28556
29055
  }
@@ -28562,13 +29061,13 @@ function selectBackwardPageUuids(index, sessionId, position, limit, maxBytes) {
28562
29061
  expansionFloor,
28563
29062
  isReplayTurnStart
28564
29063
  );
28565
- if (isReplayTurnStart(index, index.activeUuids[expandedStart])) {
29064
+ if (isReplayTurnStart(index, index.replayUuids[expandedStart])) {
28566
29065
  start = expandedStart;
28567
29066
  }
28568
29067
  let selectedStart = position;
28569
29068
  let selectedBytes = 0;
28570
29069
  for (let i = position - 1; i >= start; i--) {
28571
- const uuid = index.activeUuids[i];
29070
+ const uuid = index.replayUuids[i];
28572
29071
  const bytes = recordSegmentBytes(index, uuid);
28573
29072
  if (selectedStart < position && maxBytes !== void 0 && selectedBytes + bytes > maxBytes) {
28574
29073
  break;
@@ -28578,12 +29077,12 @@ function selectBackwardPageUuids(index, sessionId, position, limit, maxBytes) {
28578
29077
  }
28579
29078
  const logTurnExpansionSkipped = /* @__PURE__ */ __name((reason) => {
28580
29079
  debugLogger14.debug(
28581
- `backward turn expansion skipped session=${sessionId} start=${index.activeUuids[selectedStart]} reason=${reason}`
29080
+ `backward turn expansion skipped session=${sessionId} start=${index.replayUuids[selectedStart]} reason=${reason}`
28582
29081
  );
28583
29082
  }, "logTurnExpansionSkipped");
28584
29083
  let alignedToReplayBoundary = false;
28585
29084
  for (let i = selectedStart; i < position; i++) {
28586
- if (isReplayTurnStart(index, index.activeUuids[i])) {
29085
+ if (isReplayTurnStart(index, index.replayUuids[i])) {
28587
29086
  selectedStart = i;
28588
29087
  alignedToReplayBoundary = true;
28589
29088
  break;
@@ -28612,7 +29111,7 @@ function selectBackwardPageUuids(index, sessionId, position, limit, maxBytes) {
28612
29111
  expansionFloor,
28613
29112
  isReplayTurnStart
28614
29113
  );
28615
- if (isReplayTurnStart(index, index.activeUuids[candidate])) {
29114
+ if (isReplayTurnStart(index, index.replayUuids[candidate])) {
28616
29115
  if (backwardPageBytesFit(index, candidate, position, expansionByteBudget)) {
28617
29116
  selectedStart = candidate;
28618
29117
  } else {
@@ -28628,9 +29127,9 @@ function selectBackwardPageUuids(index, sessionId, position, limit, maxBytes) {
28628
29127
  pairFloor,
28629
29128
  isReplayPageStart
28630
29129
  );
28631
- if (!isReplayPageStart(index, index.activeUuids[pairStart])) {
29130
+ if (!isReplayPageStart(index, index.replayUuids[pairStart])) {
28632
29131
  debugLogger14.debug(
28633
- `backward pair extension skipped session=${sessionId} start=${index.activeUuids[selectedStart]} reason=record-budget`
29132
+ `backward pair extension skipped session=${sessionId} start=${index.replayUuids[selectedStart]} reason=record-budget`
28634
29133
  );
28635
29134
  } else if (!backwardPageBytesFit(
28636
29135
  index,
@@ -28639,14 +29138,14 @@ function selectBackwardPageUuids(index, sessionId, position, limit, maxBytes) {
28639
29138
  expansionByteBudget
28640
29139
  )) {
28641
29140
  debugLogger14.debug(
28642
- `backward pair extension skipped session=${sessionId} start=${index.activeUuids[selectedStart]} reason=byte-budget`
29141
+ `backward pair extension skipped session=${sessionId} start=${index.replayUuids[selectedStart]} reason=byte-budget`
28643
29142
  );
28644
29143
  } else {
28645
29144
  selectedStart = pairStart;
28646
29145
  }
28647
29146
  }
28648
29147
  return {
28649
- uuids: index.activeUuids.slice(selectedStart, position),
29148
+ uuids: index.replayUuids.slice(selectedStart, position),
28650
29149
  nextPosition: selectedStart
28651
29150
  };
28652
29151
  }
@@ -28672,8 +29171,14 @@ function estimateStringBytes(value) {
28672
29171
  }
28673
29172
  __name(estimateStringBytes, "estimateStringBytes");
28674
29173
  function estimateIndexCacheBytes(index) {
28675
- let total = INDEX_ENTRY_BASE_BYTES + estimateStringBytes(index.filePath) + estimateStringBytes(index.leafUuid) + estimateStringBytes(index.startTime) + estimateStringBytes(index.lastUpdated);
28676
- for (const uuid of index.activeUuids) {
29174
+ let total = INDEX_ENTRY_BASE_BYTES + INDEX_CONTAINER_BASE_BYTES * 6 + (index.physicalRecords.length + index.runtimeUuids.length + index.replayUuids.length + index.goalStatePositions.length + index.gaps.length) * INDEX_CONTAINER_SLOT_BYTES + estimateStringBytes(index.filePath) + estimateStringBytes(index.leafUuid) + estimateStringBytes(index.firstRecordUuid) + estimateStringBytes(index.restoreStartTime) + estimateStringBytes(index.startTime) + estimateStringBytes(index.lastUpdated);
29175
+ for (const record2 of index.physicalRecords) {
29176
+ total += INDEX_HINT_BASE_BYTES + estimateStringBytes(record2.uuid) + estimateStringBytes(record2.parentUuid) + estimateStringBytes(record2.type) + estimateStringBytes(record2.subtype);
29177
+ }
29178
+ for (const uuid of index.runtimeUuids) {
29179
+ total += estimateStringBytes(uuid);
29180
+ }
29181
+ for (const uuid of index.replayUuids) {
28677
29182
  total += estimateStringBytes(uuid);
28678
29183
  }
28679
29184
  total += index.goalStatePositions.length * 8;
@@ -28681,7 +29186,7 @@ function estimateIndexCacheBytes(index) {
28681
29186
  total += INDEX_ENTRY_BASE_BYTES + estimateStringBytes(gap.childUuid) + estimateStringBytes(gap.missingParentUuid);
28682
29187
  }
28683
29188
  for (const [uuid, entry] of index.byUuid) {
28684
- total += INDEX_ENTRY_BASE_BYTES + estimateStringBytes(uuid) + estimateStringBytes(entry.parentUuid) + entry.segments.length * INDEX_SEGMENT_BYTES;
29189
+ total += INDEX_ENTRY_BASE_BYTES + INDEX_HINT_BASE_BYTES * 2 + (entry.goalEvidenceHint.parsedGoalContext ? INDEX_HINT_BASE_BYTES : 0) + INDEX_MAP_ENTRY_BYTES + INDEX_CONTAINER_BASE_BYTES + entry.segments.length * INDEX_CONTAINER_SLOT_BYTES + estimateStringBytes(uuid) + estimateStringBytes(entry.parentUuid) + estimateStringBytes(entry.type) + estimateStringBytes(entry.subtype) + estimateStringBytes(entry.turnHint.turnParentUuid) + estimateStringBytes(entry.turnHint.backgroundNotificationTaskId) + estimateStringBytes(entry.goalEvidenceHint.parsedGoalContext?.goalId) + estimateStringBytes(entry.goalEvidenceHint.parsedGoalContext?.turnId) + estimateStringBytes(entry.goalEvidenceHint.claimedGoalId) + estimateStringBytes(entry.goalEvidenceHint.provenance) + entry.segments.length * INDEX_SEGMENT_BYTES;
28685
29190
  }
28686
29191
  return total;
28687
29192
  }
@@ -28722,6 +29227,7 @@ function pruneCache(now = Date.now()) {
28722
29227
  __name(pruneCache, "pruneCache");
28723
29228
  async function forEachLineInSnapshot(filePath, snapshotSize, onLine) {
28724
29229
  if (snapshotSize === 0) return;
29230
+ const scheduler = new CooperativeReadScheduler();
28725
29231
  let pending = [];
28726
29232
  let pendingLength = 0;
28727
29233
  let pendingOffset = 0;
@@ -28745,7 +29251,8 @@ async function forEachLineInSnapshot(filePath, snapshotSize, onLine) {
28745
29251
  pendingLength + currentLine.length
28746
29252
  ) : currentLine;
28747
29253
  const line = rawLine.length > 0 && rawLine[rawLine.length - 1] === 13 ? rawLine.subarray(0, rawLine.length - 1) : rawLine;
28748
- onLine(line, lineOffset, line.length);
29254
+ await onLine(line, lineOffset, line.length);
29255
+ await scheduler.afterUnit(line.length);
28749
29256
  pending = [];
28750
29257
  pendingLength = 0;
28751
29258
  lineStart = lineEnd + 1;
@@ -28763,20 +29270,32 @@ async function forEachLineInSnapshot(filePath, snapshotSize, onLine) {
28763
29270
  if (pendingLength > 0) {
28764
29271
  const rawLine = makePendingLine();
28765
29272
  const line = rawLine[rawLine.length - 1] === 13 ? rawLine.subarray(0, rawLine.length - 1) : rawLine;
28766
- onLine(line, pendingOffset, line.length);
29273
+ await onLine(line, pendingOffset, line.length);
29274
+ await scheduler.afterUnit(line.length);
28767
29275
  }
28768
29276
  }
28769
29277
  __name(forEachLineInSnapshot, "forEachLineInSnapshot");
28770
- async function readSegmentRecords(handle, filePath, segment, uuid) {
29278
+ async function readSegmentRecords(handle, filePath, segment, uuid, lineCache) {
28771
29279
  if (segment.length === 0) return [];
28772
- const buffer = Buffer.alloc(segment.length);
28773
- await handle.read(buffer, 0, segment.length, segment.offset);
28774
- const line = buffer.toString("utf8").trim();
28775
- if (line.length === 0) return [];
28776
- const records = parseLineTolerant(line, filePath).flatMap((value) => {
28777
- const record3 = validateTranscriptRecord(value).record;
28778
- return record3 && isTranscriptConversationRecord(record3) ? [record3] : [];
28779
- });
29280
+ let records;
29281
+ if (lineCache.value?.offset === segment.offset && lineCache.value.length === segment.length) {
29282
+ records = lineCache.value.records;
29283
+ } else {
29284
+ selectedLineReadHookForTest?.(segment.offset, segment.length);
29285
+ const buffer = Buffer.alloc(segment.length);
29286
+ await handle.read(buffer, 0, segment.length, segment.offset);
29287
+ const line = buffer.toString("utf8").trim();
29288
+ if (line.length === 0) return [];
29289
+ records = parseLineTolerant(line, filePath).flatMap((value) => {
29290
+ const record3 = validateTranscriptRecord(value).record;
29291
+ return record3 ? [record3] : [];
29292
+ });
29293
+ lineCache.value = {
29294
+ offset: segment.offset,
29295
+ length: segment.length,
29296
+ records
29297
+ };
29298
+ }
28780
29299
  const anomalySessionId = path10.basename(filePath, ".jsonl");
28781
29300
  const record2 = records[segment.fragmentIndex];
28782
29301
  if (!record2) {
@@ -28791,31 +29310,84 @@ async function readSegmentRecords(handle, filePath, segment, uuid) {
28791
29310
  );
28792
29311
  throw new SessionTranscriptSnapshotUnavailableError(anomalySessionId);
28793
29312
  }
29313
+ if (record2.sessionId !== anomalySessionId) {
29314
+ debugLogger14.warn(
29315
+ `segment read anomaly: session mismatch session=${anomalySessionId} recordSession=${record2.sessionId} uuid=${uuid} offset=${segment.offset}`
29316
+ );
29317
+ throw new SessionTranscriptSnapshotUnavailableError(anomalySessionId);
29318
+ }
28794
29319
  return [record2];
28795
29320
  }
28796
29321
  __name(readSegmentRecords, "readSegmentRecords");
28797
- async function readAggregatedRecords(index, uuids) {
28798
- const handle = await fsp.open(index.filePath, "r");
29322
+ async function forEachAggregatedRecord(index, uuids, onRecord, context2) {
29323
+ if (!context2) {
29324
+ await withAggregatedRecordReadContext(
29325
+ index,
29326
+ (readContext) => forEachAggregatedRecord(index, uuids, onRecord, readContext)
29327
+ );
29328
+ return;
29329
+ }
29330
+ for (const uuid of uuids) {
29331
+ const entry = index.byUuid.get(uuid);
29332
+ if (!entry) continue;
29333
+ const preloadedRecord = context2.preloadedRecords?.get(uuid);
29334
+ if (preloadedRecord) {
29335
+ context2.preloadedRecords?.delete(uuid);
29336
+ await onRecord(preloadedRecord);
29337
+ continue;
29338
+ }
29339
+ const physicalRecords = [];
29340
+ for (const segment of entry.segments) {
29341
+ physicalRecords.push(
29342
+ ...await readSegmentRecords(
29343
+ context2.handle,
29344
+ index.filePath,
29345
+ segment,
29346
+ uuid,
29347
+ context2.lineCache
29348
+ )
29349
+ );
29350
+ }
29351
+ if (physicalRecords.length > 0) {
29352
+ await onRecord(aggregateTranscriptRecordFragments(physicalRecords));
29353
+ }
29354
+ await context2.scheduler.afterUnit(
29355
+ entry.segments.reduce((total, segment) => total + segment.length, 0)
29356
+ );
29357
+ }
29358
+ }
29359
+ __name(forEachAggregatedRecord, "forEachAggregatedRecord");
29360
+ async function withAggregatedRecordReadContext(index, callback) {
29361
+ let handle;
28799
29362
  try {
28800
- const records = [];
28801
- for (const uuid of uuids) {
28802
- const entry = index.byUuid.get(uuid);
28803
- if (!entry) continue;
28804
- const physicalRecords = [];
28805
- for (const segment of entry.segments) {
28806
- physicalRecords.push(
28807
- ...await readSegmentRecords(handle, index.filePath, segment, uuid)
28808
- );
28809
- }
28810
- if (physicalRecords.length > 0) {
28811
- records.push(aggregateTranscriptRecordFragments(physicalRecords));
28812
- }
29363
+ handle = await fsp.open(index.filePath, "r");
29364
+ } catch (error) {
29365
+ if (isFileMissingError(error)) {
29366
+ throw new SessionTranscriptSnapshotUnavailableError(
29367
+ path10.basename(index.filePath, ".jsonl")
29368
+ );
28813
29369
  }
28814
- return records;
29370
+ throw error;
29371
+ }
29372
+ const context2 = {
29373
+ handle,
29374
+ scheduler: new CooperativeReadScheduler(),
29375
+ lineCache: {}
29376
+ };
29377
+ try {
29378
+ return await callback(context2);
28815
29379
  } finally {
28816
- await handle.close();
29380
+ await context2.handle.close();
28817
29381
  }
28818
29382
  }
29383
+ __name(withAggregatedRecordReadContext, "withAggregatedRecordReadContext");
29384
+ async function readAggregatedRecords(index, uuids) {
29385
+ const records = [];
29386
+ await forEachAggregatedRecord(index, uuids, (record2) => {
29387
+ records.push(record2);
29388
+ });
29389
+ return records;
29390
+ }
28819
29391
  __name(readAggregatedRecords, "readAggregatedRecords");
28820
29392
  async function readGoalStatePayloadBeforePosition(index, position) {
28821
29393
  let low = 0;
@@ -28830,7 +29402,7 @@ async function readGoalStatePayloadBeforePosition(index, position) {
28830
29402
  }
28831
29403
  const goalStatePosition = index.goalStatePositions[low - 1];
28832
29404
  if (goalStatePosition === void 0) return void 0;
28833
- const uuid = index.activeUuids[goalStatePosition];
29405
+ const uuid = index.replayUuids[goalStatePosition];
28834
29406
  const [record2] = await readAggregatedRecords(index, [uuid]);
28835
29407
  return parseGoalStateRecordPayloadV2(record2?.systemPayload);
28836
29408
  }
@@ -28852,59 +29424,121 @@ async function buildIndex(params) {
28852
29424
  `index build start session=${sessionId} snapshotSize=${snapshotSize}`
28853
29425
  );
28854
29426
  const byUuid = /* @__PURE__ */ new Map();
29427
+ const goalEvidenceAccumulators = /* @__PURE__ */ new Map();
28855
29428
  let sequence = 0;
29429
+ const physicalRecords = [];
28856
29430
  let leafUuid;
29431
+ let firstRecordUuid;
29432
+ let firstRecordTimestamp;
28857
29433
  let startTime;
28858
- let sideTaskSourceUuid;
28859
- await forEachLineInSnapshot(
28860
- filePath,
28861
- snapshotSize,
28862
- (line, offset, length) => {
28863
- const text = line.toString("utf8").trim();
28864
- if (text.length === 0) return;
28865
- let fragmentIndex = 0;
28866
- for (const value of parseLineTolerant(text, filePath)) {
28867
- const record2 = validateTranscriptRecord(value).record;
28868
- if (!record2 || !isTranscriptConversationRecord(record2)) {
28869
- continue;
28870
- }
28871
- if (record2.type === "system" && record2.subtype === "session_source" && isObjectRecord(record2.systemPayload) && record2.systemPayload["sourceType"] === "side_task") {
28872
- sideTaskSourceUuid = record2.uuid;
28873
- }
28874
- if (record2.timestamp) startTime ??= record2.timestamp;
28875
- leafUuid = record2.uuid;
28876
- const existing = byUuid.get(record2.uuid);
28877
- const segment = {
28878
- offset,
28879
- length,
28880
- sequence: sequence++,
28881
- fragmentIndex
28882
- };
28883
- fragmentIndex++;
28884
- if (existing) {
28885
- existing.segments.push(segment);
28886
- } else {
28887
- byUuid.set(record2.uuid, {
29434
+ try {
29435
+ await forEachLineInSnapshot(
29436
+ filePath,
29437
+ snapshotSize,
29438
+ (line, offset, length) => {
29439
+ const text = line.toString("utf8").trim();
29440
+ if (text.length === 0) return;
29441
+ let fragmentIndex = 0;
29442
+ for (const value of parseLineTolerant(text, filePath)) {
29443
+ const record2 = validateTranscriptRecord(value).record;
29444
+ if (!record2) {
29445
+ continue;
29446
+ }
29447
+ if (firstRecordUuid === void 0) {
29448
+ firstRecordUuid = record2.uuid;
29449
+ firstRecordTimestamp = record2.timestamp;
29450
+ }
29451
+ const sideTaskSource = record2.type === "system" && record2.subtype === "session_source" && isObjectRecord(record2.systemPayload) && record2.systemPayload["sourceType"] === "side_task";
29452
+ if (isTranscriptConversationRecord(record2)) {
29453
+ if (record2.timestamp) startTime ??= record2.timestamp;
29454
+ leafUuid = record2.uuid;
29455
+ }
29456
+ const existing = byUuid.get(record2.uuid);
29457
+ physicalRecords.push({
29458
+ uuid: record2.uuid,
28888
29459
  parentUuid: record2.parentUuid,
28889
29460
  type: record2.type,
28890
- ...record2.subtype !== void 0 ? { subtype: record2.subtype } : {},
28891
- inherited: record2.forkedFrom !== void 0,
28892
- segments: [segment]
29461
+ ...record2.subtype !== void 0 ? { subtype: record2.subtype } : {}
28893
29462
  });
29463
+ const segment = {
29464
+ offset,
29465
+ length,
29466
+ sequence: sequence++,
29467
+ fragmentIndex
29468
+ };
29469
+ fragmentIndex++;
29470
+ if (existing) {
29471
+ existing.segments.push(segment);
29472
+ existing.sessionIdMatchesFile &&= record2.sessionId === sessionId;
29473
+ if (existing.type === "assistant" && record2.usageMetadata) {
29474
+ existing.resumeTokenCountsCandidate = isResumeTokenCountsCandidate({
29475
+ ...record2,
29476
+ type: existing.type,
29477
+ subtype: existing.subtype
29478
+ });
29479
+ }
29480
+ existing.turnHint.countsAsUserPrompt ||= getSessionTurnRecordHint(
29481
+ record2,
29482
+ sessionId
29483
+ ).countsAsUserPrompt;
29484
+ goalEvidenceAccumulators.get(record2.uuid)?.addFragment(record2);
29485
+ } else {
29486
+ const chatRecord = record2;
29487
+ const goalEvidenceAccumulator = new GoalEvidenceRecordIndexAccumulator(chatRecord);
29488
+ const goalEvidenceHint = goalEvidenceAccumulator.finish();
29489
+ if (goalEvidenceHint.provenance) {
29490
+ goalEvidenceAccumulators.set(
29491
+ record2.uuid,
29492
+ goalEvidenceAccumulator
29493
+ );
29494
+ }
29495
+ byUuid.set(record2.uuid, {
29496
+ parentUuid: record2.parentUuid,
29497
+ sessionIdMatchesFile: record2.sessionId === sessionId,
29498
+ type: record2.type,
29499
+ ...record2.subtype !== void 0 ? { subtype: record2.subtype } : {},
29500
+ inherited: record2.forkedFrom !== void 0,
29501
+ sideTaskSource,
29502
+ apiHistoryCompressionCandidate: isApiHistoryCompressionCandidate(chatRecord),
29503
+ resumeTokenCountsCandidate: isResumeTokenCountsCandidate(chatRecord),
29504
+ attributionSnapshotCandidate: isAttributionSnapshotCandidate(chatRecord),
29505
+ goalRecoveryCandidate: isGoalRecoveryCandidate(chatRecord),
29506
+ goalEvidenceHint,
29507
+ turnHint: getSessionTurnRecordHint(chatRecord, sessionId),
29508
+ segments: [segment]
29509
+ });
29510
+ }
28894
29511
  }
28895
29512
  }
29513
+ );
29514
+ } catch (error) {
29515
+ if (isFileMissingError(error)) {
29516
+ throw new SessionTranscriptSnapshotUnavailableError(sessionId);
28896
29517
  }
28897
- );
28898
- if (!leafUuid) {
29518
+ throw error;
29519
+ }
29520
+ for (const [uuid, accumulator] of goalEvidenceAccumulators) {
29521
+ byUuid.get(uuid).goalEvidenceHint = accumulator.finish();
29522
+ }
29523
+ for (const [uuid, entry] of byUuid) {
29524
+ if (!entry.sessionIdMatchesFile) {
29525
+ debugLogger14.warn(
29526
+ `transcript session mismatch session=${sessionId} uuid=${uuid}`
29527
+ );
29528
+ throw new SessionTranscriptSnapshotUnavailableError(sessionId);
29529
+ }
29530
+ }
29531
+ if (!leafUuid || !firstRecordUuid) {
28899
29532
  debugLogger14.warn(
28900
- `index build failed: no transcript records session=${sessionId}`
29533
+ `index build failed: no active transcript records session=${sessionId}`
28901
29534
  );
28902
- throw new SessionTranscriptSnapshotUnavailableError(sessionId);
29535
+ throw new EmptySessionTranscriptError(sessionId);
28903
29536
  }
28904
29537
  startTime ??= lastUpdated;
29538
+ const restoreStartTime = firstRecordTimestamp ?? startTime;
28905
29539
  const chain = walkTranscriptUuidChain(leafUuid, (uuid) => {
28906
29540
  const entry = byUuid.get(uuid);
28907
- return entry ? {
29541
+ return entry && isTranscriptConversationRecord(entry) ? {
28908
29542
  uuid,
28909
29543
  parentUuid: entry.parentUuid,
28910
29544
  sessionId,
@@ -28912,11 +29546,14 @@ async function buildIndex(params) {
28912
29546
  type: "system"
28913
29547
  } : void 0;
28914
29548
  });
28915
- const sourceBoundary = sideTaskSourceUuid ? chain.uuids.indexOf(sideTaskSourceUuid) : -1;
28916
- const activeUuids = sourceBoundary >= 0 ? chain.uuids.slice(sourceBoundary).filter((uuid) => byUuid.get(uuid)?.inherited !== true) : [...chain.uuids];
29549
+ const runtimeUuids = [...chain.uuids];
29550
+ const sourceBoundary = runtimeUuids.findIndex(
29551
+ (uuid) => byUuid.get(uuid)?.sideTaskSource === true
29552
+ );
29553
+ const replayUuids = sourceBoundary >= 0 ? runtimeUuids.slice(sourceBoundary).filter((uuid) => byUuid.get(uuid)?.inherited !== true) : [...runtimeUuids];
28917
29554
  const goalStatePositions = [];
28918
- for (let position = 0; position < activeUuids.length; position++) {
28919
- const uuid = activeUuids[position];
29555
+ for (let position = 0; position < replayUuids.length; position++) {
29556
+ const uuid = replayUuids[position];
28920
29557
  const entry = byUuid.get(uuid);
28921
29558
  if (entry?.type === "system" && entry.subtype === "goal_state") {
28922
29559
  goalStatePositions.push(position);
@@ -28929,16 +29566,21 @@ async function buildIndex(params) {
28929
29566
  );
28930
29567
  }
28931
29568
  debugLogger14.debug(
28932
- `index build complete session=${sessionId} records=${byUuid.size} active=${activeUuids.length} gaps=${gaps.length}`
29569
+ `index build complete session=${sessionId} records=${byUuid.size} runtime=${runtimeUuids.length} replay=${replayUuids.length} gaps=${gaps.length}`
28933
29570
  );
29571
+ await indexBuildCompleteHookForTest?.(filePath);
28934
29572
  return {
28935
29573
  filePath,
28936
29574
  fileIdentity,
28937
29575
  snapshotSize,
28938
29576
  leafUuid,
28939
- activeUuids,
29577
+ firstRecordUuid,
29578
+ physicalRecords,
29579
+ runtimeUuids,
29580
+ replayUuids,
28940
29581
  goalStatePositions,
28941
29582
  gaps,
29583
+ restoreStartTime,
28942
29584
  startTime,
28943
29585
  lastUpdated,
28944
29586
  byUuid
@@ -28959,13 +29601,16 @@ async function getCachedIndex(params) {
28959
29601
  indexCache.delete(key);
28960
29602
  indexCache.set(key, cached);
28961
29603
  debugLogger14.debug(`index cache hit ${key}`);
29604
+ params.onCacheState?.("hit");
28962
29605
  return cached.value;
28963
29606
  }
28964
29607
  if (cached?.pending && cached.expiresAt > now) {
28965
29608
  debugLogger14.debug(`index cache pending hit ${key}`);
29609
+ params.onCacheState?.("pending");
28966
29610
  return cached.pending;
28967
29611
  }
28968
29612
  debugLogger14.debug(`index cache miss ${key}`);
29613
+ params.onCacheState?.("miss");
28969
29614
  const pending = buildIndex(params);
28970
29615
  indexCache.set(key, {
28971
29616
  pending,
@@ -28983,6 +29628,17 @@ async function getCachedIndex(params) {
28983
29628
  );
28984
29629
  return value;
28985
29630
  }
29631
+ if (indexCache.get(key)?.pending !== pending) {
29632
+ debugLogger14.debug(`index cache skipped stale completion ${key}`);
29633
+ return value;
29634
+ }
29635
+ if (getIndexCacheBytes() + byteSize > getIndexCacheMaxBytes()) {
29636
+ indexCache.delete(key);
29637
+ debugLogger14.debug(
29638
+ `index cache skipped byte-budget admission ${key} byteSize=${byteSize}`
29639
+ );
29640
+ return value;
29641
+ }
28986
29642
  indexCache.set(key, {
28987
29643
  value,
28988
29644
  byteSize,
@@ -28991,7 +29647,9 @@ async function getCachedIndex(params) {
28991
29647
  pruneCache();
28992
29648
  return value;
28993
29649
  } catch (error) {
28994
- indexCache.delete(key);
29650
+ if (indexCache.get(key)?.pending === pending) {
29651
+ indexCache.delete(key);
29652
+ }
28995
29653
  debugLogger14.debug(
28996
29654
  `index cache build failed ${key}: ${error instanceof Error ? error.message : String(error)}`
28997
29655
  );
@@ -28999,11 +29657,118 @@ async function getCachedIndex(params) {
28999
29657
  }
29000
29658
  }
29001
29659
  __name(getCachedIndex, "getCachedIndex");
29660
+ function makeReplayIndex(index, hideInheritedHistory) {
29661
+ const replayUuids = hideInheritedHistory ? index.replayUuids.filter(
29662
+ (uuid) => index.byUuid.get(uuid)?.inherited !== true
29663
+ ) : index.replayUuids;
29664
+ if (replayUuids === index.replayUuids) return index;
29665
+ const goalStatePositions = [];
29666
+ for (let position = 0; position < replayUuids.length; position++) {
29667
+ const entry = index.byUuid.get(replayUuids[position]);
29668
+ if (entry?.type === "system" && entry.subtype === "goal_state") {
29669
+ goalStatePositions.push(position);
29670
+ }
29671
+ }
29672
+ return { ...index, replayUuids, goalStatePositions };
29673
+ }
29674
+ __name(makeReplayIndex, "makeReplayIndex");
29675
+ function selectRestoreReplayUuids(index, sessionId, replay) {
29676
+ if (replay.kind === "none") return void 0;
29677
+ const replayIndex = makeReplayIndex(index, replay.hideInheritedHistory);
29678
+ if (replay.kind === "all") {
29679
+ return {
29680
+ index: replayIndex,
29681
+ uuids: replayIndex.replayUuids,
29682
+ hasMore: false,
29683
+ nextPosition: 0
29684
+ };
29685
+ }
29686
+ const limit = normalizeLimit(replay.limit);
29687
+ const selected = selectBackwardPageUuids(
29688
+ replayIndex,
29689
+ sessionId,
29690
+ replayIndex.replayUuids.length,
29691
+ limit,
29692
+ SESSION_TRANSCRIPT_MAX_PAGE_BYTES
29693
+ );
29694
+ return {
29695
+ index: replayIndex,
29696
+ uuids: selected.uuids,
29697
+ hasMore: selected.nextPosition > 0,
29698
+ nextPosition: selected.nextPosition
29699
+ };
29700
+ }
29701
+ __name(selectRestoreReplayUuids, "selectRestoreReplayUuids");
29702
+ function validateRestoreReplaySelection(replay) {
29703
+ if (replay.kind === "recent") normalizeLimit(replay.limit);
29704
+ }
29705
+ __name(validateRestoreReplaySelection, "validateRestoreReplaySelection");
29706
+ async function assertIndexSnapshotUnchanged(index, sessionId) {
29707
+ if (!await hasSnapshotSignature(
29708
+ index.filePath,
29709
+ index.fileIdentity,
29710
+ index.snapshotSize,
29711
+ index.lastUpdated
29712
+ )) {
29713
+ throw new SessionTranscriptSnapshotUnavailableError(sessionId);
29714
+ }
29715
+ }
29716
+ __name(assertIndexSnapshotUnchanged, "assertIndexSnapshotUnchanged");
29717
+ async function hasSnapshotSignature(filePath, fileIdentity, snapshotSize, lastUpdated) {
29718
+ let stats;
29719
+ try {
29720
+ stats = await fsp.stat(filePath);
29721
+ } catch (error) {
29722
+ if (isFileMissingError(error)) return false;
29723
+ throw error;
29724
+ }
29725
+ return stats.size === snapshotSize && sameFileIdentity(fileIdentityFromStats(stats), fileIdentity) && new Date(stats.mtimeMs).toISOString() === lastUpdated;
29726
+ }
29727
+ __name(hasSnapshotSignature, "hasSnapshotSignature");
29728
+ function offerFreshIndexToCache(index) {
29729
+ pruneCache();
29730
+ const key = makeCacheKey(
29731
+ index.filePath,
29732
+ index.fileIdentity,
29733
+ index.snapshotSize,
29734
+ index.lastUpdated
29735
+ );
29736
+ if (indexCache.has(key)) return;
29737
+ const byteSize = estimateIndexCacheBytes(index);
29738
+ if (byteSize > getIndexCacheMaxBytes() || getIndexCacheBytes() + byteSize > getIndexCacheMaxBytes() || indexCache.size >= INDEX_CACHE_MAX_ENTRIES) {
29739
+ debugLogger14.debug(
29740
+ `fresh index cache offer skipped ${key} byteSize=${byteSize}`
29741
+ );
29742
+ return;
29743
+ }
29744
+ indexCache.set(key, {
29745
+ value: index,
29746
+ byteSize,
29747
+ expiresAt: Date.now() + INDEX_CACHE_TTL_MS
29748
+ });
29749
+ }
29750
+ __name(offerFreshIndexToCache, "offerFreshIndexToCache");
29751
+ function lastUuidMatching(index, predicate) {
29752
+ for (let position = index.runtimeUuids.length - 1; position >= 0; position--) {
29753
+ const uuid = index.runtimeUuids[position];
29754
+ const entry = index.byUuid.get(uuid);
29755
+ if (entry && predicate(entry)) return uuid;
29756
+ }
29757
+ return void 0;
29758
+ }
29759
+ __name(lastUuidMatching, "lastUuidMatching");
29760
+ function selectArtifactUuids(index) {
29761
+ return selectActiveSideArtifactRecordUuids(
29762
+ index.physicalRecords,
29763
+ index.runtimeUuids
29764
+ );
29765
+ }
29766
+ __name(selectArtifactUuids, "selectArtifactUuids");
29002
29767
  var SessionTranscriptReader = class {
29003
- constructor(workspaceCwd, cursorCodec) {
29768
+ constructor(workspaceCwd, cursorCodec, runtimeBaseDir) {
29004
29769
  this.workspaceCwd = workspaceCwd;
29005
29770
  this.cursorCodec = cursorCodec;
29006
- this.storage = new Storage(workspaceCwd);
29771
+ this.storage = new Storage(workspaceCwd, runtimeBaseDir);
29007
29772
  }
29008
29773
  static {
29009
29774
  __name(this, "SessionTranscriptReader");
@@ -29020,6 +29785,522 @@ var SessionTranscriptReader = class {
29020
29785
  `${sessionId}.jsonl`
29021
29786
  );
29022
29787
  }
29788
+ async readRestoreProjection(sessionId, options2, readOptions = {}) {
29789
+ const filePath = this.getSessionFilePath(sessionId);
29790
+ validateRestoreReplaySelection(options2.replay);
29791
+ addDaemonRequestAttribute(
29792
+ "qwen-code.daemon.session_restore.replay_mode",
29793
+ options2.replay.kind
29794
+ );
29795
+ addDaemonRequestAttribute(
29796
+ "qwen-code.daemon.session_restore.index_cache_state",
29797
+ "fresh"
29798
+ );
29799
+ let stats;
29800
+ try {
29801
+ stats = await fsp.stat(filePath);
29802
+ } catch (error) {
29803
+ if (isFileMissingError(error)) {
29804
+ throw new SessionTranscriptSnapshotUnavailableError(sessionId);
29805
+ }
29806
+ throw error;
29807
+ }
29808
+ const fileIdentity = fileIdentityFromStats(stats);
29809
+ const lastUpdated = new Date(stats.mtimeMs).toISOString();
29810
+ let index;
29811
+ const indexStartedAt = performance3.now();
29812
+ try {
29813
+ index = await buildIndex({
29814
+ filePath,
29815
+ fileIdentity,
29816
+ snapshotSize: stats.size,
29817
+ lastUpdated
29818
+ });
29819
+ } catch (error) {
29820
+ if (error instanceof EmptySessionTranscriptError) {
29821
+ if (await hasSnapshotSignature(
29822
+ filePath,
29823
+ fileIdentity,
29824
+ stats.size,
29825
+ lastUpdated
29826
+ )) {
29827
+ return void 0;
29828
+ }
29829
+ }
29830
+ throw error;
29831
+ } finally {
29832
+ recordRestoreStage("transcript_index", indexStartedAt);
29833
+ }
29834
+ recordRestoreIndexAttributes(index);
29835
+ const selectionStartedAt = performance3.now();
29836
+ let replaySelection;
29837
+ try {
29838
+ replaySelection = selectRestoreReplayUuids(
29839
+ index,
29840
+ sessionId,
29841
+ options2.replay
29842
+ );
29843
+ } finally {
29844
+ recordRestoreStage("resume_state_select", selectionStartedAt);
29845
+ }
29846
+ const replaySet = new Set(replaySelection?.uuids ?? []);
29847
+ const modelSet = /* @__PURE__ */ new Set();
29848
+ let compressionPosition = -1;
29849
+ for (let position = 0; position < index.runtimeUuids.length; position++) {
29850
+ const entry = index.byUuid.get(index.runtimeUuids[position]);
29851
+ if (entry?.apiHistoryCompressionCandidate) {
29852
+ compressionPosition = position;
29853
+ }
29854
+ }
29855
+ for (let position = 0; position < index.runtimeUuids.length; position++) {
29856
+ const uuid = index.runtimeUuids[position];
29857
+ const entry = index.byUuid.get(uuid);
29858
+ if (position === compressionPosition || entry?.type !== "system" && (compressionPosition < 0 || position > compressionPosition)) {
29859
+ modelSet.add(uuid);
29860
+ }
29861
+ }
29862
+ addDaemonRequestAttribute(
29863
+ "qwen-code.daemon.session_restore.compression_selected",
29864
+ compressionPosition >= 0
29865
+ );
29866
+ addDaemonRequestAttribute(
29867
+ "qwen-code.daemon.session_restore.legacy_full_model_history",
29868
+ compressionPosition < 0
29869
+ );
29870
+ const tokenUuid = lastUuidMatching(
29871
+ index,
29872
+ (entry) => entry.resumeTokenCountsCandidate
29873
+ );
29874
+ const attributionUuid = lastUuidMatching(
29875
+ index,
29876
+ (entry) => entry.attributionSnapshotCandidate
29877
+ );
29878
+ const parentSessionUuid = lastUuidMatching(
29879
+ index,
29880
+ (entry) => entry.type === "system" && entry.subtype === "parent_session"
29881
+ );
29882
+ const sessionSourceUuid = lastUuidMatching(
29883
+ index,
29884
+ (entry) => entry.type === "system" && entry.subtype === "session_source"
29885
+ );
29886
+ const uiTelemetrySet = new Set(
29887
+ index.runtimeUuids.filter((uuid) => {
29888
+ const entry = index.byUuid.get(uuid);
29889
+ return entry?.type === "system" && entry.subtype === "ui_telemetry";
29890
+ })
29891
+ );
29892
+ const fileHistorySet = new Set(
29893
+ index.runtimeUuids.filter((uuid) => {
29894
+ const entry = index.byUuid.get(uuid);
29895
+ return entry?.type === "system" && entry.subtype === "file_history_snapshot";
29896
+ })
29897
+ );
29898
+ const goalSet = new Set(
29899
+ index.runtimeUuids.filter(
29900
+ (uuid) => index.byUuid.get(uuid)?.goalRecoveryCandidate === true
29901
+ )
29902
+ );
29903
+ const replayGoalSet = new Set(
29904
+ replaySelection ? replaySelection.index.replayUuids.filter(
29905
+ (uuid) => index.byUuid.get(uuid)?.goalRecoveryCandidate === true
29906
+ ) : []
29907
+ );
29908
+ const artifactUuids = selectArtifactUuids(index);
29909
+ const artifactSet = new Set(artifactUuids);
29910
+ const metadataSet = new Set(
29911
+ [parentSessionUuid, sessionSourceUuid].filter(
29912
+ (uuid) => uuid !== void 0
29913
+ )
29914
+ );
29915
+ const apiHistory = new SessionApiHistoryAccumulator();
29916
+ const resumeTokenCounts = new ResumeTokenCountsAccumulator();
29917
+ const turnState = new SessionTurnStateAccumulator(sessionId);
29918
+ for (const uuid of index.runtimeUuids) {
29919
+ const hint = index.byUuid.get(uuid)?.turnHint;
29920
+ if (hint) turnState.addHint(hint);
29921
+ }
29922
+ const uiTelemetryEvents = [];
29923
+ const fileHistory = new SessionFileHistoryAccumulator();
29924
+ const artifacts = new SessionArtifactSnapshotAccumulator(sessionId);
29925
+ const goalRecords = [];
29926
+ const goalStatePayloads = /* @__PURE__ */ new Map();
29927
+ const replayRecordsByUuid = /* @__PURE__ */ new Map();
29928
+ let attributionSnapshot;
29929
+ let parentSessionId;
29930
+ let sourceType;
29931
+ let sourceId;
29932
+ let firstRecord;
29933
+ let firstRecordSeen = false;
29934
+ let goalCheckpointAccumulator;
29935
+ let goalEvidenceSet = /* @__PURE__ */ new Set();
29936
+ const deferredPreReadRecords = /* @__PURE__ */ new Map();
29937
+ const dispatchRecord = /* @__PURE__ */ __name((record2) => {
29938
+ if (modelSet.has(record2.uuid)) apiHistory.add(record2);
29939
+ if (record2.uuid === tokenUuid) resumeTokenCounts.add(record2);
29940
+ if (uiTelemetrySet.has(record2.uuid)) {
29941
+ const uiEvent = record2.systemPayload?.uiEvent;
29942
+ if (uiEvent) uiTelemetryEvents.push(uiEvent);
29943
+ }
29944
+ if (record2.uuid === attributionUuid) {
29945
+ const snapshot = record2.systemPayload?.snapshot;
29946
+ if (snapshot && typeof snapshot === "object") {
29947
+ attributionSnapshot = snapshot;
29948
+ }
29949
+ }
29950
+ if (record2.uuid === parentSessionUuid) {
29951
+ parentSessionId = record2.systemPayload?.parentSessionId;
29952
+ } else if (record2.uuid === sessionSourceUuid) {
29953
+ const payload = record2.systemPayload;
29954
+ sourceType = payload?.sourceType;
29955
+ sourceId = payload?.sourceId;
29956
+ }
29957
+ if (fileHistorySet.has(record2.uuid)) {
29958
+ try {
29959
+ fileHistory.add(record2);
29960
+ } catch (error) {
29961
+ debugLogger14.warn(
29962
+ `restore projection: skipping malformed file_history_snapshot: ${error}`
29963
+ );
29964
+ }
29965
+ }
29966
+ if (artifactSet.has(record2.uuid)) artifacts.add(record2);
29967
+ if (goalEvidenceSet.has(record2.uuid)) {
29968
+ goalCheckpointAccumulator?.capture(record2);
29969
+ }
29970
+ if (replaySet.has(record2.uuid)) {
29971
+ replayRecordsByUuid.set(record2.uuid, record2);
29972
+ }
29973
+ }, "dispatchRecord");
29974
+ const preReadUuids = Array.from(
29975
+ /* @__PURE__ */ new Set([
29976
+ index.firstRecordUuid,
29977
+ ...index.runtimeUuids.filter((uuid) => goalSet.has(uuid))
29978
+ ])
29979
+ );
29980
+ const selectedReadsStartedAt = performance3.now();
29981
+ const selectedReadSet = new Set(preReadUuids);
29982
+ let goalRecovery;
29983
+ try {
29984
+ goalRecovery = await withAggregatedRecordReadContext(
29985
+ index,
29986
+ async (readContext) => {
29987
+ await forEachAggregatedRecord(
29988
+ index,
29989
+ preReadUuids,
29990
+ async (record2) => {
29991
+ if (record2.uuid === index.firstRecordUuid) {
29992
+ if (readOptions.validateFirstRecord && !await readOptions.validateFirstRecord(record2)) {
29993
+ throw new SessionTranscriptSnapshotUnavailableError(
29994
+ sessionId
29995
+ );
29996
+ }
29997
+ firstRecordSeen = true;
29998
+ if (!goalSet.has(record2.uuid)) firstRecord = record2;
29999
+ }
30000
+ if (goalSet.has(record2.uuid)) {
30001
+ const normalized2 = normalizeGoalRecoveryRecord(record2);
30002
+ if (normalized2) {
30003
+ goalRecords.push(normalized2);
30004
+ if (record2.subtype === "goal_state") {
30005
+ goalStatePayloads.set(
30006
+ record2.uuid,
30007
+ parseGoalStateRecordPayloadV2(normalized2.systemPayload)
30008
+ );
30009
+ }
30010
+ }
30011
+ }
30012
+ if (replaySet.has(record2.uuid)) {
30013
+ replayRecordsByUuid.set(record2.uuid, record2);
30014
+ }
30015
+ const needsDeferredDispatch = modelSet.has(record2.uuid) || record2.uuid === tokenUuid || record2.uuid === attributionUuid || metadataSet.has(record2.uuid) || uiTelemetrySet.has(record2.uuid) || fileHistorySet.has(record2.uuid) || artifactSet.has(record2.uuid);
30016
+ if (needsDeferredDispatch) {
30017
+ if (record2.uuid === index.firstRecordUuid && artifactSet.has(record2.uuid)) {
30018
+ artifacts.add(record2);
30019
+ } else {
30020
+ deferredPreReadRecords.set(record2.uuid, record2);
30021
+ }
30022
+ }
30023
+ },
30024
+ readContext
30025
+ );
30026
+ if (!firstRecordSeen) {
30027
+ throw new SessionTranscriptSnapshotUnavailableError(sessionId);
30028
+ }
30029
+ const selectedGoalRecovery = selectGoalRecoveryFromRecords(goalRecords);
30030
+ const pendingGoal = selectedGoalRecovery.recovery.kind === "v2" ? selectedGoalRecovery.recovery.payload : void 0;
30031
+ const pendingCheckpoint = pendingGoal?.checkpointPending;
30032
+ if (pendingCheckpoint && pendingGoal.snapshot.goal) {
30033
+ try {
30034
+ goalCheckpointAccumulator = new GoalEvidenceCheckpointAccumulator(
30035
+ index.runtimeUuids.map(
30036
+ (uuid) => index.byUuid.get(uuid).goalEvidenceHint
30037
+ ),
30038
+ pendingGoal.snapshot.goal,
30039
+ pendingCheckpoint.permit
30040
+ );
30041
+ } catch (error) {
30042
+ if (!(error instanceof EvidenceSourceUnavailableError)) {
30043
+ throw error;
30044
+ }
30045
+ debugLogger14.warn(
30046
+ `restore projection: deferring unavailable Goal checkpoint evidence: ${error.message}`
30047
+ );
30048
+ }
30049
+ }
30050
+ goalEvidenceSet = new Set(
30051
+ goalCheckpointAccumulator?.getCandidateUuids() ?? []
30052
+ );
30053
+ if (firstRecord && goalEvidenceSet.has(firstRecord.uuid)) {
30054
+ goalCheckpointAccumulator?.capture(firstRecord);
30055
+ }
30056
+ firstRecord = void 0;
30057
+ const selectedRuntimeUuids = index.runtimeUuids.filter(
30058
+ (uuid) => modelSet.has(uuid) || uuid === tokenUuid || uuid === attributionUuid || metadataSet.has(uuid) || uiTelemetrySet.has(uuid) || fileHistorySet.has(uuid) || replaySet.has(uuid) || goalEvidenceSet.has(uuid)
30059
+ );
30060
+ const preReadSet = new Set(preReadUuids);
30061
+ readContext.preloadedRecords = deferredPreReadRecords;
30062
+ const remainingUuids = Array.from(
30063
+ /* @__PURE__ */ new Set([...selectedRuntimeUuids, ...artifactUuids])
30064
+ ).filter(
30065
+ (uuid) => !preReadSet.has(uuid) || deferredPreReadRecords.has(uuid)
30066
+ );
30067
+ for (const uuid of remainingUuids) selectedReadSet.add(uuid);
30068
+ await forEachAggregatedRecord(
30069
+ index,
30070
+ remainingUuids,
30071
+ dispatchRecord,
30072
+ readContext
30073
+ );
30074
+ let goalCheckpointWindow;
30075
+ try {
30076
+ goalCheckpointWindow = goalCheckpointAccumulator?.finish();
30077
+ } catch (error) {
30078
+ if (!(error instanceof InvalidGoalEvidenceReferenceError)) {
30079
+ throw error;
30080
+ }
30081
+ debugLogger14.warn(
30082
+ `restore projection: deferring invalid Goal checkpoint evidence: ${error.message}`
30083
+ );
30084
+ }
30085
+ return { selectedGoalRecovery, goalCheckpointWindow };
30086
+ }
30087
+ );
30088
+ } finally {
30089
+ recordRestoreStage("selected_record_read", selectedReadsStartedAt);
30090
+ }
30091
+ recordRestoreSelectionAttributes(index, selectedReadSet, replaySet);
30092
+ let persistedTitle;
30093
+ try {
30094
+ persistedTitle = readSessionTitleInfoFromFileSync(index.filePath);
30095
+ } catch (error) {
30096
+ if (isFileMissingError(error)) {
30097
+ throw new SessionTranscriptSnapshotUnavailableError(sessionId);
30098
+ }
30099
+ throw error;
30100
+ }
30101
+ const customTitle = persistedTitle.title;
30102
+ const titleSource = persistedTitle.source;
30103
+ const turnStateValue = turnState.finish();
30104
+ const replayRecords = replaySelection ? replaySelection.uuids.map((uuid) => replayRecordsByUuid.get(uuid)).filter((record2) => record2 !== void 0) : [];
30105
+ const replayGoalRecords = replaySelection ? goalRecords.filter((record2) => replayGoalSet.has(record2.uuid)) : [];
30106
+ const replayGoalRecoverySourceUuid = replaySelection ? selectGoalRecoveryFromRecords(replayGoalRecords).sourceUuid : goalRecovery.selectedGoalRecovery.sourceUuid;
30107
+ let replay;
30108
+ if (replaySelection) {
30109
+ const goalStatePosition = replaySelection.index.goalStatePositions.findLast(
30110
+ (position) => position < replaySelection.nextPosition
30111
+ );
30112
+ const goalStateUuid = goalStatePosition === void 0 ? void 0 : replaySelection.index.replayUuids[goalStatePosition];
30113
+ const goalState = goalStateUuid ? goalStatePayloads.get(goalStateUuid) : void 0;
30114
+ replay = {
30115
+ records: replayRecords,
30116
+ gaps: index.gaps,
30117
+ hasMore: replaySelection.hasMore,
30118
+ ...replaySelection.hasMore && replayRecords[0] ? { anchorRecordId: replayRecords[0].uuid } : {},
30119
+ ...replayGoalRecoverySourceUuid && !replaySet.has(replayGoalRecoverySourceUuid) ? { goalBootstrapRecords: replayGoalRecords } : {},
30120
+ ...replayGoalRecoverySourceUuid ? { goalRecoverySourceUuid: replayGoalRecoverySourceUuid } : {},
30121
+ ...goalState ? {
30122
+ replay: {
30123
+ goalState: goalState.snapshot,
30124
+ goalCause: goalState.cause
30125
+ }
30126
+ } : {}
30127
+ };
30128
+ }
30129
+ const restoredTokenCounts = resumeTokenCounts.finish();
30130
+ const restoredFileHistory = fileHistory.finish();
30131
+ const artifactSnapshot = artifacts.finish();
30132
+ const runtime = {
30133
+ apiHistory: apiHistory.finish(),
30134
+ ...restoredTokenCounts ? { resumeTokenCounts: restoredTokenCounts } : {},
30135
+ uiTelemetryEvents,
30136
+ ...attributionSnapshot ? { attributionSnapshot } : {},
30137
+ ...index.gaps.length > 0 ? { historyGaps: index.gaps } : {},
30138
+ recording: {
30139
+ lastCompletedUuid: index.leafUuid,
30140
+ turnParentUuids: turnStateValue.turnParentUuids,
30141
+ ...customTitle !== void 0 ? { customTitle } : {},
30142
+ ...titleSource !== void 0 ? { titleSource } : {},
30143
+ ...parentSessionId !== void 0 ? { parentSessionId } : {},
30144
+ ...sourceType !== void 0 ? { sourceType } : {},
30145
+ ...sourceId !== void 0 ? { sourceId } : {}
30146
+ },
30147
+ ...restoredFileHistory ? { fileHistorySnapshots: restoredFileHistory } : {},
30148
+ ...artifactSnapshot ? { artifactSnapshot } : {},
30149
+ goalRecords,
30150
+ ...goalRecovery.selectedGoalRecovery.sourceUuid ? {
30151
+ goalRecoverySourceUuid: goalRecovery.selectedGoalRecovery.sourceUuid
30152
+ } : {},
30153
+ ...goalRecovery.goalCheckpointWindow ? { goalCheckpointWindow: goalRecovery.goalCheckpointWindow } : {},
30154
+ initialTurn: turnStateValue.initialTurn,
30155
+ backgroundNotificationTaskIds: turnStateValue.backgroundNotificationTaskIds
30156
+ };
30157
+ await assertIndexSnapshotUnchanged(index, sessionId);
30158
+ offerFreshIndexToCache(index);
30159
+ return {
30160
+ sessionId,
30161
+ filePath,
30162
+ startTime: index.restoreStartTime,
30163
+ lastUpdated: index.lastUpdated,
30164
+ runtime,
30165
+ ...replay ? { replay } : {}
30166
+ };
30167
+ }
30168
+ async readLiveRestoreProjection(sessionId, options2, readOptions = {}) {
30169
+ const filePath = this.getSessionFilePath(sessionId);
30170
+ validateRestoreReplaySelection(options2.replay);
30171
+ addDaemonRequestAttribute(
30172
+ "qwen-code.daemon.session_restore.replay_mode",
30173
+ options2.replay.kind
30174
+ );
30175
+ let stats;
30176
+ try {
30177
+ stats = await fsp.stat(filePath);
30178
+ } catch (error) {
30179
+ if (error.code === "ENOENT") return void 0;
30180
+ throw error;
30181
+ }
30182
+ let index;
30183
+ const fileIdentity = fileIdentityFromStats(stats);
30184
+ const lastUpdated = new Date(stats.mtimeMs).toISOString();
30185
+ const indexStartedAt = performance3.now();
30186
+ try {
30187
+ index = await getCachedIndex({
30188
+ filePath,
30189
+ fileIdentity,
30190
+ snapshotSize: stats.size,
30191
+ lastUpdated,
30192
+ onCacheState: /* @__PURE__ */ __name((state) => addDaemonRequestAttribute(
30193
+ "qwen-code.daemon.session_restore.index_cache_state",
30194
+ state
30195
+ ), "onCacheState")
30196
+ });
30197
+ } catch (error) {
30198
+ if (error instanceof EmptySessionTranscriptError) {
30199
+ if (await hasSnapshotSignature(
30200
+ filePath,
30201
+ fileIdentity,
30202
+ stats.size,
30203
+ lastUpdated
30204
+ )) {
30205
+ return void 0;
30206
+ }
30207
+ }
30208
+ throw error;
30209
+ } finally {
30210
+ recordRestoreStage("transcript_index", indexStartedAt);
30211
+ }
30212
+ recordRestoreIndexAttributes(index);
30213
+ const selectionStartedAt = performance3.now();
30214
+ const replaySelection = selectRestoreReplayUuids(
30215
+ index,
30216
+ sessionId,
30217
+ options2.replay
30218
+ );
30219
+ const replaySet = new Set(replaySelection?.uuids ?? []);
30220
+ const goalSet = new Set(
30221
+ replaySelection ? replaySelection.index.replayUuids.filter(
30222
+ (uuid) => index.byUuid.get(uuid)?.goalRecoveryCandidate === true
30223
+ ) : []
30224
+ );
30225
+ const goalStatePosition = replaySelection ? replaySelection.index.goalStatePositions.findLast(
30226
+ (position) => position < replaySelection.nextPosition
30227
+ ) : void 0;
30228
+ const goalStateUuid = goalStatePosition === void 0 || !replaySelection ? void 0 : replaySelection.index.replayUuids[goalStatePosition];
30229
+ const goalStateSet = new Set(goalStateUuid ? [goalStateUuid] : []);
30230
+ const artifactUuids = selectArtifactUuids(index);
30231
+ const artifactSet = new Set(artifactUuids);
30232
+ const selectedRuntimeUuids = index.runtimeUuids.filter(
30233
+ (uuid) => replaySet.has(uuid) || goalStateSet.has(uuid) || goalSet.has(uuid)
30234
+ );
30235
+ if (!selectedRuntimeUuids.includes(index.firstRecordUuid)) {
30236
+ selectedRuntimeUuids.unshift(index.firstRecordUuid);
30237
+ }
30238
+ const replayRecords = [];
30239
+ const goalRecords = [];
30240
+ const goalStatePayloads = /* @__PURE__ */ new Map();
30241
+ const artifacts = new SessionArtifactSnapshotAccumulator(sessionId);
30242
+ recordRestoreStage("resume_state_select", selectionStartedAt);
30243
+ const selectedReadSet = /* @__PURE__ */ new Set([
30244
+ ...selectedRuntimeUuids,
30245
+ ...artifactUuids
30246
+ ]);
30247
+ const selectedReadsStartedAt = performance3.now();
30248
+ try {
30249
+ await forEachAggregatedRecord(
30250
+ index,
30251
+ [...selectedReadSet],
30252
+ async (record2) => {
30253
+ if (record2.uuid === index.firstRecordUuid && readOptions.validateFirstRecord && !await readOptions.validateFirstRecord(record2)) {
30254
+ throw new SessionTranscriptSnapshotUnavailableError(sessionId);
30255
+ }
30256
+ if (replaySet.has(record2.uuid)) replayRecords.push(record2);
30257
+ if (goalStateSet.has(record2.uuid)) {
30258
+ goalStatePayloads.set(
30259
+ record2.uuid,
30260
+ parseGoalStateRecordPayloadV2(record2.systemPayload)
30261
+ );
30262
+ }
30263
+ if (goalSet.has(record2.uuid)) {
30264
+ const normalized2 = normalizeGoalRecoveryRecord(record2);
30265
+ if (normalized2) goalRecords.push(normalized2);
30266
+ }
30267
+ if (artifactSet.has(record2.uuid)) artifacts.add(record2);
30268
+ }
30269
+ );
30270
+ } finally {
30271
+ recordRestoreStage("selected_record_read", selectedReadsStartedAt);
30272
+ }
30273
+ recordRestoreSelectionAttributes(index, selectedReadSet, replaySet);
30274
+ let replay;
30275
+ if (replaySelection) {
30276
+ const goalState = goalStateUuid ? goalStatePayloads.get(goalStateUuid) : void 0;
30277
+ replay = {
30278
+ records: replayRecords,
30279
+ gaps: index.gaps,
30280
+ hasMore: replaySelection.hasMore,
30281
+ ...replaySelection.hasMore && replayRecords[0] ? { anchorRecordId: replayRecords[0].uuid } : {},
30282
+ ...goalState ? {
30283
+ replay: {
30284
+ goalState: goalState.snapshot,
30285
+ goalCause: goalState.cause
30286
+ }
30287
+ } : {}
30288
+ };
30289
+ }
30290
+ const artifactSnapshot = artifacts.finish();
30291
+ const goalRecovery = selectGoalRecoveryFromRecords(goalRecords);
30292
+ const replayGoalRecoverySourceUuid = goalRecovery.sourceUuid && replaySelection?.index.replayUuids.includes(goalRecovery.sourceUuid) ? goalRecovery.sourceUuid : void 0;
30293
+ await assertIndexSnapshotUnchanged(index, sessionId);
30294
+ return {
30295
+ sessionId,
30296
+ startTime: index.restoreStartTime,
30297
+ lastUpdated: index.lastUpdated,
30298
+ ...replay ? { replay } : {},
30299
+ ...artifactSnapshot ? { artifactSnapshot } : {},
30300
+ ...goalRecords.length > 0 ? { goalRecords } : {},
30301
+ ...replayGoalRecoverySourceUuid ? { goalRecoverySourceUuid: replayGoalRecoverySourceUuid } : {}
30302
+ };
30303
+ }
29023
30304
  async readPage(sessionId, options2 = {}) {
29024
30305
  const limit = normalizeLimit(options2.limit);
29025
30306
  const maxBytes = normalizeMaxBytes(options2.maxBytes);
@@ -29057,19 +30338,19 @@ var SessionTranscriptReader = class {
29057
30338
  throw new SessionTranscriptSnapshotUnavailableError(sessionId);
29058
30339
  }
29059
30340
  const direction = cursor?.direction ?? options2.direction ?? (options2.beforeRecordId !== void 0 ? "backward" : "forward");
29060
- let position = cursor?.position ?? (direction === "backward" ? index.activeUuids.length : 0);
30341
+ let position = cursor?.position ?? (direction === "backward" ? index.replayUuids.length : 0);
29061
30342
  if (!cursor && options2.beforeRecordId !== void 0) {
29062
30343
  if (options2.beforeRecordId.length === 0) {
29063
30344
  throw new InvalidSessionTranscriptCursorError();
29064
30345
  }
29065
- position = index.activeUuids.indexOf(options2.beforeRecordId);
30346
+ position = index.replayUuids.indexOf(options2.beforeRecordId);
29066
30347
  if (position < 0) {
29067
30348
  throw new InvalidSessionTranscriptCursorError();
29068
30349
  }
29069
30350
  }
29070
- if (position > index.activeUuids.length) {
30351
+ if (position > index.replayUuids.length) {
29071
30352
  debugLogger14.debug(
29072
- `cursor position out of range session=${sessionId} position=${position} active=${index.activeUuids.length}`
30353
+ `cursor position out of range session=${sessionId} position=${position} replay=${index.replayUuids.length}`
29073
30354
  );
29074
30355
  throw new InvalidSessionTranscriptCursorError();
29075
30356
  }
@@ -29078,7 +30359,7 @@ var SessionTranscriptReader = class {
29078
30359
  const nextPosition = backwardPage?.nextPosition ?? position + pageUuids.length;
29079
30360
  const records = await readAggregatedRecords(index, pageUuids);
29080
30361
  const backwardGoalState = direction === "backward" ? await readGoalStatePayloadBeforePosition(index, nextPosition) : void 0;
29081
- const hasMore = direction === "backward" ? nextPosition > 0 : nextPosition < index.activeUuids.length;
30362
+ const hasMore = direction === "backward" ? nextPosition > 0 : nextPosition < index.replayUuids.length;
29082
30363
  const nextCursorState = hasMore ? {
29083
30364
  v: SESSION_TRANSCRIPT_CURSOR_VERSION,
29084
30365
  sessionId,
@@ -31099,11 +32380,17 @@ var SessionService = class {
31099
32380
  projectHash;
31100
32381
  projectRoot;
31101
32382
  onWarning;
32383
+ transcriptReader;
31102
32384
  constructor(cwd, options2 = {}) {
31103
32385
  this.storage = new Storage(cwd, options2.runtimeBaseDir);
31104
32386
  this.projectRoot = cwd;
31105
32387
  this.projectHash = getProjectHash(cwd);
31106
32388
  this.onWarning = options2.onWarning;
32389
+ this.transcriptReader = new SessionTranscriptReader(
32390
+ cwd,
32391
+ void 0,
32392
+ options2.runtimeBaseDir
32393
+ );
31107
32394
  }
31108
32395
  /** The workspace root this service is bound to (the cwd it was constructed
31109
32396
  * with). Lets callers that already hold a service — e.g. the session
@@ -31364,18 +32651,7 @@ var SessionService = class {
31364
32651
  * user's pre-upgrade rename is never displayed as if it were auto-generated.
31365
32652
  */
31366
32653
  readSessionTitleInfoFromFile(filePath, tailBuffer) {
31367
- const hit = readLastJsonStringFieldsSync(
31368
- filePath,
31369
- "customTitle",
31370
- ["titleSource"],
31371
- '"subtype":"custom_title"',
31372
- tailBuffer
31373
- );
31374
- const title = hit["customTitle"];
31375
- if (!title) return {};
31376
- const rawSource = hit["titleSource"];
31377
- const source = rawSource === "auto" || rawSource === "manual" ? rawSource : void 0;
31378
- return { title, source };
32654
+ return readSessionTitleInfoFromFileSync(filePath, tailBuffer);
31379
32655
  }
31380
32656
  /**
31381
32657
  * Extracts the `parent_session` record's `parentSessionId` from records
@@ -31816,6 +33092,16 @@ var SessionService = class {
31816
33092
  async loadSession(sessionId) {
31817
33093
  return this.loadSessionFromState(sessionId, "active");
31818
33094
  }
33095
+ async readRestoreProjection(sessionId, options2) {
33096
+ return this.transcriptReader.readRestoreProjection(sessionId, options2, {
33097
+ validateFirstRecord: /* @__PURE__ */ __name((record2) => this.sessionBelongsToCurrentProject(record2.sessionId, record2.cwd), "validateFirstRecord")
33098
+ });
33099
+ }
33100
+ async readLiveRestoreProjection(sessionId, options2) {
33101
+ return this.transcriptReader.readLiveRestoreProjection(sessionId, options2, {
33102
+ validateFirstRecord: /* @__PURE__ */ __name((record2) => this.sessionBelongsToCurrentProject(record2.sessionId, record2.cwd), "validateFirstRecord")
33103
+ });
33104
+ }
31819
33105
  /**
31820
33106
  * Reads an archived session without changing its archive state.
31821
33107
  * Daemon load/resume paths must continue to use {@link loadSession}.
@@ -31881,33 +33167,17 @@ var SessionService = class {
31881
33167
  lastUpdated: new Date(stats.mtimeMs).toISOString(),
31882
33168
  messages
31883
33169
  };
31884
- const fileHistorySnapshots = [];
31885
- const seenPromptIds = /* @__PURE__ */ new Map();
33170
+ const fileHistoryAccumulator = new SessionFileHistoryAccumulator();
31886
33171
  for (const msg of messages) {
31887
- if (msg.type === "system" && msg.subtype === "file_history_snapshot" && msg.systemPayload) {
31888
- const payload = msg.systemPayload;
31889
- if (!Array.isArray(payload?.snapshots)) continue;
31890
- let deserialized;
31891
- try {
31892
- deserialized = deserializeSnapshots(payload.snapshots);
31893
- } catch (e) {
31894
- debugLogger16.warn(
31895
- `loadSession: skipping malformed file_history_snapshot: ${e}`
31896
- );
31897
- continue;
31898
- }
31899
- for (const s3 of deserialized) {
31900
- const existingIdx = seenPromptIds.get(s3.promptId);
31901
- if (existingIdx !== void 0) {
31902
- fileHistorySnapshots[existingIdx] = s3;
31903
- } else {
31904
- seenPromptIds.set(s3.promptId, fileHistorySnapshots.length);
31905
- fileHistorySnapshots.push(s3);
31906
- }
31907
- }
33172
+ try {
33173
+ fileHistoryAccumulator.add(msg);
33174
+ } catch (e) {
33175
+ debugLogger16.warn(
33176
+ `loadSession: skipping malformed file_history_snapshot: ${e}`
33177
+ );
31908
33178
  }
31909
33179
  }
31910
- const cappedSnapshots = fileHistorySnapshots.length > MAX_SNAPSHOTS ? fileHistorySnapshots.slice(-MAX_SNAPSHOTS) : fileHistorySnapshots;
33180
+ const fileHistorySnapshots = fileHistoryAccumulator.finish();
31911
33181
  const activeBranchRecords = includeActiveSideArtifactRecords(
31912
33182
  records,
31913
33183
  messages
@@ -31920,7 +33190,7 @@ var SessionService = class {
31920
33190
  conversation,
31921
33191
  filePath,
31922
33192
  lastCompletedUuid: lastMessage.uuid,
31923
- fileHistorySnapshots: cappedSnapshots.length > 0 ? cappedSnapshots : void 0,
33193
+ fileHistorySnapshots,
31924
33194
  ...artifactSnapshot ? { artifactSnapshot } : {},
31925
33195
  historyGaps: gaps.length > 0 ? gaps : void 0
31926
33196
  };
@@ -32547,95 +33817,6 @@ var SessionService = class {
32547
33817
  }
32548
33818
  }
32549
33819
  };
32550
- function stripThoughtsFromContent(content) {
32551
- if (!content.parts) return content;
32552
- const filteredParts = content.parts.filter((part) => !part.thought);
32553
- if (filteredParts.length === 0) {
32554
- return null;
32555
- }
32556
- return {
32557
- ...content,
32558
- parts: filteredParts
32559
- };
32560
- }
32561
- __name(stripThoughtsFromContent, "stripThoughtsFromContent");
32562
- function copyContentForApiHistory(content) {
32563
- return {
32564
- ...content,
32565
- parts: content.parts?.map((part) => {
32566
- if ("functionCall" in part && part.functionCall) {
32567
- return {
32568
- ...part,
32569
- functionCall: {
32570
- ...part.functionCall,
32571
- args: part.functionCall.args ? { ...part.functionCall.args } : part.functionCall.args
32572
- }
32573
- };
32574
- }
32575
- if ("functionResponse" in part && part.functionResponse) {
32576
- return {
32577
- ...part,
32578
- functionResponse: {
32579
- ...part.functionResponse
32580
- }
32581
- };
32582
- }
32583
- return { ...part };
32584
- })
32585
- };
32586
- }
32587
- __name(copyContentForApiHistory, "copyContentForApiHistory");
32588
- function appendApiHistoryRecord(history, record2) {
32589
- if (!record2.message || record2.subtype === "realtime_message") return;
32590
- const message = copyContentForApiHistory(record2.message);
32591
- if (record2.subtype === "mid_turn_user_message") {
32592
- const previous = history.at(-1);
32593
- if (previous?.role === "user") {
32594
- previous.parts = [...previous.parts ?? [], ...message.parts ?? []];
32595
- return;
32596
- }
32597
- }
32598
- history.push(message);
32599
- }
32600
- __name(appendApiHistoryRecord, "appendApiHistoryRecord");
32601
- function buildApiHistoryFromConversation(conversation, options2 = {}) {
32602
- const { stripThoughtsFromHistory = false } = options2;
32603
- const { messages } = conversation;
32604
- let lastCompressionIndex = -1;
32605
- let compressedHistory;
32606
- messages.forEach((record2, index) => {
32607
- if (record2.type === "system" && record2.subtype === "chat_compression") {
32608
- const payload = record2.systemPayload;
32609
- if (payload?.compressedHistory) {
32610
- lastCompressionIndex = index;
32611
- compressedHistory = payload.compressedHistory;
32612
- }
32613
- }
32614
- });
32615
- if (compressedHistory && lastCompressionIndex >= 0) {
32616
- const baseHistory = compressedHistory.map(
32617
- copyContentForApiHistory
32618
- );
32619
- for (let i = lastCompressionIndex + 1; i < messages.length; i++) {
32620
- const record2 = messages[i];
32621
- if (record2.type === "system") continue;
32622
- appendApiHistoryRecord(baseHistory, record2);
32623
- }
32624
- if (stripThoughtsFromHistory) {
32625
- return baseHistory.map(stripThoughtsFromContent).filter((content) => content !== null);
32626
- }
32627
- return baseHistory;
32628
- }
32629
- const result = [];
32630
- for (const record2 of messages) {
32631
- appendApiHistoryRecord(result, record2);
32632
- }
32633
- if (stripThoughtsFromHistory) {
32634
- return result.map(stripThoughtsFromContent).filter((content) => content !== null);
32635
- }
32636
- return result;
32637
- }
32638
- __name(buildApiHistoryFromConversation, "buildApiHistoryFromConversation");
32639
33820
  function remapSnapshotPromptId(snapshot, sourceSessionId, newSessionId) {
32640
33821
  const sourcePrefix = `${sourceSessionId}########`;
32641
33822
  if (!snapshot.promptId.startsWith(sourcePrefix)) {
@@ -32686,60 +33867,25 @@ function includeActiveSideArtifactRecords(records, activeRecords) {
32686
33867
  const activeByUuid = new Map(
32687
33868
  activeRecords.map((record2) => [record2.uuid, record2])
32688
33869
  );
32689
- const activeUuids = new Set(activeByUuid.keys());
32690
- const firstActiveUuid = activeRecords[0]?.uuid;
32691
- const firstActiveIndex = firstActiveUuid === void 0 ? -1 : records.findIndex((record2) => record2.uuid === firstActiveUuid);
32692
- const nextActiveUuidByIndex = /* @__PURE__ */ new Map();
32693
- const nextBlockingUuidByIndex = /* @__PURE__ */ new Map();
32694
- let nextActiveUuid;
32695
- let nextBlockingUuid;
32696
- for (let index = records.length - 1; index >= 0; index--) {
32697
- if (nextActiveUuid !== void 0) {
32698
- nextActiveUuidByIndex.set(index, nextActiveUuid);
32699
- }
32700
- if (nextBlockingUuid !== void 0) {
32701
- nextBlockingUuidByIndex.set(index, nextBlockingUuid);
32702
- }
32703
- if (activeUuids.has(records[index].uuid)) {
32704
- nextActiveUuid = records[index].uuid;
32705
- nextBlockingUuid = void 0;
32706
- } else if (!isSessionArtifactRecord(records[index]) && !isTailNeutralSideRecord(records[index])) {
32707
- nextBlockingUuid = records[index].uuid;
32708
- }
32709
- }
33870
+ const artifactUuids = new Set(
33871
+ selectActiveSideArtifactRecordUuids(
33872
+ records,
33873
+ activeRecords.map((record2) => record2.uuid)
33874
+ )
33875
+ );
32710
33876
  const selected = [];
32711
- const includedSideArtifactUuids = /* @__PURE__ */ new Set();
32712
- let previousActiveUuid;
32713
- for (let index = 0; index < records.length; index++) {
32714
- const record2 = records[index];
33877
+ for (const record2 of records) {
32715
33878
  const activeRecord = activeByUuid.get(record2.uuid);
32716
33879
  if (activeRecord) {
32717
33880
  selected.push(activeRecord);
32718
33881
  activeByUuid.delete(record2.uuid);
32719
- previousActiveUuid = record2.uuid;
32720
- continue;
32721
- }
32722
- if (!isSessionArtifactRecord(record2)) {
32723
33882
  continue;
32724
33883
  }
32725
- const nextUuid = nextActiveUuidByIndex.get(index);
32726
- const hasBlockingRecordBeforeNextActive = nextBlockingUuidByIndex.has(index);
32727
- const isInActiveSegment = !hasBlockingRecordBeforeNextActive && (nextUuid !== void 0 ? activeUuids.has(nextUuid) : previousActiveUuid !== void 0 && activeUuids.has(previousActiveUuid));
32728
- if (record2.parentUuid !== null && (activeUuids.has(record2.parentUuid) || includedSideArtifactUuids.has(record2.parentUuid)) && isInActiveSegment && (record2.parentUuid === previousActiveUuid || includedSideArtifactUuids.has(record2.parentUuid))) {
32729
- selected.push(record2);
32730
- includedSideArtifactUuids.add(record2.uuid);
32731
- } else if (record2.parentUuid === null && index < firstActiveIndex && isInActiveSegment) {
32732
- selected.push(record2);
32733
- includedSideArtifactUuids.add(record2.uuid);
32734
- }
33884
+ if (artifactUuids.has(record2.uuid)) selected.push(record2);
32735
33885
  }
32736
33886
  return selected;
32737
33887
  }
32738
33888
  __name(includeActiveSideArtifactRecords, "includeActiveSideArtifactRecords");
32739
- function isTailNeutralSideRecord(record2) {
32740
- return record2.type === "system" && record2.subtype === "custom_title";
32741
- }
32742
- __name(isTailNeutralSideRecord, "isTailNeutralSideRecord");
32743
33889
  function collectFileHistorySnapshotPromptIds(records) {
32744
33890
  const ids = /* @__PURE__ */ new Set();
32745
33891
  for (const record2 of records) {
@@ -32783,37 +33929,6 @@ function replayUiTelemetryFromConversation(conversation, sessionId) {
32783
33929
  return resumeTokenCounts;
32784
33930
  }
32785
33931
  __name(replayUiTelemetryFromConversation, "replayUiTelemetryFromConversation");
32786
- function getResumeTokenCounts(conversation) {
32787
- for (let i = conversation.messages.length - 1; i >= 0; i--) {
32788
- const record2 = conversation.messages[i];
32789
- if (record2.type === "assistant") {
32790
- const usage = record2.usageMetadata;
32791
- const candidate = usage?.promptTokenCount ?? usage?.totalTokenCount;
32792
- if (candidate) {
32793
- return {
32794
- promptTokenCount: candidate,
32795
- outputTokenCount: getUsageOutputTokenCountForPromptEstimate(usage),
32796
- isEstimated: false
32797
- };
32798
- }
32799
- }
32800
- if (record2.type === "system" && record2.subtype === "chat_compression") {
32801
- const payload = record2.systemPayload;
32802
- if (payload?.info) {
32803
- return {
32804
- promptTokenCount: payload.info.newTokenCount,
32805
- outputTokenCount: 0,
32806
- // Checkpoints created before provenance was persisted are safest to
32807
- // treat as estimates: this keeps the output clamp's overhead pad on
32808
- // and prevents an optimistic resume from overflowing the window.
32809
- isEstimated: payload.info.newTokenCountIsEstimated ?? true
32810
- };
32811
- }
32812
- }
32813
- }
32814
- return void 0;
32815
- }
32816
- __name(getResumeTokenCounts, "getResumeTokenCounts");
32817
33932
  var MAX_BRANCH_COLLISION_SCAN = 99;
32818
33933
  async function computeUniqueBranchTitle(baseName, sessionService) {
32819
33934
  const maxSuffixLen = " (Branch 1234567890123)".length;
@@ -33118,24 +34233,28 @@ function copyGoalContext(goalContext) {
33118
34233
  }
33119
34234
  __name(copyGoalContext, "copyGoalContext");
33120
34235
  var ChatRecordingService = class {
33121
- constructor(config, onWriteFailure, writerLeaseRequired = config.isSessionWriterLeaseEnabled?.() ?? config.getExperimentalZedIntegration?.() ?? true) {
34236
+ constructor(config, onWriteFailure, writerLeaseRequired = config.isSessionWriterLeaseEnabled?.() ?? config.getExperimentalZedIntegration?.() ?? true, restoreState) {
33122
34237
  this.onWriteFailure = onWriteFailure;
33123
34238
  this.config = config;
33124
34239
  this.writerLeaseRequired = writerLeaseRequired;
33125
34240
  const resumed = config.getResumedSessionData();
33126
34241
  if (writerLeaseRequired) {
33127
- this.lastRecordUuid = resumed?.lastCompletedUuid ?? null;
34242
+ this.lastRecordUuid = restoreState?.lastCompletedUuid ?? resumed?.lastCompletedUuid ?? null;
33128
34243
  this.lastPersistedRecordUuid = this.lastRecordUuid;
33129
34244
  } else {
33130
34245
  this.state = "active";
33131
34246
  this.acceptingWrites = true;
33132
- this.restoreSessionState(
33133
- resumed ? {
33134
- conversation: resumed.conversation ?? { messages: [] },
33135
- lastCompletedUuid: resumed.lastCompletedUuid
33136
- } : void 0,
33137
- resumed ? this.readPersistedTitleInfo() : void 0
33138
- );
34247
+ if (restoreState) {
34248
+ this.restoreProjectedState(restoreState);
34249
+ } else {
34250
+ this.restoreSessionState(
34251
+ resumed ? {
34252
+ conversation: resumed.conversation ?? { messages: [] },
34253
+ lastCompletedUuid: resumed.lastCompletedUuid
34254
+ } : void 0,
34255
+ resumed ? this.readPersistedTitleInfo() : void 0
34256
+ );
34257
+ }
33139
34258
  }
33140
34259
  }
33141
34260
  static {
@@ -33339,12 +34458,29 @@ var ChatRecordingService = class {
33339
34458
  this.userDisplayTextsForTitle.shift();
33340
34459
  }
33341
34460
  }
33342
- activate(lease, sessionData, persistedTitleInfo) {
34461
+ restoreProjectedState(state) {
34462
+ this.lastRecordUuid = state.lastCompletedUuid;
34463
+ this.lastPersistedRecordUuid = state.lastCompletedUuid;
34464
+ this.turnParentUuids = [...state.turnParentUuids];
34465
+ this.currentCustomTitle = state.customTitle;
34466
+ this.currentTitleSource = state.titleSource;
34467
+ this.currentParentSessionId = state.parentSessionId;
34468
+ this.currentSourceType = state.sourceType;
34469
+ this.currentSourceId = state.sourceId;
34470
+ if (this.currentCustomTitle) {
34471
+ this.bytesSinceTitleAnchor = TITLE_REANCHOR_BYTES;
34472
+ }
34473
+ }
34474
+ activate(lease, sessionData, persistedTitleInfo, restoreState) {
33343
34475
  if (!this.writerLeaseRequired || this.state !== "inactive" || lease.sessionId !== this.config.getSessionId()) {
33344
34476
  throw new SessionWriterUnavailableError();
33345
34477
  }
33346
34478
  this.binding = { sessionId: lease.sessionId, lease };
33347
- this.restoreSessionState(sessionData, persistedTitleInfo);
34479
+ if (restoreState) {
34480
+ this.restoreProjectedState(restoreState);
34481
+ } else {
34482
+ this.restoreSessionState(sessionData, persistedTitleInfo);
34483
+ }
33348
34484
  this.state = "active";
33349
34485
  this.acceptingWrites = true;
33350
34486
  }
@@ -43833,6 +44969,19 @@ function detectCommandSubstitution(command) {
43833
44969
  }
43834
44970
  }
43835
44971
  if (char === "\\" && !inSingleQuotes) {
44972
+ if (nextChar === "\n" && command[i - 1] === "$") {
44973
+ let dollarStart = i - 1;
44974
+ while (dollarStart > 0 && command[dollarStart - 1] === "$") {
44975
+ dollarStart--;
44976
+ }
44977
+ let escapeStart = dollarStart;
44978
+ while (escapeStart > 0 && command[escapeStart - 1] === "\\") {
44979
+ escapeStart--;
44980
+ }
44981
+ if ((i - dollarStart) % 2 === 1 && (dollarStart - escapeStart) % 2 === 0 && command[i + 2] === "(") {
44982
+ return true;
44983
+ }
44984
+ }
43836
44985
  i += 2;
43837
44986
  continue;
43838
44987
  }
@@ -43855,6 +45004,9 @@ function detectCommandSubstitution(command) {
43855
45004
  if (char === "$" && nextChar === "(") {
43856
45005
  return true;
43857
45006
  }
45007
+ if (char === "$" && nextChar === "{" && /^\$\{[A-Za-z_][A-Za-z0-9_]*@P\}/.test(command.slice(i))) {
45008
+ return true;
45009
+ }
43858
45010
  if (char === "<" && nextChar === "(" && !inDoubleQuotes && !inBackticks) {
43859
45011
  return true;
43860
45012
  }
@@ -43870,7 +45022,7 @@ function detectCommandSubstitution(command) {
43870
45022
  return false;
43871
45023
  }
43872
45024
  __name(detectCommandSubstitution, "detectCommandSubstitution");
43873
- var COMMAND_SUBSTITUTION_WARNING = "Contains command substitution ($(...), backticks, <(...), or >(...)).";
45025
+ var COMMAND_SUBSTITUTION_WARNING = "Contains command substitution ($(...), backticks, <(...), >(...), or ${parameter@P}).";
43874
45026
  function hasShellSubstitution(rawCommand) {
43875
45027
  if (typeof rawCommand !== "string" || rawCommand.length === 0) return false;
43876
45028
  if (detectCommandSubstitution(rawCommand)) return true;
@@ -43890,7 +45042,7 @@ async function checkCommandPermissions(command, config, sessionAllowlist) {
43890
45042
  return {
43891
45043
  allAllowed: false,
43892
45044
  disallowedCommands: [command],
43893
- blockReason: "Command substitution using $(), `` ` ``, <(), or >() is not allowed for security reasons",
45045
+ blockReason: "Command substitution using $(), `` ` ``, <(), >(), or ${parameter@P} is not allowed for security reasons",
43894
45046
  isHardDenial: true
43895
45047
  };
43896
45048
  }
@@ -46766,7 +47918,16 @@ function evaluateSubstitutions(node) {
46766
47918
  /* @__PURE__ */ new Set(["command_substitution", "process_substitution"]),
46767
47919
  true
46768
47920
  );
46769
- if (substitutions.length === 0) return "read-only";
47921
+ if (substitutions.length === 0) {
47922
+ for (const expansion of collectDescendants(node, /* @__PURE__ */ new Set(["expansion"]))) {
47923
+ for (let i = 0; i < expansion.childCount - 1; i++) {
47924
+ if (expansion.child(i)?.type === "@" && expansion.child(i + 1)?.type === "P") {
47925
+ return "unknown";
47926
+ }
47927
+ }
47928
+ }
47929
+ return "read-only";
47930
+ }
46770
47931
  return mergeSafety(
46771
47932
  "unknown",
46772
47933
  ...substitutions.flatMap((substitution) => substitution.namedChildren).map(evaluateStatementSafety)
@@ -46914,6 +48075,13 @@ async function classifyInternal(command, cwd) {
46914
48075
  const safety = mergeSafety(
46915
48076
  ...root.namedChildren.map(evaluateStatementSafety)
46916
48077
  );
48078
+ if (safety === "read-only" && command.includes("\\\n")) {
48079
+ const normalizedSafety = await classifyInternal(
48080
+ command.replaceAll("\\\n", ""),
48081
+ cwd
48082
+ );
48083
+ if (normalizedSafety !== "read-only") return "unknown";
48084
+ }
46917
48085
  if (safety !== "read-only" || !cwd) return safety;
46918
48086
  return localGitConfigMakesCommandUnsafe(root, cwd) ? "unknown" : "read-only";
46919
48087
  } finally {
@@ -58674,7 +59842,7 @@ var HybridTokenStorage = class extends BaseTokenStorage {
58674
59842
  const forceFileStorage = process.env[FORCE_FILE_STORAGE_ENV_VAR] === "true";
58675
59843
  if (!forceFileStorage) {
58676
59844
  try {
58677
- const { KeychainTokenStorage: KeychainTokenStorage2 } = await import("./keychain-token-storage-JTWUYFU7.js");
59845
+ const { KeychainTokenStorage: KeychainTokenStorage2 } = await import("./keychain-token-storage-NKKCUHI2.js");
58678
59846
  const keychainStorage = new KeychainTokenStorage2(this.serviceName);
58679
59847
  const isAvailable = await keychainStorage.isAvailable();
58680
59848
  if (isAvailable) {
@@ -60821,7 +61989,7 @@ function populateMcpServerCommand(mcpServers, mcpServerCommand, cwd) {
60821
61989
  __name(populateMcpServerCommand, "populateMcpServerCommand");
60822
61990
  async function discoverTools(mcpServerName, mcpServerConfig, mcpClient, cliConfig, opts) {
60823
61991
  try {
60824
- const { mcpToTool } = await import("./node-YSOU44FX.js");
61992
+ const { mcpToTool } = await import("./node-UUDY34IG.js");
60825
61993
  const mcpCallableTool = mcpToTool(mcpClient, {
60826
61994
  timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC
60827
61995
  });
@@ -79292,9 +80460,8 @@ init_esbuild_shims();
79292
80460
 
79293
80461
  // packages/core/src/utils/getPty.ts
79294
80462
  init_esbuild_shims();
79295
- var BUN_FORCE_PTY_ENV_VAR = "QWEN_TUI_FORCE_PTY";
79296
80463
  var getPty = /* @__PURE__ */ __name(async () => {
79297
- if ("bun" in process.versions && process.env[BUN_FORCE_PTY_ENV_VAR] !== "1") {
80464
+ if ("bun" in process.versions) {
79298
80465
  return null;
79299
80466
  }
79300
80467
  try {
@@ -79317,45 +80484,6 @@ import { spawn as cpSpawn, spawnSync as spawnSync3 } from "node:child_process";
79317
80484
  import { TextDecoder as TextDecoder2 } from "node:util";
79318
80485
  import os11 from "node:os";
79319
80486
 
79320
- // packages/core/src/utils/textUtils.ts
79321
- init_esbuild_shims();
79322
- import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
79323
- var CONTROL_CHARS_RE = /[\u0000-\u001f\u007f-\u009f]/g;
79324
- function stripAnsiAndControl(text) {
79325
- return stripVTControlCharacters2(text).replace(CONTROL_CHARS_RE, "");
79326
- }
79327
- __name(stripAnsiAndControl, "stripAnsiAndControl");
79328
- function safeLiteralReplace(str, oldString, newString) {
79329
- if (oldString === "" || !str.includes(oldString)) {
79330
- return str;
79331
- }
79332
- if (!newString.includes("$")) {
79333
- return str.replaceAll(oldString, newString);
79334
- }
79335
- const escapedNewString = newString.replaceAll("$", "$$$$");
79336
- return str.replaceAll(oldString, escapedNewString);
79337
- }
79338
- __name(safeLiteralReplace, "safeLiteralReplace");
79339
- function isBinary(data, sampleSize = 512) {
79340
- if (!data) {
79341
- return false;
79342
- }
79343
- const sample = data.length > sampleSize ? data.subarray(0, sampleSize) : data;
79344
- for (const byte of sample) {
79345
- if (byte === 0) {
79346
- return true;
79347
- }
79348
- }
79349
- return false;
79350
- }
79351
- __name(isBinary, "isBinary");
79352
- function normalizeContent(content) {
79353
- let normalized2 = content.replace(/^\uFEFF/, "");
79354
- normalized2 = normalized2.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
79355
- return normalized2;
79356
- }
79357
- __name(normalizeContent, "normalizeContent");
79358
-
79359
80487
  // packages/core/src/utils/load-xterm-headless.ts
79360
80488
  init_esbuild_shims();
79361
80489
  var xtermHeadlessModulePromise;
@@ -79833,39 +80961,6 @@ var formatMemoryUsage = /* @__PURE__ */ __name((bytes) => {
79833
80961
  // packages/core/src/utils/shellContextEnv.ts
79834
80962
  init_esbuild_shims();
79835
80963
  import { accessSync as accessSync2, closeSync as closeSync3, constants as constants4, openSync as openSync3, readSync } from "node:fs";
79836
-
79837
- // packages/core/src/utils/sessionIdContext.ts
79838
- init_esbuild_shims();
79839
- import { AsyncLocalStorage } from "node:async_hooks";
79840
- var sessionIdContext = new AsyncLocalStorage();
79841
- var projectDirBySession = /* @__PURE__ */ new Map();
79842
- function registerSessionProjectDir(sessionId, projectDir) {
79843
- if (sessionId && projectDir) projectDirBySession.set(sessionId, projectDir);
79844
- }
79845
- __name(registerSessionProjectDir, "registerSessionProjectDir");
79846
- function getSessionProjectDir(sessionId) {
79847
- return projectDirBySession.get(sessionId);
79848
- }
79849
- __name(getSessionProjectDir, "getSessionProjectDir");
79850
- function unregisterSessionProjectDir(sessionId) {
79851
- projectDirBySession.delete(sessionId);
79852
- }
79853
- __name(unregisterSessionProjectDir, "unregisterSessionProjectDir");
79854
- var modelBySession = /* @__PURE__ */ new Map();
79855
- function registerSessionModel(sessionId, model) {
79856
- if (sessionId && model) modelBySession.set(sessionId, model);
79857
- }
79858
- __name(registerSessionModel, "registerSessionModel");
79859
- function getSessionModel(sessionId) {
79860
- return modelBySession.get(sessionId);
79861
- }
79862
- __name(getSessionModel, "getSessionModel");
79863
- function unregisterSessionModel(sessionId) {
79864
- modelBySession.delete(sessionId);
79865
- }
79866
- __name(unregisterSessionModel, "unregisterSessionModel");
79867
-
79868
- // packages/core/src/utils/shellContextEnv.ts
79869
80964
  var unusableCache = /* @__PURE__ */ new Map();
79870
80965
  function isUnusableScriptEntry(path103) {
79871
80966
  if (!/\.(?:mjs|cjs|js)$/i.test(path103)) return false;
@@ -80114,10 +81209,11 @@ var serializePlainViewportToAnsiOutput = /* @__PURE__ */ __name((terminal, unwra
80114
81209
  return lines;
80115
81210
  }, "serializePlainViewportToAnsiOutput");
80116
81211
  var WINDOWS_TASKKILL = `${process.env["SystemRoot"] || "C:\\Windows"}\\System32\\taskkill.exe`;
81212
+ var WINDOWS_TASKKILL_OPTIONS = { windowsHide: true };
80117
81213
  var windowsKillPid = /* @__PURE__ */ __name((pid, tree) => {
80118
81214
  try {
80119
81215
  const args = tree ? ["/f", "/t", "/pid", pid.toString()] : ["/f", "/pid", pid.toString()];
80120
- const killer = cpSpawn(WINDOWS_TASKKILL, args);
81216
+ const killer = cpSpawn(WINDOWS_TASKKILL, args, WINDOWS_TASKKILL_OPTIONS);
80121
81217
  killer.on("error", (e) => {
80122
81218
  debugLogger58.warn(
80123
81219
  `windowsKillPid: taskkill failed to launch for pid ${pid}: ${e.message}`
@@ -80139,7 +81235,11 @@ var windowsKillPid = /* @__PURE__ */ __name((pid, tree) => {
80139
81235
  var windowsStrategy = {
80140
81236
  killPty: /* @__PURE__ */ __name((pid, pty) => {
80141
81237
  try {
80142
- spawnSync3(WINDOWS_TASKKILL, ["/f", "/t", "/pid", pid.toString()]);
81238
+ spawnSync3(
81239
+ WINDOWS_TASKKILL,
81240
+ ["/f", "/t", "/pid", pid.toString()],
81241
+ WINDOWS_TASKKILL_OPTIONS
81242
+ );
80143
81243
  } catch {
80144
81244
  }
80145
81245
  try {
@@ -80154,7 +81254,7 @@ var windowsStrategy = {
80154
81254
  for (const pid of pids) {
80155
81255
  args.push("/pid", pid.toString());
80156
81256
  }
80157
- spawnSync3(WINDOWS_TASKKILL, args);
81257
+ spawnSync3(WINDOWS_TASKKILL, args, WINDOWS_TASKKILL_OPTIONS);
80158
81258
  } catch {
80159
81259
  }
80160
81260
  }
@@ -80615,12 +81715,11 @@ var ShellExecutionService = class _ShellExecutionService {
80615
81715
  const performCancelKill = /* @__PURE__ */ __name(async () => {
80616
81716
  if (!child.pid || exited) return;
80617
81717
  if (isWindows3) {
80618
- const killer = cpSpawn(WINDOWS_TASKKILL, [
80619
- "/f",
80620
- "/t",
80621
- "/pid",
80622
- child.pid.toString()
80623
- ]);
81718
+ const killer = cpSpawn(
81719
+ WINDOWS_TASKKILL,
81720
+ ["/f", "/t", "/pid", child.pid.toString()],
81721
+ WINDOWS_TASKKILL_OPTIONS
81722
+ );
80624
81723
  const killChildFallback = /* @__PURE__ */ __name((why) => {
80625
81724
  debugLogger58.warn(
80626
81725
  `performCancelKill (child_process): taskkill ${why} for pid ${child.pid}; falling back to child.kill`
@@ -81260,12 +82359,11 @@ var ShellExecutionService = class _ShellExecutionService {
81260
82359
  cancelKillDispatched = true;
81261
82360
  if (os11.platform() === "win32") {
81262
82361
  try {
81263
- const r = spawnSync3(WINDOWS_TASKKILL, [
81264
- "/f",
81265
- "/t",
81266
- "/pid",
81267
- ptyProcess.pid.toString()
81268
- ]);
82362
+ const r = spawnSync3(
82363
+ WINDOWS_TASKKILL,
82364
+ ["/f", "/t", "/pid", ptyProcess.pid.toString()],
82365
+ WINDOWS_TASKKILL_OPTIONS
82366
+ );
81269
82367
  if (r.error || typeof r.status === "number" && r.status !== 0) {
81270
82368
  debugLogger58.warn(
81271
82369
  `performCancelKill: taskkill failed for pid ${ptyProcess.pid}: ${r.error?.message ?? `exit ${r.status}`}`
@@ -81547,6 +82645,26 @@ function readLastTranscriptRecordUuidSync(jsonlPath) {
81547
82645
  return null;
81548
82646
  }
81549
82647
  __name(readLastTranscriptRecordUuidSync, "readLastTranscriptRecordUuidSync");
82648
+ function buildAgentTranscriptAttach(config, agentId, extras) {
82649
+ const projectRoot = config.getProjectRoot();
82650
+ const options2 = {
82651
+ agentId,
82652
+ sessionId: config.getSessionId(),
82653
+ cwd: projectRoot,
82654
+ version: config.getCliVersion() || "unknown",
82655
+ gitBranch: getCachedGitBranch(projectRoot),
82656
+ ...extras
82657
+ };
82658
+ return {
82659
+ jsonlPath: getAgentJsonlPath(
82660
+ config.storage.getProjectDir(),
82661
+ options2.sessionId,
82662
+ options2.agentId
82663
+ ),
82664
+ options: options2
82665
+ };
82666
+ }
82667
+ __name(buildAgentTranscriptAttach, "buildAgentTranscriptAttach");
81550
82668
  function attachJsonlTranscriptWriter(emitter, jsonlPath, options2) {
81551
82669
  let lastUuid = options2.initialParentUuid !== void 0 ? options2.initialParentUuid : options2.appendToExisting ? readLastTranscriptRecordUuidSync(jsonlPath) : null;
81552
82670
  let fd = null;
@@ -81721,6 +82839,9 @@ function attachJsonlTranscriptWriter(emitter, jsonlPath, options2) {
81721
82839
  displayText: options2.launchTaskPrompt
81722
82840
  });
81723
82841
  }
82842
+ if (options2.retryAttempt !== void 0) {
82843
+ recordSystem("agent_retry", { attempt: options2.retryAttempt });
82844
+ }
81724
82845
  emitter.on("round_text" /* ROUND_TEXT */, onRoundText);
81725
82846
  emitter.on("stream_text" /* STREAM_TEXT */, appendStreamText);
81726
82847
  emitter.on("tool_call" /* TOOL_CALL */, onToolCall);
@@ -82218,8 +83339,8 @@ var BackgroundShellRegistry = class {
82218
83339
  /**
82219
83340
  * Subscribe to new-entry events. Called synchronously inside `register()`.
82220
83341
  * Setting `undefined` clears the existing subscriber. Single-subscriber on
82221
- * purpose — the UI hook is the only consumer in the codebase, and a list
82222
- * would invite drift in error-handling.
83342
+ * purpose — each runtime installs one owner callback, and a list would
83343
+ * invite drift in error-handling.
82223
83344
  */
82224
83345
  setRegisterCallback(cb) {
82225
83346
  this.registerCallback = cb;
@@ -82228,14 +83349,19 @@ var BackgroundShellRegistry = class {
82228
83349
  this.notificationCallback = cb;
82229
83350
  }
82230
83351
  /**
82231
- * Subscribe to status transitions (running → terminal). Called
82232
- * synchronously inside `complete()` / `fail()` / `cancel()` after the
82233
- * entry has been mutated. Same single-subscriber rationale as
82234
- * `setRegisterCallback`.
83352
+ * Subscribe to registration and status transitions (running → terminal).
83353
+ * Called synchronously after the registry has been mutated. Same
83354
+ * single-subscriber rationale as `setRegisterCallback`.
82235
83355
  */
82236
83356
  setStatusChangeCallback(cb) {
82237
83357
  this.statusChangeCallback = cb;
82238
83358
  }
83359
+ /** Retract `cb` only if it is still the installed callback. */
83360
+ clearStatusChangeCallback(cb) {
83361
+ if (this.statusChangeCallback === cb) {
83362
+ this.statusChangeCallback = void 0;
83363
+ }
83364
+ }
82239
83365
  register(registration) {
82240
83366
  const entry = registration;
82241
83367
  entry.id = registration.shellId;
@@ -82491,8 +83617,8 @@ var BackgroundShellRegistry = class {
82491
83617
  * statusChange callback exactly once after the loop. The per-entry
82492
83618
  * `cancel()` path would have triggered both side channels for every
82493
83619
  * running shell — wasteful on shutdown / `/clear` where the only
82494
- * subscriber (`useBackgroundTaskView`) just re-pulls `getAll()`
82495
- * regardless of the entry argument.
83620
+ * current subscriber just re-pulls the registry regardless of the entry
83621
+ * argument.
82496
83622
  */
82497
83623
  abortAll() {
82498
83624
  const endTime = Date.now();
@@ -95449,16 +96575,6 @@ import * as fs52 from "node:fs";
95449
96575
  import * as path55 from "node:path";
95450
96576
  import * as os16 from "node:os";
95451
96577
 
95452
- // packages/core/src/extension/redaction.ts
95453
- init_esbuild_shims();
95454
- var REDACTED_URL_CREDENTIAL = "***REDACTED***";
95455
- var URL_CREDENTIALS_PATTERN = /\b([a-z][a-z0-9+.-]*:\/\/)(?:[^/\s]+@)+/gi;
95456
- var UPLOAD_IDENTITY_PATTERN = /\bupload:v1:[0-9a-fA-F-]+:/gu;
95457
- function redactUrlCredentials(source) {
95458
- return source.replace(UPLOAD_IDENTITY_PATTERN, "upload:").replace(URL_CREDENTIALS_PATTERN, `$1${REDACTED_URL_CREDENTIAL}@`);
95459
- }
95460
- __name(redactUrlCredentials, "redactUrlCredentials");
95461
-
95462
96578
  // packages/core/src/extension/http-client.ts
95463
96579
  init_esbuild_shims();
95464
96580
  import * as http2 from "node:http";
@@ -114211,19 +115327,19 @@ var BackgroundAgentResumeService = class {
114211
115327
  subagent = result.subagent;
114212
115328
  subagentDispose = result.dispose;
114213
115329
  }
114214
- const projectRoot = this.config.getProjectRoot();
114215
- cleanupJsonl = attachJsonlTranscriptWriter(bgEventEmitter, outputFile, {
114216
- agentId: meta.agentId,
115330
+ const { jsonlPath, options: transcriptAttachOptions } = buildAgentTranscriptAttach(this.config, meta.agentId, {
115331
+ sessionId: meta.parentSessionId,
114217
115332
  agentName: target.agentName,
114218
115333
  agentColor: target.subagentConfig?.color ?? meta.agentColor,
114219
- sessionId: meta.parentSessionId,
114220
- cwd: projectRoot,
114221
- version: this.config.getCliVersion() || "unknown",
114222
- gitBranch: getGitBranch(projectRoot),
114223
115334
  initialUserPrompt: writerInitialPrompt,
114224
115335
  appendToExisting: true,
114225
115336
  initialParentUuid: recovery.lastStableUuid
114226
- }).cleanup;
115337
+ });
115338
+ cleanupJsonl = attachJsonlTranscriptWriter(
115339
+ bgEventEmitter,
115340
+ jsonlPath,
115341
+ transcriptAttachOptions
115342
+ ).cleanup;
114227
115343
  const nextResumeCount = (meta.resumeCount ?? 0) + 1;
114228
115344
  patchAgentMeta(metaPath, {
114229
115345
  status: "running",
@@ -115602,6 +116718,8 @@ async function runSpeculativeLoop(config, state, cacheSafe, modelOverride) {
115602
116718
  toolName: canonicalToolName(name),
115603
116719
  args: invocation.params,
115604
116720
  signal: state.abortController.signal,
116721
+ sessionId: config.getSessionId(),
116722
+ cwd: config.getTargetDir(),
115605
116723
  ...invocationContext ? { invocationContext } : {}
115606
116724
  }
115607
116725
  );
@@ -128755,6 +129873,11 @@ __name(buildReplacement, "buildReplacement");
128755
129873
 
128756
129874
  // packages/core/src/tools/shell.ts
128757
129875
  var debugLogger125 = createDebugLogger("SHELL");
129876
+ var DEFAULT_SHELL_OUTPUT_THRESHOLD = 3e4;
129877
+ function getShellOutputThreshold(config) {
129878
+ return config.isTruncateToolOutputThresholdExplicit() ? config.getTruncateToolOutputThreshold() : DEFAULT_SHELL_OUTPUT_THRESHOLD;
129879
+ }
129880
+ __name(getShellOutputThreshold, "getShellOutputThreshold");
128758
129881
  function statusFileGuidance(outputPath) {
128759
129882
  return `status file: ${statusFilePathFor(outputPath)}
128760
129883
  To check whether this process is still running, Read the status file (status: running|completed|failed|cancelled). Do NOT infer liveness from the output file: programs often block-buffer stdout when not attached to a TTY, so an empty output file is normal while the process is alive (for live output, re-run with e.g. \`python -u\` or \`stdbuf -oL\`).`;
@@ -130410,6 +131533,7 @@ ${result.output}` : result.output;
130410
131533
  let persistedOutputFiles;
130411
131534
  if (typeof llmContent === "string") {
130412
131535
  const originalLlmContent = llmContent;
131536
+ const outputThreshold = getShellOutputThreshold(this.config);
130413
131537
  const truncatedResult = await truncateToolOutput(
130414
131538
  this.config,
130415
131539
  ShellTool.Name,
@@ -130420,11 +131544,11 @@ ${result.output}` : result.output;
130420
131544
  // scheduler) so the long-run hint below is appended OUTSIDE the
130421
131545
  // truncation envelope; the scheduler's sentinel makes its later pass a
130422
131546
  // no-op here. lines: Infinity keeps this char-only so the global line
130423
- // cap can't undercut the declared 30k char budget — many short lines
131547
+ // cap can't undercut the effective Shell char budget — many short lines
130424
131548
  // (e.g. `find /`, `ls -R`) would otherwise truncate while chars remain.
130425
131549
  {
130426
- threshold: 3e4,
130427
- previewChars: 4e3,
131550
+ threshold: outputThreshold,
131551
+ previewChars: Math.min(4e3, outputThreshold),
130428
131552
  keep: "both",
130429
131553
  lines: Number.POSITIVE_INFINITY
130430
131554
  }
@@ -130519,12 +131643,13 @@ ${longRunHint}` : ""),
130519
131643
  if (pid !== void 0) {
130520
131644
  if (os23.platform() === "win32") {
130521
131645
  try {
130522
- const taskkillChild = childProcess.spawn("taskkill", [
130523
- "/pid",
130524
- String(pid),
130525
- "/f",
130526
- "/t"
130527
- ]);
131646
+ const taskkillChild = childProcess.spawn(
131647
+ "taskkill",
131648
+ ["/pid", String(pid), "/f", "/t"],
131649
+ // The desktop runtime daemon has no console; without this
131650
+ // flag each console-app child allocates a visible window.
131651
+ { windowsHide: true }
131652
+ );
130528
131653
  taskkillChild.on("error", () => {
130529
131654
  });
130530
131655
  } catch {
@@ -130594,12 +131719,13 @@ ${longRunHint}` : ""),
130594
131719
  if (pid !== void 0) {
130595
131720
  if (os23.platform() === "win32") {
130596
131721
  try {
130597
- const taskkillChild = childProcess.spawn("taskkill", [
130598
- "/pid",
130599
- String(pid),
130600
- "/f",
130601
- "/t"
130602
- ]);
131722
+ const taskkillChild = childProcess.spawn(
131723
+ "taskkill",
131724
+ ["/pid", String(pid), "/f", "/t"],
131725
+ // The desktop runtime daemon has no console; without this
131726
+ // flag each console-app child allocates a visible window.
131727
+ { windowsHide: true }
131728
+ );
130603
131729
  taskkillChild.on("error", (err) => {
130604
131730
  debugLogger125.warn(
130605
131731
  `promote: taskkill spawn failed for pid=${pid}: ${err.message}`
@@ -130912,7 +132038,7 @@ To inspect: /tasks (text) or the interactive Background tasks dialog (focus the
130912
132038
  const child = childProcess.execFile(
130913
132039
  "git",
130914
132040
  args,
130915
- { cwd, timeout: 2e3 },
132041
+ { cwd, timeout: 2e3, windowsHide: true },
130916
132042
  (error, stdout) => {
130917
132043
  if (error) {
130918
132044
  resolve41(0);
@@ -130940,7 +132066,7 @@ To inspect: /tasks (text) or the interactive Background tasks dialog (focus the
130940
132066
  const child = childProcess.execFile(
130941
132067
  "git",
130942
132068
  ["rev-parse", "HEAD"],
130943
- { cwd, timeout: 2e3 },
132069
+ { cwd, timeout: 2e3, windowsHide: true },
130944
132070
  (error, stdout) => {
130945
132071
  if (error) {
130946
132072
  resolve41(null);
@@ -130972,6 +132098,7 @@ To inspect: /tasks (text) or the interactive Background tasks dialog (focus the
130972
132098
  const stdout = childProcess.execFileSync("git", ["rev-parse", "HEAD"], {
130973
132099
  cwd,
130974
132100
  timeout: 2e3,
132101
+ windowsHide: true,
130975
132102
  // Discard stderr noise (e.g. "fatal: not a git repository") —
130976
132103
  // the catch-or-empty-output path already covers failure.
130977
132104
  stdio: ["ignore", "pipe", "ignore"]
@@ -131052,6 +132179,7 @@ To inspect: /tasks (text) or the interactive Background tasks dialog (focus the
131052
132179
  return childProcess.execFileSync("git", ["show", `${postHead}:${rel}`], {
131053
132180
  cwd,
131054
132181
  timeout: 2e3,
132182
+ windowsHide: true,
131055
132183
  stdio: ["ignore", "pipe", "ignore"],
131056
132184
  maxBuffer: 16 * 1024 * 1024
131057
132185
  }).toString("utf-8");
@@ -131088,7 +132216,7 @@ To inspect: /tasks (text) or the interactive Background tasks dialog (focus the
131088
132216
  const child = childProcess.execFile(
131089
132217
  notesCommand.command,
131090
132218
  notesCommand.args,
131091
- { cwd, timeout: 5e3 },
132219
+ { cwd, timeout: 5e3, windowsHide: true },
131092
132220
  (error, stdout, stderr) => {
131093
132221
  const merged = (stdout || "") + (stderr || "");
131094
132222
  if (error) {
@@ -131618,7 +132746,7 @@ var ShellTool = class _ShellTool extends BaseDeclarativeTool {
131618
132746
  }
131619
132747
  static Name = ToolNames.SHELL;
131620
132748
  get maxOutputChars() {
131621
- return 3e4;
132749
+ return getShellOutputThreshold(this.config);
131622
132750
  }
131623
132751
  validateToolParamValues(params) {
131624
132752
  if (!params.command.trim()) {
@@ -131767,6 +132895,7 @@ var TRUNCATION_EDIT_REJECTION = "Your previous response was truncated due to max
131767
132895
  function setToolSpanFailure(span, failureKind, message) {
131768
132896
  try {
131769
132897
  span.setAttribute(TOOL_FAILURE_KIND_ATTRIBUTE, failureKind);
132898
+ span.setAttribute("error.type", failureKind);
131770
132899
  span.setAttribute("success", false);
131771
132900
  } catch {
131772
132901
  }
@@ -132606,7 +133735,8 @@ var CoreToolScheduler = class {
132606
133735
  * second call for the same callId is a no-op.
132607
133736
  *
132608
133737
  * No `metadata` parameter: every caller pre-sets span status via
132609
- * `setToolSpan{Failure,Cancelled,Ok}` before this call (#4321 review).
133738
+ * `setToolSpan{Failure,Cancelled}` or the success path before this call
133739
+ * (#4321 review).
132610
133740
  */
132611
133741
  finalizeToolSpan(callId, force = false) {
132612
133742
  this.bouncedAwaitingApproval.delete(callId);
@@ -134535,6 +135665,8 @@ var CoreToolScheduler = class {
134535
135665
  toolName: canonicalName,
134536
135666
  args: invocation.params,
134537
135667
  signal,
135668
+ sessionId: this.config.getSessionId(),
135669
+ cwd: this.config.getTargetDir(),
134538
135670
  ...invocationContext ? { invocationContext } : {}
134539
135671
  }
134540
135672
  );
@@ -135087,7 +136219,6 @@ ${body}
135087
136219
  return;
135088
136220
  }
135089
136221
  this.setStatusInternal(callId, "success", successResponse);
135090
- safeSetStatus(span, { code: SpanStatusCode.OK });
135091
136222
  try {
135092
136223
  span.setAttribute("success", true);
135093
136224
  } catch {
@@ -137534,14 +138665,6 @@ __name(loadForkProfile, "loadForkProfile");
137534
138665
 
137535
138666
  // packages/core/src/tools/agent/agent.ts
137536
138667
  init_esm();
137537
- var gitBranchCache = /* @__PURE__ */ new Map();
137538
- function getCachedGitBranch(cwd) {
137539
- if (gitBranchCache.has(cwd)) return gitBranchCache.get(cwd);
137540
- const branch = getGitBranch(cwd);
137541
- gitBranchCache.set(cwd, branch);
137542
- return branch;
137543
- }
137544
- __name(getCachedGitBranch, "getCachedGitBranch");
137545
138668
  function persistBackgroundCancellation2(metaPath, persistedStatus) {
137546
138669
  patchAgentMeta(metaPath, {
137547
138670
  status: persistedStatus,
@@ -139441,17 +140564,21 @@ ${taskPrompt}`;
139441
140564
  const registry2 = this.config.getBackgroundTaskRegistry();
139442
140565
  const projectDir = this.config.storage.getProjectDir();
139443
140566
  const sessionId = this.config.getSessionId();
139444
- const jsonlPath = getAgentJsonlPath(
139445
- projectDir,
139446
- sessionId,
139447
- hookOpts.agentId
139448
- );
140567
+ const { jsonlPath, options: transcriptAttachOptions } = buildAgentTranscriptAttach(this.config, hookOpts.agentId, {
140568
+ agentName: subagentConfig.name,
140569
+ agentColor: subagentConfig.color,
140570
+ // Seed the JSONL with the launching prompt so the transcript is
140571
+ // self-describing — readers don't need to consult .meta.json to
140572
+ // know what the agent was asked to do.
140573
+ initialUserPrompt: this.params.prompt,
140574
+ bootstrapHistory: isFork ? bgInitialMessages : void 0,
140575
+ launchTaskPrompt: isFork ? bgTaskPrompt : void 0
140576
+ });
139449
140577
  const metaPath = getAgentMetaPath(
139450
140578
  projectDir,
139451
140579
  sessionId,
139452
140580
  hookOpts.agentId
139453
140581
  );
139454
- const projectRoot = this.config.getProjectRoot();
139455
140582
  try {
139456
140583
  const registerOptions = backgroundSlotReservation ? { slotReservation: backgroundSlotReservation } : {};
139457
140584
  registry2.register(
@@ -139531,21 +140658,7 @@ ${taskPrompt}`;
139531
140658
  const { cleanup: cleanupJsonl } = attachJsonlTranscriptWriter(
139532
140659
  bgEventEmitter,
139533
140660
  jsonlPath,
139534
- {
139535
- agentId: hookOpts.agentId,
139536
- agentName: subagentConfig.name,
139537
- agentColor: subagentConfig.color,
139538
- sessionId,
139539
- cwd: projectRoot,
139540
- version: this.config.getCliVersion() || "unknown",
139541
- gitBranch: getCachedGitBranch(projectRoot),
139542
- // Seed the JSONL with the launching prompt so the transcript is
139543
- // self-describing — readers don't need to consult .meta.json to
139544
- // know what the agent was asked to do.
139545
- initialUserPrompt: this.params.prompt,
139546
- bootstrapHistory: isFork ? bgInitialMessages : void 0,
139547
- launchTaskPrompt: isFork ? bgTaskPrompt : void 0
139548
- }
140661
+ transcriptAttachOptions
139549
140662
  );
139550
140663
  writeAgentMeta(metaPath, {
139551
140664
  agentId: hookOpts.agentId,
@@ -140029,17 +141142,19 @@ If asked, you can check progress before completion by using ${ToolNames.READ_FIL
140029
141142
  const registry = this.config.getBackgroundTaskRegistry();
140030
141143
  const fgProjectDir = this.config.storage.getProjectDir();
140031
141144
  const fgSessionId = this.config.getSessionId();
140032
- const fgJsonlPath = getAgentJsonlPath(
140033
- fgProjectDir,
140034
- fgSessionId,
140035
- hookOpts.agentId
140036
- );
141145
+ const { jsonlPath: fgJsonlPath, options: fgTranscriptAttachOptions } = buildAgentTranscriptAttach(this.config, hookOpts.agentId, {
141146
+ agentName: subagentConfig.name,
141147
+ agentColor: subagentConfig.color,
141148
+ // Seed the JSONL with the launching prompt so the transcript
141149
+ // is self-describing — readers don't need the meta sidecar to
141150
+ // know what the agent was asked to do.
141151
+ initialUserPrompt: this.params.prompt
141152
+ });
140037
141153
  const fgMetaPath = getAgentMetaPath(
140038
141154
  fgProjectDir,
140039
141155
  fgSessionId,
140040
141156
  hookOpts.agentId
140041
141157
  );
140042
- const fgProjectRoot = this.config.getProjectRoot();
140043
141158
  let cleanupFgJsonl;
140044
141159
  const cleanupOwnedMonitorNotifications = this.registerOwnedMonitorNotifications(
140045
141160
  hookOpts.agentId,
@@ -140086,19 +141201,7 @@ If asked, you can check progress before completion by using ${ToolNames.READ_FIL
140086
141201
  ({ cleanup: cleanupFgJsonl } = attachJsonlTranscriptWriter(
140087
141202
  this.eventEmitter,
140088
141203
  fgJsonlPath,
140089
- {
140090
- agentId: hookOpts.agentId,
140091
- agentName: subagentConfig.name,
140092
- agentColor: subagentConfig.color,
140093
- sessionId: fgSessionId,
140094
- cwd: fgProjectRoot,
140095
- version: this.config.getCliVersion() || "unknown",
140096
- gitBranch: getCachedGitBranch(fgProjectRoot),
140097
- // Seed the JSONL with the launching prompt so the transcript
140098
- // is self-describing — readers don't need the meta sidecar to
140099
- // know what the agent was asked to do.
140100
- initialUserPrompt: this.params.prompt
140101
- }
141204
+ fgTranscriptAttachOptions
140102
141205
  ));
140103
141206
  registry.register({
140104
141207
  agentId: hookOpts.agentId,
@@ -143112,7 +144215,32 @@ var GeminiClient = class _GeminiClient {
143112
144215
  return;
143113
144216
  }
143114
144217
  const resumedSessionData = this.config.getResumedSessionData();
143115
- if (resumedSessionData) {
144218
+ const restoreRuntime = this.config.getSessionRestoreRuntime?.();
144219
+ if (restoreRuntime) {
144220
+ uiTelemetryService.resetSession(sessionId);
144221
+ for (const event of restoreRuntime.uiTelemetryEvents) {
144222
+ uiTelemetryService.addEvent(event, sessionId);
144223
+ }
144224
+ this.seedRecentCompletedToolNamesFromHistory(restoreRuntime.apiHistory);
144225
+ await this.startChat(
144226
+ restoreRuntime.apiHistory,
144227
+ sessionStartSource ?? "resume" /* Resume */
144228
+ );
144229
+ const chat = this.getChat();
144230
+ if (restoreRuntime.resumeTokenCounts) {
144231
+ const counts = restoreRuntime.resumeTokenCounts;
144232
+ uiTelemetryService.setLastPromptTokenCount(counts.promptTokenCount);
144233
+ chat.seedResumeTokenCounts(
144234
+ counts.promptTokenCount,
144235
+ counts.outputTokenCount,
144236
+ counts.isEstimated
144237
+ );
144238
+ } else {
144239
+ chat.setLastPromptTokenCount(
144240
+ uiTelemetryService.getLastPromptTokenCount()
144241
+ );
144242
+ }
144243
+ } else if (resumedSessionData) {
143116
144244
  const resumeTokenCounts = replayUiTelemetryFromConversation(
143117
144245
  resumedSessionData.conversation,
143118
144246
  this.config.getSessionId()
@@ -144384,6 +145512,33 @@ var GeminiClient = class _GeminiClient {
144384
145512
  }
144385
145513
  async *sendMessageStream(request, callerSignal, prompt_id, options2, turns = MAX_TURNS2) {
144386
145514
  const messageType = options2?.type ?? "userQuery" /* UserQuery */;
145515
+ const startsInteraction = messageType === "userQuery" /* UserQuery */ || messageType === "retry" /* Retry */ || messageType === "cron" /* Cron */ || messageType === "notification" /* Notification */ || messageType === "teammate" /* Teammate */ || messageType === "goal" /* Goal */;
145516
+ let interactionOwner = startsInteraction ? void 0 : getActiveInteractionSpan(prompt_id);
145517
+ if (interactionOwner) {
145518
+ recordInteractionActivity(prompt_id, interactionOwner);
145519
+ }
145520
+ const agentOutput = new AgentOutputMessageCapture(this.config);
145521
+ const endCurrentInteraction = /* @__PURE__ */ __name((status, errorMessage, errorType) => {
145522
+ if (!interactionOwner || getActiveInteractionSpan(prompt_id) !== interactionOwner) {
145523
+ return;
145524
+ }
145525
+ if (status === "ok" && this.config.getJsonSchema?.()) {
145526
+ endInteractionSpan("error", {
145527
+ promptId: prompt_id,
145528
+ errorMessage: "model did not produce structured output",
145529
+ errorType: "structured_output_missing"
145530
+ });
145531
+ return;
145532
+ }
145533
+ if (status === "ok") {
145534
+ agentOutput.writeToSpan(interactionOwner);
145535
+ }
145536
+ endInteractionSpan(status, {
145537
+ promptId: prompt_id,
145538
+ ...errorMessage ? { errorMessage } : {},
145539
+ ...errorType ? { errorType } : {}
145540
+ });
145541
+ }, "endCurrentInteraction");
144387
145542
  if (messageType === "userQuery" /* UserQuery */ || messageType === "cron" /* Cron */ || messageType === "notification" /* Notification */ || messageType === "teammate" /* Teammate */) {
144388
145543
  await this.config.assertCanStartTurn();
144389
145544
  }
@@ -144541,6 +145696,23 @@ var GeminiClient = class _GeminiClient {
144541
145696
  pushCountAfterStrip = currentPushCount();
144542
145697
  }
144543
145698
  const preHookUserPromptText = messageType === "userQuery" /* UserQuery */ ? partToString(request) : void 0;
145699
+ if (startsInteraction) {
145700
+ this.loopDetector.reset(prompt_id);
145701
+ this.lastPromptId = prompt_id;
145702
+ startInteractionSpan(this.config, {
145703
+ promptId: prompt_id,
145704
+ model: options2?.modelOverride ?? this.config.getModel(),
145705
+ messageType
145706
+ });
145707
+ interactionOwner = getActiveInteractionSpan(prompt_id);
145708
+ if (interactionOwner && messageType === "userQuery" /* UserQuery */ && typeof options2?.submittedPrompt === "string") {
145709
+ addAgentInputMessageAttributes(
145710
+ this.config,
145711
+ interactionOwner,
145712
+ options2.submittedPrompt
145713
+ );
145714
+ }
145715
+ }
144544
145716
  let userPromptRecordPayload;
144545
145717
  let hooksEnabled;
144546
145718
  let messageBus;
@@ -144581,9 +145753,12 @@ var GeminiClient = class _GeminiClient {
144581
145753
  await runtime.finishTurn(goalPermit);
144582
145754
  goalPermitReleased = true;
144583
145755
  closeGoalStateEvents();
145756
+ endCurrentInteraction("cancelled");
144584
145757
  for (const goalEvent of takePendingGoalEvents()) {
144585
145758
  yield goalEvent;
144586
145759
  }
145760
+ } else {
145761
+ endCurrentInteraction("cancelled");
144587
145762
  }
144588
145763
  yield {
144589
145764
  type: "user_prompt_submit_blocked" /* UserPromptSubmitBlocked */,
@@ -144611,6 +145786,11 @@ var GeminiClient = class _GeminiClient {
144611
145786
  }
144612
145787
  }
144613
145788
  } catch (error) {
145789
+ endCurrentInteraction(
145790
+ signal.aborted ? "cancelled" : "error",
145791
+ signal.aborted ? void 0 : "UserPromptSubmit hook failed",
145792
+ signal.aborted ? void 0 : getErrorType(error)
145793
+ );
144614
145794
  for (const goalEvent of await finalizeInterruptedGoalTurn()) {
144615
145795
  yield goalEvent;
144616
145796
  }
@@ -144660,6 +145840,11 @@ var GeminiClient = class _GeminiClient {
144660
145840
  }
144661
145841
  if (goalRuntime) bindGoalStateEvents(goalRuntime);
144662
145842
  } catch (error) {
145843
+ endCurrentInteraction(
145844
+ signal.aborted ? "cancelled" : "error",
145845
+ signal.aborted ? void 0 : "Goal turn admission failed",
145846
+ signal.aborted ? void 0 : getErrorType(error)
145847
+ );
144663
145848
  for (const goalEvent of await finalizeInterruptedGoalTurn()) {
144664
145849
  yield goalEvent;
144665
145850
  }
@@ -144691,20 +145876,12 @@ var GeminiClient = class _GeminiClient {
144691
145876
  );
144692
145877
  this.activeAutomaticTodoWorkChainPromptIds.add(prompt_id);
144693
145878
  }
144694
- const isTopLevelInteraction = messageType === "userQuery" /* UserQuery */ || messageType === "cron" /* Cron */ || messageType === "notification" /* Notification */ || messageType === "teammate" /* Teammate */;
144695
145879
  if (messageType === "goal" /* Goal */) {
144696
145880
  this.loopDetector.reset(prompt_id);
144697
145881
  this.lastPromptId = prompt_id;
144698
145882
  }
144699
- if (isTopLevelInteraction) {
144700
- this.loopDetector.reset(prompt_id);
144701
- this.lastPromptId = prompt_id;
144702
- startInteractionSpan(this.config, {
144703
- promptId: prompt_id,
144704
- model: options2?.modelOverride ?? this.config.getModel(),
144705
- messageType
144706
- });
144707
- const interactionSpan = getActiveInteractionSpan();
145883
+ if (startsInteraction) {
145884
+ const interactionSpan = interactionOwner;
144708
145885
  if (interactionSpan && this.config.getTelemetryIncludeSensitiveSpanAttributes?.()) {
144709
145886
  addUserPromptAttributes(
144710
145887
  this.config,
@@ -144838,18 +146015,18 @@ var GeminiClient = class _GeminiClient {
144838
146015
  if (this.config.getMaxSessionTurns() > 0 && this.sessionTurnCount > this.config.getMaxSessionTurns()) {
144839
146016
  this.cancelPendingMemoryPrefetch("no_safe_delivery_point");
144840
146017
  yield { type: "max_session_turns" /* MaxSessionTurns */ };
144841
- if (isTopLevelInteraction)
144842
- endInteractionSpan("error", {
144843
- errorMessage: "max session turns exceeded"
144844
- });
146018
+ endCurrentInteraction(
146019
+ "error",
146020
+ "max session turns exceeded",
146021
+ "max_session_turns"
146022
+ );
144845
146023
  return new Turn(this.getChat(), prompt_id);
144846
146024
  }
144847
146025
  }
144848
146026
  const boundedTurns = messageType === "goal" /* Goal */ ? MAX_TURNS2 : Math.min(turns, MAX_TURNS2);
144849
146027
  if (!boundedTurns) {
144850
146028
  this.cancelPendingMemoryPrefetch("no_safe_delivery_point");
144851
- if (isTopLevelInteraction)
144852
- endInteractionSpan("error", { errorMessage: "max turns exhausted" });
146029
+ endCurrentInteraction("error", "max turns exhausted", "max_turns");
144853
146030
  return new Turn(this.getChat(), prompt_id);
144854
146031
  }
144855
146032
  const takeSteerInput = /* @__PURE__ */ __name(async (nextTurnBudget) => {
@@ -144883,10 +146060,11 @@ var GeminiClient = class _GeminiClient {
144883
146060
  message: `Session token limit exceeded: ${lastPromptTokenCount} tokens > ${sessionTokenLimit} limit. Please start a new session or increase the sessionTokenLimit in your settings.json.`
144884
146061
  }
144885
146062
  };
144886
- if (isTopLevelInteraction)
144887
- endInteractionSpan("error", {
144888
- errorMessage: "session token limit exceeded"
144889
- });
146063
+ endCurrentInteraction(
146064
+ "error",
146065
+ "session token limit exceeded",
146066
+ "session_token_limit"
146067
+ );
144890
146068
  return new Turn(this.getChat(), prompt_id);
144891
146069
  }
144892
146070
  }
@@ -144920,7 +146098,7 @@ var GeminiClient = class _GeminiClient {
144920
146098
  );
144921
146099
  await arenaAgentClient.reportCancelled();
144922
146100
  this.cancelPendingMemoryPrefetch("abort");
144923
- if (isTopLevelInteraction) endInteractionSpan("cancelled");
146101
+ endCurrentInteraction("cancelled");
144924
146102
  return new Turn(this.getChat(), prompt_id);
144925
146103
  }
144926
146104
  }
@@ -145055,6 +146233,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145055
146233
  signal,
145056
146234
  (message) => this.config.getDebugLogger().warn(message)
145057
146235
  ) : null;
146236
+ agentOutput.beginResponse();
145058
146237
  const resultStream = turn.run(model, requestToSend, signal);
145059
146238
  let didUpdateIdeContextState = false;
145060
146239
  let steerInputSettled = false;
@@ -145068,6 +146247,14 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145068
146247
  hasToolCalls = true;
145069
146248
  } else if (event.type === "retry" /* Retry */ || event.type === "model_fallback" /* ModelFallback */) {
145070
146249
  hasToolCalls = false;
146250
+ agentOutput.restartAttempt(
146251
+ event.type === "retry" /* Retry */ && event.isContinuation === true
146252
+ );
146253
+ }
146254
+ if (event.type === "content" /* Content */) {
146255
+ agentOutput.appendText(event.value);
146256
+ } else if (event.type === "finished" /* Finished */) {
146257
+ agentOutput.observeFinishReason(event.value?.reason);
145071
146258
  }
145072
146259
  if (messageDisplay && event.type === "content" /* Content */) {
145073
146260
  messageDisplay.addChunk(event.value);
@@ -145092,8 +146279,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145092
146279
  await arenaAgentClient.reportError("Loop detected");
145093
146280
  }
145094
146281
  this.lastApiCompletionTimestamp = Date.now();
145095
- if (isTopLevelInteraction)
145096
- endInteractionSpan("error", { errorMessage: "loop detected" });
146282
+ endCurrentInteraction("error", "loop detected", "loop_detected");
145097
146283
  this.cancelPendingMemoryPrefetch("no_safe_delivery_point");
145098
146284
  this.fireLoopDetectedStopFailure(loopType);
145099
146285
  return turn;
@@ -145113,8 +146299,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145113
146299
  await arenaAgentClient.reportError("Loop detected");
145114
146300
  }
145115
146301
  this.lastApiCompletionTimestamp = Date.now();
145116
- if (isTopLevelInteraction)
145117
- endInteractionSpan("error", { errorMessage: "loop detected" });
146302
+ endCurrentInteraction("error", "loop detected", "loop_detected");
145118
146303
  this.cancelPendingMemoryPrefetch("no_safe_delivery_point");
145119
146304
  this.fireLoopDetectedStopFailure(loopType);
145120
146305
  return turn;
@@ -145161,10 +146346,12 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145161
146346
  await arenaAgentClient.reportError(errorMsg);
145162
146347
  }
145163
146348
  this.lastApiCompletionTimestamp = Date.now();
145164
- if (isTopLevelInteraction) {
145165
- const errMsg = event.value instanceof Error ? "[API error]" : "unknown error";
145166
- endInteractionSpan("error", { errorMessage: errMsg });
145167
- }
146349
+ const errMsg = event.value instanceof Error ? "[API error]" : "unknown error";
146350
+ endCurrentInteraction(
146351
+ "error",
146352
+ errMsg,
146353
+ event.value instanceof Error ? getErrorType(event.value) : "api_error"
146354
+ );
145168
146355
  this.cancelPendingMemoryPrefetch("no_safe_delivery_point");
145169
146356
  return turn;
145170
146357
  }
@@ -145172,6 +146359,9 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145172
146359
  } finally {
145173
146360
  await messageDisplay?.finish();
145174
146361
  }
146362
+ agentOutput.commitResponse(
146363
+ hasToolCalls || turn.pendingToolCalls.length > 0
146364
+ );
145175
146365
  for (const goalEvent of signal.aborted ? await finalizeInterruptedGoalTurn() : takePendingGoalEvents()) {
145176
146366
  yield goalEvent;
145177
146367
  }
@@ -145198,9 +146388,10 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145198
146388
  } finally {
145199
146389
  settleSteerInput(steerInput, pushCountBefore);
145200
146390
  }
145201
- if (isTopLevelInteraction)
145202
- endInteractionSpan(signal.aborted ? "cancelled" : "ok");
145203
146391
  hasToolCalls = steeredTurn.pendingToolCalls.length > 0;
146392
+ if (!hasToolCalls) {
146393
+ endCurrentInteraction(signal.aborted ? "cancelled" : "ok");
146394
+ }
145204
146395
  normalCompletion = true;
145205
146396
  return steeredTurn;
145206
146397
  }
@@ -145238,7 +146429,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145238
146429
  if (activeGoalEvent2) {
145239
146430
  yield activeGoalEvent2;
145240
146431
  }
145241
- if (isTopLevelInteraction) endInteractionSpan("cancelled");
146432
+ endCurrentInteraction("cancelled");
145242
146433
  return turn;
145243
146434
  }
145244
146435
  const hookOutput = response.output ? createHookOutput("Stop", response.output) : void 0;
@@ -145270,7 +146461,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145270
146461
  for (const goalEvent of await finalizeInterruptedGoalTurn()) {
145271
146462
  yield goalEvent;
145272
146463
  }
145273
- if (isTopLevelInteraction) endInteractionSpan("ok");
146464
+ endCurrentInteraction("ok");
145274
146465
  return turn;
145275
146466
  } else {
145276
146467
  for (const goalEvent of takePendingGoalEvents()) {
@@ -145294,7 +146485,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145294
146485
  for (const goalEvent of await finalizeInterruptedGoalTurn()) {
145295
146486
  yield goalEvent;
145296
146487
  }
145297
- if (isTopLevelInteraction) endInteractionSpan("cancelled");
146488
+ endCurrentInteraction("cancelled");
145298
146489
  return turn;
145299
146490
  }
145300
146491
  const continueRequest = [{ text: continueReason }];
@@ -145323,8 +146514,9 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145323
146514
  } finally {
145324
146515
  settleSteerInput(pendingSteer, pushCountBefore);
145325
146516
  }
145326
- if (isTopLevelInteraction) {
145327
- endInteractionSpan(signal.aborted ? "cancelled" : "ok");
146517
+ hasToolCalls = hookTurn.pendingToolCalls.length > 0;
146518
+ if (!hasToolCalls) {
146519
+ endCurrentInteraction(signal.aborted ? "cancelled" : "ok");
145328
146520
  }
145329
146521
  normalCompletion = true;
145330
146522
  return hookTurn;
@@ -145338,7 +146530,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145338
146530
  if (activeGoalEvent3) {
145339
146531
  yield activeGoalEvent3;
145340
146532
  }
145341
- if (isTopLevelInteraction) endInteractionSpan("cancelled");
146533
+ endCurrentInteraction("cancelled");
145342
146534
  return turn;
145343
146535
  }
145344
146536
  const continueReason = getStopHookContinuationReason(stopOutput);
@@ -145370,7 +146562,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145370
146562
  value: warning
145371
146563
  };
145372
146564
  debugLogger136.warn(warning);
145373
- if (isTopLevelInteraction) endInteractionSpan("ok");
146565
+ endCurrentInteraction("ok");
145374
146566
  return turn;
145375
146567
  }
145376
146568
  const activeGoalEvent2 = maybeEmitActiveGoalChange(
@@ -145405,7 +146597,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145405
146597
  const discardGoalContinuation = goalContinuationChanged && response.hasNonGoalBlockingStopHook === false;
145406
146598
  const continuationReasonAfterSteer = discardGoalContinuation ? void 0 : goalContinuationChanged && response.hasNonGoalBlockingStopHook === true ? response.nonGoalBlockingStopReason || "No reason provided" : continueReason;
145407
146599
  if (!continuationReasonAfterSteer && !pendingSteer) {
145408
- if (isTopLevelInteraction) endInteractionSpan("ok");
146600
+ endCurrentInteraction("ok");
145409
146601
  normalCompletion = true;
145410
146602
  return turn;
145411
146603
  }
@@ -145441,9 +146633,10 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145441
146633
  } finally {
145442
146634
  settleSteerInput(pendingSteer, pushCountBefore);
145443
146635
  }
145444
- if (isTopLevelInteraction)
145445
- endInteractionSpan(signal.aborted ? "cancelled" : "ok");
145446
146636
  hasToolCalls = hookTurn.pendingToolCalls.length > 0;
146637
+ if (!hasToolCalls) {
146638
+ endCurrentInteraction(signal.aborted ? "cancelled" : "ok");
146639
+ }
145447
146640
  normalCompletion = true;
145448
146641
  return hookTurn;
145449
146642
  }
@@ -145468,6 +146661,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145468
146661
  for (const goalEvent of takePendingGoalEvents()) {
145469
146662
  yield goalEvent;
145470
146663
  }
146664
+ endCurrentInteraction("ok");
145471
146665
  normalCompletion = true;
145472
146666
  return turn;
145473
146667
  }
@@ -145497,7 +146691,7 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145497
146691
  if (arenaAgentClient) {
145498
146692
  await arenaAgentClient.reportCompleted();
145499
146693
  }
145500
- if (isTopLevelInteraction) endInteractionSpan("ok");
146694
+ endCurrentInteraction("ok");
145501
146695
  return turn;
145502
146696
  }
145503
146697
  const nextSpeakerCheck = await checkNextSpeaker(
@@ -145536,9 +146730,10 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145536
146730
  } finally {
145537
146731
  settleSteerInput(pendingSteer, pushCountBefore);
145538
146732
  }
145539
- if (isTopLevelInteraction)
145540
- endInteractionSpan(signal.aborted ? "cancelled" : "ok");
145541
146733
  hasToolCalls = continueTurn.pendingToolCalls.length > 0;
146734
+ if (!hasToolCalls) {
146735
+ endCurrentInteraction(signal.aborted ? "cancelled" : "ok");
146736
+ }
145542
146737
  normalCompletion = true;
145543
146738
  return continueTurn;
145544
146739
  }
@@ -145552,8 +146747,8 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145552
146747
  if (signal?.aborted && arenaAgentClient) {
145553
146748
  await arenaAgentClient.reportCancelled();
145554
146749
  }
145555
- if (isTopLevelInteraction) {
145556
- endInteractionSpan(signal?.aborted ? "cancelled" : "ok");
146750
+ if (!hasToolCalls) {
146751
+ endCurrentInteraction(signal?.aborted ? "cancelled" : "ok");
145557
146752
  }
145558
146753
  if (!hasToolCalls) {
145559
146754
  this.cancelPendingMemoryPrefetch("no_safe_delivery_point");
@@ -145585,10 +146780,12 @@ The current date is: ${today}. Note: This is the authoritative current date \u20
145585
146780
  signal?.aborted ? "abort" : "no_safe_delivery_point"
145586
146781
  );
145587
146782
  }
145588
- if (isTopLevelInteraction) {
145589
- endInteractionSpan(signal?.aborted ? "cancelled" : "error", {
145590
- errorMessage: "unexpected exit"
145591
- });
146783
+ if (!normalCompletion) {
146784
+ endCurrentInteraction(
146785
+ signal?.aborted ? "cancelled" : "error",
146786
+ signal?.aborted ? void 0 : "unexpected exit",
146787
+ signal?.aborted ? void 0 : "unexpected_exit"
146788
+ );
145592
146789
  }
145593
146790
  }
145594
146791
  }
@@ -147289,6 +148486,12 @@ var Config = class _Config {
147289
148486
  sessionSourceType;
147290
148487
  sessionSourceId;
147291
148488
  sessionData;
148489
+ pendingSessionRestoreProjection;
148490
+ sessionRestoreRuntime;
148491
+ sessionRestoreProjectionSource;
148492
+ restoredFileHistory = false;
148493
+ goalRestoreActivation;
148494
+ rejectGoalRestoreActivation;
147292
148495
  sessionRuntimeBaseDir;
147293
148496
  sessionProjectDirRegistered = false;
147294
148497
  pendingSessionWriterLease;
@@ -147583,6 +148786,7 @@ var Config = class _Config {
147583
148786
  runtimeStatusWrite = Promise.resolve();
147584
148787
  fileExclusions;
147585
148788
  truncateToolOutputThreshold;
148789
+ truncateToolOutputThresholdExplicit;
147586
148790
  truncateToolOutputLines;
147587
148791
  toolOutputBatchBudget;
147588
148792
  shellDefaultTimeoutMs;
@@ -147642,6 +148846,8 @@ var Config = class _Config {
147642
148846
  sessionEnvClaimed = true;
147643
148847
  }
147644
148848
  this.sessionData = params.sessionData;
148849
+ this.sessionRestoreProjectionSource = params.sessionRestoreProjectionSource;
148850
+ this.setSessionRestoreProjection(params.sessionRestoreProjection);
147645
148851
  setDebugLogSession(this);
147646
148852
  this.debugLogger = createDebugLogger();
147647
148853
  this.embeddingModel = params.embeddingModel ?? DEFAULT_QWEN_EMBEDDING_MODEL;
@@ -147833,6 +149039,7 @@ var Config = class _Config {
147833
149039
  maxBufferedOutputBytes: params.shellExecutionConfig?.maxBufferedOutputBytes
147834
149040
  };
147835
149041
  this.truncateToolOutputThreshold = params.truncateToolOutputThreshold ?? DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD;
149042
+ this.truncateToolOutputThresholdExplicit = params.truncateToolOutputThreshold != null;
147836
149043
  this.truncateToolOutputLines = params.truncateToolOutputLines ?? DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES;
147837
149044
  this.toolOutputBatchBudget = params.toolOutputBatchBudget ?? DEFAULT_TOOL_OUTPUT_BATCH_BUDGET;
147838
149045
  this.shellDefaultTimeoutMs = params.shellDefaultTimeoutMs !== void 0 && Number.isInteger(params.shellDefaultTimeoutMs) && params.shellDefaultTimeoutMs >= 0 && params.shellDefaultTimeoutMs <= 2147483647 ? params.shellDefaultTimeoutMs : void 0;
@@ -147910,7 +149117,12 @@ var Config = class _Config {
147910
149117
  }
147911
149118
  this.geminiClient = new GeminiClient(this);
147912
149119
  this.chatRecordingService = this.chatRecordingEnabled ? this.createChatRecordingService() : void 0;
147913
- this.initializeGoalRuntime(this.sessionData?.conversation.messages);
149120
+ if (!this.sessionRestoreProjectionSource || this.sessionRestoreRuntime || !this.sessionWriterLeaseEnabled) {
149121
+ this.initializeGoalRuntime(
149122
+ this.sessionRestoreRuntime?.goalRecords ?? this.sessionData?.conversation.messages,
149123
+ this.sessionRestoreRuntime
149124
+ );
149125
+ }
147914
149126
  this.extensionManager = new ExtensionManager({
147915
149127
  workspaceDir: this.targetDir,
147916
149128
  enabledExtensionOverrides: this.overrideExtensions,
@@ -147978,6 +149190,7 @@ var Config = class _Config {
147978
149190
  this.sessionProjectDirRegistered = true;
147979
149191
  await this.initializeInternal(options2);
147980
149192
  } catch (error) {
149193
+ this.clearSessionRestoreProjection();
147981
149194
  if (this.sessionProjectDirRegistered) {
147982
149195
  unregisterSessionProjectDir(this.sessionId);
147983
149196
  this.sessionProjectDirRegistered = false;
@@ -148387,7 +149600,15 @@ var Config = class _Config {
148387
149600
  throw new SessionTranscriptChangedError();
148388
149601
  }
148389
149602
  let authoritative;
148390
- if (this.sessionData || lease.transcriptExistedAtAcquire) {
149603
+ let projection;
149604
+ if (this.sessionRestoreProjectionSource) {
149605
+ addDaemonRequestAttribute(
149606
+ "qwen-code.daemon.session_restore.projection_acquisition",
149607
+ "after_writer_lease"
149608
+ );
149609
+ projection = await this.sessionRestoreProjectionSource();
149610
+ this.setSessionRestoreProjection(projection);
149611
+ } else if (this.sessionData || lease.transcriptExistedAtAcquire) {
148391
149612
  authoritative = await this.getSessionService().loadSession(
148392
149613
  this.sessionId
148393
149614
  );
@@ -148401,7 +149622,18 @@ var Config = class _Config {
148401
149622
  throw new SessionWriterShutdownError();
148402
149623
  }
148403
149624
  this.sessionData = authoritative;
148404
- recorder.activate(lease, authoritative, persistedTitleInfo);
149625
+ recorder.activate(
149626
+ lease,
149627
+ authoritative,
149628
+ persistedTitleInfo,
149629
+ projection?.runtime.recording
149630
+ );
149631
+ if (this.sessionRestoreProjectionSource) {
149632
+ this.initializeGoalRuntime(
149633
+ projection?.runtime.goalRecords,
149634
+ projection?.runtime
149635
+ );
149636
+ }
148405
149637
  this.pendingSessionWriterLease = void 0;
148406
149638
  lease = void 0;
148407
149639
  this.startPendingGoalRestore();
@@ -148799,6 +150031,68 @@ var Config = class _Config {
148799
150031
  getSessionId() {
148800
150032
  return this.sessionId;
148801
150033
  }
150034
+ getSessionRestoreRuntime() {
150035
+ return this.sessionRestoreRuntime;
150036
+ }
150037
+ consumeSessionRestoreProjection() {
150038
+ const projection = this.pendingSessionRestoreProjection;
150039
+ this.pendingSessionRestoreProjection = void 0;
150040
+ return projection;
150041
+ }
150042
+ hydrateSessionRestoreFileHistory() {
150043
+ if (this.restoredFileHistory) return;
150044
+ const snapshots = this.sessionRestoreRuntime?.fileHistorySnapshots;
150045
+ if (!snapshots?.length) return;
150046
+ const service = this.getFileHistoryService();
150047
+ if (!service.isEnabled()) return;
150048
+ service.restoreFromSnapshots(snapshots);
150049
+ this.restoredFileHistory = true;
150050
+ }
150051
+ finalizeSessionRestore() {
150052
+ const runtime = this.sessionRestoreRuntime;
150053
+ if (!runtime) return;
150054
+ this.sessionRestoreRuntime = void 0;
150055
+ if (runtime.attributionSnapshot) {
150056
+ try {
150057
+ CommitAttributionService.getInstance().restoreFromSnapshot(
150058
+ runtime.attributionSnapshot
150059
+ );
150060
+ } catch (error) {
150061
+ this.debugLogger.error(
150062
+ `Session restore attribution activation failed: ${error}`
150063
+ );
150064
+ }
150065
+ }
150066
+ const activateGoal = this.goalRestoreActivation;
150067
+ this.goalRestoreActivation = void 0;
150068
+ this.rejectGoalRestoreActivation = void 0;
150069
+ if (activateGoal) {
150070
+ try {
150071
+ void activateGoal().catch((error) => {
150072
+ this.debugLogger.error(
150073
+ `Session restore goal activation failed: ${error}`
150074
+ );
150075
+ });
150076
+ } catch (error) {
150077
+ this.debugLogger.error(
150078
+ `Session restore goal activation failed: ${error}`
150079
+ );
150080
+ }
150081
+ }
150082
+ if (this.restoredFileHistory && this.fileHistoryService) {
150083
+ try {
150084
+ void this.fileHistoryService.validateRestoredSnapshots().catch((error) => {
150085
+ this.debugLogger.error(
150086
+ `FileHistory: validateRestoredSnapshots failed: ${error}`
150087
+ );
150088
+ });
150089
+ } catch (error) {
150090
+ this.debugLogger.error(
150091
+ `FileHistory: validateRestoredSnapshots failed: ${error}`
150092
+ );
150093
+ }
150094
+ }
150095
+ }
148802
150096
  setSessionSource(sourceType, sourceId) {
148803
150097
  this.sessionSourceType = sourceType;
148804
150098
  this.sessionSourceId = sourceId;
@@ -148855,6 +150149,7 @@ var Config = class _Config {
148855
150149
  unregisterSessionModel(previousSessionId);
148856
150150
  this.publishModelEnv();
148857
150151
  this.sessionData = sessionData;
150152
+ this.clearSessionRestoreProjection();
148858
150153
  this.pendingRecoveredAgentsNotice = null;
148859
150154
  this.getOwnActiveTodoReminders().clear();
148860
150155
  this.getOwnActiveTodoWorkChainOwners().clear();
@@ -149775,12 +151070,18 @@ var Config = class _Config {
149775
151070
  }
149776
151071
  async shutdownResourcesOnce() {
149777
151072
  try {
151073
+ this.clearSessionRestoreProjection();
149778
151074
  if (this.sessionProjectDirRegistered) {
149779
151075
  unregisterSessionProjectDir(this.sessionId);
149780
151076
  this.sessionProjectDirRegistered = false;
149781
151077
  }
149782
151078
  unregisterSessionModel(this.sessionId);
149783
151079
  if (Object.hasOwn(this, "goalRuntime")) {
151080
+ this.rejectGoalRestoreActivation?.(
151081
+ new GoalPersistenceUnavailableError("Goal runtime disposed")
151082
+ );
151083
+ this.goalRestoreActivation = void 0;
151084
+ this.rejectGoalRestoreActivation = void 0;
149784
151085
  this.goalTurnHostUnbind?.();
149785
151086
  this.goalTurnHostUnbind = void 0;
149786
151087
  this.settlePendingGoalRestore(
@@ -151596,6 +152897,9 @@ var Config = class _Config {
151596
152897
  }
151597
152898
  return this.truncateToolOutputThreshold;
151598
152899
  }
152900
+ isTruncateToolOutputThresholdExplicit() {
152901
+ return this.truncateToolOutputThresholdExplicit;
152902
+ }
151599
152903
  getTruncateToolOutputLines() {
151600
152904
  if (this.truncateToolOutputLines <= 0) {
151601
152905
  return Number.POSITIVE_INFINITY;
@@ -151659,6 +152963,11 @@ var Config = class _Config {
151659
152963
  }
151660
152964
  return this.goalRuntimeReady.then(() => runtime);
151661
152965
  }
152966
+ getGoalRuntimePrepared() {
152967
+ const runtime = this.getGoalRuntime();
152968
+ if (!this.sessionRestoreRuntime) return this.getGoalRuntimeReady();
152969
+ return runtime.getPreparedRestore().then(() => runtime);
152970
+ }
151662
152971
  async rebaseGoalRuntimeFromActiveTranscript() {
151663
152972
  const runtime = this.getGoalRuntime();
151664
152973
  const recordingService = this.chatRecordingService;
@@ -151702,10 +153011,16 @@ var Config = class _Config {
151702
153011
  (event) => {
151703
153012
  this.notifyChatRecordingFailure(event);
151704
153013
  },
151705
- this.sessionWriterLeaseEnabled
153014
+ this.sessionWriterLeaseEnabled,
153015
+ this.sessionRestoreRuntime?.recording
151706
153016
  );
151707
153017
  }
151708
- initializeGoalRuntime(records) {
153018
+ initializeGoalRuntime(records, restoreRuntime) {
153019
+ this.rejectGoalRestoreActivation?.(
153020
+ new GoalPersistenceUnavailableError("Goal runtime replaced")
153021
+ );
153022
+ this.goalRestoreActivation = void 0;
153023
+ this.rejectGoalRestoreActivation = void 0;
151709
153024
  this.goalTurnHostUnbind?.();
151710
153025
  this.goalTurnHostUnbind = void 0;
151711
153026
  this.settlePendingGoalRestore(
@@ -151729,7 +153044,27 @@ var Config = class _Config {
151729
153044
  if (this.goalTurnHost) {
151730
153045
  this.goalTurnHostUnbind = runtime.bindHost(this.goalTurnHost);
151731
153046
  }
151732
- if (this.sessionWriterLeaseEnabled && !recorder.hasWriteOwnership()) {
153047
+ if (restoreRuntime) {
153048
+ const preparation = runtime.prepareRestore(
153049
+ records ?? [],
153050
+ restoreRuntime.goalCheckpointWindow
153051
+ );
153052
+ let resolveActivation;
153053
+ let rejectActivation;
153054
+ const activation = new Promise((resolve41, reject) => {
153055
+ resolveActivation = resolve41;
153056
+ rejectActivation = reject;
153057
+ });
153058
+ this.rejectGoalRestoreActivation = rejectActivation;
153059
+ this.goalRestoreActivation = () => {
153060
+ const started = runtime.activateRestoredWork();
153061
+ void started.then(resolveActivation, rejectActivation);
153062
+ return started;
153063
+ };
153064
+ this.goalRuntimeReady = Promise.all([preparation, activation]).then(
153065
+ () => runtime
153066
+ );
153067
+ } else if (this.sessionWriterLeaseEnabled && !recorder.hasWriteOwnership()) {
151733
153068
  const ready = new Promise((resolve41, reject) => {
151734
153069
  this.pendingGoalRestore = { runtime, resolve: resolve41, reject };
151735
153070
  });
@@ -151777,6 +153112,21 @@ var Config = class _Config {
151777
153112
  this.pendingGoalRestore = void 0;
151778
153113
  pending.reject(error);
151779
153114
  }
153115
+ setSessionRestoreProjection(projection) {
153116
+ this.pendingSessionRestoreProjection = projection;
153117
+ this.sessionRestoreRuntime = projection?.runtime;
153118
+ this.restoredFileHistory = false;
153119
+ }
153120
+ clearSessionRestoreProjection() {
153121
+ this.pendingSessionRestoreProjection = void 0;
153122
+ this.sessionRestoreRuntime = void 0;
153123
+ this.restoredFileHistory = false;
153124
+ this.rejectGoalRestoreActivation?.(
153125
+ new GoalPersistenceUnavailableError("Session restore was abandoned")
153126
+ );
153127
+ this.goalRestoreActivation = void 0;
153128
+ this.rejectGoalRestoreActivation = void 0;
153129
+ }
151780
153130
  notifyChatRecordingFailure(event) {
151781
153131
  for (const listener of [...this.chatRecordingFailureListeners]) {
151782
153132
  try {
@@ -152100,7 +153450,7 @@ var Config = class _Config {
152100
153450
  }
152101
153451
  if (!enabled) return;
152102
153452
  registry.registerFactory(ToolNames.IMAGE_GEN, async () => {
152103
- const { ImageGenTool } = await import("./image-gen-OTFC2S7L.js");
153453
+ const { ImageGenTool } = await import("./image-gen-YPK2AZT4.js");
152104
153454
  return new ImageGenTool(this);
152105
153455
  });
152106
153456
  }
@@ -152130,36 +153480,36 @@ var Config = class _Config {
152130
153480
  if (options2?.forSubAgent) return;
152131
153481
  const schema = this.jsonSchema;
152132
153482
  await registerLazy(ToolNames.STRUCTURED_OUTPUT, async () => {
152133
- const { SyntheticOutputTool } = await import("./syntheticOutput-D3Z64LJC.js");
153483
+ const { SyntheticOutputTool } = await import("./syntheticOutput-DVHJMUGV.js");
152134
153484
  return new SyntheticOutputTool(schema);
152135
153485
  });
152136
153486
  }, "registerStructuredOutputIfRequested");
152137
153487
  const registerGoalWorkerTools = /* @__PURE__ */ __name(async () => {
152138
153488
  if (options2?.forSubAgent) return;
152139
153489
  await registerLazy(ToolNames.GET_GOAL, async () => {
152140
- const { GetGoalTool } = await import("./goal-tools-JDK2SNMV.js");
153490
+ const { GetGoalTool } = await import("./goal-tools-M4UDAZXP.js");
152141
153491
  return new GetGoalTool(this);
152142
153492
  });
152143
153493
  await registerLazy(ToolNames.UPDATE_GOAL, async () => {
152144
- const { UpdateGoalTool } = await import("./goal-tools-JDK2SNMV.js");
153494
+ const { UpdateGoalTool } = await import("./goal-tools-M4UDAZXP.js");
152145
153495
  return new UpdateGoalTool(this);
152146
153496
  });
152147
153497
  }, "registerGoalWorkerTools");
152148
153498
  if (this.getBareMode()) {
152149
153499
  await registerLazy(ToolNames.READ_FILE, async () => {
152150
- const { ReadFileTool } = await import("./read-file-GORBXJTS.js");
153500
+ const { ReadFileTool } = await import("./read-file-LOVUSBJC.js");
152151
153501
  return new ReadFileTool(this);
152152
153502
  });
152153
153503
  await registerLazy(ToolNames.EDIT, async () => {
152154
- const { EditTool } = await import("./edit-WXVZ7FHS.js");
153504
+ const { EditTool } = await import("./edit-X73LA4YO.js");
152155
153505
  return new EditTool(this);
152156
153506
  });
152157
153507
  await registerLazy(ToolNames.NOTEBOOK_EDIT, async () => {
152158
- const { NotebookEditTool } = await import("./notebook-edit-GEPL33NO.js");
153508
+ const { NotebookEditTool } = await import("./notebook-edit-QD4TRKLY.js");
152159
153509
  return new NotebookEditTool(this);
152160
153510
  });
152161
153511
  await registerLazy(ToolNames.SHELL, async () => {
152162
- const { ShellTool: ShellTool2 } = await import("./shell-C2UP5FF2.js");
153512
+ const { ShellTool: ShellTool2 } = await import("./shell-EGTSUO2P.js");
152163
153513
  return new ShellTool2(this);
152164
153514
  });
152165
153515
  await registerGoalWorkerTools();
@@ -152171,43 +153521,43 @@ var Config = class _Config {
152171
153521
  }
152172
153522
  await registerGoalWorkerTools();
152173
153523
  await registerLazy(ToolNames.TOOL_SEARCH, async () => {
152174
- const { ToolSearchTool } = await import("./tool-search-B6F3MPUZ.js");
153524
+ const { ToolSearchTool } = await import("./tool-search-QNBLXUGR.js");
152175
153525
  return new ToolSearchTool(this);
152176
153526
  });
152177
153527
  await registerLazy(ToolNames.READ_MCP_RESOURCE, async () => {
152178
- const { ReadMcpResourceTool } = await import("./read-mcp-resource-TJSJRH4F.js");
153528
+ const { ReadMcpResourceTool } = await import("./read-mcp-resource-GWCP23WG.js");
152179
153529
  return new ReadMcpResourceTool(this);
152180
153530
  });
152181
153531
  await registerLazy(ToolNames.AGENT, async () => {
152182
- const { AgentTool: AgentTool2 } = await import("./agent-FAWBG7PP.js");
153532
+ const { AgentTool: AgentTool2 } = await import("./agent-E6V3VXQR.js");
152183
153533
  return new AgentTool2(this);
152184
153534
  });
152185
153535
  await registerLazy(ToolNames.LIST_AGENTS, async () => {
152186
- const { ListAgentsTool } = await import("./list-agents-4GQ2XNEU.js");
153536
+ const { ListAgentsTool } = await import("./list-agents-O6WSY4CT.js");
152187
153537
  return new ListAgentsTool(this);
152188
153538
  });
152189
153539
  await registerLazy(ToolNames.TASK_STOP, async () => {
152190
- const { TaskStopTool } = await import("./task-stop-HHUGCD25.js");
153540
+ const { TaskStopTool } = await import("./task-stop-YFNATTIM.js");
152191
153541
  return new TaskStopTool(this);
152192
153542
  });
152193
153543
  await registerLazy(ToolNames.SEND_MESSAGE, async () => {
152194
- const { SendMessageTool } = await import("./send-message-RBYLV5NY.js");
153544
+ const { SendMessageTool } = await import("./send-message-O7FO63UK.js");
152195
153545
  return new SendMessageTool(this);
152196
153546
  });
152197
153547
  await registerLazy(ToolNames.SKILL, async () => {
152198
- const { SkillTool } = await import("./skill-4XCNK55E.js");
153548
+ const { SkillTool } = await import("./skill-IFUD72GF.js");
152199
153549
  return new SkillTool(this);
152200
153550
  });
152201
153551
  await registerLazy(ToolNames.LS, async () => {
152202
- const { LSTool } = await import("./ls-FSHISLLA.js");
153552
+ const { LSTool } = await import("./ls-6W2D7TKU.js");
152203
153553
  return new LSTool(this);
152204
153554
  });
152205
153555
  await registerLazy(ToolNames.READ_FILE, async () => {
152206
- const { ReadFileTool } = await import("./read-file-GORBXJTS.js");
153556
+ const { ReadFileTool } = await import("./read-file-LOVUSBJC.js");
152207
153557
  return new ReadFileTool(this);
152208
153558
  });
152209
153559
  await registerLazy(ToolNames.ZOOM_IMAGE, async () => {
152210
- const { ZoomImageTool } = await import("./zoom-image-RS6MU26F.js");
153560
+ const { ZoomImageTool } = await import("./zoom-image-4MVVVM7E.js");
152211
153561
  return new ZoomImageTool(this);
152212
153562
  });
152213
153563
  if (this.getUseRipgrep()) {
@@ -152222,7 +153572,7 @@ var Config = class _Config {
152222
153572
  recordStartupEvent("config_initialize_ripgrep_probe_end");
152223
153573
  if (useRipgrep) {
152224
153574
  await registerLazy(ToolNames.GREP, async () => {
152225
- const { RipGrepTool: RipGrepTool2 } = await import("./ripGrep-RNLIZGCY.js");
153575
+ const { RipGrepTool: RipGrepTool2 } = await import("./ripGrep-ZJSHKB6H.js");
152226
153576
  return new RipGrepTool2(this);
152227
153577
  });
152228
153578
  } else {
@@ -152235,7 +153585,7 @@ var Config = class _Config {
152235
153585
  )
152236
153586
  );
152237
153587
  await registerLazy(ToolNames.GREP, async () => {
152238
- const { GrepTool } = await import("./grep-QWBLG564.js");
153588
+ const { GrepTool } = await import("./grep-F4UAR7KX.js");
152239
153589
  return new GrepTool(this);
152240
153590
  });
152241
153591
  }
@@ -152243,77 +153593,77 @@ var Config = class _Config {
152243
153593
  recordStartupEvent("config_initialize_ripgrep_probe_start");
152244
153594
  recordStartupEvent("config_initialize_ripgrep_probe_end");
152245
153595
  await registerLazy(ToolNames.GREP, async () => {
152246
- const { GrepTool } = await import("./grep-QWBLG564.js");
153596
+ const { GrepTool } = await import("./grep-F4UAR7KX.js");
152247
153597
  return new GrepTool(this);
152248
153598
  });
152249
153599
  }
152250
153600
  await registerLazy(ToolNames.GLOB, async () => {
152251
- const { GlobTool } = await import("./glob-KJ4A4ZOM.js");
153601
+ const { GlobTool } = await import("./glob-VMEEDDLO.js");
152252
153602
  return new GlobTool(this);
152253
153603
  });
152254
153604
  await registerLazy(ToolNames.EDIT, async () => {
152255
- const { EditTool } = await import("./edit-WXVZ7FHS.js");
153605
+ const { EditTool } = await import("./edit-X73LA4YO.js");
152256
153606
  return new EditTool(this);
152257
153607
  });
152258
153608
  await registerLazy(ToolNames.NOTEBOOK_EDIT, async () => {
152259
- const { NotebookEditTool } = await import("./notebook-edit-GEPL33NO.js");
153609
+ const { NotebookEditTool } = await import("./notebook-edit-QD4TRKLY.js");
152260
153610
  return new NotebookEditTool(this);
152261
153611
  });
152262
153612
  await registerLazy(ToolNames.WRITE_FILE, async () => {
152263
- const { WriteFileTool: WriteFileTool2 } = await import("./write-file-PYL3JCCD.js");
153613
+ const { WriteFileTool: WriteFileTool2 } = await import("./write-file-JJAY7JSP.js");
152264
153614
  return new WriteFileTool2(this);
152265
153615
  });
152266
153616
  await registerLazy(ToolNames.SHELL, async () => {
152267
- const { ShellTool: ShellTool2 } = await import("./shell-C2UP5FF2.js");
153617
+ const { ShellTool: ShellTool2 } = await import("./shell-EGTSUO2P.js");
152268
153618
  return new ShellTool2(this);
152269
153619
  });
152270
153620
  await registerLazy(ToolNames.TODO_WRITE, async () => {
152271
- const { TodoWriteTool } = await import("./todoWrite-WINAZSZI.js");
153621
+ const { TodoWriteTool } = await import("./todoWrite-K5K7NRE5.js");
152272
153622
  return new TodoWriteTool(this);
152273
153623
  });
152274
153624
  const supportsUserInteraction = resolveInteractionMode(this) !== "headless";
152275
153625
  if (supportsUserInteraction) {
152276
153626
  await registerLazy(ToolNames.ASK_USER_QUESTION, async () => {
152277
- const { AskUserQuestionTool } = await import("./askUserQuestion-7G3LI3IZ.js");
153627
+ const { AskUserQuestionTool } = await import("./askUserQuestion-HZJJLR3Z.js");
152278
153628
  return new AskUserQuestionTool(this);
152279
153629
  });
152280
153630
  }
152281
153631
  if (!this.sdkMode && (supportsUserInteraction || options2?.forSubAgent)) {
152282
153632
  await registerLazy(ToolNames.EXIT_PLAN_MODE, async () => {
152283
- const { ExitPlanModeTool: ExitPlanModeTool2 } = await import("./exitPlanMode-MBPAPBBV.js");
153633
+ const { ExitPlanModeTool: ExitPlanModeTool2 } = await import("./exitPlanMode-WDURQMIU.js");
152284
153634
  return new ExitPlanModeTool2(this);
152285
153635
  });
152286
153636
  }
152287
153637
  if (!this.sdkMode && supportsUserInteraction) {
152288
153638
  await registerLazy(ToolNames.ENTER_PLAN_MODE, async () => {
152289
- const { EnterPlanModeTool } = await import("./enterPlanMode-FT4MRU5N.js");
153639
+ const { EnterPlanModeTool } = await import("./enterPlanMode-6BDYUQ5T.js");
152290
153640
  return new EnterPlanModeTool(this);
152291
153641
  });
152292
153642
  }
152293
153643
  await registerLazy(ToolNames.ENTER_WORKTREE, async () => {
152294
- const { EnterWorktreeTool } = await import("./enter-worktree-TYMVXFLA.js");
153644
+ const { EnterWorktreeTool } = await import("./enter-worktree-CLRQTIVN.js");
152295
153645
  return new EnterWorktreeTool(this);
152296
153646
  });
152297
153647
  await registerLazy(ToolNames.EXIT_WORKTREE, async () => {
152298
- const { ExitWorktreeTool } = await import("./exit-worktree-ODZUQLGJ.js");
153648
+ const { ExitWorktreeTool } = await import("./exit-worktree-TFFJXCRT.js");
152299
153649
  return new ExitWorktreeTool(this);
152300
153650
  });
152301
153651
  await registerLazy(ToolNames.WEB_FETCH, async () => {
152302
- const { WebFetchTool } = await import("./web-fetch-NUOLHXPN.js");
153652
+ const { WebFetchTool } = await import("./web-fetch-MBIVXKPE.js");
152303
153653
  return new WebFetchTool(this);
152304
153654
  });
152305
153655
  if (resolveInteractionMode(this) === "interactive" && !this.sdkMode && !this.getScreenReader() && !options2?.forSubAgent) {
152306
153656
  await registerLazy(ToolNames.DISPLAY_IMAGE, async () => {
152307
- const { DisplayImageTool } = await import("./display-image-ZE3GZNIK.js");
153657
+ const { DisplayImageTool } = await import("./display-image-M2ELAVN4.js");
152308
153658
  return new DisplayImageTool(this);
152309
153659
  });
152310
153660
  }
152311
153661
  if (this.webSearchSettings?.enabled) {
152312
- const { evaluateWebSearchGate } = await import("./web-search-LVOOV4XZ.js");
153662
+ const { evaluateWebSearchGate } = await import("./web-search-4LBIN6VF.js");
152313
153663
  const gate = evaluateWebSearchGate(this);
152314
153664
  if (gate.ok) {
152315
153665
  await registerLazy(ToolNames.WEB_SEARCH, async () => {
152316
- const { WebSearchTool } = await import("./web-search-LVOOV4XZ.js");
153666
+ const { WebSearchTool } = await import("./web-search-4LBIN6VF.js");
152317
153667
  return new WebSearchTool(this);
152318
153668
  });
152319
153669
  } else if (!this.webSearchNoticeEmitted && !options2?.forSubAgent) {
@@ -152324,83 +153674,83 @@ var Config = class _Config {
152324
153674
  await this.registerImageGenerationTool(registry);
152325
153675
  if (this.isArtifactEnabled()) {
152326
153676
  await registerLazy(ToolNames.ARTIFACT, async () => {
152327
- const { ArtifactTool } = await import("./artifact-tool-FRMBPDPB.js");
153677
+ const { ArtifactTool } = await import("./artifact-tool-4GCQQDZI.js");
152328
153678
  return new ArtifactTool(this);
152329
153679
  });
152330
153680
  }
152331
153681
  if (this.isRecordArtifactEnabled()) {
152332
153682
  await registerLazy(ToolNames.RECORD_ARTIFACT, async () => {
152333
- const { RecordArtifactTool } = await import("./record-artifact-FXF5LHPE.js");
153683
+ const { RecordArtifactTool } = await import("./record-artifact-IYQDEYMV.js");
152334
153684
  return new RecordArtifactTool();
152335
153685
  });
152336
153686
  }
152337
153687
  if (this.isLspEnabled() && this.getLspClient()) {
152338
153688
  await registerLazy(ToolNames.LSP, async () => {
152339
- const { LspTool } = await import("./lsp-APQJ5ZEZ.js");
153689
+ const { LspTool } = await import("./lsp-NJ4KFBI2.js");
152340
153690
  return new LspTool(this);
152341
153691
  });
152342
153692
  }
152343
153693
  await registerStructuredOutputIfRequested();
152344
153694
  if (this.isCronEnabled()) {
152345
153695
  await registerLazy(ToolNames.CRON_CREATE, async () => {
152346
- const { CronCreateTool } = await import("./cron-create-ZOVA3CC2.js");
153696
+ const { CronCreateTool } = await import("./cron-create-2JZ2TWTF.js");
152347
153697
  return new CronCreateTool(this);
152348
153698
  });
152349
153699
  await registerLazy(ToolNames.CRON_LIST, async () => {
152350
- const { CronListTool } = await import("./cron-list-UHGX3IQG.js");
153700
+ const { CronListTool } = await import("./cron-list-V44KHAF6.js");
152351
153701
  return new CronListTool(this);
152352
153702
  });
152353
153703
  await registerLazy(ToolNames.CRON_DELETE, async () => {
152354
- const { CronDeleteTool } = await import("./cron-delete-7Z3H4LJY.js");
153704
+ const { CronDeleteTool } = await import("./cron-delete-CTPD2P26.js");
152355
153705
  return new CronDeleteTool(this);
152356
153706
  });
152357
153707
  await registerLazy(ToolNames.LOOP_WAKEUP, async () => {
152358
- const { LoopWakeupTool } = await import("./loop-wakeup-HOQI3K5D.js");
153708
+ const { LoopWakeupTool } = await import("./loop-wakeup-GVQRMUKS.js");
152359
153709
  return new LoopWakeupTool(this);
152360
153710
  });
152361
153711
  }
152362
153712
  await registerLazy(ToolNames.CREATE_SUB_SESSION, async () => {
152363
- const { CreateSubSessionTool } = await import("./create-sub-session-Y4WYDZGC.js");
153713
+ const { CreateSubSessionTool } = await import("./create-sub-session-XT6DLYOE.js");
152364
153714
  return new CreateSubSessionTool(this);
152365
153715
  });
152366
153716
  if (this.isAgentTeamEnabled()) {
152367
153717
  await registerLazy(ToolNames.TEAM_CREATE, async () => {
152368
- const { TeamCreateTool } = await import("./team-create-WZWH2NJI.js");
153718
+ const { TeamCreateTool } = await import("./team-create-B6A6MJBT.js");
152369
153719
  return new TeamCreateTool(this);
152370
153720
  });
152371
153721
  await registerLazy(ToolNames.TEAM_DELETE, async () => {
152372
- const { TeamDeleteTool } = await import("./team-delete-PZGGBQLM.js");
153722
+ const { TeamDeleteTool } = await import("./team-delete-MKYMYBFM.js");
152373
153723
  return new TeamDeleteTool(this);
152374
153724
  });
152375
153725
  await registerLazy(ToolNames.TEAM_PLAN_APPROVAL, async () => {
152376
- const { TeamPlanApprovalTool } = await import("./team-plan-approval-SUZQJCWJ.js");
153726
+ const { TeamPlanApprovalTool } = await import("./team-plan-approval-5WO3CXXU.js");
152377
153727
  return new TeamPlanApprovalTool(this);
152378
153728
  });
152379
153729
  await registerLazy(ToolNames.TASK_CREATE, async () => {
152380
- const { TaskCreateTool } = await import("./task-create-URFZ5EUX.js");
153730
+ const { TaskCreateTool } = await import("./task-create-4NC7PDI4.js");
152381
153731
  return new TaskCreateTool(this);
152382
153732
  });
152383
153733
  await registerLazy(ToolNames.TASK_UPDATE, async () => {
152384
- const { TaskUpdateTool } = await import("./task-update-DVV6CUGI.js");
153734
+ const { TaskUpdateTool } = await import("./task-update-BPLM52GD.js");
152385
153735
  return new TaskUpdateTool(this);
152386
153736
  });
152387
153737
  await registerLazy(ToolNames.TASK_LIST, async () => {
152388
- const { TaskListTool } = await import("./task-list-6JDFMPUW.js");
153738
+ const { TaskListTool } = await import("./task-list-LBSRMOC7.js");
152389
153739
  return new TaskListTool(this);
152390
153740
  });
152391
153741
  }
152392
153742
  if (this.isWorkflowsEnabled()) {
152393
153743
  await registerLazy(ToolNames.WORKFLOW, async () => {
152394
- const { WorkflowTool } = await import("./workflow-JSTYTG3K.js");
153744
+ const { WorkflowTool } = await import("./workflow-LNMA55HY.js");
152395
153745
  return new WorkflowTool(this);
152396
153746
  });
152397
153747
  }
152398
153748
  if (this.isComputerUseEnabled()) {
152399
- const { registerComputerUseTools } = await import("./computer-use-S4JEU5P7.js");
153749
+ const { registerComputerUseTools } = await import("./computer-use-F4URV4TU.js");
152400
153750
  await registerComputerUseTools(registerLazy, this);
152401
153751
  }
152402
153752
  await registerLazy(ToolNames.MONITOR, async () => {
152403
- const { MonitorTool } = await import("./monitor-PY4WDSX3.js");
153753
+ const { MonitorTool } = await import("./monitor-2MM23VDV.js");
152404
153754
  return new MonitorTool(this);
152405
153755
  });
152406
153756
  if (this.pendingMcpBudgetCallback) {
@@ -152871,6 +154221,7 @@ export {
152871
154221
  GROUP_COLOR_OPTIONS,
152872
154222
  SessionOrganizationError,
152873
154223
  SessionOrganizationService,
154224
+ collectSessionTurnState,
152874
154225
  SESSION_TRANSCRIPT_MAX_LIMIT,
152875
154226
  SESSION_TRANSCRIPT_MAX_INDEX_BYTES,
152876
154227
  SESSION_TRANSCRIPT_MAX_PAGE_BYTES,
@@ -152881,8 +154232,6 @@ export {
152881
154232
  SessionTranscriptPageTooLargeError,
152882
154233
  SessionTranscriptCursorCodec,
152883
154234
  encodeSessionTranscriptCursor,
152884
- isReplayTurnStartType,
152885
- findBoundaryAtOrBefore,
152886
154235
  SessionTranscriptReader,
152887
154236
  SessionWriterError,
152888
154237
  SESSION_WRITER_RPC_CODES,
@@ -152962,13 +154311,8 @@ export {
152962
154311
  isEditorAvailable,
152963
154312
  createPatchSmart,
152964
154313
  getDiffStat,
152965
- stripAnsiAndControl,
152966
- safeLiteralReplace,
152967
- isBinary,
152968
- normalizeContent,
152969
154314
  sanitizeChildEnv,
152970
154315
  formatMemoryUsage,
152971
- sessionIdContext,
152972
154316
  getShellContextEnvVars,
152973
154317
  getShellPagerEnv,
152974
154318
  isSignalTermination,
@@ -153017,6 +154361,8 @@ export {
153017
154361
  getSubagentsRootDir,
153018
154362
  getSubagentSessionDir,
153019
154363
  readAgentMeta,
154364
+ buildAgentTranscriptAttach,
154365
+ attachJsonlTranscriptWriter,
153020
154366
  resolveSubagentApprovalMode,
153021
154367
  TOOL_REGISTRY_REBUILT,
153022
154368
  hasRebuiltToolRegistry,
@@ -153037,8 +154383,6 @@ export {
153037
154383
  MessageDisplayDispatcher,
153038
154384
  collectMemoryDiagnostics,
153039
154385
  MCPOAuthTokenStorage,
153040
- OAUTH_DISPLAY_MESSAGE_EVENT,
153041
- OAUTH_AUTH_URL_EVENT,
153042
154386
  MCPOAuthProvider,
153043
154387
  mcpServerRequiresOAuth,
153044
154388
  getMCPDiscoveryState,
@@ -153061,7 +154405,6 @@ export {
153061
154405
  isTerminalWorkflowStatus,
153062
154406
  EXTENSIONS_CONFIG_FILENAME,
153063
154407
  So,
153064
- redactUrlCredentials,
153065
154408
  require_toml,
153066
154409
  convertTomlToMarkdown,
153067
154410
  normalizeClaudeMcpServer,