@qwen-code/qwen-code 0.21.0 → 0.21.1-nightly.20260730.1643a6c9a

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 (417) hide show
  1. package/bundled/qc-helper/docs/configuration/model-providers.md +2 -0
  2. package/bundled/qc-helper/docs/configuration/settings.md +39 -28
  3. package/bundled/qc-helper/docs/features/channels/_meta.ts +2 -0
  4. package/bundled/qc-helper/docs/features/channels/github.md +117 -0
  5. package/bundled/qc-helper/docs/features/channels/gitlab.md +171 -0
  6. package/bundled/qc-helper/docs/features/channels/overview.md +61 -6
  7. package/bundled/qc-helper/docs/features/code-review.md +1 -1
  8. package/bundled/qc-helper/docs/features/hooks.md +70 -15
  9. package/bundled/qc-helper/docs/features/mcp.md +9 -1
  10. package/bundled/qc-helper/docs/features/scheduled-tasks.md +3 -1
  11. package/bundled/qc-helper/docs/features/sub-agents.md +20 -0
  12. package/bundled/qc-helper/docs/qwen-serve.md +11 -7
  13. package/bundled/qc-helper/docs/reference/keyboard-shortcuts.md +2 -2
  14. package/bundled/qc-helper/docs/support/troubleshooting.md +2 -1
  15. package/bundled/review/DESIGN.md +19 -0
  16. package/bundled/review/SKILL.md +120 -61
  17. package/chunks/MaxSizedBox-H77LGFDG.js +86 -0
  18. package/chunks/{StandaloneSessionPicker-BIRMPLRD.js → StandaloneSessionPicker-NGKLCYX4.js} +68 -67
  19. package/chunks/{acp-startup-profiler-RV3IV562.js → acp-startup-profiler-DFVPFQ6C.js} +2 -2
  20. package/chunks/{acpAgent-6J2U72PQ.js → acpAgent-RUN53PRW.js} +1381 -543
  21. package/chunks/agent-4CFRD2OG.js +82 -0
  22. package/chunks/agent-headless-XPUCIZLL.js +76 -0
  23. package/chunks/{anthropicContentGenerator-75BKLTSP.js → anthropicContentGenerator-V2QOGVYD.js} +79 -27
  24. package/chunks/{artifact-tool-Y5T7GG7F.js → artifact-tool-6K6U7XYJ.js} +4 -4
  25. package/chunks/{askUserQuestion-2H6747FR.js → askUserQuestion-GD2IJJ7I.js} +4 -4
  26. package/chunks/bridge-B2YJLSLT.js +92 -0
  27. package/chunks/{build-RV63TIRH.js → build-GDBLPA24.js} +1 -1
  28. package/chunks/{ca-25EDXPFZ.js → ca-6W3SK7OQ.js} +6 -1
  29. package/chunks/channel-management-service-RAPKQK24.js +418 -0
  30. package/chunks/channel-settings-store-KJQKY6NN.js +89 -0
  31. package/chunks/{channel-worker-group-2ZD7TVAT.js → channel-worker-group-7SZ7MR3K.js} +11 -6
  32. package/chunks/{channel-worker-manager-4OA4BCGB.js → channel-worker-manager-RN5KJYPF.js} +11 -6
  33. package/chunks/{channel-worker-supervisor-V7KCFJTS.js → channel-worker-supervisor-CABBXYHK.js} +7 -5
  34. package/chunks/{chunk-M5JM7OSF.js → chunk-2DN4J57Y.js} +2 -3
  35. package/chunks/{chunk-6GMVPFB2.js → chunk-2IIJTXYF.js} +45 -16
  36. package/chunks/{chunk-BPJSQIJX.js → chunk-2J3OJGTL.js} +0 -2
  37. package/chunks/{chunk-EPDRMGT4.js → chunk-2LKVPASC.js} +4 -28
  38. package/chunks/{chunk-PWTZEM3C.js → chunk-2LQTH543.js} +3 -37
  39. package/chunks/{chunk-CIKQ7KKO.js → chunk-2Q4CZ3V6.js} +713 -419
  40. package/chunks/{chunk-HIJQF5B5.js → chunk-3L2SPEBH.js} +1 -1
  41. package/chunks/{chunk-JXJFVC6E.js → chunk-3QDXECUB.js} +46 -11
  42. package/chunks/{chunk-PSOO6YXD.js → chunk-3RMX26V7.js} +9 -7
  43. package/chunks/{chunk-PC6JANNU.js → chunk-4755HD5V.js} +4 -4
  44. package/chunks/{chunk-GSN55ZRI.js → chunk-4D3MHM5F.js} +19 -7
  45. package/chunks/{chunk-EBJQ6AXW.js → chunk-4FQ4OKOU.js} +260 -14
  46. package/chunks/{chunk-BIQWWWJN.js → chunk-4G2BISNC.js} +1 -1
  47. package/chunks/{chunk-IKYJHJNF.js → chunk-5EHIP3GX.js} +3 -3
  48. package/chunks/chunk-5IDU2UGL.js +2196 -0
  49. package/chunks/{chunk-DHHOYAPR.js → chunk-5TBMQLGG.js} +7 -7
  50. package/chunks/{chunk-A4UCTEB5.js → chunk-5WV5S2GT.js} +0 -1
  51. package/chunks/chunk-5YKDXHUY.js +463 -0
  52. package/chunks/{chunk-K36B6G2O.js → chunk-5ZEFGTII.js} +5 -5
  53. package/chunks/{chunk-K4XWPEWB.js → chunk-64LQLPL7.js} +4 -33
  54. package/chunks/{chunk-TGILQ3YH.js → chunk-6CH6PHMZ.js} +141 -64
  55. package/chunks/chunk-6FMJLI5M.js +1591 -0
  56. package/chunks/chunk-6MPDY6ZG.js +76 -0
  57. package/chunks/{chunk-2NH6DYI4.js → chunk-6OF62NPQ.js} +12 -12
  58. package/chunks/{chunk-JZA3JUDJ.js → chunk-6QIGFD5W.js} +1 -1
  59. package/chunks/{chunk-ETSW4KLJ.js → chunk-72E7TSGG.js} +2 -2
  60. package/chunks/{chunk-OHNBB4XR.js → chunk-75GFAX4R.js} +1 -1
  61. package/chunks/{chunk-UDX5OBWR.js → chunk-77IMMLN2.js} +94 -4
  62. package/chunks/{chunk-TEHGS6UP.js → chunk-7A4V5CJY.js} +154 -16
  63. package/chunks/{chunk-QAF7NMK7.js → chunk-7BV2P4S3.js} +1 -1
  64. package/chunks/{chunk-RIBKPMRP.js → chunk-7RFNMXPU.js} +19 -6
  65. package/chunks/{chunk-KMQ33DO4.js → chunk-7UKQW4JU.js} +4 -4
  66. package/chunks/{chunk-A5L3JMUA.js → chunk-7XATOOE7.js} +18 -4
  67. package/chunks/{chunk-5I2IWRSH.js → chunk-A3NDJ5SB.js} +2 -2
  68. package/chunks/{chunk-JLU636DO.js → chunk-ALMR3E6Q.js} +1 -0
  69. package/chunks/{chunk-TPRQ7RZH.js → chunk-ANND7YTH.js} +2341 -940
  70. package/chunks/{chunk-PJIZUQVC.js → chunk-AZQ3DT76.js} +2 -2
  71. package/chunks/{chunk-KIM5GUMA.js → chunk-B47WVQ7T.js} +400 -162
  72. package/chunks/{chunk-UH3WSE5L.js → chunk-B4AJNNOL.js} +1 -6
  73. package/chunks/{chunk-BJX6ZSUK.js → chunk-BCZFQXWK.js} +2 -2
  74. package/chunks/{chunk-BKHWX6I2.js → chunk-CAEQL6GZ.js} +11 -3
  75. package/chunks/{chunk-J56UI34H.js → chunk-CI2PGI7Z.js} +4 -2
  76. package/chunks/{chunk-2SCDWPXI.js → chunk-CUWGNCKW.js} +5 -5
  77. package/chunks/{chunk-TOFQCPDC.js → chunk-CVHIL5IG.js} +4 -5
  78. package/chunks/{chunk-VRYUBFMC.js → chunk-CYIBLZBR.js} +1 -1
  79. package/chunks/{chunk-YBL3QUDD.js → chunk-CYPJYJIX.js} +1 -1
  80. package/chunks/{chunk-XVNQMZ2I.js → chunk-DGEIYUC3.js} +0 -1
  81. package/chunks/{chunk-7MVVZO4N.js → chunk-DGV27C34.js} +4 -4
  82. package/chunks/{chunk-BPZALHVR.js → chunk-DI35ZN7T.js} +1 -1
  83. package/chunks/chunk-DZLYR4U3.js +1252 -0
  84. package/chunks/{chunk-PHOF65IG.js → chunk-EYGWU66Z.js} +41594 -50416
  85. package/chunks/{chunk-7ZCNENPP.js → chunk-FANRZEAJ.js} +1 -1
  86. package/chunks/{chunk-WBL3FJEU.js → chunk-FC4KQFCS.js} +1 -1
  87. package/chunks/{chunk-5NBDS5S6.js → chunk-FCYYAB4S.js} +162 -7
  88. package/chunks/{chunk-L26JL52R.js → chunk-FH6SU2OG.js} +48 -61
  89. package/chunks/{chunk-OKY7HXPG.js → chunk-FNMZK765.js} +2 -2
  90. package/chunks/chunk-FYJ7W2PI.js +194 -0
  91. package/chunks/{chunk-BULDBTYC.js → chunk-G7XXKQYS.js} +3 -28
  92. package/chunks/{chunk-L5UHQJTJ.js → chunk-GATT5TKW.js} +1 -1
  93. package/chunks/{chunk-MVSUYZDT.js → chunk-GKWLJW7Z.js} +4 -4
  94. package/chunks/{chunk-VAK25FTU.js → chunk-GKX7E4CO.js} +1 -1
  95. package/chunks/{chunk-LS77BEZP.js → chunk-GLCZKT5V.js} +1 -5
  96. package/chunks/{chunk-FSITMZJH.js → chunk-GOXRFPH5.js} +18 -9
  97. package/chunks/{chunk-3RN6GBKS.js → chunk-HFAV3POZ.js} +1 -1
  98. package/chunks/{chunk-YX324OPW.js → chunk-HGQIL6NG.js} +1 -1
  99. package/chunks/{chunk-55DJUCI2.js → chunk-HOSENQJL.js} +53 -43
  100. package/chunks/{chunk-GZXCZHCT.js → chunk-I3G5JWBV.js} +1 -1
  101. package/chunks/{chunk-YH6G52F2.js → chunk-I3V7RKRZ.js} +4 -4
  102. package/chunks/{chunk-RF3EXIHJ.js → chunk-IQMYZTDI.js} +30 -19
  103. package/chunks/{chunk-RWTEFFPU.js → chunk-JCJ7LKNA.js} +6140 -5616
  104. package/chunks/{chunk-S3TWXGKA.js → chunk-JE7KQ2UP.js} +4 -2
  105. package/chunks/{chunk-63P4EL5V.js → chunk-JMONIXMJ.js} +1 -1
  106. package/chunks/{chunk-OFDOK3VM.js → chunk-JQTW5CA5.js} +8 -13
  107. package/chunks/chunk-JYBU6YUE.js +378 -0
  108. package/chunks/chunk-JZQUOT4B.js +81 -0
  109. package/chunks/{chunk-Q4M4MDQ4.js → chunk-K4GTOFKY.js} +1 -1
  110. package/chunks/{chunk-T2NCM2ET.js → chunk-K6KS3LTN.js} +2 -749
  111. package/chunks/{chunk-YPE6A4GC.js → chunk-KLESQCW6.js} +2 -2
  112. package/chunks/{chunk-JVPM2ULZ.js → chunk-KQGB3ME2.js} +6 -6
  113. package/chunks/{chunk-2W3OOD4W.js → chunk-L55JWS76.js} +6 -3
  114. package/chunks/{chunk-RHLZR4E5.js → chunk-LGAOC3ZS.js} +1 -1
  115. package/chunks/{chunk-LB6DUZ26.js → chunk-LI53FGDL.js} +258 -184
  116. package/chunks/{chunk-2X55UKQE.js → chunk-LIJID5PD.js} +3 -3
  117. package/chunks/{chunk-NH6KE4JX.js → chunk-LW3RFMG7.js} +3 -3
  118. package/chunks/{chunk-MZAXJAUM.js → chunk-LW67T6GH.js} +1 -1
  119. package/chunks/{chunk-RZIX2G32.js → chunk-M4O2DCE3.js} +1 -1
  120. package/chunks/{chunk-4WIZGAH3.js → chunk-MFW7APBA.js} +6 -58
  121. package/chunks/{chunk-VIA5XA4U.js → chunk-MKQOXP2O.js} +3 -1
  122. package/chunks/{chunk-FODK6UMO.js → chunk-MPHPFVKK.js} +0 -2
  123. package/chunks/{chunk-JESCGQM3.js → chunk-NAVJD2PQ.js} +8 -7
  124. package/chunks/{chunk-H5FFA6TH.js → chunk-NOKIVHOL.js} +16 -3
  125. package/chunks/{chunk-6OUGMXDC.js → chunk-NWNEANAT.js} +7 -7
  126. package/chunks/{chunk-LQIW3YFY.js → chunk-OAOPCTG6.js} +9 -7
  127. package/chunks/chunk-OCPBI7J5.js +18 -0
  128. package/chunks/{chunk-WCXCRJYB.js → chunk-OCUM7TJA.js} +1 -1
  129. package/chunks/{chunk-R5AFZNQW.js → chunk-OIG257JR.js} +14 -7
  130. package/chunks/{chunk-IKCX4CCL.js → chunk-OINT3ZNV.js} +118 -95
  131. package/chunks/{chunk-E5TUC6CA.js → chunk-OKF7JF3R.js} +3 -3
  132. package/chunks/chunk-PEK4ARMZ.js +319 -0
  133. package/chunks/chunk-PGHTM673.js +363 -0
  134. package/chunks/{record-artifact-RQKFYO5B.js → chunk-PMGFWLAZ.js} +22 -7
  135. package/chunks/{chunk-FNQ6T3CV.js → chunk-PONHVBRT.js} +10 -7
  136. package/chunks/{chunk-VDDGDZMA.js → chunk-QHWCP53L.js} +14 -7
  137. package/chunks/{chunk-ZFDTEDCF.js → chunk-RF4FA22B.js} +6 -6
  138. package/chunks/{chunk-6FGBXPWM.js → chunk-RPLGZJV2.js} +38 -44
  139. package/chunks/{chunk-NIBLUX3Y.js → chunk-RQLRERVY.js} +148 -21
  140. package/chunks/{chunk-LKEJ26GS.js → chunk-RWZPM2BP.js} +16 -11
  141. package/chunks/{chunk-6AM5D4ME.js → chunk-S6LOFUVP.js} +0 -12
  142. package/chunks/{chunk-IO3IX5Q4.js → chunk-S7G7Z3MP.js} +1 -1
  143. package/chunks/{chunk-MUP3T3AD.js → chunk-SGFT55XI.js} +1 -35
  144. package/chunks/{chunk-PWVFN2LF.js → chunk-SMWPUA2A.js} +1 -1
  145. package/chunks/{chunk-U7M2DMGW.js → chunk-SWRHIQDT.js} +130 -5
  146. package/chunks/{chunk-VYPFXUCB.js → chunk-SZ3KHTDR.js} +1 -1
  147. package/chunks/chunk-T26EAKDL.js +13 -0
  148. package/chunks/chunk-T3CHYWJZ.js +758 -0
  149. package/chunks/{chunk-SQCQ4KO2.js → chunk-TCBP4Q3K.js} +380 -317
  150. package/chunks/{chunk-ZNAUOR2I.js → chunk-TJHLQ45J.js} +2 -2
  151. package/chunks/{chunk-LK7CHLVP.js → chunk-U4VTUMMK.js} +0 -60
  152. package/chunks/{chunk-NL7LTRLR.js → chunk-UHUSJ6X7.js} +29 -68
  153. package/chunks/{chunk-LH2BYDQ5.js → chunk-UJBURGBH.js} +18 -12
  154. package/chunks/{chunk-ZOIFNCKL.js → chunk-UPUG4GXM.js} +3 -23
  155. package/chunks/{chunk-FQK6JAFG.js → chunk-URPQ5QZM.js} +4 -4
  156. package/chunks/{chunk-M4FMGVY4.js → chunk-V47JGII4.js} +3 -3
  157. package/chunks/{chunk-Y34KJKDC.js → chunk-VBX5IFEN.js} +1 -1
  158. package/chunks/{chunk-USTWD7QV.js → chunk-W4MIWP6M.js} +26 -16
  159. package/chunks/{chunk-HTR4WV6U.js → chunk-W4RQUHY3.js} +31 -1
  160. package/chunks/{chunk-J24WCGIN.js → chunk-W7D7QTCH.js} +4 -4
  161. package/chunks/{chunk-DLWL3Z7A.js → chunk-WBSMNTSV.js} +3 -3
  162. package/chunks/{chunk-2JZBVYTU.js → chunk-WZRWHXFE.js} +1 -8
  163. package/chunks/{chunk-COH43MRJ.js → chunk-XCGIMOLN.js} +27 -1
  164. package/chunks/{chunk-IJTOWOD7.js → chunk-XTLTBZIH.js} +83 -9
  165. package/chunks/{chunk-H4SBPHSA.js → chunk-XVYRMUI5.js} +3 -3
  166. package/chunks/{chunk-3QMGYBFN.js → chunk-XWWKIXVD.js} +1 -80
  167. package/chunks/{chunk-VULLI6WQ.js → chunk-XZB72HUB.js} +6 -6
  168. package/chunks/{chunk-3SJ43L4W.js → chunk-XZC5VLBZ.js} +2 -0
  169. package/chunks/{chunk-UUUTRMI2.js → chunk-Y4IHBGBP.js} +1 -1
  170. package/chunks/{chunk-PR75REBZ.js → chunk-Y6AXW2OG.js} +12 -82
  171. package/chunks/{chunk-IPUUTYMV.js → chunk-YDLJGZHL.js} +1 -1
  172. package/chunks/{chunk-MB4MZHMJ.js → chunk-YX4DHA6S.js} +211 -522
  173. package/chunks/chunk-Z4X5MTRT.js +133 -0
  174. package/chunks/{chunk-UW5EOVUN.js → chunk-ZBVS26BY.js} +4 -4
  175. package/chunks/{chunk-ZD6UTE4A.js → chunk-ZHBO7WVX.js} +1 -1
  176. package/chunks/{chunk-7JURR4JT.js → chunk-ZM63TFJH.js} +167 -81
  177. package/chunks/{chunk-HTO4JFDZ.js → chunk-ZPJWUGCS.js} +0 -1
  178. package/chunks/{chunk-X5XDDSSH.js → chunk-ZPZ7ZJEE.js} +28 -5
  179. package/chunks/{chunk-ACY3A37B.js → chunk-ZS6Q44DY.js} +23 -18
  180. package/chunks/{chunk-ZJHVAS7M.js → chunk-ZWUDSQBD.js} +4 -5
  181. package/chunks/{computer-use-SOQ4E3VX.js → computer-use-HRVGY7OB.js} +50 -49
  182. package/chunks/{config-utils-7V7GGIW6.js → config-utils-RUFMEUYD.js} +4 -3
  183. package/chunks/contextCommand-V3N7Q3UM.js +81 -0
  184. package/chunks/core-runtime-QGEW6WBW.js +135 -0
  185. package/chunks/{create-sub-session-IWW2IZ2T.js → create-sub-session-SBYUMSSS.js} +3 -3
  186. package/chunks/{create-sub-session-QRJLW5BV.js → create-sub-session-ZUWDNFO2.js} +47 -46
  187. package/chunks/{cron-create-YIID5XAW.js → cron-create-2QK6TCEC.js} +6 -6
  188. package/chunks/{cron-delete-ZVHYCEP2.js → cron-delete-FDCDFYMG.js} +5 -5
  189. package/chunks/{cron-list-XEGS463Q.js → cron-list-XN3WVBTP.js} +6 -6
  190. package/chunks/{daemon-YO6433NF.js → daemon-QH2G5B5E.js} +403 -17
  191. package/chunks/daemon-status-provider-MB54AMNV.js +91 -0
  192. package/chunks/daemon-trust-policy-3VFDF5LU.js +86 -0
  193. package/chunks/daemon-trust-policy-monitor-4KX2OK7G.js +173 -0
  194. package/chunks/{de-HGRCYDEJ.js → de-SY6O76BF.js} +6 -1
  195. package/chunks/deferred-core-runtime-UIJL6EEU.js +90 -0
  196. package/chunks/{dist-F6IBUDR4.js → dist-2PERFI23.js} +12 -9
  197. package/chunks/dist-AOOUOG5S.js +4389 -0
  198. package/chunks/{dist-46NQKLTW.js → dist-OAOC5OV4.js} +2 -2
  199. package/chunks/{dist-YFNEUWSE.js → dist-PVEAFLHY.js} +5 -4
  200. package/chunks/{dist-AIKFMUKK.js → dist-SL2LUMML.js} +1449 -14
  201. package/chunks/dist-ULIG4M5H.js +13415 -0
  202. package/chunks/{dist-WEAHOXDM.js → dist-WGMNT3JQ.js} +2 -1
  203. package/chunks/{dist-BBLXMS3N.js → dist-ZHXOBXDN.js} +3 -3
  204. package/chunks/earlyInputCapture-QBC4ZCV7.js +83 -0
  205. package/chunks/{edit-OBDSQURM.js → edit-7ABV72VV.js} +48 -47
  206. package/chunks/{en-MTWBNGDO.js → en-NBK3JKCE.js} +9 -1
  207. package/chunks/{enter-worktree-U6MRPQ2P.js → enter-worktree-4NOWT6I2.js} +48 -47
  208. package/chunks/{enterPlanMode-BC5QUZZ2.js → enterPlanMode-4NOQ6A56.js} +48 -47
  209. package/chunks/{environment-W5UFC2CH.js → environment-ABMFNOJO.js} +49 -48
  210. package/chunks/errors-UAX4AR5Q.js +89 -0
  211. package/chunks/esm-K5FARBNI.js +5548 -0
  212. package/chunks/{exit-worktree-DGNYMECB.js → exit-worktree-CF2O5AQM.js} +48 -47
  213. package/chunks/exitPlanMode-5KEF5DLM.js +74 -0
  214. package/chunks/{fast-path-JJZFJANL.js → fast-path-RWZGR7A6.js} +16 -6
  215. package/chunks/{fr-45RLL55O.js → fr-4KG5V7UT.js} +6 -1
  216. package/chunks/{gemini-QS36EBZV.js → gemini-A4LXWU5S.js} +103 -98
  217. package/chunks/{geminiContentGenerator-AG4KB6CV.js → geminiContentGenerator-VPXAS3BM.js} +40 -11
  218. package/chunks/{getMachineId-bsd-V7W3GODC.js → getMachineId-bsd-FG7IUY6U.js} +1 -1
  219. package/chunks/{getMachineId-darwin-TDO75DQP.js → getMachineId-darwin-GLCJI2RA.js} +1 -1
  220. package/chunks/{getMachineId-linux-TF43WQT2.js → getMachineId-linux-O6OPPAKO.js} +1 -1
  221. package/chunks/{getMachineId-unsupported-ZGUO3TXT.js → getMachineId-unsupported-S6CKYVGC.js} +1 -1
  222. package/chunks/{getMachineId-win-ECFYZZFQ.js → getMachineId-win-X5SRNEH7.js} +1 -1
  223. package/chunks/{glob-V7R3PSK3.js → glob-P6ZPQOPR.js} +48 -47
  224. package/chunks/goal-tools-H2NHZKGN.js +335 -0
  225. package/chunks/{grep-QYPSK7OP.js → grep-56M3IJ36.js} +50 -48
  226. package/chunks/handleAutoUpdate-N3IMC273.js +82 -0
  227. package/chunks/i18n-UFV5QINW.js +98 -0
  228. package/chunks/{image-gen-Z3VPGKRC.js → image-gen-GPYAKETO.js} +12 -12
  229. package/chunks/initializer-OXWZKLEX.js +87 -0
  230. package/chunks/installationInfo-V2YEC52N.js +81 -0
  231. package/chunks/{ja-B7DF7DFG.js → ja-F3GSQXMF.js} +6 -1
  232. package/chunks/{keychain-token-storage-MDTG3WRM.js → keychain-token-storage-72IYCAZV.js} +3 -3
  233. package/chunks/lib-RUF3WZA6.js +9 -0
  234. package/chunks/list-UN6EJ6WB.js +90 -0
  235. package/chunks/{list-agents-5KJJHR6I.js → list-agents-R6KDXQR3.js} +3 -3
  236. package/chunks/loadedSettingsAdapter-LZK2PMOY.js +84 -0
  237. package/chunks/{loggingContentGenerator-HS3S5H3Q.js → loggingContentGenerator-PSFMRX7M.js} +78 -113
  238. package/chunks/{loop-wakeup-FXKNNYSY.js → loop-wakeup-3IQKCYAH.js} +7 -7
  239. package/chunks/{ls-NTK6VOQJ.js → ls-DKZ37A7N.js} +5 -5
  240. package/chunks/{lsp-2JI24STP.js → lsp-QNWN7KN3.js} +3 -3
  241. package/chunks/{managed-npm-update-JYEMMXA3.js → managed-npm-update-D2AO3F47.js} +48 -47
  242. package/chunks/mcp-A2VAOKMH.js +84 -0
  243. package/chunks/{monitor-R3ODH5U6.js → monitor-7EJ3WBER.js} +48 -47
  244. package/chunks/nonInteractiveCli-43LIVN4A.js +146 -0
  245. package/chunks/{notebook-edit-BNOK452R.js → notebook-edit-IQD53ULF.js} +48 -47
  246. package/chunks/{openaiContentGenerator-WMCU3O2H.js → openaiContentGenerator-YPCMNGEZ.js} +26 -27
  247. package/chunks/pidfile-3SOOBWZA.js +87 -0
  248. package/chunks/process-registry-2CHQBXH5.js +157 -0
  249. package/chunks/{processUtils-RT7UNCC2.js → processUtils-FGVHFR4V.js} +2 -2
  250. package/chunks/{pt-22Q3FP73.js → pt-EQ33KWEN.js} +6 -1
  251. package/chunks/{qwenContentGenerator-HHCRK4SX.js → qwenContentGenerator-M6YW4D6A.js} +53 -52
  252. package/chunks/{qwenOAuth2-OWLB5AKH.js → qwenOAuth2-XSYKLMNR.js} +10 -10
  253. package/chunks/read-file-XOMBFIS7.js +29 -0
  254. package/chunks/{read-mcp-resource-4DKQWGHD.js → read-mcp-resource-GFTWYXMK.js} +4 -4
  255. package/chunks/record-artifact-JANPGVS4.js +21 -0
  256. package/chunks/resumeHistoryUtils-E4EVA4PO.js +92 -0
  257. package/chunks/ripGrep-M4NYA6AM.js +74 -0
  258. package/chunks/{ru-FZCNZHDC.js → ru-7OZAUKGG.js} +6 -1
  259. package/chunks/{run-qwen-serve-FU6HEM4J.js → run-qwen-serve-QLCU2BAZ.js} +953 -248
  260. package/chunks/{runtime-XXRRTNP6.js → runtime-T36WUYIO.js} +57 -55
  261. package/chunks/{scheduler-G2ZS2Z7E.js → scheduler-C3J45Z5W.js} +47 -46
  262. package/chunks/{sdk-exporters-grpc-AK3LGHNO.js → sdk-exporters-grpc-54L4LS5L.js} +4 -4
  263. package/chunks/{sdk-exporters-http-FYBSUCPD.js → sdk-exporters-http-BFOKQFRD.js} +7 -7
  264. package/chunks/{sdk-impl-GMVPB7NB.js → sdk-impl-6CJ3JQZL.js} +14 -14
  265. package/chunks/{send-message-Q6OOR6BR.js → send-message-RJ2R4PIV.js} +6 -12
  266. package/chunks/serve-7SWJTL3K.js +90 -0
  267. package/chunks/{server-4UMH7OIZ.js → server-T2B64F4O.js} +3887 -852
  268. package/chunks/{session-K3O3Q2SV.js → session-D546I4HT.js} +99 -94
  269. package/chunks/{settings-CR2EWTBA.js → settings-ZQOOTRR7.js} +51 -50
  270. package/chunks/shell-5OR4RAKF.js +84 -0
  271. package/chunks/{skill-I3SDA4MB.js → skill-X4E5JMKV.js} +20 -21
  272. package/chunks/skill-settings-ZS3XPDMT.js +92 -0
  273. package/chunks/spawnChannel-MILVKB3G.js +83 -0
  274. package/chunks/standalone-update-UTYCSPUO.js +93 -0
  275. package/chunks/{startInteractiveUI-SLZGHRPH.js → startInteractiveUI-S4R5J4EN.js} +1220 -895
  276. package/chunks/{syntheticOutput-I3757IWH.js → syntheticOutput-355CB6CJ.js} +4 -4
  277. package/chunks/{task-create-N7WQSGYA.js → task-create-KUQIS7RA.js} +10 -10
  278. package/chunks/{task-list-FOPULZEP.js → task-list-5XNNGTF4.js} +7 -7
  279. package/chunks/{task-stop-H6RHXFVQ.js → task-stop-4ROAOBXH.js} +3 -3
  280. package/chunks/{task-update-M57TFZJT.js → task-update-4FPFYGE3.js} +10 -10
  281. package/chunks/{team-create-YJALH5D2.js → team-create-MGD3Q7W4.js} +50 -49
  282. package/chunks/{team-delete-QE2UXJL7.js → team-delete-S2RCXA4P.js} +7 -7
  283. package/chunks/{team-plan-approval-34QFYKGN.js → team-plan-approval-VMVGLPDQ.js} +48 -47
  284. package/chunks/theme-manager-U4QE2YSY.js +78 -0
  285. package/chunks/{todoWrite-VQ7FKOHL.js → todoWrite-7WM3VDMY.js} +7 -7
  286. package/chunks/{tool-search-NF7GB6LE.js → tool-search-6T7VYTYZ.js} +19 -21
  287. package/chunks/total-session-admission-PLKO4EET.js +86 -0
  288. package/chunks/trustedFolders-QZU6BO46.js +96 -0
  289. package/chunks/{update-relaunch-WBUZJC5O.js → update-relaunch-NWPFNM5L.js} +5 -5
  290. package/chunks/updateCheck-KEOCGBZR.js +93 -0
  291. package/chunks/useAutoAcceptIndicator-O6XISZEA.js +94 -0
  292. package/chunks/{validateNonInterActiveAuth-3R223G3R.js → validateNonInterActiveAuth-WCHAHO75.js} +94 -89
  293. package/chunks/{version-HS7YSFHV.js → version-VP3VZ2BM.js} +1 -1
  294. package/chunks/{web-fetch-NKCSG7ZE.js → web-fetch-KM2FSOKS.js} +19 -21
  295. package/chunks/{web-search-S62WAP4S.js → web-search-WUR6PYBO.js} +13 -13
  296. package/chunks/{workflow-QAGU5RU4.js → workflow-S6XMX55R.js} +49 -48
  297. package/chunks/workspace-providers-status-JGIZRHVT.js +87 -0
  298. package/chunks/{workspace-registration-store-24JMHDGF.js → workspace-registration-store-JDEMOOFX.js} +1 -1
  299. package/chunks/workspace-registry-NIL6253M.js +94 -0
  300. package/chunks/workspace-service-UYB6MMWL.js +101 -0
  301. package/chunks/workspace-skills-status-GSJRWER4.js +87 -0
  302. package/chunks/workspace-trust-reconciler-V2TICK2A.js +347 -0
  303. package/chunks/write-file-QHD5ELJS.js +76 -0
  304. package/chunks/xterm-headless-NTYVIBT3.js +3475 -0
  305. package/chunks/{zh-LUIGBD55.js → zh-H3YDK5QW.js} +9 -1
  306. package/chunks/{zh-TW-F5KG2IYD.js → zh-TW-JYCP7XUA.js} +9 -1
  307. package/chunks/zoom-image-236QXDRH.js +224 -0
  308. package/cli.js +13 -13
  309. package/locales/ca.js +7 -2
  310. package/locales/de.js +7 -2
  311. package/locales/en.js +10 -2
  312. package/locales/fr.js +7 -2
  313. package/locales/ja.js +7 -2
  314. package/locales/pt.js +7 -2
  315. package/locales/ru.js +7 -2
  316. package/locales/zh-TW.js +10 -2
  317. package/locales/zh.js +10 -2
  318. package/package.json +5 -4
  319. package/web-shell/assets/{arc-DcbWnB9T.js → arc-DQN8gc5j.js} +1 -1
  320. package/web-shell/assets/{architectureDiagram-3BPJPVTR-kMMF5sud.js → architectureDiagram-3BPJPVTR-C6Z867cc.js} +1 -1
  321. package/web-shell/assets/{blockDiagram-GPEHLZMM-Htl9vTJS.js → blockDiagram-GPEHLZMM-BkyNf4_J.js} +1 -1
  322. package/web-shell/assets/{c4Diagram-AAUBKEIU-BnZnm0mQ.js → c4Diagram-AAUBKEIU-BA7aurej.js} +1 -1
  323. package/web-shell/assets/channel-YzToqAUt.js +1 -0
  324. package/web-shell/assets/{chunk-2J33WTMH-DziB7kDG.js → chunk-2J33WTMH-Dp_LERgD.js} +1 -1
  325. package/web-shell/assets/{chunk-4BX2VUAB-CmkD8daw.js → chunk-4BX2VUAB-CCwcnkeW.js} +1 -1
  326. package/web-shell/assets/{chunk-55IACEB6-CHAd9A_U.js → chunk-55IACEB6-e0ytWiup.js} +1 -1
  327. package/web-shell/assets/{chunk-727SXJPM-Dqaam3fE.js → chunk-727SXJPM-DBoZrQ--.js} +1 -1
  328. package/web-shell/assets/{chunk-AQP2D5EJ-D_-saBYM.js → chunk-AQP2D5EJ-dmHU5zKq.js} +1 -1
  329. package/web-shell/assets/{chunk-FMBD7UC4-B9r_veWD.js → chunk-FMBD7UC4-PP3UKzsN.js} +1 -1
  330. package/web-shell/assets/{chunk-ND2GUHAM-B3EaCSpL.js → chunk-ND2GUHAM-Bjy0PNsP.js} +1 -1
  331. package/web-shell/assets/{chunk-QZHKN3VN-CYq8x9mn.js → chunk-QZHKN3VN-CM0H6wrK.js} +1 -1
  332. package/web-shell/assets/classDiagram-4FO5ZUOK-_le9LVNU.js +1 -0
  333. package/web-shell/assets/classDiagram-v2-Q7XG4LA2-_le9LVNU.js +1 -0
  334. package/web-shell/assets/{cose-bilkent-S5V4N54A-D0ng4uiB.js → cose-bilkent-S5V4N54A-B1B_Fozz.js} +1 -1
  335. package/web-shell/assets/{dagre-BM42HDAG-DCZollQv.js → dagre-BM42HDAG-DGFk7aBN.js} +1 -1
  336. package/web-shell/assets/{diagram-2AECGRRQ-Dfk2pWS0.js → diagram-2AECGRRQ-VdlYGHdV.js} +1 -1
  337. package/web-shell/assets/{diagram-5GNKFQAL-kX38ltWR.js → diagram-5GNKFQAL-xcEMWz6m.js} +1 -1
  338. package/web-shell/assets/{diagram-KO2AKTUF-CJz2vsXh.js → diagram-KO2AKTUF-B6Dd23eT.js} +1 -1
  339. package/web-shell/assets/{diagram-LMA3HP47-BvMLZm_7.js → diagram-LMA3HP47-C3bjiNTc.js} +1 -1
  340. package/web-shell/assets/{diagram-OG6HWLK6-l7kfStkO.js → diagram-OG6HWLK6-ChXfX8H6.js} +1 -1
  341. package/web-shell/assets/{erDiagram-TEJ5UH35-BSVa8GGT.js → erDiagram-TEJ5UH35-D7RBC3FG.js} +1 -1
  342. package/web-shell/assets/{flowDiagram-I6XJVG4X-CoawKIXH.js → flowDiagram-I6XJVG4X-bNsx8Fqb.js} +1 -1
  343. package/web-shell/assets/{ganttDiagram-6RSMTGT7-DFUDH0zF.js → ganttDiagram-6RSMTGT7-C_m4liOj.js} +1 -1
  344. package/web-shell/assets/{gitGraphDiagram-PVQCEYII-Y2pvpT4e.js → gitGraphDiagram-PVQCEYII-CzAqOmDr.js} +1 -1
  345. package/web-shell/assets/{index-D0GX0zZf.js → index-BArKGy43.js} +1 -1
  346. package/web-shell/assets/index-C2GE3DAF.js +74 -0
  347. package/web-shell/assets/index-_dIfJ82-.js +1625 -0
  348. package/web-shell/assets/index-heP6zO4t.css +5 -0
  349. package/web-shell/assets/{infoDiagram-5YYISTIA-CU8_zLiX.js → infoDiagram-5YYISTIA-BBw9H4RT.js} +1 -1
  350. package/web-shell/assets/{ishikawaDiagram-YF4QCWOH-AVQiV0DU.js → ishikawaDiagram-YF4QCWOH-C8Ns7cDb.js} +1 -1
  351. package/web-shell/assets/{journeyDiagram-JHISSGLW-DQ0VSKa3.js → journeyDiagram-JHISSGLW-BkW5h5si.js} +1 -1
  352. package/web-shell/assets/{kanban-definition-UN3LZRKU-BqnWqsE_.js → kanban-definition-UN3LZRKU-IUhsF7tq.js} +1 -1
  353. package/web-shell/assets/{linear-BkoihsaA.js → linear-CeDsMMjT.js} +1 -1
  354. package/web-shell/assets/{mermaid.core-5RJs-31j.js → mermaid.core-VTPU82QL.js} +5 -5
  355. package/web-shell/assets/{mindmap-definition-RKZ34NQL-D33Bxnpd.js → mindmap-definition-RKZ34NQL-DVohXDmC.js} +1 -1
  356. package/web-shell/assets/{pieDiagram-4H26LBE5-BuEAw3BH.js → pieDiagram-4H26LBE5-SxBFaID8.js} +1 -1
  357. package/web-shell/assets/{quadrantDiagram-W4KKPZXB-Kox_usEq.js → quadrantDiagram-W4KKPZXB-BJt8o3Cs.js} +1 -1
  358. package/web-shell/assets/{requirementDiagram-4Y6WPE33-CNjeUif0.js → requirementDiagram-4Y6WPE33-B02G8M7E.js} +1 -1
  359. package/web-shell/assets/{sankeyDiagram-5OEKKPKP-BCd2OL_U.js → sankeyDiagram-5OEKKPKP-CzMCGPib.js} +1 -1
  360. package/web-shell/assets/{sequenceDiagram-3UESZ5HK-CF2ZTsz0.js → sequenceDiagram-3UESZ5HK-CzbJgSkE.js} +1 -1
  361. package/web-shell/assets/{stateDiagram-AJRCARHV-qenSzHtm.js → stateDiagram-AJRCARHV-DhiXBOKS.js} +1 -1
  362. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-DILbnhvR.js +1 -0
  363. package/web-shell/assets/{timeline-definition-PNZ67QCA-B5DyWdgs.js → timeline-definition-PNZ67QCA-Btj5idQV.js} +1 -1
  364. package/web-shell/assets/{vennDiagram-CIIHVFJN-DqP4I_o_.js → vennDiagram-CIIHVFJN-CJz2YZq4.js} +1 -1
  365. package/web-shell/assets/{wardley-L42UT6IY-CJe2e4mg.js → wardley-L42UT6IY-CavIou7m.js} +1 -1
  366. package/web-shell/assets/{wardleyDiagram-YWT4CUSO-BMDSw-Rr.js → wardleyDiagram-YWT4CUSO-BRf62x8X.js} +1 -1
  367. package/web-shell/assets/{xychartDiagram-2RQKCTM6-BTVZYkxD.js → xychartDiagram-2RQKCTM6-ItOGZPM_.js} +1 -1
  368. package/web-shell/index.html +2 -2
  369. package/chunks/MaxSizedBox-5DPPWPGT.js +0 -85
  370. package/chunks/agent-6ODUANDO.js +0 -81
  371. package/chunks/agent-headless-7BYQTMHW.js +0 -75
  372. package/chunks/bridge-ZUB64FAE.js +0 -90
  373. package/chunks/chunk-LEH5C7FV.js +0 -232
  374. package/chunks/chunk-SZRN75WQ.js +0 -29
  375. package/chunks/chunk-UGYMA4EI.js +0 -219
  376. package/chunks/chunk-Z2BC6UJ5.js +0 -8575
  377. package/chunks/contextCommand-JLHYA34Z.js +0 -80
  378. package/chunks/daemon-status-provider-2233Q37D.js +0 -89
  379. package/chunks/earlyInputCapture-A7NDU3PF.js +0 -82
  380. package/chunks/errors-M7CLORXH.js +0 -88
  381. package/chunks/exitPlanMode-GXTBWQAR.js +0 -403
  382. package/chunks/handleAutoUpdate-6DBEZYPV.js +0 -81
  383. package/chunks/i18n-VUJJZIMU.js +0 -97
  384. package/chunks/initializer-UWAK5U5O.js +0 -86
  385. package/chunks/installationInfo-6O2YAA52.js +0 -80
  386. package/chunks/list-GB4ESM3T.js +0 -89
  387. package/chunks/loadedSettingsAdapter-OT6JVQ7U.js +0 -83
  388. package/chunks/mcp-6DBDJPFU.js +0 -83
  389. package/chunks/nonInteractiveCli-MOYCYBBU.js +0 -141
  390. package/chunks/pidfile-TFRZZZIO.js +0 -86
  391. package/chunks/read-file-APMO3PSX.js +0 -31
  392. package/chunks/resumeHistoryUtils-6KRYEAWZ.js +0 -91
  393. package/chunks/ripGrep-BEJDEDXW.js +0 -73
  394. package/chunks/serve-7BSTXJ4T.js +0 -89
  395. package/chunks/shell-HH3PF3A2.js +0 -83
  396. package/chunks/spawnChannel-RWNDBXGA.js +0 -82
  397. package/chunks/src-GE4TTTML.js +0 -3147
  398. package/chunks/standalone-update-Q6WFRZZQ.js +0 -92
  399. package/chunks/theme-manager-SWRILQHI.js +0 -77
  400. package/chunks/total-session-admission-DLHHHLD3.js +0 -84
  401. package/chunks/trustedFolders-KHXHY6PY.js +0 -93
  402. package/chunks/updateCheck-RKL6M5XN.js +0 -92
  403. package/chunks/useAutoAcceptIndicator-CFQ5BUJL.js +0 -93
  404. package/chunks/workspace-providers-status-QSVZUETE.js +0 -86
  405. package/chunks/workspace-registry-UT4RBNBM.js +0 -88
  406. package/chunks/workspace-service-JFWRUS4V.js +0 -98
  407. package/chunks/workspace-skills-status-ZBBKJOI2.js +0 -85
  408. package/chunks/write-file-VHIXW5M7.js +0 -73
  409. package/web-shell/assets/channel-Cq7YKtfC.js +0 -1
  410. package/web-shell/assets/classDiagram-4FO5ZUOK-CQ9aC1Tg.js +0 -1
  411. package/web-shell/assets/classDiagram-v2-Q7XG4LA2-CQ9aC1Tg.js +0 -1
  412. package/web-shell/assets/index-D9haPt0X.css +0 -5
  413. package/web-shell/assets/index-ckX9Pq5k.js +0 -1230
  414. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-B7W4zlCr.js +0 -1
  415. package/chunks/{chunk-TARRHLLG.js → chunk-QUGAUQGJ.js} +25 -25
  416. package/chunks/{chunk-U7ZFW55U.js → chunk-VOQXFAY5.js} +977 -977
  417. /package/chunks/{chunk-LXXMOYPL.js → chunk-VXZBKKQR.js} +0 -0
