@qwen-code/qwen-code 0.25.4-preview.0 → 0.25.4-preview.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 (306) hide show
  1. package/bundled/browser-use/runtime/native-host.js +0 -0
  2. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
  3. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
  4. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
  5. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
  6. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
  7. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
  8. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
  9. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
  10. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
  11. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
  12. package/bundled/browser-use/runtime/node_modules/playwright-core/cli.js +0 -0
  13. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
  14. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/xdg-open +0 -0
  15. package/bundled/browser-use/runtime/scripts/native-host-setup.js +0 -0
  16. package/chunks/{MaxSizedBox-M27H235V.js → MaxSizedBox-E4RKSA7W.js} +1 -1
  17. package/chunks/{StandaloneSessionPicker-LWWDDYOW.js → StandaloneSessionPicker-2D3UKLVS.js} +1 -1
  18. package/chunks/{acp-subagent-executor-NUV52JVS.js → acp-subagent-executor-UQYUN6AB.js} +1 -1
  19. package/chunks/{acpAgent-IUJDXLZM.js → acpAgent-P7WGK2BP.js} +3 -3
  20. package/chunks/{advisor-MSOUBMJ6.js → advisor-GCH2MBXT.js} +1 -1
  21. package/chunks/{agent-H7XIWYWQ.js → agent-57T4YAYP.js} +1 -1
  22. package/chunks/{agent-headless-XDN3D3S3.js → agent-headless-IBON3A7N.js} +1 -1
  23. package/chunks/{agent-host-client-AZP3PZXS.js → agent-host-client-LE7P72FR.js} +1 -1
  24. package/chunks/{agent-host-connections-JRVX7I6I.js → agent-host-connections-4DM57L26.js} +1 -1
  25. package/chunks/{anthropicContentGenerator-N7TV53LD.js → anthropicContentGenerator-C4TPFXUK.js} +1 -1
  26. package/chunks/{batch-MKSJFJUH.js → batch-YJJGMJWO.js} +1 -1
  27. package/chunks/{bridge-GNMKKHQ4.js → bridge-FIO2ENBG.js} +1 -1
  28. package/chunks/{channel-settings-store-Y4YCS7JX.js → channel-settings-store-TEBCLK2B.js} +1 -1
  29. package/chunks/{chunk-GPOUP5OK.js → chunk-27MTSS3T.js} +1 -1
  30. package/chunks/{chunk-C4ANA47H.js → chunk-2MGCRPM3.js} +1 -1
  31. package/chunks/{chunk-6DQNNRRC.js → chunk-2WBKWPSO.js} +1 -1
  32. package/chunks/{chunk-CATL2PQS.js → chunk-34WLYVDK.js} +5 -5
  33. package/chunks/{chunk-B7CXPNCV.js → chunk-3J2YNEHG.js} +1 -1
  34. package/chunks/{chunk-VTNHPXNL.js → chunk-3TBFTELA.js} +1 -1
  35. package/chunks/{chunk-7JT34VGK.js → chunk-46I6JBVL.js} +1 -1
  36. package/chunks/{chunk-FEMWELCV.js → chunk-4ZKFLOEH.js} +1 -1
  37. package/chunks/{chunk-7AYXAVTZ.js → chunk-5DUJIOOX.js} +3 -3
  38. package/chunks/{chunk-6QLHJSVW.js → chunk-6PWOLWTH.js} +1 -1
  39. package/chunks/{chunk-OW4QBRSR.js → chunk-6UZ65Z2P.js} +1 -1
  40. package/chunks/{chunk-V2JZO5MS.js → chunk-7DSJE3CL.js} +1 -1
  41. package/chunks/{chunk-TJMHIEYI.js → chunk-7LCY7GGX.js} +1 -1
  42. package/chunks/{chunk-TLJHBK3A.js → chunk-7RNTXEWH.js} +1 -1
  43. package/chunks/{chunk-YZ7OO4AQ.js → chunk-A3IF6IOB.js} +1 -1
  44. package/chunks/{chunk-VTF6AVZB.js → chunk-A6OQSOUO.js} +1 -1
  45. package/chunks/{chunk-Y7YDHCON.js → chunk-AJ6JUUP7.js} +1 -1
  46. package/chunks/{chunk-QTMHQGWQ.js → chunk-AOMEBVFW.js} +1 -1
  47. package/chunks/{chunk-KVTG2ZNH.js → chunk-AUNAS7AS.js} +1 -1
  48. package/chunks/{chunk-BOFD4CN3.js → chunk-AVIDPC5K.js} +1 -1
  49. package/chunks/{chunk-ETYTRKB2.js → chunk-BOLPBPWC.js} +1 -1
  50. package/chunks/{chunk-OAPA66DR.js → chunk-BQQBFDBY.js} +1 -1
  51. package/chunks/{chunk-NOS2CNOI.js → chunk-CN22ATWU.js} +1 -1
  52. package/chunks/{chunk-XYBEQRSZ.js → chunk-DIHJELGW.js} +1 -1
  53. package/chunks/{chunk-XCEL3EDX.js → chunk-DJFCI7TU.js} +1 -1
  54. package/chunks/{chunk-VKEL2XTM.js → chunk-DQPDMFS3.js} +1 -1
  55. package/chunks/{chunk-DJRFEZBY.js → chunk-DSYKB77N.js} +1 -1
  56. package/chunks/{chunk-UEW7Q26E.js → chunk-EDNOGHMN.js} +2 -2
  57. package/chunks/{chunk-RXNGYG64.js → chunk-EE36D2EV.js} +1 -1
  58. package/chunks/{chunk-NZKX7HYL.js → chunk-EGQDN3FJ.js} +1 -1
  59. package/chunks/{chunk-DFRSQK5Q.js → chunk-FHFBCG6N.js} +1 -1
  60. package/chunks/{chunk-PECV2VVZ.js → chunk-GI6T3RBV.js} +1 -1
  61. package/chunks/{chunk-37BNHIUB.js → chunk-GOLT5JXA.js} +1 -1
  62. package/chunks/{chunk-KITFF4GL.js → chunk-IDGXHMNL.js} +1 -1
  63. package/chunks/{chunk-6HIOSLUM.js → chunk-IIZWK7ZP.js} +1 -1
  64. package/chunks/{chunk-MPGEAX4K.js → chunk-IJC6ZH2S.js} +1 -1
  65. package/chunks/{chunk-TLYJVB5H.js → chunk-IO6LSEPV.js} +1 -1
  66. package/chunks/{chunk-QIJKEZZR.js → chunk-IYVNCBMS.js} +1 -1
  67. package/chunks/{chunk-S4GOHFRN.js → chunk-JHGOWK7M.js} +1 -1
  68. package/chunks/{chunk-GHRD2MMC.js → chunk-JRJY343T.js} +1 -1
  69. package/chunks/{chunk-WCYZSCG7.js → chunk-JVUXQU3W.js} +1 -1
  70. package/chunks/{chunk-DMCTJUIJ.js → chunk-K2K2YYWO.js} +1 -1
  71. package/chunks/{chunk-37OHWQHB.js → chunk-KF6HU732.js} +2 -2
  72. package/chunks/{chunk-5LSV73BG.js → chunk-KVWUOBH7.js} +1 -1
  73. package/chunks/{chunk-7V4BAHFT.js → chunk-LBWBGFHD.js} +1 -1
  74. package/chunks/{chunk-RKPHDO42.js → chunk-LDXZT3SG.js} +5 -5
  75. package/chunks/{chunk-BGFA2SAQ.js → chunk-LFOZ6AIH.js} +1 -1
  76. package/chunks/{chunk-4322TZID.js → chunk-LGQHT42X.js} +2 -2
  77. package/chunks/{chunk-PDXZ2CUO.js → chunk-M3O2XDHA.js} +1 -1
  78. package/chunks/{chunk-47K2NMP6.js → chunk-M3UC46LS.js} +1 -1
  79. package/chunks/{chunk-UFRY7WND.js → chunk-M7JLPTQI.js} +1 -1
  80. package/chunks/{chunk-SATEKHQP.js → chunk-MBUXP3IS.js} +1 -1
  81. package/chunks/{chunk-RN6JS263.js → chunk-MEZA3VVH.js} +1 -1
  82. package/chunks/{chunk-OBFKP7RI.js → chunk-MWN6TR36.js} +1 -1
  83. package/chunks/{chunk-VHJ43ZYJ.js → chunk-O7XRQWCG.js} +1 -1
  84. package/chunks/{chunk-H224LNV3.js → chunk-OYFRLT5E.js} +1 -1
  85. package/chunks/{chunk-3NWFV2YF.js → chunk-PMBGV76N.js} +1 -1
  86. package/chunks/{chunk-YFAPACDE.js → chunk-PVM4IVFL.js} +6 -6
  87. package/chunks/{chunk-7WS2EYMQ.js → chunk-PWHD4NK3.js} +1 -1
  88. package/chunks/{chunk-JZIQSEFO.js → chunk-Q54NROBX.js} +1 -1
  89. package/chunks/{chunk-FCLAPJ22.js → chunk-QE7R4DPT.js} +1 -1
  90. package/chunks/{chunk-J6TW7GNF.js → chunk-QIUTQICH.js} +1 -1
  91. package/chunks/{chunk-TWDCN5H2.js → chunk-QK63EULE.js} +1 -1
  92. package/chunks/{chunk-HZZT75LI.js → chunk-QTAC4W7J.js} +1 -1
  93. package/chunks/{chunk-P7DIAJNX.js → chunk-R7HBR4QQ.js} +1 -1
  94. package/chunks/{chunk-U2FJSKS3.js → chunk-RHEMFKMX.js} +1 -1
  95. package/chunks/{chunk-TRRY3QMM.js → chunk-RL57IU47.js} +1 -1
  96. package/chunks/{chunk-SPWDYRDH.js → chunk-S2OOQRLJ.js} +1 -1
  97. package/chunks/{chunk-QBRADQ7L.js → chunk-SWTMWNTZ.js} +1 -1
  98. package/chunks/{chunk-AZUDF52L.js → chunk-SXTKQHFZ.js} +1 -1
  99. package/chunks/{chunk-5RQRSPPD.js → chunk-T5S3MJIK.js} +1 -1
  100. package/chunks/{chunk-I3ORWQ2U.js → chunk-UDGDEIBB.js} +1 -1
  101. package/chunks/{chunk-EMDEBV33.js → chunk-UIFBF3E7.js} +1 -1
  102. package/chunks/{chunk-BGEMWNES.js → chunk-UQDPWI7D.js} +1 -1
  103. package/chunks/{chunk-I5LKOTZT.js → chunk-VON4MVIM.js} +1 -1
  104. package/chunks/{chunk-HJPO6MEW.js → chunk-W5D2T2JK.js} +1 -1
  105. package/chunks/{chunk-F6YYDRMH.js → chunk-WNGYYU67.js} +1 -1
  106. package/chunks/{chunk-S2GKUZZZ.js → chunk-WO3F62ZD.js} +1 -1
  107. package/chunks/{chunk-K7KW3ZJQ.js → chunk-WVY5Q6YY.js} +1 -1
  108. package/chunks/{chunk-GH6DPLWU.js → chunk-Y4Q667BW.js} +1 -1
  109. package/chunks/{chunk-FH74N7Y7.js → chunk-YJLMFUCS.js} +2 -2
  110. package/chunks/{chunk-C3Y2S5AM.js → chunk-YKHRCSKP.js} +1 -1
  111. package/chunks/{chunk-P4UJ7CXJ.js → chunk-YLIS36QA.js} +1 -1
  112. package/chunks/{chunk-4QIFOIBS.js → chunk-YVZ4XZRB.js} +1 -1
  113. package/chunks/{chunk-KGRD6G5J.js → chunk-Z27JJPKN.js} +1 -1
  114. package/chunks/{chunk-KOHHDB2L.js → chunk-ZCIS6MJZ.js} +1 -1
  115. package/chunks/{chunk-QNNDZYVW.js → chunk-ZHLQ222N.js} +1 -1
  116. package/chunks/{chunk-KWRZ3WJO.js → chunk-ZP7MTWMR.js} +1 -1
  117. package/chunks/{codex-subagent-executor-H44VDB5E.js → codex-subagent-executor-6OJVGF2S.js} +1 -1
  118. package/chunks/{config-utils-4X4SV4RL.js → config-utils-FI3A4QAN.js} +1 -1
  119. package/chunks/{contextCommand-4KVOHTAJ.js → contextCommand-YEBZQHG4.js} +1 -1
  120. package/chunks/{core-runtime-4RARI4NX.js → core-runtime-CFMHUAS7.js} +1 -1
  121. package/chunks/{create-sub-session-CNSRJFYG.js → create-sub-session-G26337FT.js} +1 -1
  122. package/chunks/{daemon-git-worktree-guard-6XQQPP2H.js → daemon-git-worktree-guard-ITU6NQIV.js} +1 -1
  123. package/chunks/{daemon-status-provider-PRTEQT5T.js → daemon-status-provider-CSWRGMRX.js} +1 -1
  124. package/chunks/{daemon-trust-policy-GXKJVZDU.js → daemon-trust-policy-IYD7NOGK.js} +1 -1
  125. package/chunks/{daemon-trust-policy-monitor-L2ORKHMM.js → daemon-trust-policy-monitor-OWUP5SYB.js} +1 -1
  126. package/chunks/{deferred-core-runtime-RZQFUSPX.js → deferred-core-runtime-CVCQU7O4.js} +1 -1
  127. package/chunks/{edit-W44XQCIS.js → edit-7YBQLILC.js} +1 -1
  128. package/chunks/{enterPlanMode-B456A2XO.js → enterPlanMode-L3PVSD2P.js} +1 -1
  129. package/chunks/{environment-DSGQSQFS.js → environment-BVEOYQHO.js} +1 -1
  130. package/chunks/{errors-KL725247.js → errors-VQWBGR6D.js} +1 -1
  131. package/chunks/{execution-tool-KT3EBWHG.js → execution-tool-P7CBXSGZ.js} +1 -1
  132. package/chunks/{execution-worker-LPQ4HMN4.js → execution-worker-RZXNYK4B.js} +1 -1
  133. package/chunks/{exitPlanMode-JLKS76IA.js → exitPlanMode-MBUTM3NW.js} +1 -1
  134. package/chunks/{fast-path-5UD52IHH.js → fast-path-T2FDUSHV.js} +1 -1
  135. package/chunks/{glob-LYA2H6X3.js → glob-RH7XXSYE.js} +1 -1
  136. package/chunks/{goal-tools-SHSIDLZX.js → goal-tools-K6XBCE5E.js} +1 -1
  137. package/chunks/{handleAutoUpdate-T4RE6CZN.js → handleAutoUpdate-PG7R3KPH.js} +1 -1
  138. package/chunks/{i18n-5DK327WA.js → i18n-EGTBMA3N.js} +1 -1
  139. package/chunks/{initializer-TJGE4OJA.js → initializer-RIKH4PCP.js} +1 -1
  140. package/chunks/{installationInfo-MZ62GDIC.js → installationInfo-BBADHZLD.js} +1 -1
  141. package/chunks/{interactive-mod-session-YCUBQ6RM.js → interactive-mod-session-7RDKAHZ4.js} +1 -1
  142. package/chunks/{list-4L3LYDQM.js → list-YEGWEHJX.js} +1 -1
  143. package/chunks/{llm-3JQWBZXV.js → llm-D3LHPY27.js} +4 -4
  144. package/chunks/{llm-content-generator-6UPJWPOM.js → llm-content-generator-BLTBMV66.js} +1 -1
  145. package/chunks/{loadedSettingsAdapter-STPKAFJG.js → loadedSettingsAdapter-PLGMKMFO.js} +1 -1
  146. package/chunks/{local-execution-environment-IE5BOI7Y.js → local-execution-environment-4LDKFNC4.js} +1 -1
  147. package/chunks/{loggingContentGenerator-4KKWPZJA.js → loggingContentGenerator-376R7DRI.js} +1 -1
  148. package/chunks/{manage-memory-CRV5SXZZ.js → manage-memory-2ZTIVKNU.js} +1 -1
  149. package/chunks/{managed-execution-engine-FHLEWVND.js → managed-execution-engine-5LOM3MXG.js} +1 -1
  150. package/chunks/{managed-npm-update-BRHPOKDU.js → managed-npm-update-2C5JYEXW.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-GIQKZ5BH.js → managed-runtime-attestation-worker-R2FECMZK.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-P72BT46H.js → managed-runtime-bootstrap-KPLGH4UE.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-IYCJDB5K.js → managed-runtime-session-worker-EVKNPK3V.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-ONT4V5ZG.js → managed-runtime-ssh-worker-IA4HZ3PD.js} +1 -1
  155. package/chunks/{mcp-NXCQVE2Y.js → mcp-S67IJLI6.js} +1 -1
  156. package/chunks/{model-call-collection-3DNL45M5.js → model-call-collection-6OGPDTPG.js} +1 -1
  157. package/chunks/{model-configuration-6HRNYBWV.js → model-configuration-6RWVBOQS.js} +1 -1
  158. package/chunks/{modelConfigUtils-SKBN64ZW.js → modelConfigUtils-M3TVVYAO.js} +1 -1
  159. package/chunks/{monitor-7I7Q73UR.js → monitor-ZHOFTN7N.js} +1 -1
  160. package/chunks/{nonInteractiveCli-YLYRJUBE.js → nonInteractiveCli-6SUGPTJ4.js} +1 -1
  161. package/chunks/{nonInteractiveToolExecutor-U2ASWT63.js → nonInteractiveToolExecutor-SAHBGO3A.js} +1 -1
  162. package/chunks/{notebook-edit-WAD7IQCF.js → notebook-edit-ETUOQH6G.js} +1 -1
  163. package/chunks/{omni-POUUDVU3.js → omni-HV2UBGMZ.js} +1 -1
  164. package/chunks/{openaiContentGenerator-L7X6IVPL.js → openaiContentGenerator-RZCG7E4M.js} +1 -1
  165. package/chunks/{openaiResponsesContentGenerator-7XCMFI6P.js → openaiResponsesContentGenerator-X23L5JV3.js} +1 -1
  166. package/chunks/{pidfile-MQQT2ZDA.js → pidfile-26WXQCHG.js} +1 -1
  167. package/chunks/{processUtils-OZLF72NC.js → processUtils-WXLFGNBT.js} +1 -1
  168. package/chunks/{prompt-terminal-ledger-IYUF6SUU.js → prompt-terminal-ledger-EIZZHF4A.js} +1 -1
  169. package/chunks/{qwenContentGenerator-DKH3ILUO.js → qwenContentGenerator-GOY7Y6KH.js} +1 -1
  170. package/chunks/{reactive-degrade-KSNGHMBN.js → reactive-degrade-MNMTTHO5.js} +1 -1
  171. package/chunks/{read-file-VEELW4OQ.js → read-file-OJNGPNTQ.js} +1 -1
  172. package/chunks/{resumeHistoryUtils-4SFDTBXU.js → resumeHistoryUtils-QWOWF4VY.js} +1 -1
  173. package/chunks/{review-QA6HRLVU.js → review-5S24HP2V.js} +1 -1
  174. package/chunks/{ripGrep-4J6ASSE3.js → ripGrep-Y4PY2MQF.js} +1 -1
  175. package/chunks/{run-qwen-serve-EJ67LA5O.js → run-qwen-serve-EOUUDZUK.js} +2 -2
  176. package/chunks/{runtime-6E2FSB5U.js → runtime-ZBPOQX6E.js} +1 -1
  177. package/chunks/{sandboxConfig-4VE4LNRI.js → sandboxConfig-R7KDS3P5.js} +1 -1
  178. package/chunks/{scheduled-tasks-GM5EJMK7.js → scheduled-tasks-Q6V7D6K6.js} +1 -1
  179. package/chunks/{scheduler-HOSVIIOE.js → scheduler-EBQY6BOK.js} +1 -1
  180. package/chunks/{search-memory-HEAQCHIK.js → search-memory-HX6E23JC.js} +1 -1
  181. package/chunks/{send-message-FAQ7XEZ5.js → send-message-OZCCCH2F.js} +1 -1
  182. package/chunks/{serve-VNKPOWSW.js → serve-CMGCI4BK.js} +1 -1
  183. package/chunks/{server-U2XBJLOV.js → server-7LOAKPDN.js} +3 -3
  184. package/chunks/{session-AZGROSFX.js → session-LVQYZSJE.js} +1 -1
  185. package/chunks/{session-attachments-root-6M2ECUNK.js → session-attachments-root-NWG7JOMN.js} +1 -1
  186. package/chunks/{session-execution-engine-selector-PYDVOSJF.js → session-execution-engine-selector-PHH47ZMA.js} +1 -1
  187. package/chunks/{session-pr-refresh-3IS7DLEV.js → session-pr-refresh-5IACZPCY.js} +1 -1
  188. package/chunks/{sessionService-3FWNA4ZB.js → sessionService-7PFAWLHC.js} +1 -1
  189. package/chunks/{settings-VHKT7JJC.js → settings-CPZBOHN5.js} +1 -1
  190. package/chunks/{shell-TYOPVB7H.js → shell-A7NLPS2W.js} +1 -1
  191. package/chunks/{skill-GJQIE5AX.js → skill-VGANGVOD.js} +1 -1
  192. package/chunks/{skill-settings-76NI6SF3.js → skill-settings-TSZO3X6N.js} +1 -1
  193. package/chunks/{spawnChannel-FMSYLDKB.js → spawnChannel-2JQYNQKT.js} +1 -1
  194. package/chunks/{standalone-update-BPZQDQHD.js → standalone-update-QXC3RM6I.js} +1 -1
  195. package/chunks/{start-opentui-ui-X7XYV5N3.js → start-opentui-ui-BKJ4JHVK.js} +1 -1
  196. package/chunks/{startInteractiveUI-UZDF4JUB.js → startInteractiveUI-4QIPR7ZY.js} +1 -1
  197. package/chunks/{team-create-RFZNEF76.js → team-create-5MU6BGXX.js} +1 -1
  198. package/chunks/{team-plan-approval-MGW3JGSC.js → team-plan-approval-NZUJ6FSA.js} +1 -1
  199. package/chunks/{terminal-image-renderer-3UED5GZV.js → terminal-image-renderer-CTMJULJ2.js} +1 -1
  200. package/chunks/{theme-manager-SF6FSSZW.js → theme-manager-6H7GA6QR.js} +1 -1
  201. package/chunks/{tool-call-W2CJR74U.js → tool-call-XG4CAD5X.js} +1 -1
  202. package/chunks/{tool-result-media-XSFON2ZQ.js → tool-result-media-RJ5ONO7R.js} +1 -1
  203. package/chunks/{tool-search-7GY5YTOU.js → tool-search-KBINGEWV.js} +1 -1
  204. package/chunks/{total-session-admission-OATGW6M5.js → total-session-admission-XNWYCO7G.js} +1 -1
  205. package/chunks/{trustedFolders-AM4PSGUB.js → trustedFolders-JT5MOB3A.js} +1 -1
  206. package/chunks/{update-relaunch-YKY52XUT.js → update-relaunch-HXMQI3HO.js} +1 -1
  207. package/chunks/{updateCheck-RKQ5CPZM.js → updateCheck-XWE3TWL5.js} +1 -1
  208. package/chunks/{upload-config-CBT7ARZY.js → upload-config-ET7NRHU7.js} +1 -1
  209. package/chunks/{useAutoAcceptIndicator-Z3YWPUNO.js → useAutoAcceptIndicator-TPMYKNJX.js} +1 -1
  210. package/chunks/{validateNonInterActiveAuth-7CQHU2RF.js → validateNonInterActiveAuth-U52KMEDS.js} +1 -1
  211. package/chunks/{version-N2OB6KWP.js → version-CW4RTJ3H.js} +1 -1
  212. package/chunks/{web-fetch-L5XCBCBA.js → web-fetch-UPMJ3XIZ.js} +1 -1
  213. package/chunks/{web-search-4EHUA3LJ.js → web-search-PXABWQVC.js} +1 -1
  214. package/chunks/{workflow-FGAUAYIP.js → workflow-UQ4V3NBZ.js} +1 -1
  215. package/chunks/{workflow-ancestor-trust-F7RRN6I3.js → workflow-ancestor-trust-QII5KTUJ.js} +1 -1
  216. package/chunks/{workspace-agents-QW4TKC52.js → workspace-agents-Q3KKMDX2.js} +1 -1
  217. package/chunks/{workspace-providers-status-MFSZT3YA.js → workspace-providers-status-3ASB64FB.js} +1 -1
  218. package/chunks/{workspace-registration-store-WQRDSIEI.js → workspace-registration-store-2NPD6U3B.js} +1 -1
  219. package/chunks/{workspace-registry-FXZFRSCH.js → workspace-registry-6QJKRCDR.js} +1 -1
  220. package/chunks/{workspace-runtime-coordinator-LJ5YAT3A.js → workspace-runtime-coordinator-ZXUWDQIB.js} +1 -1
  221. package/chunks/{workspace-service-U632SUWU.js → workspace-service-YPYTYYUN.js} +1 -1
  222. package/chunks/{workspace-skills-status-M7YXM3LF.js → workspace-skills-status-VTFHQ6R7.js} +1 -1
  223. package/chunks/{workspace-trust-reconciler-NLJGGI4K.js → workspace-trust-reconciler-52CZVPKH.js} +1 -1
  224. package/chunks/{write-file-BJCKSXX7.js → write-file-FDBR76G5.js} +1 -1
  225. package/chunks/{zoom-image-TLJPD4DB.js → zoom-image-MYKWCCXO.js} +1 -1
  226. package/cli.js +2 -2
  227. package/execution-worker.js +1 -1
  228. package/export-transcript-document.js +1 -1
  229. package/package.json +4 -4
  230. package/vendor/landlock-run/arm64-linux/qwen-landlock-run +0 -0
  231. package/vendor/landlock-run/x64-linux/qwen-landlock-run +0 -0
  232. package/vendor/ripgrep/arm64-darwin/rg +0 -0
  233. package/vendor/ripgrep/arm64-linux/rg +0 -0
  234. package/vendor/ripgrep/x64-darwin/rg +0 -0
  235. package/vendor/ripgrep/x64-linux/rg +0 -0
  236. package/vendor/tree-sitter/tree-sitter-bash.wasm +0 -0
  237. package/vendor/tree-sitter/tree-sitter.wasm +0 -0
  238. package/web-shell/assets/{PierreFilePreview-D9tbdFw8.js → PierreFilePreview-DGTp45Z4.js} +1 -1
  239. package/web-shell/assets/{SpreadsheetPreview-CeFAk2s-.js → SpreadsheetPreview-DVC_YVei.js} +1 -1
  240. package/web-shell/assets/{WorkspaceFileBrowser-iaURw8SR.js → WorkspaceFileBrowser-DaQNpS06.js} +1 -1
  241. package/web-shell/assets/{abnfDiagram-VCTEODGH-Z4CT1NCF.js → abnfDiagram-VCTEODGH-wJbiOoPK.js} +1 -1
  242. package/web-shell/assets/{agents-route-B7o2Rq-a.js → agents-route-DUhhA1KI.js} +1 -1
  243. package/web-shell/assets/{arc-DcHBdUJQ.js → arc-CvpNMy1d.js} +1 -1
  244. package/web-shell/assets/{architectureDiagram-5GKGNRK7-DRDhEC81.js → architectureDiagram-5GKGNRK7-DIhi3dIz.js} +1 -1
  245. package/web-shell/assets/{blockDiagram-NRAW4CY4-CYRE6WIc.js → blockDiagram-NRAW4CY4-CoeyTlVJ.js} +1 -1
  246. package/web-shell/assets/{c4Diagram-UCG6FXSJ-CIM8N_Sj.js → c4Diagram-UCG6FXSJ-BYoK_I9M.js} +1 -1
  247. package/web-shell/assets/channel-DvtGOCg6.js +1 -0
  248. package/web-shell/assets/{chunk-2Q5K7J3B-Bbfka9Fe.js → chunk-2Q5K7J3B-BeD4GwPg.js} +1 -1
  249. package/web-shell/assets/{chunk-5VM5RSS4-C02zF3RY.js → chunk-5VM5RSS4-BpkJsB_y.js} +1 -1
  250. package/web-shell/assets/{chunk-F27PBJKO-Dn0wRD2F.js → chunk-F27PBJKO-BROEWQ1J.js} +1 -1
  251. package/web-shell/assets/{chunk-G27WJ6UU-Dwpl3l0W.js → chunk-G27WJ6UU-DA8Wtppt.js} +1 -1
  252. package/web-shell/assets/{chunk-JWPE2WC7-sQbzSoTR.js → chunk-JWPE2WC7-GqB-QFh5.js} +1 -1
  253. package/web-shell/assets/{chunk-LCL6LL3I-DNlNDtfr.js → chunk-LCL6LL3I-DIPUwYsX.js} +1 -1
  254. package/web-shell/assets/{chunk-POPQ4Y6H-BOgf1Dl3.js → chunk-POPQ4Y6H-DbnU-jxX.js} +1 -1
  255. package/web-shell/assets/{chunk-SVP7TREG-DOofWP00.js → chunk-SVP7TREG-DvH7bQ-w.js} +1 -1
  256. package/web-shell/assets/{chunk-XXDRQBXY-Bj9FxhWU.js → chunk-XXDRQBXY-DdVWVo3U.js} +1 -1
  257. package/web-shell/assets/classDiagram-DTDB5LWJ-9NR5W1rE.js +1 -0
  258. package/web-shell/assets/classDiagram-v2-JRS7N3AN-9NR5W1rE.js +1 -0
  259. package/web-shell/assets/{cose-bilkent-JH36ORCC-CUlPjyww.js → cose-bilkent-JH36ORCC-JgMKxP9H.js} +1 -1
  260. package/web-shell/assets/{cynefin-OW5HDTMX-5noArzI7.js → cynefin-OW5HDTMX-BVUpNgVm.js} +1 -1
  261. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-DELvTqmf.js → cynefinDiagram-5FMLGOSQ-CxAdk-iS.js} +1 -1
  262. package/web-shell/assets/{dagre-3AP2YEHR-CAL6Z3hL.js → dagre-3AP2YEHR-CvXWkM86.js} +1 -1
  263. package/web-shell/assets/{diagram-S7CK7UJ4-DQC2gaIi.js → diagram-S7CK7UJ4-DD_PS4nm.js} +1 -1
  264. package/web-shell/assets/{diagram-UQ7AKVKN-CkU6M-3R.js → diagram-UQ7AKVKN-EVZkTODD.js} +1 -1
  265. package/web-shell/assets/{diagram-VSXAHHWV-CvHpHwVx.js → diagram-VSXAHHWV-CGZc1pZU.js} +1 -1
  266. package/web-shell/assets/{diagram-VX7I27RA-D9l5F9iB.js → diagram-VX7I27RA-DjNql499.js} +1 -1
  267. package/web-shell/assets/{diagram-Z3DM3KII-DW-VFvYx.js → diagram-Z3DM3KII-CCa0WtmR.js} +1 -1
  268. package/web-shell/assets/{docx-preview-8MQfOGQh.js → docx-preview-DpVElxvj.js} +1 -1
  269. package/web-shell/assets/{ebnfDiagram-PWID7BFC-C0Q71wC_.js → ebnfDiagram-PWID7BFC-W2hoOJZF.js} +1 -1
  270. package/web-shell/assets/{erDiagram-SSCWMZ5O-DWDLRh1S.js → erDiagram-SSCWMZ5O-Dz5NxxEb.js} +1 -1
  271. package/web-shell/assets/{flowDiagram-A5DVABFB-CVzJnl1P.js → flowDiagram-A5DVABFB-BTMAn8b5.js} +1 -1
  272. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-B320pcgR.js → ganttDiagram-EL5Y4UJY-BaFrd5ZY.js} +1 -1
  273. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-Di4uZh-J.js → gitGraphDiagram-WWUBYQGX-IlmdUqRk.js} +1 -1
  274. package/web-shell/assets/{index-Csr8Hx_O.js → index-C2ez0ZjE.js} +1 -1
  275. package/web-shell/assets/{index-C9BecA_H.js → index-Cs-XBNmB.js} +101 -101
  276. package/web-shell/assets/{infoDiagram-RXCK75RN-CbafhxET.js → infoDiagram-RXCK75RN-BHs9kpar.js} +1 -1
  277. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-DrQuIDeR.js → ishikawaDiagram-5VMMS53U-DWCEQ85v.js} +1 -1
  278. package/web-shell/assets/{journeyDiagram-EYS64GPL-BschmjBj.js → journeyDiagram-EYS64GPL-RTDAw9yc.js} +1 -1
  279. package/web-shell/assets/{kanban-definition-3QL26DDD-B7x9BU9N.js → kanban-definition-3QL26DDD-B7Nl9bq6.js} +1 -1
  280. package/web-shell/assets/{layout-BewPaOyO.js → layout-BabjFEb1.js} +1 -1
  281. package/web-shell/assets/{linear-CnLILCVp.js → linear-CZuGjuQd.js} +1 -1
  282. package/web-shell/assets/{mermaid.core-Csj9KPfJ.js → mermaid.core-CK78bIGt.js} +6 -6
  283. package/web-shell/assets/{mindmap-definition-FBJOCRG2-CIGTi5gg.js → mindmap-definition-FBJOCRG2-BbcCi_jP.js} +1 -1
  284. package/web-shell/assets/{pegDiagram-XKGWAZYB-CuWBRQzb.js → pegDiagram-XKGWAZYB-DpLQ7u8i.js} +1 -1
  285. package/web-shell/assets/{pieDiagram-E7YTZNPT-Co5ukXCE.js → pieDiagram-E7YTZNPT-BpWFVtM0.js} +1 -1
  286. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-B0hzjh6o.js → quadrantDiagram-AXDQQJYC-CGzYlaN1.js} +1 -1
  287. package/web-shell/assets/{railroadDiagram-O6MQD6OU-nhkJB0xD.js → railroadDiagram-O6MQD6OU-BNQYW-Zi.js} +1 -1
  288. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-C7NpxjVR.js → requirementDiagram-EFPCY7ZU-C4fCdIDW.js} +1 -1
  289. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CUWlnhZC.js → sankeyDiagram-P5KCCOFB-BvbbAnMA.js} +1 -1
  290. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BoykH0_J.js → sequenceDiagram-WJ2MYXX4-DGXNc6E1.js} +1 -1
  291. package/web-shell/assets/{sizeCapture-X5ZJPWSS-aF-PkSe5.js → sizeCapture-X5ZJPWSS-C4W45Xf5.js} +1 -1
  292. package/web-shell/assets/{stateDiagram-HBIQ2CUA-g5q0b922.js → stateDiagram-HBIQ2CUA-D3q0fen-.js} +1 -1
  293. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-XKoYIi05.js +1 -0
  294. package/web-shell/assets/{swimlanes-XN3QIQJK-BbASszfe.js → swimlanes-XN3QIQJK-D8n-ResR.js} +1 -1
  295. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-C7qJMSzs.js +8 -0
  296. package/web-shell/assets/{timeline-definition-24CTP7MA-AXIV0TJJ.js → timeline-definition-24CTP7MA-Cio4y1mM.js} +1 -1
  297. package/web-shell/assets/{vennDiagram-4TSXK5OY-B-E0rj1h.js → vennDiagram-4TSXK5OY-DVlg0xnc.js} +1 -1
  298. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DiOOYJ2D.js → wardleyDiagram-VM6X3IG4-CgeIsimQ.js} +1 -1
  299. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-De_z7HkS.js → xychartDiagram-S5SC5T6Z-UXjyTLnU.js} +1 -1
  300. package/web-shell/index.html +1 -1
  301. package/web-shell/sw.js +1 -1
  302. package/web-shell/assets/channel-Bwr9aS_E.js +0 -1
  303. package/web-shell/assets/classDiagram-DTDB5LWJ-BmY8Mmyo.js +0 -1
  304. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BmY8Mmyo.js +0 -1
  305. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CTOjUMow.js +0 -1
  306. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bz6ia3oL.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{computeCpuPercent}from"./chunk-APLMCZ35.js";import{resolveRemoteServeToken}from"./chunk-RZMDX7FA.js";import{RUNTIME_STARTUP_CANCELLED_MESSAGE}from"./chunk-UKMS3RLB.js";import{ACCESS_LOG_CONTROLLER_LOCAL,CAPABILITIES_SCHEMA_VERSION,ClientMcpSenderRegistry,HOSTED_CSI_SESSION_STORE_URL_ENV,HOSTED_HARNESS_CAPABILITY_DIGEST_ENV,PathMutexRegistry,SERVE_CAPABILITY_REGISTRY,ServeAppLifecycleController,WorkspaceVoiceCoordinator,acpChildExtraArgs,allowOriginCors,allowOriginMode,bearerAuth,createBridgeFileSystemAdapter,denyBrowserOriginCors,findNonLoopbackHttpOrigin,getAdvertisedServeFeatures,getDeviceFlowRegistry,getRateLimiter,getServeProtocolVersions,hostAllowlist,installRemoteSelfOriginMiddleware,installSelfOriginStripMiddleware,isBrowserAutomationMcpAvailable,isDeepHealthQuery,isLocalPathOpenAvailable,isLocalTerminalAvailable,isManagedScratchChild,isNativeDirectoryPickerAvailable,isSoftwareNetwork,isTrustedLoopbackMode,listLanCandidates,listenerMaxConnections,parseAllowOriginPatterns,parseDaemonStatusDetail,positiveFiniteOrNull,prepareManagedScratchRoot,pushChannelRestoreIssues,recoverBranchWorktreePreparations,resolveAcpHttpEnabled,toDaemonStatusMemoryLimits,validateHostedHarnessProfile}from"./chunk-I3ORWQ2U.js";import{ConversationDirectoryIdentityError,assertExactConversationRootIdentity,createConversationRootIdentity,getConversationDirectoryName,getConversationStagedDirectoryName,inspectConversationDirectoryIdentity,inspectConversationStagedDirectoryIdentity,isSameConversationDirectoryObject,materializeConversationDirectoryIdentity,revalidateConversationRootIdentity}from"./chunk-M7PWCW6A.js";import{DAEMON_DISCOVERY_VERSION,currentPidNamespace,daemonDiscoveryUrl,hostAssignsIpv6Loopback,isOwnInterfaceAddress,removeDaemonDiscovery,writeDaemonDiscovery}from"./chunk-LIEG4N3B.js";import{readSshWorkspace}from"./chunk-R7TNFTT4.js";import{setDeferredRuntimeRequestTiming}from"./chunk-K246IFIW.js";import{normalizeSessionIdForLookup}from"./chunk-LGFF5PJA.js";import"./chunk-M5KJJE2X.js";import"./chunk-XQGKNWG2.js";import{resolveWebShellDir}from"./chunk-N6DRGTL5.js";import{resolveSessionRestoreTimeoutMs}from"./chunk-ASTRUET5.js";import{DEFAULT_RING_SIZE}from"./chunk-BWQ5AIEA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{resolveChannelCwd}from"./chunk-HM4P6X3W.js";import{ConversationRuntimeOwnershipError,LIVE_HOST_PROTOCOL_VERSION}from"./chunk-QSHWWIZT.js";import{formatMemoryBudgetStderr,resolveDaemonMemoryBudget,serveJournalGrowthPoolMb}from"./chunk-2QYDBHYZ.js";import{assertChannelControlWorkspaceCapacity}from"./chunk-HVVB5CJL.js";import{LOAD_REPLAY_META_KEY}from"./chunk-WBDNGVHU.js";import"./chunk-VTZZXEWA.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{consumeServeFastPathRejectedLoaderKeys,loadServeFastPathSettings,preResolveServeFastPathHomeEnvOverrides}from"./chunk-UDVB5BOH.js";import"./chunk-EKGLTLET.js";import{resolveMaxRegisteredWorkspaces,resolveWorkspaceInputs,workspaceRegistrationId}from"./chunk-DJRFEZBY.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{ExtraCaInspectionError,loadableCertificates}from"./chunk-YHW42MTP.js";import"./chunk-B75LYOXZ.js";import{ChannelWebhookEnqueueError}from"./chunk-AVJJ62OC.js";import{QWEN_SERVER_TOKEN_ENV}from"./chunk-P4Y2SYO4.js";import{normalizeWorkerDiagnostic,sanitizeWorkerDiagnostic}from"./chunk-3R3Q6X2J.js";import{channelSelectionNames,normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{ChannelDeliveryError,isChannelDeliveryError}from"./chunk-O6ZQAVRG.js";import"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,EXTERNAL_TOOL_GUARD_TOKEN_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV}from"./chunk-NIEO2TBE.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{sanitizeLogText}from"./chunk-YUORVHMI.js";import"./chunk-WSOEJTOC.js";import{MAX_CHANNEL_CONTROL_WORKSPACES}from"./chunk-E4UMXDOZ.js";import"./chunk-LMUSSYJH.js";import{getEnvironmentBeforeLoad}from"./chunk-PKK2D2W4.js";import"./chunk-6S5XOXJ2.js";import{formatHostForAuthority,isLoopbackAddress,isLoopbackBind}from"./chunk-3SHHYK7S.js";import{acquireInheritedLoaderEnvScrub,clearLoaderKeyRejectionReporterIfCurrent,scrubInheritedLoaderEnv,setLoaderKeyRejectionReporter}from"./chunk-CVMMNPLX.js";import{require_express}from"./chunk-6SOKP7IN.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import"./chunk-IEWZIDC6.js";import{getCliVersion}from"./chunk-OAPA66DR.js";import"./chunk-O4EDHV64.js";import{InvalidExecutionSandboxConfigError,assertExecutionSandboxSupported,readOperatorSandboxSettings}from"./chunk-DOLUT3XC.js";import{getGlobalQwenDirLite,resolveConfigPathLite}from"./chunk-PTHIQ7ZN.js";import"./chunk-EIPLDYEY.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import"./chunk-QS2ZMQIS.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import"./chunk-MD3ZEOBX.js";import"./chunk-S6JEITQQ.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OGI5HG6N.js";import"./chunk-T7CHK6C2.js";import"./chunk-VZDZ34KK.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-PHIPLV2I.js";import"./chunk-LLX4BCWK.js";import"./chunk-QXQGUM3Y.js";import"./chunk-BMSATZXW.js";import"./chunk-5LZ2DPLH.js";import"./chunk-EBMCWXGZ.js";import"./chunk-YGLM5XPP.js";import"./chunk-XWEXQT3X.js";import"./chunk-TL3SF2GA.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import"./chunk-LFKUPU57.js";import"./chunk-LG4NL2M7.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-JU2HHQR5.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7U7CWMP7.js";import"./chunk-SLD7H2FA.js";import"./chunk-BMHYEQTI.js";import{finalizeStartupProfile,profileCheckpoint}from"./chunk-H4XFFVZ2.js";import{normalizeServeFastPathArgv}from"./chunk-X7QN6R6K.js";import{writeStderrLine,writeStdoutLine,writeStdoutLineSafe}from"./chunk-SLPJ4OII.js";import"./chunk-4YLXNRRH.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import"./chunk-JAUJI56S.js";import{TraceFlags,init_esm,isSpanContextValid,trace}from"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_express=__toESM(require_express(),1);import{X509Certificate,createHash as createHash2,timingSafeEqual}from"node:crypto";import{execFile as execFile2}from"node:child_process";import{lookup}from"node:dns/promises";import*as fs from"node:fs";import{createServer}from"node:http";import*as https from"node:https";import{isIP}from"node:net";import*as path from"node:path";import*as os2 from"node:os";import{monitorEventLoopDelay,performance as performance2}from"node:perf_hooks";init_esbuild_shims();init_esbuild_shims();var MIN_CHILD_HEAP_MB=512;var MAX_MODELED_ACP_CHILDREN=25;function createChildHeapPolicy(options){const{budget,mode}=options;let refusals=0;const admissible=Math.min(Math.floor(budget.childPoolMb/MIN_CHILD_HEAP_MB),MAX_MODELED_ACP_CHILDREN);const rawCeilingMb=admissible>0?Math.min(Math.floor(budget.childPoolMb/admissible),budget.legacyChildCeilingMb):null;const modelable=rawCeilingMb!==null&&rawCeilingMb>=MIN_CHILD_HEAP_MB;const maxConcurrentChildren=modelable?admissible:0;const perChildCeilingMb=modelable?rawCeilingMb:null;if((mode==="admit"||mode==="enforce")&&maxConcurrentChildren===0){throw new TypeError("ACP admission requires a memory budget that models at least one child.")}return{decide(concurrentChildren){if(mode==="off")return{refuse:false};const refuse=concurrentChildren>maxConcurrentChildren;if(refuse)refusals+=1;return{refuse}},snapshot(){const modeled=mode!=="off";return{mode,childPoolMb:budget.childPoolMb,minChildHeapMb:MIN_CHILD_HEAP_MB,maxConcurrentChildren:modeled?maxConcurrentChildren:null,perChildCeilingMb:modeled?perChildCeilingMb:null,refusals}}}}__name(createChildHeapPolicy,"createChildHeapPolicy");init_esbuild_shims();var import_semver=__toESM(require_semver(),1);import{execFile}from"node:child_process";import{access,readFile}from"node:fs/promises";import{constants}from"node:fs";import os from"node:os";import{isAbsolute}from"node:path";import{promisify}from"node:util";function createDaemonUpdateRestarter(options){const execve=process.execve?.bind(process);const argv=normalizeServeFastPathArgv(options.argv);if(!execve||["win32","os400"].includes(os.platform())||process.versions["bun"]||argv[0]!=="serve"||argv.includes("--")){return void 0}const env={...options.env};for(const key of["QWEN_CODE_MANAGED_NPM_PIN","QWEN_CODE_STARTUP_VERSION","QWEN_CODE_RELAUNCH_ARGS","QWEN_CODE_MANAGED_NPM_UPDATE_VERSION","QWEN_CODE_LAUNCHER_PATH","CLI_VERSION"]){delete env[key]}if(options.token)env["QWEN_SERVER_TOKEN"]=options.token;else delete env["QWEN_SERVER_TOKEN"];if(options.externalToolGuardToken){env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]=options.externalToolGuardToken}const args=[];for(let index=0;index<argv.length;index++){const arg=argv[index];const name=arg.split("=",1)[0];if(name==="--port"||name==="--token"){if(!arg.includes("="))index++;continue}if(/^--(?:no-)?open(?:-with-auth)?(?:=|$)/.test(arg)){if(!arg.includes("=")&&/^(?:true|false)$/.test(argv[index+1]??"")){index++}continue}args.push(arg)}const execArgv=[...process.execArgv];return async launcher=>{if(!isAbsolute(launcher))throw new Error("Update launcher must be absolute");const npmLauncher=launcher.endsWith(".js");await access(launcher,npmLauncher?constants.R_OK:constants.X_OK);if(!npmLauncher){const[header]=(await readFile(launcher,"utf8")).split("\n",1);if(header!=="#!/usr/bin/env sh"){throw new Error("Unsupported standalone update launcher")}const{stdout}=await promisify(execFile)(launcher,["--version"],{env,timeout:1e4});if(!import_semver.default.valid(stdout.trim())){throw new Error("Updated launcher did not report a valid version")}}const cliArgs=[...args,"--port",String(options.getPort())];await options.close();if(npmLauncher){execve(process.execPath,[process.execPath,...execArgv,launcher,...cliArgs],env)}else{execve(launcher,[launcher,...cliArgs],env)}}}__name(createDaemonUpdateRestarter,"createDaemonUpdateRestarter");init_esbuild_shims();import{networkInterfaces}from"node:os";function isUlaIpv6(address){return/^(?:fc|fd)/iu.test(address)}__name(isUlaIpv6,"isUlaIpv6");function isLinkLocalIpv4(address){return address.startsWith("169.254.")}__name(isLinkLocalIpv4,"isLinkLocalIpv4");function quickstartPrintMode(boundAddress,generated){if(!isLoopbackAddress(boundAddress))return"full";return generated?"token-only":"silent"}__name(quickstartPrintMode,"quickstartPrintMode");function tokenQrNoEffectReason(input){if(!input.requested)return void 0;if(!input.webShellMounted)return"qwen serve: --token-qr / serve.tokenQr has no effect because the Web Shell is not mounted.";if(quickstartPrintMode(input.boundAddress,input.generated)!=="full")return"qwen serve: --token-qr / serve.tokenQr has no effect on this bind: a loopback listener prints no quickstart QR.";return void 0}__name(tokenQrNoEffectReason,"tokenQrNoEffectReason");function remoteQuickstartEntries(bind,boundAddress,port,tls,interfaces){const scheme=tls?"https":"http";const url=__name(host=>`${scheme}://${formatHostForAuthority(host)}:${port}`,"url");const bound=boundAddress.trim().toLowerCase();const ipv4Wildcard=bound==="0.0.0.0"||bound==="::ffff:0.0.0.0";if(!ipv4Wildcard&&bound!=="::"){if(bind.trim().includes("%"))return[];return[{label:"Address",url:url(bind),address:bind}]}const localAddress=!ipv4Wildcard&&hostAssignsIpv6Loopback(interfaces)?"::1":"127.0.0.1";const addresses=[{label:"Local",url:url(localAddress),address:localAddress}];for(const candidate of listLanCandidates(interfaces)){addresses.push({label:`Network (${candidate.interfaceName})`,url:url(candidate.address),address:candidate.address})}if(!ipv4Wildcard){for(const[name,entries]of Object.entries(interfaces).sort()){if(isSoftwareNetwork(name))continue;for(const entry of entries??[]){if(entry.internal||entry.family!=="IPv6")continue;if(entry.address.includes("%")||!isUlaIpv6(entry.address))continue;addresses.push({label:`Network (${name})`,url:url(entry.address),address:entry.address})}}}return addresses}__name(remoteQuickstartEntries,"remoteQuickstartEntries");async function printRemoteQuickstart(input){try{const mode=quickstartPrintMode(input.boundAddress,input.generated);if(mode==="silent")return;if(mode==="token-only"){writeStdoutLineSafe(`Generated bearer token (secret; changes on restart): ${input.token}`);writeStdoutLineSafe("The listener bound loopback, so no network address or QR is printed; local clients must present this bearer.");return}const addresses=remoteQuickstartEntries(input.bind,input.boundAddress,input.port,input.tls,input.interfaces??networkInterfaces());for(const address of addresses)writeStdoutLineSafe(`${address.label}: ${address.url}`);if(input.generated){writeStdoutLineSafe(`Generated bearer token (secret; changes on restart): ${input.token}`)}if(!input.tls)writeStdoutLineSafe("HTTP is unencrypted. Use the existing TLS options for encrypted remote access.");if(!input.web)return;const candidate=addresses.find(address=>address.label!=="Local"&&!isLinkLocalIpv4(address.address))??addresses.find(address=>address.label!=="Local");if(!candidate){writeStdoutLineSafe("QR unavailable; enter the bearer token at the daemon address.");return}const suppressTokenQr=input.tokenQrMode==="veto"||!input.generated&&!process.stdout.isTTY&&input.tokenQrMode!=="force";try{const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");qrcode.generate(suppressTokenQr?candidate.url:`${candidate.url}/#token=${encodeURIComponent(input.token)}`,{small:true},code=>{if(suppressTokenQr)writeStdoutLineSafe(input.tokenQrMode==="veto"?"Token-bearing QR suppressed: the token QR was explicitly disabled for this run.":"Token-bearing QR suppressed: stable operator token with non-interactive stdout. Pass --token-qr to print it anyway.");writeStdoutLineSafe(`Scan to open Web Shell: ${candidate.url} (${candidate.label})`);writeStdoutLineSafe(suppressTokenQr?"Address-only QR: the Web Shell will ask for the bearer token.":"SECRET QR: grants daemon access. Do not share.");writeStdoutLineSafe(code.trimEnd())})}catch{writeStdoutLineSafe("QR unavailable; enter the bearer token at the daemon address.")}}catch{}}__name(printRemoteQuickstart,"printRemoteQuickstart");init_esbuild_shims();var DEFAULT_PERMISSION_AUDIT_RING_SIZE=512;function takeLast(arr,limit,methodName){if(limit===void 0)return arr.slice();if(!Number.isInteger(limit)||limit<0){throw new Error(`${methodName} limit must be a non-negative integer; got ${String(limit)}`)}return arr.slice(Math.max(0,arr.length-limit))}__name(takeLast,"takeLast");var PermissionAuditRing=class{static{__name(this,"PermissionAuditRing")}buf=[];cap;constructor(capacity=DEFAULT_PERMISSION_AUDIT_RING_SIZE){if(!Number.isInteger(capacity)||capacity<1){throw new Error(`PermissionAuditRing capacity must be a positive integer; got ${String(capacity)}`)}this.cap=capacity}push(entry){this.buf.push(entry);while(this.buf.length>this.cap)this.buf.shift()}snapshot(limit){return takeLast(this.buf,limit,"PermissionAuditRing.snapshot")}snapshotForSession(sessionId,limit){return takeLast(this.buf.filter(e=>e.sessionId===sessionId),limit,"PermissionAuditRing.snapshotForSession")}get size(){return this.buf.length}get capacity(){return this.cap}};function createPermissionAuditPublisher(deps){const{ring}=deps;const now=deps.now??(()=>Date.now());return{recordRequested(record,policy,votersAtIssue){ring.push({kind:"permission.requested",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,originatorClientId:record.originatorClientId,policy,votersAtIssue:Array.from(votersAtIssue),issuedAtMs:record.issuedAtMs,allowedOptionIds:Array.from(record.allowedOptionIds)})},recordVoted(record,vote,outcome){ring.push({kind:"permission.voted",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,clientId:vote.clientId,optionId:vote.optionId,fromLoopback:vote.fromLoopback,receivedAtMs:vote.receivedAtMs,outcome})},recordForbidden(record,vote,reason){ring.push({kind:"permission.forbidden",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,clientId:vote.clientId,optionId:vote.optionId,fromLoopback:vote.fromLoopback,reason})},recordResolved(record,resolution,decisionReason){ring.push({kind:"permission.resolved",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,resolution,decisionReason})},recordTimeout(record){ring.push({kind:"permission.timeout",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,issuedAtMs:record.issuedAtMs})}}}__name(createPermissionAuditPublisher,"createPermissionAuditPublisher");init_esbuild_shims();init_esm();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as nodeFs from"node:fs";import*as nodePath from"node:path";import*as crypto from"node:crypto";import{performance}from"node:perf_hooks";var FIXED_CTX_ORDER=["route","sessionId","clientId","childPid","channelId"];var FIXED_CTX_SET=new Set(FIXED_CTX_ORDER);var RESERVED_TRACE_CTX_KEYS=new Set(["trace_id","span_id"]);var ISSUE_ORDER=["init_failed","rotation_failed","retention_failed","queue_overflow","write_failed","lease_compromised"];var DEFAULT_POLICY={maxBytes:10*1024*1024,maxArchives:4,maxRecordBytes:256*1024,maxPendingBytes:4*1024*1024,stableAcquireBudgetMs:1e3,maintenanceAcquireBudgetMs:250,lockStaleMs:6e4,lockUpdateMs:1e4,rotationRetryIntervalMs:6e4,closeDrainBudgetMs:2e3};var ARCHIVE_RE=/^daemon-(\d{12})-(\d{8}T\d{9}Z)-([0-9a-f]{8})\.log$/;var FALLBACK_DIR_RE=/^run-[0-9a-f]{32}$/;var ARCHIVE_NAME_ATTEMPTS=3;var FILE_MODE=384;var DIRECTORY_MODE=448;function renderCtxValue(value){const s=String(value);return/[\s=]/.test(s)?JSON.stringify(s):s}__name(renderCtxValue,"renderCtxValue");function renderCtx(ctx){if(!ctx)return"";const parts=[];for(const key of FIXED_CTX_ORDER){const v=ctx[key];if(v!==void 0&&v!==null){parts.push(`${key}=${String(v)}`)}}const extraKeys=Object.keys(ctx).filter(key=>!FIXED_CTX_SET.has(key)&&!RESERVED_TRACE_CTX_KEYS.has(key)&&ctx[key]!==void 0&&ctx[key]!==null).sort();for(const key of extraKeys){parts.push(`${key}=${renderCtxValue(ctx[key])}`)}return parts.length>0?parts.join(" ")+" ":""}__name(renderCtx,"renderCtx");function getActiveTraceContext(){try{const span=trace.getActiveSpan();if(!span?.isRecording())return void 0;const spanContext=span.spanContext();if(!isSpanContextValid(spanContext)||(spanContext.traceFlags&TraceFlags.SAMPLED)===0){return void 0}return{traceId:spanContext.traceId,spanId:spanContext.spanId}}catch{return void 0}}__name(getActiveTraceContext,"getActiveTraceContext");function renderTraceContext(traceContext){return traceContext?`[trace_id=${traceContext.traceId} span_id=${traceContext.spanId}] `:""}__name(renderTraceContext,"renderTraceContext");function renderErr(err){if(!err)return"";const body=err.stack??`${err.name??"Error"}: ${err.message}`;return body.split("\n").map(line=>` ${line}`).join("\n")+"\n"}__name(renderErr,"renderErr");function formatDaemonLogLine(args){const ts=args.now.toISOString();const traceStr=renderTraceContext(args.traceContext);const ctxStr=renderCtx(args.ctx);return`${ts} [${args.level}] [DAEMON] ${traceStr}${ctxStr}${args.message}
3
+ import{computeCpuPercent}from"./chunk-APLMCZ35.js";import{resolveRemoteServeToken}from"./chunk-RZMDX7FA.js";import{RUNTIME_STARTUP_CANCELLED_MESSAGE}from"./chunk-UKMS3RLB.js";import{ACCESS_LOG_CONTROLLER_LOCAL,CAPABILITIES_SCHEMA_VERSION,ClientMcpSenderRegistry,HOSTED_CSI_SESSION_STORE_URL_ENV,HOSTED_HARNESS_CAPABILITY_DIGEST_ENV,PathMutexRegistry,SERVE_CAPABILITY_REGISTRY,ServeAppLifecycleController,WorkspaceVoiceCoordinator,acpChildExtraArgs,allowOriginCors,allowOriginMode,bearerAuth,createBridgeFileSystemAdapter,denyBrowserOriginCors,findNonLoopbackHttpOrigin,getAdvertisedServeFeatures,getDeviceFlowRegistry,getRateLimiter,getServeProtocolVersions,hostAllowlist,installRemoteSelfOriginMiddleware,installSelfOriginStripMiddleware,isBrowserAutomationMcpAvailable,isDeepHealthQuery,isLocalPathOpenAvailable,isLocalTerminalAvailable,isManagedScratchChild,isNativeDirectoryPickerAvailable,isSoftwareNetwork,isTrustedLoopbackMode,listLanCandidates,listenerMaxConnections,parseAllowOriginPatterns,parseDaemonStatusDetail,positiveFiniteOrNull,prepareManagedScratchRoot,pushChannelRestoreIssues,recoverBranchWorktreePreparations,resolveAcpHttpEnabled,toDaemonStatusMemoryLimits,validateHostedHarnessProfile}from"./chunk-UDGDEIBB.js";import{ConversationDirectoryIdentityError,assertExactConversationRootIdentity,createConversationRootIdentity,getConversationDirectoryName,getConversationStagedDirectoryName,inspectConversationDirectoryIdentity,inspectConversationStagedDirectoryIdentity,isSameConversationDirectoryObject,materializeConversationDirectoryIdentity,revalidateConversationRootIdentity}from"./chunk-M7PWCW6A.js";import{DAEMON_DISCOVERY_VERSION,currentPidNamespace,daemonDiscoveryUrl,hostAssignsIpv6Loopback,isOwnInterfaceAddress,removeDaemonDiscovery,writeDaemonDiscovery}from"./chunk-LIEG4N3B.js";import{readSshWorkspace}from"./chunk-R7TNFTT4.js";import{setDeferredRuntimeRequestTiming}from"./chunk-K246IFIW.js";import{normalizeSessionIdForLookup}from"./chunk-LGFF5PJA.js";import"./chunk-M5KJJE2X.js";import"./chunk-XQGKNWG2.js";import{resolveWebShellDir}from"./chunk-N6DRGTL5.js";import{resolveSessionRestoreTimeoutMs}from"./chunk-ASTRUET5.js";import{DEFAULT_RING_SIZE}from"./chunk-BWQ5AIEA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeCompactedReplayMaxBytes,normalizeMaxJournalBytes,normalizeMaxJournalEvents}from"./chunk-WDR5XP3Y.js";import{resolveChannelCwd}from"./chunk-HM4P6X3W.js";import{ConversationRuntimeOwnershipError,LIVE_HOST_PROTOCOL_VERSION}from"./chunk-QSHWWIZT.js";import{formatMemoryBudgetStderr,resolveDaemonMemoryBudget,serveJournalGrowthPoolMb}from"./chunk-2QYDBHYZ.js";import{assertChannelControlWorkspaceCapacity}from"./chunk-HVVB5CJL.js";import{LOAD_REPLAY_META_KEY}from"./chunk-WBDNGVHU.js";import"./chunk-VTZZXEWA.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{consumeServeFastPathRejectedLoaderKeys,loadServeFastPathSettings,preResolveServeFastPathHomeEnvOverrides}from"./chunk-UDVB5BOH.js";import"./chunk-EKGLTLET.js";import{resolveMaxRegisteredWorkspaces,resolveWorkspaceInputs,workspaceRegistrationId}from"./chunk-DSYKB77N.js";import{canonicalizeWorkspace,translateAndCheckAbsoluteWorkspacePath}from"./chunk-L5UULTGF.js";import{ExtraCaInspectionError,loadableCertificates}from"./chunk-YHW42MTP.js";import"./chunk-B75LYOXZ.js";import{ChannelWebhookEnqueueError}from"./chunk-AVJJ62OC.js";import{QWEN_SERVER_TOKEN_ENV}from"./chunk-P4Y2SYO4.js";import{normalizeWorkerDiagnostic,sanitizeWorkerDiagnostic}from"./chunk-3R3Q6X2J.js";import{channelSelectionNames,normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{ChannelDeliveryError,isChannelDeliveryError}from"./chunk-O6ZQAVRG.js";import"./chunk-3KZHPZVZ.js";import{EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE,EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,EXTERNAL_TOOL_GUARD_TOKEN_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_ENV,PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV}from"./chunk-NIEO2TBE.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{sanitizeLogText}from"./chunk-YUORVHMI.js";import"./chunk-WSOEJTOC.js";import{MAX_CHANNEL_CONTROL_WORKSPACES}from"./chunk-E4UMXDOZ.js";import"./chunk-LMUSSYJH.js";import{getEnvironmentBeforeLoad}from"./chunk-PKK2D2W4.js";import"./chunk-6S5XOXJ2.js";import{formatHostForAuthority,isLoopbackAddress,isLoopbackBind}from"./chunk-3SHHYK7S.js";import{acquireInheritedLoaderEnvScrub,clearLoaderKeyRejectionReporterIfCurrent,scrubInheritedLoaderEnv,setLoaderKeyRejectionReporter}from"./chunk-CVMMNPLX.js";import{require_express}from"./chunk-6SOKP7IN.js";import"./chunk-ELUOCI74.js";import"./chunk-IS7CHVXD.js";import"./chunk-IEWZIDC6.js";import{getCliVersion}from"./chunk-BQQBFDBY.js";import"./chunk-O4EDHV64.js";import{InvalidExecutionSandboxConfigError,assertExecutionSandboxSupported,readOperatorSandboxSettings}from"./chunk-DOLUT3XC.js";import{getGlobalQwenDirLite,resolveConfigPathLite}from"./chunk-PTHIQ7ZN.js";import"./chunk-EIPLDYEY.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import"./chunk-QS2ZMQIS.js";import{PRIVATE_CONVERSATIONS_RUNTIME_ENABLE,PRIVATE_CONVERSATIONS_RUNTIME_ENV}from"./chunk-S7IKHQ6I.js";import"./chunk-MD3ZEOBX.js";import"./chunk-S6JEITQQ.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OGI5HG6N.js";import"./chunk-T7CHK6C2.js";import"./chunk-VZDZ34KK.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-PHIPLV2I.js";import"./chunk-LLX4BCWK.js";import"./chunk-QXQGUM3Y.js";import"./chunk-BMSATZXW.js";import"./chunk-5LZ2DPLH.js";import"./chunk-EBMCWXGZ.js";import"./chunk-YGLM5XPP.js";import"./chunk-XWEXQT3X.js";import"./chunk-TL3SF2GA.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import"./chunk-LFKUPU57.js";import"./chunk-LG4NL2M7.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-JU2HHQR5.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7U7CWMP7.js";import"./chunk-SLD7H2FA.js";import"./chunk-BMHYEQTI.js";import{finalizeStartupProfile,profileCheckpoint}from"./chunk-H4XFFVZ2.js";import{normalizeServeFastPathArgv}from"./chunk-X7QN6R6K.js";import{writeStderrLine,writeStdoutLine,writeStdoutLineSafe}from"./chunk-SLPJ4OII.js";import"./chunk-4YLXNRRH.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-TM6ZCBR7.js";import"./chunk-I6S7NGX3.js";import"./chunk-JAUJI56S.js";import{TraceFlags,init_esm,isSpanContextValid,trace}from"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_express=__toESM(require_express(),1);import{X509Certificate,createHash as createHash2,timingSafeEqual}from"node:crypto";import{execFile as execFile2}from"node:child_process";import{lookup}from"node:dns/promises";import*as fs from"node:fs";import{createServer}from"node:http";import*as https from"node:https";import{isIP}from"node:net";import*as path from"node:path";import*as os2 from"node:os";import{monitorEventLoopDelay,performance as performance2}from"node:perf_hooks";init_esbuild_shims();init_esbuild_shims();var MIN_CHILD_HEAP_MB=512;var MAX_MODELED_ACP_CHILDREN=25;function createChildHeapPolicy(options){const{budget,mode}=options;let refusals=0;const admissible=Math.min(Math.floor(budget.childPoolMb/MIN_CHILD_HEAP_MB),MAX_MODELED_ACP_CHILDREN);const rawCeilingMb=admissible>0?Math.min(Math.floor(budget.childPoolMb/admissible),budget.legacyChildCeilingMb):null;const modelable=rawCeilingMb!==null&&rawCeilingMb>=MIN_CHILD_HEAP_MB;const maxConcurrentChildren=modelable?admissible:0;const perChildCeilingMb=modelable?rawCeilingMb:null;if((mode==="admit"||mode==="enforce")&&maxConcurrentChildren===0){throw new TypeError("ACP admission requires a memory budget that models at least one child.")}return{decide(concurrentChildren){if(mode==="off")return{refuse:false};const refuse=concurrentChildren>maxConcurrentChildren;if(refuse)refusals+=1;return{refuse}},snapshot(){const modeled=mode!=="off";return{mode,childPoolMb:budget.childPoolMb,minChildHeapMb:MIN_CHILD_HEAP_MB,maxConcurrentChildren:modeled?maxConcurrentChildren:null,perChildCeilingMb:modeled?perChildCeilingMb:null,refusals}}}}__name(createChildHeapPolicy,"createChildHeapPolicy");init_esbuild_shims();var import_semver=__toESM(require_semver(),1);import{execFile}from"node:child_process";import{access,readFile}from"node:fs/promises";import{constants}from"node:fs";import os from"node:os";import{isAbsolute}from"node:path";import{promisify}from"node:util";function createDaemonUpdateRestarter(options){const execve=process.execve?.bind(process);const argv=normalizeServeFastPathArgv(options.argv);if(!execve||["win32","os400"].includes(os.platform())||process.versions["bun"]||argv[0]!=="serve"||argv.includes("--")){return void 0}const env={...options.env};for(const key of["QWEN_CODE_MANAGED_NPM_PIN","QWEN_CODE_STARTUP_VERSION","QWEN_CODE_RELAUNCH_ARGS","QWEN_CODE_MANAGED_NPM_UPDATE_VERSION","QWEN_CODE_LAUNCHER_PATH","CLI_VERSION"]){delete env[key]}if(options.token)env["QWEN_SERVER_TOKEN"]=options.token;else delete env["QWEN_SERVER_TOKEN"];if(options.externalToolGuardToken){env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]=options.externalToolGuardToken}const args=[];for(let index=0;index<argv.length;index++){const arg=argv[index];const name=arg.split("=",1)[0];if(name==="--port"||name==="--token"){if(!arg.includes("="))index++;continue}if(/^--(?:no-)?open(?:-with-auth)?(?:=|$)/.test(arg)){if(!arg.includes("=")&&/^(?:true|false)$/.test(argv[index+1]??"")){index++}continue}args.push(arg)}const execArgv=[...process.execArgv];return async launcher=>{if(!isAbsolute(launcher))throw new Error("Update launcher must be absolute");const npmLauncher=launcher.endsWith(".js");await access(launcher,npmLauncher?constants.R_OK:constants.X_OK);if(!npmLauncher){const[header]=(await readFile(launcher,"utf8")).split("\n",1);if(header!=="#!/usr/bin/env sh"){throw new Error("Unsupported standalone update launcher")}const{stdout}=await promisify(execFile)(launcher,["--version"],{env,timeout:1e4});if(!import_semver.default.valid(stdout.trim())){throw new Error("Updated launcher did not report a valid version")}}const cliArgs=[...args,"--port",String(options.getPort())];await options.close();if(npmLauncher){execve(process.execPath,[process.execPath,...execArgv,launcher,...cliArgs],env)}else{execve(launcher,[launcher,...cliArgs],env)}}}__name(createDaemonUpdateRestarter,"createDaemonUpdateRestarter");init_esbuild_shims();import{networkInterfaces}from"node:os";function isUlaIpv6(address){return/^(?:fc|fd)/iu.test(address)}__name(isUlaIpv6,"isUlaIpv6");function isLinkLocalIpv4(address){return address.startsWith("169.254.")}__name(isLinkLocalIpv4,"isLinkLocalIpv4");function quickstartPrintMode(boundAddress,generated){if(!isLoopbackAddress(boundAddress))return"full";return generated?"token-only":"silent"}__name(quickstartPrintMode,"quickstartPrintMode");function tokenQrNoEffectReason(input){if(!input.requested)return void 0;if(!input.webShellMounted)return"qwen serve: --token-qr / serve.tokenQr has no effect because the Web Shell is not mounted.";if(quickstartPrintMode(input.boundAddress,input.generated)!=="full")return"qwen serve: --token-qr / serve.tokenQr has no effect on this bind: a loopback listener prints no quickstart QR.";return void 0}__name(tokenQrNoEffectReason,"tokenQrNoEffectReason");function remoteQuickstartEntries(bind,boundAddress,port,tls,interfaces){const scheme=tls?"https":"http";const url=__name(host=>`${scheme}://${formatHostForAuthority(host)}:${port}`,"url");const bound=boundAddress.trim().toLowerCase();const ipv4Wildcard=bound==="0.0.0.0"||bound==="::ffff:0.0.0.0";if(!ipv4Wildcard&&bound!=="::"){if(bind.trim().includes("%"))return[];return[{label:"Address",url:url(bind),address:bind}]}const localAddress=!ipv4Wildcard&&hostAssignsIpv6Loopback(interfaces)?"::1":"127.0.0.1";const addresses=[{label:"Local",url:url(localAddress),address:localAddress}];for(const candidate of listLanCandidates(interfaces)){addresses.push({label:`Network (${candidate.interfaceName})`,url:url(candidate.address),address:candidate.address})}if(!ipv4Wildcard){for(const[name,entries]of Object.entries(interfaces).sort()){if(isSoftwareNetwork(name))continue;for(const entry of entries??[]){if(entry.internal||entry.family!=="IPv6")continue;if(entry.address.includes("%")||!isUlaIpv6(entry.address))continue;addresses.push({label:`Network (${name})`,url:url(entry.address),address:entry.address})}}}return addresses}__name(remoteQuickstartEntries,"remoteQuickstartEntries");async function printRemoteQuickstart(input){try{const mode=quickstartPrintMode(input.boundAddress,input.generated);if(mode==="silent")return;if(mode==="token-only"){writeStdoutLineSafe(`Generated bearer token (secret; changes on restart): ${input.token}`);writeStdoutLineSafe("The listener bound loopback, so no network address or QR is printed; local clients must present this bearer.");return}const addresses=remoteQuickstartEntries(input.bind,input.boundAddress,input.port,input.tls,input.interfaces??networkInterfaces());for(const address of addresses)writeStdoutLineSafe(`${address.label}: ${address.url}`);if(input.generated){writeStdoutLineSafe(`Generated bearer token (secret; changes on restart): ${input.token}`)}if(!input.tls)writeStdoutLineSafe("HTTP is unencrypted. Use the existing TLS options for encrypted remote access.");if(!input.web)return;const candidate=addresses.find(address=>address.label!=="Local"&&!isLinkLocalIpv4(address.address))??addresses.find(address=>address.label!=="Local");if(!candidate){writeStdoutLineSafe("QR unavailable; enter the bearer token at the daemon address.");return}const suppressTokenQr=input.tokenQrMode==="veto"||!input.generated&&!process.stdout.isTTY&&input.tokenQrMode!=="force";try{const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");qrcode.generate(suppressTokenQr?candidate.url:`${candidate.url}/#token=${encodeURIComponent(input.token)}`,{small:true},code=>{if(suppressTokenQr)writeStdoutLineSafe(input.tokenQrMode==="veto"?"Token-bearing QR suppressed: the token QR was explicitly disabled for this run.":"Token-bearing QR suppressed: stable operator token with non-interactive stdout. Pass --token-qr to print it anyway.");writeStdoutLineSafe(`Scan to open Web Shell: ${candidate.url} (${candidate.label})`);writeStdoutLineSafe(suppressTokenQr?"Address-only QR: the Web Shell will ask for the bearer token.":"SECRET QR: grants daemon access. Do not share.");writeStdoutLineSafe(code.trimEnd())})}catch{writeStdoutLineSafe("QR unavailable; enter the bearer token at the daemon address.")}}catch{}}__name(printRemoteQuickstart,"printRemoteQuickstart");init_esbuild_shims();var DEFAULT_PERMISSION_AUDIT_RING_SIZE=512;function takeLast(arr,limit,methodName){if(limit===void 0)return arr.slice();if(!Number.isInteger(limit)||limit<0){throw new Error(`${methodName} limit must be a non-negative integer; got ${String(limit)}`)}return arr.slice(Math.max(0,arr.length-limit))}__name(takeLast,"takeLast");var PermissionAuditRing=class{static{__name(this,"PermissionAuditRing")}buf=[];cap;constructor(capacity=DEFAULT_PERMISSION_AUDIT_RING_SIZE){if(!Number.isInteger(capacity)||capacity<1){throw new Error(`PermissionAuditRing capacity must be a positive integer; got ${String(capacity)}`)}this.cap=capacity}push(entry){this.buf.push(entry);while(this.buf.length>this.cap)this.buf.shift()}snapshot(limit){return takeLast(this.buf,limit,"PermissionAuditRing.snapshot")}snapshotForSession(sessionId,limit){return takeLast(this.buf.filter(e=>e.sessionId===sessionId),limit,"PermissionAuditRing.snapshotForSession")}get size(){return this.buf.length}get capacity(){return this.cap}};function createPermissionAuditPublisher(deps){const{ring}=deps;const now=deps.now??(()=>Date.now());return{recordRequested(record,policy,votersAtIssue){ring.push({kind:"permission.requested",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,originatorClientId:record.originatorClientId,policy,votersAtIssue:Array.from(votersAtIssue),issuedAtMs:record.issuedAtMs,allowedOptionIds:Array.from(record.allowedOptionIds)})},recordVoted(record,vote,outcome){ring.push({kind:"permission.voted",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,clientId:vote.clientId,optionId:vote.optionId,fromLoopback:vote.fromLoopback,receivedAtMs:vote.receivedAtMs,outcome})},recordForbidden(record,vote,reason){ring.push({kind:"permission.forbidden",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,clientId:vote.clientId,optionId:vote.optionId,fromLoopback:vote.fromLoopback,reason})},recordResolved(record,resolution,decisionReason){ring.push({kind:"permission.resolved",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,resolution,decisionReason})},recordTimeout(record){ring.push({kind:"permission.timeout",recordedAtMs:now(),requestId:record.requestId,sessionId:record.sessionId,issuedAtMs:record.issuedAtMs})}}}__name(createPermissionAuditPublisher,"createPermissionAuditPublisher");init_esbuild_shims();init_esm();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as nodeFs from"node:fs";import*as nodePath from"node:path";import*as crypto from"node:crypto";import{performance}from"node:perf_hooks";var FIXED_CTX_ORDER=["route","sessionId","clientId","childPid","channelId"];var FIXED_CTX_SET=new Set(FIXED_CTX_ORDER);var RESERVED_TRACE_CTX_KEYS=new Set(["trace_id","span_id"]);var ISSUE_ORDER=["init_failed","rotation_failed","retention_failed","queue_overflow","write_failed","lease_compromised"];var DEFAULT_POLICY={maxBytes:10*1024*1024,maxArchives:4,maxRecordBytes:256*1024,maxPendingBytes:4*1024*1024,stableAcquireBudgetMs:1e3,maintenanceAcquireBudgetMs:250,lockStaleMs:6e4,lockUpdateMs:1e4,rotationRetryIntervalMs:6e4,closeDrainBudgetMs:2e3};var ARCHIVE_RE=/^daemon-(\d{12})-(\d{8}T\d{9}Z)-([0-9a-f]{8})\.log$/;var FALLBACK_DIR_RE=/^run-[0-9a-f]{32}$/;var ARCHIVE_NAME_ATTEMPTS=3;var FILE_MODE=384;var DIRECTORY_MODE=448;function renderCtxValue(value){const s=String(value);return/[\s=]/.test(s)?JSON.stringify(s):s}__name(renderCtxValue,"renderCtxValue");function renderCtx(ctx){if(!ctx)return"";const parts=[];for(const key of FIXED_CTX_ORDER){const v=ctx[key];if(v!==void 0&&v!==null){parts.push(`${key}=${String(v)}`)}}const extraKeys=Object.keys(ctx).filter(key=>!FIXED_CTX_SET.has(key)&&!RESERVED_TRACE_CTX_KEYS.has(key)&&ctx[key]!==void 0&&ctx[key]!==null).sort();for(const key of extraKeys){parts.push(`${key}=${renderCtxValue(ctx[key])}`)}return parts.length>0?parts.join(" ")+" ":""}__name(renderCtx,"renderCtx");function getActiveTraceContext(){try{const span=trace.getActiveSpan();if(!span?.isRecording())return void 0;const spanContext=span.spanContext();if(!isSpanContextValid(spanContext)||(spanContext.traceFlags&TraceFlags.SAMPLED)===0){return void 0}return{traceId:spanContext.traceId,spanId:spanContext.spanId}}catch{return void 0}}__name(getActiveTraceContext,"getActiveTraceContext");function renderTraceContext(traceContext){return traceContext?`[trace_id=${traceContext.traceId} span_id=${traceContext.spanId}] `:""}__name(renderTraceContext,"renderTraceContext");function renderErr(err){if(!err)return"";const body=err.stack??`${err.name??"Error"}: ${err.message}`;return body.split("\n").map(line=>` ${line}`).join("\n")+"\n"}__name(renderErr,"renderErr");function formatDaemonLogLine(args){const ts=args.now.toISOString();const traceStr=renderTraceContext(args.traceContext);const ctxStr=renderCtx(args.ctx);return`${ts} [${args.level}] [DAEMON] ${traceStr}${ctxStr}${args.message}
4
4
  ${renderErr(args.err)}`}__name(formatDaemonLogLine,"formatDaemonLogLine");function buildDaemonFileLogLine(args,runId,pid){const callerCtx=args.ctx?Object.fromEntries(Object.entries(args.ctx).filter(([key])=>key!=="runId"&&key!=="pid")):void 0;const traceStr=renderTraceContext(args.traceContext);const ctxStr=renderCtx(callerCtx);return`${args.now.toISOString()} [${args.level}] [DAEMON] runId=${runId} pid=${pid} ${traceStr}${ctxStr}${args.message}
5
5
  ${renderErr(args.err)}`}__name(buildDaemonFileLogLine,"buildDaemonFileLogLine");function getRuntimeBaseDir(runtimeOutputDir,cwd){const envDir=process.env["QWEN_RUNTIME_DIR"];if(envDir)return resolveConfigPathLite(envDir);if(runtimeOutputDir)return resolveConfigPathLite(runtimeOutputDir,cwd);return getGlobalQwenDirLite()}__name(getRuntimeBaseDir,"getRuntimeBaseDir");function resolveDaemonLogBaseDir(runtimeOutputDir,cwd){return nodePath.join(getRuntimeBaseDir(runtimeOutputDir,cwd),"debug")}__name(resolveDaemonLogBaseDir,"resolveDaemonLogBaseDir");function isOptedOut(){const raw=process.env["QWEN_DAEMON_LOG_FILE"];if(!raw)return false;return["0","false","off","no"].includes(raw.trim().toLowerCase())}__name(isOptedOut,"isOptedOut");function computeWorkspaceHash(boundWorkspace){return crypto.createHash("sha256").update(boundWorkspace).digest("hex").slice(0,8)}__name(computeWorkspaceHash,"computeWorkspaceHash");function computeDaemonId(pid){return`daemon:${pid}`}__name(computeDaemonId,"computeDaemonId");function isErrno(error,code){return error instanceof Error&&"code"in error&&error.code===code}__name(isErrno,"isErrno");function resolvePolicy(overrides){const policy={...DEFAULT_POLICY,...overrides};for(const[name,value]of Object.entries(policy)){if(!Number.isFinite(value)||value<0){throw new TypeError(`Invalid daemon logger policy ${name}=${value}`)}}if(policy.maxBytes===0||policy.maxArchives===0||policy.maxRecordBytes===0||policy.maxPendingBytes===0){throw new TypeError("Daemon logger size/count policy values must be positive")}if(policy.maxRecordBytes>policy.maxBytes){throw new TypeError("Daemon logger maxRecordBytes must not exceed maxBytes")}if(policy.maxRecordBytes>policy.maxPendingBytes){throw new TypeError("Daemon logger maxRecordBytes must not exceed maxPendingBytes")}return policy}__name(resolvePolicy,"resolvePolicy");function statusSnapshot(runId,mode,issues,droppedRecords,droppedBytes){return{runId,mode,health:issues.size===0?"ok":"degraded",issues:ISSUE_ORDER.filter(issue=>issues.has(issue)),droppedRecords,droppedBytes}}__name(statusSnapshot,"statusSnapshot");function createStderrOnlyLogger(input){const tee=__name((level,message,ctx,err)=>{const traceContext=getActiveTraceContext();input.stderr(formatDaemonLogLine({level,message,now:input.now(),ctx,err,traceContext}).trimEnd())},"tee");return{info:__name((message,ctx)=>tee("INFO",message,ctx),"info"),warn:__name((message,ctx)=>tee("WARN",message,ctx),"warn"),error:__name((message,err,ctx)=>tee("ERROR",message,ctx,err??void 0),"error"),raw:__name(()=>{},"raw"),getLogPath:__name(()=>"","getLogPath"),getDaemonId:__name(()=>input.daemonId,"getDaemonId"),getStatus:__name(()=>statusSnapshot(input.runId,"stderr-only",input.issues,0,0),"getStatus"),flush:__name(()=>Promise.resolve(),"flush"),close:__name(()=>Promise.resolve(),"close")}}__name(createStderrOnlyLogger,"createStderrOnlyLogger");function capUtf8Record(record,maxBytes){const bytes=Buffer.from(record,"utf8");if(bytes.length<=maxBytes)return record;const marker=`
6
6
  [truncated originalBytes=${bytes.length}]
@@ -44,7 +44,7 @@ try {
44
44
  message: error.message,
45
45
  });
46
46
  }
47
- `;async function verifyWorkerTlsTrust(opts){const timeoutMs=opts.timeoutMs??5e3;return new Promise(resolve3=>{execFile2(process.execPath,["--input-type=module","--eval",WORKER_TLS_TRUST_PROBE,opts.daemonUrl,String(timeoutMs)],{env:{...process.env,NODE_EXTRA_CA_CERTS:opts.caCertPath},encoding:"utf8",timeout:timeoutMs+1e3},(error,stdout)=>{try{const result=JSON.parse(stdout);resolve3(result.ok?void 0:result)}catch{const failure=error;resolve3({code:failure?.code!=null?String(failure.code):"WORKER_TLS_VERIFY_FAILED",message:failure?.message??"TLS verification probe failed."})}})})}__name(verifyWorkerTlsTrust,"verifyWorkerTlsTrust");function describeWorkerTlsTrustGaps(opts){const chain=parseCertChain(opts.cert);const x509=bootParsedLeaf(opts.cert);if(!x509){return[]}const gaps=[];const operatorChain=opts.operatorCaCert?loadableCertificates(opts.operatorCaCert.toString("utf8"),opts.operatorCaCertSourcePath):void 0;const servingBlocks=loadableCertificates(opts.cert.toString("utf8"),opts.certSourcePath);const operatorDiscarded=!servingBlocks&&operatorChain!==void 0;const servingChain=servingBlocks===void 0?[x509,...chain.filter(member=>member.fingerprint256!==x509.fingerprint256)]:servingBlocks.some(block=>block.fingerprint256===x509.fingerprint256)?servingBlocks:[x509,...servingBlocks];const leafHeldByWorkers=servingBlocks!==void 0&&servingBlocks.some(block=>block.fingerprint256===x509.fingerprint256);const workerTrustStore=operatorChain&&servingBlocks?[...operatorChain,...servingChain]:servingChain;const now=Date.now();const anchorPath=walkWorkerAnchorPath(x509,workerTrustStore,now,servingBlocks===void 0||leafHeldByWorkers);if(opts.operatorCaCertReadError!==void 0){const servingFallbackAnchors=anchorPath.anchored&&servingBlocks!==void 0;gaps.push(`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" could not be read by the daemon (${opts.operatorCaCertReadError}), so channel workers receive no CA from it \u2014 a root-owned or mode-600 file is the usual cause, and its contents are not the problem. `+(servingFallbackAnchors?`--tls-cert "${opts.certPath}" carries an anchor of its own, and that file is what the workers fall back to, so their trust does not rest on this one today \u2014 whatever it was meant to add reaches nobody. Fix that file's permissions or path and restart.`:servingBlocks===void 0?`--tls-cert "${opts.certPath}" itself holds no block the workers' loader can read, so their fallback bundle is that file alone and it anchors nothing \u2014 fixing this CA file's permissions changes nothing; re-export the serving file as the gap below describes and restart.`:`Every worker handshake to the daemon will fail UNABLE_TO_VERIFY_LEAF_SIGNATURE unless the issuing CA is already in the workers' default trust store. Fix that file's permissions or path and restart.`))}else if(opts.operatorCaCert&&!operatorChain){gaps.push(`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" holds no PEM certificate block Node's loader can read \u2014 every -----BEGIN/END CERTIFICATE----- marker must sit alone on its own line and every block must decode, and a DER file is never read at all. Channel workers therefore receive the daemon cert alone and anchor nothing through this file. Re-export it as PEM and restart.`)}if(!servingBlocks){gaps.push(`--tls-cert "${opts.certPath}" holds no PEM certificate block Node's loader can read, so `+(operatorDiscarded?`the channel workers' bundle cannot be merged: they receive that file alone and NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" is discarded. `:`the channel workers receive a bundle their loader takes nothing from. `)+`Every worker handshake to the daemon will fail UNABLE_TO_VERIFY_LEAF_SIGNATURE. Re-export --tls-cert as PEM with every -----BEGIN/END CERTIFICATE----- marker alone on its own line and restart.`)}const leafPurposeDefect=tlsServerPurposeDefect(x509);if(leafPurposeDefect){gaps.push(`--tls-cert "${opts.certPath}" cannot be used as a TLS server certificate because ${leafPurposeDefect}. Every worker handshake to the daemon will fail INVALID_PURPOSE. Reissue the leaf with a TLS-server keyUsage and serverAuth extendedKeyUsage, then restart.`)}if(anchorPath.nonCaTerminator){const terminatorSubject=anchorPath.nonCaTerminator.subject.replace(/\r?\n/g,", ");gaps.push(issuerRefusedForKeyUsage(anchorPath.nonCaTerminator)?`--tls-cert "${opts.certPath}" chains up to "${terminatorSubject}", which is self-signed but whose keyUsage does not include keyCertSign, so OpenSSL refuses to let it issue the certificates below it however its basicConstraints reads. Every worker handshake to the daemon will fail "key usage does not include certificate signing" even though the chain terminates on a self-signed certificate. Reissue that certificate with keyCertSign in its keyUsage and restart \u2014 CA:TRUE alone does not fix it, and no NODE_EXTRA_CA_CERTS can anchor a self-signed certificate through anything but itself.`:`--tls-cert "${opts.certPath}" chains up to "${terminatorSubject}", which is self-signed but is not a CA \u2014 it carries basicConstraints CA:FALSE or, as an X.509 v3 certificate, no basicConstraints at all, and OpenSSL refuses to let it issue the certificates below it, so every worker handshake to the daemon will fail INVALID_PURPOSE ("unsuitable certificate purpose"). Reissue that certificate with CA:TRUE, or point NODE_EXTRA_CA_CERTS at a real CA that anchors the chain, and restart.`)}else if(anchorPath.incapableIssuer){const keyUsageIsTheCause=issuerRefusedForKeyUsage(anchorPath.incapableIssuer);gaps.push(`--tls-cert "${opts.certPath}" chains through "${anchorPath.incapableIssuer.subject.replace(/\r?\n/g,", ")}", `+(keyUsageIsTheCause?`whose keyUsage does not include keyCertSign, so OpenSSL refuses to let it issue the certificate below it however its basicConstraints reads. Every worker handshake to the daemon will fail with an invalid-CA error even though the chain looks complete, and the issuing CA IS in their bundle. Reissue that intermediate with keyCertSign in its keyUsage and restart \u2014 pointing NODE_EXTRA_CA_CERTS elsewhere cannot fix it.`:`which is not a CA \u2014 it carries basicConstraints CA:FALSE or, as an X.509 v3 certificate, no basicConstraints at all, and OpenSSL refuses to let it issue the certificate below it. Every worker handshake to the daemon will fail INVALID_PURPOSE or INVALID_CA even though the chain looks complete. Reissue that intermediate with CA:TRUE, or point NODE_EXTRA_CA_CERTS at a chain whose intermediates are real CAs, and restart.`))}else if(anchorPath.pathLengthViolation){const{cert,constraint}=anchorPath.pathLengthViolation;gaps.push(`--tls-cert "${opts.certPath}" chains through "${cert.subject.replace(/\r?\n/g,", ")}", whose basicConstraints carries pathlen:${constraint} \u2014 it permits at most ${constraint} intermediate CA${constraint===1?"":"s"} below it, and this chain has more. Every worker handshake to the daemon will fail PATH_LENGTH_EXCEEDED even though every certificate in the bundle verifies. Reissue that CA with a pathlen that covers the chain, or shorten the chain, and restart.`)}else if(anchorPath.unheldSelfSignedLeaf){gaps.push(`--tls-cert "${opts.certPath}" serves a self-signed certificate whose own PEM block is not one Node's NODE_EXTRA_CA_CERTS loader takes (a -----BEGIN TRUSTED CERTIFICATE----- block, as \`openssl x509 -trustout\` writes, is the usual cause), so the channel workers never receive that certificate \u2014 and a self-signed certificate verifies only when it is itself in the trust store. The daemon serves it fine, but every worker handshake will fail DEPTH_ZERO_SELF_SIGNED_CERT with nothing logged. Re-export --tls-cert with a plain -----BEGIN CERTIFICATE----- block and restart.`)}else if(!anchorPath.anchored){gaps.push(`--tls-cert "${opts.certPath}" is issued by another CA (${x509.issuer.replace(/\r?\n/g,", ")}), not self-signed, and ${!opts.operatorCaCertPath?`no NODE_EXTRA_CA_CERTS is set`:opts.operatorCaCertReadError!==void 0?`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" could not be read, so whatever it carries reached nobody`:operatorDiscarded?`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" was discarded together with the unloadable serving file above, whatever it carries`:`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" does not carry a certificate that anchors it`}, so nothing in the channel workers' bundle anchors their trust \u2014 every worker handshake to the daemon will fail UNABLE_TO_VERIFY_LEAF_SIGNATURE unless the issuing CA is already in the workers' default trust store. `+(operatorDiscarded?`Re-export --tls-cert as described above and restart; NODE_EXTRA_CA_CERTS is not the file to change.`:opts.operatorCaCertReadError!==void 0?`Make NODE_EXTRA_CA_CERTS readable by the daemon as described above and restart.`:`Point NODE_EXTRA_CA_CERTS at the issuing CA (for mkcert: "$(mkcert -CAROOT)/rootCA.pem") and restart.`))}for(const member of anchorPath.path){if(member.fingerprint256===x509.fingerprint256)continue;const subject=member.subject.replace(/\r?\n/g,", ");if(member.keyUsage&&!member.keyUsage.includes(TLS_SERVER_AUTH_OID)){gaps.push(`--tls-cert "${opts.certPath}" chains through "${subject}", whose extendedKeyUsage does not include serverAuth \u2014 every worker handshake to the daemon will fail INVALID_PURPOSE. Reissue that chain member with serverAuth in its extendedKeyUsage and restart.`);continue}if(!certValidAt(member,now)){if(new Date(member.validTo).getTime()<now){gaps.push(`--tls-cert "${opts.certPath}" chains through "${subject}", which expired on ${member.validTo} \u2014 every worker handshake to the daemon will fail CERT_HAS_EXPIRED. Renew that chain member and restart.`)}else{gaps.push(`--tls-cert "${opts.certPath}" chains through "${subject}", which is not yet valid (validFrom: ${member.validFrom}) \u2014 every worker handshake to the daemon will fail CERT_NOT_YET_VALID. Check that chain member's notBefore date or the system clock.`)}}}const host=workerDialHost(opts.daemonUrl);if(host&&!certCoversHost(x509,host)){gaps.push(`--tls-cert "${opts.certPath}" has no subjectAltName covering "${host}", the host channel workers dial \u2014 every worker handshake will fail ERR_TLS_CERT_ALTNAME_INVALID. Reissue the certificate with that host in its SANs and restart.`)}return gaps}__name(describeWorkerTlsTrustGaps,"describeWorkerTlsTrustGaps");var BASIC_CONSTRAINTS_OID=Buffer.from([85,29,19]);var KEY_USAGE_OID=Buffer.from([85,29,15]);var KEY_CERT_SIGN_MASK=4;var TLS_SERVER_KEY_USAGE_MASK=168;var TLS_SERVER_AUTH_OID="1.3.6.1.5.5.7.3.1";var VERSION_TAG=160;var EXTENSIONS_TAG=163;var SEQUENCE_TAG=48;var BOOLEAN_TAG=1;var INTEGER_TAG=2;function derElementAt(der,at){const tag=der[at];const header=der[at+1];if(tag===void 0||header===void 0)return void 0;let start=at+2;let length=header&127;if((header&128)!==0){if(length===0||length>4)return void 0;let value=0;for(let index=0;index<length;index+=1){const byte=der[start+index];if(byte===void 0)return void 0;value=value*256+byte}start+=length;length=value}const end=start+length;return end<=der.length?{tag,start,end}:void 0}__name(derElementAt,"derElementAt");function tbsCertificateOf(cert){const certificate=derElementAt(cert.raw,0);if(certificate?.tag!==SEQUENCE_TAG)return void 0;const tbs=derElementAt(cert.raw,certificate.start);return tbs?.tag===SEQUENCE_TAG?tbs:void 0}__name(tbsCertificateOf,"tbsCertificateOf");function certificateExtension(cert,oid){const der=cert.raw;const tbs=tbsCertificateOf(cert);if(!tbs)return void 0;let at=tbs.start;while(at<tbs.end){const member=derElementAt(der,at);if(!member)return void 0;if(member.tag!==EXTENSIONS_TAG){at=member.end;continue}const list=derElementAt(der,member.start);if(list?.tag!==SEQUENCE_TAG)return void 0;let entry=list.start;while(entry<list.end){const extension=derElementAt(der,entry);if(extension?.tag!==SEQUENCE_TAG)return void 0;const id=derElementAt(der,extension.start);if(!id)return void 0;let valueAt=id.end;const critical=derElementAt(der,valueAt);if(critical?.tag===BOOLEAN_TAG)valueAt=critical.end;const value=derElementAt(der,valueAt);if(!value)return void 0;if(der.subarray(id.start,id.end).equals(oid)){return der.subarray(value.start,value.end)}entry=extension.end}return void 0}return void 0}__name(certificateExtension,"certificateExtension");function keyUsageAllowsCertSign(der){const bits=derElementAt(der,0);if(!bits)return false;const first=der[bits.start+1];return first!==void 0&&(first&KEY_CERT_SIGN_MASK)!==0}__name(keyUsageAllowsCertSign,"keyUsageAllowsCertSign");function tlsServerPurposeDefect(cert){const keyUsage=certificateExtension(cert,KEY_USAGE_OID);if(keyUsage!==void 0){const bits=derElementAt(keyUsage,0);const first=bits?keyUsage[bits.start+1]:void 0;if(first===void 0||(first&TLS_SERVER_KEY_USAGE_MASK)===0){return"its keyUsage permits none of digitalSignature, keyEncipherment, or keyAgreement"}}if(cert.keyUsage&&!cert.keyUsage.includes(TLS_SERVER_AUTH_OID)){return"its extendedKeyUsage does not include serverAuth"}return void 0}__name(tlsServerPurposeDefect,"tlsServerPurposeDefect");function isV1Certificate(cert){const tbs=tbsCertificateOf(cert);return tbs!==void 0&&cert.raw[tbs.start]!==VERSION_TAG}__name(isV1Certificate,"isV1Certificate");function cannotIssueCertificates(cert){const keyUsage=certificateExtension(cert,KEY_USAGE_OID);if(keyUsage!==void 0&&!keyUsageAllowsCertSign(keyUsage))return true;if(certificateExtension(cert,BASIC_CONSTRAINTS_OID)!==void 0){return!cert.ca}return!isV1Certificate(cert)&&keyUsage===void 0}__name(cannotIssueCertificates,"cannotIssueCertificates");function certValidAt(cert,now){return new Date(cert.validFrom).getTime()<=now&&new Date(cert.validTo).getTime()>=now}__name(certValidAt,"certValidAt");function isSelfSignedCert(x509){if(x509.subject!==x509.issuer)return false;try{return x509.verify(x509.publicKey)}catch{return true}}__name(isSelfSignedCert,"isSelfSignedCert");var PEM_CERTIFICATE_BLOCK=/-----BEGIN CERTIFICATE-----[^-]*-----END CERTIFICATE-----/g;function parseCertChain(cert){const blocks=cert.toString("utf8").match(PEM_CERTIFICATE_BLOCK);if(!blocks){try{return[new X509Certificate(cert)]}catch{return[]}}const chain=[];for(const block of blocks){try{chain.push(new X509Certificate(block))}catch{}}return chain}__name(parseCertChain,"parseCertChain");function bootParsedLeaf(cert){try{return new X509Certificate(cert)}catch{return void 0}}__name(bootParsedLeaf,"bootParsedLeaf");function certIssuedBy(cert,issuer){try{return cert.issuer===issuer.subject&&cert.verify(issuer.publicKey)}catch{return false}}__name(certIssuedBy,"certIssuedBy");function issuerRefusedForKeyUsage(cert){const keyUsage=certificateExtension(cert,KEY_USAGE_OID);return keyUsage!==void 0&&!keyUsageAllowsCertSign(keyUsage)}__name(issuerRefusedForKeyUsage,"issuerRefusedForKeyUsage");function pathLengthConstraint(cert){const value=certificateExtension(cert,BASIC_CONSTRAINTS_OID);if(!value)return void 0;const sequence=derElementAt(value,0);if(sequence?.tag!==SEQUENCE_TAG)return void 0;let at=sequence.start;const first=derElementAt(value,at);if(!first)return void 0;if(first.tag===BOOLEAN_TAG)at=first.end;const integer=derElementAt(value,at);if(integer?.tag!==INTEGER_TAG)return void 0;let length=0;for(let index=integer.start;index<integer.end;index+=1){const byte=value[index];if(byte===void 0)return void 0;length=length*256+byte}return length}__name(pathLengthConstraint,"pathLengthConstraint");function walkWorkerAnchorPath(leaf,chain,now,leafHeldByWorkers=true){let next=leaf;const walked=new Set;const path2=[];let pathLengthViolation;while(next){const current=next;path2.push(current);if(path2.length>1&&pathLengthViolation===void 0){const constraint=pathLengthConstraint(current);const intermediatesBelow=path2.length-2;if(constraint!==void 0&&intermediatesBelow>constraint){pathLengthViolation={cert:current,constraint}}}if(isSelfSignedCert(current)){if(path2.length>1&&cannotIssueCertificates(current)){return{anchored:false,path:path2,nonCaTerminator:current}}if(path2.length===1&&!leafHeldByWorkers){return{anchored:false,path:path2,unheldSelfSignedLeaf:current}}return pathLengthViolation?{anchored:false,path:path2,pathLengthViolation}:{anchored:true,path:path2}}walked.add(current.fingerprint256);const issuers=chain.filter(candidate=>!walked.has(candidate.fingerprint256)&&certIssuedBy(current,candidate));const issuer=issuers.find(candidate=>certValidAt(candidate,now))??issuers[0];if(issuer&&!isSelfSignedCert(issuer)&&!issuer.ca){return{anchored:false,path:path2,incapableIssuer:issuer}}next=issuer}return pathLengthViolation?{anchored:false,path:path2,pathLengthViolation}:{anchored:false,path:path2}}__name(walkWorkerAnchorPath,"walkWorkerAnchorPath");function workerDialHost(daemonUrl){try{const hostname=new URL(daemonUrl).hostname;if(!hostname)return void 0;return hostname.startsWith("[")&&hostname.endsWith("]")?hostname.slice(1,-1):hostname}catch{return void 0}}__name(workerDialHost,"workerDialHost");function certCoversHost(x509,host){try{return isIP(host)?Boolean(x509.checkIP(host)):Boolean(x509.checkHost(host))}catch{return true}}__name(certCoversHost,"certCoversHost");function extractContextFilename(value){if(typeof value==="string"){const trimmed=value.trim();return trimmed===""?void 0:trimmed}if(Array.isArray(value)){for(const entry of value){if(typeof entry==="string"){const trimmed=entry.trim();if(trimmed!=="")return trimmed}}return void 0}return void 0}__name(extractContextFilename,"extractContextFilename");function sessionArtifactsPersistenceAvailableFromSettings(settings){return settings?.general?.chatRecording!==false}__name(sessionArtifactsPersistenceAvailableFromSettings,"sessionArtifactsPersistenceAvailableFromSettings");function subSessionConcurrencyCapsFromSettings(serve,onWarning=writeStderrLine){const asCap=__name((key,value)=>{if(value===void 0)return void 0;if(typeof value==="number"&&Number.isInteger(value)&&value>=1){return value}onWarning(`qwen serve: ignoring invalid ${key} (${JSON.stringify(value)}); expected a positive integer, falling back to the built-in default.`);return void 0},"asCap");const maxConcurrentPerCaller=asCap("maxConcurrentSubSessionsPerCaller",serve.maxConcurrentSubSessionsPerCaller);const maxConcurrentTotal=asCap("maxConcurrentSubSessionsTotal",serve.maxConcurrentSubSessionsTotal);return{...maxConcurrentPerCaller!==void 0?{maxConcurrentPerCaller}:{},...maxConcurrentTotal!==void 0?{maxConcurrentTotal}:{}}}__name(subSessionConcurrencyCapsFromSettings,"subSessionConcurrencyCapsFromSettings");var settingsWriteLocks=new Map;function withSettingsLock(workspace,fn){const prev=settingsWriteLocks.get(workspace)??Promise.resolve();const next=prev.then(fn,fn);settingsWriteLocks.set(workspace,next);return next}__name(withSettingsLock,"withSettingsLock");var retryableChannelWorkerShutdownErrors=new WeakSet;function hasRetryableChannelWorkerShutdownError(error){if(error instanceof AggregateError){return error.errors.some(hasRetryableChannelWorkerShutdownError)}return error instanceof Error&&retryableChannelWorkerShutdownErrors.has(error)}__name(hasRetryableChannelWorkerShutdownError,"hasRetryableChannelWorkerShutdownError");var channelWorkerRuntimePromise;async function loadChannelWorkerRuntime(){channelWorkerRuntimePromise??=Promise.all([import("./channel-worker-supervisor-SQK3WRDC.js"),import("./pidfile-MQQT2ZDA.js"),import("./runtime-6E2FSB5U.js"),import("./cli-entry-path-4AZHCVCM.js"),import("./channel-worker-group-GW4KPIK3.js"),import("./channel-worker-manager-2TZEY52M.js")]).then(([supervisor,pidfile,channelRuntime,cliEntryPath,workerGroup,workerManager])=>({createChannelWorkerSupervisor:supervisor.createChannelWorkerSupervisor,resolveWorkerCaCertPath:supervisor.resolveWorkerCaCertPath,channelServicePidfile:pidfile,loadChannelsConfig:channelRuntime.loadChannelsConfig,createChannelWorkerGroup:workerGroup.createChannelWorkerGroup,createChannelWorkerManager:workerManager.createChannelWorkerManager,findCliEntryPath:cliEntryPath.findCliEntryPath})).catch(err=>{channelWorkerRuntimePromise=void 0;throw err});return channelWorkerRuntimePromise}__name(loadChannelWorkerRuntime,"loadChannelWorkerRuntime");function createDisabledChannelWorkerSupervisor(){const snapshot={enabled:false,state:"disabled",channels:[]};return{async start(){},async stop(){},async restart(){return{...snapshot,channels:[]}},killAllSync(){},snapshot:__name(()=>({...snapshot,channels:[]}),"snapshot"),async enqueueWebhookTask(){throw new ChannelWebhookEnqueueError("channel_worker_unavailable","Channel worker is not running.")}}}__name(createDisabledChannelWorkerSupervisor,"createDisabledChannelWorkerSupervisor");function writeServeChannelReservation(channelServicePidfile,channels){channelServicePidfile.reserveServeServiceInfo({channels,servePid:process.pid})}__name(writeServeChannelReservation,"writeServeChannelReservation");function channelServicePidfileConflictError(info){const owner=info.owner==="serve"?"qwen serve":"qwen channel start";return Object.assign(new Error(`Channel service is already running under ${owner} (PID ${info.pid}). Stop it before enabling daemon-managed channels.`),{code:"channel_service_conflict",owner:info.owner,pid:info.pid})}__name(channelServicePidfileConflictError,"channelServicePidfileConflictError");function channelServiceStartingConflictError(){return Object.assign(new Error("Channel service is already starting. Retry after the current startup finishes."),{code:"channel_service_conflict"})}__name(channelServiceStartingConflictError,"channelServiceStartingConflictError");function normalizeInstallModelIds(req,provider,getDefaultModelIds){const fromRequest=req.modelIds?.map(id=>id.trim()).filter(id=>id.length>0);const modelIds=fromRequest&&fromRequest.length>0?fromRequest:getDefaultModelIds(provider);return[...new Set(modelIds)]}__name(normalizeInstallModelIds,"normalizeInstallModelIds");function buildProviderSetupInputs(req,provider,helpers){const protocol=req.protocol??provider.protocol;const baseUrl=helpers.resolveBaseUrl(provider,req.baseUrl);return{...provider.protocolOptions?{protocol}:{},...req.wireApi?{wireApi:req.wireApi}:{},baseUrl,apiKey:req.apiKey.trim(),modelIds:normalizeInstallModelIds(req,provider,helpers.getDefaultModelIds),...req.advancedConfig?{advancedConfig:req.advancedConfig}:{}}}__name(buildProviderSetupInputs,"buildProviderSetupInputs");function shouldPreheatBridge(deps){if(deps.preheatBridge!==void 0)return deps.preheatBridge;return process.env["VITEST_WORKER_ID"]===void 0}__name(shouldPreheatBridge,"shouldPreheatBridge");var coreRuntimePromise;function loadCoreRuntime(){coreRuntimePromise??=import("./core-runtime-4RARI4NX.js");return coreRuntimePromise}__name(loadCoreRuntime,"loadCoreRuntime");var liveDiscoveryRuntimePromise;function loadLiveDiscoveryRuntime(){liveDiscoveryRuntimePromise??=import("./discovery-UOXKIBGP.js");return liveDiscoveryRuntimePromise}__name(loadLiveDiscoveryRuntime,"loadLiveDiscoveryRuntime");async function resolveDaemonLogBaseDirForRun(input){if(input.deps.daemonLogBaseDir){return input.deps.daemonLogBaseDir}if(input.deps.bootSettings===void 0){const core2=await loadCoreRuntime();if(core2.Storage.getRuntimeBaseDir()!==core2.Storage.getGlobalQwenDir()){return core2.Storage.getGlobalDebugDir()}}if(input.bootSettings?.advanced?.runtimeOutputDir!==void 0){return resolveDaemonLogBaseDir(input.bootSettings.advanced.runtimeOutputDir,input.boundWorkspace)}if(input.deps.bootSettings!==void 0){return resolveDaemonLogBaseDir(void 0,input.boundWorkspace)}const core=await loadCoreRuntime();return core.Storage.getGlobalDebugDir()}__name(resolveDaemonLogBaseDirForRun,"resolveDaemonLogBaseDirForRun");var settingsRuntimePromise;function loadSettingsRuntimeModules(){settingsRuntimePromise??=Promise.all([import("./settings-VHKT7JJC.js"),import("./environment-DSGQSQFS.js"),import("./loadedSettingsAdapter-STPKAFJG.js"),import("./trustedFolders-AM4PSGUB.js")]).then(([settings,environment,loadedSettingsAdapter,trustedFolders])=>({settings,environment,loadedSettingsAdapter,trustedFolders}));return settingsRuntimePromise}__name(loadSettingsRuntimeModules,"loadSettingsRuntimeModules");var channelWebhookConfigRuntimePromise;function loadChannelWebhookConfigRuntime(){channelWebhookConfigRuntimePromise??=Promise.all([import("./runtime-6E2FSB5U.js"),import("./config-utils-4X4SV4RL.js")]).then(([channelRuntime,configUtils])=>({loadChannelsConfig:channelRuntime.loadChannelsConfig,parseChannelWebhookConfig:configUtils.parseChannelWebhookConfig})).catch(err=>{channelWebhookConfigRuntimePromise=void 0;throw err});return channelWebhookConfigRuntimePromise}__name(loadChannelWebhookConfigRuntime,"loadChannelWebhookConfigRuntime");async function loadServeRuntimeModules(){const[serverModule,bridgeModule,spawnChannelModule,processRegistryModule,workspaceModule,workspaceTypesModule,daemonStatusProviderModule,workspaceProvidersStatusModule,workspaceSkillsStatusModule,totalSessionAdmissionModule,workspaceRegistryModule,workspaceRuntimeCoordinatorModule,promptLedgerModule,sessionExecutionEngineSelectorModule,managedExecutionEngineModule]=await Promise.all([import("./server-U2XBJLOV.js"),import("./bridge-GNMKKHQ4.js"),import("./spawnChannel-FMSYLDKB.js"),import("./process-registry-CCKP5HD4.js"),import("./workspace-service-U632SUWU.js"),import("./types-QZ644COX.js"),import("./daemon-status-provider-PRTEQT5T.js"),import("./workspace-providers-status-MFSZT3YA.js"),import("./workspace-skills-status-M7YXM3LF.js"),import("./total-session-admission-OATGW6M5.js"),import("./workspace-registry-FXZFRSCH.js"),import("./workspace-runtime-coordinator-LJ5YAT3A.js"),import("./prompt-terminal-ledger-IYUF6SUU.js"),import("./session-execution-engine-selector-PYDVOSJF.js"),import("./managed-execution-engine-FHLEWVND.js")]);return{createServeApp:serverModule.createServeApp,getActiveSseCount:serverModule.getActiveSseCount,resolveBoundWorkspacesFromIdeEnv:serverModule.resolveBoundWorkspacesFromIdeEnv,resolveBridgeFsFactory:serverModule.resolveBridgeFsFactory,createAcpSessionBridge:bridgeModule.createAcpSessionBridge,createSpawnChannelFactory:spawnChannelModule.createSpawnChannelFactory,daemonAcpNdJsonLimits:spawnChannelModule.DAEMON_ACP_NDJSON_LIMITS,ProcessRegistry:processRegistryModule.ProcessRegistry,createDaemonWorkspaceService:workspaceModule.createDaemonWorkspaceService,WorkspaceSettingsPartialPersistError:workspaceTypesModule.WorkspaceSettingsPartialPersistError,createDaemonStatusProvider:daemonStatusProviderModule.createDaemonStatusProvider,createWorkspaceProvidersStatusProvider:workspaceProvidersStatusModule.createWorkspaceProvidersStatusProvider,createWorkspaceSkillsStatusProvider:workspaceSkillsStatusModule.createWorkspaceSkillsStatusProvider,createTotalSessionAdmissionController:totalSessionAdmissionModule.createTotalSessionAdmissionController,createWorkspaceRegistry:workspaceRegistryModule.createWorkspaceRegistry,createWorkspaceSessionOwnerIndex:workspaceRegistryModule.createWorkspaceSessionOwnerIndex,createWorkspaceGenerationGuard:workspaceRegistryModule.createWorkspaceGenerationGuard,getWorkspaceRuntimeCoordinatorIfSupported:workspaceRuntimeCoordinatorModule.getWorkspaceRuntimeCoordinatorIfSupported,createPromptLedgerSink:promptLedgerModule.createPromptLedgerSink,createPairedExecutionEngines:sessionExecutionEngineSelectorModule.createPairedExecutionEngines,createManagedExecutionEngine:managedExecutionEngineModule.createManagedExecutionEngine}}__name(loadServeRuntimeModules,"loadServeRuntimeModules");function advertisedMaxSessions(value){if(value===void 0)return DEFAULT_MAX_SESSIONS;if(value===0||value===Number.POSITIVE_INFINITY)return null;return value}__name(advertisedMaxSessions,"advertisedMaxSessions");function advertisedMaxPendingPromptsPerSession(value){if(value===void 0)return DEFAULT_MAX_PENDING_PROMPTS_PER_SESSION;if(value===0||value===Number.POSITIVE_INFINITY)return null;return value}__name(advertisedMaxPendingPromptsPerSession,"advertisedMaxPendingPromptsPerSession");function channelIdleTimeoutMs(value){return value!==void 0&&Number.isFinite(value)&&value>0?Math.min(value,MAX_TIMEOUT_MS):0}__name(channelIdleTimeoutMs,"channelIdleTimeoutMs");function sessionIdleTimeoutMs(value){return value!==void 0?channelIdleTimeoutMs(value):DEFAULT_SESSION_IDLE_TIMEOUT_MS}__name(sessionIdleTimeoutMs,"sessionIdleTimeoutMs");function sessionPromptSettledCloseGraceMs(value){return value!==void 0?channelIdleTimeoutMs(value):DEFAULT_SESSION_PROMPT_SETTLED_CLOSE_GRACE_MS}__name(sessionPromptSettledCloseGraceMs,"sessionPromptSettledCloseGraceMs");function currentServeFeaturesForRunQwenServe(opts,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,env,nativeDirectoryPickerAvailable,localPathOpenAvailable,localTerminalOpenAvailable){return getAdvertisedServeFeatures(void 0,{requireAuth:opts.requireAuth===true,mcpPoolActive:opts.mcpPoolActive!==false,externalToolGuardActive:opts.externalToolGuard?.mode==="required",allowOriginActive:opts.allowOrigins!==void 0&&opts.allowOrigins.length>0,...opts.promptDeadlineMs!==void 0?{promptDeadlineMs:opts.promptDeadlineMs}:{},...opts.writerIdleTimeoutMs!==void 0?{writerIdleTimeoutMs:opts.writerIdleTimeoutMs}:{},persistSettingAvailable:true,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,sessionGenerationAvailable:true,currentSessionSchedulingAvailable,workspaceGenerationAvailable:true,rateLimit:opts.rateLimit===true,reloadAvailable:true,channelReloadAvailable:opts.channelSelection!==void 0,channelControlAvailable:true,channelManagementAvailable:true,persistentWorkspaceRegistrationAvailable:true,workspaceRuntimeRemovalAvailable:true,nativeDirectoryPickerAvailable,workspaceRuntimeAvailable,localPathOpenAvailable,localTerminalOpenAvailable,dynamicWorkspaceRegistrationAvailable:true,scratchWorkspaceRegistrationAvailable:true,standaloneSessionsAvailable:true,workspaceTrustHotReloadAvailable:true,acpHttpEnabled:opts.profile!=="hosted-harness"&&resolveAcpHttpEnabled(env),clientMcpOverWsEnabled:opts.clientMcpOverWs===true,cdpTunnelOverWsEnabled:opts.cdpTunnelOverWs===true,browserAutomationMcpAvailable:isBrowserAutomationMcpAvailable(opts,env)})}__name(currentServeFeaturesForRunQwenServe,"currentServeFeaturesForRunQwenServe");function createBootstrapCapabilities(input){return{v:CAPABILITIES_SCHEMA_VERSION,protocolVersions:getServeProtocolVersions(),...input.qwenCodeVersion?{qwenCodeVersion:input.qwenCodeVersion}:{},mode:input.opts.mode,features:currentServeFeaturesForRunQwenServe(input.opts,input.sessionShellCommandEnabled,input.sessionArtifactsPersistenceAvailable,input.workspaceRuntimeAvailable,input.currentSessionSchedulingAvailable,input.env,input.nativeDirectoryPickerAvailable,input.localPathOpenAvailable,input.localTerminalOpenAvailable),modelServices:[],workspaceCwd:input.boundWorkspace,transports:["rest"],policy:{permission:input.permissionPolicy??"first-responder"},limits:{maxRegisteredWorkspaces:input.opts.maxRegisteredWorkspaces,maxChannelControlWorkspaces:MAX_CHANNEL_CONTROL_WORKSPACES,...input.opts.maxTotalSessions!==void 0?{maxSessionsPerWorkspace:advertisedMaxSessions(input.opts.maxSessions),maxTotalSessions:positiveFiniteOrNull(input.opts.maxTotalSessions)}:{},maxPendingPromptsPerSession:advertisedMaxPendingPromptsPerSession(input.opts.maxPendingPromptsPerSession),sessionRestoreTimeoutMs:resolveSessionRestoreTimeoutMs(input.opts)}}}__name(createBootstrapCapabilities,"createBootstrapCapabilities");function validateRateLimitOptions(opts){if(opts.rateLimit!==true)return;for(const[name,value]of[["rateLimitPrompt",opts.rateLimitPrompt],["rateLimitMutation",opts.rateLimitMutation],["rateLimitRead",opts.rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){throw new TypeError(`Invalid ${name}: ${value}. Must be a positive integer.`)}}if(opts.rateLimitWindowMs!==void 0&&(!Number.isFinite(opts.rateLimitWindowMs)||!Number.isInteger(opts.rateLimitWindowMs)||opts.rateLimitWindowMs<1e3)){throw new TypeError(`Invalid rateLimitWindowMs: ${opts.rateLimitWindowMs}. Must be an integer >= 1000.`)}}__name(validateRateLimitOptions,"validateRateLimitOptions");function createLazyBridgeProxy(getBridge,getStartupError=()=>void 0){return new Proxy({},{get(_target,prop){const bridge=getBridge();if(!bridge){const startupError=getStartupError();if(startupError){throw new Error(`Daemon bridge runtime is not available: ${startupError}`)}throw new Error("Daemon bridge runtime is still starting.")}const value=Reflect.get(bridge,prop,bridge);return typeof value==="function"?value.bind(bridge):value}})}__name(createLazyBridgeProxy,"createLazyBridgeProxy");function resolveRuntimeStartupTimeoutMs(override){if(override!==void 0){return Number.isFinite(override)&&override>0?override:0}const raw=process.env[RUNTIME_STARTUP_TIMEOUT_ENV];if(raw===void 0||raw.trim()===""){return DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS}const trimmed=raw.trim();if(trimmed==="0")return 0;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)&&parsed>0?parsed:DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS}__name(resolveRuntimeStartupTimeoutMs,"resolveRuntimeStartupTimeoutMs");async function waitForRuntimeStartingForShutdown(runtimeStarting,daemonLog,timeoutMs=SHUTDOWN_FORCE_CLOSE_MS){if(!runtimeStarting)return;let timer;await Promise.race([runtimeStarting,new Promise(resolve3=>{timer=setTimeout(()=>{daemonLog.warn(`${timeoutMs}ms runtime-startup wait reached during shutdown; continuing listener close`);resolve3()},timeoutMs);timer.unref()})]).finally(()=>{if(timer)clearTimeout(timer)})}__name(waitForRuntimeStartingForShutdown,"waitForRuntimeStartingForShutdown");var BOOTSTRAP_HEALTH_PATH="/health";var BOOTSTRAP_CAPABILITIES_PATH="/capabilities";var BOOTSTRAP_DAEMON_STATUS_PATH="/daemon/status";var BOOTSTRAP_SERVE_PATHS=new Set([BOOTSTRAP_HEALTH_PATH,BOOTSTRAP_CAPABILITIES_PATH,BOOTSTRAP_DAEMON_STATUS_PATH]);var RUNTIME_STARTUP_FAILED_ENVELOPE={error:"Daemon runtime failed to start",code:"daemon_runtime_failed"};var RUNTIME_STARTUP_STARTING_ENVELOPE={error:"Daemon runtime is still starting",code:"daemon_runtime_starting"};function runtimeStartupEnvelope(runtimeError){return runtimeError?RUNTIME_STARTUP_FAILED_ENVELOPE:RUNTIME_STARTUP_STARTING_ENVELOPE}__name(runtimeStartupEnvelope,"runtimeStartupEnvelope");function createBootstrapServeApp(input){const{opts,getPort,boundWorkspace,startup,daemonLog,qwenCodeVersion,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,permissionPolicy,multiWorkspaceCapabilitiesRequireRuntime,getRuntimeError,getChannelWorkerSnapshot,getChannelWorkerSnapshots,getChannelRestoreFailures,onHealthServed}=input;const app=(0,import_express.default)();const nativeDirectoryPickerAvailable=isNativeDirectoryPickerAvailable();const localPathOpenAvailable=isLocalPathOpenAvailable();const localTerminalOpenAvailable=isLocalTerminalAvailable();installSelfOriginStripMiddleware(app,getPort,opts.hostname);app.use(hostAllowlist(opts.hostname,getPort));installRemoteSelfOriginMiddleware(app,opts.hostname,opts.token);if(opts.allowOrigins&&opts.allowOrigins.length>0){app.use(allowOriginCors(parseAllowOriginPatterns(opts.allowOrigins)))}else{app.use(denyBrowserOriginCors)}if(opts.profile==="hosted-harness"){app.use((req,res,next)=>{if(req.path==="/health"||req.path==="/capabilities")next();else res.sendStatus(404)})}const healthHandler=__name((req,res)=>{const runtimeError=getRuntimeError();if(runtimeError!==void 0){res.status(503).json({status:"degraded",error:runtimeError});return}if(onHealthServed){res.once("finish",onHealthServed)}if(isDeepHealthQuery(req.query["deep"])){res.setHeader("Retry-After","1");res.status(503).json({status:"degraded",reason:"bootstrap"});return}res.status(200).json({status:"ok"})},"healthHandler");const loopback=isLoopbackBind(opts.hostname);const exposeHealthPreAuth=loopback&&!opts.requireAuth;if(exposeHealthPreAuth){app.get(BOOTSTRAP_HEALTH_PATH,healthHandler)}app.use(bearerAuth(opts.token));if(!exposeHealthPreAuth){app.get(BOOTSTRAP_HEALTH_PATH,healthHandler)}app.get(BOOTSTRAP_CAPABILITIES_PATH,(_req,res)=>{if(opts.profile==="hosted-harness"){res.setHeader("Retry-After","1");res.status(503).json({error:"Hosted Harness is starting."});return}if(multiWorkspaceCapabilitiesRequireRuntime){const runtimeError=getRuntimeError();if(runtimeError===void 0){res.setHeader("Retry-After","1")}res.status(503).json(runtimeStartupEnvelope(runtimeError));return}res.status(200).json(createBootstrapCapabilities({opts,boundWorkspace,qwenCodeVersion,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,permissionPolicy,env:process.env,nativeDirectoryPickerAvailable,localPathOpenAvailable,localTerminalOpenAvailable}))});app.get(BOOTSTRAP_DAEMON_STATUS_PATH,(req,res)=>{const detail=parseDaemonStatusDetail(req.query["detail"]);if(!detail.ok||!detail.detail){res.status(400).json({error:"detail must be one of: summary, full",code:"invalid_detail"});return}const runtimeError=getRuntimeError();const bootstrapJournalGrowthPoolMb=opts.daemonMemoryBudget!==void 0?serveJournalGrowthPoolMb({budget:opts.daemonMemoryBudget,maxJournalEvents:opts.maxJournalEvents,maxJournalBytes:opts.maxJournalBytes}):0;const channelWorker=getChannelWorkerSnapshot();const channelWorkers=getChannelWorkerSnapshots();const runtimeFailed=runtimeError!==void 0;const issue=runtimeError?{code:"daemon_runtime_failed",severity:"error",message:runtimeError}:{code:"daemon_runtime_starting",severity:"warning",message:"Daemon runtime is still starting."};const daemonLogStatus=daemonLog.getStatus();const issues=[issue];pushChannelRestoreIssues(issues,getChannelRestoreFailures());if(daemonLogStatus.health==="degraded"){issues.push({code:"daemon_log_degraded",severity:"warning",message:"Daemon file logging is degraded; inspect full status for details."})}const response={v:1,detail:detail.detail,generatedAt:new Date().toISOString(),status:runtimeFailed?"error":"warning",issues,daemon:{pid:process.pid,uptimeMs:Math.round(process.uptime()*1e3),mode:opts.mode,workspaceCwd:boundWorkspace,startup:{...startup,preheat:{...startup.preheat}},...qwenCodeVersion?{qwenCodeVersion}:{},...daemonLog.getDaemonId()?{daemonId:daemonLog.getDaemonId()}:{},runId:daemonLogStatus.runId,logMode:daemonLogStatus.mode,logHealth:daemonLogStatus.health,...detail.detail==="full"&&daemonLog.getLogPath()?{logPath:daemonLog.getLogPath()}:{},...detail.detail==="full"?{logIssues:daemonLogStatus.issues,logDroppedRecords:daemonLogStatus.droppedRecords,logDroppedBytes:daemonLogStatus.droppedBytes}:{}},security:{tokenConfigured:Boolean(opts.token),requireAuth:opts.requireAuth===true,loopbackBind:loopback,allowOriginConfigured:opts.allowOrigins!==void 0&&opts.allowOrigins.length>0,allowOriginMode:allowOriginMode(opts.allowOrigins),sessionShellCommandEnabled},limits:{maxRegisteredWorkspaces:opts.maxRegisteredWorkspaces,maxChannelControlWorkspaces:MAX_CHANNEL_CONTROL_WORKSPACES,maxSessions:advertisedMaxSessions(opts.maxSessions),maxTotalSessions:positiveFiniteOrNull(opts.maxTotalSessions),maxPendingPromptsPerSession:advertisedMaxPendingPromptsPerSession(opts.maxPendingPromptsPerSession),listenerMaxConnections:listenerMaxConnections(opts.maxConnections),eventRingSize:opts.eventRingSize??DEFAULT_RING_SIZE,compactedReplayMaxBytes:opts.compactedReplayMaxBytes??DEFAULT_COMPACTED_REPLAY_MAX_BYTES,maxJournalEvents:opts.maxJournalEvents??DEFAULT_MAX_JOURNAL_EVENTS,maxJournalBytes:opts.maxJournalBytes??DEFAULT_MAX_JOURNAL_BYTES,promptDeadlineMs:positiveFiniteOrNull(opts.promptDeadlineMs),writerIdleTimeoutMs:positiveFiniteOrNull(opts.writerIdleTimeoutMs),channelIdleTimeoutMs:channelIdleTimeoutMs(opts.channelIdleTimeoutMs),sessionIdleTimeoutMs:sessionIdleTimeoutMs(opts.sessionIdleTimeoutMs),sessionPromptSettledCloseGraceMs:sessionPromptSettledCloseGraceMs(opts.sessionPromptSettledCloseGraceMs),acpConnectionCap:null,acpPreAttachMaxFramesPerStream:null,acpPreAttachMaxFramesPerConnection:null,acpPreAttachMaxFramesGlobal:null,acpPreAttachMaxPayloadBytesPerConnection:null,acpPreAttachMaxPayloadBytesGlobal:null,memory:toDaemonStatusMemoryLimits(opts.daemonMemoryBudget,void 0,bootstrapJournalGrowthPoolMb>0?{poolBytes:bootstrapJournalGrowthPoolMb*1024*1024,hardCapBytes:JOURNAL_GROWTH_HARD_CAP_BYTES,baselineMaxEvents:opts.maxJournalEvents??DEFAULT_MAX_JOURNAL_EVENTS,baselineMaxBytes:opts.maxJournalBytes??DEFAULT_MAX_JOURNAL_BYTES}:null)},capabilities:{protocolVersions:getServeProtocolVersions(),features:currentServeFeaturesForRunQwenServe(opts,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,process.env,nativeDirectoryPickerAvailable,localPathOpenAvailable,localTerminalOpenAvailable)},runtime:{loading:runtimeError===void 0,...runtimeError?{error:runtimeError}:{},sessions:{active:0},permissions:{pending:0,policy:permissionPolicy??"first-responder"},channel:{live:false},channelWorker,...channelWorkers.length>0?{channelWorkers}:{},transport:{restSseActive:0,acp:{enabled:false,connections:0,connectionStreams:0,sessionStreams:0,sseStreams:0,wsStreams:0,pendingClientRequests:0,preAttach:{bufferedConnectionFrames:0,bufferedSessionFrames:0,pendingDeliveryFrames:0,usedFrames:0,usedBytes:0,highWaterFrames:0,highWaterBytes:0,guardFailures:0}}},rateLimit:{enabled:opts.rateLimit===true,rejectedSinceStart:{prompt:0,mutation:0,read:0}},activity:{activePrompts:0,pendingPrompts:0,queuedPrompts:0,lastActivityAt:null,idleSinceMs:null},process:process.memoryUsage()},...detail.detail==="full"?{full:{sessions:[],acpMounts:[],acpConnections:[],workspace:{},auth:{supportedDeviceFlowProviders:[],pendingDeviceFlowCount:0}}}:{}};res.status(200).json(response)});app.use((_req,res)=>{res.status(503).json(runtimeStartupEnvelope(getRuntimeError()))});return app}__name(createBootstrapServeApp,"createBootstrapServeApp");function createDelegatingServeApp(bootstrapApp,getRuntimeApp,options={}){const app=(0,import_express.default)();app.use((req,res,next)=>{const dispatch=__name(async()=>{let target=getRuntimeApp();if(!target&&options.waitForDeferredRuntimeRoutes===true&&!isBootstrapServeRoute(req)&&!isCorsPreflightRequest(req)&&options.startRuntime&&options.runtimeReady){const waitStartedAt=performance2.now();const timing={startedAt:new Date,path:"joined"};const webhookRequest=isChannelWebhookRequest(req);const authGate=webhookRequest?options.authenticateDeferredChannelWebhookRequest??options.authenticateDeferredRuntimeRequest:options.authenticateDeferredRuntimeRequest;const preAuthExempted=authGate!==void 0&&await Promise.resolve(options.isPreAuthRequest?.(req)).catch(()=>false)===true;if(authGate&&!preAuthExempted){if(!runSynchronousRequestGate(authGate,req,res,next)){return}}setDeferredRuntimeRequestTiming(req,timing);if(options.startRuntime()){timing.path="started_on_request"}try{await options.runtimeReady}catch{if(preAuthExempted){res.status(503).json(RUNTIME_STARTUP_FAILED_ENVELOPE);return}}finally{timing.waitMs=Math.round((performance2.now()-waitStartedAt)*100)/100}target=getRuntimeApp()}const handler=target??bootstrapApp;handler(req,res,next)},"dispatch");void dispatch().catch(next)});return app}__name(createDelegatingServeApp,"createDelegatingServeApp");function isBootstrapServeRoute(req){const path2=req.path.length>1&&req.path.endsWith("/")?req.path.slice(0,-1):req.path;return BOOTSTRAP_SERVE_PATHS.has(path2)}__name(isBootstrapServeRoute,"isBootstrapServeRoute");function isChannelWebhookRequest(req){return req.method==="POST"&&/^\/channels\/[^/]+\/webhooks\/[^/]+\/?$/u.test(req.path)}__name(isChannelWebhookRequest,"isChannelWebhookRequest");function createDeferredChannelWebhookAuth(resolveSource,runtime,daemonLog){return(req,res,next)=>{const match=/^\/channels\/([^/]+)\/webhooks\/([^/]+)\/?$/u.exec(req.path);const channelName=decodeDeferredWebhookPathSegment(match?.[1]);const source=decodeDeferredWebhookPathSegment(match?.[2]);if(!channelName||!source){daemonLog.warn("deferred webhook auth failed",{channelName:channelName??"unknown",source:source??"unknown",reason:"invalid webhook path"});res.status(401).json({error:"Invalid webhook secret"});return}const configSource=resolveSource(channelName);const secret=readDeferredWebhookSecret(runtime,configSource.workspaceCwd,channelName,source,configSource.env);if(!matchesWebhookSecret(req.get("x-qwen-webhook-secret"),secret)){daemonLog.warn("deferred webhook auth failed",{channelName,source,reason:secret?"secret mismatch":"source not configured"});res.status(401).json({error:"Invalid webhook secret"});return}next()}}__name(createDeferredChannelWebhookAuth,"createDeferredChannelWebhookAuth");function decodeDeferredWebhookPathSegment(segment){if(segment===void 0)return void 0;try{return decodeURIComponent(segment)}catch{return void 0}}__name(decodeDeferredWebhookPathSegment,"decodeDeferredWebhookPathSegment");function readDeferredWebhookSecret(runtime,workspace,channelName,source,env){try{const rawConfig=runtime.loadChannelsConfig(workspace)[channelName];if(typeof rawConfig!=="object"||rawConfig===null){return void 0}return runtime.parseChannelWebhookConfig(channelName,rawConfig,env)?.sources[source]?.secret}catch(err){const reason=err instanceof Error?err.message:String(err);writeStderrLine(`[webhook-secret] failed to read deferred webhook secret for ${sanitizeLogText(channelName,128)}/${sanitizeLogText(source,128)}: ${sanitizeLogText(reason,512)}`);return void 0}}__name(readDeferredWebhookSecret,"readDeferredWebhookSecret");function matchesWebhookSecret(candidate,expected){if(typeof candidate!=="string"||typeof expected!=="string"||expected.length===0){return false}const expectedDigest=createHash2("sha256").update(expected).digest();const candidateDigest=createHash2("sha256").update(candidate).digest();return timingSafeEqual(expectedDigest,candidateDigest)}__name(matchesWebhookSecret,"matchesWebhookSecret");function isCorsPreflightRequest(req){return req.method==="OPTIONS"&&Boolean(req.headers.origin)&&Boolean(req.headers["access-control-request-method"]||req.headers["access-control-request-headers"])}__name(isCorsPreflightRequest,"isCorsPreflightRequest");function runSynchronousRequestGate(handler,req,res,next){let passed=false;handler(req,res,err=>{if(err){next(err);return}passed=true});return passed}__name(runSynchronousRequestGate,"runSynchronousRequestGate");function validateAndCanonicalizeWorkspaceInput(rawWorkspace){const workspace=translateAndCheckAbsoluteWorkspacePath(rawWorkspace);if(workspace===null){throw new Error(`Invalid --workspace "${rawWorkspace}": must be an absolute path.`)}try{const stats=fs.statSync(workspace);if(!stats.isDirectory()){throw new Error(`Invalid --workspace "${workspace}": exists but is not a directory.`)}}catch(err){if(err&&typeof err==="object"&&"code"in err){const code=err.code;if(code==="ENOENT"){throw new Error(`Invalid --workspace "${workspace}": directory does not exist.`)}if(code==="EACCES"||code==="EPERM"){throw new Error(`Invalid --workspace "${workspace}": permission denied (${String(code)}). The path exists but cannot be stat'd by the current user.`)}}throw err}return canonicalizeWorkspace(workspace)}__name(validateAndCanonicalizeWorkspaceInput,"validateAndCanonicalizeWorkspaceInput");async function runQwenServe(optsIn,deps={}){let daemonLog;let owner="startup";let restoreScrubbedLoaderEnv;let installedLoaderRejectionReporter;try{return await runQwenServeImpl(optsIn,deps,{initialized:__name(logger=>{daemonLog=logger},"initialized"),published:__name(()=>{if(owner==="startup")owner="handle"},"published"),signalOwned:__name(()=>{if(owner==="startup")owner="signal"},"signalOwned"),scrubApplied:__name(restore=>{restoreScrubbedLoaderEnv=restore},"scrubApplied"),reporterInstalled:__name(reporter=>{installedLoaderRejectionReporter=reporter},"reporterInstalled")})}catch(error){if(installedLoaderRejectionReporter){clearLoaderKeyRejectionReporterIfCurrent(installedLoaderRejectionReporter)}if(daemonLog&&owner==="startup"){const startupLog=daemonLog;writeDaemonLifecycleBestEffort(()=>startupLog.error("daemon startup failed",error instanceof Error?error:new Error(String(error))));await startupLog.close()}restoreScrubbedLoaderEnv?.();throw error}}__name(runQwenServe,"runQwenServe");function bridgeHasLiveSessionWithin(bridge,workspaceCwd,worktreePath){return bridge.listWorkspaceSessions(workspaceCwd).some(session=>{try{return isWithinRoot(path.resolve(bridge.getSessionExecutionSnapshot(session.sessionId).effectiveCwd),path.resolve(worktreePath))}catch{return true}})}__name(bridgeHasLiveSessionWithin,"bridgeHasLiveSessionWithin");async function createBranchRecoverySessionService(runtime){const{SessionService}=await import("./sessionService-3FWNA4ZB.js");return new SessionService(runtime.workspaceCwd,{runtimeBaseDir:runtime.sessionRuntimeBaseDir})}__name(createBranchRecoverySessionService,"createBranchRecoverySessionService");var brokenPipeGuardInstalled=false;function installServeBrokenPipeGuard(){if(brokenPipeGuardInstalled)return;brokenPipeGuardInstalled=true;const ignoreEpipe=__name(err=>{if(err.code!=="EPIPE")throw err},"ignoreEpipe");process.stdout.on("error",ignoreEpipe);process.stderr.on("error",ignoreEpipe)}__name(installServeBrokenPipeGuard,"installServeBrokenPipeGuard");async function runQwenServeImpl(optsIn,deps,loggerLifecycle){installServeBrokenPipeGuard();const runStartedAt=performance2.now();delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const channelDeliveryAuthorizations=new ChannelDeliveryAuthorizationStore;let shouldPreheat=optsIn.profile!=="hosted-harness"&&!deps.bridge&&shouldPreheatBridge(deps);const startup={processStartedAt:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),preheat:{status:deps.bridge?"external_bridge":shouldPreheat?"scheduled":"not_scheduled"}};if(optsIn.memoryProjectScope!==void 0&&!MEMORY_PROJECT_SCOPES.includes(optsIn.memoryProjectScope)){throw new TypeError(`Invalid memoryProjectScope: ${String(optsIn.memoryProjectScope)}. Must be "git-root" or "workspace".`)}preResolveServeFastPathHomeEnvOverrides();assertExecutionSandboxSupported(readOperatorSandboxSettings(),"serve / ACP / web terminals");assertExecutionSandboxSupported(deps.bootSettings??{},"serve / ACP / web terminals");const{token,generated:generatedToken}=resolveRemoteServeToken(optsIn.token,isLoopbackBind(optsIn.hostname));const hostedHarnessCapabilityDigest=optsIn.hostedHarnessCapabilityDigest??(optsIn.profile==="hosted-harness"?process.env[HOSTED_HARNESS_CAPABILITY_DIGEST_ENV]:void 0);const hostedCsiSessionStoreUrl=optsIn.hostedCsiSessionStoreUrl??process.env[HOSTED_CSI_SESSION_STORE_URL_ENV];validateHostedHarnessProfile({...optsIn,token,requireAuth:optsIn.profile==="hosted-harness"?true:optsIn.requireAuth,hostedHarnessCapabilityDigest,hostedCsiSessionStoreUrl});const baseEnv={...process.env};const launchMemoryProjectScopeValue=baseEnv["QWEN_CODE_MEMORY_PROJECT_SCOPE"];const launchMemoryProjectScope=launchMemoryProjectScopeValue?.trim()?launchMemoryProjectScopeValue:void 0;const memoryProjectScopeValue=optsIn.memoryProjectScope??launchMemoryProjectScope??"workspace";const memoryProjectScopeSource=optsIn.memoryProjectScope!==void 0?"option":launchMemoryProjectScope!==void 0?"environment":"default";const resolvedMemoryProjectScope=memoryProjectScopeValue.trim().toLowerCase()==="workspace"?"workspace":"git-root";baseEnv["QWEN_CODE_MEMORY_PROJECT_SCOPE"]=memoryProjectScopeValue;if(process.env["DEV"]!=="true"){scrubInheritedLoaderEnv(baseEnv)}const daemonRuntimeBaseEnv=Object.freeze(baseEnv);const loaderEnvScrub=acquireInheritedLoaderEnvScrub(process.env,"qwen serve","daemon");const scrubbedLoaderEnvKeys=loaderEnvScrub.removedKeys;const restoreScrubbedLoaderEnv=__name(()=>{loaderEnvScrub.release()},"restoreScrubbedLoaderEnv");loggerLifecycle.scrubApplied(restoreScrubbedLoaderEnv);if(!optsIn.hostname.trim()){throw new Error("Invalid --hostname: empty value binds every interface. Pass an explicit address (e.g. --hostname 0.0.0.0) or omit the flag.")}const bindHostname=optsIn.hostname.toLowerCase()==="localhost"?(await(deps.bindHostnameLookup??lookup)(optsIn.hostname)).address:optsIn.hostname;if(optsIn.profile==="hosted-harness"&&!isLoopbackAddress(bindHostname)){throw new Error("--profile hosted-harness resolved outside the loopback interface.")}const trustedLoopbackMode=isTrustedLoopbackMode({loopbackBind:isLoopbackAddress(bindHostname),tokenConfigured:token!==void 0,requireAuth:optsIn.requireAuth===true});const channelDeliveryDiagnosticRedaction={workerEnv:daemonRuntimeBaseEnv,...token?{daemonToken:token}:{}};const sessionShellCommandEnabled=optsIn.enableSessionShell===true&&(token!==void 0||trustedLoopbackMode);if(optsIn.enableSessionShell===true&&token===void 0&&!trustedLoopbackMode){writeStderrLine(`qwen serve: --enable-session-shell ignored because no bearer token is configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token to enable direct session shell.`)}const promptDeadlineMs=optsIn.promptDeadlineMs??parseDeadlineEnv(QWEN_SERVE_PROMPT_DEADLINE_MS_ENV,process.env[QWEN_SERVE_PROMPT_DEADLINE_MS_ENV]);const writerIdleTimeoutMs=optsIn.writerIdleTimeoutMs??parseDeadlineEnv(QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV,process.env[QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV]);const clientMcpOverWsEnv=process.env[QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV];const cdpTunnelOverWsEnv=process.env[QWEN_SERVE_CDP_TUNNEL_OVER_WS_ENV];const chromeExtensionOriginAllowed=hasChromeExtensionOrigin(optsIn.allowOrigins);const rawWorkspaces=resolveWorkspaceInputs(optsIn.workspace);const rawWorkspace=rawWorkspaces[0];const opts={...optsIn,hostname:bindHostname,requireAuth:optsIn.profile==="hosted-harness"?true:optsIn.requireAuth,maxRegisteredWorkspaces:resolveMaxRegisteredWorkspaces(optsIn.maxRegisteredWorkspaces,daemonRuntimeBaseEnv),token,hostedHarnessCapabilityDigest,hostedCsiSessionStoreUrl,promptDeadlineMs,writerIdleTimeoutMs,workspace:rawWorkspace,clientMcpOverWs:optsIn.profile==="hosted-harness"?false:optsIn.clientMcpOverWs??(!envFlagDisabled(clientMcpOverWsEnv)&&clientMcpOverWsEnv!==void 0),cdpTunnelOverWs:optsIn.profile==="hosted-harness"?false:optsIn.cdpTunnelOverWs??(!envFlagDisabled(cdpTunnelOverWsEnv)&&(cdpTunnelOverWsEnv!==void 0||chromeExtensionOriginAllowed))};let channelRuntime=opts.channelSelection?await loadChannelWorkerRuntime():void 0;let channelServicePidfile=deps.channelServicePidfile??channelRuntime?.channelServicePidfile;const ensureChannelRuntime=__name(async()=>{channelRuntime??=await loadChannelWorkerRuntime();channelServicePidfile??=channelRuntime.channelServicePidfile;return channelRuntime},"ensureChannelRuntime");let channelPidfileReserved=false;const removeCurrentServePidfile=__name(()=>{if(!channelServicePidfile)return;if(!channelPidfileReserved)return;if(channelServicePidfile.removeServeServiceInfo){if(channelServicePidfile.removeServeServiceInfo(process.pid)){channelPidfileReserved=false}else{const info2=channelServicePidfile.readServiceInfo();if(!info2||info2.owner!=="serve"||info2.pid!==process.pid||info2.servePid!==process.pid){channelPidfileReserved=false}}return}const info=channelServicePidfile.readServiceInfo();if(info?.owner==="serve"&&info.pid===process.pid&&info.servePid===process.pid){channelServicePidfile.removeServiceInfo();const remaining=channelServicePidfile.readServiceInfo();channelPidfileReserved=remaining?.owner==="serve"&&remaining.pid===process.pid&&remaining.servePid===process.pid}else{channelPidfileReserved=false}},"removeCurrentServePidfile");const reserveChannelServicePidfile=__name(selection=>{if(!channelServicePidfile){throw new Error("Channel service pidfile runtime is not available.")}const channelPidfileNames=channelSelectionNames(selection);const existingChannelService=channelServicePidfile.readServiceInfo();if(existingChannelService){throw channelServicePidfileConflictError(existingChannelService)}try{writeServeChannelReservation(channelServicePidfile,channelPidfileNames);channelPidfileReserved=true}catch(err){if(err&&typeof err==="object"&&"code"in err){const code=err.code;if(code==="EEXIST"){const info=channelServicePidfile.readServiceInfo();if(info){throw channelServicePidfileConflictError(info)}try{writeServeChannelReservation(channelServicePidfile,channelPidfileNames);channelPidfileReserved=true;return}catch(retryErr){if(retryErr&&typeof retryErr==="object"&&"code"in retryErr&&retryErr.code==="EEXIST"){throw channelServiceStartingConflictError()}throw retryErr}}}throw err}},"reserveChannelServicePidfile");validateRateLimitOptions(opts);if(!opts.hostname.startsWith("[")&&opts.hostname.split(":").length===2){const[host,port]=opts.hostname.split(":");throw new Error(`Invalid --hostname "${opts.hostname}": looks like a "host:port" combination. Use --port for the port, e.g. "--hostname ${host} --port ${port}".`)}let tlsOptions;let tlsCertPath;if(opts.tlsCert&&!opts.tlsKey||!opts.tlsCert&&opts.tlsKey){throw new Error(`--tls-cert and --tls-key must be provided together (got only --tls-${opts.tlsCert?"cert":"key"}).`)}if(opts.tlsCert&&opts.tlsKey){let cert;let key;try{cert=fs.readFileSync(opts.tlsCert)}catch(err){throw new Error(`Failed to read --tls-cert "${opts.tlsCert}": ${err instanceof Error?err.message:String(err)}`)}try{key=fs.readFileSync(opts.tlsKey)}catch(err){throw new Error(`Failed to read --tls-key "${opts.tlsKey}": ${err instanceof Error?err.message:String(err)}`)}let x509;try{x509=new X509Certificate(cert)}catch(err){throw new Error(`--tls-cert "${opts.tlsCert}" is not a valid certificate: ${err instanceof Error?err.message:String(err)}`)}const now=Date.now();if(new Date(x509.validTo).getTime()<now){throw new Error(`--tls-cert "${opts.tlsCert}" expired on ${x509.validTo}. Renew the certificate and restart.`)}if(new Date(x509.validFrom).getTime()>now){throw new Error(`--tls-cert "${opts.tlsCert}" is not yet valid (validFrom: ${x509.validFrom}). Check the certificate's notBefore date or the system clock.`)}tlsOptions={cert,key};tlsCertPath=path.resolve(opts.tlsCert)}if(!isLoopbackBind(opts.hostname)&&!token){throw new Error(`Refusing to bind ${opts.hostname}:${opts.port} without a bearer token (an explicitly empty --token or ${QWEN_SERVER_TOKEN_ENV} counts as none, since a blank source never generates one). Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or rebind to loopback (127.0.0.0/8, localhost, ::1, or [::1]).`)}if(opts.requireAuth&&!token){throw new Error(`Refusing to start with --require-auth set but no bearer token configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or omit --require-auth to keep the loopback developer default.`)}if(opts.allowOrigins&&opts.allowOrigins.length>0){const parsed=parseAllowOriginPatterns(opts.allowOrigins);if(parsed.allowAny&&!token){throw new Error(`Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or list specific origins instead of '*'.`)}const nonLoopbackHttpOrigin=findNonLoopbackHttpOrigin(parsed);if(nonLoopbackHttpOrigin&&!token){throw new Error(`Refusing to start with --allow-origin ${JSON.stringify(nonLoopbackHttpOrigin)} but no bearer token configured. Non-loopback HTTP(S) browser origins can drive the full operator API, including code execution as the daemon user. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or use a loopback origin.`)}writeStderrLine(`qwen serve: --allow-origin: ${opts.allowOrigins.join(", ")}`+(parsed.allowAny?" (WARNING: `*` admits any cross-origin browser \u2014 bearer token gates API routes; the Web Shell static assets stay pre-auth in every mode unless --no-web, and /health stays pre-auth on loopback unless --require-auth is set)":trustedLoopbackMode?" (WARNING: these browser origins receive full API authority without a bearer token in trusted loopback mode and can execute code as the daemon user)":""))}if(opts.allowPrivateAuthBaseUrl){writeStderrLine("qwen serve: --allow-private-auth-base-url enabled; /workspace/auth/provider may install localhost/private-network model endpoints. Use only for local development with trusted clients.")}const validateAndCanonicalizeWorkspace=validateAndCanonicalizeWorkspaceInput;const liveConversationWorkspace=deps.liveConversationWorkspace??new ConversationWorkspace;const isReservedConversationWorkspace=__name(candidate=>{const resolvedCandidate=path.resolve(candidate);const resolvedRoot=path.resolve(liveConversationWorkspace.rootPath);let canonicalRoot=resolvedRoot;try{canonicalRoot=fs.realpathSync.native(resolvedRoot)}catch{}return resolvedCandidate===resolvedRoot||isWithinRoot(resolvedCandidate,resolvedRoot)||resolvedCandidate===canonicalRoot||isWithinRoot(resolvedCandidate,canonicalRoot)},"isReservedConversationWorkspace");const reservedRawWorkspace=rawWorkspaces.find(workspace=>isReservedConversationWorkspace(workspace));if(reservedRawWorkspace){throw new Error(`Workspace ${JSON.stringify(reservedRawWorkspace)} is reserved for Conversations.`)}const workspaceInputs=rawWorkspaces.map(workspace=>({raw:workspace,cwd:validateAndCanonicalizeWorkspace(workspace),displayName:void 0,removable:false,registrationIds:[]}));const boundWorkspace=workspaceInputs[0].cwd;const seenCanonicalWorkspaces=new Set;for(const workspace of workspaceInputs){if(seenCanonicalWorkspaces.has(workspace.cwd)){throw new Error(`Duplicate --workspace value resolves to ${JSON.stringify(workspace.cwd)}.`)}seenCanonicalWorkspaces.add(workspace.cwd)}for(let i=0;i<workspaceInputs.length;i++){for(let j=i+1;j<workspaceInputs.length;j++){const first=workspaceInputs[i].cwd;const second=workspaceInputs[j].cwd;const firstRel=path.relative(first,second);const secondRel=path.relative(second,first);if(firstRel&&!firstRel.startsWith("..")&&!path.isAbsolute(firstRel)){throw new Error(`Nested --workspace values are not supported: ${JSON.stringify(second)} is inside ${JSON.stringify(first)}.`)}if(secondRel&&!secondRel.startsWith("..")&&!path.isAbsolute(secondRel)){throw new Error(`Nested --workspace values are not supported: ${JSON.stringify(first)} is inside ${JSON.stringify(second)}.`)}}}if(workspaceInputs.length>opts.maxRegisteredWorkspaces){throw new Error(`At most ${opts.maxRegisteredWorkspaces} --workspace values may be registered.`)}opts.daemonMemoryBudget=resolveDaemonMemoryBudget({budgetMb:opts.memoryBudgetMb});if((opts.childHeapMode==="admit"||opts.childHeapMode==="enforce")&&deps.bridge){throw new TypeError("ACP admission cannot be combined with an injected bridge.")}const admissionPolicy=opts.childHeapMode==="admit"||opts.childHeapMode==="enforce"?createChildHeapPolicy({budget:opts.daemonMemoryBudget,mode:opts.childHeapMode}):void 0;if(opts.daemonMemoryBudget.budgetSource==="flag"||opts.daemonMemoryBudget.insufficientMemory){writeStderrLine(formatMemoryBudgetStderr(opts.daemonMemoryBudget))}const journalGrowthPoolMbValue=opts.daemonMemoryBudget!==void 0?serveJournalGrowthPoolMb({budget:opts.daemonMemoryBudget,maxJournalEvents:opts.maxJournalEvents,maxJournalBytes:opts.maxJournalBytes}):0;const journalGrowthPoolBytes=journalGrowthPoolMbValue>0?journalGrowthPoolMbValue*1024*1024:void 0;const journalGrowthSessionLimitProviders=new Set;const journalGrowthSessionLimits=__name(()=>{const limits=[];for(const provider of journalGrowthSessionLimitProviders){limits.push(...provider())}return limits},"journalGrowthSessionLimits");const registerJournalGrowthSessionLimits=__name(provider=>{journalGrowthSessionLimitProviders.add(provider);return()=>{journalGrowthSessionLimitProviders.delete(provider)}},"registerJournalGrowthSessionLimits");const reservedStartupWorkspace=workspaceInputs.find(workspace=>isReservedConversationWorkspace(workspace.cwd));if(reservedStartupWorkspace){throw new Error(`Workspace ${JSON.stringify(reservedStartupWorkspace.raw)} is reserved for Conversations.`)}let workspaceRegistrationStore=deps.workspaceRegistrationStore;const explicitWorkspaceCount=workspaceInputs.length;if(workspaceRegistrationStore===void 0&&process.env["QWEN_SERVE_NO_PERSISTENT_REGISTRATION"]!=="1"){const{WorkspaceRegistrationStore}=await import("./workspace-registration-store-WQRDSIEI.js");workspaceRegistrationStore=new WorkspaceRegistrationStore(boundWorkspace)}if(workspaceRegistrationStore){try{const stored=await workspaceRegistrationStore.read();for(const storedWorkspace of stored.workspaces){const registrationId=workspaceRegistrationId(storedWorkspace);const displayName=stored.displayNames?.[registrationId];if(isReservedConversationWorkspace(storedWorkspace)){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: path is reserved for Conversations`);continue}let cwd;try{cwd=validateAndCanonicalizeWorkspace(storedWorkspace);readSshWorkspace(cwd)}catch(err){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: ${err instanceof Error?err.message:String(err)}`);continue}if(isReservedConversationWorkspace(cwd)){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: path is reserved for Conversations`);continue}const existingInput=workspaceInputs.find(workspace=>workspace.cwd===cwd);if(existingInput){existingInput.registrationIds.push(registrationId);existingInput.displayName??=displayName;continue}const nested=workspaceInputs.some(workspace=>isWithinRoot(cwd,workspace.cwd)||isWithinRoot(workspace.cwd,cwd));if(nested){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: path nests with an explicit or earlier restored workspace`);continue}workspaceInputs.push({raw:storedWorkspace,cwd,displayName,removable:true,registrationIds:[registrationId]})}}catch(err){writeStderrLine(`qwen serve: failed to read persisted workspace registrations: ${err instanceof Error?err.message:String(err)}; continuing with explicit workspaces only`)}}if(workspaceInputs.length>opts.maxRegisteredWorkspaces){throw new Error(`${explicitWorkspaceCount} explicit + ${workspaceInputs.length-explicitWorkspaceCount} restored workspaces exceed the configured limit of ${opts.maxRegisteredWorkspaces}. Restart with the previous capacity, forget registrations and reduce explicit --workspace values before lowering the limit. The registration store was not changed.`)}if(workspaceInputs.length>1&&deps.bridge){throw new Error("Injected bridge dependencies are only supported with a single workspace; multiple --workspace values require runQwenServe to construct one bridge per workspace.")}let contextFilenameForInit;let permissionPolicy;let permissionConsensusQuorum;let bootSettings;let sessionArtifactsPersistenceAvailable=true;try{bootSettings=deps.bootSettings??loadServeFastPathSettings(boundWorkspace);sessionArtifactsPersistenceAvailable=sessionArtifactsPersistenceAvailableFromSettings(bootSettings);contextFilenameForInit=extractContextFilename(bootSettings.context?.fileName);const policyConfig=bootSettings.policy??{};const resolved=validatePolicyConfig(policyConfig);permissionPolicy=resolved.permissionPolicy;permissionConsensusQuorum=resolved.permissionConsensusQuorum}catch(err){if(err instanceof InvalidPolicyConfigError||err instanceof InvalidExecutionSandboxConfigError){throw err}writeStderrLine(`qwen serve: could not read settings for context.fileName / policy.* / serve.channels / serve.tokenQr (${err instanceof Error?err.message:String(err)}); falling back to defaults. Restart with a valid settings.json to apply context.fileName / policy.* / serve.channels / serve.tokenQr overrides.`)}assertExecutionSandboxSupported(bootSettings??{},"serve / ACP / web terminals");const daemonLogBaseDir=await resolveDaemonLogBaseDirForRun({deps,bootSettings,boundWorkspace});const daemonLog=await initDaemonLogger({boundWorkspace,baseDir:daemonLogBaseDir});loggerLifecycle.initialized(daemonLog);let channelSelectionFromSettings=false;const channelSelectionFromFlag=opts.channelSelection!==void 0;const bootChannelOwnerHints=new Map;let channelOwnerHints=new Map;let channelStartupTolerantNames=new Set;const lateRestoredWorkspaces=new Set;let bootChannelClaimants=new Map;const channelRestoreFailures=createChannelRestoreFailures({isStale:__name(failure=>{if(channelWorkerManager?.committedChannelNames().includes(failure.channel)){return true}const registry=(runtimeApp??runtimeAppForCleanup)?.locals?.["workspaceRegistry"];return registry?!registry.getByWorkspaceCwd(failure.workspaceCwd):false},"isStale")});let channelHostingStoppedByOperator=false;const reportConfiguredChannelStartupFailure=__name(error=>{const message=sanitizeLogText(redactLogCredentials(error instanceof Error?error.message:String(error)),512);const detail=/[.!?]$/.test(message)?message:`${message}.`;writeStderrLine(`qwen serve: workspace serve.channels was not restored: ${detail} Continuing without channels.`);daemonLog.warn(`workspace serve.channels was not restored: ${detail} Continuing without channels`)},"reportConfiguredChannelStartupFailure");const reportStartupChannelDiagnostic=__name(diagnostic=>{const detail=sanitizeLogText(redactLogCredentials(diagnostic.message),512);if(diagnostic.code==="invalid_entry"){daemonLog.warn(detail,{workspaceCwd:diagnostic.workspaceCwd});return}if(diagnostic.code==="claimed_by_multiple_workspaces"){daemonLog.warn(detail,{code:diagnostic.code,workspaceCwd:diagnostic.workspaceCwd,...diagnostic.channel?{channel:diagnostic.channel}:{}});return}writeStderrLine(`qwen serve: workspace ${JSON.stringify(diagnostic.workspaceCwd)} serve.channels: ${detail}`);daemonLog.warn(`workspace serve.channels not fully restored: ${detail}`,{code:diagnostic.code,workspaceCwd:diagnostic.workspaceCwd,...diagnostic.channel?{channel:diagnostic.channel}:{}})},"reportStartupChannelDiagnostic");const startupChannelWorkspaces=workspaceInputs.filter(workspace=>!readSshWorkspace(workspace.cwd)).map((workspace,index)=>({workspaceCwd:workspace.cwd,primary:index===0}));const loadStartupChannelsFor=__name(workspaceCwd=>(workspaceCwd===boundWorkspace?bootSettings:loadServeFastPathSettings(workspaceCwd))?.serve?.channels,"loadStartupChannelsFor");const startupChannelsForWorkspace=__name(workspaceCwd=>{if(opts.profile==="hosted-harness")return[];const restored=resolveStartupChannelSelection({workspaces:[{workspaceCwd,primary:false}],loadStartupChannels:__name(cwd=>loadServeFastPathSettings(cwd)?.serve?.channels,"loadStartupChannels")});for(const diagnostic of restored.diagnostics){reportStartupChannelDiagnostic(diagnostic)}return restored.selection?.mode==="names"?restored.selection.names:[]},"startupChannelsForWorkspace");if(opts.profile!=="hosted-harness"&&!opts.channelSelection&&(bootSettings?.serve?.channels!==void 0||startupChannelWorkspaces.length>1)){try{const restored=resolveStartupChannelSelection({workspaces:startupChannelWorkspaces,loadStartupChannels:loadStartupChannelsFor});for(const diagnostic of restored.diagnostics){reportStartupChannelDiagnostic(diagnostic)}opts.channelSelection=restored.selection;if(opts.channelSelection){channelSelectionFromSettings=true;for(const[name,owner]of restored.ownerHints){bootChannelOwnerHints.set(name,owner)}channelOwnerHints=new Map(bootChannelOwnerHints);channelStartupTolerantNames=restored.tolerantNames;bootChannelClaimants=restored.claimants;channelRuntime=await ensureChannelRuntime();daemonLog.info("restoring channels from workspace serve.channels",{channels:channelSelectionNames(opts.channelSelection),workspaceCwd:boundWorkspace,...restored.ownerHints.size>0?{requestedByWorkspace:[...restored.ownerHints].map(([name,owner])=>`${name}@${owner}`).join(",")}:{}})}}catch(error){opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error)}}daemonLog.info("project memory scope resolved",{projectMemoryScope:resolvedMemoryProjectScope,projectMemoryScopeSource:memoryProjectScopeSource,projectMemoryScopeRaw:memoryProjectScopeValue});const loaderRejectionReporter=__name((source,freshKeys)=>{daemonLog.warn("rejected loader-affecting env keys; they were not applied",{source,rejectedKeys:freshKeys})},"loaderRejectionReporter");setLoaderKeyRejectionReporter(loaderRejectionReporter);loggerLifecycle.reporterInstalled(loaderRejectionReporter);if(scrubbedLoaderEnvKeys.length>0){daemonLog.info("scrubbed inherited loader env vars from the daemon process; session subprocesses will not inherit them",{removedKeys:scrubbedLoaderEnvKeys})}const fastPathRejectedLoaderKeys=consumeServeFastPathRejectedLoaderKeys();if(fastPathRejectedLoaderKeys.length>0){daemonLog.info("rejected loader-affecting env keys during serve fast-path boot; they were not applied to the daemon process",{rejectedKeys:fastPathRejectedLoaderKeys})}let loggerPublished=false;let loggerSignalOwned=false;writeStderrLine(`qwen serve: daemon log \u2192 ${daemonLog.getLogPath()||"(disabled)"}`);if(opts.mcpClientBudget!==void 0){if(!Number.isFinite(opts.mcpClientBudget)||!Number.isInteger(opts.mcpClientBudget)||opts.mcpClientBudget<=0){throw new TypeError(`Invalid mcpClientBudget: ${opts.mcpClientBudget}. Must be a positive integer.`)}}if(opts.mcpBudgetMode==="enforce"&&opts.mcpClientBudget===void 0){throw new Error('mcpBudgetMode="enforce" requires a positive mcpClientBudget. Pass mcpClientBudget=N, or set mcpBudgetMode to "warn" or "off".')}if(opts.promptDeadlineMs!==void 0){if(!isPositiveIntegerMs(opts.promptDeadlineMs)){throw new TypeError(`Invalid promptDeadlineMs: ${opts.promptDeadlineMs}. Must be a positive integer (milliseconds).`)}assertTimerDelayInRange("promptDeadlineMs",opts.promptDeadlineMs)}if(opts.maxSessions!==void 0){if(Number.isNaN(opts.maxSessions)||opts.maxSessions<0){throw new TypeError(`Invalid maxSessions: ${opts.maxSessions}. Must be a number >= 0 (0 / Infinity = unlimited).`)}}if(opts.maxTotalSessions!==void 0){if(!isNonNegativeIntegerOrInfinity(opts.maxTotalSessions)){throw new TypeError(`Invalid maxTotalSessions: ${opts.maxTotalSessions}. Must be a non-negative integer (0 / Infinity = unlimited).`)}}if(opts.maxPendingPromptsPerSession!==void 0){if(!isNonNegativeIntegerOrInfinity(opts.maxPendingPromptsPerSession)){throw new TypeError(`Invalid maxPendingPromptsPerSession: ${opts.maxPendingPromptsPerSession}. Must be a non-negative integer (0 / Infinity = unlimited).`)}}if(opts.eventRingSize!==void 0){if(!Number.isInteger(opts.eventRingSize)||opts.eventRingSize<1||opts.eventRingSize>MAX_EVENT_RING_SIZE){throw new TypeError(`Invalid eventRingSize: ${opts.eventRingSize}. Must be a positive integer in [1, ${MAX_EVENT_RING_SIZE}].`)}}if(opts.compactedReplayMaxBytes!==void 0){normalizeCompactedReplayMaxBytes(opts.compactedReplayMaxBytes)}if(opts.maxJournalEvents!==void 0){normalizeMaxJournalEvents(opts.maxJournalEvents)}if(opts.maxJournalBytes!==void 0){normalizeMaxJournalBytes(opts.maxJournalBytes)}if(opts.writerIdleTimeoutMs!==void 0){if(!isPositiveIntegerMs(opts.writerIdleTimeoutMs)){throw new TypeError(`Invalid writerIdleTimeoutMs: ${opts.writerIdleTimeoutMs}. Must be a positive integer (milliseconds).`)}}if(opts.channelIdleTimeoutMs!==void 0){if(!Number.isFinite(opts.channelIdleTimeoutMs)||!Number.isInteger(opts.channelIdleTimeoutMs)||opts.channelIdleTimeoutMs<0){throw new TypeError(`Invalid channelIdleTimeoutMs: ${opts.channelIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = immediate kill).`)}}if(opts.sessionReapIntervalMs!==void 0){if(!isNonNegativeIntegerMs(opts.sessionReapIntervalMs)){throw new TypeError(`Invalid sessionReapIntervalMs: ${opts.sessionReapIntervalMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`)}}if(opts.sessionIdleTimeoutMs!==void 0){if(!isNonNegativeIntegerMs(opts.sessionIdleTimeoutMs)){throw new TypeError(`Invalid sessionIdleTimeoutMs: ${opts.sessionIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`)}}if(opts.sessionPromptSettledCloseGraceMs!==void 0){if(!isNonNegativeIntegerMs(opts.sessionPromptSettledCloseGraceMs)){throw new TypeError(`Invalid sessionPromptSettledCloseGraceMs: ${opts.sessionPromptSettledCloseGraceMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`)}}if(opts.initializeTimeoutMs!==void 0){if(!isPositiveIntegerMs(opts.initializeTimeoutMs)){throw new TypeError(`Invalid initializeTimeoutMs: ${opts.initializeTimeoutMs}. Must be a positive integer (milliseconds).`)}assertTimerDelayInRange("initializeTimeoutMs",opts.initializeTimeoutMs)}const sessionRestoreTimeoutMs=resolveSessionRestoreTimeoutMs(opts);opts.sessionRestoreTimeoutMs=sessionRestoreTimeoutMs;if(opts.permissionResponseTimeoutMs!==void 0){if(!Number.isFinite(opts.permissionResponseTimeoutMs)||!Number.isInteger(opts.permissionResponseTimeoutMs)||opts.permissionResponseTimeoutMs<0){throw new TypeError(`Invalid permissionResponseTimeoutMs: ${opts.permissionResponseTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled / wait forever).`)}}const rawExternalToolGuard=opts.externalToolGuard;if(rawExternalToolGuard!==void 0&&(typeof rawExternalToolGuard!=="object"||rawExternalToolGuard===null||rawExternalToolGuard.mode!=="required")){throw new TypeError("Invalid externalToolGuard: omit it for off mode or set mode to 'required'.")}opts.maxTotalSessions??=deriveDefaultMaxTotalSessions(opts.maxSessions,workspaceInputs.length,opts.maxRegisteredWorkspaces);const inheritedNoPool=process.env["QWEN_SERVE_NO_MCP_POOL"]==="1";if(opts.mcpPoolActive===void 0&&inheritedNoPool){opts.mcpPoolActive=false}let externalToolGuardHandler;if(opts.externalToolGuard?.mode==="required"){if(deps.bridge){throw new Error("Required external tool guarding cannot be combined with an injected bridge.")}const{RequiredExternalToolGuard}=await import("./external-tool-guard-provider-G7SGGL2X.js");const provider=new RequiredExternalToolGuard({endpoint:opts.externalToolGuard.endpoint,token:opts.externalToolGuard.token,...opts.externalToolGuard.timeoutMs!==void 0?{timeoutMs:opts.externalToolGuard.timeoutMs}:{}});await provider.initialize();externalToolGuardHandler=provider.prepare;writeStderrLine("qwen serve: required external tool guard handshake succeeded.")}const{createDaemonToolGuard}=await import("./daemon-git-worktree-guard-6XQQPP2H.js");const daemonToolGuardHandler=createDaemonToolGuard(externalToolGuardHandler);const childEnvOverrides={QWEN_SERVE_MCP_CLIENT_BUDGET:opts.mcpClientBudget!==void 0?String(opts.mcpClientBudget):void 0,QWEN_SERVE_MCP_BUDGET_MODE:opts.mcpBudgetMode,QWEN_SERVE_CDP_TUNNEL_OVER_WS:opts.cdpTunnelOverWs?"1":void 0,[PRIVATE_CONVERSATIONS_RUNTIME_ENV]:void 0,[PRIVATE_EXTERNAL_TOOL_GUARD_ENV]:EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV]:externalToolGuardHandler?EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE:void 0};const cliVersionPromise=getCliVersion();let cliVersion;const diagnosticSink=__name((line,level)=>daemonLog.raw(line,level),"diagnosticSink");let actualPort=opts.port;let discoveryRecordPath;const removeDiscoveryRecord=__name(()=>{if(!discoveryRecordPath)return;discoveryRecordPath=void 0;try{removeDaemonDiscovery(actualPort,{expectedPid:process.pid})}catch{}},"removeDiscoveryRecord");const webShellDir=opts.serveWebShell===false?void 0:resolveWebShellDir();if(optsIn.requireWebShell&&!webShellDir){throw new Error("--open-with-auth requires built Web Shell assets.")}if(opts.serveWebShell!==false){if(!webShellDir){writeStderrLine("qwen serve: Web Shell assets not found; serving API only. Build the web-shell workspace (npm run build) or pass --no-web to silence this.")}else{writeStderrLine(`qwen serve: Web Shell UI served from ${webShellDir}`);if(!isLoopbackBind(opts.hostname)){writeStderrLine("qwen serve: Web Shell UI is served WITHOUT auth on a non-loopback bind (the static shell has no secrets; the API stays token-gated). Pass --no-web to disable the UI.");if(!opts.allowOrigins||opts.allowOrigins.length===0){writeStderrLine("qwen serve: same-origin Web Shell HTTP and WebSocket requests work without --allow-origin. Browsers reaching the daemon through a TLS-terminating proxy still need --allow-origin <origin>. A plain-HTTP intermediary that rewrites the Host header (nginx default proxy_set_header, k8s Ingress) needs --allow-origin <origin> for the origin the browser sees, unless it forwards Host verbatim; port translation alone (ssh -L, docker -p) is fine.")}}}}const webShellMounted=!!webShellDir;const serveAppLifecycle=new ServeAppLifecycleController;const restartForUpdate=deps.updateRestartArgv?createDaemonUpdateRestarter({argv:deps.updateRestartArgv,env:daemonRuntimeBaseEnv,token,externalToolGuardToken:optsIn.externalToolGuard?.token,getPort:__name(()=>actualPort,"getPort"),close:__name(()=>serveAppLifecycle.close(),"close")}):void 0;const liveDiscoveryStableBaseDir=path.resolve(deps.liveDiscoveryStableBaseDir??path.join(os2.homedir(),".qwen"));let resolveServeAppStartup;let rejectServeAppStartup;let serveAppStartupSettled=false;const serveAppStartupReady=new Promise((resolve3,reject)=>{resolveServeAppStartup=resolve3;rejectServeAppStartup=reject});void serveAppStartupReady.catch(()=>void 0);const markServeAppStartupReady=__name(()=>{if(serveAppStartupSettled)return;serveAppStartupSettled=true;resolveServeAppStartup()},"markServeAppStartupReady");const markServeAppStartupFailed=__name(error=>{if(serveAppStartupSettled)return;serveAppStartupSettled=true;rejectServeAppStartup(error)},"markServeAppStartupFailed");let runtimeApp;let runtimeAppForCleanup;let getWorkspaceRuntimeCoordinatorIfSupported;let bridgeRef=deps.bridge;let managedProcessRegistry;let managedChildHeapPolicy;const internalRuntimeBridgesForCleanup=[];let daemonEventLoopMonitor;let daemonMetricsSampler;let sessionPrRefreshTimer;let sessionPrRefreshGeneration=0;let runtimeStartupError;let runtimeStarting;let markRuntimeReady;let markRuntimeFailed;let runtimeStartupSettled=false;let startRuntimeAfterHealth;let startRuntimeForRequest;const deferRuntimeUntilFirstHealth=deps.resolveOnListen===true&&deps.deferRuntimeUntilFirstHealth===true;const runtimeReady=new Promise((resolve3,reject)=>{markRuntimeReady=resolve3;markRuntimeFailed=reject});void runtimeReady.catch(()=>{});const disposeDaemonEventLoopMonitor=__name(()=>{const eventLoopMonitor=daemonEventLoopMonitor;daemonEventLoopMonitor=void 0;const metricsSampler=daemonMetricsSampler;daemonMetricsSampler=void 0;const prRefreshTimer=sessionPrRefreshTimer;sessionPrRefreshTimer=void 0;sessionPrRefreshGeneration+=1;prRefreshTimer?.dispose();try{eventLoopMonitor?.dispose()}catch(err){daemonLog.warn(`event loop monitor dispose error: ${err instanceof Error?err.message:String(err)}`)}try{metricsSampler?.dispose()}catch(err){daemonLog.warn(`metrics sampler dispose error: ${err instanceof Error?err.message:String(err)}`)}},"disposeDaemonEventLoopMonitor");let channelWorkerManager;let channelWorkerManagerStarting;let channelControlDraining=false;let channelWorkspaceGroups;const channelWebhookEnvByWorkspace=new Map;let channelWebhookConfigVersion=0;let refreshChannelWebhookConfigs;let ensureChannelWorkerManager;const getChannelWebhookConfigSources=__name(()=>{const app2=runtimeApp??runtimeAppForCleanup;const registry=app2?.locals?.["workspaceRegistry"];return(channelWorkspaceGroups??[]).map(group=>{const env=registry?.getByWorkspaceCwd(group.workspaceCwd)?.env.effectiveEnv??channelWebhookEnvByWorkspace.get(group.workspaceCwd);return{workspaceCwd:group.workspaceCwd,...group.selection.mode==="names"?{channelNames:group.selection.names}:{},...env?{env}:{}}})},"getChannelWebhookConfigSources");const resolveChannelWebhookConfigSource=__name(channelName=>{const source=getChannelWebhookConfigSources().find(source2=>!source2.channelNames||source2.channelNames.includes(channelName));if(source)return source;const env=channelWebhookEnvByWorkspace.get(boundWorkspace);return{workspaceCwd:boundWorkspace,...env?{env}:{}}},"resolveChannelWebhookConfigSource");let closeServerAfterChannelWorkerStartupFailure=false;const getChannelWorkerSnapshot=__name(()=>channelWorkerManager?.primarySnapshot()??{enabled:false,state:"disabled",channels:[]},"getChannelWorkerSnapshot");const getChannelWorkerSnapshots=__name(()=>channelWorkerManager?.snapshots()??[],"getChannelWorkerSnapshots");const getChannelWorkerControl=__name(()=>channelWorkerManager?.state()??{enabled:false,selection:null,transition:"idle",workers:[]},"getChannelWorkerControl");const daemonDrainingError=__name(()=>Object.assign(new Error("Daemon is shutting down."),{code:"daemon_draining"}),"daemonDrainingError");const setChannelWorkerSelection=__name(async selection=>{if(channelControlDraining)throw daemonDrainingError();const manager=await ensureChannelWorkerManager?.();if(!manager)throw new Error("Channel worker manager is unavailable.");if(channelControlDraining){await manager.shutdown().catch(()=>void 0);throw daemonDrainingError()}const result=await manager.setSelection(selection);channelHostingStoppedByOperator=false;channelRestoreFailures.clearAll();return result},"setChannelWorkerSelection");const channelStartupMessages=__name(err=>{const startupFailures=err?.startupFailures;return new Map((Array.isArray(startupFailures)?startupFailures:[]).map(failure=>[failure.channel,failure.message]))},"channelStartupMessages");const lateRestoreFailures=__name((workspaceCwd,requested,err)=>{const committed=new Set(channelWorkerManager?.committedChannelNames());const reported=channelStartupMessages(err);const message=err instanceof Error?err.message:String(err);return requested.filter(channel=>!committed.has(channel)).map(channel=>({workspaceCwd,channel,message:reported.get(channel)??message}))},"lateRestoreFailures");const addChannelsToSelection=__name(async names=>{if(channelControlDraining)throw daemonDrainingError();const manager=await ensureChannelWorkerManager?.();if(!manager)throw new Error("Channel worker manager is unavailable.");if(channelControlDraining){await manager.shutdown().catch(()=>void 0);throw daemonDrainingError()}await manager.addChannels(names,{precondition:__name(()=>!channelHostingStoppedByOperator,"precondition")})},"addChannelsToSelection");const stopChannelWorker=__name(async()=>{if(channelControlDraining)throw daemonDrainingError();const manager=channelWorkerManager??await channelWorkerManagerStarting;if(channelControlDraining){await manager?.shutdown().catch(()=>void 0);throw daemonDrainingError()}if(!manager){return{changed:false,state:getChannelWorkerControl()}}const result=await manager.stopSelection();if(result.changed){channelHostingStoppedByOperator=true;channelRestoreFailures.clearAll()}return result},"stopChannelWorker");const reloadChannelWorker=__name(async()=>{if(channelControlDraining)throw daemonDrainingError();const manager=channelWorkerManager??await channelWorkerManagerStarting;if(channelControlDraining){await manager?.shutdown().catch(()=>void 0);throw daemonDrainingError()}if(!manager){return{enabled:false,state:"disabled",channels:[]}}try{return await manager.reload()}finally{writeChannelWorkerPidfile()}},"reloadChannelWorker");const isLiveWorker=__name(snapshot=>snapshot.state==="running"||snapshot.state==="starting","isLiveWorker");let channelWorkerPidfileUsesWorkers=workspaceInputs.length>1;const writeChannelWorkerPidfile=__name(()=>{if(runtimeStartupError!==void 0)return;if(!channelPidfileReserved||!channelServicePidfile)return;const snapshots=getChannelWorkerSnapshots();const workers=snapshots.map(snapshot=>({workspaceId:snapshot.workspaceId,workspaceCwd:snapshot.workspaceCwd,channels:snapshot.channels,...isLiveWorker(snapshot)&&snapshot.pid!==void 0?{workerPid:snapshot.pid}:{}}));const channels=[...new Set(snapshots.flatMap(snapshot=>snapshot.channels))];const primary=snapshots.find(snapshot=>snapshot.primary);if(workers.length>1||snapshots.some(snapshot=>!snapshot.primary)){channelWorkerPidfileUsesWorkers=true}const includeWorkers=channelWorkerPidfileUsesWorkers&&workers.length>0;try{channelServicePidfile.writeServeServiceInfo({channels,servePid:process.pid,...primary&&isLiveWorker(primary)&&primary.pid!==void 0?{workerPid:primary.pid}:{},...includeWorkers?{workers}:{}})}catch(err){daemonLog.warn(`failed to write channel worker pidfile metadata: ${err instanceof Error?err.message:String(err)}`)}},"writeChannelWorkerPidfile");const handleBridge=deps.bridge??createLazyBridgeProxy(()=>bridgeRef,()=>runtimeStartupError);const shutdownBridges=new WeakSet;const disposedRuntimeApps=new WeakSet;const stoppedRuntimeAppProducers=new WeakSet;const stoppedExtensionReconcilers=new WeakSet;const stoppedTrustPolicyMonitors=new WeakSet;const stopTrustPolicyMonitor=__name(app2=>{if(!app2||stoppedTrustPolicyMonitors.has(app2))return;stoppedTrustPolicyMonitors.add(app2);const stop=app2.locals?.["stopTrustPolicyMonitor"];try{stop?.()}catch(err){daemonLog.warn(`trust policy monitor dispose error: ${err instanceof Error?err.message:String(err)}`)}},"stopTrustPolicyMonitor");const stopExtensionReconciler=__name(app2=>{if(!app2||stoppedExtensionReconcilers.has(app2))return;stoppedExtensionReconcilers.add(app2);const stopExtensionGenerationReconciler=app2.locals?.["stopExtensionGenerationReconciler"];try{stopExtensionGenerationReconciler?.()}catch(err){daemonLog.warn(`extension generation reconciler dispose error: ${err instanceof Error?err.message:String(err)}`)}},"stopExtensionReconciler");const stopRuntimeAppProducers=__name(app2=>{if(!app2||stoppedRuntimeAppProducers.has(app2))return;stoppedRuntimeAppProducers.add(app2);const locals=app2.locals;const stopSafely=__name((name,stop)=>{try{stop?.()}catch(err){daemonLog.warn(`${name} dispose error: ${err instanceof Error?err.message:String(err)}`)}},"stopSafely");stopSafely("MCP App sandbox",locals.stopMcpAppSandbox);stopSafely("scheduled-task keepalive",locals.stopScheduledTaskKeepalive);stopSafely("workspace git state",locals.stopWorkspaceGitState);stopSafely("Live Host coordinator",locals.stopLiveCoordinator);stopSafely("Agent Host reconnect",locals.stopAgentHostRestore);stopSafely("web terminal registry",locals.stopWebTerminalRegistry);stopSafely("Hosted mount handbacks",locals.stopHostedMountHandbacks);stopTrustPolicyMonitor(app2);for(const stop of locals.subSessionStoppers??[]){stopSafely("sub-session launcher",stop)}stopExtensionReconciler(app2)},"stopRuntimeAppProducers");const disposeRuntimeAppResources=__name(app2=>{if(!app2||disposedRuntimeApps.has(app2))return;disposedRuntimeApps.add(app2);stopRuntimeAppProducers(app2);const deviceFlowRegistry=getDeviceFlowRegistry(app2);if(deviceFlowRegistry){try{deviceFlowRegistry.dispose()}catch(err){daemonLog.warn(`device-flow registry dispose error: ${err instanceof Error?err.message:String(err)}`)}}const localControlService=app2.locals?.["localControlService"];if(localControlService){void localControlService.dispose().catch(err=>{daemonLog.warn(`Local Control dispose error: ${err instanceof Error?err.message:String(err)}`)})}const acpHandle=app2.locals?.["acpHandle"];if(acpHandle?.dispose){try{acpHandle.dispose()}catch(err){daemonLog.warn(`ACP handle dispose error: ${err instanceof Error?err.message:String(err)}`)}}const rateLimiter=getRateLimiter(app2);if(rateLimiter){try{rateLimiter.setDraining(true);rateLimiter.dispose()}catch(err){daemonLog.warn(`rate limiter dispose error: ${err instanceof Error?err.message:String(err)}`)}}disposeDaemonEventLoopMonitor()},"disposeRuntimeAppResources");const getRuntimeBridgesForCleanup=__name(()=>{const appForCleanup=runtimeApp??runtimeAppForCleanup;const registry=appForCleanup?.locals?.["workspaceRegistry"];const bridges=[...registry?registry.listManaged().map(runtime=>runtime.bridge):[],...bridgeRef?[bridgeRef]:[],...internalRuntimeBridgesForCleanup];return[...new Set(bridges)]},"getRuntimeBridgesForCleanup");const buildRuntime=__name(async()=>{const[runtime,core,settingsRuntime,resolvedCliVersion,trustPolicy,workflowTrust]=await Promise.all([loadServeRuntimeModules(),loadCoreRuntime(),loadSettingsRuntimeModules(),cliVersionPromise,import("./daemon-trust-policy-GXKJVZDU.js"),import("./workflow-ancestor-trust-F7RRN6I3.js")]);getWorkspaceRuntimeCoordinatorIfSupported=runtime.getWorkspaceRuntimeCoordinatorIfSupported;cliVersion=resolvedCliVersion;settingsRuntime.environment.preResolveHomeEnvOverrides();const bootTrustSnapshot=await trustPolicy.readDaemonTrustPolicySnapshot();let latestTrustPolicySnapshot=bootTrustSnapshot;let publishedWorkflowTrustPolicy={publication:0,snapshot:bootTrustSnapshot};const bootWorkflowTrustAdmission={publication:0,snapshot:bootTrustSnapshot};const workflowTrustAdmissions=new WeakMap;workflowTrustAdmissions.set(bootTrustSnapshot,bootWorkflowTrustAdmission);const readWorkflowTrustAdmission=__name(async()=>{const admission=await workflowTrust.readWorkflowTrustAdmission(trustPolicy.readDaemonTrustPolicySnapshot,()=>publishedWorkflowTrustPolicy);workflowTrustAdmissions.set(admission.snapshot,admission);return admission},"readWorkflowTrustAdmission");const workflowTrustIdeScopeCwd=process.cwd();const bootPrimaryTrustDecision=trustPolicy.evaluateDaemonWorkspaceTrust(bootTrustSnapshot,boundWorkspace);const trustedWorkspace=deps.trustedWorkspace??bootPrimaryTrustDecision.targetTrusted;if(shouldPreheat&&!trustedWorkspace){shouldPreheat=false;startup.preheat.status="not_scheduled"}const workspaceTrustHotReloadAvailable=deps.trustedWorkspace===void 0&&deps.bridge===void 0&&deps.fsFactory===void 0;let managedScratchRoot;try{managedScratchRoot=prepareManagedScratchRoot(path.join(core.Storage.getGlobalQwenDir(),"scratch-workspaces"),workspaceInputs.map(workspace=>workspace.cwd))}catch(err){writeStderrLine(`qwen serve: managed scratch workspaces are unavailable: ${err instanceof Error?err.message:String(err)}`)}let runtimeBootSettings;try{runtimeBootSettings=settingsRuntime.settings.loadSettings(boundWorkspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trustedWorkspace,workspaceTrusted:trustedWorkspace})}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: could not read full settings for runtime startup (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}assertExecutionSandboxSupported(runtimeBootSettings?.merged??{},"serve workspace runtimes");if(deps.trustedWorkspace===void 0&&runtimeBootSettings&&!trustedWorkspace){daemonLog.warn("workspace file writes are disabled because the bound workspace is not trusted",{workspace:boundWorkspace})}const runtimeEnvSnapshot=runtimeBootSettings?settingsRuntime.environment.buildRuntimeEnvironment(runtimeBootSettings.merged,boundWorkspace,daemonRuntimeBaseEnv,trustedWorkspace):{effectiveEnv:{...daemonRuntimeBaseEnv},overlayKeys:Object.freeze([]),envFilePaths:Object.freeze([]),envFileReadFailed:false,envFileReadFailures:Object.freeze([])};const resolveSessionRuntimeBaseDir=__name((workspace,settings,effectiveEnv)=>{const resolveConfiguredPath=__name((configuredPath,relativeTo)=>{const expanded=configuredPath==="~"?os2.homedir():configuredPath.startsWith("~/")||configuredPath.startsWith("~\\")?path.join(os2.homedir(),...configuredPath.slice(2).split(/[/\\]+/).filter(Boolean)):configuredPath;return path.resolve(relativeTo,expanded)},"resolveConfiguredPath");const runtimeDir=effectiveEnv["QWEN_RUNTIME_DIR"];if(runtimeDir){return resolveConfiguredPath(runtimeDir,process.cwd())}const settingsDir=settings?.merged.advanced?.runtimeOutputDir;if(settingsDir){return resolveConfiguredPath(settingsDir,workspace)}const qwenHome=effectiveEnv["QWEN_HOME"];if(qwenHome){return resolveConfiguredPath(qwenHome,process.cwd())}const homeDir=os2.homedir();return homeDir?path.join(homeDir,".qwen"):path.join(os2.tmpdir(),".qwen")},"resolveSessionRuntimeBaseDir");const logRuntimeEnvFileReadFailures=__name((workspace,snapshot)=>{if(!snapshot.envFileReadFailed)return;const failedFiles=snapshot.envFileReadFailures??[];daemonLog.warn("one or more runtime env files could not be read",{workspace,...failedFiles.length>0?{failedFiles}:{}})},"logRuntimeEnvFileReadFailures");logRuntimeEnvFileReadFailures(boundWorkspace,runtimeEnvSnapshot);const primarySessionRuntimeBaseDir=resolveSessionRuntimeBaseDir(boundWorkspace,runtimeBootSettings,runtimeEnvSnapshot.effectiveEnv);const runtimeEffectiveEnv={...runtimeEnvSnapshot.effectiveEnv,QWEN_RUNTIME_DIR:primarySessionRuntimeBaseDir};const replaceRuntimeEffectiveEnv=__name(nextEnv=>{for(const key of Object.keys(runtimeEffectiveEnv)){delete runtimeEffectiveEnv[key]}Object.assign(runtimeEffectiveEnv,nextEnv);runtimeEffectiveEnv["QWEN_RUNTIME_DIR"]=primarySessionRuntimeBaseDir},"replaceRuntimeEffectiveEnv");const primaryRuntimeEnv={mode:"runtime-overlay",overlayKeys:[...runtimeEnvSnapshot.overlayKeys],effectiveEnv:runtimeEffectiveEnv,workflowsEnabledBySettings:runtimeBootSettings?.merged.tools?.workflowsEnabled===true,envFilePaths:[...runtimeEnvSnapshot.envFilePaths],envFileReadFailed:runtimeEnvSnapshot.envFileReadFailed,envFileReadFailures:[...runtimeEnvSnapshot.envFileReadFailures]};const daemonWorkspaceHash=core.hashDaemonWorkspace(boundWorkspace);let daemonTelemetrySettings;try{daemonTelemetrySettings=await core.resolveTelemetrySettings({env:process.env,settings:runtimeBootSettings?.merged.telemetry})}catch(err){if(err instanceof core.FatalConfigError){throw new core.FatalConfigError(`Invalid telemetry configuration: ${err.message}.`)}throw err}await core.initializeTelemetry(createDaemonTelemetryRuntimeConfig(daemonTelemetrySettings,resolvedCliVersion,`daemon:${process.pid}`,{otlpEndpoint:core.DEFAULT_OTLP_ENDPOINT,telemetryTarget:core.DEFAULT_TELEMETRY_TARGET}));core.initializeDaemonMetrics();daemonEventLoopMonitor?.dispose();daemonEventLoopMonitor=core.startEventLoopLagMonitor({onNewMaxStall:__name(maxMs=>{daemonLog.warn("daemon event loop stall detected",{maxMs})},"onNewMaxStall")});const currentDaemonEventLoopMonitor=daemonEventLoopMonitor;core.registerDaemonEventLoopLagGauge(()=>currentDaemonEventLoopMonitor.snapshot());const metricsRing=new DaemonMetricsRing({capacity:DAEMON_METRICS_CAPACITY});const pipeStats={inbound:{count:0,totalBytes:0,maxBytes:0},outbound:{count:0,totalBytes:0,maxBytes:0}};const promptQueueWaitStats={count:0,totalMs:0,maxMs:0,lastMs:null};const recordPipeMessage=__name((direction,bytes)=>{const stats=pipeStats[direction];stats.count+=1;stats.totalBytes+=bytes;stats.maxBytes=Math.max(stats.maxBytes,bytes);core.recordDaemonPipeMessage(direction,bytes);metricsRing.recordPipe(direction,bytes)},"recordPipeMessage");const observeLargePipeFrame=createLargePipeFrameObserver({daemonLog,emitTelemetryLog:core.emitDaemonLog});const warnAcpQueueSaturated=__name(info=>{daemonLog.warn("ACP NDJSON decoded queue saturated",{requiredBytes:info.requiredBytes,availableBytes:info.availableBytes,maxQueuedMessages:info.maxQueuedMessages,maxQueuedBytes:info.maxQueuedBytes,queueSaturationGraceMs:info.graceMs})},"warnAcpQueueSaturated");const recordPromptQueueWait=__name(durationMs=>{promptQueueWaitStats.count+=1;promptQueueWaitStats.totalMs+=durationMs;promptQueueWaitStats.maxMs=Math.max(promptQueueWaitStats.maxMs,durationMs);promptQueueWaitStats.lastMs=durationMs;core.recordDaemonPromptQueueWait(durationMs)},"recordPromptQueueWait");const createRuntimeBridgeTelemetry=__name(workspaceHash=>{const telemetry=core.createDaemonBridgeTelemetry();telemetry.metrics={sessionLifecycle(action){core.recordDaemonSessionLifecycle(action);core.emitDaemonLog(`Session ${action}.`,{"qwen-code.workspace.hash":workspaceHash},{eventName:`qwen-code.daemon.session.${action}`})},channelLifecycle(action,expected){core.recordDaemonChannelLifecycle(action,expected);core.emitDaemonLog(action==="spawn"?"ACP channel spawned.":`ACP channel exited (expected=${expected??true}).`,{...action==="exit"?{"qwen-code.daemon.channel.expected":expected??true}:{}},{eventName:`qwen-code.daemon.channel.${action}`,...expected===false&&action==="exit"?{severityNumber:13}:{}})},promptQueueWait(durationMs){recordPromptQueueWait(durationMs);metricsRing.recordPromptQueueWait(durationMs)},promptDuration(durationMs){core.recordDaemonPromptDuration(durationMs);metricsRing.recordPromptDuration(durationMs)},cancelled:core.recordDaemonCancel,tokenUsage(inputTokens,outputTokens,durationMs,apiErrors,apiRetries){metricsRing.recordTokens(inputTokens,outputTokens);if(typeof durationMs==="number"){metricsRing.recordLlmDuration(durationMs)}metricsRing.recordApiActivity(apiErrors??0,apiRetries??0)}};return telemetry},"createRuntimeBridgeTelemetry");const daemonTelemetry=createRuntimeBridgeTelemetry(daemonWorkspaceHash);const permissionAuditRing=new PermissionAuditRing;const permissionAuditPublisher=createPermissionAuditPublisher({ring:permissionAuditRing});const customIgnoreFiles=runtimeBootSettings?.merged.context?.fileFiltering?.customIgnoreFiles;const boundWorkspaces=runtime.resolveBoundWorkspacesFromIdeEnv(boundWorkspace,void 0,(workspace,index)=>{if(index===0)return true;const trustedSecondary=trustPolicy.evaluateDaemonWorkspaceTrust(bootTrustSnapshot,workspace).targetTrusted;if(!trustedSecondary){daemonLog.warn("excluding untrusted secondary workspace root from file-system access",{workspace})}return trustedSecondary});daemonLog.info("daemon workspace roots initialized",{primary:boundWorkspaces[0],secondary:boundWorkspaces.slice(1),ideEnvPresent:!!process.env["QWEN_CODE_IDE_WORKSPACE_PATH"]});const primaryGenerationGuard=runtime.createWorkspaceGenerationGuard();const primaryTrustMaterialization=JSON.stringify({trusted:trustedWorkspace,boundWorkspaces:[...boundWorkspaces].sort()});const sharedPathLocks=new PathMutexRegistry;const workspaceTrustOperationGate=new PathMutexRegistry;const runWorkspaceTrustOperation=__name(operation=>workspaceTrustOperationGate.runExclusive("runtime-topology",operation),"runWorkspaceTrustOperation");const idleReclaimerRef={};const processRegistry=new runtime.ProcessRegistry;managedProcessRegistry=processRegistry;const childHeapPolicy=opts.daemonMemoryBudget&&!deps.bridge?admissionPolicy??createChildHeapPolicy({budget:opts.daemonMemoryBudget,mode:opts.childHeapMode??"observe"}):void 0;managedChildHeapPolicy=childHeapPolicy;const fsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces,injected:deps.fsFactory,trusted:trustedWorkspace,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard:primaryGenerationGuard,...customIgnoreFiles!==void 0?{customIgnoreFiles}:{}});const routeFsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces:[boundWorkspace],trusted:trustedWorkspace,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard:primaryGenerationGuard,...customIgnoreFiles!==void 0?{customIgnoreFiles}:{}});const channelFactoryOptions={processRegistry,childHeapPolicy,reclaimIdleChild:__name(async signal=>{await idleReclaimerRef.current?.(daemonWorkspaceHash,signal)},"reclaimIdleChild"),pipeLimits:runtime.daemonAcpNdJsonLimits,sourceEnv:runtimeEffectiveEnv,onDiagnosticLine:diagnosticSink,pipeHooks:{onMessageSent:__name(bytes=>recordPipeMessage("outbound",bytes),"onMessageSent"),onMessageReceived:__name(bytes=>recordPipeMessage("inbound",bytes),"onMessageReceived"),onMessageObserved:__name(({direction,bytes,message})=>observeLargePipeFrame({direction:daemonPipeDirection(direction),bytes,message}),"onMessageObserved"),onQueueSaturated:warnAcpQueueSaturated},...acpChildExtraArgs(opts)?{extraArgs:acpChildExtraArgs(opts)}:{}};const channelFactory=runtime.createSpawnChannelFactory(channelFactoryOptions);const statusProvider=runtime.createDaemonStatusProvider({env:runtimeEffectiveEnv});const workspaceProvidersStatusProvider=runtime.createWorkspaceProvidersStatusProvider({env:runtimeEffectiveEnv,workspaceTrusted:trustedWorkspace});const workspaceSkillsStatusProvider=runtime.createWorkspaceSkillsStatusProvider({workspaceTrusted:trustedWorkspace});const clientMcpSenderRegistry=new ClientMcpSenderRegistry;const runtimeBridges=[];const runtimeEpochSources=new Map;const runtimeEpochSourceFor=__name(workspaceCwd=>{let source=runtimeEpochSources.get(workspaceCwd);if(!source){let epoch=0;source={current:__name(()=>epoch,"current"),allocate:__name(()=>++epoch,"allocate")};runtimeEpochSources.set(workspaceCwd,source)}return source},"runtimeEpochSourceFor");let mcpAuthenticationActive=false;const acquireMcpAuthentication=__name(()=>{if(mcpAuthenticationActive)return void 0;mcpAuthenticationActive=true;let released=false;return()=>{if(released)return;released=true;mcpAuthenticationActive=false}},"acquireMcpAuthentication");const totalSessionAdmission=runtime.createTotalSessionAdmissionController({maxTotalSessions:opts.maxTotalSessions,getBridges:__name(()=>runtimeBridges.length>0?runtimeBridges:bridgeRef?[bridgeRef]:[],"getBridges")});const sessionOwnerIndex=runtime.createWorkspaceSessionOwnerIndex();const workspaceRegistryForPersistence={current:void 0};const createRuntimeWorkflowAncestorTrustHandler=__name((workspaceCwd,getBridge,generationGuard,admissionPolicy2)=>workflowTrust.createWorkflowAncestorTrustHandler({generationGuard,admissionPolicy:admissionPolicy2,getPublished:__name(()=>publishedWorkflowTrustPolicy,"getPublished"),ideScopeCwd:workflowTrustIdeScopeCwd,isCurrentOwner:__name(sessionId=>{const registry=workspaceRegistryForPersistence.current;if(!registry)return false;const owner=registry.resolveLiveSessionOwner(sessionId);const entry=registry.getManagedEntryByWorkspaceCwd(workspaceCwd);return owner.kind==="found"&&owner.runtime.trusted&&owner.runtime.workspaceCwd===workspaceCwd&&owner.runtime.bridge===getBridge()&&entry?.state==="active"&&entry.current?.runtime===owner.runtime&&entry.current.guard===generationGuard},"isCurrentOwner")}),"createRuntimeWorkflowAncestorTrustHandler");const isWorkspaceTrustedForPersistence=__name(workspace=>workspaceRegistryForPersistence.current?.getByWorkspaceCwd(workspace)?.trusted??(workspaceRegistryForPersistence.current===void 0&&workspace===boundWorkspace&&trustedWorkspace),"isWorkspaceTrustedForPersistence");const loadSettingsForPersistence=__name(workspace=>{const trusted=isWorkspaceTrustedForPersistence(workspace);return settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted})},"loadSettingsForPersistence");const resolveSkillToggleIdentities=__name(async(workspace,skillNames)=>{let skills;try{const workspaceRuntime=workspaceRegistryForPersistence.current?.getByWorkspaceCwd(workspace);const status=await workspaceRuntime?.workspaceService.getWorkspaceSkillsStatus({route:"skill settings persistence",workspaceCwd:workspace});if(status?.initialized)skills=status.skills}catch{}const skillsByName=new Map(skills?.map(skill=>[skill.name.trim().toLowerCase(),skill]));return skillNames.map(skillName=>{const skill=skillsByName.get(skillName.trim().toLowerCase());if(!skill){const prefixEnd=skillName.indexOf(":");return{name:skillName,...prefixEnd>0?{authoredName:skillName.slice(prefixEnd+1)}:{}}}if(skill.level!=="extension"||!skill.extensionName){return{name:skillName}}return{name:skillName,authoredName:skillName.slice(skill.extensionName.length+1)}})},"resolveSkillToggleIdentities");const persistDisabledToolsFn=__name((workspace,toolName,enabled,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=loadSettingsForPersistence(workspace);const wsScope=fresh.forScope(WORKSPACE_SETTING_SCOPE).settings;const wsDisabled=wsScope.tools?.disabled;const current=Array.isArray(wsDisabled)?wsDisabled.filter(v=>typeof v==="string"):[];const next=new Set(current);if(enabled)next.delete(toolName);else next.add(toolName);assertGenerationOpen?.();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.disabled",[...next].sort(),assertGenerationOpen)}),"persistDisabledToolsFn");const persistDisabledSkillsFn=__name((workspace,skillName,enabled,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const{skillSettingStrings,skillToggleBlockForName,updateWorkspaceSkillSettingLists}=await import("./skill-settings-76NI6SF3.js");const fresh=loadSettingsForPersistence(workspace);const workspaceDisabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"disabled");const workspaceEnabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"enabled");if(enabled){const[skillIdentity]=await resolveSkillToggleIdentities(workspace,[skillName]);const block=skillToggleBlockForName(fresh,skillIdentity);if(block){return{changed:false,disabled:workspaceDisabled,block}}}const next=updateWorkspaceSkillSettingLists({disabled:workspaceDisabled,enabled:workspaceEnabled},skillName,enabled);const settingsChanges=[];if(JSON.stringify(next.disabled)!==JSON.stringify(workspaceDisabled)){settingsChanges.push({key:"skills.disabled",value:next.disabled.length>0?next.disabled:void 0})}if(JSON.stringify(next.enabled)!==JSON.stringify(workspaceEnabled)){settingsChanges.push({key:"skills.enabled",value:next.enabled.length>0?next.enabled:void 0})}if(settingsChanges.length===0){return{changed:false,disabled:workspaceDisabled}}assertGenerationOpen?.();fresh.setValues(settingsChanges.map(change=>({scope:WORKSPACE_SETTING_SCOPE,...change})),void 0,assertGenerationOpen);return{changed:true,disabled:next.disabled,settingsChanges}}),"persistDisabledSkillsFn");const persistDisabledSkillsBatchFn=__name((workspace,skillNames,enabled,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const{skillSettingStrings,skillToggleBlockForName,updateWorkspaceSkillSettingLists}=await import("./skill-settings-76NI6SF3.js");const fresh=loadSettingsForPersistence(workspace);const initialDisabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"disabled");const initialEnabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"enabled");const skillIdentities=enabled?await resolveSkillToggleIdentities(workspace,skillNames):skillNames.map(name=>({name}));let next={disabled:initialDisabled,enabled:initialEnabled};const outcomes=skillNames.map(skillName=>({skillName,changed:false}));let pending=skillNames.map((_,index)=>index);for(let pass=0;pass<skillNames.length;pass+=1){const refused=[];let listChanged=false;for(const index of pending){const skillName=skillNames[index];if(enabled){const block=skillToggleBlockForName(fresh,skillIdentities[index]);if(block&&!(block.scope==="Workspace"&&block.list==="disabled"&&!next.disabled.some(name=>name.trim().toLowerCase()===block.entry))){refused.push(index);continue}}const updated=updateWorkspaceSkillSettingLists(next,skillName,enabled);const changed=JSON.stringify(updated.disabled)!==JSON.stringify(next.disabled)||JSON.stringify(updated.enabled)!==JSON.stringify(next.enabled);next=updated;outcomes[index]={skillName,changed};listChanged||=changed}pending=refused;if(pending.length===0||!listChanged)break}const settingsChanges=[];if(JSON.stringify(next.disabled)!==JSON.stringify(initialDisabled)){settingsChanges.push({key:"skills.disabled",value:next.disabled.length>0?next.disabled:void 0})}if(JSON.stringify(next.enabled)!==JSON.stringify(initialEnabled)){settingsChanges.push({key:"skills.enabled",value:next.enabled.length>0?next.enabled:void 0})}if(settingsChanges.length>0){assertGenerationOpen?.();fresh.setValues(settingsChanges.map(change=>({scope:WORKSPACE_SETTING_SCOPE,...change})),void 0,assertGenerationOpen)}return{outcomes,settingsChanges}}),"persistDisabledSkillsBatchFn");const persistSettingFn=__name((workspace,scope,key,value,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=loadSettingsForPersistence(workspace);assertGenerationOpen?.();fresh.setValue(scope,key,value,assertGenerationOpen);return fresh}),"persistSettingFn");const persistSettingsFn=__name((workspace,writes,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=loadSettingsForPersistence(workspace);const writesByScope=new Map;for(const write of writes){writesByScope.set(write.scope,(writesByScope.get(write.scope)??0)+1)}const committedScopes=new Set;let committed=0;try{assertGenerationOpen?.();fresh.setValues(writes,scope=>{committedScopes.add(scope);committed+=writesByScope.get(scope)??0},assertGenerationOpen)}catch(err){const failedWrite=writes.find(write=>!committedScopes.has(write.scope))??writes[committed];const message=`persistSettings partial failure (workspace=${workspace}, committed=${committed}/${writes.length}, failedKey=${failedWrite?.key??"<unknown>"}, failedScope=${failedWrite?.scope??"<unknown>"}): ${err instanceof Error?err.message:String(err)}`;writeStderrLine(`qwen serve: ${message}`);throw new runtime.WorkspaceSettingsPartialPersistError(message,writes.filter(write=>committedScopes.has(write.scope)),err)}}),"persistSettingsFn");const[{createSubSessionLauncher},scheduledTaskRoutes]=await Promise.all([import("./create-sub-session-CNSRJFYG.js"),import("./scheduled-tasks-GM5EJMK7.js")]);const{sessionAttachmentsRoots}=await import("./session-attachments-root-6M2ECUNK.js");const createCurrentSessionScheduledTaskHandler=__name((workspaceCwd,runtimeBaseDir,getBridge,assertGenerationOpen)=>async({callerSessionId,cron,prompt,recurring,assertCallerPromptActive})=>{const targetBridge=getBridge();if(!targetBridge){throw new Error("Current-session scheduling is unavailable while the workspace runtime is starting.")}const task=await scheduledTaskRoutes.createScheduledTaskWithExistingSession({workspaceCwd,runtimeBaseDir,bridge:targetBridge,assertGenerationOpen,resolveLiveSessionOwner:__name(sessionId=>workspaceRegistryForPersistence.current===void 0?{kind:"unavailable"}:workspaceRegistryForPersistence.current.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")},{sessionId:callerSessionId,cron,prompt,recurring},{source:"cron-tool",assertCallerPromptActive});return{id:task.id,cron:task.cron}},"createCurrentSessionScheduledTaskHandler");const subSessionLauncher=createSubSessionLauncher({getBridge:__name(()=>bridgeRef,"getBridge"),boundWorkspace,runtimeBaseDir:primarySessionRuntimeBaseDir,...subSessionConcurrencyCapsFromSettings(runtimeBootSettings?.merged.serve??{})});const attachmentsRoots=sessionAttachmentsRoots(boundWorkspace,primarySessionRuntimeBaseDir);const bridge=deps.bridge??runtime.createAcpSessionBridge({onWorkflowAncestorTrust:createRuntimeWorkflowAncestorTrustHandler(boundWorkspace,()=>bridgeRef,primaryGenerationGuard,bootWorkflowTrustAdmission),artifactSnapshotRuntimeBaseDir:primarySessionRuntimeBaseDir,sessionAttachmentsRoot:attachmentsRoots.root,sessionAttachmentsFallbackRoot:attachmentsRoots.fallback,clientMcpSender:clientMcpSenderRegistry.lookup,onCreateSubSession:subSessionLauncher.launch,onCreateCurrentSessionScheduledTask:createCurrentSessionScheduledTaskHandler(boundWorkspace,primarySessionRuntimeBaseDir,()=>bridgeRef,()=>primaryGenerationGuard.assertOpen()),onChannelDelivery:createBoundChannelDeliveryHandler(boundWorkspace,()=>channelWorkerManager,channelDeliveryAuthorizations,daemonLog,channelDeliveryDiagnosticRedaction),maxSessions:opts.maxSessions,...opts.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},freshSessionAdmission:totalSessionAdmission.admit,sessionLifecycle:__name(event=>{if(event.type==="registered"&&primaryGenerationGuard.closed){return}sessionOwnerIndex.handleBridgeSessionLifecycle(event)},"sessionLifecycle"),...opts.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:opts.maxPendingPromptsPerSession}:{},...opts.eventRingSize!==void 0?{eventRingSize:opts.eventRingSize}:{},...opts.compactedReplayMaxBytes!==void 0?{compactedReplayMaxBytes:opts.compactedReplayMaxBytes}:{},...opts.maxJournalEvents!==void 0?{maxJournalEvents:opts.maxJournalEvents}:{},...opts.maxJournalBytes!==void 0?{maxJournalBytes:opts.maxJournalBytes}:{},...journalGrowthPoolBytes!==void 0?{journalGrowthPoolBytes,journalGrowthSessionLimits,registerJournalGrowthSessionLimits}:{},...opts.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:opts.channelIdleTimeoutMs}:{},...opts.initializeTimeoutMs!==void 0?{initializeTimeoutMs:opts.initializeTimeoutMs}:{},sessionRestoreTimeoutMs,...opts.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:opts.sessionReapIntervalMs}:{},...opts.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:opts.sessionIdleTimeoutMs}:{},...opts.sessionPromptSettledCloseGraceMs!==void 0?{sessionPromptSettledCloseGraceMs:opts.sessionPromptSettledCloseGraceMs}:{},...opts.permissionResponseTimeoutMs!==void 0?{permissionResponseTimeoutMs:opts.permissionResponseTimeoutMs}:{},boundWorkspace,runtimeEpochSource:runtimeEpochSourceFor(boundWorkspace),acquireMcpAuthentication,promptLedger:runtime.createPromptLedgerSink(boundWorkspace,primarySessionRuntimeBaseDir),sessionShellCommandEnabled,childEnvOverrides,...opts.experimentalPairedEngines?{executionEngines:runtime.createPairedExecutionEngines({legacy:channelFactory,managed:runtime.createManagedExecutionEngine({legacy:channelFactoryOptions,host:{workspaceCwd:boundWorkspace,workspaceTrusted:trustedWorkspace,environment:runtimeEffectiveEnv,forwardedArgs:acpChildExtraArgs(opts)??[],hasLiveMcpServers:__name(()=>bridgeRef?.hasRuntimeMcpServers()===true,"hasLiveMcpServers")}}),runtimeBaseDir:primarySessionRuntimeBaseDir})}:{channelFactory},externalToolGuard:daemonToolGuardHandler,onDiagnosticLine:diagnosticSink,telemetry:daemonTelemetry,...permissionPolicy!==void 0?{permissionPolicy}:{},...permissionConsensusQuorum!==void 0?{permissionConsensusQuorum}:{},permissionAudit:permissionAuditPublisher,statusProvider,delegateReadTextFileToClient:false,fileSystem:createBridgeFileSystemAdapter(fsFactory,{allowSameHostToolWritesOutsideWorkspace:deps.fsFactory===void 0}),persistApprovalMode:__name((workspace,mode)=>withSettingsLock(workspace,async()=>{primaryGenerationGuard.assertOpen();if(!trustedWorkspace){throw new Error("Cannot persist approval mode for an untrusted workspace.")}const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,workspaceTrusted:trustedWorkspace});primaryGenerationGuard.assertOpen();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.approvalMode",mode,()=>primaryGenerationGuard.assertOpen())}),"persistApprovalMode")});if(!deps.bridge){bridgeRef=bridge;internalRuntimeBridgesForCleanup.push(bridge)}runtimeBridges.push(bridge);let invalidatePrimaryServeFeaturesCache=__name(()=>{},"invalidatePrimaryServeFeaturesCache");const reloadPrimaryDaemonEnv=__name((workspace,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trustedWorkspace,workspaceTrusted:trustedWorkspace});assertGenerationOpen?.();let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,trustedWorkspace)}catch(err){const fallbackReason=err instanceof Error?err.message:String(err);primaryRuntimeEnv.fallbackReason=fallbackReason;daemonLog.warn("failed to rebuild runtime env snapshot before daemon env reload; preserving previous runtime env",{error:fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}const result=settingsRuntime.settings.reloadEnvironment(fresh.merged,workspace,trustedWorkspace,{failClosedOnEnvFileReadError:true});if(result.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}replaceRuntimeEffectiveEnv(refreshedRuntimeEnv.effectiveEnv);primaryRuntimeEnv.workflowsEnabledBySettings=fresh.merged.tools?.workflowsEnabled===true;delete primaryRuntimeEnv.fallbackReason;primaryRuntimeEnv.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;primaryRuntimeEnv.envFileReadFailures.splice(0,primaryRuntimeEnv.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);primaryRuntimeEnv.overlayKeys.splice(0,primaryRuntimeEnv.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);primaryRuntimeEnv.envFilePaths.splice(0,primaryRuntimeEnv.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);return{...result,runtimeEnvironmentApplied:true}}),"reloadPrimaryDaemonEnv");const workspaceService=runtime.createDaemonWorkspaceService({boundWorkspace,isWorkspaceTrusted:__name(()=>trustedWorkspace,"isWorkspaceTrusted"),assertGenerationOpen:__name(()=>primaryGenerationGuard.assertOpen(),"assertGenerationOpen"),contextFilename:contextFilenameForInit??"QWEN.md",statusProvider,workspaceProvidersStatusProvider,workspaceSkillsStatusProvider,skillInstallEnv:runtimeEffectiveEnv,voiceEnv:runtimeEffectiveEnv,isChannelLive:__name(()=>bridge.isWorkspaceControlLive?.()??bridge.isChannelLive(),"isChannelLive"),persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,preheatAcpChild:__name(()=>bridge.preheat(),"preheatAcpChild"),reloadDaemonEnv:reloadPrimaryDaemonEnv,reloadModelProvidersDaemonEnv:__name((workspace,assertGenerationOpen)=>reloadRuntimeOverlaySnapshotForModelProviders(workspace,trustedWorkspace,{metadata:primaryRuntimeEnv,replace:replaceRuntimeEffectiveEnv},assertGenerationOpen),"reloadModelProvidersDaemonEnv"),queryWorkspaceStatus:__name((method,idle)=>bridge.queryWorkspaceStatus(method,idle),"queryWorkspaceStatus"),invokeWorkspaceCommand:__name((method,params,invokeOpts)=>bridge.invokeWorkspaceCommand(method,params,invokeOpts),"invokeWorkspaceCommand"),refreshExtensionsForAllSessions:__name(sessionIds=>sessionIds===void 0?bridge.refreshExtensionsForAllSessions():bridge.refreshExtensionsForAllSessions(void 0,{sessionIds}),"refreshExtensionsForAllSessions"),publishWorkspaceEvent:__name(event=>{if(event.type==="settings_changed"||event.type==="settings_reloaded"){invalidatePrimaryServeFeaturesCache()}bridge.publishWorkspaceEvent(event)},"publishWorkspaceEvent")});const workspaceRuntimes=[{workspaceId:daemonWorkspaceHash,workspaceCwd:boundWorkspace,sessionRuntimeBaseDir:primarySessionRuntimeBaseDir,...workspaceInputs[0]?.displayName?{displayName:workspaceInputs[0].displayName}:{},primary:true,trusted:trustedWorkspace,removable:false,registrationIds:workspaceInputs[0]?.registrationIds??[],env:primaryRuntimeEnv,bridge,workspaceService,routeFileSystemFactory:routeFsFactory,clientMcpSenderRegistry,generationGuard:primaryGenerationGuard,trustMaterialization:primaryTrustMaterialization}];if(trustedWorkspace){await recoverBranchWorktreePreparations({workspaceCwd:boundWorkspace,sessionService:await createBranchRecoverySessionService(workspaceRuntimes[0]),assertGenerationOpen:__name(()=>primaryGenerationGuard.assertOpen(),"assertGenerationOpen"),isWorktreeOccupied:__name(worktreePath=>bridgeHasLiveSessionWithin(bridge,boundWorkspace,worktreePath),"isWorktreeOccupied"),warn:__name((message,fields)=>daemonLog.warn(message,fields),"warn")}).catch(error=>{daemonLog.warn("branch worktree recovery sweep failed",{workspace:boundWorkspace,error:error instanceof Error?error.message:String(error)})})}const createRuntimeEnvMetadata=__name((workspace,settings,trusted)=>{const snapshot=settings?settingsRuntime.environment.buildRuntimeEnvironment(settings.merged,workspace,daemonRuntimeBaseEnv,trusted):{effectiveEnv:{...daemonRuntimeBaseEnv},overlayKeys:Object.freeze([]),envFilePaths:Object.freeze([]),envFileReadFailed:false,envFileReadFailures:Object.freeze([])};logRuntimeEnvFileReadFailures(workspace,snapshot);const sessionRuntimeBaseDir=resolveSessionRuntimeBaseDir(workspace,settings,snapshot.effectiveEnv);const effectiveEnv={...snapshot.effectiveEnv,QWEN_RUNTIME_DIR:sessionRuntimeBaseDir};const metadata={mode:"runtime-overlay",overlayKeys:[...snapshot.overlayKeys],effectiveEnv,workflowsEnabledBySettings:settings?.merged.tools?.workflowsEnabled===true,envFilePaths:[...snapshot.envFilePaths],envFileReadFailed:snapshot.envFileReadFailed,envFileReadFailures:[...snapshot.envFileReadFailures]};return{metadata,effectiveEnv,sessionRuntimeBaseDir,replace(nextEnv){for(const key of Object.keys(effectiveEnv)){delete effectiveEnv[key]}Object.assign(effectiveEnv,nextEnv);effectiveEnv["QWEN_RUNTIME_DIR"]=sessionRuntimeBaseDir}}},"createRuntimeEnvMetadata");const reloadRuntimeOverlaySnapshotForModelProviders=__name((workspace,trusted,env,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted});assertGenerationOpen?.();let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,trusted)}catch(err){env.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to rebuild runtime overlay for model-provider reload; preserving previous runtime env",{workspace,error:env.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}assertGenerationOpen?.();try{env.replace(refreshedRuntimeEnv.effectiveEnv);env.metadata.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;env.metadata.envFileReadFailures.splice(0,env.metadata.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);env.metadata.overlayKeys.splice(0,env.metadata.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);env.metadata.envFilePaths.splice(0,env.metadata.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);delete env.metadata.fallbackReason;return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:true}}catch(err){env.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to apply runtime overlay for model-provider reload; preserving previous runtime env",{workspace,error:env.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}}),"reloadRuntimeOverlaySnapshotForModelProviders");const readLiveConversationScheduledTasks=__name(async()=>{if(!fs.existsSync(liveConversationWorkspace.rootPath))return[];const{canonicalRoot}=await liveConversationWorkspace.revalidate();let settings;try{settings=settingsRuntime.settings.loadSettings(canonicalRoot,{skipLoadEnvironment:true,skipWorkspaceSettings:false,workspaceTrusted:true})}catch(err){writeStderrLine(`qwen serve: could not read full settings for Conversations (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}const env=createRuntimeEnvMetadata(canonicalRoot,settings,true);return core.Storage.runWithResolvedRuntimeBaseDir(env.sessionRuntimeBaseDir,()=>core.readCronTasks(canonicalRoot))},"readLiveConversationScheduledTasks");const subSessionStoppers=[];const subSessionStoppersByRuntime=new WeakMap;const runtimeCleanupPromises=new WeakMap;const removeArrayValue=__name((values,value)=>{const index=values.indexOf(value);if(index>=0)values.splice(index,1)},"removeArrayValue");for(const workspaceInput of workspaceInputs.slice(1)){assertExecutionSandboxSupported(readOperatorSandboxSettings(),"serve workspace runtimes");const secondaryDecision=trustPolicy.evaluateDaemonWorkspaceTrust(bootTrustSnapshot,workspaceInput.cwd);const secondaryTrusted=secondaryDecision.targetTrusted;let secondarySettings;try{secondarySettings=settingsRuntime.settings.loadSettings(workspaceInput.cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!secondaryTrusted,workspaceTrusted:secondaryTrusted})}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: could not read full settings for secondary workspace ${workspaceInput.cwd} (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}assertExecutionSandboxSupported(secondarySettings?.merged??{},"serve workspace runtimes");if(!secondaryTrusted){daemonLog.warn("secondary workspace is not trusted",{workspace:workspaceInput.cwd,trustSettingsAvailable:secondarySettings!==void 0})}const secondaryEnv=createRuntimeEnvMetadata(workspaceInput.cwd,secondarySettings,secondaryTrusted);const secondaryCustomIgnoreFiles=secondarySettings?.merged.context?.fileFiltering?.customIgnoreFiles;const secondaryContextFilename=extractContextFilename(secondarySettings?.merged.context?.fileName)??contextFilenameForInit??"QWEN.md";const secondaryWorkspaceHash=core.hashDaemonWorkspace(workspaceInput.cwd);const secondaryGenerationGuard=runtime.createWorkspaceGenerationGuard();const secondaryStatusProvider=runtime.createDaemonStatusProvider({env:secondaryEnv.effectiveEnv});const secondaryBridgeFsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces:[workspaceInput.cwd],trusted:secondaryTrusted,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard:secondaryGenerationGuard,...secondaryCustomIgnoreFiles!==void 0?{customIgnoreFiles:secondaryCustomIgnoreFiles}:{}});const secondaryChannelFactoryOptions={processRegistry,childHeapPolicy,reclaimIdleChild:__name(async signal=>{await idleReclaimerRef.current?.(secondaryWorkspaceHash,signal)},"reclaimIdleChild"),pipeLimits:runtime.daemonAcpNdJsonLimits,sourceEnv:secondaryEnv.effectiveEnv,onDiagnosticLine:diagnosticSink,pipeHooks:{onMessageSent:__name(bytes=>recordPipeMessage("outbound",bytes),"onMessageSent"),onMessageReceived:__name(bytes=>recordPipeMessage("inbound",bytes),"onMessageReceived"),onMessageObserved:__name(({direction,bytes,message})=>observeLargePipeFrame({direction:daemonPipeDirection(direction),bytes,message}),"onMessageObserved"),onQueueSaturated:warnAcpQueueSaturated},...acpChildExtraArgs(opts)?{extraArgs:acpChildExtraArgs(opts)}:{}};const secondaryChannelFactory=runtime.createSpawnChannelFactory(secondaryChannelFactoryOptions);const secondaryClientMcpSenderRegistry=new ClientMcpSenderRegistry;let secondaryBridgeRef;const secondarySubSessionLauncher=createSubSessionLauncher({getBridge:__name(()=>secondaryBridgeRef,"getBridge"),boundWorkspace:workspaceInput.cwd,runtimeBaseDir:secondaryEnv.sessionRuntimeBaseDir,...subSessionConcurrencyCapsFromSettings(secondarySettings?.merged.serve??{})});const secondaryAttachmentsRoots=sessionAttachmentsRoots(workspaceInput.cwd,secondaryEnv.sessionRuntimeBaseDir);const secondaryBridge=runtime.createAcpSessionBridge({onWorkflowAncestorTrust:createRuntimeWorkflowAncestorTrustHandler(workspaceInput.cwd,()=>secondaryBridgeRef,secondaryGenerationGuard,bootWorkflowTrustAdmission),artifactSnapshotRuntimeBaseDir:secondaryEnv.sessionRuntimeBaseDir,sessionAttachmentsRoot:secondaryAttachmentsRoots.root,sessionAttachmentsFallbackRoot:secondaryAttachmentsRoots.fallback,clientMcpSender:secondaryClientMcpSenderRegistry.lookup,onCreateSubSession:secondarySubSessionLauncher.launch,onCreateCurrentSessionScheduledTask:createCurrentSessionScheduledTaskHandler(workspaceInput.cwd,secondaryEnv.sessionRuntimeBaseDir,()=>secondaryBridgeRef,()=>secondaryGenerationGuard.assertOpen()),onChannelDelivery:createBoundChannelDeliveryHandler(workspaceInput.cwd,()=>channelWorkerManager,channelDeliveryAuthorizations,daemonLog,channelDeliveryDiagnosticRedaction),maxSessions:opts.maxSessions,...opts.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},freshSessionAdmission:totalSessionAdmission.admit,sessionLifecycle:__name(event=>{if(event.type==="registered"&&secondaryGenerationGuard.closed){return}sessionOwnerIndex.handleBridgeSessionLifecycle(event)},"sessionLifecycle"),...opts.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:opts.maxPendingPromptsPerSession}:{},...opts.eventRingSize!==void 0?{eventRingSize:opts.eventRingSize}:{},...opts.compactedReplayMaxBytes!==void 0?{compactedReplayMaxBytes:opts.compactedReplayMaxBytes}:{},...opts.maxJournalEvents!==void 0?{maxJournalEvents:opts.maxJournalEvents}:{},...opts.maxJournalBytes!==void 0?{maxJournalBytes:opts.maxJournalBytes}:{},...journalGrowthPoolBytes!==void 0?{journalGrowthPoolBytes,journalGrowthSessionLimits,registerJournalGrowthSessionLimits}:{},...opts.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:opts.channelIdleTimeoutMs}:{},...opts.initializeTimeoutMs!==void 0?{initializeTimeoutMs:opts.initializeTimeoutMs}:{},sessionRestoreTimeoutMs,...opts.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:opts.sessionReapIntervalMs}:{},...opts.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:opts.sessionIdleTimeoutMs}:{},...opts.sessionPromptSettledCloseGraceMs!==void 0?{sessionPromptSettledCloseGraceMs:opts.sessionPromptSettledCloseGraceMs}:{},...opts.permissionResponseTimeoutMs!==void 0?{permissionResponseTimeoutMs:opts.permissionResponseTimeoutMs}:{},boundWorkspace:workspaceInput.cwd,runtimeEpochSource:runtimeEpochSourceFor(workspaceInput.cwd),acquireMcpAuthentication,promptLedger:runtime.createPromptLedgerSink(workspaceInput.cwd,secondaryEnv.sessionRuntimeBaseDir),sessionShellCommandEnabled,childEnvOverrides,...opts.experimentalPairedEngines?{executionEngines:runtime.createPairedExecutionEngines({legacy:secondaryChannelFactory,managed:runtime.createManagedExecutionEngine({legacy:secondaryChannelFactoryOptions,host:{workspaceCwd:workspaceInput.cwd,workspaceTrusted:secondaryTrusted,environment:secondaryEnv.effectiveEnv,forwardedArgs:acpChildExtraArgs(opts)??[],hasLiveMcpServers:__name(()=>secondaryBridgeRef?.hasRuntimeMcpServers()===true,"hasLiveMcpServers")}}),runtimeBaseDir:secondaryEnv.sessionRuntimeBaseDir})}:{channelFactory:secondaryChannelFactory},externalToolGuard:daemonToolGuardHandler,onDiagnosticLine:diagnosticSink,telemetry:createRuntimeBridgeTelemetry(secondaryWorkspaceHash),...permissionPolicy!==void 0?{permissionPolicy}:{},...permissionConsensusQuorum!==void 0?{permissionConsensusQuorum}:{},permissionAudit:permissionAuditPublisher,statusProvider:secondaryStatusProvider,delegateReadTextFileToClient:false,fileSystem:createBridgeFileSystemAdapter(secondaryBridgeFsFactory,{allowSameHostToolWritesOutsideWorkspace:true}),persistApprovalMode:__name((workspace,mode)=>withSettingsLock(workspace,async()=>{secondaryGenerationGuard.assertOpen();if(!secondaryTrusted){throw new Error("Cannot persist approval mode for an untrusted workspace.")}const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,workspaceTrusted:secondaryTrusted});secondaryGenerationGuard.assertOpen();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.approvalMode",mode,()=>secondaryGenerationGuard.assertOpen())}),"persistApprovalMode")});secondaryBridgeRef=secondaryBridge;runtimeBridges.push(secondaryBridge);internalRuntimeBridgesForCleanup.push(secondaryBridge);subSessionStoppers.push(secondarySubSessionLauncher.stop);const secondaryWorkspaceService=runtime.createDaemonWorkspaceService({boundWorkspace:workspaceInput.cwd,isWorkspaceTrusted:__name(()=>secondaryTrusted,"isWorkspaceTrusted"),assertGenerationOpen:__name(()=>secondaryGenerationGuard.assertOpen(),"assertGenerationOpen"),contextFilename:secondaryContextFilename,statusProvider:secondaryStatusProvider,workspaceProvidersStatusProvider:runtime.createWorkspaceProvidersStatusProvider({env:secondaryEnv.effectiveEnv,workspaceTrusted:secondaryTrusted}),workspaceSkillsStatusProvider:runtime.createWorkspaceSkillsStatusProvider({workspaceTrusted:secondaryTrusted}),skillInstallEnv:secondaryEnv.effectiveEnv,voiceEnv:secondaryEnv.effectiveEnv,voiceSettingsScope:WORKSPACE_SETTING_SCOPE,isChannelLive:__name(()=>secondaryBridge.isWorkspaceControlLive?.()??secondaryBridge.isChannelLive(),"isChannelLive"),preheatAcpChild:__name(()=>secondaryBridge.preheat(),"preheatAcpChild"),persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,reloadDaemonEnv:__name((workspace,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!secondaryTrusted,workspaceTrusted:secondaryTrusted});assertGenerationOpen?.();let runtimeEnvironmentApplied=false;let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,secondaryTrusted)}catch(err){secondaryEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to rebuild secondary runtime env snapshot before daemon env reload; preserving previous runtime env",{workspace,error:secondaryEnv.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}const result=settingsRuntime.settings.reloadEnvironment(fresh.merged,workspace,secondaryTrusted,{failClosedOnEnvFileReadError:true});if(result.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}try{secondaryEnv.replace(refreshedRuntimeEnv.effectiveEnv);secondaryEnv.metadata.workflowsEnabledBySettings=fresh.merged.tools?.workflowsEnabled===true;secondaryEnv.metadata.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;secondaryEnv.metadata.envFileReadFailures.splice(0,secondaryEnv.metadata.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);secondaryEnv.metadata.overlayKeys.splice(0,secondaryEnv.metadata.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);secondaryEnv.metadata.envFilePaths.splice(0,secondaryEnv.metadata.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);delete secondaryEnv.metadata.fallbackReason;runtimeEnvironmentApplied=true;return{...result,runtimeEnvironmentApplied}}catch(err){secondaryEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to apply secondary runtime env snapshot after daemon env reload; preserving previous runtime env",{workspace,error:secondaryEnv.metadata.fallbackReason});return{...result,runtimeEnvironmentApplied}}}),"reloadDaemonEnv"),reloadModelProvidersDaemonEnv:__name((workspace,assertGenerationOpen)=>reloadRuntimeOverlaySnapshotForModelProviders(workspace,secondaryTrusted,secondaryEnv,assertGenerationOpen),"reloadModelProvidersDaemonEnv"),queryWorkspaceStatus:__name((method,idle)=>secondaryBridge.queryWorkspaceStatus(method,idle),"queryWorkspaceStatus"),invokeWorkspaceCommand:__name((method,params,invokeOpts)=>secondaryBridge.invokeWorkspaceCommand(method,params,invokeOpts),"invokeWorkspaceCommand"),refreshExtensionsForAllSessions:__name(sessionIds=>sessionIds===void 0?secondaryBridge.refreshExtensionsForAllSessions():secondaryBridge.refreshExtensionsForAllSessions(void 0,{sessionIds}),"refreshExtensionsForAllSessions"),publishWorkspaceEvent:__name(event=>secondaryBridge.publishWorkspaceEvent(event),"publishWorkspaceEvent")});const secondaryRuntime={workspaceId:secondaryWorkspaceHash,workspaceCwd:workspaceInput.cwd,sessionRuntimeBaseDir:secondaryEnv.sessionRuntimeBaseDir,...workspaceInput.displayName?{displayName:workspaceInput.displayName}:{},primary:false,trusted:secondaryTrusted,removable:workspaceInput.removable,registrationIds:workspaceInput.registrationIds,env:secondaryEnv.metadata,bridge:secondaryBridge,workspaceService:secondaryWorkspaceService,routeFileSystemFactory:secondaryBridgeFsFactory,clientMcpSenderRegistry:secondaryClientMcpSenderRegistry,generationGuard:secondaryGenerationGuard,trustMaterialization:JSON.stringify({trusted:secondaryTrusted,boundWorkspaces:[workspaceInput.cwd]})};subSessionStoppersByRuntime.set(secondaryRuntime,secondarySubSessionLauncher.stop);workspaceRuntimes.push(secondaryRuntime)}const workspaceRegistry=runtime.createWorkspaceRegistry(workspaceRuntimes,{sessionOwnerIndex,scanUnindexedOwners:deps.bridge!==void 0});workspaceRegistryForPersistence.current=workspaceRegistry;const workspaceVoiceCoordinator=new WorkspaceVoiceCoordinator;core.registerDaemonGaugeCallbacks({sessionCount:__name(()=>workspaceRegistry.listAll().reduce((sum,item)=>sum+item.bridge.sessionCount,0),"sessionCount"),sseCount:__name(()=>runtime.getActiveSseCount(),"sseCount"),heapUsed:__name(()=>process.memoryUsage().heapUsed,"heapUsed")});daemonMetricsSampler?.dispose();const metricsLoopDelay=monitorEventLoopDelay({resolution:20});metricsLoopDelay.enable();const cpuCoreCount=os2.availableParallelism?.()??os2.cpus().length??1;let prevCpu=safeCpuUsage();let prevCpuAt=Date.now();let prevRateRejected;const metricsSamplerTimer=setInterval(()=>{const nowMs=Date.now();const eventLoopLagP99Ms=metricsLoopDelay.percentile(99)/1e6;try{const mem=process.memoryUsage();const cpu=safeCpuUsage();const cpuPercent=computeCpuPercent(prevCpu,cpu,nowMs-prevCpuAt,cpuCoreCount);if(cpu){prevCpu=cpu;prevCpuAt=nowMs}const acp=app2.locals?.["acpHandle"]?.getSnapshot();const hits=getRateLimiter(app2)?.getHitCounts();const rejectedTotal=hits?hits.prompt+hits.mutation+hits.read:0;const rateLimitRejected=prevRateRejected===void 0?0:Math.max(0,rejectedTotal-prevRateRejected);prevRateRejected=rejectedTotal;const primaryEntry=workspaceRegistry.primaryEntry;const primaryRuntimeBridge=primaryEntry.state==="active"?primaryEntry.current?.runtime.bridge:void 0;const child=primaryRuntimeBridge?.getChildResourceSnapshot?.();if(runtime.getActiveSseCount()>0||(acp?.wsStreams??0)>0){for(const managed of workspaceRegistry.listManaged()){void managed.bridge.refreshChildResource?.().catch(err=>{daemonLog.warn("ACP child resource refresh failed",{workspaceId:managed.workspaceId,error:err instanceof Error?err.message:String(err)})})}}metricsRing.sample(nowMs,{cpuPercent,rssBytes:mem.rss,heapUsedBytes:mem.heapUsed,activeSessions:workspaceRegistry.listAll().reduce((sum,item)=>sum+item.bridge.sessionCount,0),activePrompts:workspaceRegistry.listAll().reduce((sum,item)=>sum+(item.bridge.activePromptCount??0),0),queuedPrompts:workspaceRegistry.listAll().reduce((sum,item)=>sum+(item.bridge.pendingPromptTotal??0),0),eventLoopLagP99Ms,sseConnections:runtime.getActiveSseCount(),wsConnections:acp?.wsStreams??0,acpConnections:acp?.connectionCount??0,rateLimitRejected,childCpuPercent:child?.cpuPercent??0,childRssBytes:child?.rssBytes??0})}catch(err){daemonLog.warn(`metrics sampler tick failed: ${err instanceof Error?err.message:String(err)}`);try{metricsRing.sample(nowMs,{cpuPercent:0,rssBytes:0,heapUsedBytes:0,activeSessions:0,activePrompts:0,queuedPrompts:0,eventLoopLagP99Ms,sseConnections:0,wsConnections:0,acpConnections:0,rateLimitRejected:0,childCpuPercent:0,childRssBytes:0})}catch{}}finally{metricsLoopDelay.reset()}},DAEMON_METRICS_SAMPLE_MS);metricsSamplerTimer.unref();daemonMetricsSampler={dispose(){clearInterval(metricsSamplerTimer);metricsLoopDelay.disable()}};sessionPrRefreshTimer?.dispose();const refreshGeneration=++sessionPrRefreshGeneration;void import("./session-pr-refresh-3IS7DLEV.js").then(mod=>{if(refreshGeneration!==sessionPrRefreshGeneration)return;sessionPrRefreshTimer=mod.startSessionPrRefreshTimer({workspaceRegistry,getArchiveCoordinator:__name(()=>app2.locals.sessionArchiveCoordinator,"getArchiveCoordinator")})}).catch(error=>{daemonLog.warn(`session-pr-refresh load failed: ${error instanceof Error?error.message:String(error)}`)});const createDynamicWorkspaceRuntime=__name(async(cwd,buildOptions)=>{const provenance=buildOptions?.provenance??"existing";if(provenance==="managed-scratch"&&(!managedScratchRoot||!isManagedScratchChild(cwd,managedScratchRoot.canonicalRoot))){throw new Error("Managed scratch runtime must use an accepted direct child directory")}if(provenance==="live-conversation"){await liveConversationWorkspace.assertExactRoot(cwd)}const workflowTrustAdmission=buildOptions?.snapshot?workflowTrustAdmissions.get(buildOptions.snapshot)??{snapshot:buildOptions.snapshot,publication:-1}:await readWorkflowTrustAdmission();const snapshot=workflowTrustAdmission.snapshot;const decision=buildOptions?.decision??trustPolicy.evaluateDaemonWorkspaceTrust(snapshot,cwd);const trusted=provenance==="managed-scratch"||provenance==="live-conversation"?true:buildOptions?.trusted??decision.targetTrusted;assertExecutionSandboxSupported(readOperatorSandboxSettings(),"serve workspace runtimes");let wsSettings;try{wsSettings=settingsRuntime.settings.loadSettings(cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted})}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: could not read full settings for dynamic workspace ${cwd} (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}assertExecutionSandboxSupported(wsSettings?.merged??{},"serve workspace runtimes");const wsEnv=createRuntimeEnvMetadata(cwd,wsSettings,trusted);const wsCustomIgnoreFiles=wsSettings?.merged.context?.fileFiltering?.customIgnoreFiles;const wsContextFilename=extractContextFilename(wsSettings?.merged.context?.fileName)??contextFilenameForInit??"QWEN.md";const wsHash=core.hashDaemonWorkspace(cwd);const generationGuard=buildOptions?.generationGuard??runtime.createWorkspaceGenerationGuard();const runtimeBoundWorkspaces=buildOptions?.boundWorkspaces??[cwd];const wsFsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces:runtimeBoundWorkspaces,trusted,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard,...wsCustomIgnoreFiles!==void 0?{customIgnoreFiles:wsCustomIgnoreFiles}:{}});const wsRouteFsFactory=buildOptions?.primary===true&&runtimeBoundWorkspaces.length>1?runtime.resolveBridgeFsFactory({boundWorkspaces:[cwd],trusted,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard,...wsCustomIgnoreFiles!==void 0?{customIgnoreFiles:wsCustomIgnoreFiles}:{}}):wsFsFactory;const wsChannelFactoryOptions={processRegistry,childHeapPolicy,reclaimIdleChild:__name(async signal=>{await idleReclaimerRef.current?.(wsHash,signal)},"reclaimIdleChild"),pipeLimits:runtime.daemonAcpNdJsonLimits,sourceEnv:wsEnv.effectiveEnv,onDiagnosticLine:diagnosticSink,pipeHooks:{onMessageSent:__name(bytes=>recordPipeMessage("outbound",bytes),"onMessageSent"),onMessageReceived:__name(bytes=>recordPipeMessage("inbound",bytes),"onMessageReceived"),onMessageObserved:__name(({direction,bytes,message})=>observeLargePipeFrame({direction:daemonPipeDirection(direction),bytes,message}),"onMessageObserved"),onQueueSaturated:warnAcpQueueSaturated},...acpChildExtraArgs(opts)?{extraArgs:acpChildExtraArgs(opts)}:{}};const wsChannelFactory=runtime.createSpawnChannelFactory(wsChannelFactoryOptions);const wsClientMcpRegistry=new ClientMcpSenderRegistry;let wsBridgeRef;const wsSubSessionLauncher=createSubSessionLauncher({getBridge:__name(()=>wsBridgeRef,"getBridge"),boundWorkspace:cwd,runtimeBaseDir:wsEnv.sessionRuntimeBaseDir,...provenance==="live-conversation"?{notifySentCompletion:true,getStandaloneSessionService:__name(()=>(runtimeApp??runtimeAppForCleanup)?.locals?.["standaloneSessionService"],"getStandaloneSessionService"),isolatedWorkspace:{materializeDirectory:__name(sessionId=>liveConversationWorkspace.materializeConversationDirectory(sessionId),"materializeDirectory"),discardEmptyDirectory:__name(sessionId=>liveConversationWorkspace.discardEmptyConversationDirectory(sessionId),"discardEmptyDirectory")}}:{},...subSessionConcurrencyCapsFromSettings(wsSettings?.merged.serve??{})});let wsBridge;try{const wsAttachmentsRoots=sessionAttachmentsRoots(cwd,wsEnv.sessionRuntimeBaseDir);wsBridge=runtime.createAcpSessionBridge({onWorkflowAncestorTrust:createRuntimeWorkflowAncestorTrustHandler(cwd,()=>wsBridgeRef,generationGuard,workflowTrustAdmission),artifactSnapshotRuntimeBaseDir:wsEnv.sessionRuntimeBaseDir,sessionAttachmentsRoot:wsAttachmentsRoots.root,sessionAttachmentsFallbackRoot:wsAttachmentsRoots.fallback,clientMcpSender:wsClientMcpRegistry.lookup,onCreateSubSession:wsSubSessionLauncher.launch,onCreateCurrentSessionScheduledTask:createCurrentSessionScheduledTaskHandler(cwd,wsEnv.sessionRuntimeBaseDir,()=>wsBridgeRef,()=>generationGuard.assertOpen()),onChannelDelivery:createBoundChannelDeliveryHandler(cwd,()=>channelWorkerManager,channelDeliveryAuthorizations,daemonLog,channelDeliveryDiagnosticRedaction),maxSessions:opts.maxSessions,...opts.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},freshSessionAdmission:totalSessionAdmission.admit,sessionLifecycle:__name(event=>{if(event.type==="registered"&&generationGuard.closed)return;sessionOwnerIndex.handleBridgeSessionLifecycle(event)},"sessionLifecycle"),...opts.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:opts.maxPendingPromptsPerSession}:{},...opts.eventRingSize!==void 0?{eventRingSize:opts.eventRingSize}:{},...opts.compactedReplayMaxBytes!==void 0?{compactedReplayMaxBytes:opts.compactedReplayMaxBytes}:{},...opts.maxJournalEvents!==void 0?{maxJournalEvents:opts.maxJournalEvents}:{},...opts.maxJournalBytes!==void 0?{maxJournalBytes:opts.maxJournalBytes}:{},...journalGrowthPoolBytes!==void 0?{journalGrowthPoolBytes,journalGrowthSessionLimits,registerJournalGrowthSessionLimits}:{},...opts.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:opts.channelIdleTimeoutMs}:{},...opts.initializeTimeoutMs!==void 0?{initializeTimeoutMs:opts.initializeTimeoutMs}:{},sessionRestoreTimeoutMs,...opts.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:opts.sessionReapIntervalMs}:{},...opts.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:opts.sessionIdleTimeoutMs}:{},...opts.sessionPromptSettledCloseGraceMs!==void 0?{sessionPromptSettledCloseGraceMs:opts.sessionPromptSettledCloseGraceMs}:{},...opts.permissionResponseTimeoutMs!==void 0?{permissionResponseTimeoutMs:opts.permissionResponseTimeoutMs}:{},boundWorkspace:cwd,runtimeEpochSource:runtimeEpochSourceFor(cwd),acquireMcpAuthentication,...provenance==="live-conversation"?{}:{promptLedger:runtime.createPromptLedgerSink(cwd,wsEnv.sessionRuntimeBaseDir)},sessionShellCommandEnabled,childEnvOverrides:provenance==="live-conversation"?{...childEnvOverrides,[PRIVATE_CONVERSATIONS_RUNTIME_ENV]:PRIVATE_CONVERSATIONS_RUNTIME_ENABLE}:childEnvOverrides,...opts.experimentalPairedEngines&&provenance!=="live-conversation"?{executionEngines:runtime.createPairedExecutionEngines({legacy:wsChannelFactory,managed:runtime.createManagedExecutionEngine({legacy:wsChannelFactoryOptions,host:{workspaceCwd:cwd,workspaceTrusted:trusted,environment:wsEnv.effectiveEnv,forwardedArgs:acpChildExtraArgs(opts)??[],hasLiveMcpServers:__name(()=>wsBridgeRef?.hasRuntimeMcpServers()===true,"hasLiveMcpServers")}}),runtimeBaseDir:wsEnv.sessionRuntimeBaseDir})}:{channelFactory:wsChannelFactory},externalToolGuard:daemonToolGuardHandler,onDiagnosticLine:diagnosticSink,telemetry:createRuntimeBridgeTelemetry(wsHash),...permissionPolicy!==void 0?{permissionPolicy}:{},...permissionConsensusQuorum!==void 0?{permissionConsensusQuorum}:{},permissionAudit:permissionAuditPublisher,statusProvider:runtime.createDaemonStatusProvider({env:wsEnv.effectiveEnv}),delegateReadTextFileToClient:false,fileSystem:createBridgeFileSystemAdapter(wsFsFactory,{allowSameHostToolWritesOutsideWorkspace:true}),persistApprovalMode:__name((workspace,mode)=>withSettingsLock(workspace,async()=>{generationGuard.assertOpen();if(!trusted){throw new Error("Cannot persist approval mode for an untrusted workspace.")}const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,workspaceTrusted:trusted});generationGuard.assertOpen();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.approvalMode",mode,()=>generationGuard.assertOpen())}),"persistApprovalMode")})}catch(err){wsSubSessionLauncher.stop();throw err}wsBridgeRef=wsBridge;let wsService;try{wsService=runtime.createDaemonWorkspaceService({boundWorkspace:cwd,isWorkspaceTrusted:__name(()=>trusted,"isWorkspaceTrusted"),assertGenerationOpen:__name(()=>generationGuard.assertOpen(),"assertGenerationOpen"),contextFilename:wsContextFilename,statusProvider:runtime.createDaemonStatusProvider({env:wsEnv.effectiveEnv}),workspaceProvidersStatusProvider:runtime.createWorkspaceProvidersStatusProvider({env:wsEnv.effectiveEnv,workspaceTrusted:trusted}),workspaceSkillsStatusProvider:runtime.createWorkspaceSkillsStatusProvider({workspaceTrusted:trusted}),skillInstallEnv:wsEnv.effectiveEnv,voiceEnv:wsEnv.effectiveEnv,...buildOptions?.primary===true?{}:{voiceSettingsScope:WORKSPACE_SETTING_SCOPE},isChannelLive:__name(()=>wsBridge.isWorkspaceControlLive?.()??wsBridge.isChannelLive(),"isChannelLive"),preheatAcpChild:__name(()=>wsBridge.preheat(),"preheatAcpChild"),persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,reloadDaemonEnv:__name((workspace,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted});assertGenerationOpen?.();let runtimeEnvironmentApplied=false;let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,trusted)}catch(err){wsEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to rebuild dynamic runtime env snapshot before daemon env reload; preserving previous runtime env",{workspace,error:wsEnv.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}const result=settingsRuntime.settings.reloadEnvironment(fresh.merged,workspace,trusted,{failClosedOnEnvFileReadError:true});if(result.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}try{wsEnv.replace(refreshedRuntimeEnv.effectiveEnv);wsEnv.metadata.workflowsEnabledBySettings=fresh.merged.tools?.workflowsEnabled===true;wsEnv.metadata.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;wsEnv.metadata.envFileReadFailures.splice(0,wsEnv.metadata.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);wsEnv.metadata.overlayKeys.splice(0,wsEnv.metadata.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);wsEnv.metadata.envFilePaths.splice(0,wsEnv.metadata.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);delete wsEnv.metadata.fallbackReason;runtimeEnvironmentApplied=true;return{...result,runtimeEnvironmentApplied}}catch(err){wsEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to apply dynamic runtime env snapshot after daemon env reload; preserving previous runtime env",{workspace,error:wsEnv.metadata.fallbackReason});return{...result,runtimeEnvironmentApplied}}}),"reloadDaemonEnv"),reloadModelProvidersDaemonEnv:__name((workspace,assertGenerationOpen)=>reloadRuntimeOverlaySnapshotForModelProviders(workspace,trusted,wsEnv,assertGenerationOpen),"reloadModelProvidersDaemonEnv"),queryWorkspaceStatus:__name((method,idle)=>wsBridge.queryWorkspaceStatus(method,idle),"queryWorkspaceStatus"),invokeWorkspaceCommand:__name((method,params,invokeOpts)=>wsBridge.invokeWorkspaceCommand(method,params,invokeOpts),"invokeWorkspaceCommand"),refreshExtensionsForAllSessions:__name(sessionIds=>sessionIds===void 0?wsBridge.refreshExtensionsForAllSessions():wsBridge.refreshExtensionsForAllSessions(void 0,{sessionIds}),"refreshExtensionsForAllSessions"),publishWorkspaceEvent:__name(event=>{if(buildOptions?.primary===true&&(event.type==="settings_changed"||event.type==="settings_reloaded")){invalidatePrimaryServeFeaturesCache()}wsBridge.publishWorkspaceEvent(event)},"publishWorkspaceEvent")})}catch(err){wsSubSessionLauncher.stop();await wsBridge.shutdown().catch(()=>{try{wsBridge.killAllSync()}catch{}});throw err}runtimeBridges.push(wsBridge);internalRuntimeBridgesForCleanup.push(wsBridge);subSessionStoppers.push(wsSubSessionLauncher.stop);const wsRuntime={workspaceId:wsHash,workspaceCwd:cwd,sessionRuntimeBaseDir:wsEnv.sessionRuntimeBaseDir,...buildOptions?.displayName!==void 0?{displayName:buildOptions.displayName}:provenance==="live-conversation"?{displayName:"Conversations"}:{},primary:buildOptions?.primary??false,trusted,provenance,removable:buildOptions?.removable??provenance!=="live-conversation",registrationIds:[...buildOptions?.registrationIds??[]],env:wsEnv.metadata,bridge:wsBridge,workspaceService:wsService,routeFileSystemFactory:wsRouteFsFactory,clientMcpSenderRegistry:wsClientMcpRegistry,generationGuard,trustMaterialization:buildOptions?.trustMaterialization??JSON.stringify({trusted,boundWorkspaces:[...runtimeBoundWorkspaces].sort()})};subSessionStoppersByRuntime.set(wsRuntime,wsSubSessionLauncher.stop);if(provenance==="existing"&&!buildOptions?.snapshot){const latest=await trustPolicy.readDaemonTrustPolicySnapshot();if(latest.revision!==snapshot.revision){generationGuard.close();wsSubSessionLauncher.stop();await wsBridge.shutdown({reason:"trust_reconfigured"}).catch(()=>{try{wsBridge.killAllSync()}catch{}});subSessionStoppersByRuntime.delete(wsRuntime);removeArrayValue(subSessionStoppers,wsSubSessionLauncher.stop);removeArrayValue(runtimeBridges,wsBridge);removeArrayValue(internalRuntimeBridgesForCleanup,wsBridge);if((buildOptions?.validationAttempt??0)>=2){throw new Error("Workspace trust policy kept changing during runtime creation.")}const{generationGuard:_staleGuard,...retryOptions}=buildOptions??{};return createDynamicWorkspaceRuntime(cwd,{...retryOptions,validationAttempt:(buildOptions?.validationAttempt??0)+1})}}if(wsRuntime.primary&&wsRuntime.trusted){await recoverBranchWorktreePreparations({workspaceCwd:cwd,sessionService:await createBranchRecoverySessionService(wsRuntime),assertGenerationOpen:__name(()=>generationGuard.assertOpen(),"assertGenerationOpen"),isWorktreeOccupied:__name(worktreePath=>bridgeHasLiveSessionWithin(wsBridge,cwd,worktreePath),"isWorktreeOccupied"),warn:__name((message,fields)=>daemonLog.warn(message,fields),"warn")}).catch(error=>{daemonLog.warn("branch worktree recovery sweep failed",{workspace:cwd,error:error instanceof Error?error.message:String(error)})})}return wsRuntime},"createDynamicWorkspaceRuntime");const serveAppForRuntimeLifecycle={current:void 0};const workspaceRuntimeRemoval={async runtimeAdded(runtimeAdded){const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const startScheduledTaskKeepaliveForWorkspace=app3?.locals?.["startScheduledTaskKeepaliveForWorkspace"];startScheduledTaskKeepaliveForWorkspace?.(runtimeAdded);if(runtimeAdded.provenance==="live-conversation")return;channelWebhookEnvByWorkspace.set(runtimeAdded.workspaceCwd,workspaceRuntimeEffectiveEnv(runtimeAdded,daemonRuntimeBaseEnv));channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.();if(channelWorkerManager){const manager=channelWorkerManager;const activatedCwd=runtimeAdded.workspaceCwd;const activatedTrusted=runtimeAdded.trusted;void(async()=>{try{if(activatedTrusted){await manager.restoreWorkspace(activatedCwd)}await manager.refreshWorkspaces()}catch(err){daemonLog.error("workspace channel worker startup error",err instanceof Error?err:null)}finally{writeChannelWorkerPidfile()}})()}const workspaceCwd=runtimeAdded.workspaceCwd;if(!runtimeAdded.trusted||runtimeAdded.primary||channelSelectionFromFlag||lateRestoredWorkspaces.has(workspaceCwd)||readSshWorkspace(workspaceCwd)){return}if(channelHostingStoppedByOperator){daemonLog.info("skipping serve.channels for a workspace registered after boot: channel hosting was stopped",{workspaceCwd});return}if(channelWorkerManager?.state().selection?.mode==="all"){return}const requested=startupChannelsForWorkspace(workspaceCwd);if(requested.length===0)return;lateRestoredWorkspaces.add(workspaceCwd);daemonLog.info("restoring serve.channels for a workspace registered after boot",{workspaceCwd,channels:requested});void addChannelsToSelection(requested).catch(err=>{daemonLog.error(`serve.channels for a workspace registered after boot were not restored: ${sanitizeLogText(redactLogCredentials(err instanceof Error?err.message:String(err)),512)}`,null,{workspaceCwd});if(channelControlDraining)return;channelRestoreFailures.record(lateRestoreFailures(workspaceCwd,requested,err))}).finally(()=>{writeChannelWorkerPidfile()})},beginDrain(runtimeToDrain){if(runtimeToDrain.primary){if(bridgeRef===runtimeToDrain.bridge)bridgeRef=void 0;invalidatePrimaryServeFeaturesCache()}totalSessionAdmission.beginWorkspaceDrain(runtimeToDrain.workspaceCwd);if(runtimeToDrain.provenance!=="live-conversation"){channelWorkerManager?.beginWorkspaceDrain(runtimeToDrain.workspaceCwd)}workspaceVoiceCoordinator.beginWorkspaceDrain(runtimeToDrain);channelWebhookEnvByWorkspace.delete(runtimeToDrain.workspaceCwd);channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.();const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const stopScheduledTaskKeepaliveForWorkspace=app3?.locals?.["stopScheduledTaskKeepaliveForWorkspace"];try{stopScheduledTaskKeepaliveForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace scheduled-task drain error",err instanceof Error?err:null)}},cancelDrain(runtimeToDrain){if(runtimeToDrain.primary&&bridgeRef===void 0){bridgeRef=runtimeToDrain.bridge;invalidatePrimaryServeFeaturesCache()}if(runtimeToDrain.provenance!=="live-conversation"){channelWorkerManager?.cancelWorkspaceDrain(runtimeToDrain.workspaceCwd)}totalSessionAdmission.cancelWorkspaceDrain(runtimeToDrain.workspaceCwd);workspaceVoiceCoordinator.cancelWorkspaceDrain(runtimeToDrain);if(runtimeToDrain.provenance!=="live-conversation"){channelWebhookEnvByWorkspace.set(runtimeToDrain.workspaceCwd,workspaceRuntimeEffectiveEnv(runtimeToDrain,daemonRuntimeBaseEnv));channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.()}const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const startScheduledTaskKeepaliveForWorkspace=app3?.locals?.["startScheduledTaskKeepaliveForWorkspace"];try{startScheduledTaskKeepaliveForWorkspace?.(runtimeToDrain)}catch(err){daemonLog.error("workspace scheduled-task drain rollback error",err instanceof Error?err:null)}},completeDrain(runtimeToDrain){totalSessionAdmission.completeWorkspaceDrain(runtimeToDrain.workspaceCwd);workspaceVoiceCoordinator.completeWorkspaceDrain(runtimeToDrain)},getActivity(runtimeToDrain){return{pendingSessionStarts:totalSessionAdmission.snapshotForWorkspace(runtimeToDrain.workspaceCwd).inFlight,channelWorkers:runtimeToDrain.provenance==="live-conversation"?0:channelWorkerManager?.workspaceActivity(runtimeToDrain.workspaceCwd)??0,voiceSessions:workspaceVoiceCoordinator.getWorkspaceActivity(runtimeToDrain)}},disposeRuntime(runtimeToDrain,reason="workspace_removed"){const existing=runtimeCleanupPromises.get(runtimeToDrain);if(existing)return existing;const cleanup=(async()=>{runtime.getWorkspaceRuntimeCoordinatorIfSupported(runtimeToDrain)?.dispose();const containmentErrors=[];try{await workspaceVoiceCoordinator.disposeRuntime(runtimeToDrain,reason)}catch(err){daemonLog.error("workspace voice cleanup error",err instanceof Error?err:null)}if(reason==="trust_reconfigured"&&workspaceVoiceCoordinator.getWorkspaceActivity(runtimeToDrain)>0){containmentErrors.push(new Error("Workspace voice sessions are still active."))}const stopSubSessions=subSessionStoppersByRuntime.get(runtimeToDrain);try{stopSubSessions?.()}catch{}if(reason!=="daemon_shutdown"&&channelWorkerManager&&runtimeToDrain.provenance!=="live-conversation"){await channelWorkerManager.removeWorkspace(runtimeToDrain.workspaceCwd,{permanent:reason==="workspace_removed"}).catch(err=>{daemonLog.error("workspace channel worker cleanup error",err instanceof Error?err:null)});try{await channelWorkerManager.refreshWorkspaces()}catch(err){channelWorkspaceGroups=(channelWorkspaceGroups??[]).filter(group=>group.workspaceCwd!==runtimeToDrain.workspaceCwd);channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.();daemonLog.error("workspace channel worker topology refresh error",err instanceof Error?err:null)}writeChannelWorkerPidfile();if(reason==="trust_reconfigured"&&channelWorkerManager.workspaceActivity(runtimeToDrain.workspaceCwd)>0){containmentErrors.push(new Error("Workspace channel workers are still active."))}}if(reason!=="daemon_shutdown"){const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const stopWorkspaceGitStateForWorkspace=app3?.locals?.["stopWorkspaceGitStateForWorkspace"];const stopScheduledTaskKeepaliveForWorkspace=app3?.locals?.["stopScheduledTaskKeepaliveForWorkspace"];const releaseWebTerminalsForWorkspace=app3?.locals?.["releaseWebTerminalsForWorkspace"];try{stopWorkspaceGitStateForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace git-state cleanup error",err instanceof Error?err:null)}try{stopScheduledTaskKeepaliveForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace scheduled-task cleanup error",err instanceof Error?err:null)}try{releaseWebTerminalsForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace web-terminal cleanup error",err instanceof Error?err:null)}}let bridgeStopped=false;try{if(!shutdownBridges.has(runtimeToDrain.bridge)){try{await runtimeToDrain.bridge.shutdown({reason})}catch(shutdownError){try{runtimeToDrain.bridge.killAllSync();daemonLog.warn("workspace bridge required forceful shutdown",{workspace:runtimeToDrain.workspaceCwd,reason,error:shutdownError instanceof Error?shutdownError.message:String(shutdownError)})}catch(killError){throw new AggregateError([shutdownError,killError],"Workspace bridge shutdown could not be confirmed.")}}}bridgeStopped=true}finally{if(bridgeStopped){subSessionStoppersByRuntime.delete(runtimeToDrain);if(stopSubSessions){removeArrayValue(subSessionStoppers,stopSubSessions)}removeArrayValue(runtimeBridges,runtimeToDrain.bridge);removeArrayValue(internalRuntimeBridgesForCleanup,runtimeToDrain.bridge);shutdownBridges.add(runtimeToDrain.bridge)}}if(containmentErrors.length>0){throw new AggregateError(containmentErrors,"Workspace runtime containment could not be confirmed.")}})();runtimeCleanupPromises.set(runtimeToDrain,cleanup);void cleanup.catch(()=>{if(runtimeCleanupPromises.get(runtimeToDrain)===cleanup){runtimeCleanupPromises.delete(runtimeToDrain)}});return cleanup}};const channelManagementServices=new WeakMap;const channelManagementService=__name(targetRuntime=>{const existing=channelManagementServices.get(targetRuntime);if(existing)return existing;const pending=(async()=>{if(!ensureChannelWorkerManager){throw Object.assign(new Error("Channel worker manager is unavailable."),{code:"channel_worker_unavailable"})}const[{createChannelManagementService},{WorkspaceChannelSettingsStore}]=await Promise.all([import("./channel-management-service-YVXFZXFY.js"),import("./channel-settings-store-Y4YCS7JX.js")]);const manager=await ensureChannelWorkerManager();const workerRuntime=await ensureChannelRuntime();const settingsRuntime2=await loadSettingsRuntimeModules();return createChannelManagementService({workspaceCwd:targetRuntime.workspaceCwd,store:new WorkspaceChannelSettingsStore(targetRuntime.workspaceCwd),manager,loadChannelsConfig:__name(cwd=>workerRuntime.loadChannelsConfig(cwd,settingsRuntime2.settings.loadSettings(cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!targetRuntime.trusted,workspaceTrusted:targetRuntime.trusted})),"loadChannelsConfig"),restoreFailures:channelRestoreFailures})})();channelManagementServices.set(targetRuntime,pending);void pending.catch(()=>{if(channelManagementServices.get(targetRuntime)===pending){channelManagementServices.delete(targetRuntime)}});return pending},"channelManagementService");const validateWorkspaceRuntimeForPublication=__name(async runtimeForPublication=>{let candidate=runtimeForPublication;for(let attempt=0;attempt<3;attempt++){const snapshot=await trustPolicy.readDaemonTrustPolicySnapshot();const decision=trustPolicy.evaluateDaemonWorkspaceTrust(snapshot,candidate.workspaceCwd);const materialization=JSON.stringify({trusted:decision.targetTrusted,boundWorkspaces:[candidate.workspaceCwd]});if(candidate.trustMaterialization===materialization){return candidate}candidate.generationGuard?.close();await workspaceRuntimeRemoval.disposeRuntime(candidate,"trust_reconfigured");if(attempt===2){throw new Error("Workspace trust policy kept changing before runtime publication.")}candidate=await createDynamicWorkspaceRuntime(runtimeForPublication.workspaceCwd,{primary:runtimeForPublication.primary,removable:runtimeForPublication.removable,displayName:runtimeForPublication.displayName,registrationIds:runtimeForPublication.registrationIds})}throw new Error("Workspace runtime publication validation failed.")},"validateWorkspaceRuntimeForPublication");const app2=runtime.createServeApp(opts,()=>actualPort,{restartForUpdate,maxChannelControlWorkspaces:MAX_CHANNEL_CONTROL_WORKSPACES,serveAppLifecycle,liveDiscoveryStableBaseDir,workspaceRegistry,getSessionBridges:__name(()=>runtimeBridges,"getSessionBridges"),createWorkspaceRuntime:createDynamicWorkspaceRuntime,...workspaceTrustHotReloadAvailable?{validateWorkspaceRuntimeForPublication,runWorkspaceTrustOperation,getWorkspaceTrustPolicySnapshot:__name(()=>latestTrustPolicySnapshot,"getWorkspaceTrustPolicySnapshot")}:{},managedScratchRoot,liveConversationWorkspace,readLiveConversationScheduledTasks,workspaceRegistrationStore,workspaceRuntimeRemoval,workspaceTrustHotReloadAvailable,voiceCoordinator:workspaceVoiceCoordinator,bridge,webShellDir,boundWorkspace,qwenCodeVersion:resolvedCliVersion,startup,manageScheduledTaskSessions:opts.profile!=="hosted-harness",currentSessionSchedulingAvailable:deps.bridge===void 0,fsFactory:routeFsFactory,primaryWorkspaceTrusted:trustedWorkspace,primaryRuntimeEnv,daemonEnv:daemonRuntimeBaseEnv,modelSelectionBaseEnv:getEnvironmentBeforeLoad()??daemonRuntimeBaseEnv,runtimePlatform:deps.runtimePlatform,daemonLog,getChannelWorkerSnapshot,getChannelWorkerSnapshots,getChannelRestoreFailures:__name(()=>channelRestoreFailures.list(),"getChannelRestoreFailures"),getChannelWorkerControl,isChannelControlDraining:__name(()=>channelControlDraining,"isChannelControlDraining"),isChannelControlInitializing:__name(()=>channelWorkerManagerStarting!==void 0,"isChannelControlInitializing"),setChannelWorkerSelection,stopChannelWorker,getChannelWebhookConfigSources,getChannelWebhookConfigVersion:__name(()=>channelWebhookConfigVersion,"getChannelWebhookConfigVersion"),registerChannelWebhookConfigRefresh:__name(refresh=>{refreshChannelWebhookConfigs=refresh},"registerChannelWebhookConfigRefresh"),enqueueChannelWebhookTask:__name(async task=>{if(!channelWorkerManager){throw new ChannelWebhookEnqueueError("channel_worker_unavailable","Channel worker is not running.")}return channelWorkerManager.enqueueWebhookTask(task)},"enqueueChannelWebhookTask"),deliverChannelMessage:__name(async(workspaceCwd,request)=>{if(!channelWorkerManager){throw new ChannelDeliveryError("channel_worker_unavailable","Channel worker is not running.")}return channelWorkerManager.deliverChannelMessage(workspaceCwd,request)},"deliverChannelMessage"),channelDeliveryAuthorizations,reloadChannelWorker,channelManagementService,getPerfSnapshot:__name(()=>({eventLoop:currentDaemonEventLoopMonitor.snapshot(),promptQueueWait:{count:promptQueueWaitStats.count,meanMs:promptQueueWaitStats.count===0?0:promptQueueWaitStats.totalMs/promptQueueWaitStats.count,maxMs:promptQueueWaitStats.maxMs,lastMs:promptQueueWaitStats.lastMs},pipe:{inbound:{...pipeStats.inbound},outbound:{...pipeStats.outbound}}}),"getPerfSnapshot"),getMetricsSeries:__name(()=>metricsRing.snapshot(),"getMetricsSeries"),getTotalSessionAdmissionSnapshot:totalSessionAdmission.snapshot,getChildHeapPolicySnapshot:__name(()=>managedChildHeapPolicy?.snapshot(),"getChildHeapPolicySnapshot"),...childHeapPolicy?{managedChildProcesses:{registry:processRegistry,policy:childHeapPolicy,ownsBridge:__name(candidate=>runtimeBridges.includes(candidate),"ownsBridge")}}:{},recordDaemonRequest:__name((durationMs,statusCode)=>metricsRing.recordRequest(durationMs,statusCode),"recordDaemonRequest"),workspace:workspaceService,clientMcpSenderRegistry,persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,sessionArtifactsPersistenceAvailable:sessionArtifactsPersistenceAvailableFromSettings(runtimeBootSettings?.merged),updateModelContextWindow:__name((workspace,key,size,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen();const{updateModelContextWindow}=await import("./model-configuration-6HRNYBWV.js");return updateModelContextWindow(loadSettingsForPersistence(workspace),key,size,assertGenerationOpen)}),"updateModelContextWindow"),installAuthProvider:__name((req,assertGenerationOpen)=>withSettingsLock(boundWorkspace,async()=>{assertGenerationOpen?.();const provider=core.findProviderById(req.providerId);if(!provider){throw new Error(`Unsupported auth provider: ${req.providerId}`)}const inputs=buildProviderSetupInputs(req,provider,{getDefaultModelIds:core.getDefaultModelIds,resolveBaseUrl:core.resolveBaseUrl});const fresh=loadSettingsForPersistence(boundWorkspace);const plan=core.buildInstallPlan(provider,inputs,core.getModelsForProviderProtocol(fresh.merged.modelProviders,inputs.protocol??provider.protocol,fresh.merged.providerProtocol),{authType:fresh.merged.security?.auth?.selectedType,id:fresh.merged.model?.name,baseUrl:fresh.merged.model?.baseUrl});const adapter=settingsRuntime.loadedSettingsAdapter.createLoadedSettingsAdapter(fresh);const{getAuthTypeFromEnv}=await import("./modelConfigUtils-SKBN64ZW.js");const hasConversationAuth=adapter.getValue("security.auth.selectedType")||getAuthTypeFromEnv(primaryRuntimeEnv.effectiveEnv);await core.applyProviderInstallPlan(plan,{settings:adapter,doRefreshAuth:false});assertGenerationOpen?.();core.emitDaemonLog("Auth provider installed.",{"qwen-code.daemon.auth.provider_id":provider.id,"qwen-code.daemon.auth.auth_type":plan.authType});const effectiveModelId=adapter.getValue("model.name")??plan.modelSelection?.modelId;const effectiveBaseUrl=adapter.getValue("model.baseUrl")??plan.modelSelection?.baseUrl??inputs.baseUrl;return{v:1,providerId:provider.id,providerLabel:provider.label,authType:plan.authType,...effectiveModelId?{modelId:effectiveModelId}:{},...effectiveBaseUrl?{baseUrl:effectiveBaseUrl}:{},message:!plan.modelSelection?hasConversationAuth?"Service models saved.":"Service models saved. Configure a conversation model to start chatting.":`Successfully configured ${provider.label}. Use /model to switch models.`}}),"installAuthProvider")});idleReclaimerRef.current=app2.locals["reclaimIdleAcp"];serveAppForRuntimeLifecycle.current=app2;invalidatePrimaryServeFeaturesCache=app2.locals.invalidateServeFeaturesCache??invalidatePrimaryServeFeaturesCache;app2.locals.subSessionStoppers=subSessionStoppers;subSessionStoppers.push(subSessionLauncher.stop);subSessionStoppersByRuntime.set(workspaceRegistry.primary,subSessionLauncher.stop);if(workspaceTrustHotReloadAvailable){const[{createWorkspaceTrustReconciler},{createDaemonTrustPolicyMonitor}]=await Promise.all([import("./workspace-trust-reconciler-NLJGGI4K.js"),import("./daemon-trust-policy-monitor-L2ORKHMM.js")]);const materializationFor=__name((entry,snapshot,decision)=>{const boundWorkspaces2=entry.primary&&decision.targetTrusted?runtime.resolveBoundWorkspacesFromIdeEnv(entry.workspaceCwd,void 0,(workspace,index)=>index===0||trustPolicy.evaluateDaemonWorkspaceTrust(snapshot,workspace).targetTrusted):[entry.workspaceCwd];return{key:JSON.stringify({trusted:decision.targetTrusted,boundWorkspaces:[...boundWorkspaces2].sort()}),boundWorkspaces:boundWorkspaces2}},"materializationFor");const acpHandle=__name(()=>app2.locals?.["acpHandle"],"acpHandle");const trustReconciler=createWorkspaceTrustReconciler({registry:workspaceRegistry,readLatestSnapshot:__name(async()=>(await readWorkflowTrustAdmission()).snapshot,"readLatestSnapshot"),materializationKey:__name(({entry,snapshot,decision})=>materializationFor(entry,snapshot,decision).key,"materializationKey"),isTrustDecrease:__name(({runtime:current,nextMaterialization,decision})=>{if(current.trusted&&!decision.targetTrusted)return true;if(!current.primary||!current.trusted)return false;try{const previous=JSON.parse(current.trustMaterialization??"{}");const next=JSON.parse(nextMaterialization);if(!Array.isArray(previous.boundWorkspaces)||!Array.isArray(next.boundWorkspaces)){return true}const nextRoots=new Set(next.boundWorkspaces.filter(value=>typeof value==="string"));return previous.boundWorkspaces.some(value=>typeof value!=="string"||!nextRoots.has(value))}catch{return true}},"isTrustDecrease"),buildRuntime:__name(async({entry,trusted,snapshot,decision,generationGuard})=>{const materialized=materializationFor(entry,snapshot,trusted===decision.targetTrusted?decision:{...decision,targetTrusted:trusted});return createDynamicWorkspaceRuntime(entry.workspaceCwd,{trusted,snapshot,decision,generationGuard,primary:entry.primary,removable:entry.removable,displayName:entry.displayName,registrationIds:entry.registrationIds,boundWorkspaces:materialized.boundWorkspaces,trustMaterialization:materialized.key})},"buildRuntime"),drainRuntime:__name(async runtimeToDrain=>{workspaceRuntimeRemoval.beginDrain(runtimeToDrain);acpHandle()?.beginWorkspaceDrain(runtimeToDrain.workspaceId)},"drainRuntime"),disposeRuntime:__name(async(runtimeToDispose,reason)=>{const errors=[];try{await workspaceRuntimeRemoval.disposeRuntime(runtimeToDispose,reason)}catch(error){errors.push(error)}try{const handle=acpHandle();if(!runtimeToDispose.primary){handle?.commitWorkspaceRemoval(runtimeToDispose.workspaceId)}handle?.disposeWorkspace(runtimeToDispose.workspaceId);const deadline=Date.now()+1e3;while((handle?.getWorkspaceActivity(runtimeToDispose.workspaceId).memoryTasks??0)>0&&Date.now()<deadline){await new Promise(resolve3=>setTimeout(resolve3,25))}if((handle?.getWorkspaceActivity(runtimeToDispose.workspaceId).memoryTasks??0)>0){throw new Error("Workspace memory tasks did not stop after runtime disposal.")}}catch(error){errors.push(error)}if(errors.length===1)throw errors[0];if(errors.length>1){throw new AggregateError(errors,"Workspace runtime and ACP cleanup failed.")}},"disposeRuntime"),runtimeActivated:__name(async runtimeAdded=>{workspaceRuntimeRemoval.cancelDrain(runtimeAdded);acpHandle()?.cancelWorkspaceDrain(runtimeAdded.workspaceId);if(runtimeAdded.primary){bridgeRef=runtimeAdded.bridge;invalidatePrimaryServeFeaturesCache()}await workspaceRuntimeRemoval.runtimeAdded(runtimeAdded)},"runtimeActivated"),onError:__name((entry,error)=>{daemonLog.error(`workspace trust reconciliation failed for ${entry.workspaceCwd}`,error instanceof Error?error:null)},"onError")});const trustMonitor=createDaemonTrustPolicyMonitor({onSnapshot:__name(snapshot=>{latestTrustPolicySnapshot=snapshot;publishedWorkflowTrustPolicy={publication:publishedWorkflowTrustPolicy.publication+1,snapshot};workflowTrustAdmissions.set(snapshot,{publication:publishedWorkflowTrustPolicy.publication,snapshot});return runWorkspaceTrustOperation(()=>trustReconciler.reconcile(snapshot))},"onSnapshot"),onError:__name(error=>{publishedWorkflowTrustPolicy={publication:publishedWorkflowTrustPolicy.publication+1};daemonLog.error("workspace trust policy monitor failed",error instanceof Error?error:null)},"onError")});app2.locals.stopTrustPolicyMonitor=()=>trustMonitor.stop();app2.locals.requestTrustReconcile=()=>trustMonitor.requestReconcile("manual");app2.locals.waitForTrustPolicyIdle=()=>runWorkspaceTrustOperation(async()=>void 0);await trustMonitor.start()}const activePrimaryBridge=workspaceRegistry.primaryEntry.current?.runtime.bridge;bridgeRef=activePrimaryBridge;return{app:app2,bridge:activePrimaryBridge}},"buildRuntime");if(deps.bridge){const runtime=await buildRuntime();runtimeAppForCleanup=runtime.app;bridgeRef=runtime.bridge;if(!opts.channelSelection){runtimeApp=runtime.app;runtimeStartupSettled=true;markRuntimeReady()}}cliVersion??=await cliVersionPromise;const bootstrapApp=createBootstrapServeApp({opts,getPort:__name(()=>actualPort,"getPort"),boundWorkspace,startup,daemonLog,qwenCodeVersion:cliVersion,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable:deps.bridge===void 0||typeof deps.bridge.getWorkspaceRuntimeLifecycleSnapshot==="function",currentSessionSchedulingAvailable:false,permissionPolicy,multiWorkspaceCapabilitiesRequireRuntime:workspaceInputs.length>1,getRuntimeError:__name(()=>runtimeStartupError,"getRuntimeError"),getChannelWorkerSnapshot,getChannelWorkerSnapshots,getChannelRestoreFailures:__name(()=>channelRestoreFailures.list(),"getChannelRestoreFailures"),onHealthServed:deferRuntimeUntilFirstHealth?()=>startRuntimeAfterHealth?.():void 0});const deferredChannelWebhookAuth=deferRuntimeUntilFirstHealth?createDeferredChannelWebhookAuth(resolveChannelWebhookConfigSource,await loadChannelWebhookConfigRuntime(),daemonLog):void 0;const app=runtimeApp??createDelegatingServeApp(bootstrapApp,()=>runtimeApp,{waitForDeferredRuntimeRoutes:deferRuntimeUntilFirstHealth,startRuntime:__name(()=>startRuntimeForRequest?.()??false,"startRuntime"),runtimeReady,authenticateDeferredRuntimeRequest:bearerAuth(opts.token),authenticateDeferredChannelWebhookRequest:deferredChannelWebhookAuth,isPreAuthRequest:__name(async req=>{if(req.path.startsWith("/agent-hosts/")){return true}if(!webShellMounted){return false}const webShellStatic=await import("./web-shell-static-FZQRCYGX.js");return webShellStatic.isPreAuthWebShellRequest(req)},"isPreAuthRequest")});let listenHostname=opts.hostname;if(opts.hostname.startsWith("[")){const inner=opts.hostname.slice(1,-1);if(!opts.hostname.endsWith("]")||inner.length===0||inner.includes("]")){throw new Error(`Invalid --hostname "${opts.hostname}": brackets indicate an IPv6 literal but the value isn't a clean [addr] form. Pass the address without a trailing :port (use --port for that), e.g. "--hostname [::1] --port 4170".`)}listenHostname=inner}if(opts.maxConnections!==void 0&&(Number.isNaN(opts.maxConnections)||opts.maxConnections<0)){throw new TypeError(`Invalid maxConnections: ${opts.maxConnections}. Must be >= 0 (0 / Infinity = unlimited).`)}let channelValidationSettingsRuntime;let channelValidationTrustPolicy;let channelValidationTrustSnapshot;const resolveChannelWorkspaceGroupsAtListen=__name(()=>{const validationSettingsRuntime=channelValidationSettingsRuntime;if(!opts.channelSelection||!validationSettingsRuntime||!channelRuntime){return void 0}const registry=(runtimeApp??runtimeAppForCleanup)?.locals?.["workspaceRegistry"];const resolveRuntime=__name(workspaceCwd=>{const runtime=registry?.getByWorkspaceCwd(workspaceCwd);if(registry&&!runtime){throw Object.assign(new Error(`Workspace "${workspaceCwd}" is unavailable.`),{code:"workspace_unavailable"})}return runtime},"resolveRuntime");const resolveTrusted=__name((workspaceCwd,primary,runtime)=>{if(runtime)return runtime.trusted;if(primary&&deps.trustedWorkspace!==void 0){return deps.trustedWorkspace}if(!channelValidationTrustPolicy||!channelValidationTrustSnapshot){return false}return channelValidationTrustPolicy.evaluateDaemonWorkspaceTrust(channelValidationTrustSnapshot,workspaceCwd).targetTrusted},"resolveTrusted");const settingsByWorkspace=new Map;if(workspaceInputs.length===1){const workspace=workspaceInputs[0];const runtime=resolveRuntime(workspace.cwd);const trusted=resolveTrusted(workspace.cwd,true,runtime);if(!trusted){throw Object.assign(new Error(`Primary workspace "${workspace.cwd}" is not trusted; cannot host channels.`),{code:"untrusted_workspace"})}const effectiveEnv=runtime?workspaceRuntimeEffectiveEnv(runtime,daemonRuntimeBaseEnv):validationSettingsRuntime.environment.buildRuntimeEnvironment(validationSettingsRuntime.settings.loadSettings(workspace.cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:false,workspaceTrusted:true}).merged,workspace.cwd,daemonRuntimeBaseEnv,trusted).effectiveEnv;channelWebhookEnvByWorkspace.set(workspace.cwd,effectiveEnv);return void 0}const channelWorkspaces=workspaceInputs.filter(workspace=>!readSshWorkspace(workspace.cwd));const workspaces=channelWorkspaces.map((workspace,index)=>{const runtime=resolveRuntime(workspace.cwd);const trusted=resolveTrusted(workspace.cwd,index===0,runtime);const settings=validationSettingsRuntime.settings.loadSettings(workspace.cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted});settingsByWorkspace.set(workspace.cwd,settings);channelWebhookEnvByWorkspace.set(workspace.cwd,runtime?workspaceRuntimeEffectiveEnv(runtime,daemonRuntimeBaseEnv):validationSettingsRuntime.environment.buildRuntimeEnvironment(settings.merged,workspace.cwd,daemonRuntimeBaseEnv,trusted).effectiveEnv);return{workspaceCwd:workspace.cwd,primary:runtime?.primary??index===0,trusted}});const grouping=resolveChannelWorkspaceGroups({workspaces,selection:opts.channelSelection,loadChannelsConfig:__name(cwd=>{const settings=settingsByWorkspace.get(cwd);if(!settings)return{};return channelRuntime.loadChannelsConfig(cwd,settings)},"loadChannelsConfig"),preferredOwners:channelOwnerHints,tolerant:channelStartupTolerantNames});if(!grouping.ok){throw Object.assign(new Error(grouping.error.message),{code:grouping.error.code,...grouping.error.channel?{channel:grouping.error.channel}:{}})}return{groups:grouping.groups,skipped:grouping.skipped??[]}},"resolveChannelWorkspaceGroupsAtListen");if(opts.channelSelection){try{channelValidationSettingsRuntime=await loadSettingsRuntimeModules();channelValidationTrustPolicy=await import("./daemon-trust-policy-GXKJVZDU.js");channelValidationTrustSnapshot=await channelValidationTrustPolicy.readDaemonTrustPolicySnapshot();if(opts.channelSelection.mode==="names"&&workspaceInputs.length>MAX_CHANNEL_CONTROL_WORKSPACES){const resolved=resolveChannelWorkspaceGroupsAtListen();assertChannelControlWorkspaceCapacity(resolved?.groups.map(group=>group.workspaceCwd)??[])}reserveChannelServicePidfile(opts.channelSelection)}catch(error){if(!channelSelectionFromSettings)throw error;removeCurrentServePidfile();opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error)}}return await new Promise((resolve3,reject)=>{let closeHost;const onListening=__name(error=>{if(error)return;startup.listenerReadyAt=new Date().toISOString();startup.processToListenMs=Math.round(process.uptime()*1e3);startup.runQwenServeToListenMs=Math.round(performance2.now()-runStartedAt);profileCheckpoint("serve_listener_ready");finalizeStartupProfile(`serve-${process.pid}`);const cap=opts.maxConnections??256;if(cap>0&&Number.isFinite(cap)){server.maxConnections=cap}const addr=server.address();actualPort=typeof addr==="object"&&addr?addr.port:opts.port;const scheme=tlsOptions?"https":"http";const url=`${scheme}://${formatHostForUrl(optsIn.hostname)}:${actualPort}`;const liveRuntimeBaseDir=path.dirname(daemonLogBaseDir);const liveDiscoveryOwners=[];const rememberLiveDiscoveryOwner=__name(owner=>{if(liveDiscoveryOwners.some(candidate=>candidate.runtimeBaseDir===owner.runtimeBaseDir&&candidate.instanceNonce===owner.instanceNonce&&candidate.pid===owner.pid)){return}liveDiscoveryOwners.push(owner)},"rememberLiveDiscoveryOwner");let liveDiscoveryPublish;let liveDiscoveryRetryTimer;let liveDiscoveryRetryTask;let liveDiscoveryBootRetryApp;let liveDiscoveryEnabled=false;let liveDiscoveryShuttingDown=false;let liveDiscoveryToggle=Promise.resolve();let attemptPendingLiveDiscovery;const pendingLiveDiscoveryBaseDirs=new Set;const warnedLiveDiscoveryOwners=new Set;let warnedLiveDiscoveryBootFailure=false;const liveDiscoveryRetryDelayMs=deps.liveDiscoveryRetryDelayMs!==void 0&&Number.isFinite(deps.liveDiscoveryRetryDelayMs)&&deps.liveDiscoveryRetryDelayMs>=10?Math.min(deps.liveDiscoveryRetryDelayMs,6e4):DEFAULT_LIVE_DISCOVERY_RETRY_MS;const scheduleLiveDiscoveryRetry=__name(()=>{if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled||liveDiscoveryRetryTimer||liveDiscoveryRetryTask||!liveDiscoveryBootRetryApp&&(pendingLiveDiscoveryBaseDirs.size===0||!attemptPendingLiveDiscovery)){return}liveDiscoveryRetryTimer=setTimeout(()=>{liveDiscoveryRetryTimer=void 0;if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled){return}const retryApp=liveDiscoveryBootRetryApp;liveDiscoveryBootRetryApp=void 0;const retryOperation=retryApp?publishLiveDiscovery(retryApp):attemptPendingLiveDiscovery?.();if(!retryOperation)return;const retry=retryOperation.finally(()=>{if(liveDiscoveryRetryTask===retry){liveDiscoveryRetryTask=void 0}scheduleLiveDiscoveryRetry()});liveDiscoveryRetryTask=retry},liveDiscoveryRetryDelayMs);liveDiscoveryRetryTimer.unref()},"scheduleLiveDiscoveryRetry");const cancelLiveDiscoveryRetry=__name(()=>{if(!liveDiscoveryRetryTimer)return;clearTimeout(liveDiscoveryRetryTimer);liveDiscoveryRetryTimer=void 0},"cancelLiveDiscoveryRetry");const publishLiveDiscovery=__name(candidateApp=>{if(liveDiscoveryShuttingDown)return Promise.resolve();if(!resolveAcpHttpEnabled())return Promise.resolve();if(candidateApp.locals?.["liveVoiceEnabled"]!==true)return Promise.resolve();liveDiscoveryEnabled=true;if(liveDiscoveryPublish)return liveDiscoveryPublish;const coordinator=candidateApp.locals?.["liveCoordinator"];const instanceNonce=coordinator?.daemonInstanceNonce;if(typeof instanceNonce!=="string")return Promise.resolve();let publicationFailed=false;let publicationRetryable=false;const publication=serveAppLifecycle.startBoot().then(()=>loadLiveDiscoveryRuntime()).then(async({handoffLiveDiscoveryOwner,LiveDiscoveryOwnerActiveError,LiveDiscoveryPublicationError,removeLiveDiscoveryFile,writeLiveDiscoveryFile})=>{if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled)return;liveDiscoveryBootRetryApp=void 0;warnedLiveDiscoveryBootFailure=false;const stableBaseDir=liveDiscoveryStableBaseDir;const runtimeBaseDir=path.resolve(liveRuntimeBaseDir);const targetBaseDirs=new Set;if(runtimeBaseDir!==stableBaseDir){targetBaseDirs.add(runtimeBaseDir)}targetBaseDirs.add(stableBaseDir);for(const baseDir of targetBaseDirs){pendingLiveDiscoveryBaseDirs.add(baseDir)}const record={url,...token?{token}:{},protocolVersion:LIVE_HOST_PROTOCOL_VERSION,pid:process.pid,instanceNonce};attemptPendingLiveDiscovery=__name(async()=>{const targets=[...pendingLiveDiscoveryBaseDirs];const published=[];const rollbackPublished=__name(async()=>{for(const owner of published.splice(0)){try{await removeLiveDiscoveryFile(owner.runtimeBaseDir,owner)}catch(cleanupError){rememberLiveDiscoveryOwner(owner);daemonLog.warn(`failed to roll back Live Host discovery at ${owner.runtimeBaseDir}: ${cleanupError instanceof Error?cleanupError.message:String(cleanupError)}`)}}},"rollbackPublished");for(const runtimeBaseDir2 of targets){if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled){await rollbackPublished();return}try{await handoffLiveDiscoveryOwner(runtimeBaseDir2,record,async()=>void 0);await writeLiveDiscoveryFile(runtimeBaseDir2,record);published.push({runtimeBaseDir:runtimeBaseDir2,instanceNonce,pid:process.pid})}catch(err){if(err instanceof LiveDiscoveryPublicationError&&err.published){published.push({runtimeBaseDir:runtimeBaseDir2,instanceNonce,pid:process.pid})}await rollbackPublished();if(err instanceof LiveDiscoveryOwnerActiveError){if(!warnedLiveDiscoveryOwners.has(runtimeBaseDir2)){warnedLiveDiscoveryOwners.add(runtimeBaseDir2);daemonLog.warn(`failed to publish Live Host discovery at ${runtimeBaseDir2}: ${err.message}`)}return}daemonLog.warn(`failed to publish Live Host discovery at ${runtimeBaseDir2}: ${err instanceof Error?err.message:String(err)}`);return}}for(const owner of published){pendingLiveDiscoveryBaseDirs.delete(owner.runtimeBaseDir);warnedLiveDiscoveryOwners.delete(owner.runtimeBaseDir);rememberLiveDiscoveryOwner(owner)}},"attemptPendingLiveDiscovery");await attemptPendingLiveDiscovery();scheduleLiveDiscoveryRetry()}).catch(err=>{publicationFailed=true;publicationRetryable=err instanceof ConversationRuntimeOwnershipError&&err.retryable;if(!publicationRetryable||!warnedLiveDiscoveryBootFailure){warnedLiveDiscoveryBootFailure=publicationRetryable;daemonLog.warn(`failed to publish Live Host discovery: ${err instanceof Error?err.message:String(err)}`)}});const trackedPublication=publication.finally(()=>{if(publicationFailed&&liveDiscoveryPublish===trackedPublication){liveDiscoveryPublish=void 0;if(publicationRetryable&&!liveDiscoveryShuttingDown&&liveDiscoveryEnabled){liveDiscoveryBootRetryApp=candidateApp;scheduleLiveDiscoveryRetry()}}});liveDiscoveryPublish=trackedPublication;return liveDiscoveryPublish},"publishLiveDiscovery");const removeLiveDiscoveryOwners=__name(async()=>{const owners=[...liveDiscoveryOwners];if(owners.length===0)return;let removeLiveDiscoveryFile;try{({removeLiveDiscoveryFile}=await loadLiveDiscoveryRuntime())}catch(err){throw new Error("Failed to load Live discovery cleanup support.",{cause:err})}const errors=[];for(const owner of owners){try{await removeLiveDiscoveryFile(owner.runtimeBaseDir,owner);const index=liveDiscoveryOwners.indexOf(owner);if(index>=0)liveDiscoveryOwners.splice(index,1)}catch(err){errors.push(err)}}if(errors.length>0){throw new AggregateError(errors,"Live Host discovery cleanup is incomplete.")}},"removeLiveDiscoveryOwners");const unpublishLiveDiscovery=__name(async()=>{liveDiscoveryEnabled=false;liveDiscoveryBootRetryApp=void 0;warnedLiveDiscoveryBootFailure=false;cancelLiveDiscoveryRetry();pendingLiveDiscoveryBaseDirs.clear();attemptPendingLiveDiscovery=void 0;await liveDiscoveryPublish;await liveDiscoveryRetryTask;liveDiscoveryPublish=void 0;liveDiscoveryRetryTask=void 0;await removeLiveDiscoveryOwners()},"unpublishLiveDiscovery");const attachLiveDiscoveryControl=__name(candidateApp=>{candidateApp.locals.setLiveDiscoveryEnabled=enabled=>{const operation=liveDiscoveryToggle.then(()=>enabled?publishLiveDiscovery(candidateApp):unpublishLiveDiscovery());liveDiscoveryToggle=operation.catch(()=>void 0);return operation};candidateApp.locals.onConversationRuntimeReady=()=>{void publishLiveDiscovery(candidateApp)}},"attachLiveDiscoveryControl");const cleanupLiveDiscovery=__name(async()=>{liveDiscoveryShuttingDown=true;cancelLiveDiscoveryRetry();await liveDiscoveryToggle;await unpublishLiveDiscovery()},"cleanupLiveDiscovery");let shuttingDown=false;let closePromise;let runtimeStartupTimer;let runtimeStartAfterHealthTimer;let runtimeStartFallbackTimer;const runtimeStartupTimeoutMs=resolveRuntimeStartupTimeoutMs(deps.runtimeStartupTimeoutMs);const clearRuntimeStartupTimer=__name(()=>{if(!runtimeStartupTimer)return;clearTimeout(runtimeStartupTimer);runtimeStartupTimer=void 0},"clearRuntimeStartupTimer");const clearRuntimeStartFallbackTimer=__name(()=>{if(!runtimeStartFallbackTimer)return;clearTimeout(runtimeStartFallbackTimer);runtimeStartFallbackTimer=void 0},"clearRuntimeStartFallbackTimer");const clearRuntimeStartAfterHealthTimer=__name(()=>{if(!runtimeStartAfterHealthTimer)return;clearTimeout(runtimeStartAfterHealthTimer);runtimeStartAfterHealthTimer=void 0},"clearRuntimeStartAfterHealthTimer");const cancelDeferredRuntimeStartup=__name(()=>{if(!deferRuntimeUntilFirstHealth||runtimeStarting||runtimeStartupSettled)return;daemonLog.info("deferred runtime: cancelled, server closed before startup");runtimeStartupSettled=true;const error2=new Error(RUNTIME_STARTUP_CANCELLED_MESSAGE);runtimeStartupError=error2.message;markRuntimeFailed(error2)},"cancelDeferredRuntimeStartup");const shutdownBridgeAfterFailedStartup=__name(async bridge=>{if(!bridge||deps.bridge)return;if(shutdownBridges.has(bridge))return;shutdownBridges.add(bridge);try{await bridge.shutdown()}catch(shutdownErr){daemonLog.error("bridge shutdown after runtime startup error failed",shutdownErr instanceof Error?shutdownErr:null)}finally{if(bridgeRef===bridge){bridgeRef=void 0}}},"shutdownBridgeAfterFailedStartup");const stopChannelWorkerAfterFailedStartup=__name(async()=>{if(!channelWorkerManager)return true;try{await channelWorkerManager.shutdown();return true}catch(stopErr){daemonLog.error("channel worker stop after runtime startup error failed",stopErr instanceof Error?stopErr:null);return false}},"stopChannelWorkerAfterFailedStartup");const failRuntimeStartup=__name(async(err,bridgeForCleanup)=>{const error2=err instanceof Error?err:new Error(String(err));markServeAppStartupFailed(error2);if(runtimeStartupSettled){disposeRuntimeAppResources(runtimeApp??runtimeAppForCleanup);await shutdownBridgeAfterFailedStartup(bridgeForCleanup);return}runtimeStartupSettled=true;disposeRuntimeAppResources(runtimeApp??runtimeAppForCleanup);runtimeApp=void 0;clearRuntimeStartupTimer();const message=error2.message;runtimeStartupError=message;if(startup.preheat.status==="scheduled"||startup.preheat.status==="running"){startup.preheat.status="failed";startup.preheat.error=message}writeStderrLine(`qwen serve: runtime startup failed: ${message}`);daemonLog.error("runtime startup failed",error2);markRuntimeFailed(error2);if(closeServerAfterChannelWorkerStartupFailure&&server.listening){server.close(closeErr=>{if(closeErr){daemonLog.error("server close after runtime startup error failed",closeErr)}});server.closeAllConnections()}const channelWorkerStopped=await stopChannelWorkerAfterFailedStartup();disposeDaemonEventLoopMonitor();if(channelWorkerStopped)removeCurrentServePidfile();const bridgesForCleanup=bridgeForCleanup?[bridgeForCleanup,...getRuntimeBridgesForCleanup()]:getRuntimeBridgesForCleanup();for(const bridge of[...new Set(bridgesForCleanup)]){await shutdownBridgeAfterFailedStartup(bridge)}},"failRuntimeStartup");const armRuntimeStartupTimer=__name(()=>{if(runtimeStartupTimeoutMs<=0||runtimeStartupTimer)return;runtimeStartupTimer=setTimeout(()=>{const timeoutError=new Error(`Daemon runtime startup timed out after ${runtimeStartupTimeoutMs}ms.`);void failRuntimeStartup(timeoutError)},runtimeStartupTimeoutMs);runtimeStartupTimer.unref()},"armRuntimeStartupTimer");const resolveRuntimeChannelGroups=__name(async(channelSelection,candidateApp,operation)=>{const registry=candidateApp.locals?.["workspaceRegistry"];if(!registry){throw new Error("Workspace registry is not available for channel workers.")}const runtimes=registry.list().filter(runtime=>runtime.provenance!=="live-conversation");if(runtimes.length<=1&&operation==="initial"){const primary=registry.primary;if(!primary.trusted){throw Object.assign(new Error(`Primary workspace "${primary.workspaceCwd}" is not trusted; cannot host channels.`),{code:"untrusted_workspace"})}return[{workspaceCwd:primary.workspaceCwd,selection:channelSelection}]}const workerRuntime=await ensureChannelRuntime();const settingsRuntime=await loadSettingsRuntimeModules();const settingsByWorkspace=new Map;const channelRuntimes=runtimes.filter(runtime=>!runtime.routeFileSystemFactory.sshWorkspace);const grouping=resolveChannelWorkspaceGroups({workspaces:channelRuntimes.map(runtime=>{const settings=settingsRuntime.settings.loadSettings(runtime.workspaceCwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!runtime.trusted,workspaceTrusted:runtime.trusted});settingsByWorkspace.set(runtime.workspaceCwd,settings);return{workspaceCwd:runtime.workspaceCwd,primary:runtime.primary,trusted:runtime.trusted,provenance:runtime.provenance}}),selection:channelSelection,loadChannelsConfig:__name(cwd=>{const settings=settingsByWorkspace.get(cwd);return settings?workerRuntime.loadChannelsConfig(cwd,settings):{}},"loadChannelsConfig"),preferredOwners:channelOwnerHints});if(!grouping.ok){throw Object.assign(new Error(grouping.error.message),{code:grouping.error.code,...grouping.error.channel?{channel:grouping.error.channel}:{}})}return grouping.groups},"resolveRuntimeChannelGroups");ensureChannelWorkerManager=__name(()=>{if(channelWorkerManager)return Promise.resolve(channelWorkerManager);if(channelWorkerManagerStarting)return channelWorkerManagerStarting;const starting=(async()=>{const candidateApp=runtimeApp??runtimeAppForCleanup;const registry=candidateApp?.locals?.["workspaceRegistry"];if(!candidateApp||!registry){throw new Error("Workspace registry is not available for channels.")}const workerRuntime=await ensureChannelRuntime();const workerHostname=tlsOptions?optsIn.hostname:opts.hostname;const workerDaemonUrl=formatChannelWorkerDaemonUrl(workerHostname,actualPort,tlsOptions!==void 0);(deps.channelWorkerUrlCertifier??assertChannelWorkerDaemonUrlIsLocal)(workerDaemonUrl,workerHostname);if(tlsOptions&&tlsCertPath&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]==="0"){daemonLog.warn(`NODE_TLS_REJECT_UNAUTHORIZED=0 disables certificate verification for channel workers; skipping the worker TLS trust check.`)}else if(tlsOptions&&tlsCertPath){const operatorCaCertPath=process.env["NODE_EXTRA_CA_CERTS"];let operatorCaCert;let operatorCaCertReadError;if(operatorCaCertPath){try{operatorCaCert=fs.readFileSync(operatorCaCertPath)}catch(error2){operatorCaCertReadError=error2?.code??"read failed"}}let predictedGaps=[];try{predictedGaps=describeWorkerTlsTrustGaps({cert:tlsOptions.cert,certPath:tlsCertPath,certSourcePath:tlsCertPath,daemonUrl:workerDaemonUrl,...operatorCaCertPath?{operatorCaCertPath}:{},...operatorCaCert?{operatorCaCert,operatorCaCertSourcePath:operatorCaCertPath}:{},...operatorCaCertReadError?{operatorCaCertReadError}:{}})}catch(error2){if(!(error2 instanceof ExtraCaInspectionError))throw error2;daemonLog.warn(`Channel worker TLS trust-gap inspection could not run: ${error2.message} Continuing with the live handshake probe only.`)}const workerCaCertPath=workerRuntime.resolveWorkerCaCertPath(tlsCertPath,operatorCaCertPath);const trustFailure=await(deps.workerTlsTrustVerifier??verifyWorkerTlsTrust)({daemonUrl:workerDaemonUrl,caCertPath:workerCaCertPath});if(shuttingDown||runtimeStartupError!==void 0){throw new Error("Daemon stopped while the channel worker TLS trust check was running.")}if(trustFailure){if(predictedGaps.length>0){for(const gap of predictedGaps)daemonLog.warn(gap)}else{daemonLog.warn(`Channel worker TLS verification failed against the exact CA bundle workers receive (${sanitizeLogText(normalizeWorkerDiagnostic(trustFailure.code),80)}): ${sanitizeLogText(normalizeWorkerDiagnostic(trustFailure.message),300)}`)}}}const createSupervisor=deps.channelWorkerSupervisorFactory??workerRuntime.createChannelWorkerSupervisor;const createGroup=__name(groups=>workerRuntime.createChannelWorkerGroup({groups,registry,createSupervisor,shared:{cliEntryPath:workerRuntime.findCliEntryPath(),daemonUrl:workerDaemonUrl,...token?{daemonToken:token}:{},...tlsCertPath?{workerTlsCaCertPath:tlsCertPath}:{}},onReady:__name(snapshot=>{if(runtimeStartupError!==void 0)return;if(workspaceInputs.length>1){daemonLog.info("channel worker ready",{workspace:snapshot.workspaceCwd,pid:snapshot.pid,channels:snapshot.channels})}channelWorkerManager?.workerChanged();if(!runtimeStartupSettled)writeChannelWorkerPidfile()},"onReady"),onExit:__name(snapshot=>{const workspacePrefix=workspaceInputs.length>1?`workspace=${snapshot.workspaceCwd}, `:"";daemonLog.warn(`channel worker exited (${workspacePrefix}state=${snapshot.state}, pid=${snapshot.pid??"unknown"}, code=${snapshot.exitCode??"null"}, signal=${snapshot.signal??"null"}, error=${snapshot.error??"none"}, restartCount=${snapshot.restartCount??0}, nextRestartAt=${snapshot.nextRestartAt??"none"}, staleHeartbeatAt=${snapshot.staleHeartbeatAt??"none"})`);channelWorkerManager?.workerChanged();if(!runtimeStartupSettled)writeChannelWorkerPidfile()},"onExit"),onStateChange:__name(()=>{channelWorkerManager?.workerChanged();if(!runtimeStartupSettled)writeChannelWorkerPidfile()},"onStateChange"),onLog:__name(({stream,line,workspaceCwd})=>{const message=workspaceInputs.length>1?`channel worker [${workspaceCwd}] ${stream}: ${line}`:`channel worker ${stream}: ${line}`;if(stream==="stderr")daemonLog.warn(message);else daemonLog.info(message)},"onLog")}),"createGroup");channelWorkerManager=workerRuntime.createChannelWorkerManager({resolveGroups:__name((selection,operation)=>resolveRuntimeChannelGroups(selection,candidateApp,operation),"resolveGroups"),createGroup,reserveLease:reserveChannelServicePidfile,releaseLease:__name(()=>{removeCurrentServePidfile();if(channelPidfileReserved){throw new Error("Failed to release the channel service lease.")}},"releaseLease"),initialLeaseReserved:channelPidfileReserved,onCommittedSelection:__name((_selection,groups)=>{channelWorkspaceGroups=groups;channelOwnerHints=new Map([...bootChannelOwnerHints,...groups.flatMap(group=>group.selection.mode==="names"?group.selection.names.map(name=>[name,group.workspaceCwd]):[])]);channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.()},"onCommittedSelection"),onStateChange:__name(()=>{if(runtimeStartupSettled)writeChannelWorkerPidfile()},"onStateChange")});return channelWorkerManager})();channelWorkerManagerStarting=starting;void starting.then(()=>{if(channelWorkerManagerStarting===starting){channelWorkerManagerStarting=void 0}},()=>{if(channelWorkerManagerStarting===starting){channelWorkerManagerStarting=void 0}});return starting},"ensureChannelWorkerManager");const completeRuntimeStartup=__name(async candidateApp=>{if(runtimeStartupSettled)return;runtimeApp=candidateApp;attachLiveDiscoveryControl(candidateApp);const acpHandle=candidateApp.locals?.["acpHandle"];attachAcpWsTransport(acpHandle);if(opts.channelSelection){closeServerAfterChannelWorkerStartupFailure=true;let manager;try{manager=await ensureChannelWorkerManager();await manager.startInitial(opts.channelSelection)}catch(error2){if(!channelSelectionFromSettings||runtimeStartupSettled){throw error2}closeServerAfterChannelWorkerStartupFailure=false;if(opts.channelSelection?.mode==="names"){const reported=channelStartupMessages(error2);const message=error2 instanceof Error?error2.message:String(error2);channelRestoreFailures.record(opts.channelSelection.names.flatMap(channel=>{const owners=bootChannelClaimants.get(channel)??[boundWorkspace];return owners.map(workspaceCwd=>({workspaceCwd,channel,message:reported.get(channel)??message}))}))}opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error2);try{if(manager){await manager.stopSelection()}else{removeCurrentServePidfile();if(channelPidfileReserved){throw new Error("Failed to release the channel service lease.")}}}catch(cleanupError){reportConfiguredChannelStartupFailure(cleanupError)}}if(runtimeStartupSettled)return}if(runtimeStartupSettled)return;markServeAppStartupReady();await publishLiveDiscovery(candidateApp);runtimeStartupSettled=true;clearRuntimeStartupTimer();markRuntimeReady()},"completeRuntimeStartup");const scheduleWorkspaceMcpDiscoveryAfterPreheat=__name(app2=>{if(runtimeStartupError!==void 0){daemonLog.info("workspace runtime ensure after preheat skipped: runtime startup failed");return}if(shuttingDown){daemonLog.info("workspace runtime ensure after preheat skipped: shutting down");return}const registry=app2.locals?.["workspaceRegistry"];const primaryEntry=registry?.primaryEntry;const runtime=primaryEntry?.state==="active"?primaryEntry.current?.runtime:void 0;if(!runtime){daemonLog.info("workspace runtime ensure after preheat skipped: no primary runtime");return}const coordinator=getWorkspaceRuntimeCoordinatorIfSupported?.(runtime);if(!coordinator){daemonLog.info("workspace runtime ensure after preheat skipped: workspace runtime lifecycle is not supported");return}void coordinator.ensure({keepAliveMs:ENSURE_KEEP_ALIVE_MS}).catch(err=>{if(shuttingDown||runtimeStartupError!==void 0){return}daemonLog.warn(`workspace runtime ensure after preheat failed: ${deepestErrorMessage(err)}`)})},"scheduleWorkspaceMcpDiscoveryAfterPreheat");const startBridgePreheat=__name((bridge,app2)=>{startup.preheat.status="running";const preheatStartedAt=performance2.now();bridge.preheat().then(()=>{startup.preheat.status="succeeded";startup.preheat.durationMs=Math.round(performance2.now()-preheatStartedAt);scheduleWorkspaceMcpDiscoveryAfterPreheat(app2)}).catch(err=>{const message=err instanceof Error?err.message:String(err);startup.preheat.status="failed";startup.preheat.durationMs=Math.round(performance2.now()-preheatStartedAt);startup.preheat.error=message;writeStderrLine(`qwen serve: ACP preheat failed, will retry on first session: ${message}`)})},"startBridgePreheat");const startRuntime=__name(()=>{if(runtimeStarting)return false;armRuntimeStartupTimer();clearRuntimeStartAfterHealthTimer();clearRuntimeStartFallbackTimer();runtimeStarting=buildRuntime().then(async runtime=>{if(runtimeStartupSettled){disposeRuntimeAppResources(runtime.app);await shutdownBridgeAfterFailedStartup(runtime.bridge);return}bridgeRef=runtime.bridge;runtimeAppForCleanup=runtime.app;if(shuttingDown){await failRuntimeStartup(new Error("Daemon runtime stopped before mounting."),runtime.bridge);return}if(shouldPreheat&&runtime.bridge){startBridgePreheat(runtime.bridge,runtime.app)}await completeRuntimeStartup(runtime.app)}).catch(err=>failRuntimeStartup(err));return true},"startRuntime");startRuntimeForRequest=startRuntime;const scheduleRuntimeStartFallback=__name(()=>{if(shuttingDown||runtimeStarting||runtimeStartFallbackTimer)return;daemonLog.info(`deferred runtime: scheduling fallback start in ${FAST_PATH_RUNTIME_START_FALLBACK_MS}ms`);runtimeStartFallbackTimer=setTimeout(()=>{runtimeStartFallbackTimer=void 0;if(shuttingDown)return;daemonLog.info("deferred runtime: fallback timer fired, starting");startRuntime()},FAST_PATH_RUNTIME_START_FALLBACK_MS);runtimeStartFallbackTimer.unref()},"scheduleRuntimeStartFallback");startRuntimeAfterHealth=__name(()=>{if(shuttingDown||runtimeStarting||runtimeStartAfterHealthTimer){return}clearRuntimeStartFallbackTimer();daemonLog.info(`deferred runtime: health served, scheduling start in ${FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS}ms`);runtimeStartAfterHealthTimer=setTimeout(()=>{runtimeStartAfterHealthTimer=void 0;if(shuttingDown)return;daemonLog.info("deferred runtime: health timer fired, starting");startRuntime()},FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS);runtimeStartAfterHealthTimer.unref()},"startRuntimeAfterHealth");const onSignal=__name(async signal=>{if(shuttingDown){daemonLog.warn(`received ${signal} during drain \u2014 forcing exit`);removeDiscoveryRecord();try{managedProcessRegistry?.killAllSync();channelWorkerManager?.killAllSync();for(const runtimeBridge of getRuntimeBridgesForCleanup()){runtimeBridge.killAllSync()}}catch(err){daemonLog.error("force-kill error",err instanceof Error?err:null)}await flushDaemonLogBounded(daemonLog,DAEMON_LOG_FORCED_FLUSH_BUDGET_MS);process.exit(1);return}if(!loggerPublished){loggerSignalOwned=true;loggerLifecycle.signalOwned()}daemonLog.warn(`received ${signal}, draining`);try{await handle.close();process.exit(runtimeStartupError===void 0?0:1)}catch(err){daemonLog.error("shutdown error",err instanceof Error?err:null);if(hasRetryableChannelWorkerShutdownError(err)){daemonLog.error("refusing to exit while a channel worker or service lease remains; signal again to retry after the child exits (another signal during that retry forces exit)");return}await flushDaemonLogBounded(daemonLog,DAEMON_LOG_FORCED_FLUSH_BUDGET_MS);process.exit(1)}},"onSignal");const onUncaughtExceptionMonitor=__name(()=>{if(process.listenerCount("uncaughtException")===0&&!channelWorkerManager?.state().enabled){removeCurrentServePidfile()}},"onUncaughtExceptionMonitor");const handle={server,url,bridge:handleBridge,webShellMounted,resolvedToken:token,runtimeReady,getPrimaryWorkspaceRuntime:__name(()=>{const registry=runtimeApp?.locals?.["workspaceRegistry"];const entry=registry?.primaryEntry;return entry?.state==="active"?entry.current?.runtime:void 0},"getPrimaryWorkspaceRuntime"),getLocalControl:__name(()=>(runtimeApp??runtimeAppForCleanup)?.locals?.["localControlService"],"getLocalControl"),close:__name(()=>{if(closePromise)return closePromise;closePromise=new Promise((res,rej)=>{shuttingDown=true;liveDiscoveryShuttingDown=true;cancelLiveDiscoveryRetry();channelControlDraining=true;const initiallyMountedApp=runtimeApp??runtimeAppForCleanup;const beginRuntimeCoordinatorDrains=__name(app2=>{const registry=app2?.locals?.["workspaceRegistry"];for(const workspaceRuntime of registry?.list()??[]){getWorkspaceRuntimeCoordinatorIfSupported?.(workspaceRuntime)?.beginDrain()}},"beginRuntimeCoordinatorDrains");beginRuntimeCoordinatorDrains(initiallyMountedApp);const initiallyMountedManagement=initiallyMountedApp?.locals?.["workspaceManagementHandle"];const initiallyMountedSessionMaintenance=initiallyMountedApp?.locals?.["sessionArchiveCoordinator"];const initiallyMountedConversationActivity=initiallyMountedApp?.locals?.["conversationRuntimeActivity"];const initiallyMountedCsiStop=initiallyMountedApp?.locals?.["stopHostedCsiSessions"];const initialManagementWait=initiallyMountedManagement?.sealAndWait?.();const initiallyMountedLive=initiallyMountedApp?.locals;const initialLiveWait=initiallyMountedLive?.sealAndWaitLiveCoordinator?.();const initialSessionMaintenanceWait=initiallyMountedSessionMaintenance?.sealMaintenanceAndWait?.();const initialConversationActivityWait=initiallyMountedConversationActivity?.sealAndWait?.();const initialCsiWait=initiallyMountedCsiStop?.();let processRegistryShutdown;const startProcessRegistryShutdown=__name(()=>{processRegistryShutdown??=managedProcessRegistry?.shutdown().then(()=>void 0,error2=>error2 instanceof Error?error2:new Error(String(error2)))},"startProcessRegistryShutdown");startProcessRegistryShutdown();clearRuntimeStartAfterHealthTimer();clearRuntimeStartFallbackTimer();cancelDeferredRuntimeStartup();drainPreTransportUpgrades?.();let settled=false;let bridgeShutdownError;let channelWorkerShutdownError;const finish=__name(err=>{if(settled)return;settled=true;const accessLogController=(runtimeApp??runtimeAppForCleanup)?.locals?.[ACCESS_LOG_CONTROLLER_LOCAL];accessLogController?.sealAndFlushSuppressed();const preserveSignalHandlers=channelWorkerShutdownError!==void 0&&channelWorkerManager?.state().enabled===true;if(!preserveSignalHandlers){process.removeListener("SIGINT",onSignal);process.removeListener("SIGTERM",onSignal);process.removeListener("SIGHUP",onSignal)}process.removeListener("uncaughtExceptionMonitor",onUncaughtExceptionMonitor);void(coreRuntimePromise?coreRuntimePromise.then(core=>core.shutdownTelemetry()):Promise.resolve()).catch(telemetryErr=>{writeStderrLine(`qwen serve: telemetry shutdown error: ${telemetryErr instanceof Error?telemetryErr.message:String(telemetryErr)}`)}).finally(async()=>{let finalErr=err??bridgeShutdownError??channelWorkerShutdownError;const retryableChannelClose=channelWorkerShutdownError!==void 0&&channelWorkerManager?.state().enabled===true;if(retryableChannelClose){const retryableError=channelWorkerShutdownError;await flushDaemonLogBounded(daemonLog,DAEMON_LOG_FORCED_FLUSH_BUDGET_MS);closePromise=void 0;shuttingDown=false;channelControlDraining=false;retryableChannelWorkerShutdownErrors.add(retryableError);rej(retryableError);return}try{await cleanupLiveDiscovery()}catch(cleanupError){const normalizedCleanupError=cleanupError instanceof Error?cleanupError:new Error(String(cleanupError));if(finalErr){writeDaemonLifecycleBestEffort(()=>{daemonLog.error("Live Host discovery cleanup failed during shutdown",normalizedCleanupError)})}finalErr??=normalizedCleanupError}if(loggerPublished||loggerSignalOwned){writeDaemonLifecycleBestEffort(()=>{if(finalErr){daemonLog.error("daemon shutdown incomplete",finalErr)}else{daemonLog.info("daemon stopped")}});clearLoaderKeyRejectionReporterIfCurrent(loaderRejectionReporter);await daemonLog.close()}restoreScrubbedLoaderEnv();if(finalErr)rej(finalErr);else res()})},"finish");void(coreRuntimePromise?coreRuntimePromise.then(core=>core.forceFlushMetrics()):Promise.resolve()).catch(flushErr=>{daemonLog.warn(`pre-shutdown metrics flush failed: ${flushErr instanceof Error?flushErr.message:String(flushErr)}`)});Promise.resolve().then(async()=>{await waitForRuntimeStartingForShutdown(runtimeStarting,daemonLog);const appForCleanup=runtimeApp??runtimeAppForCleanup;await appForCleanup?.locals?.["cleanupDaemonUpdate"]?.();const workspaceManagementHandle=appForCleanup?.locals?.["workspaceManagementHandle"];const sessionMaintenance=appForCleanup?.locals?.["sessionArchiveCoordinator"];const conversationActivity=appForCleanup?.locals?.["conversationRuntimeActivity"];await initialManagementWait;if(workspaceManagementHandle!==initiallyMountedManagement){await workspaceManagementHandle?.sealAndWait?.()}const liveLifecycleHandle=appForCleanup?.locals;await initialLiveWait;if(liveLifecycleHandle!==initiallyMountedLive){await liveLifecycleHandle?.sealAndWaitLiveCoordinator?.()}await initialSessionMaintenanceWait;if(sessionMaintenance!==initiallyMountedSessionMaintenance){await sessionMaintenance?.sealMaintenanceAndWait?.()}await initialConversationActivityWait;if(conversationActivity!==initiallyMountedConversationActivity){await conversationActivity?.sealAndWait?.()}const csiStop=appForCleanup?.locals?.["stopHostedCsiSessions"];await initialCsiWait;if(csiStop!==initiallyMountedCsiStop)await csiStop?.();stopTrustPolicyMonitor(appForCleanup);const waitForTrustPolicyIdle=appForCleanup?.locals?.["waitForTrustPolicyIdle"];await waitForTrustPolicyIdle?.().catch(err=>{daemonLog.error("workspace trust reconciliation shutdown wait failed",err instanceof Error?err:null)});beginRuntimeCoordinatorDrains(appForCleanup);startProcessRegistryShutdown();disposeRuntimeAppResources(appForCleanup);disposeDaemonEventLoopMonitor();if(channelWorkerManager){await channelWorkerManager.shutdown().catch(err=>{daemonLog.error("channel worker stop error",err instanceof Error?err:null);channelWorkerShutdownError=err instanceof Error?err:new Error(String(err))})}else{removeCurrentServePidfile()}const runtimeRemoval=appForCleanup?.locals?.["workspaceRuntimeRemoval"];const workspaceRegistry=appForCleanup?.locals?.["workspaceRegistry"];const managedRuntimeBridges=new Set;if(runtimeRemoval&&workspaceRegistry){const managedRuntimes=workspaceRegistry.listManaged();for(const workspaceRuntime of managedRuntimes){managedRuntimeBridges.add(workspaceRuntime.bridge)}await Promise.all(managedRuntimes.map(workspaceRuntime=>runtimeRemoval.disposeRuntime(workspaceRuntime,"daemon_shutdown").catch(err=>{daemonLog.error("workspace runtime shutdown error",err instanceof Error?err:null);bridgeShutdownError=err instanceof Error?err:new Error(String(err));try{workspaceRuntime.bridge.killAllSync()}catch{}})))}for(const bridgeForShutdown of getRuntimeBridgesForCleanup()){if(managedRuntimeBridges.has(bridgeForShutdown))continue;if(shutdownBridges.has(bridgeForShutdown))continue;shutdownBridges.add(bridgeForShutdown);await bridgeForShutdown.shutdown().catch(err=>{shutdownBridges.delete(bridgeForShutdown);daemonLog.error("bridge shutdown error",err instanceof Error?err:null);bridgeShutdownError=err instanceof Error?err:new Error(String(err))})}const processRegistryError=await processRegistryShutdown;if(processRegistryError){daemonLog.error("ACP process registry shutdown error",processRegistryError);bridgeShutdownError??=processRegistryError}}).then(()=>finish(),error2=>finish(error2 instanceof Error?error2:new Error(String(error2))))});return closePromise},"close")};closeHost=handle.close;handle.close=async()=>{await serveAppLifecycle.close();removeDiscoveryRecord()};try{const resolved=resolveChannelWorkspaceGroupsAtListen();channelWorkspaceGroups=resolved?.groups;if(resolved){for(const skip of resolved.skipped){const detail=sanitizeLogText(redactLogCredentials(skip.message),512);writeStderrLine(`qwen serve: channel "${skip.channel}" was not restored: ${detail}`);daemonLog.warn(`channel was not restored: ${detail}`,{code:skip.code,channel:skip.channel});channelRestoreFailures.record((bootChannelClaimants.get(skip.channel)??[]).map(workspaceCwd=>({workspaceCwd,channel:skip.channel,message:skip.message})))}if(resolved.skipped.length>0){const hosted=new Set(resolved.groups.flatMap(group=>group.selection.mode==="names"?group.selection.names:[]));const remaining=opts.channelSelection?.mode==="names"?opts.channelSelection.names.filter(name=>hosted.has(name)):[];opts.channelSelection=remaining.length>0?{mode:"names",names:remaining}:void 0;if(!opts.channelSelection){channelWorkspaceGroups=void 0;removeCurrentServePidfile();reportConfiguredChannelStartupFailure(new Error("No configured channel could be hosted."))}}}}catch(err){removeCurrentServePidfile();const error2=err instanceof Error?err:new Error(String(err));if(channelSelectionFromSettings){opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error2)}else{markServeAppStartupFailed(error2);void serveAppLifecycle.close().then(()=>reject(error2),closeError=>reject(closeError instanceof Error?new AggregateError([error2,closeError],error2.message):error2));return}}if(channelWorkspaceGroups){for(const group of channelWorkspaceGroups){daemonLog.info("channel worker group assigned",{workspace:group.workspaceCwd,channels:group.selection.mode==="all"?["all"]:group.selection.names})}if(opts.channelSelection?.mode==="all"){writeStderrLine(channelSelectionFromSettings?'qwen serve: workspace serve.channels selection "all" is primary-workspace only; non-primary workspace channels are not hosted.':"qwen serve: --channel all is primary-workspace only; non-primary workspace channels are not hosted.")}}writeStdoutLine(`qwen serve listening on ${url} (mode=${opts.mode}, workspace=${boundWorkspace})`);try{const discoveryLogPath=daemonLog.getLogPath();discoveryRecordPath=writeDaemonDiscovery({v:DAEMON_DISCOVERY_VERSION,pid:process.pid,port:actualPort,hostname:opts.hostname,url:daemonDiscoveryUrl(url),workspaces:workspaceInputs.map(workspace=>workspace.cwd),primaryWorkspace:boundWorkspace,startedAt:new Date().toISOString(),auth:token?"bearer":"none",...generatedToken?{tokenGenerated:true}:{},...discoveryLogPath?{logPath:discoveryLogPath}:{},pidNamespace:currentPidNamespace()});process.once("exit",removeDiscoveryRecord)}catch(err){writeStderrLine(`qwen serve: could not write the daemon discovery record: ${err instanceof Error?err.message:String(err)}`)}const boundAddress=typeof addr==="object"&&addr?addr.address:opts.hostname;const settingTokenQr=bootSettings?.serve?.tokenQr;if(opts.tokenQr===void 0&&settingTokenQr!==void 0&&typeof settingTokenQr!=="boolean"){writeStderrLine(`qwen serve: serve.tokenQr must be a boolean; ignoring a ${typeof settingTokenQr} value.`)}for(const ignoredKey of bootSettings?.ignoredWorkspaceKeys??[]){writeStderrLine(`qwen serve: ${ignoredKey} in workspace settings (${path.join(boundWorkspace,".qwen","settings.json")}) is ignored; it is honored from user, system, and system-defaults scopes only.`)}const tokenQrMode=opts.tokenQr===false?"veto":opts.tokenQr===true||settingTokenQr===true?"force":"policy";const tokenQrNoEffect=tokenQrNoEffectReason({requested:tokenQrMode==="force",webShellMounted,boundAddress,generated:generatedToken});if(tokenQrNoEffect)writeStderrLine(tokenQrNoEffect);if(token){void printRemoteQuickstart({bind:opts.hostname,boundAddress,port:actualPort,tls:Boolean(tlsOptions),token,generated:generatedToken,web:webShellMounted,tokenQrMode})}writeStderrLine(`qwen serve: bound to workspace ${JSON.stringify(boundWorkspace)}`);writeStderrLine(`qwen serve: startup timing: processToListenMs=${startup.processToListenMs} runQwenServeToListenMs=${startup.runQwenServeToListenMs}`);if(!token){writeStderrLine(`qwen serve: trusted loopback mode; local callers have full API access without bearer authentication, including code execution as the daemon user. Use --require-auth with ${QWEN_SERVER_TOKEN_ENV} on shared or untrusted hosts.`);if(opts.clientMcpOverWs===true){writeStderrLine(`qwen serve: client-hosted MCP tools are accepted over the WebSocket without auth. Set ${QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV}=0 to disable.`)}}else if(opts.requireAuth){writeStderrLine("qwen serve: --require-auth enabled (bearer token mandatory on every route, including loopback /health).")}writeStderrLine(`qwen serve: manage this daemon with \`qwen daemon status\`, \`qwen daemon logs --port ${actualPort} --follow\`, or \`qwen daemon stop --port ${actualPort}\`.`);process.on("SIGINT",onSignal);process.on("SIGTERM",onSignal);process.on("SIGHUP",onSignal);process.on("uncaughtExceptionMonitor",onUncaughtExceptionMonitor);server.on("error",err=>{daemonLog.error("server error",err instanceof Error?err:null)});const preparedRuntimeApp=runtimeApp??runtimeAppForCleanup;if(preparedRuntimeApp&&bridgeRef&&deps.bridge){runtimeApp??=preparedRuntimeApp;attachLiveDiscoveryControl(preparedRuntimeApp);if(shouldPreheat){startBridgePreheat(bridgeRef,preparedRuntimeApp)}if(opts.channelSelection&&!runtimeStartupSettled){armRuntimeStartupTimer();runtimeStarting=completeRuntimeStartup(preparedRuntimeApp).catch(err=>failRuntimeStartup(err,bridgeRef))}else{const acpHandle=preparedRuntimeApp.locals?.["acpHandle"];attachAcpWsTransport(acpHandle);markServeAppStartupReady();void publishLiveDiscovery(preparedRuntimeApp);if(!runtimeStartupSettled){runtimeStartupSettled=true;clearRuntimeStartupTimer();markRuntimeReady()}}}else if(deferRuntimeUntilFirstHealth){scheduleRuntimeStartFallback()}else{startRuntime()}if(deps.resolveOnListen){loggerPublished=true;loggerLifecycle.published();void(liveDiscoveryPublish??Promise.resolve()).then(()=>resolve3(handle))}else{void runtimeReady.then(async()=>{await liveDiscoveryPublish;loggerPublished=true;loggerLifecycle.published();resolve3(handle)},err=>{void handle.close().then(()=>{reject(err instanceof Error?err:new Error(String(err)))},closeErr=>{writeDaemonLifecycleBestEffort(()=>daemonLog.error("shutdown after runtime startup error failed",closeErr instanceof Error?closeErr:null));if(hasRetryableChannelWorkerShutdownError(closeErr)){writeDaemonLifecycleBestEffort(()=>daemonLog.error("runtime startup failed, but qwen serve remains alive to retain the channel service lease until worker exit is confirmed"));return}reject(err instanceof Error?err:new Error(String(err)))})})}},"onListening");let drainPreTransportUpgrades=void 0;let server;if(tlsOptions){try{server=https.createServer(tlsOptions,app)}catch(err){reject(new Error(`--tls-cert "${opts.tlsCert}" and --tls-key "${opts.tlsKey}" could not be loaded (do they match?): ${err instanceof Error?err.message:String(err)}`));return}}else{server=deps.httpServerFactory?.(app)??createServer(app)}serveAppLifecycle.bindServer(server,{startupReady:serveAppStartupReady,drainHost:__name(()=>{if(closeHost)return closeHost();if(!server.listening)return Promise.resolve();return new Promise((resolve4,rejectClose)=>{server.close(error=>{if(error)rejectClose(error);else resolve4()})})},"drainHost")});const preTransportUpgrades=[];let acpWsTransportAttached=false;let preTransportUpgradeGateClosed=false;const dropPreTransportUpgrade=__name(socket=>{const index=preTransportUpgrades.findIndex(queued=>queued.socket===socket);if(index!==-1)preTransportUpgrades.splice(index,1)},"dropPreTransportUpgrade");const answerPreTransportUpgrade503=__name((socket,retryable)=>{socket.once("error",()=>{});socket.write(retryable?"HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\n\r\n":"HTTP/1.1 503 Service Unavailable\r\n\r\n");socket.destroy()},"answerPreTransportUpgrade503");const releasePreTransportUpgrades=__name(()=>{const queued=preTransportUpgrades.splice(0);let rejected=0;for(const{req,socket,head,detach}of queued){detach();if(socket.destroyed)continue;if(acpWsTransportAttached){server.emit("upgrade",req,socket,head)}else{rejected+=1;answerPreTransportUpgrade503(socket,false)}}if(rejected>0){daemonLog.warn(`deferred runtime: answered ${rejected} parked upgrade(s) with 503 (no ACP transport attached)`)}},"releasePreTransportUpgrades");const attachAcpWsTransport=__name(acpHandle=>{if(!acpHandle||acpWsTransportAttached)return;acpHandle.attachServer(server);acpWsTransportAttached=true},"attachAcpWsTransport");const preTransportUpgradeGuard=__name((req,socket,head)=>{if(acpWsTransportAttached)return;if(preTransportUpgradeGateClosed){answerPreTransportUpgrade503(socket,false);return}if(preTransportUpgrades.length>=PRE_TRANSPORT_UPGRADE_HOLD_MAX){answerPreTransportUpgrade503(socket,true);return}const dropAndDestroy=__name(()=>{dropPreTransportUpgrade(socket);socket.destroy()},"dropAndDestroy");const drop=__name(()=>dropPreTransportUpgrade(socket),"drop");const entry={req,socket,head,detach:__name(()=>{},"detach")};const accumulate=__name(chunk=>{if(entry.head.byteLength+chunk.byteLength<=PRE_TRANSPORT_UPGRADE_HEAD_MAX){entry.head=Buffer.concat([entry.head,chunk])}else{dropAndDestroy()}},"accumulate");const detach=__name(()=>{socket.removeListener("data",accumulate);socket.removeListener("error",dropAndDestroy);socket.removeListener("end",dropAndDestroy);socket.removeListener("close",drop)},"detach");entry.detach=detach;socket.on("data",accumulate);socket.once("error",dropAndDestroy);socket.once("end",dropAndDestroy);socket.once("close",drop);preTransportUpgrades.push(entry);daemonLog.info(`deferred runtime: parked pre-transport upgrade ${req.url?.split("?",1)[0]??"/"} from ${socket.remoteAddress??"unknown"} (${preTransportUpgrades.length} held)`);if(!runtimeStartupSettled)startRuntimeForRequest?.()},"preTransportUpgradeGuard");server.on("upgrade",preTransportUpgradeGuard);drainPreTransportUpgrades=__name(()=>{preTransportUpgradeGateClosed=true;const queued=preTransportUpgrades.splice(0);for(const{socket,detach}of queued){detach();if(socket.destroyed)continue;answerPreTransportUpgrade503(socket,false)}},"drainPreTransportUpgrades");void runtimeReady.then(()=>{const acpHandle=(runtimeApp??runtimeAppForCleanup)?.locals?.["acpHandle"];if(!acpHandle){server.removeListener("upgrade",preTransportUpgradeGuard);daemonLog.info("deferred runtime: settled without an ACP transport, restoring Express upgrade fall-through")}preTransportUpgradeGateClosed=true;releasePreTransportUpgrades()},()=>{if(acpWsTransportAttached&&server.listenerCount("upgrade")<2){acpWsTransportAttached=false}if(opts.profile==="hosted-harness"||!resolveAcpHttpEnabled(daemonRuntimeBaseEnv)){server.removeListener("upgrade",preTransportUpgradeGuard);daemonLog.info("deferred runtime: startup failed without an ACP transport, restoring Express upgrade fall-through")}preTransportUpgradeGateClosed=true;releasePreTransportUpgrades()});const tryListen=__name((attemptPort,attempt)=>{const handleListening=__name(()=>{server.removeListener("error",handleError);const address=server.address();if(trustedLoopbackMode&&(typeof address!=="object"||address===null||!isLoopbackAddress(address.address))){const resolvedAddress=typeof address==="object"&&address!==null?address.address:String(address);const error=new Error(`Refusing trusted-loopback mode because ${opts.hostname} bound to non-loopback address ${resolvedAddress}. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or bind to an explicit loopback address.`);removeCurrentServePidfile();markServeAppStartupFailed(error);void serveAppLifecycle.close().then(()=>reject(error),closeError=>reject(closeError instanceof Error?new AggregateError([error,closeError],error.message):error));return}onListening()},"handleListening");const handleError=__name(err=>{server.removeListener("listening",handleListening);const nextPort=attemptPort+1;if(err.code==="EADDRINUSE"&&opts.port!==0&&nextPort<=65535&&attempt<MAX_PORT_ATTEMPTS-1){writeStderrLine(`qwen serve: port ${attemptPort} is in use, trying ${nextPort}...`);tryListen(nextPort,attempt+1);return}if(err.code==="EADDRINUSE"&&attempt>0){writeStderrLine(`qwen serve: all ports ${opts.port}\u2013${attemptPort} are in use`)}removeCurrentServePidfile();markServeAppStartupFailed(err);void serveAppLifecycle.close().then(()=>reject(err),closeError=>reject(closeError instanceof Error?new AggregateError([err,closeError],err.message):err))},"handleError");try{server.once("listening",handleListening);server.once("error",handleError);server.listen(attemptPort,listenHostname)}catch(err){removeCurrentServePidfile();server.removeListener("listening",handleListening);server.removeListener("error",handleError);const error=err instanceof Error?err:new Error(String(err));markServeAppStartupFailed(error);void serveAppLifecycle.close().then(()=>reject(error),closeError=>reject(closeError instanceof Error?new AggregateError([error,closeError],error.message):error));return}},"tryListen");tryListen(opts.port,0)})}__name(runQwenServeImpl,"runQwenServeImpl");export{InvalidPolicyConfigError,assertChannelWorkerDaemonUrlIsLocal,createBoundChannelDeliveryHandler,createDisabledChannelWorkerSupervisor,createLazyBridgeProxy,describeWorkerTlsTrustGaps,extractContextFilename,formatChannelWorkerDaemonUrl,resolveRuntimeStartupTimeoutMs,runQwenServe,subSessionConcurrencyCapsFromSettings,validateAndCanonicalizeWorkspaceInput,validatePolicyConfig,verifyWorkerTlsTrust,waitForRuntimeStartingForShutdown};
47
+ `;async function verifyWorkerTlsTrust(opts){const timeoutMs=opts.timeoutMs??5e3;return new Promise(resolve3=>{execFile2(process.execPath,["--input-type=module","--eval",WORKER_TLS_TRUST_PROBE,opts.daemonUrl,String(timeoutMs)],{env:{...process.env,NODE_EXTRA_CA_CERTS:opts.caCertPath},encoding:"utf8",timeout:timeoutMs+1e3},(error,stdout)=>{try{const result=JSON.parse(stdout);resolve3(result.ok?void 0:result)}catch{const failure=error;resolve3({code:failure?.code!=null?String(failure.code):"WORKER_TLS_VERIFY_FAILED",message:failure?.message??"TLS verification probe failed."})}})})}__name(verifyWorkerTlsTrust,"verifyWorkerTlsTrust");function describeWorkerTlsTrustGaps(opts){const chain=parseCertChain(opts.cert);const x509=bootParsedLeaf(opts.cert);if(!x509){return[]}const gaps=[];const operatorChain=opts.operatorCaCert?loadableCertificates(opts.operatorCaCert.toString("utf8"),opts.operatorCaCertSourcePath):void 0;const servingBlocks=loadableCertificates(opts.cert.toString("utf8"),opts.certSourcePath);const operatorDiscarded=!servingBlocks&&operatorChain!==void 0;const servingChain=servingBlocks===void 0?[x509,...chain.filter(member=>member.fingerprint256!==x509.fingerprint256)]:servingBlocks.some(block=>block.fingerprint256===x509.fingerprint256)?servingBlocks:[x509,...servingBlocks];const leafHeldByWorkers=servingBlocks!==void 0&&servingBlocks.some(block=>block.fingerprint256===x509.fingerprint256);const workerTrustStore=operatorChain&&servingBlocks?[...operatorChain,...servingChain]:servingChain;const now=Date.now();const anchorPath=walkWorkerAnchorPath(x509,workerTrustStore,now,servingBlocks===void 0||leafHeldByWorkers);if(opts.operatorCaCertReadError!==void 0){const servingFallbackAnchors=anchorPath.anchored&&servingBlocks!==void 0;gaps.push(`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" could not be read by the daemon (${opts.operatorCaCertReadError}), so channel workers receive no CA from it \u2014 a root-owned or mode-600 file is the usual cause, and its contents are not the problem. `+(servingFallbackAnchors?`--tls-cert "${opts.certPath}" carries an anchor of its own, and that file is what the workers fall back to, so their trust does not rest on this one today \u2014 whatever it was meant to add reaches nobody. Fix that file's permissions or path and restart.`:servingBlocks===void 0?`--tls-cert "${opts.certPath}" itself holds no block the workers' loader can read, so their fallback bundle is that file alone and it anchors nothing \u2014 fixing this CA file's permissions changes nothing; re-export the serving file as the gap below describes and restart.`:`Every worker handshake to the daemon will fail UNABLE_TO_VERIFY_LEAF_SIGNATURE unless the issuing CA is already in the workers' default trust store. Fix that file's permissions or path and restart.`))}else if(opts.operatorCaCert&&!operatorChain){gaps.push(`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" holds no PEM certificate block Node's loader can read \u2014 every -----BEGIN/END CERTIFICATE----- marker must sit alone on its own line and every block must decode, and a DER file is never read at all. Channel workers therefore receive the daemon cert alone and anchor nothing through this file. Re-export it as PEM and restart.`)}if(!servingBlocks){gaps.push(`--tls-cert "${opts.certPath}" holds no PEM certificate block Node's loader can read, so `+(operatorDiscarded?`the channel workers' bundle cannot be merged: they receive that file alone and NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" is discarded. `:`the channel workers receive a bundle their loader takes nothing from. `)+`Every worker handshake to the daemon will fail UNABLE_TO_VERIFY_LEAF_SIGNATURE. Re-export --tls-cert as PEM with every -----BEGIN/END CERTIFICATE----- marker alone on its own line and restart.`)}const leafPurposeDefect=tlsServerPurposeDefect(x509);if(leafPurposeDefect){gaps.push(`--tls-cert "${opts.certPath}" cannot be used as a TLS server certificate because ${leafPurposeDefect}. Every worker handshake to the daemon will fail INVALID_PURPOSE. Reissue the leaf with a TLS-server keyUsage and serverAuth extendedKeyUsage, then restart.`)}if(anchorPath.nonCaTerminator){const terminatorSubject=anchorPath.nonCaTerminator.subject.replace(/\r?\n/g,", ");gaps.push(issuerRefusedForKeyUsage(anchorPath.nonCaTerminator)?`--tls-cert "${opts.certPath}" chains up to "${terminatorSubject}", which is self-signed but whose keyUsage does not include keyCertSign, so OpenSSL refuses to let it issue the certificates below it however its basicConstraints reads. Every worker handshake to the daemon will fail "key usage does not include certificate signing" even though the chain terminates on a self-signed certificate. Reissue that certificate with keyCertSign in its keyUsage and restart \u2014 CA:TRUE alone does not fix it, and no NODE_EXTRA_CA_CERTS can anchor a self-signed certificate through anything but itself.`:`--tls-cert "${opts.certPath}" chains up to "${terminatorSubject}", which is self-signed but is not a CA \u2014 it carries basicConstraints CA:FALSE or, as an X.509 v3 certificate, no basicConstraints at all, and OpenSSL refuses to let it issue the certificates below it, so every worker handshake to the daemon will fail INVALID_PURPOSE ("unsuitable certificate purpose"). Reissue that certificate with CA:TRUE, or point NODE_EXTRA_CA_CERTS at a real CA that anchors the chain, and restart.`)}else if(anchorPath.incapableIssuer){const keyUsageIsTheCause=issuerRefusedForKeyUsage(anchorPath.incapableIssuer);gaps.push(`--tls-cert "${opts.certPath}" chains through "${anchorPath.incapableIssuer.subject.replace(/\r?\n/g,", ")}", `+(keyUsageIsTheCause?`whose keyUsage does not include keyCertSign, so OpenSSL refuses to let it issue the certificate below it however its basicConstraints reads. Every worker handshake to the daemon will fail with an invalid-CA error even though the chain looks complete, and the issuing CA IS in their bundle. Reissue that intermediate with keyCertSign in its keyUsage and restart \u2014 pointing NODE_EXTRA_CA_CERTS elsewhere cannot fix it.`:`which is not a CA \u2014 it carries basicConstraints CA:FALSE or, as an X.509 v3 certificate, no basicConstraints at all, and OpenSSL refuses to let it issue the certificate below it. Every worker handshake to the daemon will fail INVALID_PURPOSE or INVALID_CA even though the chain looks complete. Reissue that intermediate with CA:TRUE, or point NODE_EXTRA_CA_CERTS at a chain whose intermediates are real CAs, and restart.`))}else if(anchorPath.pathLengthViolation){const{cert,constraint}=anchorPath.pathLengthViolation;gaps.push(`--tls-cert "${opts.certPath}" chains through "${cert.subject.replace(/\r?\n/g,", ")}", whose basicConstraints carries pathlen:${constraint} \u2014 it permits at most ${constraint} intermediate CA${constraint===1?"":"s"} below it, and this chain has more. Every worker handshake to the daemon will fail PATH_LENGTH_EXCEEDED even though every certificate in the bundle verifies. Reissue that CA with a pathlen that covers the chain, or shorten the chain, and restart.`)}else if(anchorPath.unheldSelfSignedLeaf){gaps.push(`--tls-cert "${opts.certPath}" serves a self-signed certificate whose own PEM block is not one Node's NODE_EXTRA_CA_CERTS loader takes (a -----BEGIN TRUSTED CERTIFICATE----- block, as \`openssl x509 -trustout\` writes, is the usual cause), so the channel workers never receive that certificate \u2014 and a self-signed certificate verifies only when it is itself in the trust store. The daemon serves it fine, but every worker handshake will fail DEPTH_ZERO_SELF_SIGNED_CERT with nothing logged. Re-export --tls-cert with a plain -----BEGIN CERTIFICATE----- block and restart.`)}else if(!anchorPath.anchored){gaps.push(`--tls-cert "${opts.certPath}" is issued by another CA (${x509.issuer.replace(/\r?\n/g,", ")}), not self-signed, and ${!opts.operatorCaCertPath?`no NODE_EXTRA_CA_CERTS is set`:opts.operatorCaCertReadError!==void 0?`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" could not be read, so whatever it carries reached nobody`:operatorDiscarded?`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" was discarded together with the unloadable serving file above, whatever it carries`:`NODE_EXTRA_CA_CERTS "${opts.operatorCaCertPath}" does not carry a certificate that anchors it`}, so nothing in the channel workers' bundle anchors their trust \u2014 every worker handshake to the daemon will fail UNABLE_TO_VERIFY_LEAF_SIGNATURE unless the issuing CA is already in the workers' default trust store. `+(operatorDiscarded?`Re-export --tls-cert as described above and restart; NODE_EXTRA_CA_CERTS is not the file to change.`:opts.operatorCaCertReadError!==void 0?`Make NODE_EXTRA_CA_CERTS readable by the daemon as described above and restart.`:`Point NODE_EXTRA_CA_CERTS at the issuing CA (for mkcert: "$(mkcert -CAROOT)/rootCA.pem") and restart.`))}for(const member of anchorPath.path){if(member.fingerprint256===x509.fingerprint256)continue;const subject=member.subject.replace(/\r?\n/g,", ");if(member.keyUsage&&!member.keyUsage.includes(TLS_SERVER_AUTH_OID)){gaps.push(`--tls-cert "${opts.certPath}" chains through "${subject}", whose extendedKeyUsage does not include serverAuth \u2014 every worker handshake to the daemon will fail INVALID_PURPOSE. Reissue that chain member with serverAuth in its extendedKeyUsage and restart.`);continue}if(!certValidAt(member,now)){if(new Date(member.validTo).getTime()<now){gaps.push(`--tls-cert "${opts.certPath}" chains through "${subject}", which expired on ${member.validTo} \u2014 every worker handshake to the daemon will fail CERT_HAS_EXPIRED. Renew that chain member and restart.`)}else{gaps.push(`--tls-cert "${opts.certPath}" chains through "${subject}", which is not yet valid (validFrom: ${member.validFrom}) \u2014 every worker handshake to the daemon will fail CERT_NOT_YET_VALID. Check that chain member's notBefore date or the system clock.`)}}}const host=workerDialHost(opts.daemonUrl);if(host&&!certCoversHost(x509,host)){gaps.push(`--tls-cert "${opts.certPath}" has no subjectAltName covering "${host}", the host channel workers dial \u2014 every worker handshake will fail ERR_TLS_CERT_ALTNAME_INVALID. Reissue the certificate with that host in its SANs and restart.`)}return gaps}__name(describeWorkerTlsTrustGaps,"describeWorkerTlsTrustGaps");var BASIC_CONSTRAINTS_OID=Buffer.from([85,29,19]);var KEY_USAGE_OID=Buffer.from([85,29,15]);var KEY_CERT_SIGN_MASK=4;var TLS_SERVER_KEY_USAGE_MASK=168;var TLS_SERVER_AUTH_OID="1.3.6.1.5.5.7.3.1";var VERSION_TAG=160;var EXTENSIONS_TAG=163;var SEQUENCE_TAG=48;var BOOLEAN_TAG=1;var INTEGER_TAG=2;function derElementAt(der,at){const tag=der[at];const header=der[at+1];if(tag===void 0||header===void 0)return void 0;let start=at+2;let length=header&127;if((header&128)!==0){if(length===0||length>4)return void 0;let value=0;for(let index=0;index<length;index+=1){const byte=der[start+index];if(byte===void 0)return void 0;value=value*256+byte}start+=length;length=value}const end=start+length;return end<=der.length?{tag,start,end}:void 0}__name(derElementAt,"derElementAt");function tbsCertificateOf(cert){const certificate=derElementAt(cert.raw,0);if(certificate?.tag!==SEQUENCE_TAG)return void 0;const tbs=derElementAt(cert.raw,certificate.start);return tbs?.tag===SEQUENCE_TAG?tbs:void 0}__name(tbsCertificateOf,"tbsCertificateOf");function certificateExtension(cert,oid){const der=cert.raw;const tbs=tbsCertificateOf(cert);if(!tbs)return void 0;let at=tbs.start;while(at<tbs.end){const member=derElementAt(der,at);if(!member)return void 0;if(member.tag!==EXTENSIONS_TAG){at=member.end;continue}const list=derElementAt(der,member.start);if(list?.tag!==SEQUENCE_TAG)return void 0;let entry=list.start;while(entry<list.end){const extension=derElementAt(der,entry);if(extension?.tag!==SEQUENCE_TAG)return void 0;const id=derElementAt(der,extension.start);if(!id)return void 0;let valueAt=id.end;const critical=derElementAt(der,valueAt);if(critical?.tag===BOOLEAN_TAG)valueAt=critical.end;const value=derElementAt(der,valueAt);if(!value)return void 0;if(der.subarray(id.start,id.end).equals(oid)){return der.subarray(value.start,value.end)}entry=extension.end}return void 0}return void 0}__name(certificateExtension,"certificateExtension");function keyUsageAllowsCertSign(der){const bits=derElementAt(der,0);if(!bits)return false;const first=der[bits.start+1];return first!==void 0&&(first&KEY_CERT_SIGN_MASK)!==0}__name(keyUsageAllowsCertSign,"keyUsageAllowsCertSign");function tlsServerPurposeDefect(cert){const keyUsage=certificateExtension(cert,KEY_USAGE_OID);if(keyUsage!==void 0){const bits=derElementAt(keyUsage,0);const first=bits?keyUsage[bits.start+1]:void 0;if(first===void 0||(first&TLS_SERVER_KEY_USAGE_MASK)===0){return"its keyUsage permits none of digitalSignature, keyEncipherment, or keyAgreement"}}if(cert.keyUsage&&!cert.keyUsage.includes(TLS_SERVER_AUTH_OID)){return"its extendedKeyUsage does not include serverAuth"}return void 0}__name(tlsServerPurposeDefect,"tlsServerPurposeDefect");function isV1Certificate(cert){const tbs=tbsCertificateOf(cert);return tbs!==void 0&&cert.raw[tbs.start]!==VERSION_TAG}__name(isV1Certificate,"isV1Certificate");function cannotIssueCertificates(cert){const keyUsage=certificateExtension(cert,KEY_USAGE_OID);if(keyUsage!==void 0&&!keyUsageAllowsCertSign(keyUsage))return true;if(certificateExtension(cert,BASIC_CONSTRAINTS_OID)!==void 0){return!cert.ca}return!isV1Certificate(cert)&&keyUsage===void 0}__name(cannotIssueCertificates,"cannotIssueCertificates");function certValidAt(cert,now){return new Date(cert.validFrom).getTime()<=now&&new Date(cert.validTo).getTime()>=now}__name(certValidAt,"certValidAt");function isSelfSignedCert(x509){if(x509.subject!==x509.issuer)return false;try{return x509.verify(x509.publicKey)}catch{return true}}__name(isSelfSignedCert,"isSelfSignedCert");var PEM_CERTIFICATE_BLOCK=/-----BEGIN CERTIFICATE-----[^-]*-----END CERTIFICATE-----/g;function parseCertChain(cert){const blocks=cert.toString("utf8").match(PEM_CERTIFICATE_BLOCK);if(!blocks){try{return[new X509Certificate(cert)]}catch{return[]}}const chain=[];for(const block of blocks){try{chain.push(new X509Certificate(block))}catch{}}return chain}__name(parseCertChain,"parseCertChain");function bootParsedLeaf(cert){try{return new X509Certificate(cert)}catch{return void 0}}__name(bootParsedLeaf,"bootParsedLeaf");function certIssuedBy(cert,issuer){try{return cert.issuer===issuer.subject&&cert.verify(issuer.publicKey)}catch{return false}}__name(certIssuedBy,"certIssuedBy");function issuerRefusedForKeyUsage(cert){const keyUsage=certificateExtension(cert,KEY_USAGE_OID);return keyUsage!==void 0&&!keyUsageAllowsCertSign(keyUsage)}__name(issuerRefusedForKeyUsage,"issuerRefusedForKeyUsage");function pathLengthConstraint(cert){const value=certificateExtension(cert,BASIC_CONSTRAINTS_OID);if(!value)return void 0;const sequence=derElementAt(value,0);if(sequence?.tag!==SEQUENCE_TAG)return void 0;let at=sequence.start;const first=derElementAt(value,at);if(!first)return void 0;if(first.tag===BOOLEAN_TAG)at=first.end;const integer=derElementAt(value,at);if(integer?.tag!==INTEGER_TAG)return void 0;let length=0;for(let index=integer.start;index<integer.end;index+=1){const byte=value[index];if(byte===void 0)return void 0;length=length*256+byte}return length}__name(pathLengthConstraint,"pathLengthConstraint");function walkWorkerAnchorPath(leaf,chain,now,leafHeldByWorkers=true){let next=leaf;const walked=new Set;const path2=[];let pathLengthViolation;while(next){const current=next;path2.push(current);if(path2.length>1&&pathLengthViolation===void 0){const constraint=pathLengthConstraint(current);const intermediatesBelow=path2.length-2;if(constraint!==void 0&&intermediatesBelow>constraint){pathLengthViolation={cert:current,constraint}}}if(isSelfSignedCert(current)){if(path2.length>1&&cannotIssueCertificates(current)){return{anchored:false,path:path2,nonCaTerminator:current}}if(path2.length===1&&!leafHeldByWorkers){return{anchored:false,path:path2,unheldSelfSignedLeaf:current}}return pathLengthViolation?{anchored:false,path:path2,pathLengthViolation}:{anchored:true,path:path2}}walked.add(current.fingerprint256);const issuers=chain.filter(candidate=>!walked.has(candidate.fingerprint256)&&certIssuedBy(current,candidate));const issuer=issuers.find(candidate=>certValidAt(candidate,now))??issuers[0];if(issuer&&!isSelfSignedCert(issuer)&&!issuer.ca){return{anchored:false,path:path2,incapableIssuer:issuer}}next=issuer}return pathLengthViolation?{anchored:false,path:path2,pathLengthViolation}:{anchored:false,path:path2}}__name(walkWorkerAnchorPath,"walkWorkerAnchorPath");function workerDialHost(daemonUrl){try{const hostname=new URL(daemonUrl).hostname;if(!hostname)return void 0;return hostname.startsWith("[")&&hostname.endsWith("]")?hostname.slice(1,-1):hostname}catch{return void 0}}__name(workerDialHost,"workerDialHost");function certCoversHost(x509,host){try{return isIP(host)?Boolean(x509.checkIP(host)):Boolean(x509.checkHost(host))}catch{return true}}__name(certCoversHost,"certCoversHost");function extractContextFilename(value){if(typeof value==="string"){const trimmed=value.trim();return trimmed===""?void 0:trimmed}if(Array.isArray(value)){for(const entry of value){if(typeof entry==="string"){const trimmed=entry.trim();if(trimmed!=="")return trimmed}}return void 0}return void 0}__name(extractContextFilename,"extractContextFilename");function sessionArtifactsPersistenceAvailableFromSettings(settings){return settings?.general?.chatRecording!==false}__name(sessionArtifactsPersistenceAvailableFromSettings,"sessionArtifactsPersistenceAvailableFromSettings");function subSessionConcurrencyCapsFromSettings(serve,onWarning=writeStderrLine){const asCap=__name((key,value)=>{if(value===void 0)return void 0;if(typeof value==="number"&&Number.isInteger(value)&&value>=1){return value}onWarning(`qwen serve: ignoring invalid ${key} (${JSON.stringify(value)}); expected a positive integer, falling back to the built-in default.`);return void 0},"asCap");const maxConcurrentPerCaller=asCap("maxConcurrentSubSessionsPerCaller",serve.maxConcurrentSubSessionsPerCaller);const maxConcurrentTotal=asCap("maxConcurrentSubSessionsTotal",serve.maxConcurrentSubSessionsTotal);return{...maxConcurrentPerCaller!==void 0?{maxConcurrentPerCaller}:{},...maxConcurrentTotal!==void 0?{maxConcurrentTotal}:{}}}__name(subSessionConcurrencyCapsFromSettings,"subSessionConcurrencyCapsFromSettings");var settingsWriteLocks=new Map;function withSettingsLock(workspace,fn){const prev=settingsWriteLocks.get(workspace)??Promise.resolve();const next=prev.then(fn,fn);settingsWriteLocks.set(workspace,next);return next}__name(withSettingsLock,"withSettingsLock");var retryableChannelWorkerShutdownErrors=new WeakSet;function hasRetryableChannelWorkerShutdownError(error){if(error instanceof AggregateError){return error.errors.some(hasRetryableChannelWorkerShutdownError)}return error instanceof Error&&retryableChannelWorkerShutdownErrors.has(error)}__name(hasRetryableChannelWorkerShutdownError,"hasRetryableChannelWorkerShutdownError");var channelWorkerRuntimePromise;async function loadChannelWorkerRuntime(){channelWorkerRuntimePromise??=Promise.all([import("./channel-worker-supervisor-SQK3WRDC.js"),import("./pidfile-26WXQCHG.js"),import("./runtime-ZBPOQX6E.js"),import("./cli-entry-path-4AZHCVCM.js"),import("./channel-worker-group-GW4KPIK3.js"),import("./channel-worker-manager-2TZEY52M.js")]).then(([supervisor,pidfile,channelRuntime,cliEntryPath,workerGroup,workerManager])=>({createChannelWorkerSupervisor:supervisor.createChannelWorkerSupervisor,resolveWorkerCaCertPath:supervisor.resolveWorkerCaCertPath,channelServicePidfile:pidfile,loadChannelsConfig:channelRuntime.loadChannelsConfig,createChannelWorkerGroup:workerGroup.createChannelWorkerGroup,createChannelWorkerManager:workerManager.createChannelWorkerManager,findCliEntryPath:cliEntryPath.findCliEntryPath})).catch(err=>{channelWorkerRuntimePromise=void 0;throw err});return channelWorkerRuntimePromise}__name(loadChannelWorkerRuntime,"loadChannelWorkerRuntime");function createDisabledChannelWorkerSupervisor(){const snapshot={enabled:false,state:"disabled",channels:[]};return{async start(){},async stop(){},async restart(){return{...snapshot,channels:[]}},killAllSync(){},snapshot:__name(()=>({...snapshot,channels:[]}),"snapshot"),async enqueueWebhookTask(){throw new ChannelWebhookEnqueueError("channel_worker_unavailable","Channel worker is not running.")}}}__name(createDisabledChannelWorkerSupervisor,"createDisabledChannelWorkerSupervisor");function writeServeChannelReservation(channelServicePidfile,channels){channelServicePidfile.reserveServeServiceInfo({channels,servePid:process.pid})}__name(writeServeChannelReservation,"writeServeChannelReservation");function channelServicePidfileConflictError(info){const owner=info.owner==="serve"?"qwen serve":"qwen channel start";return Object.assign(new Error(`Channel service is already running under ${owner} (PID ${info.pid}). Stop it before enabling daemon-managed channels.`),{code:"channel_service_conflict",owner:info.owner,pid:info.pid})}__name(channelServicePidfileConflictError,"channelServicePidfileConflictError");function channelServiceStartingConflictError(){return Object.assign(new Error("Channel service is already starting. Retry after the current startup finishes."),{code:"channel_service_conflict"})}__name(channelServiceStartingConflictError,"channelServiceStartingConflictError");function normalizeInstallModelIds(req,provider,getDefaultModelIds){const fromRequest=req.modelIds?.map(id=>id.trim()).filter(id=>id.length>0);const modelIds=fromRequest&&fromRequest.length>0?fromRequest:getDefaultModelIds(provider);return[...new Set(modelIds)]}__name(normalizeInstallModelIds,"normalizeInstallModelIds");function buildProviderSetupInputs(req,provider,helpers){const protocol=req.protocol??provider.protocol;const baseUrl=helpers.resolveBaseUrl(provider,req.baseUrl);return{...provider.protocolOptions?{protocol}:{},...req.wireApi?{wireApi:req.wireApi}:{},baseUrl,apiKey:req.apiKey.trim(),modelIds:normalizeInstallModelIds(req,provider,helpers.getDefaultModelIds),...req.advancedConfig?{advancedConfig:req.advancedConfig}:{}}}__name(buildProviderSetupInputs,"buildProviderSetupInputs");function shouldPreheatBridge(deps){if(deps.preheatBridge!==void 0)return deps.preheatBridge;return process.env["VITEST_WORKER_ID"]===void 0}__name(shouldPreheatBridge,"shouldPreheatBridge");var coreRuntimePromise;function loadCoreRuntime(){coreRuntimePromise??=import("./core-runtime-CFMHUAS7.js");return coreRuntimePromise}__name(loadCoreRuntime,"loadCoreRuntime");var liveDiscoveryRuntimePromise;function loadLiveDiscoveryRuntime(){liveDiscoveryRuntimePromise??=import("./discovery-UOXKIBGP.js");return liveDiscoveryRuntimePromise}__name(loadLiveDiscoveryRuntime,"loadLiveDiscoveryRuntime");async function resolveDaemonLogBaseDirForRun(input){if(input.deps.daemonLogBaseDir){return input.deps.daemonLogBaseDir}if(input.deps.bootSettings===void 0){const core2=await loadCoreRuntime();if(core2.Storage.getRuntimeBaseDir()!==core2.Storage.getGlobalQwenDir()){return core2.Storage.getGlobalDebugDir()}}if(input.bootSettings?.advanced?.runtimeOutputDir!==void 0){return resolveDaemonLogBaseDir(input.bootSettings.advanced.runtimeOutputDir,input.boundWorkspace)}if(input.deps.bootSettings!==void 0){return resolveDaemonLogBaseDir(void 0,input.boundWorkspace)}const core=await loadCoreRuntime();return core.Storage.getGlobalDebugDir()}__name(resolveDaemonLogBaseDirForRun,"resolveDaemonLogBaseDirForRun");var settingsRuntimePromise;function loadSettingsRuntimeModules(){settingsRuntimePromise??=Promise.all([import("./settings-CPZBOHN5.js"),import("./environment-BVEOYQHO.js"),import("./loadedSettingsAdapter-PLGMKMFO.js"),import("./trustedFolders-JT5MOB3A.js")]).then(([settings,environment,loadedSettingsAdapter,trustedFolders])=>({settings,environment,loadedSettingsAdapter,trustedFolders}));return settingsRuntimePromise}__name(loadSettingsRuntimeModules,"loadSettingsRuntimeModules");var channelWebhookConfigRuntimePromise;function loadChannelWebhookConfigRuntime(){channelWebhookConfigRuntimePromise??=Promise.all([import("./runtime-ZBPOQX6E.js"),import("./config-utils-FI3A4QAN.js")]).then(([channelRuntime,configUtils])=>({loadChannelsConfig:channelRuntime.loadChannelsConfig,parseChannelWebhookConfig:configUtils.parseChannelWebhookConfig})).catch(err=>{channelWebhookConfigRuntimePromise=void 0;throw err});return channelWebhookConfigRuntimePromise}__name(loadChannelWebhookConfigRuntime,"loadChannelWebhookConfigRuntime");async function loadServeRuntimeModules(){const[serverModule,bridgeModule,spawnChannelModule,processRegistryModule,workspaceModule,workspaceTypesModule,daemonStatusProviderModule,workspaceProvidersStatusModule,workspaceSkillsStatusModule,totalSessionAdmissionModule,workspaceRegistryModule,workspaceRuntimeCoordinatorModule,promptLedgerModule,sessionExecutionEngineSelectorModule,managedExecutionEngineModule]=await Promise.all([import("./server-7LOAKPDN.js"),import("./bridge-FIO2ENBG.js"),import("./spawnChannel-2JQYNQKT.js"),import("./process-registry-CCKP5HD4.js"),import("./workspace-service-YPYTYYUN.js"),import("./types-QZ644COX.js"),import("./daemon-status-provider-CSWRGMRX.js"),import("./workspace-providers-status-3ASB64FB.js"),import("./workspace-skills-status-VTFHQ6R7.js"),import("./total-session-admission-XNWYCO7G.js"),import("./workspace-registry-6QJKRCDR.js"),import("./workspace-runtime-coordinator-ZXUWDQIB.js"),import("./prompt-terminal-ledger-EIZZHF4A.js"),import("./session-execution-engine-selector-PHH47ZMA.js"),import("./managed-execution-engine-5LOM3MXG.js")]);return{createServeApp:serverModule.createServeApp,getActiveSseCount:serverModule.getActiveSseCount,resolveBoundWorkspacesFromIdeEnv:serverModule.resolveBoundWorkspacesFromIdeEnv,resolveBridgeFsFactory:serverModule.resolveBridgeFsFactory,createAcpSessionBridge:bridgeModule.createAcpSessionBridge,createSpawnChannelFactory:spawnChannelModule.createSpawnChannelFactory,daemonAcpNdJsonLimits:spawnChannelModule.DAEMON_ACP_NDJSON_LIMITS,ProcessRegistry:processRegistryModule.ProcessRegistry,createDaemonWorkspaceService:workspaceModule.createDaemonWorkspaceService,WorkspaceSettingsPartialPersistError:workspaceTypesModule.WorkspaceSettingsPartialPersistError,createDaemonStatusProvider:daemonStatusProviderModule.createDaemonStatusProvider,createWorkspaceProvidersStatusProvider:workspaceProvidersStatusModule.createWorkspaceProvidersStatusProvider,createWorkspaceSkillsStatusProvider:workspaceSkillsStatusModule.createWorkspaceSkillsStatusProvider,createTotalSessionAdmissionController:totalSessionAdmissionModule.createTotalSessionAdmissionController,createWorkspaceRegistry:workspaceRegistryModule.createWorkspaceRegistry,createWorkspaceSessionOwnerIndex:workspaceRegistryModule.createWorkspaceSessionOwnerIndex,createWorkspaceGenerationGuard:workspaceRegistryModule.createWorkspaceGenerationGuard,getWorkspaceRuntimeCoordinatorIfSupported:workspaceRuntimeCoordinatorModule.getWorkspaceRuntimeCoordinatorIfSupported,createPromptLedgerSink:promptLedgerModule.createPromptLedgerSink,createPairedExecutionEngines:sessionExecutionEngineSelectorModule.createPairedExecutionEngines,createManagedExecutionEngine:managedExecutionEngineModule.createManagedExecutionEngine}}__name(loadServeRuntimeModules,"loadServeRuntimeModules");function advertisedMaxSessions(value){if(value===void 0)return DEFAULT_MAX_SESSIONS;if(value===0||value===Number.POSITIVE_INFINITY)return null;return value}__name(advertisedMaxSessions,"advertisedMaxSessions");function advertisedMaxPendingPromptsPerSession(value){if(value===void 0)return DEFAULT_MAX_PENDING_PROMPTS_PER_SESSION;if(value===0||value===Number.POSITIVE_INFINITY)return null;return value}__name(advertisedMaxPendingPromptsPerSession,"advertisedMaxPendingPromptsPerSession");function channelIdleTimeoutMs(value){return value!==void 0&&Number.isFinite(value)&&value>0?Math.min(value,MAX_TIMEOUT_MS):0}__name(channelIdleTimeoutMs,"channelIdleTimeoutMs");function sessionIdleTimeoutMs(value){return value!==void 0?channelIdleTimeoutMs(value):DEFAULT_SESSION_IDLE_TIMEOUT_MS}__name(sessionIdleTimeoutMs,"sessionIdleTimeoutMs");function sessionPromptSettledCloseGraceMs(value){return value!==void 0?channelIdleTimeoutMs(value):DEFAULT_SESSION_PROMPT_SETTLED_CLOSE_GRACE_MS}__name(sessionPromptSettledCloseGraceMs,"sessionPromptSettledCloseGraceMs");function currentServeFeaturesForRunQwenServe(opts,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,env,nativeDirectoryPickerAvailable,localPathOpenAvailable,localTerminalOpenAvailable){return getAdvertisedServeFeatures(void 0,{requireAuth:opts.requireAuth===true,mcpPoolActive:opts.mcpPoolActive!==false,externalToolGuardActive:opts.externalToolGuard?.mode==="required",allowOriginActive:opts.allowOrigins!==void 0&&opts.allowOrigins.length>0,...opts.promptDeadlineMs!==void 0?{promptDeadlineMs:opts.promptDeadlineMs}:{},...opts.writerIdleTimeoutMs!==void 0?{writerIdleTimeoutMs:opts.writerIdleTimeoutMs}:{},persistSettingAvailable:true,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,sessionGenerationAvailable:true,currentSessionSchedulingAvailable,workspaceGenerationAvailable:true,rateLimit:opts.rateLimit===true,reloadAvailable:true,channelReloadAvailable:opts.channelSelection!==void 0,channelControlAvailable:true,channelManagementAvailable:true,persistentWorkspaceRegistrationAvailable:true,workspaceRuntimeRemovalAvailable:true,nativeDirectoryPickerAvailable,workspaceRuntimeAvailable,localPathOpenAvailable,localTerminalOpenAvailable,dynamicWorkspaceRegistrationAvailable:true,scratchWorkspaceRegistrationAvailable:true,standaloneSessionsAvailable:true,workspaceTrustHotReloadAvailable:true,acpHttpEnabled:opts.profile!=="hosted-harness"&&resolveAcpHttpEnabled(env),clientMcpOverWsEnabled:opts.clientMcpOverWs===true,cdpTunnelOverWsEnabled:opts.cdpTunnelOverWs===true,browserAutomationMcpAvailable:isBrowserAutomationMcpAvailable(opts,env)})}__name(currentServeFeaturesForRunQwenServe,"currentServeFeaturesForRunQwenServe");function createBootstrapCapabilities(input){return{v:CAPABILITIES_SCHEMA_VERSION,protocolVersions:getServeProtocolVersions(),...input.qwenCodeVersion?{qwenCodeVersion:input.qwenCodeVersion}:{},mode:input.opts.mode,features:currentServeFeaturesForRunQwenServe(input.opts,input.sessionShellCommandEnabled,input.sessionArtifactsPersistenceAvailable,input.workspaceRuntimeAvailable,input.currentSessionSchedulingAvailable,input.env,input.nativeDirectoryPickerAvailable,input.localPathOpenAvailable,input.localTerminalOpenAvailable),modelServices:[],workspaceCwd:input.boundWorkspace,transports:["rest"],policy:{permission:input.permissionPolicy??"first-responder"},limits:{maxRegisteredWorkspaces:input.opts.maxRegisteredWorkspaces,maxChannelControlWorkspaces:MAX_CHANNEL_CONTROL_WORKSPACES,...input.opts.maxTotalSessions!==void 0?{maxSessionsPerWorkspace:advertisedMaxSessions(input.opts.maxSessions),maxTotalSessions:positiveFiniteOrNull(input.opts.maxTotalSessions)}:{},maxPendingPromptsPerSession:advertisedMaxPendingPromptsPerSession(input.opts.maxPendingPromptsPerSession),sessionRestoreTimeoutMs:resolveSessionRestoreTimeoutMs(input.opts)}}}__name(createBootstrapCapabilities,"createBootstrapCapabilities");function validateRateLimitOptions(opts){if(opts.rateLimit!==true)return;for(const[name,value]of[["rateLimitPrompt",opts.rateLimitPrompt],["rateLimitMutation",opts.rateLimitMutation],["rateLimitRead",opts.rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){throw new TypeError(`Invalid ${name}: ${value}. Must be a positive integer.`)}}if(opts.rateLimitWindowMs!==void 0&&(!Number.isFinite(opts.rateLimitWindowMs)||!Number.isInteger(opts.rateLimitWindowMs)||opts.rateLimitWindowMs<1e3)){throw new TypeError(`Invalid rateLimitWindowMs: ${opts.rateLimitWindowMs}. Must be an integer >= 1000.`)}}__name(validateRateLimitOptions,"validateRateLimitOptions");function createLazyBridgeProxy(getBridge,getStartupError=()=>void 0){return new Proxy({},{get(_target,prop){const bridge=getBridge();if(!bridge){const startupError=getStartupError();if(startupError){throw new Error(`Daemon bridge runtime is not available: ${startupError}`)}throw new Error("Daemon bridge runtime is still starting.")}const value=Reflect.get(bridge,prop,bridge);return typeof value==="function"?value.bind(bridge):value}})}__name(createLazyBridgeProxy,"createLazyBridgeProxy");function resolveRuntimeStartupTimeoutMs(override){if(override!==void 0){return Number.isFinite(override)&&override>0?override:0}const raw=process.env[RUNTIME_STARTUP_TIMEOUT_ENV];if(raw===void 0||raw.trim()===""){return DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS}const trimmed=raw.trim();if(trimmed==="0")return 0;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)&&parsed>0?parsed:DEFAULT_RUNTIME_STARTUP_TIMEOUT_MS}__name(resolveRuntimeStartupTimeoutMs,"resolveRuntimeStartupTimeoutMs");async function waitForRuntimeStartingForShutdown(runtimeStarting,daemonLog,timeoutMs=SHUTDOWN_FORCE_CLOSE_MS){if(!runtimeStarting)return;let timer;await Promise.race([runtimeStarting,new Promise(resolve3=>{timer=setTimeout(()=>{daemonLog.warn(`${timeoutMs}ms runtime-startup wait reached during shutdown; continuing listener close`);resolve3()},timeoutMs);timer.unref()})]).finally(()=>{if(timer)clearTimeout(timer)})}__name(waitForRuntimeStartingForShutdown,"waitForRuntimeStartingForShutdown");var BOOTSTRAP_HEALTH_PATH="/health";var BOOTSTRAP_CAPABILITIES_PATH="/capabilities";var BOOTSTRAP_DAEMON_STATUS_PATH="/daemon/status";var BOOTSTRAP_SERVE_PATHS=new Set([BOOTSTRAP_HEALTH_PATH,BOOTSTRAP_CAPABILITIES_PATH,BOOTSTRAP_DAEMON_STATUS_PATH]);var RUNTIME_STARTUP_FAILED_ENVELOPE={error:"Daemon runtime failed to start",code:"daemon_runtime_failed"};var RUNTIME_STARTUP_STARTING_ENVELOPE={error:"Daemon runtime is still starting",code:"daemon_runtime_starting"};function runtimeStartupEnvelope(runtimeError){return runtimeError?RUNTIME_STARTUP_FAILED_ENVELOPE:RUNTIME_STARTUP_STARTING_ENVELOPE}__name(runtimeStartupEnvelope,"runtimeStartupEnvelope");function createBootstrapServeApp(input){const{opts,getPort,boundWorkspace,startup,daemonLog,qwenCodeVersion,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,permissionPolicy,multiWorkspaceCapabilitiesRequireRuntime,getRuntimeError,getChannelWorkerSnapshot,getChannelWorkerSnapshots,getChannelRestoreFailures,onHealthServed}=input;const app=(0,import_express.default)();const nativeDirectoryPickerAvailable=isNativeDirectoryPickerAvailable();const localPathOpenAvailable=isLocalPathOpenAvailable();const localTerminalOpenAvailable=isLocalTerminalAvailable();installSelfOriginStripMiddleware(app,getPort,opts.hostname);app.use(hostAllowlist(opts.hostname,getPort));installRemoteSelfOriginMiddleware(app,opts.hostname,opts.token);if(opts.allowOrigins&&opts.allowOrigins.length>0){app.use(allowOriginCors(parseAllowOriginPatterns(opts.allowOrigins)))}else{app.use(denyBrowserOriginCors)}if(opts.profile==="hosted-harness"){app.use((req,res,next)=>{if(req.path==="/health"||req.path==="/capabilities")next();else res.sendStatus(404)})}const healthHandler=__name((req,res)=>{const runtimeError=getRuntimeError();if(runtimeError!==void 0){res.status(503).json({status:"degraded",error:runtimeError});return}if(onHealthServed){res.once("finish",onHealthServed)}if(isDeepHealthQuery(req.query["deep"])){res.setHeader("Retry-After","1");res.status(503).json({status:"degraded",reason:"bootstrap"});return}res.status(200).json({status:"ok"})},"healthHandler");const loopback=isLoopbackBind(opts.hostname);const exposeHealthPreAuth=loopback&&!opts.requireAuth;if(exposeHealthPreAuth){app.get(BOOTSTRAP_HEALTH_PATH,healthHandler)}app.use(bearerAuth(opts.token));if(!exposeHealthPreAuth){app.get(BOOTSTRAP_HEALTH_PATH,healthHandler)}app.get(BOOTSTRAP_CAPABILITIES_PATH,(_req,res)=>{if(opts.profile==="hosted-harness"){res.setHeader("Retry-After","1");res.status(503).json({error:"Hosted Harness is starting."});return}if(multiWorkspaceCapabilitiesRequireRuntime){const runtimeError=getRuntimeError();if(runtimeError===void 0){res.setHeader("Retry-After","1")}res.status(503).json(runtimeStartupEnvelope(runtimeError));return}res.status(200).json(createBootstrapCapabilities({opts,boundWorkspace,qwenCodeVersion,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,permissionPolicy,env:process.env,nativeDirectoryPickerAvailable,localPathOpenAvailable,localTerminalOpenAvailable}))});app.get(BOOTSTRAP_DAEMON_STATUS_PATH,(req,res)=>{const detail=parseDaemonStatusDetail(req.query["detail"]);if(!detail.ok||!detail.detail){res.status(400).json({error:"detail must be one of: summary, full",code:"invalid_detail"});return}const runtimeError=getRuntimeError();const bootstrapJournalGrowthPoolMb=opts.daemonMemoryBudget!==void 0?serveJournalGrowthPoolMb({budget:opts.daemonMemoryBudget,maxJournalEvents:opts.maxJournalEvents,maxJournalBytes:opts.maxJournalBytes}):0;const channelWorker=getChannelWorkerSnapshot();const channelWorkers=getChannelWorkerSnapshots();const runtimeFailed=runtimeError!==void 0;const issue=runtimeError?{code:"daemon_runtime_failed",severity:"error",message:runtimeError}:{code:"daemon_runtime_starting",severity:"warning",message:"Daemon runtime is still starting."};const daemonLogStatus=daemonLog.getStatus();const issues=[issue];pushChannelRestoreIssues(issues,getChannelRestoreFailures());if(daemonLogStatus.health==="degraded"){issues.push({code:"daemon_log_degraded",severity:"warning",message:"Daemon file logging is degraded; inspect full status for details."})}const response={v:1,detail:detail.detail,generatedAt:new Date().toISOString(),status:runtimeFailed?"error":"warning",issues,daemon:{pid:process.pid,uptimeMs:Math.round(process.uptime()*1e3),mode:opts.mode,workspaceCwd:boundWorkspace,startup:{...startup,preheat:{...startup.preheat}},...qwenCodeVersion?{qwenCodeVersion}:{},...daemonLog.getDaemonId()?{daemonId:daemonLog.getDaemonId()}:{},runId:daemonLogStatus.runId,logMode:daemonLogStatus.mode,logHealth:daemonLogStatus.health,...detail.detail==="full"&&daemonLog.getLogPath()?{logPath:daemonLog.getLogPath()}:{},...detail.detail==="full"?{logIssues:daemonLogStatus.issues,logDroppedRecords:daemonLogStatus.droppedRecords,logDroppedBytes:daemonLogStatus.droppedBytes}:{}},security:{tokenConfigured:Boolean(opts.token),requireAuth:opts.requireAuth===true,loopbackBind:loopback,allowOriginConfigured:opts.allowOrigins!==void 0&&opts.allowOrigins.length>0,allowOriginMode:allowOriginMode(opts.allowOrigins),sessionShellCommandEnabled},limits:{maxRegisteredWorkspaces:opts.maxRegisteredWorkspaces,maxChannelControlWorkspaces:MAX_CHANNEL_CONTROL_WORKSPACES,maxSessions:advertisedMaxSessions(opts.maxSessions),maxTotalSessions:positiveFiniteOrNull(opts.maxTotalSessions),maxPendingPromptsPerSession:advertisedMaxPendingPromptsPerSession(opts.maxPendingPromptsPerSession),listenerMaxConnections:listenerMaxConnections(opts.maxConnections),eventRingSize:opts.eventRingSize??DEFAULT_RING_SIZE,compactedReplayMaxBytes:opts.compactedReplayMaxBytes??DEFAULT_COMPACTED_REPLAY_MAX_BYTES,maxJournalEvents:opts.maxJournalEvents??DEFAULT_MAX_JOURNAL_EVENTS,maxJournalBytes:opts.maxJournalBytes??DEFAULT_MAX_JOURNAL_BYTES,promptDeadlineMs:positiveFiniteOrNull(opts.promptDeadlineMs),writerIdleTimeoutMs:positiveFiniteOrNull(opts.writerIdleTimeoutMs),channelIdleTimeoutMs:channelIdleTimeoutMs(opts.channelIdleTimeoutMs),sessionIdleTimeoutMs:sessionIdleTimeoutMs(opts.sessionIdleTimeoutMs),sessionPromptSettledCloseGraceMs:sessionPromptSettledCloseGraceMs(opts.sessionPromptSettledCloseGraceMs),acpConnectionCap:null,acpPreAttachMaxFramesPerStream:null,acpPreAttachMaxFramesPerConnection:null,acpPreAttachMaxFramesGlobal:null,acpPreAttachMaxPayloadBytesPerConnection:null,acpPreAttachMaxPayloadBytesGlobal:null,memory:toDaemonStatusMemoryLimits(opts.daemonMemoryBudget,void 0,bootstrapJournalGrowthPoolMb>0?{poolBytes:bootstrapJournalGrowthPoolMb*1024*1024,hardCapBytes:JOURNAL_GROWTH_HARD_CAP_BYTES,baselineMaxEvents:opts.maxJournalEvents??DEFAULT_MAX_JOURNAL_EVENTS,baselineMaxBytes:opts.maxJournalBytes??DEFAULT_MAX_JOURNAL_BYTES}:null)},capabilities:{protocolVersions:getServeProtocolVersions(),features:currentServeFeaturesForRunQwenServe(opts,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable,currentSessionSchedulingAvailable,process.env,nativeDirectoryPickerAvailable,localPathOpenAvailable,localTerminalOpenAvailable)},runtime:{loading:runtimeError===void 0,...runtimeError?{error:runtimeError}:{},sessions:{active:0},permissions:{pending:0,policy:permissionPolicy??"first-responder"},channel:{live:false},channelWorker,...channelWorkers.length>0?{channelWorkers}:{},transport:{restSseActive:0,acp:{enabled:false,connections:0,connectionStreams:0,sessionStreams:0,sseStreams:0,wsStreams:0,pendingClientRequests:0,preAttach:{bufferedConnectionFrames:0,bufferedSessionFrames:0,pendingDeliveryFrames:0,usedFrames:0,usedBytes:0,highWaterFrames:0,highWaterBytes:0,guardFailures:0}}},rateLimit:{enabled:opts.rateLimit===true,rejectedSinceStart:{prompt:0,mutation:0,read:0}},activity:{activePrompts:0,pendingPrompts:0,queuedPrompts:0,lastActivityAt:null,idleSinceMs:null},process:process.memoryUsage()},...detail.detail==="full"?{full:{sessions:[],acpMounts:[],acpConnections:[],workspace:{},auth:{supportedDeviceFlowProviders:[],pendingDeviceFlowCount:0}}}:{}};res.status(200).json(response)});app.use((_req,res)=>{res.status(503).json(runtimeStartupEnvelope(getRuntimeError()))});return app}__name(createBootstrapServeApp,"createBootstrapServeApp");function createDelegatingServeApp(bootstrapApp,getRuntimeApp,options={}){const app=(0,import_express.default)();app.use((req,res,next)=>{const dispatch=__name(async()=>{let target=getRuntimeApp();if(!target&&options.waitForDeferredRuntimeRoutes===true&&!isBootstrapServeRoute(req)&&!isCorsPreflightRequest(req)&&options.startRuntime&&options.runtimeReady){const waitStartedAt=performance2.now();const timing={startedAt:new Date,path:"joined"};const webhookRequest=isChannelWebhookRequest(req);const authGate=webhookRequest?options.authenticateDeferredChannelWebhookRequest??options.authenticateDeferredRuntimeRequest:options.authenticateDeferredRuntimeRequest;const preAuthExempted=authGate!==void 0&&await Promise.resolve(options.isPreAuthRequest?.(req)).catch(()=>false)===true;if(authGate&&!preAuthExempted){if(!runSynchronousRequestGate(authGate,req,res,next)){return}}setDeferredRuntimeRequestTiming(req,timing);if(options.startRuntime()){timing.path="started_on_request"}try{await options.runtimeReady}catch{if(preAuthExempted){res.status(503).json(RUNTIME_STARTUP_FAILED_ENVELOPE);return}}finally{timing.waitMs=Math.round((performance2.now()-waitStartedAt)*100)/100}target=getRuntimeApp()}const handler=target??bootstrapApp;handler(req,res,next)},"dispatch");void dispatch().catch(next)});return app}__name(createDelegatingServeApp,"createDelegatingServeApp");function isBootstrapServeRoute(req){const path2=req.path.length>1&&req.path.endsWith("/")?req.path.slice(0,-1):req.path;return BOOTSTRAP_SERVE_PATHS.has(path2)}__name(isBootstrapServeRoute,"isBootstrapServeRoute");function isChannelWebhookRequest(req){return req.method==="POST"&&/^\/channels\/[^/]+\/webhooks\/[^/]+\/?$/u.test(req.path)}__name(isChannelWebhookRequest,"isChannelWebhookRequest");function createDeferredChannelWebhookAuth(resolveSource,runtime,daemonLog){return(req,res,next)=>{const match=/^\/channels\/([^/]+)\/webhooks\/([^/]+)\/?$/u.exec(req.path);const channelName=decodeDeferredWebhookPathSegment(match?.[1]);const source=decodeDeferredWebhookPathSegment(match?.[2]);if(!channelName||!source){daemonLog.warn("deferred webhook auth failed",{channelName:channelName??"unknown",source:source??"unknown",reason:"invalid webhook path"});res.status(401).json({error:"Invalid webhook secret"});return}const configSource=resolveSource(channelName);const secret=readDeferredWebhookSecret(runtime,configSource.workspaceCwd,channelName,source,configSource.env);if(!matchesWebhookSecret(req.get("x-qwen-webhook-secret"),secret)){daemonLog.warn("deferred webhook auth failed",{channelName,source,reason:secret?"secret mismatch":"source not configured"});res.status(401).json({error:"Invalid webhook secret"});return}next()}}__name(createDeferredChannelWebhookAuth,"createDeferredChannelWebhookAuth");function decodeDeferredWebhookPathSegment(segment){if(segment===void 0)return void 0;try{return decodeURIComponent(segment)}catch{return void 0}}__name(decodeDeferredWebhookPathSegment,"decodeDeferredWebhookPathSegment");function readDeferredWebhookSecret(runtime,workspace,channelName,source,env){try{const rawConfig=runtime.loadChannelsConfig(workspace)[channelName];if(typeof rawConfig!=="object"||rawConfig===null){return void 0}return runtime.parseChannelWebhookConfig(channelName,rawConfig,env)?.sources[source]?.secret}catch(err){const reason=err instanceof Error?err.message:String(err);writeStderrLine(`[webhook-secret] failed to read deferred webhook secret for ${sanitizeLogText(channelName,128)}/${sanitizeLogText(source,128)}: ${sanitizeLogText(reason,512)}`);return void 0}}__name(readDeferredWebhookSecret,"readDeferredWebhookSecret");function matchesWebhookSecret(candidate,expected){if(typeof candidate!=="string"||typeof expected!=="string"||expected.length===0){return false}const expectedDigest=createHash2("sha256").update(expected).digest();const candidateDigest=createHash2("sha256").update(candidate).digest();return timingSafeEqual(expectedDigest,candidateDigest)}__name(matchesWebhookSecret,"matchesWebhookSecret");function isCorsPreflightRequest(req){return req.method==="OPTIONS"&&Boolean(req.headers.origin)&&Boolean(req.headers["access-control-request-method"]||req.headers["access-control-request-headers"])}__name(isCorsPreflightRequest,"isCorsPreflightRequest");function runSynchronousRequestGate(handler,req,res,next){let passed=false;handler(req,res,err=>{if(err){next(err);return}passed=true});return passed}__name(runSynchronousRequestGate,"runSynchronousRequestGate");function validateAndCanonicalizeWorkspaceInput(rawWorkspace){const workspace=translateAndCheckAbsoluteWorkspacePath(rawWorkspace);if(workspace===null){throw new Error(`Invalid --workspace "${rawWorkspace}": must be an absolute path.`)}try{const stats=fs.statSync(workspace);if(!stats.isDirectory()){throw new Error(`Invalid --workspace "${workspace}": exists but is not a directory.`)}}catch(err){if(err&&typeof err==="object"&&"code"in err){const code=err.code;if(code==="ENOENT"){throw new Error(`Invalid --workspace "${workspace}": directory does not exist.`)}if(code==="EACCES"||code==="EPERM"){throw new Error(`Invalid --workspace "${workspace}": permission denied (${String(code)}). The path exists but cannot be stat'd by the current user.`)}}throw err}return canonicalizeWorkspace(workspace)}__name(validateAndCanonicalizeWorkspaceInput,"validateAndCanonicalizeWorkspaceInput");async function runQwenServe(optsIn,deps={}){let daemonLog;let owner="startup";let restoreScrubbedLoaderEnv;let installedLoaderRejectionReporter;try{return await runQwenServeImpl(optsIn,deps,{initialized:__name(logger=>{daemonLog=logger},"initialized"),published:__name(()=>{if(owner==="startup")owner="handle"},"published"),signalOwned:__name(()=>{if(owner==="startup")owner="signal"},"signalOwned"),scrubApplied:__name(restore=>{restoreScrubbedLoaderEnv=restore},"scrubApplied"),reporterInstalled:__name(reporter=>{installedLoaderRejectionReporter=reporter},"reporterInstalled")})}catch(error){if(installedLoaderRejectionReporter){clearLoaderKeyRejectionReporterIfCurrent(installedLoaderRejectionReporter)}if(daemonLog&&owner==="startup"){const startupLog=daemonLog;writeDaemonLifecycleBestEffort(()=>startupLog.error("daemon startup failed",error instanceof Error?error:new Error(String(error))));await startupLog.close()}restoreScrubbedLoaderEnv?.();throw error}}__name(runQwenServe,"runQwenServe");function bridgeHasLiveSessionWithin(bridge,workspaceCwd,worktreePath){return bridge.listWorkspaceSessions(workspaceCwd).some(session=>{try{return isWithinRoot(path.resolve(bridge.getSessionExecutionSnapshot(session.sessionId).effectiveCwd),path.resolve(worktreePath))}catch{return true}})}__name(bridgeHasLiveSessionWithin,"bridgeHasLiveSessionWithin");async function createBranchRecoverySessionService(runtime){const{SessionService}=await import("./sessionService-7PFAWLHC.js");return new SessionService(runtime.workspaceCwd,{runtimeBaseDir:runtime.sessionRuntimeBaseDir})}__name(createBranchRecoverySessionService,"createBranchRecoverySessionService");var brokenPipeGuardInstalled=false;function installServeBrokenPipeGuard(){if(brokenPipeGuardInstalled)return;brokenPipeGuardInstalled=true;const ignoreEpipe=__name(err=>{if(err.code!=="EPIPE")throw err},"ignoreEpipe");process.stdout.on("error",ignoreEpipe);process.stderr.on("error",ignoreEpipe)}__name(installServeBrokenPipeGuard,"installServeBrokenPipeGuard");async function runQwenServeImpl(optsIn,deps,loggerLifecycle){installServeBrokenPipeGuard();const runStartedAt=performance2.now();delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const channelDeliveryAuthorizations=new ChannelDeliveryAuthorizationStore;let shouldPreheat=optsIn.profile!=="hosted-harness"&&!deps.bridge&&shouldPreheatBridge(deps);const startup={processStartedAt:new Date(Date.now()-Math.round(process.uptime()*1e3)).toISOString(),preheat:{status:deps.bridge?"external_bridge":shouldPreheat?"scheduled":"not_scheduled"}};if(optsIn.memoryProjectScope!==void 0&&!MEMORY_PROJECT_SCOPES.includes(optsIn.memoryProjectScope)){throw new TypeError(`Invalid memoryProjectScope: ${String(optsIn.memoryProjectScope)}. Must be "git-root" or "workspace".`)}preResolveServeFastPathHomeEnvOverrides();assertExecutionSandboxSupported(readOperatorSandboxSettings(),"serve / ACP / web terminals");assertExecutionSandboxSupported(deps.bootSettings??{},"serve / ACP / web terminals");const{token,generated:generatedToken}=resolveRemoteServeToken(optsIn.token,isLoopbackBind(optsIn.hostname));const hostedHarnessCapabilityDigest=optsIn.hostedHarnessCapabilityDigest??(optsIn.profile==="hosted-harness"?process.env[HOSTED_HARNESS_CAPABILITY_DIGEST_ENV]:void 0);const hostedCsiSessionStoreUrl=optsIn.hostedCsiSessionStoreUrl??process.env[HOSTED_CSI_SESSION_STORE_URL_ENV];validateHostedHarnessProfile({...optsIn,token,requireAuth:optsIn.profile==="hosted-harness"?true:optsIn.requireAuth,hostedHarnessCapabilityDigest,hostedCsiSessionStoreUrl});const baseEnv={...process.env};const launchMemoryProjectScopeValue=baseEnv["QWEN_CODE_MEMORY_PROJECT_SCOPE"];const launchMemoryProjectScope=launchMemoryProjectScopeValue?.trim()?launchMemoryProjectScopeValue:void 0;const memoryProjectScopeValue=optsIn.memoryProjectScope??launchMemoryProjectScope??"workspace";const memoryProjectScopeSource=optsIn.memoryProjectScope!==void 0?"option":launchMemoryProjectScope!==void 0?"environment":"default";const resolvedMemoryProjectScope=memoryProjectScopeValue.trim().toLowerCase()==="workspace"?"workspace":"git-root";baseEnv["QWEN_CODE_MEMORY_PROJECT_SCOPE"]=memoryProjectScopeValue;if(process.env["DEV"]!=="true"){scrubInheritedLoaderEnv(baseEnv)}const daemonRuntimeBaseEnv=Object.freeze(baseEnv);const loaderEnvScrub=acquireInheritedLoaderEnvScrub(process.env,"qwen serve","daemon");const scrubbedLoaderEnvKeys=loaderEnvScrub.removedKeys;const restoreScrubbedLoaderEnv=__name(()=>{loaderEnvScrub.release()},"restoreScrubbedLoaderEnv");loggerLifecycle.scrubApplied(restoreScrubbedLoaderEnv);if(!optsIn.hostname.trim()){throw new Error("Invalid --hostname: empty value binds every interface. Pass an explicit address (e.g. --hostname 0.0.0.0) or omit the flag.")}const bindHostname=optsIn.hostname.toLowerCase()==="localhost"?(await(deps.bindHostnameLookup??lookup)(optsIn.hostname)).address:optsIn.hostname;if(optsIn.profile==="hosted-harness"&&!isLoopbackAddress(bindHostname)){throw new Error("--profile hosted-harness resolved outside the loopback interface.")}const trustedLoopbackMode=isTrustedLoopbackMode({loopbackBind:isLoopbackAddress(bindHostname),tokenConfigured:token!==void 0,requireAuth:optsIn.requireAuth===true});const channelDeliveryDiagnosticRedaction={workerEnv:daemonRuntimeBaseEnv,...token?{daemonToken:token}:{}};const sessionShellCommandEnabled=optsIn.enableSessionShell===true&&(token!==void 0||trustedLoopbackMode);if(optsIn.enableSessionShell===true&&token===void 0&&!trustedLoopbackMode){writeStderrLine(`qwen serve: --enable-session-shell ignored because no bearer token is configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token to enable direct session shell.`)}const promptDeadlineMs=optsIn.promptDeadlineMs??parseDeadlineEnv(QWEN_SERVE_PROMPT_DEADLINE_MS_ENV,process.env[QWEN_SERVE_PROMPT_DEADLINE_MS_ENV]);const writerIdleTimeoutMs=optsIn.writerIdleTimeoutMs??parseDeadlineEnv(QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV,process.env[QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS_ENV]);const clientMcpOverWsEnv=process.env[QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV];const cdpTunnelOverWsEnv=process.env[QWEN_SERVE_CDP_TUNNEL_OVER_WS_ENV];const chromeExtensionOriginAllowed=hasChromeExtensionOrigin(optsIn.allowOrigins);const rawWorkspaces=resolveWorkspaceInputs(optsIn.workspace);const rawWorkspace=rawWorkspaces[0];const opts={...optsIn,hostname:bindHostname,requireAuth:optsIn.profile==="hosted-harness"?true:optsIn.requireAuth,maxRegisteredWorkspaces:resolveMaxRegisteredWorkspaces(optsIn.maxRegisteredWorkspaces,daemonRuntimeBaseEnv),token,hostedHarnessCapabilityDigest,hostedCsiSessionStoreUrl,promptDeadlineMs,writerIdleTimeoutMs,workspace:rawWorkspace,clientMcpOverWs:optsIn.profile==="hosted-harness"?false:optsIn.clientMcpOverWs??(!envFlagDisabled(clientMcpOverWsEnv)&&clientMcpOverWsEnv!==void 0),cdpTunnelOverWs:optsIn.profile==="hosted-harness"?false:optsIn.cdpTunnelOverWs??(!envFlagDisabled(cdpTunnelOverWsEnv)&&(cdpTunnelOverWsEnv!==void 0||chromeExtensionOriginAllowed))};let channelRuntime=opts.channelSelection?await loadChannelWorkerRuntime():void 0;let channelServicePidfile=deps.channelServicePidfile??channelRuntime?.channelServicePidfile;const ensureChannelRuntime=__name(async()=>{channelRuntime??=await loadChannelWorkerRuntime();channelServicePidfile??=channelRuntime.channelServicePidfile;return channelRuntime},"ensureChannelRuntime");let channelPidfileReserved=false;const removeCurrentServePidfile=__name(()=>{if(!channelServicePidfile)return;if(!channelPidfileReserved)return;if(channelServicePidfile.removeServeServiceInfo){if(channelServicePidfile.removeServeServiceInfo(process.pid)){channelPidfileReserved=false}else{const info2=channelServicePidfile.readServiceInfo();if(!info2||info2.owner!=="serve"||info2.pid!==process.pid||info2.servePid!==process.pid){channelPidfileReserved=false}}return}const info=channelServicePidfile.readServiceInfo();if(info?.owner==="serve"&&info.pid===process.pid&&info.servePid===process.pid){channelServicePidfile.removeServiceInfo();const remaining=channelServicePidfile.readServiceInfo();channelPidfileReserved=remaining?.owner==="serve"&&remaining.pid===process.pid&&remaining.servePid===process.pid}else{channelPidfileReserved=false}},"removeCurrentServePidfile");const reserveChannelServicePidfile=__name(selection=>{if(!channelServicePidfile){throw new Error("Channel service pidfile runtime is not available.")}const channelPidfileNames=channelSelectionNames(selection);const existingChannelService=channelServicePidfile.readServiceInfo();if(existingChannelService){throw channelServicePidfileConflictError(existingChannelService)}try{writeServeChannelReservation(channelServicePidfile,channelPidfileNames);channelPidfileReserved=true}catch(err){if(err&&typeof err==="object"&&"code"in err){const code=err.code;if(code==="EEXIST"){const info=channelServicePidfile.readServiceInfo();if(info){throw channelServicePidfileConflictError(info)}try{writeServeChannelReservation(channelServicePidfile,channelPidfileNames);channelPidfileReserved=true;return}catch(retryErr){if(retryErr&&typeof retryErr==="object"&&"code"in retryErr&&retryErr.code==="EEXIST"){throw channelServiceStartingConflictError()}throw retryErr}}}throw err}},"reserveChannelServicePidfile");validateRateLimitOptions(opts);if(!opts.hostname.startsWith("[")&&opts.hostname.split(":").length===2){const[host,port]=opts.hostname.split(":");throw new Error(`Invalid --hostname "${opts.hostname}": looks like a "host:port" combination. Use --port for the port, e.g. "--hostname ${host} --port ${port}".`)}let tlsOptions;let tlsCertPath;if(opts.tlsCert&&!opts.tlsKey||!opts.tlsCert&&opts.tlsKey){throw new Error(`--tls-cert and --tls-key must be provided together (got only --tls-${opts.tlsCert?"cert":"key"}).`)}if(opts.tlsCert&&opts.tlsKey){let cert;let key;try{cert=fs.readFileSync(opts.tlsCert)}catch(err){throw new Error(`Failed to read --tls-cert "${opts.tlsCert}": ${err instanceof Error?err.message:String(err)}`)}try{key=fs.readFileSync(opts.tlsKey)}catch(err){throw new Error(`Failed to read --tls-key "${opts.tlsKey}": ${err instanceof Error?err.message:String(err)}`)}let x509;try{x509=new X509Certificate(cert)}catch(err){throw new Error(`--tls-cert "${opts.tlsCert}" is not a valid certificate: ${err instanceof Error?err.message:String(err)}`)}const now=Date.now();if(new Date(x509.validTo).getTime()<now){throw new Error(`--tls-cert "${opts.tlsCert}" expired on ${x509.validTo}. Renew the certificate and restart.`)}if(new Date(x509.validFrom).getTime()>now){throw new Error(`--tls-cert "${opts.tlsCert}" is not yet valid (validFrom: ${x509.validFrom}). Check the certificate's notBefore date or the system clock.`)}tlsOptions={cert,key};tlsCertPath=path.resolve(opts.tlsCert)}if(!isLoopbackBind(opts.hostname)&&!token){throw new Error(`Refusing to bind ${opts.hostname}:${opts.port} without a bearer token (an explicitly empty --token or ${QWEN_SERVER_TOKEN_ENV} counts as none, since a blank source never generates one). Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or rebind to loopback (127.0.0.0/8, localhost, ::1, or [::1]).`)}if(opts.requireAuth&&!token){throw new Error(`Refusing to start with --require-auth set but no bearer token configured. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or omit --require-auth to keep the loopback developer default.`)}if(opts.allowOrigins&&opts.allowOrigins.length>0){const parsed=parseAllowOriginPatterns(opts.allowOrigins);if(parsed.allowAny&&!token){throw new Error(`Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or list specific origins instead of '*'.`)}const nonLoopbackHttpOrigin=findNonLoopbackHttpOrigin(parsed);if(nonLoopbackHttpOrigin&&!token){throw new Error(`Refusing to start with --allow-origin ${JSON.stringify(nonLoopbackHttpOrigin)} but no bearer token configured. Non-loopback HTTP(S) browser origins can drive the full operator API, including code execution as the daemon user. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or use a loopback origin.`)}writeStderrLine(`qwen serve: --allow-origin: ${opts.allowOrigins.join(", ")}`+(parsed.allowAny?" (WARNING: `*` admits any cross-origin browser \u2014 bearer token gates API routes; the Web Shell static assets stay pre-auth in every mode unless --no-web, and /health stays pre-auth on loopback unless --require-auth is set)":trustedLoopbackMode?" (WARNING: these browser origins receive full API authority without a bearer token in trusted loopback mode and can execute code as the daemon user)":""))}if(opts.allowPrivateAuthBaseUrl){writeStderrLine("qwen serve: --allow-private-auth-base-url enabled; /workspace/auth/provider may install localhost/private-network model endpoints. Use only for local development with trusted clients.")}const validateAndCanonicalizeWorkspace=validateAndCanonicalizeWorkspaceInput;const liveConversationWorkspace=deps.liveConversationWorkspace??new ConversationWorkspace;const isReservedConversationWorkspace=__name(candidate=>{const resolvedCandidate=path.resolve(candidate);const resolvedRoot=path.resolve(liveConversationWorkspace.rootPath);let canonicalRoot=resolvedRoot;try{canonicalRoot=fs.realpathSync.native(resolvedRoot)}catch{}return resolvedCandidate===resolvedRoot||isWithinRoot(resolvedCandidate,resolvedRoot)||resolvedCandidate===canonicalRoot||isWithinRoot(resolvedCandidate,canonicalRoot)},"isReservedConversationWorkspace");const reservedRawWorkspace=rawWorkspaces.find(workspace=>isReservedConversationWorkspace(workspace));if(reservedRawWorkspace){throw new Error(`Workspace ${JSON.stringify(reservedRawWorkspace)} is reserved for Conversations.`)}const workspaceInputs=rawWorkspaces.map(workspace=>({raw:workspace,cwd:validateAndCanonicalizeWorkspace(workspace),displayName:void 0,removable:false,registrationIds:[]}));const boundWorkspace=workspaceInputs[0].cwd;const seenCanonicalWorkspaces=new Set;for(const workspace of workspaceInputs){if(seenCanonicalWorkspaces.has(workspace.cwd)){throw new Error(`Duplicate --workspace value resolves to ${JSON.stringify(workspace.cwd)}.`)}seenCanonicalWorkspaces.add(workspace.cwd)}for(let i=0;i<workspaceInputs.length;i++){for(let j=i+1;j<workspaceInputs.length;j++){const first=workspaceInputs[i].cwd;const second=workspaceInputs[j].cwd;const firstRel=path.relative(first,second);const secondRel=path.relative(second,first);if(firstRel&&!firstRel.startsWith("..")&&!path.isAbsolute(firstRel)){throw new Error(`Nested --workspace values are not supported: ${JSON.stringify(second)} is inside ${JSON.stringify(first)}.`)}if(secondRel&&!secondRel.startsWith("..")&&!path.isAbsolute(secondRel)){throw new Error(`Nested --workspace values are not supported: ${JSON.stringify(first)} is inside ${JSON.stringify(second)}.`)}}}if(workspaceInputs.length>opts.maxRegisteredWorkspaces){throw new Error(`At most ${opts.maxRegisteredWorkspaces} --workspace values may be registered.`)}opts.daemonMemoryBudget=resolveDaemonMemoryBudget({budgetMb:opts.memoryBudgetMb});if((opts.childHeapMode==="admit"||opts.childHeapMode==="enforce")&&deps.bridge){throw new TypeError("ACP admission cannot be combined with an injected bridge.")}const admissionPolicy=opts.childHeapMode==="admit"||opts.childHeapMode==="enforce"?createChildHeapPolicy({budget:opts.daemonMemoryBudget,mode:opts.childHeapMode}):void 0;if(opts.daemonMemoryBudget.budgetSource==="flag"||opts.daemonMemoryBudget.insufficientMemory){writeStderrLine(formatMemoryBudgetStderr(opts.daemonMemoryBudget))}const journalGrowthPoolMbValue=opts.daemonMemoryBudget!==void 0?serveJournalGrowthPoolMb({budget:opts.daemonMemoryBudget,maxJournalEvents:opts.maxJournalEvents,maxJournalBytes:opts.maxJournalBytes}):0;const journalGrowthPoolBytes=journalGrowthPoolMbValue>0?journalGrowthPoolMbValue*1024*1024:void 0;const journalGrowthSessionLimitProviders=new Set;const journalGrowthSessionLimits=__name(()=>{const limits=[];for(const provider of journalGrowthSessionLimitProviders){limits.push(...provider())}return limits},"journalGrowthSessionLimits");const registerJournalGrowthSessionLimits=__name(provider=>{journalGrowthSessionLimitProviders.add(provider);return()=>{journalGrowthSessionLimitProviders.delete(provider)}},"registerJournalGrowthSessionLimits");const reservedStartupWorkspace=workspaceInputs.find(workspace=>isReservedConversationWorkspace(workspace.cwd));if(reservedStartupWorkspace){throw new Error(`Workspace ${JSON.stringify(reservedStartupWorkspace.raw)} is reserved for Conversations.`)}let workspaceRegistrationStore=deps.workspaceRegistrationStore;const explicitWorkspaceCount=workspaceInputs.length;if(workspaceRegistrationStore===void 0&&process.env["QWEN_SERVE_NO_PERSISTENT_REGISTRATION"]!=="1"){const{WorkspaceRegistrationStore}=await import("./workspace-registration-store-2NPD6U3B.js");workspaceRegistrationStore=new WorkspaceRegistrationStore(boundWorkspace)}if(workspaceRegistrationStore){try{const stored=await workspaceRegistrationStore.read();for(const storedWorkspace of stored.workspaces){const registrationId=workspaceRegistrationId(storedWorkspace);const displayName=stored.displayNames?.[registrationId];if(isReservedConversationWorkspace(storedWorkspace)){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: path is reserved for Conversations`);continue}let cwd;try{cwd=validateAndCanonicalizeWorkspace(storedWorkspace);readSshWorkspace(cwd)}catch(err){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: ${err instanceof Error?err.message:String(err)}`);continue}if(isReservedConversationWorkspace(cwd)){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: path is reserved for Conversations`);continue}const existingInput=workspaceInputs.find(workspace=>workspace.cwd===cwd);if(existingInput){existingInput.registrationIds.push(registrationId);existingInput.displayName??=displayName;continue}const nested=workspaceInputs.some(workspace=>isWithinRoot(cwd,workspace.cwd)||isWithinRoot(workspace.cwd,cwd));if(nested){writeStderrLine(`qwen serve: skipping persisted workspace registration ${JSON.stringify(storedWorkspace)}: path nests with an explicit or earlier restored workspace`);continue}workspaceInputs.push({raw:storedWorkspace,cwd,displayName,removable:true,registrationIds:[registrationId]})}}catch(err){writeStderrLine(`qwen serve: failed to read persisted workspace registrations: ${err instanceof Error?err.message:String(err)}; continuing with explicit workspaces only`)}}if(workspaceInputs.length>opts.maxRegisteredWorkspaces){throw new Error(`${explicitWorkspaceCount} explicit + ${workspaceInputs.length-explicitWorkspaceCount} restored workspaces exceed the configured limit of ${opts.maxRegisteredWorkspaces}. Restart with the previous capacity, forget registrations and reduce explicit --workspace values before lowering the limit. The registration store was not changed.`)}if(workspaceInputs.length>1&&deps.bridge){throw new Error("Injected bridge dependencies are only supported with a single workspace; multiple --workspace values require runQwenServe to construct one bridge per workspace.")}let contextFilenameForInit;let permissionPolicy;let permissionConsensusQuorum;let bootSettings;let sessionArtifactsPersistenceAvailable=true;try{bootSettings=deps.bootSettings??loadServeFastPathSettings(boundWorkspace);sessionArtifactsPersistenceAvailable=sessionArtifactsPersistenceAvailableFromSettings(bootSettings);contextFilenameForInit=extractContextFilename(bootSettings.context?.fileName);const policyConfig=bootSettings.policy??{};const resolved=validatePolicyConfig(policyConfig);permissionPolicy=resolved.permissionPolicy;permissionConsensusQuorum=resolved.permissionConsensusQuorum}catch(err){if(err instanceof InvalidPolicyConfigError||err instanceof InvalidExecutionSandboxConfigError){throw err}writeStderrLine(`qwen serve: could not read settings for context.fileName / policy.* / serve.channels / serve.tokenQr (${err instanceof Error?err.message:String(err)}); falling back to defaults. Restart with a valid settings.json to apply context.fileName / policy.* / serve.channels / serve.tokenQr overrides.`)}assertExecutionSandboxSupported(bootSettings??{},"serve / ACP / web terminals");const daemonLogBaseDir=await resolveDaemonLogBaseDirForRun({deps,bootSettings,boundWorkspace});const daemonLog=await initDaemonLogger({boundWorkspace,baseDir:daemonLogBaseDir});loggerLifecycle.initialized(daemonLog);let channelSelectionFromSettings=false;const channelSelectionFromFlag=opts.channelSelection!==void 0;const bootChannelOwnerHints=new Map;let channelOwnerHints=new Map;let channelStartupTolerantNames=new Set;const lateRestoredWorkspaces=new Set;let bootChannelClaimants=new Map;const channelRestoreFailures=createChannelRestoreFailures({isStale:__name(failure=>{if(channelWorkerManager?.committedChannelNames().includes(failure.channel)){return true}const registry=(runtimeApp??runtimeAppForCleanup)?.locals?.["workspaceRegistry"];return registry?!registry.getByWorkspaceCwd(failure.workspaceCwd):false},"isStale")});let channelHostingStoppedByOperator=false;const reportConfiguredChannelStartupFailure=__name(error=>{const message=sanitizeLogText(redactLogCredentials(error instanceof Error?error.message:String(error)),512);const detail=/[.!?]$/.test(message)?message:`${message}.`;writeStderrLine(`qwen serve: workspace serve.channels was not restored: ${detail} Continuing without channels.`);daemonLog.warn(`workspace serve.channels was not restored: ${detail} Continuing without channels`)},"reportConfiguredChannelStartupFailure");const reportStartupChannelDiagnostic=__name(diagnostic=>{const detail=sanitizeLogText(redactLogCredentials(diagnostic.message),512);if(diagnostic.code==="invalid_entry"){daemonLog.warn(detail,{workspaceCwd:diagnostic.workspaceCwd});return}if(diagnostic.code==="claimed_by_multiple_workspaces"){daemonLog.warn(detail,{code:diagnostic.code,workspaceCwd:diagnostic.workspaceCwd,...diagnostic.channel?{channel:diagnostic.channel}:{}});return}writeStderrLine(`qwen serve: workspace ${JSON.stringify(diagnostic.workspaceCwd)} serve.channels: ${detail}`);daemonLog.warn(`workspace serve.channels not fully restored: ${detail}`,{code:diagnostic.code,workspaceCwd:diagnostic.workspaceCwd,...diagnostic.channel?{channel:diagnostic.channel}:{}})},"reportStartupChannelDiagnostic");const startupChannelWorkspaces=workspaceInputs.filter(workspace=>!readSshWorkspace(workspace.cwd)).map((workspace,index)=>({workspaceCwd:workspace.cwd,primary:index===0}));const loadStartupChannelsFor=__name(workspaceCwd=>(workspaceCwd===boundWorkspace?bootSettings:loadServeFastPathSettings(workspaceCwd))?.serve?.channels,"loadStartupChannelsFor");const startupChannelsForWorkspace=__name(workspaceCwd=>{if(opts.profile==="hosted-harness")return[];const restored=resolveStartupChannelSelection({workspaces:[{workspaceCwd,primary:false}],loadStartupChannels:__name(cwd=>loadServeFastPathSettings(cwd)?.serve?.channels,"loadStartupChannels")});for(const diagnostic of restored.diagnostics){reportStartupChannelDiagnostic(diagnostic)}return restored.selection?.mode==="names"?restored.selection.names:[]},"startupChannelsForWorkspace");if(opts.profile!=="hosted-harness"&&!opts.channelSelection&&(bootSettings?.serve?.channels!==void 0||startupChannelWorkspaces.length>1)){try{const restored=resolveStartupChannelSelection({workspaces:startupChannelWorkspaces,loadStartupChannels:loadStartupChannelsFor});for(const diagnostic of restored.diagnostics){reportStartupChannelDiagnostic(diagnostic)}opts.channelSelection=restored.selection;if(opts.channelSelection){channelSelectionFromSettings=true;for(const[name,owner]of restored.ownerHints){bootChannelOwnerHints.set(name,owner)}channelOwnerHints=new Map(bootChannelOwnerHints);channelStartupTolerantNames=restored.tolerantNames;bootChannelClaimants=restored.claimants;channelRuntime=await ensureChannelRuntime();daemonLog.info("restoring channels from workspace serve.channels",{channels:channelSelectionNames(opts.channelSelection),workspaceCwd:boundWorkspace,...restored.ownerHints.size>0?{requestedByWorkspace:[...restored.ownerHints].map(([name,owner])=>`${name}@${owner}`).join(",")}:{}})}}catch(error){opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error)}}daemonLog.info("project memory scope resolved",{projectMemoryScope:resolvedMemoryProjectScope,projectMemoryScopeSource:memoryProjectScopeSource,projectMemoryScopeRaw:memoryProjectScopeValue});const loaderRejectionReporter=__name((source,freshKeys)=>{daemonLog.warn("rejected loader-affecting env keys; they were not applied",{source,rejectedKeys:freshKeys})},"loaderRejectionReporter");setLoaderKeyRejectionReporter(loaderRejectionReporter);loggerLifecycle.reporterInstalled(loaderRejectionReporter);if(scrubbedLoaderEnvKeys.length>0){daemonLog.info("scrubbed inherited loader env vars from the daemon process; session subprocesses will not inherit them",{removedKeys:scrubbedLoaderEnvKeys})}const fastPathRejectedLoaderKeys=consumeServeFastPathRejectedLoaderKeys();if(fastPathRejectedLoaderKeys.length>0){daemonLog.info("rejected loader-affecting env keys during serve fast-path boot; they were not applied to the daemon process",{rejectedKeys:fastPathRejectedLoaderKeys})}let loggerPublished=false;let loggerSignalOwned=false;writeStderrLine(`qwen serve: daemon log \u2192 ${daemonLog.getLogPath()||"(disabled)"}`);if(opts.mcpClientBudget!==void 0){if(!Number.isFinite(opts.mcpClientBudget)||!Number.isInteger(opts.mcpClientBudget)||opts.mcpClientBudget<=0){throw new TypeError(`Invalid mcpClientBudget: ${opts.mcpClientBudget}. Must be a positive integer.`)}}if(opts.mcpBudgetMode==="enforce"&&opts.mcpClientBudget===void 0){throw new Error('mcpBudgetMode="enforce" requires a positive mcpClientBudget. Pass mcpClientBudget=N, or set mcpBudgetMode to "warn" or "off".')}if(opts.promptDeadlineMs!==void 0){if(!isPositiveIntegerMs(opts.promptDeadlineMs)){throw new TypeError(`Invalid promptDeadlineMs: ${opts.promptDeadlineMs}. Must be a positive integer (milliseconds).`)}assertTimerDelayInRange("promptDeadlineMs",opts.promptDeadlineMs)}if(opts.maxSessions!==void 0){if(Number.isNaN(opts.maxSessions)||opts.maxSessions<0){throw new TypeError(`Invalid maxSessions: ${opts.maxSessions}. Must be a number >= 0 (0 / Infinity = unlimited).`)}}if(opts.maxTotalSessions!==void 0){if(!isNonNegativeIntegerOrInfinity(opts.maxTotalSessions)){throw new TypeError(`Invalid maxTotalSessions: ${opts.maxTotalSessions}. Must be a non-negative integer (0 / Infinity = unlimited).`)}}if(opts.maxPendingPromptsPerSession!==void 0){if(!isNonNegativeIntegerOrInfinity(opts.maxPendingPromptsPerSession)){throw new TypeError(`Invalid maxPendingPromptsPerSession: ${opts.maxPendingPromptsPerSession}. Must be a non-negative integer (0 / Infinity = unlimited).`)}}if(opts.eventRingSize!==void 0){if(!Number.isInteger(opts.eventRingSize)||opts.eventRingSize<1||opts.eventRingSize>MAX_EVENT_RING_SIZE){throw new TypeError(`Invalid eventRingSize: ${opts.eventRingSize}. Must be a positive integer in [1, ${MAX_EVENT_RING_SIZE}].`)}}if(opts.compactedReplayMaxBytes!==void 0){normalizeCompactedReplayMaxBytes(opts.compactedReplayMaxBytes)}if(opts.maxJournalEvents!==void 0){normalizeMaxJournalEvents(opts.maxJournalEvents)}if(opts.maxJournalBytes!==void 0){normalizeMaxJournalBytes(opts.maxJournalBytes)}if(opts.writerIdleTimeoutMs!==void 0){if(!isPositiveIntegerMs(opts.writerIdleTimeoutMs)){throw new TypeError(`Invalid writerIdleTimeoutMs: ${opts.writerIdleTimeoutMs}. Must be a positive integer (milliseconds).`)}}if(opts.channelIdleTimeoutMs!==void 0){if(!Number.isFinite(opts.channelIdleTimeoutMs)||!Number.isInteger(opts.channelIdleTimeoutMs)||opts.channelIdleTimeoutMs<0){throw new TypeError(`Invalid channelIdleTimeoutMs: ${opts.channelIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = immediate kill).`)}}if(opts.sessionReapIntervalMs!==void 0){if(!isNonNegativeIntegerMs(opts.sessionReapIntervalMs)){throw new TypeError(`Invalid sessionReapIntervalMs: ${opts.sessionReapIntervalMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`)}}if(opts.sessionIdleTimeoutMs!==void 0){if(!isNonNegativeIntegerMs(opts.sessionIdleTimeoutMs)){throw new TypeError(`Invalid sessionIdleTimeoutMs: ${opts.sessionIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`)}}if(opts.sessionPromptSettledCloseGraceMs!==void 0){if(!isNonNegativeIntegerMs(opts.sessionPromptSettledCloseGraceMs)){throw new TypeError(`Invalid sessionPromptSettledCloseGraceMs: ${opts.sessionPromptSettledCloseGraceMs}. Must be a non-negative integer (milliseconds, 0 = disabled).`)}}if(opts.initializeTimeoutMs!==void 0){if(!isPositiveIntegerMs(opts.initializeTimeoutMs)){throw new TypeError(`Invalid initializeTimeoutMs: ${opts.initializeTimeoutMs}. Must be a positive integer (milliseconds).`)}assertTimerDelayInRange("initializeTimeoutMs",opts.initializeTimeoutMs)}const sessionRestoreTimeoutMs=resolveSessionRestoreTimeoutMs(opts);opts.sessionRestoreTimeoutMs=sessionRestoreTimeoutMs;if(opts.permissionResponseTimeoutMs!==void 0){if(!Number.isFinite(opts.permissionResponseTimeoutMs)||!Number.isInteger(opts.permissionResponseTimeoutMs)||opts.permissionResponseTimeoutMs<0){throw new TypeError(`Invalid permissionResponseTimeoutMs: ${opts.permissionResponseTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = disabled / wait forever).`)}}const rawExternalToolGuard=opts.externalToolGuard;if(rawExternalToolGuard!==void 0&&(typeof rawExternalToolGuard!=="object"||rawExternalToolGuard===null||rawExternalToolGuard.mode!=="required")){throw new TypeError("Invalid externalToolGuard: omit it for off mode or set mode to 'required'.")}opts.maxTotalSessions??=deriveDefaultMaxTotalSessions(opts.maxSessions,workspaceInputs.length,opts.maxRegisteredWorkspaces);const inheritedNoPool=process.env["QWEN_SERVE_NO_MCP_POOL"]==="1";if(opts.mcpPoolActive===void 0&&inheritedNoPool){opts.mcpPoolActive=false}let externalToolGuardHandler;if(opts.externalToolGuard?.mode==="required"){if(deps.bridge){throw new Error("Required external tool guarding cannot be combined with an injected bridge.")}const{RequiredExternalToolGuard}=await import("./external-tool-guard-provider-G7SGGL2X.js");const provider=new RequiredExternalToolGuard({endpoint:opts.externalToolGuard.endpoint,token:opts.externalToolGuard.token,...opts.externalToolGuard.timeoutMs!==void 0?{timeoutMs:opts.externalToolGuard.timeoutMs}:{}});await provider.initialize();externalToolGuardHandler=provider.prepare;writeStderrLine("qwen serve: required external tool guard handshake succeeded.")}const{createDaemonToolGuard}=await import("./daemon-git-worktree-guard-ITU6NQIV.js");const daemonToolGuardHandler=createDaemonToolGuard(externalToolGuardHandler);const childEnvOverrides={QWEN_SERVE_MCP_CLIENT_BUDGET:opts.mcpClientBudget!==void 0?String(opts.mcpClientBudget):void 0,QWEN_SERVE_MCP_BUDGET_MODE:opts.mcpBudgetMode,QWEN_SERVE_CDP_TUNNEL_OVER_WS:opts.cdpTunnelOverWs?"1":void 0,[PRIVATE_CONVERSATIONS_RUNTIME_ENV]:void 0,[PRIVATE_EXTERNAL_TOOL_GUARD_ENV]:EXTERNAL_TOOL_GUARD_REQUIRED_VALUE,[PRIVATE_EXTERNAL_TOOL_GUARD_PROVIDER_ENV]:externalToolGuardHandler?EXTERNAL_TOOL_GUARD_PROVIDER_ATTACHED_VALUE:void 0};const cliVersionPromise=getCliVersion();let cliVersion;const diagnosticSink=__name((line,level)=>daemonLog.raw(line,level),"diagnosticSink");let actualPort=opts.port;let discoveryRecordPath;const removeDiscoveryRecord=__name(()=>{if(!discoveryRecordPath)return;discoveryRecordPath=void 0;try{removeDaemonDiscovery(actualPort,{expectedPid:process.pid})}catch{}},"removeDiscoveryRecord");const webShellDir=opts.serveWebShell===false?void 0:resolveWebShellDir();if(optsIn.requireWebShell&&!webShellDir){throw new Error("--open-with-auth requires built Web Shell assets.")}if(opts.serveWebShell!==false){if(!webShellDir){writeStderrLine("qwen serve: Web Shell assets not found; serving API only. Build the web-shell workspace (npm run build) or pass --no-web to silence this.")}else{writeStderrLine(`qwen serve: Web Shell UI served from ${webShellDir}`);if(!isLoopbackBind(opts.hostname)){writeStderrLine("qwen serve: Web Shell UI is served WITHOUT auth on a non-loopback bind (the static shell has no secrets; the API stays token-gated). Pass --no-web to disable the UI.");if(!opts.allowOrigins||opts.allowOrigins.length===0){writeStderrLine("qwen serve: same-origin Web Shell HTTP and WebSocket requests work without --allow-origin. Browsers reaching the daemon through a TLS-terminating proxy still need --allow-origin <origin>. A plain-HTTP intermediary that rewrites the Host header (nginx default proxy_set_header, k8s Ingress) needs --allow-origin <origin> for the origin the browser sees, unless it forwards Host verbatim; port translation alone (ssh -L, docker -p) is fine.")}}}}const webShellMounted=!!webShellDir;const serveAppLifecycle=new ServeAppLifecycleController;const restartForUpdate=deps.updateRestartArgv?createDaemonUpdateRestarter({argv:deps.updateRestartArgv,env:daemonRuntimeBaseEnv,token,externalToolGuardToken:optsIn.externalToolGuard?.token,getPort:__name(()=>actualPort,"getPort"),close:__name(()=>serveAppLifecycle.close(),"close")}):void 0;const liveDiscoveryStableBaseDir=path.resolve(deps.liveDiscoveryStableBaseDir??path.join(os2.homedir(),".qwen"));let resolveServeAppStartup;let rejectServeAppStartup;let serveAppStartupSettled=false;const serveAppStartupReady=new Promise((resolve3,reject)=>{resolveServeAppStartup=resolve3;rejectServeAppStartup=reject});void serveAppStartupReady.catch(()=>void 0);const markServeAppStartupReady=__name(()=>{if(serveAppStartupSettled)return;serveAppStartupSettled=true;resolveServeAppStartup()},"markServeAppStartupReady");const markServeAppStartupFailed=__name(error=>{if(serveAppStartupSettled)return;serveAppStartupSettled=true;rejectServeAppStartup(error)},"markServeAppStartupFailed");let runtimeApp;let runtimeAppForCleanup;let getWorkspaceRuntimeCoordinatorIfSupported;let bridgeRef=deps.bridge;let managedProcessRegistry;let managedChildHeapPolicy;const internalRuntimeBridgesForCleanup=[];let daemonEventLoopMonitor;let daemonMetricsSampler;let sessionPrRefreshTimer;let sessionPrRefreshGeneration=0;let runtimeStartupError;let runtimeStarting;let markRuntimeReady;let markRuntimeFailed;let runtimeStartupSettled=false;let startRuntimeAfterHealth;let startRuntimeForRequest;const deferRuntimeUntilFirstHealth=deps.resolveOnListen===true&&deps.deferRuntimeUntilFirstHealth===true;const runtimeReady=new Promise((resolve3,reject)=>{markRuntimeReady=resolve3;markRuntimeFailed=reject});void runtimeReady.catch(()=>{});const disposeDaemonEventLoopMonitor=__name(()=>{const eventLoopMonitor=daemonEventLoopMonitor;daemonEventLoopMonitor=void 0;const metricsSampler=daemonMetricsSampler;daemonMetricsSampler=void 0;const prRefreshTimer=sessionPrRefreshTimer;sessionPrRefreshTimer=void 0;sessionPrRefreshGeneration+=1;prRefreshTimer?.dispose();try{eventLoopMonitor?.dispose()}catch(err){daemonLog.warn(`event loop monitor dispose error: ${err instanceof Error?err.message:String(err)}`)}try{metricsSampler?.dispose()}catch(err){daemonLog.warn(`metrics sampler dispose error: ${err instanceof Error?err.message:String(err)}`)}},"disposeDaemonEventLoopMonitor");let channelWorkerManager;let channelWorkerManagerStarting;let channelControlDraining=false;let channelWorkspaceGroups;const channelWebhookEnvByWorkspace=new Map;let channelWebhookConfigVersion=0;let refreshChannelWebhookConfigs;let ensureChannelWorkerManager;const getChannelWebhookConfigSources=__name(()=>{const app2=runtimeApp??runtimeAppForCleanup;const registry=app2?.locals?.["workspaceRegistry"];return(channelWorkspaceGroups??[]).map(group=>{const env=registry?.getByWorkspaceCwd(group.workspaceCwd)?.env.effectiveEnv??channelWebhookEnvByWorkspace.get(group.workspaceCwd);return{workspaceCwd:group.workspaceCwd,...group.selection.mode==="names"?{channelNames:group.selection.names}:{},...env?{env}:{}}})},"getChannelWebhookConfigSources");const resolveChannelWebhookConfigSource=__name(channelName=>{const source=getChannelWebhookConfigSources().find(source2=>!source2.channelNames||source2.channelNames.includes(channelName));if(source)return source;const env=channelWebhookEnvByWorkspace.get(boundWorkspace);return{workspaceCwd:boundWorkspace,...env?{env}:{}}},"resolveChannelWebhookConfigSource");let closeServerAfterChannelWorkerStartupFailure=false;const getChannelWorkerSnapshot=__name(()=>channelWorkerManager?.primarySnapshot()??{enabled:false,state:"disabled",channels:[]},"getChannelWorkerSnapshot");const getChannelWorkerSnapshots=__name(()=>channelWorkerManager?.snapshots()??[],"getChannelWorkerSnapshots");const getChannelWorkerControl=__name(()=>channelWorkerManager?.state()??{enabled:false,selection:null,transition:"idle",workers:[]},"getChannelWorkerControl");const daemonDrainingError=__name(()=>Object.assign(new Error("Daemon is shutting down."),{code:"daemon_draining"}),"daemonDrainingError");const setChannelWorkerSelection=__name(async selection=>{if(channelControlDraining)throw daemonDrainingError();const manager=await ensureChannelWorkerManager?.();if(!manager)throw new Error("Channel worker manager is unavailable.");if(channelControlDraining){await manager.shutdown().catch(()=>void 0);throw daemonDrainingError()}const result=await manager.setSelection(selection);channelHostingStoppedByOperator=false;channelRestoreFailures.clearAll();return result},"setChannelWorkerSelection");const channelStartupMessages=__name(err=>{const startupFailures=err?.startupFailures;return new Map((Array.isArray(startupFailures)?startupFailures:[]).map(failure=>[failure.channel,failure.message]))},"channelStartupMessages");const lateRestoreFailures=__name((workspaceCwd,requested,err)=>{const committed=new Set(channelWorkerManager?.committedChannelNames());const reported=channelStartupMessages(err);const message=err instanceof Error?err.message:String(err);return requested.filter(channel=>!committed.has(channel)).map(channel=>({workspaceCwd,channel,message:reported.get(channel)??message}))},"lateRestoreFailures");const addChannelsToSelection=__name(async names=>{if(channelControlDraining)throw daemonDrainingError();const manager=await ensureChannelWorkerManager?.();if(!manager)throw new Error("Channel worker manager is unavailable.");if(channelControlDraining){await manager.shutdown().catch(()=>void 0);throw daemonDrainingError()}await manager.addChannels(names,{precondition:__name(()=>!channelHostingStoppedByOperator,"precondition")})},"addChannelsToSelection");const stopChannelWorker=__name(async()=>{if(channelControlDraining)throw daemonDrainingError();const manager=channelWorkerManager??await channelWorkerManagerStarting;if(channelControlDraining){await manager?.shutdown().catch(()=>void 0);throw daemonDrainingError()}if(!manager){return{changed:false,state:getChannelWorkerControl()}}const result=await manager.stopSelection();if(result.changed){channelHostingStoppedByOperator=true;channelRestoreFailures.clearAll()}return result},"stopChannelWorker");const reloadChannelWorker=__name(async()=>{if(channelControlDraining)throw daemonDrainingError();const manager=channelWorkerManager??await channelWorkerManagerStarting;if(channelControlDraining){await manager?.shutdown().catch(()=>void 0);throw daemonDrainingError()}if(!manager){return{enabled:false,state:"disabled",channels:[]}}try{return await manager.reload()}finally{writeChannelWorkerPidfile()}},"reloadChannelWorker");const isLiveWorker=__name(snapshot=>snapshot.state==="running"||snapshot.state==="starting","isLiveWorker");let channelWorkerPidfileUsesWorkers=workspaceInputs.length>1;const writeChannelWorkerPidfile=__name(()=>{if(runtimeStartupError!==void 0)return;if(!channelPidfileReserved||!channelServicePidfile)return;const snapshots=getChannelWorkerSnapshots();const workers=snapshots.map(snapshot=>({workspaceId:snapshot.workspaceId,workspaceCwd:snapshot.workspaceCwd,channels:snapshot.channels,...isLiveWorker(snapshot)&&snapshot.pid!==void 0?{workerPid:snapshot.pid}:{}}));const channels=[...new Set(snapshots.flatMap(snapshot=>snapshot.channels))];const primary=snapshots.find(snapshot=>snapshot.primary);if(workers.length>1||snapshots.some(snapshot=>!snapshot.primary)){channelWorkerPidfileUsesWorkers=true}const includeWorkers=channelWorkerPidfileUsesWorkers&&workers.length>0;try{channelServicePidfile.writeServeServiceInfo({channels,servePid:process.pid,...primary&&isLiveWorker(primary)&&primary.pid!==void 0?{workerPid:primary.pid}:{},...includeWorkers?{workers}:{}})}catch(err){daemonLog.warn(`failed to write channel worker pidfile metadata: ${err instanceof Error?err.message:String(err)}`)}},"writeChannelWorkerPidfile");const handleBridge=deps.bridge??createLazyBridgeProxy(()=>bridgeRef,()=>runtimeStartupError);const shutdownBridges=new WeakSet;const disposedRuntimeApps=new WeakSet;const stoppedRuntimeAppProducers=new WeakSet;const stoppedExtensionReconcilers=new WeakSet;const stoppedTrustPolicyMonitors=new WeakSet;const stopTrustPolicyMonitor=__name(app2=>{if(!app2||stoppedTrustPolicyMonitors.has(app2))return;stoppedTrustPolicyMonitors.add(app2);const stop=app2.locals?.["stopTrustPolicyMonitor"];try{stop?.()}catch(err){daemonLog.warn(`trust policy monitor dispose error: ${err instanceof Error?err.message:String(err)}`)}},"stopTrustPolicyMonitor");const stopExtensionReconciler=__name(app2=>{if(!app2||stoppedExtensionReconcilers.has(app2))return;stoppedExtensionReconcilers.add(app2);const stopExtensionGenerationReconciler=app2.locals?.["stopExtensionGenerationReconciler"];try{stopExtensionGenerationReconciler?.()}catch(err){daemonLog.warn(`extension generation reconciler dispose error: ${err instanceof Error?err.message:String(err)}`)}},"stopExtensionReconciler");const stopRuntimeAppProducers=__name(app2=>{if(!app2||stoppedRuntimeAppProducers.has(app2))return;stoppedRuntimeAppProducers.add(app2);const locals=app2.locals;const stopSafely=__name((name,stop)=>{try{stop?.()}catch(err){daemonLog.warn(`${name} dispose error: ${err instanceof Error?err.message:String(err)}`)}},"stopSafely");stopSafely("MCP App sandbox",locals.stopMcpAppSandbox);stopSafely("scheduled-task keepalive",locals.stopScheduledTaskKeepalive);stopSafely("workspace git state",locals.stopWorkspaceGitState);stopSafely("Live Host coordinator",locals.stopLiveCoordinator);stopSafely("Agent Host reconnect",locals.stopAgentHostRestore);stopSafely("web terminal registry",locals.stopWebTerminalRegistry);stopSafely("Hosted mount handbacks",locals.stopHostedMountHandbacks);stopTrustPolicyMonitor(app2);for(const stop of locals.subSessionStoppers??[]){stopSafely("sub-session launcher",stop)}stopExtensionReconciler(app2)},"stopRuntimeAppProducers");const disposeRuntimeAppResources=__name(app2=>{if(!app2||disposedRuntimeApps.has(app2))return;disposedRuntimeApps.add(app2);stopRuntimeAppProducers(app2);const deviceFlowRegistry=getDeviceFlowRegistry(app2);if(deviceFlowRegistry){try{deviceFlowRegistry.dispose()}catch(err){daemonLog.warn(`device-flow registry dispose error: ${err instanceof Error?err.message:String(err)}`)}}const localControlService=app2.locals?.["localControlService"];if(localControlService){void localControlService.dispose().catch(err=>{daemonLog.warn(`Local Control dispose error: ${err instanceof Error?err.message:String(err)}`)})}const acpHandle=app2.locals?.["acpHandle"];if(acpHandle?.dispose){try{acpHandle.dispose()}catch(err){daemonLog.warn(`ACP handle dispose error: ${err instanceof Error?err.message:String(err)}`)}}const rateLimiter=getRateLimiter(app2);if(rateLimiter){try{rateLimiter.setDraining(true);rateLimiter.dispose()}catch(err){daemonLog.warn(`rate limiter dispose error: ${err instanceof Error?err.message:String(err)}`)}}disposeDaemonEventLoopMonitor()},"disposeRuntimeAppResources");const getRuntimeBridgesForCleanup=__name(()=>{const appForCleanup=runtimeApp??runtimeAppForCleanup;const registry=appForCleanup?.locals?.["workspaceRegistry"];const bridges=[...registry?registry.listManaged().map(runtime=>runtime.bridge):[],...bridgeRef?[bridgeRef]:[],...internalRuntimeBridgesForCleanup];return[...new Set(bridges)]},"getRuntimeBridgesForCleanup");const buildRuntime=__name(async()=>{const[runtime,core,settingsRuntime,resolvedCliVersion,trustPolicy,workflowTrust]=await Promise.all([loadServeRuntimeModules(),loadCoreRuntime(),loadSettingsRuntimeModules(),cliVersionPromise,import("./daemon-trust-policy-IYD7NOGK.js"),import("./workflow-ancestor-trust-QII5KTUJ.js")]);getWorkspaceRuntimeCoordinatorIfSupported=runtime.getWorkspaceRuntimeCoordinatorIfSupported;cliVersion=resolvedCliVersion;settingsRuntime.environment.preResolveHomeEnvOverrides();const bootTrustSnapshot=await trustPolicy.readDaemonTrustPolicySnapshot();let latestTrustPolicySnapshot=bootTrustSnapshot;let publishedWorkflowTrustPolicy={publication:0,snapshot:bootTrustSnapshot};const bootWorkflowTrustAdmission={publication:0,snapshot:bootTrustSnapshot};const workflowTrustAdmissions=new WeakMap;workflowTrustAdmissions.set(bootTrustSnapshot,bootWorkflowTrustAdmission);const readWorkflowTrustAdmission=__name(async()=>{const admission=await workflowTrust.readWorkflowTrustAdmission(trustPolicy.readDaemonTrustPolicySnapshot,()=>publishedWorkflowTrustPolicy);workflowTrustAdmissions.set(admission.snapshot,admission);return admission},"readWorkflowTrustAdmission");const workflowTrustIdeScopeCwd=process.cwd();const bootPrimaryTrustDecision=trustPolicy.evaluateDaemonWorkspaceTrust(bootTrustSnapshot,boundWorkspace);const trustedWorkspace=deps.trustedWorkspace??bootPrimaryTrustDecision.targetTrusted;if(shouldPreheat&&!trustedWorkspace){shouldPreheat=false;startup.preheat.status="not_scheduled"}const workspaceTrustHotReloadAvailable=deps.trustedWorkspace===void 0&&deps.bridge===void 0&&deps.fsFactory===void 0;let managedScratchRoot;try{managedScratchRoot=prepareManagedScratchRoot(path.join(core.Storage.getGlobalQwenDir(),"scratch-workspaces"),workspaceInputs.map(workspace=>workspace.cwd))}catch(err){writeStderrLine(`qwen serve: managed scratch workspaces are unavailable: ${err instanceof Error?err.message:String(err)}`)}let runtimeBootSettings;try{runtimeBootSettings=settingsRuntime.settings.loadSettings(boundWorkspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trustedWorkspace,workspaceTrusted:trustedWorkspace})}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: could not read full settings for runtime startup (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}assertExecutionSandboxSupported(runtimeBootSettings?.merged??{},"serve workspace runtimes");if(deps.trustedWorkspace===void 0&&runtimeBootSettings&&!trustedWorkspace){daemonLog.warn("workspace file writes are disabled because the bound workspace is not trusted",{workspace:boundWorkspace})}const runtimeEnvSnapshot=runtimeBootSettings?settingsRuntime.environment.buildRuntimeEnvironment(runtimeBootSettings.merged,boundWorkspace,daemonRuntimeBaseEnv,trustedWorkspace):{effectiveEnv:{...daemonRuntimeBaseEnv},overlayKeys:Object.freeze([]),envFilePaths:Object.freeze([]),envFileReadFailed:false,envFileReadFailures:Object.freeze([])};const resolveSessionRuntimeBaseDir=__name((workspace,settings,effectiveEnv)=>{const resolveConfiguredPath=__name((configuredPath,relativeTo)=>{const expanded=configuredPath==="~"?os2.homedir():configuredPath.startsWith("~/")||configuredPath.startsWith("~\\")?path.join(os2.homedir(),...configuredPath.slice(2).split(/[/\\]+/).filter(Boolean)):configuredPath;return path.resolve(relativeTo,expanded)},"resolveConfiguredPath");const runtimeDir=effectiveEnv["QWEN_RUNTIME_DIR"];if(runtimeDir){return resolveConfiguredPath(runtimeDir,process.cwd())}const settingsDir=settings?.merged.advanced?.runtimeOutputDir;if(settingsDir){return resolveConfiguredPath(settingsDir,workspace)}const qwenHome=effectiveEnv["QWEN_HOME"];if(qwenHome){return resolveConfiguredPath(qwenHome,process.cwd())}const homeDir=os2.homedir();return homeDir?path.join(homeDir,".qwen"):path.join(os2.tmpdir(),".qwen")},"resolveSessionRuntimeBaseDir");const logRuntimeEnvFileReadFailures=__name((workspace,snapshot)=>{if(!snapshot.envFileReadFailed)return;const failedFiles=snapshot.envFileReadFailures??[];daemonLog.warn("one or more runtime env files could not be read",{workspace,...failedFiles.length>0?{failedFiles}:{}})},"logRuntimeEnvFileReadFailures");logRuntimeEnvFileReadFailures(boundWorkspace,runtimeEnvSnapshot);const primarySessionRuntimeBaseDir=resolveSessionRuntimeBaseDir(boundWorkspace,runtimeBootSettings,runtimeEnvSnapshot.effectiveEnv);const runtimeEffectiveEnv={...runtimeEnvSnapshot.effectiveEnv,QWEN_RUNTIME_DIR:primarySessionRuntimeBaseDir};const replaceRuntimeEffectiveEnv=__name(nextEnv=>{for(const key of Object.keys(runtimeEffectiveEnv)){delete runtimeEffectiveEnv[key]}Object.assign(runtimeEffectiveEnv,nextEnv);runtimeEffectiveEnv["QWEN_RUNTIME_DIR"]=primarySessionRuntimeBaseDir},"replaceRuntimeEffectiveEnv");const primaryRuntimeEnv={mode:"runtime-overlay",overlayKeys:[...runtimeEnvSnapshot.overlayKeys],effectiveEnv:runtimeEffectiveEnv,workflowsEnabledBySettings:runtimeBootSettings?.merged.tools?.workflowsEnabled===true,envFilePaths:[...runtimeEnvSnapshot.envFilePaths],envFileReadFailed:runtimeEnvSnapshot.envFileReadFailed,envFileReadFailures:[...runtimeEnvSnapshot.envFileReadFailures]};const daemonWorkspaceHash=core.hashDaemonWorkspace(boundWorkspace);let daemonTelemetrySettings;try{daemonTelemetrySettings=await core.resolveTelemetrySettings({env:process.env,settings:runtimeBootSettings?.merged.telemetry})}catch(err){if(err instanceof core.FatalConfigError){throw new core.FatalConfigError(`Invalid telemetry configuration: ${err.message}.`)}throw err}await core.initializeTelemetry(createDaemonTelemetryRuntimeConfig(daemonTelemetrySettings,resolvedCliVersion,`daemon:${process.pid}`,{otlpEndpoint:core.DEFAULT_OTLP_ENDPOINT,telemetryTarget:core.DEFAULT_TELEMETRY_TARGET}));core.initializeDaemonMetrics();daemonEventLoopMonitor?.dispose();daemonEventLoopMonitor=core.startEventLoopLagMonitor({onNewMaxStall:__name(maxMs=>{daemonLog.warn("daemon event loop stall detected",{maxMs})},"onNewMaxStall")});const currentDaemonEventLoopMonitor=daemonEventLoopMonitor;core.registerDaemonEventLoopLagGauge(()=>currentDaemonEventLoopMonitor.snapshot());const metricsRing=new DaemonMetricsRing({capacity:DAEMON_METRICS_CAPACITY});const pipeStats={inbound:{count:0,totalBytes:0,maxBytes:0},outbound:{count:0,totalBytes:0,maxBytes:0}};const promptQueueWaitStats={count:0,totalMs:0,maxMs:0,lastMs:null};const recordPipeMessage=__name((direction,bytes)=>{const stats=pipeStats[direction];stats.count+=1;stats.totalBytes+=bytes;stats.maxBytes=Math.max(stats.maxBytes,bytes);core.recordDaemonPipeMessage(direction,bytes);metricsRing.recordPipe(direction,bytes)},"recordPipeMessage");const observeLargePipeFrame=createLargePipeFrameObserver({daemonLog,emitTelemetryLog:core.emitDaemonLog});const warnAcpQueueSaturated=__name(info=>{daemonLog.warn("ACP NDJSON decoded queue saturated",{requiredBytes:info.requiredBytes,availableBytes:info.availableBytes,maxQueuedMessages:info.maxQueuedMessages,maxQueuedBytes:info.maxQueuedBytes,queueSaturationGraceMs:info.graceMs})},"warnAcpQueueSaturated");const recordPromptQueueWait=__name(durationMs=>{promptQueueWaitStats.count+=1;promptQueueWaitStats.totalMs+=durationMs;promptQueueWaitStats.maxMs=Math.max(promptQueueWaitStats.maxMs,durationMs);promptQueueWaitStats.lastMs=durationMs;core.recordDaemonPromptQueueWait(durationMs)},"recordPromptQueueWait");const createRuntimeBridgeTelemetry=__name(workspaceHash=>{const telemetry=core.createDaemonBridgeTelemetry();telemetry.metrics={sessionLifecycle(action){core.recordDaemonSessionLifecycle(action);core.emitDaemonLog(`Session ${action}.`,{"qwen-code.workspace.hash":workspaceHash},{eventName:`qwen-code.daemon.session.${action}`})},channelLifecycle(action,expected){core.recordDaemonChannelLifecycle(action,expected);core.emitDaemonLog(action==="spawn"?"ACP channel spawned.":`ACP channel exited (expected=${expected??true}).`,{...action==="exit"?{"qwen-code.daemon.channel.expected":expected??true}:{}},{eventName:`qwen-code.daemon.channel.${action}`,...expected===false&&action==="exit"?{severityNumber:13}:{}})},promptQueueWait(durationMs){recordPromptQueueWait(durationMs);metricsRing.recordPromptQueueWait(durationMs)},promptDuration(durationMs){core.recordDaemonPromptDuration(durationMs);metricsRing.recordPromptDuration(durationMs)},cancelled:core.recordDaemonCancel,tokenUsage(inputTokens,outputTokens,durationMs,apiErrors,apiRetries){metricsRing.recordTokens(inputTokens,outputTokens);if(typeof durationMs==="number"){metricsRing.recordLlmDuration(durationMs)}metricsRing.recordApiActivity(apiErrors??0,apiRetries??0)}};return telemetry},"createRuntimeBridgeTelemetry");const daemonTelemetry=createRuntimeBridgeTelemetry(daemonWorkspaceHash);const permissionAuditRing=new PermissionAuditRing;const permissionAuditPublisher=createPermissionAuditPublisher({ring:permissionAuditRing});const customIgnoreFiles=runtimeBootSettings?.merged.context?.fileFiltering?.customIgnoreFiles;const boundWorkspaces=runtime.resolveBoundWorkspacesFromIdeEnv(boundWorkspace,void 0,(workspace,index)=>{if(index===0)return true;const trustedSecondary=trustPolicy.evaluateDaemonWorkspaceTrust(bootTrustSnapshot,workspace).targetTrusted;if(!trustedSecondary){daemonLog.warn("excluding untrusted secondary workspace root from file-system access",{workspace})}return trustedSecondary});daemonLog.info("daemon workspace roots initialized",{primary:boundWorkspaces[0],secondary:boundWorkspaces.slice(1),ideEnvPresent:!!process.env["QWEN_CODE_IDE_WORKSPACE_PATH"]});const primaryGenerationGuard=runtime.createWorkspaceGenerationGuard();const primaryTrustMaterialization=JSON.stringify({trusted:trustedWorkspace,boundWorkspaces:[...boundWorkspaces].sort()});const sharedPathLocks=new PathMutexRegistry;const workspaceTrustOperationGate=new PathMutexRegistry;const runWorkspaceTrustOperation=__name(operation=>workspaceTrustOperationGate.runExclusive("runtime-topology",operation),"runWorkspaceTrustOperation");const idleReclaimerRef={};const processRegistry=new runtime.ProcessRegistry;managedProcessRegistry=processRegistry;const childHeapPolicy=opts.daemonMemoryBudget&&!deps.bridge?admissionPolicy??createChildHeapPolicy({budget:opts.daemonMemoryBudget,mode:opts.childHeapMode??"observe"}):void 0;managedChildHeapPolicy=childHeapPolicy;const fsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces,injected:deps.fsFactory,trusted:trustedWorkspace,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard:primaryGenerationGuard,...customIgnoreFiles!==void 0?{customIgnoreFiles}:{}});const routeFsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces:[boundWorkspace],trusted:trustedWorkspace,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard:primaryGenerationGuard,...customIgnoreFiles!==void 0?{customIgnoreFiles}:{}});const channelFactoryOptions={processRegistry,childHeapPolicy,reclaimIdleChild:__name(async signal=>{await idleReclaimerRef.current?.(daemonWorkspaceHash,signal)},"reclaimIdleChild"),pipeLimits:runtime.daemonAcpNdJsonLimits,sourceEnv:runtimeEffectiveEnv,onDiagnosticLine:diagnosticSink,pipeHooks:{onMessageSent:__name(bytes=>recordPipeMessage("outbound",bytes),"onMessageSent"),onMessageReceived:__name(bytes=>recordPipeMessage("inbound",bytes),"onMessageReceived"),onMessageObserved:__name(({direction,bytes,message})=>observeLargePipeFrame({direction:daemonPipeDirection(direction),bytes,message}),"onMessageObserved"),onQueueSaturated:warnAcpQueueSaturated},...acpChildExtraArgs(opts)?{extraArgs:acpChildExtraArgs(opts)}:{}};const channelFactory=runtime.createSpawnChannelFactory(channelFactoryOptions);const statusProvider=runtime.createDaemonStatusProvider({env:runtimeEffectiveEnv});const workspaceProvidersStatusProvider=runtime.createWorkspaceProvidersStatusProvider({env:runtimeEffectiveEnv,workspaceTrusted:trustedWorkspace});const workspaceSkillsStatusProvider=runtime.createWorkspaceSkillsStatusProvider({workspaceTrusted:trustedWorkspace});const clientMcpSenderRegistry=new ClientMcpSenderRegistry;const runtimeBridges=[];const runtimeEpochSources=new Map;const runtimeEpochSourceFor=__name(workspaceCwd=>{let source=runtimeEpochSources.get(workspaceCwd);if(!source){let epoch=0;source={current:__name(()=>epoch,"current"),allocate:__name(()=>++epoch,"allocate")};runtimeEpochSources.set(workspaceCwd,source)}return source},"runtimeEpochSourceFor");let mcpAuthenticationActive=false;const acquireMcpAuthentication=__name(()=>{if(mcpAuthenticationActive)return void 0;mcpAuthenticationActive=true;let released=false;return()=>{if(released)return;released=true;mcpAuthenticationActive=false}},"acquireMcpAuthentication");const totalSessionAdmission=runtime.createTotalSessionAdmissionController({maxTotalSessions:opts.maxTotalSessions,getBridges:__name(()=>runtimeBridges.length>0?runtimeBridges:bridgeRef?[bridgeRef]:[],"getBridges")});const sessionOwnerIndex=runtime.createWorkspaceSessionOwnerIndex();const workspaceRegistryForPersistence={current:void 0};const createRuntimeWorkflowAncestorTrustHandler=__name((workspaceCwd,getBridge,generationGuard,admissionPolicy2)=>workflowTrust.createWorkflowAncestorTrustHandler({generationGuard,admissionPolicy:admissionPolicy2,getPublished:__name(()=>publishedWorkflowTrustPolicy,"getPublished"),ideScopeCwd:workflowTrustIdeScopeCwd,isCurrentOwner:__name(sessionId=>{const registry=workspaceRegistryForPersistence.current;if(!registry)return false;const owner=registry.resolveLiveSessionOwner(sessionId);const entry=registry.getManagedEntryByWorkspaceCwd(workspaceCwd);return owner.kind==="found"&&owner.runtime.trusted&&owner.runtime.workspaceCwd===workspaceCwd&&owner.runtime.bridge===getBridge()&&entry?.state==="active"&&entry.current?.runtime===owner.runtime&&entry.current.guard===generationGuard},"isCurrentOwner")}),"createRuntimeWorkflowAncestorTrustHandler");const isWorkspaceTrustedForPersistence=__name(workspace=>workspaceRegistryForPersistence.current?.getByWorkspaceCwd(workspace)?.trusted??(workspaceRegistryForPersistence.current===void 0&&workspace===boundWorkspace&&trustedWorkspace),"isWorkspaceTrustedForPersistence");const loadSettingsForPersistence=__name(workspace=>{const trusted=isWorkspaceTrustedForPersistence(workspace);return settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted})},"loadSettingsForPersistence");const resolveSkillToggleIdentities=__name(async(workspace,skillNames)=>{let skills;try{const workspaceRuntime=workspaceRegistryForPersistence.current?.getByWorkspaceCwd(workspace);const status=await workspaceRuntime?.workspaceService.getWorkspaceSkillsStatus({route:"skill settings persistence",workspaceCwd:workspace});if(status?.initialized)skills=status.skills}catch{}const skillsByName=new Map(skills?.map(skill=>[skill.name.trim().toLowerCase(),skill]));return skillNames.map(skillName=>{const skill=skillsByName.get(skillName.trim().toLowerCase());if(!skill){const prefixEnd=skillName.indexOf(":");return{name:skillName,...prefixEnd>0?{authoredName:skillName.slice(prefixEnd+1)}:{}}}if(skill.level!=="extension"||!skill.extensionName){return{name:skillName}}return{name:skillName,authoredName:skillName.slice(skill.extensionName.length+1)}})},"resolveSkillToggleIdentities");const persistDisabledToolsFn=__name((workspace,toolName,enabled,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=loadSettingsForPersistence(workspace);const wsScope=fresh.forScope(WORKSPACE_SETTING_SCOPE).settings;const wsDisabled=wsScope.tools?.disabled;const current=Array.isArray(wsDisabled)?wsDisabled.filter(v=>typeof v==="string"):[];const next=new Set(current);if(enabled)next.delete(toolName);else next.add(toolName);assertGenerationOpen?.();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.disabled",[...next].sort(),assertGenerationOpen)}),"persistDisabledToolsFn");const persistDisabledSkillsFn=__name((workspace,skillName,enabled,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const{skillSettingStrings,skillToggleBlockForName,updateWorkspaceSkillSettingLists}=await import("./skill-settings-TSZO3X6N.js");const fresh=loadSettingsForPersistence(workspace);const workspaceDisabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"disabled");const workspaceEnabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"enabled");if(enabled){const[skillIdentity]=await resolveSkillToggleIdentities(workspace,[skillName]);const block=skillToggleBlockForName(fresh,skillIdentity);if(block){return{changed:false,disabled:workspaceDisabled,block}}}const next=updateWorkspaceSkillSettingLists({disabled:workspaceDisabled,enabled:workspaceEnabled},skillName,enabled);const settingsChanges=[];if(JSON.stringify(next.disabled)!==JSON.stringify(workspaceDisabled)){settingsChanges.push({key:"skills.disabled",value:next.disabled.length>0?next.disabled:void 0})}if(JSON.stringify(next.enabled)!==JSON.stringify(workspaceEnabled)){settingsChanges.push({key:"skills.enabled",value:next.enabled.length>0?next.enabled:void 0})}if(settingsChanges.length===0){return{changed:false,disabled:workspaceDisabled}}assertGenerationOpen?.();fresh.setValues(settingsChanges.map(change=>({scope:WORKSPACE_SETTING_SCOPE,...change})),void 0,assertGenerationOpen);return{changed:true,disabled:next.disabled,settingsChanges}}),"persistDisabledSkillsFn");const persistDisabledSkillsBatchFn=__name((workspace,skillNames,enabled,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const{skillSettingStrings,skillToggleBlockForName,updateWorkspaceSkillSettingLists}=await import("./skill-settings-TSZO3X6N.js");const fresh=loadSettingsForPersistence(workspace);const initialDisabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"disabled");const initialEnabled=skillSettingStrings(fresh,WORKSPACE_SETTING_SCOPE,"enabled");const skillIdentities=enabled?await resolveSkillToggleIdentities(workspace,skillNames):skillNames.map(name=>({name}));let next={disabled:initialDisabled,enabled:initialEnabled};const outcomes=skillNames.map(skillName=>({skillName,changed:false}));let pending=skillNames.map((_,index)=>index);for(let pass=0;pass<skillNames.length;pass+=1){const refused=[];let listChanged=false;for(const index of pending){const skillName=skillNames[index];if(enabled){const block=skillToggleBlockForName(fresh,skillIdentities[index]);if(block&&!(block.scope==="Workspace"&&block.list==="disabled"&&!next.disabled.some(name=>name.trim().toLowerCase()===block.entry))){refused.push(index);continue}}const updated=updateWorkspaceSkillSettingLists(next,skillName,enabled);const changed=JSON.stringify(updated.disabled)!==JSON.stringify(next.disabled)||JSON.stringify(updated.enabled)!==JSON.stringify(next.enabled);next=updated;outcomes[index]={skillName,changed};listChanged||=changed}pending=refused;if(pending.length===0||!listChanged)break}const settingsChanges=[];if(JSON.stringify(next.disabled)!==JSON.stringify(initialDisabled)){settingsChanges.push({key:"skills.disabled",value:next.disabled.length>0?next.disabled:void 0})}if(JSON.stringify(next.enabled)!==JSON.stringify(initialEnabled)){settingsChanges.push({key:"skills.enabled",value:next.enabled.length>0?next.enabled:void 0})}if(settingsChanges.length>0){assertGenerationOpen?.();fresh.setValues(settingsChanges.map(change=>({scope:WORKSPACE_SETTING_SCOPE,...change})),void 0,assertGenerationOpen)}return{outcomes,settingsChanges}}),"persistDisabledSkillsBatchFn");const persistSettingFn=__name((workspace,scope,key,value,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=loadSettingsForPersistence(workspace);assertGenerationOpen?.();fresh.setValue(scope,key,value,assertGenerationOpen);return fresh}),"persistSettingFn");const persistSettingsFn=__name((workspace,writes,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=loadSettingsForPersistence(workspace);const writesByScope=new Map;for(const write of writes){writesByScope.set(write.scope,(writesByScope.get(write.scope)??0)+1)}const committedScopes=new Set;let committed=0;try{assertGenerationOpen?.();fresh.setValues(writes,scope=>{committedScopes.add(scope);committed+=writesByScope.get(scope)??0},assertGenerationOpen)}catch(err){const failedWrite=writes.find(write=>!committedScopes.has(write.scope))??writes[committed];const message=`persistSettings partial failure (workspace=${workspace}, committed=${committed}/${writes.length}, failedKey=${failedWrite?.key??"<unknown>"}, failedScope=${failedWrite?.scope??"<unknown>"}): ${err instanceof Error?err.message:String(err)}`;writeStderrLine(`qwen serve: ${message}`);throw new runtime.WorkspaceSettingsPartialPersistError(message,writes.filter(write=>committedScopes.has(write.scope)),err)}}),"persistSettingsFn");const[{createSubSessionLauncher},scheduledTaskRoutes]=await Promise.all([import("./create-sub-session-G26337FT.js"),import("./scheduled-tasks-Q6V7D6K6.js")]);const{sessionAttachmentsRoots}=await import("./session-attachments-root-NWG7JOMN.js");const createCurrentSessionScheduledTaskHandler=__name((workspaceCwd,runtimeBaseDir,getBridge,assertGenerationOpen)=>async({callerSessionId,cron,prompt,recurring,assertCallerPromptActive})=>{const targetBridge=getBridge();if(!targetBridge){throw new Error("Current-session scheduling is unavailable while the workspace runtime is starting.")}const task=await scheduledTaskRoutes.createScheduledTaskWithExistingSession({workspaceCwd,runtimeBaseDir,bridge:targetBridge,assertGenerationOpen,resolveLiveSessionOwner:__name(sessionId=>workspaceRegistryForPersistence.current===void 0?{kind:"unavailable"}:workspaceRegistryForPersistence.current.resolveLiveSessionOwner(sessionId),"resolveLiveSessionOwner")},{sessionId:callerSessionId,cron,prompt,recurring},{source:"cron-tool",assertCallerPromptActive});return{id:task.id,cron:task.cron}},"createCurrentSessionScheduledTaskHandler");const subSessionLauncher=createSubSessionLauncher({getBridge:__name(()=>bridgeRef,"getBridge"),boundWorkspace,runtimeBaseDir:primarySessionRuntimeBaseDir,...subSessionConcurrencyCapsFromSettings(runtimeBootSettings?.merged.serve??{})});const attachmentsRoots=sessionAttachmentsRoots(boundWorkspace,primarySessionRuntimeBaseDir);const bridge=deps.bridge??runtime.createAcpSessionBridge({onWorkflowAncestorTrust:createRuntimeWorkflowAncestorTrustHandler(boundWorkspace,()=>bridgeRef,primaryGenerationGuard,bootWorkflowTrustAdmission),artifactSnapshotRuntimeBaseDir:primarySessionRuntimeBaseDir,sessionAttachmentsRoot:attachmentsRoots.root,sessionAttachmentsFallbackRoot:attachmentsRoots.fallback,clientMcpSender:clientMcpSenderRegistry.lookup,onCreateSubSession:subSessionLauncher.launch,onCreateCurrentSessionScheduledTask:createCurrentSessionScheduledTaskHandler(boundWorkspace,primarySessionRuntimeBaseDir,()=>bridgeRef,()=>primaryGenerationGuard.assertOpen()),onChannelDelivery:createBoundChannelDeliveryHandler(boundWorkspace,()=>channelWorkerManager,channelDeliveryAuthorizations,daemonLog,channelDeliveryDiagnosticRedaction),maxSessions:opts.maxSessions,...opts.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},freshSessionAdmission:totalSessionAdmission.admit,sessionLifecycle:__name(event=>{if(event.type==="registered"&&primaryGenerationGuard.closed){return}sessionOwnerIndex.handleBridgeSessionLifecycle(event)},"sessionLifecycle"),...opts.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:opts.maxPendingPromptsPerSession}:{},...opts.eventRingSize!==void 0?{eventRingSize:opts.eventRingSize}:{},...opts.compactedReplayMaxBytes!==void 0?{compactedReplayMaxBytes:opts.compactedReplayMaxBytes}:{},...opts.maxJournalEvents!==void 0?{maxJournalEvents:opts.maxJournalEvents}:{},...opts.maxJournalBytes!==void 0?{maxJournalBytes:opts.maxJournalBytes}:{},...journalGrowthPoolBytes!==void 0?{journalGrowthPoolBytes,journalGrowthSessionLimits,registerJournalGrowthSessionLimits}:{},...opts.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:opts.channelIdleTimeoutMs}:{},...opts.initializeTimeoutMs!==void 0?{initializeTimeoutMs:opts.initializeTimeoutMs}:{},sessionRestoreTimeoutMs,...opts.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:opts.sessionReapIntervalMs}:{},...opts.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:opts.sessionIdleTimeoutMs}:{},...opts.sessionPromptSettledCloseGraceMs!==void 0?{sessionPromptSettledCloseGraceMs:opts.sessionPromptSettledCloseGraceMs}:{},...opts.permissionResponseTimeoutMs!==void 0?{permissionResponseTimeoutMs:opts.permissionResponseTimeoutMs}:{},boundWorkspace,runtimeEpochSource:runtimeEpochSourceFor(boundWorkspace),acquireMcpAuthentication,promptLedger:runtime.createPromptLedgerSink(boundWorkspace,primarySessionRuntimeBaseDir),sessionShellCommandEnabled,childEnvOverrides,...opts.experimentalPairedEngines?{executionEngines:runtime.createPairedExecutionEngines({legacy:channelFactory,managed:runtime.createManagedExecutionEngine({legacy:channelFactoryOptions,host:{workspaceCwd:boundWorkspace,workspaceTrusted:trustedWorkspace,environment:runtimeEffectiveEnv,forwardedArgs:acpChildExtraArgs(opts)??[],hasLiveMcpServers:__name(()=>bridgeRef?.hasRuntimeMcpServers()===true,"hasLiveMcpServers")}}),runtimeBaseDir:primarySessionRuntimeBaseDir})}:{channelFactory},externalToolGuard:daemonToolGuardHandler,onDiagnosticLine:diagnosticSink,telemetry:daemonTelemetry,...permissionPolicy!==void 0?{permissionPolicy}:{},...permissionConsensusQuorum!==void 0?{permissionConsensusQuorum}:{},permissionAudit:permissionAuditPublisher,statusProvider,delegateReadTextFileToClient:false,fileSystem:createBridgeFileSystemAdapter(fsFactory,{allowSameHostToolWritesOutsideWorkspace:deps.fsFactory===void 0}),persistApprovalMode:__name((workspace,mode)=>withSettingsLock(workspace,async()=>{primaryGenerationGuard.assertOpen();if(!trustedWorkspace){throw new Error("Cannot persist approval mode for an untrusted workspace.")}const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,workspaceTrusted:trustedWorkspace});primaryGenerationGuard.assertOpen();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.approvalMode",mode,()=>primaryGenerationGuard.assertOpen())}),"persistApprovalMode")});if(!deps.bridge){bridgeRef=bridge;internalRuntimeBridgesForCleanup.push(bridge)}runtimeBridges.push(bridge);let invalidatePrimaryServeFeaturesCache=__name(()=>{},"invalidatePrimaryServeFeaturesCache");const reloadPrimaryDaemonEnv=__name((workspace,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trustedWorkspace,workspaceTrusted:trustedWorkspace});assertGenerationOpen?.();let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,trustedWorkspace)}catch(err){const fallbackReason=err instanceof Error?err.message:String(err);primaryRuntimeEnv.fallbackReason=fallbackReason;daemonLog.warn("failed to rebuild runtime env snapshot before daemon env reload; preserving previous runtime env",{error:fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}const result=settingsRuntime.settings.reloadEnvironment(fresh.merged,workspace,trustedWorkspace,{failClosedOnEnvFileReadError:true});if(result.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}replaceRuntimeEffectiveEnv(refreshedRuntimeEnv.effectiveEnv);primaryRuntimeEnv.workflowsEnabledBySettings=fresh.merged.tools?.workflowsEnabled===true;delete primaryRuntimeEnv.fallbackReason;primaryRuntimeEnv.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;primaryRuntimeEnv.envFileReadFailures.splice(0,primaryRuntimeEnv.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);primaryRuntimeEnv.overlayKeys.splice(0,primaryRuntimeEnv.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);primaryRuntimeEnv.envFilePaths.splice(0,primaryRuntimeEnv.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);return{...result,runtimeEnvironmentApplied:true}}),"reloadPrimaryDaemonEnv");const workspaceService=runtime.createDaemonWorkspaceService({boundWorkspace,isWorkspaceTrusted:__name(()=>trustedWorkspace,"isWorkspaceTrusted"),assertGenerationOpen:__name(()=>primaryGenerationGuard.assertOpen(),"assertGenerationOpen"),contextFilename:contextFilenameForInit??"QWEN.md",statusProvider,workspaceProvidersStatusProvider,workspaceSkillsStatusProvider,skillInstallEnv:runtimeEffectiveEnv,voiceEnv:runtimeEffectiveEnv,isChannelLive:__name(()=>bridge.isWorkspaceControlLive?.()??bridge.isChannelLive(),"isChannelLive"),persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,preheatAcpChild:__name(()=>bridge.preheat(),"preheatAcpChild"),reloadDaemonEnv:reloadPrimaryDaemonEnv,reloadModelProvidersDaemonEnv:__name((workspace,assertGenerationOpen)=>reloadRuntimeOverlaySnapshotForModelProviders(workspace,trustedWorkspace,{metadata:primaryRuntimeEnv,replace:replaceRuntimeEffectiveEnv},assertGenerationOpen),"reloadModelProvidersDaemonEnv"),queryWorkspaceStatus:__name((method,idle)=>bridge.queryWorkspaceStatus(method,idle),"queryWorkspaceStatus"),invokeWorkspaceCommand:__name((method,params,invokeOpts)=>bridge.invokeWorkspaceCommand(method,params,invokeOpts),"invokeWorkspaceCommand"),refreshExtensionsForAllSessions:__name(sessionIds=>sessionIds===void 0?bridge.refreshExtensionsForAllSessions():bridge.refreshExtensionsForAllSessions(void 0,{sessionIds}),"refreshExtensionsForAllSessions"),publishWorkspaceEvent:__name(event=>{if(event.type==="settings_changed"||event.type==="settings_reloaded"){invalidatePrimaryServeFeaturesCache()}bridge.publishWorkspaceEvent(event)},"publishWorkspaceEvent")});const workspaceRuntimes=[{workspaceId:daemonWorkspaceHash,workspaceCwd:boundWorkspace,sessionRuntimeBaseDir:primarySessionRuntimeBaseDir,...workspaceInputs[0]?.displayName?{displayName:workspaceInputs[0].displayName}:{},primary:true,trusted:trustedWorkspace,removable:false,registrationIds:workspaceInputs[0]?.registrationIds??[],env:primaryRuntimeEnv,bridge,workspaceService,routeFileSystemFactory:routeFsFactory,clientMcpSenderRegistry,generationGuard:primaryGenerationGuard,trustMaterialization:primaryTrustMaterialization}];if(trustedWorkspace){await recoverBranchWorktreePreparations({workspaceCwd:boundWorkspace,sessionService:await createBranchRecoverySessionService(workspaceRuntimes[0]),assertGenerationOpen:__name(()=>primaryGenerationGuard.assertOpen(),"assertGenerationOpen"),isWorktreeOccupied:__name(worktreePath=>bridgeHasLiveSessionWithin(bridge,boundWorkspace,worktreePath),"isWorktreeOccupied"),warn:__name((message,fields)=>daemonLog.warn(message,fields),"warn")}).catch(error=>{daemonLog.warn("branch worktree recovery sweep failed",{workspace:boundWorkspace,error:error instanceof Error?error.message:String(error)})})}const createRuntimeEnvMetadata=__name((workspace,settings,trusted)=>{const snapshot=settings?settingsRuntime.environment.buildRuntimeEnvironment(settings.merged,workspace,daemonRuntimeBaseEnv,trusted):{effectiveEnv:{...daemonRuntimeBaseEnv},overlayKeys:Object.freeze([]),envFilePaths:Object.freeze([]),envFileReadFailed:false,envFileReadFailures:Object.freeze([])};logRuntimeEnvFileReadFailures(workspace,snapshot);const sessionRuntimeBaseDir=resolveSessionRuntimeBaseDir(workspace,settings,snapshot.effectiveEnv);const effectiveEnv={...snapshot.effectiveEnv,QWEN_RUNTIME_DIR:sessionRuntimeBaseDir};const metadata={mode:"runtime-overlay",overlayKeys:[...snapshot.overlayKeys],effectiveEnv,workflowsEnabledBySettings:settings?.merged.tools?.workflowsEnabled===true,envFilePaths:[...snapshot.envFilePaths],envFileReadFailed:snapshot.envFileReadFailed,envFileReadFailures:[...snapshot.envFileReadFailures]};return{metadata,effectiveEnv,sessionRuntimeBaseDir,replace(nextEnv){for(const key of Object.keys(effectiveEnv)){delete effectiveEnv[key]}Object.assign(effectiveEnv,nextEnv);effectiveEnv["QWEN_RUNTIME_DIR"]=sessionRuntimeBaseDir}}},"createRuntimeEnvMetadata");const reloadRuntimeOverlaySnapshotForModelProviders=__name((workspace,trusted,env,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted});assertGenerationOpen?.();let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,trusted)}catch(err){env.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to rebuild runtime overlay for model-provider reload; preserving previous runtime env",{workspace,error:env.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}assertGenerationOpen?.();try{env.replace(refreshedRuntimeEnv.effectiveEnv);env.metadata.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;env.metadata.envFileReadFailures.splice(0,env.metadata.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);env.metadata.overlayKeys.splice(0,env.metadata.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);env.metadata.envFilePaths.splice(0,env.metadata.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);delete env.metadata.fallbackReason;return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:true}}catch(err){env.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to apply runtime overlay for model-provider reload; preserving previous runtime env",{workspace,error:env.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}}),"reloadRuntimeOverlaySnapshotForModelProviders");const readLiveConversationScheduledTasks=__name(async()=>{if(!fs.existsSync(liveConversationWorkspace.rootPath))return[];const{canonicalRoot}=await liveConversationWorkspace.revalidate();let settings;try{settings=settingsRuntime.settings.loadSettings(canonicalRoot,{skipLoadEnvironment:true,skipWorkspaceSettings:false,workspaceTrusted:true})}catch(err){writeStderrLine(`qwen serve: could not read full settings for Conversations (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}const env=createRuntimeEnvMetadata(canonicalRoot,settings,true);return core.Storage.runWithResolvedRuntimeBaseDir(env.sessionRuntimeBaseDir,()=>core.readCronTasks(canonicalRoot))},"readLiveConversationScheduledTasks");const subSessionStoppers=[];const subSessionStoppersByRuntime=new WeakMap;const runtimeCleanupPromises=new WeakMap;const removeArrayValue=__name((values,value)=>{const index=values.indexOf(value);if(index>=0)values.splice(index,1)},"removeArrayValue");for(const workspaceInput of workspaceInputs.slice(1)){assertExecutionSandboxSupported(readOperatorSandboxSettings(),"serve workspace runtimes");const secondaryDecision=trustPolicy.evaluateDaemonWorkspaceTrust(bootTrustSnapshot,workspaceInput.cwd);const secondaryTrusted=secondaryDecision.targetTrusted;let secondarySettings;try{secondarySettings=settingsRuntime.settings.loadSettings(workspaceInput.cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!secondaryTrusted,workspaceTrusted:secondaryTrusted})}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: could not read full settings for secondary workspace ${workspaceInput.cwd} (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}assertExecutionSandboxSupported(secondarySettings?.merged??{},"serve workspace runtimes");if(!secondaryTrusted){daemonLog.warn("secondary workspace is not trusted",{workspace:workspaceInput.cwd,trustSettingsAvailable:secondarySettings!==void 0})}const secondaryEnv=createRuntimeEnvMetadata(workspaceInput.cwd,secondarySettings,secondaryTrusted);const secondaryCustomIgnoreFiles=secondarySettings?.merged.context?.fileFiltering?.customIgnoreFiles;const secondaryContextFilename=extractContextFilename(secondarySettings?.merged.context?.fileName)??contextFilenameForInit??"QWEN.md";const secondaryWorkspaceHash=core.hashDaemonWorkspace(workspaceInput.cwd);const secondaryGenerationGuard=runtime.createWorkspaceGenerationGuard();const secondaryStatusProvider=runtime.createDaemonStatusProvider({env:secondaryEnv.effectiveEnv});const secondaryBridgeFsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces:[workspaceInput.cwd],trusted:secondaryTrusted,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard:secondaryGenerationGuard,...secondaryCustomIgnoreFiles!==void 0?{customIgnoreFiles:secondaryCustomIgnoreFiles}:{}});const secondaryChannelFactoryOptions={processRegistry,childHeapPolicy,reclaimIdleChild:__name(async signal=>{await idleReclaimerRef.current?.(secondaryWorkspaceHash,signal)},"reclaimIdleChild"),pipeLimits:runtime.daemonAcpNdJsonLimits,sourceEnv:secondaryEnv.effectiveEnv,onDiagnosticLine:diagnosticSink,pipeHooks:{onMessageSent:__name(bytes=>recordPipeMessage("outbound",bytes),"onMessageSent"),onMessageReceived:__name(bytes=>recordPipeMessage("inbound",bytes),"onMessageReceived"),onMessageObserved:__name(({direction,bytes,message})=>observeLargePipeFrame({direction:daemonPipeDirection(direction),bytes,message}),"onMessageObserved"),onQueueSaturated:warnAcpQueueSaturated},...acpChildExtraArgs(opts)?{extraArgs:acpChildExtraArgs(opts)}:{}};const secondaryChannelFactory=runtime.createSpawnChannelFactory(secondaryChannelFactoryOptions);const secondaryClientMcpSenderRegistry=new ClientMcpSenderRegistry;let secondaryBridgeRef;const secondarySubSessionLauncher=createSubSessionLauncher({getBridge:__name(()=>secondaryBridgeRef,"getBridge"),boundWorkspace:workspaceInput.cwd,runtimeBaseDir:secondaryEnv.sessionRuntimeBaseDir,...subSessionConcurrencyCapsFromSettings(secondarySettings?.merged.serve??{})});const secondaryAttachmentsRoots=sessionAttachmentsRoots(workspaceInput.cwd,secondaryEnv.sessionRuntimeBaseDir);const secondaryBridge=runtime.createAcpSessionBridge({onWorkflowAncestorTrust:createRuntimeWorkflowAncestorTrustHandler(workspaceInput.cwd,()=>secondaryBridgeRef,secondaryGenerationGuard,bootWorkflowTrustAdmission),artifactSnapshotRuntimeBaseDir:secondaryEnv.sessionRuntimeBaseDir,sessionAttachmentsRoot:secondaryAttachmentsRoots.root,sessionAttachmentsFallbackRoot:secondaryAttachmentsRoots.fallback,clientMcpSender:secondaryClientMcpSenderRegistry.lookup,onCreateSubSession:secondarySubSessionLauncher.launch,onCreateCurrentSessionScheduledTask:createCurrentSessionScheduledTaskHandler(workspaceInput.cwd,secondaryEnv.sessionRuntimeBaseDir,()=>secondaryBridgeRef,()=>secondaryGenerationGuard.assertOpen()),onChannelDelivery:createBoundChannelDeliveryHandler(workspaceInput.cwd,()=>channelWorkerManager,channelDeliveryAuthorizations,daemonLog,channelDeliveryDiagnosticRedaction),maxSessions:opts.maxSessions,...opts.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},freshSessionAdmission:totalSessionAdmission.admit,sessionLifecycle:__name(event=>{if(event.type==="registered"&&secondaryGenerationGuard.closed){return}sessionOwnerIndex.handleBridgeSessionLifecycle(event)},"sessionLifecycle"),...opts.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:opts.maxPendingPromptsPerSession}:{},...opts.eventRingSize!==void 0?{eventRingSize:opts.eventRingSize}:{},...opts.compactedReplayMaxBytes!==void 0?{compactedReplayMaxBytes:opts.compactedReplayMaxBytes}:{},...opts.maxJournalEvents!==void 0?{maxJournalEvents:opts.maxJournalEvents}:{},...opts.maxJournalBytes!==void 0?{maxJournalBytes:opts.maxJournalBytes}:{},...journalGrowthPoolBytes!==void 0?{journalGrowthPoolBytes,journalGrowthSessionLimits,registerJournalGrowthSessionLimits}:{},...opts.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:opts.channelIdleTimeoutMs}:{},...opts.initializeTimeoutMs!==void 0?{initializeTimeoutMs:opts.initializeTimeoutMs}:{},sessionRestoreTimeoutMs,...opts.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:opts.sessionReapIntervalMs}:{},...opts.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:opts.sessionIdleTimeoutMs}:{},...opts.sessionPromptSettledCloseGraceMs!==void 0?{sessionPromptSettledCloseGraceMs:opts.sessionPromptSettledCloseGraceMs}:{},...opts.permissionResponseTimeoutMs!==void 0?{permissionResponseTimeoutMs:opts.permissionResponseTimeoutMs}:{},boundWorkspace:workspaceInput.cwd,runtimeEpochSource:runtimeEpochSourceFor(workspaceInput.cwd),acquireMcpAuthentication,promptLedger:runtime.createPromptLedgerSink(workspaceInput.cwd,secondaryEnv.sessionRuntimeBaseDir),sessionShellCommandEnabled,childEnvOverrides,...opts.experimentalPairedEngines?{executionEngines:runtime.createPairedExecutionEngines({legacy:secondaryChannelFactory,managed:runtime.createManagedExecutionEngine({legacy:secondaryChannelFactoryOptions,host:{workspaceCwd:workspaceInput.cwd,workspaceTrusted:secondaryTrusted,environment:secondaryEnv.effectiveEnv,forwardedArgs:acpChildExtraArgs(opts)??[],hasLiveMcpServers:__name(()=>secondaryBridgeRef?.hasRuntimeMcpServers()===true,"hasLiveMcpServers")}}),runtimeBaseDir:secondaryEnv.sessionRuntimeBaseDir})}:{channelFactory:secondaryChannelFactory},externalToolGuard:daemonToolGuardHandler,onDiagnosticLine:diagnosticSink,telemetry:createRuntimeBridgeTelemetry(secondaryWorkspaceHash),...permissionPolicy!==void 0?{permissionPolicy}:{},...permissionConsensusQuorum!==void 0?{permissionConsensusQuorum}:{},permissionAudit:permissionAuditPublisher,statusProvider:secondaryStatusProvider,delegateReadTextFileToClient:false,fileSystem:createBridgeFileSystemAdapter(secondaryBridgeFsFactory,{allowSameHostToolWritesOutsideWorkspace:true}),persistApprovalMode:__name((workspace,mode)=>withSettingsLock(workspace,async()=>{secondaryGenerationGuard.assertOpen();if(!secondaryTrusted){throw new Error("Cannot persist approval mode for an untrusted workspace.")}const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,workspaceTrusted:secondaryTrusted});secondaryGenerationGuard.assertOpen();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.approvalMode",mode,()=>secondaryGenerationGuard.assertOpen())}),"persistApprovalMode")});secondaryBridgeRef=secondaryBridge;runtimeBridges.push(secondaryBridge);internalRuntimeBridgesForCleanup.push(secondaryBridge);subSessionStoppers.push(secondarySubSessionLauncher.stop);const secondaryWorkspaceService=runtime.createDaemonWorkspaceService({boundWorkspace:workspaceInput.cwd,isWorkspaceTrusted:__name(()=>secondaryTrusted,"isWorkspaceTrusted"),assertGenerationOpen:__name(()=>secondaryGenerationGuard.assertOpen(),"assertGenerationOpen"),contextFilename:secondaryContextFilename,statusProvider:secondaryStatusProvider,workspaceProvidersStatusProvider:runtime.createWorkspaceProvidersStatusProvider({env:secondaryEnv.effectiveEnv,workspaceTrusted:secondaryTrusted}),workspaceSkillsStatusProvider:runtime.createWorkspaceSkillsStatusProvider({workspaceTrusted:secondaryTrusted}),skillInstallEnv:secondaryEnv.effectiveEnv,voiceEnv:secondaryEnv.effectiveEnv,voiceSettingsScope:WORKSPACE_SETTING_SCOPE,isChannelLive:__name(()=>secondaryBridge.isWorkspaceControlLive?.()??secondaryBridge.isChannelLive(),"isChannelLive"),preheatAcpChild:__name(()=>secondaryBridge.preheat(),"preheatAcpChild"),persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,reloadDaemonEnv:__name((workspace,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!secondaryTrusted,workspaceTrusted:secondaryTrusted});assertGenerationOpen?.();let runtimeEnvironmentApplied=false;let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,secondaryTrusted)}catch(err){secondaryEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to rebuild secondary runtime env snapshot before daemon env reload; preserving previous runtime env",{workspace,error:secondaryEnv.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}const result=settingsRuntime.settings.reloadEnvironment(fresh.merged,workspace,secondaryTrusted,{failClosedOnEnvFileReadError:true});if(result.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}try{secondaryEnv.replace(refreshedRuntimeEnv.effectiveEnv);secondaryEnv.metadata.workflowsEnabledBySettings=fresh.merged.tools?.workflowsEnabled===true;secondaryEnv.metadata.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;secondaryEnv.metadata.envFileReadFailures.splice(0,secondaryEnv.metadata.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);secondaryEnv.metadata.overlayKeys.splice(0,secondaryEnv.metadata.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);secondaryEnv.metadata.envFilePaths.splice(0,secondaryEnv.metadata.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);delete secondaryEnv.metadata.fallbackReason;runtimeEnvironmentApplied=true;return{...result,runtimeEnvironmentApplied}}catch(err){secondaryEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to apply secondary runtime env snapshot after daemon env reload; preserving previous runtime env",{workspace,error:secondaryEnv.metadata.fallbackReason});return{...result,runtimeEnvironmentApplied}}}),"reloadDaemonEnv"),reloadModelProvidersDaemonEnv:__name((workspace,assertGenerationOpen)=>reloadRuntimeOverlaySnapshotForModelProviders(workspace,secondaryTrusted,secondaryEnv,assertGenerationOpen),"reloadModelProvidersDaemonEnv"),queryWorkspaceStatus:__name((method,idle)=>secondaryBridge.queryWorkspaceStatus(method,idle),"queryWorkspaceStatus"),invokeWorkspaceCommand:__name((method,params,invokeOpts)=>secondaryBridge.invokeWorkspaceCommand(method,params,invokeOpts),"invokeWorkspaceCommand"),refreshExtensionsForAllSessions:__name(sessionIds=>sessionIds===void 0?secondaryBridge.refreshExtensionsForAllSessions():secondaryBridge.refreshExtensionsForAllSessions(void 0,{sessionIds}),"refreshExtensionsForAllSessions"),publishWorkspaceEvent:__name(event=>secondaryBridge.publishWorkspaceEvent(event),"publishWorkspaceEvent")});const secondaryRuntime={workspaceId:secondaryWorkspaceHash,workspaceCwd:workspaceInput.cwd,sessionRuntimeBaseDir:secondaryEnv.sessionRuntimeBaseDir,...workspaceInput.displayName?{displayName:workspaceInput.displayName}:{},primary:false,trusted:secondaryTrusted,removable:workspaceInput.removable,registrationIds:workspaceInput.registrationIds,env:secondaryEnv.metadata,bridge:secondaryBridge,workspaceService:secondaryWorkspaceService,routeFileSystemFactory:secondaryBridgeFsFactory,clientMcpSenderRegistry:secondaryClientMcpSenderRegistry,generationGuard:secondaryGenerationGuard,trustMaterialization:JSON.stringify({trusted:secondaryTrusted,boundWorkspaces:[workspaceInput.cwd]})};subSessionStoppersByRuntime.set(secondaryRuntime,secondarySubSessionLauncher.stop);workspaceRuntimes.push(secondaryRuntime)}const workspaceRegistry=runtime.createWorkspaceRegistry(workspaceRuntimes,{sessionOwnerIndex,scanUnindexedOwners:deps.bridge!==void 0});workspaceRegistryForPersistence.current=workspaceRegistry;const workspaceVoiceCoordinator=new WorkspaceVoiceCoordinator;core.registerDaemonGaugeCallbacks({sessionCount:__name(()=>workspaceRegistry.listAll().reduce((sum,item)=>sum+item.bridge.sessionCount,0),"sessionCount"),sseCount:__name(()=>runtime.getActiveSseCount(),"sseCount"),heapUsed:__name(()=>process.memoryUsage().heapUsed,"heapUsed")});daemonMetricsSampler?.dispose();const metricsLoopDelay=monitorEventLoopDelay({resolution:20});metricsLoopDelay.enable();const cpuCoreCount=os2.availableParallelism?.()??os2.cpus().length??1;let prevCpu=safeCpuUsage();let prevCpuAt=Date.now();let prevRateRejected;const metricsSamplerTimer=setInterval(()=>{const nowMs=Date.now();const eventLoopLagP99Ms=metricsLoopDelay.percentile(99)/1e6;try{const mem=process.memoryUsage();const cpu=safeCpuUsage();const cpuPercent=computeCpuPercent(prevCpu,cpu,nowMs-prevCpuAt,cpuCoreCount);if(cpu){prevCpu=cpu;prevCpuAt=nowMs}const acp=app2.locals?.["acpHandle"]?.getSnapshot();const hits=getRateLimiter(app2)?.getHitCounts();const rejectedTotal=hits?hits.prompt+hits.mutation+hits.read:0;const rateLimitRejected=prevRateRejected===void 0?0:Math.max(0,rejectedTotal-prevRateRejected);prevRateRejected=rejectedTotal;const primaryEntry=workspaceRegistry.primaryEntry;const primaryRuntimeBridge=primaryEntry.state==="active"?primaryEntry.current?.runtime.bridge:void 0;const child=primaryRuntimeBridge?.getChildResourceSnapshot?.();if(runtime.getActiveSseCount()>0||(acp?.wsStreams??0)>0){for(const managed of workspaceRegistry.listManaged()){void managed.bridge.refreshChildResource?.().catch(err=>{daemonLog.warn("ACP child resource refresh failed",{workspaceId:managed.workspaceId,error:err instanceof Error?err.message:String(err)})})}}metricsRing.sample(nowMs,{cpuPercent,rssBytes:mem.rss,heapUsedBytes:mem.heapUsed,activeSessions:workspaceRegistry.listAll().reduce((sum,item)=>sum+item.bridge.sessionCount,0),activePrompts:workspaceRegistry.listAll().reduce((sum,item)=>sum+(item.bridge.activePromptCount??0),0),queuedPrompts:workspaceRegistry.listAll().reduce((sum,item)=>sum+(item.bridge.pendingPromptTotal??0),0),eventLoopLagP99Ms,sseConnections:runtime.getActiveSseCount(),wsConnections:acp?.wsStreams??0,acpConnections:acp?.connectionCount??0,rateLimitRejected,childCpuPercent:child?.cpuPercent??0,childRssBytes:child?.rssBytes??0})}catch(err){daemonLog.warn(`metrics sampler tick failed: ${err instanceof Error?err.message:String(err)}`);try{metricsRing.sample(nowMs,{cpuPercent:0,rssBytes:0,heapUsedBytes:0,activeSessions:0,activePrompts:0,queuedPrompts:0,eventLoopLagP99Ms,sseConnections:0,wsConnections:0,acpConnections:0,rateLimitRejected:0,childCpuPercent:0,childRssBytes:0})}catch{}}finally{metricsLoopDelay.reset()}},DAEMON_METRICS_SAMPLE_MS);metricsSamplerTimer.unref();daemonMetricsSampler={dispose(){clearInterval(metricsSamplerTimer);metricsLoopDelay.disable()}};sessionPrRefreshTimer?.dispose();const refreshGeneration=++sessionPrRefreshGeneration;void import("./session-pr-refresh-5IACZPCY.js").then(mod=>{if(refreshGeneration!==sessionPrRefreshGeneration)return;sessionPrRefreshTimer=mod.startSessionPrRefreshTimer({workspaceRegistry,getArchiveCoordinator:__name(()=>app2.locals.sessionArchiveCoordinator,"getArchiveCoordinator")})}).catch(error=>{daemonLog.warn(`session-pr-refresh load failed: ${error instanceof Error?error.message:String(error)}`)});const createDynamicWorkspaceRuntime=__name(async(cwd,buildOptions)=>{const provenance=buildOptions?.provenance??"existing";if(provenance==="managed-scratch"&&(!managedScratchRoot||!isManagedScratchChild(cwd,managedScratchRoot.canonicalRoot))){throw new Error("Managed scratch runtime must use an accepted direct child directory")}if(provenance==="live-conversation"){await liveConversationWorkspace.assertExactRoot(cwd)}const workflowTrustAdmission=buildOptions?.snapshot?workflowTrustAdmissions.get(buildOptions.snapshot)??{snapshot:buildOptions.snapshot,publication:-1}:await readWorkflowTrustAdmission();const snapshot=workflowTrustAdmission.snapshot;const decision=buildOptions?.decision??trustPolicy.evaluateDaemonWorkspaceTrust(snapshot,cwd);const trusted=provenance==="managed-scratch"||provenance==="live-conversation"?true:buildOptions?.trusted??decision.targetTrusted;assertExecutionSandboxSupported(readOperatorSandboxSettings(),"serve workspace runtimes");let wsSettings;try{wsSettings=settingsRuntime.settings.loadSettings(cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted})}catch(err){if(err instanceof InvalidExecutionSandboxConfigError)throw err;writeStderrLine(`qwen serve: could not read full settings for dynamic workspace ${cwd} (${err instanceof Error?err.message:String(err)}); falling back to defaults.`)}assertExecutionSandboxSupported(wsSettings?.merged??{},"serve workspace runtimes");const wsEnv=createRuntimeEnvMetadata(cwd,wsSettings,trusted);const wsCustomIgnoreFiles=wsSettings?.merged.context?.fileFiltering?.customIgnoreFiles;const wsContextFilename=extractContextFilename(wsSettings?.merged.context?.fileName)??contextFilenameForInit??"QWEN.md";const wsHash=core.hashDaemonWorkspace(cwd);const generationGuard=buildOptions?.generationGuard??runtime.createWorkspaceGenerationGuard();const runtimeBoundWorkspaces=buildOptions?.boundWorkspaces??[cwd];const wsFsFactory=runtime.resolveBridgeFsFactory({boundWorkspaces:runtimeBoundWorkspaces,trusted,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard,...wsCustomIgnoreFiles!==void 0?{customIgnoreFiles:wsCustomIgnoreFiles}:{}});const wsRouteFsFactory=buildOptions?.primary===true&&runtimeBoundWorkspaces.length>1?runtime.resolveBridgeFsFactory({boundWorkspaces:[cwd],trusted,emit:deps.fsAuditEmit,pathLocks:sharedPathLocks,generationGuard,...wsCustomIgnoreFiles!==void 0?{customIgnoreFiles:wsCustomIgnoreFiles}:{}}):wsFsFactory;const wsChannelFactoryOptions={processRegistry,childHeapPolicy,reclaimIdleChild:__name(async signal=>{await idleReclaimerRef.current?.(wsHash,signal)},"reclaimIdleChild"),pipeLimits:runtime.daemonAcpNdJsonLimits,sourceEnv:wsEnv.effectiveEnv,onDiagnosticLine:diagnosticSink,pipeHooks:{onMessageSent:__name(bytes=>recordPipeMessage("outbound",bytes),"onMessageSent"),onMessageReceived:__name(bytes=>recordPipeMessage("inbound",bytes),"onMessageReceived"),onMessageObserved:__name(({direction,bytes,message})=>observeLargePipeFrame({direction:daemonPipeDirection(direction),bytes,message}),"onMessageObserved"),onQueueSaturated:warnAcpQueueSaturated},...acpChildExtraArgs(opts)?{extraArgs:acpChildExtraArgs(opts)}:{}};const wsChannelFactory=runtime.createSpawnChannelFactory(wsChannelFactoryOptions);const wsClientMcpRegistry=new ClientMcpSenderRegistry;let wsBridgeRef;const wsSubSessionLauncher=createSubSessionLauncher({getBridge:__name(()=>wsBridgeRef,"getBridge"),boundWorkspace:cwd,runtimeBaseDir:wsEnv.sessionRuntimeBaseDir,...provenance==="live-conversation"?{notifySentCompletion:true,getStandaloneSessionService:__name(()=>(runtimeApp??runtimeAppForCleanup)?.locals?.["standaloneSessionService"],"getStandaloneSessionService"),isolatedWorkspace:{materializeDirectory:__name(sessionId=>liveConversationWorkspace.materializeConversationDirectory(sessionId),"materializeDirectory"),discardEmptyDirectory:__name(sessionId=>liveConversationWorkspace.discardEmptyConversationDirectory(sessionId),"discardEmptyDirectory")}}:{},...subSessionConcurrencyCapsFromSettings(wsSettings?.merged.serve??{})});let wsBridge;try{const wsAttachmentsRoots=sessionAttachmentsRoots(cwd,wsEnv.sessionRuntimeBaseDir);wsBridge=runtime.createAcpSessionBridge({onWorkflowAncestorTrust:createRuntimeWorkflowAncestorTrustHandler(cwd,()=>wsBridgeRef,generationGuard,workflowTrustAdmission),artifactSnapshotRuntimeBaseDir:wsEnv.sessionRuntimeBaseDir,sessionAttachmentsRoot:wsAttachmentsRoots.root,sessionAttachmentsFallbackRoot:wsAttachmentsRoots.fallback,clientMcpSender:wsClientMcpRegistry.lookup,onCreateSubSession:wsSubSessionLauncher.launch,onCreateCurrentSessionScheduledTask:createCurrentSessionScheduledTaskHandler(cwd,wsEnv.sessionRuntimeBaseDir,()=>wsBridgeRef,()=>generationGuard.assertOpen()),onChannelDelivery:createBoundChannelDeliveryHandler(cwd,()=>channelWorkerManager,channelDeliveryAuthorizations,daemonLog,channelDeliveryDiagnosticRedaction),maxSessions:opts.maxSessions,...opts.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},freshSessionAdmission:totalSessionAdmission.admit,sessionLifecycle:__name(event=>{if(event.type==="registered"&&generationGuard.closed)return;sessionOwnerIndex.handleBridgeSessionLifecycle(event)},"sessionLifecycle"),...opts.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:opts.maxPendingPromptsPerSession}:{},...opts.eventRingSize!==void 0?{eventRingSize:opts.eventRingSize}:{},...opts.compactedReplayMaxBytes!==void 0?{compactedReplayMaxBytes:opts.compactedReplayMaxBytes}:{},...opts.maxJournalEvents!==void 0?{maxJournalEvents:opts.maxJournalEvents}:{},...opts.maxJournalBytes!==void 0?{maxJournalBytes:opts.maxJournalBytes}:{},...journalGrowthPoolBytes!==void 0?{journalGrowthPoolBytes,journalGrowthSessionLimits,registerJournalGrowthSessionLimits}:{},...opts.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:opts.channelIdleTimeoutMs}:{},...opts.initializeTimeoutMs!==void 0?{initializeTimeoutMs:opts.initializeTimeoutMs}:{},sessionRestoreTimeoutMs,...opts.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:opts.sessionReapIntervalMs}:{},...opts.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:opts.sessionIdleTimeoutMs}:{},...opts.sessionPromptSettledCloseGraceMs!==void 0?{sessionPromptSettledCloseGraceMs:opts.sessionPromptSettledCloseGraceMs}:{},...opts.permissionResponseTimeoutMs!==void 0?{permissionResponseTimeoutMs:opts.permissionResponseTimeoutMs}:{},boundWorkspace:cwd,runtimeEpochSource:runtimeEpochSourceFor(cwd),acquireMcpAuthentication,...provenance==="live-conversation"?{}:{promptLedger:runtime.createPromptLedgerSink(cwd,wsEnv.sessionRuntimeBaseDir)},sessionShellCommandEnabled,childEnvOverrides:provenance==="live-conversation"?{...childEnvOverrides,[PRIVATE_CONVERSATIONS_RUNTIME_ENV]:PRIVATE_CONVERSATIONS_RUNTIME_ENABLE}:childEnvOverrides,...opts.experimentalPairedEngines&&provenance!=="live-conversation"?{executionEngines:runtime.createPairedExecutionEngines({legacy:wsChannelFactory,managed:runtime.createManagedExecutionEngine({legacy:wsChannelFactoryOptions,host:{workspaceCwd:cwd,workspaceTrusted:trusted,environment:wsEnv.effectiveEnv,forwardedArgs:acpChildExtraArgs(opts)??[],hasLiveMcpServers:__name(()=>wsBridgeRef?.hasRuntimeMcpServers()===true,"hasLiveMcpServers")}}),runtimeBaseDir:wsEnv.sessionRuntimeBaseDir})}:{channelFactory:wsChannelFactory},externalToolGuard:daemonToolGuardHandler,onDiagnosticLine:diagnosticSink,telemetry:createRuntimeBridgeTelemetry(wsHash),...permissionPolicy!==void 0?{permissionPolicy}:{},...permissionConsensusQuorum!==void 0?{permissionConsensusQuorum}:{},permissionAudit:permissionAuditPublisher,statusProvider:runtime.createDaemonStatusProvider({env:wsEnv.effectiveEnv}),delegateReadTextFileToClient:false,fileSystem:createBridgeFileSystemAdapter(wsFsFactory,{allowSameHostToolWritesOutsideWorkspace:true}),persistApprovalMode:__name((workspace,mode)=>withSettingsLock(workspace,async()=>{generationGuard.assertOpen();if(!trusted){throw new Error("Cannot persist approval mode for an untrusted workspace.")}const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,workspaceTrusted:trusted});generationGuard.assertOpen();fresh.setValue(WORKSPACE_SETTING_SCOPE,"tools.approvalMode",mode,()=>generationGuard.assertOpen())}),"persistApprovalMode")})}catch(err){wsSubSessionLauncher.stop();throw err}wsBridgeRef=wsBridge;let wsService;try{wsService=runtime.createDaemonWorkspaceService({boundWorkspace:cwd,isWorkspaceTrusted:__name(()=>trusted,"isWorkspaceTrusted"),assertGenerationOpen:__name(()=>generationGuard.assertOpen(),"assertGenerationOpen"),contextFilename:wsContextFilename,statusProvider:runtime.createDaemonStatusProvider({env:wsEnv.effectiveEnv}),workspaceProvidersStatusProvider:runtime.createWorkspaceProvidersStatusProvider({env:wsEnv.effectiveEnv,workspaceTrusted:trusted}),workspaceSkillsStatusProvider:runtime.createWorkspaceSkillsStatusProvider({workspaceTrusted:trusted}),skillInstallEnv:wsEnv.effectiveEnv,voiceEnv:wsEnv.effectiveEnv,...buildOptions?.primary===true?{}:{voiceSettingsScope:WORKSPACE_SETTING_SCOPE},isChannelLive:__name(()=>wsBridge.isWorkspaceControlLive?.()??wsBridge.isChannelLive(),"isChannelLive"),preheatAcpChild:__name(()=>wsBridge.preheat(),"preheatAcpChild"),persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,reloadDaemonEnv:__name((workspace,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen?.();const fresh=settingsRuntime.settings.loadSettings(workspace,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted});assertGenerationOpen?.();let runtimeEnvironmentApplied=false;let refreshedRuntimeEnv;try{refreshedRuntimeEnv=settingsRuntime.environment.buildRuntimeEnvironment(fresh.merged,workspace,daemonRuntimeBaseEnv,trusted)}catch(err){wsEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to rebuild dynamic runtime env snapshot before daemon env reload; preserving previous runtime env",{workspace,error:wsEnv.metadata.fallbackReason});return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied}}logRuntimeEnvFileReadFailures(workspace,refreshedRuntimeEnv);if(refreshedRuntimeEnv.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}const result=settingsRuntime.settings.reloadEnvironment(fresh.merged,workspace,trusted,{failClosedOnEnvFileReadError:true});if(result.envFileReadFailed){return{updatedKeys:[],removedKeys:[],runtimeEnvironmentApplied:false}}try{wsEnv.replace(refreshedRuntimeEnv.effectiveEnv);wsEnv.metadata.workflowsEnabledBySettings=fresh.merged.tools?.workflowsEnabled===true;wsEnv.metadata.envFileReadFailed=refreshedRuntimeEnv.envFileReadFailed;wsEnv.metadata.envFileReadFailures.splice(0,wsEnv.metadata.envFileReadFailures.length,...refreshedRuntimeEnv.envFileReadFailures);wsEnv.metadata.overlayKeys.splice(0,wsEnv.metadata.overlayKeys.length,...refreshedRuntimeEnv.overlayKeys);wsEnv.metadata.envFilePaths.splice(0,wsEnv.metadata.envFilePaths.length,...refreshedRuntimeEnv.envFilePaths);delete wsEnv.metadata.fallbackReason;runtimeEnvironmentApplied=true;return{...result,runtimeEnvironmentApplied}}catch(err){wsEnv.metadata.fallbackReason=err instanceof Error?err.message:String(err);daemonLog.warn("failed to apply dynamic runtime env snapshot after daemon env reload; preserving previous runtime env",{workspace,error:wsEnv.metadata.fallbackReason});return{...result,runtimeEnvironmentApplied}}}),"reloadDaemonEnv"),reloadModelProvidersDaemonEnv:__name((workspace,assertGenerationOpen)=>reloadRuntimeOverlaySnapshotForModelProviders(workspace,trusted,wsEnv,assertGenerationOpen),"reloadModelProvidersDaemonEnv"),queryWorkspaceStatus:__name((method,idle)=>wsBridge.queryWorkspaceStatus(method,idle),"queryWorkspaceStatus"),invokeWorkspaceCommand:__name((method,params,invokeOpts)=>wsBridge.invokeWorkspaceCommand(method,params,invokeOpts),"invokeWorkspaceCommand"),refreshExtensionsForAllSessions:__name(sessionIds=>sessionIds===void 0?wsBridge.refreshExtensionsForAllSessions():wsBridge.refreshExtensionsForAllSessions(void 0,{sessionIds}),"refreshExtensionsForAllSessions"),publishWorkspaceEvent:__name(event=>{if(buildOptions?.primary===true&&(event.type==="settings_changed"||event.type==="settings_reloaded")){invalidatePrimaryServeFeaturesCache()}wsBridge.publishWorkspaceEvent(event)},"publishWorkspaceEvent")})}catch(err){wsSubSessionLauncher.stop();await wsBridge.shutdown().catch(()=>{try{wsBridge.killAllSync()}catch{}});throw err}runtimeBridges.push(wsBridge);internalRuntimeBridgesForCleanup.push(wsBridge);subSessionStoppers.push(wsSubSessionLauncher.stop);const wsRuntime={workspaceId:wsHash,workspaceCwd:cwd,sessionRuntimeBaseDir:wsEnv.sessionRuntimeBaseDir,...buildOptions?.displayName!==void 0?{displayName:buildOptions.displayName}:provenance==="live-conversation"?{displayName:"Conversations"}:{},primary:buildOptions?.primary??false,trusted,provenance,removable:buildOptions?.removable??provenance!=="live-conversation",registrationIds:[...buildOptions?.registrationIds??[]],env:wsEnv.metadata,bridge:wsBridge,workspaceService:wsService,routeFileSystemFactory:wsRouteFsFactory,clientMcpSenderRegistry:wsClientMcpRegistry,generationGuard,trustMaterialization:buildOptions?.trustMaterialization??JSON.stringify({trusted,boundWorkspaces:[...runtimeBoundWorkspaces].sort()})};subSessionStoppersByRuntime.set(wsRuntime,wsSubSessionLauncher.stop);if(provenance==="existing"&&!buildOptions?.snapshot){const latest=await trustPolicy.readDaemonTrustPolicySnapshot();if(latest.revision!==snapshot.revision){generationGuard.close();wsSubSessionLauncher.stop();await wsBridge.shutdown({reason:"trust_reconfigured"}).catch(()=>{try{wsBridge.killAllSync()}catch{}});subSessionStoppersByRuntime.delete(wsRuntime);removeArrayValue(subSessionStoppers,wsSubSessionLauncher.stop);removeArrayValue(runtimeBridges,wsBridge);removeArrayValue(internalRuntimeBridgesForCleanup,wsBridge);if((buildOptions?.validationAttempt??0)>=2){throw new Error("Workspace trust policy kept changing during runtime creation.")}const{generationGuard:_staleGuard,...retryOptions}=buildOptions??{};return createDynamicWorkspaceRuntime(cwd,{...retryOptions,validationAttempt:(buildOptions?.validationAttempt??0)+1})}}if(wsRuntime.primary&&wsRuntime.trusted){await recoverBranchWorktreePreparations({workspaceCwd:cwd,sessionService:await createBranchRecoverySessionService(wsRuntime),assertGenerationOpen:__name(()=>generationGuard.assertOpen(),"assertGenerationOpen"),isWorktreeOccupied:__name(worktreePath=>bridgeHasLiveSessionWithin(wsBridge,cwd,worktreePath),"isWorktreeOccupied"),warn:__name((message,fields)=>daemonLog.warn(message,fields),"warn")}).catch(error=>{daemonLog.warn("branch worktree recovery sweep failed",{workspace:cwd,error:error instanceof Error?error.message:String(error)})})}return wsRuntime},"createDynamicWorkspaceRuntime");const serveAppForRuntimeLifecycle={current:void 0};const workspaceRuntimeRemoval={async runtimeAdded(runtimeAdded){const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const startScheduledTaskKeepaliveForWorkspace=app3?.locals?.["startScheduledTaskKeepaliveForWorkspace"];startScheduledTaskKeepaliveForWorkspace?.(runtimeAdded);if(runtimeAdded.provenance==="live-conversation")return;channelWebhookEnvByWorkspace.set(runtimeAdded.workspaceCwd,workspaceRuntimeEffectiveEnv(runtimeAdded,daemonRuntimeBaseEnv));channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.();if(channelWorkerManager){const manager=channelWorkerManager;const activatedCwd=runtimeAdded.workspaceCwd;const activatedTrusted=runtimeAdded.trusted;void(async()=>{try{if(activatedTrusted){await manager.restoreWorkspace(activatedCwd)}await manager.refreshWorkspaces()}catch(err){daemonLog.error("workspace channel worker startup error",err instanceof Error?err:null)}finally{writeChannelWorkerPidfile()}})()}const workspaceCwd=runtimeAdded.workspaceCwd;if(!runtimeAdded.trusted||runtimeAdded.primary||channelSelectionFromFlag||lateRestoredWorkspaces.has(workspaceCwd)||readSshWorkspace(workspaceCwd)){return}if(channelHostingStoppedByOperator){daemonLog.info("skipping serve.channels for a workspace registered after boot: channel hosting was stopped",{workspaceCwd});return}if(channelWorkerManager?.state().selection?.mode==="all"){return}const requested=startupChannelsForWorkspace(workspaceCwd);if(requested.length===0)return;lateRestoredWorkspaces.add(workspaceCwd);daemonLog.info("restoring serve.channels for a workspace registered after boot",{workspaceCwd,channels:requested});void addChannelsToSelection(requested).catch(err=>{daemonLog.error(`serve.channels for a workspace registered after boot were not restored: ${sanitizeLogText(redactLogCredentials(err instanceof Error?err.message:String(err)),512)}`,null,{workspaceCwd});if(channelControlDraining)return;channelRestoreFailures.record(lateRestoreFailures(workspaceCwd,requested,err))}).finally(()=>{writeChannelWorkerPidfile()})},beginDrain(runtimeToDrain){if(runtimeToDrain.primary){if(bridgeRef===runtimeToDrain.bridge)bridgeRef=void 0;invalidatePrimaryServeFeaturesCache()}totalSessionAdmission.beginWorkspaceDrain(runtimeToDrain.workspaceCwd);if(runtimeToDrain.provenance!=="live-conversation"){channelWorkerManager?.beginWorkspaceDrain(runtimeToDrain.workspaceCwd)}workspaceVoiceCoordinator.beginWorkspaceDrain(runtimeToDrain);channelWebhookEnvByWorkspace.delete(runtimeToDrain.workspaceCwd);channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.();const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const stopScheduledTaskKeepaliveForWorkspace=app3?.locals?.["stopScheduledTaskKeepaliveForWorkspace"];try{stopScheduledTaskKeepaliveForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace scheduled-task drain error",err instanceof Error?err:null)}},cancelDrain(runtimeToDrain){if(runtimeToDrain.primary&&bridgeRef===void 0){bridgeRef=runtimeToDrain.bridge;invalidatePrimaryServeFeaturesCache()}if(runtimeToDrain.provenance!=="live-conversation"){channelWorkerManager?.cancelWorkspaceDrain(runtimeToDrain.workspaceCwd)}totalSessionAdmission.cancelWorkspaceDrain(runtimeToDrain.workspaceCwd);workspaceVoiceCoordinator.cancelWorkspaceDrain(runtimeToDrain);if(runtimeToDrain.provenance!=="live-conversation"){channelWebhookEnvByWorkspace.set(runtimeToDrain.workspaceCwd,workspaceRuntimeEffectiveEnv(runtimeToDrain,daemonRuntimeBaseEnv));channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.()}const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const startScheduledTaskKeepaliveForWorkspace=app3?.locals?.["startScheduledTaskKeepaliveForWorkspace"];try{startScheduledTaskKeepaliveForWorkspace?.(runtimeToDrain)}catch(err){daemonLog.error("workspace scheduled-task drain rollback error",err instanceof Error?err:null)}},completeDrain(runtimeToDrain){totalSessionAdmission.completeWorkspaceDrain(runtimeToDrain.workspaceCwd);workspaceVoiceCoordinator.completeWorkspaceDrain(runtimeToDrain)},getActivity(runtimeToDrain){return{pendingSessionStarts:totalSessionAdmission.snapshotForWorkspace(runtimeToDrain.workspaceCwd).inFlight,channelWorkers:runtimeToDrain.provenance==="live-conversation"?0:channelWorkerManager?.workspaceActivity(runtimeToDrain.workspaceCwd)??0,voiceSessions:workspaceVoiceCoordinator.getWorkspaceActivity(runtimeToDrain)}},disposeRuntime(runtimeToDrain,reason="workspace_removed"){const existing=runtimeCleanupPromises.get(runtimeToDrain);if(existing)return existing;const cleanup=(async()=>{runtime.getWorkspaceRuntimeCoordinatorIfSupported(runtimeToDrain)?.dispose();const containmentErrors=[];try{await workspaceVoiceCoordinator.disposeRuntime(runtimeToDrain,reason)}catch(err){daemonLog.error("workspace voice cleanup error",err instanceof Error?err:null)}if(reason==="trust_reconfigured"&&workspaceVoiceCoordinator.getWorkspaceActivity(runtimeToDrain)>0){containmentErrors.push(new Error("Workspace voice sessions are still active."))}const stopSubSessions=subSessionStoppersByRuntime.get(runtimeToDrain);try{stopSubSessions?.()}catch{}if(reason!=="daemon_shutdown"&&channelWorkerManager&&runtimeToDrain.provenance!=="live-conversation"){await channelWorkerManager.removeWorkspace(runtimeToDrain.workspaceCwd,{permanent:reason==="workspace_removed"}).catch(err=>{daemonLog.error("workspace channel worker cleanup error",err instanceof Error?err:null)});try{await channelWorkerManager.refreshWorkspaces()}catch(err){channelWorkspaceGroups=(channelWorkspaceGroups??[]).filter(group=>group.workspaceCwd!==runtimeToDrain.workspaceCwd);channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.();daemonLog.error("workspace channel worker topology refresh error",err instanceof Error?err:null)}writeChannelWorkerPidfile();if(reason==="trust_reconfigured"&&channelWorkerManager.workspaceActivity(runtimeToDrain.workspaceCwd)>0){containmentErrors.push(new Error("Workspace channel workers are still active."))}}if(reason!=="daemon_shutdown"){const app3=serveAppForRuntimeLifecycle.current??runtimeApp??runtimeAppForCleanup;const stopWorkspaceGitStateForWorkspace=app3?.locals?.["stopWorkspaceGitStateForWorkspace"];const stopScheduledTaskKeepaliveForWorkspace=app3?.locals?.["stopScheduledTaskKeepaliveForWorkspace"];const releaseWebTerminalsForWorkspace=app3?.locals?.["releaseWebTerminalsForWorkspace"];try{stopWorkspaceGitStateForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace git-state cleanup error",err instanceof Error?err:null)}try{stopScheduledTaskKeepaliveForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace scheduled-task cleanup error",err instanceof Error?err:null)}try{releaseWebTerminalsForWorkspace?.(runtimeToDrain.workspaceCwd)}catch(err){daemonLog.error("workspace web-terminal cleanup error",err instanceof Error?err:null)}}let bridgeStopped=false;try{if(!shutdownBridges.has(runtimeToDrain.bridge)){try{await runtimeToDrain.bridge.shutdown({reason})}catch(shutdownError){try{runtimeToDrain.bridge.killAllSync();daemonLog.warn("workspace bridge required forceful shutdown",{workspace:runtimeToDrain.workspaceCwd,reason,error:shutdownError instanceof Error?shutdownError.message:String(shutdownError)})}catch(killError){throw new AggregateError([shutdownError,killError],"Workspace bridge shutdown could not be confirmed.")}}}bridgeStopped=true}finally{if(bridgeStopped){subSessionStoppersByRuntime.delete(runtimeToDrain);if(stopSubSessions){removeArrayValue(subSessionStoppers,stopSubSessions)}removeArrayValue(runtimeBridges,runtimeToDrain.bridge);removeArrayValue(internalRuntimeBridgesForCleanup,runtimeToDrain.bridge);shutdownBridges.add(runtimeToDrain.bridge)}}if(containmentErrors.length>0){throw new AggregateError(containmentErrors,"Workspace runtime containment could not be confirmed.")}})();runtimeCleanupPromises.set(runtimeToDrain,cleanup);void cleanup.catch(()=>{if(runtimeCleanupPromises.get(runtimeToDrain)===cleanup){runtimeCleanupPromises.delete(runtimeToDrain)}});return cleanup}};const channelManagementServices=new WeakMap;const channelManagementService=__name(targetRuntime=>{const existing=channelManagementServices.get(targetRuntime);if(existing)return existing;const pending=(async()=>{if(!ensureChannelWorkerManager){throw Object.assign(new Error("Channel worker manager is unavailable."),{code:"channel_worker_unavailable"})}const[{createChannelManagementService},{WorkspaceChannelSettingsStore}]=await Promise.all([import("./channel-management-service-YVXFZXFY.js"),import("./channel-settings-store-TEBCLK2B.js")]);const manager=await ensureChannelWorkerManager();const workerRuntime=await ensureChannelRuntime();const settingsRuntime2=await loadSettingsRuntimeModules();return createChannelManagementService({workspaceCwd:targetRuntime.workspaceCwd,store:new WorkspaceChannelSettingsStore(targetRuntime.workspaceCwd),manager,loadChannelsConfig:__name(cwd=>workerRuntime.loadChannelsConfig(cwd,settingsRuntime2.settings.loadSettings(cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!targetRuntime.trusted,workspaceTrusted:targetRuntime.trusted})),"loadChannelsConfig"),restoreFailures:channelRestoreFailures})})();channelManagementServices.set(targetRuntime,pending);void pending.catch(()=>{if(channelManagementServices.get(targetRuntime)===pending){channelManagementServices.delete(targetRuntime)}});return pending},"channelManagementService");const validateWorkspaceRuntimeForPublication=__name(async runtimeForPublication=>{let candidate=runtimeForPublication;for(let attempt=0;attempt<3;attempt++){const snapshot=await trustPolicy.readDaemonTrustPolicySnapshot();const decision=trustPolicy.evaluateDaemonWorkspaceTrust(snapshot,candidate.workspaceCwd);const materialization=JSON.stringify({trusted:decision.targetTrusted,boundWorkspaces:[candidate.workspaceCwd]});if(candidate.trustMaterialization===materialization){return candidate}candidate.generationGuard?.close();await workspaceRuntimeRemoval.disposeRuntime(candidate,"trust_reconfigured");if(attempt===2){throw new Error("Workspace trust policy kept changing before runtime publication.")}candidate=await createDynamicWorkspaceRuntime(runtimeForPublication.workspaceCwd,{primary:runtimeForPublication.primary,removable:runtimeForPublication.removable,displayName:runtimeForPublication.displayName,registrationIds:runtimeForPublication.registrationIds})}throw new Error("Workspace runtime publication validation failed.")},"validateWorkspaceRuntimeForPublication");const app2=runtime.createServeApp(opts,()=>actualPort,{restartForUpdate,maxChannelControlWorkspaces:MAX_CHANNEL_CONTROL_WORKSPACES,serveAppLifecycle,liveDiscoveryStableBaseDir,workspaceRegistry,getSessionBridges:__name(()=>runtimeBridges,"getSessionBridges"),createWorkspaceRuntime:createDynamicWorkspaceRuntime,...workspaceTrustHotReloadAvailable?{validateWorkspaceRuntimeForPublication,runWorkspaceTrustOperation,getWorkspaceTrustPolicySnapshot:__name(()=>latestTrustPolicySnapshot,"getWorkspaceTrustPolicySnapshot")}:{},managedScratchRoot,liveConversationWorkspace,readLiveConversationScheduledTasks,workspaceRegistrationStore,workspaceRuntimeRemoval,workspaceTrustHotReloadAvailable,voiceCoordinator:workspaceVoiceCoordinator,bridge,webShellDir,boundWorkspace,qwenCodeVersion:resolvedCliVersion,startup,manageScheduledTaskSessions:opts.profile!=="hosted-harness",currentSessionSchedulingAvailable:deps.bridge===void 0,fsFactory:routeFsFactory,primaryWorkspaceTrusted:trustedWorkspace,primaryRuntimeEnv,daemonEnv:daemonRuntimeBaseEnv,modelSelectionBaseEnv:getEnvironmentBeforeLoad()??daemonRuntimeBaseEnv,runtimePlatform:deps.runtimePlatform,daemonLog,getChannelWorkerSnapshot,getChannelWorkerSnapshots,getChannelRestoreFailures:__name(()=>channelRestoreFailures.list(),"getChannelRestoreFailures"),getChannelWorkerControl,isChannelControlDraining:__name(()=>channelControlDraining,"isChannelControlDraining"),isChannelControlInitializing:__name(()=>channelWorkerManagerStarting!==void 0,"isChannelControlInitializing"),setChannelWorkerSelection,stopChannelWorker,getChannelWebhookConfigSources,getChannelWebhookConfigVersion:__name(()=>channelWebhookConfigVersion,"getChannelWebhookConfigVersion"),registerChannelWebhookConfigRefresh:__name(refresh=>{refreshChannelWebhookConfigs=refresh},"registerChannelWebhookConfigRefresh"),enqueueChannelWebhookTask:__name(async task=>{if(!channelWorkerManager){throw new ChannelWebhookEnqueueError("channel_worker_unavailable","Channel worker is not running.")}return channelWorkerManager.enqueueWebhookTask(task)},"enqueueChannelWebhookTask"),deliverChannelMessage:__name(async(workspaceCwd,request)=>{if(!channelWorkerManager){throw new ChannelDeliveryError("channel_worker_unavailable","Channel worker is not running.")}return channelWorkerManager.deliverChannelMessage(workspaceCwd,request)},"deliverChannelMessage"),channelDeliveryAuthorizations,reloadChannelWorker,channelManagementService,getPerfSnapshot:__name(()=>({eventLoop:currentDaemonEventLoopMonitor.snapshot(),promptQueueWait:{count:promptQueueWaitStats.count,meanMs:promptQueueWaitStats.count===0?0:promptQueueWaitStats.totalMs/promptQueueWaitStats.count,maxMs:promptQueueWaitStats.maxMs,lastMs:promptQueueWaitStats.lastMs},pipe:{inbound:{...pipeStats.inbound},outbound:{...pipeStats.outbound}}}),"getPerfSnapshot"),getMetricsSeries:__name(()=>metricsRing.snapshot(),"getMetricsSeries"),getTotalSessionAdmissionSnapshot:totalSessionAdmission.snapshot,getChildHeapPolicySnapshot:__name(()=>managedChildHeapPolicy?.snapshot(),"getChildHeapPolicySnapshot"),...childHeapPolicy?{managedChildProcesses:{registry:processRegistry,policy:childHeapPolicy,ownsBridge:__name(candidate=>runtimeBridges.includes(candidate),"ownsBridge")}}:{},recordDaemonRequest:__name((durationMs,statusCode)=>metricsRing.recordRequest(durationMs,statusCode),"recordDaemonRequest"),workspace:workspaceService,clientMcpSenderRegistry,persistDisabledTools:persistDisabledToolsFn,persistDisabledSkills:persistDisabledSkillsFn,persistDisabledSkillsBatch:persistDisabledSkillsBatchFn,persistSetting:persistSettingFn,persistSettings:persistSettingsFn,sessionArtifactsPersistenceAvailable:sessionArtifactsPersistenceAvailableFromSettings(runtimeBootSettings?.merged),updateModelContextWindow:__name((workspace,key,size,assertGenerationOpen)=>withSettingsLock(workspace,async()=>{assertGenerationOpen();const{updateModelContextWindow}=await import("./model-configuration-6RWVBOQS.js");return updateModelContextWindow(loadSettingsForPersistence(workspace),key,size,assertGenerationOpen)}),"updateModelContextWindow"),installAuthProvider:__name((req,assertGenerationOpen)=>withSettingsLock(boundWorkspace,async()=>{assertGenerationOpen?.();const provider=core.findProviderById(req.providerId);if(!provider){throw new Error(`Unsupported auth provider: ${req.providerId}`)}const inputs=buildProviderSetupInputs(req,provider,{getDefaultModelIds:core.getDefaultModelIds,resolveBaseUrl:core.resolveBaseUrl});const fresh=loadSettingsForPersistence(boundWorkspace);const plan=core.buildInstallPlan(provider,inputs,core.getModelsForProviderProtocol(fresh.merged.modelProviders,inputs.protocol??provider.protocol,fresh.merged.providerProtocol),{authType:fresh.merged.security?.auth?.selectedType,id:fresh.merged.model?.name,baseUrl:fresh.merged.model?.baseUrl});const adapter=settingsRuntime.loadedSettingsAdapter.createLoadedSettingsAdapter(fresh);const{getAuthTypeFromEnv}=await import("./modelConfigUtils-M3TVVYAO.js");const hasConversationAuth=adapter.getValue("security.auth.selectedType")||getAuthTypeFromEnv(primaryRuntimeEnv.effectiveEnv);await core.applyProviderInstallPlan(plan,{settings:adapter,doRefreshAuth:false});assertGenerationOpen?.();core.emitDaemonLog("Auth provider installed.",{"qwen-code.daemon.auth.provider_id":provider.id,"qwen-code.daemon.auth.auth_type":plan.authType});const effectiveModelId=adapter.getValue("model.name")??plan.modelSelection?.modelId;const effectiveBaseUrl=adapter.getValue("model.baseUrl")??plan.modelSelection?.baseUrl??inputs.baseUrl;return{v:1,providerId:provider.id,providerLabel:provider.label,authType:plan.authType,...effectiveModelId?{modelId:effectiveModelId}:{},...effectiveBaseUrl?{baseUrl:effectiveBaseUrl}:{},message:!plan.modelSelection?hasConversationAuth?"Service models saved.":"Service models saved. Configure a conversation model to start chatting.":`Successfully configured ${provider.label}. Use /model to switch models.`}}),"installAuthProvider")});idleReclaimerRef.current=app2.locals["reclaimIdleAcp"];serveAppForRuntimeLifecycle.current=app2;invalidatePrimaryServeFeaturesCache=app2.locals.invalidateServeFeaturesCache??invalidatePrimaryServeFeaturesCache;app2.locals.subSessionStoppers=subSessionStoppers;subSessionStoppers.push(subSessionLauncher.stop);subSessionStoppersByRuntime.set(workspaceRegistry.primary,subSessionLauncher.stop);if(workspaceTrustHotReloadAvailable){const[{createWorkspaceTrustReconciler},{createDaemonTrustPolicyMonitor}]=await Promise.all([import("./workspace-trust-reconciler-52CZVPKH.js"),import("./daemon-trust-policy-monitor-OWUP5SYB.js")]);const materializationFor=__name((entry,snapshot,decision)=>{const boundWorkspaces2=entry.primary&&decision.targetTrusted?runtime.resolveBoundWorkspacesFromIdeEnv(entry.workspaceCwd,void 0,(workspace,index)=>index===0||trustPolicy.evaluateDaemonWorkspaceTrust(snapshot,workspace).targetTrusted):[entry.workspaceCwd];return{key:JSON.stringify({trusted:decision.targetTrusted,boundWorkspaces:[...boundWorkspaces2].sort()}),boundWorkspaces:boundWorkspaces2}},"materializationFor");const acpHandle=__name(()=>app2.locals?.["acpHandle"],"acpHandle");const trustReconciler=createWorkspaceTrustReconciler({registry:workspaceRegistry,readLatestSnapshot:__name(async()=>(await readWorkflowTrustAdmission()).snapshot,"readLatestSnapshot"),materializationKey:__name(({entry,snapshot,decision})=>materializationFor(entry,snapshot,decision).key,"materializationKey"),isTrustDecrease:__name(({runtime:current,nextMaterialization,decision})=>{if(current.trusted&&!decision.targetTrusted)return true;if(!current.primary||!current.trusted)return false;try{const previous=JSON.parse(current.trustMaterialization??"{}");const next=JSON.parse(nextMaterialization);if(!Array.isArray(previous.boundWorkspaces)||!Array.isArray(next.boundWorkspaces)){return true}const nextRoots=new Set(next.boundWorkspaces.filter(value=>typeof value==="string"));return previous.boundWorkspaces.some(value=>typeof value!=="string"||!nextRoots.has(value))}catch{return true}},"isTrustDecrease"),buildRuntime:__name(async({entry,trusted,snapshot,decision,generationGuard})=>{const materialized=materializationFor(entry,snapshot,trusted===decision.targetTrusted?decision:{...decision,targetTrusted:trusted});return createDynamicWorkspaceRuntime(entry.workspaceCwd,{trusted,snapshot,decision,generationGuard,primary:entry.primary,removable:entry.removable,displayName:entry.displayName,registrationIds:entry.registrationIds,boundWorkspaces:materialized.boundWorkspaces,trustMaterialization:materialized.key})},"buildRuntime"),drainRuntime:__name(async runtimeToDrain=>{workspaceRuntimeRemoval.beginDrain(runtimeToDrain);acpHandle()?.beginWorkspaceDrain(runtimeToDrain.workspaceId)},"drainRuntime"),disposeRuntime:__name(async(runtimeToDispose,reason)=>{const errors=[];try{await workspaceRuntimeRemoval.disposeRuntime(runtimeToDispose,reason)}catch(error){errors.push(error)}try{const handle=acpHandle();if(!runtimeToDispose.primary){handle?.commitWorkspaceRemoval(runtimeToDispose.workspaceId)}handle?.disposeWorkspace(runtimeToDispose.workspaceId);const deadline=Date.now()+1e3;while((handle?.getWorkspaceActivity(runtimeToDispose.workspaceId).memoryTasks??0)>0&&Date.now()<deadline){await new Promise(resolve3=>setTimeout(resolve3,25))}if((handle?.getWorkspaceActivity(runtimeToDispose.workspaceId).memoryTasks??0)>0){throw new Error("Workspace memory tasks did not stop after runtime disposal.")}}catch(error){errors.push(error)}if(errors.length===1)throw errors[0];if(errors.length>1){throw new AggregateError(errors,"Workspace runtime and ACP cleanup failed.")}},"disposeRuntime"),runtimeActivated:__name(async runtimeAdded=>{workspaceRuntimeRemoval.cancelDrain(runtimeAdded);acpHandle()?.cancelWorkspaceDrain(runtimeAdded.workspaceId);if(runtimeAdded.primary){bridgeRef=runtimeAdded.bridge;invalidatePrimaryServeFeaturesCache()}await workspaceRuntimeRemoval.runtimeAdded(runtimeAdded)},"runtimeActivated"),onError:__name((entry,error)=>{daemonLog.error(`workspace trust reconciliation failed for ${entry.workspaceCwd}`,error instanceof Error?error:null)},"onError")});const trustMonitor=createDaemonTrustPolicyMonitor({onSnapshot:__name(snapshot=>{latestTrustPolicySnapshot=snapshot;publishedWorkflowTrustPolicy={publication:publishedWorkflowTrustPolicy.publication+1,snapshot};workflowTrustAdmissions.set(snapshot,{publication:publishedWorkflowTrustPolicy.publication,snapshot});return runWorkspaceTrustOperation(()=>trustReconciler.reconcile(snapshot))},"onSnapshot"),onError:__name(error=>{publishedWorkflowTrustPolicy={publication:publishedWorkflowTrustPolicy.publication+1};daemonLog.error("workspace trust policy monitor failed",error instanceof Error?error:null)},"onError")});app2.locals.stopTrustPolicyMonitor=()=>trustMonitor.stop();app2.locals.requestTrustReconcile=()=>trustMonitor.requestReconcile("manual");app2.locals.waitForTrustPolicyIdle=()=>runWorkspaceTrustOperation(async()=>void 0);await trustMonitor.start()}const activePrimaryBridge=workspaceRegistry.primaryEntry.current?.runtime.bridge;bridgeRef=activePrimaryBridge;return{app:app2,bridge:activePrimaryBridge}},"buildRuntime");if(deps.bridge){const runtime=await buildRuntime();runtimeAppForCleanup=runtime.app;bridgeRef=runtime.bridge;if(!opts.channelSelection){runtimeApp=runtime.app;runtimeStartupSettled=true;markRuntimeReady()}}cliVersion??=await cliVersionPromise;const bootstrapApp=createBootstrapServeApp({opts,getPort:__name(()=>actualPort,"getPort"),boundWorkspace,startup,daemonLog,qwenCodeVersion:cliVersion,sessionShellCommandEnabled,sessionArtifactsPersistenceAvailable,workspaceRuntimeAvailable:deps.bridge===void 0||typeof deps.bridge.getWorkspaceRuntimeLifecycleSnapshot==="function",currentSessionSchedulingAvailable:false,permissionPolicy,multiWorkspaceCapabilitiesRequireRuntime:workspaceInputs.length>1,getRuntimeError:__name(()=>runtimeStartupError,"getRuntimeError"),getChannelWorkerSnapshot,getChannelWorkerSnapshots,getChannelRestoreFailures:__name(()=>channelRestoreFailures.list(),"getChannelRestoreFailures"),onHealthServed:deferRuntimeUntilFirstHealth?()=>startRuntimeAfterHealth?.():void 0});const deferredChannelWebhookAuth=deferRuntimeUntilFirstHealth?createDeferredChannelWebhookAuth(resolveChannelWebhookConfigSource,await loadChannelWebhookConfigRuntime(),daemonLog):void 0;const app=runtimeApp??createDelegatingServeApp(bootstrapApp,()=>runtimeApp,{waitForDeferredRuntimeRoutes:deferRuntimeUntilFirstHealth,startRuntime:__name(()=>startRuntimeForRequest?.()??false,"startRuntime"),runtimeReady,authenticateDeferredRuntimeRequest:bearerAuth(opts.token),authenticateDeferredChannelWebhookRequest:deferredChannelWebhookAuth,isPreAuthRequest:__name(async req=>{if(req.path.startsWith("/agent-hosts/")){return true}if(!webShellMounted){return false}const webShellStatic=await import("./web-shell-static-FZQRCYGX.js");return webShellStatic.isPreAuthWebShellRequest(req)},"isPreAuthRequest")});let listenHostname=opts.hostname;if(opts.hostname.startsWith("[")){const inner=opts.hostname.slice(1,-1);if(!opts.hostname.endsWith("]")||inner.length===0||inner.includes("]")){throw new Error(`Invalid --hostname "${opts.hostname}": brackets indicate an IPv6 literal but the value isn't a clean [addr] form. Pass the address without a trailing :port (use --port for that), e.g. "--hostname [::1] --port 4170".`)}listenHostname=inner}if(opts.maxConnections!==void 0&&(Number.isNaN(opts.maxConnections)||opts.maxConnections<0)){throw new TypeError(`Invalid maxConnections: ${opts.maxConnections}. Must be >= 0 (0 / Infinity = unlimited).`)}let channelValidationSettingsRuntime;let channelValidationTrustPolicy;let channelValidationTrustSnapshot;const resolveChannelWorkspaceGroupsAtListen=__name(()=>{const validationSettingsRuntime=channelValidationSettingsRuntime;if(!opts.channelSelection||!validationSettingsRuntime||!channelRuntime){return void 0}const registry=(runtimeApp??runtimeAppForCleanup)?.locals?.["workspaceRegistry"];const resolveRuntime=__name(workspaceCwd=>{const runtime=registry?.getByWorkspaceCwd(workspaceCwd);if(registry&&!runtime){throw Object.assign(new Error(`Workspace "${workspaceCwd}" is unavailable.`),{code:"workspace_unavailable"})}return runtime},"resolveRuntime");const resolveTrusted=__name((workspaceCwd,primary,runtime)=>{if(runtime)return runtime.trusted;if(primary&&deps.trustedWorkspace!==void 0){return deps.trustedWorkspace}if(!channelValidationTrustPolicy||!channelValidationTrustSnapshot){return false}return channelValidationTrustPolicy.evaluateDaemonWorkspaceTrust(channelValidationTrustSnapshot,workspaceCwd).targetTrusted},"resolveTrusted");const settingsByWorkspace=new Map;if(workspaceInputs.length===1){const workspace=workspaceInputs[0];const runtime=resolveRuntime(workspace.cwd);const trusted=resolveTrusted(workspace.cwd,true,runtime);if(!trusted){throw Object.assign(new Error(`Primary workspace "${workspace.cwd}" is not trusted; cannot host channels.`),{code:"untrusted_workspace"})}const effectiveEnv=runtime?workspaceRuntimeEffectiveEnv(runtime,daemonRuntimeBaseEnv):validationSettingsRuntime.environment.buildRuntimeEnvironment(validationSettingsRuntime.settings.loadSettings(workspace.cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:false,workspaceTrusted:true}).merged,workspace.cwd,daemonRuntimeBaseEnv,trusted).effectiveEnv;channelWebhookEnvByWorkspace.set(workspace.cwd,effectiveEnv);return void 0}const channelWorkspaces=workspaceInputs.filter(workspace=>!readSshWorkspace(workspace.cwd));const workspaces=channelWorkspaces.map((workspace,index)=>{const runtime=resolveRuntime(workspace.cwd);const trusted=resolveTrusted(workspace.cwd,index===0,runtime);const settings=validationSettingsRuntime.settings.loadSettings(workspace.cwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!trusted,workspaceTrusted:trusted});settingsByWorkspace.set(workspace.cwd,settings);channelWebhookEnvByWorkspace.set(workspace.cwd,runtime?workspaceRuntimeEffectiveEnv(runtime,daemonRuntimeBaseEnv):validationSettingsRuntime.environment.buildRuntimeEnvironment(settings.merged,workspace.cwd,daemonRuntimeBaseEnv,trusted).effectiveEnv);return{workspaceCwd:workspace.cwd,primary:runtime?.primary??index===0,trusted}});const grouping=resolveChannelWorkspaceGroups({workspaces,selection:opts.channelSelection,loadChannelsConfig:__name(cwd=>{const settings=settingsByWorkspace.get(cwd);if(!settings)return{};return channelRuntime.loadChannelsConfig(cwd,settings)},"loadChannelsConfig"),preferredOwners:channelOwnerHints,tolerant:channelStartupTolerantNames});if(!grouping.ok){throw Object.assign(new Error(grouping.error.message),{code:grouping.error.code,...grouping.error.channel?{channel:grouping.error.channel}:{}})}return{groups:grouping.groups,skipped:grouping.skipped??[]}},"resolveChannelWorkspaceGroupsAtListen");if(opts.channelSelection){try{channelValidationSettingsRuntime=await loadSettingsRuntimeModules();channelValidationTrustPolicy=await import("./daemon-trust-policy-IYD7NOGK.js");channelValidationTrustSnapshot=await channelValidationTrustPolicy.readDaemonTrustPolicySnapshot();if(opts.channelSelection.mode==="names"&&workspaceInputs.length>MAX_CHANNEL_CONTROL_WORKSPACES){const resolved=resolveChannelWorkspaceGroupsAtListen();assertChannelControlWorkspaceCapacity(resolved?.groups.map(group=>group.workspaceCwd)??[])}reserveChannelServicePidfile(opts.channelSelection)}catch(error){if(!channelSelectionFromSettings)throw error;removeCurrentServePidfile();opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error)}}return await new Promise((resolve3,reject)=>{let closeHost;const onListening=__name(error=>{if(error)return;startup.listenerReadyAt=new Date().toISOString();startup.processToListenMs=Math.round(process.uptime()*1e3);startup.runQwenServeToListenMs=Math.round(performance2.now()-runStartedAt);profileCheckpoint("serve_listener_ready");finalizeStartupProfile(`serve-${process.pid}`);const cap=opts.maxConnections??256;if(cap>0&&Number.isFinite(cap)){server.maxConnections=cap}const addr=server.address();actualPort=typeof addr==="object"&&addr?addr.port:opts.port;const scheme=tlsOptions?"https":"http";const url=`${scheme}://${formatHostForUrl(optsIn.hostname)}:${actualPort}`;const liveRuntimeBaseDir=path.dirname(daemonLogBaseDir);const liveDiscoveryOwners=[];const rememberLiveDiscoveryOwner=__name(owner=>{if(liveDiscoveryOwners.some(candidate=>candidate.runtimeBaseDir===owner.runtimeBaseDir&&candidate.instanceNonce===owner.instanceNonce&&candidate.pid===owner.pid)){return}liveDiscoveryOwners.push(owner)},"rememberLiveDiscoveryOwner");let liveDiscoveryPublish;let liveDiscoveryRetryTimer;let liveDiscoveryRetryTask;let liveDiscoveryBootRetryApp;let liveDiscoveryEnabled=false;let liveDiscoveryShuttingDown=false;let liveDiscoveryToggle=Promise.resolve();let attemptPendingLiveDiscovery;const pendingLiveDiscoveryBaseDirs=new Set;const warnedLiveDiscoveryOwners=new Set;let warnedLiveDiscoveryBootFailure=false;const liveDiscoveryRetryDelayMs=deps.liveDiscoveryRetryDelayMs!==void 0&&Number.isFinite(deps.liveDiscoveryRetryDelayMs)&&deps.liveDiscoveryRetryDelayMs>=10?Math.min(deps.liveDiscoveryRetryDelayMs,6e4):DEFAULT_LIVE_DISCOVERY_RETRY_MS;const scheduleLiveDiscoveryRetry=__name(()=>{if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled||liveDiscoveryRetryTimer||liveDiscoveryRetryTask||!liveDiscoveryBootRetryApp&&(pendingLiveDiscoveryBaseDirs.size===0||!attemptPendingLiveDiscovery)){return}liveDiscoveryRetryTimer=setTimeout(()=>{liveDiscoveryRetryTimer=void 0;if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled){return}const retryApp=liveDiscoveryBootRetryApp;liveDiscoveryBootRetryApp=void 0;const retryOperation=retryApp?publishLiveDiscovery(retryApp):attemptPendingLiveDiscovery?.();if(!retryOperation)return;const retry=retryOperation.finally(()=>{if(liveDiscoveryRetryTask===retry){liveDiscoveryRetryTask=void 0}scheduleLiveDiscoveryRetry()});liveDiscoveryRetryTask=retry},liveDiscoveryRetryDelayMs);liveDiscoveryRetryTimer.unref()},"scheduleLiveDiscoveryRetry");const cancelLiveDiscoveryRetry=__name(()=>{if(!liveDiscoveryRetryTimer)return;clearTimeout(liveDiscoveryRetryTimer);liveDiscoveryRetryTimer=void 0},"cancelLiveDiscoveryRetry");const publishLiveDiscovery=__name(candidateApp=>{if(liveDiscoveryShuttingDown)return Promise.resolve();if(!resolveAcpHttpEnabled())return Promise.resolve();if(candidateApp.locals?.["liveVoiceEnabled"]!==true)return Promise.resolve();liveDiscoveryEnabled=true;if(liveDiscoveryPublish)return liveDiscoveryPublish;const coordinator=candidateApp.locals?.["liveCoordinator"];const instanceNonce=coordinator?.daemonInstanceNonce;if(typeof instanceNonce!=="string")return Promise.resolve();let publicationFailed=false;let publicationRetryable=false;const publication=serveAppLifecycle.startBoot().then(()=>loadLiveDiscoveryRuntime()).then(async({handoffLiveDiscoveryOwner,LiveDiscoveryOwnerActiveError,LiveDiscoveryPublicationError,removeLiveDiscoveryFile,writeLiveDiscoveryFile})=>{if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled)return;liveDiscoveryBootRetryApp=void 0;warnedLiveDiscoveryBootFailure=false;const stableBaseDir=liveDiscoveryStableBaseDir;const runtimeBaseDir=path.resolve(liveRuntimeBaseDir);const targetBaseDirs=new Set;if(runtimeBaseDir!==stableBaseDir){targetBaseDirs.add(runtimeBaseDir)}targetBaseDirs.add(stableBaseDir);for(const baseDir of targetBaseDirs){pendingLiveDiscoveryBaseDirs.add(baseDir)}const record={url,...token?{token}:{},protocolVersion:LIVE_HOST_PROTOCOL_VERSION,pid:process.pid,instanceNonce};attemptPendingLiveDiscovery=__name(async()=>{const targets=[...pendingLiveDiscoveryBaseDirs];const published=[];const rollbackPublished=__name(async()=>{for(const owner of published.splice(0)){try{await removeLiveDiscoveryFile(owner.runtimeBaseDir,owner)}catch(cleanupError){rememberLiveDiscoveryOwner(owner);daemonLog.warn(`failed to roll back Live Host discovery at ${owner.runtimeBaseDir}: ${cleanupError instanceof Error?cleanupError.message:String(cleanupError)}`)}}},"rollbackPublished");for(const runtimeBaseDir2 of targets){if(liveDiscoveryShuttingDown||!liveDiscoveryEnabled){await rollbackPublished();return}try{await handoffLiveDiscoveryOwner(runtimeBaseDir2,record,async()=>void 0);await writeLiveDiscoveryFile(runtimeBaseDir2,record);published.push({runtimeBaseDir:runtimeBaseDir2,instanceNonce,pid:process.pid})}catch(err){if(err instanceof LiveDiscoveryPublicationError&&err.published){published.push({runtimeBaseDir:runtimeBaseDir2,instanceNonce,pid:process.pid})}await rollbackPublished();if(err instanceof LiveDiscoveryOwnerActiveError){if(!warnedLiveDiscoveryOwners.has(runtimeBaseDir2)){warnedLiveDiscoveryOwners.add(runtimeBaseDir2);daemonLog.warn(`failed to publish Live Host discovery at ${runtimeBaseDir2}: ${err.message}`)}return}daemonLog.warn(`failed to publish Live Host discovery at ${runtimeBaseDir2}: ${err instanceof Error?err.message:String(err)}`);return}}for(const owner of published){pendingLiveDiscoveryBaseDirs.delete(owner.runtimeBaseDir);warnedLiveDiscoveryOwners.delete(owner.runtimeBaseDir);rememberLiveDiscoveryOwner(owner)}},"attemptPendingLiveDiscovery");await attemptPendingLiveDiscovery();scheduleLiveDiscoveryRetry()}).catch(err=>{publicationFailed=true;publicationRetryable=err instanceof ConversationRuntimeOwnershipError&&err.retryable;if(!publicationRetryable||!warnedLiveDiscoveryBootFailure){warnedLiveDiscoveryBootFailure=publicationRetryable;daemonLog.warn(`failed to publish Live Host discovery: ${err instanceof Error?err.message:String(err)}`)}});const trackedPublication=publication.finally(()=>{if(publicationFailed&&liveDiscoveryPublish===trackedPublication){liveDiscoveryPublish=void 0;if(publicationRetryable&&!liveDiscoveryShuttingDown&&liveDiscoveryEnabled){liveDiscoveryBootRetryApp=candidateApp;scheduleLiveDiscoveryRetry()}}});liveDiscoveryPublish=trackedPublication;return liveDiscoveryPublish},"publishLiveDiscovery");const removeLiveDiscoveryOwners=__name(async()=>{const owners=[...liveDiscoveryOwners];if(owners.length===0)return;let removeLiveDiscoveryFile;try{({removeLiveDiscoveryFile}=await loadLiveDiscoveryRuntime())}catch(err){throw new Error("Failed to load Live discovery cleanup support.",{cause:err})}const errors=[];for(const owner of owners){try{await removeLiveDiscoveryFile(owner.runtimeBaseDir,owner);const index=liveDiscoveryOwners.indexOf(owner);if(index>=0)liveDiscoveryOwners.splice(index,1)}catch(err){errors.push(err)}}if(errors.length>0){throw new AggregateError(errors,"Live Host discovery cleanup is incomplete.")}},"removeLiveDiscoveryOwners");const unpublishLiveDiscovery=__name(async()=>{liveDiscoveryEnabled=false;liveDiscoveryBootRetryApp=void 0;warnedLiveDiscoveryBootFailure=false;cancelLiveDiscoveryRetry();pendingLiveDiscoveryBaseDirs.clear();attemptPendingLiveDiscovery=void 0;await liveDiscoveryPublish;await liveDiscoveryRetryTask;liveDiscoveryPublish=void 0;liveDiscoveryRetryTask=void 0;await removeLiveDiscoveryOwners()},"unpublishLiveDiscovery");const attachLiveDiscoveryControl=__name(candidateApp=>{candidateApp.locals.setLiveDiscoveryEnabled=enabled=>{const operation=liveDiscoveryToggle.then(()=>enabled?publishLiveDiscovery(candidateApp):unpublishLiveDiscovery());liveDiscoveryToggle=operation.catch(()=>void 0);return operation};candidateApp.locals.onConversationRuntimeReady=()=>{void publishLiveDiscovery(candidateApp)}},"attachLiveDiscoveryControl");const cleanupLiveDiscovery=__name(async()=>{liveDiscoveryShuttingDown=true;cancelLiveDiscoveryRetry();await liveDiscoveryToggle;await unpublishLiveDiscovery()},"cleanupLiveDiscovery");let shuttingDown=false;let closePromise;let runtimeStartupTimer;let runtimeStartAfterHealthTimer;let runtimeStartFallbackTimer;const runtimeStartupTimeoutMs=resolveRuntimeStartupTimeoutMs(deps.runtimeStartupTimeoutMs);const clearRuntimeStartupTimer=__name(()=>{if(!runtimeStartupTimer)return;clearTimeout(runtimeStartupTimer);runtimeStartupTimer=void 0},"clearRuntimeStartupTimer");const clearRuntimeStartFallbackTimer=__name(()=>{if(!runtimeStartFallbackTimer)return;clearTimeout(runtimeStartFallbackTimer);runtimeStartFallbackTimer=void 0},"clearRuntimeStartFallbackTimer");const clearRuntimeStartAfterHealthTimer=__name(()=>{if(!runtimeStartAfterHealthTimer)return;clearTimeout(runtimeStartAfterHealthTimer);runtimeStartAfterHealthTimer=void 0},"clearRuntimeStartAfterHealthTimer");const cancelDeferredRuntimeStartup=__name(()=>{if(!deferRuntimeUntilFirstHealth||runtimeStarting||runtimeStartupSettled)return;daemonLog.info("deferred runtime: cancelled, server closed before startup");runtimeStartupSettled=true;const error2=new Error(RUNTIME_STARTUP_CANCELLED_MESSAGE);runtimeStartupError=error2.message;markRuntimeFailed(error2)},"cancelDeferredRuntimeStartup");const shutdownBridgeAfterFailedStartup=__name(async bridge=>{if(!bridge||deps.bridge)return;if(shutdownBridges.has(bridge))return;shutdownBridges.add(bridge);try{await bridge.shutdown()}catch(shutdownErr){daemonLog.error("bridge shutdown after runtime startup error failed",shutdownErr instanceof Error?shutdownErr:null)}finally{if(bridgeRef===bridge){bridgeRef=void 0}}},"shutdownBridgeAfterFailedStartup");const stopChannelWorkerAfterFailedStartup=__name(async()=>{if(!channelWorkerManager)return true;try{await channelWorkerManager.shutdown();return true}catch(stopErr){daemonLog.error("channel worker stop after runtime startup error failed",stopErr instanceof Error?stopErr:null);return false}},"stopChannelWorkerAfterFailedStartup");const failRuntimeStartup=__name(async(err,bridgeForCleanup)=>{const error2=err instanceof Error?err:new Error(String(err));markServeAppStartupFailed(error2);if(runtimeStartupSettled){disposeRuntimeAppResources(runtimeApp??runtimeAppForCleanup);await shutdownBridgeAfterFailedStartup(bridgeForCleanup);return}runtimeStartupSettled=true;disposeRuntimeAppResources(runtimeApp??runtimeAppForCleanup);runtimeApp=void 0;clearRuntimeStartupTimer();const message=error2.message;runtimeStartupError=message;if(startup.preheat.status==="scheduled"||startup.preheat.status==="running"){startup.preheat.status="failed";startup.preheat.error=message}writeStderrLine(`qwen serve: runtime startup failed: ${message}`);daemonLog.error("runtime startup failed",error2);markRuntimeFailed(error2);if(closeServerAfterChannelWorkerStartupFailure&&server.listening){server.close(closeErr=>{if(closeErr){daemonLog.error("server close after runtime startup error failed",closeErr)}});server.closeAllConnections()}const channelWorkerStopped=await stopChannelWorkerAfterFailedStartup();disposeDaemonEventLoopMonitor();if(channelWorkerStopped)removeCurrentServePidfile();const bridgesForCleanup=bridgeForCleanup?[bridgeForCleanup,...getRuntimeBridgesForCleanup()]:getRuntimeBridgesForCleanup();for(const bridge of[...new Set(bridgesForCleanup)]){await shutdownBridgeAfterFailedStartup(bridge)}},"failRuntimeStartup");const armRuntimeStartupTimer=__name(()=>{if(runtimeStartupTimeoutMs<=0||runtimeStartupTimer)return;runtimeStartupTimer=setTimeout(()=>{const timeoutError=new Error(`Daemon runtime startup timed out after ${runtimeStartupTimeoutMs}ms.`);void failRuntimeStartup(timeoutError)},runtimeStartupTimeoutMs);runtimeStartupTimer.unref()},"armRuntimeStartupTimer");const resolveRuntimeChannelGroups=__name(async(channelSelection,candidateApp,operation)=>{const registry=candidateApp.locals?.["workspaceRegistry"];if(!registry){throw new Error("Workspace registry is not available for channel workers.")}const runtimes=registry.list().filter(runtime=>runtime.provenance!=="live-conversation");if(runtimes.length<=1&&operation==="initial"){const primary=registry.primary;if(!primary.trusted){throw Object.assign(new Error(`Primary workspace "${primary.workspaceCwd}" is not trusted; cannot host channels.`),{code:"untrusted_workspace"})}return[{workspaceCwd:primary.workspaceCwd,selection:channelSelection}]}const workerRuntime=await ensureChannelRuntime();const settingsRuntime=await loadSettingsRuntimeModules();const settingsByWorkspace=new Map;const channelRuntimes=runtimes.filter(runtime=>!runtime.routeFileSystemFactory.sshWorkspace);const grouping=resolveChannelWorkspaceGroups({workspaces:channelRuntimes.map(runtime=>{const settings=settingsRuntime.settings.loadSettings(runtime.workspaceCwd,{skipLoadEnvironment:true,skipWorkspaceSettings:!runtime.trusted,workspaceTrusted:runtime.trusted});settingsByWorkspace.set(runtime.workspaceCwd,settings);return{workspaceCwd:runtime.workspaceCwd,primary:runtime.primary,trusted:runtime.trusted,provenance:runtime.provenance}}),selection:channelSelection,loadChannelsConfig:__name(cwd=>{const settings=settingsByWorkspace.get(cwd);return settings?workerRuntime.loadChannelsConfig(cwd,settings):{}},"loadChannelsConfig"),preferredOwners:channelOwnerHints});if(!grouping.ok){throw Object.assign(new Error(grouping.error.message),{code:grouping.error.code,...grouping.error.channel?{channel:grouping.error.channel}:{}})}return grouping.groups},"resolveRuntimeChannelGroups");ensureChannelWorkerManager=__name(()=>{if(channelWorkerManager)return Promise.resolve(channelWorkerManager);if(channelWorkerManagerStarting)return channelWorkerManagerStarting;const starting=(async()=>{const candidateApp=runtimeApp??runtimeAppForCleanup;const registry=candidateApp?.locals?.["workspaceRegistry"];if(!candidateApp||!registry){throw new Error("Workspace registry is not available for channels.")}const workerRuntime=await ensureChannelRuntime();const workerHostname=tlsOptions?optsIn.hostname:opts.hostname;const workerDaemonUrl=formatChannelWorkerDaemonUrl(workerHostname,actualPort,tlsOptions!==void 0);(deps.channelWorkerUrlCertifier??assertChannelWorkerDaemonUrlIsLocal)(workerDaemonUrl,workerHostname);if(tlsOptions&&tlsCertPath&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]==="0"){daemonLog.warn(`NODE_TLS_REJECT_UNAUTHORIZED=0 disables certificate verification for channel workers; skipping the worker TLS trust check.`)}else if(tlsOptions&&tlsCertPath){const operatorCaCertPath=process.env["NODE_EXTRA_CA_CERTS"];let operatorCaCert;let operatorCaCertReadError;if(operatorCaCertPath){try{operatorCaCert=fs.readFileSync(operatorCaCertPath)}catch(error2){operatorCaCertReadError=error2?.code??"read failed"}}let predictedGaps=[];try{predictedGaps=describeWorkerTlsTrustGaps({cert:tlsOptions.cert,certPath:tlsCertPath,certSourcePath:tlsCertPath,daemonUrl:workerDaemonUrl,...operatorCaCertPath?{operatorCaCertPath}:{},...operatorCaCert?{operatorCaCert,operatorCaCertSourcePath:operatorCaCertPath}:{},...operatorCaCertReadError?{operatorCaCertReadError}:{}})}catch(error2){if(!(error2 instanceof ExtraCaInspectionError))throw error2;daemonLog.warn(`Channel worker TLS trust-gap inspection could not run: ${error2.message} Continuing with the live handshake probe only.`)}const workerCaCertPath=workerRuntime.resolveWorkerCaCertPath(tlsCertPath,operatorCaCertPath);const trustFailure=await(deps.workerTlsTrustVerifier??verifyWorkerTlsTrust)({daemonUrl:workerDaemonUrl,caCertPath:workerCaCertPath});if(shuttingDown||runtimeStartupError!==void 0){throw new Error("Daemon stopped while the channel worker TLS trust check was running.")}if(trustFailure){if(predictedGaps.length>0){for(const gap of predictedGaps)daemonLog.warn(gap)}else{daemonLog.warn(`Channel worker TLS verification failed against the exact CA bundle workers receive (${sanitizeLogText(normalizeWorkerDiagnostic(trustFailure.code),80)}): ${sanitizeLogText(normalizeWorkerDiagnostic(trustFailure.message),300)}`)}}}const createSupervisor=deps.channelWorkerSupervisorFactory??workerRuntime.createChannelWorkerSupervisor;const createGroup=__name(groups=>workerRuntime.createChannelWorkerGroup({groups,registry,createSupervisor,shared:{cliEntryPath:workerRuntime.findCliEntryPath(),daemonUrl:workerDaemonUrl,...token?{daemonToken:token}:{},...tlsCertPath?{workerTlsCaCertPath:tlsCertPath}:{}},onReady:__name(snapshot=>{if(runtimeStartupError!==void 0)return;if(workspaceInputs.length>1){daemonLog.info("channel worker ready",{workspace:snapshot.workspaceCwd,pid:snapshot.pid,channels:snapshot.channels})}channelWorkerManager?.workerChanged();if(!runtimeStartupSettled)writeChannelWorkerPidfile()},"onReady"),onExit:__name(snapshot=>{const workspacePrefix=workspaceInputs.length>1?`workspace=${snapshot.workspaceCwd}, `:"";daemonLog.warn(`channel worker exited (${workspacePrefix}state=${snapshot.state}, pid=${snapshot.pid??"unknown"}, code=${snapshot.exitCode??"null"}, signal=${snapshot.signal??"null"}, error=${snapshot.error??"none"}, restartCount=${snapshot.restartCount??0}, nextRestartAt=${snapshot.nextRestartAt??"none"}, staleHeartbeatAt=${snapshot.staleHeartbeatAt??"none"})`);channelWorkerManager?.workerChanged();if(!runtimeStartupSettled)writeChannelWorkerPidfile()},"onExit"),onStateChange:__name(()=>{channelWorkerManager?.workerChanged();if(!runtimeStartupSettled)writeChannelWorkerPidfile()},"onStateChange"),onLog:__name(({stream,line,workspaceCwd})=>{const message=workspaceInputs.length>1?`channel worker [${workspaceCwd}] ${stream}: ${line}`:`channel worker ${stream}: ${line}`;if(stream==="stderr")daemonLog.warn(message);else daemonLog.info(message)},"onLog")}),"createGroup");channelWorkerManager=workerRuntime.createChannelWorkerManager({resolveGroups:__name((selection,operation)=>resolveRuntimeChannelGroups(selection,candidateApp,operation),"resolveGroups"),createGroup,reserveLease:reserveChannelServicePidfile,releaseLease:__name(()=>{removeCurrentServePidfile();if(channelPidfileReserved){throw new Error("Failed to release the channel service lease.")}},"releaseLease"),initialLeaseReserved:channelPidfileReserved,onCommittedSelection:__name((_selection,groups)=>{channelWorkspaceGroups=groups;channelOwnerHints=new Map([...bootChannelOwnerHints,...groups.flatMap(group=>group.selection.mode==="names"?group.selection.names.map(name=>[name,group.workspaceCwd]):[])]);channelWebhookConfigVersion+=1;refreshChannelWebhookConfigs?.()},"onCommittedSelection"),onStateChange:__name(()=>{if(runtimeStartupSettled)writeChannelWorkerPidfile()},"onStateChange")});return channelWorkerManager})();channelWorkerManagerStarting=starting;void starting.then(()=>{if(channelWorkerManagerStarting===starting){channelWorkerManagerStarting=void 0}},()=>{if(channelWorkerManagerStarting===starting){channelWorkerManagerStarting=void 0}});return starting},"ensureChannelWorkerManager");const completeRuntimeStartup=__name(async candidateApp=>{if(runtimeStartupSettled)return;runtimeApp=candidateApp;attachLiveDiscoveryControl(candidateApp);const acpHandle=candidateApp.locals?.["acpHandle"];attachAcpWsTransport(acpHandle);if(opts.channelSelection){closeServerAfterChannelWorkerStartupFailure=true;let manager;try{manager=await ensureChannelWorkerManager();await manager.startInitial(opts.channelSelection)}catch(error2){if(!channelSelectionFromSettings||runtimeStartupSettled){throw error2}closeServerAfterChannelWorkerStartupFailure=false;if(opts.channelSelection?.mode==="names"){const reported=channelStartupMessages(error2);const message=error2 instanceof Error?error2.message:String(error2);channelRestoreFailures.record(opts.channelSelection.names.flatMap(channel=>{const owners=bootChannelClaimants.get(channel)??[boundWorkspace];return owners.map(workspaceCwd=>({workspaceCwd,channel,message:reported.get(channel)??message}))}))}opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error2);try{if(manager){await manager.stopSelection()}else{removeCurrentServePidfile();if(channelPidfileReserved){throw new Error("Failed to release the channel service lease.")}}}catch(cleanupError){reportConfiguredChannelStartupFailure(cleanupError)}}if(runtimeStartupSettled)return}if(runtimeStartupSettled)return;markServeAppStartupReady();await publishLiveDiscovery(candidateApp);runtimeStartupSettled=true;clearRuntimeStartupTimer();markRuntimeReady()},"completeRuntimeStartup");const scheduleWorkspaceMcpDiscoveryAfterPreheat=__name(app2=>{if(runtimeStartupError!==void 0){daemonLog.info("workspace runtime ensure after preheat skipped: runtime startup failed");return}if(shuttingDown){daemonLog.info("workspace runtime ensure after preheat skipped: shutting down");return}const registry=app2.locals?.["workspaceRegistry"];const primaryEntry=registry?.primaryEntry;const runtime=primaryEntry?.state==="active"?primaryEntry.current?.runtime:void 0;if(!runtime){daemonLog.info("workspace runtime ensure after preheat skipped: no primary runtime");return}const coordinator=getWorkspaceRuntimeCoordinatorIfSupported?.(runtime);if(!coordinator){daemonLog.info("workspace runtime ensure after preheat skipped: workspace runtime lifecycle is not supported");return}void coordinator.ensure({keepAliveMs:ENSURE_KEEP_ALIVE_MS}).catch(err=>{if(shuttingDown||runtimeStartupError!==void 0){return}daemonLog.warn(`workspace runtime ensure after preheat failed: ${deepestErrorMessage(err)}`)})},"scheduleWorkspaceMcpDiscoveryAfterPreheat");const startBridgePreheat=__name((bridge,app2)=>{startup.preheat.status="running";const preheatStartedAt=performance2.now();bridge.preheat().then(()=>{startup.preheat.status="succeeded";startup.preheat.durationMs=Math.round(performance2.now()-preheatStartedAt);scheduleWorkspaceMcpDiscoveryAfterPreheat(app2)}).catch(err=>{const message=err instanceof Error?err.message:String(err);startup.preheat.status="failed";startup.preheat.durationMs=Math.round(performance2.now()-preheatStartedAt);startup.preheat.error=message;writeStderrLine(`qwen serve: ACP preheat failed, will retry on first session: ${message}`)})},"startBridgePreheat");const startRuntime=__name(()=>{if(runtimeStarting)return false;armRuntimeStartupTimer();clearRuntimeStartAfterHealthTimer();clearRuntimeStartFallbackTimer();runtimeStarting=buildRuntime().then(async runtime=>{if(runtimeStartupSettled){disposeRuntimeAppResources(runtime.app);await shutdownBridgeAfterFailedStartup(runtime.bridge);return}bridgeRef=runtime.bridge;runtimeAppForCleanup=runtime.app;if(shuttingDown){await failRuntimeStartup(new Error("Daemon runtime stopped before mounting."),runtime.bridge);return}if(shouldPreheat&&runtime.bridge){startBridgePreheat(runtime.bridge,runtime.app)}await completeRuntimeStartup(runtime.app)}).catch(err=>failRuntimeStartup(err));return true},"startRuntime");startRuntimeForRequest=startRuntime;const scheduleRuntimeStartFallback=__name(()=>{if(shuttingDown||runtimeStarting||runtimeStartFallbackTimer)return;daemonLog.info(`deferred runtime: scheduling fallback start in ${FAST_PATH_RUNTIME_START_FALLBACK_MS}ms`);runtimeStartFallbackTimer=setTimeout(()=>{runtimeStartFallbackTimer=void 0;if(shuttingDown)return;daemonLog.info("deferred runtime: fallback timer fired, starting");startRuntime()},FAST_PATH_RUNTIME_START_FALLBACK_MS);runtimeStartFallbackTimer.unref()},"scheduleRuntimeStartFallback");startRuntimeAfterHealth=__name(()=>{if(shuttingDown||runtimeStarting||runtimeStartAfterHealthTimer){return}clearRuntimeStartFallbackTimer();daemonLog.info(`deferred runtime: health served, scheduling start in ${FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS}ms`);runtimeStartAfterHealthTimer=setTimeout(()=>{runtimeStartAfterHealthTimer=void 0;if(shuttingDown)return;daemonLog.info("deferred runtime: health timer fired, starting");startRuntime()},FAST_PATH_RUNTIME_START_AFTER_HEALTH_MS);runtimeStartAfterHealthTimer.unref()},"startRuntimeAfterHealth");const onSignal=__name(async signal=>{if(shuttingDown){daemonLog.warn(`received ${signal} during drain \u2014 forcing exit`);removeDiscoveryRecord();try{managedProcessRegistry?.killAllSync();channelWorkerManager?.killAllSync();for(const runtimeBridge of getRuntimeBridgesForCleanup()){runtimeBridge.killAllSync()}}catch(err){daemonLog.error("force-kill error",err instanceof Error?err:null)}await flushDaemonLogBounded(daemonLog,DAEMON_LOG_FORCED_FLUSH_BUDGET_MS);process.exit(1);return}if(!loggerPublished){loggerSignalOwned=true;loggerLifecycle.signalOwned()}daemonLog.warn(`received ${signal}, draining`);try{await handle.close();process.exit(runtimeStartupError===void 0?0:1)}catch(err){daemonLog.error("shutdown error",err instanceof Error?err:null);if(hasRetryableChannelWorkerShutdownError(err)){daemonLog.error("refusing to exit while a channel worker or service lease remains; signal again to retry after the child exits (another signal during that retry forces exit)");return}await flushDaemonLogBounded(daemonLog,DAEMON_LOG_FORCED_FLUSH_BUDGET_MS);process.exit(1)}},"onSignal");const onUncaughtExceptionMonitor=__name(()=>{if(process.listenerCount("uncaughtException")===0&&!channelWorkerManager?.state().enabled){removeCurrentServePidfile()}},"onUncaughtExceptionMonitor");const handle={server,url,bridge:handleBridge,webShellMounted,resolvedToken:token,runtimeReady,getPrimaryWorkspaceRuntime:__name(()=>{const registry=runtimeApp?.locals?.["workspaceRegistry"];const entry=registry?.primaryEntry;return entry?.state==="active"?entry.current?.runtime:void 0},"getPrimaryWorkspaceRuntime"),getLocalControl:__name(()=>(runtimeApp??runtimeAppForCleanup)?.locals?.["localControlService"],"getLocalControl"),close:__name(()=>{if(closePromise)return closePromise;closePromise=new Promise((res,rej)=>{shuttingDown=true;liveDiscoveryShuttingDown=true;cancelLiveDiscoveryRetry();channelControlDraining=true;const initiallyMountedApp=runtimeApp??runtimeAppForCleanup;const beginRuntimeCoordinatorDrains=__name(app2=>{const registry=app2?.locals?.["workspaceRegistry"];for(const workspaceRuntime of registry?.list()??[]){getWorkspaceRuntimeCoordinatorIfSupported?.(workspaceRuntime)?.beginDrain()}},"beginRuntimeCoordinatorDrains");beginRuntimeCoordinatorDrains(initiallyMountedApp);const initiallyMountedManagement=initiallyMountedApp?.locals?.["workspaceManagementHandle"];const initiallyMountedSessionMaintenance=initiallyMountedApp?.locals?.["sessionArchiveCoordinator"];const initiallyMountedConversationActivity=initiallyMountedApp?.locals?.["conversationRuntimeActivity"];const initiallyMountedCsiStop=initiallyMountedApp?.locals?.["stopHostedCsiSessions"];const initialManagementWait=initiallyMountedManagement?.sealAndWait?.();const initiallyMountedLive=initiallyMountedApp?.locals;const initialLiveWait=initiallyMountedLive?.sealAndWaitLiveCoordinator?.();const initialSessionMaintenanceWait=initiallyMountedSessionMaintenance?.sealMaintenanceAndWait?.();const initialConversationActivityWait=initiallyMountedConversationActivity?.sealAndWait?.();const initialCsiWait=initiallyMountedCsiStop?.();let processRegistryShutdown;const startProcessRegistryShutdown=__name(()=>{processRegistryShutdown??=managedProcessRegistry?.shutdown().then(()=>void 0,error2=>error2 instanceof Error?error2:new Error(String(error2)))},"startProcessRegistryShutdown");startProcessRegistryShutdown();clearRuntimeStartAfterHealthTimer();clearRuntimeStartFallbackTimer();cancelDeferredRuntimeStartup();drainPreTransportUpgrades?.();let settled=false;let bridgeShutdownError;let channelWorkerShutdownError;const finish=__name(err=>{if(settled)return;settled=true;const accessLogController=(runtimeApp??runtimeAppForCleanup)?.locals?.[ACCESS_LOG_CONTROLLER_LOCAL];accessLogController?.sealAndFlushSuppressed();const preserveSignalHandlers=channelWorkerShutdownError!==void 0&&channelWorkerManager?.state().enabled===true;if(!preserveSignalHandlers){process.removeListener("SIGINT",onSignal);process.removeListener("SIGTERM",onSignal);process.removeListener("SIGHUP",onSignal)}process.removeListener("uncaughtExceptionMonitor",onUncaughtExceptionMonitor);void(coreRuntimePromise?coreRuntimePromise.then(core=>core.shutdownTelemetry()):Promise.resolve()).catch(telemetryErr=>{writeStderrLine(`qwen serve: telemetry shutdown error: ${telemetryErr instanceof Error?telemetryErr.message:String(telemetryErr)}`)}).finally(async()=>{let finalErr=err??bridgeShutdownError??channelWorkerShutdownError;const retryableChannelClose=channelWorkerShutdownError!==void 0&&channelWorkerManager?.state().enabled===true;if(retryableChannelClose){const retryableError=channelWorkerShutdownError;await flushDaemonLogBounded(daemonLog,DAEMON_LOG_FORCED_FLUSH_BUDGET_MS);closePromise=void 0;shuttingDown=false;channelControlDraining=false;retryableChannelWorkerShutdownErrors.add(retryableError);rej(retryableError);return}try{await cleanupLiveDiscovery()}catch(cleanupError){const normalizedCleanupError=cleanupError instanceof Error?cleanupError:new Error(String(cleanupError));if(finalErr){writeDaemonLifecycleBestEffort(()=>{daemonLog.error("Live Host discovery cleanup failed during shutdown",normalizedCleanupError)})}finalErr??=normalizedCleanupError}if(loggerPublished||loggerSignalOwned){writeDaemonLifecycleBestEffort(()=>{if(finalErr){daemonLog.error("daemon shutdown incomplete",finalErr)}else{daemonLog.info("daemon stopped")}});clearLoaderKeyRejectionReporterIfCurrent(loaderRejectionReporter);await daemonLog.close()}restoreScrubbedLoaderEnv();if(finalErr)rej(finalErr);else res()})},"finish");void(coreRuntimePromise?coreRuntimePromise.then(core=>core.forceFlushMetrics()):Promise.resolve()).catch(flushErr=>{daemonLog.warn(`pre-shutdown metrics flush failed: ${flushErr instanceof Error?flushErr.message:String(flushErr)}`)});Promise.resolve().then(async()=>{await waitForRuntimeStartingForShutdown(runtimeStarting,daemonLog);const appForCleanup=runtimeApp??runtimeAppForCleanup;await appForCleanup?.locals?.["cleanupDaemonUpdate"]?.();const workspaceManagementHandle=appForCleanup?.locals?.["workspaceManagementHandle"];const sessionMaintenance=appForCleanup?.locals?.["sessionArchiveCoordinator"];const conversationActivity=appForCleanup?.locals?.["conversationRuntimeActivity"];await initialManagementWait;if(workspaceManagementHandle!==initiallyMountedManagement){await workspaceManagementHandle?.sealAndWait?.()}const liveLifecycleHandle=appForCleanup?.locals;await initialLiveWait;if(liveLifecycleHandle!==initiallyMountedLive){await liveLifecycleHandle?.sealAndWaitLiveCoordinator?.()}await initialSessionMaintenanceWait;if(sessionMaintenance!==initiallyMountedSessionMaintenance){await sessionMaintenance?.sealMaintenanceAndWait?.()}await initialConversationActivityWait;if(conversationActivity!==initiallyMountedConversationActivity){await conversationActivity?.sealAndWait?.()}const csiStop=appForCleanup?.locals?.["stopHostedCsiSessions"];await initialCsiWait;if(csiStop!==initiallyMountedCsiStop)await csiStop?.();stopTrustPolicyMonitor(appForCleanup);const waitForTrustPolicyIdle=appForCleanup?.locals?.["waitForTrustPolicyIdle"];await waitForTrustPolicyIdle?.().catch(err=>{daemonLog.error("workspace trust reconciliation shutdown wait failed",err instanceof Error?err:null)});beginRuntimeCoordinatorDrains(appForCleanup);startProcessRegistryShutdown();disposeRuntimeAppResources(appForCleanup);disposeDaemonEventLoopMonitor();if(channelWorkerManager){await channelWorkerManager.shutdown().catch(err=>{daemonLog.error("channel worker stop error",err instanceof Error?err:null);channelWorkerShutdownError=err instanceof Error?err:new Error(String(err))})}else{removeCurrentServePidfile()}const runtimeRemoval=appForCleanup?.locals?.["workspaceRuntimeRemoval"];const workspaceRegistry=appForCleanup?.locals?.["workspaceRegistry"];const managedRuntimeBridges=new Set;if(runtimeRemoval&&workspaceRegistry){const managedRuntimes=workspaceRegistry.listManaged();for(const workspaceRuntime of managedRuntimes){managedRuntimeBridges.add(workspaceRuntime.bridge)}await Promise.all(managedRuntimes.map(workspaceRuntime=>runtimeRemoval.disposeRuntime(workspaceRuntime,"daemon_shutdown").catch(err=>{daemonLog.error("workspace runtime shutdown error",err instanceof Error?err:null);bridgeShutdownError=err instanceof Error?err:new Error(String(err));try{workspaceRuntime.bridge.killAllSync()}catch{}})))}for(const bridgeForShutdown of getRuntimeBridgesForCleanup()){if(managedRuntimeBridges.has(bridgeForShutdown))continue;if(shutdownBridges.has(bridgeForShutdown))continue;shutdownBridges.add(bridgeForShutdown);await bridgeForShutdown.shutdown().catch(err=>{shutdownBridges.delete(bridgeForShutdown);daemonLog.error("bridge shutdown error",err instanceof Error?err:null);bridgeShutdownError=err instanceof Error?err:new Error(String(err))})}const processRegistryError=await processRegistryShutdown;if(processRegistryError){daemonLog.error("ACP process registry shutdown error",processRegistryError);bridgeShutdownError??=processRegistryError}}).then(()=>finish(),error2=>finish(error2 instanceof Error?error2:new Error(String(error2))))});return closePromise},"close")};closeHost=handle.close;handle.close=async()=>{await serveAppLifecycle.close();removeDiscoveryRecord()};try{const resolved=resolveChannelWorkspaceGroupsAtListen();channelWorkspaceGroups=resolved?.groups;if(resolved){for(const skip of resolved.skipped){const detail=sanitizeLogText(redactLogCredentials(skip.message),512);writeStderrLine(`qwen serve: channel "${skip.channel}" was not restored: ${detail}`);daemonLog.warn(`channel was not restored: ${detail}`,{code:skip.code,channel:skip.channel});channelRestoreFailures.record((bootChannelClaimants.get(skip.channel)??[]).map(workspaceCwd=>({workspaceCwd,channel:skip.channel,message:skip.message})))}if(resolved.skipped.length>0){const hosted=new Set(resolved.groups.flatMap(group=>group.selection.mode==="names"?group.selection.names:[]));const remaining=opts.channelSelection?.mode==="names"?opts.channelSelection.names.filter(name=>hosted.has(name)):[];opts.channelSelection=remaining.length>0?{mode:"names",names:remaining}:void 0;if(!opts.channelSelection){channelWorkspaceGroups=void 0;removeCurrentServePidfile();reportConfiguredChannelStartupFailure(new Error("No configured channel could be hosted."))}}}}catch(err){removeCurrentServePidfile();const error2=err instanceof Error?err:new Error(String(err));if(channelSelectionFromSettings){opts.channelSelection=void 0;reportConfiguredChannelStartupFailure(error2)}else{markServeAppStartupFailed(error2);void serveAppLifecycle.close().then(()=>reject(error2),closeError=>reject(closeError instanceof Error?new AggregateError([error2,closeError],error2.message):error2));return}}if(channelWorkspaceGroups){for(const group of channelWorkspaceGroups){daemonLog.info("channel worker group assigned",{workspace:group.workspaceCwd,channels:group.selection.mode==="all"?["all"]:group.selection.names})}if(opts.channelSelection?.mode==="all"){writeStderrLine(channelSelectionFromSettings?'qwen serve: workspace serve.channels selection "all" is primary-workspace only; non-primary workspace channels are not hosted.':"qwen serve: --channel all is primary-workspace only; non-primary workspace channels are not hosted.")}}writeStdoutLine(`qwen serve listening on ${url} (mode=${opts.mode}, workspace=${boundWorkspace})`);try{const discoveryLogPath=daemonLog.getLogPath();discoveryRecordPath=writeDaemonDiscovery({v:DAEMON_DISCOVERY_VERSION,pid:process.pid,port:actualPort,hostname:opts.hostname,url:daemonDiscoveryUrl(url),workspaces:workspaceInputs.map(workspace=>workspace.cwd),primaryWorkspace:boundWorkspace,startedAt:new Date().toISOString(),auth:token?"bearer":"none",...generatedToken?{tokenGenerated:true}:{},...discoveryLogPath?{logPath:discoveryLogPath}:{},pidNamespace:currentPidNamespace()});process.once("exit",removeDiscoveryRecord)}catch(err){writeStderrLine(`qwen serve: could not write the daemon discovery record: ${err instanceof Error?err.message:String(err)}`)}const boundAddress=typeof addr==="object"&&addr?addr.address:opts.hostname;const settingTokenQr=bootSettings?.serve?.tokenQr;if(opts.tokenQr===void 0&&settingTokenQr!==void 0&&typeof settingTokenQr!=="boolean"){writeStderrLine(`qwen serve: serve.tokenQr must be a boolean; ignoring a ${typeof settingTokenQr} value.`)}for(const ignoredKey of bootSettings?.ignoredWorkspaceKeys??[]){writeStderrLine(`qwen serve: ${ignoredKey} in workspace settings (${path.join(boundWorkspace,".qwen","settings.json")}) is ignored; it is honored from user, system, and system-defaults scopes only.`)}const tokenQrMode=opts.tokenQr===false?"veto":opts.tokenQr===true||settingTokenQr===true?"force":"policy";const tokenQrNoEffect=tokenQrNoEffectReason({requested:tokenQrMode==="force",webShellMounted,boundAddress,generated:generatedToken});if(tokenQrNoEffect)writeStderrLine(tokenQrNoEffect);if(token){void printRemoteQuickstart({bind:opts.hostname,boundAddress,port:actualPort,tls:Boolean(tlsOptions),token,generated:generatedToken,web:webShellMounted,tokenQrMode})}writeStderrLine(`qwen serve: bound to workspace ${JSON.stringify(boundWorkspace)}`);writeStderrLine(`qwen serve: startup timing: processToListenMs=${startup.processToListenMs} runQwenServeToListenMs=${startup.runQwenServeToListenMs}`);if(!token){writeStderrLine(`qwen serve: trusted loopback mode; local callers have full API access without bearer authentication, including code execution as the daemon user. Use --require-auth with ${QWEN_SERVER_TOKEN_ENV} on shared or untrusted hosts.`);if(opts.clientMcpOverWs===true){writeStderrLine(`qwen serve: client-hosted MCP tools are accepted over the WebSocket without auth. Set ${QWEN_SERVE_CLIENT_MCP_OVER_WS_ENV}=0 to disable.`)}}else if(opts.requireAuth){writeStderrLine("qwen serve: --require-auth enabled (bearer token mandatory on every route, including loopback /health).")}writeStderrLine(`qwen serve: manage this daemon with \`qwen daemon status\`, \`qwen daemon logs --port ${actualPort} --follow\`, or \`qwen daemon stop --port ${actualPort}\`.`);process.on("SIGINT",onSignal);process.on("SIGTERM",onSignal);process.on("SIGHUP",onSignal);process.on("uncaughtExceptionMonitor",onUncaughtExceptionMonitor);server.on("error",err=>{daemonLog.error("server error",err instanceof Error?err:null)});const preparedRuntimeApp=runtimeApp??runtimeAppForCleanup;if(preparedRuntimeApp&&bridgeRef&&deps.bridge){runtimeApp??=preparedRuntimeApp;attachLiveDiscoveryControl(preparedRuntimeApp);if(shouldPreheat){startBridgePreheat(bridgeRef,preparedRuntimeApp)}if(opts.channelSelection&&!runtimeStartupSettled){armRuntimeStartupTimer();runtimeStarting=completeRuntimeStartup(preparedRuntimeApp).catch(err=>failRuntimeStartup(err,bridgeRef))}else{const acpHandle=preparedRuntimeApp.locals?.["acpHandle"];attachAcpWsTransport(acpHandle);markServeAppStartupReady();void publishLiveDiscovery(preparedRuntimeApp);if(!runtimeStartupSettled){runtimeStartupSettled=true;clearRuntimeStartupTimer();markRuntimeReady()}}}else if(deferRuntimeUntilFirstHealth){scheduleRuntimeStartFallback()}else{startRuntime()}if(deps.resolveOnListen){loggerPublished=true;loggerLifecycle.published();void(liveDiscoveryPublish??Promise.resolve()).then(()=>resolve3(handle))}else{void runtimeReady.then(async()=>{await liveDiscoveryPublish;loggerPublished=true;loggerLifecycle.published();resolve3(handle)},err=>{void handle.close().then(()=>{reject(err instanceof Error?err:new Error(String(err)))},closeErr=>{writeDaemonLifecycleBestEffort(()=>daemonLog.error("shutdown after runtime startup error failed",closeErr instanceof Error?closeErr:null));if(hasRetryableChannelWorkerShutdownError(closeErr)){writeDaemonLifecycleBestEffort(()=>daemonLog.error("runtime startup failed, but qwen serve remains alive to retain the channel service lease until worker exit is confirmed"));return}reject(err instanceof Error?err:new Error(String(err)))})})}},"onListening");let drainPreTransportUpgrades=void 0;let server;if(tlsOptions){try{server=https.createServer(tlsOptions,app)}catch(err){reject(new Error(`--tls-cert "${opts.tlsCert}" and --tls-key "${opts.tlsKey}" could not be loaded (do they match?): ${err instanceof Error?err.message:String(err)}`));return}}else{server=deps.httpServerFactory?.(app)??createServer(app)}serveAppLifecycle.bindServer(server,{startupReady:serveAppStartupReady,drainHost:__name(()=>{if(closeHost)return closeHost();if(!server.listening)return Promise.resolve();return new Promise((resolve4,rejectClose)=>{server.close(error=>{if(error)rejectClose(error);else resolve4()})})},"drainHost")});const preTransportUpgrades=[];let acpWsTransportAttached=false;let preTransportUpgradeGateClosed=false;const dropPreTransportUpgrade=__name(socket=>{const index=preTransportUpgrades.findIndex(queued=>queued.socket===socket);if(index!==-1)preTransportUpgrades.splice(index,1)},"dropPreTransportUpgrade");const answerPreTransportUpgrade503=__name((socket,retryable)=>{socket.once("error",()=>{});socket.write(retryable?"HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\n\r\n":"HTTP/1.1 503 Service Unavailable\r\n\r\n");socket.destroy()},"answerPreTransportUpgrade503");const releasePreTransportUpgrades=__name(()=>{const queued=preTransportUpgrades.splice(0);let rejected=0;for(const{req,socket,head,detach}of queued){detach();if(socket.destroyed)continue;if(acpWsTransportAttached){server.emit("upgrade",req,socket,head)}else{rejected+=1;answerPreTransportUpgrade503(socket,false)}}if(rejected>0){daemonLog.warn(`deferred runtime: answered ${rejected} parked upgrade(s) with 503 (no ACP transport attached)`)}},"releasePreTransportUpgrades");const attachAcpWsTransport=__name(acpHandle=>{if(!acpHandle||acpWsTransportAttached)return;acpHandle.attachServer(server);acpWsTransportAttached=true},"attachAcpWsTransport");const preTransportUpgradeGuard=__name((req,socket,head)=>{if(acpWsTransportAttached)return;if(preTransportUpgradeGateClosed){answerPreTransportUpgrade503(socket,false);return}if(preTransportUpgrades.length>=PRE_TRANSPORT_UPGRADE_HOLD_MAX){answerPreTransportUpgrade503(socket,true);return}const dropAndDestroy=__name(()=>{dropPreTransportUpgrade(socket);socket.destroy()},"dropAndDestroy");const drop=__name(()=>dropPreTransportUpgrade(socket),"drop");const entry={req,socket,head,detach:__name(()=>{},"detach")};const accumulate=__name(chunk=>{if(entry.head.byteLength+chunk.byteLength<=PRE_TRANSPORT_UPGRADE_HEAD_MAX){entry.head=Buffer.concat([entry.head,chunk])}else{dropAndDestroy()}},"accumulate");const detach=__name(()=>{socket.removeListener("data",accumulate);socket.removeListener("error",dropAndDestroy);socket.removeListener("end",dropAndDestroy);socket.removeListener("close",drop)},"detach");entry.detach=detach;socket.on("data",accumulate);socket.once("error",dropAndDestroy);socket.once("end",dropAndDestroy);socket.once("close",drop);preTransportUpgrades.push(entry);daemonLog.info(`deferred runtime: parked pre-transport upgrade ${req.url?.split("?",1)[0]??"/"} from ${socket.remoteAddress??"unknown"} (${preTransportUpgrades.length} held)`);if(!runtimeStartupSettled)startRuntimeForRequest?.()},"preTransportUpgradeGuard");server.on("upgrade",preTransportUpgradeGuard);drainPreTransportUpgrades=__name(()=>{preTransportUpgradeGateClosed=true;const queued=preTransportUpgrades.splice(0);for(const{socket,detach}of queued){detach();if(socket.destroyed)continue;answerPreTransportUpgrade503(socket,false)}},"drainPreTransportUpgrades");void runtimeReady.then(()=>{const acpHandle=(runtimeApp??runtimeAppForCleanup)?.locals?.["acpHandle"];if(!acpHandle){server.removeListener("upgrade",preTransportUpgradeGuard);daemonLog.info("deferred runtime: settled without an ACP transport, restoring Express upgrade fall-through")}preTransportUpgradeGateClosed=true;releasePreTransportUpgrades()},()=>{if(acpWsTransportAttached&&server.listenerCount("upgrade")<2){acpWsTransportAttached=false}if(opts.profile==="hosted-harness"||!resolveAcpHttpEnabled(daemonRuntimeBaseEnv)){server.removeListener("upgrade",preTransportUpgradeGuard);daemonLog.info("deferred runtime: startup failed without an ACP transport, restoring Express upgrade fall-through")}preTransportUpgradeGateClosed=true;releasePreTransportUpgrades()});const tryListen=__name((attemptPort,attempt)=>{const handleListening=__name(()=>{server.removeListener("error",handleError);const address=server.address();if(trustedLoopbackMode&&(typeof address!=="object"||address===null||!isLoopbackAddress(address.address))){const resolvedAddress=typeof address==="object"&&address!==null?address.address:String(address);const error=new Error(`Refusing trusted-loopback mode because ${opts.hostname} bound to non-loopback address ${resolvedAddress}. Set ${QWEN_SERVER_TOKEN_ENV} or pass --token, or bind to an explicit loopback address.`);removeCurrentServePidfile();markServeAppStartupFailed(error);void serveAppLifecycle.close().then(()=>reject(error),closeError=>reject(closeError instanceof Error?new AggregateError([error,closeError],error.message):error));return}onListening()},"handleListening");const handleError=__name(err=>{server.removeListener("listening",handleListening);const nextPort=attemptPort+1;if(err.code==="EADDRINUSE"&&opts.port!==0&&nextPort<=65535&&attempt<MAX_PORT_ATTEMPTS-1){writeStderrLine(`qwen serve: port ${attemptPort} is in use, trying ${nextPort}...`);tryListen(nextPort,attempt+1);return}if(err.code==="EADDRINUSE"&&attempt>0){writeStderrLine(`qwen serve: all ports ${opts.port}\u2013${attemptPort} are in use`)}removeCurrentServePidfile();markServeAppStartupFailed(err);void serveAppLifecycle.close().then(()=>reject(err),closeError=>reject(closeError instanceof Error?new AggregateError([err,closeError],err.message):err))},"handleError");try{server.once("listening",handleListening);server.once("error",handleError);server.listen(attemptPort,listenHostname)}catch(err){removeCurrentServePidfile();server.removeListener("listening",handleListening);server.removeListener("error",handleError);const error=err instanceof Error?err:new Error(String(err));markServeAppStartupFailed(error);void serveAppLifecycle.close().then(()=>reject(error),closeError=>reject(closeError instanceof Error?new AggregateError([error,closeError],error.message):error));return}},"tryListen");tryListen(opts.port,0)})}__name(runQwenServeImpl,"runQwenServeImpl");export{InvalidPolicyConfigError,assertChannelWorkerDaemonUrlIsLocal,createBoundChannelDeliveryHandler,createDisabledChannelWorkerSupervisor,createLazyBridgeProxy,describeWorkerTlsTrustGaps,extractContextFilename,formatChannelWorkerDaemonUrl,resolveRuntimeStartupTimeoutMs,runQwenServe,subSessionConcurrencyCapsFromSettings,validateAndCanonicalizeWorkspaceInput,validatePolicyConfig,verifyWorkerTlsTrust,waitForRuntimeStartingForShutdown};
48
48
  /**
49
49
  * @license
50
50
  * Copyright 2026 Qwen Team