@qwen-code/qwen-code 0.27.2-preview.0 → 0.27.2

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 (302) hide show
  1. package/chunks/{MaxSizedBox-XGJBXFET.js → MaxSizedBox-QRQEXRXW.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-BNFJWFLQ.js → StandaloneSessionPicker-X274Q6BX.js} +1 -1
  3. package/chunks/{acp-subagent-executor-P5FBYPD5.js → acp-subagent-executor-YIFQD4LJ.js} +1 -1
  4. package/chunks/{acpAgent-J6G57ZCE.js → acpAgent-NW4XNW7P.js} +3 -3
  5. package/chunks/{advisor-3O63GFOM.js → advisor-W7KCVPBR.js} +1 -1
  6. package/chunks/{agent-ALZEISY2.js → agent-FGDWPNXW.js} +1 -1
  7. package/chunks/{agent-headless-XAKKB6OT.js → agent-headless-7KA3VVAB.js} +1 -1
  8. package/chunks/{agent-host-client-DIV2XAL5.js → agent-host-client-YZJLSOLB.js} +1 -1
  9. package/chunks/{agent-host-connections-ZQUMCO2F.js → agent-host-connections-5JGDPG3L.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-ZE7TAQPO.js → anthropicContentGenerator-QUXJVJ3I.js} +1 -1
  11. package/chunks/{autofix-pr-RZ4PWQ46.js → autofix-pr-UDRPJC7L.js} +1 -1
  12. package/chunks/{batch-AIMBHUMX.js → batch-GCEHGR5P.js} +1 -1
  13. package/chunks/{bridge-A3RRGPEI.js → bridge-JY2JXNVV.js} +1 -1
  14. package/chunks/{channel-settings-store-P3KM5GTN.js → channel-settings-store-EX6ZU6R3.js} +1 -1
  15. package/chunks/{chunk-P22U5UQR.js → chunk-27MJJU2I.js} +1 -1
  16. package/chunks/{chunk-RYRMDOIX.js → chunk-2LDABIAY.js} +3 -3
  17. package/chunks/{chunk-MYPEVUKI.js → chunk-2QZDPMIH.js} +1 -1
  18. package/chunks/{chunk-TW2REHPX.js → chunk-2SGTJMSU.js} +1 -1
  19. package/chunks/{chunk-NCW3NPS5.js → chunk-3BHXPXCC.js} +1 -1
  20. package/chunks/{chunk-XUB4JKSR.js → chunk-3NR3JBMA.js} +6 -6
  21. package/chunks/{chunk-NRJOUWP4.js → chunk-3QCFMVI6.js} +1 -1
  22. package/chunks/{chunk-EGMV4S6D.js → chunk-3YOERSU5.js} +1 -1
  23. package/chunks/{chunk-WXKD4L4A.js → chunk-4NIUXYUF.js} +1 -1
  24. package/chunks/{chunk-YHC27L5W.js → chunk-5FS5OQHO.js} +1 -1
  25. package/chunks/{chunk-L76RFQKW.js → chunk-5MGG2BGT.js} +1 -1
  26. package/chunks/{chunk-HHDQ5JAA.js → chunk-66LFVQJP.js} +1 -1
  27. package/chunks/{chunk-RJPELYUW.js → chunk-6KU7LHBT.js} +1 -1
  28. package/chunks/{chunk-SKU5J7Q7.js → chunk-6O7CARPF.js} +1 -1
  29. package/chunks/{chunk-CPOFE42B.js → chunk-6Z3TBTUS.js} +1 -1
  30. package/chunks/{chunk-HRRQHZQE.js → chunk-73TSS7KS.js} +1 -1
  31. package/chunks/{chunk-BSGONILH.js → chunk-776L3HAN.js} +1 -1
  32. package/chunks/{chunk-MZNZYCAC.js → chunk-7BL2OTHX.js} +1 -1
  33. package/chunks/{chunk-5DPLJQUC.js → chunk-7GYFDPEP.js} +1 -1
  34. package/chunks/{chunk-OD44AOSX.js → chunk-7KGCNYE4.js} +1 -1
  35. package/chunks/{chunk-4JLLFT6S.js → chunk-7SX547WS.js} +1 -1
  36. package/chunks/{chunk-5Q6POUDM.js → chunk-7VIES3RW.js} +1 -1
  37. package/chunks/{chunk-NMK72ZA4.js → chunk-ABEBQNYK.js} +1 -1
  38. package/chunks/{chunk-QZ5JBF3E.js → chunk-AD7JBW6R.js} +2 -2
  39. package/chunks/{chunk-E6XRNALG.js → chunk-AEX3XSTE.js} +1 -1
  40. package/chunks/{chunk-B7CYUTAO.js → chunk-AKDODQCI.js} +1 -1
  41. package/chunks/{chunk-EEARSY3D.js → chunk-B3I5LFFK.js} +1 -1
  42. package/chunks/{chunk-YSGVX6LT.js → chunk-B5Y56PDI.js} +1 -1
  43. package/chunks/{chunk-MEFN5DY3.js → chunk-BEBKKJP3.js} +1 -1
  44. package/chunks/{chunk-GYCGVZ32.js → chunk-BFPP7X4E.js} +1 -1
  45. package/chunks/{chunk-GNWPYWGQ.js → chunk-BY5GX6DQ.js} +1 -1
  46. package/chunks/{chunk-6W5ZZSQF.js → chunk-CUX3C6QV.js} +1 -1
  47. package/chunks/{chunk-HXYHIEMH.js → chunk-CXPRHT3E.js} +1 -1
  48. package/chunks/{chunk-53CWA7N2.js → chunk-D5H5GARR.js} +1 -1
  49. package/chunks/{chunk-DV67DRNT.js → chunk-DLY7QJ5Y.js} +1 -1
  50. package/chunks/{chunk-SFDOJ2FF.js → chunk-DN4QKOFL.js} +1 -1
  51. package/chunks/{chunk-VOAIDOUV.js → chunk-DP4YE24V.js} +1 -1
  52. package/chunks/{chunk-D2X6A5FH.js → chunk-DQLI7HH7.js} +1 -1
  53. package/chunks/{chunk-ET7ADS4X.js → chunk-DS2FKATN.js} +1 -1
  54. package/chunks/{chunk-FRSSRLIO.js → chunk-E6EW43WZ.js} +1 -1
  55. package/chunks/{chunk-F4AWT5LV.js → chunk-EEBFFC76.js} +1 -1
  56. package/chunks/{chunk-B7PJ5TNK.js → chunk-EGKUF5NS.js} +2 -2
  57. package/chunks/{chunk-B2YLVSQE.js → chunk-ERMAKXS3.js} +2 -2
  58. package/chunks/{chunk-PEZZTKPM.js → chunk-FB73O3E5.js} +1 -1
  59. package/chunks/{chunk-36DBNBTF.js → chunk-FEIUMWFA.js} +1 -1
  60. package/chunks/{chunk-YE3LA3U4.js → chunk-FWJKQA2H.js} +1 -1
  61. package/chunks/{chunk-VDNPMX5W.js → chunk-FZQJOSHD.js} +1 -1
  62. package/chunks/{chunk-YYSMMFK7.js → chunk-GNI5J2ON.js} +1 -1
  63. package/chunks/{chunk-6OCKLRQC.js → chunk-H3VGRICV.js} +1 -1
  64. package/chunks/{chunk-OSLFWRV2.js → chunk-HRTWLOGK.js} +1 -1
  65. package/chunks/{chunk-XZYQKCTU.js → chunk-IGIZ6AZE.js} +1 -1
  66. package/chunks/{chunk-RIBVEHUG.js → chunk-IHB7CDQ2.js} +1 -1
  67. package/chunks/{chunk-LO6OFMFC.js → chunk-IHEGGZBE.js} +1 -1
  68. package/chunks/{chunk-N5S6SIRO.js → chunk-IMTHBYJP.js} +1 -1
  69. package/chunks/{chunk-I5F24CVP.js → chunk-IP3K5SRR.js} +1 -1
  70. package/chunks/{chunk-2FYWJVGW.js → chunk-ISA4MFNT.js} +1 -1
  71. package/chunks/{chunk-GV3E2RHX.js → chunk-JGF3ND5D.js} +1 -1
  72. package/chunks/{chunk-ASQ7BSJ4.js → chunk-JJ4UPR4A.js} +1 -1
  73. package/chunks/{chunk-HOCNE2LO.js → chunk-JTUWFGEB.js} +1 -1
  74. package/chunks/{chunk-FDQFJFO5.js → chunk-KAN5KUJD.js} +1 -1
  75. package/chunks/{chunk-K7GCWWTI.js → chunk-KU4F6SSJ.js} +2 -2
  76. package/chunks/{chunk-QDQQFQB4.js → chunk-LBAINHIN.js} +1 -1
  77. package/chunks/{chunk-BAPIZCC7.js → chunk-LTJLPYFS.js} +1 -1
  78. package/chunks/{chunk-ZOUMCSDW.js → chunk-MSNPEQ2I.js} +1 -1
  79. package/chunks/{chunk-MPDGSR2S.js → chunk-N3YWQWSR.js} +5 -5
  80. package/chunks/{chunk-VEVQB4CI.js → chunk-NDTPBVER.js} +1 -1
  81. package/chunks/{chunk-L4WG2XDS.js → chunk-NJ77L3GS.js} +1 -1
  82. package/chunks/{chunk-U2DX235N.js → chunk-NL62UQDW.js} +1 -1
  83. package/chunks/{chunk-QASJXL5B.js → chunk-NYXR2655.js} +1 -1
  84. package/chunks/{chunk-5SPQ5V35.js → chunk-OEPXWKZL.js} +1 -1
  85. package/chunks/{chunk-EOR7AP7Z.js → chunk-OIKWJN7E.js} +1 -1
  86. package/chunks/{chunk-BT7V3O75.js → chunk-OIQKVWR7.js} +1 -1
  87. package/chunks/{chunk-ESXBBANA.js → chunk-OPBSEVFC.js} +1 -1
  88. package/chunks/{chunk-NW3H676V.js → chunk-P5RBFVMP.js} +1 -1
  89. package/chunks/{chunk-F7KVMGGZ.js → chunk-QD4KNY2J.js} +1 -1
  90. package/chunks/{chunk-2ZE6CAZV.js → chunk-RSLBGXPB.js} +1 -1
  91. package/chunks/{chunk-3R7NEEW7.js → chunk-S542WTV7.js} +1 -1
  92. package/chunks/{chunk-KXAZ2Z5M.js → chunk-SEK234IM.js} +1 -1
  93. package/chunks/{chunk-5DPXLL3H.js → chunk-TM6IVXAM.js} +1 -1
  94. package/chunks/{chunk-KMJLEAS3.js → chunk-TPTV6HPU.js} +1 -1
  95. package/chunks/{chunk-DCUBMMWG.js → chunk-TQ6FKWSC.js} +1 -1
  96. package/chunks/{chunk-JK2S74SA.js → chunk-TUBHG6EI.js} +1 -1
  97. package/chunks/{chunk-FMZ5U7J5.js → chunk-UBPC3F32.js} +1 -1
  98. package/chunks/{chunk-XB7DJWOJ.js → chunk-UG5B4UOQ.js} +6 -6
  99. package/chunks/{chunk-36S57YYW.js → chunk-UGWTN5IK.js} +1 -1
  100. package/chunks/{chunk-SK2DTYBZ.js → chunk-URMRX2MG.js} +1 -1
  101. package/chunks/{chunk-VB4DB57C.js → chunk-UY6J5CHF.js} +1 -1
  102. package/chunks/{chunk-STQ3TEZW.js → chunk-VSTQT667.js} +2 -2
  103. package/chunks/{chunk-SGUUOXLH.js → chunk-WDO33SWR.js} +1 -1
  104. package/chunks/{chunk-IVXR5JO2.js → chunk-WFJHBU7B.js} +1 -1
  105. package/chunks/{chunk-BINJRUHZ.js → chunk-XSRHGC5R.js} +1 -1
  106. package/chunks/{chunk-HN7EGFIP.js → chunk-XVF3FMTM.js} +1 -1
  107. package/chunks/{chunk-C5X6K67T.js → chunk-XYRNYCRQ.js} +1 -1
  108. package/chunks/{chunk-HZOPWFFL.js → chunk-YAMLF3SM.js} +1 -1
  109. package/chunks/{chunk-CMW64XU2.js → chunk-ZEZCRRQC.js} +1 -1
  110. package/chunks/{chunk-J5W6P7QD.js → chunk-ZF56DRDP.js} +1 -1
  111. package/chunks/{chunk-LHIEE3A2.js → chunk-ZSPOFXP3.js} +1 -1
  112. package/chunks/{chunk-Q6CXEN4H.js → chunk-ZZXAOGUV.js} +1 -1
  113. package/chunks/{codex-subagent-executor-HB3MUCY4.js → codex-subagent-executor-7RAVQBYA.js} +1 -1
  114. package/chunks/{config-utils-F7OF5UR2.js → config-utils-JFD4RJK3.js} +1 -1
  115. package/chunks/{contextCommand-Y3KO2FY6.js → contextCommand-U6CD3CW7.js} +1 -1
  116. package/chunks/{core-runtime-D7DAA5NY.js → core-runtime-ORCZRJ4O.js} +1 -1
  117. package/chunks/{create-sub-session-2HTWYAP4.js → create-sub-session-57WMU2AE.js} +1 -1
  118. package/chunks/{cron-create-Y5I6E2X4.js → cron-create-V466MOUE.js} +1 -1
  119. package/chunks/{daemon-git-worktree-guard-UOBMXOUC.js → daemon-git-worktree-guard-ATD77XOF.js} +1 -1
  120. package/chunks/{daemon-status-provider-L2225KDS.js → daemon-status-provider-5FVRNMAZ.js} +1 -1
  121. package/chunks/{daemon-trust-policy-5D52N5GL.js → daemon-trust-policy-6YRQV4ZM.js} +1 -1
  122. package/chunks/{daemon-trust-policy-monitor-RUE25K7A.js → daemon-trust-policy-monitor-QRUOWZQP.js} +1 -1
  123. package/chunks/{deferred-core-runtime-6BO5DI5B.js → deferred-core-runtime-TXIXMDDH.js} +1 -1
  124. package/chunks/{edit-B6DKSK3O.js → edit-FNXBINJ3.js} +1 -1
  125. package/chunks/{enterPlanMode-WVJ3XC3P.js → enterPlanMode-YMLAOTTS.js} +1 -1
  126. package/chunks/{environment-7WMACN3E.js → environment-RFNJLRF7.js} +1 -1
  127. package/chunks/{errors-BN73QF2O.js → errors-NHGSZ2BV.js} +1 -1
  128. package/chunks/{execution-tool-IGDH3MQT.js → execution-tool-L2BF6ZKP.js} +1 -1
  129. package/chunks/{execution-worker-WWP3JZGV.js → execution-worker-F5B2BI2W.js} +1 -1
  130. package/chunks/{exitPlanMode-7WHKOTS7.js → exitPlanMode-ZZVBF5V4.js} +1 -1
  131. package/chunks/{fast-path-B37HGFQO.js → fast-path-TOJYOAD3.js} +1 -1
  132. package/chunks/{glob-ZRXU5G5X.js → glob-SYPMYU4V.js} +1 -1
  133. package/chunks/{goal-tools-DQ5IZXCM.js → goal-tools-NOXNXZFR.js} +1 -1
  134. package/chunks/{handleAutoUpdate-FD7QAG2R.js → handleAutoUpdate-RS6Y2IWS.js} +1 -1
  135. package/chunks/{i18n-TI3ZCEHR.js → i18n-WWZD25J5.js} +1 -1
  136. package/chunks/{initializer-SB7P3LRU.js → initializer-YGR4YXAM.js} +1 -1
  137. package/chunks/{installationInfo-B337C7R4.js → installationInfo-EPURVILN.js} +1 -1
  138. package/chunks/{interactive-mod-session-OWRMETPP.js → interactive-mod-session-2VSTTHPA.js} +1 -1
  139. package/chunks/{list-2QKQIEOB.js → list-6JAKVRMZ.js} +1 -1
  140. package/chunks/{llm-GQ76E4DL.js → llm-V272EOVL.js} +4 -4
  141. package/chunks/{llm-content-generator-2A23HFLD.js → llm-content-generator-EXMC3NYS.js} +1 -1
  142. package/chunks/{loadedSettingsAdapter-RGQOA5BG.js → loadedSettingsAdapter-T6W2CKFA.js} +1 -1
  143. package/chunks/{local-OEBLERSJ.js → local-NUBKA3T2.js} +1 -1
  144. package/chunks/{local-execution-environment-FT5J4SUH.js → local-execution-environment-WO62QDKJ.js} +1 -1
  145. package/chunks/{loggingContentGenerator-WC23RZYM.js → loggingContentGenerator-KHRN6S3S.js} +1 -1
  146. package/chunks/{loop-wakeup-GIIIDUNG.js → loop-wakeup-TTAZMOYH.js} +1 -1
  147. package/chunks/{manage-memory-E2OAR2RV.js → manage-memory-BKA7QM4N.js} +1 -1
  148. package/chunks/{managed-execution-engine-CYYNVVP5.js → managed-execution-engine-32BLALNC.js} +1 -1
  149. package/chunks/{managed-local-serve-TUVNNY7K.js → managed-local-serve-UTJFLZI6.js} +1 -1
  150. package/chunks/{managed-npm-update-IDRZ32UK.js → managed-npm-update-XPIRAQ47.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-HON7TGY2.js → managed-runtime-attestation-worker-DDU4HUGS.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-OMLX5CTV.js → managed-runtime-bootstrap-7TTCLDQJ.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-J3P7WMDW.js → managed-runtime-session-worker-WBYLRXU3.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-LPFPOBTL.js → managed-runtime-ssh-worker-X2U2OK2E.js} +1 -1
  155. package/chunks/{managed-session-authority-I5OHOM7N.js → managed-session-authority-U76OGS6U.js} +1 -1
  156. package/chunks/{mcp-CGDIDRDI.js → mcp-UROGTJ3U.js} +1 -1
  157. package/chunks/{memory-VKXOH5UM.js → memory-M4OF6FV7.js} +1 -1
  158. package/chunks/{model-call-collection-ZTYFDFBB.js → model-call-collection-TW6Q7SXP.js} +1 -1
  159. package/chunks/{model-configuration-EXLM4SD3.js → model-configuration-4PJUBAYR.js} +1 -1
  160. package/chunks/{modelConfigUtils-XDMB6XPY.js → modelConfigUtils-ARMBTDAK.js} +1 -1
  161. package/chunks/{monitor-LKKCC6MQ.js → monitor-URMSEGAJ.js} +1 -1
  162. package/chunks/{nonInteractiveCli-J3Z3IZIF.js → nonInteractiveCli-YHOC5KZF.js} +1 -1
  163. package/chunks/{nonInteractiveToolExecutor-UQTMGYN2.js → nonInteractiveToolExecutor-DM5IGBP7.js} +1 -1
  164. package/chunks/{notebook-edit-JFD2KDI6.js → notebook-edit-3YSG73BK.js} +1 -1
  165. package/chunks/{omni-CI5JTMPR.js → omni-J6YYWKII.js} +1 -1
  166. package/chunks/{openaiContentGenerator-YZOV2TQX.js → openaiContentGenerator-UIFSPMTE.js} +1 -1
  167. package/chunks/{openaiResponsesContentGenerator-AHL7V6TE.js → openaiResponsesContentGenerator-U6Q536RZ.js} +1 -1
  168. package/chunks/{pidfile-ULOUTG67.js → pidfile-WCZE5ONH.js} +1 -1
  169. package/chunks/{processUtils-XX62FVFO.js → processUtils-3CDEN2GV.js} +1 -1
  170. package/chunks/{prompt-terminal-ledger-L6CWXBAW.js → prompt-terminal-ledger-VAQC6TC3.js} +1 -1
  171. package/chunks/{qwenContentGenerator-ZDXJW7EM.js → qwenContentGenerator-RWBGMON6.js} +1 -1
  172. package/chunks/{reactive-degrade-4OJ7XKSJ.js → reactive-degrade-GOTSVZKO.js} +1 -1
  173. package/chunks/{read-file-H6I32UZS.js → read-file-WNNTTHL5.js} +1 -1
  174. package/chunks/{resumeHistoryUtils-CTRMXPKQ.js → resumeHistoryUtils-UAGV4TC3.js} +1 -1
  175. package/chunks/{review-7SV2M7EL.js → review-JETUJT7N.js} +1 -1
  176. package/chunks/{ripGrep-Y2TGCQH5.js → ripGrep-OJNMOYPD.js} +1 -1
  177. package/chunks/{run-qwen-serve-6SWKYY6I.js → run-qwen-serve-BVNSBOLL.js} +1 -1
  178. package/chunks/{runtime-ITZIIC6D.js → runtime-CERVMTEG.js} +1 -1
  179. package/chunks/{sandboxConfig-FF2YF3RY.js → sandboxConfig-ZHW3GTMH.js} +1 -1
  180. package/chunks/{scheduled-tasks-WWPWNM3Y.js → scheduled-tasks-AAB5OESY.js} +1 -1
  181. package/chunks/{scheduler-ELSUH4GZ.js → scheduler-4ZZA357S.js} +1 -1
  182. package/chunks/{search-memory-465ZSHKG.js → search-memory-USJ3D7WQ.js} +1 -1
  183. package/chunks/{send-message-M5JFT3VH.js → send-message-QE2YZZ6M.js} +1 -1
  184. package/chunks/{serve-VTR7PTK2.js → serve-SX2PK3OZ.js} +1 -1
  185. package/chunks/{server-5NHPPEPR.js → server-OGTIIX65.js} +3 -3
  186. package/chunks/{session-HZLRQKEB.js → session-DXORIQDK.js} +1 -1
  187. package/chunks/{session-attachments-root-LS5Q4OT3.js → session-attachments-root-VHH2OZF6.js} +1 -1
  188. package/chunks/{session-execution-engine-selector-GS4LJPUU.js → session-execution-engine-selector-5WKZ6WXX.js} +1 -1
  189. package/chunks/{session-pr-refresh-FKYCCTWD.js → session-pr-refresh-MHXNT44I.js} +1 -1
  190. package/chunks/{sessionService-XUBKN4CM.js → sessionService-QDDGXOB7.js} +1 -1
  191. package/chunks/{settings-BFTTGWJN.js → settings-W3ALYJZM.js} +1 -1
  192. package/chunks/{shell-YEUMIQVE.js → shell-YROF2KXZ.js} +1 -1
  193. package/chunks/{skill-2MJ7S5SK.js → skill-CBEQAUIQ.js} +1 -1
  194. package/chunks/{skill-settings-DP7A2GMB.js → skill-settings-YRN4SHJO.js} +1 -1
  195. package/chunks/{spawnChannel-3IZ7S6U7.js → spawnChannel-M7Q6URLT.js} +1 -1
  196. package/chunks/{standalone-update-NAI3OI3P.js → standalone-update-WIRHMWE6.js} +1 -1
  197. package/chunks/{start-opentui-ui-D6ETKJSG.js → start-opentui-ui-OLHWNKCY.js} +1 -1
  198. package/chunks/{startInteractiveUI-FR5ZT72L.js → startInteractiveUI-KCHCIQWO.js} +1 -1
  199. package/chunks/{subscription-content-generator-JHU5YG2L.js → subscription-content-generator-YQLQKG6S.js} +1 -1
  200. package/chunks/{team-create-ZW3NXJ2M.js → team-create-I432CHIX.js} +1 -1
  201. package/chunks/{team-plan-approval-GPFOKUEV.js → team-plan-approval-APMPMLXS.js} +1 -1
  202. package/chunks/{terminal-image-renderer-WTEEKRMJ.js → terminal-image-renderer-3BNICGAX.js} +1 -1
  203. package/chunks/{theme-manager-STF74SF2.js → theme-manager-6KY7Q4ZR.js} +1 -1
  204. package/chunks/{tool-call-TVX5UHRJ.js → tool-call-QGOVXOVJ.js} +1 -1
  205. package/chunks/{tool-result-media-QALAETZ4.js → tool-result-media-LRSYJOND.js} +1 -1
  206. package/chunks/{tool-search-ZGJEYTBI.js → tool-search-HXP25AWV.js} +1 -1
  207. package/chunks/{total-session-admission-BOYLCRYA.js → total-session-admission-ISTRHUQ7.js} +1 -1
  208. package/chunks/{trustedFolders-65OZWLQO.js → trustedFolders-5BXMWMYB.js} +1 -1
  209. package/chunks/{update-relaunch-4LJ3SY6L.js → update-relaunch-NYGYYLSC.js} +1 -1
  210. package/chunks/{updateCheck-2QOAKEIH.js → updateCheck-UBLS3LUD.js} +1 -1
  211. package/chunks/{upload-config-5N7UDWC6.js → upload-config-Y372LVXX.js} +1 -1
  212. package/chunks/{useAutoAcceptIndicator-V37CGGMF.js → useAutoAcceptIndicator-RXZJRU74.js} +1 -1
  213. package/chunks/{validateNonInterActiveAuth-6ZTVWZ6W.js → validateNonInterActiveAuth-2GJ4ICJ3.js} +1 -1
  214. package/chunks/{version-EO3VIRH6.js → version-XRSNVEB2.js} +1 -1
  215. package/chunks/{web-fetch-B6LNZ2YK.js → web-fetch-B4VFVGWW.js} +1 -1
  216. package/chunks/{web-search-VIPZWUJX.js → web-search-3DSQWMAV.js} +1 -1
  217. package/chunks/{workflow-W5QEAOGN.js → workflow-RCCH5FPV.js} +1 -1
  218. package/chunks/{workflow-ancestor-trust-VE7B4RD2.js → workflow-ancestor-trust-N3QYH3OL.js} +1 -1
  219. package/chunks/{workspace-agents-D32D3K5S.js → workspace-agents-KEV4VBZD.js} +1 -1
  220. package/chunks/{workspace-providers-status-BOH7RJPV.js → workspace-providers-status-HW4VI4T7.js} +1 -1
  221. package/chunks/{workspace-recovery-worker-53GJWYJ5.js → workspace-recovery-worker-C3SSJ64A.js} +1 -1
  222. package/chunks/{workspace-registration-store-BMX2NT45.js → workspace-registration-store-K7VEBHIU.js} +1 -1
  223. package/chunks/{workspace-registry-SS2NKLEL.js → workspace-registry-C5ZPYT4P.js} +1 -1
  224. package/chunks/{workspace-runtime-coordinator-7ZKVLJDC.js → workspace-runtime-coordinator-ALWOLW3N.js} +1 -1
  225. package/chunks/{workspace-service-GIUD3D25.js → workspace-service-TNZJAC7M.js} +1 -1
  226. package/chunks/{workspace-skills-status-36A76TDX.js → workspace-skills-status-TI763F5M.js} +1 -1
  227. package/chunks/{workspace-trust-reconciler-VKKSY2AR.js → workspace-trust-reconciler-6UQ7HSUG.js} +1 -1
  228. package/chunks/{write-file-43JOGU55.js → write-file-2XXEHBZR.js} +1 -1
  229. package/chunks/{zoom-image-USUXATDM.js → zoom-image-P3E3V6PQ.js} +1 -1
  230. package/cli.js +2 -2
  231. package/execution-worker.js +1 -1
  232. package/export-transcript-document.js +1 -1
  233. package/package.json +3 -3
  234. package/web-shell/assets/{PierreFilePreview-Dx075_VT.js → PierreFilePreview-DtTOu9VE.js} +1 -1
  235. package/web-shell/assets/{SpreadsheetPreview-l2R-Y1o6.js → SpreadsheetPreview-C21imJIX.js} +1 -1
  236. package/web-shell/assets/{WorkspaceFileBrowser-CGi_eR1a.js → WorkspaceFileBrowser-DIWHfhtl.js} +1 -1
  237. package/web-shell/assets/{abnfDiagram-VCTEODGH-DZPHyWbH.js → abnfDiagram-VCTEODGH-qffA9juk.js} +1 -1
  238. package/web-shell/assets/{agents-route-Bp0Yjhm4.js → agents-route-4f6fKJaY.js} +1 -1
  239. package/web-shell/assets/{arc-BAS_Ct0z.js → arc-BOZg4dn0.js} +1 -1
  240. package/web-shell/assets/{architectureDiagram-5GKGNRK7-C5a7ooE1.js → architectureDiagram-5GKGNRK7-BOYWC6dJ.js} +1 -1
  241. package/web-shell/assets/{blockDiagram-NRAW4CY4-D-Wzzi9Z.js → blockDiagram-NRAW4CY4-CiN_IMJ7.js} +1 -1
  242. package/web-shell/assets/{c4Diagram-UCG6FXSJ-BiYnmYkI.js → c4Diagram-UCG6FXSJ-WYLA0JW0.js} +1 -1
  243. package/web-shell/assets/channel-DtcoR96T.js +1 -0
  244. package/web-shell/assets/{chunk-2Q5K7J3B-DHi3a_yf.js → chunk-2Q5K7J3B-BZUPB745.js} +1 -1
  245. package/web-shell/assets/{chunk-5VM5RSS4-DKgiHWPM.js → chunk-5VM5RSS4-BHfjsu8x.js} +1 -1
  246. package/web-shell/assets/{chunk-F27PBJKO-qvFMzdl_.js → chunk-F27PBJKO-DHtQsOyA.js} +1 -1
  247. package/web-shell/assets/{chunk-G27WJ6UU-C9Apl4Df.js → chunk-G27WJ6UU-DvEX_QHY.js} +1 -1
  248. package/web-shell/assets/{chunk-JWPE2WC7-ManrSgDL.js → chunk-JWPE2WC7-CwQJmw1a.js} +1 -1
  249. package/web-shell/assets/{chunk-LCL6LL3I-DNZqkjQu.js → chunk-LCL6LL3I-Cv7bRuRV.js} +1 -1
  250. package/web-shell/assets/{chunk-POPQ4Y6H-CxineRE8.js → chunk-POPQ4Y6H-zGw4PzDB.js} +1 -1
  251. package/web-shell/assets/{chunk-SVP7TREG-BzmCQ6Bh.js → chunk-SVP7TREG-DZMGVnJg.js} +1 -1
  252. package/web-shell/assets/{chunk-XXDRQBXY-Dm6Ascgd.js → chunk-XXDRQBXY-Dg5_qrTq.js} +1 -1
  253. package/web-shell/assets/classDiagram-DTDB5LWJ-CBq-DXYQ.js +1 -0
  254. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBq-DXYQ.js +1 -0
  255. package/web-shell/assets/{cose-bilkent-JH36ORCC-Cs-vIewG.js → cose-bilkent-JH36ORCC-D07aXZdD.js} +1 -1
  256. package/web-shell/assets/{cynefin-OW5HDTMX-CrxyzLrG.js → cynefin-OW5HDTMX-B4txjD0l.js} +1 -1
  257. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Bf7RdtX4.js → cynefinDiagram-5FMLGOSQ-zFtLauJ6.js} +1 -1
  258. package/web-shell/assets/{dagre-3AP2YEHR-jN7qDhRR.js → dagre-3AP2YEHR-CKZj9zbB.js} +1 -1
  259. package/web-shell/assets/{diagram-S7CK7UJ4-KcNQ38Ue.js → diagram-S7CK7UJ4-DIsLTku6.js} +1 -1
  260. package/web-shell/assets/{diagram-UQ7AKVKN-9VmCS0SV.js → diagram-UQ7AKVKN-60CC00CO.js} +1 -1
  261. package/web-shell/assets/{diagram-VSXAHHWV-D-MA8NCD.js → diagram-VSXAHHWV-BCfHqY7L.js} +1 -1
  262. package/web-shell/assets/{diagram-VX7I27RA-323tLIBS.js → diagram-VX7I27RA-BbTOx9qC.js} +1 -1
  263. package/web-shell/assets/{diagram-Z3DM3KII-C547h61H.js → diagram-Z3DM3KII-DLjgnodz.js} +1 -1
  264. package/web-shell/assets/{docx-preview-DHO0seXT.js → docx-preview-CfGqg6IJ.js} +1 -1
  265. package/web-shell/assets/{ebnfDiagram-PWID7BFC-DfB8wLF5.js → ebnfDiagram-PWID7BFC-Cf1IQbGo.js} +1 -1
  266. package/web-shell/assets/{erDiagram-SSCWMZ5O-tzqYkCjp.js → erDiagram-SSCWMZ5O-BTVNpu1y.js} +1 -1
  267. package/web-shell/assets/{flowDiagram-A5DVABFB-Dsw6uHjD.js → flowDiagram-A5DVABFB-BC404IkJ.js} +1 -1
  268. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-D1SaF3O0.js → ganttDiagram-EL5Y4UJY-BHP58V1Y.js} +1 -1
  269. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D0EzECMT.js → gitGraphDiagram-WWUBYQGX-s1PkjMd4.js} +1 -1
  270. package/web-shell/assets/{index-ob2Iut7D.js → index-DZnv4pXI.js} +6 -6
  271. package/web-shell/assets/{index-C-YHF5xI.js → index-YpdTDWts.js} +1 -1
  272. package/web-shell/assets/{infoDiagram-RXCK75RN-6NnYMmcC.js → infoDiagram-RXCK75RN-DDaQbbGu.js} +1 -1
  273. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BnxsfuuS.js → ishikawaDiagram-5VMMS53U-FpQWCzWS.js} +1 -1
  274. package/web-shell/assets/{journeyDiagram-EYS64GPL-DduswigY.js → journeyDiagram-EYS64GPL-CC5YG1zk.js} +1 -1
  275. package/web-shell/assets/{kanban-definition-3QL26DDD-D0trNRAQ.js → kanban-definition-3QL26DDD-CsitCmSH.js} +1 -1
  276. package/web-shell/assets/{layout-nP-pCdd_.js → layout-DR8LNzXS.js} +1 -1
  277. package/web-shell/assets/{linear-DCw4lqG9.js → linear-Dt61H2xY.js} +1 -1
  278. package/web-shell/assets/{mermaid.core-DYjTp4Sk.js → mermaid.core-C3SdL30W.js} +6 -6
  279. package/web-shell/assets/{mindmap-definition-FBJOCRG2-BK9iSa2V.js → mindmap-definition-FBJOCRG2-BjxTLs9R.js} +1 -1
  280. package/web-shell/assets/{pegDiagram-XKGWAZYB-Dg0TQ1Ty.js → pegDiagram-XKGWAZYB-eBurSwq6.js} +1 -1
  281. package/web-shell/assets/{pieDiagram-E7YTZNPT-DKeqeVkg.js → pieDiagram-E7YTZNPT-BFWkbtZz.js} +1 -1
  282. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-C4zBeQXd.js → quadrantDiagram-AXDQQJYC-SThzXP6T.js} +1 -1
  283. package/web-shell/assets/{railroadDiagram-O6MQD6OU-jDnAGU3z.js → railroadDiagram-O6MQD6OU-D73YId-T.js} +1 -1
  284. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-D0sIdHq4.js → requirementDiagram-EFPCY7ZU-YecInWjM.js} +1 -1
  285. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BFz_QzXx.js → sankeyDiagram-P5KCCOFB-D4Gl35cC.js} +1 -1
  286. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DhDmjiCT.js → sequenceDiagram-WJ2MYXX4-C1JdJSRH.js} +1 -1
  287. package/web-shell/assets/{sizeCapture-X5ZJPWSS-D8Ov3K_0.js → sizeCapture-X5ZJPWSS-D3mHX34v.js} +1 -1
  288. package/web-shell/assets/{stateDiagram-HBIQ2CUA-Bb4f1ILo.js → stateDiagram-HBIQ2CUA-BR05d7ll.js} +1 -1
  289. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BBhqVmOU.js +1 -0
  290. package/web-shell/assets/{swimlanes-XN3QIQJK-CQyilPoS.js → swimlanes-XN3QIQJK-CENq9EQ7.js} +1 -1
  291. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DI8ON7to.js +8 -0
  292. package/web-shell/assets/{timeline-definition-24CTP7MA-B_CntdLT.js → timeline-definition-24CTP7MA-DFhKdLgc.js} +1 -1
  293. package/web-shell/assets/{vennDiagram-4TSXK5OY-BbuHkADM.js → vennDiagram-4TSXK5OY-C-p5h-ue.js} +1 -1
  294. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-0mNKcB-T.js → wardleyDiagram-VM6X3IG4-BCWSjHZH.js} +1 -1
  295. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BL-rMOQs.js → xychartDiagram-S5SC5T6Z-DBvE_Y0y.js} +1 -1
  296. package/web-shell/index.html +1 -1
  297. package/web-shell/sw.js +1 -1
  298. package/web-shell/assets/channel-B31dxYCL.js +0 -1
  299. package/web-shell/assets/classDiagram-DTDB5LWJ-CxU_Ty2M.js +0 -1
  300. package/web-shell/assets/classDiagram-v2-JRS7N3AN-CxU_Ty2M.js +0 -1
  301. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-xbht8Czs.js +0 -1
  302. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dz34bASJ.js +0 -8
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{listExplicitCandidates}from"./chunk-EIVJHHRA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,DEFAULT_RING_MAX_BYTES,DEFAULT_RING_SIZE,JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeMaxRingBytes}from"./chunk-OFWAMIMB.js";import{JOURNAL_GROWTH_POOL_FRACTION,MAX_JOURNAL_GROWTH_POOL_MB,MIN_MEMORY_BUDGET_MB,isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{EXTERNAL_TOOL_GUARD_TOKEN_ENV}from"./chunk-NIEO2TBE.js";import{loadSettings}from"./chunk-E6XRNALG.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-XUB4JKSR.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{openBrowserSecurely,shouldLaunchBrowser}from"./chunk-3YWXKSOI.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var SEGMENT=/^[A-Za-z0-9_-]{1,256}$/;function parseJoinLink(link){let url;try{url=new URL(link.trim())}catch{throw new Error("--join expects the link shown by the coordinator.")}const marker=url.pathname.lastIndexOf("/join/");const[workspaceId,...rest]=marker>=0?url.pathname.slice(marker+"/join/".length).split("/"):[];if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.search||url.hash||!workspaceId||rest.some(Boolean)||!SEGMENT.test(workspaceId)){throw new Error("--join expects a link like https://host:4170/join/<workspace>.")}const base=url.pathname.slice(0,marker).replace(/\/+$/,"");return{serverUrl:`${url.origin}${base}`,workspaceId}}__name(parseJoinLink,"parseJoinLink");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");var DEFAULT_SERVE_HOSTNAME="127.0.0.1";function validateManagedLocalFlags(args){const supported=new Set(["--managed","--managed-data-dir","--port","--hostname","--open","--no-open","--open-with-auth","--no-open-with-auth","--web","--require-auth","--http-bridge"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed. Use --port, --managed-data-dir, and --open.`)}}__name(validateManagedLocalFlags,"validateManagedLocalFlags");function validateManagedWebFlags(args){const supported=new Set(["--managed-web-config","--hostname","--port","--allow-origin","--token","--require-auth"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed-web-config. Only hostname, port, allow-origin and browser authentication options are supported.`)}}__name(validateManagedWebFlags,"validateManagedWebFlags");async function startLocalControl(handle,address){await handle.runtimeReady;if(!handle.webShellMounted){throw new Error("Local Control requires the Web Shell.")}const service=handle.getLocalControl();if(!service){throw new Error("Local Control is unavailable on this daemon.")}let status;try{status=await service.enable(address?{address,allowExplicitAddress:true}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}if(err instanceof Error&&err.code==="no_lan_interface"){throw new Error(`${err.message} If this host's usable address is outside private/link-local space, or sits on a VPN/tunnel interface, name it: --local-control-address <ip>.`)}if(err instanceof Error&&err.code==="unknown_lan_interface"){const candidates=listExplicitCandidates();throw new Error(`${err.message}${candidates.length?` This host currently has: ${candidates.map(c=>`${c.interfaceName} (${c.address})`).join(", ")}.`:""}`)}throw err}if(!status.url){throw new Error("Local Control did not return a pairing URL.")}const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");writeStdoutLine("\nLocal Control is on. Scan this QR code from the same network:");writeStdoutLine(`
4
- ${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("managed",{type:"boolean",default:false,description:"Start the daemon and Managed Agent with shared WebShell and embedded storage; downloads the server on first use and requires Java 21."}).option("managed-data-dir",{type:"string",requiresArg:true,description:"Private persistent data directory for --managed; defaults to <Qwen home>/managed-local."}).option("managed-web-config",{type:"string",requiresArg:true,description:"Run only the authenticated Managed Web gateway using a JSON file with apiUrl, tenantId, actorId and signingKeyFile. Requires a non-empty independent browser token via QWEN_SERVER_TOKEN or --token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable. Defaults to 32, or to the serve.maxSessions setting (user, system, and system-defaults scopes only); the flag wins when passed."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("conversations-dir",{type:"string",requiresArg:true,description:"Absolute working-directory root shared by standalone and Live Conversations. Overrides QWEN_CONVERSATIONS_DIR; defaults to ~/Documents/Qwen Code/Conversations."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice. Naming an address outside RFC 1918/3927 space, or one on a VPN/tunnel interface (e.g. phone and laptop on the same corporate VPN), is accepted as an explicit opt-in; out-of-private-space picks are logged with a warning."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(Array.isArray(argv["conversations-dir"])){throw new Error("pass --conversations-dir once.")}normalizeMaxRingBytes(argv["event-ring-max-bytes"]);if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("event-ring-max-bytes",{type:"number",nargs:1,default:DEFAULT_RING_MAX_BYTES,description:"Per-session retained SSE replay ring byte cap, including the latest full commands snapshot. Must be a positive safe integer up to 256 MiB; no unlimited sentinel."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients. Accepts `*`, a canonical origin, or a loopback port wildcard like `http://127.0.0.1:*` (requires a bearer token)."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_URL."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_TOKEN; prefer the variable, since this option puts the credential in the process list."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{if(argv["managed-web-config"]!==void 0){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedWebFlags(process.argv.slice(serveIndex+1));if(argv.managed||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0){throw new Error("--managed-web-config cannot be combined with daemon execution or Managed local mode.")}const{runManagedWebServe}=await import("./managed-web-serve-OZTNI6DM.js");const handle=await runManagedWebServe({configFile:argv["managed-web-config"],hostname:argv.hostname,port:argv.port,token:argv.token,allowOrigins:argv["allow-origin"]});writeStdoutLine(`Managed WebShell: ${handle.url}`);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv.managed){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedLocalFlags(process.argv.slice(serveIndex+1));if(argv.hostname!==DEFAULT_SERVE_HOSTNAME||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0||argv.token!==void 0||argv["tls-cert"]||argv["tls-key"]||argv["local-control"]||argv.join||argv["agent-host-server"]||argv.channel!==void 0||argv["experimental-paired-engines"]||argv["experimental-managed-agents"]||argv["experimental-managed-runtime-worker"]||argv["experimental-managed-runtime-auto-local"]||argv["experimental-managed-runtime-url"]!==void 0||argv["managed-runtime-broker-url"]!==void 0||argv["managed-runtime-broker-token"]!==void 0||argv["allow-origin"]?.length||argv["enable-session-shell"]||!argv["http-bridge"]){throw new Error("--managed uses its own loopback services, persistent credentials, and application-owned Workspaces. Use --port, --managed-data-dir, and --open; other deployment, workspace-import, or execution modes cannot be combined.")}const{runManagedLocalServe}=await import("./managed-local-serve-TUVNNY7K.js");const handle=await runManagedLocalServe({port:argv.port,dataDirectory:argv["managed-data-dir"]});await maybeOpenWebShellBrowser(handle,argv.open||argv["open-with-auth"],argv["open-with-auth"]);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv["managed-data-dir"]!==void 0){writeStderrLine("qwen serve: --managed-data-dir requires --managed.");process.exit(1)}const managedRuntimeBrokerUrl=argv["managed-runtime-broker-url"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];const managedRuntimeBrokerToken=argv["managed-runtime-broker-token"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}if(argv["managed-runtime-broker-token"]!==void 0){writeStderrLine("qwen serve: --managed-runtime-broker-token is visible in the process command line; prefer the QWEN_MANAGED_RUNTIME_BROKER_TOKEN env var.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-6SWKYY6I.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],eventRingMaxBytes:argv["event-ring-max-bytes"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["conversations-dir"]!==void 0?{conversationsDir:argv["conversations-dir"]}:{},...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...managedRuntimeBrokerUrl!==void 0?{managedRuntimeBrokerUrl}:{},...managedRuntimeBrokerToken!==void 0?{managedRuntimeBrokerToken}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-DIV2XAL5.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,validateManagedLocalFlags,validateManagedWebFlags,maybeOpenWebShellBrowser,serveCommand};
3
+ import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{listExplicitCandidates}from"./chunk-EIVJHHRA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,DEFAULT_RING_MAX_BYTES,DEFAULT_RING_SIZE,JOURNAL_GROWTH_HARD_CAP_BYTES,normalizeMaxRingBytes}from"./chunk-OFWAMIMB.js";import{JOURNAL_GROWTH_POOL_FRACTION,MAX_JOURNAL_GROWTH_POOL_MB,MIN_MEMORY_BUDGET_MB,isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{EXTERNAL_TOOL_GUARD_TOKEN_ENV}from"./chunk-NIEO2TBE.js";import{loadSettings}from"./chunk-AEX3XSTE.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-3NR3JBMA.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{openBrowserSecurely,shouldLaunchBrowser}from"./chunk-3YWXKSOI.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var SEGMENT=/^[A-Za-z0-9_-]{1,256}$/;function parseJoinLink(link){let url;try{url=new URL(link.trim())}catch{throw new Error("--join expects the link shown by the coordinator.")}const marker=url.pathname.lastIndexOf("/join/");const[workspaceId,...rest]=marker>=0?url.pathname.slice(marker+"/join/".length).split("/"):[];if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.search||url.hash||!workspaceId||rest.some(Boolean)||!SEGMENT.test(workspaceId)){throw new Error("--join expects a link like https://host:4170/join/<workspace>.")}const base=url.pathname.slice(0,marker).replace(/\/+$/,"");return{serverUrl:`${url.origin}${base}`,workspaceId}}__name(parseJoinLink,"parseJoinLink");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");var DEFAULT_SERVE_HOSTNAME="127.0.0.1";function validateManagedLocalFlags(args){const supported=new Set(["--managed","--managed-data-dir","--port","--hostname","--open","--no-open","--open-with-auth","--no-open-with-auth","--web","--require-auth","--http-bridge"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed. Use --port, --managed-data-dir, and --open.`)}}__name(validateManagedLocalFlags,"validateManagedLocalFlags");function validateManagedWebFlags(args){const supported=new Set(["--managed-web-config","--hostname","--port","--allow-origin","--token","--require-auth"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed-web-config. Only hostname, port, allow-origin and browser authentication options are supported.`)}}__name(validateManagedWebFlags,"validateManagedWebFlags");async function startLocalControl(handle,address){await handle.runtimeReady;if(!handle.webShellMounted){throw new Error("Local Control requires the Web Shell.")}const service=handle.getLocalControl();if(!service){throw new Error("Local Control is unavailable on this daemon.")}let status;try{status=await service.enable(address?{address,allowExplicitAddress:true}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}if(err instanceof Error&&err.code==="no_lan_interface"){throw new Error(`${err.message} If this host's usable address is outside private/link-local space, or sits on a VPN/tunnel interface, name it: --local-control-address <ip>.`)}if(err instanceof Error&&err.code==="unknown_lan_interface"){const candidates=listExplicitCandidates();throw new Error(`${err.message}${candidates.length?` This host currently has: ${candidates.map(c=>`${c.interfaceName} (${c.address})`).join(", ")}.`:""}`)}throw err}if(!status.url){throw new Error("Local Control did not return a pairing URL.")}const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");writeStdoutLine("\nLocal Control is on. Scan this QR code from the same network:");writeStdoutLine(`
4
+ ${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("managed",{type:"boolean",default:false,description:"Start the daemon and Managed Agent with shared WebShell and embedded storage; downloads the server on first use and requires Java 21."}).option("managed-data-dir",{type:"string",requiresArg:true,description:"Private persistent data directory for --managed; defaults to <Qwen home>/managed-local."}).option("managed-web-config",{type:"string",requiresArg:true,description:"Run only the authenticated Managed Web gateway using a JSON file with apiUrl, tenantId, actorId and signingKeyFile. Requires a non-empty independent browser token via QWEN_SERVER_TOKEN or --token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable. Defaults to 32, or to the serve.maxSessions setting (user, system, and system-defaults scopes only); the flag wins when passed."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("conversations-dir",{type:"string",requiresArg:true,description:"Absolute working-directory root shared by standalone and Live Conversations. Overrides QWEN_CONVERSATIONS_DIR; defaults to ~/Documents/Qwen Code/Conversations."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice. Naming an address outside RFC 1918/3927 space, or one on a VPN/tunnel interface (e.g. phone and laptop on the same corporate VPN), is accepted as an explicit opt-in; out-of-private-space picks are logged with a warning."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(Array.isArray(argv["conversations-dir"])){throw new Error("pass --conversations-dir once.")}normalizeMaxRingBytes(argv["event-ring-max-bytes"]);if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("event-ring-max-bytes",{type:"number",nargs:1,default:DEFAULT_RING_MAX_BYTES,description:"Per-session retained SSE replay ring byte cap, including the latest full commands snapshot. Must be a positive safe integer up to 256 MiB; no unlimited sentinel."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients. Accepts `*`, a canonical origin, or a loopback port wildcard like `http://127.0.0.1:*` (requires a bearer token)."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_URL."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_TOKEN; prefer the variable, since this option puts the credential in the process list."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{if(argv["managed-web-config"]!==void 0){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedWebFlags(process.argv.slice(serveIndex+1));if(argv.managed||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0){throw new Error("--managed-web-config cannot be combined with daemon execution or Managed local mode.")}const{runManagedWebServe}=await import("./managed-web-serve-OZTNI6DM.js");const handle=await runManagedWebServe({configFile:argv["managed-web-config"],hostname:argv.hostname,port:argv.port,token:argv.token,allowOrigins:argv["allow-origin"]});writeStdoutLine(`Managed WebShell: ${handle.url}`);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv.managed){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedLocalFlags(process.argv.slice(serveIndex+1));if(argv.hostname!==DEFAULT_SERVE_HOSTNAME||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv["conversations-dir"]!==void 0||argv.token!==void 0||argv["tls-cert"]||argv["tls-key"]||argv["local-control"]||argv.join||argv["agent-host-server"]||argv.channel!==void 0||argv["experimental-paired-engines"]||argv["experimental-managed-agents"]||argv["experimental-managed-runtime-worker"]||argv["experimental-managed-runtime-auto-local"]||argv["experimental-managed-runtime-url"]!==void 0||argv["managed-runtime-broker-url"]!==void 0||argv["managed-runtime-broker-token"]!==void 0||argv["allow-origin"]?.length||argv["enable-session-shell"]||!argv["http-bridge"]){throw new Error("--managed uses its own loopback services, persistent credentials, and application-owned Workspaces. Use --port, --managed-data-dir, and --open; other deployment, workspace-import, or execution modes cannot be combined.")}const{runManagedLocalServe}=await import("./managed-local-serve-UTJFLZI6.js");const handle=await runManagedLocalServe({port:argv.port,dataDirectory:argv["managed-data-dir"]});await maybeOpenWebShellBrowser(handle,argv.open||argv["open-with-auth"],argv["open-with-auth"]);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv["managed-data-dir"]!==void 0){writeStderrLine("qwen serve: --managed-data-dir requires --managed.");process.exit(1)}const managedRuntimeBrokerUrl=argv["managed-runtime-broker-url"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];const managedRuntimeBrokerToken=argv["managed-runtime-broker-token"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}if(argv["managed-runtime-broker-token"]!==void 0){writeStderrLine("qwen serve: --managed-runtime-broker-token is visible in the process command line; prefer the QWEN_MANAGED_RUNTIME_BROKER_TOKEN env var.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-BVNSBOLL.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],eventRingMaxBytes:argv["event-ring-max-bytes"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["conversations-dir"]!==void 0?{conversationsDir:argv["conversations-dir"]}:{},...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...managedRuntimeBrokerUrl!==void 0?{managedRuntimeBrokerUrl}:{},...managedRuntimeBrokerToken!==void 0?{managedRuntimeBrokerToken}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-YZJLSOLB.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,validateManagedLocalFlags,validateManagedWebFlags,maybeOpenWebShellBrowser,serveCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{DEFAULT_DARK_THEME_NAME,DEFAULT_LIGHT_THEME_NAME}from"./chunk-UWCF7JIF.js";import{customDeepMerge,getSettingsSchema}from"./chunk-F7KVMGGZ.js";import{CONSOLIDATED_DISABLE_KEYS,V1_INDICATOR_KEYS,V1_TO_V2_MIGRATION_MAP,V1_TO_V2_PRESERVE_DISABLE_MAP,V2_CONTAINER_KEYS}from"./chunk-LMUSSYJH.js";import{t}from"./chunk-HRRQHZQE.js";import{SUPPORTED_LANGUAGES,getLanguageNameFromLocale}from"./chunk-YE3LA3U4.js";import{SETTINGS_DIRECTORY_NAME,getHomeEnvFallbackVars,loadEnvironment,preResolveHomeEnvOverrides}from"./chunk-OSLFWRV2.js";import{ENV_CORRUPTED_PATH,ENV_WAS_RECOVERED,applyVerifyPrCoordinateEnv}from"./chunk-AJTR5LAF.js";import{parseExecutionSandboxSettings,readBareModeOperatorSettings,readOperatorSandboxSettings,require_strip_json_comments,selectOperatorCatalogRefresh,selectOperatorExecutionSandbox,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{getGlobalQwenDirLite,getSystemDefaultsPath,getSystemSettingsPath,spawnedEnvironmentView}from"./chunk-ERGT5BD3.js";import{isWorkspaceTrusted,updateSettingsFilePreservingFormat}from"./chunk-SGUUOXLH.js";import{isValidAdvisorMaxUses}from"./chunk-XUB4JKSR.js";import{resolveEnvVarsInObject}from"./chunk-ZOTKZI2P.js";import{stripRuntimeSnapshotPrefix}from"./chunk-N3AKLLXG.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{FatalConfigError,getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs3 from"node:fs";import*as path2 from"node:path";import{homedir}from"node:os";import process from"node:process";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);init_esbuild_shims();function hasOwnModelProviders(settingsObj){if(!settingsObj||typeof settingsObj!=="object"){return false}const obj=settingsObj;return Object.prototype.hasOwnProperty.call(obj,"modelProviders")}__name(hasOwnModelProviders,"hasOwnModelProviders");function getModelProvidersOwnerScope(settings){if(settings.isTrusted&&hasOwnModelProviders(settings.workspace.settings)){return"Workspace"}if(hasOwnModelProviders(settings.user.settings)){return"User"}return void 0}__name(getModelProvidersOwnerScope,"getModelProvidersOwnerScope");function getPersistScopeForModelSelection(settings){if(settings.isTrusted&&settings.workspace.settings.security?.auth?.selectedType==="qwen-subscription"){return"Workspace"}return getModelProvidersOwnerScope(settings)??"User"}__name(getPersistScopeForModelSelection,"getPersistScopeForModelSelection");function getSubscriptionStartupFallbackModel(settings,authType,config){if(authType!=="qwen-subscription"||!settings.isTrusted||!settings.workspaceSettingsActive){return void 0}const{user,workspace,system}=settings;const enforcedType=settings.merged.security?.auth?.enforcedType;const projectModel=workspace.settings.model;if(projectModel?.name&&projectModel.name===config.getModel()&&user.settings.security?.auth?.selectedType===authType&&(!enforcedType||enforcedType===authType)&&workspace.settings.security?.auth?.selectedType===void 0&&!projectModel.baseUrl&&workspace.settings.modelProviders===void 0&&system.settings.security?.auth?.selectedType===void 0&&system.settings.model?.name===void 0){return user.settings.model?.name}return void 0}__name(getSubscriptionStartupFallbackModel,"getSubscriptionStartupFallbackModel");function getWritableScopes(settings){return settings.isTrusted?["Workspace","User"]:["User"]}__name(getWritableScopes,"getWritableScopes");function getOwnKeyScope(settings,key){for(const scope of getWritableScopes(settings)){const obj=settings.forScope(scope).settings;if(Object.prototype.hasOwnProperty.call(obj,key))return scope}return void 0}__name(getOwnKeyScope,"getOwnKeyScope");init_esbuild_shims();init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var LLM_OUTPUT_LANGUAGE_RULE_FILENAME="output-language.md";var LLM_OUTPUT_LANGUAGE_MARKER_PREFIX="qwen-code:llm-output-language:";var OUTPUT_LANGUAGE_AUTO="auto";function isAutoLanguage(value){return!value||value.toLowerCase()===OUTPUT_LANGUAGE_AUTO}__name(isAutoLanguage,"isAutoLanguage");function normalizeOutputLanguage(language){const normalized=language.trim().replace(/_/g,"-").toLowerCase();const knownLanguageName=SUPPORTED_LANGUAGES.find(supportedLanguage=>supportedLanguage.fullName.toLowerCase()===normalized);if(knownLanguageName){return knownLanguageName.fullName}const knownLocaleCode=SUPPORTED_LANGUAGES.some(supportedLanguage=>{const code=supportedLanguage.code.toLowerCase();const id=supportedLanguage.id.toLowerCase();return normalized===code||normalized===id||normalized.startsWith(`${code}-`)||normalized.startsWith(`${id}-`)||normalized.startsWith(`${code}.`)||normalized.startsWith(`${id}.`)||normalized.startsWith(`${code}@`)||normalized.startsWith(`${id}@`)});if(!knownLocaleCode){return language}return getLanguageNameFromLocale(normalized)}__name(normalizeOutputLanguage,"normalizeOutputLanguage");function resolveOutputLanguage(value){if(isAutoLanguage(value)){throw new Error("resolveOutputLanguage does not accept auto; use resolveOutputLanguageOrPreserveAuto instead.")}return normalizeOutputLanguage(value)}__name(resolveOutputLanguage,"resolveOutputLanguage");function resolveOutputLanguageOrPreserveAuto(value){return isAutoLanguage(value)?OUTPUT_LANGUAGE_AUTO:resolveOutputLanguage(value)}__name(resolveOutputLanguageOrPreserveAuto,"resolveOutputLanguageOrPreserveAuto");function getOutputLanguageFilePath(){return path.join(Storage.getGlobalQwenDir(),LLM_OUTPUT_LANGUAGE_RULE_FILENAME)}__name(getOutputLanguageFilePath,"getOutputLanguageFilePath");function sanitizeForMarker(language){return language.replace(/[\r\n]/g," ").replace(/--!?>/g,"").replace(/--/g,"")}__name(sanitizeForMarker,"sanitizeForMarker");function generateOutputLanguageFileContent(language){const safeLanguage=sanitizeForMarker(language);if(isAutoLanguage(language)){return`# Output language preference: ${OUTPUT_LANGUAGE_AUTO}
3
+ import{DEFAULT_DARK_THEME_NAME,DEFAULT_LIGHT_THEME_NAME}from"./chunk-UWCF7JIF.js";import{customDeepMerge,getSettingsSchema}from"./chunk-QD4KNY2J.js";import{CONSOLIDATED_DISABLE_KEYS,V1_INDICATOR_KEYS,V1_TO_V2_MIGRATION_MAP,V1_TO_V2_PRESERVE_DISABLE_MAP,V2_CONTAINER_KEYS}from"./chunk-LMUSSYJH.js";import{t}from"./chunk-73TSS7KS.js";import{SUPPORTED_LANGUAGES,getLanguageNameFromLocale}from"./chunk-FWJKQA2H.js";import{SETTINGS_DIRECTORY_NAME,getHomeEnvFallbackVars,loadEnvironment,preResolveHomeEnvOverrides}from"./chunk-HRTWLOGK.js";import{ENV_CORRUPTED_PATH,ENV_WAS_RECOVERED,applyVerifyPrCoordinateEnv}from"./chunk-AJTR5LAF.js";import{parseExecutionSandboxSettings,readBareModeOperatorSettings,readOperatorSandboxSettings,require_strip_json_comments,selectOperatorCatalogRefresh,selectOperatorExecutionSandbox,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{getGlobalQwenDirLite,getSystemDefaultsPath,getSystemSettingsPath,spawnedEnvironmentView}from"./chunk-ERGT5BD3.js";import{isWorkspaceTrusted,updateSettingsFilePreservingFormat}from"./chunk-WDO33SWR.js";import{isValidAdvisorMaxUses}from"./chunk-3NR3JBMA.js";import{resolveEnvVarsInObject}from"./chunk-ZOTKZI2P.js";import{stripRuntimeSnapshotPrefix}from"./chunk-N3AKLLXG.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{FatalConfigError,getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs3 from"node:fs";import*as path2 from"node:path";import{homedir}from"node:os";import process from"node:process";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);init_esbuild_shims();function hasOwnModelProviders(settingsObj){if(!settingsObj||typeof settingsObj!=="object"){return false}const obj=settingsObj;return Object.prototype.hasOwnProperty.call(obj,"modelProviders")}__name(hasOwnModelProviders,"hasOwnModelProviders");function getModelProvidersOwnerScope(settings){if(settings.isTrusted&&hasOwnModelProviders(settings.workspace.settings)){return"Workspace"}if(hasOwnModelProviders(settings.user.settings)){return"User"}return void 0}__name(getModelProvidersOwnerScope,"getModelProvidersOwnerScope");function getPersistScopeForModelSelection(settings){if(settings.isTrusted&&settings.workspace.settings.security?.auth?.selectedType==="qwen-subscription"){return"Workspace"}return getModelProvidersOwnerScope(settings)??"User"}__name(getPersistScopeForModelSelection,"getPersistScopeForModelSelection");function getSubscriptionStartupFallbackModel(settings,authType,config){if(authType!=="qwen-subscription"||!settings.isTrusted||!settings.workspaceSettingsActive){return void 0}const{user,workspace,system}=settings;const enforcedType=settings.merged.security?.auth?.enforcedType;const projectModel=workspace.settings.model;if(projectModel?.name&&projectModel.name===config.getModel()&&user.settings.security?.auth?.selectedType===authType&&(!enforcedType||enforcedType===authType)&&workspace.settings.security?.auth?.selectedType===void 0&&!projectModel.baseUrl&&workspace.settings.modelProviders===void 0&&system.settings.security?.auth?.selectedType===void 0&&system.settings.model?.name===void 0){return user.settings.model?.name}return void 0}__name(getSubscriptionStartupFallbackModel,"getSubscriptionStartupFallbackModel");function getWritableScopes(settings){return settings.isTrusted?["Workspace","User"]:["User"]}__name(getWritableScopes,"getWritableScopes");function getOwnKeyScope(settings,key){for(const scope of getWritableScopes(settings)){const obj=settings.forScope(scope).settings;if(Object.prototype.hasOwnProperty.call(obj,key))return scope}return void 0}__name(getOwnKeyScope,"getOwnKeyScope");init_esbuild_shims();init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var LLM_OUTPUT_LANGUAGE_RULE_FILENAME="output-language.md";var LLM_OUTPUT_LANGUAGE_MARKER_PREFIX="qwen-code:llm-output-language:";var OUTPUT_LANGUAGE_AUTO="auto";function isAutoLanguage(value){return!value||value.toLowerCase()===OUTPUT_LANGUAGE_AUTO}__name(isAutoLanguage,"isAutoLanguage");function normalizeOutputLanguage(language){const normalized=language.trim().replace(/_/g,"-").toLowerCase();const knownLanguageName=SUPPORTED_LANGUAGES.find(supportedLanguage=>supportedLanguage.fullName.toLowerCase()===normalized);if(knownLanguageName){return knownLanguageName.fullName}const knownLocaleCode=SUPPORTED_LANGUAGES.some(supportedLanguage=>{const code=supportedLanguage.code.toLowerCase();const id=supportedLanguage.id.toLowerCase();return normalized===code||normalized===id||normalized.startsWith(`${code}-`)||normalized.startsWith(`${id}-`)||normalized.startsWith(`${code}.`)||normalized.startsWith(`${id}.`)||normalized.startsWith(`${code}@`)||normalized.startsWith(`${id}@`)});if(!knownLocaleCode){return language}return getLanguageNameFromLocale(normalized)}__name(normalizeOutputLanguage,"normalizeOutputLanguage");function resolveOutputLanguage(value){if(isAutoLanguage(value)){throw new Error("resolveOutputLanguage does not accept auto; use resolveOutputLanguageOrPreserveAuto instead.")}return normalizeOutputLanguage(value)}__name(resolveOutputLanguage,"resolveOutputLanguage");function resolveOutputLanguageOrPreserveAuto(value){return isAutoLanguage(value)?OUTPUT_LANGUAGE_AUTO:resolveOutputLanguage(value)}__name(resolveOutputLanguageOrPreserveAuto,"resolveOutputLanguageOrPreserveAuto");function getOutputLanguageFilePath(){return path.join(Storage.getGlobalQwenDir(),LLM_OUTPUT_LANGUAGE_RULE_FILENAME)}__name(getOutputLanguageFilePath,"getOutputLanguageFilePath");function sanitizeForMarker(language){return language.replace(/[\r\n]/g," ").replace(/--!?>/g,"").replace(/--/g,"")}__name(sanitizeForMarker,"sanitizeForMarker");function generateOutputLanguageFileContent(language){const safeLanguage=sanitizeForMarker(language);if(isAutoLanguage(language)){return`# Output language preference: ${OUTPUT_LANGUAGE_AUTO}
4
4
  <!-- ${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX} ${OUTPUT_LANGUAGE_AUTO} -->
5
5
 
6
6
  ## Rule
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{encodeTextFileContentAsync}from"./chunk-XUB4JKSR.js";import{assertShellSandboxCwd}from"./chunk-IWT6YN3M.js";import{executeSandbox}from"./chunk-UYYKHWZ6.js";import{sandboxAsset}from"./chunk-MTPKKEGR.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
3
+ import{encodeTextFileContentAsync}from"./chunk-3NR3JBMA.js";import{assertShellSandboxCwd}from"./chunk-IWT6YN3M.js";import{executeSandbox}from"./chunk-UYYKHWZ6.js";import{sandboxAsset}from"./chunk-MTPKKEGR.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{DropNoticeThrottle,DropReceiptCoalescer,getPeerControllerRegistryPath,readPeerControllerRegistrySync,resolveControllerToken,startPeerInbox}from"./chunk-HXYHIEMH.js";import{InboundGate,MAX_HELD_MESSAGES,PEER_ADMISSION_LIMITS,canonicalizeMsgId,drainSendPacer,forgetSendPacerMessages,peerSenderKey,refundSendPacerMessage,refundSendPacerToken,sendDeliveryStatus,settleSentPeerMessage}from"./chunk-UNDRWCST.js";import{formatPeerDisplay,formatPeerEnvelope}from"./chunk-VMRQ6FA2.js";import{MESSAGING_SOCKET_ENV,MESSAGING_TOKEN_ENV,clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomBytes}from"node:crypto";var debugLogger=createDebugLogger("PEER_MESSAGING");var MAX_ACCEPTED_BACKLOG=MAX_HELD_MESSAGES;var CLOSE_DROP_FLUSH_BOUND_MS=1e3;var MAX_UNHEARD_DROP_NOTICES=20;var RECEIVER_REFILL_MS=PEER_ADMISSION_LIMITS.bucketCapacity/PEER_ADMISSION_LIMITS.refillPerSecond*1e3;var PeerMessaging=class _PeerMessaging{static{__name(this,"PeerMessaging")}inbox=null;gate=null;updateSessionRegistryIpcPath=__name(async()=>{},"updateSessionRegistryIpcPath");getSessionId=null;ownsSessionId=null;settleSentMessage=settleSentPeerMessage;reassertSessionRecord=null;drainMirror=drainSendPacer;forgetMirror=forgetSendPacerMessages;refundMirror=refundSendPacerMessage;refundMirrorToken=refundSendPacerToken;receiptListeners=new Set;dropListeners=new Set;unheardDrops=[];dropReceipts=null;submitFn=null;buffered=[];controllerRegistryPath=null;validControllerIds=null;outstanding=[];queuedPeerCount=null;heldListeners=new Set;listedHeld=null;closed=false;constructor(){}static async start(options){if(options.getSessionId&&options.ownsSessionId){throw new Error("PeerMessaging: pass getSessionId or ownsSessionId, not both")}const messaging=new _PeerMessaging;const controllerRegistryPath=options.controllerRegistryPath??getPeerControllerRegistryPath();messaging.controllerRegistryPath=controllerRegistryPath;const dropReceipts=new DropReceiptCoalescer(({frame,reason,droppedMsgIds})=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status:"dropped",origMsgId:frame.msgId,from:messaging.inbox?.socketPath,dropReason:reason,droppedMsgIds},frame.replyToken)},options.dropReceiptTrailMs!==void 0?{trailMs:options.dropReceiptTrailMs}:{});messaging.dropReceipts=dropReceipts;const dropNotices=new DropNoticeThrottle(notice=>messaging.emitDropped(notice));const gate=new InboundGate({getApprovalMode:options.getApprovalMode,getPolicySetting:options.getPolicySetting,...options.getHeldExpiryMs!==void 0?{getHeldExpiryMs:options.getHeldExpiryMs}:{},...options.getPolicyScope?{getPolicyScope:options.getPolicyScope}:{},isControllerValid:__name(id=>messaging.validControllerIds?.has(id)??true,"isControllerValid"),...options.admission?{admission:options.admission}:{},getSessionId:options.getSessionId,...options.ownsSessionId?{ownsSessionId:options.ownsSessionId}:{},deliver:__name((frame,origin)=>messaging.deliver(frame,origin),"deliver"),reportDropped:__name((frame,reason,origin)=>dropReceipts.note(frame,origin??{selfSent:false},reason),"reportDropped"),onDropped:__name((frame,origin,reason)=>dropNotices.note(frame,origin,reason),"onDropped"),reportStatus:__name((frame,status)=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status,origMsgId:frame.msgId,from:messaging.inbox?.socketPath},frame.replyToken)},"reportStatus"),onHeldChange:__name(held=>messaging.emitHeldChange(held),"onHeldChange")});messaging.gate=gate;messaging.getSessionId=options.getSessionId??null;messaging.ownsSessionId=options.ownsSessionId??null;messaging.settleSentMessage=options.settleSentMessage??settleSentPeerMessage;messaging.reassertSessionRecord=options.reassertSessionRecord??null;messaging.drainMirror=options.drainMirror??drainSendPacer;messaging.forgetMirror=options.forgetMirror??forgetSendPacerMessages;messaging.refundMirror=options.refundMirror??refundSendPacerMessage;messaging.refundMirrorToken=options.refundMirrorToken??refundSendPacerToken;clearInheritedPeerMessagingEnv();const ipcToken=options.ipcToken??randomBytes(32).toString("hex");const childToken=options.childToken??randomBytes(32).toString("hex");const inbox=await startPeerInbox({...options.socketPath!==void 0?{socketPath:options.socketPath}:{},requiredToken:ipcToken,childToken,resolveController:__name(presented=>resolveControllerToken(presented,controllerRegistryPath),"resolveController"),onFrame:__name((frame,auth,controller)=>messaging.onFrame(frame,{selfSent:auth==="child",...controller?{controller}:{}}),"onFrame")});if(!inbox)return null;messaging.inbox=inbox;messaging.updateSessionRegistryIpcPath=options.updateSessionRegistryIpcPath;await messaging.updateSessionRegistryIpcPath(inbox.socketPath,ipcToken);process.env[MESSAGING_SOCKET_ENV]=inbox.socketPath;process.env[MESSAGING_TOKEN_ENV]=childToken;return messaging}get socketPath(){return this.inbox?.socketPath}setSubmitFn(fn){if(this.closed)return;this.withControllerValidity(()=>{this.submitFn=fn;while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin))break;this.buffered.shift()}})}setQueuedPeerCount(fn){this.queuedPeerCount=fn}getHeld(){return this.withControllerValidity(()=>this.gate?.getHeld()??[])}getHeldExpiryMs(sessionId){return this.gate?.getHeldExpiryMs(sessionId)??null}recordHeldListing(heldEntries){this.listedHeld=heldEntries.map(entry=>({id:entry.frame.msgId,heldAt:entry.heldAt}))}heldSetChangedSinceListing(){const listed=this.listedHeld;if(listed===null)return true;const pinned=new Map(listed.map(entry=>[entry.id,entry.heldAt]));const current=this.getHeld();if(current.some(entry=>pinned.get(entry.frame.msgId)!==entry.heldAt))return true;const liveIds=current.map(entry=>canonicalizeMsgId(entry.frame.msgId));const liveSet=new Set(liveIds);for(const id of pinned.keys()){const departed=canonicalizeMsgId(id);if(liveSet.has(departed))continue;if(liveIds.some(live=>live.startsWith(departed)))return true}return false}decide(msgId,decision){return this.withControllerValidity(()=>this.gate?.decide(msgId,decision)??"gone")}forgetController(id){return this.withControllerValidity(()=>this.gate?.forgetController(id)??0)}reevaluate(reason){return this.withControllerValidity(()=>this.gate?.reevaluate(reason)??0)}onHeldChange(listener){this.heldListeners.add(listener);try{listener(this.getHeld())}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}return()=>this.heldListeners.delete(listener)}onReceipt(listener){this.receiptListeners.add(listener);return()=>this.receiptListeners.delete(listener)}onDropped(listener){const first=this.dropListeners.size===0;this.dropListeners.add(listener);if(first&&this.unheardDrops.length>0){const unheard=this.unheardDrops.splice(0,this.unheardDrops.length);for(const notice of unheard){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw on replay: ${error instanceof Error?error.message:String(error)}`)}}}return()=>this.dropListeners.delete(listener)}emitDropped(notice){if(this.dropListeners.size===0){if(this.unheardDrops.length<MAX_UNHEARD_DROP_NOTICES){this.unheardDrops.push(notice)}return}for(const listener of this.dropListeners){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw: ${error instanceof Error?error.message:String(error)}`)}}}emitReceipt(receipt){for(const listener of this.receiptListeners){try{listener(receipt)}catch(error){debugLogger.debug(`receipt listener threw: ${error instanceof Error?error.message:String(error)}`)}}}async close(){if(this.closed)return;this.closed=true;const shuttingDown=this.gate?.shutdown();await this.inbox?.close();await shuttingDown;await this.settleUnconsumed();clearInheritedPeerMessagingEnv();await this.updateSessionRegistryIpcPath(void 0);await this.dropReceipts?.flush(CLOSE_DROP_FLUSH_BOUND_MS);this.dropReceipts?.dispose()}async settleUnconsumed(){const queued=this.queuedPeerCount?.()??0;const dropped=this.outstanding.slice(Math.max(0,this.outstanding.length-this.buffered.length-queued));const receipts=dropped.filter(frame=>frame.from!==void 0).map(frame=>sendDeliveryStatus(frame.from,{status:"expired",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken));await Promise.allSettled(receipts)}onDroppedReceipt(frame){const ids=[frame.origMsgId,...frame.droppedMsgIds??[]];let first;let settledCount=0;const settledByPath=new Map;for(const id of ids){const settled=this.settleSentMessage(id,"dropped");if(!settled)continue;first??=settled;settledCount+=1;const entry=settledByPath.get(settled.ipcPath)??{ids:[],freshestAgeMs:Number.POSITIVE_INFINITY};entry.ids.push(id);entry.freshestAgeMs=Math.min(entry.freshestAgeMs,settled.ageMs);settledByPath.set(settled.ipcPath,entry)}if(!first){debugLogger.debug(`ignoring dropped receipt for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`dropped receipt from ${first.address} (${frame.dropReason??"unspecified"}) settled ${settledCount} message(s)`);if(frame.dropReason==="duplicate"){for(const[ipcPath,entry]of settledByPath){for(const id of entry.ids)this.refundMirrorToken(ipcPath,id)}}else{for(const[ipcPath,entry]of settledByPath){this.forgetMirror(ipcPath,entry.ids)}}if(frame.dropReason==="rate-limited"){for(const[ipcPath,entry]of settledByPath){if(entry.freshestAgeMs<=RECEIVER_REFILL_MS)this.drainMirror(ipcPath)}}this.emitReceipt({status:"dropped",address:first.address,origMsgId:frame.origMsgId,previous:"pending",...frame.dropReason?{dropReason:frame.dropReason}:{},dropped:settledCount})}onFrame(frame,origin){if(frame.type==="control"){if(frame.status==="dropped"){this.onDroppedReceipt(frame);return}const settled=this.settleSentMessage(frame.origMsgId,frame.status);if(!settled){debugLogger.debug(`ignoring delivery status ${frame.status} for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`delivery status from ${settled.address}: ${settled.previous} -> ${frame.status} for ${frame.origMsgId}`);if(frame.status!=="held"&&frame.status!=="delivered"){if(frame.status==="misaddressed"){this.refundMirror(settled.ipcPath,frame.origMsgId)}else{this.forgetMirror(settled.ipcPath,[frame.origMsgId])}}this.emitReceipt({status:frame.status,address:settled.address,origMsgId:frame.origMsgId,previous:settled.previous});return}const ownSessionId=this.getSessionId?.();const ownsSessionId=this.ownsSessionId;const misaddressed=ownsSessionId?frame.toSessionId===void 0||!ownsSessionId(frame.toSessionId):frame.toSessionId!==void 0&&ownSessionId!==void 0&&frame.toSessionId!==ownSessionId;if(misaddressed){debugLogger.debug(`refusing peer message ${frame.msgId}: addressed to session ${frame.toSessionId??"(unspecified)"}, this process does not hold it`);if(frame.from){void sendDeliveryStatus(frame.from,{status:"misaddressed",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken)}void this.reassertSessionRecord?.().catch(error=>{debugLogger.debug(`re-asserting the session record failed: ${error instanceof Error?error.message:String(error)}`)});return}this.gate?.admit(frame,origin)}deliver(frame,origin){if(!this.submitFn){if(this.buffered.length>=MAX_ACCEPTED_BACKLOG){throw new Error("accepted-message backlog is full")}this.buffered.push({frame,origin});this.trackOutstanding(frame);return}if(this.buffered.length>0){this.withControllerValidity(()=>{while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin)){throw new Error("accepted-message backlog is full")}this.buffered.shift()}})}if(!this.submit(frame,origin)){throw new Error("accepted-message backlog is full")}this.trackOutstanding(frame)}trackOutstanding(frame){this.outstanding.push(frame);while(this.outstanding.length>2*MAX_ACCEPTED_BACKLOG){this.outstanding.shift()}}withControllerValidity(action){if(this.controllerRegistryPath===null||this.validControllerIds){return action()}this.validControllerIds=new Set(readPeerControllerRegistrySync(this.controllerRegistryPath).controllers.map(controller=>controller.id));for(const delivery of this.buffered){const controller=delivery.origin.controller;if(controller&&!this.validControllerIds.has(controller.id)){delete delivery.origin.controller}}try{return action()}finally{this.validControllerIds=null}}submit(frame,origin){const from=frame.from??(origin.controller?"controller":origin.selfSent?"own process":"unknown session");const attribution={selfSent:origin.selfSent,...origin.controller?{controller:origin.controller}:{}};return this.submitFn?.(formatPeerEnvelope({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),formatPeerDisplay({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),{msgId:frame.msgId,admissionKey:peerSenderKey(frame,origin),...frame.from!==void 0?{from:frame.from}:{},...frame.replyToken!==void 0?{replyToken:frame.replyToken}:{},...frame.toSessionId!==void 0?{toSessionId:frame.toSessionId}:{}})??false}drainQueuedFrame(delivery){const ownSessionId=this.getSessionId?.();if(delivery?.toSessionId===void 0||ownSessionId===void 0||delivery.toSessionId===ownSessionId){return true}debugLogger.debug(`dropping queued peer message ${delivery.msgId}: addressed to session ${delivery.toSessionId}, this is ${ownSessionId}`);if(delivery.from){void sendDeliveryStatus(delivery.from,{status:"misaddressed",origMsgId:delivery.msgId,from:this.inbox?.socketPath},delivery.replyToken)}if(delivery.admissionKey!==void 0){this.gate?.forgetAdmittedMessage(delivery.admissionKey,delivery.msgId)}return false}emitHeldChange(held){for(const listener of this.heldListeners){try{listener(held)}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}}}};export{MAX_ACCEPTED_BACKLOG,PeerMessaging};
3
+ import{DropNoticeThrottle,DropReceiptCoalescer,getPeerControllerRegistryPath,readPeerControllerRegistrySync,resolveControllerToken,startPeerInbox}from"./chunk-CXPRHT3E.js";import{InboundGate,MAX_HELD_MESSAGES,PEER_ADMISSION_LIMITS,canonicalizeMsgId,drainSendPacer,forgetSendPacerMessages,peerSenderKey,refundSendPacerMessage,refundSendPacerToken,sendDeliveryStatus,settleSentPeerMessage}from"./chunk-UNDRWCST.js";import{formatPeerDisplay,formatPeerEnvelope}from"./chunk-VMRQ6FA2.js";import{MESSAGING_SOCKET_ENV,MESSAGING_TOKEN_ENV,clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomBytes}from"node:crypto";var debugLogger=createDebugLogger("PEER_MESSAGING");var MAX_ACCEPTED_BACKLOG=MAX_HELD_MESSAGES;var CLOSE_DROP_FLUSH_BOUND_MS=1e3;var MAX_UNHEARD_DROP_NOTICES=20;var RECEIVER_REFILL_MS=PEER_ADMISSION_LIMITS.bucketCapacity/PEER_ADMISSION_LIMITS.refillPerSecond*1e3;var PeerMessaging=class _PeerMessaging{static{__name(this,"PeerMessaging")}inbox=null;gate=null;updateSessionRegistryIpcPath=__name(async()=>{},"updateSessionRegistryIpcPath");getSessionId=null;ownsSessionId=null;settleSentMessage=settleSentPeerMessage;reassertSessionRecord=null;drainMirror=drainSendPacer;forgetMirror=forgetSendPacerMessages;refundMirror=refundSendPacerMessage;refundMirrorToken=refundSendPacerToken;receiptListeners=new Set;dropListeners=new Set;unheardDrops=[];dropReceipts=null;submitFn=null;buffered=[];controllerRegistryPath=null;validControllerIds=null;outstanding=[];queuedPeerCount=null;heldListeners=new Set;listedHeld=null;closed=false;constructor(){}static async start(options){if(options.getSessionId&&options.ownsSessionId){throw new Error("PeerMessaging: pass getSessionId or ownsSessionId, not both")}const messaging=new _PeerMessaging;const controllerRegistryPath=options.controllerRegistryPath??getPeerControllerRegistryPath();messaging.controllerRegistryPath=controllerRegistryPath;const dropReceipts=new DropReceiptCoalescer(({frame,reason,droppedMsgIds})=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status:"dropped",origMsgId:frame.msgId,from:messaging.inbox?.socketPath,dropReason:reason,droppedMsgIds},frame.replyToken)},options.dropReceiptTrailMs!==void 0?{trailMs:options.dropReceiptTrailMs}:{});messaging.dropReceipts=dropReceipts;const dropNotices=new DropNoticeThrottle(notice=>messaging.emitDropped(notice));const gate=new InboundGate({getApprovalMode:options.getApprovalMode,getPolicySetting:options.getPolicySetting,...options.getHeldExpiryMs!==void 0?{getHeldExpiryMs:options.getHeldExpiryMs}:{},...options.getPolicyScope?{getPolicyScope:options.getPolicyScope}:{},isControllerValid:__name(id=>messaging.validControllerIds?.has(id)??true,"isControllerValid"),...options.admission?{admission:options.admission}:{},getSessionId:options.getSessionId,...options.ownsSessionId?{ownsSessionId:options.ownsSessionId}:{},deliver:__name((frame,origin)=>messaging.deliver(frame,origin),"deliver"),reportDropped:__name((frame,reason,origin)=>dropReceipts.note(frame,origin??{selfSent:false},reason),"reportDropped"),onDropped:__name((frame,origin,reason)=>dropNotices.note(frame,origin,reason),"onDropped"),reportStatus:__name((frame,status)=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status,origMsgId:frame.msgId,from:messaging.inbox?.socketPath},frame.replyToken)},"reportStatus"),onHeldChange:__name(held=>messaging.emitHeldChange(held),"onHeldChange")});messaging.gate=gate;messaging.getSessionId=options.getSessionId??null;messaging.ownsSessionId=options.ownsSessionId??null;messaging.settleSentMessage=options.settleSentMessage??settleSentPeerMessage;messaging.reassertSessionRecord=options.reassertSessionRecord??null;messaging.drainMirror=options.drainMirror??drainSendPacer;messaging.forgetMirror=options.forgetMirror??forgetSendPacerMessages;messaging.refundMirror=options.refundMirror??refundSendPacerMessage;messaging.refundMirrorToken=options.refundMirrorToken??refundSendPacerToken;clearInheritedPeerMessagingEnv();const ipcToken=options.ipcToken??randomBytes(32).toString("hex");const childToken=options.childToken??randomBytes(32).toString("hex");const inbox=await startPeerInbox({...options.socketPath!==void 0?{socketPath:options.socketPath}:{},requiredToken:ipcToken,childToken,resolveController:__name(presented=>resolveControllerToken(presented,controllerRegistryPath),"resolveController"),onFrame:__name((frame,auth,controller)=>messaging.onFrame(frame,{selfSent:auth==="child",...controller?{controller}:{}}),"onFrame")});if(!inbox)return null;messaging.inbox=inbox;messaging.updateSessionRegistryIpcPath=options.updateSessionRegistryIpcPath;await messaging.updateSessionRegistryIpcPath(inbox.socketPath,ipcToken);process.env[MESSAGING_SOCKET_ENV]=inbox.socketPath;process.env[MESSAGING_TOKEN_ENV]=childToken;return messaging}get socketPath(){return this.inbox?.socketPath}setSubmitFn(fn){if(this.closed)return;this.withControllerValidity(()=>{this.submitFn=fn;while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin))break;this.buffered.shift()}})}setQueuedPeerCount(fn){this.queuedPeerCount=fn}getHeld(){return this.withControllerValidity(()=>this.gate?.getHeld()??[])}getHeldExpiryMs(sessionId){return this.gate?.getHeldExpiryMs(sessionId)??null}recordHeldListing(heldEntries){this.listedHeld=heldEntries.map(entry=>({id:entry.frame.msgId,heldAt:entry.heldAt}))}heldSetChangedSinceListing(){const listed=this.listedHeld;if(listed===null)return true;const pinned=new Map(listed.map(entry=>[entry.id,entry.heldAt]));const current=this.getHeld();if(current.some(entry=>pinned.get(entry.frame.msgId)!==entry.heldAt))return true;const liveIds=current.map(entry=>canonicalizeMsgId(entry.frame.msgId));const liveSet=new Set(liveIds);for(const id of pinned.keys()){const departed=canonicalizeMsgId(id);if(liveSet.has(departed))continue;if(liveIds.some(live=>live.startsWith(departed)))return true}return false}decide(msgId,decision){return this.withControllerValidity(()=>this.gate?.decide(msgId,decision)??"gone")}forgetController(id){return this.withControllerValidity(()=>this.gate?.forgetController(id)??0)}reevaluate(reason){return this.withControllerValidity(()=>this.gate?.reevaluate(reason)??0)}onHeldChange(listener){this.heldListeners.add(listener);try{listener(this.getHeld())}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}return()=>this.heldListeners.delete(listener)}onReceipt(listener){this.receiptListeners.add(listener);return()=>this.receiptListeners.delete(listener)}onDropped(listener){const first=this.dropListeners.size===0;this.dropListeners.add(listener);if(first&&this.unheardDrops.length>0){const unheard=this.unheardDrops.splice(0,this.unheardDrops.length);for(const notice of unheard){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw on replay: ${error instanceof Error?error.message:String(error)}`)}}}return()=>this.dropListeners.delete(listener)}emitDropped(notice){if(this.dropListeners.size===0){if(this.unheardDrops.length<MAX_UNHEARD_DROP_NOTICES){this.unheardDrops.push(notice)}return}for(const listener of this.dropListeners){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw: ${error instanceof Error?error.message:String(error)}`)}}}emitReceipt(receipt){for(const listener of this.receiptListeners){try{listener(receipt)}catch(error){debugLogger.debug(`receipt listener threw: ${error instanceof Error?error.message:String(error)}`)}}}async close(){if(this.closed)return;this.closed=true;const shuttingDown=this.gate?.shutdown();await this.inbox?.close();await shuttingDown;await this.settleUnconsumed();clearInheritedPeerMessagingEnv();await this.updateSessionRegistryIpcPath(void 0);await this.dropReceipts?.flush(CLOSE_DROP_FLUSH_BOUND_MS);this.dropReceipts?.dispose()}async settleUnconsumed(){const queued=this.queuedPeerCount?.()??0;const dropped=this.outstanding.slice(Math.max(0,this.outstanding.length-this.buffered.length-queued));const receipts=dropped.filter(frame=>frame.from!==void 0).map(frame=>sendDeliveryStatus(frame.from,{status:"expired",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken));await Promise.allSettled(receipts)}onDroppedReceipt(frame){const ids=[frame.origMsgId,...frame.droppedMsgIds??[]];let first;let settledCount=0;const settledByPath=new Map;for(const id of ids){const settled=this.settleSentMessage(id,"dropped");if(!settled)continue;first??=settled;settledCount+=1;const entry=settledByPath.get(settled.ipcPath)??{ids:[],freshestAgeMs:Number.POSITIVE_INFINITY};entry.ids.push(id);entry.freshestAgeMs=Math.min(entry.freshestAgeMs,settled.ageMs);settledByPath.set(settled.ipcPath,entry)}if(!first){debugLogger.debug(`ignoring dropped receipt for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`dropped receipt from ${first.address} (${frame.dropReason??"unspecified"}) settled ${settledCount} message(s)`);if(frame.dropReason==="duplicate"){for(const[ipcPath,entry]of settledByPath){for(const id of entry.ids)this.refundMirrorToken(ipcPath,id)}}else{for(const[ipcPath,entry]of settledByPath){this.forgetMirror(ipcPath,entry.ids)}}if(frame.dropReason==="rate-limited"){for(const[ipcPath,entry]of settledByPath){if(entry.freshestAgeMs<=RECEIVER_REFILL_MS)this.drainMirror(ipcPath)}}this.emitReceipt({status:"dropped",address:first.address,origMsgId:frame.origMsgId,previous:"pending",...frame.dropReason?{dropReason:frame.dropReason}:{},dropped:settledCount})}onFrame(frame,origin){if(frame.type==="control"){if(frame.status==="dropped"){this.onDroppedReceipt(frame);return}const settled=this.settleSentMessage(frame.origMsgId,frame.status);if(!settled){debugLogger.debug(`ignoring delivery status ${frame.status} for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`delivery status from ${settled.address}: ${settled.previous} -> ${frame.status} for ${frame.origMsgId}`);if(frame.status!=="held"&&frame.status!=="delivered"){if(frame.status==="misaddressed"){this.refundMirror(settled.ipcPath,frame.origMsgId)}else{this.forgetMirror(settled.ipcPath,[frame.origMsgId])}}this.emitReceipt({status:frame.status,address:settled.address,origMsgId:frame.origMsgId,previous:settled.previous});return}const ownSessionId=this.getSessionId?.();const ownsSessionId=this.ownsSessionId;const misaddressed=ownsSessionId?frame.toSessionId===void 0||!ownsSessionId(frame.toSessionId):frame.toSessionId!==void 0&&ownSessionId!==void 0&&frame.toSessionId!==ownSessionId;if(misaddressed){debugLogger.debug(`refusing peer message ${frame.msgId}: addressed to session ${frame.toSessionId??"(unspecified)"}, this process does not hold it`);if(frame.from){void sendDeliveryStatus(frame.from,{status:"misaddressed",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken)}void this.reassertSessionRecord?.().catch(error=>{debugLogger.debug(`re-asserting the session record failed: ${error instanceof Error?error.message:String(error)}`)});return}this.gate?.admit(frame,origin)}deliver(frame,origin){if(!this.submitFn){if(this.buffered.length>=MAX_ACCEPTED_BACKLOG){throw new Error("accepted-message backlog is full")}this.buffered.push({frame,origin});this.trackOutstanding(frame);return}if(this.buffered.length>0){this.withControllerValidity(()=>{while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin)){throw new Error("accepted-message backlog is full")}this.buffered.shift()}})}if(!this.submit(frame,origin)){throw new Error("accepted-message backlog is full")}this.trackOutstanding(frame)}trackOutstanding(frame){this.outstanding.push(frame);while(this.outstanding.length>2*MAX_ACCEPTED_BACKLOG){this.outstanding.shift()}}withControllerValidity(action){if(this.controllerRegistryPath===null||this.validControllerIds){return action()}this.validControllerIds=new Set(readPeerControllerRegistrySync(this.controllerRegistryPath).controllers.map(controller=>controller.id));for(const delivery of this.buffered){const controller=delivery.origin.controller;if(controller&&!this.validControllerIds.has(controller.id)){delete delivery.origin.controller}}try{return action()}finally{this.validControllerIds=null}}submit(frame,origin){const from=frame.from??(origin.controller?"controller":origin.selfSent?"own process":"unknown session");const attribution={selfSent:origin.selfSent,...origin.controller?{controller:origin.controller}:{}};return this.submitFn?.(formatPeerEnvelope({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),formatPeerDisplay({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),{msgId:frame.msgId,admissionKey:peerSenderKey(frame,origin),...frame.from!==void 0?{from:frame.from}:{},...frame.replyToken!==void 0?{replyToken:frame.replyToken}:{},...frame.toSessionId!==void 0?{toSessionId:frame.toSessionId}:{}})??false}drainQueuedFrame(delivery){const ownSessionId=this.getSessionId?.();if(delivery?.toSessionId===void 0||ownSessionId===void 0||delivery.toSessionId===ownSessionId){return true}debugLogger.debug(`dropping queued peer message ${delivery.msgId}: addressed to session ${delivery.toSessionId}, this is ${ownSessionId}`);if(delivery.from){void sendDeliveryStatus(delivery.from,{status:"misaddressed",origMsgId:delivery.msgId,from:this.inbox?.socketPath},delivery.replyToken)}if(delivery.admissionKey!==void 0){this.gate?.forgetAdmittedMessage(delivery.admissionKey,delivery.msgId)}return false}emitHeldChange(held){for(const listener of this.heldListeners){try{listener(held)}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}}}};export{MAX_ACCEPTED_BACKLOG,PeerMessaging};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{clipToWidth,cpLen,cpSlice,getCachedStringWidth,sanitizeTerminalLine}from"./chunk-64CA3W6G.js";import{normalizeProjectRoot}from"./chunk-JDZ3UHK5.js";import{readProjectEnvFiles}from"./chunk-OSLFWRV2.js";import{require_strip_json_comments}from"./chunk-EKRCICRK.js";import{resolveEnvVarsInObject}from"./chunk-ZOTKZI2P.js";import{atomicWriteFile}from"./chunk-2GF3E5MI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{HookEventName}from"./chunk-4WFJ5OPA.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as crypto from"node:crypto";import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var HOOK_APPROVALS_FILENAME="hookApprovals.json";function getHookApprovalsPath(){if(process.env["QWEN_CODE_HOOK_APPROVALS_PATH"]){return process.env["QWEN_CODE_HOOK_APPROVALS_PATH"]}return path.join(Storage.getGlobalQwenDir(),HOOK_APPROVALS_FILENAME)}__name(getHookApprovalsPath,"getHookApprovalsPath");function getProjectHooksRoot(settings){return path.dirname(path.dirname(settings.workspace.path))}__name(getProjectHooksRoot,"getProjectHooksRoot");function getProjectHooksForApproval(settings){const resolved=settings.getProjectHooks();if(!isRecord(resolved)||summarizeProjectHooks(resolved).length===0){return void 0}const hooks=settings.workspace.originalSettings.hooks;if(!isRecord(hooks))return void 0;const root=getProjectHooksRoot(settings);return{root,hooks,resolved,env:{files:readProjectEnvFiles(settings.merged,root),settings:settings.workspace.originalSettings.env??null}}}__name(getProjectHooksForApproval,"getProjectHooksForApproval");function getProjectHooksForApprovalFromRawWorkspace(settings){const hooks=settings.workspace.originalSettings.hooks;if(!isRecord(hooks))return void 0;const resolved=resolveEnvVarsInObject(hooks);if(summarizeProjectHooks(resolved,hooks).length===0)return void 0;const root=getProjectHooksRoot(settings);return{root,hooks,resolved,env:{files:readProjectEnvFiles(settings.merged,root,true),settings:settings.workspace.originalSettings.env??null}}}__name(getProjectHooksForApprovalFromRawWorkspace,"getProjectHooksForApprovalFromRawWorkspace");function getSeparatedHookSettings(settings){const projectHooks=structuredClone(settings.getProjectHooks());const projectHooksApproval=getProjectHooksForApproval(settings);return{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks,projectHooksDisplayOnly:structuredClone(settings.workspace?.originalSettings?.hooks),...projectHooksApproval?{projectHooksApproval}:{}}}__name(getSeparatedHookSettings,"getSeparatedHookSettings");function hashProjectHooks(approval){const stable=JSON.stringify({hooks:approval.hooks,env:approval.env},(_key,value)=>{if(value&&typeof value==="object"&&!Array.isArray(value)){const obj=value;const sorted=Object.create(null);for(const k of Object.keys(obj).sort()){sorted[k]=obj[k]}return sorted}return value});return crypto.createHash("sha256").update(stable).digest("hex")}__name(hashProjectHooks,"hashProjectHooks");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function displayText(value,max=200){const text=sanitizeTerminalLine(String(value??"")).replace(new RegExp("\\p{Cf}","gu"),"");const length=cpLen(text);return length>max?`${cpSlice(text,0,max)}\u2026 [${length} chars, full value in .qwen/settings.json]`:text}__name(displayText,"displayText");function envList(value){if(!isRecord(value))return keyList(value);return Object.entries(value).map(([k,v])=>`${displayText(k)}=${displayText(v,80)}`).join(", ")}__name(envList,"envList");function keyList(value){if(Array.isArray(value))return value.map(v=>displayText(v)).join(", ");if(isRecord(value))return Object.keys(value).map(k=>displayText(k)).join(", ");return void 0}__name(keyList,"keyList");function describeHook(hook,raw,matcher){const details=[];const add=__name((label,value)=>{if(value)details.push(`${label}: ${value}`)},"add");let head;switch(hook["type"]){case"command":head=displayText(raw["command"]);if(typeof raw["command"]==="string"&&/\$\{?\w/.test(raw["command"])){details.push("resolves ${VAR} from the environment (project .env/settings.env or shell)")}add("env",envList(raw["env"]));if(raw["shell"])add("shell",displayText(raw["shell"]));if(hook["async"]===true)details.push("async");break;case"http":head=`http ${displayText(raw["url"])}`;add("headers",keyList(raw["headers"]));add("allowedEnvVars",keyList(raw["allowedEnvVars"]));break;default:head=`prompt "${displayText(raw["prompt"])}"`;if(raw["model"])add("model",displayText(raw["model"],80))}if(raw["type"]!==hook["type"])add("type",displayText(raw["type"]));if(matcher)add("matcher",displayText(matcher,80));return details.length>0?`${head} [${details.join("; ")}]`:head}__name(describeHook,"describeHook");var HOOK_EVENTS=new Set(Object.values(HookEventName));var REQUIRED_FIELD={command:"command",http:"url",prompt:"prompt"};function isRunnableHook(hook){if(!isRecord(hook)||typeof hook["type"]!=="string")return false;const field=REQUIRED_FIELD[hook["type"]];return field!==void 0&&Boolean(hook[field])}__name(isRunnableHook,"isRunnableHook");function entry(value,key){if(Array.isArray(value)&&typeof key==="number")return value[key];return isRecord(value)?value[key]:void 0}__name(entry,"entry");function summarizeProjectHooks(resolved,raw=resolved){const lines=[];for(const[event,definitions]of Object.entries(resolved)){if(!HOOK_EVENTS.has(event)||!Array.isArray(definitions))continue;definitions.forEach((definition,i)=>{if(!isRecord(definition)||!Array.isArray(definition["hooks"]))return;const rawDefinition=entry(entry(raw,event),i);definition["hooks"].forEach((hook,j)=>{if(!isRunnableHook(hook))return;const rawHook=entry(entry(rawDefinition,"hooks"),j);const rawMatcher=entry(rawDefinition,"matcher");lines.push(`${displayText(event,24)} ${describeHook(hook,isRecord(rawHook)?rawHook:hook,rawMatcher??definition["matcher"])}`)})})}return lines}__name(summarizeProjectHooks,"summarizeProjectHooks");function fitHookLines(lines,maxRows){const rows=Math.max(1,Math.floor(maxRows));if(lines.length<=rows)return lines;const shown=Math.max(0,rows-1);return[...lines.slice(0,shown),`\u2026 and ${lines.length-shown} more (see .qwen/settings.json)`]}__name(fitHookLines,"fitHookLines");function fitHookLine(line,width){if(getCachedStringWidth(line)<=width)return line;const total=cpLen(line);const marker=`\u2026 [+${total} chars]`;const kept=clipToWidth(line,width-getCachedStringWidth(marker));return`${kept}\u2026 [+${total-cpLen(kept)} chars]`}__name(fitHookLine,"fitHookLine");var LoadedHookApprovals=class{constructor(file,errors){this.file=file;this.errors=errors}static{__name(this,"LoadedHookApprovals")}getState(approval){const record=this.file.config[normalizeProjectRoot(approval.root)];if(!isRecord(record)||record["hash"]!==hashProjectHooks(approval)){return"pending"}const status=record["status"];return status==="approved"||status==="rejected"?status:"pending"}async setState(approval,status){const{config,errors}=readHookApprovals(this.file.path);if(errors.length>0){throw new Error(`${errors[0].message} (${this.file.path})`)}Object.defineProperty(config,normalizeProjectRoot(approval.root),{value:{hash:hashProjectHooks(approval),status},enumerable:true,configurable:true,writable:true});fs.mkdirSync(path.dirname(this.file.path),{recursive:true});await atomicWriteFile(this.file.path,JSON.stringify(config,null,2),{mode:384,forceMode:true});this.file.config=config}};var warnedErrors=new Set;function readHookApprovals(filePath){const errors=[];let config=Object.create(null);try{if(fs.existsSync(filePath)){const parsed=JSON.parse((0,import_strip_json_comments.default)(fs.readFileSync(filePath,"utf-8")));if(isRecord(parsed)){config=Object.assign(Object.create(null),parsed)}else{errors.push({message:"Hook approvals file is not a valid JSON object.",path:filePath})}}}catch(error){errors.push({message:getErrorMessage(error),path:filePath})}return{config,errors}}__name(readHookApprovals,"readHookApprovals");function loadHookApprovals(){const filePath=getHookApprovalsPath();const{config,errors}=readHookApprovals(filePath);for(const error of errors){if(warnedErrors.has(error.message))continue;warnedErrors.add(error.message);writeStderrLine(`Warning: hook approvals file error: ${error.message}`)}return new LoadedHookApprovals({path:filePath,config},errors)}__name(loadHookApprovals,"loadHookApprovals");function getProjectHooksApprovalState(approval){return approval?loadHookApprovals().getState(approval):void 0}__name(getProjectHooksApprovalState,"getProjectHooksApprovalState");function applyProjectHooksApproval(config,approval){const state=getProjectHooksApprovalState(approval);const trusted=config.isExplicitlyTrustedFolder?.()===true;config.setProjectHooksPendingApproval(state!==void 0&&state!=="approved"&&!(trusted&&state!=="rejected"),state==="rejected");return state}__name(applyProjectHooksApproval,"applyProjectHooksApproval");function getProjectHooksHeadlessWarning(state){return state==="rejected"?`Project hooks in .qwen/settings.json were not loaded: they were rejected for this folder and are not asked about again until they change (decisions are kept in ${getHookApprovalsPath()}).`:"Project hooks in .qwen/settings.json were not loaded: they are not approved for this folder. Run qwen interactively here to review them."}__name(getProjectHooksHeadlessWarning,"getProjectHooksHeadlessWarning");export{getProjectHooksForApproval,getProjectHooksForApprovalFromRawWorkspace,getSeparatedHookSettings,hashProjectHooks,summarizeProjectHooks,fitHookLines,fitHookLine,loadHookApprovals,getProjectHooksApprovalState,applyProjectHooksApproval,getProjectHooksHeadlessWarning};
3
+ import{clipToWidth,cpLen,cpSlice,getCachedStringWidth,sanitizeTerminalLine}from"./chunk-64CA3W6G.js";import{normalizeProjectRoot}from"./chunk-JDZ3UHK5.js";import{readProjectEnvFiles}from"./chunk-HRTWLOGK.js";import{require_strip_json_comments}from"./chunk-EKRCICRK.js";import{resolveEnvVarsInObject}from"./chunk-ZOTKZI2P.js";import{atomicWriteFile}from"./chunk-2GF3E5MI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{HookEventName}from"./chunk-4WFJ5OPA.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as crypto from"node:crypto";import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var HOOK_APPROVALS_FILENAME="hookApprovals.json";function getHookApprovalsPath(){if(process.env["QWEN_CODE_HOOK_APPROVALS_PATH"]){return process.env["QWEN_CODE_HOOK_APPROVALS_PATH"]}return path.join(Storage.getGlobalQwenDir(),HOOK_APPROVALS_FILENAME)}__name(getHookApprovalsPath,"getHookApprovalsPath");function getProjectHooksRoot(settings){return path.dirname(path.dirname(settings.workspace.path))}__name(getProjectHooksRoot,"getProjectHooksRoot");function getProjectHooksForApproval(settings){const resolved=settings.getProjectHooks();if(!isRecord(resolved)||summarizeProjectHooks(resolved).length===0){return void 0}const hooks=settings.workspace.originalSettings.hooks;if(!isRecord(hooks))return void 0;const root=getProjectHooksRoot(settings);return{root,hooks,resolved,env:{files:readProjectEnvFiles(settings.merged,root),settings:settings.workspace.originalSettings.env??null}}}__name(getProjectHooksForApproval,"getProjectHooksForApproval");function getProjectHooksForApprovalFromRawWorkspace(settings){const hooks=settings.workspace.originalSettings.hooks;if(!isRecord(hooks))return void 0;const resolved=resolveEnvVarsInObject(hooks);if(summarizeProjectHooks(resolved,hooks).length===0)return void 0;const root=getProjectHooksRoot(settings);return{root,hooks,resolved,env:{files:readProjectEnvFiles(settings.merged,root,true),settings:settings.workspace.originalSettings.env??null}}}__name(getProjectHooksForApprovalFromRawWorkspace,"getProjectHooksForApprovalFromRawWorkspace");function getSeparatedHookSettings(settings){const projectHooks=structuredClone(settings.getProjectHooks());const projectHooksApproval=getProjectHooksForApproval(settings);return{systemHooks:settings.getSystemHooks(),userHooks:settings.getUserHooks(),projectHooks,projectHooksDisplayOnly:structuredClone(settings.workspace?.originalSettings?.hooks),...projectHooksApproval?{projectHooksApproval}:{}}}__name(getSeparatedHookSettings,"getSeparatedHookSettings");function hashProjectHooks(approval){const stable=JSON.stringify({hooks:approval.hooks,env:approval.env},(_key,value)=>{if(value&&typeof value==="object"&&!Array.isArray(value)){const obj=value;const sorted=Object.create(null);for(const k of Object.keys(obj).sort()){sorted[k]=obj[k]}return sorted}return value});return crypto.createHash("sha256").update(stable).digest("hex")}__name(hashProjectHooks,"hashProjectHooks");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function displayText(value,max=200){const text=sanitizeTerminalLine(String(value??"")).replace(new RegExp("\\p{Cf}","gu"),"");const length=cpLen(text);return length>max?`${cpSlice(text,0,max)}\u2026 [${length} chars, full value in .qwen/settings.json]`:text}__name(displayText,"displayText");function envList(value){if(!isRecord(value))return keyList(value);return Object.entries(value).map(([k,v])=>`${displayText(k)}=${displayText(v,80)}`).join(", ")}__name(envList,"envList");function keyList(value){if(Array.isArray(value))return value.map(v=>displayText(v)).join(", ");if(isRecord(value))return Object.keys(value).map(k=>displayText(k)).join(", ");return void 0}__name(keyList,"keyList");function describeHook(hook,raw,matcher){const details=[];const add=__name((label,value)=>{if(value)details.push(`${label}: ${value}`)},"add");let head;switch(hook["type"]){case"command":head=displayText(raw["command"]);if(typeof raw["command"]==="string"&&/\$\{?\w/.test(raw["command"])){details.push("resolves ${VAR} from the environment (project .env/settings.env or shell)")}add("env",envList(raw["env"]));if(raw["shell"])add("shell",displayText(raw["shell"]));if(hook["async"]===true)details.push("async");break;case"http":head=`http ${displayText(raw["url"])}`;add("headers",keyList(raw["headers"]));add("allowedEnvVars",keyList(raw["allowedEnvVars"]));break;default:head=`prompt "${displayText(raw["prompt"])}"`;if(raw["model"])add("model",displayText(raw["model"],80))}if(raw["type"]!==hook["type"])add("type",displayText(raw["type"]));if(matcher)add("matcher",displayText(matcher,80));return details.length>0?`${head} [${details.join("; ")}]`:head}__name(describeHook,"describeHook");var HOOK_EVENTS=new Set(Object.values(HookEventName));var REQUIRED_FIELD={command:"command",http:"url",prompt:"prompt"};function isRunnableHook(hook){if(!isRecord(hook)||typeof hook["type"]!=="string")return false;const field=REQUIRED_FIELD[hook["type"]];return field!==void 0&&Boolean(hook[field])}__name(isRunnableHook,"isRunnableHook");function entry(value,key){if(Array.isArray(value)&&typeof key==="number")return value[key];return isRecord(value)?value[key]:void 0}__name(entry,"entry");function summarizeProjectHooks(resolved,raw=resolved){const lines=[];for(const[event,definitions]of Object.entries(resolved)){if(!HOOK_EVENTS.has(event)||!Array.isArray(definitions))continue;definitions.forEach((definition,i)=>{if(!isRecord(definition)||!Array.isArray(definition["hooks"]))return;const rawDefinition=entry(entry(raw,event),i);definition["hooks"].forEach((hook,j)=>{if(!isRunnableHook(hook))return;const rawHook=entry(entry(rawDefinition,"hooks"),j);const rawMatcher=entry(rawDefinition,"matcher");lines.push(`${displayText(event,24)} ${describeHook(hook,isRecord(rawHook)?rawHook:hook,rawMatcher??definition["matcher"])}`)})})}return lines}__name(summarizeProjectHooks,"summarizeProjectHooks");function fitHookLines(lines,maxRows){const rows=Math.max(1,Math.floor(maxRows));if(lines.length<=rows)return lines;const shown=Math.max(0,rows-1);return[...lines.slice(0,shown),`\u2026 and ${lines.length-shown} more (see .qwen/settings.json)`]}__name(fitHookLines,"fitHookLines");function fitHookLine(line,width){if(getCachedStringWidth(line)<=width)return line;const total=cpLen(line);const marker=`\u2026 [+${total} chars]`;const kept=clipToWidth(line,width-getCachedStringWidth(marker));return`${kept}\u2026 [+${total-cpLen(kept)} chars]`}__name(fitHookLine,"fitHookLine");var LoadedHookApprovals=class{constructor(file,errors){this.file=file;this.errors=errors}static{__name(this,"LoadedHookApprovals")}getState(approval){const record=this.file.config[normalizeProjectRoot(approval.root)];if(!isRecord(record)||record["hash"]!==hashProjectHooks(approval)){return"pending"}const status=record["status"];return status==="approved"||status==="rejected"?status:"pending"}async setState(approval,status){const{config,errors}=readHookApprovals(this.file.path);if(errors.length>0){throw new Error(`${errors[0].message} (${this.file.path})`)}Object.defineProperty(config,normalizeProjectRoot(approval.root),{value:{hash:hashProjectHooks(approval),status},enumerable:true,configurable:true,writable:true});fs.mkdirSync(path.dirname(this.file.path),{recursive:true});await atomicWriteFile(this.file.path,JSON.stringify(config,null,2),{mode:384,forceMode:true});this.file.config=config}};var warnedErrors=new Set;function readHookApprovals(filePath){const errors=[];let config=Object.create(null);try{if(fs.existsSync(filePath)){const parsed=JSON.parse((0,import_strip_json_comments.default)(fs.readFileSync(filePath,"utf-8")));if(isRecord(parsed)){config=Object.assign(Object.create(null),parsed)}else{errors.push({message:"Hook approvals file is not a valid JSON object.",path:filePath})}}}catch(error){errors.push({message:getErrorMessage(error),path:filePath})}return{config,errors}}__name(readHookApprovals,"readHookApprovals");function loadHookApprovals(){const filePath=getHookApprovalsPath();const{config,errors}=readHookApprovals(filePath);for(const error of errors){if(warnedErrors.has(error.message))continue;warnedErrors.add(error.message);writeStderrLine(`Warning: hook approvals file error: ${error.message}`)}return new LoadedHookApprovals({path:filePath,config},errors)}__name(loadHookApprovals,"loadHookApprovals");function getProjectHooksApprovalState(approval){return approval?loadHookApprovals().getState(approval):void 0}__name(getProjectHooksApprovalState,"getProjectHooksApprovalState");function applyProjectHooksApproval(config,approval){const state=getProjectHooksApprovalState(approval);const trusted=config.isExplicitlyTrustedFolder?.()===true;config.setProjectHooksPendingApproval(state!==void 0&&state!=="approved"&&!(trusted&&state!=="rejected"),state==="rejected");return state}__name(applyProjectHooksApproval,"applyProjectHooksApproval");function getProjectHooksHeadlessWarning(state){return state==="rejected"?`Project hooks in .qwen/settings.json were not loaded: they were rejected for this folder and are not asked about again until they change (decisions are kept in ${getHookApprovalsPath()}).`:"Project hooks in .qwen/settings.json were not loaded: they are not approved for this folder. Run qwen interactively here to review them."}__name(getProjectHooksHeadlessWarning,"getProjectHooksHeadlessWarning");export{getProjectHooksForApproval,getProjectHooksForApprovalFromRawWorkspace,getSeparatedHookSettings,hashProjectHooks,summarizeProjectHooks,fitHookLines,fitHookLine,loadHookApprovals,getProjectHooksApprovalState,applyProjectHooksApproval,getProjectHooksHeadlessWarning};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{performStandaloneUpdate}from"./chunk-2FYWJVGW.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{getHomebrewLatestVersion,getInstallationInfo,getNpmNodePath,resolveUpdateCommand}from"./chunk-ACKQAOX7.js";import{t}from"./chunk-HRRQHZQE.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{spawn}from"node:child_process";var spawnWrapper=spawn;import os from"node:os";var debugLogger=createDebugLogger("AUTO_UPDATE");var UPDATE_SUCCESS_MESSAGE="Update successful! The new version will be used on your next run.";var UPDATE_FAILED_MESSAGE="Automatic update failed. Please try updating manually.";async function handleAutoUpdate(info,settings,projectRoot,spawnFn=spawnWrapper){if(!info){return}const isAutoUpdateEnabled=settings.merged.general?.enableAutoUpdate!==false;const installationInfo=getInstallationInfo(projectRoot,isAutoUpdateEnabled);if(installationInfo.packageManager==="homebrew"){const installedVersion=import_semver.default.coerce(info.update.current)?.version;const brewLatestVersion=import_semver.default.coerce(await getHomebrewLatestVersion()??void 0)?.version;if(installedVersion&&brewLatestVersion&&!import_semver.default.gt(brewLatestVersion,installedVersion)){return}}let combinedMessage=info.message;if(installationInfo.updateMessage){combinedMessage+=`
3
+ import{performStandaloneUpdate}from"./chunk-ISA4MFNT.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{getHomebrewLatestVersion,getInstallationInfo,getNpmNodePath,resolveUpdateCommand}from"./chunk-ACKQAOX7.js";import{t}from"./chunk-73TSS7KS.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{spawn}from"node:child_process";var spawnWrapper=spawn;import os from"node:os";var debugLogger=createDebugLogger("AUTO_UPDATE");var UPDATE_SUCCESS_MESSAGE="Update successful! The new version will be used on your next run.";var UPDATE_FAILED_MESSAGE="Automatic update failed. Please try updating manually.";async function handleAutoUpdate(info,settings,projectRoot,spawnFn=spawnWrapper){if(!info){return}const isAutoUpdateEnabled=settings.merged.general?.enableAutoUpdate!==false;const installationInfo=getInstallationInfo(projectRoot,isAutoUpdateEnabled);if(installationInfo.packageManager==="homebrew"){const installedVersion=import_semver.default.coerce(info.update.current)?.version;const brewLatestVersion=import_semver.default.coerce(await getHomebrewLatestVersion()??void 0)?.version;if(installedVersion&&brewLatestVersion&&!import_semver.default.gt(brewLatestVersion,installedVersion)){return}}let combinedMessage=info.message;if(installationInfo.updateMessage){combinedMessage+=`
4
4
  ${t(installationInfo.updateMessage)}`}updateEventEmitter.emit("update-received",{message:combinedMessage});if(installationInfo.isStandalone&&installationInfo.standaloneDir&&isAutoUpdateEnabled){performStandaloneUpdate(installationInfo.standaloneDir,info.update.latest).then(result=>{const message=result==="deferred"?t("Update downloaded. It will be applied after you exit this session."):t("Update successful! The new version will be used on your next run.");updateEventEmitter.emit("update-success",{message})}).catch(err=>{updateEventEmitter.emit("update-failed",{message:t("Automatic update failed: {{error}}. Re-run the installer to update manually.",{error:err.message})})});return}if(!installationInfo.updateCommand||!isAutoUpdateEnabled){return}const updateCommand=resolveUpdateCommand(installationInfo.updateCommand,info.update.latest);const platform=os.platform();const isWindows=platform==="win32";const isManagedNpmUpdate=installationInfo.packageManager==="npm";const command=isManagedNpmUpdate?getNpmNodePath():isWindows?"cmd.exe":"bash";const commandArgs=isManagedNpmUpdate?[process.argv[1]]:isWindows?["/c",updateCommand]:["-c",updateCommand];const updateProcess=spawnFn(command,commandArgs,{...isManagedNpmUpdate?{detached:true,env:{...process.env,QWEN_CODE_MANAGED_NPM_UPDATE_VERSION:info.update.latest},stdio:["ignore","ignore","pipe"],windowsHide:true}:{stdio:["pipe","ignore","pipe"]}});let errorOutput="";updateProcess.stderr?.on("data",data=>{errorOutput+=data.toString()});return new Promise(resolve=>{let settled=false;const finish=__name(error=>{if(settled)return;settled=true;try{if(error)throw error;updateEventEmitter.emit("update-success",{message:t(UPDATE_SUCCESS_MESSAGE)});resolve(true)}catch(error2){debugLogger.warn("Automatic update failed:",error2);updateEventEmitter.emit("update-failed",{message:t(UPDATE_FAILED_MESSAGE)});resolve(false)}},"finish");updateProcess.once("close",code=>{finish(code===0?void 0:new Error(`Command failed: ${updateCommand}; stderr: ${errorOutput.trim()}`))});updateProcess.once("error",error=>{finish(error)})})}__name(handleAutoUpdate,"handleAutoUpdate");function setUpdateHandler(addItem,setUpdateInfo,isIdleRef={current:true}){let successfullyInstalled=false;const pendingNotifications=[];const addItemOrDefer=__name(item=>{if(isIdleRef.current){addItem(item,Date.now())}else{pendingNotifications.push(item)}},"addItemOrDefer");const handleUpdateReceived=__name(info=>{setUpdateInfo(info);const savedMessage=info.message;setTimeout(()=>{if(!successfullyInstalled){addItemOrDefer({type:"info",text:savedMessage})}setUpdateInfo(null)},6e4)},"handleUpdateReceived");const handleUpdateFailed=__name(data=>{setUpdateInfo(null);addItemOrDefer({type:data?.severity==="warning"?"warning":"error",text:data?.message??t(UPDATE_FAILED_MESSAGE)})},"handleUpdateFailed");const handleUpdateSuccess=__name(data=>{successfullyInstalled=true;setUpdateInfo(null);addItemOrDefer({type:"info",text:data?.message??t(UPDATE_SUCCESS_MESSAGE)})},"handleUpdateSuccess");const handleUpdateInfo=__name(data=>{addItemOrDefer({type:"info",text:data.message})},"handleUpdateInfo");updateEventEmitter.on("update-received",handleUpdateReceived);updateEventEmitter.on("update-failed",handleUpdateFailed);updateEventEmitter.on("update-success",handleUpdateSuccess);updateEventEmitter.on("update-info",handleUpdateInfo);const cleanup=__name(()=>{updateEventEmitter.off("update-received",handleUpdateReceived);updateEventEmitter.off("update-failed",handleUpdateFailed);updateEventEmitter.off("update-success",handleUpdateSuccess);updateEventEmitter.off("update-info",handleUpdateInfo);pendingNotifications.length=0},"cleanup");const flush=__name(()=>{while(pendingNotifications.length>0){const item=pendingNotifications.shift();addItem(item,Date.now())}},"flush");return{cleanup,flush}}__name(setUpdateHandler,"setUpdateHandler");export{handleAutoUpdate,setUpdateHandler};
5
5
  /**
6
6
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{appEvents}from"./chunk-MPDGSR2S.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-ET7ADS4X.js";import{getMCPServerStatus}from"./chunk-R5AA46IX.js";import{require_fast_deep_equal}from"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
3
+ import{appEvents}from"./chunk-N3YWQWSR.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-DS2FKATN.js";import{getMCPServerStatus}from"./chunk-R5AA46IX.js";import{require_fast_deep_equal}from"./chunk-3KUHQGOS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen