@qwen-code/qwen-code 0.23.1-preview.1 → 0.23.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 (351) hide show
  1. package/bundled/computer-use/SKILL.md +189 -116
  2. package/bundled/goal-draft/SKILL.md +23 -13
  3. package/bundled/qc-helper/docs/_meta.ts +1 -0
  4. package/bundled/qc-helper/docs/configuration/model-providers.md +47 -1
  5. package/bundled/qc-helper/docs/configuration/settings.md +57 -7
  6. package/bundled/qc-helper/docs/conversations-recovery.md +102 -0
  7. package/bundled/qc-helper/docs/features/channels/dingtalk.md +26 -0
  8. package/bundled/qc-helper/docs/features/channels/overview.md +1 -1
  9. package/bundled/qc-helper/docs/features/commands.md +71 -6
  10. package/bundled/qc-helper/docs/features/computer-use.md +9 -7
  11. package/bundled/qc-helper/docs/features/followup-suggestions.md +2 -2
  12. package/bundled/qc-helper/docs/features/goals.md +15 -3
  13. package/bundled/qc-helper/docs/features/skills.md +40 -0
  14. package/bundled/qc-helper/docs/qwen-serve.md +19 -1
  15. package/chunks/{MaxSizedBox-5ARLO5PR.js → MaxSizedBox-UDO6Y7RB.js} +35 -36
  16. package/chunks/{StandaloneSessionPicker-T6B322CB.js → StandaloneSessionPicker-D4CUOO4H.js} +55 -56
  17. package/chunks/{acp-startup-profiler-6ULXXQMS.js → acp-startup-profiler-KEU6VAYR.js} +2 -2
  18. package/chunks/{acpAgent-WTDEY5KD.js → acpAgent-KWLJFADK.js} +210 -131
  19. package/chunks/{agent-NXPUXEVZ.js → agent-GSUPGEOL.js} +24 -25
  20. package/chunks/{agent-headless-QQZTWOKO.js → agent-headless-HNYCQUJB.js} +24 -25
  21. package/chunks/{anthropicContentGenerator-6XDHXIII.js → anthropicContentGenerator-I7LQZH26.js} +30 -7
  22. package/chunks/{artifact-tool-DFVVJXL2.js → artifact-tool-P52OKKEF.js} +1 -1
  23. package/chunks/{askUserQuestion-GF7VQ44M.js → askUserQuestion-I5W5S3D6.js} +2 -2
  24. package/chunks/{bridge-OHY5OGOZ.js → bridge-B7CV6RVI.js} +40 -41
  25. package/chunks/{channel-management-service-ZDDG3G5S.js → channel-management-service-TRTLQTSV.js} +4 -4
  26. package/chunks/{channel-settings-store-7BJAS2SU.js → channel-settings-store-FW45IRUP.js} +46 -47
  27. package/chunks/{channel-worker-group-2ISMRENV.js → channel-worker-group-PIYPVCTF.js} +6 -6
  28. package/chunks/{channel-worker-manager-VSRPVPRH.js → channel-worker-manager-FQHEDTD2.js} +6 -6
  29. package/chunks/{channel-worker-supervisor-SRJBK72Z.js → channel-worker-supervisor-XJPZZ3VK.js} +3 -3
  30. package/chunks/{chunk-2WGJG2KW.js → chunk-25CBAK3H.js} +4 -4
  31. package/chunks/{chunk-XUSOYE2I.js → chunk-27LTEY6D.js} +1 -1
  32. package/chunks/{chunk-WTW36TJ3.js → chunk-2EKVPSIJ.js} +1 -1
  33. package/chunks/{chunk-NAKALAL4.js → chunk-2TMJRF46.js} +116 -15
  34. package/chunks/{chunk-E4L5BM2B.js → chunk-2YS3NU4A.js} +4 -4
  35. package/chunks/chunk-2Z3T52OC.js +82 -0
  36. package/chunks/{chunk-ER273QE6.js → chunk-2ZFO5JD7.js} +21 -4
  37. package/chunks/{chunk-WXC6OAWD.js → chunk-3BTHHXXE.js} +1 -1
  38. package/chunks/{chunk-GXZHYPHZ.js → chunk-3LPJ776W.js} +5 -2
  39. package/chunks/{chunk-XY3USGFE.js → chunk-3VDLQUR2.js} +1 -1
  40. package/chunks/{chunk-LK7S2D6V.js → chunk-3VWPPK5Q.js} +58 -4
  41. package/chunks/{chunk-IKLFS6SC.js → chunk-3YQMUBTS.js} +3 -3
  42. package/chunks/{chunk-P4RUUG64.js → chunk-45ROPFQY.js} +1 -1
  43. package/chunks/{chunk-W4LL5RZO.js → chunk-4ALNJDHL.js} +52 -13
  44. package/chunks/{chunk-D6PIMKY3.js → chunk-4VY3ITHR.js} +4 -4
  45. package/chunks/{chunk-H3UDNQLO.js → chunk-5CVY5Q2P.js} +3 -3
  46. package/chunks/{chunk-6UIACMGH.js → chunk-5DQ4YTIZ.js} +1 -1
  47. package/chunks/{chunk-P6LATTDG.js → chunk-5IL2BZHW.js} +3 -3
  48. package/chunks/{chunk-537SQ2AI.js → chunk-5WC2ECUK.js} +104 -16
  49. package/chunks/{chunk-HFTB354P.js → chunk-5Z4FCEPY.js} +60 -6
  50. package/chunks/{chunk-3K65MUKD.js → chunk-65I7S4Z3.js} +2 -1
  51. package/chunks/{chunk-AQ5NAGWI.js → chunk-66JBCTJF.js} +8 -7
  52. package/chunks/{chunk-54TF2ZIQ.js → chunk-6JXHO7LG.js} +3 -3
  53. package/chunks/{chunk-YCDL2SAS.js → chunk-6QILGINT.js} +2 -2
  54. package/chunks/{chunk-P5LDR7FI.js → chunk-6QV7Z74P.js} +3 -3
  55. package/chunks/{chunk-4HC4DYKN.js → chunk-6RZX2HIH.js} +1 -1
  56. package/chunks/{chunk-O45WBTNS.js → chunk-6SADVYQQ.js} +3 -3
  57. package/chunks/{chunk-KE3Q4JMY.js → chunk-6TPVIESH.js} +5 -7
  58. package/chunks/{chunk-2LD5U7Q3.js → chunk-6YEOCHSE.js} +29 -1
  59. package/chunks/{chunk-QWZOOIR3.js → chunk-75LBC7SV.js} +69 -12
  60. package/chunks/{chunk-7BZS4ZDV.js → chunk-7SL55L5H.js} +25 -18
  61. package/chunks/{chunk-O2GG7H4C.js → chunk-ARYNBBBM.js} +3 -3
  62. package/chunks/{chunk-CZACBHAW.js → chunk-B3EL44K3.js} +5 -5
  63. package/chunks/{chunk-VY6UVU7G.js → chunk-CABDNUJ4.js} +2 -2
  64. package/chunks/{chunk-RVNS7NWN.js → chunk-CALNF3Z3.js} +1 -1
  65. package/chunks/{chunk-MWHY26G3.js → chunk-CHVU543W.js} +1 -1
  66. package/chunks/{chunk-GZWW2QWR.js → chunk-CIKL2DQP.js} +2 -2
  67. package/chunks/{chunk-R355CUNQ.js → chunk-CLKE4IY3.js} +1 -77
  68. package/chunks/{chunk-MUZCSTOO.js → chunk-CRZBDVP2.js} +5 -4
  69. package/chunks/{chunk-SFMCYMVF.js → chunk-D6AQNMUA.js} +4 -4
  70. package/chunks/{chunk-D4CU6DKR.js → chunk-DO5SMV52.js} +10 -8
  71. package/chunks/{chunk-ZAZ3NFL6.js → chunk-DXQ6Z7AH.js} +315 -63
  72. package/chunks/{chunk-IXSGOSEG.js → chunk-DZ6D4B3K.js} +28 -25
  73. package/chunks/{chunk-GMNLYQOS.js → chunk-E6TI726I.js} +1 -1
  74. package/chunks/{chunk-JBTZUFR4.js → chunk-E7XSUYCZ.js} +6 -6
  75. package/chunks/{chunk-AHBLRVD5.js → chunk-EEKU6COG.js} +4 -4
  76. package/chunks/{chunk-47BZVBTE.js → chunk-EHTKOO6W.js} +4 -4
  77. package/chunks/{chunk-HJ34U5J4.js → chunk-ENZDGHGJ.js} +4 -4
  78. package/chunks/{chunk-IFD3BTEA.js → chunk-EOET4H7C.js} +3 -3
  79. package/chunks/{chunk-ZTAVGFKA.js → chunk-ERXNTINK.js} +1 -1
  80. package/chunks/{chunk-F47DITLZ.js → chunk-FAWTMDX7.js} +14 -0
  81. package/chunks/{chunk-KPXRFTT7.js → chunk-FETY36NQ.js} +1 -1
  82. package/chunks/{chunk-5JLQWQK6.js → chunk-FV4DM2M4.js} +2 -2
  83. package/chunks/{chunk-4F2QRVW6.js → chunk-FW4E4QPG.js} +1 -1
  84. package/chunks/{chunk-KJJPJYHI.js → chunk-FWRRUITH.js} +8 -8
  85. package/chunks/{chunk-4VUVBN3Y.js → chunk-G6UUOCUT.js} +87 -0
  86. package/chunks/{chunk-4JAGXZR3.js → chunk-GM44O6F7.js} +1 -1
  87. package/chunks/{chunk-4MCY33Y2.js → chunk-GNY7B3CA.js} +1 -1
  88. package/chunks/{chunk-VEFRT7NX.js → chunk-H3Q3RSKZ.js} +1 -1
  89. package/chunks/{chunk-43NOB5NM.js → chunk-HIXUUCGY.js} +188 -13
  90. package/chunks/{chunk-EJNYBDYC.js → chunk-HNLMYDQE.js} +1 -1
  91. package/chunks/{chunk-JOPC3FND.js → chunk-HUX2DOTF.js} +5 -5
  92. package/chunks/{chunk-GCFZ2LAX.js → chunk-HZ2HUXX7.js} +2 -2
  93. package/chunks/{chunk-CWNC7M73.js → chunk-IKG2YVRZ.js} +2 -2
  94. package/chunks/{chunk-L4R7BCVV.js → chunk-J3TJH52D.js} +1 -1
  95. package/chunks/{chunk-QMFOYPGV.js → chunk-J3VZF2AL.js} +2 -2
  96. package/chunks/{chunk-ZJ2LM2SI.js → chunk-JGDRB4FP.js} +104 -33
  97. package/chunks/{chunk-LMJQSPWB.js → chunk-KA5HR3G2.js} +1 -1
  98. package/chunks/{chunk-G34YLYCS.js → chunk-L7V52QEZ.js} +10 -10
  99. package/chunks/{chunk-GVVCLL2P.js → chunk-LNCNUMJ5.js} +451 -396
  100. package/chunks/{chunk-RDKXZ2LS.js → chunk-LYT2OU7D.js} +1 -1
  101. package/chunks/{chunk-SAZS4IWW.js → chunk-LZGFVUWZ.js} +3 -3
  102. package/chunks/{chunk-32YDNYXP.js → chunk-M73KHGNR.js} +13 -66
  103. package/chunks/{chunk-ADJD4LZF.js → chunk-MA5OUNN6.js} +1 -1
  104. package/chunks/{chunk-2RYWGYB3.js → chunk-MFYH2VXV.js} +3 -3
  105. package/chunks/{chunk-RPBMP6BN.js → chunk-MWIO7MF6.js} +3 -0
  106. package/chunks/{chunk-OECNP26L.js → chunk-N6S3NUYJ.js} +1 -1
  107. package/chunks/{chunk-5MTARK4Y.js → chunk-N7YQEKGX.js} +6 -6
  108. package/chunks/{chunk-XOVVCGZX.js → chunk-NB3NDQQK.js} +1 -1
  109. package/chunks/chunk-NOO4QFXM.js +171 -0
  110. package/chunks/{chunk-NGX4NUNP.js → chunk-O2FEO2CB.js} +131 -6
  111. package/chunks/{chunk-XHGGYCTA.js → chunk-O2JBJQCF.js} +1 -1
  112. package/chunks/{chunk-LPBQODMR.js → chunk-OESZTXTG.js} +4 -4
  113. package/chunks/{chunk-UKADFFL2.js → chunk-OFVAS4AR.js} +1 -1
  114. package/chunks/{chunk-TDP7UULF.js → chunk-OPMKGOLD.js} +1 -1
  115. package/chunks/{chunk-LDS57224.js → chunk-OWCFKIFQ.js} +1 -1
  116. package/chunks/{chunk-I72PHOKL.js → chunk-PDUMGZ2P.js} +1524 -1382
  117. package/chunks/{chunk-JRYL3T2O.js → chunk-PQSCGZT2.js} +1 -1
  118. package/chunks/{chunk-WEXA2DNG.js → chunk-PSPAM24S.js} +14 -0
  119. package/chunks/{chunk-UKKYOIVT.js → chunk-QAZ2MGYT.js} +2 -2
  120. package/chunks/{chunk-J3O5I5ZD.js → chunk-QK4K76T6.js} +3 -3
  121. package/chunks/{chunk-NUQFUXOG.js → chunk-QTNCGZHQ.js} +2 -0
  122. package/chunks/{chunk-5YY5MZT6.js → chunk-QZOXVQPK.js} +1 -1
  123. package/chunks/{chunk-QJVZLILI.js → chunk-R7OO56VZ.js} +1 -1
  124. package/chunks/{chunk-IQN2CCIE.js → chunk-RNYENHN5.js} +398 -55
  125. package/chunks/{chunk-64MQTIX7.js → chunk-RPFJJ33Z.js} +2 -2
  126. package/chunks/{chunk-4VZCORNT.js → chunk-RXT4QBDX.js} +1 -1
  127. package/chunks/{chunk-SN5FV4FY.js → chunk-S6QVI3MV.js} +3 -3
  128. package/chunks/{chunk-NXWYCSPL.js → chunk-SOA4HKRJ.js} +1 -1
  129. package/chunks/{chunk-JLWFGYXU.js → chunk-T2IHCZLS.js} +2 -2
  130. package/chunks/{chunk-DNPHKA72.js → chunk-TGC4264Q.js} +6 -6
  131. package/chunks/{chunk-PZV2FASB.js → chunk-TRWQQBVH.js} +1 -1
  132. package/chunks/{chunk-Y3ZKI4RQ.js → chunk-TWAMIEQ2.js} +85 -22
  133. package/chunks/{chunk-KK2GZGBK.js → chunk-TWWS7XUW.js} +14 -11
  134. package/chunks/{chunk-4IQKBLTQ.js → chunk-UHUT4IDM.js} +18 -9
  135. package/chunks/{chunk-BKNY7PDI.js → chunk-USN6VNTO.js} +1 -1
  136. package/chunks/{chunk-TMWB67LS.js → chunk-UXDVUFKU.js} +3 -3
  137. package/chunks/{chunk-HY3DXYZK.js → chunk-UYDQYDW2.js} +1 -1
  138. package/chunks/{chunk-3K456UJF.js → chunk-VF6D6EGV.js} +12 -4
  139. package/chunks/{chunk-PZUOHCWI.js → chunk-WAASYFPK.js} +2 -2
  140. package/chunks/{chunk-OHOO527W.js → chunk-WG7BL3FY.js} +52 -2
  141. package/chunks/{chunk-JPEAQJNS.js → chunk-WJDXKQIO.js} +1 -1
  142. package/chunks/{chunk-MNEYUNOE.js → chunk-WNISCNTA.js} +40 -2
  143. package/chunks/{chunk-Z6WZPXQH.js → chunk-WQMUGQ6G.js} +2 -2
  144. package/chunks/{chunk-N7VURC4O.js → chunk-WXFCI3O5.js} +2 -2
  145. package/chunks/{chunk-VU7O7CGQ.js → chunk-XDNFODER.js} +1 -1
  146. package/chunks/{chunk-N7EYO2E7.js → chunk-XQ4RDO5B.js} +1 -1
  147. package/chunks/{chunk-VDXYYVCD.js → chunk-XVTCSVBK.js} +579 -57
  148. package/chunks/{chunk-PTFFWTTO.js → chunk-XZ3Z43XL.js} +3 -3
  149. package/chunks/{chunk-QSC5YOEC.js → chunk-YAC7H4K3.js} +2 -2
  150. package/chunks/{chunk-43JNQAHO.js → chunk-YCEKI7QX.js} +51 -10
  151. package/chunks/{chunk-7IKXTGZT.js → chunk-YI2YCNSP.js} +1 -1
  152. package/chunks/{chunk-VUSSAGKI.js → chunk-YZTGGCEE.js} +10 -2
  153. package/chunks/{chunk-WR3SH3EY.js → chunk-ZNO5BUAD.js} +149 -66
  154. package/chunks/{chunk-URSCX7S7.js → chunk-ZPL2TZNA.js} +353 -11
  155. package/chunks/{chunk-UEZOXZNI.js → chunk-ZU2T5JIS.js} +804 -371
  156. package/chunks/{config-utils-QXDOTXEQ.js → config-utils-KTDSQ4MU.js} +39 -40
  157. package/chunks/{contextCommand-RN4KARWC.js → contextCommand-UQ3KRYGK.js} +37 -38
  158. package/chunks/{core-runtime-NAZCOKHB.js → core-runtime-JR34JAFH.js} +35 -36
  159. package/chunks/{create-sub-session-BCSM4WKB.js → create-sub-session-RGPJOI4S.js} +45 -40
  160. package/chunks/{create-sub-session-BQ3SE4TX.js → create-sub-session-TGIX63YU.js} +2 -2
  161. package/chunks/{cron-create-D6HQ7I7I.js → cron-create-GTPVMJCF.js} +1 -1
  162. package/chunks/{cron-delete-KK3D2SQV.js → cron-delete-ZBK27Z4K.js} +1 -1
  163. package/chunks/{cron-list-VBF3IZMF.js → cron-list-KTFKFDKC.js} +1 -1
  164. package/chunks/{daemon-LCUELM6E.js → daemon-UI6SQSBV.js} +1 -1
  165. package/chunks/{daemon-git-worktree-guard-3K5CAU36.js → daemon-git-worktree-guard-H3OA26KQ.js} +35 -36
  166. package/chunks/{daemon-status-provider-4X3ZZQTZ.js → daemon-status-provider-6WZLKSZU.js} +45 -46
  167. package/chunks/{daemon-trust-policy-R45CFUJA.js → daemon-trust-policy-3EDP2BYD.js} +42 -43
  168. package/chunks/{daemon-trust-policy-monitor-DSSFCO3K.js → daemon-trust-policy-monitor-CRHZPK52.js} +42 -43
  169. package/chunks/{deferred-core-runtime-UO2M6WYI.js → deferred-core-runtime-LO5NTQQ4.js} +35 -36
  170. package/chunks/{discovery-TUM3ZQ6U.js → discovery-XP4RMDUM.js} +4 -2
  171. package/chunks/{display-image-EVVTBVYE.js → display-image-CTNHJRZC.js} +4 -4
  172. package/chunks/{dist-SIHF5MU2.js → dist-24TCWK5H.js} +1 -1
  173. package/chunks/{dist-AFH3BMZZ.js → dist-5I4HLUTO.js} +1 -1
  174. package/chunks/{dist-3T5MDUHP.js → dist-FDISN4AK.js} +1 -1
  175. package/chunks/{dist-SB2XRXZA.js → dist-M4CBX53H.js} +1 -1
  176. package/chunks/{dist-UVHW2U56.js → dist-NQ2636VT.js} +1 -1
  177. package/chunks/{dist-PH5RSTEA.js → dist-OR2ZQTXZ.js} +1 -1
  178. package/chunks/{dist-MK5PPBRF.js → dist-STAGIFNB.js} +1099 -67
  179. package/chunks/{dist-R5Y34V6T.js → dist-WZTUKIDR.js} +2 -2
  180. package/chunks/{dist-QUU7TVE3.js → dist-XJ25G6OH.js} +1 -1
  181. package/chunks/{edit-VNBCTRWP.js → edit-LB7Z7XK5.js} +24 -25
  182. package/chunks/{en-JMR535HP.js → en-YJNRUQG4.js} +1 -1
  183. package/chunks/{enter-worktree-CEVK7MQ2.js → enter-worktree-YFTKHXHZ.js} +4 -4
  184. package/chunks/{enterPlanMode-4KMZMUIA.js → enterPlanMode-P6TVUFIY.js} +24 -25
  185. package/chunks/{environment-S2HYQDON.js → environment-QATJNNKI.js} +38 -39
  186. package/chunks/{errors-DAAN5TL7.js → errors-3XJ37PS2.js} +37 -38
  187. package/chunks/{exit-worktree-D3YE6MUN.js → exit-worktree-NF2XEMES.js} +5 -5
  188. package/chunks/{exitPlanMode-HR36HG3D.js → exitPlanMode-A3OKL5UO.js} +24 -25
  189. package/chunks/{fast-path-4IWSW3UV.js → fast-path-DBIT5YQQ.js} +3 -3
  190. package/chunks/{fast-path-settings-ISEJPRYE.js → fast-path-settings-SATXY3PD.js} +3 -3
  191. package/chunks/{glob-IZYB2XH2.js → glob-73EDTXUE.js} +24 -25
  192. package/chunks/{goal-tools-VGUPKQDJ.js → goal-tools-DFI6YMSD.js} +24 -25
  193. package/chunks/{grep-OUVLNXG7.js → grep-BLHF2S5D.js} +2 -2
  194. package/chunks/{handleAutoUpdate-D56FMDTW.js → handleAutoUpdate-2FUNJO3B.js} +38 -39
  195. package/chunks/{i18n-BKE5WO6T.js → i18n-FDIA6KFI.js} +38 -37
  196. package/chunks/{image-gen-SHVQ3XID.js → image-gen-XP4NNIYG.js} +5 -5
  197. package/chunks/{initializer-MS4SGEHF.js → initializer-4MJTJOTW.js} +42 -43
  198. package/chunks/{installationInfo-542MGC4S.js → installationInfo-232RA2OK.js} +35 -36
  199. package/chunks/{list-H6XTKUWL.js → list-WN6WSGEB.js} +45 -46
  200. package/chunks/{list-agents-ULYBGJXC.js → list-agents-I5TRH3J7.js} +2 -2
  201. package/chunks/{llm-3NUC4EJY.js → llm-UDFWQWZA.js} +77 -78
  202. package/chunks/{llm-content-generator-R4NL3OQN.js → llm-content-generator-VLMZ2A7A.js} +23 -8
  203. package/chunks/{loadedSettingsAdapter-3XLKYDVT.js → loadedSettingsAdapter-OBQEIXM7.js} +42 -43
  204. package/chunks/{loggingContentGenerator-ZYSWVNEO.js → loggingContentGenerator-RGVUMUVX.js} +26 -27
  205. package/chunks/{loop-wakeup-B27BEYRL.js → loop-wakeup-HL6XOWI4.js} +2 -2
  206. package/chunks/{ls-3IIMMVKF.js → ls-YV7RKLKY.js} +1 -1
  207. package/chunks/{lsp-VJAT7XKS.js → lsp-NO3AMRZT.js} +1 -1
  208. package/chunks/{managed-npm-update-L2I53ZAI.js → managed-npm-update-QBAJYCFU.js} +35 -36
  209. package/chunks/{mcp-4PIXQASW.js → mcp-OTIZZCPY.js} +42 -43
  210. package/chunks/{monitor-O2YQTOZZ.js → monitor-BV5XF6LL.js} +24 -25
  211. package/chunks/{nonInteractiveCli-LV7CDBA2.js → nonInteractiveCli-W6MUKDVJ.js} +79 -77
  212. package/chunks/{notebook-edit-4RE2ALH4.js → notebook-edit-HGBEKGTE.js} +24 -25
  213. package/chunks/{openaiContentGenerator-7ND7K5CP.js → openaiContentGenerator-NSU3ERBH.js} +15 -15
  214. package/chunks/{pidfile-UFTLQ7NP.js → pidfile-LE3TU4GE.js} +35 -36
  215. package/chunks/{processUtils-3XBB4FYV.js → processUtils-YFBGJK67.js} +2 -2
  216. package/chunks/{prompt-terminal-ledger-2QASOGMM.js → prompt-terminal-ledger-4W4W7DSO.js} +36 -37
  217. package/chunks/{qwenContentGenerator-AELTUTH6.js → qwenContentGenerator-HTA57WFC.js} +28 -29
  218. package/chunks/{qwenOAuth2-BS5D2LYV.js → qwenOAuth2-KX6LVYQ3.js} +4 -4
  219. package/chunks/{read-file-PDWHZPHX.js → read-file-KHPQ2MB6.js} +4 -4
  220. package/chunks/{read-mcp-resource-YXJZ75UB.js → read-mcp-resource-D3N75DGF.js} +1 -1
  221. package/chunks/{record-artifact-WJDOV6XU.js → record-artifact-Q5CRGJTP.js} +2 -2
  222. package/chunks/{report-findings-Q4UACKWR.js → report-findings-TJ34R7QK.js} +3 -3
  223. package/chunks/{request-shutdown-2YZ3E3GH.js → request-shutdown-LRKMTBAD.js} +6 -6
  224. package/chunks/{resumeHistoryUtils-QRXZEEBA.js → resumeHistoryUtils-K7RV3QBN.js} +39 -40
  225. package/chunks/{ripGrep-KSOOLE6H.js → ripGrep-NBBVCMG4.js} +7 -7
  226. package/chunks/{run-qwen-serve-RTAREPT6.js → run-qwen-serve-A3JBOZCM.js} +58 -60
  227. package/chunks/{runtime-ESFSCJRZ.js → runtime-7YOU2KJ3.js} +47 -48
  228. package/chunks/{scheduled-tasks-6ZHRNBH6.js → scheduled-tasks-52LXK7LN.js} +42 -43
  229. package/chunks/{scheduler-DQI6KV7T.js → scheduler-J44M72VM.js} +37 -38
  230. package/chunks/{send-message-PQCVSVMN.js → send-message-AWKUDJBH.js} +8 -8
  231. package/chunks/{serve-FY7ZEW52.js → serve-TRC6XJUB.js} +42 -43
  232. package/chunks/{server-KNDY6K5F.js → server-YPNTJLX2.js} +1314 -841
  233. package/chunks/{session-MCEPXAZP.js → session-FMMIBFYX.js} +98 -84
  234. package/chunks/{session-attachments-root-OLNAE6GF.js → session-attachments-root-LDJMNK7K.js} +35 -36
  235. package/chunks/{session-pr-refresh-HKJHQQQK.js → session-pr-refresh-NLR4EK2J.js} +41 -42
  236. package/chunks/{settings-VXO4WBMK.js → settings-A46L577J.js} +41 -42
  237. package/chunks/{shell-U263OTES.js → shell-Q5LSQPPY.js} +24 -25
  238. package/chunks/{skill-SDODGBKL.js → skill-75KPJRCM.js} +10 -57
  239. package/chunks/{skill-settings-YEIA22QJ.js → skill-settings-775YT4YR.js} +41 -42
  240. package/chunks/{spawnChannel-4WJZVFPP.js → spawnChannel-XY73I5CU.js} +37 -38
  241. package/chunks/{standalone-update-ZWVQUO64.js → standalone-update-L46XXNQ2.js} +37 -38
  242. package/chunks/{start-opentui-ui-BFYCJQRZ.js → start-opentui-ui-WLV43247.js} +2007 -1003
  243. package/chunks/{startInteractiveUI-JYAFCMHL.js → startInteractiveUI-F5DKMLOV.js} +1231 -1528
  244. package/chunks/{syntheticOutput-AUAJBNXR.js → syntheticOutput-D2P5V6RG.js} +2 -2
  245. package/chunks/{task-create-LD5ISM3E.js → task-create-PMAFST2T.js} +7 -7
  246. package/chunks/{task-list-YISJ4RJA.js → task-list-R2HSY2NC.js} +1 -1
  247. package/chunks/{task-stop-65ZOVATJ.js → task-stop-BFSKRTGV.js} +1 -1
  248. package/chunks/{task-update-AAN4ZVEY.js → task-update-JYC57USF.js} +7 -7
  249. package/chunks/{team-create-KU7MABNO.js → team-create-2PATB77U.js} +24 -25
  250. package/chunks/{team-delete-XFRRTJTT.js → team-delete-CBHVBTPB.js} +1 -1
  251. package/chunks/{team-plan-approval-DPB377A3.js → team-plan-approval-QTANEWOS.js} +24 -25
  252. package/chunks/{terminal-image-renderer-WGWRENOF.js → terminal-image-renderer-OGULCFNF.js} +37 -38
  253. package/chunks/{theme-manager-GBUFULSO.js → theme-manager-CNO3QERP.js} +35 -36
  254. package/chunks/{todoWrite-G7NT4IFP.js → todoWrite-5ERKFWAK.js} +3 -5
  255. package/chunks/{tool-search-6YUXHBPT.js → tool-search-VXWEOZE7.js} +9 -9
  256. package/chunks/{total-session-admission-54R2JQ5L.js → total-session-admission-4KAADZPB.js} +41 -42
  257. package/chunks/{trustedFolders-KAJIDJTH.js → trustedFolders-PPJSOPOT.js} +36 -37
  258. package/chunks/{update-relaunch-XM4IWBFD.js → update-relaunch-4PT4MW7B.js} +5 -5
  259. package/chunks/{updateCheck-W6UZFURI.js → updateCheck-WAVFLWNG.js} +37 -38
  260. package/chunks/{useAutoAcceptIndicator-LAWYHY3U.js → useAutoAcceptIndicator-XNED4NRB.js} +44 -45
  261. package/chunks/{validateNonInterActiveAuth-7WCKHRN2.js → validateNonInterActiveAuth-J676DUQ2.js} +74 -74
  262. package/chunks/{version-3ZU43RJ6.js → version-J6SRRQB2.js} +1 -1
  263. package/chunks/{web-fetch-QHI2SQL4.js → web-fetch-FMZZYX44.js} +7 -7
  264. package/chunks/{web-search-3KZZKWNY.js → web-search-3G2KXCX5.js} +19 -8
  265. package/chunks/{workflow-HRW7Y2X4.js → workflow-PPZZICQ7.js} +26 -27
  266. package/chunks/{workspace-providers-status-KTGCWCPC.js → workspace-providers-status-IIYTAQST.js} +46 -47
  267. package/chunks/{workspace-registration-store-LHLPPWNE.js → workspace-registration-store-VHCDXAV7.js} +1 -1
  268. package/chunks/{workspace-registry-X34MLN52.js → workspace-registry-I7VQIPS2.js} +41 -42
  269. package/chunks/{workspace-runtime-coordinator-U4PW4P7K.js → workspace-runtime-coordinator-DBGNY32G.js} +41 -42
  270. package/chunks/{workspace-service-KD7BCGYL.js → workspace-service-QSKB2T54.js} +47 -48
  271. package/chunks/{workspace-skills-status-YJGO6Y3T.js → workspace-skills-status-T7GPT65J.js} +43 -44
  272. package/chunks/{workspace-trust-reconciler-EUYHISCH.js → workspace-trust-reconciler-2PKRDAU4.js} +48 -49
  273. package/chunks/{write-file-EBSB34NJ.js → write-file-L76CGFTQ.js} +26 -27
  274. package/chunks/{zh-TW-W2GNP2IU.js → zh-TW-N2TBF2F2.js} +1 -1
  275. package/chunks/{zh-DVFYHRK5.js → zh-VBFCRQBL.js} +1 -1
  276. package/chunks/{zoom-image-UJ5VKWKP.js → zoom-image-TDJJY2VZ.js} +4 -4
  277. package/cli.js +13 -13
  278. package/export-transcript-document.js +126 -122
  279. package/locales/en.js +2 -2
  280. package/locales/zh-TW.js +2 -2
  281. package/locales/zh.js +2 -2
  282. package/package.json +3 -3
  283. package/web-shell/assets/{abnfDiagram-VCTEODGH-Dur--luQ.js → abnfDiagram-VCTEODGH-DHc6plZn.js} +1 -1
  284. package/web-shell/assets/{arc-tYLobxFi.js → arc-BQ9m8TDV.js} +1 -1
  285. package/web-shell/assets/{architectureDiagram-5GKGNRK7-IG6aXD03.js → architectureDiagram-5GKGNRK7-D5ap3oVB.js} +1 -1
  286. package/web-shell/assets/{blockDiagram-NRAW4CY4-C6eBSkfA.js → blockDiagram-NRAW4CY4-BIbnyNph.js} +1 -1
  287. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BrX3HJqB.js → c4Diagram-UCG6FXSJ-BRsdx_iG.js} +1 -1
  288. package/web-shell/assets/channel-uMMdTrYk.js +1 -0
  289. package/web-shell/assets/{chunk-2Q5K7J3B-B3fcJ8ee.js → chunk-2Q5K7J3B-3lf1fNlx.js} +1 -1
  290. package/web-shell/assets/{chunk-5VM5RSS4-CeC90yKM.js → chunk-5VM5RSS4-DP8VNRc4.js} +1 -1
  291. package/web-shell/assets/{chunk-F27PBJKO-CW44RVki.js → chunk-F27PBJKO-DrohDmZ6.js} +1 -1
  292. package/web-shell/assets/{chunk-G27WJ6UU-D1PAMukD.js → chunk-G27WJ6UU-UZ2QhSx6.js} +1 -1
  293. package/web-shell/assets/{chunk-JWPE2WC7-Dt3Y2Fvx.js → chunk-JWPE2WC7-BIMHVcZK.js} +1 -1
  294. package/web-shell/assets/{chunk-LCL6LL3I-CZHw2lLI.js → chunk-LCL6LL3I-izRxdSDd.js} +1 -1
  295. package/web-shell/assets/{chunk-POPQ4Y6H-ysNAdTGx.js → chunk-POPQ4Y6H-CXADD4PP.js} +1 -1
  296. package/web-shell/assets/{chunk-SVP7TREG-BdNXW6YQ.js → chunk-SVP7TREG-B96d8Y_1.js} +1 -1
  297. package/web-shell/assets/{chunk-XXDRQBXY-DgqQ9UA8.js → chunk-XXDRQBXY-CF2sVQpv.js} +1 -1
  298. package/web-shell/assets/classDiagram-DTDB5LWJ-DcY-26Ig.js +1 -0
  299. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DcY-26Ig.js +1 -0
  300. package/web-shell/assets/{cose-bilkent-JH36ORCC-BILImXzJ.js → cose-bilkent-JH36ORCC-CT6tXVAS.js} +1 -1
  301. package/web-shell/assets/csv-CX7rUNeC.svg +1 -0
  302. package/web-shell/assets/{cynefin-OW5HDTMX-DR88Pund.js → cynefin-OW5HDTMX-X1NS4vtV.js} +1 -1
  303. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-BYFbfkA6.js → cynefinDiagram-5FMLGOSQ-DNsKNOT4.js} +1 -1
  304. package/web-shell/assets/{dagre-3AP2YEHR-rfpyc6sX.js → dagre-3AP2YEHR-9-AHKqsb.js} +1 -1
  305. package/web-shell/assets/{diagram-S7CK7UJ4-BJxLmEwH.js → diagram-S7CK7UJ4-Bjgms7j6.js} +1 -1
  306. package/web-shell/assets/{diagram-UQ7AKVKN-H34xm7k3.js → diagram-UQ7AKVKN-h6bCprbE.js} +1 -1
  307. package/web-shell/assets/{diagram-VSXAHHWV-HYxhwNLx.js → diagram-VSXAHHWV-4SbQXVLt.js} +1 -1
  308. package/web-shell/assets/{diagram-VX7I27RA-BJazso8F.js → diagram-VX7I27RA-B5gPCzzB.js} +1 -1
  309. package/web-shell/assets/{diagram-Z3DM3KII-Clje1aNy.js → diagram-Z3DM3KII-DFJXIA3A.js} +1 -1
  310. package/web-shell/assets/{ebnfDiagram-PWID7BFC-M93YBkFh.js → ebnfDiagram-PWID7BFC-FwyaU7VY.js} +1 -1
  311. package/web-shell/assets/{erDiagram-SSCWMZ5O-DY8XzSHU.js → erDiagram-SSCWMZ5O-8vJQh2te.js} +1 -1
  312. package/web-shell/assets/{flowDiagram-A5DVABFB-CE6Aylcq.js → flowDiagram-A5DVABFB-BzA_1gMN.js} +1 -1
  313. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-DI-5LL22.js → ganttDiagram-EL5Y4UJY-Co-ABbVX.js} +1 -1
  314. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-C7BZWElk.js → gitGraphDiagram-WWUBYQGX-DW_FcyrX.js} +1 -1
  315. package/web-shell/assets/{index-DclFHns9.js → index-BbMXfhNG.js} +1 -1
  316. package/web-shell/assets/{index-CVyqwW7y.js → index-Bu-rZoJ-.js} +483 -475
  317. package/web-shell/assets/index-CsPwZ1ut.css +36 -0
  318. package/web-shell/assets/{infoDiagram-RXCK75RN-CGUSy4Pc.js → infoDiagram-RXCK75RN-BEgfhUFN.js} +1 -1
  319. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-B5BVks9q.js → ishikawaDiagram-5VMMS53U-DCsMxQmc.js} +1 -1
  320. package/web-shell/assets/{journeyDiagram-EYS64GPL-CFh6Tf7h.js → journeyDiagram-EYS64GPL-DyIEYoHz.js} +1 -1
  321. package/web-shell/assets/{kanban-definition-3QL26DDD-B7TlxP7c.js → kanban-definition-3QL26DDD-CkxjqCNr.js} +1 -1
  322. package/web-shell/assets/{layout-Br_pZq2Q.js → layout-BEWc0Al9.js} +1 -1
  323. package/web-shell/assets/{linear-BVlP6fte.js → linear-CNuNxirL.js} +1 -1
  324. package/web-shell/assets/{mermaid.core-TrcYWoiF.js → mermaid.core-DZBre674.js} +6 -6
  325. package/web-shell/assets/{mindmap-definition-FBJOCRG2-BJ4LzqjZ.js → mindmap-definition-FBJOCRG2-CpafFz_F.js} +1 -1
  326. package/web-shell/assets/{pegDiagram-XKGWAZYB-1b_MxlOl.js → pegDiagram-XKGWAZYB-DfZqk_dq.js} +1 -1
  327. package/web-shell/assets/{pieDiagram-E7YTZNPT-B8zl0YhY.js → pieDiagram-E7YTZNPT-S0UWXlgC.js} +1 -1
  328. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-CIZO8ukl.js → quadrantDiagram-AXDQQJYC-dd37_Ohj.js} +1 -1
  329. package/web-shell/assets/{railroadDiagram-O6MQD6OU-CepHSbCj.js → railroadDiagram-O6MQD6OU-CH8NJZ7u.js} +1 -1
  330. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-BCgxkcSW.js → requirementDiagram-EFPCY7ZU-CFdqWYih.js} +1 -1
  331. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CE5CcoMM.js → sankeyDiagram-P5KCCOFB-CsddcEGD.js} +1 -1
  332. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DvgHi-d5.js → sequenceDiagram-WJ2MYXX4-BZ270mGw.js} +1 -1
  333. package/web-shell/assets/{sizeCapture-X5ZJPWSS-T-fAsCPX.js → sizeCapture-X5ZJPWSS-CGaS4DBV.js} +1 -1
  334. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DYHaul-5.js → stateDiagram-HBIQ2CUA-COpIzMu6.js} +1 -1
  335. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-D6qEVAji.js +1 -0
  336. package/web-shell/assets/{swimlanes-XN3QIQJK-Dbz3Qiej.js → swimlanes-XN3QIQJK-CMF889m3.js} +1 -1
  337. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-mem5Jj4m.js +8 -0
  338. package/web-shell/assets/{timeline-definition-24CTP7MA-9NVRts3N.js → timeline-definition-24CTP7MA-BelnxYz5.js} +1 -1
  339. package/web-shell/assets/{vennDiagram-4TSXK5OY-C7cb7vnH.js → vennDiagram-4TSXK5OY-CU-NRqIB.js} +1 -1
  340. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-CG-8Ddjm.js → wardleyDiagram-VM6X3IG4-CDNKqWh-.js} +1 -1
  341. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-iGeYAcP4.js → xychartDiagram-S5SC5T6Z-CLqguL5D.js} +1 -1
  342. package/web-shell/index.html +6 -3
  343. package/chunks/chunk-3UMWOKJC.js +0 -78
  344. package/chunks/chunk-FKJM6JKY.js +0 -98
  345. package/chunks/chunk-IQAFKVXS.js +0 -22
  346. package/web-shell/assets/channel-uEkvKckd.js +0 -1
  347. package/web-shell/assets/classDiagram-DTDB5LWJ-DuPsnhWS.js +0 -1
  348. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DuPsnhWS.js +0 -1
  349. package/web-shell/assets/index-FO7JXPnH.css +0 -36
  350. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BcYho9a4.js +0 -1
  351. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-D6HsOIgX.js +0 -8