@@ -12,48 +12,47 @@ import {
12
12
  matchMcpServerByRef,
13
13
  parseExtensionRef,
14
14
  parseMcpServerRef
15
- } from "./chunk-VULLI6WQ.js";
15
+ } from "./chunk-XZB72HUB.js";
16
16
  import {
17
17
  getAvailableCommands,
18
18
  handleSlashCommand,
19
19
  insertAfterFunctionResponses,
20
20
  isSlashCommand,
21
21
  normalizePartList
22
- } from "./chunk-LB6DUZ26.js";
22
+ } from "./chunk-LI53FGDL.js";
23
23
  import {
24
24
  collectContextData,
25
25
  formatContextUsageText
26
- } from "./chunk-R5AFZNQW.js";
26
+ } from "./chunk-OIG257JR.js";
27
27
  import {
28
28
  recomputeMcpGating
29
- } from "./chunk-OFDOK3VM.js";
29
+ } from "./chunk-JQTW5CA5.js";
30
30
  import {
31
31
  appEvents,
32
32
  buildDisabledSkillNamesProvider,
33
+ cleanupReviewWorktreeLeases,
33
34
  loadCliConfig,
34
35
  normalizeDisabledToolList
35
- } from "./chunk-TPRQ7RZH.js";
36
+ } from "./chunk-ANND7YTH.js";
36
37
  import {
37
38
  getCommandSubcommandNames
38
- } from "./chunk-RZIX2G32.js";
39
+ } from "./chunk-M4O2DCE3.js";
39
40
  import {
40
41
  getEffectiveSupportedModes
41
- } from "./chunk-U7M2DMGW.js";
42
- import "./chunk-J56UI34H.js";
42
+ } from "./chunk-SWRHIQDT.js";
43
43
  import "./chunk-4WGODMVR.js";
44
44
  import "./chunk-PQNHRFJC.js";
45
- import "./chunk-M4FMGVY4.js";
46
- import "./chunk-L5UHQJTJ.js";
47
- import "./chunk-GSN55ZRI.js";
48
- import "./chunk-6H67XLET.js";
45
+ import "./chunk-CI2PGI7Z.js";
46
+ import "./chunk-GATT5TKW.js";
49
47
  import {
50
48
  beginAcpBootstrapConfigProfiling,
51
49
  buildAndFreezeAcpStartupProfile,
52
50
  endAcpBootstrapConfigProfiling,
53
51
  markAcpStartup
54
- } from "./chunk-HIJQF5B5.js";
55
- import "./chunk-7MVVZO4N.js";
56
- import "./chunk-IKYJHJNF.js";
52
+ } from "./chunk-3L2SPEBH.js";
53
+ import "./chunk-DGV27C34.js";
54
+ import "./chunk-5EHIP3GX.js";
55
+ import "./chunk-V47JGII4.js";
57
56
  import "./chunk-YAF2MQZ6.js";
58
57
  import {
59
58
  GENERATION_MAX_PROMPT_BYTES,
@@ -74,7 +73,7 @@ import {
74
73
  shouldSuppressRememberErrorDetails,
75
74
  workspaceMemoryFailureCode,
76
75
  workspaceMemoryFailureDiagnostics
77
- } from "./chunk-RIBKPMRP.js";
76
+ } from "./chunk-7RFNMXPU.js";
78
77
  import {
79
78
  HistoryReplayer,
80
79
  MessageEmitter,
@@ -84,71 +83,57 @@ import {
84
83
  goalTerminalEventToHistoryItem,
85
84
  recordGoalStatusItem,
86
85
  restoreGoalFromHistory
87
- } from "./chunk-EBJQ6AXW.js";
88
- import "./chunk-RHLZR4E5.js";
89
- import "./chunk-IPUUTYMV.js";
90
- import "./chunk-WCXCRJYB.js";
86
+ } from "./chunk-4FQ4OKOU.js";
87
+ import "./chunk-LGAOC3ZS.js";
88
+ import "./chunk-YDLJGZHL.js";
89
+ import "./chunk-OCUM7TJA.js";
91
90
  import "./chunk-2MIN6GRR.js";
