@qwen-code/qwen-code 0.21.1-simplify-system-prompt.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (405) hide show
  1. package/bundled/qc-helper/docs/configuration/model-providers.md +2 -0
  2. package/bundled/qc-helper/docs/configuration/settings.md +38 -28
  3. package/bundled/qc-helper/docs/features/channels/_meta.ts +1 -0
  4. package/bundled/qc-helper/docs/features/channels/github.md +107 -0
  5. package/bundled/qc-helper/docs/features/channels/overview.md +61 -6
  6. package/bundled/qc-helper/docs/features/code-review.md +1 -1
  7. package/bundled/qc-helper/docs/features/hooks.md +52 -15
  8. package/bundled/qc-helper/docs/features/mcp.md +9 -1
  9. package/bundled/qc-helper/docs/features/scheduled-tasks.md +3 -1
  10. package/bundled/qc-helper/docs/features/sub-agents.md +20 -0
  11. package/bundled/qc-helper/docs/qwen-serve.md +4 -2
  12. package/bundled/qc-helper/docs/reference/keyboard-shortcuts.md +2 -2
  13. package/bundled/qc-helper/docs/support/troubleshooting.md +2 -1
  14. package/bundled/review/DESIGN.md +19 -0
  15. package/bundled/review/SKILL.md +120 -61
  16. package/chunks/MaxSizedBox-VI3ROJJA.js +84 -0
  17. package/chunks/{StandaloneSessionPicker-O6RKBPU4.js → StandaloneSessionPicker-LYXKD2EV.js} +66 -68
  18. package/chunks/{acp-startup-profiler-RV3IV562.js → acp-startup-profiler-DFVPFQ6C.js} +2 -2
  19. package/chunks/{acpAgent-HYFVXVDR.js → acpAgent-WN5SRDQO.js} +1317 -542
  20. package/chunks/agent-K6ECSM64.js +80 -0
  21. package/chunks/agent-headless-NO4Y2HOE.js +74 -0
  22. package/chunks/{anthropicContentGenerator-LXUXMOE7.js → anthropicContentGenerator-V2QOGVYD.js} +61 -20
  23. package/chunks/{artifact-tool-Y5T7GG7F.js → artifact-tool-6K6U7XYJ.js} +4 -4
  24. package/chunks/{askUserQuestion-2H6747FR.js → askUserQuestion-GD2IJJ7I.js} +4 -4
  25. package/chunks/bridge-3KJEWDNE.js +90 -0
  26. package/chunks/{build-RV63TIRH.js → build-S6DO7LMM.js} +1 -1
  27. package/chunks/{ca-25EDXPFZ.js → ca-6W3SK7OQ.js} +6 -1
  28. package/chunks/{channel-management-service-G74LFADV.js → channel-management-service-XR7GZSWF.js} +4 -4
  29. package/chunks/channel-settings-store-HW4FXXUA.js +87 -0
  30. package/chunks/{channel-worker-group-PTJIJSKC.js → channel-worker-group-XDPTDWTX.js} +9 -5
  31. package/chunks/{channel-worker-manager-WIMGM2FD.js → channel-worker-manager-YYEHVRRE.js} +9 -5
  32. package/chunks/{channel-worker-supervisor-KUFTR6P5.js → channel-worker-supervisor-74HTWA2G.js} +5 -4
  33. package/chunks/{chunk-M5JM7OSF.js → chunk-2DN4J57Y.js} +2 -3
  34. package/chunks/{chunk-WDSWXQU3.js → chunk-2FAK6PNM.js} +2 -2
  35. package/chunks/{chunk-BPJSQIJX.js → chunk-2J3OJGTL.js} +0 -2
  36. package/chunks/{chunk-EPDRMGT4.js → chunk-2LKVPASC.js} +4 -28
  37. package/chunks/{chunk-PWTZEM3C.js → chunk-2LQTH543.js} +3 -37
  38. package/chunks/{chunk-PANH4R3B.js → chunk-2N7CODY5.js} +18 -12
  39. package/chunks/{chunk-ER5LWJR6.js → chunk-2XSLTRFZ.js} +3 -3
  40. package/chunks/{chunk-6PSLCFQ2.js → chunk-3EFXSQCM.js} +18 -9
  41. package/chunks/{chunk-HIJQF5B5.js → chunk-3L2SPEBH.js} +1 -1
  42. package/chunks/{chunk-BIQWWWJN.js → chunk-4G2BISNC.js} +1 -1
  43. package/chunks/{chunk-B4UMZKMU.js → chunk-52ZSWYEG.js} +1 -1
  44. package/chunks/{chunk-YAF5VNU7.js → chunk-5KTQXHPY.js} +4 -5
  45. package/chunks/{chunk-2YZJCM5T.js → chunk-5MKRTI4T.js} +4 -4
  46. package/chunks/{chunk-DHHOYAPR.js → chunk-5TBMQLGG.js} +7 -7
  47. package/chunks/{chunk-A4UCTEB5.js → chunk-5WV5S2GT.js} +0 -1
  48. package/chunks/{chunk-FY3M44RD.js → chunk-5YKDXHUY.js} +3 -3
  49. package/chunks/{chunk-TF2X2WCT.js → chunk-5ZF5XXTS.js} +2 -2
  50. package/chunks/{chunk-K4XWPEWB.js → chunk-64LQLPL7.js} +4 -33
  51. package/chunks/{chunk-B7QDM6Z7.js → chunk-657BH7VM.js} +2 -2
  52. package/chunks/{chunk-5THCYPLO.js → chunk-65PQENQP.js} +14 -7
  53. package/chunks/{chunk-J6D3VXCC.js → chunk-6PE7N3A4.js} +17 -6
  54. package/chunks/{chunk-JZA3JUDJ.js → chunk-6QIGFD5W.js} +1 -1
  55. package/chunks/{chunk-Z5BLYMZM.js → chunk-6RPMI2AB.js} +6 -6
  56. package/chunks/{chunk-OHNBB4XR.js → chunk-75GFAX4R.js} +1 -1
  57. package/chunks/{chunk-BO4XCS7P.js → chunk-75MIQ3LV.js} +20 -85
  58. package/chunks/{chunk-52O2CIUL.js → chunk-7AEJDLRA.js} +130 -5
  59. package/chunks/{chunk-BYFNTGKI.js → chunk-7BAU433D.js} +2287 -941
  60. package/chunks/{chunk-ZE5WPL4I.js → chunk-7DXQIJID.js} +3 -3
  61. package/chunks/{chunk-ML52PL6O.js → chunk-7I5GTCT4.js} +483 -248
  62. package/chunks/{chunk-A5L3JMUA.js → chunk-7XATOOE7.js} +18 -4
  63. package/chunks/{chunk-C3NS4F2Q.js → chunk-A2D5BAVP.js} +1 -1
  64. package/chunks/{chunk-5I2IWRSH.js → chunk-A3NDJ5SB.js} +2 -2
  65. package/chunks/{chunk-2JM6GZ5D.js → chunk-A4COXFB3.js} +8 -13
  66. package/chunks/{chunk-CC4N4M36.js → chunk-AQIDMUGU.js} +1 -1
  67. package/chunks/{chunk-PJIZUQVC.js → chunk-AZQ3DT76.js} +2 -2
  68. package/chunks/{chunk-UH3WSE5L.js → chunk-B4AJNNOL.js} +1 -6
  69. package/chunks/{chunk-BJX6ZSUK.js → chunk-BCZFQXWK.js} +2 -2
  70. package/chunks/{chunk-SRZ6DXVG.js → chunk-BGTQCTQW.js} +44 -136
  71. package/chunks/{chunk-PSWQZHEA.js → chunk-BMFALVGQ.js} +1 -1
  72. package/chunks/{chunk-XHRTVPG2.js → chunk-BNWB5CYE.js} +7 -7
  73. package/chunks/{chunk-P5V4T7NK.js → chunk-BPZKP57P.js} +11 -3
  74. package/chunks/{chunk-2OM7GEXO.js → chunk-CAPPWD3X.js} +3 -3
  75. package/chunks/{chunk-LNURQEMZ.js → chunk-CQL64ESB.js} +7 -7
  76. package/chunks/{chunk-TOFQCPDC.js → chunk-CVHIL5IG.js} +4 -5
  77. package/chunks/{chunk-XVNQMZ2I.js → chunk-DGEIYUC3.js} +0 -1
  78. package/chunks/{chunk-BPZALHVR.js → chunk-DI35ZN7T.js} +1 -1
  79. package/chunks/{chunk-SQBYH7PX.js → chunk-DZLYR4U3.js} +1 -1
  80. package/chunks/{chunk-JALU3ZDU.js → chunk-EIF3FXTB.js} +117 -24
  81. package/chunks/{chunk-TQCBGUHN.js → chunk-EJGJIBRS.js} +5 -5
  82. package/chunks/{chunk-5U4IPFBR.js → chunk-EVKE2FZL.js} +4 -4
  83. package/chunks/{chunk-OKY7HXPG.js → chunk-FNMZK765.js} +2 -2
  84. package/chunks/{chunk-KU5XMLDK.js → chunk-FTD6DP4T.js} +3 -1
  85. package/chunks/chunk-FYJ7W2PI.js +194 -0
  86. package/chunks/{chunk-L5UHQJTJ.js → chunk-GATT5TKW.js} +1 -1
  87. package/chunks/{chunk-MVS3NS2N.js → chunk-GEBV2JGB.js} +28 -5
  88. package/chunks/{chunk-VAK25FTU.js → chunk-GKX7E4CO.js} +1 -1
  89. package/chunks/{chunk-LS77BEZP.js → chunk-GLCZKT5V.js} +1 -5
  90. package/chunks/{chunk-N3FAY5CM.js → chunk-GNR2RNMP.js} +157 -4
  91. package/chunks/{chunk-YH6G52F2.js → chunk-GXIJHV66.js} +4 -4
  92. package/chunks/{chunk-HV3G62R6.js → chunk-GZ3RCT54.js} +1 -1
  93. package/chunks/{chunk-QY5MMZ6O.js → chunk-HMRM2A3U.js} +3 -3
  94. package/chunks/chunk-HV26XH34.js +319 -0
  95. package/chunks/{chunk-M4UKFCZ2.js → chunk-J7OACQDE.js} +193 -155
  96. package/chunks/{chunk-3HBZKBMQ.js → chunk-JFMA7Y5M.js} +5 -5
  97. package/chunks/{chunk-OJGCZBB7.js → chunk-JHNRZMHI.js} +41 -36
  98. package/chunks/{chunk-63P4EL5V.js → chunk-JMONIXMJ.js} +1 -1
  99. package/chunks/{chunk-L26JL52R.js → chunk-JSD33JG6.js} +47 -64
  100. package/chunks/{chunk-KIUFNBHR.js → chunk-JTV5K7NH.js} +1 -1
  101. package/chunks/{chunk-PHVR5UUY.js → chunk-JX27F6QS.js} +1 -1
  102. package/chunks/chunk-JYBU6YUE.js +378 -0
  103. package/chunks/{chunk-A6UO2C7C.js → chunk-KAMYKP7E.js} +167 -81
  104. package/chunks/{chunk-LG4GZIVV.js → chunk-KCO4FLFJ.js} +4 -4
  105. package/chunks/{chunk-2W3OOD4W.js → chunk-L55JWS76.js} +6 -3
  106. package/chunks/{chunk-RHLZR4E5.js → chunk-LGAOC3ZS.js} +1 -1
  107. package/chunks/{chunk-DM22XS4K.js → chunk-LO4ROVP4.js} +261 -15
  108. package/chunks/{chunk-NH6KE4JX.js → chunk-LW3RFMG7.js} +3 -3
  109. package/chunks/{chunk-J56UI34H.js → chunk-M7OONWYU.js} +2 -2
  110. package/chunks/{chunk-V6VRAM7B.js → chunk-MHAIJPTD.js} +12 -12
  111. package/chunks/{chunk-FODK6UMO.js → chunk-MPHPFVKK.js} +0 -2
  112. package/chunks/{chunk-LZEMEFKY.js → chunk-MR5EAQ5M.js} +1 -1
  113. package/chunks/{chunk-JESCGQM3.js → chunk-NAVJD2PQ.js} +8 -7
  114. package/chunks/{chunk-H5FFA6TH.js → chunk-NOKIVHOL.js} +16 -3
  115. package/chunks/{chunk-6OUGMXDC.js → chunk-NWNEANAT.js} +7 -7
  116. package/chunks/{chunk-B6ZJ7SI6.js → chunk-OCESJA77.js} +391 -328
  117. package/chunks/chunk-OCPBI7J5.js +18 -0
  118. package/chunks/{chunk-E5TUC6CA.js → chunk-OKF7JF3R.js} +3 -3
  119. package/chunks/{chunk-2Q3OT4OV.js → chunk-P4WOAOJW.js} +141 -64
  120. package/chunks/{chunk-4M377AZG.js → chunk-PB3MBFKG.js} +6 -6
  121. package/chunks/{chunk-QPDRAXDJ.js → chunk-PLDQBIO6.js} +1 -1
  122. package/chunks/{chunk-FNQ6T3CV.js → chunk-PONHVBRT.js} +10 -7
  123. package/chunks/{chunk-RWS5VYWC.js → chunk-PT722TDT.js} +267 -378
  124. package/chunks/chunk-Q43KPN7X.js +2196 -0
  125. package/chunks/{chunk-VDDGDZMA.js → chunk-QHWCP53L.js} +14 -7
  126. package/chunks/{chunk-SASBXAQL.js → chunk-QIZKCVM3.js} +4 -4
  127. package/chunks/{chunk-32MVHM4T.js → chunk-RCUQIPTN.js} +1 -1
  128. package/chunks/{chunk-6FGBXPWM.js → chunk-RPLGZJV2.js} +38 -44
  129. package/chunks/{chunk-3IXOIAKE.js → chunk-S4WJVPZW.js} +18 -6
  130. package/chunks/{chunk-6AM5D4ME.js → chunk-S6LOFUVP.js} +0 -12
  131. package/chunks/{chunk-INADJJGW.js → chunk-S7W2GKIO.js} +0 -2
  132. package/chunks/{chunk-MUP3T3AD.js → chunk-SGFT55XI.js} +1 -35
  133. package/chunks/{chunk-VYPFXUCB.js → chunk-SZ3KHTDR.js} +1 -1
  134. package/chunks/chunk-T26EAKDL.js +13 -0
  135. package/chunks/{chunk-3MSHSCSN.js → chunk-T2QMKU3R.js} +79 -1
  136. package/chunks/{chunk-VFSJ5VRH.js → chunk-T3O2B4XO.js} +3 -3
  137. package/chunks/{chunk-MSLKI6C2.js → chunk-T4TXDL7G.js} +32 -21
  138. package/chunks/{chunk-E5WH5O3C.js → chunk-TBBV36Y4.js} +4 -4
  139. package/chunks/{chunk-VV6XU5L7.js → chunk-TCIFAA7K.js} +16 -11
  140. package/chunks/{chunk-DN6ZX5AY.js → chunk-TDL6LB4K.js} +46 -11
  141. package/chunks/{chunk-W4CQXHT6.js → chunk-TFRMVU6R.js} +1 -1
  142. package/chunks/{chunk-GDIPH4JY.js → chunk-TV64SXKD.js} +6 -6
  143. package/chunks/{chunk-FQK6JAFG.js → chunk-U3E3UQAA.js} +4 -4
  144. package/chunks/{chunk-7FZEBPKS.js → chunk-UBEPNVDI.js} +23 -18
  145. package/chunks/{chunk-NL7LTRLR.js → chunk-UHUSJ6X7.js} +29 -68
  146. package/chunks/{chunk-ZOIFNCKL.js → chunk-UPUG4GXM.js} +3 -23
  147. package/chunks/{chunk-6GMVPFB2.js → chunk-UWMLWVCA.js} +19 -6
  148. package/chunks/{chunk-U7TXFVUN.js → chunk-VCPIZRYH.js} +118 -95
  149. package/chunks/{chunk-LNARWLZQ.js → chunk-VWOOBLTY.js} +2 -2
  150. package/chunks/{chunk-I7XZ3RY5.js → chunk-VYOXCEPJ.js} +1 -1
  151. package/chunks/{chunk-USTWD7QV.js → chunk-W4MIWP6M.js} +26 -16
  152. package/chunks/{chunk-DLWL3Z7A.js → chunk-WBSMNTSV.js} +3 -3
  153. package/chunks/{chunk-G4WFQUYQ.js → chunk-WUZ7H6DP.js} +1 -1
  154. package/chunks/{chunk-2JZBVYTU.js → chunk-WZRWHXFE.js} +1 -8
  155. package/chunks/{chunk-DM4Q4JJH.js → chunk-X5WNMMIA.js} +22506 -33611
  156. package/chunks/{chunk-MK7VQDN3.js → chunk-XBYYDKAZ.js} +7 -6
  157. package/chunks/{chunk-COH43MRJ.js → chunk-XCGIMOLN.js} +27 -1
  158. package/chunks/{chunk-BRRAJXPA.js → chunk-XFZYFU3I.js} +1 -1
  159. package/chunks/{chunk-3QMGYBFN.js → chunk-XWWKIXVD.js} +1 -80
  160. package/chunks/{chunk-3SJ43L4W.js → chunk-XZC5VLBZ.js} +2 -0
  161. package/chunks/{chunk-UUUTRMI2.js → chunk-Y4IHBGBP.js} +1 -1
  162. package/chunks/{chunk-PR75REBZ.js → chunk-Y6AXW2OG.js} +12 -82
  163. package/chunks/{chunk-IPUUTYMV.js → chunk-YDLJGZHL.js} +1 -1
  164. package/chunks/{chunk-3JAQDSXN.js → chunk-YGF33UXG.js} +70 -8
  165. package/chunks/chunk-Z4X5MTRT.js +133 -0
  166. package/chunks/{chunk-UW5EOVUN.js → chunk-ZBVS26BY.js} +4 -4
  167. package/chunks/{chunk-ZD6UTE4A.js → chunk-ZHBO7WVX.js} +1 -1
  168. package/chunks/{chunk-HTO4JFDZ.js → chunk-ZPJWUGCS.js} +0 -1
  169. package/chunks/{chunk-66RMLJHC.js → chunk-ZURDMIDR.js} +355 -143
  170. package/chunks/{computer-use-DOFAHZAB.js → computer-use-ZTIDHMMA.js} +48 -50
  171. package/chunks/{config-utils-VFQXVGNR.js → config-utils-NYSXDMEQ.js} +4 -4
  172. package/chunks/contextCommand-2PIEU37Z.js +79 -0
  173. package/chunks/core-runtime-3XEYLQFK.js +133 -0
  174. package/chunks/{create-sub-session-7543K2QA.js → create-sub-session-R76FVXCI.js} +45 -47
  175. package/chunks/{create-sub-session-IWW2IZ2T.js → create-sub-session-SBYUMSSS.js} +3 -3
  176. package/chunks/{cron-create-YIID5XAW.js → cron-create-2QK6TCEC.js} +6 -6
  177. package/chunks/{cron-delete-ZVHYCEP2.js → cron-delete-FDCDFYMG.js} +5 -5
  178. package/chunks/{cron-list-XEGS463Q.js → cron-list-XN3WVBTP.js} +6 -6
  179. package/chunks/{daemon-VOMQW7KZ.js → daemon-Q2AB5Z23.js} +167 -15
  180. package/chunks/daemon-status-provider-3XJI6CAL.js +89 -0
  181. package/chunks/daemon-trust-policy-ILUDTLHD.js +84 -0
  182. package/chunks/daemon-trust-policy-monitor-HS3PKKRO.js +171 -0
  183. package/chunks/{de-HGRCYDEJ.js → de-SY6O76BF.js} +6 -1
  184. package/chunks/deferred-core-runtime-X4QV662U.js +88 -0
  185. package/chunks/dist-BSTVRPMT.js +4227 -0
  186. package/chunks/{dist-NNVBBOGU.js → dist-DOLYHMXE.js} +2 -2
  187. package/chunks/{dist-RTJFMNEZ.js → dist-HVRQ2CFL.js} +271 -11
  188. package/chunks/{dist-ANLAT3GS.js → dist-IXQEQWRG.js} +2 -1
  189. package/chunks/{dist-BRB6EXK4.js → dist-SSU66DM4.js} +3 -3
  190. package/chunks/{dist-KTYYJ2C5.js → dist-SV7Q3AWJ.js} +1 -1
  191. package/chunks/{dist-K6Y4E7FX.js → dist-YGBBMK3Z.js} +1 -1
  192. package/chunks/earlyInputCapture-XKLZT7ZD.js +81 -0
  193. package/chunks/{edit-RIEOJWKB.js → edit-HHGIOTQ2.js} +47 -49
  194. package/chunks/{en-MTWBNGDO.js → en-NBK3JKCE.js} +9 -1
  195. package/chunks/{enter-worktree-OGK5FQ3R.js → enter-worktree-ZN7PUQ46.js} +47 -49
  196. package/chunks/{enterPlanMode-IWZYALIB.js → enterPlanMode-EIFIDSIV.js} +47 -49
  197. package/chunks/{environment-VZ7BRI4Q.js → environment-XXQ75D2Q.js} +47 -49
  198. package/chunks/errors-4GMVU7CK.js +87 -0
  199. package/chunks/esm-K5FARBNI.js +5548 -0
  200. package/chunks/{exit-worktree-4TEYVIVP.js → exit-worktree-GXMI4ATY.js} +47 -49
  201. package/chunks/exitPlanMode-34UVY7M6.js +72 -0
  202. package/chunks/{fast-path-HYE7IFEV.js → fast-path-VPIVA7L6.js} +13 -3
  203. package/chunks/{fr-45RLL55O.js → fr-4KG5V7UT.js} +6 -1
  204. package/chunks/{gemini-NGRQX3YJ.js → gemini-4BWIK4WD.js} +103 -103
  205. package/chunks/{geminiContentGenerator-FQHPFZSR.js → geminiContentGenerator-3XVV5MSS.js} +7 -7
  206. package/chunks/{getMachineId-bsd-V7W3GODC.js → getMachineId-bsd-FG7IUY6U.js} +1 -1
  207. package/chunks/{getMachineId-darwin-TDO75DQP.js → getMachineId-darwin-GLCJI2RA.js} +1 -1
  208. package/chunks/{getMachineId-linux-TF43WQT2.js → getMachineId-linux-O6OPPAKO.js} +1 -1
  209. package/chunks/{getMachineId-unsupported-ZGUO3TXT.js → getMachineId-unsupported-S6CKYVGC.js} +1 -1
  210. package/chunks/{getMachineId-win-ECFYZZFQ.js → getMachineId-win-X5SRNEH7.js} +1 -1
  211. package/chunks/{glob-FRTM3X2E.js → glob-TZ2ABCJG.js} +47 -49
  212. package/chunks/{grep-RKWVROCW.js → grep-BEF463NA.js} +49 -50
  213. package/chunks/handleAutoUpdate-L6ERF36Y.js +80 -0
  214. package/chunks/i18n-FMM5FDXR.js +96 -0
  215. package/chunks/{image-gen-WIEM7KZA.js → image-gen-HHVLF7HS.js} +12 -12
  216. package/chunks/initializer-625TIAIO.js +85 -0
  217. package/chunks/installationInfo-6AM4I2Y3.js +79 -0
  218. package/chunks/{ja-B7DF7DFG.js → ja-F3GSQXMF.js} +6 -1
  219. package/chunks/{keychain-token-storage-MDTG3WRM.js → keychain-token-storage-72IYCAZV.js} +3 -3
  220. package/chunks/lib-RUF3WZA6.js +9 -0
  221. package/chunks/list-L2GA674Y.js +88 -0
  222. package/chunks/{list-agents-5KJJHR6I.js → list-agents-R6KDXQR3.js} +3 -3
  223. package/chunks/loadedSettingsAdapter-SPUTNKAV.js +82 -0
  224. package/chunks/{loggingContentGenerator-WGM27QAW.js → loggingContentGenerator-LKOF7XI7.js} +31 -30
  225. package/chunks/{loop-wakeup-FXKNNYSY.js → loop-wakeup-3IQKCYAH.js} +7 -7
  226. package/chunks/{ls-NTK6VOQJ.js → ls-DKZ37A7N.js} +5 -5
  227. package/chunks/{lsp-2JI24STP.js → lsp-QNWN7KN3.js} +3 -3
  228. package/chunks/{managed-npm-update-JQ2CG3RH.js → managed-npm-update-ACQGGIN5.js} +46 -48
  229. package/chunks/mcp-SZLHKFJW.js +82 -0
  230. package/chunks/{monitor-7FEWXX5F.js → monitor-DF52UVHI.js} +47 -49
  231. package/chunks/nonInteractiveCli-5T7KYKLK.js +144 -0
  232. package/chunks/{notebook-edit-JGJV2K6J.js → notebook-edit-FCWS4XVN.js} +47 -49
  233. package/chunks/{openaiContentGenerator-JPVXDTAO.js → openaiContentGenerator-7LDK3DCJ.js} +25 -27
  234. package/chunks/pidfile-6ERW3DF4.js +85 -0
  235. package/chunks/process-registry-2CHQBXH5.js +157 -0
  236. package/chunks/{processUtils-V2LCK6T6.js → processUtils-COKZAMUP.js} +2 -2
  237. package/chunks/{pt-22Q3FP73.js → pt-EQ33KWEN.js} +6 -1
  238. package/chunks/{qwenContentGenerator-TICV2W2Z.js → qwenContentGenerator-TKWUMR7N.js} +51 -53
  239. package/chunks/{qwenOAuth2-XGFI5XJG.js → qwenOAuth2-7HMU47SF.js} +10 -10
  240. package/chunks/read-file-X6DRC574.js +29 -0
  241. package/chunks/{read-mcp-resource-4DKQWGHD.js → read-mcp-resource-GFTWYXMK.js} +4 -4
  242. package/chunks/{record-artifact-RQKFYO5B.js → record-artifact-XAMSFSW4.js} +3 -3
  243. package/chunks/resumeHistoryUtils-PFPM2GWM.js +90 -0
  244. package/chunks/ripGrep-OWV2IVJC.js +72 -0
  245. package/chunks/{ru-FZCNZHDC.js → ru-7OZAUKGG.js} +6 -1
  246. package/chunks/{run-qwen-serve-3VCV4I7E.js → run-qwen-serve-TSTCO4XE.js} +917 -249
  247. package/chunks/{runtime-AXJWIEDU.js → runtime-DAUPSUKI.js} +55 -57
  248. package/chunks/{scheduler-RS2I6RU5.js → scheduler-KMADMT26.js} +45 -47
  249. package/chunks/{sdk-exporters-grpc-AK3LGHNO.js → sdk-exporters-grpc-54L4LS5L.js} +4 -4
  250. package/chunks/{sdk-exporters-http-FS6ZV7MF.js → sdk-exporters-http-WO556XNU.js} +7 -7
  251. package/chunks/{sdk-impl-7FZSCSXB.js → sdk-impl-LPAVACSF.js} +10 -10
  252. package/chunks/{send-message-Q6OOR6BR.js → send-message-SAWK4DZX.js} +6 -6
  253. package/chunks/serve-NNRWS6F4.js +88 -0
  254. package/chunks/{server-HRZ23U7M.js → server-WEH7DVCH.js} +3304 -842
  255. package/chunks/{session-7XHZKTVV.js → session-WXC56V2I.js} +94 -94
  256. package/chunks/{settings-7ZGZDXAS.js → settings-DJDXFDZ3.js} +54 -56
  257. package/chunks/shell-JN5VRQXD.js +82 -0
  258. package/chunks/{skill-LIWXNLDW.js → skill-SGXPKJCS.js} +20 -22
  259. package/chunks/skill-settings-VJ5PDMZI.js +90 -0
  260. package/chunks/spawnChannel-ETMJW7YX.js +81 -0
  261. package/chunks/standalone-update-MK3Z7KBI.js +91 -0
  262. package/chunks/{startInteractiveUI-IW3CSKHA.js → startInteractiveUI-ZCGIXPGT.js} +715 -373
  263. package/chunks/{syntheticOutput-I3757IWH.js → syntheticOutput-355CB6CJ.js} +4 -4
  264. package/chunks/{task-create-N7WQSGYA.js → task-create-INGWNUG4.js} +10 -10
  265. package/chunks/{task-list-FOPULZEP.js → task-list-5XNNGTF4.js} +7 -7
  266. package/chunks/{task-stop-H6RHXFVQ.js → task-stop-4ROAOBXH.js} +3 -3
  267. package/chunks/{task-update-M57TFZJT.js → task-update-CRK5VWWZ.js} +10 -10
  268. package/chunks/{team-create-O2FROQ4R.js → team-create-QQGAJG7P.js} +49 -51
  269. package/chunks/{team-delete-QE2UXJL7.js → team-delete-S2RCXA4P.js} +7 -7
  270. package/chunks/{team-plan-approval-Q6WDBXTQ.js → team-plan-approval-RT7Q5R6O.js} +47 -49
  271. package/chunks/theme-manager-EEWIQJ7J.js +76 -0
  272. package/chunks/{todoWrite-VQ7FKOHL.js → todoWrite-7WM3VDMY.js} +7 -7
  273. package/chunks/{tool-search-APECNQ3Z.js → tool-search-Z3Z4AYKP.js} +19 -21
  274. package/chunks/total-session-admission-44JKRWQD.js +84 -0
  275. package/chunks/{tree-sitter-FS4VPMZA.js → tree-sitter-4D7QS7F6.js} +1 -1
  276. package/chunks/{tree-sitter-bash-6B46JJCV.js → tree-sitter-bash-VEJGF5XF.js} +1 -1
  277. package/chunks/trustedFolders-X2JEIO57.js +94 -0
  278. package/chunks/{update-relaunch-ON5MDJQG.js → update-relaunch-VWNPYDIP.js} +5 -5
  279. package/chunks/updateCheck-KAQH67DV.js +91 -0
  280. package/chunks/useAutoAcceptIndicator-JH6BCF7S.js +92 -0
  281. package/chunks/{validateNonInterActiveAuth-JBLKBKRD.js → validateNonInterActiveAuth-GIUJ2UFS.js} +88 -88
  282. package/chunks/{version-LTNUBQJY.js → version-BGLYIJUY.js} +1 -1
  283. package/chunks/{web-fetch-L5UTI53V.js → web-fetch-OTDU4VQF.js} +19 -21
  284. package/chunks/{web-search-KM33JOS3.js → web-search-FP6SIHPR.js} +13 -13
  285. package/chunks/{workflow-K7FAWV77.js → workflow-YCIVBYSB.js} +48 -50
  286. package/chunks/workspace-providers-status-S35YAIUS.js +85 -0
  287. package/chunks/{workspace-registration-store-6TGVDJV5.js → workspace-registration-store-OTMS3H4C.js} +1 -1
  288. package/chunks/workspace-registry-O63R6IZ4.js +92 -0
  289. package/chunks/workspace-service-M6LLHKJ5.js +99 -0
  290. package/chunks/workspace-skills-status-C2V7BAIS.js +85 -0
  291. package/chunks/workspace-trust-reconciler-IBUPOUJN.js +345 -0
  292. package/chunks/write-file-3BZC3EAE.js +72 -0
  293. package/chunks/xterm-headless-NTYVIBT3.js +3475 -0
  294. package/chunks/{zh-LUIGBD55.js → zh-H3YDK5QW.js} +9 -1
  295. package/chunks/{zh-TW-F5KG2IYD.js → zh-TW-JYCP7XUA.js} +9 -1
  296. package/chunks/zoom-image-TZ6S2O57.js +351 -0
  297. package/cli.js +13 -13
  298. package/locales/ca.js +7 -2
  299. package/locales/de.js +7 -2
  300. package/locales/en.js +10 -2
  301. package/locales/fr.js +7 -2
  302. package/locales/ja.js +7 -2
  303. package/locales/pt.js +7 -2
  304. package/locales/ru.js +7 -2
  305. package/locales/zh-TW.js +10 -2
  306. package/locales/zh.js +10 -2
  307. package/package.json +5 -4
  308. package/web-shell/assets/{arc-BbHijhiN.js → arc-75-Wdeo3.js} +1 -1
  309. package/web-shell/assets/{architectureDiagram-3BPJPVTR-Cb4B_JD0.js → architectureDiagram-3BPJPVTR-FKeXQbyP.js} +1 -1
  310. package/web-shell/assets/{blockDiagram-GPEHLZMM-Dsjlh3H-.js → blockDiagram-GPEHLZMM-CY0vc-A3.js} +1 -1
  311. package/web-shell/assets/{c4Diagram-AAUBKEIU-Cp5AeR4U.js → c4Diagram-AAUBKEIU-CNP-A-8u.js} +1 -1
  312. package/web-shell/assets/channel-DPYMT76A.js +1 -0
  313. package/web-shell/assets/{chunk-2J33WTMH-CLcY7W2e.js → chunk-2J33WTMH-GybS4Gii.js} +1 -1
  314. package/web-shell/assets/{chunk-4BX2VUAB-BUhvY2LR.js → chunk-4BX2VUAB-02H91V8v.js} +1 -1
  315. package/web-shell/assets/{chunk-55IACEB6-kDIFC_71.js → chunk-55IACEB6-D3M-2VT6.js} +1 -1
  316. package/web-shell/assets/{chunk-727SXJPM-CIBO15f2.js → chunk-727SXJPM-CCu29u4H.js} +1 -1
  317. package/web-shell/assets/{chunk-AQP2D5EJ-BJ_T_slV.js → chunk-AQP2D5EJ-CaFKWgrn.js} +1 -1
  318. package/web-shell/assets/{chunk-FMBD7UC4-BEkW35J8.js → chunk-FMBD7UC4-ZZpPqIwQ.js} +1 -1
  319. package/web-shell/assets/{chunk-ND2GUHAM-GGPxofay.js → chunk-ND2GUHAM-D22DqGs8.js} +1 -1
  320. package/web-shell/assets/{chunk-QZHKN3VN-Bifllrb6.js → chunk-QZHKN3VN-Bu85S0fw.js} +1 -1
  321. package/web-shell/assets/classDiagram-4FO5ZUOK--JstsIgL.js +1 -0
  322. package/web-shell/assets/classDiagram-v2-Q7XG4LA2--JstsIgL.js +1 -0
  323. package/web-shell/assets/{cose-bilkent-S5V4N54A-C-Add_Dp.js → cose-bilkent-S5V4N54A-f1CK1Gwe.js} +1 -1
  324. package/web-shell/assets/{dagre-BM42HDAG-B7MfwNq2.js → dagre-BM42HDAG-D0Ow8F_n.js} +1 -1
  325. package/web-shell/assets/{diagram-2AECGRRQ-CY_0zuDz.js → diagram-2AECGRRQ-BPrmTWp8.js} +1 -1
  326. package/web-shell/assets/{diagram-5GNKFQAL-VyYSbCgA.js → diagram-5GNKFQAL-HccuFAzy.js} +1 -1
  327. package/web-shell/assets/{diagram-KO2AKTUF-CBiIZ2PL.js → diagram-KO2AKTUF-BrS76mbA.js} +1 -1
  328. package/web-shell/assets/{diagram-LMA3HP47-BL3CrVOx.js → diagram-LMA3HP47-V7T9lU-5.js} +1 -1
  329. package/web-shell/assets/{diagram-OG6HWLK6-CZUPx96P.js → diagram-OG6HWLK6-DKidyJMR.js} +1 -1
  330. package/web-shell/assets/{erDiagram-TEJ5UH35-B81xHr1-.js → erDiagram-TEJ5UH35-DBadZIkp.js} +1 -1
  331. package/web-shell/assets/{flowDiagram-I6XJVG4X-EZWhir-J.js → flowDiagram-I6XJVG4X-BymfqdNJ.js} +1 -1
  332. package/web-shell/assets/{ganttDiagram-6RSMTGT7-CVFSuIAg.js → ganttDiagram-6RSMTGT7-DOw340jf.js} +1 -1
  333. package/web-shell/assets/{gitGraphDiagram-PVQCEYII-C1H2uQDv.js → gitGraphDiagram-PVQCEYII-_8EiD8sl.js} +1 -1
  334. package/web-shell/assets/{index-BYo99NBH.js → index-CKIadvET.js} +1 -1
  335. package/web-shell/assets/index-D1eXNRHe.js +1389 -0
  336. package/web-shell/assets/index-DVLD4CQq.css +5 -0
  337. package/web-shell/assets/{infoDiagram-5YYISTIA-BwyFMlF8.js → infoDiagram-5YYISTIA-D61KYQBu.js} +1 -1
  338. package/web-shell/assets/{ishikawaDiagram-YF4QCWOH-CQ7Yhn2Y.js → ishikawaDiagram-YF4QCWOH-CsiXSpNx.js} +1 -1
  339. package/web-shell/assets/{journeyDiagram-JHISSGLW-CJn2sf0l.js → journeyDiagram-JHISSGLW-Sdfionyh.js} +1 -1
  340. package/web-shell/assets/{kanban-definition-UN3LZRKU-DaNRqwVN.js → kanban-definition-UN3LZRKU-C3WI3Cnl.js} +1 -1
  341. package/web-shell/assets/{linear-DCKODZe2.js → linear-Dpigcc62.js} +1 -1
  342. package/web-shell/assets/{mermaid.core-CTGJOk27.js → mermaid.core-Ct97pqgW.js} +5 -5
  343. package/web-shell/assets/{mindmap-definition-RKZ34NQL-BKU3_3rg.js → mindmap-definition-RKZ34NQL-BzeaN0rB.js} +1 -1
  344. package/web-shell/assets/{pieDiagram-4H26LBE5-COcwBJ82.js → pieDiagram-4H26LBE5-CvjgcbVD.js} +1 -1
  345. package/web-shell/assets/{quadrantDiagram-W4KKPZXB-CQnQ443x.js → quadrantDiagram-W4KKPZXB-BUzgTNdH.js} +1 -1
  346. package/web-shell/assets/{requirementDiagram-4Y6WPE33-CZ2oj5cD.js → requirementDiagram-4Y6WPE33-B7zKlgUQ.js} +1 -1
  347. package/web-shell/assets/{sankeyDiagram-5OEKKPKP-BxAv5mNu.js → sankeyDiagram-5OEKKPKP-Bb9CQgrT.js} +1 -1
  348. package/web-shell/assets/{sequenceDiagram-3UESZ5HK-CztaySPs.js → sequenceDiagram-3UESZ5HK-DJ6V7itG.js} +1 -1
  349. package/web-shell/assets/{stateDiagram-AJRCARHV-CTQT1oGD.js → stateDiagram-AJRCARHV-IImflERY.js} +1 -1
  350. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-CYI_YoNR.js +1 -0
  351. package/web-shell/assets/{timeline-definition-PNZ67QCA-K9Mkex5A.js → timeline-definition-PNZ67QCA-6Q_uWHKh.js} +1 -1
  352. package/web-shell/assets/{vennDiagram-CIIHVFJN-B2rVIw76.js → vennDiagram-CIIHVFJN-TmyKyjwv.js} +1 -1
  353. package/web-shell/assets/{wardley-L42UT6IY-Z1w2JR4M.js → wardley-L42UT6IY-CRh9uiPv.js} +1 -1
  354. package/web-shell/assets/{wardleyDiagram-YWT4CUSO-CIX9aKXf.js → wardleyDiagram-YWT4CUSO-59TKAW8w.js} +1 -1
  355. package/web-shell/assets/{xychartDiagram-2RQKCTM6-CI9DLIKB.js → xychartDiagram-2RQKCTM6-GCSUIK2L.js} +1 -1
  356. package/web-shell/index.html +2 -2
  357. package/chunks/MaxSizedBox-INHRH72H.js +0 -86
  358. package/chunks/agent-VXDAN5JK.js +0 -82
  359. package/chunks/agent-headless-K4ZMMNBD.js +0 -76
  360. package/chunks/bridge-LGPZCFHO.js +0 -91
  361. package/chunks/channel-settings-store-CHCDRTPY.js +0 -89
  362. package/chunks/chunk-SZRN75WQ.js +0 -29
  363. package/chunks/chunk-UGYMA4EI.js +0 -219
  364. package/chunks/chunk-VCBZUOSI.js +0 -8575
  365. package/chunks/contextCommand-QIZYHDR5.js +0 -81
  366. package/chunks/daemon-status-provider-OS5UWBHV.js +0 -90
  367. package/chunks/earlyInputCapture-WQT24RWD.js +0 -83
  368. package/chunks/errors-PCX25DVP.js +0 -89
  369. package/chunks/exitPlanMode-GHPUHBZJ.js +0 -423
  370. package/chunks/handleAutoUpdate-2CZQRJ66.js +0 -82
  371. package/chunks/i18n-XEQVMRKN.js +0 -98
  372. package/chunks/initializer-OVGZ4FLY.js +0 -87
  373. package/chunks/installationInfo-5UUQJI6Y.js +0 -81
  374. package/chunks/list-HODU6RXD.js +0 -90
  375. package/chunks/loadedSettingsAdapter-TYNLBALY.js +0 -84
  376. package/chunks/mcp-J3DFWX4A.js +0 -84
  377. package/chunks/nonInteractiveCli-F4GYSMHT.js +0 -144
  378. package/chunks/pidfile-4VNAR3EP.js +0 -87
  379. package/chunks/read-file-LZXUR4TO.js +0 -31
  380. package/chunks/resumeHistoryUtils-65OX3SGJ.js +0 -92
  381. package/chunks/ripGrep-2U2FRGMV.js +0 -74
  382. package/chunks/serve-W2GC47CM.js +0 -90
  383. package/chunks/shell-45IPBDP5.js +0 -84
  384. package/chunks/spawnChannel-PVXQ5AGV.js +0 -83
  385. package/chunks/src-AY65BYR7.js +0 -3166
  386. package/chunks/standalone-update-ZMFNKAEY.js +0 -93
  387. package/chunks/theme-manager-YYPZFBAH.js +0 -78
  388. package/chunks/total-session-admission-JXES723M.js +0 -85
  389. package/chunks/trustedFolders-HVI7IXUH.js +0 -94
  390. package/chunks/updateCheck-WUJGHWZZ.js +0 -93
  391. package/chunks/useAutoAcceptIndicator-CHSTZLZD.js +0 -94
  392. package/chunks/workspace-providers-status-GAKSF4LL.js +0 -87
  393. package/chunks/workspace-registry-A7NQUONG.js +0 -89
  394. package/chunks/workspace-service-STGVSO4N.js +0 -99
  395. package/chunks/workspace-skills-status-66AK3DUA.js +0 -86
  396. package/chunks/write-file-HUUCEG4P.js +0 -74
  397. package/web-shell/assets/channel-Bzdx6E8P.js +0 -1
  398. package/web-shell/assets/classDiagram-4FO5ZUOK-Cd6wbiuK.js +0 -1
  399. package/web-shell/assets/classDiagram-v2-Q7XG4LA2-Cd6wbiuK.js +0 -1
  400. package/web-shell/assets/index-B2bXx96W.js +0 -1249
  401. package/web-shell/assets/index-_8mKjx8q.css +0 -5
  402. package/web-shell/assets/stateDiagram-v2-BHNVJYJU-BjMdT6E_.js +0 -1
  403. package/chunks/{chunk-TARRHLLG.js → chunk-QUGAUQGJ.js} +25 -25
  404. package/chunks/{chunk-U7ZFW55U.js → chunk-VOQXFAY5.js} +977 -977
  405. /package/chunks/{chunk-LXXMOYPL.js → chunk-VXZBKKQR.js} +0 -0