@@ -20,7 +20,7 @@ import {
20
20
  shouldSuppressRememberErrorDetails,
21
21
  workspaceMemoryFailureCode,
22
22
  workspaceMemoryFailureDiagnostics
23
- } from "./chunk-PTFFWTTO.js";
23
+ } from "./chunk-XZ3Z43XL.js";
24
24
  import {
25
25
  SetupGithubError,
26
26
  collectSessionData,
@@ -32,13 +32,13 @@ import {
32
32
  toJson,
33
33
  toJsonl,
34
34
  toMarkdown
35
- } from "./chunk-KK2GZGBK.js";
35
+ } from "./chunk-TWWS7XUW.js";
36
36
  import {
37
37
  OBSERVED_CONTACT_MAX_FRESH_WITHIN_SECONDS,
38
38
  ObservedChannelContactStore
39
39
  } from "./chunk-M3JGHRMQ.js";
40
40
  import "./chunk-VFFQAOPR.js";
41
- import "./chunk-ZTAVGFKA.js";
41
+ import "./chunk-ERXNTINK.js";
42
42
  import {
43
43
  escapeAnsiCtrlCodes
44
44
  } from "./chunk-47ECGEJC.js";
@@ -54,7 +54,6 @@ import {
54
54
  AcpPreAttachBudget,
55
55
  CAPABILITIES_SCHEMA_VERSION,
56
56
  ClientMcpSenderRegistry,
57
- ConversationRuntimeOwnershipError,
58
57
  CredentialStore,
59
58
  DeviceFlowRegistry,
60
59
  LocalPathOpenUnavailableError,
@@ -73,10 +72,6 @@ import {
73
72
  bearerAuth,
74
73
  brandSecret,
75
74
  buildDaemonStatusResponse,
76
- conversationRootCompromisedError,
77
- conversationRuntimeInUseError,
78
- conversationRuntimeOwnershipCompromisedError,
79
- conversationRuntimeUnavailableError,
80
75
  createBridgeFileSystemAdapter,
81
76
  createClientMcpServerProvider,
82
77
  createManagedScratchDirectory,
@@ -114,7 +109,7 @@ import {
114
109
  singleTokenCredentials,
115
110
  tagListener,
116
111
  unsafeRevealSecret
117
- } from "./chunk-32YDNYXP.js";
112
+ } from "./chunk-M73KHGNR.js";
118
113
  import {
119
114
  ConversationDirectoryIdentityError,
120
115
  getConversationDirectoryName,
@@ -125,15 +120,16 @@ import {
125
120
  import "./chunk-UXEO7E3V.js";
126
121
  import {
127
122
  createTotalSessionAdmissionController
128
- } from "./chunk-7IKXTGZT.js";
123
+ } from "./chunk-YI2YCNSP.js";
129
124
  import {
130
125
  assertValidChannelSecretUpdates
131
- } from "./chunk-SAZS4IWW.js";
126
+ } from "./chunk-LZGFVUWZ.js";
132
127
  import {
133
128
  AONE_MAX_MR_VIEW_CALLS_PER_RUN,
134
129
  DaemonDrainingError,
135
130
  InvalidCursorError,
136
131
  SessionArchiveCoordinator,
132
+ acquireWorktreeOwnershipOp,
137
133
  archiveDaemonSessions,
138
134
  assertSessionArchived,
139
135
  assertSessionLoadable,
@@ -156,7 +152,7 @@ import {
156
152
  runWithWorkspaceRuntimeStorage,
157
153
  searchWorkspaceSessionsForResponse,
158
154
  unarchiveDaemonSessions
159
- } from "./chunk-URSCX7S7.js";
155
+ } from "./chunk-ZPL2TZNA.js";
160
156
  import {
161
157
  LIVE_SESSION_SOURCE_PREFIX,
162
158
  isCompatibleLiveSessionSource,
@@ -208,17 +204,17 @@ import {
208
204
  import {
209
205
  evaluateDaemonWorkspaceTrust,
210
206
  readDaemonTrustPolicySnapshot
211
- } from "./chunk-IFD3BTEA.js";
207
+ } from "./chunk-EOET4H7C.js";
212
208
  import {
213
209
  readRecentPromptTerminals,
214
210
  reconcileDanglingPromptTerminals,
215
211
  withPromptTerminals
216
- } from "./chunk-CWNC7M73.js";
212
+ } from "./chunk-IKG2YVRZ.js";
217
213
  import {
218
214
  WorkspaceGenerationClosedError,
219
215
  createSingleWorkspaceRegistry,
220
216
  createWorkspaceSessionOwnerIndex
221
- } from "./chunk-QJVZLILI.js";
217
+ } from "./chunk-R7OO56VZ.js";
222
218
  import {
223
219
  sessionAttachmentsRoots
224
220
  } from "./chunk-XWJFDJZK.js";
@@ -244,11 +240,11 @@ import {
244
240
  sendUntrustedWorkspaceResponse,
245
241
  sendWorkspaceRuntimeUnavailable,
246
242
  setWorkspaceRouteContext
247
- } from "./chunk-CZACBHAW.js";
243
+ } from "./chunk-B3EL44K3.js";
248
244
  import {
249
245
  normalizeChannelDelivery,
250
246
  parseChannelDelivery
251
- } from "./chunk-PZUOHCWI.js";
247
+ } from "./chunk-WAASYFPK.js";
252
248
  import {
253
249
  isValidSessionId,
254
250
  normalizeSessionIdForLookup,
@@ -263,7 +259,7 @@ import {
263
259
  getWorkspaceRuntimeCoordinator,
264
260
  getWorkspaceRuntimeCoordinatorIfSupported,
265
261
  supportsWorkspaceRuntimeLifecycle
266
- } from "./chunk-GCFZ2LAX.js";
262
+ } from "./chunk-HZ2HUXX7.js";
267
263
  import "./chunk-OIBUG24X.js";
268
264
  import {
269
265
  MAX_SESSION_RESTORE_TIMEOUT_MS,
@@ -285,14 +281,14 @@ import {
285
281
  validateWorkspaceSkillName,
286
282
  validateWorkspaceVoiceState,
287
283
  voiceSettingsScopeToWire
288
- } from "./chunk-KJJPJYHI.js";
284
+ } from "./chunk-FWRRUITH.js";
289
285
  import {
290
286
  PermissionRulesValidationError,
291
287
  buildPermissionSettings,
292
288
  isPermissionRuleType,
293
289
  normalizePermissionRules,
294
290
  readPermissionRuleSet
295
- } from "./chunk-MWHY26G3.js";
291
+ } from "./chunk-CHVU543W.js";
296
292
  import {
297
293
  assertVoiceBaseUrlNetworkAllowed,
298
294
  isStreamingVoiceModel,
@@ -300,18 +296,18 @@ import {
300
296
  resolveVoiceTranscriptionConfig,
301
297
  sanitizeVoiceErrorMessage,
302
298
  transcribeVoiceAudio
303
- } from "./chunk-4MCY33Y2.js";
299
+ } from "./chunk-GNY7B3CA.js";
304
300
  import {
305
301
  isVoiceEnabled,
306
302
  isVoiceMode,
307
303
  readVoiceModel
308
- } from "./chunk-XOVVCGZX.js";
304
+ } from "./chunk-NB3NDQQK.js";
309
305
  import "./chunk-Y53DG2HA.js";
310
306
  import {
311
307
  createDaemonStatusProvider
312
- } from "./chunk-LPBQODMR.js";
313
- import "./chunk-P6LATTDG.js";
314
- import "./chunk-YCDL2SAS.js";
308
+ } from "./chunk-OESZTXTG.js";
309
+ import "./chunk-5IL2BZHW.js";
310
+ import "./chunk-6QILGINT.js";
315
311
  import "./chunk-JS73NNWF.js";
316
312
  import {
317
313
  SessionArtifactAuthorizationError,
@@ -320,7 +316,7 @@ import {
320
316
  extractErrorCode,
321
317
  extractErrorMessage,
322
318
  parseSessionSource
323
- } from "./chunk-NAKALAL4.js";
319
+ } from "./chunk-2TMJRF46.js";
324
320
  import {
325
321
  EVENT_SCHEMA_VERSION,
326
322
  EventBus,
@@ -330,24 +326,24 @@ import "./chunk-WCCLLK7X.js";
330
326
  import "./chunk-OCPBI7J5.js";
331
327
  import {
332
328
  createSpawnChannelFactory
333
- } from "./chunk-LMJQSPWB.js";
329
+ } from "./chunk-KA5HR3G2.js";
334
330
  import {
335
331
  createWorkspaceProvidersStatusProvider
336
- } from "./chunk-D4CU6DKR.js";
332
+ } from "./chunk-DO5SMV52.js";
337
333
  import {
338
334
  PERSIST_REASONING_SELECTION_META_KEY,
339
335
  REASONING_SELECTION_PERSISTED_META_KEY
340
- } from "./chunk-ZJ2LM2SI.js";
336
+ } from "./chunk-JGDRB4FP.js";
341
337
  import {
342
338
  getAuthTypeFromEnv,
343
339
  resolveCliGenerationConfig
344
- } from "./chunk-O2GG7H4C.js";
340
+ } from "./chunk-ARYNBBBM.js";
345
341
  import {
346
342
  snapshotProcessEnv
347
- } from "./chunk-4HC4DYKN.js";
343
+ } from "./chunk-6RZX2HIH.js";
348
344
  import {
349
345
  createWorkspaceSkillsStatusProvider
350
- } from "./chunk-J3O5I5ZD.js";
346
+ } from "./chunk-QK4K76T6.js";
351
347
  import "./chunk-BHTYRHJF.js";
352
348
  import {
353
349
  BridgeTimeoutError,
@@ -356,7 +352,7 @@ import {
356
352
  SessionRestoreTimeoutError,
357
353
  createIdleWorkspaceMemoryStatus,
358
354
  mapDomainErrorToErrorKind
359
- } from "./chunk-KPXRFTT7.js";
355
+ } from "./chunk-FETY36NQ.js";
360
356
  import {
361
357
  resolveSkillSettings
362
358
  } from "./chunk-HWVUSYSN.js";
@@ -366,29 +362,35 @@ import {
366
362
  WorkspaceSkillNotFoundError,
367
363
  mapWorkspaceSkillToggleError
368
364
  } from "./chunk-FTJMWDND.js";
369
- import "./chunk-537SQ2AI.js";
365
+ import "./chunk-5WC2ECUK.js";
370
366
  import {
371
367
  daemonObservedContactsPath,
372
368
  loadChannelsConfig
373
- } from "./chunk-IXSGOSEG.js";
374
- import "./chunk-AHBLRVD5.js";
369
+ } from "./chunk-DZ6D4B3K.js";
370
+ import "./chunk-EEKU6COG.js";
375
371
  import "./chunk-57OAHC2Y.js";
376
372
  import {
377
373
  parseChannelWebhookConfigLenient
378
- } from "./chunk-TMWB67LS.js";
374
+ } from "./chunk-UXDVUFKU.js";
379
375
  import {
380
376
  supportedChannelCatalog
381
- } from "./chunk-4IQKBLTQ.js";
382
- import "./chunk-WXC6OAWD.js";
377
+ } from "./chunk-UHUT4IDM.js";
378
+ import "./chunk-3BTHHXXE.js";
383
379
  import "./chunk-V6WHFGST.js";
384
380
  import {
381
+ assertLiveDiscoveryPublisher,
385
382
  getStableLiveDiscoveryBaseDir
386
- } from "./chunk-OHOO527W.js";
383
+ } from "./chunk-WG7BL3FY.js";
387
384
  import {
385
+ ConversationRuntimeOwnershipError,
388
386
  LIVE_HOST_BUNDLE_ID,
389
387
  LIVE_HOST_PROTOCOL_VERSION,
390
- LIVE_INPUT_AUDIO_EPOCH_BYTES
391
- } from "./chunk-IQAFKVXS.js";
388
+ LIVE_INPUT_AUDIO_EPOCH_BYTES,
389
+ conversationRootCompromisedError,
390
+ conversationRuntimeInUseError,
391
+ conversationRuntimeOwnershipCompromisedError,
392
+ conversationRuntimeUnavailableError
393
+ } from "./chunk-2Z3T52OC.js";
392
394
  import "./chunk-ZL4HFSL6.js";
393
395
  import "./chunk-K6KS3LTN.js";
394
396
  import "./chunk-OSHQMOBS.js";
@@ -399,13 +401,13 @@ import {
399
401
  WorkspaceRegistrationStoreLimitError,
400
402
  normalizeWorkspaceDisplayName,
401
403
  workspaceRegistrationId
402
- } from "./chunk-5YY5MZT6.js";
404
+ } from "./chunk-QZOXVQPK.js";
403
405
  import {
404
406
  CHANNEL_PROMPT_META_KEY,
405
407
  DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,
406
408
  REQUESTED_SESSION_ID_META_KEY,
407
409
  gradeActiveWorkCoverage
408
- } from "./chunk-WEXA2DNG.js";
410
+ } from "./chunk-PSPAM24S.js";
409
411
  import {
410
412
  BranchWhilePromptActiveError,
411
413
  BridgeChannelQuarantinedError,
@@ -431,6 +433,7 @@ import {
431
433
  SessionLimitExceededError,
432
434
  SessionNotArchivedError,
433
435
  SessionNotFoundError,
436
+ SessionResetPendingError,
434
437
  SessionShellClientRequiredError,
435
438
  SessionShellDisabledError,
436
439
  StandaloneSessionSpawnError,
@@ -441,7 +444,7 @@ import {
441
444
  WorkspaceInitRaceError,
442
445
  WorkspaceInitSymlinkError,
443
446
  WorkspaceMismatchError
444
- } from "./chunk-F47DITLZ.js";
447
+ } from "./chunk-FAWTMDX7.js";
445
448
  import {
446
449
  MAX_WORKSPACE_PATH_LENGTH,
447
450
  canonicalizeWorkspace,
@@ -461,7 +464,7 @@ import {
461
464
  } from "./chunk-STUJ7IMZ.js";
462
465
  import {
463
466
  normalizeWorkerDiagnostic
464
- } from "./chunk-4JAGXZR3.js";
467
+ } from "./chunk-GM44O6F7.js";
465
468
  import {
466
469
  QWEN_SERVER_TOKEN_ENV
467
470
  } from "./chunk-GYTKQYDB.js";
@@ -479,7 +482,7 @@ import {
479
482
  import "./chunk-3VUENPWF.js";
480
483
  import {
481
484
  sanitizeLogText
482
- } from "./chunk-VDXYYVCD.js";
485
+ } from "./chunk-XVTCSVBK.js";
483
486
  import "./chunk-IW6RQPQB.js";
484
487
  import "./chunk-5HBA2Z7V.js";
485
488
  import {
@@ -494,8 +497,8 @@ import {
494
497
  resolveOutputLanguageOrPreserveAuto,
495
498
  updateOutputLanguageFile,
496
499
  validateSettingValue
497
- } from "./chunk-AQ5NAGWI.js";
498
- import "./chunk-ER273QE6.js";
500
+ } from "./chunk-66JBCTJF.js";
501
+ import "./chunk-2ZFO5JD7.js";
499
502
  import "./chunk-RKUWKYED.js";
500
503
  import "./chunk-BW4333PP.js";
501
504
  import "./chunk-IDS7MSUP.js";
@@ -504,18 +507,18 @@ import {
504
507
  getCurrentLanguage,
505
508
  resolveLanguageSetting,
506
509
  setLanguageAsync
507
- } from "./chunk-MUZCSTOO.js";
510
+ } from "./chunk-CRZBDVP2.js";
508
511
  import {
509
512
  SUPPORTED_LANGUAGES,
510
513
  resolveSupportedLanguage
511
514
  } from "./chunk-5EJZE3FP.js";
512
- import "./chunk-H3UDNQLO.js";
513
- import "./chunk-NUQFUXOG.js";
514
- import "./chunk-XUSOYE2I.js";
515
+ import "./chunk-5CVY5Q2P.js";
516
+ import "./chunk-QTNCGZHQ.js";
517
+ import "./chunk-27LTEY6D.js";
515
518
  import "./chunk-W3N5XAZ6.js";
516
519
  import {
517
520
  getWorkspaceTrustStatus
518
- } from "./chunk-XY3USGFE.js";
521
+ } from "./chunk-3VDLQUR2.js";
519
522
  import "./chunk-NPQ5ZKRP.js";
520
523
  import {
521
524
  isWithinRoot as isWithinRoot2
@@ -532,24 +535,25 @@ import {
532
535
  loadIgnoreRules,
533
536
  shouldShowStep,
534
537
  writeWorkspaceContextFile
535
- } from "./chunk-UEZOXZNI.js";
538
+ } from "./chunk-ZU2T5JIS.js";
536
539
  import "./chunk-GELRJXE2.js";