92
91
  import "./chunk-QHTIBUWB.js";
93
92
  import {
94
93
  isTerminalGoalStatusKind
95
94
  } from "./chunk-QTERJVPZ.js";
96
95
  import "./chunk-3Z43GZUQ.js";
96
+ import {
97
+ computeCpuPercent
98
+ } from "./chunk-HGT6JR3U.js";
99
+ import "./chunk-RXFQM6FQ.js";
100
+ import "./chunk-4D3MHM5F.js";
101
+ import "./chunk-6H67XLET.js";
102
+ import {
103
+ mapSkillConfigToStatus
104
+ } from "./chunk-L55JWS76.js";
97
105
  import {
98
106
  PERMISSION_RULE_TYPES,
99
107
  PermissionRulesValidationError,
100
108
  buildPermissionSettings,
101
109
  normalizePermissionRules,
102
110
  readPermissionRuleSet
103
- } from "./chunk-VRYUBFMC.js";
111
+ } from "./chunk-CYIBLZBR.js";
104
112
  import {
105
113
  MAX_AUDIO_BYTES,
106
114
  sanitizeVoiceErrorMessage,
107
115
  transcribeVoiceAudio
108
- } from "./chunk-H4SBPHSA.js";
116
+ } from "./chunk-XVYRMUI5.js";
109
117
  import {
110
118
  readVoiceModel
111
- } from "./chunk-YBL3QUDD.js";
112
- import "./chunk-ZD6UTE4A.js";
113
- import {
114
- computeCpuPercent
115
- } from "./chunk-HGT6JR3U.js";
116
- import "./chunk-RXFQM6FQ.js";
117
- import "./chunk-PSOO6YXD.js";
118
- import "./chunk-PC6JANNU.js";
119
- import "./chunk-57OAHC2Y.js";
119
+ } from "./chunk-CYPJYJIX.js";
120
+ import "./chunk-ZHBO7WVX.js";
120
121
  import {
121
122
  createLoadedSettingsAdapter
122
- } from "./chunk-IO3IX5Q4.js";
123
- import "./chunk-LXXMOYPL.js";
124
- import "./chunk-MVSUYZDT.js";
123
+ } from "./chunk-S7G7Z3MP.js";
124
+ import "./chunk-VXZBKKQR.js";
125
+ import "./chunk-GKWLJW7Z.js";
125
126
  import "./chunk-E5Z2AVNV.js";
126
127
  import {
128
+ SESSION_SOURCE_META_KEY,
127
129
  parseSessionSource
128
- } from "./chunk-KIM5GUMA.js";
130
+ } from "./chunk-B47WVQ7T.js";
129
131
  import "./chunk-GLWP3FDB.js";
130
- import {
131
- NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE,
132
- isNotCurrentlyGeneratingCancelError
133
- } from "./chunk-UH3WSE5L.js";
134
- import "./chunk-COH43MRJ.js";
135
- import {
136
- CHANNEL_STARTUP_PROFILE_META_KEY,
137
- CHANNEL_STARTUP_PROFILE_VERSION,
138
- CLIENT_MCP_OVER_WS_CONFIG_FLAG,
139
- DAEMON_CHANNEL_DELIVERY_META_KEY,
140
- LOAD_REPLAY_BULK_MODE,
141
- LOAD_REPLAY_META_KEY,
142
- LOAD_REPLAY_MODE_META_KEY,
143
- LOAD_REPLAY_PAGE_SIZE_META_KEY,
144
- LOAD_REPLAY_VERSION,
145
- MID_TURN_QUEUE_DRAIN_METHOD,
146
- PROMPT_CANCEL_METHOD,
147
- TODO_STOP_GUARD_QUEUE_RELEASE_METHOD
148
- } from "./chunk-3SJ43L4W.js";
132
+ import "./chunk-XCGIMOLN.js";
133
+ import "./chunk-OCPBI7J5.js";
149
134
  import {
150
135
  ndJsonStream
151
- } from "./chunk-7JURR4JT.js";
136
+ } from "./chunk-ZM63TFJH.js";
152
137
  import {
153
138
  ACP_ROUTE_ID_PREFIX,
154
139
  buildAcpModelOptions,
@@ -157,10 +142,7 @@ import {
157
142
  parseAcpModelOption,
158
143
  resolveAcpModelOption,
159
144
  sanitizeProviderBaseUrl
160
- } from "./chunk-KMQ33DO4.js";
161
- import {
162
- mapSkillConfigToStatus
163
- } from "./chunk-2W3OOD4W.js";
145
+ } from "./chunk-7UKQW4JU.js";
164
146
  import {
165
147
  ACP_PREFLIGHT_KINDS,
166
148
  IDLE_HOOK_EVENTS,
@@ -168,28 +150,55 @@ import {
168
150
  SERVE_STATUS_EXT_METHODS,
169
151
  STATUS_SCHEMA_VERSION,
170
152
  mapDomainErrorToErrorKind
171
- } from "./chunk-VIA5XA4U.js";
172
- import "./chunk-X5XDDSSH.js";
173
- import "./chunk-4WIZGAH3.js";
174
- import "./chunk-7ZCNENPP.js";
153
+ } from "./chunk-MKQOXP2O.js";
154
+ import {
155
+ resolveSkillSettings
156
+ } from "./chunk-Z4X5MTRT.js";
157
+ import "./chunk-3RMX26V7.js";
158
+ import "./chunk-4755HD5V.js";
159
+ import "./chunk-57OAHC2Y.js";
160
+ import "./chunk-MFW7APBA.js";
161
+ import "./chunk-FANRZEAJ.js";
162
+ import "./chunk-JZQUOT4B.js";
175
163
  import "./chunk-V6WHFGST.js";
176
164
  import {
177
- assembleMcpServers,
178
- loadMcpApprovals
179
- } from "./chunk-JVPM2ULZ.js";
180
- import "./chunk-ZNAUOR2I.js";
165
+ CHANNEL_STARTUP_PROFILE_META_KEY,
166
+ CHANNEL_STARTUP_PROFILE_VERSION,
167
+ CLIENT_MCP_OVER_WS_CONFIG_FLAG,
168
+ DAEMON_CHANNEL_DELIVERY_META_KEY,
169
+ LOAD_REPLAY_BULK_MODE,
170
+ LOAD_REPLAY_META_KEY,
171
+ LOAD_REPLAY_MODE_META_KEY,
172
+ LOAD_REPLAY_PAGE_SIZE_META_KEY,
173
+ LOAD_REPLAY_VERSION,
174
+ MID_TURN_QUEUE_DRAIN_METHOD,
175
+ PROMPT_CANCEL_METHOD,
176
+ TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,
177
+ TODO_STOP_GUARD_QUEUE_RELEASE_METHOD
178
+ } from "./chunk-XZC5VLBZ.js";
179
+ import {
180
+ NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE,
181
+ isNotCurrentlyGeneratingCancelError
182
+ } from "./chunk-B4AJNNOL.js";
181
183
  import "./chunk-2RFKHEXL.js";
182
- import "./chunk-LK7CHLVP.js";
183
- import "./chunk-JLU636DO.js";
184
+ import "./chunk-FYJ7W2PI.js";
185
+ import "./chunk-U4VTUMMK.js";
186
+ import "./chunk-6MPDY6ZG.js";
187
+ import "./chunk-ALMR3E6Q.js";
184
188
  import "./chunk-BK2UNYWD.js";
185
189
  import "./chunk-M5GB774H.js";
186
- import "./chunk-RWTEFFPU.js";
190
+ import "./chunk-4G2BISNC.js";
191
+ import "./chunk-ZPZ7ZJEE.js";
192
+ import "./chunk-JCJ7LKNA.js";
187
193
  import {
188
194
  AgentSideConnection,
189
195
  PROTOCOL_VERSION,
190
196
  RequestError
191
197
  } from "./chunk-UDXSXLER.js";
192
- import "./chunk-BIQWWWJN.js";
198
+ import {
199
+ assembleMcpServers,
200
+ loadMcpApprovals
201
+ } from "./chunk-KQGB3ME2.js";
193
202
  import {
194
203
  getOutputLanguageFilePath,
195
204
  getPersistScopeForModelSelection,
@@ -198,7 +207,7 @@ import {
198
207
  resolveOutputLanguageOrPreserveAuto,
199
208
  updateOutputLanguageFile,
200
209
  writeOutputLanguageAndRegisterPath
201
- } from "./chunk-TEHGS6UP.js";
210
+ } from "./chunk-7A4V5CJY.js";
202
211
  import "./chunk-RKUWKYED.js";
203
212
  import "./chunk-GOXKNSDZ.js";
204
213
  import {
@@ -209,27 +218,28 @@ import {
209
218
  SUPPORTED_LANGUAGES,
210
219
  getCurrentLanguage,
211
220
  setLanguageAsync
212
- } from "./chunk-LKEJ26GS.js";
221
+ } from "./chunk-RWZPM2BP.js";
213
222
  import {
214
223
  findEnvFiles,
215
224
  preResolveHomeEnvOverrides,
216
225
  reloadEnvironment
217
- } from "./chunk-LH2BYDQ5.js";
226
+ } from "./chunk-UJBURGBH.js";
218
227
  import "./chunk-6PEXNQTX.js";
219
- import "./chunk-YX324OPW.js";
220
- import "./chunk-VJNBRRZG.js";
228
+ import "./chunk-TJHLQ45J.js";
221
229
  import {
222
230
  isFolderTrustEnabled,
223
231
  isWorkspaceTrusted,
224
232
  loadTrustedFolders
225
- } from "./chunk-Z2BC6UJ5.js";
233
+ } from "./chunk-5IDU2UGL.js";
226
234
  import "./chunk-ALGGS7UH.js";
227
235
  import "./chunk-MR3PXB6E.js";
236
+ import "./chunk-XFSFZCM5.js";
237
+ import "./chunk-HGQIL6NG.js";
238
+ import "./chunk-VJNBRRZG.js";
228
239
  import {
229
240
  writeStderrLine,
230
241
  writeStderrLineSafe
231
242
  } from "./chunk-OWAK7LMW.js";
232
- import "./chunk-XFSFZCM5.js";
233
243
  import {
234
244
  ALL_PROVIDERS,
235
245
  APPROVAL_MODE_INFO,
@@ -269,6 +279,7 @@ import {
269
279
  applyAutoModeDecision,
270
280
  applyProviderInstallPlan,
271
281
  approxBase64Bytes,
282
+ bridgeToolResultImages,
272
283
  buildBackgroundEntryLabel,
273
284
  buildBtwCacheSafeParams,
274
285
  buildBtwPrompt,
@@ -329,6 +340,7 @@ import {
329
340
  normalizeEventPayload,
330
341
  normalizeSnapshotPayload,
331
342
  persistPermissionOutcome,
343
+ promptIdContext,
332
344
  readManyFiles,
333
345
  recordAllow,
334
346
  recordFallbackApprove,
@@ -352,68 +364,73 @@ import {
352
364
  updateSetting,
353
365
  validatePlanModeShellApproval,
354
366
  validatePlanModeShellContext
355
- } from "./chunk-PHOF65IG.js";
367
+ } from "./chunk-EYGWU66Z.js";
356
368
  import "./chunk-5M6IDOMF.js";
357
369
  import "./chunk-TWPJO254.js";
358
370
  import {
359
371
  external_exports
360
372
  } from "./chunk-H6XPXXMH.js";
361
- import "./chunk-K4XWPEWB.js";
362
- import "./chunk-TOFQCPDC.js";
363
- import "./chunk-IRH27ZC2.js";
364
- import "./chunk-VDDGDZMA.js";
365
- import "./chunk-FNQ6T3CV.js";
366
- import "./chunk-ZOIFNCKL.js";
367
- import "./chunk-PWTZEM3C.js";
373
+ import "./chunk-CVHIL5IG.js";
374
+ import "./chunk-UPUG4GXM.js";
375
+ import "./chunk-64LQLPL7.js";
376
+ import "./chunk-2LQTH543.js";
368
377
  import "./chunk-KRXPRVGL.js";
369
378
  import {
370
379
  parsePositiveIntegerEnv
371
380
  } from "./chunk-6PVPNMXU.js";
372
- import "./chunk-MZAXJAUM.js";
373
- import "./chunk-SZRN75WQ.js";
374
- import "./chunk-HTO4JFDZ.js";
381
+ import "./chunk-LW67T6GH.js";
382
+ import "./chunk-IRH27ZC2.js";
383
+ import "./chunk-QHWCP53L.js";
384
+ import "./chunk-PONHVBRT.js";
385
+ import "./chunk-PMGFWLAZ.js";
386
+ import "./chunk-T26EAKDL.js";
375
387
  import "./chunk-CPBF7KYF.js";
388
+ import "./chunk-6QIGFD5W.js";
389
+ import {
390
+ HookEventName,
391
+ createHookOutput
392
+ } from "./chunk-XWWKIXVD.js";
393
+ import "./chunk-75GFAX4R.js";
394
+ import "./chunk-OKF7JF3R.js";
395
+ import "./chunk-6FMJLI5M.js";
376
396
  import {
377
397
  APPROVAL_MODES,
378
398
  FORK_SUBAGENT_TYPE,
379
399
  getStartupContextLength,
380
400
  isSystemReminderContent,
381
401
  runWithRuntimeContentGenerator
382
- } from "./chunk-L26JL52R.js";
383
- import "./chunk-6AM5D4ME.js";
384
- import "./chunk-JZA3JUDJ.js";
385
- import {
386
- HookEventName,
387
- createHookOutput
388
- } from "./chunk-3QMGYBFN.js";
402
+ } from "./chunk-FH6SU2OG.js";
403
+ import "./chunk-S6LOFUVP.js";
389
404
  import "./chunk-JCW2R7WC.js";
390
- import "./chunk-M5JM7OSF.js";
391
- import "./chunk-OHNBB4XR.js";
392
- import "./chunk-E5TUC6CA.js";
405
+ import "./chunk-2DN4J57Y.js";
406
+ import "./chunk-ZPJWUGCS.js";
393
407
  import {
394
408
  clearCachedCredentialFile,
395
409
  qwenOAuth2Events
396
- } from "./chunk-EPDRMGT4.js";
397
- import "./chunk-JESCGQM3.js";
398
- import "./chunk-NH6KE4JX.js";
399
- import "./chunk-USTWD7QV.js";
400
- import "./chunk-XVNQMZ2I.js";
401
- import "./chunk-FODK6UMO.js";
410
+ } from "./chunk-2LKVPASC.js";
411
+ import "./chunk-NAVJD2PQ.js";
412
+ import "./chunk-LW3RFMG7.js";
413
+ import "./chunk-W4MIWP6M.js";
414
+ import "./chunk-DGEIYUC3.js";
415
+ import "./chunk-MPHPFVKK.js";
402
416
  import "./chunk-GLNBDYUX.js";
403
417
  import "./chunk-DJ2GSRLV.js";
404
- import "./chunk-ZJHVAS7M.js";
418
+ import "./chunk-ZWUDSQBD.js";
405
419
  import {
420
+ addToolArgumentsAttributes,
421
+ addToolCallResultAttributes,
406
422
  extractDaemonTraceContext,
407
423
  registerAcpEventLoopLagGauge,
408
424
  startEventLoopLagMonitor,
409
425
  withDaemonSpan
410
- } from "./chunk-NIBLUX3Y.js";
411
- import "./chunk-BPJSQIJX.js";
426
+ } from "./chunk-RQLRERVY.js";
427
+ import "./chunk-2J3OJGTL.js";
412
428
  import "./chunk-P3QQPMQA.js";
413
- import "./chunk-6FGBXPWM.js";
429
+ import "./chunk-RPLGZJV2.js";
414
430
  import {
415
431
  getToolCallPreparations
416
- } from "./chunk-LS77BEZP.js";
432
+ } from "./chunk-GLCZKT5V.js";
433
+ import "./chunk-DZLYR4U3.js";
417
434
  import {
418
435
  ConversationFinishedEvent,
419
436
  DiscoveredMCPTool,
@@ -427,6 +444,7 @@ import {
427
444
  formatVisionBridgeNotice,
428
445
  getAllGeminiMdFilenames,
429
446
  getFullTurnVisionModelSelector,
447
+ getInvocationContext,
430
448
  getMCPServerStatus,
431
449
  getSpecificMimeType,
432
450
  hasImageParts,
@@ -443,25 +461,30 @@ import {
443
461
  shouldRunVisionBridge,
444
462
  splitImageParts,
445
463
  uiTelemetryService
446
- } from "./chunk-CIKQ7KKO.js";
464
+ } from "./chunk-2Q4CZ3V6.js";
447
465
  import "./chunk-VGC4I5JJ.js";
448
466
  import {
449
467
  getAutoMemoryRoot,
450
468
  getUserAutoMemoryRoot
451
- } from "./chunk-MUP3T3AD.js";
469
+ } from "./chunk-SGFT55XI.js";
470
+ import "./chunk-Y4IHBGBP.js";
471
+ import {
472
+ ToolConfirmationOutcome,
473
+ ToolNames,
474
+ isShellProgressData
475
+ } from "./chunk-Y6AXW2OG.js";
452
476
  import {
453
- AuthType
454
- } from "./chunk-IKCX4CCL.js";
477
+ AuthType,
478
+ preloadContentGenerator
479
+ } from "./chunk-OINT3ZNV.js";
455
480
  import "./chunk-46UV252V.js";
456
- import "./chunk-A4UCTEB5.js";
457
- import "./chunk-XWRJCPHC.js";
458
481
  import {
459
482
  DEFAULT_TOKEN_LIMIT,
460
483
  tokenLimit
461
- } from "./chunk-UW5EOVUN.js";
462
- import "./chunk-2JZBVYTU.js";
463
- import "./chunk-5I2IWRSH.js";
464
- import "./chunk-A5L3JMUA.js";
484
+ } from "./chunk-ZBVS26BY.js";
485
+ import "./chunk-WZRWHXFE.js";
486
+ import "./chunk-A3NDJ5SB.js";
487
+ import "./chunk-7XATOOE7.js";
465
488
  import {
466
489
  endToolExecutionSpan,
467
490
  endToolSpan,
@@ -470,32 +493,26 @@ import {
470
493
  startToolExecutionSpan,
471
494
  startToolSpan,
472
495
  withInteractionSpan
473
- } from "./chunk-MB4MZHMJ.js";
474
- import "./chunk-HTR4WV6U.js";
475
- import "./chunk-BULDBTYC.js";
476
- import "./chunk-U7ZFW55U.js";
477
- import "./chunk-UUUTRMI2.js";
478
- import {
479
- ToolConfirmationOutcome,
480
- ToolNames,
481
- isShellProgressData
482
- } from "./chunk-PR75REBZ.js";
496
+ } from "./chunk-YX4DHA6S.js";
497
+ import "./chunk-W4RQUHY3.js";
498
+ import "./chunk-G7XXKQYS.js";
483
499
  import {
484
500
  Storage,
485
501
  createDebugLogger,
486
502
  getErrorMessage,
487
503
  getErrorStatus,
488
504
  isSubpath
489
- } from "./chunk-NL7LTRLR.js";
490
- import "./chunk-QAF7NMK7.js";
505
+ } from "./chunk-UHUSJ6X7.js";
506
+ import "./chunk-VOQXFAY5.js";
507
+ import "./chunk-7BV2P4S3.js";
491
508
  import {
492
509
  runExitCleanup
493
- } from "./chunk-PWVFN2LF.js";
510
+ } from "./chunk-SMWPUA2A.js";
494
511
  import "./chunk-75DOP5OR.js";
495
512
  import "./chunk-DMTGGOSA.js";
496
513
  import "./chunk-YQ3U5MUC.js";
497
514
  import "./chunk-AMDSOFFV.js";
498
- import "./chunk-TARRHLLG.js";
515
+ import "./chunk-QUGAUQGJ.js";
499
516
  import {
500
517
  init_esbuild_shims
501
518
  } from "./chunk-5O2XNYP6.js";
@@ -1949,6 +1966,7 @@ var DaemonTodoStopGuard = class {
1949
1966
  // packages/cli/src/acp-integration/session/Session.ts
1950
1967
  var debugLogger6 = createDebugLogger("SESSION");
1951
1968
  var USER_CANCEL_ABORT_REASON = "qwen:user-cancel";
1969
+ var SESSION_DISPOSE_ABORT_REASON = "qwen:session-dispose";
1952
1970
  var DAEMON_RETRY_META_KEY = "qwen.daemon.retry";
1953
1971
  var DAEMON_CONTINUE_META_KEY = "qwen.daemon.continueLastTurn";
1954
1972
  var TODO_STOP_GUARD_PROMPT_PREFIX = "[Todo Stop Guard] ";
@@ -2220,6 +2238,20 @@ function parseMidTurnDrainResponse(response) {
2220
2238
  ).map((message) => ({ kind: "text", message }));
2221
2239
  }
2222
2240
  __name(parseMidTurnDrainResponse, "parseMidTurnDrainResponse");
2241
+ function isValidMidTurnDrainResponse(response, requireQueuedPromptState) {
2242
+ if (!isRecord2(response) || requireQueuedPromptState && typeof response["hasQueuedPrompt"] !== "boolean") {
2243
+ return false;
2244
+ }
2245
+ if (Array.isArray(response["items"])) {
2246
+ return response["items"].every(
2247
+ (item) => isRecord2(item) && Array.isArray(item["content"]) && item["content"].length > 0 && item["content"].every(isContentBlock)
2248
+ );
2249
+ }
2250
+ return Array.isArray(response["messages"]) && response["messages"].every(
2251
+ (message) => typeof message === "string" && message.trim().length > 0
2252
+ );
2253
+ }
2254
+ __name(isValidMidTurnDrainResponse, "isValidMidTurnDrainResponse");
2223
2255
  var MidTurnDrainTimeoutError = class extends Error {
2224
2256
  static {
2225
2257
  __name(this, "MidTurnDrainTimeoutError");
@@ -2230,6 +2262,16 @@ var MidTurnDrainTimeoutError = class extends Error {
2230
2262
  );
2231
2263
  }
2232
2264
  };