@@ -1,8 +1,5 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import {
4
- recomputeMcpGating
5
- } from "./chunk-2JM6GZ5D.js";
6
3
  import {
7
4
  classifyApiError
8
5
  } from "./chunk-V7RNNPGC.js";
@@ -15,50 +12,53 @@ import {
15
12
  matchMcpServerByRef,
16
13
  parseExtensionRef,
17
14
  parseMcpServerRef
18
- } from "./chunk-GDIPH4JY.js";
15
+ } from "./chunk-TV64SXKD.js";
19
16
  import {
20
17
  getAvailableCommands,
21
18
  handleSlashCommand,
22
19
  insertAfterFunctionResponses,
23
20
  isSlashCommand,
24
21
  normalizePartList
25
- } from "./chunk-M4UKFCZ2.js";
22
+ } from "./chunk-J7OACQDE.js";
23
+ import {
24
+ recomputeMcpGating
25
+ } from "./chunk-A4COXFB3.js";
26
26
  import {
27
27
  appEvents,
28
28
  buildDisabledSkillNamesProvider,
29
29
  cleanupReviewWorktreeLeases,
30
30
  loadCliConfig,
31
31
  normalizeDisabledToolList
32
- } from "./chunk-BYFNTGKI.js";
33
- import "./chunk-PQNHRFJC.js";
34
- import {
35
- collectContextData,
36
- formatContextUsageText
37
- } from "./chunk-5THCYPLO.js";
32
+ } from "./chunk-7BAU433D.js";
38
33
  import {
39
34
  getCommandSubcommandNames
40
- } from "./chunk-PHVR5UUY.js";
35
+ } from "./chunk-JX27F6QS.js";
41
36
  import {
42
37
  getEffectiveSupportedModes
43
- } from "./chunk-52O2CIUL.js";
44
- import "./chunk-J56UI34H.js";
38
+ } from "./chunk-7AEJDLRA.js";
39
+ import "./chunk-PQNHRFJC.js";
40
+ import "./chunk-M7OONWYU.js";
41
+ import {
42
+ collectContextData,
43
+ formatContextUsageText
44
+ } from "./chunk-65PQENQP.js";
45
45
  import "./chunk-4WGODMVR.js";