537
540
  import "./chunk-32CM56LO.js";
538
- import "./chunk-JPEAQJNS.js";
539
- import "./chunk-WTW36TJ3.js";
541
+ import "./chunk-WJDXKQIO.js";
542
+ import "./chunk-2EKVPSIJ.js";
540
543
  import "./chunk-LJZSMWOH.js";
541
544
  import {
545
+ clearWorktreeSession,
542
546
  readWorktreeSession,
543
547
  readWorktreeSessionStrict,
544
548
  writeWorktreeSession
545
- } from "./chunk-VUSSAGKI.js";
546
- import "./chunk-O45WBTNS.js";
549
+ } from "./chunk-YZTGGCEE.js";
550
+ import "./chunk-6SADVYQQ.js";
547
551
  import "./chunk-DJXSOEFB.js";
548
- import "./chunk-2WGJG2KW.js";
549
- import "./chunk-QMFOYPGV.js";
550
- import "./chunk-LDS57224.js";
552
+ import "./chunk-25CBAK3H.js";
553
+ import "./chunk-J3VZF2AL.js";
554
+ import "./chunk-OWCFKIFQ.js";
551
555
  import "./chunk-ZPJWUGCS.js";
552
- import "./chunk-HFTB354P.js";
556
+ import "./chunk-5Z4FCEPY.js";
553
557
  import "./chunk-BUQN5LTI.js";
554
558
  import {
555
559
  QwenOAuth2Client,
@@ -559,8 +563,8 @@ import {
559
563
  isDeviceAuthorizationSuccess,
560
564
  isDeviceTokenPending,
561
565
  isDeviceTokenSuccess
562
- } from "./chunk-VU7O7CGQ.js";
563
- import "./chunk-QSC5YOEC.js";
566
+ } from "./chunk-XDNFODER.js";
567
+ import "./chunk-YAC7H4K3.js";
564
568
  import "./chunk-VNOVK4I7.js";
565
569
  import {
566
570
  BuiltinAgentRegistry,
@@ -644,20 +648,22 @@ import {
644
648
  toSessionPrInfo,
645
649
  upsertSessionPr,
646
650
  watchRepoBranch
647
- } from "./chunk-I72PHOKL.js";
651
+ } from "./chunk-PDUMGZ2P.js";
648
652
  import "./chunk-GOFAQQZA.js";
649
- import "./chunk-3K65MUKD.js";
653
+ import "./chunk-65I7S4Z3.js";
650
654
  import "./chunk-6HUXPLB5.js";
651
655
  import "./chunk-TWPJO254.js";
652
656
  import "./chunk-CQ35AJ4Z.js";
653
657
  import "./chunk-YHDGABDC.js";
654
- import "./chunk-RDKXZ2LS.js";
658
+ import "./chunk-LYT2OU7D.js";
655
659
  import "./chunk-B54PFQS5.js";
656
660
  import {
657
661
  GitWorktreeService,
662
+ WorktreeMarkerCommittedError,
658
663
  createWorktreeSessionMarkerExclusive,
659
- readWorktreeSessionMarkerStrict
660
- } from "./chunk-43NOB5NM.js";
664
+ readWorktreeSessionMarkerStrict,
665
+ transferWorktreeSessionMarkerOwner
666
+ } from "./chunk-HIXUUCGY.js";
661
667
  import "./chunk-6PVPNMXU.js";
662
668
  import "./chunk-565U2ANU.js";
663
669
  import "./chunk-FDOGGKAA.js";
@@ -669,14 +675,14 @@ import {
669
675
  taskHasLegacyCondition,
670
676
  updateCronTasks
671
677
  } from "./chunk-F53KKZUD.js";
672
- import "./chunk-PZV2FASB.js";
678
+ import "./chunk-TRWQQBVH.js";
673
679
  import {
674
680
  glob
675
681
  } from "./chunk-QJNDUTOL.js";
676
- import "./chunk-OECNP26L.js";
682
+ import "./chunk-N6S3NUYJ.js";
677
683
  import "./chunk-O6GEWCJA.js";
678
684
  import "./chunk-CHEIIBT3.js";
679
- import "./chunk-UKKYOIVT.js";
685
+ import "./chunk-QAZ2MGYT.js";
680
686
  import "./chunk-B44JBZBB.js";
681
687
  import "./chunk-BF3RUIVP.js";
682
688
  import {
@@ -686,28 +692,27 @@ import {
686
692
  recordDaemonBridgeError,
687
693
  recordDaemonHttpRequest,
688
694
  validateSkillName
689
- } from "./chunk-R355CUNQ.js";
690
- import "./chunk-4VUVBN3Y.js";
695
+ } from "./chunk-CLKE4IY3.js";
691
696
  import "./chunk-ZSTCM3MX.js";
692
- import "./chunk-NXWYCSPL.js";
697
+ import "./chunk-SOA4HKRJ.js";
693
698
  import "./chunk-MLXTMF7H.js";
694
- import "./chunk-GXZHYPHZ.js";
699
+ import "./chunk-3LPJ776W.js";
695
700
  import {
696
701
  findGitRoot
697
702
  } from "./chunk-3CZ2BQV6.js";
698
703
  import "./chunk-PQEISIKS.js";
699
- import "./chunk-3K456UJF.js";
700
- import "./chunk-VEFRT7NX.js";
704
+ import "./chunk-VF6D6EGV.js";
705
+ import "./chunk-H3Q3RSKZ.js";
701
706
  import "./chunk-S6LOFUVP.js";
702
707
  import "./chunk-NAVJD2PQ.js";
703
- import "./chunk-UKADFFL2.js";
704
- import "./chunk-EJNYBDYC.js";
708
+ import "./chunk-OFVAS4AR.js";
709
+ import "./chunk-HNLMYDQE.js";
705
710
  import "./chunk-QHMLYMMS.js";
706
711
  import "./chunk-CFKIH3D3.js";
707
- import "./chunk-2LD5U7Q3.js";
712
+ import "./chunk-6YEOCHSE.js";
708
713
  import "./chunk-DJ2GSRLV.js";
709
- import "./chunk-W4LL5RZO.js";
710
- import "./chunk-3UMWOKJC.js";
714
+ import "./chunk-4ALNJDHL.js";
715
+ import "./chunk-NOO4QFXM.js";
711
716
  import "./chunk-KFFCDLKV.js";
712
717
  import {
713
718
  addDaemonRequestAttribute,
@@ -725,7 +730,7 @@ import "./chunk-XWRJCPHC.js";
725
730
  import {
726
731
  parseLineTolerant,
727
732
  read
728
- } from "./chunk-P5LDR7FI.js";
733
+ } from "./chunk-6QV7Z74P.js";
729
734
  import "./chunk-5ETULJLP.js";
730
735
  import "./chunk-XBVNNDPK.js";
731
736
  import "./chunk-VGC4I5JJ.js";
@@ -743,7 +748,7 @@ import "./chunk-HD7O6WLV.js";
743
748
  import "./chunk-WZAD4ZNJ.js";
744
749
  import "./chunk-FPGTNKCP.js";
745
750
  import "./chunk-TIGXX4PA.js";
746
- import "./chunk-5MTARK4Y.js";
751
+ import "./chunk-N7YQEKGX.js";
747
752
  import "./chunk-XFFRI3WM.js";
748
753
  import "./chunk-4HOEU2OR.js";
749
754
  import "./chunk-HHJLM3WQ.js";
@@ -753,17 +758,17 @@ import {
753
758
  stripAnsiAndControl
754
759
  } from "./chunk-7VEYUF3N.js";
755
760
  import "./chunk-74TONY4F.js";
756
- import "./chunk-GMNLYQOS.js";
761
+ import "./chunk-E6TI726I.js";
757
762
  import {
758
763
  SubagentError,
759
764
  SubagentErrorCode
760
- } from "./chunk-D6PIMKY3.js";
761
- import "./chunk-NGX4NUNP.js";
765
+ } from "./chunk-4VY3ITHR.js";
766
+ import "./chunk-O2FEO2CB.js";
762
767
  import {
763
768
  escapeXml
764
- } from "./chunk-FKJM6JKY.js";
769
+ } from "./chunk-G6UUOCUT.js";
765
770
  import "./chunk-IZ2U57NY.js";
766
- import "./chunk-RPBMP6BN.js";
771
+ import "./chunk-MWIO7MF6.js";
767
772
  import {
768
773
  FatalConfigError,
769
774
  Storage,
@@ -6221,7 +6226,7 @@ __name(createRequestedSessionIdAdmission, "createRequestedSessionIdAdmission");
6221
6226
 
6222
6227
  // packages/cli/src/serve/conversations/standalone-session-service.ts
6223
6228
  init_esbuild_shims();
6224
- import { randomUUID as randomUUID5 } from "node:crypto";
6229
+ import { randomUUID as randomUUID4 } from "node:crypto";
6225
6230
 
6226
6231
  // packages/cli/src/serve/server/session-export.ts
6227
6232
  init_esbuild_shims();
@@ -6290,473 +6295,10 @@ __name(exportSessionTranscript, "exportSessionTranscript");
6290
6295
 
6291
6296
  // packages/cli/src/serve/conversations/standalone-deletion-journal.ts
6292
6297
  init_esbuild_shims();
6293
- import { randomUUID as randomUUID4 } from "node:crypto";
6294
- import { constants as fsConstants3 } from "node:fs";
6295
- import * as fs2 from "node:fs/promises";
6296
- import * as path8 from "node:path";
6297
-
6298
- // packages/cli/src/serve/conversations/conversation-runtime-ownership.ts
6299
- init_esbuild_shims();
6300
6298
  import { randomUUID as randomUUID3 } from "node:crypto";
6301
6299
  import { constants as fsConstants2 } from "node:fs";
6302
6300
  import * as fs from "node:fs/promises";
6303
6301
  import * as path7 from "node:path";
6304
- var OWNER_DIRECTORY = "conversations";
6305
- var OWNER_FILE = "runtime-owner.json";
6306
- var OWNER_LOCK = ".runtime-owner.lock";
6307
- var MAX_OWNER_BYTES = 4 * 1024;
6308
- var NONCE_PATTERN = /^[A-Za-z0-9_-]{16,256}$/;
6309
- var DEFAULT_HANDOFF_GRACE_MS = 1e3;
6310
- var UnsafeOwnershipStateError = class extends Error {
6311
- static {
6312
- __name(this, "UnsafeOwnershipStateError");
6313
- }
6314
- };
6315
- function getConversationRuntimeOwnerPath(stableBaseDir) {
6316
- return path7.join(stableBaseDir, OWNER_DIRECTORY, OWNER_FILE);
6317
- }
6318
- __name(getConversationRuntimeOwnerPath, "getConversationRuntimeOwnerPath");
6319
- function processIsAlive(pid) {
6320
- try {
6321
- process.kill(pid, 0);
6322
- return true;
6323
- } catch (error2) {
6324
- return error2.code !== "ESRCH";
6325
- }
6326
- }
6327
- __name(processIsAlive, "processIsAlive");
6328
- function delay(milliseconds) {
6329
- return new Promise((resolve7) => {
6330
- setTimeout(resolve7, milliseconds);
6331
- });
6332
- }
6333
- __name(delay, "delay");
6334
- function isMissing(error2) {
6335
- return error2.code === "ENOENT";
6336
- }
6337
- __name(isMissing, "isMissing");
6338
- function assertOwnerRecord(value) {
6339
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
6340
- throw new UnsafeOwnershipStateError();
6341
- }
6342
- const keys = Object.keys(value).sort();
6343
- if (keys.length !== 3 || keys[0] !== "instanceNonce" || keys[1] !== "pid" || keys[2] !== "version") {
6344
- throw new UnsafeOwnershipStateError();
6345
- }
6346
- const record = value;
6347
- if (record["version"] !== 1 || !Number.isSafeInteger(record["pid"]) || record["pid"] <= 0 || typeof record["instanceNonce"] !== "string" || !NONCE_PATTERN.test(record["instanceNonce"])) {
6348
- throw new UnsafeOwnershipStateError();
6349
- }
6350
- return {
6351
- version: 1,
6352
- pid: record["pid"],
6353
- instanceNonce: record["instanceNonce"]
6354
- };
6355
- }
6356
- __name(assertOwnerRecord, "assertOwnerRecord");
6357
- function sameRecord(left, right) {
6358
- return left.version === right.version && left.pid === right.pid && left.instanceNonce === right.instanceNonce;
6359
- }
6360
- __name(sameRecord, "sameRecord");
6361
- async function inspectDirectory(directory, requirePrivateMode) {
6362
- const stat3 = await fs.lstat(directory);
6363
- if (!stat3.isDirectory() || stat3.isSymbolicLink()) {
6364
- throw new UnsafeOwnershipStateError();
6365
- }
6366
- if (process.platform !== "win32" && (typeof process.getuid === "function" && stat3.uid !== process.getuid() || requirePrivateMode && (stat3.mode & 511) !== 448)) {
6367
- throw new UnsafeOwnershipStateError();
6368
- }
6369
- return { dev: stat3.dev, ino: stat3.ino };
6370
- }
6371
- __name(inspectDirectory, "inspectDirectory");
6372
- async function ensureDirectory(directory, requirePrivateMode) {
6373
- try {
6374
- return await inspectDirectory(directory, requirePrivateMode);
6375
- } catch (error2) {
6376
- if (error2 instanceof UnsafeOwnershipStateError || !isMissing(error2)) {
6377
- throw error2;
6378
- }
6379
- }
6380
- const parent = path7.dirname(directory);
6381
- if (parent === directory) throw new UnsafeOwnershipStateError();
6382
- const parentIdentity = await ensureDirectory(parent, false);
6383
- await assertDirectoryIdentity(parent, parentIdentity, false);
6384
- let created = false;
6385
- try {
6386
- await fs.mkdir(directory, { mode: 448 });
6387
- created = true;
6388
- } catch (error2) {
6389
- if (error2.code !== "EEXIST") throw error2;
6390
- }
6391
- if (created && process.platform !== "win32") {
6392
- await fs.chmod(directory, 448);
6393
- }
6394
- await assertDirectoryIdentity(parent, parentIdentity, false);
6395
- return inspectDirectory(directory, requirePrivateMode);
6396
- }
6397
- __name(ensureDirectory, "ensureDirectory");
6398
- async function assertDirectoryIdentity(directory, expected, requirePrivateMode = true) {
6399
- const current = await inspectDirectory(directory, requirePrivateMode);
6400
- if (current.dev !== expected.dev || current.ino !== expected.ino) {
6401
- throw new UnsafeOwnershipStateError();
6402
- }
6403
- }
6404
- __name(assertDirectoryIdentity, "assertDirectoryIdentity");
6405
- async function assertLockShapeIfPresent(lockPath) {
6406
- let stat3;
6407
- try {
6408
- stat3 = await fs.lstat(lockPath);
6409
- } catch (error2) {
6410
- if (isMissing(error2)) return;
6411
- throw error2;
6412
- }
6413
- if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && typeof process.getuid === "function" && stat3.uid !== process.getuid()) {
6414
- throw new UnsafeOwnershipStateError();
6415
- }
6416
- }
6417
- __name(assertLockShapeIfPresent, "assertLockShapeIfPresent");
6418
- async function readOwnerRecord(ownerPath) {
6419
- let pathStat;
6420
- try {
6421
- pathStat = await fs.lstat(ownerPath);
6422
- } catch (error2) {
6423
- if (isMissing(error2)) return void 0;
6424
- throw error2;
6425
- }
6426
- if (!pathStat.isFile() || pathStat.isSymbolicLink() || pathStat.nlink !== 1 || pathStat.size <= 0 || pathStat.size > MAX_OWNER_BYTES || process.platform !== "win32" && ((pathStat.mode & 511) !== 384 || typeof process.getuid === "function" && pathStat.uid !== process.getuid())) {
6427
- throw new UnsafeOwnershipStateError();
6428
- }
6429
- let handle;
6430
- try {
6431
- handle = await fs.open(
6432
- ownerPath,
6433
- process.platform === "win32" ? fsConstants2.O_RDONLY : fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW
6434
- );
6435
- } catch (error2) {
6436
- if (error2.code === "ELOOP") {
6437
- throw new UnsafeOwnershipStateError(void 0, { cause: error2 });
6438
- }
6439
- throw error2;
6440
- }
6441
- try {
6442
- const handleStat = await handle.stat();
6443
- if (!handleStat.isFile() || handleStat.nlink !== 1 || handleStat.dev !== pathStat.dev || handleStat.ino !== pathStat.ino || handleStat.size !== pathStat.size || process.platform !== "win32" && ((handleStat.mode & 511) !== 384 || typeof process.getuid === "function" && handleStat.uid !== process.getuid())) {
6444
- throw new UnsafeOwnershipStateError();
6445
- }
6446
- const serialized = await handle.readFile("utf8");
6447
- let parsed;
6448
- try {
6449
- parsed = JSON.parse(serialized);
6450
- } catch (error2) {
6451
- throw new UnsafeOwnershipStateError(void 0, { cause: error2 });
6452
- }
6453
- return assertOwnerRecord(parsed);
6454
- } finally {
6455
- await handle.close();
6456
- }
6457
- }
6458
- __name(readOwnerRecord, "readOwnerRecord");
6459
- async function syncDirectory(directory) {
6460
- if (process.platform === "win32") return;
6461
- const handle = await fs.open(directory, fsConstants2.O_RDONLY);
6462
- try {
6463
- await handle.sync();
6464
- } finally {
6465
- await handle.close();
6466
- }
6467
- }
6468
- __name(syncDirectory, "syncDirectory");
6469
- var FileConversationRuntimeOwnership = class {
6470
- static {
6471
- __name(this, "FileConversationRuntimeOwnership");
6472
- }
6473
- stableBaseDir;
6474
- ownerDirectory;
6475
- ownerPath;
6476
- lockPath;
6477
- current;
6478
- isProcessAlive;
6479
- wait;
6480
- handoffGraceMs;
6481
- lockOptions;
6482
- state = "unclaimed";
6483
- terminalError;
6484
- acquirePending;
6485
- releasePending;
6486
- constructor(options) {
6487
- this.stableBaseDir = options.stableBaseDir;
6488
- this.ownerDirectory = path7.dirname(
6489
- getConversationRuntimeOwnerPath(options.stableBaseDir)
6490
- );
6491
- this.ownerPath = getConversationRuntimeOwnerPath(options.stableBaseDir);
6492
- this.lockPath = path7.join(this.ownerDirectory, OWNER_LOCK);
6493
- this.current = {
6494
- version: 1,
6495
- pid: options.pid,
6496
- instanceNonce: options.instanceNonce
6497
- };
6498
- this.isProcessAlive = options.isProcessAlive ?? processIsAlive;
6499
- this.wait = options.wait ?? delay;
6500
- this.handoffGraceMs = options.handoffGraceMs ?? DEFAULT_HANDOFF_GRACE_MS;
6501
- this.lockOptions = options.lockOptions ?? {
6502
- stale: 5e3,
6503
- update: 1e3,
6504
- retries: {
6505
- retries: 40,
6506
- minTimeout: 10,
6507
- maxTimeout: 50,
6508
- factor: 1.2,
6509
- randomize: true
6510
- }
6511
- };
6512
- }
6513
- acquire() {
6514
- if (this.acquirePending) return this.acquirePending;
6515
- const pending = this.acquireOnce().finally(() => {
6516
- if (this.acquirePending === pending) this.acquirePending = void 0;
6517
- });
6518
- this.acquirePending = pending;
6519
- return pending;
6520
- }
6521
- release() {
6522
- if (this.releasePending) return this.releasePending;
6523
- const pending = this.releaseOnce().finally(() => {
6524
- if (this.releasePending === pending) this.releasePending = void 0;
6525
- });
6526
- this.releasePending = pending;
6527
- return pending;
6528
- }
6529
- async acquireOnce() {
6530
- if (this.terminalError) throw this.terminalError;
6531
- if (this.state === "released") {
6532
- throw this.compromise();
6533
- }
6534
- if (this.releasePending) {
6535
- await this.releasePending.catch(() => void 0);
6536
- throw this.compromise();
6537
- }
6538
- const identity = await this.prepareOwnerDirectory();
6539
- let releaseLock;
6540
- let operationError;
6541
- let reclaimed = false;
6542
- let lockCompromise;
6543
- try {
6544
- await assertLockShapeIfPresent(this.lockPath);
6545
- const lockfile = (await import("./proper-lockfile-3LHWIM44.js")).default;
6546
- releaseLock = await lockfile.lock(this.ownerDirectory, {
6547
- realpath: false,
6548
- lockfilePath: this.lockPath,
6549
- ...this.lockOptions,
6550
- onCompromised: /* @__PURE__ */ __name((error2) => {
6551
- lockCompromise = error2;
6552
- }, "onCompromised")
6553
- });
6554
- await assertLockShapeIfPresent(this.lockPath);
6555
- await assertDirectoryIdentity(this.ownerDirectory, identity);
6556
- if (lockCompromise) throw new UnsafeOwnershipStateError();
6557
- const existing = await readOwnerRecord(this.ownerPath);
6558
- const commitOwner = /* @__PURE__ */ __name(async () => {
6559
- if (this.state === "owned") {
6560
- if (!existing || !sameRecord(existing, this.current)) {
6561
- throw new UnsafeOwnershipStateError();
6562
- }
6563
- } else if (existing && sameRecord(existing, this.current)) {
6564
- this.state = "provisional";
6565
- } else if (existing) {
6566
- if (existing.pid === this.current.pid || this.isProcessAlive(existing.pid)) {
6567
- throw conversationRuntimeInUseError();
6568
- }
6569
- reclaimed = true;
6570
- await this.commitRecord(identity, existing);
6571
- } else {
6572
- await this.commitRecord(identity, void 0);
6573
- }
6574
- }, "commitOwner");
6575
- const liveDiscovery = await import("./discovery-TUM3ZQ6U.js");
6576
- const handoff = await liveDiscovery.handoffLiveDiscoveryOwner(
6577
- this.stableBaseDir,
6578
- this.current,
6579
- commitOwner,
6580
- {
6581
- isProcessAlive: this.isProcessAlive,
6582
- waitForHandoffGrace: false
6583
- }
6584
- );
6585
- reclaimed ||= handoff.reclaimed;
6586
- } catch (error2) {
6587
- operationError = error2;
6588
- }
6589
- let releaseError;
6590
- if (releaseLock) {
6591
- try {
6592
- await releaseLock();
6593
- } catch (error2) {
6594
- releaseError = error2;
6595
- }
6596
- }
6597
- if (lockCompromise || releaseError) {
6598
- throw this.compromise(lockCompromise ?? releaseError);
6599
- }
6600
- if (operationError) {
6601
- throw this.mapAcquireError(operationError);
6602
- }
6603
- if (reclaimed) {
6604
- try {
6605
- await this.wait(this.handoffGraceMs);
6606
- } catch (error2) {
6607
- throw this.compromise(error2);
6608
- }
6609
- }
6610
- if (this.state === "provisional") this.state = "owned";
6611
- return { reclaimed };
6612
- }
6613
- async releaseOnce() {
6614
- if (this.acquirePending) {
6615
- await this.acquirePending.catch(() => void 0);
6616
- }
6617
- if (this.state === "unclaimed" || this.state === "released") return false;
6618
- if (this.state === "provisional" || this.terminalError) {
6619
- throw this.terminalError ?? this.compromise();
6620
- }
6621
- const identity = await this.prepareOwnerDirectory();
6622
- let releaseLock;
6623
- let operationError;
6624
- let lockCompromise;
6625
- try {
6626
- await assertLockShapeIfPresent(this.lockPath);
6627
- const lockfile = (await import("./proper-lockfile-3LHWIM44.js")).default;
6628
- releaseLock = await lockfile.lock(this.ownerDirectory, {
6629
- realpath: false,
6630
- lockfilePath: this.lockPath,
6631
- ...this.lockOptions,
6632
- onCompromised: /* @__PURE__ */ __name((error2) => {
6633
- lockCompromise = error2;
6634
- }, "onCompromised")
6635
- });
6636
- await assertLockShapeIfPresent(this.lockPath);
6637
- await assertDirectoryIdentity(this.ownerDirectory, identity);
6638
- const existing = await readOwnerRecord(this.ownerPath);
6639
- if (lockCompromise || !existing || !sameRecord(existing, this.current)) {
6640
- throw new UnsafeOwnershipStateError();
6641
- }
6642
- await assertDirectoryIdentity(this.ownerDirectory, identity);
6643
- await fs.unlink(this.ownerPath);
6644
- this.state = "released";
6645
- await syncDirectory(this.ownerDirectory);
6646
- } catch (error2) {
6647
- operationError = error2;
6648
- }
6649
- let releaseError;
6650
- if (releaseLock) {
6651
- try {
6652
- await releaseLock();
6653
- } catch (error2) {
6654
- releaseError = error2;
6655
- }
6656
- }
6657
- if (lockCompromise || releaseError) {
6658
- if (this.state !== "released") this.compromise(lockCompromise);
6659
- throw conversationRuntimeOwnershipCompromisedError(
6660
- lockCompromise ?? releaseError
6661
- );
6662
- }
6663
- if (operationError) {
6664
- if (this.state === "released") {
6665
- throw conversationRuntimeOwnershipCompromisedError(operationError);
6666
- }
6667
- if (operationError instanceof UnsafeOwnershipStateError) {
6668
- throw this.compromise(operationError);
6669
- }
6670
- throw conversationRuntimeUnavailableError(operationError);
6671
- }
6672
- return true;
6673
- }
6674
- async prepareOwnerDirectory() {
6675
- try {
6676
- if (this.state === "unclaimed") {
6677
- await ensureDirectory(this.stableBaseDir, false);
6678
- return await ensureDirectory(this.ownerDirectory, true);
6679
- }
6680
- await inspectDirectory(this.stableBaseDir, false);
6681
- return await inspectDirectory(this.ownerDirectory, true);
6682
- } catch (error2) {
6683
- if (error2 instanceof UnsafeOwnershipStateError || this.state !== "unclaimed" && isMissing(error2)) {
6684
- throw this.compromise(error2);
6685
- }
6686
- throw conversationRuntimeUnavailableError(error2);
6687
- }
6688
- }
6689
- async commitRecord(identity, expected) {
6690
- const temporaryPath = path7.join(
6691
- this.ownerDirectory,
6692
- `.runtime-owner.${this.current.pid}.${randomUUID3()}.tmp`
6693
- );
6694
- let handle;
6695
- let renamed = false;
6696
- try {
6697
- handle = await fs.open(temporaryPath, "wx", 384);
6698
- await handle.writeFile(`${JSON.stringify(this.current)}
6699
- `, "utf8");
6700
- await handle.sync();
6701
- if (process.platform !== "win32") await handle.chmod(384);
6702
- await handle.close();
6703
- handle = void 0;
6704
- await assertDirectoryIdentity(this.ownerDirectory, identity);
6705
- const observed = await readOwnerRecord(this.ownerPath);
6706
- if (expected === void 0 && observed !== void 0 || expected !== void 0 && (!observed || !sameRecord(observed, expected))) {
6707
- throw new UnsafeOwnershipStateError();
6708
- }
6709
- await assertDirectoryIdentity(this.ownerDirectory, identity);
6710
- if (process.platform === "win32" && observed) {
6711
- await fs.unlink(this.ownerPath);
6712
- try {
6713
- await fs.rename(temporaryPath, this.ownerPath);
6714
- } catch (error2) {
6715
- await this.wait(this.handoffGraceMs);
6716
- throw error2;
6717
- }
6718
- } else {
6719
- await fs.rename(temporaryPath, this.ownerPath);
6720
- }
6721
- renamed = true;
6722
- this.state = "provisional";
6723
- await syncDirectory(this.ownerDirectory);
6724
- } finally {
6725
- await handle?.close().catch(() => void 0);
6726
- if (!renamed) {
6727
- await fs.unlink(temporaryPath).catch(() => void 0);
6728
- }
6729
- }
6730
- }
6731
- mapAcquireError(error2) {
6732
- if (error2 instanceof ConversationRuntimeOwnershipError) return error2;
6733
- if (error2 instanceof Error && error2.name === "LiveDiscoveryOwnerActiveError") {
6734
- return conversationRuntimeInUseError();
6735
- }
6736
- if (error2 instanceof UnsafeOwnershipStateError) {
6737
- return this.compromise(error2);
6738
- }
6739
- if (this.state === "provisional" || error2 instanceof Error && error2.name === "LiveDiscoveryStateError") {
6740
- return this.compromise(error2);
6741
- }
6742
- const code = error2.code;
6743
- if (code === "ECOMPROMISED") return this.compromise(error2);
6744
- return conversationRuntimeUnavailableError(error2);
6745
- }
6746
- compromise(cause) {
6747
- this.terminalError ??= conversationRuntimeOwnershipCompromisedError(cause);
6748
- return this.terminalError;
6749
- }
6750
- };
6751
- function createConversationRuntimeOwnership(options) {
6752
- if (!path7.isAbsolute(options.stableBaseDir) || !Number.isSafeInteger(options.pid) || options.pid <= 0 || !NONCE_PATTERN.test(options.instanceNonce) || !Number.isSafeInteger(options.handoffGraceMs ?? DEFAULT_HANDOFF_GRACE_MS) || (options.handoffGraceMs ?? DEFAULT_HANDOFF_GRACE_MS) < 0) {
6753
- throw new TypeError("Invalid Conversations runtime ownership options.");
6754
- }
6755
- return new FileConversationRuntimeOwnership(options);
6756
- }
6757
- __name(createConversationRuntimeOwnership, "createConversationRuntimeOwnership");
6758
-
6759
- // packages/cli/src/serve/conversations/standalone-deletion-journal.ts
6760
6302
  var JOURNAL_DIRECTORY = "deletions";