2265
+ var TodoStopGuardClaimTimeoutError = class extends Error {
2266
+ static {
2267
+ __name(this, "TodoStopGuardClaimTimeoutError");
2268
+ }
2269
+ constructor() {
2270
+ super(
2271
+ `Todo Stop Guard continuation claim got no response within ${MID_TURN_QUEUE_DRAIN_TIMEOUT_MS}ms`
2272
+ );
2273
+ }
2274
+ };
2233
2275
  function beginChannelDeliveryResponseBlock(capture) {
2234
2276
  if (!capture) return void 0;
2235
2277
  capture.finalText = "";
@@ -2563,7 +2605,12 @@ var Session = class {
2563
2605
  midTurnRecoveredMessages = [];
2564
2606
  todoStopGuard;
2565
2607
  todoStopGuardBackgroundBaseline;
2608
+ relatedAgentIds = /* @__PURE__ */ new Set();
2609
+ provisionalRelatedAgentCounts = /* @__PURE__ */ new Map();
2566
2610
  todoStopGuardQueuedPromptPriority = false;
2611
+ todoStopGuardQueuedPromptOwnerPromptId;
2612
+ todoStopGuardClaimOwnerCounts = /* @__PURE__ */ new Map();
2613
+ todoStopGuardReleasedDuringClaim = /* @__PURE__ */ new Set();
2567
2614
  todoStopGuardDrainAutomaticQueuesWhenIdle = false;
2568
2615
  // Background notification drain state. ACP does not have the TUI's idle
2569
2616
  // hook, so the session serializes registry callbacks through this queue.
@@ -2615,7 +2662,7 @@ var Session = class {
2615
2662
  }
2616
2663
  const drainSupersededAutomaticQueues = this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuard.hasCommittedContinuation || this.todoStopGuardQueuedPromptPriority;
2617
2664
  if (this.config.getApprovalMode() === "plan" /* PLAN */) {
2618
- this.todoStopGuardQueuedPromptPriority = false;
2665
+ this.#clearTodoStopGuardQueuedPromptWait();
2619
2666
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2620
2667
  return {
2621
2668
  startsWorkChain: false,
@@ -2626,7 +2673,7 @@ var Session = class {
2626
2673
  const isRetry = params.retry === true || metadata?.[DAEMON_RETRY_META_KEY] === true;
2627
2674
  const isContinue = metadata?.[DAEMON_CONTINUE_META_KEY] === true;
2628
2675
  if (isRetry || isContinue) {
2629
- this.todoStopGuardQueuedPromptPriority = false;
2676
+ this.#clearTodoStopGuardQueuedPromptWait();
2630
2677
  if (this.todoStopGuard.hasTrustedUnfinishedState) {
2631
2678
  this.todoStopGuard.resumeTrustedPrompt();
2632
2679
  return {
@@ -2640,7 +2687,7 @@ var Session = class {
2640
2687
  drainSupersededAutomaticQueues
2641
2688
  };
2642
2689
  }
2643
- this.todoStopGuardQueuedPromptPriority = false;
2690
+ this.#clearTodoStopGuardQueuedPromptWait();
2644
2691
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2645
2692
  return {
2646
2693
  startsWorkChain: true,
@@ -2653,7 +2700,7 @@ var Session = class {
2653
2700
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2654
2701
  return;
2655
2702
  }
2656
- if (continuesCurrentWorkChain && this.todoStopGuard.isHardSuspended) {
2703
+ if (this.todoStopGuard.isHardSuspended) {
2657
2704
  return;
2658
2705
  }
2659
2706
  if (continuesCurrentWorkChain && this.todoStopGuard.hasTrustedUnfinishedState) {
@@ -2661,7 +2708,7 @@ var Session = class {
2661
2708
  return;
2662
2709
  }
2663
2710
  this.todoStopGuard.clearTrust();
2664
- this.todoStopGuardBackgroundBaseline = this.#captureTodoStopGuardBackgroundBaseline();
2711
+ this.#resetTodoStopGuardBackgroundLineage();
2665
2712
  }
2666
2713
  #clearTodoStopGuardTrustAndDrainAutomaticQueues() {
2667
2714
  const preserveQueuedPromptPriority = this.todoStopGuardQueuedPromptPriority;
@@ -2675,35 +2722,116 @@ var Session = class {
2675
2722
  void this.#drainCronQueue();
2676
2723
  void this.#drainNotificationQueue();
2677
2724
  }
2678
- releaseTodoStopGuardQueuedPromptWait() {
2679
- if (!this.todoStopGuardQueuedPromptPriority) return false;
2680
- this.todoStopGuardQueuedPromptPriority = false;
2725
+ releaseTodoStopGuardQueuedPromptWait(promptId) {
2726
+ const matchesCurrentWait = this.todoStopGuardQueuedPromptPriority && this.todoStopGuardQueuedPromptOwnerPromptId === promptId;
2727
+ if (!matchesCurrentWait) {
2728
+ if ((this.todoStopGuardClaimOwnerCounts.get(promptId) ?? 0) === 0) {
2729
+ return false;
2730
+ }
2731
+ this.todoStopGuardReleasedDuringClaim.add(promptId);
2732
+ if (!this.todoStopGuardQueuedPromptPriority) {
2733
+ this.#finishTodoStopGuardQueuedPromptRelease();
2734
+ }
2735
+ return true;
2736
+ }
2737
+ this.#clearTodoStopGuardQueuedPromptWait(promptId);
2738
+ this.#finishTodoStopGuardQueuedPromptRelease();
2739
+ return true;
2740
+ }
2741
+ #finishTodoStopGuardQueuedPromptRelease() {
2681
2742
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2682
2743
  if (this.pendingPrompt) {
2683
2744
  this.todoStopGuardDrainAutomaticQueuesWhenIdle = true;
2684
- return true;
2745
+ return;
2685
2746
  }
2686
2747
  void this.#drainCronQueue();
2687
2748
  void this.#drainNotificationQueue();
2688
- return true;
2689
2749
  }
2690
2750
  clearTodoStopGuardTrust() {
2691
2751
  this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
2692
2752
  }
2693
- #beginTodoStopGuardQueuedPromptCheck() {
2694
- this.todoStopGuardQueuedPromptPriority = this.todoStopGuard.awaitQueuedPrompt();
2753
+ hardSuspendTodoStopGuard() {
2754
+ this.#clearTodoStopGuardQueuedPromptWait();
2755
+ this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
2756
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2695
2757
  }
2696
- #finishTodoStopGuardQueuedPromptCheck(hasQueuedPrompt) {
2697
- const shouldWait = hasQueuedPrompt && this.todoStopGuardQueuedPromptPriority;
2698
- this.todoStopGuardQueuedPromptPriority = shouldWait;
2699
- if (!shouldWait) this.todoStopGuard.resumeTrustedPrompt();
2700
- return shouldWait;
2758
+ #clearTodoStopGuardQueuedPromptWait(expectedOwner) {
2759
+ if (expectedOwner !== void 0 && this.todoStopGuardQueuedPromptOwnerPromptId !== expectedOwner) {
2760
+ return;
2761
+ }
2762
+ this.todoStopGuardQueuedPromptPriority = false;
2763
+ this.todoStopGuardQueuedPromptOwnerPromptId = void 0;
2764
+ }
2765
+ #awaitTodoStopGuardQueuedPrompt(promptId) {
2766
+ this.todoStopGuard.awaitQueuedPrompt();
2767
+ this.todoStopGuardQueuedPromptPriority = true;
2768
+ this.todoStopGuardQueuedPromptOwnerPromptId = promptId;
2769
+ }
2770
+ async #claimTodoStopGuardContinuation(abortSignal) {
2771
+ const context = getInvocationContext();
2772
+ const ownerPromptId = context?.sessionId === this.sessionId ? context.promptId : void 0;
2773
+ if (ownerPromptId) {
2774
+ this.todoStopGuardClaimOwnerCounts.set(
2775
+ ownerPromptId,
2776
+ (this.todoStopGuardClaimOwnerCounts.get(ownerPromptId) ?? 0) + 1
2777
+ );
2778
+ }
2779
+ let timeoutHandle;
2780
+ try {
2781
+ const claimPromise = this.client.extMethod(
2782
+ TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,
2783
+ {
2784
+ sessionId: this.sessionId,
2785
+ ...ownerPromptId ? { promptId: ownerPromptId } : {}
2786
+ }
2787
+ );
2788
+ const timeoutPromise = new Promise((_, reject) => {
2789
+ timeoutHandle = setTimeout(
2790
+ () => reject(new TodoStopGuardClaimTimeoutError()),
2791
+ MID_TURN_QUEUE_DRAIN_TIMEOUT_MS
2792
+ );
2793
+ });
2794
+ const response = await Promise.race([claimPromise, timeoutPromise]);
2795
+ if (abortSignal.aborted || !isRecord2(response)) {
2796
+ return "unavailable";
2797
+ }
2798
+ if (ownerPromptId && response["claimed"] === false && response["hasQueuedPrompt"] === true) {
2799
+ if (this.closing || this.disposed) return "unavailable";
2800
+ if (this.todoStopGuardReleasedDuringClaim.has(ownerPromptId)) {
2801
+ return "unavailable";
2802
+ }
2803
+ this.#awaitTodoStopGuardQueuedPrompt(ownerPromptId);
2804
+ return "queued";
2805
+ }
2806
+ if (this.todoStopGuard.isHardSuspended) return "unavailable";
2807
+ if (response["claimed"] === true && response["hasQueuedPrompt"] === false) {
2808
+ if (ownerPromptId) {
2809
+ this.#clearTodoStopGuardQueuedPromptWait(ownerPromptId);
2810
+ }
2811
+ this.todoStopGuard.resumeTrustedPrompt();
2812
+ return "claimed";
2813
+ }
2814
+ return "unavailable";
2815
+ } catch (error) {
2816
+ debugLogger6.warn(
2817
+ `Todo Stop Guard continuation claim unavailable [session ${this.sessionId}]: ${this.#formatError(error)}`
2818
+ );
2819
+ return "unavailable";
2820
+ } finally {
2821
+ clearTimeout(timeoutHandle);
2822
+ if (ownerPromptId) {
2823
+ const remaining = (this.todoStopGuardClaimOwnerCounts.get(ownerPromptId) ?? 1) - 1;
2824
+ if (remaining > 0) {
2825
+ this.todoStopGuardClaimOwnerCounts.set(ownerPromptId, remaining);
2826
+ } else {
2827
+ this.todoStopGuardClaimOwnerCounts.delete(ownerPromptId);
2828
+ this.todoStopGuardReleasedDuringClaim.delete(ownerPromptId);
2829
+ }
2830
+ }
2831
+ }
2701
2832
  }
2702
2833
  #notificationContinuesTodoStopGuardWorkChain(item) {
2703
- const baseline = this.todoStopGuardBackgroundBaseline;
2704
- if (item.kind === "agent") return !baseline.agents.has(item.taskId);
2705
- if (item.kind === "shell") return !baseline.shells.has(item.taskId);
2706
- return !baseline.monitors.has(item.taskId);
2834
+ return item.continuesTodoStopGuardWorkChain;
2707
2835
  }
2708
2836
  #cronContinuesTodoStopGuardWorkChain(item) {
2709
2837
  return item.source === "loop" && item.taskId !== void 0 && !this.todoStopGuardBackgroundBaseline.wakeups.has(item.taskId);
@@ -2736,6 +2864,37 @@ var Session = class {
2736
2864
  ])
2737
2865
  };
2738
2866
  }
2867
+ #resetTodoStopGuardBackgroundLineage() {
2868
+ this.relatedAgentIds.clear();
2869
+ this.provisionalRelatedAgentCounts.clear();
2870
+ this.todoStopGuardBackgroundBaseline = this.#captureTodoStopGuardBackgroundBaseline();
2871
+ for (const item of this.notificationQueue) {
2872
+ item.continuesTodoStopGuardWorkChain = false;
2873
+ }
2874
+ }
2875
+ #agentContinuesTodoStopGuardWorkChain(taskId, visiting = /* @__PURE__ */ new Set()) {
2876
+ if (this.relatedAgentIds.has(taskId) || (this.provisionalRelatedAgentCounts.get(taskId) ?? 0) > 0) {
2877
+ return true;
2878
+ }
2879
+ if (this.todoStopGuardBackgroundBaseline.agents.has(taskId)) return false;
2880
+ if (visiting.has(taskId)) return false;
2881
+ const task = this.config.getBackgroundTaskRegistry?.()?.get?.(taskId);
2882
+ if (!task) return false;
2883
+ if (!task.parentAgentId) return true;
2884
+ visiting.add(taskId);
2885
+ const related = this.#agentContinuesTodoStopGuardWorkChain(
2886
+ task.parentAgentId,
2887
+ visiting
2888
+ );
2889
+ visiting.delete(taskId);
2890
+ return related;
2891
+ }
2892
+ #monitorContinuesTodoStopGuardWorkChain(monitorId, ownerAgentId) {
2893
+ if (ownerAgentId) {
2894
+ return this.#agentContinuesTodoStopGuardWorkChain(ownerAgentId);
2895
+ }
2896
+ return !this.todoStopGuardBackgroundBaseline.monitors.has(monitorId);
2897
+ }
2739
2898
  #hasRelevantTodoStopGuardBackgroundInput() {
2740
2899
  if (this.notificationQueue.some(
2741
2900
  (item) => this.#notificationContinuesTodoStopGuardWorkChain(item)
@@ -2747,7 +2906,7 @@ var Session = class {
2747
2906
  const baseline = this.todoStopGuardBackgroundBaseline;
2748
2907
  const agents = this.config.getBackgroundTaskRegistry?.()?.getAll?.() ?? [];
2749
2908
  if (agents.some(
2750
- (task) => !baseline.agents.has(task.id) && task.isBackgrounded && (task.status === "running" || task.status === "paused" || task.status === "cancelled" && !task.notified)
2909
+ (task) => this.#agentContinuesTodoStopGuardWorkChain(task.id) && task.isBackgrounded && (task.status === "running" || task.status === "paused" || task.status === "cancelled" && !task.notified)
2751
2910
  )) {
2752
2911
  return true;
2753
2912
  }
@@ -2759,7 +2918,10 @@ var Session = class {
2759
2918
  }
2760
2919
  const monitors = this.config.getMonitorRegistry?.()?.getAll?.() ?? [];
2761
2920
  if (monitors.some(
2762
- (task) => !baseline.monitors.has(task.id) && task.status === "running"
2921
+ (task) => this.#monitorContinuesTodoStopGuardWorkChain(
2922
+ task.id,
2923
+ task.ownerAgentId
2924
+ ) && task.status === "running"
2763
2925
  )) {
2764
2926
  return true;
2765
2927
  }
@@ -2890,12 +3052,19 @@ var Session = class {
2890
3052
  return this.closeGateCompletion ?? Promise.resolve();
2891
3053
  }
2892
3054
  async waitForActiveTurnsToSettle() {
2893
- const pending = [
2894
- this.pendingPromptCompletion,
2895
- this.cronCompletion,
2896
- this.notificationCompletion
2897
- ].filter((completion) => completion !== null);
2898
- await Promise.allSettled(pending);
3055
+ while (this.#hasActiveTurn()) {
3056
+ const pending = [
3057
+ this.pendingPromptCompletion,
3058
+ this.cronCompletion,
3059
+ this.notificationCompletion
3060
+ ].filter(
3061
+ (completion) => completion !== null
3062
+ );
3063
+ if (pending.length > 0) {
3064
+ await Promise.allSettled(pending);
3065
+ }
3066
+ await new Promise((resolve5) => setImmediate(resolve5));
3067
+ }
2899
3068
  }
2900
3069
  #deferAutomaticQueueDrainUntilTurnsSettle() {
2901
3070
  const completions = [
@@ -2924,12 +3093,12 @@ var Session = class {
2924
3093
  dispose() {
2925
3094
  this.disposed = true;
2926
3095
  this.closing = true;
3096
+ this.pendingPrompt?.abort(SESSION_DISPOSE_ABORT_REASON);
3097
+ this.pendingPrompt = null;
2927
3098
  this.resolveCloseGate?.();
2928
3099
  this.resolveCloseGate = null;
2929
3100
  this.closeGateCompletion = null;
2930
- this.todoStopGuardQueuedPromptPriority = false;
2931
- this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
2932
- this.todoStopGuard.clearTrust();
3101
+ this.hardSuspendTodoStopGuard();
2933
3102
  this.notificationQueue = [];
2934
3103
  this.cronQueue = [];
2935
3104
  this.notificationAbortController?.abort();
@@ -3170,6 +3339,9 @@ var Session = class {
3170
3339
  throw RequestError.invalidParams(void 0, "Session is closing");
3171
3340
  }
3172
3341
  await this.assertCanStartTurn();
3342
+ if (this.closing) {
3343
+ throw RequestError.invalidParams(void 0, "Session is closing");
3344
+ }
3173
3345
  if (admissionCancellation?.aborted) {
3174
3346
  return { stopReason: "cancelled" };
3175
3347
  }
@@ -3231,9 +3403,9 @@ var Session = class {
3231
3403
  return { stopReason: "cancelled" };
3232
3404
  }
3233
3405
  if (todoStopGuardPreparation.startsWorkChain) {
3234
- this.todoStopGuardQueuedPromptPriority = false;
3406
+ this.#clearTodoStopGuardQueuedPromptWait();
3235
3407
  this.todoStopGuard.startOrdinaryPrompt();
3236
- this.todoStopGuardBackgroundBaseline = this.#captureTodoStopGuardBackgroundBaseline();
3408
+ this.#resetTodoStopGuardBackgroundLineage();
3237
3409
  }
3238
3410
  this.duplicateProviderToolCallResponseIds.clear();
3239
3411
  const channelDelivery = parsePromptChannelDelivery(params);
@@ -3274,9 +3446,12 @@ var Session = class {
3274
3446
  }
3275
3447
  throw error;
3276
3448
  } finally {
3449
+ const stillOwnsPendingPrompt = this.pendingPrompt === pendingSend;
3277
3450
  releasePendingSend();
3278
3451
  const shouldDrainAutomaticQueues = todoStopGuardPreparation.drainSupersededAutomaticQueues || this.todoStopGuardDrainAutomaticQueuesWhenIdle || this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuard.hasCommittedContinuation || this.todoStopGuardQueuedPromptPriority;
3279
- this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
3452
+ if (stillOwnsPendingPrompt) {
3453
+ this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
3454
+ }
3280
3455
  if (shouldDrainAutomaticQueues) {
3281
3456
  void this.#drainCronQueue();
3282
3457
  void this.#drainNotificationQueue();
@@ -3431,6 +3606,7 @@ var Session = class {
3431
3606
  }
3432
3607
  this.turn += 1;
3433
3608
  const promptId = this.config.getSessionId() + "########" + this.turn;
3609
+ promptIdContext.enterWith(promptId);
3434
3610
  const parentContext = extractDaemonTraceContext(params);
3435
3611
  return await withInteractionSpan(
3436
3612
  this.config,
@@ -3496,6 +3672,9 @@ var Session = class {
3496
3672
  let parts;
3497
3673
  let fullTurnModelOverride;
3498
3674
  const onFullTurnModel = /* @__PURE__ */ __name((model) => {
3675
+ if (fullTurnModelOverride === model) {
3676
+ return true;
3677
+ }
3499
3678
  if (fullTurnModelOverride) {
3500
3679
  return false;
3501
3680
  }
@@ -3704,7 +3883,8 @@ ${this.pendingRecoveredAgentsNotice}
3704
3883
  }
3705
3884
  strippedOrphanEntries = null;
3706
3885
  }
3707
- if (pendingSend.signal.aborted && pendingSend.signal.reason === USER_CANCEL_ABORT_REASON && this.#isAbortError(error)) {
3886
+ const isControlledCancellation = pendingSend.signal.aborted && (pendingSend.signal.reason === USER_CANCEL_ABORT_REASON || pendingSend.signal.reason === SESSION_DISPOSE_ABORT_REASON);
3887
+ if (isControlledCancellation) {
3708
3888
  this.todoStopGuard.suspend();
3709
3889
  return { stopReason: "cancelled" };
3710
3890
  }
@@ -3756,7 +3936,8 @@ ${this.pendingRecoveredAgentsNotice}
3756
3936
  pendingSend.signal,
3757
3937
  promptId,
3758
3938
  functionCalls,
3759
- toolLoopState
3939
+ toolLoopState,
3940
+ onFullTurnModel
3760
3941
  )
3761
3942
  );
3762
3943
  if (toolRun.stopAfterPermissionCancel) {
@@ -3811,6 +3992,11 @@ ${this.pendingRecoveredAgentsNotice}
3811
3992
  turnCount
3812
3993
  )
3813
3994
  );
3995
+ cleanupReviewWorktreeLeases({
3996
+ sessionId: this.config.getSessionId(),
3997
+ promptId,
3998
+ repositoryRoot: this.config.getProjectRoot()
3999
+ });
3814
4000
  }
3815
4001
  },
3816
4002
  (result) => result.stopReason === "cancelled" ? "cancelled" : "ok"
@@ -3823,6 +4009,9 @@ ${this.pendingRecoveredAgentsNotice}
3823
4009
  let stopHookIterationCount = 0;
3824
4010
  let stopHookReasons = [];
3825
4011
  const onFullTurnModel = /* @__PURE__ */ __name((model) => {
4012
+ if (modelOverride === model) {
4013
+ return true;
4014
+ }
3826
4015
  if (modelOverride) {
3827
4016
  return false;
3828
4017
  }
@@ -3831,6 +4020,9 @@ ${this.pendingRecoveredAgentsNotice}
3831
4020
  }, "onFullTurnModel");
3832
4021
  let midTurnContinuationCount = 0;
3833
4022
  while (true) {
4023
+ if (this.pendingPrompt && this.pendingPrompt !== pendingSend) {
4024
+ return { stopReason: "cancelled" };
4025
+ }
3834
4026
  if (pendingSend.signal.aborted) {
3835
4027
  this.todoStopGuard.suspend();
3836
4028
  return { stopReason: "cancelled" };
@@ -3842,15 +4034,26 @@ ${this.pendingRecoveredAgentsNotice}
3842
4034
  return { stopReason: "end_turn" };
3843
4035
  }
3844
4036
  if (this.todoStopGuard.needsStopInspection) {
3845
- this.#beginTodoStopGuardQueuedPromptCheck();
3846
4037
  const drained = await this.#drainMidTurnInput(pendingSend.signal, {
3847
4038
  watchQueuedPromptForTodoStopGuard: true,
3848
4039
  onFullTurnModel
3849
4040
  });
3850
- const waitsForQueuedPrompt = this.#finishTodoStopGuardQueuedPromptCheck(
3851
- drained.hasQueuedPrompt
3852
- );
3853
4041
  if (drained.parts.length > 0) {
4042
+ if (drained.hasQueuedPrompt) {
4043
+ const claim = await this.#claimTodoStopGuardContinuation(
4044
+ pendingSend.signal
4045
+ );
4046
+ if (claim === "queued") {
4047
+ this.#preserveUnsentMessageHistory(
4048
+ { role: "user", parts: drained.parts },
4049
+ true
4050
+ );
4051
+ return { stopReason: "end_turn" };
4052
+ }
4053
+ if (claim === "unavailable") {
4054
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4055
+ }
4056
+ }
3854
4057
  this.todoStopGuard.acceptMidTurnUserInput();
3855
4058
  const continuation2 = await this.#runStopContinuation(
3856
4059
  pendingSend,
@@ -3869,13 +4072,22 @@ ${this.pendingRecoveredAgentsNotice}
3869
4072
  }
3870
4073
  continue;
3871
4074
  }
3872
- if (waitsForQueuedPrompt) {
3873
- return { stopReason: "end_turn" };
4075
+ if (!drained.reliable) {
4076
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4077
+ } else if (drained.hasQueuedPrompt) {
4078
+ const claim = await this.#claimTodoStopGuardContinuation(
4079
+ pendingSend.signal
4080
+ );
4081
+ if (claim === "queued") {
4082
+ return { stopReason: "end_turn" };
4083
+ }
4084
+ if (claim === "unavailable") {
4085
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4086
+ }
3874
4087
  }
3875
4088
  }
3876
4089
  let externalReason = null;
3877
4090
  let stopHookCount = 1;
3878
- let queuedPromptArrivedDuringStopHook = false;
3879
4091
  if (allowExternalHooks && hooksEnabled && messageBus && stopHookIterationCount < stopHookBlockingCap && this.config.hasHooksForEvent?.("Stop")) {
3880
4092
  const responseText = this.#getCurrentChat().getLastModelMessageText?.() || "[no response text]";
3881
4093
  const contextUsage = buildContextUsage(
@@ -3906,14 +4118,26 @@ ${this.pendingRecoveredAgentsNotice}
3906
4118
  return { stopReason: "cancelled" };
3907
4119
  }
3908
4120
  if (this.todoStopGuard.needsStopInspection) {
3909
- this.#beginTodoStopGuardQueuedPromptCheck();
3910
4121
  const drained = await this.#drainMidTurnInput(pendingSend.signal, {
3911
4122
  watchQueuedPromptForTodoStopGuard: true,
3912
4123
  onFullTurnModel
3913
4124
  });
3914
- const waitsForQueuedPrompt = this.#finishTodoStopGuardQueuedPromptCheck(drained.hasQueuedPrompt);
3915
- queuedPromptArrivedDuringStopHook = waitsForQueuedPrompt;
3916
4125
  if (drained.parts.length > 0) {
4126
+ if (drained.hasQueuedPrompt) {
4127
+ const claim = await this.#claimTodoStopGuardContinuation(
4128
+ pendingSend.signal
4129
+ );
4130
+ if (claim === "queued") {
4131
+ this.#preserveUnsentMessageHistory(
4132
+ { role: "user", parts: drained.parts },
4133
+ true
4134
+ );
4135
+ return { stopReason: "end_turn" };
4136
+ }
4137
+ if (claim === "unavailable") {
4138
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4139
+ }
4140
+ }
3917
4141
  this.todoStopGuard.acceptMidTurnUserInput();
3918
4142
  const continuation2 = await this.#runStopContinuation(
3919
4143
  pendingSend,
@@ -3930,6 +4154,20 @@ ${this.pendingRecoveredAgentsNotice}
3930
4154
  if (continuation2.kind === "terminal") {
3931
4155
  return { stopReason: continuation2.stopReason };
3932
4156
  }