46
- import "./chunk-ZE5WPL4I.js";
46
+ import "./chunk-GATT5TKW.js";
47
+ import "./chunk-EVKE2FZL.js";
48
+ import "./chunk-T3O2B4XO.js";
49
+ import "./chunk-7DXQIJID.js";
47
50
  import "./chunk-YAF2MQZ6.js";
48
- import "./chunk-L5UHQJTJ.js";
49
51
  import {
50
52
  computeCpuPercent
51
53
  } from "./chunk-HGT6JR3U.js";
52
- import "./chunk-3IXOIAKE.js";
54
+ import "./chunk-S4WJVPZW.js";
53
55
  import "./chunk-6H67XLET.js";
54
56
  import {
55
57
  beginAcpBootstrapConfigProfiling,
56
58
  buildAndFreezeAcpStartupProfile,
57
59
  endAcpBootstrapConfigProfiling,
58
60
  markAcpStartup
59
- } from "./chunk-HIJQF5B5.js";
60
- import "./chunk-5U4IPFBR.js";
61
- import "./chunk-VFSJ5VRH.js";
61
+ } from "./chunk-3L2SPEBH.js";
62
62
  import {
63
63
  GENERATION_MAX_PROMPT_BYTES,
64
64
  GENERATION_TIMEOUT_MS,
@@ -78,7 +78,7 @@ import {
78
78
  shouldSuppressRememberErrorDetails,
79
79
  workspaceMemoryFailureCode,
80
80
  workspaceMemoryFailureDiagnostics
81
- } from "./chunk-J6D3VXCC.js";
81
+ } from "./chunk-6PE7N3A4.js";
82
82
  import {
83
83
  HistoryReplayer,
84
84
  MessageEmitter,
@@ -88,10 +88,10 @@ import {
88
88
  goalTerminalEventToHistoryItem,
89
89
  recordGoalStatusItem,
90
90
  restoreGoalFromHistory
91
- } from "./chunk-DM22XS4K.js";
92
- import "./chunk-RHLZR4E5.js";
93
- import "./chunk-IPUUTYMV.js";
94
- import "./chunk-BRRAJXPA.js";
91
+ } from "./chunk-LO4ROVP4.js";
92
+ import "./chunk-LGAOC3ZS.js";
93
+ import "./chunk-XFZYFU3I.js";
94
+ import "./chunk-YDLJGZHL.js";
95
95
  import "./chunk-2MIN6GRR.js";
96
96
  import "./chunk-QHTIBUWB.js";
97
97
  import {
@@ -105,51 +105,31 @@ import {
105
105
  buildPermissionSettings,
106
106
  normalizePermissionRules,
107
107
  readPermissionRuleSet
108
- } from "./chunk-LZEMEFKY.js";
108
+ } from "./chunk-MR5EAQ5M.js";
109
109
  import {
110
110
  MAX_AUDIO_BYTES,
111
111
  sanitizeVoiceErrorMessage,
112
112
  transcribeVoiceAudio
113
- } from "./chunk-2OM7GEXO.js";
113
+ } from "./chunk-CAPPWD3X.js";
114
114
  import {
115
115
  readVoiceModel
116
- } from "./chunk-KIUFNBHR.js";
117
- import "./chunk-ZD6UTE4A.js";
118
- import "./chunk-XHRTVPG2.js";
119
- import "./chunk-2YZJCM5T.js";
120
- import "./chunk-57OAHC2Y.js";
116
+ } from "./chunk-JTV5K7NH.js";
117
+ import "./chunk-ZHBO7WVX.js";
121
118
  import {
122
119
  createLoadedSettingsAdapter
123
- } from "./chunk-G4WFQUYQ.js";
124
- import "./chunk-LXXMOYPL.js";
125
- import "./chunk-SASBXAQL.js";
120
+ } from "./chunk-WUZ7H6DP.js";
121
+ import "./chunk-VXZBKKQR.js";
122
+ import "./chunk-QIZKCVM3.js";
126
123
  import "./chunk-E5Z2AVNV.js";
127
124
  import {
128
125
  parseSessionSource
129
- } from "./chunk-66RMLJHC.js";
126
+ } from "./chunk-ZURDMIDR.js";
130
127
  import "./chunk-GLWP3FDB.js";
131
- import "./chunk-COH43MRJ.js";
132
- import {
133
- CHANNEL_STARTUP_PROFILE_META_KEY,
134
- CHANNEL_STARTUP_PROFILE_VERSION,
135
- CLIENT_MCP_OVER_WS_CONFIG_FLAG,
136
- DAEMON_CHANNEL_DELIVERY_META_KEY,
137
- LOAD_REPLAY_BULK_MODE,
138
- LOAD_REPLAY_META_KEY,
139
- LOAD_REPLAY_MODE_META_KEY,
140
- LOAD_REPLAY_PAGE_SIZE_META_KEY,
141
- LOAD_REPLAY_VERSION,
142
- MID_TURN_QUEUE_DRAIN_METHOD,
143
- PROMPT_CANCEL_METHOD,
144
- TODO_STOP_GUARD_QUEUE_RELEASE_METHOD
145
- } from "./chunk-3SJ43L4W.js";
146
- import {
147
- NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE,
148
- isNotCurrentlyGeneratingCancelError
149
- } from "./chunk-UH3WSE5L.js";
128
+ import "./chunk-XCGIMOLN.js";
129
+ import "./chunk-OCPBI7J5.js";
150
130
  import {
151
131
  ndJsonStream
152
- } from "./chunk-A6UO2C7C.js";
132
+ } from "./chunk-KAMYKP7E.js";
153
133
  import {
154
134
  ACP_ROUTE_ID_PREFIX,
155
135
  buildAcpModelOptions,
@@ -158,10 +138,10 @@ import {
158
138
  parseAcpModelOption,
159
139
  resolveAcpModelOption,
160
140
  sanitizeProviderBaseUrl
161
- } from "./chunk-LG4GZIVV.js";
141
+ } from "./chunk-KCO4FLFJ.js";
162
142
  import {
163
143
  mapSkillConfigToStatus
164
- } from "./chunk-2W3OOD4W.js";
144
+ } from "./chunk-L55JWS76.js";
165
145
  import {
166
146
  ACP_PREFLIGHT_KINDS,
167
147
  IDLE_HOOK_EVENTS,
@@ -169,30 +149,55 @@ import {
169
149
  SERVE_STATUS_EXT_METHODS,
170
150
  STATUS_SCHEMA_VERSION,
171
151
  mapDomainErrorToErrorKind
172
- } from "./chunk-KU5XMLDK.js";
173
- import "./chunk-MVS3NS2N.js";
174
- import "./chunk-ER5LWJR6.js";
175
- import "./chunk-W4CQXHT6.js";
176
- import "./chunk-MK7VQDN3.js";
152
+ } from "./chunk-FTD6DP4T.js";
153
+ import {
154
+ resolveSkillSettings
155
+ } from "./chunk-Z4X5MTRT.js";
156
+ import "./chunk-BNWB5CYE.js";
157
+ import "./chunk-5MKRTI4T.js";
158
+ import "./chunk-57OAHC2Y.js";
159
+ import "./chunk-2XSLTRFZ.js";
160
+ import "./chunk-TFRMVU6R.js";
161
+ import "./chunk-XBYYDKAZ.js";
177
162
  import "./chunk-V6WHFGST.js";
178
163
  import {
179
- assembleMcpServers,
180
- loadMcpApprovals
181
- } from "./chunk-Z5BLYMZM.js";
182
- import "./chunk-LNARWLZQ.js";
164
+ CHANNEL_STARTUP_PROFILE_META_KEY,
165
+ CHANNEL_STARTUP_PROFILE_VERSION,
166
+ CLIENT_MCP_OVER_WS_CONFIG_FLAG,
167
+ DAEMON_CHANNEL_DELIVERY_META_KEY,
168
+ LOAD_REPLAY_BULK_MODE,
169
+ LOAD_REPLAY_META_KEY,
170
+ LOAD_REPLAY_MODE_META_KEY,
171
+ LOAD_REPLAY_PAGE_SIZE_META_KEY,
172
+ LOAD_REPLAY_VERSION,
173
+ MID_TURN_QUEUE_DRAIN_METHOD,
174
+ PROMPT_CANCEL_METHOD,
175
+ TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,
176
+ TODO_STOP_GUARD_QUEUE_RELEASE_METHOD
177
+ } from "./chunk-XZC5VLBZ.js";
178
+ import {
179
+ NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE,
180
+ isNotCurrentlyGeneratingCancelError
181
+ } from "./chunk-B4AJNNOL.js";
183
182
  import "./chunk-2RFKHEXL.js";
183
+ import "./chunk-FYJ7W2PI.js";
184
184
  import "./chunk-U4VTUMMK.js";
185
- import "./chunk-HV3G62R6.js";
185
+ import "./chunk-GZ3RCT54.js";
186
186
  import "./chunk-ALMR3E6Q.js";
187
187
  import "./chunk-BK2UNYWD.js";
188
188
  import "./chunk-M5GB774H.js";
189
- import "./chunk-ML52PL6O.js";
189
+ import "./chunk-4G2BISNC.js";
190
+ import "./chunk-GEBV2JGB.js";
191
+ import "./chunk-7I5GTCT4.js";
190
192
  import {
191
193
  AgentSideConnection,
192
194
  PROTOCOL_VERSION,
193
195
  RequestError
194
196
  } from "./chunk-UDXSXLER.js";
195
- import "./chunk-BIQWWWJN.js";
197
+ import {
198
+ assembleMcpServers,
199
+ loadMcpApprovals
200
+ } from "./chunk-6RPMI2AB.js";
196
201
  import {
197
202
  getOutputLanguageFilePath,
198
203
  getPersistScopeForModelSelection,
@@ -201,38 +206,39 @@ import {
201
206
  resolveOutputLanguageOrPreserveAuto,
202
207
  updateOutputLanguageFile,
203
208
  writeOutputLanguageAndRegisterPath
204
- } from "./chunk-JALU3ZDU.js";
209
+ } from "./chunk-EIF3FXTB.js";
205
210
  import "./chunk-RKUWKYED.js";
206
- import "./chunk-GOXKNSDZ.js";
207
- import {
208
- getSystemDefaultsPath,
209
- getSystemSettingsPath
210
- } from "./chunk-IDS7MSUP.js";
211
211
  import {
212
212
  SUPPORTED_LANGUAGES,
213
213
  getCurrentLanguage,
214
214
  setLanguageAsync
215
- } from "./chunk-VV6XU5L7.js";
215
+ } from "./chunk-TCIFAA7K.js";
216
216
  import {
217
217
  findEnvFiles,
218
218
  preResolveHomeEnvOverrides,
219
219
  reloadEnvironment
220
- } from "./chunk-PANH4R3B.js";
220
+ } from "./chunk-2N7CODY5.js";
221
+ import "./chunk-VWOOBLTY.js";
222
+ import "./chunk-GOXKNSDZ.js";
223
+ import {
224
+ getSystemDefaultsPath,
225
+ getSystemSettingsPath
226
+ } from "./chunk-IDS7MSUP.js";
221
227
  import "./chunk-6PEXNQTX.js";
222
- import "./chunk-I7XZ3RY5.js";
228
+ import "./chunk-XFSFZCM5.js";
229
+ import "./chunk-VYOXCEPJ.js";
223
230
  import "./chunk-VJNBRRZG.js";
224
231
  import {
225
232
  isFolderTrustEnabled,
226
233
  isWorkspaceTrusted,
227
234
  loadTrustedFolders
228
- } from "./chunk-VCBZUOSI.js";
235
+ } from "./chunk-Q43KPN7X.js";
229
236
  import "./chunk-ALGGS7UH.js";
230
237
  import "./chunk-MR3PXB6E.js";
231
238
  import {
232
239
  writeStderrLine,
233
240
  writeStderrLineSafe
234
241
  } from "./chunk-OWAK7LMW.js";
235
- import "./chunk-XFSFZCM5.js";
236
242
  import {
237
243
  ALL_PROVIDERS,
238
244
  APPROVAL_MODE_INFO,
@@ -272,6 +278,7 @@ import {
272
278
  applyAutoModeDecision,
273
279
  applyProviderInstallPlan,
274
280
  approxBase64Bytes,
281
+ bridgeToolResultImages,
275
282
  buildBackgroundEntryLabel,
276
283
  buildBtwCacheSafeParams,
277
284
  buildBtwPrompt,
@@ -356,56 +363,56 @@ import {
356
363
  updateSetting,
357
364
  validatePlanModeShellApproval,
358
365
  validatePlanModeShellContext
359
- } from "./chunk-DM4Q4JJH.js";
360
- import "./chunk-5M6IDOMF.js";
366
+ } from "./chunk-X5WNMMIA.js";
361
367
  import "./chunk-TWPJO254.js";
362
368
  import {
363
369
  external_exports
364
370
  } from "./chunk-H6XPXXMH.js";
365
- import "./chunk-K4XWPEWB.js";
366
- import "./chunk-TOFQCPDC.js";
367
- import "./chunk-IRH27ZC2.js";
368
- import "./chunk-VDDGDZMA.js";
369
- import "./chunk-FNQ6T3CV.js";
370
- import "./chunk-ZOIFNCKL.js";
371
- import "./chunk-PWTZEM3C.js";
371
+ import "./chunk-5M6IDOMF.js";
372
+ import "./chunk-UPUG4GXM.js";
373
+ import "./chunk-64LQLPL7.js";
374
+ import "./chunk-2LQTH543.js";
372
375
  import "./chunk-KRXPRVGL.js";
376
+ import "./chunk-BMFALVGQ.js";
377
+ import "./chunk-CVHIL5IG.js";
378
+ import "./chunk-IRH27ZC2.js";
379
+ import "./chunk-QHWCP53L.js";
380
+ import "./chunk-PONHVBRT.js";
381
+ import "./chunk-T26EAKDL.js";
373
382
  import {
374
383
  parsePositiveIntegerEnv
375
384
  } from "./chunk-6PVPNMXU.js";
376
- import "./chunk-PSWQZHEA.js";
377
- import "./chunk-SZRN75WQ.js";
378
- import "./chunk-HTO4JFDZ.js";
379
385
  import "./chunk-CPBF7KYF.js";
386
+ import "./chunk-6QIGFD5W.js";
387
+ import {
388
+ HookEventName,
389
+ createHookOutput
390
+ } from "./chunk-XWWKIXVD.js";
391
+ import "./chunk-75GFAX4R.js";
392
+ import "./chunk-OKF7JF3R.js";
380
393
  import {
381
394
  APPROVAL_MODES,
382
395
  FORK_SUBAGENT_TYPE,
383
396
  getStartupContextLength,
384
397
  isSystemReminderContent,
385
398
  runWithRuntimeContentGenerator
386
- } from "./chunk-L26JL52R.js";
387
- import "./chunk-6AM5D4ME.js";
388
- import "./chunk-JZA3JUDJ.js";
389
- import {
390
- HookEventName,
391
- createHookOutput
392
- } from "./chunk-3QMGYBFN.js";
399
+ } from "./chunk-JSD33JG6.js";
400
+ import "./chunk-S6LOFUVP.js";
393
401
  import "./chunk-JCW2R7WC.js";
394
- import "./chunk-M5JM7OSF.js";
395
- import "./chunk-OHNBB4XR.js";
396
- import "./chunk-E5TUC6CA.js";
402
+ import "./chunk-2DN4J57Y.js";
403
+ import "./chunk-ZPJWUGCS.js";
397
404
  import {
398
405
  clearCachedCredentialFile,
399
406
  qwenOAuth2Events
400
- } from "./chunk-EPDRMGT4.js";
401
- import "./chunk-JESCGQM3.js";
402
- import "./chunk-NH6KE4JX.js";
403
- import "./chunk-USTWD7QV.js";
404
- import "./chunk-XVNQMZ2I.js";
405
- import "./chunk-FODK6UMO.js";
407
+ } from "./chunk-2LKVPASC.js";
408
+ import "./chunk-NAVJD2PQ.js";
409
+ import "./chunk-LW3RFMG7.js";
410
+ import "./chunk-W4MIWP6M.js";
411
+ import "./chunk-DGEIYUC3.js";
412
+ import "./chunk-MPHPFVKK.js";
406
413
  import "./chunk-GLNBDYUX.js";
407
414
  import "./chunk-DJ2GSRLV.js";
408
- import "./chunk-YAF5VNU7.js";
415
+ import "./chunk-5KTQXHPY.js";
409
416
  import {
410
417
  addToolArgumentsAttributes,
411
418
  addToolCallResultAttributes,
@@ -413,14 +420,14 @@ import {
413
420
  registerAcpEventLoopLagGauge,
414
421
  startEventLoopLagMonitor,
415
422
  withDaemonSpan
416
- } from "./chunk-BO4XCS7P.js";
417
- import "./chunk-BPJSQIJX.js";
423
+ } from "./chunk-75MIQ3LV.js";
424
+ import "./chunk-2J3OJGTL.js";
418
425
  import "./chunk-P3QQPMQA.js";
419
- import "./chunk-6FGBXPWM.js";
426
+ import "./chunk-RPLGZJV2.js";
420
427
  import {
421
428
  getToolCallPreparations
422
- } from "./chunk-LS77BEZP.js";
423
- import "./chunk-SQBYH7PX.js";
429
+ } from "./chunk-GLCZKT5V.js";
430
+ import "./chunk-DZLYR4U3.js";
424
431
  import {
425
432
  ConversationFinishedEvent,
426
433
  DiscoveredMCPTool,
@@ -434,6 +441,7 @@ import {
434
441
  formatVisionBridgeNotice,
435
442
  getAllGeminiMdFilenames,
436
443
  getFullTurnVisionModelSelector,
444
+ getInvocationContext,
437
445
  getMCPServerStatus,
438
446
  getSpecificMimeType,
439
447
  hasImageParts,
@@ -450,25 +458,30 @@ import {
450
458
  shouldRunVisionBridge,
451
459
  splitImageParts,
452
460
  uiTelemetryService
453
- } from "./chunk-RWS5VYWC.js";
461
+ } from "./chunk-PT722TDT.js";
454
462
  import "./chunk-VGC4I5JJ.js";
455
463
  import {
456
464
  getAutoMemoryRoot,
457
465
  getUserAutoMemoryRoot
458
- } from "./chunk-MUP3T3AD.js";
466
+ } from "./chunk-SGFT55XI.js";
467
+ import "./chunk-Y4IHBGBP.js";
459
468
  import {
460
- AuthType
461
- } from "./chunk-U7TXFVUN.js";
469
+ ToolConfirmationOutcome,
470
+ ToolNames,
471
+ isShellProgressData
472
+ } from "./chunk-Y6AXW2OG.js";
473
+ import {
474
+ AuthType,
475
+ preloadContentGenerator
476
+ } from "./chunk-VCPIZRYH.js";
462
477
  import "./chunk-46UV252V.js";
463
- import "./chunk-A4UCTEB5.js";
464
- import "./chunk-XWRJCPHC.js";
465
478
  import {
466
479
  DEFAULT_TOKEN_LIMIT,
467
480
  tokenLimit
468
- } from "./chunk-UW5EOVUN.js";
469
- import "./chunk-2JZBVYTU.js";
470
- import "./chunk-5I2IWRSH.js";
471
- import "./chunk-A5L3JMUA.js";
481
+ } from "./chunk-ZBVS26BY.js";
482
+ import "./chunk-WZRWHXFE.js";
483
+ import "./chunk-A3NDJ5SB.js";
484
+ import "./chunk-7XATOOE7.js";
472
485
  import {
473
486
  endToolExecutionSpan,
474
487
  endToolSpan,
@@ -477,32 +490,26 @@ import {
477
490
  startToolExecutionSpan,
478
491
  startToolSpan,
479
492
  withInteractionSpan
480
- } from "./chunk-SRZ6DXVG.js";
493
+ } from "./chunk-BGTQCTQW.js";
481
494
  import "./chunk-W4RQUHY3.js";
482
- import "./chunk-INADJJGW.js";
483
- import "./chunk-U7ZFW55U.js";
484
- import "./chunk-UUUTRMI2.js";
485
- import {
486
- ToolConfirmationOutcome,
487
- ToolNames,
488
- isShellProgressData
489
- } from "./chunk-PR75REBZ.js";
495
+ import "./chunk-S7W2GKIO.js";
490
496
  import {
491
497
  Storage,
492
498
  createDebugLogger,
493
499
  getErrorMessage,
494
500
  getErrorStatus,
495
501
  isSubpath
496
- } from "./chunk-NL7LTRLR.js";
497
- import "./chunk-32MVHM4T.js";
502
+ } from "./chunk-UHUSJ6X7.js";
503
+ import "./chunk-VOQXFAY5.js";
504
+ import "./chunk-RCUQIPTN.js";
498
505
  import {
499
506
  runExitCleanup
500
- } from "./chunk-B4UMZKMU.js";
507
+ } from "./chunk-52ZSWYEG.js";
501
508
  import "./chunk-75DOP5OR.js";
502
509
  import "./chunk-DMTGGOSA.js";
503
510
  import "./chunk-YQ3U5MUC.js";
504
511
  import "./chunk-AMDSOFFV.js";
505
- import "./chunk-TARRHLLG.js";
512
+ import "./chunk-QUGAUQGJ.js";
506
513
  import {
507
514
  init_esbuild_shims
508
515
  } from "./chunk-5O2XNYP6.js";
@@ -1956,6 +1963,7 @@ var DaemonTodoStopGuard = class {
1956
1963
  // packages/cli/src/acp-integration/session/Session.ts
1957
1964
  var debugLogger6 = createDebugLogger("SESSION");
1958
1965
  var USER_CANCEL_ABORT_REASON = "qwen:user-cancel";
1966
+ var SESSION_DISPOSE_ABORT_REASON = "qwen:session-dispose";
1959
1967
  var DAEMON_RETRY_META_KEY = "qwen.daemon.retry";
1960
1968
  var DAEMON_CONTINUE_META_KEY = "qwen.daemon.continueLastTurn";
1961
1969
  var TODO_STOP_GUARD_PROMPT_PREFIX = "[Todo Stop Guard] ";
@@ -2227,6 +2235,20 @@ function parseMidTurnDrainResponse(response) {
2227
2235
  ).map((message) => ({ kind: "text", message }));
2228
2236
  }
2229
2237
  __name(parseMidTurnDrainResponse, "parseMidTurnDrainResponse");
2238
+ function isValidMidTurnDrainResponse(response, requireQueuedPromptState) {
2239
+ if (!isRecord2(response) || requireQueuedPromptState && typeof response["hasQueuedPrompt"] !== "boolean") {
2240
+ return false;
2241
+ }
2242
+ if (Array.isArray(response["items"])) {
2243
+ return response["items"].every(
2244
+ (item) => isRecord2(item) && Array.isArray(item["content"]) && item["content"].length > 0 && item["content"].every(isContentBlock)
2245
+ );
2246
+ }
2247
+ return Array.isArray(response["messages"]) && response["messages"].every(
2248
+ (message) => typeof message === "string" && message.trim().length > 0
2249
+ );
2250
+ }
2251
+ __name(isValidMidTurnDrainResponse, "isValidMidTurnDrainResponse");
2230
2252
  var MidTurnDrainTimeoutError = class extends Error {
2231
2253
  static {
2232
2254
  __name(this, "MidTurnDrainTimeoutError");
@@ -2237,6 +2259,16 @@ var MidTurnDrainTimeoutError = class extends Error {
2237
2259
  );
2238
2260
  }
2239
2261
  };