6761
6303
  var MAX_RECORD_BYTES = 8 * 1024;
6762
6304
  var STORAGE_SESSION_ID_PATTERN = /^[0-9a-fA-F-]{32,36}$/;
@@ -6771,10 +6313,10 @@ var StandaloneDeletionJournalError = class extends Error {
6771
6313
  }
6772
6314
  name = "StandaloneDeletionJournalError";
6773
6315
  };
6774
- function isMissing2(error2) {
6316
+ function isMissing(error2) {
6775
6317
  return error2.code === "ENOENT";
6776
6318
  }
6777
- __name(isMissing2, "isMissing");
6319
+ __name(isMissing, "isMissing");
6778
6320
  function parseSessionId(value) {
6779
6321
  const parsed = parseCallerSuppliedSessionId(value);
6780
6322
  if (parsed.kind !== "valid") {
@@ -6805,7 +6347,7 @@ function parseIdentity(value, pathField) {
6805
6347
  if (!isIdentityNumber(value["device"]) || !isIdentityNumber(value["inode"]) || typeof value["inodeVerifiable"] !== "boolean" || (value["inodeVerifiable"] ? value["inode"] === 0 : value["inode"] !== 0)) {
6806
6348
  return void 0;
6807
6349
  }
6808
- if (pathField && (typeof value["canonicalPath"] !== "string" || value["canonicalPath"].length === 0 || value["canonicalPath"].length > 4096 || !path8.isAbsolute(value["canonicalPath"]))) {
6350
+ if (pathField && (typeof value["canonicalPath"] !== "string" || value["canonicalPath"].length === 0 || value["canonicalPath"].length > 4096 || !path7.isAbsolute(value["canonicalPath"]))) {
6809
6351
  return void 0;
6810
6352
  }
6811
6353
  return {
@@ -6900,25 +6442,26 @@ function sameImmutableRecord(prepared, staged) {
6900
6442
  }
6901
6443
  __name(sameImmutableRecord, "sameImmutableRecord");
6902
6444
  var StandaloneDeletionJournal = class {
6445
+ constructor(stableBaseDir) {
6446
+ this.stableBaseDir = stableBaseDir;
6447
+ if (!path7.isAbsolute(stableBaseDir)) {
6448
+ throw new TypeError("Standalone deletion journal base must be absolute.");
6449
+ }
6450
+ this.stateDirectory = path7.join(stableBaseDir, "conversations");
6451
+ this.journalDirectory = path7.join(this.stateDirectory, JOURNAL_DIRECTORY);
6452
+ }
6903
6453
  static {
6904
6454
  __name(this, "StandaloneDeletionJournal");
6905
6455
  }
6906
- ownerDirectory;
6456
+ stateDirectory;
6907
6457
  journalDirectory;
6458
+ directoryIdentities = /* @__PURE__ */ new Map();
6459
+ canonicalBaseDir;
6908
6460
  pendingClears = /* @__PURE__ */ new Map();
6909
- constructor(stableBaseDir) {
6910
- if (!path8.isAbsolute(stableBaseDir)) {
6911
- throw new TypeError("Standalone deletion journal base must be absolute.");
6912
- }
6913
- this.ownerDirectory = path8.dirname(
6914
- getConversationRuntimeOwnerPath(stableBaseDir)
6915
- );
6916
- this.journalDirectory = path8.join(this.ownerDirectory, JOURNAL_DIRECTORY);
6917
- }
6918
6461
  async hasRecord(rawSessionId) {
6919
6462
  const sessionId = parseSessionId(rawSessionId);
6920
- if (this.pendingClears.has(sessionId)) return true;
6921
6463
  const identity = await this.inspectJournalDirectory();
6464
+ if (this.pendingClears.has(sessionId)) return true;
6922
6465
  if (!identity) return false;
6923
6466
  const exists = await this.pathExists(this.recordPath(sessionId, "prepared")) || await this.pathExists(this.recordPath(sessionId, "staged"));
6924
6467
  await this.assertDirectoryIdentity(this.journalDirectory, identity);
@@ -6932,9 +6475,9 @@ var StandaloneDeletionJournal = class {
6932
6475
  }
6933
6476
  let names;
6934
6477
  try {
6935
- names = await fs2.readdir(this.journalDirectory);
6478
+ names = await fs.readdir(this.journalDirectory);
6936
6479
  } catch (error2) {
6937
- if (isMissing2(error2)) {
6480
+ if (isMissing(error2)) {
6938
6481
  return [...ids].sort().slice(0, Math.max(0, limit));
6939
6482
  }
6940
6483
  throw error2;
@@ -6948,11 +6491,11 @@ var StandaloneDeletionJournal = class {
6948
6491
  }
6949
6492
  async read(rawSessionId, currentRoot) {
6950
6493
  const sessionId = parseSessionId(rawSessionId);
6494
+ const identity = await this.inspectJournalDirectory();
6951
6495
  const pending = this.pendingClears.get(sessionId);
6952
6496
  if (pending) {
6953
6497
  return this.validatePendingEntry(pending.entry, currentRoot);
6954
6498
  }
6955
- const identity = await this.inspectJournalDirectory();
6956
6499
  if (!identity) return void 0;
6957
6500
  const prepared = await this.readPhase(sessionId, "prepared", currentRoot);
6958
6501
  const staged = await this.readPhase(sessionId, "staged", currentRoot);
@@ -6995,6 +6538,7 @@ var StandaloneDeletionJournal = class {
6995
6538
  }
6996
6539
  async clear(rawSessionId, currentRoot) {
6997
6540
  const sessionId = parseSessionId(rawSessionId);
6541
+ await this.inspectJournalDirectory();
6998
6542
  const pending = this.pendingClears.get(sessionId);
6999
6543
  if (pending) {
7000
6544
  this.validatePendingEntry(pending.entry, currentRoot);
@@ -7046,7 +6590,7 @@ var StandaloneDeletionJournal = class {
7046
6590
  return { prepared, ...staged ? { staged } : {} };
7047
6591
  }
7048
6592
  recordPath(sessionId, phase) {
7049
- return path8.join(
6593
+ return path7.join(
7050
6594
  this.journalDirectory,
7051
6595
  `delete-${sessionId}.${phase}.json`
7052
6596
  );
@@ -7055,17 +6599,17 @@ var StandaloneDeletionJournal = class {
7055
6599
  const filePath = this.recordPath(sessionId, phase);
7056
6600
  let pathStat;
7057
6601
  try {
7058
- pathStat = await fs2.lstat(filePath);
6602
+ pathStat = await fs.lstat(filePath);
7059
6603
  } catch (error2) {
7060
- if (isMissing2(error2)) return void 0;
6604
+ if (isMissing(error2)) return void 0;
7061
6605
  throw error2;
7062
6606
  }
7063
6607
  this.assertRecordFile(pathStat);
7064
6608
  let handle;
7065
6609
  try {
7066
- handle = await fs2.open(
6610
+ handle = await fs.open(
7067
6611
  filePath,
7068
- fsConstants3.O_RDONLY | (process.platform === "win32" ? 0 : fsConstants3.O_NOFOLLOW ?? 0)
6612
+ fsConstants2.O_RDONLY | (process.platform === "win32" ? 0 : fsConstants2.O_NOFOLLOW ?? 0)
7069
6613
  );
7070
6614
  } catch (error2) {
7071
6615
  if (error2.code === "ELOOP") {
@@ -7100,9 +6644,9 @@ var StandaloneDeletionJournal = class {
7100
6644
  const identity = await this.ensureJournalDirectory();
7101
6645
  const target = this.recordPath(record.sessionId, record.phase);
7102
6646
  await this.assertPathAbsent(target);
7103
- const temporary = path8.join(
6647
+ const temporary = path7.join(
7104
6648
  this.journalDirectory,
7105
- `.${path8.basename(target)}.${randomUUID4()}.tmp`
6649
+ `.${path7.basename(target)}.${randomUUID3()}.tmp`
7106
6650
  );
7107
6651
  const directory = await this.openDurableDirectory(
7108
6652
  this.journalDirectory,
@@ -7111,9 +6655,9 @@ var StandaloneDeletionJournal = class {
7111
6655
  let handle;
7112
6656
  try {
7113
6657
  await this.assertDirectoryIdentity(this.journalDirectory, identity);
7114
- handle = await fs2.open(
6658
+ handle = await fs.open(
7115
6659
  temporary,
7116
- fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_WRONLY | (process.platform === "win32" ? 0 : fsConstants3.O_NOFOLLOW ?? 0),
6660
+ fsConstants2.O_CREAT | fsConstants2.O_EXCL | fsConstants2.O_WRONLY | (process.platform === "win32" ? 0 : fsConstants2.O_NOFOLLOW ?? 0),
7117
6661
  384
7118
6662
  );
7119
6663
  await handle.writeFile(serialized, "utf8");
@@ -7122,12 +6666,12 @@ var StandaloneDeletionJournal = class {
7122
6666
  handle = void 0;
7123
6667
  await this.assertDirectoryIdentity(this.journalDirectory, identity);
7124
6668
  await this.assertPathAbsent(target);
7125
- await fs2.rename(temporary, target);
7126
- if (process.platform !== "win32") await fs2.chmod(target, 384);
6669
+ await fs.rename(temporary, target);
6670
+ if (process.platform !== "win32") await fs.chmod(target, 384);
7127
6671
  await this.syncDurableDirectory(directory);
7128
6672
  } catch (error2) {
7129
6673
  await handle?.close().catch(() => void 0);
7130
- await fs2.unlink(temporary).catch(() => void 0);
6674
+ await fs.unlink(temporary).catch(() => void 0);
7131
6675
  if (error2.code === "EEXIST") {
7132
6676
  throw new StandaloneDeletionJournalError("conflict");
7133
6677
  }
@@ -7137,48 +6681,107 @@ var StandaloneDeletionJournal = class {
7137
6681
  }
7138
6682
  }
7139
6683
  async ensureJournalDirectory() {
7140
- const owner = await this.inspectPrivateDirectory(this.ownerDirectory);
6684
+ await this.ensureStateDirectory(this.stableBaseDir, false);
6685
+ const owner = await this.ensureStateDirectory(this.stateDirectory, true);
7141
6686
  const ownerHandle = await this.openDurableDirectory(
7142
- this.ownerDirectory,
6687
+ this.stateDirectory,
7143
6688
  owner
7144
6689
  );
7145
6690
  try {
7146
6691
  let created = false;
7147
6692
  try {
7148
- await fs2.mkdir(this.journalDirectory, { mode: 448 });
6693
+ await fs.mkdir(this.journalDirectory, { mode: 448 });
7149
6694
  created = true;
7150
6695
  } catch (error2) {
7151
6696
  if (error2.code !== "EEXIST") throw error2;
7152
6697
  }
7153
6698
  if (created && process.platform !== "win32") {
7154
- await fs2.chmod(this.journalDirectory, 448);
6699
+ await fs.chmod(this.journalDirectory, 448);
7155
6700
  }
7156
6701
  await this.syncDurableDirectory(ownerHandle);
7157
6702
  } finally {
7158
6703
  await ownerHandle.handle.close().catch(() => void 0);
7159
6704
  }
7160
- return this.inspectPrivateDirectory(this.journalDirectory);
6705
+ return await this.inspectJournalDirectory();
6706
+ }
6707
+ async ensureStateDirectory(directory, requirePrivate) {
6708
+ try {
6709
+ return await this.inspectPrivateDirectory(directory, requirePrivate);
6710
+ } catch (error2) {
6711
+ if (!isMissing(error2)) throw error2;
6712
+ }
6713
+ const parent = path7.dirname(directory);
6714
+ if (parent === directory)
6715
+ throw new StandaloneDeletionJournalError("compromised");
6716
+ const before = await this.ensureStateDirectory(parent, false);
6717
+ let created = false;
6718
+ try {
6719
+ await fs.mkdir(directory, { mode: 448 });
6720
+ created = true;
6721
+ } catch (error2) {
6722
+ if (error2.code !== "EEXIST") throw error2;
6723
+ }
6724
+ if (created && process.platform !== "win32")
6725
+ await fs.chmod(directory, 448);
6726
+ const after = await this.inspectPrivateDirectory(parent, false);
6727
+ if (!sameDirectoryIdentity(before, after)) {
6728
+ throw new StandaloneDeletionJournalError("compromised");
6729
+ }
6730
+ const handle = await fs.open(parent, fsConstants2.O_RDONLY);
6731
+ try {
6732
+ if (process.platform !== "win32") await handle.sync();
6733
+ } finally {
6734
+ await handle.close();
6735
+ }
6736
+ return this.inspectPrivateDirectory(directory, requirePrivate);
6737
+ }
6738
+ async inspectStateParent() {
6739
+ await this.inspectPrivateDirectory(this.stableBaseDir, false);
6740
+ const canonical = await fs.realpath(this.stableBaseDir);
6741
+ if (this.canonicalBaseDir !== void 0 && this.canonicalBaseDir !== canonical) {
6742
+ throw new StandaloneDeletionJournalError("compromised");
6743
+ }
6744
+ this.canonicalBaseDir = canonical;
6745
+ await this.inspectPrivateDirectory(this.stateDirectory);
7161
6746
  }
7162
6747
  async inspectJournalDirectory() {
7163
6748
  try {
6749
+ await this.inspectStateParent();
7164
6750
  return await this.inspectPrivateDirectory(this.journalDirectory);
7165
6751
  } catch (error2) {
7166
- if (isMissing2(error2)) return void 0;
6752
+ if (isMissing(error2)) return void 0;
7167
6753
  throw error2;
7168
6754
  }
7169
6755
  }
7170
- async inspectPrivateDirectory(directory) {
7171
- const stat3 = await fs2.lstat(directory);
7172
- if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && ((stat3.mode & 511) !== 448 || typeof process.getuid === "function" && stat3.uid !== process.getuid())) {
6756
+ async inspectPrivateDirectory(directory, requirePrivate = true) {
6757
+ let stat3;
6758
+ try {
6759
+ stat3 = await fs.lstat(directory);
6760
+ } catch (error2) {
6761
+ if (isMissing(error2) && this.directoryIdentities.has(directory)) {
6762
+ throw new StandaloneDeletionJournalError("compromised");
6763
+ }
6764
+ throw error2;
6765
+ }
6766
+ if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && (requirePrivate && (stat3.mode & 511) !== 448 || typeof process.getuid === "function" && stat3.uid !== process.getuid())) {
7173
6767
  throw new StandaloneDeletionJournalError("compromised");
7174
6768
  }
7175
- return {
6769
+ const identity = {
7176
6770
  device: stat3.dev,
7177
6771
  inode: normalizedInode(stat3.ino),
7178
6772
  inodeVerifiable: hasVerifiableInode(stat3.ino)
7179
6773
  };
6774
+ if (directory === this.stableBaseDir || directory === this.stateDirectory || directory === this.journalDirectory) {
6775
+ const expected = this.directoryIdentities.get(directory);
6776
+ if (expected && !sameDirectoryIdentity(identity, expected)) {
6777
+ throw new StandaloneDeletionJournalError("compromised");
6778
+ }
6779
+ this.directoryIdentities.set(directory, identity);
6780
+ }
6781
+ return identity;
7180
6782
  }
7181
6783
  async assertDirectoryIdentity(directory, expected) {
6784
+ await this.inspectStateParent();
7182
6785
  const current = await this.inspectPrivateDirectory(directory);
7183
6786
  if (!sameDirectoryIdentity(current, expected)) {
7184
6787
  throw new StandaloneDeletionJournalError("compromised");
@@ -7191,35 +6794,35 @@ var StandaloneDeletionJournal = class {
7191
6794
  }
7192
6795
  async assertPathAbsent(filePath) {
7193
6796
  try {
7194
- await fs2.lstat(filePath);
6797
+ await fs.lstat(filePath);
7195
6798
  } catch (error2) {
7196
- if (isMissing2(error2)) return;
6799
+ if (isMissing(error2)) return;
7197
6800
  throw error2;
7198
6801
  }
7199
6802
  throw new StandaloneDeletionJournalError("conflict");
7200
6803
  }
7201
6804
  async pathExists(filePath) {
7202
6805
  try {
7203
- await fs2.lstat(filePath);
6806
+ await fs.lstat(filePath);
7204
6807
  return true;
7205
6808
  } catch (error2) {
7206
- if (isMissing2(error2)) return false;
6809
+ if (isMissing(error2)) return false;
7207
6810
  throw error2;
7208
6811
  }
7209
6812
  }
7210
6813
  async unlinkIfExists(filePath) {
7211
6814
  try {
7212
- await fs2.unlink(filePath);
6815
+ await fs.unlink(filePath);
7213
6816
  } catch (error2) {
7214
- if (!isMissing2(error2)) throw error2;
6817
+ if (!isMissing(error2)) throw error2;
7215
6818
  }
7216
6819
  }
7217
6820
  async openDurableDirectory(directory, expected) {
7218
6821
  let handle;
7219
6822
  try {
7220
- handle = await fs2.open(
6823
+ handle = await fs.open(
7221
6824
  directory,
7222
- fsConstants3.O_RDONLY | (process.platform === "win32" ? 0 : fsConstants3.O_NOFOLLOW ?? 0)
6825
+ fsConstants2.O_RDONLY | (process.platform === "win32" ? 0 : fsConstants2.O_NOFOLLOW ?? 0)
7223
6826
  );
7224
6827
  const opened = await handle.stat();
7225
6828
  const openedIdentity = {
@@ -7376,6 +6979,7 @@ function mergeLiveStandaloneSummary(persisted, live) {
7376
6979
  updatedAt: laterTimestamp(live.updatedAt, persisted.updatedAt),
7377
6980
  clientCount: live.clientCount,
7378
6981
  hasActivePrompt: live.hasActivePrompt,
6982
+ ...live.activeWorkState !== void 0 ? { activeWorkState: live.activeWorkState } : {},
7379
6983
  ...live.isWaitingForPermission !== void 0 ? { isWaitingForPermission: live.isWaitingForPermission } : {},
7380
6984
  ...live.isWaitingForUserQuestion !== void 0 ? { isWaitingForUserQuestion: live.isWaitingForUserQuestion } : {},
7381
6985
  ...live.pendingInteractionCount !== void 0 ? { pendingInteractionCount: live.pendingInteractionCount } : {},
@@ -7587,7 +7191,7 @@ var StandaloneSessionService = class {
7587
7191
  });
7588
7192
  }
7589
7193
  async repairDirectory(rawSessionId) {
7590
- const clientId = randomUUID5();
7194
+ const clientId = randomUUID4();
7591
7195
  const restored = await this.restore("resume", rawSessionId, { clientId });
7592
7196
  try {
7593
7197
  await this.cleanupDisconnectedRestore(restored);
@@ -9059,7 +8663,7 @@ var StandaloneSessionService = class {
9059
8663
  }
9060
8664
  return { ...created, initialPrompt: created.initialPrompt };
9061
8665
  }
9062
- async createInternal(request2, prompt, parentSessionId, promptId = randomUUID5()) {
8666
+ async createInternal(request2, prompt, parentSessionId, promptId = randomUUID4()) {
9063
8667
  const { sessionId } = parseRequiredSessionId(request2.sessionId);
9064
8668
  let entry;
9065
8669
  try {
@@ -9602,8 +9206,8 @@ var StandaloneSessionService = class {
9602
9206
 
9603
9207
  // packages/cli/src/serve/workspace-memory.ts
9604
9208
  init_esbuild_shims();
9605
- import { promises as fs3 } from "node:fs";
9606
- import * as path9 from "node:path";
9209
+ import { promises as fs2 } from "node:fs";
9210
+ import * as path8 from "node:path";
9607
9211
  function requireTrustedWorkspace2(deps, res) {
9608
9212
  if (deps.isWorkspaceTrusted?.() !== false) return true;
9609
9213
  res.status(403).json({
@@ -9926,9 +9530,9 @@ async function collectWorkspaceMemoryStatus(boundWorkspace) {
9926
9530
  files.push(...workspaceFiles);
9927
9531
  const globalDir = Storage.getGlobalQwenDir();
9928
9532
  for (const filename of filenames) {
9929
- const candidate = path9.join(globalDir, filename);
9533
+ const candidate = path8.join(globalDir, filename);
9930
9534
  try {
9931
- const stat3 = await fs3.stat(candidate);
9535
+ const stat3 = await fs2.stat(candidate);
9932
9536
  if (stat3.isFile()) {
9933
9537
  files.push({
9934
9538
  absolutePath: candidate,
@@ -9975,9 +9579,9 @@ __name(collectWorkspaceMemoryStatus, "collectWorkspaceMemoryStatus");
9975
9579
  async function walkWorkspaceForMemory(start, filenames, errors) {
9976
9580
  const out = [];
9977
9581
  for (const filename of filenames) {
9978
- const candidate = path9.join(start, filename);
9582
+ const candidate = path8.join(start, filename);
9979
9583
  try {
9980
- const stat3 = await fs3.stat(candidate);
9584
+ const stat3 = await fs2.stat(candidate);
9981
9585
  if (stat3.isFile()) {
9982
9586
  out.push({
9983
9587
  absolutePath: candidate,
@@ -10007,7 +9611,7 @@ __name(isEnoent, "isEnoent");
10007
9611
 
10008
9612
  // packages/cli/src/serve/workspace-agents.ts
10009
9613
  init_esbuild_shims();
10010
- import { promises as fs4 } from "node:fs";
9614
+ import { promises as fs3 } from "node:fs";
10011
9615
  import { isDeepStrictEqual } from "node:util";
10012
9616
  var AGENT_TYPE_PATTERN = /^[\p{L}\p{N}_-]+$/u;
10013
9617
  var AGENT_TYPE_MAX_LENGTH = 64;
@@ -10460,7 +10064,7 @@ function mountWorkspaceAgentsRoutes(app, deps) {
10460
10064
  continue;
10461
10065
  }
10462
10066
  try {
10463
- await fs4.access(found.filePath);
10067
+ await fs3.access(found.filePath);
10464
10068
  remaining.push(found);
10465
10069
  } catch {
10466
10070
  removed.push(found);
@@ -10809,7 +10413,7 @@ function mountWorkspaceQualifiedAgentsRoutes(app, deps) {
10809
10413
  }
10810
10414
  if (existing?.filePath) {
10811
10415
  try {
10812
- await fs4.access(existing.filePath);
10416
+ await fs3.access(existing.filePath);
10813
10417
  writeStderrLine(
10814
10418
  `qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} partial \u2014 remaining=${existing.level}:${existing.filePath}`
10815
10419
  );
@@ -13384,6 +12988,7 @@ var AcpDispatcher = class {
13384
12988
  ...s.sourceId !== void 0 ? { sourceId: s.sourceId } : {},
13385
12989
  clientCount: s.clientCount,
13386
12990
  hasActivePrompt: s.hasActivePrompt,
12991
+ ...s.activeWorkState !== void 0 ? { activeWorkState: s.activeWorkState } : {},
13387
12992
  isArchived: s.isArchived === true,
13388
12993
  ...s.isPinned !== void 0 ? { isPinned: s.isPinned } : {},
13389
12994
  ...s.pinnedAt !== void 0 ? { pinnedAt: s.pinnedAt } : {},
@@ -15705,6 +15310,7 @@ var AcpDispatcher = class {
15705
15310
  bridge: this.bridge,
15706
15311
  coordinator: this.archiveCoordinator,
15707
15312
  assertCanMutate: assertGenerationOpen,
15313
+ runtimeWorkspaceCwd: this.boundWorkspace,
15708
15314
  onError: /* @__PURE__ */ __name(({ phase, sessionId, error: error2 }) => {
15709
15315
  const safeSessionId = logSafe(sessionId.slice(0, 8));
15710
15316
  const safeMessage = logSafe(error2);
@@ -16383,7 +15989,7 @@ var AcpDispatcher = class {
16383
15989
 
16384
15990
  // packages/cli/src/serve/acp-http/connection-registry.ts
16385
15991
  init_esbuild_shims();
16386
- import { randomUUID as randomUUID6 } from "node:crypto";
15992
+ import { randomUUID as randomUUID5 } from "node:crypto";
16387
15993
  var DEFAULT_MAX_CONNECTIONS = 64;
16388
15994
  var AcpConnection = class {
16389
15995
  constructor(connectionId, fromLoopback, onAbandonPending, onDetachSession, preAttachBudget = new AcpPreAttachBudget(), onFatalConnection, maxFramesPerConnection = ACP_PRE_ATTACH_MAX_FRAMES_PER_CONNECTION, maxPayloadBytesPerConnection = ACP_PRE_ATTACH_MAX_PAYLOAD_BYTES_PER_CONNECTION, onPreAttachGuardFailure) {
@@ -16394,8 +16000,8 @@ var AcpConnection = class {
16394
16000
  this.maxFramesPerConnection = maxFramesPerConnection;
16395
16001
  this.maxPayloadBytesPerConnection = maxPayloadBytesPerConnection;
16396
16002
  this.onPreAttachGuardFailure = onPreAttachGuardFailure;
16397
- this.connectionId = connectionId ?? randomUUID6();
16398
- this.clientId = randomUUID6();
16003
+ this.connectionId = connectionId ?? randomUUID5();
16004
+ this.clientId = randomUUID5();
16399
16005
  this.fromLoopback = fromLoopback;
16400
16006
  }
16401
16007
  static {
@@ -18446,6 +18052,23 @@ var CdpBrowserEmulator = class {
18446
18052
  });
18447
18053
  case "Target.getDevToolsTarget":
18448
18054
  return this.cb.reply({ id, result: {} });
18055
+ // Target mutations the tunnel cannot perform: behind it is ONE tab the
18056
+ // user already has open, so there is nothing to create, close, or
18057
+ // isolate. These must not fall through to the empty ack below — a CDP
18058
+ // client reads `targetId` out of the createTarget result and then waits
18059
+ // for a target that never appears, so a fake success turns "open a new
18060
+ // page" into a protocol timeout instead of an immediate refusal.
18061
+ case "Target.createTarget":
18062
+ case "Target.closeTarget":
18063
+ case "Target.createBrowserContext":
18064
+ case "Target.disposeBrowserContext":
18065
+ return this.cb.reply({
18066
+ id,
18067
+ error: {
18068
+ code: SERVER_ERROR,
18069
+ message: `${method} is not supported by the CDP tunnel: it drives a single existing tab`
18070
+ }
18071
+ });
18449
18072
  case "Target.attachToTarget": {
18450
18073
  const targetId = params?.["targetId"];
18451
18074
  if (targetId !== PAGE_TARGET_ID) {
@@ -18805,10 +18428,10 @@ function isAcpChannelUnavailable(err) {
18805
18428
  return err?.data?.errorKind === "acp_channel_unavailable";
18806
18429
  }
18807
18430
  __name(isAcpChannelUnavailable, "isAcpChannelUnavailable");
18808
- function delay2(ms) {
18431
+ function delay(ms) {
18809
18432
  return new Promise((resolve7) => setTimeout(resolve7, ms));
18810
18433
  }
18811
- __name(delay2, "delay");
18434
+ __name(delay, "delay");
18812
18435
  function buildChromeDevToolsMcpRuntimeConfig(localPort, hostname, env) {
18813
18436
  if (localPort === void 0 || !Number.isInteger(localPort) || localPort <= 0) {
18814
18437
  return void 0;
@@ -19069,7 +18692,7 @@ function mountAcpHttp(app, bridge, opts) {
19069
18692
  if (!isAcpChannelUnavailable(err) || attempt >= RUNTIME_MCP_RETRY_ATTEMPTS || !opts.cdpTunnelRegistry?.hasActive()) {
19070
18693
  throw err;
19071
18694
  }
19072
- await delay2(RUNTIME_MCP_RETRY_DELAY_MS);
18695
+ await delay(RUNTIME_MCP_RETRY_DELAY_MS);
19073
18696
  }
19074
18697
  }
19075
18698
  if (result.skipped) {
@@ -22062,9 +21685,9 @@ __name(registerWorkspaceAuthRoutes, "registerWorkspaceAuthRoutes");
22062
21685
  // packages/cli/src/serve/routes/workspace-extensions.ts
22063
21686
  init_esbuild_shims();
22064
21687
  import * as crypto2 from "node:crypto";
22065
- import * as fs5 from "node:fs/promises";
21688
+ import * as fs4 from "node:fs/promises";
22066
21689
  import * as os from "node:os";
22067
- import * as path10 from "node:path";
21690
+ import * as path9 from "node:path";
22068
21691
  var import_express2 = __toESM(require_express(), 1);
22069
21692
 
22070
21693
  // packages/cli/src/serve/extension-operation-scheduler.ts
@@ -22432,14 +22055,18 @@ function createExtensionsController(deps) {
22432
22055
  async (release) => {
22433
22056
  assertGenerationOpen?.();
22434
22057
  return await task((generation) => {
22435
- reconciliationReservation ??= options.reserveRuntimeReconciliation?.();
22058
+ if (!options.skipRefresh) {
22059
+ reconciliationReservation ??= options.reserveRuntimeReconciliation?.();
22060
+ }
22436
22061
  committedGeneration = generation;
22437
22062
  release();
22438
22063
  });
22439
22064
  }
22440
22065
  );
22441
22066
  if (committedGeneration === void 0) {
22442
- reconciliationReservation ??= options.reserveRuntimeReconciliation?.();
22067
+ if (!options.skipRefresh) {
22068
+ reconciliationReservation ??= options.reserveRuntimeReconciliation?.();
22069
+ }
22443
22070
  committedGeneration = result.generation;
22444
22071
  }
22445
22072
  for (const warning of result.warnings ?? []) {
@@ -22847,7 +22474,7 @@ var extensionArchiveBodyParser = import_express2.default.raw({
22847
22474
  });
22848
22475
  var assertDaemonExtensionInstallSource = /* @__PURE__ */ __name((installMetadata, source, ref, autoUpdate) => {
22849
22476
  if (installMetadata.type === "local") {
22850
- if (!path10.isAbsolute(source)) {
22477
+ if (!path9.isAbsolute(source)) {
22851
22478
  throw new Error(
22852
22479
  "Local extension sources must be absolute daemon-host paths; relative paths are not supported over the daemon endpoint."
22853
22480
  );
@@ -23303,11 +22930,6 @@ function registerWorkspaceExtensionRoutes(app, deps) {
23303
22930
  reserveRuntimeReconciliation,
23304
22931
  onRuntimeReconciled
23305
22932
  } : {}, "globalReconciliationOptions");
23306
- const workspaceReconciliationOptions = /* @__PURE__ */ __name(() => workspaceRegistry ? {
23307
- refreshRuntimes: [workspaceRegistry.primary],
23308
- reserveRuntimeReconciliation,
23309
- onRuntimeReconciled
23310
- } : {}, "workspaceReconciliationOptions");
23311
22933
  const mutationClientBridges = /* @__PURE__ */ __name((runtimes) => (typeof runtimes === "function" ? runtimes() : runtimes ?? workspaceRegistry?.listAll())?.map((runtime) => runtime.bridge) ?? [bridge], "mutationClientBridges");
23312
22934
  if (workspaceRegistry) {
23313
22935
  let observedGeneration;
@@ -23559,14 +23181,14 @@ function registerWorkspaceExtensionRoutes(app, deps) {
23559
23181
  let result;
23560
23182
  let failure;
23561
23183
  try {
23562
- uploadDir = await fs5.mkdtemp(
23563
- path10.join(os.tmpdir(), "qwen-extension-upload-")
23184
+ uploadDir = await fs4.mkdtemp(
23185
+ path9.join(os.tmpdir(), "qwen-extension-upload-")
23564
23186
  );
23565
- const archivePath = path10.join(
23187
+ const archivePath = path9.join(
23566
23188
  uploadDir,
23567
23189
  `extension${archiveName.suffix}`
23568
23190
  );
23569
- await fs5.writeFile(archivePath, archive);
23191
+ await fs4.writeFile(archivePath, archive);
23570
23192
  archive = void 0;
23571
23193
  const prepared = await context.prepare(async (signal) => {
23572
23194
  supersedeActiveInstallOperations(ctrl, operationId);
@@ -23599,7 +23221,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
23599
23221
  }
23600
23222
  if (uploadDir) {
23601
23223
  try {
23602
- await fs5.rm(uploadDir, { recursive: true, force: true });
23224
+ await fs4.rm(uploadDir, { recursive: true, force: true });
23603
23225
  } catch (error2) {
23604
23226
  failure ??= sanitizeUploadError(error2);
23605
23227
  }
@@ -23963,7 +23585,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
23963
23585
  return { status: "enabled", name: extension.name };
23964
23586
  },
23965
23587
  {
23966
- ...scope === "User" /* User */ ? globalReconciliationOptions() : workspaceReconciliationOptions()
23588
+ skipRefresh: true
23967
23589
  }
23968
23590
  );
23969
23591
  } catch (err) {
@@ -24010,7 +23632,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
24010
23632
  return { status: "disabled", name: extension.name };
24011
23633
  },
24012
23634
  {
24013
- ...scope === "User" /* User */ ? globalReconciliationOptions() : workspaceReconciliationOptions()
23635
+ skipRefresh: true
24014
23636
  }
24015
23637
  );
24016
23638
  } catch (err) {
@@ -24299,6 +23921,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
24299
23921
  };
24300
23922
  },
24301
23923
  {
23924
+ skipRefresh: true,
24302
23925
  ...workspaceRegistry ? { refreshRuntimes: /* @__PURE__ */ __name(() => workspaceRegistry.listAll(), "refreshRuntimes") } : {}
24303
23926
  }
24304
23927
  );
@@ -24339,6 +23962,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
24339
23962
  };
24340
23963
  },
24341
23964
  {
23965
+ skipRefresh: true,
24342
23966
  ...workspaceRegistry ? { refreshRuntimes: /* @__PURE__ */ __name(() => workspaceRegistry.listAll(), "refreshRuntimes") } : {}
24343
23967
  }
24344
23968
  );
@@ -24859,6 +24483,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
24859
24483
  };
24860
24484
  },
24861
24485
  {
24486
+ skipRefresh: true,
24862
24487
  refreshRuntimes: [runtime],
24863
24488
  assertGenerationOpen: /* @__PURE__ */ __name(() => runtime.generationGuard?.assertOpen(), "assertGenerationOpen")
24864
24489
  }
@@ -24905,6 +24530,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
24905
24530
  };
24906
24531
  },
24907
24532
  {
24533
+ skipRefresh: true,
24908
24534
  refreshRuntimes: [runtime],
24909
24535
  assertGenerationOpen: /* @__PURE__ */ __name(() => runtime.generationGuard?.assertOpen(), "assertGenerationOpen")
24910
24536
  }
@@ -24950,6 +24576,7 @@ function registerWorkspaceExtensionRoutes(app, deps) {
24950
24576
  return { status: activation.effective, name: extension.name };
24951
24577
  },
24952
24578
  {
24579
+ skipRefresh: true,
24953
24580
  refreshRuntimes: [runtime],
24954
24581
  assertGenerationOpen: /* @__PURE__ */ __name(() => runtime.generationGuard?.assertOpen(), "assertGenerationOpen")
24955
24582
  }
@@ -24988,7 +24615,7 @@ __name(registerWorkspaceExtensionRoutes, "registerWorkspaceExtensionRoutes");
24988
24615
  // packages/cli/src/serve/routes/workspace-file-write.ts
24989
24616
  init_esbuild_shims();
24990
24617
  var import_express3 = __toESM(require_express(), 1);
24991
- import * as path11 from "node:path";
24618
+ import * as path10 from "node:path";
24992
24619
  function getFsFactory3(req, res) {
24993
24620
  const context = getWorkspaceRouteContext(req);
24994
24621
  if (context) return context.runtime.routeFileSystemFactory;
@@ -25421,8 +25048,8 @@ function fileUploadAdmission(deps, opts) {
25421
25048
  sendParseError(res, ROUTE2, "`path` query parameter is required");
25422
25049
  return;
25423
25050
  }
25424
- const dir = path11.dirname(queryPath);
25425
- const basename9 = path11.basename(queryPath);
25051
+ const dir = path10.dirname(queryPath);
25052
+ const basename9 = path10.basename(queryPath);
25426
25053
  if (queryPath.endsWith("/") || basename9.length === 0 || basename9 === "." || basename9 === "..") {
25427
25054
  sendParseError(res, ROUTE2, "`path` must name a file");
25428
25055
  return;
@@ -25543,11 +25170,11 @@ async function handlePostFileUpload(req, res) {
25543
25170
  );
25544
25171
  return;
25545
25172
  }
25546
- const candidateAbs = path11.join(resolvedDir, candidateBasename);
25173
+ const candidateAbs = path10.join(resolvedDir, candidateBasename);
25547
25174
  let resolved;
25548
25175
  try {
25549
25176
  resolved = await fs10.resolve(
25550
- path11.join(queryDir, candidateBasename),
25177
+ path10.join(queryDir, candidateBasename),
25551
25178
  "write"
25552
25179
  );
25553
25180
  } catch (err) {
@@ -25902,6 +25529,12 @@ var legacySessionTelemetryRoutes = [
25902
25529
  attribution: "handler_resolved",
25903
25530
  route: "POST /session/:id/resume"
25904
25531
  },
25532
+ {
25533
+ method: "POST",
25534
+ path: "/session/:id/worktree-reset",
25535
+ attribution: "handler_resolved",
25536
+ route: "POST /session/:id/worktree-reset"
25537
+ },
25905
25538
  {
25906
25539
  method: "POST",
25907
25540
  path: "/session/:id/branch",
@@ -26877,11 +26510,92 @@ __name(registerPermissionRoutes, "registerPermissionRoutes");
26877
26510
  // packages/cli/src/serve/routes/session.ts
26878
26511
  init_esbuild_shims();
26879
26512
  import * as crypto3 from "node:crypto";
26880
- import * as fs7 from "node:fs";
26881
- import * as path12 from "node:path";
26513
+ import * as fs6 from "node:fs";
26514
+ import * as path11 from "node:path";
26882
26515
  import { inspect } from "node:util";
26883
26516
  var import_express4 = __toESM(require_express(), 1);
26884
26517
 
26518
+ // packages/cli/src/serve/server/worktree-reset-errors.ts
26519
+ init_esbuild_shims();
26520
+ var WorktreeSessionSupersededError = class extends Error {
26521
+ static {
26522
+ __name(this, "WorktreeSessionSupersededError");
26523
+ }
26524
+ sessionId;
26525
+ replacementSessionId;
26526
+ constructor(sessionId, replacementSessionId) {
26527
+ super(
26528
+ `Session ${sessionId} was superseded by a worktree reset; restore the replacement session instead`
26529
+ );
26530
+ this.name = "WorktreeSessionSupersededError";
26531
+ this.sessionId = sessionId;
26532
+ this.replacementSessionId = replacementSessionId;
26533
+ }
26534
+ };
26535
+ var WorktreeMarkerMissingError = class extends Error {
26536
+ static {
26537
+ __name(this, "WorktreeMarkerMissingError");
26538
+ }
26539
+ sessionId;
26540
+ constructor(sessionId) {
26541
+ super(
26542
+ `Worktree ownership marker for session ${sessionId} is missing; reset the task to recreate it`
26543
+ );
26544
+ this.name = "WorktreeMarkerMissingError";
26545
+ this.sessionId = sessionId;
26546
+ }
26547
+ };
26548
+ var WorktreeResetInterruptedError = class extends Error {
26549
+ static {
26550
+ __name(this, "WorktreeResetInterruptedError");
26551
+ }
26552
+ sessionId;
26553
+ constructor(sessionId) {
26554
+ super(
26555
+ "A previous worktree reset was interrupted; retry the reset against the superseded session to finish or roll it back"
26556
+ );
26557
+ this.name = "WorktreeResetInterruptedError";
26558
+ this.sessionId = sessionId;
26559
+ }
26560
+ };
26561
+ var WorktreeResetActiveError = class extends Error {
26562
+ static {
26563
+ __name(this, "WorktreeResetActiveError");
26564
+ }
26565
+ sessionId;
26566
+ constructor(sessionId) {
26567
+ super(
26568
+ `Session ${sessionId} has a prompt in progress; wait for it to finish before resetting`
26569
+ );
26570
+ this.name = "WorktreeResetActiveError";
26571
+ this.sessionId = sessionId;
26572
+ }
26573
+ };
26574
+ var WorktreeResetUnsupportedError = class extends Error {
26575
+ static {
26576
+ __name(this, "WorktreeResetUnsupportedError");
26577
+ }
26578
+ sessionId;
26579
+ constructor(sessionId) {
26580
+ super(`Session ${sessionId} is not a worktree session`);
26581
+ this.name = "WorktreeResetUnsupportedError";
26582
+ this.sessionId = sessionId;
26583
+ }
26584
+ };
26585
+ var WorktreeResetInvalidStateError = class extends Error {
26586
+ static {
26587
+ __name(this, "WorktreeResetInvalidStateError");
26588
+ }
26589
+ sessionId;
26590
+ constructor(sessionId) {
26591
+ super(
26592
+ `Session ${sessionId}'s worktree ownership state is invalid; the reset made no destructive change`
26593
+ );
26594
+ this.name = "WorktreeResetInvalidStateError";
26595
+ this.sessionId = sessionId;
26596
+ }
26597
+ };
26598
+
26885
26599
  // packages/cli/src/serve/server/prompt-deadline.ts
26886
26600
  init_esbuild_shims();
26887
26601
  function resolvePromptDeadlineMs(serverMs, requestMs) {
@@ -27006,7 +26720,7 @@ __name(deleteBranch, "deleteBranch");
27006
26720
 
27007
26721
  // packages/cli/src/serve/virtual-subagent-sessions.ts
27008
26722
  init_esbuild_shims();
27009
- import * as fs6 from "node:fs/promises";
26723
+ import * as fs5 from "node:fs/promises";
27010
26724
  import { createReadStream } from "node:fs";
27011
26725
  import readline from "node:readline";
27012
26726
  var PREFIX = "subagent.";
@@ -27216,7 +26930,7 @@ var VirtualSubagentTarget = class _VirtualSubagentTarget {
27216
26930
  async readNewRecords(endOffset) {
27217
26931
  let handle;
27218
26932
  try {
27219
- handle = await fs6.open(this.task.outputFile, "r");
26933
+ handle = await fs5.open(this.task.outputFile, "r");
27220
26934
  const stat3 = await handle.stat();
27221
26935
  const identity = `${stat3.dev}:${stat3.ino}`;
27222
26936
  if (this.transcriptIdentity !== void 0 && this.transcriptIdentity !== identity || stat3.size < this.offset) {
@@ -27260,7 +26974,7 @@ var VirtualSubagentTarget = class _VirtualSubagentTarget {
27260
26974
  const filePath = `${this.task.outputFile}.stream`;
27261
26975
  let handle;
27262
26976
  try {
27263
- handle = await fs6.open(filePath, "r");
26977
+ handle = await fs5.open(filePath, "r");
27264
26978
  const stat3 = await handle.stat();
27265
26979
  const identity = `${stat3.dev}:${stat3.ino}`;
27266
26980
  if (this.streamIdentity !== void 0 && this.streamIdentity !== identity) {
@@ -27425,7 +27139,7 @@ var VirtualSubagentTarget = class _VirtualSubagentTarget {
27425
27139
  async captureReadBounds() {
27426
27140
  const size = /* @__PURE__ */ __name(async (filePath) => {
27427
27141
  try {
27428
- return (await fs6.stat(filePath)).size;
27142
+ return (await fs5.stat(filePath)).size;
27429
27143
  } catch (error2) {
27430
27144
  if (error2.code === "ENOENT") return 0;
27431
27145
  throw error2;
@@ -27554,7 +27268,7 @@ var VirtualSubagentSessions = class {
27554
27268
  const sessionDir = getSubagentSessionDir(projectDir, parentSessionId);
27555
27269
  let names;
27556
27270
  try {
27557
- names = await fs6.readdir(sessionDir);
27271
+ names = await fs5.readdir(sessionDir);
27558
27272
  } catch (error2) {
27559
27273
  if (error2.code === "ENOENT") return void 0;
27560
27274
  throw error2;
@@ -27610,7 +27324,7 @@ var VirtualSubagentSessions = class {
27610
27324
  const sessionDir = getSubagentSessionDir(projectDir, parentSessionId);
27611
27325
  let names;
27612
27326
  try {
27613
- names = await fs6.readdir(sessionDir);
27327
+ names = await fs5.readdir(sessionDir);
27614
27328
  } catch (error2) {
27615
27329
  if (error2.code === "ENOENT") return void 0;
27616
27330
  throw error2;
@@ -28135,34 +27849,6 @@ function registerSessionRoutes(app, deps) {
28135
27849
  const LANGUAGE_CODES = deps.languageCodes;
28136
27850
  const transcriptCursorMasterKey = crypto3.randomBytes(32);
28137
27851
  const transcriptCursorCodecs = /* @__PURE__ */ new Map();
28138
- const worktreeRestoreTails = /* @__PURE__ */ new WeakMap();
28139
- const acquireWorktreeRestore = /* @__PURE__ */ __name(async (bridge, sessionId) => {
28140
- let tails = worktreeRestoreTails.get(bridge);
28141
- if (!tails) {
28142
- tails = /* @__PURE__ */ new Map();
28143
- worktreeRestoreTails.set(bridge, tails);
28144
- }
28145
- const key = normalizeSessionIdForLookup(sessionId);
28146
- const previous = tails.get(key);
28147
- let releaseGate;
28148
- const gate = new Promise((resolve7) => {
28149
- releaseGate = resolve7;
28150
- });
28151
- const tail = (previous ?? Promise.resolve()).then(() => gate);
28152
- tails.set(key, tail);
28153
- if (previous) {
28154
- await previous;
28155
- }
28156
- let released = false;
28157
- return () => {
28158
- if (released) return;
28159
- released = true;
28160
- releaseGate();
28161
- if (tails.get(key) === tail) {
28162
- tails.delete(key);
28163
- }
28164
- };
28165
- }, "acquireWorktreeRestore");
28166
27852
  const activeBranchSessions = /* @__PURE__ */ new Map();
28167
27853
  const inFlightBranchWorkspaces = /* @__PURE__ */ new Set();
28168
27854
  const clearBranchSessionEntry = /* @__PURE__ */ __name((sessionId) => {
@@ -28271,28 +27957,28 @@ function registerSessionRoutes(app, deps) {
28271
27957
  const cwd = parseOptionalWorkspaceCwd(body, boundWorkspace, res);
28272
27958
  if (cwd === void 0) return void 0;
28273
27959
  const isWithinConversationRoot = /* @__PURE__ */ __name((root, candidate) => {
28274
- const relative5 = path12.relative(root, candidate);
28275
- return relative5 === "" || relative5 !== ".." && !relative5.startsWith(`..${path12.sep}`) && !path12.isAbsolute(relative5);
27960
+ const relative5 = path11.relative(root, candidate);
27961
+ return relative5 === "" || relative5 !== ".." && !relative5.startsWith(`..${path11.sep}`) && !path11.isAbsolute(relative5);
28276
27962
  }, "isWithinConversationRoot");
28277
27963
  const canonicalizeIfPresent = /* @__PURE__ */ __name((candidate) => {
28278
- const resolved = path12.resolve(candidate);
27964
+ const resolved = path11.resolve(candidate);
28279
27965
  try {
28280
- return fs7.realpathSync.native(resolved);
27966
+ return fs6.realpathSync.native(resolved);
28281
27967
  } catch {
28282
27968
  return resolved;
28283
27969
  }
28284
27970
  }, "canonicalizeIfPresent");
28285
27971
  const canonicalizeExistingAncestor = /* @__PURE__ */ __name((candidate) => {
28286
- let ancestor = path12.resolve(candidate);
27972
+ let ancestor = path11.resolve(candidate);
28287
27973
  const missingTail = [];
28288
27974
  while (true) {
28289
27975
  try {
28290
- return path12.join(fs7.realpathSync.native(ancestor), ...missingTail);
27976
+ return path11.join(fs6.realpathSync.native(ancestor), ...missingTail);
28291
27977
  } catch (error2) {
28292
27978
  if (error2.code !== "ENOENT") throw error2;
28293
- const parent = path12.dirname(ancestor);
27979
+ const parent = path11.dirname(ancestor);
28294
27980
  if (parent === ancestor) throw error2;
28295
- missingTail.unshift(path12.basename(ancestor));
27981
+ missingTail.unshift(path11.basename(ancestor));
28296
27982
  ancestor = parent;
28297
27983
  }
28298
27984
  }
@@ -28305,8 +27991,8 @@ function registerSessionRoutes(app, deps) {
28305
27991
  return void 0;
28306
27992
  }, "rejectReservedConversationRoot");
28307
27993
  if ("cwd" in body && deps.liveConversationRootPath && isWithinConversationRoot(
28308
- path12.resolve(deps.liveConversationRootPath),
28309
- path12.resolve(cwd)
27994
+ path11.resolve(deps.liveConversationRootPath),
27995
+ path11.resolve(cwd)
28310
27996
  )) {
28311
27997
  return rejectReservedConversationRoot();
28312
27998
  }
@@ -28329,7 +28015,7 @@ function registerSessionRoutes(app, deps) {
28329
28015
  const liveRoots = [
28330
28016
  ...workspaceRegistry.listAllEntries().filter((entry2) => entry2.internal).map((entry2) => entry2.workspaceCwd),
28331
28017
  ...deps.liveConversationRootPath ? [
28332
- path12.resolve(deps.liveConversationRootPath),
28018
+ path11.resolve(deps.liveConversationRootPath),
28333
28019
  canonicalizeIfPresent(deps.liveConversationRootPath)
28334
28020
  ] : []
28335
28021
  ];
@@ -28379,7 +28065,7 @@ function registerSessionRoutes(app, deps) {
28379
28065
  const workspaceParam = req.params[paramName] ?? "";
28380
28066
  const byId = workspaceRegistry.getByWorkspaceId(workspaceParam);
28381
28067
  if (byId) return byId;
28382
- if (!path12.isAbsolute(workspaceParam)) {
28068
+ if (!path11.isAbsolute(workspaceParam)) {
28383
28069
  res.status(400).json({
28384
28070
  error: `\`:${paramName}\` must decode to a workspace id or absolute path`
28385
28071
  });
@@ -28432,11 +28118,11 @@ function registerSessionRoutes(app, deps) {
28432
28118
  }
28433
28119
  const selector = req.params[paramName] ?? "";
28434
28120
  let entry = workspaceRegistry.getManagedEntryByWorkspaceId(selector);
28435
- if (!entry && path12.isAbsolute(selector)) {
28121
+ if (!entry && path11.isAbsolute(selector)) {
28436
28122
  entry = workspaceRegistry.getManagedEntryByWorkspaceCwd(selector);
28437
28123
  }
28438
- const configuredRoot = deps.liveConversationRootPath ? path12.resolve(deps.liveConversationRootPath) : void 0;
28439
- const matchesConfiguredRoot = configuredRoot !== void 0 && selector === configuredRoot && path12.resolve(selector) === selector;
28124
+ const configuredRoot = deps.liveConversationRootPath ? path11.resolve(deps.liveConversationRootPath) : void 0;
28125
+ const matchesConfiguredRoot = configuredRoot !== void 0 && selector === configuredRoot && path11.resolve(selector) === selector;
28440
28126
  if ((!entry || !entry.internal) && !matchesConfiguredRoot) {
28441
28127
  return void 0;
28442
28128
  }
@@ -28465,7 +28151,7 @@ function registerSessionRoutes(app, deps) {
28465
28151
  }, "resolveLiveCatalogRuntime");
28466
28152
  const resolveQualifiedSessionTarget = /* @__PURE__ */ __name((req, res, options = {}) => {
28467
28153
  const selector = req.params["workspace"] ?? "";
28468
- const entry = workspaceRegistry.getManagedEntryByWorkspaceId(selector) ?? (path12.isAbsolute(selector) ? workspaceRegistry.getManagedEntryByWorkspaceCwd(selector) : void 0);
28154
+ const entry = workspaceRegistry.getManagedEntryByWorkspaceId(selector) ?? (path11.isAbsolute(selector) ? workspaceRegistry.getManagedEntryByWorkspaceCwd(selector) : void 0);
28469
28155
  if (entry?.internal) return { kind: "internal", entry };
28470
28156
  const runtime = resolveWorkspaceRuntimeFromParam(
28471
28157
  workspaceRegistry,
@@ -28742,8 +28428,8 @@ function registerSessionRoutes(app, deps) {
28742
28428
  const resolveRuntimeForSessionRestore = /* @__PURE__ */ __name(async (body, res, route, sessionId) => {
28743
28429
  const cwd = parseOptionalWorkspaceCwd(body, boundWorkspace, res);
28744
28430
  if (cwd === void 0) return void 0;
28745
- const configuredRoot = deps.liveConversationRootPath ? path12.resolve(deps.liveConversationRootPath) : void 0;
28746
- const bootstrappedRuntime = "cwd" in body && configuredRoot !== void 0 && path12.isAbsolute(cwd) && path12.resolve(cwd) === configuredRoot && deps.ensureConversationRuntime ? await deps.ensureConversationRuntime() : void 0;
28431
+ const configuredRoot = deps.liveConversationRootPath ? path11.resolve(deps.liveConversationRootPath) : void 0;
28432
+ const bootstrappedRuntime = "cwd" in body && configuredRoot !== void 0 && path11.isAbsolute(cwd) && path11.resolve(cwd) === configuredRoot && deps.ensureConversationRuntime ? await deps.ensureConversationRuntime() : void 0;
28747
28433
  let key;
28748
28434
  try {
28749
28435
  key = canonicalizeWorkspace(cwd);
@@ -29452,6 +29138,7 @@ function registerSessionRoutes(app, deps) {
29452
29138
  coordinator: archiveCoordinator,
29453
29139
  coordinatorLockHeld,
29454
29140
  assertCanMutate,
29141
+ runtimeWorkspaceCwd: runtime.workspaceCwd,
29455
29142
  onError: /* @__PURE__ */ __name(({ phase, sessionId, error: error2 }) => {
29456
29143
  writeStderrLine(
29457
29144
  `qwen serve: ${phase}Session failed for ${safeLogValue(sessionId)}: ${safeLogValue(error2)}`
@@ -29902,7 +29589,7 @@ function registerSessionRoutes(app, deps) {
29902
29589
  } catch (error2) {
29903
29590
  if (!session.attached) {
29904
29591
  try {
29905
- const removed = await runWithWorkspaceRuntimeStorage(
29592
+ await runWithWorkspaceRuntimeStorage(
29906
29593
  runtime,
29907
29594
  () => deleteDaemonSessionIfOrphan({
29908
29595
  sessionId: session.sessionId,
@@ -29911,18 +29598,25 @@ function registerSessionRoutes(app, deps) {
29911
29598
  coordinator: archiveCoordinator
29912
29599
  })
29913
29600
  );
29914
- if (removed) {
29915
- if (worktreeMeta) {
29916
- await new GitWorktreeService(workspaceCwd).removeUserWorktree(worktreeMeta.slug, { deleteBranch: true }).catch(() => {
29917
- });
29918
- }
29919
- }
29920
29601
  } catch {
29921
29602
  }
29922
29603
  } else {
29923
29604
  await runtime.bridge.detachClient(session.sessionId, session.clientId).catch(() => {
29924
29605
  });
29925
29606
  }
29607
+ if (worktreeMeta) {
29608
+ const rollbackSlug = worktreeMeta.slug;
29609
+ await new GitWorktreeService(workspaceCwd).removeUserWorktree(rollbackSlug, { deleteBranch: true }).catch((removalError) => {
29610
+ daemonLog?.warn(
29611
+ "worktree removal failed during generation-closed rollback",
29612
+ {
29613
+ sessionId: session.sessionId,
29614
+ slug: rollbackSlug,
29615
+ error: removalError instanceof Error ? removalError.message : String(removalError)
29616
+ }
29617
+ );
29618
+ });
29619
+ }
29926
29620
  throw error2;
29927
29621
  }
29928
29622
  if (daemonLog) {
@@ -29987,7 +29681,7 @@ function registerSessionRoutes(app, deps) {
29987
29681
  if (worktreeMeta) {
29988
29682
  try {
29989
29683
  const createAllowedRoots = [
29990
- path12.join(workspaceCwd, ".qwen", "worktrees")
29684
+ path11.join(workspaceCwd, ".qwen", "worktrees")
29991
29685
  ];
29992
29686
  let createRepoTop = null;
29993
29687
  try {
@@ -29998,10 +29692,10 @@ function registerSessionRoutes(app, deps) {
29998
29692
  }
29999
29693
  if (createRepoTop && createRepoTop !== workspaceCwd) {
30000
29694
  createAllowedRoots.push(
30001
- path12.join(createRepoTop, ".qwen", "worktrees")
29695
+ path11.join(createRepoTop, ".qwen", "worktrees")
30002
29696
  );
30003
29697
  }
30004
- const expectedWorktreePath = fs7.realpathSync(worktreeMeta.path);
29698
+ const expectedWorktreePath = fs6.realpathSync(worktreeMeta.path);
30005
29699
  const changed = await runtime.bridge.changeSessionCwd(
30006
29700
  session.sessionId,
30007
29701
  {
@@ -30351,21 +30045,42 @@ function registerSessionRoutes(app, deps) {
30351
30045
  };
30352
30046
  const isChannelRestore = restoreRequestMetadata.sourceType === "channel";
30353
30047
  let isPart4AWorktreeRestore = false;
30354
- if (isChannelRestore && runtime.provenance !== "live-conversation") {
30048
+ let part4AWorktreeKey;
30049
+ if (runtime.provenance !== "live-conversation") {
30355
30050
  const sidecarBeforeRestore = await readWorktreeSessionStrict(
30356
30051
  sessionService.getWorktreeSessionPath(restoredStorageSessionId)
30357
30052
  );
30053
+ if (isChannelRestore) {
30054
+ suppressWorktreeContextRestore = !(sidecarBeforeRestore.state === "valid" && sidecarBeforeRestore.session.workspaceCwd === void 0);
30055
+ }
30358
30056
  isPart4AWorktreeRestore = sidecarBeforeRestore.state === "valid" && sidecarBeforeRestore.session.workspaceCwd !== void 0;
30359
- suppressWorktreeContextRestore = !(sidecarBeforeRestore.state === "valid" && sidecarBeforeRestore.session.workspaceCwd === void 0);
30057
+ if (isPart4AWorktreeRestore && sidecarBeforeRestore.state === "valid") {
30058
+ const recordedPath = sidecarBeforeRestore.session.worktreePath;
30059
+ try {
30060
+ part4AWorktreeKey = fs6.realpathSync(recordedPath);
30061
+ } catch {
30062
+ part4AWorktreeKey = recordedPath;
30063
+ }
30064
+ }
30360
30065
  } else {
30361
30066
  suppressWorktreeContextRestore = isChannelRestore;
30362
30067
  }
30363
30068
  deferRestoreAskUserQuestionPrompt = suppressWorktreeContextRestore && runtime.bridge.fireDeferredRestoreAskUserQuestionPrompt !== void 0 && runtime.bridge.discardDeferredRestoreAskUserQuestionPrompt !== void 0;
30364
- if (deferRestoreAskUserQuestionPrompt && isPart4AWorktreeRestore) {
30365
- releaseWorktreeRestore = await acquireWorktreeRestore(
30366
- runtime.bridge,
30367
- sessionId
30368
- );
30069
+ if (isPart4AWorktreeRestore && part4AWorktreeKey !== void 0) {
30070
+ releaseWorktreeRestore = await acquireWorktreeOwnershipOp(part4AWorktreeKey);
30071
+ if (isChannelRestore) {
30072
+ const sidecarUnderLock = await readWorktreeSessionStrict(
30073
+ sessionService.getWorktreeSessionPath(
30074
+ restoredStorageSessionId
30075
+ )
30076
+ );
30077
+ if (sidecarUnderLock.state === "valid" && sidecarUnderLock.session.supersededBy !== void 0) {
30078
+ throw new WorktreeSessionSupersededError(
30079
+ restoredStorageSessionId,
30080
+ sidecarUnderLock.session.supersededBy
30081
+ );
30082
+ }
30083
+ }
30369
30084
  }
30370
30085
  assertRuntimeGenerationOpen?.();
30371
30086
  if (isInternalWorkspaceRuntime(runtime)) {
@@ -30512,7 +30227,7 @@ function registerSessionRoutes(app, deps) {
30512
30227
  let candidateRoots = [];
30513
30228
  let validationError;
30514
30229
  try {
30515
- const workspaceRoots = [fs7.realpathSync(workspaceCwd)];
30230
+ const workspaceRoots = [fs6.realpathSync(workspaceCwd)];
30516
30231
  let repoTop = null;
30517
30232
  try {
30518
30233
  repoTop = await new GitWorktreeService(
@@ -30521,24 +30236,24 @@ function registerSessionRoutes(app, deps) {
30521
30236
  } catch {
30522
30237
  }
30523
30238
  if (repoTop) {
30524
- const realRepoTop = fs7.realpathSync(repoTop);
30239
+ const realRepoTop = fs6.realpathSync(repoTop);
30525
30240
  if (!workspaceRoots.includes(realRepoTop)) {
30526
30241
  workspaceRoots.push(realRepoTop);
30527
30242
  }
30528
30243
  }
30529
- const realOriginalCwd = fs7.realpathSync(sidecar.originalCwd);
30244
+ const realOriginalCwd = fs6.realpathSync(sidecar.originalCwd);
30530
30245
  if (!workspaceRoots.includes(realOriginalCwd)) {
30531
30246
  throw new Error("legacy sidecar belongs to another workspace");
30532
30247
  }
30533
30248
  candidateRoots = workspaceRoots.map(
30534
- (root) => path12.join(root, ".qwen", "worktrees")
30249
+ (root) => path11.join(root, ".qwen", "worktrees")
30535
30250
  );
30536
- realTarget = fs7.realpathSync(sidecar.worktreePath);
30251
+ realTarget = fs6.realpathSync(sidecar.worktreePath);
30537
30252
  const contained = candidateRoots.some((root) => {
30538
30253
  try {
30539
- const realRoot = fs7.realpathSync(root);
30540
- const relative5 = path12.relative(realRoot, realTarget);
30541
- return relative5.length > 0 && !relative5.startsWith("..") && !path12.isAbsolute(relative5);
30254
+ const realRoot = fs6.realpathSync(root);
30255
+ const relative5 = path11.relative(realRoot, realTarget);
30256
+ return relative5.length > 0 && !relative5.startsWith("..") && !path11.isAbsolute(relative5);
30542
30257
  } catch {
30543
30258
  return false;
30544
30259
  }
@@ -30585,11 +30300,17 @@ function registerSessionRoutes(app, deps) {
30585
30300
  throw new Error("Worktree sidecar is missing or invalid");
30586
30301
  }
30587
30302
  const sidecar = sidecarResult.session;
30588
- const realWorkspace = fs7.realpathSync(workspaceCwd);
30303
+ if (sidecar.supersededBy !== void 0) {
30304
+ throw new WorktreeSessionSupersededError(
30305
+ restoredStorageSessionId,
30306
+ sidecar.supersededBy
30307
+ );
30308
+ }
30309
+ const realWorkspace = fs6.realpathSync(workspaceCwd);
30589
30310
  if (sidecar.workspaceCwd !== void 0) {
30590
30311
  let realSidecarWorkspace;
30591
30312
  try {
30592
- realSidecarWorkspace = fs7.realpathSync(sidecar.workspaceCwd);
30313
+ realSidecarWorkspace = fs6.realpathSync(sidecar.workspaceCwd);
30593
30314
  } catch {
30594
30315
  throw new Error(
30595
30316
  "Worktree sidecar workspace is missing or inaccessible"
@@ -30610,11 +30331,11 @@ function registerSessionRoutes(app, deps) {
30610
30331
  } catch {
30611
30332
  }
30612
30333
  if (repoTop && repoTop !== realWorkspace) {
30613
- workspaceRoots.push(fs7.realpathSync(repoTop));
30334
+ workspaceRoots.push(fs6.realpathSync(repoTop));
30614
30335
  }
30615
30336
  let realOriginalCwd;
30616
30337
  try {
30617
- realOriginalCwd = fs7.realpathSync(sidecar.originalCwd);
30338
+ realOriginalCwd = fs6.realpathSync(sidecar.originalCwd);
30618
30339
  } catch {
30619
30340
  throw new Error(
30620
30341
  "Worktree sidecar workspace is missing or inaccessible"
@@ -30626,19 +30347,19 @@ function registerSessionRoutes(app, deps) {
30626
30347
  );
30627
30348
  }
30628
30349
  const candidateRoots = workspaceRoots.map(
30629
- (root) => path12.join(root, ".qwen", "worktrees")
30350
+ (root) => path11.join(root, ".qwen", "worktrees")
30630
30351
  );
30631
30352
  let realTarget;
30632
30353
  try {
30633
- realTarget = fs7.realpathSync(sidecar.worktreePath);
30354
+ realTarget = fs6.realpathSync(sidecar.worktreePath);
30634
30355
  } catch {
30635
30356
  throw new Error("Worktree checkout is missing or inaccessible");
30636
30357
  }
30637
30358
  const contained = candidateRoots.some((root) => {
30638
30359
  try {
30639
- const realRoot = fs7.realpathSync(root);
30640
- const relative5 = path12.relative(realRoot, realTarget);
30641
- return relative5.length > 0 && !relative5.startsWith("..") && !path12.isAbsolute(relative5);
30360
+ const realRoot = fs6.realpathSync(root);
30361
+ const relative5 = path11.relative(realRoot, realTarget);
30362
+ return relative5.length > 0 && !relative5.startsWith("..") && !path11.isAbsolute(relative5);
30642
30363
  } catch {
30643
30364
  return false;
30644
30365
  }
@@ -30648,6 +30369,30 @@ function registerSessionRoutes(app, deps) {
30648
30369
  }
30649
30370
  const marker = await readWorktreeSessionMarkerStrict(realTarget);
30650
30371
  if (marker.state !== "valid" || marker.sessionId !== restoredStorageSessionId) {
30372
+ if (sidecar.supersedes !== void 0 && (marker.state === "missing" || marker.state === "valid" && marker.sessionId === sidecar.supersedes)) {
30373
+ const oldSidecar = await readWorktreeSessionStrict(
30374
+ createWorkspaceRuntimeSessionService(
30375
+ runtime
30376
+ ).getWorktreeSessionPath(sidecar.supersedes)
30377
+ );
30378
+ if (oldSidecar.state === "valid" && oldSidecar.session.supersededBy === restoredStorageSessionId) {
30379
+ daemonLog?.warn(
30380
+ "worktree restore found an interrupted reset",
30381
+ {
30382
+ sessionId: restoredStorageSessionId,
30383
+ supersedesSessionId: sidecar.supersedes
30384
+ }
30385
+ );
30386
+ throw new WorktreeResetInterruptedError(
30387
+ restoredStorageSessionId
30388
+ );
30389
+ }
30390
+ }
30391
+ if (marker.state === "missing") {
30392
+ throw new WorktreeMarkerMissingError(
30393
+ restoredStorageSessionId
30394
+ );
30395
+ }
30651
30396
  throw new Error("Worktree marker ownership is invalid");
30652
30397
  }
30653
30398
  const worktree = {
@@ -30655,28 +30400,28 @@ function registerSessionRoutes(app, deps) {
30655
30400
  path: realTarget,
30656
30401
  branch: sidecar.worktreeBranch
30657
30402
  };
30658
- const hasUnlocatedRestoredPrompt = session.hasActivePrompt && !session.attached && session.currentCwd === void 0;
30403
+ const hasUnlocatedRestoredPrompt = session.hasActivePrompt && !session.attached && session.currentCwd === void 0 && !deferRestoreAskUserQuestionPrompt;
30659
30404
  if (hasUnlocatedRestoredPrompt) {
30660
30405
  runtime.bridge.setSessionWorktree(sessionId, worktree);
30661
30406
  session.worktree = worktree;
30662
- } else if (session.hasActivePrompt) {
30663
- if (session.currentCwd !== realTarget) {
30664
- throw new Error("Active session is outside its worktree");
30665
- }
30666
30407
  } else {
30667
- const changed = await runtime.bridge.changeSessionCwd(
30668
- sessionId,
30669
- {
30670
- path: realTarget,
30671
- allowedRoots: candidateRoots
30408
+ if (session.hasActivePrompt) {
30409
+ if (session.currentCwd !== realTarget) {
30410
+ throw new Error("Active session is outside its worktree");
30672
30411
  }
30673
- );
30674
- if (changed.newCwd !== realTarget) {
30675
- throw new Error("Worktree relocation was rejected");
30412
+ } else {
30413
+ const changed = await runtime.bridge.changeSessionCwd(
30414
+ sessionId,
30415
+ {
30416
+ path: realTarget,
30417
+ allowedRoots: candidateRoots
30418
+ }
30419
+ );
30420
+ if (changed.newCwd !== realTarget) {
30421
+ throw new Error("Worktree relocation was rejected");
30422
+ }
30423
+ session.currentCwd = changed.newCwd;
30676
30424
  }
30677
- session.currentCwd = changed.newCwd;
30678
- }
30679
- if (!hasUnlocatedRestoredPrompt) {
30680
30425
  runtime.bridge.setSessionWorktree(sessionId, worktree);
30681
30426
  assertRuntimeGenerationOpen?.();
30682
30427
  session.worktree = worktree;
@@ -30751,6 +30496,448 @@ function registerSessionRoutes(app, deps) {
30751
30496
  }, "restoreSessionHandler");
30752
30497
  app.post("/session/:id/load", mutate(), restoreSessionHandler("load"));
30753
30498
  app.post("/session/:id/resume", mutate(), restoreSessionHandler("resume"));
30499
+ const resolveWorktreeOwnershipTarget = /* @__PURE__ */ __name(async (runtime, workspaceCwd, sidecar, sessionId) => {
30500
+ const invalidState = /* @__PURE__ */ __name((reason) => {
30501
+ daemonLog?.warn("worktree reset rejected sidecar state", {
30502
+ sessionId,
30503
+ reason
30504
+ });
30505
+ return new WorktreeResetInvalidStateError(sessionId);
30506
+ }, "invalidState");
30507
+ const realWorkspace = fs6.realpathSync(workspaceCwd);
30508
+ if (sidecar.workspaceCwd !== void 0) {
30509
+ let realSidecarWorkspace;
30510
+ try {
30511
+ realSidecarWorkspace = fs6.realpathSync(sidecar.workspaceCwd);
30512
+ } catch {
30513
+ throw invalidState("sidecar workspace is missing or inaccessible");
30514
+ }
30515
+ if (realSidecarWorkspace !== realWorkspace) {
30516
+ throw invalidState("sidecar belongs to another workspace");
30517
+ }
30518
+ }
30519
+ const workspaceRoots = [realWorkspace];
30520
+ let repoTop = null;
30521
+ try {
30522
+ repoTop = await new GitWorktreeService(realWorkspace).getRepoTopLevel();
30523
+ } catch {
30524
+ }
30525
+ if (repoTop && repoTop !== realWorkspace) {
30526
+ workspaceRoots.push(fs6.realpathSync(repoTop));
30527
+ }
30528
+ let realOriginalCwd;
30529
+ try {
30530
+ realOriginalCwd = fs6.realpathSync(sidecar.originalCwd);
30531
+ } catch {
30532
+ throw invalidState("sidecar original cwd is missing or inaccessible");
30533
+ }
30534
+ if (!workspaceRoots.includes(realOriginalCwd)) {
30535
+ throw invalidState("sidecar original cwd is outside the accepted roots");
30536
+ }
30537
+ const candidateRoots = workspaceRoots.map(
30538
+ (root) => path11.join(root, ".qwen", "worktrees")
30539
+ );
30540
+ let realTarget;
30541
+ try {
30542
+ realTarget = fs6.realpathSync(sidecar.worktreePath);
30543
+ } catch {
30544
+ throw invalidState("worktree checkout is missing or inaccessible");
30545
+ }
30546
+ const contained = candidateRoots.some((root) => {
30547
+ try {
30548
+ const realRoot = fs6.realpathSync(root);
30549
+ const relative5 = path11.relative(realRoot, realTarget);
30550
+ return relative5.length > 0 && !relative5.startsWith("..") && !path11.isAbsolute(relative5);
30551
+ } catch {
30552
+ return false;
30553
+ }
30554
+ });
30555
+ if (!contained) {
30556
+ throw invalidState("worktree path failed containment");
30557
+ }
30558
+ return { realTarget, candidateRoots };
30559
+ }, "resolveWorktreeOwnershipTarget");
30560
+ const worktreeResetHandler = /* @__PURE__ */ __name(async (req, res) => {
30561
+ const route = "POST /session/:id/worktree-reset";
30562
+ const sessionId = requireSessionId(req, res);
30563
+ if (!sessionId) return;
30564
+ if (parseVirtualSubagentSessionId(sessionId)) {
30565
+ res.status(400).json({
30566
+ error: "Virtual subagent sessions do not support worktree reset",
30567
+ code: "unsupported_action",
30568
+ sessionId
30569
+ });
30570
+ return;
30571
+ }
30572
+ const body = safeBody(req);
30573
+ let resolvedRuntime;
30574
+ try {
30575
+ resolvedRuntime = await resolveRuntimeForSessionRestore(
30576
+ body,
30577
+ res,
30578
+ route,
30579
+ sessionId
30580
+ );
30581
+ } catch (err) {
30582
+ if (sendConversationRuntimeError(res, err)) return;
30583
+ sendBridgeError2(res, err, { route, sessionId });
30584
+ return;
30585
+ }
30586
+ if (resolvedRuntime === void 0) return;
30587
+ const { runtime, workspaceCwd } = resolvedRuntime;
30588
+ const approvalMode = parseOptionalApprovalMode(body, res);
30589
+ if (approvalMode === null) return;
30590
+ const source = parseRequestedSessionSource(body, res);
30591
+ if (source === null) return;
30592
+ const modelServiceId = typeof body["modelServiceId"] === "string" ? body["modelServiceId"] : void 0;
30593
+ const assertRuntimeGenerationOpen = captureRuntimeGenerationAssertion(runtime);
30594
+ try {
30595
+ await runOwnerRuntimeActivity(
30596
+ runtime,
30597
+ () => archiveCoordinator.runSharedMany([sessionId], async () => {
30598
+ const sessionService = createWorkspaceRuntimeSessionService(runtime);
30599
+ const storageSessionId = await resolveSessionIdForRestore(
30600
+ sessionService,
30601
+ sessionId
30602
+ );
30603
+ if (storageSessionId === void 0) {
30604
+ throw new SessionNotFoundError(sessionId);
30605
+ }
30606
+ const oldSidecarPath = sessionService.getWorktreeSessionPath(storageSessionId);
30607
+ if (runtime.bridge.setSessionResetPending === void 0 || runtime.bridge.clearSessionResetPending === void 0 || runtime.bridge.clearSessionWorktree === void 0 || runtime.bridge.severSessionClients === void 0) {
30608
+ throw new Error("Bridge does not support worktree reset");
30609
+ }
30610
+ const preRead = await readWorktreeSessionStrict(oldSidecarPath);
30611
+ if (preRead.state === "missing" || preRead.state === "valid" && preRead.session.workspaceCwd === void 0) {
30612
+ throw new WorktreeResetUnsupportedError(sessionId);
30613
+ }
30614
+ if (preRead.state !== "valid") {
30615
+ daemonLog?.warn("worktree reset rejected invalid sidecar", {
30616
+ sessionId,
30617
+ reason: preRead.reason
30618
+ });
30619
+ throw new WorktreeResetInvalidStateError(sessionId);
30620
+ }
30621
+ const preTarget = await resolveWorktreeOwnershipTarget(
30622
+ runtime,
30623
+ workspaceCwd,
30624
+ preRead.session,
30625
+ sessionId
30626
+ );
30627
+ const releaseOwnership = await acquireWorktreeOwnershipOp(
30628
+ preTarget.realTarget
30629
+ );
30630
+ try {
30631
+ const lockedRead = await readWorktreeSessionStrict(oldSidecarPath);
30632
+ if (lockedRead.state === "missing" || lockedRead.state === "valid" && lockedRead.session.workspaceCwd === void 0) {
30633
+ throw new WorktreeResetUnsupportedError(sessionId);
30634
+ }
30635
+ if (lockedRead.state !== "valid") {
30636
+ daemonLog?.warn("worktree reset rejected invalid sidecar", {
30637
+ sessionId,
30638
+ reason: lockedRead.reason
30639
+ });
30640
+ throw new WorktreeResetInvalidStateError(sessionId);
30641
+ }
30642
+ const oldSidecar = lockedRead.session;
30643
+ const { realTarget, candidateRoots } = await resolveWorktreeOwnershipTarget(
30644
+ runtime,
30645
+ workspaceCwd,
30646
+ oldSidecar,
30647
+ sessionId
30648
+ );
30649
+ if (realTarget !== preTarget.realTarget) {
30650
+ daemonLog?.warn("worktree reset rejected: sidecar moved", {
30651
+ sessionId
30652
+ });
30653
+ throw new WorktreeResetInvalidStateError(sessionId);
30654
+ }
30655
+ const readSummary = /* @__PURE__ */ __name((id) => {
30656
+ try {
30657
+ return runtime.bridge.getSessionSummary(id);
30658
+ } catch (error2) {
30659
+ if (error2 instanceof SessionNotFoundError) return void 0;
30660
+ throw error2;
30661
+ }
30662
+ }, "readSummary");
30663
+ runtime.bridge.setSessionResetPending(sessionId);
30664
+ let barrierArmed = true;
30665
+ try {
30666
+ let effectiveOldSidecar = oldSidecar;
30667
+ if (oldSidecar.supersededBy !== void 0) {
30668
+ const replacementId = oldSidecar.supersededBy;
30669
+ const newSidecarPath = sessionService.getWorktreeSessionPath(replacementId);
30670
+ const newRead = await readWorktreeSessionStrict(newSidecarPath);
30671
+ const linksAgree = newRead.state === "valid" && newRead.session.supersedes === storageSessionId;
30672
+ const marker = await readWorktreeSessionMarkerStrict(realTarget);
30673
+ if (marker.state === "invalid") {
30674
+ daemonLog?.warn("worktree reset resume rejected marker", {
30675
+ sessionId,
30676
+ reason: marker.reason
30677
+ });
30678
+ throw new WorktreeResetInvalidStateError(sessionId);
30679
+ }
30680
+ if (marker.state === "missing" || marker.state === "valid" && marker.sessionId === storageSessionId) {
30681
+ if (!linksAgree) {
30682
+ daemonLog?.warn(
30683
+ "worktree reset resume found inconsistent links",
30684
+ { sessionId, replacementSessionId: replacementId }
30685
+ );
30686
+ throw new WorktreeResetInvalidStateError(sessionId);
30687
+ }
30688
+ if (marker.state === "missing" && readSummary(replacementId) !== void 0) {
30689
+ daemonLog?.warn(
30690
+ "worktree reset resume found a live replacement with no marker",
30691
+ { sessionId, replacementSessionId: replacementId }
30692
+ );
30693
+ throw new WorktreeResetInvalidStateError(sessionId);
30694
+ }
30695
+ const { supersededBy: _drop, ...restoredOld } = oldSidecar;
30696
+ const removed = await runWithWorkspaceRuntimeStorage(
30697
+ runtime,
30698
+ () => deleteDaemonSessionIfOrphan({
30699
+ sessionId: replacementId,
30700
+ service: sessionService,
30701
+ bridge: runtime.bridge,
30702
+ coordinator: archiveCoordinator
30703
+ })
30704
+ ).catch(() => false);
30705
+ if (!removed) {
30706
+ daemonLog?.warn(
30707
+ "worktree reset could not remove the interrupted replacement",
30708
+ { sessionId, replacementSessionId: replacementId }
30709
+ );
30710
+ throw new WorktreeResetInvalidStateError(sessionId);
30711
+ }
30712
+ await clearWorktreeSession(newSidecarPath);
30713
+ await writeWorktreeSession(oldSidecarPath, restoredOld);
30714
+ daemonLog?.warn(
30715
+ "worktree reset rolled back an interrupted transfer",
30716
+ { sessionId, replacementSessionId: replacementId }
30717
+ );
30718
+ effectiveOldSidecar = restoredOld;
30719
+ } else if (marker.state === "valid" && marker.sessionId === replacementId) {
30720
+ barrierArmed = false;
30721
+ if (!linksAgree) {
30722
+ daemonLog?.warn(
30723
+ "worktree reset resume found inconsistent links",
30724
+ { sessionId, replacementSessionId: replacementId }
30725
+ );
30726
+ throw new WorktreeResetInvalidStateError(sessionId);
30727
+ }
30728
+ const newSummary = readSummary(replacementId);
30729
+ if (newSummary && (newSummary.hasActivePrompt || (newSummary.pendingInteractionCount ?? 0) > 0)) {
30730
+ throw new WorktreeResetActiveError(replacementId);
30731
+ }
30732
+ runtime.bridge.clearSessionWorktree(sessionId);
30733
+ const severCompleted = await runtime.bridge.severSessionClients(sessionId);
30734
+ if (severCompleted) {
30735
+ runtime.bridge.clearSessionResetPending(sessionId);
30736
+ } else {
30737
+ daemonLog?.warn(
30738
+ "worktree reset left the superseded session live",
30739
+ { sessionId, replacementSessionId: replacementId }
30740
+ );
30741
+ }
30742
+ assertRuntimeGenerationOpen?.();
30743
+ daemonLog?.info(
30744
+ "worktree session reset resumed after interruption",
30745
+ { sessionId, replacementSessionId: replacementId }
30746
+ );
30747
+ res.status(200).json({
30748
+ sessionId: replacementId,
30749
+ workspaceCwd,
30750
+ currentCwd: realTarget,
30751
+ worktree: {
30752
+ slug: oldSidecar.slug,
30753
+ path: realTarget,
30754
+ branch: oldSidecar.worktreeBranch
30755
+ },
30756
+ worktreeState: "persisted-v1",
30757
+ attached: false,
30758
+ ...severCompleted ? {} : { supersededSessionLive: true }
30759
+ });
30760
+ return;
30761
+ } else {
30762
+ daemonLog?.warn(
30763
+ "worktree reset resume found a marker naming another session",
30764
+ { sessionId }
30765
+ );
30766
+ throw new WorktreeResetInvalidStateError(sessionId);
30767
+ }
30768
+ }
30769
+ const oldSummary = readSummary(sessionId);
30770
+ if (oldSummary && (oldSummary.hasActivePrompt || (oldSummary.pendingInteractionCount ?? 0) > 0)) {
30771
+ throw new WorktreeResetActiveError(sessionId);
30772
+ }
30773
+ let spawnedNew;
30774
+ let newSidecarWritten = false;
30775
+ let oldSupersededWritten = false;
30776
+ let markerTransferred = false;
30777
+ try {
30778
+ assertRuntimeGenerationOpen?.();
30779
+ const spawned = await runtime.bridge.spawnOrAttach({
30780
+ workspaceCwd,
30781
+ modelServiceId,
30782
+ sessionScope: "thread",
30783
+ ...approvalMode !== void 0 ? { approvalMode } : {},
30784
+ ...source.sourceType !== void 0 ? { sourceType: source.sourceType } : {},
30785
+ ...source.sourceId !== void 0 ? { sourceId: source.sourceId } : {}
30786
+ });
30787
+ spawnedNew = { sessionId: spawned.sessionId };
30788
+ const changed = await runtime.bridge.changeSessionCwd(
30789
+ spawned.sessionId,
30790
+ { path: realTarget, allowedRoots: candidateRoots }
30791
+ );
30792
+ if (changed.newCwd !== realTarget) {
30793
+ throw new Error("Worktree relocation was rejected");
30794
+ }
30795
+ await writeWorktreeSession(oldSidecarPath, {
30796
+ ...effectiveOldSidecar,
30797
+ supersededBy: spawned.sessionId
30798
+ });
30799
+ oldSupersededWritten = true;
30800
+ const newSidecarPath = sessionService.getWorktreeSessionPath(
30801
+ spawned.sessionId
30802
+ );
30803
+ const {
30804
+ supersededBy: _dropOld,
30805
+ supersedes: _dropOldLink,
30806
+ ...oldSidecarCore
30807
+ } = effectiveOldSidecar;
30808
+ await writeWorktreeSession(newSidecarPath, {
30809
+ ...oldSidecarCore,
30810
+ supersedes: storageSessionId
30811
+ });
30812
+ newSidecarWritten = true;
30813
+ if (res.destroyed || res.socket?.writable === false) {
30814
+ throw new Error(
30815
+ "Client disconnected before the worktree ownership flip"
30816
+ );
30817
+ }
30818
+ const windingDown = readSummary(sessionId);
30819
+ if (windingDown && (windingDown.hasActivePrompt || (windingDown.pendingInteractionCount ?? 0) > 0)) {
30820
+ throw new WorktreeResetActiveError(sessionId);
30821
+ }
30822
+ const markerBeforeFlip = await readWorktreeSessionMarkerStrict(realTarget);
30823
+ try {
30824
+ await transferWorktreeSessionMarkerOwner(
30825
+ realTarget,
30826
+ markerBeforeFlip.state === "missing" ? null : storageSessionId,
30827
+ spawned.sessionId
30828
+ );
30829
+ } catch (markerError) {
30830
+ daemonLog?.warn("worktree marker transfer failed", {
30831
+ sessionId,
30832
+ replacementSessionId: spawned.sessionId,
30833
+ error: markerError instanceof Error ? markerError.message : String(markerError)
30834
+ });
30835
+ if (markerError instanceof WorktreeMarkerCommittedError) {
30836
+ markerTransferred = true;
30837
+ barrierArmed = false;
30838
+ throw new Error(
30839
+ "Worktree ownership moved to the replacement, but the marker commit did not finish cleanly; retry the reset to complete the transfer"
30840
+ );
30841
+ }
30842
+ throw new WorktreeResetInvalidStateError(sessionId);
30843
+ }
30844
+ markerTransferred = true;
30845
+ barrierArmed = false;
30846
+ const newWorktree = {
30847
+ slug: effectiveOldSidecar.slug,
30848
+ path: realTarget,
30849
+ branch: effectiveOldSidecar.worktreeBranch
30850
+ };
30851
+ runtime.bridge.setSessionWorktree(
30852
+ spawned.sessionId,
30853
+ newWorktree
30854
+ );
30855
+ assertRuntimeGenerationOpen?.();
30856
+ runtime.bridge.clearSessionWorktree(sessionId);
30857
+ const severCompleted = await runtime.bridge.severSessionClients(sessionId);
30858
+ if (severCompleted) {
30859
+ runtime.bridge.clearSessionResetPending(sessionId);
30860
+ } else {
30861
+ daemonLog?.warn(
30862
+ "worktree reset left the superseded session live",
30863
+ {
30864
+ sessionId,
30865
+ replacementSessionId: spawned.sessionId
30866
+ }
30867
+ );
30868
+ }
30869
+ daemonLog?.info("worktree session reset", {
30870
+ sessionId,
30871
+ replacementSessionId: spawned.sessionId
30872
+ });
30873
+ res.status(200).json({
30874
+ ...spawned,
30875
+ currentCwd: realTarget,
30876
+ worktree: newWorktree,
30877
+ worktreeState: "persisted-v1",
30878
+ ...severCompleted ? {} : { supersededSessionLive: true }
30879
+ });
30880
+ } catch (transferError) {
30881
+ if (markerTransferred) {
30882
+ daemonLog?.warn(
30883
+ "worktree reset failed after the ownership flip",
30884
+ {
30885
+ sessionId,
30886
+ replacementSessionId: spawnedNew?.sessionId,
30887
+ error: transferError instanceof Error ? transferError.message : String(transferError)
30888
+ }
30889
+ );
30890
+ throw transferError;
30891
+ }
30892
+ if (spawnedNew) {
30893
+ const orphanSessionId = spawnedNew.sessionId;
30894
+ const removed = await runWithWorkspaceRuntimeStorage(
30895
+ runtime,
30896
+ () => deleteDaemonSessionIfOrphan({
30897
+ sessionId: orphanSessionId,
30898
+ service: sessionService,
30899
+ bridge: runtime.bridge,
30900
+ coordinator: archiveCoordinator
30901
+ })
30902
+ ).catch(() => false);
30903
+ if (!removed) {
30904
+ daemonLog?.warn(
30905
+ "worktree reset could not remove the spawned replacement",
30906
+ { sessionId, replacementSessionId: orphanSessionId }
30907
+ );
30908
+ throw transferError;
30909
+ }
30910
+ }
30911
+ if (newSidecarWritten && spawnedNew) {
30912
+ await clearWorktreeSession(
30913
+ sessionService.getWorktreeSessionPath(spawnedNew.sessionId)
30914
+ );
30915
+ }
30916
+ if (oldSupersededWritten) {
30917
+ await writeWorktreeSession(
30918
+ oldSidecarPath,
30919
+ effectiveOldSidecar
30920
+ );
30921
+ }
30922
+ throw transferError;
30923
+ }
30924
+ } finally {
30925
+ if (barrierArmed) {
30926
+ runtime.bridge.clearSessionResetPending(sessionId);
30927
+ }
30928
+ }
30929
+ } finally {
30930
+ releaseOwnership();
30931
+ }
30932
+ })
30933
+ );
30934
+ } catch (err) {
30935
+ if (!res.headersSent) {
30936
+ sendBridgeError2(res, err, { route, sessionId });
30937
+ }
30938
+ }
30939
+ }, "worktreeResetHandler");
30940
+ app.post("/session/:id/worktree-reset", mutate(), worktreeResetHandler);
30754
30941
  app.get("/session/:id/subagents/:subagentRef", async (req, res) => {
30755
30942
  const route = "GET /session/:id/subagents/:subagentRef";
30756
30943
  const sessionId = requireSessionId(req, res);
@@ -31019,7 +31206,7 @@ function registerSessionRoutes(app, deps) {
31019
31206
  async (req, res, sessionId, runtime) => {
31020
31207
  const body = safeBody(req);
31021
31208
  const targetPath = body["path"];
31022
- if (typeof targetPath !== "string" || targetPath.length === 0 || !path12.isAbsolute(targetPath)) {
31209
+ if (typeof targetPath !== "string" || targetPath.length === 0 || !path11.isAbsolute(targetPath)) {
31023
31210
  res.status(400).json({
31024
31211
  error: "`path` is required and must be an absolute path",
31025
31212
  code: "invalid_path"
@@ -33487,6 +33674,7 @@ function registerSessionRoutes(app, deps) {
33487
33674
  sessionId: session.sessionId,
33488
33675
  clientCount: session.clientCount,
33489
33676
  hasActivePrompt: session.hasActivePrompt,
33677
+ ...session.activeWorkState !== void 0 ? { activeWorkState: session.activeWorkState } : {},
33490
33678
  isWaitingForPermission: session.isWaitingForPermission ?? false,
33491
33679
  isWaitingForUserQuestion: session.isWaitingForUserQuestion ?? false,
33492
33680
  // Bridge-local activity watermark, absent until a running prompt in
@@ -34084,8 +34272,8 @@ __name(registerSessionRoutes, "registerSessionRoutes");
34084
34272
  // packages/cli/src/serve/routes/session-pr-backfill.ts
34085
34273
  init_esbuild_shims();
34086
34274
  import { existsSync } from "node:fs";
34087
- import * as fs8 from "node:fs/promises";
34088
- import * as path13 from "node:path";
34275
+ import * as fs7 from "node:fs/promises";
34276
+ import * as path12 from "node:path";
34089
34277
  var SLUG_PR_PATTERN = /^pr-([1-9]\d{0,8})$/;
34090
34278
  var BRANCH_PR_PATTERN = /^worktree-pr-([1-9]\d{0,8})$/;
34091
34279
  function parsePrNumberFromWorktree(slug, branch) {
@@ -34174,7 +34362,7 @@ async function backfillWorkspaceSessionPrs(runtime, fetchPullRequests = fetchGit
34174
34362
  for (const sessionId of sessionIds) {
34175
34363
  if (!isValidSessionId(sessionId)) continue;
34176
34364
  result.scanned += 1;
34177
- const dir = path13.dirname(
34365
+ const dir = path12.dirname(
34178
34366
  sessionService.getWorktreeSessionPathForArchiveState(
34179
34367
  sessionId,
34180
34368
  archiveState
@@ -34183,15 +34371,15 @@ async function backfillWorkspaceSessionPrs(runtime, fetchPullRequests = fetchGit
34183
34371
  let worktree;
34184
34372
  try {
34185
34373
  worktree = await readWorktreeSession(
34186
- path13.join(dir, `${sessionId}.worktree.json`)
34374
+ path12.join(dir, `${sessionId}.worktree.json`)
34187
34375
  );
34188
34376
  } catch {
34189
34377
  worktree = null;
34190
34378
  }
34191
34379
  let transcriptRaw;
34192
34380
  try {
34193
- transcriptRaw = await fs8.readFile(
34194
- path13.join(dir, `${sessionId}.jsonl`),
34381
+ transcriptRaw = await fs7.readFile(
34382
+ path12.join(dir, `${sessionId}.jsonl`),
34195
34383
  "utf8"
34196
34384
  );
34197
34385
  } catch {
@@ -34211,7 +34399,7 @@ async function backfillWorkspaceSessionPrs(runtime, fetchPullRequests = fetchGit
34211
34399
  candidates.push({
34212
34400
  sessionId,
34213
34401
  archiveState,
34214
- transcriptPath: path13.join(dir, `${sessionId}.jsonl`),
34402
+ transcriptPath: path12.join(dir, `${sessionId}.jsonl`),
34215
34403
  conventionNumber,
34216
34404
  mentions: reviewed.mentions,
34217
34405
  reviewedUrlForms: reviewed.reviewedUrlForms
@@ -34343,8 +34531,8 @@ async function backfillWorkspaceSessionPrs(runtime, fetchPullRequests = fetchGit
34343
34531
  candidate.sessionId,
34344
34532
  archiveState
34345
34533
  );
34346
- const transcriptPath = path13.join(
34347
- path13.dirname(prPath),
34534
+ const transcriptPath = path12.join(
34535
+ path12.dirname(prPath),
34348
34536
  `${candidate.sessionId}.jsonl`
34349
34537
  );
34350
34538
  const snapshotAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -34987,7 +35175,7 @@ __name(registerStandaloneSessionRoutes, "registerStandaloneSessionRoutes");
34987
35175
 
34988
35176
  // packages/cli/src/serve/routes/channel-notify.ts
34989
35177
  init_esbuild_shims();
34990
- import { randomUUID as randomUUID10 } from "node:crypto";
35178
+ import { randomUUID as randomUUID9 } from "node:crypto";
34991
35179
  function sendDeliveryError(res, error2) {
34992
35180
  if (!isChannelDeliveryError(error2)) {
34993
35181
  res.status(502).json({
@@ -35008,7 +35196,7 @@ function parseNotifyBody(body) {
35008
35196
  );
35009
35197
  }
35010
35198
  return normalizeChannelDelivery(
35011
- randomUUID10(),
35199
+ randomUUID9(),
35012
35200
  parseChannelDelivery(body["delivery"]),
35013
35201
  body["text"]
35014
35202
  );
@@ -35211,7 +35399,7 @@ __name(registerUsageStatsRoutes, "registerUsageStatsRoutes");
35211
35399
  // packages/cli/src/serve/scheduled-task-keepalive.ts
35212
35400
  init_esbuild_shims();
35213
35401
  import * as fsSync from "node:fs";
35214
- import * as path14 from "node:path";
35402
+ import * as path13 from "node:path";
35215
35403
  var log = createDebugLogger("SCHED_KEEPALIVE");
35216
35404
  function collectBoundSessionIds(tasks) {
35217
35405
  const seen = /* @__PURE__ */ new Set();
@@ -35443,8 +35631,8 @@ function startScheduledTaskKeepalive(opts) {
35443
35631
  opts.runtimeBaseDir,
35444
35632
  () => getCronFilePath(boundWorkspace)
35445
35633
  );
35446
- const cronDir = path14.dirname(cronFilePath);
35447
- const cronFileName = path14.basename(cronFilePath);
35634
+ const cronDir = path13.dirname(cronFilePath);
35635
+ const cronFileName = path13.basename(cronFilePath);
35448
35636
  let fileWatcher;
35449
35637
  try {
35450
35638
  fsSync.mkdirSync(cronDir, { recursive: true });
@@ -36167,6 +36355,10 @@ function workflowsEnabledForRuntime(runtime, daemonEnv) {
36167
36355
  }
36168
36356
  __name(workflowsEnabledForRuntime, "workflowsEnabledForRuntime");
36169
36357
  function registerCapabilitiesRoutes(app, deps) {
36358
+ const configuredPollIntervalMs = Number(
36359
+ deps.daemonEnv["QWEN_SESSION_LIVE_STATE_POLL_INTERVAL_MS"]
36360
+ );
36361
+ const sessionLiveStatePollIntervalMs = Number.isSafeInteger(configuredPollIntervalMs) && configuredPollIntervalMs >= 1e3 && configuredPollIntervalMs <= 2147483647 ? configuredPollIntervalMs : 5e3;
36170
36362
  app.get("/capabilities", (_req, res) => {
36171
36363
  const entries = deps.workspaceRegistry.listAllEntries().filter(
36172
36364
  (entry) => !entry.internal || entry.state === "active" && entry.current !== void 0
@@ -36183,6 +36375,7 @@ function registerCapabilitiesRoutes(app, deps) {
36183
36375
  ...deps.qwenCodeVersion ? { qwenCodeVersion: deps.qwenCodeVersion } : {},
36184
36376
  mode: deps.mode,
36185
36377
  features,
36378
+ sessionLiveStatePollIntervalMs,
36186
36379
  modelServices: [],
36187
36380
  // Surface the primary workspace so clients can omit `cwd` on
36188
36381
  // `POST /session`; multi-workspace clients use `workspaces[]`.
@@ -37243,7 +37436,7 @@ __name(registerUserLanguageRoutes, "registerUserLanguageRoutes");
37243
37436
 
37244
37437
  // packages/cli/src/serve/routes/sse-events.ts
37245
37438
  init_esbuild_shims();
37246
- import { randomUUID as randomUUID11 } from "node:crypto";
37439
+ import { randomUUID as randomUUID10 } from "node:crypto";
37247
37440
  import { performance as performance3 } from "node:perf_hooks";
37248
37441
 
37249
37442
  // packages/cli/src/serve/server/error-response.ts
@@ -37624,6 +37817,63 @@ function sendBridgeError(res, err, ctx, daemonLog) {
37624
37817
  });
37625
37818
  return;
37626
37819
  }
37820
+ if (err instanceof SessionResetPendingError) {
37821
+ res.status(409).json({
37822
+ error: err.message,
37823
+ code: "worktree_reset_active",
37824
+ sessionId: err.sessionId
37825
+ });
37826
+ return;
37827
+ }
37828
+ if (err instanceof WorktreeSessionSupersededError) {
37829
+ res.status(409).json({
37830
+ error: err.message,
37831
+ code: "worktree_session_superseded",
37832
+ sessionId: err.sessionId,
37833
+ replacementSessionId: err.replacementSessionId
37834
+ });
37835
+ return;
37836
+ }
37837
+ if (err instanceof WorktreeMarkerMissingError) {
37838
+ res.status(409).json({
37839
+ error: err.message,
37840
+ code: "worktree_marker_missing",
37841
+ sessionId: err.sessionId
37842
+ });
37843
+ return;
37844
+ }
37845
+ if (err instanceof WorktreeResetInterruptedError) {
37846
+ res.status(409).json({
37847
+ error: err.message,
37848
+ code: "worktree_reset_interrupted",
37849
+ sessionId: err.sessionId
37850
+ });
37851
+ return;
37852
+ }
37853
+ if (err instanceof WorktreeResetActiveError) {
37854
+ res.status(409).json({
37855
+ error: err.message,
37856
+ code: "worktree_reset_active",
37857
+ sessionId: err.sessionId
37858
+ });
37859
+ return;
37860
+ }
37861
+ if (err instanceof WorktreeResetUnsupportedError) {
37862
+ res.status(409).json({
37863
+ error: err.message,
37864
+ code: "worktree_reset_unsupported",
37865
+ sessionId: err.sessionId
37866
+ });
37867
+ return;
37868
+ }
37869
+ if (err instanceof WorktreeResetInvalidStateError) {
37870
+ res.status(409).json({
37871
+ error: err.message,
37872
+ code: "worktree_reset_invalid_state",
37873
+ sessionId: err.sessionId
37874
+ });
37875
+ return;
37876
+ }
37627
37877
  if (err instanceof TrustGateError) {
37628
37878
  res.status(403).json({
37629
37879
  error: err.message,
@@ -38089,7 +38339,7 @@ function registerSseEventsRoutes(app, deps) {
38089
38339
  app.get("/session/:id/events", async (req, res) => {
38090
38340
  const sessionId = req.params["id"];
38091
38341
  const diagnosticSessionId = boundedDiagnosticString(sessionId);
38092
- const streamId = randomUUID11();
38342
+ const streamId = randomUUID10();
38093
38343
  const clientId = parseSseClientId(req.headers["x-qwen-client-id"]);
38094
38344
  const connectReason = parseSseConnectReason(req.query["connectReason"]);
38095
38345
  const previousStreamId = parsePreviousSseStreamId(
@@ -38981,7 +39231,7 @@ __name(registerWorkspaceModelsRoutes, "registerWorkspaceModelsRoutes");
38981
39231
  // packages/cli/src/serve/routes/a2ui-action.ts
38982
39232
  init_esbuild_shims();
38983
39233
  import * as fsp4 from "node:fs/promises";
38984
- import * as path15 from "node:path";
39234
+ import * as path14 from "node:path";
38985
39235
  var A2UI_MIME = "application/a2ui+json";
38986
39236
  var ACTION_TOOL = "action";
38987
39237
  var CALL_TIMEOUT_MS = 15e3;
@@ -39004,7 +39254,7 @@ __name(usableServerConfig, "usableServerConfig");
39004
39254
  async function findFromSettingsFile(workspaceCwd) {
39005
39255
  try {
39006
39256
  const raw = await fsp4.readFile(
39007
- path15.join(workspaceCwd, ".qwen", "settings.json"),
39257
+ path14.join(workspaceCwd, ".qwen", "settings.json"),
39008
39258
  "utf8"
39009
39259
  );
39010
39260
  const settings = JSON.parse(raw);
@@ -39165,7 +39415,7 @@ __name(registerA2uiActionRoutes, "registerA2uiActionRoutes");
39165
39415
 
39166
39416
  // packages/cli/src/serve/server/fs-factory.ts
39167
39417
  init_esbuild_shims();
39168
- import * as path16 from "node:path";
39418
+ import * as path15 from "node:path";
39169
39419
  var IDE_WORKSPACE_PATH_ENV_VAR = "QWEN_CODE_IDE_WORKSPACE_PATH";
39170
39420
  var NEW_FILE_MODE_ENV_VAR = "QWEN_SERVE_NEW_FILE_MODE";
39171
39421
  function parseNewFileModePolicy(env = process.env) {
@@ -39254,14 +39504,14 @@ function parseIdeWorkspacePathEnv(value) {
39254
39504
  const parsed = JSON.parse(value);
39255
39505
  if (Array.isArray(parsed) && parsed.every((item) => typeof item === "string")) {
39256
39506
  return parsed.filter(
39257
- (workspace) => workspace.length > 0 && path16.isAbsolute(workspace)
39507
+ (workspace) => workspace.length > 0 && path15.isAbsolute(workspace)
39258
39508
  );
39259
39509
  }
39260
39510
  throw new Error("IDE workspace path JSON must be a string array");
39261
39511
  } catch {
39262
39512
  }
39263
39513
  }
39264
- return value.split(path16.delimiter).filter((workspace) => workspace.length > 0 && path16.isAbsolute(workspace));
39514
+ return value.split(path15.delimiter).filter((workspace) => workspace.length > 0 && path15.isAbsolute(workspace));
39265
39515
  }
39266
39516
  __name(parseIdeWorkspacePathEnv, "parseIdeWorkspacePathEnv");
39267
39517
  function dropNestedWorkspacesPreservingPrimary(workspaces) {
@@ -39750,7 +40000,7 @@ __name(registerWorkspaceQualifiedLifecycleRoutes, "registerWorkspaceQualifiedLif
39750
40000
  init_esbuild_shims();
39751
40001
  import { readdir as readdir3, stat as stat2 } from "node:fs/promises";
39752
40002
  import { realpathSync as realpathSync2 } from "node:fs";
39753
- import { basename as basename7, dirname as dirname9, isAbsolute as isAbsolute10, join as join12, resolve as resolve5, sep as sep4 } from "node:path";
40003
+ import { basename as basename7, dirname as dirname8, isAbsolute as isAbsolute9, join as join11, resolve as resolve5, sep as sep4 } from "node:path";
39754
40004
  var MAX_PATH_SUGGESTIONS = 50;
39755
40005
  function registerWorkspaceManagementRoutes(app, deps) {
39756
40006
  const {
@@ -40139,7 +40389,7 @@ function registerWorkspaceManagementRoutes(app, deps) {
40139
40389
  });
40140
40390
  return;
40141
40391
  }
40142
- if (!isAbsolute10(prefix)) {
40392
+ if (!isAbsolute9(prefix)) {
40143
40393
  res.status(400).json({
40144
40394
  error: "`prefix` must be an absolute path",
40145
40395
  code: "invalid_prefix"
@@ -40147,7 +40397,7 @@ function registerWorkspaceManagementRoutes(app, deps) {
40147
40397
  return;
40148
40398
  }
40149
40399
  const endsWithSep = prefix.endsWith("/") || process.platform === "win32" && prefix.endsWith("\\");
40150
- const dir = endsWithSep ? join12(prefix, ".") : dirname9(prefix);
40400
+ const dir = endsWithSep ? join11(prefix, ".") : dirname8(prefix);
40151
40401
  const filter = endsWithSep ? "" : basename7(prefix);
40152
40402
  const filterLower = filter.toLowerCase();
40153
40403
  const suggestions = [];
@@ -40163,7 +40413,7 @@ function registerWorkspaceManagementRoutes(app, deps) {
40163
40413
  let isDir = entry.isDirectory();
40164
40414
  if (!isDir && entry.isSymbolicLink()) {
40165
40415
  try {
40166
- isDir = (await stat2(join12(dir, entry.name))).isDirectory();
40416
+ isDir = (await stat2(join11(dir, entry.name))).isDirectory();
40167
40417
  } catch {
40168
40418
  continue;
40169
40419
  }
@@ -40173,7 +40423,7 @@ function registerWorkspaceManagementRoutes(app, deps) {
40173
40423
  truncated = true;
40174
40424
  break;
40175
40425
  }
40176
- suggestions.push({ name: entry.name, path: join12(dir, entry.name) });
40426
+ suggestions.push({ name: entry.name, path: join11(dir, entry.name) });
40177
40427
  }
40178
40428
  } catch {
40179
40429
  }
@@ -45647,7 +45897,7 @@ init_esbuild_shims();
45647
45897
 
45648
45898
  // packages/cli/src/serve/live/live-host-coordinator.ts
45649
45899
  init_esbuild_shims();
45650
- import { randomUUID as randomUUID12, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
45900
+ import { randomUUID as randomUUID11, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
45651
45901
  var DEFAULT_HELLO_TIMEOUT_MS = 5e3;
45652
45902
  var DEFAULT_HEARTBEAT_INTERVAL_MS = 5e3;
45653
45903
  var DEFAULT_HEARTBEAT_TIMEOUT_MS = 15e3;
@@ -45830,7 +46080,7 @@ __name(projectStatusForHost, "projectStatusForHost");
45830
46080
  var LiveHostCoordinator = class {
45831
46081
  constructor(options) {
45832
46082
  this.options = options;
45833
- this.daemonInstanceNonce = options.daemonInstanceNonce ?? randomUUID12();
46083
+ this.daemonInstanceNonce = options.daemonInstanceNonce ?? randomUUID11();
45834
46084
  this.handlers = options.handlers ?? {};
45835
46085
  this.now = options.now ?? Date.now;
45836
46086
  this.helloTimeoutMs = options.helloTimeoutMs ?? DEFAULT_HELLO_TIMEOUT_MS;
@@ -45861,6 +46111,7 @@ var LiveHostCoordinator = class {
45861
46111
  };
45862
46112
  call;
45863
46113
  pendingStartMode;
46114
+ actionGeneration = 0;
45864
46115
  nextEpoch = 0;
45865
46116
  inputMuted = false;
45866
46117
  outputMuted = false;
@@ -45881,6 +46132,7 @@ var LiveHostCoordinator = class {
45881
46132
  return this.getStatus();
45882
46133
  }
45883
46134
  async deactivate() {
46135
+ ++this.actionGeneration;
45884
46136
  this.pendingStartMode = void 0;
45885
46137
  if (this.call) {
45886
46138
  const stopped = new Promise((resolve7) => {
@@ -45996,6 +46248,18 @@ var LiveHostCoordinator = class {
45996
46248
  } : {}
45997
46249
  };
45998
46250
  }
46251
+ async requestStart(mode) {
46252
+ const generation = ++this.actionGeneration;
46253
+ this.pendingStartMode = void 0;
46254
+ try {
46255
+ await this.handlers.beforeStart?.();
46256
+ } catch (error2) {
46257
+ if (generation !== this.actionGeneration) return this.getStatus();
46258
+ throw error2;
46259
+ }
46260
+ if (generation !== this.actionGeneration) return this.getStatus();
46261
+ return this.start(mode).status;
46262
+ }
45999
46263
  start(mode) {
46000
46264
  const status = this.getStatus();
46001
46265
  if (!status.available) throw new LiveUnavailableError(status);
@@ -46022,7 +46286,7 @@ var LiveHostCoordinator = class {
46022
46286
  startCall(mode) {
46023
46287
  const call = {
46024
46288
  epoch: ++this.nextEpoch,
46025
- callId: randomUUID12(),
46289
+ callId: randomUUID11(),
46026
46290
  mode,
46027
46291
  state: "starting",
46028
46292
  pendingPermission: false,
@@ -46047,6 +46311,7 @@ var LiveHostCoordinator = class {
46047
46311
  return { epoch: call.epoch, callId: call.callId, status: this.getStatus() };
46048
46312
  }
46049
46313
  stop() {
46314
+ ++this.actionGeneration;
46050
46315
  this.pendingStartMode = void 0;
46051
46316
  if (this.call) this.beginCallStop(this.call);
46052
46317
  return this.getStatus();
@@ -46081,7 +46346,7 @@ var LiveHostCoordinator = class {
46081
46346
  new Error("Qwen Live Host must be connected to change the shortcut.")
46082
46347
  );
46083
46348
  }
46084
- const requestId = randomUUID12();
46349
+ const requestId = randomUUID11();
46085
46350
  return new Promise((resolve7, reject) => {
46086
46351
  const timer = setTimeout(() => {
46087
46352
  this.rejectPendingShortcut(
@@ -46171,7 +46436,7 @@ var LiveHostCoordinator = class {
46171
46436
  )
46172
46437
  );
46173
46438
  }
46174
- const requestId = randomUUID12();
46439
+ const requestId = randomUUID11();
46175
46440
  return new Promise((resolve7, reject) => {
46176
46441
  const timer = setTimeout(() => {
46177
46442
  this.pendingAppshots.delete(requestId);
@@ -46236,6 +46501,7 @@ var LiveHostCoordinator = class {
46236
46501
  this.sendHost({ type: "host.clear_output", epoch });
46237
46502
  }
46238
46503
  dispose() {
46504
+ ++this.actionGeneration;
46239
46505
  this.pendingStartMode = void 0;
46240
46506
  if (this.call) this.finishCall(this.call);
46241
46507
  if (this.host) {
@@ -46460,19 +46726,14 @@ var LiveHostCoordinator = class {
46460
46726
  }
46461
46727
  }
46462
46728
  startFromHost(mode) {
46463
- try {
46464
- this.start(mode);
46465
- } catch (error2) {
46729
+ void this.requestStart(mode).catch((error2) => {
46466
46730
  if (error2 instanceof LiveUnavailableError) {
46467
46731
  this.sendState(error2.status);
46468
46732
  return;
46469
46733
  }
46470
- this.sendState({
46471
- ...this.getStatus(),
46472
- state: "error",
46473
- message: "Live Voice failed to start."
46474
- });
46475
- }
46734
+ this.lastCallError = error2 instanceof ConversationRuntimeOwnershipError ? error2.message : "Live Voice failed to start.";
46735
+ this.sendState(this.buildStatus(false));
46736
+ });
46476
46737
  }
46477
46738
  handleAudioFrame(lease, data) {
46478
46739
  if (!lease.hello) {
@@ -46514,7 +46775,7 @@ var LiveHostCoordinator = class {
46514
46775
  this.disconnectHost(lease, 4008, "Live Host heartbeat timed out.");
46515
46776
  return;
46516
46777
  }
46517
- const pingId = randomUUID12();
46778
+ const pingId = randomUUID11();
46518
46779
  lease.pingId = pingId;
46519
46780
  this.sendHost({ type: "host.ping", pingId });
46520
46781
  }
@@ -46599,9 +46860,10 @@ var LiveHostCoordinator = class {
46599
46860
  this.broadcastState();
46600
46861
  }
46601
46862
  stopForReadinessLoss() {
46863
+ ++this.actionGeneration;
46864
+ this.pendingStartMode = void 0;
46602
46865
  const call = this.call;
46603
46866
  if (!call) return;
46604
- this.pendingStartMode = void 0;
46605
46867
  this.beginCallStop(call);
46606
46868
  }
46607
46869
  disconnectHost(lease, code, reason) {
@@ -46695,8 +46957,7 @@ function registerLiveRoutes(app, deps) {
46695
46957
  });
46696
46958
  app.post("/live/start", deps.mutate(), async (_req, res) => {
46697
46959
  try {
46698
- await deps.ensureRuntimeReady?.();
46699
- res.status(200).json(deps.coordinator.start("resume").status);
46960
+ res.status(200).json(await deps.coordinator.requestStart("resume"));
46700
46961
  } catch (error2) {
46701
46962
  if (sendUnavailable(res, error2)) return;
46702
46963
  throw error2;
@@ -46704,8 +46965,7 @@ function registerLiveRoutes(app, deps) {
46704
46965
  });
46705
46966
  app.post("/live/new", deps.mutate(), async (_req, res) => {
46706
46967
  try {
46707
- await deps.ensureRuntimeReady?.();
46708
- res.status(200).json(deps.coordinator.start("new").status);
46968
+ res.status(200).json(await deps.coordinator.requestStart("new"));
46709
46969
  } catch (error2) {
46710
46970
  if (sendUnavailable(res, error2)) return;
46711
46971
  throw error2;
@@ -46782,7 +47042,7 @@ init_esbuild_shims();
46782
47042
 
46783
47043
  // packages/cli/src/serve/live/live-setup-controller.ts
46784
47044
  init_esbuild_shims();
46785
- import { randomUUID as randomUUID14 } from "node:crypto";
47045
+ import { randomUUID as randomUUID13 } from "node:crypto";
46786
47046
 
46787
47047
  // packages/cli/src/serve/live/provider-credentials.ts
46788
47048
  init_esbuild_shims();
@@ -46880,7 +47140,7 @@ __name(resolveLiveProviderCredential, "resolveLiveProviderCredential");
46880
47140
 
46881
47141
  // packages/cli/src/serve/live/qwen-realtime-session.ts
46882
47142
  init_esbuild_shims();
46883
- import { randomUUID as randomUUID13 } from "node:crypto";
47143
+ import { randomUUID as randomUUID12 } from "node:crypto";
46884
47144
  var QWEN_REALTIME_LIMITS = {
46885
47145
  maxInputAudioFrameBytes: 64 * 1024,
46886
47146
  maxOutputAudioFrameBytes: 256 * 1024,
@@ -47295,7 +47555,7 @@ function openQwenRealtimeSession(config, callbacks = {}, deps = {}) {
47295
47555
  const sendJson = /* @__PURE__ */ __name((body) => {
47296
47556
  if (terminal || closedByClient || ws.readyState !== ws.OPEN) return false;
47297
47557
  try {
47298
- ws.send(JSON.stringify({ event_id: randomUUID13(), ...body }));
47558
+ ws.send(JSON.stringify({ event_id: randomUUID12(), ...body }));
47299
47559
  return true;
47300
47560
  } catch (error2) {
47301
47561
  fail(
@@ -48658,7 +48918,7 @@ async function validateCredential(credential) {
48658
48918
  apiKey: credential.apiKey,
48659
48919
  model: credential.realtimeModel,
48660
48920
  voice: credential.voice,
48661
- callEpoch: `setup-${randomUUID14()}`
48921
+ callEpoch: `setup-${randomUUID13()}`
48662
48922
  });
48663
48923
  session.close({ discardPendingInput: true });
48664
48924
  }
@@ -48965,11 +49225,11 @@ __name(registerLiveSetupRoutes, "registerLiveSetupRoutes");
48965
49225
  // packages/cli/src/serve/live/live-host-installer.ts
48966
49226
  init_esbuild_shims();
48967
49227
  import { execFile as execFile2 } from "node:child_process";
48968
- import { createHash as createHash4, randomUUID as randomUUID15 } from "node:crypto";
48969
- import * as fs9 from "node:fs";
49228
+ import { createHash as createHash4, randomUUID as randomUUID14 } from "node:crypto";
49229
+ import * as fs8 from "node:fs";
48970
49230
  import * as fsp5 from "node:fs/promises";
48971
49231
  import * as os2 from "node:os";
48972
- import * as path17 from "node:path";
49232
+ import * as path16 from "node:path";
48973
49233
  import { Readable, Transform } from "node:stream";
48974
49234
  import { pipeline } from "node:stream/promises";
48975
49235
  import { promisify as promisify2 } from "node:util";
@@ -49049,7 +49309,7 @@ async function readBundleValue(appPath, key) {
49049
49309
  "raw",
49050
49310
  "-o",
49051
49311
  "-",
49052
- path17.join(appPath, "Contents", "Info.plist")
49312
+ path16.join(appPath, "Contents", "Info.plist")
49053
49313
  ]);
49054
49314
  }
49055
49315
  __name(readBundleValue, "readBundleValue");
@@ -49157,7 +49417,7 @@ async function downloadAsset(asset, url, destination, onProgress, fetchImpl) {
49157
49417
  await pipeline(
49158
49418
  Readable.fromWeb(response.body),
49159
49419
  guard,
49160
- fs9.createWriteStream(destination, { flags: "wx", mode: 384 })
49420
+ fs8.createWriteStream(destination, { flags: "wx", mode: 384 })
49161
49421
  );
49162
49422
  if (received !== asset.size || hash.digest("hex") !== asset.sha256) {
49163
49423
  throw new Error("Live Host checksum verification failed.");
@@ -49191,13 +49451,13 @@ async function downloadLiveHostRelease(currentArchitecture, destination, onProgr
49191
49451
  __name(downloadLiveHostRelease, "downloadLiveHostRelease");
49192
49452
  async function installLatestHost(currentArchitecture, onStatus) {
49193
49453
  const temporaryDirectory = await fsp5.mkdtemp(
49194
- path17.join(os2.tmpdir(), "qwen-live-host-")
49454
+ path16.join(os2.tmpdir(), "qwen-live-host-")
49195
49455
  );
49196
- const archivePath = path17.join(temporaryDirectory, "Qwen-Live-Host.zip");
49197
- const extractedPath = path17.join(temporaryDirectory, "extracted");
49198
- const candidatePath = path17.join(extractedPath, LIVE_HOST_APP_NAME);
49199
- const stagingPath = `/Applications/.Qwen Live Host.install-${randomUUID15()}.app`;
49200
- const backupPath = `/Applications/.Qwen Live Host.backup-${randomUUID15()}.app`;
49456
+ const archivePath = path16.join(temporaryDirectory, "Qwen-Live-Host.zip");
49457
+ const extractedPath = path16.join(temporaryDirectory, "extracted");
49458
+ const candidatePath = path16.join(extractedPath, LIVE_HOST_APP_NAME);
49459
+ const stagingPath = `/Applications/.Qwen Live Host.install-${randomUUID14()}.app`;
49460
+ const backupPath = `/Applications/.Qwen Live Host.backup-${randomUUID14()}.app`;
49201
49461
  let movedExisting = false;
49202
49462
  let installedCandidate = false;
49203
49463
  try {
@@ -49348,15 +49608,15 @@ var LiveHostInstaller = class {
49348
49608
 
49349
49609
  // packages/cli/src/serve/live/live-session-coordinator.ts
49350
49610
  init_esbuild_shims();
49351
- import { createHash as createHash5, randomUUID as randomUUID16 } from "node:crypto";
49611
+ import { createHash as createHash5, randomUUID as randomUUID15 } from "node:crypto";
49352
49612
  import { createWriteStream as createWriteStream2, mkdirSync as mkdirSync2 } from "node:fs";
49353
- import { join as join15 } from "node:path";
49613
+ import { join as join14 } from "node:path";
49354
49614
 
49355
49615
  // packages/cli/src/serve/live/realtime-startup-context.ts
49356
49616
  init_esbuild_shims();
49357
49617
  import { readdirSync } from "node:fs";
49358
49618
  import { homedir } from "node:os";
49359
- import { basename as basename8, join as join14 } from "node:path";
49619
+ import { basename as basename8, join as join13 } from "node:path";
49360
49620
  var STARTUP_CONTEXT_HEADER = "Startup context from Qwen Code.\nThis is background context about recent work and machine/workspace layout. It may be incomplete or stale. Use it to inform responses, and do not repeat it back unless relevant.";
49361
49621
  var CURRENT_THREAD_SECTION_TOKEN_BUDGET = 1200;
49362
49622
  var RECENT_WORK_SECTION_TOKEN_BUDGET = 2200;
@@ -49598,7 +49858,7 @@ function collectTreeLines(directory, depth, lines) {
49598
49858
  const indent = " ".repeat(depth);
49599
49859
  lines.push(`${indent}- ${entry.name}${entry.isDirectory() ? "/" : ""}`);
49600
49860
  if (entry.isDirectory()) {
49601
- collectTreeLines(join14(directory, entry.name), depth + 1, lines);
49861
+ collectTreeLines(join13(directory, entry.name), depth + 1, lines);
49602
49862
  }
49603
49863
  }
49604
49864
  if (entries.length > DIR_ENTRY_LIMIT) {
@@ -49717,7 +49977,7 @@ function openLiveAudioCapture(source, identifier) {
49717
49977
  try {
49718
49978
  mkdirSync2(directory, { recursive: true, mode: 448 });
49719
49979
  const safeIdentifier = identifier.replace(/[^A-Za-z0-9_-]/g, "_");
49720
- const path19 = join15(
49980
+ const path19 = join14(
49721
49981
  directory,
49722
49982
  `${source}-${Date.now()}-${safeIdentifier}.pcm`
49723
49983
  );
@@ -50078,7 +50338,7 @@ var LiveSessionCoordinator = class {
50078
50338
  context.speechInProgress = true;
50079
50339
  context.inputCommitPending = true;
50080
50340
  context.inputAwaitingResponse = false;
50081
- const partialItemId = itemId ?? `partial:${randomUUID16()}`;
50341
+ const partialItemId = itemId ?? `partial:${randomUUID15()}`;
50082
50342
  context.activePartialInputItemId = partialItemId;
50083
50343
  if (!context.partialInputTranscripts.has(partialItemId)) {
50084
50344
  context.partialInputTranscripts.set(partialItemId, "");
@@ -50108,7 +50368,7 @@ var LiveSessionCoordinator = class {
50108
50368
  }, "onInputCommitted"),
50109
50369
  onInputTranscriptDelta: /* @__PURE__ */ __name(({ itemId, text }) => {
50110
50370
  if (this.isCurrentSocket(context, generation)) {
50111
- const partialItemId = itemId ?? context.activePartialInputItemId ?? `partial:${randomUUID16()}`;
50371
+ const partialItemId = itemId ?? context.activePartialInputItemId ?? `partial:${randomUUID15()}`;
50112
50372
  context.activePartialInputItemId = partialItemId;
50113
50373
  context.partialInputTranscripts.set(partialItemId, text);
50114
50374
  this.options.host.setTranscript?.(context.epoch, text);
@@ -50118,7 +50378,7 @@ var LiveSessionCoordinator = class {
50118
50378
  if (this.isCurrentSocket(context, generation)) {
50119
50379
  context.speechInProgress = false;
50120
50380
  context.inputCommitPending = false;
50121
- const completedItemId = itemId ?? context.activePartialInputItemId ?? `unattributed:${randomUUID16()}`;
50381
+ const completedItemId = itemId ?? context.activePartialInputItemId ?? `unattributed:${randomUUID15()}`;
50122
50382
  context.partialInputTranscripts.delete(completedItemId);
50123
50383
  if (context.activePartialInputItemId === completedItemId) {
50124
50384
  context.activePartialInputItemId = void 0;
@@ -50850,7 +51110,7 @@ var LiveSessionCoordinator = class {
50850
51110
  const runtime = context.runtime;
50851
51111
  if (!runtime) throw new Error("Conversation workspace is unavailable.");
50852
51112
  const bridge = runtime.bridge;
50853
- const promptId = randomUUID16();
51113
+ const promptId = randomUUID15();
50854
51114
  const lastEventId = bridge.getSessionLastEventId(locator.sessionId);
50855
51115
  const turnAbort = new AbortController();
50856
51116
  this.inFlightTurnAborts.add(turnAbort);
@@ -51167,7 +51427,7 @@ var LiveSessionCoordinator = class {
51167
51427
 
51168
51428
  // packages/cli/src/serve/live/live-task-service.ts
51169
51429
  init_esbuild_shims();
51170
- import { randomUUID as randomUUID17 } from "node:crypto";
51430
+ import { randomUUID as randomUUID16 } from "node:crypto";
51171
51431
  var DEFAULT_LIST_LIMIT = 20;
51172
51432
  var DEFAULT_READ_TURN_LIMIT = 3;
51173
51433
  var DEFAULT_WAIT_TIMEOUT_MS = 12e4;
@@ -51853,7 +52113,7 @@ var LiveTaskService = class {
51853
52113
  const record = target;
51854
52114
  if (record["type"] === "projectless") {
51855
52115
  const created = await this.getStandaloneSessionService().createWithInitialPrompt(
51856
- { sessionId: randomUUID17() },
52116
+ { sessionId: randomUUID16() },
51857
52117
  prompt
51858
52118
  );
51859
52119
  return {
@@ -51905,7 +52165,7 @@ var LiveTaskService = class {
51905
52165
  { sessionId, prompt: [{ type: "text", text: prompt }] },
51906
52166
  void 0,
51907
52167
  {
51908
- promptId: randomUUID17(),
52168
+ promptId: randomUUID16(),
51909
52169
  onPromptAdmitted: /* @__PURE__ */ __name(() => {
51910
52170
  admitted = true;
51911
52171
  onAdmitted?.();
@@ -52178,7 +52438,7 @@ var ConversationRuntimeManager = class {
52178
52438
  }
52179
52439
  async ensureOnce() {
52180
52440
  this.assertNotTerminal();
52181
- await this.options.ownership.acquire();
52441
+ if (!this.runtime) await this.options.checkLegacyOwner();
52182
52442
  this.assertNotTerminal();
52183
52443
  const root = await this.revalidateRoot();
52184
52444
  this.assertNotTerminal();
@@ -52269,6 +52529,226 @@ var ConversationRuntimeManager = class {
52269
52529
  }
52270
52530
  };
52271
52531
 
52532
+ // packages/cli/src/serve/conversations/conversation-runtime-ownership.ts
52533
+ init_esbuild_shims();
52534
+ import { constants as fsConstants3 } from "node:fs";
52535
+ import * as fs9 from "node:fs/promises";
52536
+ import * as path17 from "node:path";
52537
+ var OWNER_DIRECTORY = "conversations";
52538
+ var OWNER_FILE = "runtime-owner.json";
52539
+ var OWNER_LOCK = ".runtime-owner.lock";
52540
+ var MAX_OWNER_BYTES = 4 * 1024;
52541
+ var NONCE_PATTERN = /^[A-Za-z0-9_-]{16,256}$/;
52542
+ var DEFAULT_HANDOFF_GRACE_MS = 1e3;
52543
+ var UnsafeOwnershipStateError = class extends Error {
52544
+ static {
52545
+ __name(this, "UnsafeOwnershipStateError");
52546
+ }
52547
+ };
52548
+ function getConversationRuntimeOwnerPath(stableBaseDir) {
52549
+ return path17.join(stableBaseDir, OWNER_DIRECTORY, OWNER_FILE);
52550
+ }
52551
+ __name(getConversationRuntimeOwnerPath, "getConversationRuntimeOwnerPath");
52552
+ function processIsAlive(pid) {
52553
+ try {
52554
+ process.kill(pid, 0);
52555
+ return true;
52556
+ } catch (error2) {
52557
+ return error2.code !== "ESRCH";
52558
+ }
52559
+ }
52560
+ __name(processIsAlive, "processIsAlive");
52561
+ function delay2(milliseconds) {
52562
+ return new Promise((resolve7) => {
52563
+ setTimeout(resolve7, milliseconds);
52564
+ });
52565
+ }
52566
+ __name(delay2, "delay");
52567
+ function isMissing2(error2) {
52568
+ return error2.code === "ENOENT";
52569
+ }
52570
+ __name(isMissing2, "isMissing");
52571
+ function assertOwnerRecord(value) {
52572
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
52573
+ throw new UnsafeOwnershipStateError();
52574
+ }
52575
+ const keys = Object.keys(value).sort();
52576
+ if (keys.length !== 3 || keys[0] !== "instanceNonce" || keys[1] !== "pid" || keys[2] !== "version") {
52577
+ throw new UnsafeOwnershipStateError();
52578
+ }
52579
+ const record = value;
52580
+ if (record["version"] !== 1 || !Number.isSafeInteger(record["pid"]) || record["pid"] <= 0 || typeof record["instanceNonce"] !== "string" || !NONCE_PATTERN.test(record["instanceNonce"])) {
52581
+ throw new UnsafeOwnershipStateError();
52582
+ }
52583
+ return {
52584
+ version: 1,
52585
+ pid: record["pid"],
52586
+ instanceNonce: record["instanceNonce"]
52587
+ };
52588
+ }
52589
+ __name(assertOwnerRecord, "assertOwnerRecord");
52590
+ function sameRecord(left, right) {
52591
+ return left.version === right.version && left.pid === right.pid && left.instanceNonce === right.instanceNonce;
52592
+ }
52593
+ __name(sameRecord, "sameRecord");
52594
+ async function inspectDirectory(directory, requirePrivateMode) {
52595
+ const stat3 = await fs9.lstat(directory);
52596
+ if (!stat3.isDirectory() || stat3.isSymbolicLink()) {
52597
+ throw new UnsafeOwnershipStateError();
52598
+ }
52599
+ if (process.platform !== "win32" && (typeof process.getuid === "function" && stat3.uid !== process.getuid() || requirePrivateMode && (stat3.mode & 511) !== 448)) {
52600
+ throw new UnsafeOwnershipStateError();
52601
+ }
52602
+ return { dev: stat3.dev, ino: stat3.ino };
52603
+ }
52604
+ __name(inspectDirectory, "inspectDirectory");
52605
+ async function assertDirectoryIdentity(directory, expected, requirePrivateMode = true) {
52606
+ const current = await inspectDirectory(directory, requirePrivateMode);
52607
+ if (current.dev !== expected.dev || current.ino !== expected.ino) {
52608
+ throw new UnsafeOwnershipStateError();
52609
+ }
52610
+ }
52611
+ __name(assertDirectoryIdentity, "assertDirectoryIdentity");
52612
+ async function assertLockShapeIfPresent(lockPath) {
52613
+ let stat3;
52614
+ try {
52615
+ stat3 = await fs9.lstat(lockPath);
52616
+ } catch (error2) {
52617
+ if (isMissing2(error2)) return;
52618
+ throw error2;
52619
+ }
52620
+ if (!stat3.isDirectory() || stat3.isSymbolicLink() || process.platform !== "win32" && typeof process.getuid === "function" && stat3.uid !== process.getuid()) {
52621
+ throw new UnsafeOwnershipStateError();
52622
+ }
52623
+ }
52624
+ __name(assertLockShapeIfPresent, "assertLockShapeIfPresent");
52625
+ async function readOwnerRecord(ownerPath) {
52626
+ let pathStat;
52627
+ try {
52628
+ pathStat = await fs9.lstat(ownerPath);
52629
+ } catch (error2) {
52630
+ if (isMissing2(error2)) return void 0;
52631
+ throw error2;
52632
+ }
52633
+ if (!pathStat.isFile() || pathStat.isSymbolicLink() || pathStat.nlink !== 1 || pathStat.size <= 0 || pathStat.size > MAX_OWNER_BYTES || process.platform !== "win32" && ((pathStat.mode & 511) !== 384 || typeof process.getuid === "function" && pathStat.uid !== process.getuid())) {
52634
+ throw new UnsafeOwnershipStateError();
52635
+ }
52636
+ let handle;
52637
+ try {
52638
+ handle = await fs9.open(
52639
+ ownerPath,
52640
+ process.platform === "win32" ? fsConstants3.O_RDONLY : fsConstants3.O_RDONLY | fsConstants3.O_NOFOLLOW
52641
+ );
52642
+ } catch (error2) {
52643
+ if (error2.code === "ELOOP") {
52644
+ throw new UnsafeOwnershipStateError(void 0, { cause: error2 });
52645
+ }
52646
+ throw error2;
52647
+ }
52648
+ try {
52649
+ const handleStat = await handle.stat();
52650
+ if (!handleStat.isFile() || handleStat.nlink !== 1 || handleStat.dev !== pathStat.dev || handleStat.ino !== pathStat.ino || handleStat.size !== pathStat.size || process.platform !== "win32" && ((handleStat.mode & 511) !== 384 || typeof process.getuid === "function" && handleStat.uid !== process.getuid())) {
52651
+ throw new UnsafeOwnershipStateError();
52652
+ }
52653
+ const serialized = await handle.readFile("utf8");
52654
+ let parsed;
52655
+ try {
52656
+ parsed = JSON.parse(serialized);
52657
+ } catch (error2) {
52658
+ throw new UnsafeOwnershipStateError(void 0, { cause: error2 });
52659
+ }
52660
+ return assertOwnerRecord(parsed);
52661
+ } finally {
52662
+ await handle.close();
52663
+ }
52664
+ }
52665
+ __name(readOwnerRecord, "readOwnerRecord");
52666
+ async function syncDirectory(directory) {
52667
+ if (process.platform === "win32") return;
52668
+ const handle = await fs9.open(directory, fsConstants3.O_RDONLY);
52669
+ try {
52670
+ await handle.sync();
52671
+ } finally {
52672
+ await handle.close();
52673
+ }
52674
+ }
52675
+ __name(syncDirectory, "syncDirectory");
52676
+ async function checkLegacyConversationRuntimeOwner(options) {
52677
+ const ownerPath = getConversationRuntimeOwnerPath(options.stableBaseDir);
52678
+ const directory = path17.dirname(ownerPath);
52679
+ const lockPath = path17.join(directory, OWNER_LOCK);
52680
+ let reclaimed = false;
52681
+ try {
52682
+ let base;
52683
+ let identity;
52684
+ try {
52685
+ base = await inspectDirectory(options.stableBaseDir, false);
52686
+ identity = await inspectDirectory(directory, true);
52687
+ } catch (error2) {
52688
+ if (isMissing2(error2)) return;
52689
+ throw error2;
52690
+ }
52691
+ await assertLockShapeIfPresent(lockPath);
52692
+ const lockfile = (await import("./proper-lockfile-3LHWIM44.js")).default;
52693
+ let compromised = false;
52694
+ const release = await lockfile.lock(directory, {
52695
+ realpath: false,
52696
+ lockfilePath: lockPath,
52697
+ stale: 5e3,
52698
+ update: 1e3,
52699
+ retries: { retries: 40, minTimeout: 10, maxTimeout: 50 },
52700
+ ...options.lockOptions,
52701
+ onCompromised: /* @__PURE__ */ __name(() => {
52702
+ compromised = true;
52703
+ }, "onCompromised")
52704
+ });
52705
+ let operationError;
52706
+ try {
52707
+ await assertLockShapeIfPresent(lockPath);
52708
+ await assertDirectoryIdentity(options.stableBaseDir, base, false);
52709
+ await assertDirectoryIdentity(directory, identity);
52710
+ const existing = await readOwnerRecord(ownerPath);
52711
+ if (compromised) throw new UnsafeOwnershipStateError();
52712
+ if (existing) {
52713
+ if ((options.isProcessAlive ?? processIsAlive)(existing.pid)) {
52714
+ throw conversationRuntimeInUseError();
52715
+ }
52716
+ const confirmed = await readOwnerRecord(ownerPath);
52717
+ if (!confirmed || !sameRecord(existing, confirmed)) {
52718
+ throw new UnsafeOwnershipStateError();
52719
+ }
52720
+ await assertDirectoryIdentity(options.stableBaseDir, base, false);
52721
+ await assertDirectoryIdentity(directory, identity);
52722
+ if (compromised) throw new UnsafeOwnershipStateError();
52723
+ await fs9.unlink(ownerPath);
52724
+ await syncDirectory(directory);
52725
+ reclaimed = true;
52726
+ }
52727
+ } catch (error2) {
52728
+ operationError = error2;
52729
+ }
52730
+ try {
52731
+ await release();
52732
+ } catch (error2) {
52733
+ throw new UnsafeOwnershipStateError(void 0, { cause: error2 });
52734
+ }
52735
+ if (compromised) throw new UnsafeOwnershipStateError();
52736
+ if (operationError) throw operationError;
52737
+ if (reclaimed) {
52738
+ await (options.wait ?? delay2)(
52739
+ options.handoffGraceMs ?? DEFAULT_HANDOFF_GRACE_MS
52740
+ );
52741
+ }
52742
+ } catch (error2) {
52743
+ if (error2 instanceof ConversationRuntimeOwnershipError) throw error2;
52744
+ if (error2 instanceof UnsafeOwnershipStateError || error2.code === "ECOMPROMISED") {
52745
+ throw conversationRuntimeOwnershipCompromisedError(error2);
52746
+ }
52747
+ throw conversationRuntimeUnavailableError(error2);
52748
+ }
52749
+ }
52750
+ __name(checkLegacyConversationRuntimeOwner, "checkLegacyConversationRuntimeOwner");
52751
+
52272
52752
  // packages/cli/src/serve/server.ts
52273
52753
  var warnedDefaultTrust = false;
52274
52754
  function loadServeChannelWebhookConfigs(sources) {
@@ -52809,22 +53289,9 @@ function createServeApp(opts, getPort = () => opts.port, deps = {}) {
52809
53289
  }
52810
53290
  }, "getProviderReadiness")
52811
53291
  });
52812
- const conversationRuntimeOwnership = deps.liveConversationWorkspace ? deps.conversationRuntimeOwnershipFactory?.(
52813
- process.pid,
52814
- liveCoordinator.daemonInstanceNonce,
52815
- path18.resolve(
52816
- deps.liveDiscoveryStableBaseDir ?? getStableLiveDiscoveryBaseDir()
52817
- )
52818
- ) ?? createConversationRuntimeOwnership({
52819
- pid: process.pid,
52820
- instanceNonce: liveCoordinator.daemonInstanceNonce,
52821
- stableBaseDir: path18.resolve(
52822
- deps.liveDiscoveryStableBaseDir ?? getStableLiveDiscoveryBaseDir()
52823
- )
52824
- }) : void 0;
52825
- if (conversationRuntimeOwnership) {
52826
- serveAppLifecycle.setOwnership(conversationRuntimeOwnership);
52827
- }
53292
+ const stableLiveDiscoveryBaseDir = path18.resolve(
53293
+ deps.liveDiscoveryStableBaseDir ?? getStableLiveDiscoveryBaseDir()
53294
+ );
52828
53295
  liveCoordinator.setAppshotReadiness(
52829
53296
  liveVoiceEnabled && deps.liveConversationWorkspace ? {
52830
53297
  state: "checking",
@@ -52836,7 +53303,9 @@ function createServeApp(opts, getPort = () => opts.port, deps = {}) {
52836
53303
  );
52837
53304
  let standaloneSessionService;
52838
53305
  const conversationRuntimeManager = deps.liveConversationWorkspace ? new ConversationRuntimeManager({
52839
- ownership: conversationRuntimeOwnership,
53306
+ checkLegacyOwner: deps.checkLegacyConversationOwner ?? (() => checkLegacyConversationRuntimeOwner({
53307
+ stableBaseDir: stableLiveDiscoveryBaseDir
53308
+ })),
52840
53309
  workspace: deps.liveConversationWorkspace,
52841
53310
  registry: workspaceRegistry,
52842
53311
  publishRuntime: /* @__PURE__ */ __name(async (canonicalRoot, validate) => {
@@ -53120,6 +53589,14 @@ function createServeApp(opts, getPort = () => opts.port, deps = {}) {
53120
53589
  interruptTaskWaits: /* @__PURE__ */ __name((callerSessionId) => liveTaskService.interruptWait(callerSessionId), "interruptTaskWaits")
53121
53590
  });
53122
53591
  liveCoordinator.setHandlers({
53592
+ beforeStart: /* @__PURE__ */ __name(async () => {
53593
+ await ensureConversationRuntimeWithLifecycle();
53594
+ await publishLiveVoiceEnabled(true);
53595
+ await assertLiveDiscoveryPublisher(stableLiveDiscoveryBaseDir, {
53596
+ pid: process.pid,
53597
+ instanceNonce: liveCoordinator.daemonInstanceNonce
53598
+ });
53599
+ }, "beforeStart"),
53123
53600
  onHostReady: /* @__PURE__ */ __name(() => {
53124
53601
  if (!liveVoiceEnabled) return;
53125
53602
  void verifyLiveAppshotChannel();
@@ -53413,10 +53890,6 @@ function createServeApp(opts, getPort = () => opts.port, deps = {}) {
53413
53890
  if (liveVoiceSurfaceAvailable) {
53414
53891
  registerLiveRoutes(app, {
53415
53892
  coordinator: liveCoordinator,
53416
- ensureRuntimeReady: /* @__PURE__ */ __name(async () => {
53417
- await ensureConversationRuntimeWithLifecycle();
53418
- await publishLiveVoiceEnabled(true);
53419
- }, "ensureRuntimeReady"),
53420
53893
  mutate,
53421
53894
  ...deps.persistSetting ? {
53422
53895
  persistShortcut: /* @__PURE__ */ __name(async (shortcut) => {