4157
+ continue;
4158
+ }
4159
+ if (!drained.reliable) {
4160
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4161
+ } else if (drained.hasQueuedPrompt) {
4162
+ const claim = await this.#claimTodoStopGuardContinuation(
4163
+ pendingSend.signal
4164
+ );
4165
+ if (claim === "queued") {
4166
+ return { stopReason: "end_turn" };
4167
+ }
4168
+ if (claim === "unavailable") {
4169
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4170
+ }
3933
4171
  }
3934
4172
  }
3935
4173
  const hookOutput = response.output ? createHookOutput("Stop", response.output) : void 0;
@@ -3942,9 +4180,13 @@ ${this.pendingRecoveredAgentsNotice}
3942
4180
  stopHookIterationCount++;
3943
4181
  stopHookReasons = [...stopHookReasons, externalReason];
3944
4182
  stopHookCount = response.stopHookCount ?? 1;
4183
+ } else {
4184
+ stopHookIterationCount = 0;
4185
+ stopHookReasons = [];
4186
+ stopHookCount = 1;
3945
4187
  }
3946
4188
  }
3947
- const guardDecision = queuedPromptArrivedDuringStopHook ? null : this.todoStopGuard.decide(
4189
+ const guardDecision = this.todoStopGuard.decide(
3948
4190
  this.todoStopGuard.needsStopInspection ? this.#hasRelevantTodoStopGuardBackgroundInput() : false
3949
4191
  );
3950
4192
  const guardContinuation = guardDecision?.kind === "continue" ? guardDecision : null;
@@ -3967,9 +4209,6 @@ ${this.pendingRecoveredAgentsNotice}
3967
4209
  debugLogger6.warn(warning);
3968
4210
  return { stopReason: "end_turn" };
3969
4211
  }
3970
- if (queuedPromptArrivedDuringStopHook) {
3971
- return { stopReason: "end_turn" };
3972
- }
3973
4212
  if (!externalReason && !guardContinuation) {
3974
4213
  return { stopReason: "end_turn" };
3975
4214
  }
@@ -4025,8 +4264,27 @@ ${this.pendingRecoveredAgentsNotice}
4025
4264
  let initialSend = true;
4026
4265
  let automaticContinuationValidated = false;
4027
4266
  let supersededAutomaticContinuation = false;
4267
+ const preservePendingMessage = /* @__PURE__ */ __name((message) => {
4268
+ if (initialSend) return;
4269
+ const preservedParts = (message.parts ?? []).filter(
4270
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4271
+ );
4272
+ this.#preserveUnsentMessageHistory(
4273
+ preservedParts.length > 0 ? { ...message, parts: preservedParts } : null,
4274
+ true
4275
+ );
4276
+ }, "preservePendingMessage");
4028
4277
  while (nextMessage !== null) {
4278
+ if (this.pendingPrompt && this.pendingPrompt !== pendingSend) {
4279
+ preservePendingMessage(nextMessage);
4280
+ return {
4281
+ kind: "terminal",
4282
+ stopReason: "cancelled",
4283
+ ...supersededAutomaticContinuation ? { supersededAutomaticContinuation: true } : {}
4284
+ };
4285
+ }
4029
4286
  if (pendingSend.signal.aborted) {
4287
+ preservePendingMessage(nextMessage);
4030
4288
  this.todoStopGuard.suspend();
4031
4289
  return {
4032
4290
  kind: "terminal",
@@ -4044,12 +4302,18 @@ ${this.pendingRecoveredAgentsNotice}
4044
4302
  let guardForThisSend = nextGuardContinuation;
4045
4303
  let preserveGuardOnSkippedSend = false;
4046
4304
  let messageForPreservation = nextMessage;
4305
+ let preparedMessage = nextMessage.parts ?? [];
4306
+ let preservePreparedMessageOnSkippedSend = !guardForThisSend && preparedMessage.some(
4307
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4308
+ );
4047
4309
  const externalParts = initialSend ? options.externalParts : void 0;
4048
4310
  const promptIdForSend = guardForThisSend && guardForThisSend.attempt !== options.guardContinuation?.attempt ? toolPromptId + "_todo_stop_guard_" + guardForThisSend.attempt : streamPromptId;
4049
4311
  const messageDisplay = this.#createMessageDisplayDispatcher(
4050
4312
  pendingSend.signal
4051
4313
  );
4052
4314
  let channelDeliveryResponseBlock;
4315
+ let providerSendChat;
4316
+ let userContentPushCountBeforeSend = 0;
4053
4317
  try {
4054
4318
  const sendResult = await this.#sendMessageStreamWithAutoCompression(
4055
4319
  promptIdForSend,
@@ -4058,44 +4322,134 @@ ${this.pendingRecoveredAgentsNotice}
4058
4322
  {
4059
4323
  skipCompression: skipCompression || (guardForThisSend?.attempt ?? 0) > 1,
4060
4324
  getModelOverride: options.getModelOverride,
4061
- beforeSend: guardForThisSend || !automaticContinuationValidated && options.onAutomaticContinuationValidated ? async ({ compressionFailed }) => {
4062
- const inspectGuardPriority = guardForThisSend !== void 0;
4063
- const guardCompressionFailed = inspectGuardPriority && compressionFailed;
4064
- if (inspectGuardPriority) {
4065
- this.#beginTodoStopGuardQueuedPromptCheck();
4066
- const drained = await this.#drainMidTurnInput(
4067
- pendingSend.signal,
4068
- {
4069
- watchQueuedPromptForTodoStopGuard: true,
4070
- onFullTurnModel: options.onFullTurnModel
4325
+ prepareBeforeCompression: guardForThisSend ? async () => {
4326
+ const drained = await this.#drainMidTurnInput(
4327
+ pendingSend.signal,
4328
+ {
4329
+ watchQueuedPromptForTodoStopGuard: true,
4330
+ onFullTurnModel: options.onFullTurnModel
4331
+ }
4332
+ );
4333
+ if (drained.parts.length > 0) {
4334
+ if (drained.hasQueuedPrompt) {
4335
+ const claim = await this.#claimTodoStopGuardContinuation(
4336
+ pendingSend.signal
4337
+ );
4338
+ if (claim === "queued") {
4339
+ guardForThisSend = void 0;
4340
+ nextGuardContinuation = void 0;
4341
+ preserveGuardOnSkippedSend = true;
4342
+ preservePreparedMessageOnSkippedSend = true;
4343
+ messageForPreservation = {
4344
+ role: "user",
4345
+ parts: drained.parts
4346
+ };
4347
+ if (initialSend) {
4348
+ supersededAutomaticContinuation = true;
4349
+ }
4350
+ return { kind: "stop", stopReason: "end_turn" };
4071
4351
  }
4352
+ if (claim === "unavailable") {
4353
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4354
+ }
4355
+ }
4356
+ preservePreparedMessageOnSkippedSend = true;
4357
+ this.todoStopGuard.acceptMidTurnUserInput();
4358
+ guardForThisSend = void 0;
4359
+ nextGuardContinuation = void 0;
4360
+ if (initialSend) {
4361
+ supersededAutomaticContinuation = true;
4362
+ }
4363
+ preparedMessage = initialSend ? drained.parts : [
4364
+ ...(nextMessage?.parts ?? []).filter(
4365
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4366
+ ),
4367
+ ...drained.parts
4368
+ ];
4369
+ messageForPreservation = {
4370
+ role: "user",
4371
+ parts: preparedMessage
4372
+ };
4373
+ return { kind: "send", message: preparedMessage };
4374
+ }
4375
+ if (!drained.reliable) {
4376
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4377
+ guardForThisSend = void 0;
4378
+ nextGuardContinuation = void 0;
4379
+ if (!options.externalParts) {
4380
+ preserveGuardOnSkippedSend = true;
4381
+ return { kind: "stop", stopReason: "end_turn" };
4382
+ }
4383
+ if (!initialSend && nextMessage) {
4384
+ nextMessage = {
4385
+ ...nextMessage,
4386
+ parts: (nextMessage.parts ?? []).filter(
4387
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4388
+ )
4389
+ };
4390
+ }
4391
+ } else if (drained.hasQueuedPrompt) {
4392
+ const probe = await this.#claimTodoStopGuardContinuation(
4393
+ pendingSend.signal
4072
4394
  );
4073
- const waitsForQueuedPrompt = this.#finishTodoStopGuardQueuedPromptCheck(
4074
- drained.hasQueuedPrompt
4075
- );
4076
- if (drained.parts.length > 0) {
4077
- this.todoStopGuard.acceptMidTurnUserInput();
4395
+ if (probe === "queued") {
4078
4396
  guardForThisSend = void 0;
4079
4397
  nextGuardContinuation = void 0;
4398
+ preserveGuardOnSkippedSend = true;
4080
4399
  if (initialSend) {
4081
4400
  supersededAutomaticContinuation = true;
4082
4401
  }
4083
- const replacementMessage = initialSend ? drained.parts : [
4084
- ...(nextMessage?.parts ?? []).filter(
4085
- (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4086
- ),
4087
- ...drained.parts
4088
- ];
4089
- messageForPreservation = {
4090
- role: "user",
4091
- parts: replacementMessage
4092
- };
4093
- return {
4094
- kind: "send",
4095
- message: replacementMessage
4096
- };
4402
+ return { kind: "stop", stopReason: "end_turn" };
4403
+ }
4404
+ if (probe === "unavailable") {
4405
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4406
+ guardForThisSend = void 0;
4407
+ nextGuardContinuation = void 0;
4408
+ if (!options.externalParts) {
4409
+ preserveGuardOnSkippedSend = true;
4410
+ return { kind: "stop", stopReason: "end_turn" };
4411
+ }
4412
+ if (!initialSend && nextMessage) {
4413
+ nextMessage = {
4414
+ ...nextMessage,
4415
+ parts: (nextMessage.parts ?? []).filter(
4416
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4417
+ )
4418
+ };
4419
+ }
4420
+ }
4421
+ }
4422
+ if (guardForThisSend && this.config.getApprovalMode() === "plan" /* PLAN */) {
4423
+ this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
4424
+ }
4425
+ if (guardForThisSend) {
4426
+ const hasRelevantBackgroundInput = this.#hasRelevantTodoStopGuardBackgroundInput();
4427
+ const refreshedDecision = guardForThisSend.toolClosure ? this.todoStopGuard.decideToolClosure(
4428
+ guardForThisSend.attempt - 1,
4429
+ hasRelevantBackgroundInput
4430
+ ) : this.todoStopGuard.decide(hasRelevantBackgroundInput);
4431
+ if (refreshedDecision.kind !== "continue" || refreshedDecision.attempt !== guardForThisSend.attempt) {
4432
+ guardForThisSend = void 0;
4433
+ nextGuardContinuation = void 0;
4434
+ if (!options.externalParts) {
4435
+ preserveGuardOnSkippedSend = true;
4436
+ return { kind: "stop", stopReason: "end_turn" };
4437
+ }
4438
+ if (!initialSend && nextMessage) {
4439
+ nextMessage = {
4440
+ ...nextMessage,
4441
+ parts: (nextMessage.parts ?? []).filter(
4442
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4443
+ )
4444
+ };
4445
+ }
4097
4446
  }
4098
- if (waitsForQueuedPrompt) {
4447
+ }
4448
+ if (guardForThisSend) {
4449
+ const claim = await this.#claimTodoStopGuardContinuation(
4450
+ pendingSend.signal
4451
+ );
4452
+ if (claim === "queued") {
4099
4453
  guardForThisSend = void 0;
4100
4454
  nextGuardContinuation = void 0;
4101
4455
  preserveGuardOnSkippedSend = true;
@@ -4104,41 +4458,21 @@ ${this.pendingRecoveredAgentsNotice}
4104
4458
  }
4105
4459
  return { kind: "stop", stopReason: "end_turn" };
4106
4460
  }
4107
- if (guardCompressionFailed) {
4108
- this.todoStopGuard.suspend();
4461
+ if (claim === "unavailable") {
4462
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4109
4463
  guardForThisSend = void 0;
4110
4464
  nextGuardContinuation = void 0;
4111
- if (!externalParts || externalParts.length === 0) {
4465
+ if (!options.externalParts) {
4112
4466
  preserveGuardOnSkippedSend = true;
4113
4467
  return { kind: "stop", stopReason: "end_turn" };
4114
4468
  }
4115
- }
4116
- if (guardForThisSend && this.config.getApprovalMode() === "plan" /* PLAN */) {
4117
- this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
4118
- }
4119
- if (guardForThisSend) {
4120
- const hasRelevantBackgroundInput = this.#hasRelevantTodoStopGuardBackgroundInput();
4121
- const refreshedDecision = guardForThisSend.toolClosure ? this.todoStopGuard.decideToolClosure(
4122
- guardForThisSend.attempt - 1,
4123
- hasRelevantBackgroundInput
4124
- ) : this.todoStopGuard.decide(
4125
- hasRelevantBackgroundInput
4126
- );
4127
- if (refreshedDecision.kind !== "continue" || refreshedDecision.attempt !== guardForThisSend.attempt) {
4128
- guardForThisSend = void 0;
4129
- nextGuardContinuation = void 0;
4130
- if (!options.externalParts) {
4131
- preserveGuardOnSkippedSend = true;
4132
- return { kind: "stop", stopReason: "end_turn" };
4133
- }
4134
- if (!initialSend && nextMessage) {
4135
- nextMessage = {
4136
- ...nextMessage,
4137
- parts: (nextMessage.parts ?? []).filter(
4138
- (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4139
- )
4140
- };
4141
- }
4469
+ if (!initialSend && nextMessage) {
4470
+ nextMessage = {
4471
+ ...nextMessage,
4472
+ parts: (nextMessage.parts ?? []).filter(
4473
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4474
+ )
4475
+ };
4142
4476
  }
4143
4477
  }
4144
4478
  }
@@ -4146,16 +4480,42 @@ ${this.pendingRecoveredAgentsNotice}
4146
4480
  await options.onAutomaticContinuationValidated();
4147
4481
  automaticContinuationValidated = true;
4148
4482
  }
4149
- const selectedMessage = guardForThisSend || !externalParts ? nextMessage?.parts ?? [] : externalParts;
4483
+ preparedMessage = guardForThisSend || !externalParts ? nextMessage?.parts ?? [] : externalParts;
4150
4484
  messageForPreservation = {
4151
4485
  role: "user",
4152
- parts: selectedMessage
4486
+ parts: preparedMessage
4153
4487
  };
4154
- return {
4155
- kind: "send",
4156
- message: selectedMessage
4488
+ preservePreparedMessageOnSkippedSend = preparedMessage.some(
4489
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4490
+ );
4491
+ return { kind: "send", message: preparedMessage };
4492
+ } : void 0,
4493
+ beforeSend: /* @__PURE__ */ __name(async ({ compressionFailed }) => {
4494
+ if (guardForThisSend && compressionFailed) {
4495
+ this.todoStopGuard.suspend();
4496
+ guardForThisSend = void 0;
4497
+ nextGuardContinuation = void 0;
4498
+ if (!options.externalParts) {
4499
+ preserveGuardOnSkippedSend = true;
4500
+ return { kind: "stop", stopReason: "end_turn" };
4501
+ }
4502
+ preparedMessage = initialSend && externalParts ? externalParts : preparedMessage.filter(
4503
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4504
+ );
4505
+ preservePreparedMessageOnSkippedSend = true;
4506
+ }
4507
+ if (!automaticContinuationValidated && options.onAutomaticContinuationValidated) {
4508
+ await options.onAutomaticContinuationValidated();
4509
+ automaticContinuationValidated = true;
4510
+ }
4511
+ messageForPreservation = {
4512
+ role: "user",
4513
+ parts: preparedMessage
4157
4514
  };
4158
- } : void 0
4515
+ providerSendChat = this.#getCurrentChat();
4516
+ userContentPushCountBeforeSend = providerSendChat.getUserContentPushCount?.() ?? 0;
4517
+ return { kind: "send", message: preparedMessage };
4518
+ }, "beforeSend")
4159
4519
  }
4160
4520
  );
4161
4521
  if (!sendResult.responseStream) {
@@ -4171,7 +4531,7 @@ ${this.pendingRecoveredAgentsNotice}
4171
4531
  );
4172
4532
  this.#preserveUnsentMessageHistory(
4173
4533
  preservedParts.length > 0 ? { ...messageForPreservation, parts: preservedParts } : null,
4174
- sendResult.stopReason === "cancelled"
4534
+ sendResult.stopReason === "cancelled" || preservePreparedMessageOnSkippedSend
4175
4535
  );
4176
4536
  return {
4177
4537
  kind: "terminal",
@@ -4193,7 +4553,7 @@ ${this.pendingRecoveredAgentsNotice}
4193
4553
  if (guardCommitted) {
4194
4554
  await this.#emitTodoStopGuardContinuation(guardForThisSend);
4195
4555
  }
4196
- if (!guardCommitted && externalParts) {
4556
+ if (!guardCommitted && options.externalParts) {
4197
4557
  guardForThisSend = void 0;
4198
4558
  }
4199
4559
  }
@@ -4247,6 +4607,24 @@ ${this.pendingRecoveredAgentsNotice}
4247
4607
  }
4248
4608
  } catch (error) {
4249
4609
  streamFailed = true;
4610
+ const preservedParts = (messageForPreservation.parts ?? []).filter(
4611
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4612
+ );
4613
+ if (preservedParts.length > 0 && (!providerSendChat || (providerSendChat.getUserContentPushCount?.() ?? 0) <= userContentPushCountBeforeSend)) {
4614
+ this.#preserveUnsentMessageHistory(
4615
+ { ...messageForPreservation, parts: preservedParts },
4616
+ true
4617
+ );
4618
+ }
4619
+ const isControlledCancellation = pendingSend.signal.aborted && (pendingSend.signal.reason === USER_CANCEL_ABORT_REASON || pendingSend.signal.reason === SESSION_DISPOSE_ABORT_REASON);
4620
+ if (isControlledCancellation) {
4621
+ this.todoStopGuard.suspend();
4622
+ return {
4623
+ kind: "terminal",
4624
+ stopReason: "cancelled",
4625
+ ...supersededAutomaticContinuation ? { supersededAutomaticContinuation: true } : {}
4626
+ };
4627
+ }
4250
4628
  this.todoStopGuard.pauseForTrustedRetry();
4251
4629
  const errorStatus = getErrorStatus(error);
4252
4630
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -4296,7 +4674,8 @@ ${this.pendingRecoveredAgentsNotice}
4296
4674
  pendingSend.signal,
4297
4675
  toolPromptId,
4298
4676
  functionCalls,
4299
- toolLoopState
4677
+ toolLoopState,
4678
+ options.onFullTurnModel
4300
4679
  )
4301
4680
  );
4302
4681
  if (toolRun.stopAfterPermissionCancel || toolRun.loopDetected) {
@@ -4454,6 +4833,19 @@ ${this.pendingRecoveredAgentsNotice}
4454
4833
  */
4455
4834
  async #sendMessageStreamWithAutoCompression(promptId, message, abortSignal, options = {}) {
4456
4835
  const geminiClient = this.config.getGeminiClient();
4836
+ if (options.prepareBeforeCompression) {
4837
+ const decision = await options.prepareBeforeCompression();
4838
+ if (decision.kind === "stop") {
4839
+ return { responseStream: null, stopReason: decision.stopReason };
4840
+ }
4841
+ message = decision.message;
4842
+ }
4843
+ if (abortSignal.aborted) {
4844
+ debugLogger6.debug(
4845
+ `Send aborted after pre-compression preparation for prompt ${promptId}`
4846
+ );
4847
+ return { responseStream: null, stopReason: "cancelled" };
4848
+ }
4457
4849
  let compressionDiagnostic = null;
4458
4850
  let compressionInfo = null;
4459
4851
  let compressionFailed = false;
@@ -4475,10 +4867,13 @@ ${this.pendingRecoveredAgentsNotice}
4475
4867
  compressionDiagnostic = `IMPORTANT: This conversation ${reasonClause}. A compressed context will be sent for future messages (compressed from: ${compressed.originalTokenCount ?? "unknown"} to ${compressed.newTokenCount ?? "unknown"} tokens).`;
4476
4868
  }
4477
4869
  } catch (compressionError) {
4478
- if (abortSignal.aborted || this.#isAbortError(compressionError)) {
4870
+ if (abortSignal.aborted) {
4479
4871
  debugLogger6.debug(`Auto-compression aborted for prompt ${promptId}`);
4480
4872
  return { responseStream: null, stopReason: "cancelled" };
4481
4873
  }
4874
+ if (this.#isAbortError(compressionError)) {
4875
+ throw compressionError;
4876
+ }
4482
4877
  debugLogger6.warn(
4483
4878
  `Auto-compression failed for prompt ${promptId}; proceeding without compression: ` + this.#formatError(compressionError)
4484
4879
  );
@@ -4693,7 +5088,8 @@ ${this.pendingRecoveredAgentsNotice}
4693
5088
  if (this.midTurnDrainUnavailable) {
4694
5089
  return {
4695
5090
  parts: await this.#buildMidTurnParts(recovered, abortSignal, options),
4696
- hasQueuedPrompt: false
5091
+ hasQueuedPrompt: false,
5092
+ reliable: false
4697
5093
  };
4698
5094
  }
4699
5095
  let drainPromise;
@@ -4716,13 +5112,18 @@ ${this.pendingRecoveredAgentsNotice}
4716
5112
  clearTimeout(timeoutHandle);
4717
5113
  }
4718
5114
  this.midTurnDrainTimeoutStrikes = 0;
5115
+ const reliable = isValidMidTurnDrainResponse(
5116
+ response,
5117
+ options.watchQueuedPromptForTodoStopGuard === true
5118
+ );
4719
5119
  return {
4720
5120
  parts: await this.#buildMidTurnParts(
4721
5121
  [...recovered, ...parseMidTurnDrainResponse(response)],
4722
5122
  abortSignal,
4723
5123
  options
4724
5124
  ),
4725
- hasQueuedPrompt: isRecord2(response) && response["hasQueuedPrompt"] === true
5125
+ hasQueuedPrompt: isRecord2(response) && response["hasQueuedPrompt"] === true,
5126
+ reliable
4726
5127
  };
4727
5128
  } catch (error) {
4728
5129
  const errorMessage = error instanceof Error ? error.message : error && typeof error === "object" && "message" in error ? String(error.message) : String(error);
@@ -4741,7 +5142,8 @@ ${this.pendingRecoveredAgentsNotice}
4741
5142
  );
4742
5143
  return {
4743
5144
  parts: await this.#buildMidTurnParts(recovered, abortSignal, options),
4744
- hasQueuedPrompt: false
5145
+ hasQueuedPrompt: false,
5146
+ reliable: false
4745
5147
  };
4746
5148
  }
4747
5149
  }
@@ -4881,26 +5283,39 @@ ${this.pendingRecoveredAgentsNotice}
4881
5283
  );
4882
5284
  }
4883
5285
  #enqueueCronPrompt(item) {