2262
+ var TodoStopGuardClaimTimeoutError = class extends Error {
2263
+ static {
2264
+ __name(this, "TodoStopGuardClaimTimeoutError");
2265
+ }
2266
+ constructor() {
2267
+ super(
2268
+ `Todo Stop Guard continuation claim got no response within ${MID_TURN_QUEUE_DRAIN_TIMEOUT_MS}ms`
2269
+ );
2270
+ }
2271
+ };
2240
2272
  function beginChannelDeliveryResponseBlock(capture) {
2241
2273
  if (!capture) return void 0;
2242
2274
  capture.finalText = "";
@@ -2570,7 +2602,12 @@ var Session = class {
2570
2602
  midTurnRecoveredMessages = [];
2571
2603
  todoStopGuard;
2572
2604
  todoStopGuardBackgroundBaseline;
2605
+ relatedAgentIds = /* @__PURE__ */ new Set();
2606
+ provisionalRelatedAgentCounts = /* @__PURE__ */ new Map();
2573
2607
  todoStopGuardQueuedPromptPriority = false;
2608
+ todoStopGuardQueuedPromptOwnerPromptId;
2609
+ todoStopGuardClaimOwnerCounts = /* @__PURE__ */ new Map();
2610
+ todoStopGuardReleasedDuringClaim = /* @__PURE__ */ new Set();
2574
2611
  todoStopGuardDrainAutomaticQueuesWhenIdle = false;
2575
2612
  // Background notification drain state. ACP does not have the TUI's idle
2576
2613
  // hook, so the session serializes registry callbacks through this queue.
@@ -2622,7 +2659,7 @@ var Session = class {
2622
2659
  }
2623
2660
  const drainSupersededAutomaticQueues = this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuard.hasCommittedContinuation || this.todoStopGuardQueuedPromptPriority;
2624
2661
  if (this.config.getApprovalMode() === "plan" /* PLAN */) {
2625
- this.todoStopGuardQueuedPromptPriority = false;
2662
+ this.#clearTodoStopGuardQueuedPromptWait();
2626
2663
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2627
2664
  return {
2628
2665
  startsWorkChain: false,
@@ -2633,7 +2670,7 @@ var Session = class {
2633
2670
  const isRetry = params.retry === true || metadata?.[DAEMON_RETRY_META_KEY] === true;
2634
2671
  const isContinue = metadata?.[DAEMON_CONTINUE_META_KEY] === true;
2635
2672
  if (isRetry || isContinue) {
2636
- this.todoStopGuardQueuedPromptPriority = false;
2673
+ this.#clearTodoStopGuardQueuedPromptWait();
2637
2674
  if (this.todoStopGuard.hasTrustedUnfinishedState) {
2638
2675
  this.todoStopGuard.resumeTrustedPrompt();
2639
2676
  return {
@@ -2647,7 +2684,7 @@ var Session = class {
2647
2684
  drainSupersededAutomaticQueues
2648
2685
  };
2649
2686
  }
2650
- this.todoStopGuardQueuedPromptPriority = false;
2687
+ this.#clearTodoStopGuardQueuedPromptWait();
2651
2688
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2652
2689
  return {
2653
2690
  startsWorkChain: true,
@@ -2660,7 +2697,7 @@ var Session = class {
2660
2697
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2661
2698
  return;
2662
2699
  }
2663
- if (continuesCurrentWorkChain && this.todoStopGuard.isHardSuspended) {
2700
+ if (this.todoStopGuard.isHardSuspended) {
2664
2701
  return;
2665
2702
  }
2666
2703
  if (continuesCurrentWorkChain && this.todoStopGuard.hasTrustedUnfinishedState) {
@@ -2668,7 +2705,7 @@ var Session = class {
2668
2705
  return;
2669
2706
  }
2670
2707
  this.todoStopGuard.clearTrust();
2671
- this.todoStopGuardBackgroundBaseline = this.#captureTodoStopGuardBackgroundBaseline();
2708
+ this.#resetTodoStopGuardBackgroundLineage();
2672
2709
  }
2673
2710
  #clearTodoStopGuardTrustAndDrainAutomaticQueues() {
2674
2711
  const preserveQueuedPromptPriority = this.todoStopGuardQueuedPromptPriority;
@@ -2682,35 +2719,116 @@ var Session = class {
2682
2719
  void this.#drainCronQueue();
2683
2720
  void this.#drainNotificationQueue();
2684
2721
  }
2685
- releaseTodoStopGuardQueuedPromptWait() {
2686
- if (!this.todoStopGuardQueuedPromptPriority) return false;
2687
- this.todoStopGuardQueuedPromptPriority = false;
2722
+ releaseTodoStopGuardQueuedPromptWait(promptId) {
2723
+ const matchesCurrentWait = this.todoStopGuardQueuedPromptPriority && this.todoStopGuardQueuedPromptOwnerPromptId === promptId;
2724
+ if (!matchesCurrentWait) {
2725
+ if ((this.todoStopGuardClaimOwnerCounts.get(promptId) ?? 0) === 0) {
2726
+ return false;
2727
+ }
2728
+ this.todoStopGuardReleasedDuringClaim.add(promptId);
2729
+ if (!this.todoStopGuardQueuedPromptPriority) {
2730
+ this.#finishTodoStopGuardQueuedPromptRelease();
2731
+ }
2732
+ return true;
2733
+ }
2734
+ this.#clearTodoStopGuardQueuedPromptWait(promptId);
2735
+ this.#finishTodoStopGuardQueuedPromptRelease();
2736
+ return true;
2737
+ }
2738
+ #finishTodoStopGuardQueuedPromptRelease() {
2688
2739
  this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2689
2740
  if (this.pendingPrompt) {
2690
2741
  this.todoStopGuardDrainAutomaticQueuesWhenIdle = true;
2691
- return true;
2742
+ return;
2692
2743
  }
2693
2744
  void this.#drainCronQueue();
2694
2745
  void this.#drainNotificationQueue();
2695
- return true;
2696
2746
  }
2697
2747
  clearTodoStopGuardTrust() {
2698
2748
  this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
2699
2749
  }
2700
- #beginTodoStopGuardQueuedPromptCheck() {
2701
- this.todoStopGuardQueuedPromptPriority = this.todoStopGuard.awaitQueuedPrompt();
2750
+ hardSuspendTodoStopGuard() {
2751
+ this.#clearTodoStopGuardQueuedPromptWait();
2752
+ this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
2753
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
2702
2754
  }
2703
- #finishTodoStopGuardQueuedPromptCheck(hasQueuedPrompt) {
2704
- const shouldWait = hasQueuedPrompt && this.todoStopGuardQueuedPromptPriority;
2705
- this.todoStopGuardQueuedPromptPriority = shouldWait;
2706
- if (!shouldWait) this.todoStopGuard.resumeTrustedPrompt();
2707
- return shouldWait;
2755
+ #clearTodoStopGuardQueuedPromptWait(expectedOwner) {
2756
+ if (expectedOwner !== void 0 && this.todoStopGuardQueuedPromptOwnerPromptId !== expectedOwner) {
2757
+ return;
2758
+ }
2759
+ this.todoStopGuardQueuedPromptPriority = false;
2760
+ this.todoStopGuardQueuedPromptOwnerPromptId = void 0;
2761
+ }
2762
+ #awaitTodoStopGuardQueuedPrompt(promptId) {
2763
+ this.todoStopGuard.awaitQueuedPrompt();
2764
+ this.todoStopGuardQueuedPromptPriority = true;
2765
+ this.todoStopGuardQueuedPromptOwnerPromptId = promptId;
2766
+ }
2767
+ async #claimTodoStopGuardContinuation(abortSignal) {
2768
+ const context = getInvocationContext();
2769
+ const ownerPromptId = context?.sessionId === this.sessionId ? context.promptId : void 0;
2770
+ if (ownerPromptId) {
2771
+ this.todoStopGuardClaimOwnerCounts.set(
2772
+ ownerPromptId,
2773
+ (this.todoStopGuardClaimOwnerCounts.get(ownerPromptId) ?? 0) + 1
2774
+ );
2775
+ }
2776
+ let timeoutHandle;
2777
+ try {
2778
+ const claimPromise = this.client.extMethod(
2779
+ TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,
2780
+ {
2781
+ sessionId: this.sessionId,
2782
+ ...ownerPromptId ? { promptId: ownerPromptId } : {}
2783
+ }
2784
+ );
2785
+ const timeoutPromise = new Promise((_, reject) => {
2786
+ timeoutHandle = setTimeout(
2787
+ () => reject(new TodoStopGuardClaimTimeoutError()),
2788
+ MID_TURN_QUEUE_DRAIN_TIMEOUT_MS
2789
+ );
2790
+ });
2791
+ const response = await Promise.race([claimPromise, timeoutPromise]);
2792
+ if (abortSignal.aborted || !isRecord2(response)) {
2793
+ return "unavailable";
2794
+ }
2795
+ if (ownerPromptId && response["claimed"] === false && response["hasQueuedPrompt"] === true) {
2796
+ if (this.closing || this.disposed) return "unavailable";
2797
+ if (this.todoStopGuardReleasedDuringClaim.has(ownerPromptId)) {
2798
+ return "unavailable";
2799
+ }
2800
+ this.#awaitTodoStopGuardQueuedPrompt(ownerPromptId);
2801
+ return "queued";
2802
+ }
2803
+ if (this.todoStopGuard.isHardSuspended) return "unavailable";
2804
+ if (response["claimed"] === true && response["hasQueuedPrompt"] === false) {
2805
+ if (ownerPromptId) {
2806
+ this.#clearTodoStopGuardQueuedPromptWait(ownerPromptId);
2807
+ }
2808
+ this.todoStopGuard.resumeTrustedPrompt();
2809
+ return "claimed";
2810
+ }
2811
+ return "unavailable";
2812
+ } catch (error) {
2813
+ debugLogger6.warn(
2814
+ `Todo Stop Guard continuation claim unavailable [session ${this.sessionId}]: ${this.#formatError(error)}`
2815
+ );
2816
+ return "unavailable";
2817
+ } finally {
2818
+ clearTimeout(timeoutHandle);
2819
+ if (ownerPromptId) {
2820
+ const remaining = (this.todoStopGuardClaimOwnerCounts.get(ownerPromptId) ?? 1) - 1;
2821
+ if (remaining > 0) {
2822
+ this.todoStopGuardClaimOwnerCounts.set(ownerPromptId, remaining);
2823
+ } else {
2824
+ this.todoStopGuardClaimOwnerCounts.delete(ownerPromptId);
2825
+ this.todoStopGuardReleasedDuringClaim.delete(ownerPromptId);
2826
+ }
2827
+ }
2828
+ }
2708
2829
  }
2709
2830
  #notificationContinuesTodoStopGuardWorkChain(item) {
2710
- const baseline = this.todoStopGuardBackgroundBaseline;
2711
- if (item.kind === "agent") return !baseline.agents.has(item.taskId);
2712
- if (item.kind === "shell") return !baseline.shells.has(item.taskId);
2713
- return !baseline.monitors.has(item.taskId);
2831
+ return item.continuesTodoStopGuardWorkChain;
2714
2832
  }
2715
2833
  #cronContinuesTodoStopGuardWorkChain(item) {
2716
2834
  return item.source === "loop" && item.taskId !== void 0 && !this.todoStopGuardBackgroundBaseline.wakeups.has(item.taskId);
@@ -2743,6 +2861,37 @@ var Session = class {
2743
2861
  ])
2744
2862
  };
2745
2863
  }
2864
+ #resetTodoStopGuardBackgroundLineage() {
2865
+ this.relatedAgentIds.clear();
2866
+ this.provisionalRelatedAgentCounts.clear();
2867
+ this.todoStopGuardBackgroundBaseline = this.#captureTodoStopGuardBackgroundBaseline();
2868
+ for (const item of this.notificationQueue) {
2869
+ item.continuesTodoStopGuardWorkChain = false;
2870
+ }
2871
+ }
2872
+ #agentContinuesTodoStopGuardWorkChain(taskId, visiting = /* @__PURE__ */ new Set()) {
2873
+ if (this.relatedAgentIds.has(taskId) || (this.provisionalRelatedAgentCounts.get(taskId) ?? 0) > 0) {
2874
+ return true;
2875
+ }
2876
+ if (this.todoStopGuardBackgroundBaseline.agents.has(taskId)) return false;
2877
+ if (visiting.has(taskId)) return false;
2878
+ const task = this.config.getBackgroundTaskRegistry?.()?.get?.(taskId);
2879
+ if (!task) return false;
2880
+ if (!task.parentAgentId) return true;
2881
+ visiting.add(taskId);
2882
+ const related = this.#agentContinuesTodoStopGuardWorkChain(
2883
+ task.parentAgentId,
2884
+ visiting
2885
+ );
2886
+ visiting.delete(taskId);
2887
+ return related;
2888
+ }
2889
+ #monitorContinuesTodoStopGuardWorkChain(monitorId, ownerAgentId) {
2890
+ if (ownerAgentId) {
2891
+ return this.#agentContinuesTodoStopGuardWorkChain(ownerAgentId);
2892
+ }
2893
+ return !this.todoStopGuardBackgroundBaseline.monitors.has(monitorId);
2894
+ }
2746
2895
  #hasRelevantTodoStopGuardBackgroundInput() {
2747
2896
  if (this.notificationQueue.some(
2748
2897
  (item) => this.#notificationContinuesTodoStopGuardWorkChain(item)
@@ -2754,7 +2903,7 @@ var Session = class {
2754
2903
  const baseline = this.todoStopGuardBackgroundBaseline;
2755
2904
  const agents = this.config.getBackgroundTaskRegistry?.()?.getAll?.() ?? [];
2756
2905
  if (agents.some(
2757
- (task) => !baseline.agents.has(task.id) && task.isBackgrounded && (task.status === "running" || task.status === "paused" || task.status === "cancelled" && !task.notified)
2906
+ (task) => this.#agentContinuesTodoStopGuardWorkChain(task.id) && task.isBackgrounded && (task.status === "running" || task.status === "paused" || task.status === "cancelled" && !task.notified)
2758
2907
  )) {
2759
2908
  return true;
2760
2909
  }
@@ -2766,7 +2915,10 @@ var Session = class {
2766
2915
  }
2767
2916
  const monitors = this.config.getMonitorRegistry?.()?.getAll?.() ?? [];
2768
2917
  if (monitors.some(
2769
- (task) => !baseline.monitors.has(task.id) && task.status === "running"
2918
+ (task) => this.#monitorContinuesTodoStopGuardWorkChain(
2919
+ task.id,
2920
+ task.ownerAgentId
2921
+ ) && task.status === "running"
2770
2922
  )) {
2771
2923
  return true;
2772
2924
  }
@@ -2897,12 +3049,19 @@ var Session = class {
2897
3049
  return this.closeGateCompletion ?? Promise.resolve();
2898
3050
  }
2899
3051
  async waitForActiveTurnsToSettle() {
2900
- const pending = [
2901
- this.pendingPromptCompletion,
2902
- this.cronCompletion,
2903
- this.notificationCompletion
2904
- ].filter((completion) => completion !== null);
2905
- await Promise.allSettled(pending);
3052
+ while (this.#hasActiveTurn()) {
3053
+ const pending = [
3054
+ this.pendingPromptCompletion,
3055
+ this.cronCompletion,
3056
+ this.notificationCompletion
3057
+ ].filter(
3058
+ (completion) => completion !== null
3059
+ );
3060
+ if (pending.length > 0) {
3061
+ await Promise.allSettled(pending);
3062
+ }
3063
+ await new Promise((resolve5) => setImmediate(resolve5));
3064
+ }
2906
3065
  }
2907
3066
  #deferAutomaticQueueDrainUntilTurnsSettle() {
2908
3067
  const completions = [
@@ -2931,12 +3090,12 @@ var Session = class {
2931
3090
  dispose() {
2932
3091
  this.disposed = true;
2933
3092
  this.closing = true;
3093
+ this.pendingPrompt?.abort(SESSION_DISPOSE_ABORT_REASON);
3094
+ this.pendingPrompt = null;
2934
3095
  this.resolveCloseGate?.();
2935
3096
  this.resolveCloseGate = null;
2936
3097
  this.closeGateCompletion = null;
2937
- this.todoStopGuardQueuedPromptPriority = false;
2938
- this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
2939
- this.todoStopGuard.clearTrust();
3098
+ this.hardSuspendTodoStopGuard();
2940
3099
  this.notificationQueue = [];
2941
3100
  this.cronQueue = [];
2942
3101
  this.notificationAbortController?.abort();
@@ -3177,6 +3336,9 @@ var Session = class {
3177
3336
  throw RequestError.invalidParams(void 0, "Session is closing");
3178
3337
  }
3179
3338
  await this.assertCanStartTurn();
3339
+ if (this.closing) {
3340
+ throw RequestError.invalidParams(void 0, "Session is closing");
3341
+ }
3180
3342
  if (admissionCancellation?.aborted) {
3181
3343
  return { stopReason: "cancelled" };
3182
3344
  }
@@ -3238,9 +3400,9 @@ var Session = class {
3238
3400
  return { stopReason: "cancelled" };
3239
3401
  }
3240
3402
  if (todoStopGuardPreparation.startsWorkChain) {
3241
- this.todoStopGuardQueuedPromptPriority = false;
3403
+ this.#clearTodoStopGuardQueuedPromptWait();
3242
3404
  this.todoStopGuard.startOrdinaryPrompt();
3243
- this.todoStopGuardBackgroundBaseline = this.#captureTodoStopGuardBackgroundBaseline();
3405
+ this.#resetTodoStopGuardBackgroundLineage();
3244
3406
  }
3245
3407
  this.duplicateProviderToolCallResponseIds.clear();
3246
3408
  const channelDelivery = parsePromptChannelDelivery(params);
@@ -3281,9 +3443,12 @@ var Session = class {
3281
3443
  }
3282
3444
  throw error;
3283
3445
  } finally {
3446
+ const stillOwnsPendingPrompt = this.pendingPrompt === pendingSend;
3284
3447
  releasePendingSend();
3285
3448
  const shouldDrainAutomaticQueues = todoStopGuardPreparation.drainSupersededAutomaticQueues || this.todoStopGuardDrainAutomaticQueuesWhenIdle || this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuard.hasCommittedContinuation || this.todoStopGuardQueuedPromptPriority;
3286
- this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
3449
+ if (stillOwnsPendingPrompt) {
3450
+ this.todoStopGuardDrainAutomaticQueuesWhenIdle = false;
3451
+ }
3287
3452
  if (shouldDrainAutomaticQueues) {
3288
3453
  void this.#drainCronQueue();
3289
3454
  void this.#drainNotificationQueue();
@@ -3504,6 +3669,9 @@ var Session = class {
3504
3669
  let parts;
3505
3670
  let fullTurnModelOverride;
3506
3671
  const onFullTurnModel = /* @__PURE__ */ __name((model) => {
3672
+ if (fullTurnModelOverride === model) {
3673
+ return true;
3674
+ }
3507
3675
  if (fullTurnModelOverride) {
3508
3676
  return false;
3509
3677
  }
@@ -3712,7 +3880,8 @@ ${this.pendingRecoveredAgentsNotice}
3712
3880
  }
3713
3881
  strippedOrphanEntries = null;
3714
3882
  }
3715
- if (pendingSend.signal.aborted && pendingSend.signal.reason === USER_CANCEL_ABORT_REASON && this.#isAbortError(error)) {
3883
+ const isControlledCancellation = pendingSend.signal.aborted && (pendingSend.signal.reason === USER_CANCEL_ABORT_REASON || pendingSend.signal.reason === SESSION_DISPOSE_ABORT_REASON);
3884
+ if (isControlledCancellation) {
3716
3885
  this.todoStopGuard.suspend();
3717
3886
  return { stopReason: "cancelled" };
3718
3887
  }
@@ -3764,7 +3933,8 @@ ${this.pendingRecoveredAgentsNotice}
3764
3933
  pendingSend.signal,
3765
3934
  promptId,
3766
3935
  functionCalls,
3767
- toolLoopState
3936
+ toolLoopState,
3937
+ onFullTurnModel
3768
3938
  )
3769
3939
  );
3770
3940
  if (toolRun.stopAfterPermissionCancel) {
@@ -3836,6 +4006,9 @@ ${this.pendingRecoveredAgentsNotice}
3836
4006
  let stopHookIterationCount = 0;
3837
4007
  let stopHookReasons = [];
3838
4008
  const onFullTurnModel = /* @__PURE__ */ __name((model) => {
4009
+ if (modelOverride === model) {
4010
+ return true;
4011
+ }
3839
4012
  if (modelOverride) {
3840
4013
  return false;
3841
4014
  }
@@ -3844,6 +4017,9 @@ ${this.pendingRecoveredAgentsNotice}
3844
4017
  }, "onFullTurnModel");
3845
4018
  let midTurnContinuationCount = 0;
3846
4019
  while (true) {
4020
+ if (this.pendingPrompt && this.pendingPrompt !== pendingSend) {
4021
+ return { stopReason: "cancelled" };
4022
+ }
3847
4023
  if (pendingSend.signal.aborted) {
3848
4024
  this.todoStopGuard.suspend();
3849
4025
  return { stopReason: "cancelled" };
@@ -3855,15 +4031,26 @@ ${this.pendingRecoveredAgentsNotice}
3855
4031
  return { stopReason: "end_turn" };
3856
4032
  }
3857
4033
  if (this.todoStopGuard.needsStopInspection) {
3858
- this.#beginTodoStopGuardQueuedPromptCheck();
3859
4034
  const drained = await this.#drainMidTurnInput(pendingSend.signal, {
3860
4035
  watchQueuedPromptForTodoStopGuard: true,
3861
4036
  onFullTurnModel
3862
4037
  });
3863
- const waitsForQueuedPrompt = this.#finishTodoStopGuardQueuedPromptCheck(
3864
- drained.hasQueuedPrompt
3865
- );
3866
4038
  if (drained.parts.length > 0) {
4039
+ if (drained.hasQueuedPrompt) {
4040
+ const claim = await this.#claimTodoStopGuardContinuation(
4041
+ pendingSend.signal
4042
+ );
4043
+ if (claim === "queued") {
4044
+ this.#preserveUnsentMessageHistory(
4045
+ { role: "user", parts: drained.parts },
4046
+ true
4047
+ );
4048
+ return { stopReason: "end_turn" };
4049
+ }
4050
+ if (claim === "unavailable") {
4051
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4052
+ }
4053
+ }
3867
4054
  this.todoStopGuard.acceptMidTurnUserInput();
3868
4055
  const continuation2 = await this.#runStopContinuation(
3869
4056
  pendingSend,
@@ -3882,13 +4069,22 @@ ${this.pendingRecoveredAgentsNotice}
3882
4069
  }
3883
4070
  continue;
3884
4071
  }
3885
- if (waitsForQueuedPrompt) {
3886
- return { stopReason: "end_turn" };
4072
+ if (!drained.reliable) {
4073
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4074
+ } else if (drained.hasQueuedPrompt) {
4075
+ const claim = await this.#claimTodoStopGuardContinuation(
4076
+ pendingSend.signal
4077
+ );
4078
+ if (claim === "queued") {
4079
+ return { stopReason: "end_turn" };
4080
+ }
4081
+ if (claim === "unavailable") {
4082
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4083
+ }
3887
4084
  }
3888
4085
  }
3889
4086
  let externalReason = null;
3890
4087
  let stopHookCount = 1;
3891
- let queuedPromptArrivedDuringStopHook = false;
3892
4088
  if (allowExternalHooks && hooksEnabled && messageBus && stopHookIterationCount < stopHookBlockingCap && this.config.hasHooksForEvent?.("Stop")) {
3893
4089
  const responseText = this.#getCurrentChat().getLastModelMessageText?.() || "[no response text]";
3894
4090
  const contextUsage = buildContextUsage(
@@ -3919,14 +4115,26 @@ ${this.pendingRecoveredAgentsNotice}
3919
4115
  return { stopReason: "cancelled" };
3920
4116
  }
3921
4117
  if (this.todoStopGuard.needsStopInspection) {
3922
- this.#beginTodoStopGuardQueuedPromptCheck();
3923
4118
  const drained = await this.#drainMidTurnInput(pendingSend.signal, {
3924
4119
  watchQueuedPromptForTodoStopGuard: true,
3925
4120
  onFullTurnModel
3926
4121
  });
3927
- const waitsForQueuedPrompt = this.#finishTodoStopGuardQueuedPromptCheck(drained.hasQueuedPrompt);
3928
- queuedPromptArrivedDuringStopHook = waitsForQueuedPrompt;
3929
4122
  if (drained.parts.length > 0) {
4123
+ if (drained.hasQueuedPrompt) {
4124
+ const claim = await this.#claimTodoStopGuardContinuation(
4125
+ pendingSend.signal
4126
+ );
4127
+ if (claim === "queued") {
4128
+ this.#preserveUnsentMessageHistory(
4129
+ { role: "user", parts: drained.parts },
4130
+ true
4131
+ );
4132
+ return { stopReason: "end_turn" };
4133
+ }
4134
+ if (claim === "unavailable") {
4135
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4136
+ }
4137
+ }
3930
4138
  this.todoStopGuard.acceptMidTurnUserInput();
3931
4139
  const continuation2 = await this.#runStopContinuation(
3932
4140
  pendingSend,
@@ -3943,6 +4151,20 @@ ${this.pendingRecoveredAgentsNotice}
3943
4151
  if (continuation2.kind === "terminal") {
3944
4152
  return { stopReason: continuation2.stopReason };
3945
4153
  }
4154
+ continue;
4155
+ }
4156
+ if (!drained.reliable) {
4157
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4158
+ } else if (drained.hasQueuedPrompt) {
4159
+ const claim = await this.#claimTodoStopGuardContinuation(
4160
+ pendingSend.signal
4161
+ );
4162
+ if (claim === "queued") {
4163
+ return { stopReason: "end_turn" };
4164
+ }
4165
+ if (claim === "unavailable") {
4166
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4167
+ }
3946
4168
  }
3947
4169
  }
3948
4170
  const hookOutput = response.output ? createHookOutput("Stop", response.output) : void 0;
@@ -3955,9 +4177,13 @@ ${this.pendingRecoveredAgentsNotice}
3955
4177
  stopHookIterationCount++;
3956
4178
  stopHookReasons = [...stopHookReasons, externalReason];
3957
4179
  stopHookCount = response.stopHookCount ?? 1;
4180
+ } else {
4181
+ stopHookIterationCount = 0;
4182
+ stopHookReasons = [];
4183
+ stopHookCount = 1;
3958
4184
  }
3959
4185
  }
3960
- const guardDecision = queuedPromptArrivedDuringStopHook ? null : this.todoStopGuard.decide(
4186
+ const guardDecision = this.todoStopGuard.decide(
3961
4187
  this.todoStopGuard.needsStopInspection ? this.#hasRelevantTodoStopGuardBackgroundInput() : false
3962
4188
  );
3963
4189
  const guardContinuation = guardDecision?.kind === "continue" ? guardDecision : null;
@@ -3980,9 +4206,6 @@ ${this.pendingRecoveredAgentsNotice}
3980
4206
  debugLogger6.warn(warning);
3981
4207
  return { stopReason: "end_turn" };
3982
4208
  }
3983
- if (queuedPromptArrivedDuringStopHook) {
3984
- return { stopReason: "end_turn" };
3985
- }
3986
4209
  if (!externalReason && !guardContinuation) {
3987
4210
  return { stopReason: "end_turn" };
3988
4211
  }
@@ -4038,8 +4261,27 @@ ${this.pendingRecoveredAgentsNotice}
4038
4261
  let initialSend = true;
4039
4262
  let automaticContinuationValidated = false;
4040
4263
  let supersededAutomaticContinuation = false;
4264
+ const preservePendingMessage = /* @__PURE__ */ __name((message) => {
4265
+ if (initialSend) return;
4266
+ const preservedParts = (message.parts ?? []).filter(
4267
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4268
+ );
4269
+ this.#preserveUnsentMessageHistory(
4270
+ preservedParts.length > 0 ? { ...message, parts: preservedParts } : null,
4271
+ true
4272
+ );
4273
+ }, "preservePendingMessage");
4041
4274
  while (nextMessage !== null) {
4275
+ if (this.pendingPrompt && this.pendingPrompt !== pendingSend) {
4276
+ preservePendingMessage(nextMessage);
4277
+ return {
4278
+ kind: "terminal",
4279
+ stopReason: "cancelled",
4280
+ ...supersededAutomaticContinuation ? { supersededAutomaticContinuation: true } : {}
4281
+ };
4282
+ }
4042
4283
  if (pendingSend.signal.aborted) {
4284
+ preservePendingMessage(nextMessage);
4043
4285
  this.todoStopGuard.suspend();
4044
4286
  return {
4045
4287
  kind: "terminal",
@@ -4057,12 +4299,18 @@ ${this.pendingRecoveredAgentsNotice}
4057
4299
  let guardForThisSend = nextGuardContinuation;
4058
4300
  let preserveGuardOnSkippedSend = false;
4059
4301
  let messageForPreservation = nextMessage;
4302
+ let preparedMessage = nextMessage.parts ?? [];
4303
+ let preservePreparedMessageOnSkippedSend = !guardForThisSend && preparedMessage.some(
4304
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4305
+ );
4060
4306
  const externalParts = initialSend ? options.externalParts : void 0;
4061
4307
  const promptIdForSend = guardForThisSend && guardForThisSend.attempt !== options.guardContinuation?.attempt ? toolPromptId + "_todo_stop_guard_" + guardForThisSend.attempt : streamPromptId;
4062
4308
  const messageDisplay = this.#createMessageDisplayDispatcher(
4063
4309
  pendingSend.signal
4064
4310
  );
4065
4311
  let channelDeliveryResponseBlock;
4312
+ let providerSendChat;
4313
+ let userContentPushCountBeforeSend = 0;
4066
4314
  try {
4067
4315
  const sendResult = await this.#sendMessageStreamWithAutoCompression(
4068
4316
  promptIdForSend,
@@ -4071,44 +4319,134 @@ ${this.pendingRecoveredAgentsNotice}
4071
4319
  {
4072
4320
  skipCompression: skipCompression || (guardForThisSend?.attempt ?? 0) > 1,
4073
4321
  getModelOverride: options.getModelOverride,
4074
- beforeSend: guardForThisSend || !automaticContinuationValidated && options.onAutomaticContinuationValidated ? async ({ compressionFailed }) => {
4075
- const inspectGuardPriority = guardForThisSend !== void 0;
4076
- const guardCompressionFailed = inspectGuardPriority && compressionFailed;
4077
- if (inspectGuardPriority) {
4078
- this.#beginTodoStopGuardQueuedPromptCheck();
4079
- const drained = await this.#drainMidTurnInput(
4080
- pendingSend.signal,
4081
- {
4082
- watchQueuedPromptForTodoStopGuard: true,
4083
- onFullTurnModel: options.onFullTurnModel
4322
+ prepareBeforeCompression: guardForThisSend ? async () => {
4323
+ const drained = await this.#drainMidTurnInput(
4324
+ pendingSend.signal,
4325
+ {
4326
+ watchQueuedPromptForTodoStopGuard: true,
4327
+ onFullTurnModel: options.onFullTurnModel
4328
+ }
4329
+ );
4330
+ if (drained.parts.length > 0) {
4331
+ if (drained.hasQueuedPrompt) {
4332
+ const claim = await this.#claimTodoStopGuardContinuation(
4333
+ pendingSend.signal
4334
+ );
4335
+ if (claim === "queued") {
4336
+ guardForThisSend = void 0;
4337
+ nextGuardContinuation = void 0;
4338
+ preserveGuardOnSkippedSend = true;
4339
+ preservePreparedMessageOnSkippedSend = true;
4340
+ messageForPreservation = {
4341
+ role: "user",
4342
+ parts: drained.parts
4343
+ };
4344
+ if (initialSend) {
4345
+ supersededAutomaticContinuation = true;
4346
+ }
4347
+ return { kind: "stop", stopReason: "end_turn" };
4084
4348
  }
4349
+ if (claim === "unavailable") {
4350
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4351
+ }
4352
+ }
4353
+ preservePreparedMessageOnSkippedSend = true;
4354
+ this.todoStopGuard.acceptMidTurnUserInput();
4355
+ guardForThisSend = void 0;
4356
+ nextGuardContinuation = void 0;
4357
+ if (initialSend) {
4358
+ supersededAutomaticContinuation = true;
4359
+ }
4360
+ preparedMessage = initialSend ? drained.parts : [
4361
+ ...(nextMessage?.parts ?? []).filter(
4362
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4363
+ ),
4364
+ ...drained.parts
4365
+ ];
4366
+ messageForPreservation = {
4367
+ role: "user",
4368
+ parts: preparedMessage
4369
+ };
4370
+ return { kind: "send", message: preparedMessage };
4371
+ }
4372
+ if (!drained.reliable) {
4373
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4374
+ guardForThisSend = void 0;
4375
+ nextGuardContinuation = void 0;
4376
+ if (!options.externalParts) {
4377
+ preserveGuardOnSkippedSend = true;
4378
+ return { kind: "stop", stopReason: "end_turn" };
4379
+ }
4380
+ if (!initialSend && nextMessage) {
4381
+ nextMessage = {
4382
+ ...nextMessage,
4383
+ parts: (nextMessage.parts ?? []).filter(
4384
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4385
+ )
4386
+ };
4387
+ }
4388
+ } else if (drained.hasQueuedPrompt) {
4389
+ const probe = await this.#claimTodoStopGuardContinuation(
4390
+ pendingSend.signal
4085
4391
  );
4086
- const waitsForQueuedPrompt = this.#finishTodoStopGuardQueuedPromptCheck(
4087
- drained.hasQueuedPrompt
4088
- );
4089
- if (drained.parts.length > 0) {
4090
- this.todoStopGuard.acceptMidTurnUserInput();
4392
+ if (probe === "queued") {
4091
4393
  guardForThisSend = void 0;
4092
4394
  nextGuardContinuation = void 0;
4395
+ preserveGuardOnSkippedSend = true;
4093
4396
  if (initialSend) {
4094
4397
  supersededAutomaticContinuation = true;
4095
4398
  }
4096
- const replacementMessage = initialSend ? drained.parts : [
4097
- ...(nextMessage?.parts ?? []).filter(
4098
- (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4099
- ),
4100
- ...drained.parts
4101
- ];
4102
- messageForPreservation = {
4103
- role: "user",
4104
- parts: replacementMessage
4105
- };
4106
- return {
4107
- kind: "send",
4108
- message: replacementMessage
4109
- };
4399
+ return { kind: "stop", stopReason: "end_turn" };
4400
+ }
4401
+ if (probe === "unavailable") {
4402
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4403
+ guardForThisSend = void 0;
4404
+ nextGuardContinuation = void 0;
4405
+ if (!options.externalParts) {
4406
+ preserveGuardOnSkippedSend = true;
4407
+ return { kind: "stop", stopReason: "end_turn" };
4408
+ }
4409
+ if (!initialSend && nextMessage) {
4410
+ nextMessage = {
4411
+ ...nextMessage,
4412
+ parts: (nextMessage.parts ?? []).filter(
4413
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4414
+ )
4415
+ };
4416
+ }
4417
+ }
4418
+ }
4419
+ if (guardForThisSend && this.config.getApprovalMode() === "plan" /* PLAN */) {
4420
+ this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
4421
+ }
4422
+ if (guardForThisSend) {
4423
+ const hasRelevantBackgroundInput = this.#hasRelevantTodoStopGuardBackgroundInput();
4424
+ const refreshedDecision = guardForThisSend.toolClosure ? this.todoStopGuard.decideToolClosure(
4425
+ guardForThisSend.attempt - 1,
4426
+ hasRelevantBackgroundInput
4427
+ ) : this.todoStopGuard.decide(hasRelevantBackgroundInput);
4428
+ if (refreshedDecision.kind !== "continue" || refreshedDecision.attempt !== guardForThisSend.attempt) {
4429
+ guardForThisSend = void 0;
4430
+ nextGuardContinuation = void 0;
4431
+ if (!options.externalParts) {
4432
+ preserveGuardOnSkippedSend = true;
4433
+ return { kind: "stop", stopReason: "end_turn" };
4434
+ }
4435
+ if (!initialSend && nextMessage) {
4436
+ nextMessage = {
4437
+ ...nextMessage,
4438
+ parts: (nextMessage.parts ?? []).filter(
4439
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4440
+ )
4441
+ };
4442
+ }
4110
4443
  }
4111
- if (waitsForQueuedPrompt) {
4444
+ }
4445
+ if (guardForThisSend) {
4446
+ const claim = await this.#claimTodoStopGuardContinuation(
4447
+ pendingSend.signal
4448
+ );
4449
+ if (claim === "queued") {
4112
4450
  guardForThisSend = void 0;
4113
4451
  nextGuardContinuation = void 0;
4114
4452
  preserveGuardOnSkippedSend = true;
@@ -4117,41 +4455,21 @@ ${this.pendingRecoveredAgentsNotice}
4117
4455
  }
4118
4456
  return { kind: "stop", stopReason: "end_turn" };
4119
4457
  }
4120
- if (guardCompressionFailed) {
4121
- this.todoStopGuard.suspend();
4458
+ if (claim === "unavailable") {
4459
+ this.todoStopGuard.blockUntilOrdinaryPromptStarts();
4122
4460
  guardForThisSend = void 0;
4123
4461
  nextGuardContinuation = void 0;
4124
- if (!externalParts || externalParts.length === 0) {
4462
+ if (!options.externalParts) {
4125
4463
  preserveGuardOnSkippedSend = true;
4126
4464
  return { kind: "stop", stopReason: "end_turn" };
4127
4465
  }
4128
- }
4129
- if (guardForThisSend && this.config.getApprovalMode() === "plan" /* PLAN */) {
4130
- this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
4131
- }
4132
- if (guardForThisSend) {
4133
- const hasRelevantBackgroundInput = this.#hasRelevantTodoStopGuardBackgroundInput();
4134
- const refreshedDecision = guardForThisSend.toolClosure ? this.todoStopGuard.decideToolClosure(
4135
- guardForThisSend.attempt - 1,
4136
- hasRelevantBackgroundInput
4137
- ) : this.todoStopGuard.decide(
4138
- hasRelevantBackgroundInput
4139
- );
4140
- if (refreshedDecision.kind !== "continue" || refreshedDecision.attempt !== guardForThisSend.attempt) {
4141
- guardForThisSend = void 0;
4142
- nextGuardContinuation = void 0;
4143
- if (!options.externalParts) {
4144
- preserveGuardOnSkippedSend = true;
4145
- return { kind: "stop", stopReason: "end_turn" };
4146
- }
4147
- if (!initialSend && nextMessage) {
4148
- nextMessage = {
4149
- ...nextMessage,
4150
- parts: (nextMessage.parts ?? []).filter(
4151
- (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4152
- )
4153
- };
4154
- }
4466
+ if (!initialSend && nextMessage) {
4467
+ nextMessage = {
4468
+ ...nextMessage,
4469
+ parts: (nextMessage.parts ?? []).filter(
4470
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4471
+ )
4472
+ };
4155
4473
  }
4156
4474
  }
4157
4475
  }
@@ -4159,16 +4477,42 @@ ${this.pendingRecoveredAgentsNotice}
4159
4477
  await options.onAutomaticContinuationValidated();
4160
4478
  automaticContinuationValidated = true;
4161
4479
  }
4162
- const selectedMessage = guardForThisSend || !externalParts ? nextMessage?.parts ?? [] : externalParts;
4480
+ preparedMessage = guardForThisSend || !externalParts ? nextMessage?.parts ?? [] : externalParts;
4163
4481
  messageForPreservation = {
4164
4482
  role: "user",
4165
- parts: selectedMessage
4483
+ parts: preparedMessage
4166
4484
  };
4167
- return {
4168
- kind: "send",
4169
- message: selectedMessage
4485
+ preservePreparedMessageOnSkippedSend = preparedMessage.some(
4486
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4487
+ );
4488
+ return { kind: "send", message: preparedMessage };
4489
+ } : void 0,
4490
+ beforeSend: /* @__PURE__ */ __name(async ({ compressionFailed }) => {
4491
+ if (guardForThisSend && compressionFailed) {
4492
+ this.todoStopGuard.suspend();
4493
+ guardForThisSend = void 0;
4494
+ nextGuardContinuation = void 0;
4495
+ if (!options.externalParts) {
4496
+ preserveGuardOnSkippedSend = true;
4497
+ return { kind: "stop", stopReason: "end_turn" };
4498
+ }
4499
+ preparedMessage = initialSend && externalParts ? externalParts : preparedMessage.filter(
4500
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4501
+ );
4502
+ preservePreparedMessageOnSkippedSend = true;
4503
+ }
4504
+ if (!automaticContinuationValidated && options.onAutomaticContinuationValidated) {
4505
+ await options.onAutomaticContinuationValidated();
4506
+ automaticContinuationValidated = true;
4507
+ }
4508
+ messageForPreservation = {
4509
+ role: "user",
4510
+ parts: preparedMessage
4170
4511
  };
4171
- } : void 0
4512
+ providerSendChat = this.#getCurrentChat();
4513
+ userContentPushCountBeforeSend = providerSendChat.getUserContentPushCount?.() ?? 0;
4514
+ return { kind: "send", message: preparedMessage };
4515
+ }, "beforeSend")
4172
4516
  }
4173
4517
  );
4174
4518
  if (!sendResult.responseStream) {
@@ -4184,7 +4528,7 @@ ${this.pendingRecoveredAgentsNotice}
4184
4528
  );
4185
4529
  this.#preserveUnsentMessageHistory(
4186
4530
  preservedParts.length > 0 ? { ...messageForPreservation, parts: preservedParts } : null,
4187
- sendResult.stopReason === "cancelled"
4531
+ sendResult.stopReason === "cancelled" || preservePreparedMessageOnSkippedSend
4188
4532
  );
4189
4533
  return {
4190
4534
  kind: "terminal",
@@ -4206,7 +4550,7 @@ ${this.pendingRecoveredAgentsNotice}
4206
4550
  if (guardCommitted) {
4207
4551
  await this.#emitTodoStopGuardContinuation(guardForThisSend);
4208
4552
  }
4209
- if (!guardCommitted && externalParts) {
4553
+ if (!guardCommitted && options.externalParts) {
4210
4554
  guardForThisSend = void 0;
4211
4555
  }
4212
4556
  }
@@ -4260,6 +4604,24 @@ ${this.pendingRecoveredAgentsNotice}
4260
4604
  }
4261
4605
  } catch (error) {
4262
4606
  streamFailed = true;
4607
+ const preservedParts = (messageForPreservation.parts ?? []).filter(
4608
+ (part) => !("text" in part && isTodoStopGuardPromptText(part.text))
4609
+ );
4610
+ if (preservedParts.length > 0 && (!providerSendChat || (providerSendChat.getUserContentPushCount?.() ?? 0) <= userContentPushCountBeforeSend)) {
4611
+ this.#preserveUnsentMessageHistory(
4612
+ { ...messageForPreservation, parts: preservedParts },
4613
+ true
4614
+ );
4615
+ }
4616
+ const isControlledCancellation = pendingSend.signal.aborted && (pendingSend.signal.reason === USER_CANCEL_ABORT_REASON || pendingSend.signal.reason === SESSION_DISPOSE_ABORT_REASON);
4617
+ if (isControlledCancellation) {
4618
+ this.todoStopGuard.suspend();
4619
+ return {
4620
+ kind: "terminal",
4621
+ stopReason: "cancelled",
4622
+ ...supersededAutomaticContinuation ? { supersededAutomaticContinuation: true } : {}
4623
+ };
4624
+ }
4263
4625
  this.todoStopGuard.pauseForTrustedRetry();
4264
4626
  const errorStatus = getErrorStatus(error);
4265
4627
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -4309,7 +4671,8 @@ ${this.pendingRecoveredAgentsNotice}
4309
4671
  pendingSend.signal,
4310
4672
  toolPromptId,
4311
4673
  functionCalls,
4312
- toolLoopState
4674
+ toolLoopState,
4675
+ options.onFullTurnModel
4313
4676
  )
4314
4677
  );
4315
4678
  if (toolRun.stopAfterPermissionCancel || toolRun.loopDetected) {
@@ -4467,6 +4830,19 @@ ${this.pendingRecoveredAgentsNotice}
4467
4830
  */
4468
4831
  async #sendMessageStreamWithAutoCompression(promptId, message, abortSignal, options = {}) {
4469
4832
  const geminiClient = this.config.getGeminiClient();
4833
+ if (options.prepareBeforeCompression) {
4834
+ const decision = await options.prepareBeforeCompression();
4835
+ if (decision.kind === "stop") {
4836
+ return { responseStream: null, stopReason: decision.stopReason };
4837
+ }
4838
+ message = decision.message;
4839
+ }
4840
+ if (abortSignal.aborted) {
4841
+ debugLogger6.debug(
4842
+ `Send aborted after pre-compression preparation for prompt ${promptId}`
4843
+ );
4844
+ return { responseStream: null, stopReason: "cancelled" };
4845
+ }
4470
4846
  let compressionDiagnostic = null;
4471
4847
  let compressionInfo = null;
4472
4848
  let compressionFailed = false;
@@ -4488,10 +4864,13 @@ ${this.pendingRecoveredAgentsNotice}
4488
4864
  compressionDiagnostic = `IMPORTANT: This conversation ${reasonClause}. A compressed context will be sent for future messages (compressed from: ${compressed.originalTokenCount ?? "unknown"} to ${compressed.newTokenCount ?? "unknown"} tokens).`;
4489
4865
  }
4490
4866
  } catch (compressionError) {
4491
- if (abortSignal.aborted || this.#isAbortError(compressionError)) {
4867
+ if (abortSignal.aborted) {
4492
4868
  debugLogger6.debug(`Auto-compression aborted for prompt ${promptId}`);
4493
4869
  return { responseStream: null, stopReason: "cancelled" };
4494
4870
  }
4871
+ if (this.#isAbortError(compressionError)) {
4872
+ throw compressionError;
4873
+ }
4495
4874
  debugLogger6.warn(
4496
4875
  `Auto-compression failed for prompt ${promptId}; proceeding without compression: ` + this.#formatError(compressionError)
4497
4876
  );
@@ -4706,7 +5085,8 @@ ${this.pendingRecoveredAgentsNotice}
4706
5085
  if (this.midTurnDrainUnavailable) {
4707
5086
  return {
4708
5087
  parts: await this.#buildMidTurnParts(recovered, abortSignal, options),
4709
- hasQueuedPrompt: false
5088
+ hasQueuedPrompt: false,
5089
+ reliable: false
4710
5090
  };
4711
5091
  }
4712
5092
  let drainPromise;
@@ -4729,13 +5109,18 @@ ${this.pendingRecoveredAgentsNotice}
4729
5109
  clearTimeout(timeoutHandle);
4730
5110
  }
4731
5111
  this.midTurnDrainTimeoutStrikes = 0;
5112
+ const reliable = isValidMidTurnDrainResponse(
5113
+ response,
5114
+ options.watchQueuedPromptForTodoStopGuard === true
5115
+ );
4732
5116
  return {
4733
5117
  parts: await this.#buildMidTurnParts(
4734
5118
  [...recovered, ...parseMidTurnDrainResponse(response)],
4735
5119
  abortSignal,
4736
5120
  options
4737
5121
  ),
4738
- hasQueuedPrompt: isRecord2(response) && response["hasQueuedPrompt"] === true
5122
+ hasQueuedPrompt: isRecord2(response) && response["hasQueuedPrompt"] === true,
5123
+ reliable
4739
5124
  };