4884
- if ((this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuardQueuedPromptPriority) && !this.#cronContinuesTodoStopGuardWorkChain(item)) {
4885
- if (item.taskId) {
5286
+ const automaticWorkDeferred = this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuardQueuedPromptPriority;
5287
+ if (automaticWorkDeferred) {
5288
+ const incomingIsRelated = this.#cronContinuesTodoStopGuardWorkChain(item);
5289
+ let shouldAppend = true;
5290
+ if (!incomingIsRelated && item.taskId) {
4886
5291
  const duplicateIndex = this.cronQueue.findIndex(
4887
5292
  (queued) => queued.taskId === item.taskId && !this.#cronContinuesTodoStopGuardWorkChain(queued)
4888
5293
  );
4889
5294
  if (duplicateIndex >= 0) {
4890
5295
  this.cronQueue[duplicateIndex] = item;
4891
- return;
5296
+ shouldAppend = false;
4892
5297
  }
4893
5298
  }
4894
- const unrelatedIndices = this.cronQueue.map(
4895
- (queued, index) => this.#cronContinuesTodoStopGuardWorkChain(queued) ? -1 : index
4896
- ).filter((index) => index >= 0);
4897
- if (unrelatedIndices.length >= MAX_DEFERRED_UNRELATED_CRON_QUEUE) {
4898
- const evictedIndex = unrelatedIndices[0];
5299
+ const maxBeforeAppend = MAX_DEFERRED_UNRELATED_CRON_QUEUE - (shouldAppend && !incomingIsRelated ? 1 : 0);
5300
+ let unrelatedCount = this.cronQueue.filter(
5301
+ (queued) => !this.#cronContinuesTodoStopGuardWorkChain(queued)
5302
+ ).length;
5303
+ const evictedTaskIds = [];
5304
+ while (unrelatedCount > maxBeforeAppend) {
5305
+ const evictedIndex = this.cronQueue.findIndex(
5306
+ (queued) => !this.#cronContinuesTodoStopGuardWorkChain(queued)
5307
+ );
5308
+ if (evictedIndex < 0) break;
4899
5309
  const [evicted] = this.cronQueue.splice(evictedIndex, 1);
5310
+ evictedTaskIds.push(evicted?.taskId ?? "unknown");
5311
+ unrelatedCount--;
5312
+ }
5313
+ if (evictedTaskIds.length > 0) {
4900
5314
  debugLogger6.warn(
4901
- `Cron queue overflow while automatic work is deferred: evicting task=${evicted?.taskId ?? "unknown"}`
5315
+ `Cron queue overflow while automatic work is deferred: evicted ${evictedTaskIds.length} unrelated task(s): ${evictedTaskIds.join(", ")}`
4902
5316
  );
4903
5317
  }
5318
+ if (!shouldAppend) return;
4904
5319
  }
4905
5320
  this.cronQueue.push(item);
4906
5321
  }
@@ -5302,6 +5717,7 @@ ${this.pendingRecoveredAgentsNotice}
5302
5717
  taskId: meta.agentId,
5303
5718
  status: meta.status,
5304
5719
  kind: "agent",
5720
+ continuesTodoStopGuardWorkChain: this.#agentContinuesTodoStopGuardWorkChain(meta.agentId),
5305
5721
  toolUseId: meta.toolUseId
5306
5722
  });
5307
5723
  }
@@ -5317,6 +5733,10 @@ ${this.pendingRecoveredAgentsNotice}
5317
5733
  taskId: meta.monitorId,
5318
5734
  status: meta.status,
5319
5735
  kind: "monitor",
5736
+ continuesTodoStopGuardWorkChain: this.#monitorContinuesTodoStopGuardWorkChain(
5737
+ meta.monitorId,
5738
+ meta.ownerAgentId
5739
+ ),
5320
5740
  toolUseId: meta.toolUseId
5321
5741
  });
5322
5742
  });
@@ -5327,7 +5747,8 @@ ${this.pendingRecoveredAgentsNotice}
5327
5747
  modelText,
5328
5748
  taskId: meta.shellId,
5329
5749
  status: meta.status,
5330
- kind: "shell"
5750
+ kind: "shell",
5751
+ continuesTodoStopGuardWorkChain: !this.todoStopGuardBackgroundBaseline.shells.has(meta.shellId)
5331
5752
  });
5332
5753
  });