4740
5125
  } catch (error) {
4741
5126
  const errorMessage = error instanceof Error ? error.message : error && typeof error === "object" && "message" in error ? String(error.message) : String(error);
@@ -4754,7 +5139,8 @@ ${this.pendingRecoveredAgentsNotice}
4754
5139
  );
4755
5140
  return {
4756
5141
  parts: await this.#buildMidTurnParts(recovered, abortSignal, options),
4757
- hasQueuedPrompt: false
5142
+ hasQueuedPrompt: false,
5143
+ reliable: false
4758
5144
  };
4759
5145
  }
4760
5146
  }
@@ -4894,26 +5280,39 @@ ${this.pendingRecoveredAgentsNotice}
4894
5280
  );
4895
5281
  }
4896
5282
  #enqueueCronPrompt(item) {
4897
- if ((this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuardQueuedPromptPriority) && !this.#cronContinuesTodoStopGuardWorkChain(item)) {
4898
- if (item.taskId) {
5283
+ const automaticWorkDeferred = this.todoStopGuard.blocksUnrelatedAutomaticTurns || this.todoStopGuardQueuedPromptPriority;
5284
+ if (automaticWorkDeferred) {
5285
+ const incomingIsRelated = this.#cronContinuesTodoStopGuardWorkChain(item);
5286
+ let shouldAppend = true;
5287
+ if (!incomingIsRelated && item.taskId) {
4899
5288
  const duplicateIndex = this.cronQueue.findIndex(
4900
5289
  (queued) => queued.taskId === item.taskId && !this.#cronContinuesTodoStopGuardWorkChain(queued)
4901
5290
  );
4902
5291
  if (duplicateIndex >= 0) {
4903
5292
  this.cronQueue[duplicateIndex] = item;
4904
- return;
5293
+ shouldAppend = false;
4905
5294
  }
4906
5295
  }
4907
- const unrelatedIndices = this.cronQueue.map(
4908
- (queued, index) => this.#cronContinuesTodoStopGuardWorkChain(queued) ? -1 : index
4909
- ).filter((index) => index >= 0);
4910
- if (unrelatedIndices.length >= MAX_DEFERRED_UNRELATED_CRON_QUEUE) {
4911
- const evictedIndex = unrelatedIndices[0];
5296
+ const maxBeforeAppend = MAX_DEFERRED_UNRELATED_CRON_QUEUE - (shouldAppend && !incomingIsRelated ? 1 : 0);
5297
+ let unrelatedCount = this.cronQueue.filter(
5298
+ (queued) => !this.#cronContinuesTodoStopGuardWorkChain(queued)
5299
+ ).length;
5300
+ const evictedTaskIds = [];
5301
+ while (unrelatedCount > maxBeforeAppend) {
5302
+ const evictedIndex = this.cronQueue.findIndex(
5303
+ (queued) => !this.#cronContinuesTodoStopGuardWorkChain(queued)
5304
+ );
5305
+ if (evictedIndex < 0) break;
4912
5306
  const [evicted] = this.cronQueue.splice(evictedIndex, 1);
5307
+ evictedTaskIds.push(evicted?.taskId ?? "unknown");
5308
+ unrelatedCount--;
5309
+ }
5310
+ if (evictedTaskIds.length > 0) {
4913
5311
  debugLogger6.warn(
4914
- `Cron queue overflow while automatic work is deferred: evicting task=${evicted?.taskId ?? "unknown"}`
5312
+ `Cron queue overflow while automatic work is deferred: evicted ${evictedTaskIds.length} unrelated task(s): ${evictedTaskIds.join(", ")}`
4915
5313
  );
4916
5314
  }
5315
+ if (!shouldAppend) return;
4917
5316
  }
4918
5317
  this.cronQueue.push(item);
4919
5318
  }
@@ -5315,6 +5714,7 @@ ${this.pendingRecoveredAgentsNotice}
5315
5714
  taskId: meta.agentId,
5316
5715
  status: meta.status,
5317
5716
  kind: "agent",
5717
+ continuesTodoStopGuardWorkChain: this.#agentContinuesTodoStopGuardWorkChain(meta.agentId),
5318
5718
  toolUseId: meta.toolUseId
5319
5719
  });
5320
5720
  }
@@ -5330,6 +5730,10 @@ ${this.pendingRecoveredAgentsNotice}
5330
5730
  taskId: meta.monitorId,
5331
5731
  status: meta.status,
5332
5732
  kind: "monitor",
5733
+ continuesTodoStopGuardWorkChain: this.#monitorContinuesTodoStopGuardWorkChain(
5734
+ meta.monitorId,
5735
+ meta.ownerAgentId
5736
+ ),
5333
5737
  toolUseId: meta.toolUseId
5334
5738
  });
5335
5739
  });
@@ -5340,7 +5744,8 @@ ${this.pendingRecoveredAgentsNotice}
5340
5744
  modelText,
5341
5745
  taskId: meta.shellId,
5342
5746
  status: meta.status,
5343
- kind: "shell"
5747
+ kind: "shell",
5748
+ continuesTodoStopGuardWorkChain: !this.todoStopGuardBackgroundBaseline.shells.has(meta.shellId)
5344
5749
  });
5345
5750
  });
5346
5751
  this.config.getChatRecordingService()?.setTitleRecordedCallback((customTitle, titleSource, sessionId) => {
@@ -5472,7 +5877,12 @@ ${this.pendingRecoveredAgentsNotice}
5472
5877
  if (ac.signal.aborted) return;
5473
5878
  await this.#emitBackgroundNotificationDisplay(item);
5474
5879
  const notificationParts = [{ text: item.modelText }];
5475
- this.config.getChatRecordingService()?.recordNotification(notificationParts, item.displayText);
5880
+ this.config.getChatRecordingService()?.recordNotification(notificationParts, item.displayText, {
5881
+ taskId: item.taskId,
5882
+ status: item.status,
5883
+ kind: item.kind,
5884
+ toolUseId: item.toolUseId
5885
+ });
5476
5886
  const notificationReminders = await this.#buildInitialSystemReminders();
5477
5887
  let nextMessage = {
5478
5888
  role: "user",
@@ -5925,7 +6335,7 @@ ${this.pendingRecoveredAgentsNotice}
5925
6335
  * sequential batch to preserve the implicit ordering the model may rely
5926
6336
  * on. Response-part ordering matches the original `functionCalls` order.
5927
6337
  */
5928
- async runToolCalls(abortSignal, promptId, functionCalls, toolLoopState) {
6338
+ async runToolCalls(abortSignal, promptId, functionCalls, toolLoopState, onFullTurnModel) {
5929
6339
  const dedupedFunctionCalls = dedupeToolCallsById(functionCalls);
5930
6340
  const generatedCallIdBase = randomUUID();
5931
6341
  const executionCallIds = new Map(
@@ -6202,7 +6612,8 @@ ${this.pendingRecoveredAgentsNotice}
6202
6612
  toolLoopState,
6203
6613
  recordSkippedToolCall,
6204
6614
  queueToolResultRecord,
6205
- executionCallIds.get(calls[i])
6615
+ executionCallIds.get(calls[i]),
6616
+ onFullTurnModel
6206
6617
  );
6207
6618
  results[i] = r;
6208
6619
  if (r.loopDetected) {
@@ -6236,7 +6647,8 @@ ${this.pendingRecoveredAgentsNotice}
6236
6647
  toolLoopState,
6237
6648
  recordSkippedToolCall,
6238
6649
  queueToolResultRecord,
6239
- executionCallIds.get(calls[idx])
6650
+ executionCallIds.get(calls[idx]),
6651
+ onFullTurnModel
6240
6652
  ).then((r) => {
6241
6653
  results[idx] = r;
6242
6654
  }).finally(() => {
@@ -6360,7 +6772,8 @@ ${this.pendingRecoveredAgentsNotice}
6360
6772
  toolLoopState,
6361
6773
  recordSkippedToolCall,
6362
6774
  queueToolResultRecord,
6363
- executionCallIds.get(fc)
6775
+ executionCallIds.get(fc),
6776
+ onFullTurnModel
6364
6777
  );
6365
6778
  parts.push(...r.parts);
6366
6779
  collectMemoryWriteCandidates(r);
@@ -6425,7 +6838,7 @@ ${this.pendingRecoveredAgentsNotice}
6425
6838
  }
6426
6839
  return reminders;
6427
6840
  }
6428
- async runTool(abortSignal, promptId, fc, onStopAfterPermissionCancel, toolLoopState, recordSkippedToolCall, queueToolResultRecord, generatedCallId) {
6841
+ async runTool(abortSignal, promptId, fc, onStopAfterPermissionCancel, toolLoopState, recordSkippedToolCall, queueToolResultRecord, generatedCallId, onFullTurnModel) {
6429
6842
  const callId = fc.id ?? generatedCallId ?? `${fc.name}-${Date.now()}`;
6430
6843
  let args = fc.args ?? {};
6431
6844
  if (toolLoopState?.loopDetected) {
@@ -6541,7 +6954,8 @@ ${this.pendingRecoveredAgentsNotice}
6541
6954
  call_id: callId,
6542
6955
  tool_name: policyToolName
6543
6956
  },
6544
- tool.description
6957
+ tool.description,
6958
+ promptId
6545
6959
  );
6546
6960
  let spanSuccess = false;
6547
6961
  try {
@@ -6580,6 +6994,10 @@ ${this.pendingRecoveredAgentsNotice}
6580
6994
  let toolBuildSucceeded = false;
6581
6995
  try {
6582
6996
  const invocation = tool.build(args);
6997
+ if (policyToolName === ToolNames.MONITOR) {
6998
+ const callIdAware = invocation;
6999
+ callIdAware.setCallId?.(callId);
7000
+ }
6583
7001
  toolBuildSucceeded = true;
6584
7002
  const taskEventEmitter = invocation.eventEmitter;
6585
7003
  if (isAgentTool && taskEventEmitter) {
@@ -7095,6 +7513,33 @@ ${this.pendingRecoveredAgentsNotice}
7095
7513
  );
7096
7514
  }
7097
7515
  }
7516
+ const continuedAgentId = toolName === ToolNames.SEND_MESSAGE && typeof args["task_id"] === "string" && args["task_id"].length > 0 ? args["task_id"] : void 0;
7517
+ const provisionalRelatedAgent = continuedAgentId !== void 0 && !this.relatedAgentIds.has(continuedAgentId);
7518
+ if (provisionalRelatedAgent) {
7519
+ this.provisionalRelatedAgentCounts.set(
7520
+ continuedAgentId,
7521
+ (this.provisionalRelatedAgentCounts.get(continuedAgentId) ?? 0) + 1
7522
+ );
7523
+ }
7524
+ let relatedAgentSettled = false;
7525
+ const settleRelatedAgent = /* @__PURE__ */ __name((succeeded2) => {
7526
+ if (relatedAgentSettled || !provisionalRelatedAgent || !continuedAgentId) {
7527
+ return;
7528
+ }
7529
+ relatedAgentSettled = true;
7530
+ const remaining = (this.provisionalRelatedAgentCounts.get(continuedAgentId) ?? 1) - 1;
7531
+ if (remaining > 0) {
7532
+ this.provisionalRelatedAgentCounts.set(
7533
+ continuedAgentId,
7534
+ remaining
7535
+ );
7536
+ } else {
7537
+ this.provisionalRelatedAgentCounts.delete(continuedAgentId);
7538
+ }
7539
+ if (succeeded2) {
7540
+ this.relatedAgentIds.add(continuedAgentId);
7541
+ }
7542
+ }, "settleRelatedAgent");
7098
7543
  const execSpan = startToolExecutionSpan();
7099
7544
  let toolResult;
7100
7545
  let isExecutionTimeout = false;
@@ -7154,6 +7599,7 @@ ${this.pendingRecoveredAgentsNotice}
7154
7599
  }
7155
7600
  isExecutionTimeout = toolResult.error?.type === "execution_timeout" /* EXECUTION_TIMEOUT */;
7156
7601
  aborted = activeToolAbortSignal.aborted && !isExecutionTimeout;
7602
+ settleRelatedAgent(!toolResult.error && !aborted);
7157
7603
  endToolExecutionSpan(execSpan, {
7158
7604
  success: !toolResult.error && !aborted,
7159
7605
  error: aborted ? "tool_cancelled" : isExecutionTimeout ? "tool_timeout" : toolResult.error ? "tool_error" : void 0,
@@ -7161,6 +7607,7 @@ ${this.pendingRecoveredAgentsNotice}
7161
7607
  ...heartbeatSpanAttributes()
7162
7608
  });
7163
7609
  } catch (execError) {
7610
+ settleRelatedAgent(false);
7164
7611
  endToolExecutionSpan(execSpan, {
7165
7612
  success: false,
7166
7613
  error: activeToolAbortSignal.aborted ? "tool_cancelled" : "tool_exception",
@@ -7176,7 +7623,7 @@ ${this.pendingRecoveredAgentsNotice}
7176
7623
  this.#clearTodoStopGuardTrustAndDrainAutomaticQueues();
7177
7624
  }
7178
7625
  }
7179
- const responseParts = toolResult.error ? convertToFunctionErrorResponse(
7626
+ let responseParts = toolResult.error ? convertToFunctionErrorResponse(
7180
7627
  toolName,
7181
7628
  callId,
7182
7629
  toolResult.llmContent,
@@ -7254,6 +7701,18 @@ ${this.pendingRecoveredAgentsNotice}
7254
7701
  artifacts: failureHookResult.artifacts
7255
7702
  });
7256
7703
  }
7704
+ const visionBridgeNotices = [];
7705
+ responseParts = await bridgeToolResultImages({
7706
+ config: this.config,
7707
+ responseParts,
7708
+ signal: activeToolAbortSignal,
7709
+ onFullTurnModel,
7710
+ onVisionBridgeNotice: /* @__PURE__ */ __name((notice) => visionBridgeNotices.push(notice), "onVisionBridgeNotice")
7711
+ });
7712
+ const visionBridgeNotice = visionBridgeNotices.length > 0 ? visionBridgeNotices.join("\n") : void 0;
7713
+ if (visionBridgeNotice) {
7714
+ await this.messageEmitter.emitAgentMessage(visionBridgeNotice);
7715
+ }
7257
7716
  if (isTodoWriteTool) {
7258
7717
  const todos = this.planEmitter.extractTodos(
7259
7718
  toolResult.returnDisplay,
@@ -7297,6 +7756,7 @@ ${this.pendingRecoveredAgentsNotice}
7297
7756
  callId,
7298
7757
  status,
7299
7758
  resultDisplay: toolResult.returnDisplay,
7759
+ ...visionBridgeNotice !== void 0 ? { visionBridgeNotice } : {},
7300
7760
  error: toolResult.error ? new Error(toolResult.error.message) : void 0,
7301
7761
  errorType: toolResult.error?.type
7302
7762
  }
@@ -7985,7 +8445,8 @@ function serializeMonitorTask(entry, now) {
7985
8445
  ...optionalField("pid", entry.pid),
7986
8446
  ...optionalField("exitCode", entry.exitCode),
7987
8447
  ...optionalField("error", entry.error),
7988
- ...optionalField("ownerAgentId", entry.ownerAgentId)
8448
+ ...optionalField("ownerAgentId", entry.ownerAgentId),
8449
+ ...optionalField("toolUseId", entry.toolUseId)
7989
8450
  };
7990
8451
  }
7991
8452
  __name(serializeMonitorTask, "serializeMonitorTask");
@@ -9656,7 +10117,97 @@ async function deliverClientMcpMessage(connection, serverName, message, sessionI
9656
10117
  return payload;
9657
10118
  }
9658
10119
  __name(deliverClientMcpMessage, "deliverClientMcpMessage");
10120
+ function readRuntimeMcpRequest(params) {
10121
+ const name = params["name"];
10122
+ if (typeof name !== "string" || name.length === 0) {
10123
+ throw RequestError.invalidParams(void 0, "Invalid or missing name");
10124
+ }
10125
+ if (!isValidServerName(name)) {
10126
+ throw RequestError.invalidParams(
10127
+ void 0,
10128
+ "Server name must be \u2264256 chars, alphanumeric + underscore/hyphen, and not a reserved JS property name"
10129
+ );
10130
+ }
10131
+ const originatorClientId = params["originatorClientId"];
10132
+ return {
10133
+ name,
10134
+ runtimeClientId: typeof originatorClientId === "string" && originatorClientId.length > 0 ? originatorClientId : "daemon"
10135
+ };
10136
+ }
10137
+ __name(readRuntimeMcpRequest, "readRuntimeMcpRequest");
10138
+ function readRuntimeMcpAddRequest(params) {
10139
+ const request = readRuntimeMcpRequest(params);
10140
+ const config = params["config"];
10141
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
10142
+ throw RequestError.invalidParams(void 0, "Invalid or missing config");
10143
+ }
10144
+ const {
10145
+ trust: _trust,
10146
+ authProviderType: _auth,
10147
+ includeTools: _inc,
10148
+ excludeTools: _exc,
10149
+ cwd: _cwd,
10150
+ env: _env,
10151
+ oauth: _oauth,
10152
+ headers: _headers,
10153
+ type: _type,
10154
+ [CLIENT_MCP_OVER_WS_CONFIG_FLAG]: clientMcpOverWs,
10155
+ ...safeConfig
10156
+ } = config;
10157
+ if (clientMcpOverWs === true) {
10158
+ safeConfig["type"] = "sdk";
10159
+ }
10160
+ return {
10161
+ ...request,
10162
+ config: safeConfig
10163
+ };
10164
+ }
10165
+ __name(readRuntimeMcpAddRequest, "readRuntimeMcpAddRequest");
10166
+ function getRuntimeMcpManager(config) {
10167
+ const manager = config.getToolRegistry()?.getMcpClientManager();
10168
+ if (!manager) {
10169
+ throw RequestError.internalError(
10170
+ void 0,
10171
+ "McpClientManager unavailable on this Config"
10172
+ );
10173
+ }
10174
+ return manager;
10175
+ }
10176
+ __name(getRuntimeMcpManager, "getRuntimeMcpManager");
10177
+ async function addRuntimeMcpServer(manager, request) {
10178
+ try {
10179
+ return await manager.addRuntimeMcpServer(
10180
+ request.name,
10181
+ request.config,
10182
+ request.runtimeClientId
10183
+ );
10184
+ } catch (err) {
10185
+ if (err instanceof McpBudgetWouldExceedError) {
10186
+ throw new RequestError(-32099, err.message, {
10187
+ errorKind: err.code,
10188
+ serverName: err.serverName
10189
+ });
10190
+ }
10191
+ if (err instanceof McpServerSpawnFailedError) {
10192
+ throw new RequestError(-32099, err.message, {
10193
+ errorKind: err.code,
10194
+ serverName: err.serverName,
10195
+ ...err.details
10196
+ });
10197
+ }
10198
+ if (err instanceof InvalidMcpConfigError) {
10199
+ throw new RequestError(-32099, err.message, {
10200
+ errorKind: err.code,
10201
+ serverName: err.serverName,
10202
+ reason: err.reason
10203
+ });
10204
+ }
10205
+ throw err;
10206
+ }
10207
+ }
10208
+ __name(addRuntimeMcpServer, "addRuntimeMcpServer");
9659
10209
  async function runAcpAgent(config, settings, argv, options) {
10210
+ const sessionWriterLeaseEnabledAtStartup = typeof config.isSessionWriterLeaseEnabled === "function" ? config.isSessionWriterLeaseEnabled() : settings.merged.experimental?.sessionWriterLease === true;
9660
10211
  const privateParentCapability = options === void 0 ? process.env[PRIVATE_ACP_CAPABILITY_ENV] : options.privateParentCapability;
9661
10212
  delete process.env[PRIVATE_ACP_CAPABILITY_ENV];
9662
10213
  let acpConnection;
@@ -9696,12 +10247,31 @@ async function runAcpAgent(config, settings, argv, options) {
9696
10247
  console.info = console.error;
9697
10248
  console.debug = console.error;
9698
10249
  let initializeRequestId;
10250
+ const pendingNewSessionRequestIds = /* @__PURE__ */ new Set();
9699
10251
  const stream = ndJsonStream(stdout, stdin, {
9700
10252
  onMessageObserved: /* @__PURE__ */ __name(({ direction, message }) => {
9701
- if (direction === "received" && "id" in message && "method" in message && message.method === "initialize") {
9702
- initializeRequestId = message.id;
10253
+ if (direction === "received" && "id" in message && "method" in message) {
10254
+ if (message.method === "session/new") {
10255
+ pendingNewSessionRequestIds.add(message.id);
10256
+ } else if (message.method === "initialize") {
10257
+ initializeRequestId = message.id;
10258
+ }
9703
10259
  return;
9704
10260
  }
10261
+ 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") {
10262
+ const sessionId = message.result.sessionId;
10263
+ setImmediate(() => {
10264
+ const session = agentInstance?.getActiveSessions().find((candidate) => candidate.getId() === sessionId);
10265
+ if (!session) return;
10266
+ void preloadContentGenerator(
10267
+ session.getConfig().getContentGenerator()
10268
+ ).catch((error) => {
10269
+ debugLogger7.debug(
10270
+ `[ACP] Session provider preload failed for ${sessionId}: ${error instanceof Error ? error.message : String(error)}`
10271
+ );
10272
+ });
10273
+ }).unref();
10274
+ }
9705
10275
  if (direction !== "sent" || initializeRequestId === void 0 || !("id" in message) || "method" in message || message.id !== initializeRequestId) {
9706
10276
  return;
9707
10277
  }
@@ -9720,7 +10290,8 @@ async function runAcpAgent(config, settings, argv, options) {
9720
10290
  settings,
9721
10291
  argv,
9722
10292
  conn,
9723
- privateParentCapability
10293
+ privateParentCapability,
10294
+ sessionWriterLeaseEnabledAtStartup
9724
10295
  );
9725
10296
  return agentInstance;
9726
10297
  }, stream);
@@ -9729,48 +10300,136 @@ async function runAcpAgent(config, settings, argv, options) {
9729
10300
  eventLoopMonitor.dispose();
9730
10301
  throw err;
9731
10302
  }
9732
- const drainPoolBeforeExit = /* @__PURE__ */ __name(async (label) => {
10303
+ const drainPoolBeforeExit = /* @__PURE__ */ __name(async (label, strict = false) => {
9733
10304
  if (!agentInstance) return;
9734
10305
  try {
9735
10306
  await agentInstance.shutdownMcpPool(8e3);
9736
10307
  } catch (err) {
9737
10308
  debugLogger7.error(`[ACP] MCP pool drain (${label}) error:`, err);
10309
+ if (strict) throw err;
9738
10310
  }
9739
10311
  }, "drainPoolBeforeExit");
9740
10312
  let shuttingDown = false;
10313
+ let managedShutdownPromise;
9741
10314
  let sessionEndFired = false;
9742
- const fireSessionEndOnce = /* @__PURE__ */ __name(async (reason) => {
10315
+ const fireSessionEndOnce = /* @__PURE__ */ __name(async (reason, managedConfigs) => {
9743
10316
  if (sessionEndFired) return;
9744
10317
  sessionEndFired = true;
9745
- const configs = /* @__PURE__ */ new Set([config]);
9746
- const sessions = agentInstance?.getActiveSessions();
9747
- if (sessions) {
9748
- for (const session of sessions) {
9749
- const sessionConfig = session.getConfig?.();
9750
- if (sessionConfig) {
9751
- configs.add(sessionConfig);
10318
+ const configs = new Set(managedConfigs ?? [config]);
10319
+ if (!managedConfigs) {
10320
+ const sessions = agentInstance?.getActiveSessions();
10321
+ if (sessions) {
10322
+ for (const session of sessions) {
10323
+ const sessionConfig = session.getConfig?.();
10324
+ if (sessionConfig) {
10325
+ configs.add(sessionConfig);
10326
+ }
9752
10327
  }
9753
10328
  }
9754
10329
  }
10330
+ const failures = [];
9755
10331
  for (const cfg of configs) {
9756
10332
  const hookSystem = cfg.getHookSystem?.();
9757
10333
  const hooksEnabled = !cfg.getDisableAllHooks?.();
9758
10334
  if (!hooksEnabled || !hookSystem || !cfg.hasHooksForEvent?.("SessionEnd")) {
9759
10335
  continue;
9760
10336
  }
9761
- try {
9762
- await hookSystem.fireSessionEndEvent(reason);
9763
- } catch (err) {
9764
- debugLogger7.warn(
9765
- `SessionEnd hook failed: ${err instanceof Error ? err.message : String(err)}`
9766
- );
10337
+ try {
10338
+ await hookSystem.fireSessionEndEvent(reason);
10339
+ } catch (err) {
10340
+ if (managedConfigs) failures.push(err);
10341
+ debugLogger7.warn(
10342
+ `SessionEnd hook failed: ${err instanceof Error ? err.message : String(err)}`
10343
+ );
10344
+ }
10345
+ }
10346
+ if (failures.length > 0) {
10347
+ throw new AggregateError(failures, "SessionEnd hook shutdown failed");
10348
+ }
10349
+ }, "fireSessionEndOnce");
10350
+ const shutdownManagedAgent = /* @__PURE__ */ __name((reason, label) => {
10351
+ if (managedShutdownPromise) return managedShutdownPromise;
10352
+ const agent = agentInstance;
10353
+ if (!agent?.isTrustedManagedParent()) {
10354
+ return Promise.reject(
10355
+ new Error("Managed shutdown requires a trusted private parent")
10356
+ );
10357
+ }
10358
+ const terminal = agent.beginManagedShutdown();
10359
+ managedShutdownPromise = (async () => {
10360
+ const failures = [];
10361
+ try {
10362
+ await terminal.writerShutdown;
10363
+ } catch (error) {
10364
+ failures.push(error);
10365
+ debugLogger7.error("[ACP] Managed writer shutdown error:", error);
10366
+ const retainedLockPaths = terminal.configs.flatMap((config2) => {
10367
+ if (typeof config2.getSessionRuntimeBaseDir !== "function" || typeof config2.getSessionId !== "function") {
10368
+ return [];
10369
+ }
10370
+ return [
10371
+ path4.join(
10372
+ config2.getSessionRuntimeBaseDir(),
10373
+ "tmp",
10374
+ "session-writer-locks",
10375
+ `${encodeURIComponent(config2.getSessionId())}.lock`
10376
+ )
10377
+ ];
10378
+ });
10379
+ writeStderrLineSafe(
10380
+ "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(", ")}` : "")
10381
+ );
10382
+ }
10383
+ try {
10384
+ await fireSessionEndOnce(reason, terminal.configs);
10385
+ } catch (error) {
10386
+ failures.push(error);
10387
+ }
10388
+ try {
10389
+ await agent.finishManagedShutdown(terminal.configs);
10390
+ } catch (error) {
10391
+ failures.push(error);
10392
+ debugLogger7.error("[ACP] Managed resource shutdown error:", error);
10393
+ }
10394
+ try {
10395
+ await drainPoolBeforeExit(label, true);
10396
+ } catch (error) {
10397
+ failures.push(error);
10398
+ }
10399
+ try {
10400
+ await runExitCleanup();
10401
+ } catch (error) {
10402
+ failures.push(error);
10403
+ debugLogger7.error("[ACP] Cleanup error:", error);
10404
+ }
10405
+ if (failures.length > 0) {
10406
+ throw new AggregateError(failures, "Managed ACP shutdown failed");
9767
10407
  }
9768
- }
9769
- }, "fireSessionEndOnce");
10408
+ })();
10409
+ return managedShutdownPromise;
10410
+ }, "shutdownManagedAgent");
9770
10411
  const shutdownHandler = /* @__PURE__ */ __name(async () => {
9771
10412
  if (shuttingDown) return;
9772
10413
  shuttingDown = true;
9773
10414
  debugLogger7.debug("[ACP] Shutdown signal received, closing streams");
10415
+ if (agentInstance?.isTrustedManagedParent()) {
10416
+ let exitCode = 0;
10417
+ try {
10418
+ await shutdownManagedAgent("other" /* Other */, "signal");
10419
+ } catch (err) {
10420
+ exitCode = 1;
10421
+ debugLogger7.error("[ACP] Managed shutdown error:", err);
10422
+ } finally {
10423
+ eventLoopMonitor.dispose();
10424
+ }
10425
+ try {
10426
+ process.stdin.destroy();
10427
+ process.stdout.destroy();
10428
+ } catch {
10429
+ }
10430
+ process.exit(exitCode);
10431
+ return;
10432
+ }
9774
10433
  try {
9775
10434
  await fireSessionEndOnce("other" /* Other */);
9776
10435
  await agentInstance?.disposeSessions();
@@ -9798,9 +10457,21 @@ async function runAcpAgent(config, settings, argv, options) {
9798
10457
  process.on("SIGINT", shutdownHandler);
9799
10458
  try {
9800
10459
  await connection.closed;
9801
- await fireSessionEndOnce("prompt_input_exit" /* PromptInputExit */);
9802
- await drainPoolBeforeExit("ide_close");
9803
- await agentInstance?.disposeSessions();
10460
+ if (agentInstance?.isTrustedManagedParent()) {
10461
+ try {
10462
+ await shutdownManagedAgent(
10463
+ "prompt_input_exit" /* PromptInputExit */,
10464
+ "ide_close"
10465
+ );
10466
+ } catch (error) {
10467
+ process.exitCode = 1;
10468
+ throw error;
10469
+ }
10470
+ } else {
10471
+ await fireSessionEndOnce("prompt_input_exit" /* PromptInputExit */);
10472
+ await drainPoolBeforeExit("ide_close");
10473
+ await agentInstance?.disposeSessions();
10474
+ }
9804
10475
  } finally {
9805
10476
  process.off("SIGTERM", shutdownHandler);
9806
10477
  process.off("SIGINT", shutdownHandler);
@@ -9917,12 +10588,13 @@ function parseAcpSessionListCursor(value) {
9917
10588
  }
9918
10589
  __name(parseAcpSessionListCursor, "parseAcpSessionListCursor");
9919
10590
  var QwenAgent = class {
9920
- constructor(config, settings, argv, connection, expectedPrivateParentCapability) {
10591
+ constructor(config, settings, argv, connection, expectedPrivateParentCapability, sessionWriterLeaseEnabledAtStartup = false) {
9921
10592
  this.config = config;
9922
10593
  this.settings = settings;
9923
10594
  this.argv = argv;
9924
10595
  this.connection = connection;
9925
10596
  this.expectedPrivateParentCapability = expectedPrivateParentCapability;
10597
+ this.sessionWriterLeaseEnabledAtStartup = sessionWriterLeaseEnabledAtStartup;
9926
10598
  if (process.env["QWEN_SERVE_NO_MCP_POOL"] === "1") {
9927
10599
  this.mcpPool = void 0;
9928
10600
  this.workspaceMcpBudget = void 0;
@@ -9963,6 +10635,8 @@ var QwenAgent = class {
9963
10635
  workspaceGenerationControllers = /* @__PURE__ */ new Map();
9964
10636
  transcriptReplayConfigCache = /* @__PURE__ */ new Map();
9965
10637
  pendingConfigCleanup = /* @__PURE__ */ new Map();
10638
+ initializingConfigs = /* @__PURE__ */ new Set();
10639
+ managedShuttingDown = false;
9966
10640
  clientCapabilities;
9967
10641
  privateParentState = "uninitialized";
9968
10642
  // CPU-usage delta baseline for the daemon's `workspaceResource` extMethod
@@ -9996,6 +10670,102 @@ var QwenAgent = class {
9996
10670
  getActiveSessions() {
9997
10671
  return [...this.sessions.values()];
9998
10672
  }
10673
+ isTrustedManagedParent() {
10674
+ return this.privateParentState === "trusted";
10675
+ }
10676
+ assertManagedSessionAdmission() {
10677
+ if (this.expectedPrivateParentCapability !== void 0 && !this.isTrustedManagedParent()) {
10678
+ throw RequestError.invalidParams(
10679
+ void 0,
10680
+ "Private ACP parent is not initialized"
10681
+ );
10682
+ }
10683
+ if (this.managedShuttingDown) {
10684
+ throw new SessionWriterUnavailableError();
10685
+ }
10686
+ }
10687
+ beginManagedShutdown() {
10688
+ if (!this.isTrustedManagedParent()) {
10689
+ throw new Error("Managed shutdown requires a trusted private parent");
10690
+ }
10691
+ this.managedShuttingDown = true;
10692
+ for (const generation of this.generationControllers.values()) {
10693
+ generation.controller.abort();
10694
+ }
10695
+ this.generationControllers.clear();
10696
+ for (const controller of this.workspaceGenerationControllers.values()) {
10697
+ controller.abort();
10698
+ }
10699
+ this.workspaceGenerationControllers.clear();
10700
+ const configs = /* @__PURE__ */ new Set([this.config, ...this.initializingConfigs]);
10701
+ for (const session of this.sessions.values()) {
10702
+ try {
10703
+ session.beginCloseIfAvailable();
10704
+ } catch (error) {
10705
+ debugLogger7.debug(
10706
+ `Session ${session.getId()} admission close during managed shutdown failed: ${error instanceof Error ? error.message : String(error)}`
10707
+ );
10708
+ }
10709
+ void session.cancelPendingPrompt().catch((error) => {
10710
+ debugLogger7.debug(
10711
+ `Session ${session.getId()} cancel during managed shutdown failed: ${error instanceof Error ? error.message : String(error)}`
10712
+ );
10713
+ });
10714
+ configs.add(session.getConfig());
10715
+ }
10716
+ for (const pending of this.pendingConfigCleanup.values()) {
10717
+ for (const config of pending) configs.add(config);
10718
+ }
10719
+ const configList = [...configs];
10720
+ const writerTerminals = [];
10721
+ for (const config of configList) {
10722
+ try {
10723
+ writerTerminals.push(config.closeSessionWriter());
10724
+ } catch (error) {
10725
+ writerTerminals.push(Promise.reject(error));
10726
+ }
10727
+ }
10728
+ const writerShutdown = Promise.allSettled(writerTerminals).then(
10729
+ (results) => {
10730
+ const failures = results.flatMap(
10731
+ (result) => result.status === "rejected" ? [result.reason] : []
10732
+ );
10733
+ if (failures.length > 0) {
10734
+ throw new AggregateError(
10735
+ failures,
10736
+ "Managed session writer shutdown failed"
10737
+ );
10738
+ }
10739
+ }
10740
+ );
10741
+ return { configs: configList, writerShutdown };
10742
+ }
10743
+ async finishManagedShutdown(configs) {
10744
+ const failures = [];
10745
+ for (const [sessionId, session] of [...this.sessions]) {
10746
+ await this.removeStoredSessionEntry(sessionId, session, failures, {
10747
+ shutdownConfig: false
10748
+ });
10749
+ }
10750
+ const results = await Promise.allSettled(
10751
+ configs.map(
10752
+ (config) => config.shutdown({
10753
+ shutdownTelemetry: false,
10754
+ skipSessionWriter: true,
10755
+ strictResourceCleanup: true
10756
+ })
10757
+ )
10758
+ );
10759
+ for (const result of results) {
10760
+ if (result.status === "rejected") failures.push(result.reason);
10761
+ }
10762
+ this.initializingConfigs.clear();
10763
+ this.pendingConfigCleanup.clear();
10764
+ this.disposeTranscriptReplayConfigs();
10765
+ if (failures.length > 0) {
10766
+ throw new AggregateError(failures, "Managed session cleanup failed");
10767
+ }
10768
+ }
9999
10769
  getWorkspaceMcpConfig(serverName) {
10000
10770
  if (serverName && this.config.getRuntimeMcpServers?.()[serverName] !== void 0) {
10001
10771
  return this.config;
@@ -10138,16 +10908,18 @@ var QwenAgent = class {
10138
10908
  for (const config of liveConfigs) {
10139
10909
  try {
10140
10910
  const cwd = config.getTargetDir();
10141
- const mcpServers = assembleMcpServers(
10911
+ const isBareOrSafe = config.getBareMode() || config.isSafeMode();
10912
+ const mcpServers = isBareOrSafe ? { ...config.getTopTierMcpServers() } : assembleMcpServers(
10142
10913
  settings.merged.mcpServers,
10143
10914
  cwd,
10144
10915
  config.getTopTierMcpServers()
10145
10916
  );
10146
- const gating = recomputeMcpGating(
10917
+ const bootAllowed = config.getCliAllowedMcpServerNames();
10918
+ const gating = isBareOrSafe ? { allowed: bootAllowed ? [...bootAllowed] : void 0 } : recomputeMcpGating(
10147
10919
  settings,
10148
10920
  mcpServers,
10149
10921
  cwd,
10150
- config.getCliAllowedMcpServerNames(),
10922
+ bootAllowed,
10151
10923
  config.getApprovalMode() === "yolo" /* YOLO */
10152
10924
  );
10153
10925
  config.setExcludedMcpServers(gating.excluded ?? []);
@@ -10240,11 +11012,15 @@ var QwenAgent = class {
10240
11012
  debugLogger7.warn(
10241
11013
  `MCP pool drain: ${result.drained} clean, ${result.forced} timed out, ${result.errors.length} errors`
10242
11014
  );
11015
+ throw new Error(
11016
+ `MCP pool drain incomplete: ${result.forced} forced, ${result.errors.length} errors`
11017
+ );
10243
11018
  }
10244
11019
  } catch (err) {
10245
11020
  debugLogger7.error(
10246
11021
  `MCP pool drainAll failed: ${err instanceof Error ? err.message : String(err)}`
10247
11022
  );
11023
+ throw err;
10248
11024
  }
10249
11025
  }
10250
11026
  async removeStoredSessionEntry(sessionId, session, cleanupErrors = [], options = {}) {
@@ -10315,11 +11091,13 @@ var QwenAgent = class {
10315
11091
  try {
10316
11092
  await shutdownSessionConfig(config);
10317
11093
  } catch (error) {
11094
+ this.initializingConfigs.delete(config);
10318
11095
  const pending2 = this.pendingConfigCleanup.get(cleanupKey) ?? /* @__PURE__ */ new Set();
10319
11096
  pending2.add(config);
10320
11097
  this.pendingConfigCleanup.set(cleanupKey, pending2);
10321
11098
  throw mapSessionWriterRequestError(error);
10322
11099
  }
11100
+ this.initializingConfigs.delete(config);
10323
11101
  const pending = this.pendingConfigCleanup.get(cleanupKey);
10324
11102
  pending?.delete(config);
10325
11103
  if (pending?.size === 0) {
@@ -10334,7 +11112,7 @@ var QwenAgent = class {
10334
11112
  `Session cleanup failed while preserving the original request error: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`
10335
11113
  );
10336
11114
  }
10337
- throw error;
11115
+ throw mapSessionWriterRequestError(error);
10338
11116
  }
10339
11117
  pendingConfigCleanupKey(runtimeBaseDir, sessionId) {
10340
11118
  return `${path4.resolve(runtimeBaseDir)}\0${sessionId}`;
@@ -10524,7 +11302,7 @@ var QwenAgent = class {
10524
11302
  }
10525
11303
  this.clientCapabilities = args.clientCapabilities;
10526
11304
  const authMethods = buildAuthMethods();
10527
- const version = "0.21.1-simplify-system-prompt.0";
11305
+ const version = "0.21.1";
10528
11306
  const response = {
10529
11307
  protocolVersion: PROTOCOL_VERSION,
10530
11308
  agentInfo: {
@@ -10719,16 +11497,59 @@ var QwenAgent = class {
10719
11497
  const sessionData = config.getResumedSessionData();
10720
11498
  const bulkReplay = isBulkLoadReplayRequest(params);
10721
11499
  const replayPageSize = bulkReplay ? getLoadReplayPageSize(params) : void 0;
10722
- let session;
11500
+ let replayEnvelope;
10723
11501
  try {
10724
11502
  await this.ensureAuthenticated(config);
10725
11503
  this.setupFileSystem(config);
10726
- session = await this.createAndStoreSession(
10727
- config,
10728
- settings,
10729
- sessionData,
10730
- bulkReplay ? { replayHistory: false, startPostReplayServices: false } : {}
10731
- );
11504
+ await this.createAndStoreSession(config, settings, sessionData, {
11505
+ ...bulkReplay ? { replayHistory: false } : {},
11506
+ beforeStartPostReplayServices: /* @__PURE__ */ __name(async (createdSession) => {
11507
+ if (bulkReplay) {
11508
+ const records = sessionData?.conversation.messages;
11509
+ let replayUpdates = [];
11510
+ if (records) {
11511
+ createdSession.primeTurnFromHistory(records);
11512
+ const replayPage = selectRecentHistoryRecords(
11513
+ records,
11514
+ replayPageSize
11515
+ );
11516
+ const replayUsage = createReplayCumulativeUsage();
11517
+ const replay = await collectHistoryReplayUpdates({
11518
+ sessionId: params.sessionId,
11519
+ config,
11520
+ records: replayPage.records,
11521
+ gaps: sessionData?.historyGaps,
11522
+ cumulativeUsage: replayUsage,
11523
+ supersedeUnrestorableGoal: true,
11524
+ logger: debugLogger7
11525
+ });
11526
+ replayUpdates = replay.updates;
11527
+ copyCumulativeUsage(createdSession.cumulativeUsage, replayUsage);
11528
+ if (replay.replayError !== void 0) {
11529
+ replayEnvelope = {
11530
+ v: LOAD_REPLAY_VERSION,
11531
+ updates: replayUpdates,
11532
+ partial: true,
11533
+ replayError: replay.replayError,
11534
+ ...replayPage.hasMore ? { hasMore: true } : {}
11535
+ };
11536
+ }
11537
+ replayEnvelope ??= {
11538
+ v: LOAD_REPLAY_VERSION,
11539
+ updates: replayUpdates,
11540
+ ...replayPage.hasMore ? { hasMore: true } : {}
11541
+ };
11542
+ }
11543
+ replayEnvelope ??= {
11544
+ v: LOAD_REPLAY_VERSION,
11545
+ updates: replayUpdates
11546
+ };
11547
+ }
11548
+ await this.#restoreWorktreeOnResume(config, createdSession);
11549
+ await this.#restoreBackgroundAgentsOnResume(config, createdSession);
11550
+ this.#restoreGoalOnResume(config, createdSession);
11551
+ }, "beforeStartPostReplayServices")
11552
+ });
10732
11553
  } catch (error) {
10733
11554
  return this.cleanupAfterRequestFailure(error, async () => {
10734
11555
  if (this.sessions.get(config.getSessionId())?.getConfig() !== config) {
@@ -10736,72 +11557,6 @@ var QwenAgent = class {
10736
11557
  }
10737
11558
  });
10738
11559
  }
10739
- let replayEnvelope;
10740
- if (bulkReplay) {
10741
- try {
10742
- const records = sessionData?.conversation.messages;
10743
- let replayUpdates = [];
10744
- if (records) {
10745
- session.primeTurnFromHistory(records);
10746
- const replayPage = selectRecentHistoryRecords(
10747
- records,
10748
- replayPageSize
10749
- );
10750
- const replayUsage = createReplayCumulativeUsage();
10751
- const replay = await collectHistoryReplayUpdates({
10752
- sessionId: params.sessionId,
10753
- config,
10754
- records: replayPage.records,
10755
- gaps: sessionData?.historyGaps,
10756
- cumulativeUsage: replayUsage,
10757
- // A resume: the goal restore runs right after this.
10758
- supersedeUnrestorableGoal: true,
10759
- logger: debugLogger7
10760
- });
10761
- replayUpdates = replay.updates;
10762
- copyCumulativeUsage(session.cumulativeUsage, replayUsage);
10763
- if (replay.replayError !== void 0) {
10764
- replayEnvelope = {
10765
- v: LOAD_REPLAY_VERSION,
10766
- updates: replayUpdates,
10767
- partial: true,
10768
- replayError: replay.replayError,
10769
- ...replayPage.hasMore ? { hasMore: true } : {}
10770
- };
10771
- }
10772
- replayEnvelope ??= {
10773
- v: LOAD_REPLAY_VERSION,
10774
- updates: replayUpdates,
10775
- ...replayPage.hasMore ? { hasMore: true } : {}
10776
- };
10777
- }
10778
- replayEnvelope ??= {
10779
- v: LOAD_REPLAY_VERSION,
10780
- updates: replayUpdates
10781
- };
10782
- session.installRewriter();
10783
- session.startCronScheduler();
10784
- } catch (err) {
10785
- return this.cleanupAfterRequestFailure(err, async () => {
10786
- try {
10787
- await this.discardStoredSessionIfCurrent(params.sessionId, session);
10788
- } catch (cleanupError) {
10789
- await this.removeStoredSessionEntry(
10790
- params.sessionId,
10791
- session,
10792
- [cleanupError],
10793
- {
10794
- shutdownConfig: false
10795
- }
10796
- );
10797
- await this.cleanupUnstoredConfig(config);
10798
- }
10799
- });
10800
- }
10801
- }
10802
- await this.#restoreWorktreeOnResume(config, session);
10803
- await this.#restoreBackgroundAgentsOnResume(config, session);
10804
- this.#restoreGoalOnResume(config, session);
10805
11560
  const modesData = this.buildModesData(config);
10806
11561
  const availableModels = this.buildAvailableModels(config);
10807
11562
  const configOptions = this.buildConfigOptions(config);
@@ -10857,15 +11612,21 @@ var QwenAgent = class {
10857
11612
  params.sessionId,
10858
11613
  true
10859
11614
  );
10860
- let session;
10861
11615
  try {
10862
11616
  await this.ensureAuthenticated(config);
10863
11617
  this.setupFileSystem(config);
10864
- session = await this.createAndStoreSession(
11618
+ await this.createAndStoreSession(
10865
11619
  config,
10866
11620
  settings,
10867
11621
  config.getResumedSessionData(),
10868
- { replayHistory: false }
11622
+ {
11623
+ replayHistory: false,
11624
+ beforeStartPostReplayServices: /* @__PURE__ */ __name(async (createdSession) => {
11625
+ await this.#restoreWorktreeOnResume(config, createdSession);
11626
+ await this.#restoreBackgroundAgentsOnResume(config, createdSession);
11627
+ this.#restoreGoalOnResume(config, createdSession);
11628
+ }, "beforeStartPostReplayServices")
11629
+ }
10869
11630
  );
10870
11631
  } catch (error) {
10871
11632
  return this.cleanupAfterRequestFailure(error, async () => {
@@ -10874,9 +11635,6 @@ var QwenAgent = class {
10874
11635
  }
10875
11636
  });
10876
11637
  }
10877
- await this.#restoreWorktreeOnResume(config, session);
10878
- await this.#restoreBackgroundAgentsOnResume(config, session);
10879
- this.#restoreGoalOnResume(config, session);
10880
11638
  const modesData = this.buildModesData(config);
10881
11639
  const availableModels = this.buildAvailableModels(config);
10882
11640
  const configOptions = this.buildConfigOptions(config);
@@ -11788,7 +12546,21 @@ var QwenAgent = class {
11788
12546
  };
11789
12547
  }
11790
12548
  try {
11791
- const disabled = config.getDisabledSkillNames();
12549
+ const resolved = resolveSkillSettings(
12550
+ loadSettings(this.workspaceCwd(config), {
12551
+ consumeCorruptionEnvVars: false,
12552
+ skipLoadEnvironment: true
12553
+ })
12554
+ );
12555
+ const disablements = new Map(
12556
+ Array.from(config.getDisabledSkillNames(), (name) => {
12557
+ const normalizedName = name.trim().toLowerCase();
12558
+ return [
12559
+ normalizedName,
12560
+ resolved.disablements.get(normalizedName) ?? { reason: "hard" }
12561
+ ];
12562
+ })
12563
+ );
11792
12564
  try {
11793
12565
  await config.getExtensionManager().refreshCache();
11794
12566
  } catch (error) {
@@ -11804,7 +12576,7 @@ var QwenAgent = class {
11804
12576
  const skillsByKey = new Map(
11805
12577
  skills.map((skill) => [
11806
12578
  `${skill.level}:${skill.extensionName ?? ""}:${skill.name}`,
11807
- mapSkillConfigToStatus(skill, disabled, {
12579
+ mapSkillConfigToStatus(skill, disablements, {
11808
12580
  disabled: isInactiveExtensionSkill(skill, inactiveSkillRefs)
11809
12581
  })
11810
12582
  ])
@@ -11825,7 +12597,7 @@ var QwenAgent = class {
11825
12597
  level: "extension",
11826
12598
  extensionName
11827
12599
  },
11828
- disabled,
12600
+ disablements,
11829
12601
  { disabled: true }
11830
12602
  )
11831
12603
  );
@@ -12885,12 +13657,19 @@ var QwenAgent = class {
12885
13657
  }
12886
13658
  case TODO_STOP_GUARD_QUEUE_RELEASE_METHOD: {
12887
13659
  const sessionId = params["sessionId"];
13660
+ const promptId = params["promptId"];
12888
13661
  if (typeof sessionId !== "string" || sessionId.length === 0) {
12889
13662
  throw RequestError.invalidParams(
12890
13663
  void 0,
12891
13664
  "Invalid or missing sessionId"
12892
13665
  );
12893
13666
  }
13667
+ if (typeof promptId !== "string" || promptId.length === 0) {
13668
+ throw RequestError.invalidParams(
13669
+ void 0,
13670
+ "Invalid or missing promptId"
13671
+ );
13672
+ }
12894
13673
  const session = this.sessions.get(sessionId);
12895
13674
  if (!session) {
12896
13675
  throw RequestError.invalidParams(
@@ -12899,7 +13678,7 @@ var QwenAgent = class {
12899
13678
  );
12900
13679
  }
12901
13680
  return {
12902
- released: session.releaseTodoStopGuardQueuedPromptWait()
13681
+ released: session.releaseTodoStopGuardQueuedPromptWait(promptId)
12903
13682
  };
12904
13683
  }
12905
13684
  case "qwen/providers/list": {
@@ -14320,10 +15099,12 @@ var QwenAgent = class {
14320
15099
  }
14321
15100
  }
14322
15101
  const previousCwd = config.getTargetDir();
14323
- if (canonicalPath === previousCwd) {
14324
- return { previousCwd, newCwd: canonicalPath, warnings: [] };
14325
- }
14326
- if (isFolderTrustEnabled(this.settings.merged)) {
15102
+ let trustValidated = false;
15103
+ const validateTrust = /* @__PURE__ */ __name(() => {
15104
+ if (!isFolderTrustEnabled(this.settings.merged)) {
15105
+ trustValidated = true;
15106
+ return;
15107
+ }
14327
15108
  const trustedFolders = loadTrustedFolders();
14328
15109
  if (trustedFolders.isPathTrusted(canonicalPath) !== true) {
14329
15110
  throw new RequestError(
@@ -14332,27 +15113,62 @@ var QwenAgent = class {
14332
15113
  { errorKind: "directory_not_trusted", path: canonicalPath }
14333
15114
  );
14334
15115
  }
15116
+ trustValidated = true;
15117
+ }, "validateTrust");
15118
+ if (canonicalPath !== previousCwd) {
15119
+ validateTrust();
14335
15120
  }
14336
- const warnings = [];
14337
- const relocation = await config.relocateWorkingDirectory(
14338
- canonicalPath,
14339
- canonicalPath,
14340
- { skipProcessChdir: true, skipArtifactMigration: true }
15121
+ const releaseGate = await beginSessionCloseAfterCurrentGate(
15122
+ session,
15123
+ SESSION_DRAIN_TIMEOUT_MS
14341
15124
  );
14342
- if (relocation.memoryRefreshError) {
14343
- warnings.push(
14344
- `Memory refresh failed: ${relocation.memoryRefreshError instanceof Error ? relocation.memoryRefreshError.message : String(relocation.memoryRefreshError)}`
14345
- );
14346
- }
14347
15125
  try {
14348
- await config.getGeminiClient()?.addWorkingDirectoryChangedContext(previousCwd, canonicalPath);
14349
- } catch (error) {
14350
- warnings.push(
14351
- `Model context refresh failed: ${error instanceof Error ? error.message : String(error)}`
15126
+ const settledPreviousCwd = config.getTargetDir();
15127
+ if (canonicalPath === settledPreviousCwd) {
15128
+ return {
15129
+ previousCwd: settledPreviousCwd,
15130
+ newCwd: canonicalPath,
15131
+ warnings: []
15132
+ };
15133
+ }
15134
+ if (!trustValidated) {
15135
+ validateTrust();
15136
+ }
15137
+ session.hardSuspendTodoStopGuard();
15138
+ await waitForSessionDrain(
15139
+ session.waitForActiveTurnsToSettle(),
15140
+ SESSION_DRAIN_TIMEOUT_MS,
15141
+ "close"
14352
15142
  );
15143
+ const warnings = [];
15144
+ const relocation = await config.relocateWorkingDirectory(
15145
+ canonicalPath,
15146
+ canonicalPath,
15147
+ { skipProcessChdir: true, skipArtifactMigration: true }
15148
+ );
15149
+ if (relocation.memoryRefreshError) {
15150
+ warnings.push(
15151
+ `Memory refresh failed: ${relocation.memoryRefreshError instanceof Error ? relocation.memoryRefreshError.message : String(relocation.memoryRefreshError)}`
15152
+ );
15153
+ }
15154
+ try {
15155
+ await config.getGeminiClient()?.addWorkingDirectoryChangedContext(
15156
+ settledPreviousCwd,
15157
+ canonicalPath
15158
+ );
15159
+ } catch (error) {
15160
+ warnings.push(
15161
+ `Model context refresh failed: ${error instanceof Error ? error.message : String(error)}`
15162
+ );
15163
+ }
15164
+ return {
15165
+ previousCwd: settledPreviousCwd,
15166
+ newCwd: canonicalPath,
15167
+ warnings
15168
+ };
15169
+ } finally {
15170
+ releaseGate();
14353
15171
  }
14354
- session.clearTodoStopGuardTrust();
14355
- return { previousCwd, newCwd: canonicalPath, warnings };
14356
15172
  }
14357
15173
  case SERVE_CONTROL_EXT_METHODS.sessionApprovalMode: {
14358
15174
  const sessionId = params["sessionId"];
@@ -14868,147 +15684,82 @@ ${outputText}
14868
15684
  return result;
14869
15685
  }
14870
15686
  case SERVE_CONTROL_EXT_METHODS.workspaceMcpRuntimeAdd: {
14871
- const name = params["name"];
14872
- const config = params["config"];
14873
- const originatorClientId = params["originatorClientId"];
14874
- if (typeof name !== "string" || name.length === 0) {
14875
- throw RequestError.invalidParams(
14876
- void 0,
14877
- "Invalid or missing name"
14878
- );
14879
- }
14880
- if (!isValidServerName(name)) {
14881
- throw RequestError.invalidParams(
14882
- void 0,
14883
- "Server name must be \u2264256 chars, alphanumeric + underscore/hyphen, and not a reserved JS property name"
14884
- );
14885
- }
14886
- if (!config || typeof config !== "object" || Array.isArray(config)) {
14887
- throw RequestError.invalidParams(
14888
- void 0,
14889
- "Invalid or missing config"
14890
- );
14891
- }
14892
- const runtimeClientId = typeof originatorClientId === "string" && originatorClientId.length > 0 ? originatorClientId : "daemon";
14893
- const manager = this.config.getToolRegistry()?.getMcpClientManager();
14894
- if (!manager) {
14895
- throw RequestError.internalError(
14896
- void 0,
14897
- "McpClientManager unavailable on this Config"
14898
- );
14899
- }
14900
- try {
14901
- const {
14902
- trust: _trust,
14903
- authProviderType: _auth,
14904
- includeTools: _inc,
14905
- excludeTools: _exc,
14906
- cwd: _cwd,
14907
- env: _env,
14908
- oauth: _oauth,
14909
- headers: _headers,
14910
- type: _type,
14911
- // Reverse tool channel marker (issue #5626, Phase 2). The parent
14912
- // serve process stamps this on a client-hosted (extension) MCP
14913
- // server's runtime config; it never reaches the transport itself.
14914
- [CLIENT_MCP_OVER_WS_CONFIG_FLAG]: clientMcpOverWs,
14915
- ...safeConfig
14916
- } = config;
14917
- if (clientMcpOverWs === true) {
14918
- safeConfig["type"] = "sdk";
14919
- }
14920
- const result = await manager.addRuntimeMcpServer(
14921
- name,
14922
- safeConfig,
14923
- runtimeClientId
14924
- );
14925
- await Promise.all(
14926
- this.getActiveSessions().map(async (session) => {
14927
- const sessionManager = session.getConfig().getToolRegistry()?.getMcpClientManager();
14928
- if (!sessionManager) return;
14929
- try {
14930
- await sessionManager.addRuntimeMcpServer(
14931
- name,
14932
- safeConfig,
14933
- runtimeClientId
14934
- );
14935
- } catch (sessionErr) {
14936
- debugLogger7.warn(
14937
- `workspaceMcpRuntimeAdd: failed to add runtime MCP server '${name}' to active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
14938
- );
14939
- }
14940
- })
14941
- );
14942
- return result;
14943
- } catch (err) {
14944
- if (err instanceof McpBudgetWouldExceedError) {
14945
- throw new RequestError(-32099, err.message, {
14946
- errorKind: err.code,
14947
- serverName: err.serverName
14948
- });
14949
- }
14950
- if (err instanceof McpServerSpawnFailedError) {
14951
- throw new RequestError(-32099, err.message, {
14952
- errorKind: err.code,
14953
- serverName: err.serverName,
14954
- ...err.details
14955
- });
14956
- }
14957
- if (err instanceof InvalidMcpConfigError) {
14958
- throw new RequestError(-32099, err.message, {
14959
- errorKind: err.code,
14960
- serverName: err.serverName,
14961
- reason: err.reason
14962
- });
14963
- }
14964
- throw err;
14965
- }
15687
+ const request = readRuntimeMcpAddRequest(params);
15688
+ const result = await addRuntimeMcpServer(
15689
+ getRuntimeMcpManager(this.config),
15690
+ request
15691
+ );
15692
+ await Promise.all(
15693
+ this.getActiveSessions().map(async (session) => {
15694
+ const sessionManager = session.getConfig().getToolRegistry()?.getMcpClientManager();
15695
+ if (!sessionManager) return;
15696
+ try {
15697
+ await sessionManager.addRuntimeMcpServer(
15698
+ request.name,
15699
+ request.config,
15700
+ request.runtimeClientId
15701
+ );
15702
+ } catch (sessionErr) {
15703
+ debugLogger7.warn(
15704
+ `workspaceMcpRuntimeAdd: failed to add runtime MCP server '${request.name}' to active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
15705
+ );
15706
+ }
15707
+ })
15708
+ );
15709
+ return result;
14966
15710
  }
14967
15711
  case SERVE_CONTROL_EXT_METHODS.workspaceMcpRuntimeRemove: {
14968
- const name = params["name"];
14969
- const originatorClientId = params["originatorClientId"];
14970
- if (typeof name !== "string" || name.length === 0) {
14971
- throw RequestError.invalidParams(
14972
- void 0,
14973
- "Invalid or missing name"
14974
- );
14975
- }
14976
- if (!isValidServerName(name)) {
14977
- throw RequestError.invalidParams(
14978
- void 0,
14979
- "Server name must be \u2264256 chars, alphanumeric + underscore/hyphen, and not a reserved JS property name"
14980
- );
14981
- }
14982
- const runtimeClientId = typeof originatorClientId === "string" && originatorClientId.length > 0 ? originatorClientId : "daemon";
14983
- const manager = this.config.getToolRegistry()?.getMcpClientManager();
14984
- if (!manager) {
14985
- throw RequestError.internalError(
14986
- void 0,
14987
- "McpClientManager unavailable on this Config"
14988
- );
14989
- }
14990
- const result = await manager.removeRuntimeMcpServer(
14991
- name,
14992
- runtimeClientId
14993
- );
15712
+ const request = readRuntimeMcpRequest(params);
15713
+ const result = await getRuntimeMcpManager(
15714
+ this.config
15715
+ ).removeRuntimeMcpServer(request.name, request.runtimeClientId);
14994
15716
  await Promise.all(
14995
15717
  this.getActiveSessions().map(async (session) => {
14996
15718
  const sessionManager = session.getConfig().getToolRegistry()?.getMcpClientManager();
14997
15719
  if (!sessionManager) return;
14998
15720
  try {
14999
15721
  await sessionManager.removeRuntimeMcpServer(
15000
- name,
15001
- runtimeClientId
15722
+ request.name,
15723
+ request.runtimeClientId
15002
15724
  );
15003
15725
  } catch (sessionErr) {
15004
15726
  debugLogger7.warn(
15005
- `workspaceMcpRuntimeRemove: failed to remove runtime MCP server '${name}' from active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
15727
+ `workspaceMcpRuntimeRemove: failed to remove runtime MCP server '${request.name}' from active session ${session.getConfig().getSessionId()}: ${sessionErr instanceof Error ? sessionErr.message : String(sessionErr)}`
15006
15728
  );
15007
15729
  }
15008
15730
  })
15009
15731
  );
15010
15732
  return result;
15011
15733
  }
15734
+ case SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd: {
15735
+ const sessionId = params["sessionId"];
15736
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
15737
+ throw RequestError.invalidParams(
15738
+ void 0,
15739
+ "Invalid or missing sessionId"
15740
+ );
15741
+ }
15742
+ const session = this.sessionOrThrow(sessionId);
15743
+ return addRuntimeMcpServer(
15744
+ getRuntimeMcpManager(session.getConfig()),
15745
+ readRuntimeMcpAddRequest(params)
15746
+ );
15747
+ }
15748
+ case SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove: {
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
+ const request = readRuntimeMcpRequest(params);
15758
+ const result = await getRuntimeMcpManager(
15759
+ session.getConfig()
15760
+ ).removeRuntimeMcpServer(request.name, request.runtimeClientId);
15761
+ return result;
15762
+ }
15012
15763
  case SERVE_CONTROL_EXT_METHODS.workspaceExtensionsRefresh: {
15013
15764
  const sessionId = params["sessionId"];
15014
15765
  const session = this.sessionOrThrow(sessionId);
@@ -15824,6 +16575,7 @@ ${outputText}
15824
16575
  }
15825
16576
  async newSessionConfig(cwd, mcpServers, settings, sessionId, resume, initializeOptions = {}, chatRecording) {
15826
16577
  try {
16578
+ this.assertManagedSessionAdmission();
15827
16579
  return await this.runWithPinnedRuntimeBaseDir(settings, cwd, async () => {
15828
16580
  await this.retryPendingConfigCleanup(
15829
16581
  Storage.getRuntimeBaseDir(),
@@ -15901,7 +16653,13 @@ ${outputText}
15901
16653
  continue;
15902
16654
  }
15903
16655
  }
15904
- const mergedSettings = settings.merged;
16656
+ const mergedSettings = {
16657
+ ...settings.merged,
16658
+ experimental: {
16659
+ ...settings.merged.experimental,
16660
+ sessionWriterLease: this.sessionWriterLeaseEnabledAtStartup
16661
+ }
16662
+ };
15905
16663
  const sessionArg = resume === true ? { resume: sessionId, sessionId: void 0 } : { sessionId, resume: void 0 };
15906
16664
  const argvForSession = {
15907
16665
  ...this.argv,
@@ -15936,6 +16694,20 @@ ${outputText}
15936
16694
  buildDisabledSkillNamesProvider(settings),
15937
16695
  sessionMcpServers
15938
16696
  );
16697
+ if (chatRecording !== false) {
16698
+ this.initializingConfigs.add(config);
16699
+ }
16700
+ try {
16701
+ this.assertManagedSessionAdmission();
16702
+ if (this.isTrustedManagedParent()) {
16703
+ config.setSessionWriterReclaimPolicy("never");
16704
+ }
16705
+ } catch (error) {
16706
+ return this.cleanupAfterRequestFailure(
16707
+ error,
16708
+ () => this.cleanupUnstoredConfig(config)
16709
+ );
16710
+ }
15939
16711
  if (!initializeOptions.skipFileCheckpointing && typeof config.enableFileCheckpointing === "function") {
15940
16712
  config.enableFileCheckpointing();
15941
16713
  }
@@ -15976,6 +16748,7 @@ ${outputText}
15976
16748
  // (the daemon only adds SDK-type runtime servers for client MCP).
15977
16749
  sendSdkMcpMessage: this.buildClientMcpSender(wiredSessionId)
15978
16750
  });
16751
+ this.assertManagedSessionAdmission();
15979
16752
  } catch (error) {
15980
16753
  return this.cleanupAfterRequestFailure(
15981
16754
  error,
@@ -16036,17 +16809,20 @@ ${outputText}
16036
16809
  config.setFileSystemService(acpFileSystemService);
16037
16810
  }
16038
16811
  async createAndStoreSession(config, settings, sessionData, options = {}) {
16812
+ this.assertManagedSessionAdmission();
16039
16813
  const sessionId = config.getSessionId();
16040
16814
  const geminiClient = config.getGeminiClient();
16041
16815
  const needsInitialize = !geminiClient.isInitialized();
16042
16816
  if (needsInitialize) {
16043
16817
  await geminiClient.initialize();
16044
16818
  }
16819
+ this.assertManagedSessionAdmission();
16045
16820
  if (this.sessions.has(sessionId)) {
16046
16821
  throw new Error(`Session ${sessionId} is already active.`);
16047
16822
  }
16048
16823
  const session = new Session(sessionId, config, this.connection, settings);
16049
16824
  this.sessions.set(sessionId, session);
16825
+ this.initializingConfigs.delete(config);
16050
16826
  try {
16051
16827
  if (sessionData?.fileHistorySnapshots?.length) {
16052
16828
  config.getFileHistoryService().restoreFromSnapshots(sessionData.fileHistorySnapshots);
@@ -16060,10 +16836,9 @@ ${outputText}
16060
16836
  sessionData.historyGaps
16061
16837
  );
16062
16838
  }
16063
- if (options.startPostReplayServices !== false) {
16064
- session.installRewriter();
16065
- session.startCronScheduler();
16066
- }
16839
+ await options.beforeStartPostReplayServices?.(session);
16840
+ session.installRewriter();
16841
+ session.startCronScheduler();
16067
16842
  setTimeout(() => {
16068
16843
  void session.sendAvailableCommandsUpdate();
16069
16844
  }, 0);