5333
5754
  this.config.getChatRecordingService()?.setTitleRecordedCallback((customTitle, titleSource, sessionId) => {
@@ -5459,7 +5880,12 @@ ${this.pendingRecoveredAgentsNotice}
5459
5880
  if (ac.signal.aborted) return;
5460
5881
  await this.#emitBackgroundNotificationDisplay(item);
5461
5882
  const notificationParts = [{ text: item.modelText }];
5462
- this.config.getChatRecordingService()?.recordNotification(notificationParts, item.displayText);
5883
+ this.config.getChatRecordingService()?.recordNotification(notificationParts, item.displayText, {
5884
+ taskId: item.taskId,
5885
+ status: item.status,
5886
+ kind: item.kind,
5887
+ toolUseId: item.toolUseId
5888
+ });
5463
5889
  const notificationReminders = await this.#buildInitialSystemReminders();
5464
5890
  let nextMessage = {
5465
5891
  role: "user",
@@ -5912,7 +6338,7 @@ ${this.pendingRecoveredAgentsNotice}
5912
6338
  * sequential batch to preserve the implicit ordering the model may rely
5913
6339
  * on. Response-part ordering matches the original `functionCalls` order.
5914
6340
  */
5915
- async runToolCalls(abortSignal, promptId, functionCalls, toolLoopState) {
6341
+ async runToolCalls(abortSignal, promptId, functionCalls, toolLoopState, onFullTurnModel) {
5916
6342
  const dedupedFunctionCalls = dedupeToolCallsById(functionCalls);
5917
6343
  const generatedCallIdBase = randomUUID();
5918
6344
  const executionCallIds = new Map(
@@ -6189,7 +6615,8 @@ ${this.pendingRecoveredAgentsNotice}
6189
6615
  toolLoopState,
6190
6616
  recordSkippedToolCall,
6191
6617
  queueToolResultRecord,
6192
- executionCallIds.get(calls[i])
6618
+ executionCallIds.get(calls[i]),
6619
+ onFullTurnModel
6193
6620
  );
6194
6621
  results[i] = r;
6195
6622
  if (r.loopDetected) {
@@ -6223,7 +6650,8 @@ ${this.pendingRecoveredAgentsNotice}
6223
6650
  toolLoopState,
6224
6651
  recordSkippedToolCall,
6225
6652
  queueToolResultRecord,
6226
- executionCallIds.get(calls[idx])
6653
+ executionCallIds.get(calls[idx]),
6654
+ onFullTurnModel
6227
6655
  ).then((r) => {
6228
6656
  results[idx] = r;
6229
6657
  }).finally(() => {
@@ -6347,7 +6775,8 @@ ${this.pendingRecoveredAgentsNotice}
6347
6775
  toolLoopState,
6348
6776
  recordSkippedToolCall,
6349
6777
  queueToolResultRecord,
6350
- executionCallIds.get(fc)
6778
+ executionCallIds.get(fc),
6779
+ onFullTurnModel
6351
6780
  );
6352
6781
  parts.push(...r.parts);
6353
6782
  collectMemoryWriteCandidates(r);
@@ -6412,7 +6841,7 @@ ${this.pendingRecoveredAgentsNotice}
6412
6841
  }
6413
6842
  return reminders;
6414
6843
  }
6415
- async runTool(abortSignal, promptId, fc, onStopAfterPermissionCancel, toolLoopState, recordSkippedToolCall, queueToolResultRecord, generatedCallId) {
6844
+ async runTool(abortSignal, promptId, fc, onStopAfterPermissionCancel, toolLoopState, recordSkippedToolCall, queueToolResultRecord, generatedCallId, onFullTurnModel) {
6416
6845
  const callId = fc.id ?? generatedCallId ?? `${fc.name}-${Date.now()}`;
6417
6846
  let args = fc.args ?? {};
6418
6847
  if (toolLoopState?.loopDetected) {
@@ -6517,15 +6946,20 @@ ${this.pendingRecoveredAgentsNotice}
6517
6946
  }
6518
6947
  const policyToolName = tool.name;
6519
6948
  const originalPolicyRequestArgs = policyToolName === ToolNames.SHELL || policyToolName === ToolNames.MONITOR ? structuredClone(args) : args;
6520
- const toolSpan = startToolSpan(policyToolName, {
6521
- "tool.call_id": callId,
6522
- "gen_ai.tool.call.id": getProviderToolCallId(fc) ?? callId,
6523
- // Dual-emit the legacy call_id/tool_name aliases like CoreToolScheduler
6524
- // (coreToolScheduler.ts) so pre-Phase-2 dashboards keyed off call_id keep
6525
- // matching daemon/ACP tool spans during the migration window.
6526
- call_id: callId,
6527
- tool_name: policyToolName
6528
- });
6949
+ const toolSpan = startToolSpan(
6950
+ policyToolName,
6951
+ {
6952
+ "tool.call_id": callId,
6953
+ "gen_ai.tool.call.id": getProviderToolCallId(fc) ?? callId,
6954
+ // Dual-emit the legacy call_id/tool_name aliases like CoreToolScheduler
6955
+ // (coreToolScheduler.ts) so pre-Phase-2 dashboards keyed off call_id keep
6956
+ // matching daemon/ACP tool spans during the migration window.
6957
+ call_id: callId,
6958
+ tool_name: policyToolName
6959
+ },
6960
+ tool.description,
6961
+ promptId
6962
+ );
6529
6963
  let spanSuccess = false;
6530
6964
  try {
6531
6965
  return await runInToolSpanContext(toolSpan, async () => {
@@ -6563,6 +6997,10 @@ ${this.pendingRecoveredAgentsNotice}
6563
6997
  let toolBuildSucceeded = false;
6564
6998
  try {
6565
6999
  const invocation = tool.build(args);
7000
+ if (policyToolName === ToolNames.MONITOR) {
7001
+ const callIdAware = invocation;
7002
+ callIdAware.setCallId?.(callId);
7003
+ }
6566
7004
  toolBuildSucceeded = true;
6567
7005
  const taskEventEmitter = invocation.eventEmitter;
6568
7006
  if (isAgentTool && taskEventEmitter) {
@@ -7078,6 +7516,33 @@ ${this.pendingRecoveredAgentsNotice}
7078
7516
  );
7079
7517
  }
7080
7518
  }
7519
+ const continuedAgentId = toolName === ToolNames.SEND_MESSAGE && typeof args["task_id"] === "string" && args["task_id"].length > 0 ? args["task_id"] : void 0;
7520
+ const provisionalRelatedAgent = continuedAgentId !== void 0 && !this.relatedAgentIds.has(continuedAgentId);
7521
+ if (provisionalRelatedAgent) {
7522
+ this.provisionalRelatedAgentCounts.set(
7523
+ continuedAgentId,
7524
+ (this.provisionalRelatedAgentCounts.get(continuedAgentId) ?? 0) + 1
7525
+ );
7526
+ }
7527
+ let relatedAgentSettled = false;
7528
+ const settleRelatedAgent = /* @__PURE__ */ __name((succeeded2) => {
7529
+ if (relatedAgentSettled || !provisionalRelatedAgent || !continuedAgentId) {
7530
+ return;
7531
+ }
7532
+ relatedAgentSettled = true;
7533
+ const remaining = (this.provisionalRelatedAgentCounts.get(continuedAgentId) ?? 1) - 1;
7534
+ if (remaining > 0) {
7535
+ this.provisionalRelatedAgentCounts.set(
7536
+ continuedAgentId,
7537
+ remaining
7538
+ );
7539
+ } else {
7540
+ this.provisionalRelatedAgentCounts.delete(continuedAgentId);
7541
+ }
7542
+ if (succeeded2) {
7543
+ this.relatedAgentIds.add(continuedAgentId);
7544
+ }
7545
+ }, "settleRelatedAgent");
7081
7546
  const execSpan = startToolExecutionSpan();
7082
7547
  let toolResult;
7083
7548
  let isExecutionTimeout = false;
@@ -7116,6 +7581,17 @@ ${this.pendingRecoveredAgentsNotice}
7116
7581
  `Qwen Code is executing tool ${toolName}`
7117
7582
  );
7118
7583
  try {
7584
+ try {
7585
+ addToolArgumentsAttributes(
7586
+ this.config,
7587
+ toolSpan,
7588
+ invocation.params
7589
+ );
7590
+ } catch {
7591
+ debugLogger6.debug(
7592
+ "[Session.runTool] Failed to record tool arguments telemetry"
7593
+ );
7594
+ }
7119
7595
  toolResult = await invocation.execute(
7120
7596
  activeToolAbortSignal,
7121
7597
  onToolProgress
@@ -7126,6 +7602,7 @@ ${this.pendingRecoveredAgentsNotice}
7126
7602
  }
7127
7603
  isExecutionTimeout = toolResult.error?.type === "execution_timeout" /* EXECUTION_TIMEOUT */;
7128
7604
  aborted = activeToolAbortSignal.aborted && !isExecutionTimeout;
7605
+ settleRelatedAgent(!toolResult.error && !aborted);
7129
7606
  endToolExecutionSpan(execSpan, {
7130
7607
  success: !toolResult.error && !aborted,
7131
7608
  error: aborted ? "tool_cancelled" : isExecutionTimeout ? "tool_timeout" : toolResult.error ? "tool_error" : void 0,
@@ -7133,6 +7610,7 @@ ${this.pendingRecoveredAgentsNotice}
7133
7610
  ...heartbeatSpanAttributes()
7134
7611
  });
7135
7612
  } catch (execError) {
7613
+ settleRelatedAgent(false);
7136
7614
  endToolExecutionSpan(execSpan, {
7137
7615
  success: false,
7138
7616
  error: activeToolAbortSignal.aborted ? "tool_cancelled" : "tool_exception",
@@ -7148,7 +7626,7 @@ ${this.pendingRecoveredAgentsNotice}
7148
7626
  this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
7149
7627
  }
7150
7628
  }
7151
- const responseParts = toolResult.error ? convertToFunctionErrorResponse(
7629
+ let responseParts = toolResult.error ? convertToFunctionErrorResponse(
7152
7630
  toolName,
7153
7631
  callId,
7154
7632
  toolResult.llmContent,
@@ -7226,6 +7704,18 @@ ${this.pendingRecoveredAgentsNotice}
7226
7704
  artifacts: failureHookResult.artifacts
7227
7705
  });
7228
7706
  }
7707
+ const visionBridgeNotices = [];
7708
+ responseParts = await bridgeToolResultImages({
7709
+ config: this.config,
7710
+ responseParts,
7711
+ signal: activeToolAbortSignal,
7712
+ onFullTurnModel,
7713
+ onVisionBridgeNotice: /* @__PURE__ */ __name((notice) => visionBridgeNotices.push(notice), "onVisionBridgeNotice")
7714
+ });
7715
+ const visionBridgeNotice = visionBridgeNotices.length > 0 ? visionBridgeNotices.join("\n") : void 0;
7716
+ if (visionBridgeNotice) {
7717
+ await this.messageEmitter.emitAgentMessage(visionBridgeNotice);
7718
+ }
7229
7719
  if (isTodoWriteTool) {
7230
7720
  const todos = this.planEmitter.extractTodos(
7231
7721
  toolResult.returnDisplay,
@@ -7269,11 +7759,26 @@ ${this.pendingRecoveredAgentsNotice}
7269
7759
  callId,
7270
7760
  status,
7271
7761
  resultDisplay: toolResult.returnDisplay,
7762
+ ...visionBridgeNotice !== void 0 ? { visionBridgeNotice } : {},
7272
7763
  error: toolResult.error ? new Error(toolResult.error.message) : void 0,
7273
7764
  errorType: toolResult.error?.type
7274
7765
  }
7275
7766
  });
7276
7767
  spanSuccess = succeeded;
7768
+ if (succeeded && !nestedPermissionCancelled) {
7769
+ const result = responseParts.find(
7770
+ (part) => part.functionResponse !== void 0
7771
+ )?.functionResponse?.response;
7772
+ if (result !== void 0) {
7773
+ try {
7774
+ addToolCallResultAttributes(this.config, toolSpan, result);
7775
+ } catch {
7776
+ debugLogger6.debug(
7777
+ "[Session.runTool] Failed to record tool result telemetry"
7778
+ );
7779
+ }
7780
+ }
7781
+ }
7277
7782
  if (toolResult.error) {
7278
7783
  spanError = toolResult.error.message;
7279
7784
  } else if (aborted) {
@@ -7943,7 +8448,8 @@ function serializeMonitorTask(entry, now) {
7943
8448
  ...optionalField("pid", entry.pid),
7944
8449
  ...optionalField("exitCode", entry.exitCode),
7945
8450
  ...optionalField("error", entry.error),
7946
- ...optionalField("ownerAgentId", entry.ownerAgentId)
8451
+ ...optionalField("ownerAgentId", entry.ownerAgentId),
8452
+ ...optionalField("toolUseId", entry.toolUseId)
7947
8453
  };
7948
8454
  }
7949
8455
  __name(serializeMonitorTask, "serializeMonitorTask");
@@ -8131,6 +8637,9 @@ function buildAcpLocalReadRoots(config) {
8131
8637
  getUserAutoMemoryRoot(),
8132
8638
  ...config.storage.getUserSkillsDirs(),
8133
8639
  Storage.getUserExtensionsDir(),
8640
+ // Saved plan files (see ReadFileTool.getDefaultPermission for why the
8641
+ // plans dir must be readable without a confirmation prompt).
8642
+ config.getPlansDir(),
8134
8643
  ...defaultAcpOnlyLocalReadRoots(),
8135
8644
  ...parseAcpLocalReadRootsEnv()
8136
8645
  ];
@@ -8182,6 +8691,12 @@ function isBulkLoadReplayRequest(params) {
8182
8691
  return meta?.[LOAD_REPLAY_MODE_META_KEY] === LOAD_REPLAY_BULK_MODE;
8183
8692
  }
8184
8693
  __name(isBulkLoadReplayRequest, "isBulkLoadReplayRequest");
8694
+ function isChannelSessionRequest(params) {
8695
+ const meta = isObjectRecord(params._meta) ? params._meta : void 0;
8696
+ const value = meta?.[SESSION_SOURCE_META_KEY];
8697
+ return isObjectRecord(value) && value["sourceType"] === "channel";
8698
+ }
8699
+ __name(isChannelSessionRequest, "isChannelSessionRequest");
8185
8700
  function getLoadReplayPageSize(params) {
8186
8701
  const meta = isObjectRecord(params._meta) ? params._meta : void 0;
8187
8702
  const value = meta?.[LOAD_REPLAY_PAGE_SIZE_META_KEY];
@@ -9611,7 +10126,97 @@ async function deliverClientMcpMessage(connection, serverName, message, sessionI
9611
10126
  return payload;
9612
10127
  }
9613
10128
  __name(deliverClientMcpMessage, "deliverClientMcpMessage");
10129
+ function readRuntimeMcpRequest(params) {
10130
+ const name = params["name"];
10131
+ if (typeof name !== "string" || name.length === 0) {
10132
+ throw RequestError.invalidParams(void 0, "Invalid or missing name");
10133
+ }
10134
+ if (!isValidServerName(name)) {
10135
+ throw RequestError.invalidParams(
10136
+ void 0,
10137
+ "Server name must be \u2264256 chars, alphanumeric + underscore/hyphen, and not a reserved JS property name"
10138
+ );
10139
+ }
10140
+ const originatorClientId = params["originatorClientId"];
10141
+ return {
10142
+ name,
10143
+ runtimeClientId: typeof originatorClientId === "string" && originatorClientId.length > 0 ? originatorClientId : "daemon"
10144
+ };
10145
+ }
10146
+ __name(readRuntimeMcpRequest, "readRuntimeMcpRequest");
10147
+ function readRuntimeMcpAddRequest(params) {
10148
+ const request = readRuntimeMcpRequest(params);
10149
+ const config = params["config"];
10150
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
10151
+ throw RequestError.invalidParams(void 0, "Invalid or missing config");
10152
+ }
10153
+ const {
10154
+ trust: _trust,
10155
+ authProviderType: _auth,
10156
+ includeTools: _inc,
10157
+ excludeTools: _exc,
10158
+ cwd: _cwd,
10159
+ env: _env,
10160
+ oauth: _oauth,
10161
+ headers: _headers,
10162
+ type: _type,
10163
+ [CLIENT_MCP_OVER_WS_CONFIG_FLAG]: clientMcpOverWs,
10164
+ ...safeConfig
10165
+ } = config;
10166
+ if (clientMcpOverWs === true) {
10167
+ safeConfig["type"] = "sdk";
10168
+ }
10169
+ return {
10170
+ ...request,
10171
+ config: safeConfig
10172
+ };
10173
+ }
10174
+ __name(readRuntimeMcpAddRequest, "readRuntimeMcpAddRequest");
10175
+ function getRuntimeMcpManager(config) {
10176
+ const manager = config.getToolRegistry()?.getMcpClientManager();
10177
+ if (!manager) {
10178
+ throw RequestError.internalError(
10179
+ void 0,
10180
+ "McpClientManager unavailable on this Config"
10181
+ );
10182
+ }
10183
+ return manager;
10184
+ }
10185
+ __name(getRuntimeMcpManager, "getRuntimeMcpManager");
10186
+ async function addRuntimeMcpServer(manager, request) {
10187
+ try {
10188
+ return await manager.addRuntimeMcpServer(
10189
+ request.name,
10190
+ request.config,
10191
+ request.runtimeClientId
10192
+ );
10193
+ } catch (err) {
10194
+ if (err instanceof McpBudgetWouldExceedError) {
10195
+ throw new RequestError(-32099, err.message, {
10196
+ errorKind: err.code,
10197
+ serverName: err.serverName
10198
+ });
10199
+ }
10200
+ if (err instanceof McpServerSpawnFailedError) {
10201
+ throw new RequestError(-32099, err.message, {
10202
+ errorKind: err.code,
10203
+ serverName: err.serverName,
10204
+ ...err.details
10205
+ });
10206
+ }
10207
+ if (err instanceof InvalidMcpConfigError) {
10208
+ throw new RequestError(-32099, err.message, {
10209
+ errorKind: err.code,
10210
+ serverName: err.serverName,
10211
+ reason: err.reason
10212
+ });
10213
+ }
10214
+ throw err;
10215
+ }
10216
+ }
10217
+ __name(addRuntimeMcpServer, "addRuntimeMcpServer");
9614
10218
  async function runAcpAgent(config, settings, argv, options) {
10219
+ const sessionWriterLeaseEnabledAtStartup = typeof config.isSessionWriterLeaseEnabled === "function" ? config.isSessionWriterLeaseEnabled() : settings.merged.experimental?.sessionWriterLease === true;
9615
10220
  const privateParentCapability = options === void 0 ? process.env[PRIVATE_ACP_CAPABILITY_ENV] : options.privateParentCapability;
9616
10221
  delete process.env[PRIVATE_ACP_CAPABILITY_ENV];
9617
10222
  let acpConnection;
@@ -9651,12 +10256,31 @@ async function runAcpAgent(config, settings, argv, options) {
9651
10256
  console.info = console.error;
9652
10257
  console.debug = console.error;
9653
10258
  let initializeRequestId;
10259
+ const pendingNewSessionRequestIds = /* @__PURE__ */ new Set();
9654
10260
  const stream = ndJsonStream(stdout, stdin, {
9655
10261
  onMessageObserved: /* @__PURE__ */ __name(({ direction, message }) => {
9656
- if (direction === "received" && "id" in message && "method" in message && message.method === "initialize") {
9657
- initializeRequestId = message.id;
10262
+ if (direction === "received" && "id" in message && "method" in message) {
10263
+ if (message.method === "session/new") {
10264
+ pendingNewSessionRequestIds.add(message.id);
10265
+ } else if (message.method === "initialize") {
10266
+ initializeRequestId = message.id;
10267
+ }
9658
10268
  return;
9659
10269
  }
10270
+ if (direction === "sent" && "id" in message && !("method" in message) && pendingNewSessionRequestIds.delete(message.id) && "result" in message && typeof message.result === "object" && message.result !== null && "sessionId" in message.result && typeof message.result.sessionId === "string") {
10271
+ const sessionId = message.result.sessionId;
10272
+ setImmediate(() => {
10273
+ const session = agentInstance?.getActiveSessions().find((candidate) => candidate.getId() === sessionId);
10274
+ if (!session) return;
10275
+ void preloadContentGenerator(
10276
+ session.getConfig().getContentGenerator()
10277
+ ).catch((error) => {
10278
+ debugLogger7.debug(
10279
+ `[ACP] Session provider preload failed for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`
10280
+ );
10281
+ });
10282
+ }).unref();
10283
+ }
9660
10284
  if (direction !== "sent" || initializeRequestId === void 0 || !("id" in message) || "method" in message || message.id !== initializeRequestId) {
9661
10285
  return;
9662
10286
  }
@@ -9675,7 +10299,8 @@ async function runAcpAgent(config, settings, argv, options) {
9675
10299
  settings,
9676
10300
  argv,
9677
10301
  conn,
9678
- privateParentCapability
10302
+ privateParentCapability,
10303
+ sessionWriterLeaseEnabledAtStartup
9679
10304
  );
9680
10305
  return agentInstance;
9681
10306
  }, stream);
@@ -9684,29 +10309,34 @@ async function runAcpAgent(config, settings, argv, options) {
9684
10309
  eventLoopMonitor.dispose();
9685
10310
  throw err;
9686
10311
  }
9687
- const drainPoolBeforeExit = /* @__PURE__ */ __name(async (label) => {
10312
+ const drainPoolBeforeExit = /* @__PURE__ */ __name(async (label, strict = false) => {
9688
10313
  if (!agentInstance) return;
9689
10314
  try {
9690
10315
  await agentInstance.shutdownMcpPool(8e3);
9691
10316
  } catch (err) {
9692
10317
  debugLogger7.error(`[ACP] MCP pool drain (${label}) error:`, err);
10318
+ if (strict) throw err;
9693
10319
  }
9694
10320
  }, "drainPoolBeforeExit");
9695
10321
  let shuttingDown = false;
10322
+ let managedShutdownPromise;
9696
10323
  let sessionEndFired = false;
9697
- const fireSessionEndOnce = /* @__PURE__ */ __name(async (reason) => {
10324
+ const fireSessionEndOnce = /* @__PURE__ */ __name(async (reason, managedConfigs) => {
9698
10325
  if (sessionEndFired) return;
9699
10326
  sessionEndFired = true;
9700
- const configs = /* @__PURE__ */ new Set([config]);
9701
- const sessions = agentInstance?.getActiveSessions();
9702
- if (sessions) {
9703
- for (const session of sessions) {
9704
- const sessionConfig = session.getConfig?.();
9705
- if (sessionConfig) {
9706
- configs.add(sessionConfig);
10327
+ const configs = new Set(managedConfigs ?? [config]);
10328
+ if (!managedConfigs) {
10329
+ const sessions = agentInstance?.getActiveSessions();
10330
+ if (sessions) {
10331
+ for (const session of sessions) {
10332
+ const sessionConfig = session.getConfig?.();
10333
+ if (sessionConfig) {
10334
+ configs.add(sessionConfig);
10335
+ }
9707
10336
  }
9708
10337
  }
9709
10338
  }
10339
+ const failures = [];
9710
10340
  for (const cfg of configs) {
9711
10341
  const hookSystem = cfg.getHookSystem?.();
9712
10342
  const hooksEnabled = !cfg.getDisableAllHooks?.();
@@ -9716,16 +10346,99 @@ async function runAcpAgent(config, settings, argv, options) {
9716
10346
  try {
9717
10347
  await hookSystem.fireSessionEndEvent(reason);
9718
10348
  } catch (err) {
10349
+ if (managedConfigs) failures.push(err);
9719
10350
  debugLogger7.warn(
9720
10351
  `SessionEnd hook failed: ${err instanceof Error ? err.message : String(err)}`
9721
10352
  );
9722
10353
  }
9723
- }
9724
- }, "fireSessionEndOnce");
10354
+ }
10355
+ if (failures.length > 0) {
10356
+ throw new AggregateError(failures, "SessionEnd hook shutdown failed");
10357
+ }
10358
+ }, "fireSessionEndOnce");
10359
+ const shutdownManagedAgent = /* @__PURE__ */ __name((reason, label) => {
10360
+ if (managedShutdownPromise) return managedShutdownPromise;
10361
+ const agent = agentInstance;
10362
+ if (!agent?.isTrustedManagedParent()) {
10363
+ return Promise.reject(
10364
+ new Error("Managed shutdown requires a trusted private parent")
10365
+ );
10366
+ }
10367
+ const terminal = agent.beginManagedShutdown();
10368
+ managedShutdownPromise = (async () => {
10369
+ const failures = [];
10370
+ try {
10371
+ await terminal.writerShutdown;
10372
+ } catch (error) {
10373
+ failures.push(error);
10374
+ debugLogger7.error("[ACP] Managed writer shutdown error:", error);
10375
+ const retainedLockPaths = terminal.configs.flatMap((config2) => {
10376
+ if (typeof config2.getSessionRuntimeBaseDir !== "function" || typeof config2.getSessionId !== "function") {
10377
+ return [];
10378
+ }
10379
+ return [
10380
+ path4.join(
10381
+ config2.getSessionRuntimeBaseDir(),
10382
+ "tmp",
10383
+ "session-writer-locks",
10384
+ `${encodeURIComponent(config2.getSessionId())}.lock`
10385
+ )
10386
+ ];
10387
+ });
10388
+ writeStderrLineSafe(
10389
+ "qwen --acp: managed session writer shutdown failed; a writer lock may be retained for safety. Verify that no previous writer is running before manual cleanup." + (retainedLockPaths.length > 0 ? ` Candidate lock paths: ${retainedLockPaths.join(", ")}` : "")
10390
+ );
10391
+ }
10392
+ try {
10393
+ await fireSessionEndOnce(reason, terminal.configs);
10394
+ } catch (error) {
10395
+ failures.push(error);
10396
+ }
10397
+ try {
10398
+ await agent.finishManagedShutdown(terminal.configs);
10399
+ } catch (error) {
10400
+ failures.push(error);
10401
+ debugLogger7.error("[ACP] Managed resource shutdown error:", error);
10402
+ }
10403
+ try {
10404
+ await drainPoolBeforeExit(label, true);
10405
+ } catch (error) {
10406
+ failures.push(error);
10407
+ }
10408
+ try {
10409
+ await runExitCleanup();
10410
+ } catch (error) {
10411
+ failures.push(error);
10412
+ debugLogger7.error("[ACP] Cleanup error:", error);
10413
+ }
10414
+ if (failures.length > 0) {
10415
+ throw new AggregateError(failures, "Managed ACP shutdown failed");
10416
+ }
10417
+ })();
10418
+ return managedShutdownPromise;
10419
+ }, "shutdownManagedAgent");
9725
10420
  const shutdownHandler = /* @__PURE__ */ __name(async () => {
9726
10421
  if (shuttingDown) return;
9727
10422
  shuttingDown = true;
9728
10423
  debugLogger7.debug("[ACP] Shutdown signal received, closing streams");
10424
+ if (agentInstance?.isTrustedManagedParent()) {
10425
+ let exitCode = 0;
10426
+ try {
10427
+ await shutdownManagedAgent("other" /* Other */, "signal");
10428
+ } catch (err) {
10429
+ exitCode = 1;
10430
+ debugLogger7.error("[ACP] Managed shutdown error:", err);
10431
+ } finally {
10432
+ eventLoopMonitor.dispose();
10433
+ }
10434
+ try {
10435
+ process.stdin.destroy();
10436
+ process.stdout.destroy();
10437
+ } catch {
10438
+ }
10439
+ process.exit(exitCode);
10440
+ return;
10441
+ }
9729
10442
  try {
9730
10443
  await fireSessionEndOnce("other" /* Other */);
9731
10444
  await agentInstance?.disposeSessions();
@@ -9753,9 +10466,21 @@ async function runAcpAgent(config, settings, argv, options) {
9753
10466
  process.on("SIGINT", shutdownHandler);
9754
10467
  try {
9755
10468
  await connection.closed;
9756
- await fireSessionEndOnce("prompt_input_exit" /* PromptInputExit */);
9757
- await drainPoolBeforeExit("ide_close");
9758
- await agentInstance?.disposeSessions();
10469
+ if (agentInstance?.isTrustedManagedParent()) {
10470
+ try {
10471
+ await shutdownManagedAgent(
10472
+ "prompt_input_exit" /* PromptInputExit */,
10473
+ "ide_close"
10474
+ );
10475
+ } catch (error) {
10476
+ process.exitCode = 1;
10477
+ throw error;
10478
+ }
10479
+ } else {
10480
+ await fireSessionEndOnce("prompt_input_exit" /* PromptInputExit */);
10481
+ await drainPoolBeforeExit("ide_close");
10482
+ await agentInstance?.disposeSessions();
10483
+ }
9759
10484
  } finally {
9760
10485
  process.off("SIGTERM", shutdownHandler);
9761
10486
  process.off("SIGINT", shutdownHandler);
@@ -9872,12 +10597,13 @@ function parseAcpSessionListCursor(value) {
9872
10597
  }
9873
10598
  __name(parseAcpSessionListCursor, "parseAcpSessionListCursor");
9874
10599
  var QwenAgent = class {
9875
- constructor(config, settings, argv, connection, expectedPrivateParentCapability) {
10600
+ constructor(config, settings, argv, connection, expectedPrivateParentCapability, sessionWriterLeaseEnabledAtStartup = false) {
9876
10601
  this.config = config;
9877
10602
  this.settings = settings;
9878
10603
  this.argv = argv;
9879
10604
  this.connection = connection;
9880
10605
  this.expectedPrivateParentCapability = expectedPrivateParentCapability;
10606
+ this.sessionWriterLeaseEnabledAtStartup = sessionWriterLeaseEnabledAtStartup;
9881
10607
  if (process.env["QWEN_SERVE_NO_MCP_POOL"] === "1") {
9882
10608
  this.mcpPool = void 0;
9883
10609
  this.workspaceMcpBudget = void 0;
@@ -9918,6 +10644,8 @@ var QwenAgent = class {
9918
10644
  workspaceGenerationControllers = /* @__PURE__ */ new Map();
9919
10645
  transcriptReplayConfigCache = /* @__PURE__ */ new Map();
9920
10646
  pendingConfigCleanup = /* @__PURE__ */ new Map();
10647
+ initializingConfigs = /* @__PURE__ */ new Set();
10648
+ managedShuttingDown = false;
9921
10649
  clientCapabilities;
9922
10650
  privateParentState = "uninitialized";
9923
10651
  // CPU-usage delta baseline for the daemon's `workspaceResource` extMethod
@@ -9951,6 +10679,102 @@ var QwenAgent = class {
9951
10679
  getActiveSessions() {
9952
10680
  return [...this.sessions.values()];
9953
10681
  }
10682
+ isTrustedManagedParent() {
10683
+ return this.privateParentState === "trusted";
10684
+ }
10685
+ assertManagedSessionAdmission() {
10686
+ if (this.expectedPrivateParentCapability !== void 0 && !this.isTrustedManagedParent()) {
10687
+ throw RequestError.invalidParams(
10688
+ void 0,
10689
+ "Private ACP parent is not initialized"
10690
+ );
10691
+ }
10692
+ if (this.managedShuttingDown) {
10693
+ throw new SessionWriterUnavailableError();
10694
+ }
10695
+ }
10696
+ beginManagedShutdown() {
10697
+ if (!this.isTrustedManagedParent()) {
10698
+ throw new Error("Managed shutdown requires a trusted private parent");
10699
+ }
10700
+ this.managedShuttingDown = true;
10701
+ for (const generation of this.generationControllers.values()) {
10702
+ generation.controller.abort();
10703
+ }
10704
+ this.generationControllers.clear();
10705
+ for (const controller of this.workspaceGenerationControllers.values()) {
10706
+ controller.abort();
10707
+ }
10708
+ this.workspaceGenerationControllers.clear();
10709
+ const configs = /* @__PURE__ */ new Set([this.config, ...this.initializingConfigs]);
10710
+ for (const session of this.sessions.values()) {
10711
+ try {
10712
+ session.beginCloseIfAvailable();
10713
+ } catch (error) {
10714
+ debugLogger7.debug(
10715
+ `Session ${session.getId()} admission close during managed shutdown failed: ${error instanceof Error ? error.message : String(error)}`
10716
+ );
10717
+ }
10718
+ void session.cancelPendingPrompt().catch((error) => {
10719
+ debugLogger7.debug(
10720
+ `Session ${session.getId()} cancel during managed shutdown failed: ${error instanceof Error ? error.message : String(error)}`
10721
+ );
10722
+ });
10723
+ configs.add(session.getConfig());
10724
+ }
10725
+ for (const pending of this.pendingConfigCleanup.values()) {
10726
+ for (const config of pending) configs.add(config);
10727
+ }
10728
+ const configList = [...configs];
10729
+ const writerTerminals = [];
10730
+ for (const config of configList) {
10731
+ try {
10732
+ writerTerminals.push(config.closeSessionWriter({ handoff: true }));
10733
+ } catch (error) {
10734
+ writerTerminals.push(Promise.reject(error));
10735
+ }
10736
+ }
10737
+ const writerShutdown = Promise.allSettled(writerTerminals).then(
10738
+ (results) => {
10739
+ const failures = results.flatMap(
10740
+ (result) => result.status === "rejected" ? [result.reason] : []
10741
+ );
10742
+ if (failures.length > 0) {
10743
+ throw new AggregateError(
10744
+ failures,
10745
+ "Managed session writer shutdown failed"
10746
+ );
10747
+ }
10748
+ }
10749
+ );
10750
+ return { configs: configList, writerShutdown };
10751
+ }
10752
+ async finishManagedShutdown(configs) {
10753
+ const failures = [];
10754
+ for (const [sessionId, session] of [...this.sessions]) {
10755
+ await this.removeStoredSessionEntry(sessionId, session, failures, {
10756
+ shutdownConfig: false
10757
+ });
10758
+ }
10759
+ const results = await Promise.allSettled(
10760
+ configs.map(
10761
+ (config) => config.shutdown({
10762
+ shutdownTelemetry: false,
10763
+ skipSessionWriter: true,
10764
+ strictResourceCleanup: true
10765
+ })
10766
+ )
10767
+ );
10768
+ for (const result of results) {
10769
+ if (result.status === "rejected") failures.push(result.reason);
10770
+ }
10771
+ this.initializingConfigs.clear();
10772
+ this.pendingConfigCleanup.clear();
10773
+ this.disposeTranscriptReplayConfigs();
10774
+ if (failures.length > 0) {
10775
+ throw new AggregateError(failures, "Managed session cleanup failed");
10776
+ }
10777
+ }
9954
10778
  getWorkspaceMcpConfig(serverName) {
9955
10779
  if (serverName && this.config.getRuntimeMcpServers?.()[serverName] !== void 0) {
9956
10780
  return this.config;
@@ -10093,16 +10917,18 @@ var QwenAgent = class {
10093
10917
  for (const config of liveConfigs) {
10094
10918
  try {
10095
10919
  const cwd = config.getTargetDir();
10096
- const mcpServers = assembleMcpServers(
10920
+ const isBareOrSafe = config.getBareMode() || config.isSafeMode();
10921
+ const mcpServers = isBareOrSafe ? { ...config.getTopTierMcpServers() } : assembleMcpServers(
10097
10922
  settings.merged.mcpServers,
10098
10923
  cwd,
10099
10924
  config.getTopTierMcpServers()
10100
10925
  );
10101
- const gating = recomputeMcpGating(
10926
+ const bootAllowed = config.getCliAllowedMcpServerNames();
10927
+ const gating = isBareOrSafe ? { allowed: bootAllowed ? [...bootAllowed] : void 0 } : recomputeMcpGating(
10102
10928
  settings,
10103
10929
  mcpServers,
10104
10930
  cwd,
10105
- config.getCliAllowedMcpServerNames(),
10931
+ bootAllowed,
10106
10932
  config.getApprovalMode() === "yolo" /* YOLO */
10107
10933
  );
10108
10934
  config.setExcludedMcpServers(gating.excluded ?? []);
@@ -10195,11 +11021,15 @@ var QwenAgent = class {
10195
11021
  debugLogger7.warn(
10196
11022
  `MCP pool drain: ${result.drained} clean, ${result.forced} timed out, ${result.errors.length} errors`
10197
11023
  );
11024
+ throw new Error(
11025
+ `MCP pool drain incomplete: ${result.forced} forced, ${result.errors.length} errors`
11026
+ );
10198
11027
  }
10199
11028
  } catch (err) {
10200
11029
  debugLogger7.error(
10201
11030
  `MCP pool drainAll failed: ${err instanceof Error ? err.message : String(err)}`
10202
11031
  );
11032
+ throw err;
10203
11033
  }
10204
11034
  }
10205
11035
  async removeStoredSessionEntry(sessionId, session, cleanupErrors = [], options = {}) {
@@ -10270,11 +11100,13 @@ var QwenAgent = class {
10270
11100
  try {
10271
11101
  await shutdownSessionConfig(config);
10272
11102
  } catch (error) {
11103
+ this.initializingConfigs.delete(config);
10273
11104
  const pending2 = this.pendingConfigCleanup.get(cleanupKey) ?? /* @__PURE__ */ new Set();
10274
11105
  pending2.add(config);
10275
11106
  this.pendingConfigCleanup.set(cleanupKey, pending2);
10276
11107
  throw mapSessionWriterRequestError(error);
10277
11108
  }
11109
+ this.initializingConfigs.delete(config);
10278
11110
  const pending = this.pendingConfigCleanup.get(cleanupKey);
10279
11111
  pending?.delete(config);
10280
11112
  if (pending?.size === 0) {
@@ -10289,7 +11121,7 @@ var QwenAgent = class {
10289
11121
  `Session cleanup failed while preserving the original request error: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`
10290
11122
  );
10291
11123
  }
10292
- throw error;
11124
+ throw mapSessionWriterRequestError(error);
10293
11125
  }
10294
11126
  pendingConfigCleanupKey(runtimeBaseDir, sessionId) {
10295
11127
  return `${path4.resolve(runtimeBaseDir)}\0${sessionId}`;
@@ -10479,7 +11311,7 @@ var QwenAgent = class {
10479
11311
  }
10480
11312
  this.clientCapabilities = args.clientCapabilities;
10481
11313
  const authMethods = buildAuthMethods();
10482
- const version = "0.21.0";
11314
+ const version = "0.21.1-nightly.20260730.1643a6c9a";
10483
11315
  const response = {
10484
11316
  protocolVersion: PROTOCOL_VERSION,
10485
11317
  agentInfo: {
@@ -10553,6 +11385,7 @@ var QwenAgent = class {
10553
11385
  }
10554
11386
  async newSession(params) {
10555
11387
  const { cwd, mcpServers } = params;
11388
+ const isChannelSession = isChannelSessionRequest(params);
10556
11389
  const parentContext = extractDaemonTraceContext(params);
10557
11390
  return await withDaemonSpan(
10558
11391
  "qwen-code.daemon.session_start",
@@ -10566,7 +11399,7 @@ var QwenAgent = class {
10566
11399
  this.settings = settings;
10567
11400
  const config = await profiler.time(
10568
11401
  "config_setup",
10569
- () => this.newSessionConfig(cwd, mcpServers, settings)
11402
+ () => this.newSessionConfig(cwd, mcpServers, settings, isChannelSession)
10570
11403
  );
10571
11404
  let session;
10572
11405
  try {
@@ -10598,6 +11431,7 @@ var QwenAgent = class {
10598
11431
  );
10599
11432
  }
10600
11433
  async loadSession(params) {
11434
+ const isChannelSession = isChannelSessionRequest(params);
10601
11435
  const settings = loadSettingsCached(params.cwd);
10602
11436
  const liveSession = this.sessions.get(params.sessionId);
10603
11437
  if (liveSession) {
@@ -10668,22 +11502,66 @@ var QwenAgent = class {
10668
11502
  // a `null`/`undefined` would otherwise throw `TypeError`.
10669
11503
  params.mcpServers ?? [],
10670
11504
  settings,
11505
+ isChannelSession,
10671
11506
  params.sessionId,
10672
11507
  true
10673
11508
  );
10674
11509
  const sessionData = config.getResumedSessionData();
10675
11510
  const bulkReplay = isBulkLoadReplayRequest(params);
10676
11511
  const replayPageSize = bulkReplay ? getLoadReplayPageSize(params) : void 0;
10677
- let session;
11512
+ let replayEnvelope;
10678
11513
  try {
10679
11514
  await this.ensureAuthenticated(config);
10680
11515
  this.setupFileSystem(config);
10681
- session = await this.createAndStoreSession(
10682
- config,
10683
- settings,
10684
- sessionData,
10685
- bulkReplay ? { replayHistory: false, startPostReplayServices: false } : {}
10686
- );
11516
+ await this.createAndStoreSession(config, settings, sessionData, {
11517
+ ...bulkReplay ? { replayHistory: false } : {},
11518
+ beforeStartPostReplayServices: /* @__PURE__ */ __name(async (createdSession) => {
11519
+ if (bulkReplay) {
11520
+ const records = sessionData?.conversation.messages;
11521
+ let replayUpdates = [];
11522
+ if (records) {
11523
+ createdSession.primeTurnFromHistory(records);
11524
+ const replayPage = selectRecentHistoryRecords(
11525
+ records,
11526
+ replayPageSize
11527
+ );
11528
+ const replayUsage = createReplayCumulativeUsage();
11529
+ const replay = await collectHistoryReplayUpdates({
11530
+ sessionId: params.sessionId,
11531
+ config,
11532
+ records: replayPage.records,
11533
+ gaps: sessionData?.historyGaps,
11534
+ cumulativeUsage: replayUsage,
11535
+ supersedeUnrestorableGoal: true,
11536
+ logger: debugLogger7
11537
+ });
11538
+ replayUpdates = replay.updates;
11539
+ copyCumulativeUsage(createdSession.cumulativeUsage, replayUsage);
11540
+ if (replay.replayError !== void 0) {
11541
+ replayEnvelope = {
11542
+ v: LOAD_REPLAY_VERSION,
11543
+ updates: replayUpdates,
11544
+ partial: true,
11545
+ replayError: replay.replayError,
11546
+ ...replayPage.hasMore ? { hasMore: true } : {}
11547
+ };
11548
+ }
11549
+ replayEnvelope ??= {
11550
+ v: LOAD_REPLAY_VERSION,
11551
+ updates: replayUpdates,
11552
+ ...replayPage.hasMore ? { hasMore: true } : {}
11553
+ };
11554
+ }
11555
+ replayEnvelope ??= {
11556
+ v: LOAD_REPLAY_VERSION,
11557
+ updates: replayUpdates
11558
+ };
11559
+ }
11560
+ await this.#restoreWorktreeOnResume(config, createdSession);
11561
+ await this.#restoreBackgroundAgentsOnResume(config, createdSession);
11562
+ this.#restoreGoalOnResume(config, createdSession);
11563
+ }, "beforeStartPostReplayServices")
11564
+ });
10687
11565
  } catch (error) {
10688
11566
  return this.cleanupAfterRequestFailure(error, async () => {
10689
11567
  if (this.sessions.get(config.getSessionId())?.getConfig() !== config) {
@@ -10691,72 +11569,6 @@ var QwenAgent = class {
10691
11569
  }
10692
11570
  });
10693
11571
  }
10694
- let replayEnvelope;
10695
- if (bulkReplay) {
10696
- try {
10697
- const records = sessionData?.conversation.messages;
10698
- let replayUpdates = [];
10699
- if (records) {
10700
- session.primeTurnFromHistory(records);
10701
- const replayPage = selectRecentHistoryRecords(
10702
- records,
10703
- replayPageSize
10704
- );
10705
- const replayUsage = createReplayCumulativeUsage();
10706
- const replay = await collectHistoryReplayUpdates({
10707
- sessionId: params.sessionId,
10708
- config,
10709
- records: replayPage.records,
10710
- gaps: sessionData?.historyGaps,
10711
- cumulativeUsage: replayUsage,
10712
- // A resume: the goal restore runs right after this.
10713
- supersedeUnrestorableGoal: true,
10714
- logger: debugLogger7
10715
- });
10716
- replayUpdates = replay.updates;
10717
- copyCumulativeUsage(session.cumulativeUsage, replayUsage);
10718
- if (replay.replayError !== void 0) {
10719
- replayEnvelope = {
10720
- v: LOAD_REPLAY_VERSION,
10721
- updates: replayUpdates,
10722
- partial: true,
10723
- replayError: replay.replayError,
10724
- ...replayPage.hasMore ? { hasMore: true } : {}
10725
- };
10726
- }
10727
- replayEnvelope ??= {
10728
- v: LOAD_REPLAY_VERSION,
10729
- updates: replayUpdates,
10730
- ...replayPage.hasMore ? { hasMore: true } : {}
10731
- };
10732
- }
10733
- replayEnvelope ??= {
10734
- v: LOAD_REPLAY_VERSION,
10735
- updates: replayUpdates
10736
- };
10737
- session.installRewriter();
10738
- session.startCronScheduler();
10739
- } catch (err) {
10740
- return this.cleanupAfterRequestFailure(err, async () => {
10741
- try {
10742
- await this.discardStoredSessionIfCurrent(params.sessionId, session);
10743
- } catch (cleanupError) {
10744
- await this.removeStoredSessionEntry(
10745
- params.sessionId,
10746
- session,
10747
- [cleanupError],
10748
- {
10749
- shutdownConfig: false
10750
- }
10751
- );
10752
- await this.cleanupUnstoredConfig(config);
10753
- }
10754
- });
10755
- }
10756
- }
10757
- await this.#restoreWorktreeOnResume(config, session);
10758
- await this.#restoreBackgroundAgentsOnResume(config, session);
10759
- this.#restoreGoalOnResume(config, session);
10760
11572
  const modesData = this.buildModesData(config);
10761
11573
  const availableModels = this.buildAvailableModels(config);
10762
11574
  const configOptions = this.buildConfigOptions(config);
@@ -10777,6 +11589,7 @@ var QwenAgent = class {
10777
11589
  };
10778
11590
  }
10779
11591
  async unstable_resumeSession(params) {
11592
+ const isChannelSession = isChannelSessionRequest(params);
10780
11593
  const settings = loadSettingsCached(params.cwd);
10781
11594
  const liveSession = this.sessions.get(params.sessionId);
10782
11595
  if (liveSession) {
@@ -10809,18 +11622,25 @@ var QwenAgent = class {
10809
11622
  params.cwd,
10810
11623
  params.mcpServers ?? [],
10811
11624
  settings,
11625
+ isChannelSession,
10812
11626
  params.sessionId,
10813
11627
  true
10814
11628
  );
10815
- let session;
10816
11629
  try {
10817
11630
  await this.ensureAuthenticated(config);
10818
11631
  this.setupFileSystem(config);
10819
- session = await this.createAndStoreSession(
11632
+ await this.createAndStoreSession(
10820
11633
  config,
10821
11634
  settings,
10822
11635
  config.getResumedSessionData(),
10823
- { replayHistory: false }
11636
+ {
11637
+ replayHistory: false,
11638
+ beforeStartPostReplayServices: /* @__PURE__ */ __name(async (createdSession) => {
11639
+ await this.#restoreWorktreeOnResume(config, createdSession);
11640
+ await this.#restoreBackgroundAgentsOnResume(config, createdSession);
11641
+ this.#restoreGoalOnResume(config, createdSession);
11642
+ }, "beforeStartPostReplayServices")
11643
+ }
10824
11644
  );
10825
11645
  } catch (error) {
10826
11646
  return this.cleanupAfterRequestFailure(error, async () => {
@@ -10829,9 +11649,6 @@ var QwenAgent = class {
10829
11649
  }
10830
11650
  });
10831
11651
  }
10832
- await this.#restoreWorktreeOnResume(config, session);
10833
- await this.#restoreBackgroundAgentsOnResume(config, session);
10834
- this.#restoreGoalOnResume(config, session);
10835
11652
  const modesData = this.buildModesData(config);
10836
11653
  const availableModels = this.buildAvailableModels(config);
10837
11654
  const configOptions = this.buildConfigOptions(config);
@@ -11743,7 +12560,21 @@ var QwenAgent = class {
11743
12560
  };
11744
12561
  }
11745
12562
  try {
11746
- const disabled = config.getDisabledSkillNames();
12563
+ const resolved = resolveSkillSettings(
12564
+ loadSettings(this.workspaceCwd(config), {
12565
+ consumeCorruptionEnvVars: false,
12566
+ skipLoadEnvironment: true
12567
+ })
12568
+ );
12569
+ const disablements = new Map(
12570
+ Array.from(config.getDisabledSkillNames(), (name) => {
12571
+ const normalizedName = name.trim().toLowerCase();
12572
+ return [
12573
+ normalizedName,
12574
+ resolved.disablements.get(normalizedName) ?? { reason: "hard" }
12575
+ ];
12576
+ })
12577
+ );
11747
12578
  try {
11748
12579
  await config.getExtensionManager().refreshCache();
11749
12580
  } catch (error) {
@@ -11759,7 +12590,7 @@ var QwenAgent = class {
11759
12590
  const skillsByKey = new Map(
11760
12591
  skills.map((skill) => [
11761
12592
  `${skill.level}:${skill.extensionName ?? ""}:${skill.name}`,
11762
- mapSkillConfigToStatus(skill, disabled, {
12593
+ mapSkillConfigToStatus(skill, disablements, {
11763
12594
  disabled: isInactiveExtensionSkill(skill, inactiveSkillRefs)
11764
12595
  })
11765
12596
  ])
@@ -11780,7 +12611,7 @@ var QwenAgent = class {
11780
12611
  level: "extension",
11781
12612
  extensionName
11782
12613
  },
11783
- disabled,
12614
+ disablements,
11784
12615
  { disabled: true }
11785
12616
  )
11786
12617
  );
@@ -12840,12 +13671,19 @@ var QwenAgent = class {
12840
13671
  }
12841
13672
  case TODO_STOP_GUARD_QUEUE_RELEASE_METHOD: {
12842
13673
  const sessionId = params["sessionId"];
13674
+ const promptId = params["promptId"];
12843
13675
  if (typeof sessionId !== "string" || sessionId.length === 0) {
12844
13676
  throw RequestError.invalidParams(
12845
13677
  void 0,
12846
13678
  "Invalid or missing sessionId"
12847
13679
  );
12848
13680
  }
13681
+ if (typeof promptId !== "string" || promptId.length === 0) {
13682
+ throw RequestError.invalidParams(
13683
+ void 0,
13684
+ "Invalid or missing promptId"
13685
+ );
13686
+ }
12849
13687
  const session = this.sessions.get(sessionId);
12850
13688
  if (!session) {
12851
13689
  throw RequestError.invalidParams(
@@ -12854,7 +13692,7 @@ var QwenAgent = class {
12854
13692
  );
12855
13693
  }
12856
13694
  return {
12857
- released: session.releaseTodoStopGuardQueuedPromptWait()
13695
+ released: session.releaseTodoStopGuardQueuedPromptWait(promptId)
12858
13696
  };
12859
13697
  }
12860
13698
  case "qwen/providers/list": {
@@ -14275,10 +15113,12 @@ var QwenAgent = class {
14275
15113
  }
14276
15114
  }
14277
15115
  const previousCwd = config.getTargetDir();
14278
- if (canonicalPath === previousCwd) {
14279
- return { previousCwd, newCwd: canonicalPath, warnings: [] };
14280
- }
14281
- if (isFolderTrustEnabled(this.settings.merged)) {
15116
+ let trustValidated = false;
15117
+ const validateTrust = /* @__PURE__ */ __name(() => {
15118
+ if (!isFolderTrustEnabled(this.settings.merged)) {
15119
+ trustValidated = true;
15120
+ return;
15121
+ }
14282
15122
  const trustedFolders = loadTrustedFolders();
14283
15123
  if (trustedFolders.isPathTrusted(canonicalPath) !== true) {
14284
15124
  throw new RequestError(
@@ -14287,27 +15127,62 @@ var QwenAgent = class {
14287
15127
  { errorKind: "directory_not_trusted", path: canonicalPath }
14288
15128
  );
14289
15129
  }
15130
+ trustValidated = true;
15131
+ }, "validateTrust");
15132
+ if (canonicalPath !== previousCwd) {
15133
+ validateTrust();
14290
15134
  }
14291
- const warnings = [];
14292
- const relocation = await config.relocateWorkingDirectory(
14293
- canonicalPath,
14294
- canonicalPath,
14295
- { skipProcessChdir: true, skipArtifactMigration: true }
15135
+ const releaseGate = await beginSessionCloseAfterCurrentGate(
15136
+ session,
15137
+ SESSION_DRAIN_TIMEOUT_MS
14296
15138
  );
14297
- if (relocation.memoryRefreshError) {
14298
- warnings.push(
14299
- `Memory refresh failed: ${relocation.memoryRefreshError instanceof Error ? relocation.memoryRefreshError.message : String(relocation.memoryRefreshError)}`
14300
- );
14301
- }
14302
15139
  try {
14303
- await config.getGeminiClient()?.addWorkingDirectoryChangedContext(previousCwd, canonicalPath);
14304
- } catch (error) {
14305
- warnings.push(
14306
- `Model context refresh failed: ${error instanceof Error ? error.message : String(error)}`
15140
+ const settledPreviousCwd = config.getTargetDir();
15141
+ if (canonicalPath === settledPreviousCwd) {
15142
+ return {
15143
+ previousCwd: settledPreviousCwd,
15144
+ newCwd: canonicalPath,
15145
+ warnings: []
15146
+ };
15147
+ }
15148
+ if (!trustValidated) {
15149
+ validateTrust();
15150
+ }
15151
+ session.hardSuspendTodoStopGuard();
15152
+ await waitForSessionDrain(
15153
+ session.waitForActiveTurnsToSettle(),
15154
+ SESSION_DRAIN_TIMEOUT_MS,
15155
+ "close"
15156
+ );
15157
+ const warnings = [];
15158
+ const relocation = await config.relocateWorkingDirectory(
15159
+ canonicalPath,
15160
+ canonicalPath,
15161
+ { skipProcessChdir: true, skipArtifactMigration: true }
14307
15162
  );
15163
+ if (relocation.memoryRefreshError) {
15164
+ warnings.push(
15165
+ `Memory refresh failed: ${relocation.memoryRefreshError instanceof Error ? relocation.memoryRefreshError.message : String(relocation.memoryRefreshError)}`
15166
+ );
15167
+ }
15168
+ try {
15169
+ await config.getGeminiClient()?.addWorkingDirectoryChangedContext(
15170
+ settledPreviousCwd,
15171
+ canonicalPath
15172
+ );
15173
+ } catch (error) {
15174
+ warnings.push(
15175
+ `Model context refresh failed: ${error instanceof Error ? error.message : String(error)}`
15176
+ );
15177
+ }
15178
+ return {
15179
+ previousCwd: settledPreviousCwd,
15180
+ newCwd: canonicalPath,
15181
+ warnings
15182
+ };
15183
+ } finally {
15184
+ releaseGate();
14308
15185
  }
14309
- session.clearTodoStopGuardTrust();
14310
- return { previousCwd, newCwd: canonicalPath, warnings };
14311
15186
  }
14312
15187
  case SERVE_CONTROL_EXT_METHODS.sessionApprovalMode: {
14313
15188
  const sessionId = params["sessionId"];
@@ -14823,147 +15698,82 @@ ${outputText}
14823
15698
  return result;
14824
15699
  }
14825
15700
  case SERVE_CONTROL_EXT_METHODS.workspaceMcpRuntimeAdd: {
14826
- const name = params["name"];
14827
- const config = params["config"];
14828
- const originatorClientId = params["originatorClientId"];
14829
- if (typeof name !== "string" || name.length === 0) {
14830
- throw RequestError.invalidParams(
14831
- void 0,
14832
- "Invalid or missing name"
14833
- );
14834
- }
14835
- if (!isValidServerName(name)) {
14836
- throw RequestError.invalidParams(
14837
- void 0,
14838
- "Server name must be \u2264256 chars, alphanumeric + underscore/hyphen, and not a reserved JS property name"
14839
- );
14840
- }
14841
- if (!config || typeof config !== "object" || Array.isArray(config)) {
14842
- throw RequestError.invalidParams(
14843
- void 0,
14844
- "Invalid or missing config"
14845
- );
14846
- }
14847
- const runtimeClientId = typeof originatorClientId === "string" && originatorClientId.length > 0 ? originatorClientId : "daemon";
14848
- const manager = this.config.getToolRegistry()?.getMcpClientManager();
14849
- if (!manager) {
14850
- throw RequestError.internalError(
14851
- void 0,
14852
- "McpClientManager unavailable on this Config"
14853
- );
14854
- }
14855
- try {
14856
- const {
14857
- trust: _trust,
14858
- authProviderType: _auth,
14859
- includeTools: _inc,
14860
- excludeTools: _exc,
14861
- cwd: _cwd,
14862
- env: _env,
14863
- oauth: _oauth,
14864
- headers: _headers,
14865
- type: _type,
14866
- // Reverse tool channel marker (issue #5626, Phase 2). The parent
14867
- // serve process stamps this on a client-hosted (extension) MCP
14868
- // server's runtime config; it never reaches the transport itself.
14869
- [CLIENT_MCP_OVER_WS_CONFIG_FLAG]: clientMcpOverWs,
14870
- ...safeConfig
14871
- } = config;
14872
- if (clientMcpOverWs === true) {
14873
- safeConfig["type"] = "sdk";
14874
- }
14875
- const result = await manager.addRuntimeMcpServer(
14876
- name,
14877
- safeConfig,
14878
- runtimeClientId
14879
- );
14880
- await Promise.all(
14881
- this.getActiveSessions().map(async (session) => {
14882
- const sessionManager = session.getConfig().getToolRegistry()?.getMcpClientManager();
14883
- if (!sessionManager) return;
14884
- try {
14885
- await sessionManager.addRuntimeMcpServer(
14886
- name,
14887
- safeConfig,
14888
- runtimeClientId
14889
- );
14890
- } catch (sessionErr) {
14891
- debugLogger7.warn(
14892
- `workspaceMcpRuntimeAdd: failed to add runtime MCP server '${name}' to active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
14893
- );
14894
- }
14895
- })
14896
- );
14897
- return result;
14898
- } catch (err) {
14899
- if (err instanceof McpBudgetWouldExceedError) {
14900
- throw new RequestError(-32099, err.message, {
14901
- errorKind: err.code,
14902
- serverName: err.serverName
14903
- });
14904
- }
14905
- if (err instanceof McpServerSpawnFailedError) {
14906
- throw new RequestError(-32099, err.message, {
14907
- errorKind: err.code,
14908
- serverName: err.serverName,
14909
- ...err.details
14910
- });
14911
- }
14912
- if (err instanceof InvalidMcpConfigError) {
14913
- throw new RequestError(-32099, err.message, {
14914
- errorKind: err.code,
14915
- serverName: err.serverName,
14916
- reason: err.reason
14917
- });
14918
- }
14919
- throw err;
14920
- }
15701
+ const request = readRuntimeMcpAddRequest(params);
15702
+ const result = await addRuntimeMcpServer(
15703
+ getRuntimeMcpManager(this.config),
15704
+ request
15705
+ );
15706
+ await Promise.all(
15707
+ this.getActiveSessions().map(async (session) => {
15708
+ const sessionManager = session.getConfig().getToolRegistry()?.getMcpClientManager();
15709
+ if (!sessionManager) return;
15710
+ try {
15711
+ await sessionManager.addRuntimeMcpServer(
15712
+ request.name,
15713
+ request.config,
15714
+ request.runtimeClientId
15715
+ );
15716
+ } catch (sessionErr) {
15717
+ debugLogger7.warn(
15718
+ `workspaceMcpRuntimeAdd: failed to add runtime MCP server '${request.name}' to active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
15719
+ );
15720
+ }
15721
+ })
15722
+ );
15723
+ return result;
14921
15724
  }
14922
15725
  case SERVE_CONTROL_EXT_METHODS.workspaceMcpRuntimeRemove: {
14923
- const name = params["name"];
14924
- const originatorClientId = params["originatorClientId"];
14925
- if (typeof name !== "string" || name.length === 0) {
14926
- throw RequestError.invalidParams(
14927
- void 0,
14928
- "Invalid or missing name"
14929
- );
14930
- }
14931
- if (!isValidServerName(name)) {
14932
- throw RequestError.invalidParams(
14933
- void 0,
14934
- "Server name must be \u2264256 chars, alphanumeric + underscore/hyphen, and not a reserved JS property name"
14935
- );
14936
- }
14937
- const runtimeClientId = typeof originatorClientId === "string" && originatorClientId.length > 0 ? originatorClientId : "daemon";
14938
- const manager = this.config.getToolRegistry()?.getMcpClientManager();
14939
- if (!manager) {
14940
- throw RequestError.internalError(
14941
- void 0,
14942
- "McpClientManager unavailable on this Config"
14943
- );
14944
- }
14945
- const result = await manager.removeRuntimeMcpServer(
14946
- name,
14947
- runtimeClientId
14948
- );
15726
+ const request = readRuntimeMcpRequest(params);
15727
+ const result = await getRuntimeMcpManager(
15728
+ this.config
15729
+ ).removeRuntimeMcpServer(request.name, request.runtimeClientId);
14949
15730
  await Promise.all(
14950
15731
  this.getActiveSessions().map(async (session) => {
14951
15732
  const sessionManager = session.getConfig().getToolRegistry()?.getMcpClientManager();
14952
15733
  if (!sessionManager) return;
14953
15734
  try {
14954
15735
  await sessionManager.removeRuntimeMcpServer(
14955
- name,
14956
- runtimeClientId
15736
+ request.name,
15737
+ request.runtimeClientId
14957
15738
  );
14958
15739
  } catch (sessionErr) {
14959
15740
  debugLogger7.warn(
14960
- `workspaceMcpRuntimeRemove: failed to remove runtime MCP server '${name}' from active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
15741
+ `workspaceMcpRuntimeRemove: failed to remove runtime MCP server '${request.name}' from active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
14961
15742
  );
14962
15743
  }
14963
15744
  })
14964
15745
  );
14965
15746
  return result;
14966
15747
  }
15748
+ case SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd: {
15749
+ const sessionId = params["sessionId"];
15750
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
15751
+ throw RequestError.invalidParams(
15752
+ void 0,
15753
+ "Invalid or missing sessionId"
15754
+ );
15755
+ }
15756
+ const session = this.sessionOrThrow(sessionId);
15757
+ return addRuntimeMcpServer(
15758
+ getRuntimeMcpManager(session.getConfig()),
15759
+ readRuntimeMcpAddRequest(params)
15760
+ );
15761
+ }
15762
+ case SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove: {
15763
+ const sessionId = params["sessionId"];
15764
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
15765
+ throw RequestError.invalidParams(
15766
+ void 0,
15767
+ "Invalid or missing sessionId"
15768
+ );
15769
+ }
15770
+ const session = this.sessionOrThrow(sessionId);
15771
+ const request = readRuntimeMcpRequest(params);
15772
+ const result = await getRuntimeMcpManager(
15773
+ session.getConfig()
15774
+ ).removeRuntimeMcpServer(request.name, request.runtimeClientId);
15775
+ return result;
15776
+ }
14967
15777
  case SERVE_CONTROL_EXT_METHODS.workspaceExtensionsRefresh: {
14968
15778
  const sessionId = params["sessionId"];
14969
15779
  const session = this.sessionOrThrow(sessionId);
@@ -15736,6 +16546,7 @@ ${outputText}
15736
16546
  [],
15737
16547
  settings,
15738
16548
  void 0,
16549
+ void 0,
15739
16550
  false,
15740
16551
  {
15741
16552
  skipMcpDiscovery: true,
@@ -15777,8 +16588,9 @@ ${outputText}
15777
16588
  throw error;
15778
16589
  }
15779
16590
  }
15780
- async newSessionConfig(cwd, mcpServers, settings, sessionId, resume, initializeOptions = {}, chatRecording) {
16591
+ async newSessionConfig(cwd, mcpServers, settings, isChannelSession, sessionId, resume, initializeOptions = {}, chatRecording) {
15781
16592
  try {
16593
+ this.assertManagedSessionAdmission();
15782
16594
  return await this.runWithPinnedRuntimeBaseDir(settings, cwd, async () => {
15783
16595
  await this.retryPendingConfigCleanup(
15784
16596
  Storage.getRuntimeBaseDir(),
@@ -15788,6 +16600,7 @@ ${outputText}
15788
16600
  cwd,
15789
16601
  mcpServers,
15790
16602
  settings,
16603
+ isChannelSession,
15791
16604
  sessionId,
15792
16605
  resume,
15793
16606
  initializeOptions,
@@ -15804,7 +16617,7 @@ ${outputText}
15804
16617
  throw error;
15805
16618
  }
15806
16619
  }
15807
- async newSessionConfigInRuntimeContext(cwd, mcpServers, settings, sessionId, resume, initializeOptions = {}, chatRecording) {
16620
+ async newSessionConfigInRuntimeContext(cwd, mcpServers, settings, isChannelSession, sessionId, resume, initializeOptions = {}, chatRecording) {
15808
16621
  const sessionMcpServers = {};
15809
16622
  for (const server of mcpServers) {
15810
16623
  const stdioServer = toStdioServer(server);
@@ -15856,7 +16669,14 @@ ${outputText}
15856
16669
  continue;
15857
16670
  }
15858
16671
  }
15859
- const mergedSettings = settings.merged;
16672
+ const mergedSettings = {
16673
+ ...settings.merged,
16674
+ experimental: {
16675
+ ...settings.merged.experimental,
16676
+ sessionWriterLease: this.sessionWriterLeaseEnabledAtStartup,
16677
+ ...isChannelSession ? { cron: false } : {}
16678
+ }
16679
+ };
15860
16680
  const sessionArg = resume === true ? { resume: sessionId, sessionId: void 0 } : { sessionId, resume: void 0 };
15861
16681
  const argvForSession = {
15862
16682
  ...this.argv,
@@ -15891,6 +16711,21 @@ ${outputText}
15891
16711
  buildDisabledSkillNamesProvider(settings),
15892
16712
  sessionMcpServers
15893
16713
  );
16714
+ if (chatRecording !== false) {
16715
+ this.initializingConfigs.add(config);
16716
+ }
16717
+ try {
16718
+ this.assertManagedSessionAdmission();
16719
+ if (this.isTrustedManagedParent()) {
16720
+ config.setSessionWriterReclaimPolicy("never");
16721
+ config.setSessionWriterTakeoverPolicy("certified");
16722
+ }
16723
+ } catch (error) {
16724
+ return this.cleanupAfterRequestFailure(
16725
+ error,
16726
+ () => this.cleanupUnstoredConfig(config)
16727
+ );
16728
+ }
15894
16729
  if (!initializeOptions.skipFileCheckpointing && typeof config.enableFileCheckpointing === "function") {
15895
16730
  config.enableFileCheckpointing();
15896
16731
  }
@@ -15931,6 +16766,7 @@ ${outputText}
15931
16766
  // (the daemon only adds SDK-type runtime servers for client MCP).
15932
16767
  sendSdkMcpMessage: this.buildClientMcpSender(wiredSessionId)
15933
16768
  });
16769
+ this.assertManagedSessionAdmission();
15934
16770
  } catch (error) {
15935
16771
  return this.cleanupAfterRequestFailure(
15936
16772
  error,
@@ -15991,17 +16827,20 @@ ${outputText}
15991
16827
  config.setFileSystemService(acpFileSystemService);
15992
16828
  }
15993
16829
  async createAndStoreSession(config, settings, sessionData, options = {}) {
16830
+ this.assertManagedSessionAdmission();
15994
16831
  const sessionId = config.getSessionId();
15995
16832
  const geminiClient = config.getGeminiClient();
15996
16833
  const needsInitialize = !geminiClient.isInitialized();
15997
16834
  if (needsInitialize) {
15998
16835
  await geminiClient.initialize();
15999
16836
  }
16837
+ this.assertManagedSessionAdmission();
16000
16838
  if (this.sessions.has(sessionId)) {
16001
16839
  throw new Error(`Session ${sessionId} is already active.`);
16002
16840
  }
16003
16841
  const session = new Session(sessionId, config, this.connection, settings);
16004
16842
  this.sessions.set(sessionId, session);
16843
+ this.initializingConfigs.delete(config);
16005
16844
  try {
16006
16845
  if (sessionData?.fileHistorySnapshots?.length) {
16007
16846
  config.getFileHistoryService().restoreFromSnapshots(sessionData.fileHistorySnapshots);
@@ -16015,10 +16854,9 @@ ${outputText}
16015
16854
  sessionData.historyGaps
16016
16855
  );
16017
16856
  }
16018
- if (options.startPostReplayServices !== false) {
16019
- session.installRewriter();
16020
- session.startCronScheduler();
16021
- }
16857
+ await options.beforeStartPostReplayServices?.(session);
16858
+ session.installRewriter();
16859
+ session.startCronScheduler();
16022
16860
  setTimeout(() => {
16023
16861
  void session.sendAvailableCommandsUpdate();
16024
16862
  }, 0);